Compare commits
52
Commits
85093c859b
..
main
@@ -75,7 +75,7 @@ Everything is optional. Set these in the environment or in a `.env` file beside
|
|||||||
| Variable | When | What it does |
|
| Variable | When | What it does |
|
||||||
|----------|------|--------------|
|
|----------|------|--------------|
|
||||||
| `BASE_URL` | Behind a proxy | The public URL, used in email links and SSO redirects |
|
| `BASE_URL` | Behind a proxy | The public URL, used in email links and SSO redirects |
|
||||||
| `TRUSTED_PROXY_HOPS` | Behind a proxy | How many reverse proxies stand in front of Grimoire (default `1`; the compose file above sets `0` because it publishes the port directly). The client address and HTTPS are read from the proxy's headers by it |
|
| `TRUSTED_PROXY_HOPS` | Rarely | The starting count of reverse proxies in front of Grimoire (default `1`; the compose file above sets `0` because it publishes the port directly). Check and change it in **Settings → Config → Reverse proxy**, which shows what each count reads for your own request; behind Cloudflare it is usually `2` |
|
||||||
| `POSTGRES_PASSWORD` | Before the first start | The database password (defaults to `grimoire`; the database is reachable only inside the compose network). Postgres takes it once, when the volume is created |
|
| `POSTGRES_PASSWORD` | Before the first start | The database password (defaults to `grimoire`; the database is reachable only inside the compose network). Postgres takes it once, when the volume is created |
|
||||||
| `SECRET_KEY` | Rarely | A key you manage yourself, instead of the one Grimoire keeps. It wins over the kept key; remove it to go back |
|
| `SECRET_KEY` | Rarely | A key you manage yourself, instead of the one Grimoire keeps. It wins over the kept key; remove it to go back |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""rule enforcement and salience — what a rule does when it arrives, and how much it outranks
|
||||||
|
|
||||||
|
Revision ID: 0128
|
||||||
|
Revises: 0127
|
||||||
|
Create Date: 2026-11-22
|
||||||
|
|
||||||
|
Two declared columns on a rule, read by the one function that orders what
|
||||||
|
reaches a moment:
|
||||||
|
|
||||||
|
- `enforcement`: `enforce` (the act itself is checked), `hold` (the reply or act
|
||||||
|
waits for one read), `inform` (a line beside the work). Every existing rule
|
||||||
|
starts as `inform`; declaring which ones hold is the author's call.
|
||||||
|
- `salience`: `high`, `normal`, `low` — the author's ranking among rules of
|
||||||
|
the same enforcement.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0128"
|
||||||
|
down_revision = "0127"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
_ENFORCEMENTS = ("enforce", "hold", "inform")
|
||||||
|
_SALIENCES = ("high", "normal", "low")
|
||||||
|
|
||||||
|
|
||||||
|
def _in_list(column: str, values: tuple[str, ...]) -> str:
|
||||||
|
return f"{column} IN ({', '.join(repr(v) for v in values)})"
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("rules", sa.Column("enforcement", sa.Text(), nullable=False, server_default="inform"))
|
||||||
|
op.add_column("rules", sa.Column("salience", sa.Text(), nullable=False, server_default="normal"))
|
||||||
|
op.create_check_constraint("ck_rules_enforcement", "rules", _in_list("enforcement", _ENFORCEMENTS))
|
||||||
|
op.create_check_constraint("ck_rules_salience", "rules", _in_list("salience", _SALIENCES))
|
||||||
|
# A preference claims no force: it is how work is liked done, not a bar.
|
||||||
|
op.create_check_constraint(
|
||||||
|
"ck_rules_preference_informs", "rules", "kind <> 'preference' OR enforcement = 'inform'",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_constraint("ck_rules_preference_informs", "rules", type_="check")
|
||||||
|
op.drop_constraint("ck_rules_salience", "rules", type_="check")
|
||||||
|
op.drop_constraint("ck_rules_enforcement", "rules", type_="check")
|
||||||
|
op.drop_column("rules", "salience")
|
||||||
|
op.drop_column("rules", "enforcement")
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""rule deliveries — each rule line a session was shown, and whether it was opened after
|
||||||
|
|
||||||
|
Revision ID: 0129
|
||||||
|
Revises: 0128
|
||||||
|
Create Date: 2026-11-22
|
||||||
|
|
||||||
|
One row per rule line delivered to a session, with the open stamped on the
|
||||||
|
delivery it followed. The open rate per rule and moment is read from it, both
|
||||||
|
for the ordering of what reaches a moment and for the adherence readout.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0129"
|
||||||
|
down_revision = "0128"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"rule_deliveries",
|
||||||
|
sa.Column("id", sa.BigInteger(), primary_key=True),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("session_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("rule_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False),
|
||||||
|
sa.Column("at", sa.Text(), nullable=False),
|
||||||
|
sa.Column("form", sa.Text(), nullable=False),
|
||||||
|
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False,
|
||||||
|
server_default=sa.func.now()),
|
||||||
|
sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.CheckConstraint("form IN ('full', 'repeat')", name="ck_rule_deliveries_form"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_rule_deliveries_session_rule", "rule_deliveries",
|
||||||
|
["user_id", "session_id", "rule_id", "delivered_at"])
|
||||||
|
op.create_index("ix_rule_deliveries_rule_at", "rule_deliveries", ["rule_id", "at"])
|
||||||
|
op.create_index("ix_rule_deliveries_delivered_at", "rule_deliveries", ["delivered_at"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("rule_deliveries")
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""rule triggers — typed predicates on the act that deliver a rule, checked in code
|
||||||
|
|
||||||
|
Revision ID: 0130
|
||||||
|
Revises: 0129
|
||||||
|
Create Date: 2026-11-22
|
||||||
|
|
||||||
|
A trigger is a kind (tool, path, command, keyword) and a pattern, optionally
|
||||||
|
scoped to a moment. Unscoped, it delivers the rule on any act that matches;
|
||||||
|
scoped, it makes the rule's mount on that moment conditional on the act
|
||||||
|
matching. Matched in code against the act, never by embedding.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0130"
|
||||||
|
down_revision = "0129"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"rule_triggers",
|
||||||
|
sa.Column("rule_id", sa.BigInteger(),
|
||||||
|
sa.ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
|
||||||
|
sa.Column("kind", sa.Text(), primary_key=True),
|
||||||
|
sa.Column("pattern", sa.Text(), primary_key=True),
|
||||||
|
sa.Column("moment", sa.Text(), primary_key=True, server_default=""),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"kind IN ('tool', 'path', 'command', 'keyword')", name="ck_rule_triggers_kind",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("length(pattern) > 0", name="ck_rule_triggers_pattern"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_table("rule_triggers")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""retrieval_logs records the cue-swap gate: its bar and how many lines passed
|
||||||
|
|
||||||
|
Revision ID: 0131
|
||||||
|
Revises: 0130
|
||||||
|
Create Date: 2026-11-23
|
||||||
|
|
||||||
|
A gated surface shows a line found by resemblance only when its score beats
|
||||||
|
most of the user's own recent cues on that surface. Each call row keeps the
|
||||||
|
bar it was held to and how many lines reached it, so how often a surface
|
||||||
|
speaks can be read back, per surface, as the store grows.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0131"
|
||||||
|
down_revision = "0130"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("retrieval_logs", sa.Column("gate_bar", sa.Float(), nullable=True))
|
||||||
|
op.add_column("retrieval_logs", sa.Column("gate_kept", sa.Integer(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("retrieval_logs", "gate_kept")
|
||||||
|
op.drop_column("retrieval_logs", "gate_bar")
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""rule field judgments — proposed and judged enforcement, salience and triggers
|
||||||
|
|
||||||
|
Revision ID: 0132
|
||||||
|
Revises: 0131
|
||||||
|
Create Date: 2026-11-23
|
||||||
|
|
||||||
|
A pass reads each rule with its delivery history and proposes how strongly it
|
||||||
|
should arrive and what should reach it; a person confirms or rejects each
|
||||||
|
value. One row per (rule, field, value), so a rejected value is never proposed
|
||||||
|
again and a rule the pass agreed with reads as looked at.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
revision = "0132"
|
||||||
|
down_revision = "0131"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"rule_field_judgments",
|
||||||
|
sa.Column("id", sa.BigInteger(), primary_key=True),
|
||||||
|
sa.Column("rule_id", sa.BigInteger(),
|
||||||
|
sa.ForeignKey("rules.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("field", sa.Text(), nullable=False),
|
||||||
|
sa.Column("value", sa.Text(), nullable=False),
|
||||||
|
sa.Column("state", sa.Text(), nullable=False, server_default="suggested"),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False, server_default="pass"),
|
||||||
|
sa.Column("note", sa.Text(), nullable=True),
|
||||||
|
sa.Column("evidence", postgresql.JSONB(), nullable=True),
|
||||||
|
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
|
||||||
|
server_default=sa.func.now()),
|
||||||
|
sa.UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"field IN ('enforcement', 'salience', 'trigger')", name="ck_rule_field_judgments_field",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint(
|
||||||
|
"state IN ('suggested', 'confirmed', 'rejected')", name="ck_rule_field_judgments_state",
|
||||||
|
),
|
||||||
|
sa.CheckConstraint("source IN ('pass', 'edit')", name="ck_rule_field_judgments_source"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_rule_field_judgments_rule_id", "rule_field_judgments", ["rule_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_rule_field_judgments_rule_id", table_name="rule_field_judgments")
|
||||||
|
op.drop_table("rule_field_judgments")
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""rule deliveries record the plugin version that asked for the line
|
||||||
|
|
||||||
|
Revision ID: 0133
|
||||||
|
Revises: 0132
|
||||||
|
Create Date: 2026-11-23
|
||||||
|
|
||||||
|
Only a plugin that sends its version reports every open, so the open-rate
|
||||||
|
readers count only deliveries that carry one. Existing rows stay null: they
|
||||||
|
were made while sessions ran a plugin that did not report opens of the rules
|
||||||
|
a hook had named, so their missing opens are not evidence.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0133"
|
||||||
|
down_revision = "0132"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column("rule_deliveries", sa.Column("plugin", sa.Text(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_column("rule_deliveries", "plugin")
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""rule adherence: whether a rule in force at a moment of a session was followed
|
||||||
|
|
||||||
|
Revision ID: 0134
|
||||||
|
Revises: 0133
|
||||||
|
Create Date: 2026-11-23
|
||||||
|
|
||||||
|
One verdict per rule, per place it was delivered, per session — the unit
|
||||||
|
`rule_deliveries` records — from an `enforce` refusal, the session's own
|
||||||
|
`rule_outcome` / `rule_misfired`, or a transcript review.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0134"
|
||||||
|
down_revision = "0133"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"rule_adherence",
|
||||||
|
sa.Column("id", sa.BigInteger(), primary_key=True),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("session_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("rule_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("at", sa.Text(), nullable=False),
|
||||||
|
sa.Column("verdict", sa.Text(), nullable=False),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False),
|
||||||
|
sa.Column("evidence", sa.Text(), nullable=True),
|
||||||
|
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=False,
|
||||||
|
server_default=sa.func.now()),
|
||||||
|
sa.UniqueConstraint("user_id", "session_id", "rule_id", "at",
|
||||||
|
name="uq_rule_adherence_session_rule_at"),
|
||||||
|
)
|
||||||
|
op.create_index("ix_rule_adherence_rule_at", "rule_adherence", ["rule_id", "at"])
|
||||||
|
op.create_index("ix_rule_adherence_judged_at", "rule_adherence", ["judged_at"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_rule_adherence_judged_at", table_name="rule_adherence")
|
||||||
|
op.drop_index("ix_rule_adherence_rule_at", table_name="rule_adherence")
|
||||||
|
op.drop_table("rule_adherence")
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""a delivery of a rule the session had already opened counts as opened
|
||||||
|
|
||||||
|
Revision ID: 0135
|
||||||
|
Revises: 0134
|
||||||
|
Create Date: 2026-11-24
|
||||||
|
|
||||||
|
From now on a line for a rule the session has opened in the last six hours
|
||||||
|
is stamped opened as it is written (`rule_deliveries._read_already`). This
|
||||||
|
stamps the deliveries already recorded the same way, so the open rates, the
|
||||||
|
adherence readout and the weighing pass read one definition across old and
|
||||||
|
new rows: a rule read early in a session is not counted unread each time it
|
||||||
|
arrives again. The stamp is the delivery's own time. Only rows that carry a
|
||||||
|
plugin version are touched: every reader skips the others
|
||||||
|
(`rule_deliveries.REPORTS_OPENS`), and they are most of the table, so the
|
||||||
|
lookup runs on the few rows recorded since 0133 rather than on all of them.
|
||||||
|
Not reversible: the downgrade leaves the stamps, which the earlier code reads
|
||||||
|
as ordinary opens.
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0135"
|
||||||
|
down_revision = "0134"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
UPDATE rule_deliveries d
|
||||||
|
SET opened_at = d.delivered_at
|
||||||
|
WHERE d.opened_at IS NULL
|
||||||
|
AND d.plugin IS NOT NULL
|
||||||
|
AND EXISTS (
|
||||||
|
SELECT 1 FROM rule_deliveries e
|
||||||
|
WHERE e.user_id = d.user_id
|
||||||
|
AND e.session_id = d.session_id
|
||||||
|
AND e.rule_id = d.rule_id
|
||||||
|
AND e.opened_at IS NOT NULL
|
||||||
|
AND e.opened_at <= d.delivered_at
|
||||||
|
AND e.opened_at >= d.delivered_at - INTERVAL '6 hours'
|
||||||
|
)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""record deliveries: each non-rule record put in front of a session, and whether it was opened
|
||||||
|
|
||||||
|
Revision ID: 0136
|
||||||
|
Revises: 0135
|
||||||
|
Create Date: 2026-11-24
|
||||||
|
|
||||||
|
The note-side twin of `rule_deliveries`. A row per record a hook pushed, a
|
||||||
|
search the session ran returned, or the session opened with nothing
|
||||||
|
delivering it first, so opens can be told apart by the way the record
|
||||||
|
arrived.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0136"
|
||||||
|
down_revision = "0135"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"record_deliveries",
|
||||||
|
sa.Column("id", sa.BigInteger(), primary_key=True),
|
||||||
|
sa.Column("user_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("session_id", sa.Text(), nullable=False),
|
||||||
|
sa.Column("note_id", sa.BigInteger(), nullable=False),
|
||||||
|
sa.Column("kind", sa.Text(), nullable=False),
|
||||||
|
sa.Column("way", sa.Text(), nullable=False),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False),
|
||||||
|
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False,
|
||||||
|
server_default=sa.func.now()),
|
||||||
|
sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("plugin", sa.Text(), nullable=True),
|
||||||
|
)
|
||||||
|
op.create_index("ix_record_deliveries_session_note", "record_deliveries",
|
||||||
|
["user_id", "session_id", "note_id", "delivered_at"])
|
||||||
|
op.create_index("ix_record_deliveries_delivered_at", "record_deliveries", ["delivered_at"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_record_deliveries_delivered_at", table_name="record_deliveries")
|
||||||
|
op.drop_index("ix_record_deliveries_session_note", table_name="record_deliveries")
|
||||||
|
op.drop_table("record_deliveries")
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
"""lesson_situations — when a lesson applies, as moments and triggers
|
||||||
|
|
||||||
|
Revision ID: 0137
|
||||||
|
Revises: 0136
|
||||||
|
Create Date: 2026-11-25
|
||||||
|
|
||||||
|
One row per (lesson, kind, value). `kind` is `moment` (a catalog moment
|
||||||
|
key), `trigger` (a typed predicate on the act, in rule_field_judgments'
|
||||||
|
trigger_value form) or `none` (no situation fits; value ''). `state` is
|
||||||
|
`suggested` while a pass's proposal waits, `confirmed` or `rejected` once a
|
||||||
|
person judges it; only confirmed rows deliver. CASCADE on the lesson: a
|
||||||
|
situation of a record that no longer exists says nothing. No backfill: no
|
||||||
|
lesson had a situation before this table.
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "0137"
|
||||||
|
down_revision = "0136"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
# One place each, so the CHECKs and the model's tuples cannot drift (a new
|
||||||
|
# value later means DROP + ADD CONSTRAINT in the same migration).
|
||||||
|
_KINDS = ("moment", "trigger", "none")
|
||||||
|
_STATES = ("suggested", "confirmed", "rejected")
|
||||||
|
_SOURCES = ("pass", "edit")
|
||||||
|
|
||||||
|
|
||||||
|
def _in(values) -> str:
|
||||||
|
return "(" + ", ".join(f"'{v}'" for v in values) + ")"
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.create_table(
|
||||||
|
"lesson_situations",
|
||||||
|
sa.Column("id", sa.BigInteger(), primary_key=True),
|
||||||
|
sa.Column("lesson_id", sa.BigInteger(), sa.ForeignKey("notes.id", ondelete="CASCADE"), nullable=False),
|
||||||
|
sa.Column("kind", sa.Text(), nullable=False),
|
||||||
|
sa.Column("value", sa.Text(), nullable=False, server_default=""),
|
||||||
|
sa.Column("state", sa.Text(), nullable=False, server_default="suggested"),
|
||||||
|
sa.Column("source", sa.Text(), nullable=False, server_default="pass"),
|
||||||
|
sa.Column("note", sa.Text(), nullable=True),
|
||||||
|
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
|
||||||
|
sa.UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"),
|
||||||
|
)
|
||||||
|
op.create_check_constraint("ck_lesson_situations_kind", "lesson_situations", "kind IN " + _in(_KINDS))
|
||||||
|
op.create_check_constraint("ck_lesson_situations_state", "lesson_situations", "state IN " + _in(_STATES))
|
||||||
|
op.create_check_constraint("ck_lesson_situations_source", "lesson_situations", "source IN " + _in(_SOURCES))
|
||||||
|
op.create_index("ix_lesson_situations_lesson_id", "lesson_situations", ["lesson_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index("ix_lesson_situations_lesson_id", table_name="lesson_situations")
|
||||||
|
for name in ("source", "state", "kind"):
|
||||||
|
op.drop_constraint(f"ck_lesson_situations_{name}", "lesson_situations", type_="check")
|
||||||
|
op.drop_table("lesson_situations")
|
||||||
@@ -114,6 +114,10 @@ endpoint at `/mcp`, not these REST routes.
|
|||||||
| GET | `/api/lessons/rule-candidates` | Rules a draft lesson resembles, before it is saved |
|
| GET | `/api/lessons/rule-candidates` | Rules a draft lesson resembles, before it is saved |
|
||||||
| GET | `/api/lessons/taught-by/:record_id` | Lessons drawn from one record |
|
| GET | `/api/lessons/taught-by/:record_id` | Lessons drawn from one record |
|
||||||
| PUT | `/api/lessons/:id/rules/:rule_id` | Confirm or reject a lesson → rule link |
|
| PUT | `/api/lessons/:id/rules/:rule_id` | Confirm or reject a lesson → rule link |
|
||||||
|
| GET / POST | `/api/lessons/:id/situations` | A lesson's situations (moments and triggers it arrives at); add one |
|
||||||
|
| DELETE | `/api/lessons/situations/:situation_id` | Take a situation off its lesson |
|
||||||
|
| GET | `/api/lessons/situations/proposals` | Situations a pass proposed, waiting on a judgment, with counts |
|
||||||
|
| POST | `/api/lessons/situations/judge` | Confirm or reject proposed situations |
|
||||||
|
|
||||||
## Design systems
|
## Design systems
|
||||||
|
|
||||||
@@ -281,6 +285,7 @@ These serve the plugin's hooks.
|
|||||||
| GET / PUT | `/api/admin/smtp` · POST `/api/admin/smtp/test` | SMTP config + test email |
|
| GET / PUT | `/api/admin/smtp` · POST `/api/admin/smtp/test` | SMTP config + test email |
|
||||||
| GET | `/api/admin/logs` · `/api/admin/logs/stats` | Log entries + category counts |
|
| GET | `/api/admin/logs` · `/api/admin/logs/stats` | Log entries + category counts |
|
||||||
| GET / PUT | `/api/admin/base-url` | Get / set the public base URL |
|
| GET / PUT | `/api/admin/base-url` | Get / set the public base URL |
|
||||||
|
| GET / PUT | `/api/admin/proxy` | Get / set how many reverse proxies stand in front of Grimoire (`{"hops": n}`, or `null` for the environment's count), with what each count would read for this request |
|
||||||
| GET / PUT | `/api/admin/db-maintenance` (+ `/health`, POST `/run`) | VACUUM schedule, health, manual run |
|
| GET / PUT | `/api/admin/db-maintenance` (+ `/health`, POST `/run`) | VACUUM schedule, health, manual run |
|
||||||
| POST / GET / DELETE | `/api/admin/invitations` (+ `/:id`) | Create / list / revoke invite links |
|
| POST / GET / DELETE | `/api/admin/invitations` (+ `/:id`) | Create / list / revoke invite links |
|
||||||
| GET / PUT | `/api/admin/backups` | Scheduled backups: destination, schedule and recent runs |
|
| GET / PUT | `/api/admin/backups` | Scheduled backups: destination, schedule and recent runs |
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ Any variable marked *secret* can also be read from a file: set `<NAME>_FILE` to
|
|||||||
| `SECRET_KEY` *(secret)* | kept in `DATA_DIR` | Signs sessions and seals stored credentials. Unset, the instance makes its own on first start and keeps it in `DATA_DIR/secret_key`. Set it only to manage the key yourself; it wins over the kept one (see below) |
|
| `SECRET_KEY` *(secret)* | kept in `DATA_DIR` | Signs sessions and seals stored credentials. Unset, the instance makes its own on first start and keeps it in `DATA_DIR/secret_key`. Set it only to manage the key yourself; it wins over the kept one (see below) |
|
||||||
| `DATA_DIR` | `/data` | Where the instance keeps its own `SECRET_KEY`. Mount a volume here |
|
| `DATA_DIR` | `/data` | Where the instance keeps its own `SECRET_KEY`. Mount a volume here |
|
||||||
| `BASE_URL` | `http://localhost:5000` | Public URL, used in email links and OIDC redirects |
|
| `BASE_URL` | `http://localhost:5000` | Public URL, used in email links and OIDC redirects |
|
||||||
| `TRUSTED_PROXY_HOPS` | `1` | How many reverse proxies stand in front of Grimoire. The client address and the scheme are read that many entries in from the right of `X-Forwarded-For` and `X-Forwarded-Proto`; `0` ignores both headers. See [Behind a reverse proxy](#behind-a-reverse-proxy) |
|
| `TRUSTED_PROXY_HOPS` | `1` | The starting count of reverse proxies in front of Grimoire. **Settings → Config → Reverse proxy** is where the count is checked and set, and a count saved there wins over this. The client address and the scheme are read that many entries in from the right of `X-Forwarded-For` and `X-Forwarded-Proto`; `0` ignores both headers. See [Behind a reverse proxy](#behind-a-reverse-proxy) |
|
||||||
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR` |
|
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR` |
|
||||||
| `LOG_RETENTION_DAYS` | `90` | Days of app logs to keep |
|
| `LOG_RETENTION_DAYS` | `90` | Days of app logs to keep |
|
||||||
| `FASTEMBED_CACHE_DIR` | `/data/fastembed-cache` | Where the embedding model is stored after its first download |
|
| `FASTEMBED_CACHE_DIR` | `/data/fastembed-cache` | Where the embedding model is stored after its first download |
|
||||||
@@ -95,7 +95,11 @@ Back up the database with **Settings → Data → Scheduled backups** ([Backups]
|
|||||||
|
|
||||||
## Behind a reverse proxy
|
## Behind a reverse proxy
|
||||||
|
|
||||||
Grimoire doesn't terminate TLS. Put it behind Nginx, Traefik or Caddy, forward to port 5000, and keep port 5000 off the internet. Set `BASE_URL`, and `TRUSTED_PROXY_HOPS` to the number of proxies a request passes through (one proxy is `1`, the default; Cloudflare in front of Traefik is `2`).
|
Grimoire doesn't terminate TLS. Put it behind Nginx, Traefik or Caddy, forward to port 5000, and keep port 5000 off the internet. Set `BASE_URL`, then set the proxy count to the number of proxies a request passes through: one proxy is `1`, the default; Cloudflare's proxied DNS in front of your own proxy is `2`.
|
||||||
|
|
||||||
|
**Settings → Config → Reverse proxy** sets the count and checks it against your own request. It shows the address Grimoire reads you as, and what each count from 0 to 3 would read. Pick the count that shows your own address. When a request comes through Cloudflare, the section names the count that reads the address Cloudflare reports, with a button that sets it. `TRUSTED_PROXY_HOPS` in the environment is only the starting value: a count saved in Settings wins, and **Use the environment's** goes back to it.
|
||||||
|
|
||||||
|
A count that is too low makes every visitor read as the proxy, so they share one sign-in rate limit and a few bad sign-ins block everyone. The "too many attempts" message says so and points here. The block on sign-ins lifts after a minute; an admin who is already signed in can fix the count at once.
|
||||||
|
|
||||||
```nginx
|
```nginx
|
||||||
location / {
|
location / {
|
||||||
@@ -110,7 +114,7 @@ location / {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Each proxy appends its entry to `X-Forwarded-For` and `X-Forwarded-Proto`, so Grimoire reads the entry `TRUSTED_PROXY_HOPS` in from the right: the one your own proxy wrote. Whatever a client puts to the left of it is ignored. A header with fewer entries than that (a LAN road with one proxy beside a Cloudflare road with two) is read at its leftmost entry, the one the first proxy wrote.
|
Each proxy appends its entry to `X-Forwarded-For` and `X-Forwarded-Proto`, so Grimoire reads the entry that many in from the right: the one your own proxy wrote. Whatever a client puts to the left of it is ignored. A header with fewer entries than that (a LAN road with one proxy beside a Cloudflare road with two) is read at its leftmost entry, the one the first proxy wrote.
|
||||||
|
|
||||||
When that entry says `https`, the session cookie is marked `Secure` and the response carries `Strict-Transport-Security: max-age=31536000`. Over plain HTTP neither is sent, and Grimoire never redirects to HTTPS, so a LAN install keeps working.
|
When that entry says `https`, the session cookie is marked `Secure` and the response carries `Strict-Transport-Security: max-age=31536000`. Over plain HTTP neither is sent, and Grimoire never redirects to HTTPS, so a LAN install keeps working.
|
||||||
|
|
||||||
@@ -119,7 +123,7 @@ A hop count higher than the real number of proxies lets a client choose its own
|
|||||||
## Security checklist
|
## Security checklist
|
||||||
|
|
||||||
- **Keep the key.** Forge tokens and the backup destination's S3 secret are sealed under a key derived from `SECRET_KEY`, so a copy of the database alone can't read them. Unset, the instance makes a random key and keeps it in `/data/secret_key`, readable by its owner only; keep that volume. If the key changes (say, a restore onto an instance with a different key), Settings marks those credentials and asks for them again; nothing else breaks. The app warns at startup when `SECRET_KEY` is a public placeholder or `/data` is not a mounted volume, and refuses to start with a placeholder key (`dev-secret-change-me`, `change-me-in-production`).
|
- **Keep the key.** Forge tokens and the backup destination's S3 secret are sealed under a key derived from `SECRET_KEY`, so a copy of the database alone can't read them. Unset, the instance makes a random key and keeps it in `/data/secret_key`, readable by its owner only; keep that volume. If the key changes (say, a restore onto an instance with a different key), Settings marks those credentials and asks for them again; nothing else breaks. The app warns at startup when `SECRET_KEY` is a public placeholder or `/data` is not a mounted volume, and refuses to start with a placeholder key (`dev-secret-change-me`, `change-me-in-production`).
|
||||||
- **`TRUSTED_PROXY_HOPS`** matches the number of proxies in front of Grimoire, so rate limits and the audit log see the real client and the cookie is `Secure` over HTTPS.
|
- **The proxy count** (Settings → Config → Reverse proxy) matches the number of proxies in front of Grimoire, so rate limits and the audit log see the real client and the cookie is `Secure` over HTTPS. The section shows whether it does.
|
||||||
- **Registration** is open only for the first account. Invite people, or open it briefly from Settings.
|
- **Registration** is open only for the first account. Invite people, or open it briefly from Settings.
|
||||||
- **Signing everyone else out**: changing a password ends that user's other sessions; Settings → Account has a button for it too.
|
- **Signing everyone else out**: changing a password ends that user's other sessions; Settings → Account has a button for it too.
|
||||||
- **API keys** are per user, shown once, and can be read-only. Revoke any you no longer use under Settings → MCP Access.
|
- **API keys** are per user, shown once, and can be read-only. Revoke any you no longer use under Settings → MCP Access.
|
||||||
|
|||||||
+1
-1
@@ -103,7 +103,7 @@ Email and password, plus optional OIDC single sign-on (Authentik, Keycloak, ...)
|
|||||||
| Integrations | SearXNG, git forge connections |
|
| Integrations | SearXNG, git forge connections |
|
||||||
| Data | Export, backup and restore, scheduled backups (admin) |
|
| Data | Export, backup and restore, scheduled backups (admin) |
|
||||||
| MCP Access | API keys and the command to connect Claude |
|
| MCP Access | API keys and the command to connect Claude |
|
||||||
| Config (admin) | What's running, application URL, plugin marketplace, database maintenance, SMTP, forge webhook |
|
| Config (admin) | What's running, reverse proxy count (checked against your own request), application URL, plugin marketplace, database maintenance, SMTP, forge webhook |
|
||||||
| Shared areas (admin) | The canonical areas systems map to |
|
| Shared areas (admin) | The canonical areas systems map to |
|
||||||
| Platforms (admin) | The platform catalogue family canon is grouped by |
|
| Platforms (admin) | The platform catalogue family canon is grouped by |
|
||||||
| Users (admin) | Registration, invites, users |
|
| Users (admin) | Registration, invites, users |
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { RecordUsage } from "@/types/usage";
|
import type { RecordUsage } from "@/types/usage";
|
||||||
|
|
||||||
import { apiGet, apiPost, apiPut, apiPatch, apiDelete } from "@/api/client";
|
import { apiGet, apiPost, apiPut, apiPatch, apiDelete } from "@/api/client";
|
||||||
import type { RuleKind } from "@/api/rulebooks";
|
import type { RuleKind, RuleTrigger } from "@/api/rulebooks";
|
||||||
|
|
||||||
/** Where a lesson stands on "which rule is this an instance of?"
|
/** Where a lesson stands on "which rule is this an instance of?"
|
||||||
* (`services/lesson_rules.py`: LINKED / NO_RULE / UNJUDGED). Three answers,
|
* (`services/lesson_rules.py`: LINKED / NO_RULE / UNJUDGED). Three answers,
|
||||||
@@ -11,8 +11,8 @@ import type { RuleKind } from "@/api/rulebooks";
|
|||||||
* another one fits. */
|
* another one fits. */
|
||||||
export type RuleJudgment = "linked" | "no_rule" | "unjudged";
|
export type RuleJudgment = "linked" | "no_rule" | "unjudged";
|
||||||
|
|
||||||
/** A link's state (`models/lesson_rule_link.py` LINK_STATES). */
|
/** A judged link's state; the reads list only these two. */
|
||||||
export type LinkState = "suggested" | "confirmed" | "rejected";
|
export type LinkState = "confirmed" | "rejected";
|
||||||
|
|
||||||
/** One link from a lesson to a rule, in the reader's view: only rules the
|
/** One link from a lesson to a rule, in the reader's view: only rules the
|
||||||
* reader owns are listed (`rules_for_lessons`). */
|
* reader owns are listed (`rules_for_lessons`). */
|
||||||
@@ -20,14 +20,11 @@ export interface LessonRuleLink {
|
|||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
kind: RuleKind;
|
kind: RuleKind;
|
||||||
/** `suggested` carries nothing in retrieval until it is judged; only
|
/** `confirmed` changes what surfaces; `rejected` is kept so the reason
|
||||||
* `confirmed` changes what surfaces; `rejected` is kept so the pair is
|
* stays readable. */
|
||||||
* never proposed again. */
|
|
||||||
state: LinkState;
|
state: LinkState;
|
||||||
/** Why it was confirmed or rejected. */
|
/** Why it was confirmed or rejected. */
|
||||||
note: string;
|
note: string;
|
||||||
/** What a suggestion rests on — sent on suggested links only. */
|
|
||||||
evidence?: { situations: number; projects: number; co_surfaced: number };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A lesson: a transferable insight, retrievable by the SITUATION it applies
|
/** A lesson: a transferable insight, retrievable by the SITUATION it applies
|
||||||
@@ -79,7 +76,7 @@ export interface Lesson {
|
|||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
systems?: { id: number; name: string }[];
|
systems?: { id: number; name: string }[];
|
||||||
usage?: RecordUsage;
|
usage?: RecordUsage;
|
||||||
/** The rules this lesson points at, confirmed first, then suggested, then
|
/** The rules this lesson was judged against, confirmed first, then
|
||||||
* rejected. Absent (with `rule_judgment`) when the links could not be read
|
* rejected. Absent (with `rule_judgment`) when the links could not be read
|
||||||
* — which is "not attached", never "no rule". */
|
* — which is "not attached", never "no rule". */
|
||||||
rules?: LessonRuleLink[];
|
rules?: LessonRuleLink[];
|
||||||
@@ -232,3 +229,77 @@ export function lessonsTaughtBy(
|
|||||||
`/api/lessons/taught-by/${recordId}`,
|
`/api/lessons/taught-by/${recordId}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── when a lesson applies (services/lesson_situations.py) ────────────────
|
||||||
|
|
||||||
|
/** `moment` — a catalog moment; `trigger` — a typed predicate on the act. */
|
||||||
|
export type SituationKind = "moment" | "trigger";
|
||||||
|
|
||||||
|
/** One situation of a lesson: live (`confirmed`) or waiting on a person
|
||||||
|
* (`suggested`). `describes` is how it reads in the line a session sees. */
|
||||||
|
export interface LessonSituation {
|
||||||
|
id: number;
|
||||||
|
lesson_id: number;
|
||||||
|
kind: SituationKind;
|
||||||
|
value: string;
|
||||||
|
state: "suggested" | "confirmed";
|
||||||
|
source: "pass" | "edit";
|
||||||
|
note: string;
|
||||||
|
describes: string;
|
||||||
|
trigger?: RuleTrigger;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LessonSituationProposals {
|
||||||
|
lessons: {
|
||||||
|
lesson_id: number;
|
||||||
|
title: string;
|
||||||
|
when_to_apply: string;
|
||||||
|
proposals: LessonSituation[];
|
||||||
|
}[];
|
||||||
|
total: number;
|
||||||
|
/** Readable lessons by where they stand: arriving at a situation, read
|
||||||
|
* and found to have none, waiting on a judgment, or not yet read. */
|
||||||
|
counts: { situated: number; none_fits: number; waiting: number; unsituated: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LessonSituationsPayload {
|
||||||
|
situations: LessonSituation[];
|
||||||
|
catalog: { name: string; means: string }[];
|
||||||
|
trigger_kinds: RuleTrigger["kind"][];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SituationJudgment {
|
||||||
|
id: number;
|
||||||
|
verdict: "confirm" | "reject";
|
||||||
|
note?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLessonSituationProposals(): Promise<LessonSituationProposals> {
|
||||||
|
return apiGet("/api/lessons/situations/proposals");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A confirm makes the lesson arrive at that situation, once per session; a
|
||||||
|
* reject stops the value being proposed again. */
|
||||||
|
export function judgeLessonSituations(
|
||||||
|
judgments: SituationJudgment[],
|
||||||
|
): Promise<{ judged: LessonSituation[] }> {
|
||||||
|
return apiPost("/api/lessons/situations/judge", { judgments });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getLessonSituations(lessonId: number): Promise<LessonSituationsPayload> {
|
||||||
|
return apiGet(`/api/lessons/${lessonId}/situations`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Make one situation live: a moment, or a trigger. */
|
||||||
|
export function addLessonSituation(
|
||||||
|
lessonId: number,
|
||||||
|
body: { moment: string } | { trigger: RuleTrigger },
|
||||||
|
): Promise<LessonSituation> {
|
||||||
|
return apiPost(`/api/lessons/${lessonId}/situations`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Take a situation off its lesson; kept as rejected so it is not proposed
|
||||||
|
* again. `apiDelete` discards the body. */
|
||||||
|
export function removeLessonSituation(situationId: number): Promise<void> {
|
||||||
|
return apiDelete(`/api/lessons/situations/${situationId}`);
|
||||||
|
}
|
||||||
|
|||||||
+175
-1
@@ -1,4 +1,5 @@
|
|||||||
import { apiGet, apiPost, apiDelete } from "@/api/client";
|
import { apiGet, apiPost, apiPut, apiDelete } from "@/api/client";
|
||||||
|
import type { RuleEnforcement, RuleSalience, RuleTrigger } from "@/api/rulebooks";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The moments of work rules mount on, and the actions that
|
* The moments of work rules mount on, and the actions that
|
||||||
@@ -180,3 +181,176 @@ export function getProposals(ruleId?: number): Promise<ProposalsPayload> {
|
|||||||
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
|
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
|
||||||
return apiPost("/api/retrieval/moments/proposals/judge", { judgments });
|
return apiPost("/api/retrieval/moments/proposals/judge", { judgments });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Suggestions for how strongly a rule arrives (`enforcement`, `salience`) and
|
||||||
|
* which typed triggers reach it, from a pass that read the rule beside its
|
||||||
|
* delivery history. Nothing changes until a person confirms one.
|
||||||
|
* `GET /api/retrieval/weights/proposals`, the payload the
|
||||||
|
* `rule_weight_proposals` MCP tool returns.
|
||||||
|
*/
|
||||||
|
export type WeightField = "enforcement" | "salience" | "trigger";
|
||||||
|
|
||||||
|
/** What happened when the rule reached a session, over `days`. */
|
||||||
|
export interface WeightEvidence {
|
||||||
|
days?: number;
|
||||||
|
delivered?: number;
|
||||||
|
opened?: number;
|
||||||
|
places?: { at: string; delivered: number; opened: number }[];
|
||||||
|
pulled?: number;
|
||||||
|
applied?: number;
|
||||||
|
departed?: number;
|
||||||
|
misfire_days?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WeightProposal {
|
||||||
|
field: WeightField;
|
||||||
|
/** The enforcement or salience name; for a trigger, its stored form. */
|
||||||
|
value: string;
|
||||||
|
trigger?: RuleTrigger;
|
||||||
|
why: string;
|
||||||
|
source: "pass" | "edit";
|
||||||
|
evidence: WeightEvidence;
|
||||||
|
created_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RuleWeightProposals {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
kind: string;
|
||||||
|
statement: string;
|
||||||
|
when_to_apply: string;
|
||||||
|
home: "global" | "project";
|
||||||
|
enforcement: RuleEnforcement;
|
||||||
|
salience: RuleSalience;
|
||||||
|
mounted: string[];
|
||||||
|
triggers: RuleTrigger[];
|
||||||
|
proposals: WeightProposal[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WeightProposalsPayload {
|
||||||
|
rules: RuleWeightProposals[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WeightJudgment {
|
||||||
|
rule_id: number;
|
||||||
|
field: WeightField;
|
||||||
|
value: string | RuleTrigger;
|
||||||
|
verdict: Verdict;
|
||||||
|
note?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WeightJudgeResult {
|
||||||
|
judged: { rule_id: number; field: WeightField; value: string; state: string }[];
|
||||||
|
refused: { rule_id: number; field?: string; error: string }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One rule at one place, or a sum of them: how many sessions it was in
|
||||||
|
* force in, opened in, and what each was judged. */
|
||||||
|
export interface AdherenceCounts {
|
||||||
|
in_force: number;
|
||||||
|
opened: number;
|
||||||
|
followed: number;
|
||||||
|
/** Read and deliberately not followed, with a stated reason. */
|
||||||
|
departed: number;
|
||||||
|
broken: number;
|
||||||
|
not_applicable: number;
|
||||||
|
unjudged: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RuleAdherenceRow extends AdherenceCounts {
|
||||||
|
rule_id: number;
|
||||||
|
/** Null for a rule deleted since. */
|
||||||
|
title: string | null;
|
||||||
|
by_moment: (AdherenceCounts & { at: string })[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MomentAdherenceRow extends AdherenceCounts {
|
||||||
|
/** A moment (`work.deliver`) or an arm (`pre_tool_rule`). */
|
||||||
|
at: string;
|
||||||
|
by_rule: (AdherenceCounts & { rule_id: number; title: string | null })[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdherencePayload {
|
||||||
|
days: number;
|
||||||
|
totals: AdherenceCounts;
|
||||||
|
by_rule: RuleAdherenceRow[];
|
||||||
|
by_moment: MomentAdherenceRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One door of the kind×moment table: where a record search fires, and
|
||||||
|
* the kinds of record it may consider. */
|
||||||
|
export interface RecordKindsDoor {
|
||||||
|
/** A catalog moment, or `message` for the operator's message. */
|
||||||
|
door: string;
|
||||||
|
label: string;
|
||||||
|
fires: string;
|
||||||
|
kinds: string[];
|
||||||
|
default: string[];
|
||||||
|
/** The user changed this door; otherwise it follows the shipped default. */
|
||||||
|
changed: boolean;
|
||||||
|
/** Its lines are recorded per session; a door that answers in a tool
|
||||||
|
* reply is not, so it has no counts. */
|
||||||
|
measured: boolean;
|
||||||
|
/** Lines this door pushed of each kind, and how many were opened. */
|
||||||
|
evidence: Record<string, WayCounts>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecordKindsTable {
|
||||||
|
days: number;
|
||||||
|
evidence_failed: boolean;
|
||||||
|
kinds: { kind: string; label: string }[];
|
||||||
|
doors: RecordKindsDoor[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getRecordKinds(days = 30): Promise<RecordKindsTable> {
|
||||||
|
return apiGet(`/api/retrieval/record-kinds?days=${days}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `kinds: null` puts the door back to its shipped default. */
|
||||||
|
export function setRecordKinds(door: string, kinds: string[] | null): Promise<RecordKindsTable> {
|
||||||
|
return apiPut("/api/retrieval/record-kinds", { door, kinds });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How a record arrived in front of a session. */
|
||||||
|
export type RecordWay = "pushed" | "pointed" | "asked" | "direct";
|
||||||
|
|
||||||
|
export interface WayCounts {
|
||||||
|
delivered: number;
|
||||||
|
opened: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecordReachKind {
|
||||||
|
/** `snippet`, `note`, `lesson`, `process`, or `task:<kind>`. */
|
||||||
|
kind: string;
|
||||||
|
ways: Record<RecordWay, WayCounts>;
|
||||||
|
sources: { way: RecordWay; source: string; delivered: number; opened: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RecordReachPayload {
|
||||||
|
days: number;
|
||||||
|
sessions: number;
|
||||||
|
totals: Record<RecordWay, WayCounts>;
|
||||||
|
by_kind: RecordReachKind[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** How non-rule records reached sessions: pushed, asked for, or opened directly. */
|
||||||
|
export function getRecordReach(days = 30): Promise<RecordReachPayload> {
|
||||||
|
return apiGet(`/api/retrieval/record-reach?days=${days}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the rules in force at each moment were followed there. */
|
||||||
|
export function getAdherence(days = 30): Promise<AdherencePayload> {
|
||||||
|
return apiGet(`/api/retrieval/adherence?days=${days}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getWeightProposals(ruleId?: number): Promise<WeightProposalsPayload> {
|
||||||
|
return apiGet(`/api/retrieval/weights/proposals${ruleId ? `?rule_id=${ruleId}` : ""}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A confirm sets the field on the rule (a trigger is added beside its
|
||||||
|
* others); a reject stops that value being proposed again. */
|
||||||
|
export function judgeWeightProposals(judgments: WeightJudgment[]): Promise<WeightJudgeResult> {
|
||||||
|
return apiPost("/api/retrieval/weights/proposals/judge", { judgments });
|
||||||
|
}
|
||||||
|
|||||||
@@ -54,6 +54,27 @@ export interface RulebookTopic {
|
|||||||
*/
|
*/
|
||||||
export type RuleKind = "rule" | "preference";
|
export type RuleKind = "rule" | "preference";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What a rule does when it arrives, declared by its author. `inform` puts a
|
||||||
|
* line beside the work; `hold` makes the reply or command it governs wait for
|
||||||
|
* one read; `enforce` refuses an act its moment or trigger reaches. A
|
||||||
|
* preference is always `inform`.
|
||||||
|
*/
|
||||||
|
export type RuleEnforcement = "enforce" | "hold" | "inform";
|
||||||
|
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
|
||||||
|
export type RuleSalience = "high" | "normal" | "low";
|
||||||
|
/** What a trigger is matched against on the act: the tool called, a path it
|
||||||
|
* touches, the head of a command it runs, or a word in what it writes. */
|
||||||
|
export type RuleTriggerKind = "tool" | "path" | "command" | "keyword";
|
||||||
|
/** A typed predicate on the act, checked exactly. With no `moment` it
|
||||||
|
* delivers the rule on any matching act; with one, it makes the rule's
|
||||||
|
* mount on that moment conditional on the act matching. */
|
||||||
|
export interface RuleTrigger {
|
||||||
|
kind: RuleTriggerKind;
|
||||||
|
pattern: string;
|
||||||
|
moment?: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** A new record opened from somewhere that already knows what it is for —
|
/** A new record opened from somewhere that already knows what it is for —
|
||||||
* "Adjust this" on a reply shape opens a preference mounted on that shape's
|
* "Adjust this" on a reply shape opens a preference mounted on that shape's
|
||||||
* moment. The editor applies it once, when creating. */
|
* moment. The editor applies it once, when creating. */
|
||||||
@@ -70,6 +91,8 @@ export interface Rule {
|
|||||||
title: string;
|
title: string;
|
||||||
statement: string;
|
statement: string;
|
||||||
kind: RuleKind;
|
kind: RuleKind;
|
||||||
|
enforcement: RuleEnforcement;
|
||||||
|
salience: RuleSalience;
|
||||||
/** WHEN this rule fires — the trigger, not the instruction. */
|
/** WHEN this rule fires — the trigger, not the instruction. */
|
||||||
when_to_apply: string;
|
when_to_apply: string;
|
||||||
why: string;
|
why: string;
|
||||||
@@ -94,10 +117,12 @@ export interface Rule {
|
|||||||
/** The moments this rule arrives at whenever they happen,
|
/** The moments this rule arrives at whenever they happen,
|
||||||
* in catalog order. Present only when the rule is mounted. */
|
* in catalog order. Present only when the rule is mounted. */
|
||||||
moments?: string[];
|
moments?: string[];
|
||||||
|
/** Present only when the rule has triggers. */
|
||||||
|
triggers?: RuleTrigger[];
|
||||||
relations?: RuleRelation[];
|
relations?: RuleRelation[];
|
||||||
/** The lessons that point at this rule — the concrete
|
/** The lessons judged against this rule — confirmed instances of it
|
||||||
* situations judged instances of it, plus any suggested and awaiting a
|
* first, then those judged not to be. Readable lessons only; omitted when
|
||||||
* judgment. Readable lessons only; omitted when there are none. */
|
* there are none. */
|
||||||
lessons?: { id: number; title: string; state: LinkState; note: string }[];
|
lessons?: { id: number; title: string; state: LinkState; note: string }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,6 +138,10 @@ export interface RuleHeader {
|
|||||||
topic_id: number | null;
|
topic_id: number | null;
|
||||||
/** Unconditional on the wire (services.rulebooks.rule_brief). */
|
/** Unconditional on the wire (services.rulebooks.rule_brief). */
|
||||||
kind: RuleKind;
|
kind: RuleKind;
|
||||||
|
/** Unconditional on the wire, like `kind`. */
|
||||||
|
enforcement: RuleEnforcement;
|
||||||
|
/** Present only when raised or lowered from `normal`. */
|
||||||
|
salience?: RuleSalience;
|
||||||
/** A date (YYYY-MM-DD), not a timestamp. */
|
/** A date (YYYY-MM-DD), not a timestamp. */
|
||||||
updated_at: string | null;
|
updated_at: string | null;
|
||||||
when_to_apply?: string;
|
when_to_apply?: string;
|
||||||
@@ -217,6 +246,8 @@ export interface RuleWrite {
|
|||||||
/** Writable from the editor: a preference is not a lesser rule, it is a
|
/** Writable from the editor: a preference is not a lesser rule, it is a
|
||||||
* different force, and the person writing it is the one who knows which. */
|
* different force, and the person writing it is the one who knows which. */
|
||||||
kind: RuleKind;
|
kind: RuleKind;
|
||||||
|
enforcement: RuleEnforcement;
|
||||||
|
salience: RuleSalience;
|
||||||
when_to_apply: string;
|
when_to_apply: string;
|
||||||
why: string;
|
why: string;
|
||||||
how_to_apply: string;
|
how_to_apply: string;
|
||||||
@@ -224,6 +255,8 @@ export interface RuleWrite {
|
|||||||
system_ids: number[];
|
system_ids: number[];
|
||||||
/** Replaces the set; [] unmounts the rule from every moment. */
|
/** Replaces the set; [] unmounts the rule from every moment. */
|
||||||
moments: string[];
|
moments: string[];
|
||||||
|
/** Replaces the set; [] clears every trigger. */
|
||||||
|
triggers: RuleTrigger[];
|
||||||
arose_from_id: number | null;
|
arose_from_id: number | null;
|
||||||
verify_with: string;
|
verify_with: string;
|
||||||
expires_when: string;
|
expires_when: string;
|
||||||
|
|||||||
@@ -147,6 +147,45 @@
|
|||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A record reference — `#4286`, `milestone 639`, `rule 34`. Reads as a link in
|
||||||
|
running text rather than a chip: a work log cites a dozen of them, and a row
|
||||||
|
of pills would drown the sentence they sit in. */
|
||||||
|
.record-ref {
|
||||||
|
color: var(--fs-wikilink);
|
||||||
|
text-decoration: underline;
|
||||||
|
text-decoration-color: color-mix(in srgb, var(--fs-wikilink) 40%, transparent);
|
||||||
|
text-underline-offset: 0.15em;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
border-radius: var(--fs-radius-sm);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.record-ref:hover {
|
||||||
|
text-decoration-color: currentColor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Drawn with its title: the title reads as the link, the number after it is
|
||||||
|
the citation, quieter and never split across lines. */
|
||||||
|
.record-ref__id {
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
font-size: 0.85em;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.record-ref:focus-visible {
|
||||||
|
outline: none;
|
||||||
|
box-shadow: var(--fs-focus-ring);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* One the reader cannot open: missing, trashed or not shared. Still legible —
|
||||||
|
the number is part of the sentence — but plainly not a way through. */
|
||||||
|
.record-ref--missing {
|
||||||
|
color: var(--fs-text-tertiary-fg);
|
||||||
|
text-decoration-style: dashed;
|
||||||
|
text-decoration-color: var(--fs-text-tertiary);
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
/* Task list */
|
/* Task list */
|
||||||
.prose ul[data-type="taskList"] {
|
.prose ul[data-type="taskList"] {
|
||||||
list-style: none;
|
list-style: none;
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/* A proposal about a rule waiting on a person — the panels under
|
||||||
|
Settings › Moments that list mount proposals and weight suggestions.
|
||||||
|
Loaded scoped by each, so these class names stay local to the panels. */
|
||||||
|
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
|
||||||
|
.proposals-bar { display: flex; justify-content: flex-end; }
|
||||||
|
.proposal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.proposal-rule {
|
||||||
|
padding: var(--fs-space-3);
|
||||||
|
background: var(--fs-surface-page);
|
||||||
|
border: 1px dashed var(--fs-border-color);
|
||||||
|
border-radius: var(--fs-radius-md);
|
||||||
|
}
|
||||||
|
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
|
||||||
|
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
|
||||||
|
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
|
||||||
|
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
|
||||||
|
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
|
||||||
|
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
|
||||||
|
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
|
||||||
|
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
|
||||||
|
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
|
||||||
|
.proposal-reasons {
|
||||||
|
flex-basis: 100%;
|
||||||
|
margin: 0;
|
||||||
|
padding-left: var(--fs-space-4);
|
||||||
|
font-size: var(--fs-size-tiny);
|
||||||
|
color: var(--fs-text-tertiary);
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from "vue";
|
||||||
|
import {
|
||||||
|
getLessonSituationProposals, judgeLessonSituations,
|
||||||
|
type LessonSituation, type LessonSituationProposals,
|
||||||
|
} from "@/api/lessons";
|
||||||
|
import { apiErrorMessage } from "@/api/client";
|
||||||
|
import { useToastStore } from "@/stores/toast";
|
||||||
|
import ConfirmDialog from "@/components/ConfirmDialog.vue";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When each lesson applies, waiting on a person. A pass read each lesson
|
||||||
|
* beside the rules it is an instance of and proposed the moments of work, or
|
||||||
|
* the triggers on an act (a path, a command, a tool, a word), at which it
|
||||||
|
* should arrive. A lesson with a confirmed situation arrives there, once per
|
||||||
|
* session, instead of whenever an edit's words resemble it. Nothing changes
|
||||||
|
* until "Apply" is pressed; "Not this" keeps the value from being proposed
|
||||||
|
* again. The same judgment `judge_lesson_situations` makes in a session.
|
||||||
|
*/
|
||||||
|
const toast = useToastStore();
|
||||||
|
|
||||||
|
const data = ref<LessonSituationProposals | null>(null);
|
||||||
|
const failed = ref(false);
|
||||||
|
const busy = ref<number | "all" | null>(null);
|
||||||
|
const confirmingAll = ref(false);
|
||||||
|
|
||||||
|
const lessons = computed(() => data.value?.lessons ?? []);
|
||||||
|
const counts = computed(() => data.value?.counts);
|
||||||
|
const allIds = computed(() => lessons.value.flatMap((l) => l.proposals.map((p) => p.id)));
|
||||||
|
|
||||||
|
const allSummary = computed(() => {
|
||||||
|
const n = allIds.value.length;
|
||||||
|
const across = `${lessons.value.length} lesson${lessons.value.length === 1 ? "" : "s"}`;
|
||||||
|
return `${n} situation${n === 1 ? "" : "s"} across ${across} take effect at once: each lesson `
|
||||||
|
+ "will arrive when its situation is reached, once per session.";
|
||||||
|
});
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
data.value = await getLessonSituationProposals();
|
||||||
|
failed.value = false;
|
||||||
|
} catch {
|
||||||
|
failed.value = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decide(p: LessonSituation, verdict: "confirm" | "reject") {
|
||||||
|
busy.value = p.id;
|
||||||
|
try {
|
||||||
|
await judgeLessonSituations([{
|
||||||
|
id: p.id, verdict,
|
||||||
|
note: verdict === "confirm" ? "Applied in Settings." : "Declined in Settings.",
|
||||||
|
}]);
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, "Could not record that"), "error");
|
||||||
|
} finally {
|
||||||
|
busy.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyAll() {
|
||||||
|
confirmingAll.value = false;
|
||||||
|
busy.value = "all";
|
||||||
|
try {
|
||||||
|
const out = await judgeLessonSituations(allIds.value.map((id) => ({
|
||||||
|
id, verdict: "confirm" as const, note: "Applied with Apply all in Settings.",
|
||||||
|
})));
|
||||||
|
toast.show(`${out.judged.length} applied.`, "success");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, "Could not apply the suggestions"), "error");
|
||||||
|
} finally {
|
||||||
|
busy.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="proposals" aria-labelledby="lesson-situations-title">
|
||||||
|
<h3 id="lesson-situations-title" class="sub-title">When lessons arrive</h3>
|
||||||
|
<p v-if="failed" class="error-msg">
|
||||||
|
The lesson situations could not be loaded.
|
||||||
|
<button type="button" class="btn-text" @click="load">Try again</button>
|
||||||
|
</p>
|
||||||
|
<template v-else-if="data">
|
||||||
|
<p class="field-hint">
|
||||||
|
A lesson with a situation arrives when the work reaches it — a moment like delivering or
|
||||||
|
finishing, or an act on a path, command or tool — once per session. A lesson without one
|
||||||
|
is found only when a message resembles it.
|
||||||
|
<template v-if="counts">
|
||||||
|
{{ counts.situated }} arrive by situation, {{ counts.none_fits }} were read and fit none,
|
||||||
|
{{ counts.waiting }} wait on you, and {{ counts.unsituated }} have not been read.
|
||||||
|
</template>
|
||||||
|
</p>
|
||||||
|
<p v-if="!lessons.length" class="field-hint empty-note">
|
||||||
|
Nothing is waiting. A session proposes situations with <code>lessons_to_situate</code> and
|
||||||
|
<code>propose_lesson_situations</code>; they appear here to apply or decline.
|
||||||
|
</p>
|
||||||
|
<template v-else>
|
||||||
|
<div class="proposals-bar">
|
||||||
|
<button
|
||||||
|
type="button" class="btn-primary btn-sm"
|
||||||
|
:disabled="busy !== null"
|
||||||
|
@click="confirmingAll = true"
|
||||||
|
>Apply all {{ allIds.length }}</button>
|
||||||
|
</div>
|
||||||
|
<ul class="proposal-list">
|
||||||
|
<li v-for="lesson in lessons" :key="lesson.lesson_id" class="proposal-rule">
|
||||||
|
<div class="rule-head">
|
||||||
|
<router-link :to="`/lessons/${lesson.lesson_id}`" class="rule-title">
|
||||||
|
#{{ lesson.lesson_id }} {{ lesson.title }}
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
<p v-if="lesson.when_to_apply" class="rule-statement">
|
||||||
|
When to apply: {{ lesson.when_to_apply }}
|
||||||
|
</p>
|
||||||
|
<ul class="proposal-items">
|
||||||
|
<li v-for="p in lesson.proposals" :key="p.id" class="proposal-item">
|
||||||
|
<code class="moment-name">{{ p.describes }}</code>
|
||||||
|
<span class="proposal-why">{{ p.note }}</span>
|
||||||
|
<span class="proposal-actions">
|
||||||
|
<button
|
||||||
|
type="button" class="btn-primary btn-sm"
|
||||||
|
:disabled="busy !== null"
|
||||||
|
@click="decide(p, 'confirm')"
|
||||||
|
>Apply</button>
|
||||||
|
<button
|
||||||
|
type="button" class="btn-text"
|
||||||
|
:disabled="busy !== null"
|
||||||
|
@click="decide(p, 'reject')"
|
||||||
|
>Not this</button>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
<ConfirmDialog
|
||||||
|
v-if="confirmingAll"
|
||||||
|
title="Apply every situation?"
|
||||||
|
:message="allSummary"
|
||||||
|
confirm-label="Apply all"
|
||||||
|
:danger="false"
|
||||||
|
@confirm="applyAll"
|
||||||
|
@cancel="confirmingAll = false"
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped src="@/assets/rule-proposals.css" />
|
||||||
|
|
||||||
|
<style src="@/assets/moments-shared.css" />
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.empty-note { margin: 0; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref, watch } from "vue";
|
||||||
|
import {
|
||||||
|
addLessonSituation, getLessonSituations, judgeLessonSituations, removeLessonSituation,
|
||||||
|
type LessonSituation, type LessonSituationsPayload,
|
||||||
|
} from "@/api/lessons";
|
||||||
|
import type { RuleTrigger } from "@/api/rulebooks";
|
||||||
|
import { apiErrorMessage } from "@/api/client";
|
||||||
|
import { useToastStore } from "@/stores/toast";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When a lesson arrives. A situation is a moment of work (delivering,
|
||||||
|
* finishing, …) or a trigger on an act (a path, a command, a tool, a word);
|
||||||
|
* the lesson is shown to a session when its work reaches one, once per
|
||||||
|
* session. Proposals from a pass wait here and in Settings › Moments until
|
||||||
|
* applied or declined. A writer can add a situation directly or take one off;
|
||||||
|
* one taken off is not proposed again.
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ lessonId: number; canWrite: boolean }>();
|
||||||
|
const toast = useToastStore();
|
||||||
|
|
||||||
|
const data = ref<LessonSituationsPayload | null>(null);
|
||||||
|
const failed = ref(false);
|
||||||
|
const busy = ref(false);
|
||||||
|
|
||||||
|
// The add form: what kind of situation, then a moment or a pattern.
|
||||||
|
const what = ref<"moment" | RuleTrigger["kind"]>("moment");
|
||||||
|
const moment = ref("");
|
||||||
|
const pattern = ref("");
|
||||||
|
|
||||||
|
// Placeholders are generic shapes, never anyone's own paths or commands.
|
||||||
|
const PLACEHOLDER: Record<string, string> = {
|
||||||
|
path: "e.g. migrations/**/*.py",
|
||||||
|
command: "e.g. git push",
|
||||||
|
tool: "e.g. edit",
|
||||||
|
keyword: "e.g. release",
|
||||||
|
};
|
||||||
|
|
||||||
|
const live = computed(() => (data.value?.situations ?? []).filter((s) => s.state === "confirmed"));
|
||||||
|
const waiting = computed(() => (data.value?.situations ?? []).filter((s) => s.state === "suggested"));
|
||||||
|
const canAdd = computed(() =>
|
||||||
|
what.value === "moment" ? !!moment.value : pattern.value.trim().length > 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
data.value = await getLessonSituations(props.lessonId);
|
||||||
|
failed.value = false;
|
||||||
|
} catch {
|
||||||
|
failed.value = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function run(action: () => Promise<unknown>, done: string, failure: string) {
|
||||||
|
busy.value = true;
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
toast.show(done, "success");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, failure), "error");
|
||||||
|
} finally {
|
||||||
|
busy.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function add() {
|
||||||
|
const body = what.value === "moment"
|
||||||
|
? { moment: moment.value }
|
||||||
|
: { trigger: { kind: what.value, pattern: pattern.value.trim() } };
|
||||||
|
return run(async () => {
|
||||||
|
await addLessonSituation(props.lessonId, body);
|
||||||
|
moment.value = "";
|
||||||
|
pattern.value = "";
|
||||||
|
}, "The lesson now arrives there", "Could not add that situation");
|
||||||
|
}
|
||||||
|
|
||||||
|
function remove(s: LessonSituation) {
|
||||||
|
return run(() => removeLessonSituation(s.id), "Taken off", "Could not take that off");
|
||||||
|
}
|
||||||
|
|
||||||
|
function judge(s: LessonSituation, verdict: "confirm" | "reject") {
|
||||||
|
return run(
|
||||||
|
() => judgeLessonSituations([{
|
||||||
|
id: s.id, verdict, note: verdict === "confirm" ? "Applied on the lesson." : "Declined on the lesson.",
|
||||||
|
}]),
|
||||||
|
verdict === "confirm" ? "Applied" : "Declined",
|
||||||
|
"Could not record that",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
watch(() => props.lessonId, load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="ls-panel" aria-labelledby="ls-title">
|
||||||
|
<h2 id="ls-title" class="ls-label">When it arrives</h2>
|
||||||
|
<p v-if="failed" class="ls-muted">
|
||||||
|
The situations could not be loaded.
|
||||||
|
<button type="button" class="ls-text-btn" @click="load">Try again</button>
|
||||||
|
</p>
|
||||||
|
<template v-else-if="data">
|
||||||
|
<ul v-if="live.length" class="ls-list">
|
||||||
|
<li v-for="s in live" :key="s.id" class="ls-item">
|
||||||
|
<code class="ls-value">{{ s.describes }}</code>
|
||||||
|
<button
|
||||||
|
v-if="canWrite" type="button" class="ls-text-btn"
|
||||||
|
:disabled="busy" :aria-label="`Take off ${s.describes}`"
|
||||||
|
@click="remove(s)"
|
||||||
|
>Take off</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-else class="ls-muted">
|
||||||
|
No situation yet — the lesson is found only when a message resembles it.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<template v-if="waiting.length">
|
||||||
|
<h3 class="ls-sub">Proposed</h3>
|
||||||
|
<ul class="ls-list">
|
||||||
|
<li v-for="s in waiting" :key="s.id" class="ls-item">
|
||||||
|
<code class="ls-value">{{ s.describes }}</code>
|
||||||
|
<span v-if="s.note" class="ls-note">{{ s.note }}</span>
|
||||||
|
<span v-if="canWrite" class="ls-actions">
|
||||||
|
<button type="button" class="ls-btn" :disabled="busy" @click="judge(s, 'confirm')">Apply</button>
|
||||||
|
<button type="button" class="ls-text-btn" :disabled="busy" @click="judge(s, 'reject')">Not this</button>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<form v-if="canWrite" class="ls-add" @submit.prevent="add">
|
||||||
|
<label class="ls-field">
|
||||||
|
<span class="ls-field-label">Arrive at</span>
|
||||||
|
<select v-model="what" class="ls-input" :disabled="busy">
|
||||||
|
<option value="moment">a moment of work</option>
|
||||||
|
<option v-for="k in data.trigger_kinds" :key="k" :value="k">a {{ k }}</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label v-if="what === 'moment'" class="ls-field ls-grow">
|
||||||
|
<span class="ls-field-label">Moment</span>
|
||||||
|
<select v-model="moment" class="ls-input" :disabled="busy">
|
||||||
|
<option value="" disabled>Choose a moment</option>
|
||||||
|
<option v-for="m in data.catalog" :key="m.name" :value="m.name">
|
||||||
|
{{ m.name }} — {{ m.means }}
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label v-else class="ls-field ls-grow">
|
||||||
|
<span class="ls-field-label">Pattern</span>
|
||||||
|
<input
|
||||||
|
v-model="pattern" class="ls-input" type="text" maxlength="200"
|
||||||
|
:placeholder="PLACEHOLDER[what]" :disabled="busy"
|
||||||
|
>
|
||||||
|
</label>
|
||||||
|
<button type="submit" class="ls-btn" :disabled="busy || !canAdd">Add</button>
|
||||||
|
</form>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.ls-panel {
|
||||||
|
margin-top: 1.75rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
border-top: 1px solid var(--fs-border-color);
|
||||||
|
}
|
||||||
|
.ls-label {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
font-weight: 500;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
color: var(--fs-text-tertiary);
|
||||||
|
}
|
||||||
|
.ls-sub {
|
||||||
|
margin: var(--fs-space-3) 0 var(--fs-space-1);
|
||||||
|
font-size: var(--fs-size-label);
|
||||||
|
font-weight: var(--fs-weight-medium);
|
||||||
|
color: var(--fs-text-tertiary);
|
||||||
|
}
|
||||||
|
.ls-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
|
||||||
|
.ls-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: 0.9rem; }
|
||||||
|
.ls-value { font-size: var(--fs-size-label); color: var(--fs-text-primary); }
|
||||||
|
.ls-note { flex: 1 1 14rem; color: var(--fs-text-secondary); font-size: var(--fs-size-label); }
|
||||||
|
.ls-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
|
||||||
|
.ls-muted { margin: 0; color: var(--fs-text-secondary); font-size: 0.88rem; }
|
||||||
|
.ls-add {
|
||||||
|
display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--fs-space-2);
|
||||||
|
margin-top: var(--fs-space-3);
|
||||||
|
}
|
||||||
|
.ls-field { display: flex; flex-direction: column; gap: var(--fs-space-1); }
|
||||||
|
.ls-grow { flex: 1 1 14rem; }
|
||||||
|
.ls-field-label { font-size: var(--fs-size-label); color: var(--fs-text-tertiary); }
|
||||||
|
.ls-input {
|
||||||
|
padding: 0.4rem 0.6rem;
|
||||||
|
border: 1px solid var(--fs-border-color);
|
||||||
|
border-radius: var(--fs-radius-sm);
|
||||||
|
background: var(--fs-surface-raised);
|
||||||
|
color: var(--fs-text-primary);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
}
|
||||||
|
.ls-btn {
|
||||||
|
padding: 0.4rem 0.9rem;
|
||||||
|
border: 1px solid var(--fs-border-color);
|
||||||
|
border-radius: var(--fs-radius-sm);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--fs-text-primary);
|
||||||
|
font: inherit;
|
||||||
|
font-size: 0.88rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.ls-text-btn {
|
||||||
|
padding: 0;
|
||||||
|
border: none;
|
||||||
|
background: none;
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
font: inherit;
|
||||||
|
font-size: var(--fs-size-label);
|
||||||
|
text-decoration: underline;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.ls-input:focus-visible,
|
||||||
|
.ls-btn:focus-visible,
|
||||||
|
.ls-text-btn:focus-visible { outline: none; box-shadow: var(--fs-focus-ring); }
|
||||||
|
.ls-btn:disabled,
|
||||||
|
.ls-text-btn:disabled,
|
||||||
|
.ls-input:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
|
||||||
|
</style>
|
||||||
@@ -158,33 +158,6 @@ onMounted(load);
|
|||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped src="@/assets/rule-proposals.css" />
|
||||||
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
|
||||||
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
|
|
||||||
.proposal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
|
||||||
.proposal-rule {
|
|
||||||
padding: var(--fs-space-3);
|
|
||||||
background: var(--fs-surface-page);
|
|
||||||
border: 1px dashed var(--fs-border-color);
|
|
||||||
border-radius: var(--fs-radius-md);
|
|
||||||
}
|
|
||||||
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
|
|
||||||
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
|
|
||||||
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
|
|
||||||
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
|
|
||||||
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
|
||||||
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
|
|
||||||
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
|
|
||||||
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
|
|
||||||
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
|
|
||||||
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
|
|
||||||
.proposal-reasons {
|
|
||||||
flex-basis: 100%;
|
|
||||||
margin: 0;
|
|
||||||
padding-left: var(--fs-space-4);
|
|
||||||
font-size: var(--fs-size-tiny);
|
|
||||||
color: var(--fs-text-tertiary);
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|
||||||
<style src="@/assets/moments-shared.css" />
|
<style src="@/assets/moments-shared.css" />
|
||||||
|
|||||||
@@ -1,12 +1,26 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { MomentRuleUsage } from "@/api/moments";
|
import type { AdherenceCounts, MomentRuleUsage } from "@/api/moments";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Which rules a moment delivered, and whether an agent went on to read each.
|
* Which rules a moment delivered, whether an agent went on to read each, and
|
||||||
* The moment's own counts cannot say this once two rules are mounted there.
|
* — where a verdict exists — whether it was followed there. The moment's own
|
||||||
* Closed by default: the counts in the row above are what most visits want.
|
* counts cannot say this once two rules are mounted there. Closed by default:
|
||||||
|
* the counts in the row above are what most visits want.
|
||||||
*/
|
*/
|
||||||
defineProps<{ rules: MomentRuleUsage[] }>();
|
withDefaults(defineProps<{
|
||||||
|
rules: MomentRuleUsage[];
|
||||||
|
/** This moment's adherence per rule id, from the adherence readout. */
|
||||||
|
adherence?: Record<number, AdherenceCounts>;
|
||||||
|
}>(), { adherence: () => ({}) });
|
||||||
|
|
||||||
|
function verdicts(c: AdherenceCounts | undefined): string {
|
||||||
|
if (!c) return "";
|
||||||
|
const parts = [`followed ${c.followed} of ${c.in_force}`];
|
||||||
|
if (c.broken) parts.push(`broken ${c.broken}`);
|
||||||
|
if (c.departed) parts.push(`departed ${c.departed}`);
|
||||||
|
if (c.not_applicable) parts.push(`not applicable ${c.not_applicable}`);
|
||||||
|
return parts.join(" · ");
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -19,6 +33,7 @@ defineProps<{ rules: MomentRuleUsage[] }>();
|
|||||||
<span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'">
|
<span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'">
|
||||||
{{ r.opened ? "opened" : "not opened" }}
|
{{ r.opened ? "opened" : "not opened" }}
|
||||||
</span>
|
</span>
|
||||||
|
<span v-if="adherence[r.rule_id]" class="delivered-count">{{ verdicts(adherence[r.rule_id]) }}</span>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</details>
|
</details>
|
||||||
|
|||||||
@@ -3,7 +3,13 @@ import { computed, onMounted, ref } from "vue";
|
|||||||
import { useMomentsStore } from "@/stores/moments";
|
import { useMomentsStore } from "@/stores/moments";
|
||||||
import MomentProposals from "@/components/MomentProposals.vue";
|
import MomentProposals from "@/components/MomentProposals.vue";
|
||||||
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
|
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
|
||||||
import type { MomentAction, MomentUsage } from "@/api/moments";
|
import WeightProposals from "@/components/WeightProposals.vue";
|
||||||
|
import LessonSituationProposals from "@/components/LessonSituationProposals.vue";
|
||||||
|
import RecordKinds from "@/components/RecordKinds.vue";
|
||||||
|
import RecordReach from "@/components/RecordReach.vue";
|
||||||
|
import RuleAdherence from "@/components/RuleAdherence.vue";
|
||||||
|
import { getAdherence, getRecordReach } from "@/api/moments";
|
||||||
|
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload } from "@/api/moments";
|
||||||
import { fmtDate } from "@/utils/dateFormat";
|
import { fmtDate } from "@/utils/dateFormat";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -31,6 +37,42 @@ function usage(moment: string): MomentUsage | null {
|
|||||||
return data.value?.usage.by_moment[moment] ?? null;
|
return data.value?.usage.by_moment[moment] ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Adherence is read on its own, so a failure there leaves the catalog and the
|
||||||
|
// delivery counts standing and says so in its own panel.
|
||||||
|
const adherence = ref<AdherencePayload | null>(null);
|
||||||
|
const adherenceFailed = ref(false);
|
||||||
|
|
||||||
|
async function loadAdherence() {
|
||||||
|
try {
|
||||||
|
adherence.value = await getAdherence(days.value);
|
||||||
|
adherenceFailed.value = false;
|
||||||
|
} catch {
|
||||||
|
adherenceFailed.value = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// How records other than rules reach sessions, read on its own for the same
|
||||||
|
// reason as adherence.
|
||||||
|
const reach = ref<RecordReachPayload | null>(null);
|
||||||
|
const reachFailed = ref(false);
|
||||||
|
|
||||||
|
async function loadReach() {
|
||||||
|
try {
|
||||||
|
reach.value = await getRecordReach(days.value);
|
||||||
|
reachFailed.value = false;
|
||||||
|
} catch {
|
||||||
|
reachFailed.value = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function followed(moment: string): MomentAdherenceRow | null {
|
||||||
|
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function verdictsByRule(moment: string): Record<number, MomentAdherenceRow["by_rule"][number]> {
|
||||||
|
return Object.fromEntries((followed(moment)?.by_rule ?? []).map((r) => [r.rule_id, r]));
|
||||||
|
}
|
||||||
|
|
||||||
// A named procedure is its own moment (`skill.<name>`), so it appears here
|
// A named procedure is its own moment (`skill.<name>`), so it appears here
|
||||||
// only once something is mounted on it or has been delivered at it — the
|
// only once something is mounted on it or has been delivered at it — the
|
||||||
// catalog cannot list procedures it has never heard of.
|
// catalog cannot list procedures it has never heard of.
|
||||||
@@ -101,7 +143,10 @@ async function addMapping() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(() => store.load(true));
|
onMounted(async () => {
|
||||||
|
await store.load(true);
|
||||||
|
await Promise.all([loadAdherence(), loadReach()]);
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -126,6 +171,11 @@ onMounted(() => store.load(true));
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<MomentProposals />
|
<MomentProposals />
|
||||||
|
<WeightProposals />
|
||||||
|
<LessonSituationProposals />
|
||||||
|
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
|
||||||
|
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
|
||||||
|
<RecordKinds :days="days" />
|
||||||
|
|
||||||
<ul class="moment-list">
|
<ul class="moment-list">
|
||||||
<li v-for="m in catalog" :key="m.name" class="moment-row">
|
<li v-for="m in catalog" :key="m.name" class="moment-row">
|
||||||
@@ -142,6 +192,9 @@ onMounted(() => store.load(true));
|
|||||||
last {{ fmtDate(usage(m.name)!.last_delivered_at!) }}
|
last {{ fmtDate(usage(m.name)!.last_delivered_at!) }}
|
||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
|
<span v-if="followed(m.name)">
|
||||||
|
followed {{ followed(m.name)!.followed }} of {{ followed(m.name)!.in_force }} in force
|
||||||
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<p class="moment-desc">{{ m.means }}</p>
|
<p class="moment-desc">{{ m.means }}</p>
|
||||||
@@ -168,7 +221,9 @@ onMounted(() => store.load(true));
|
|||||||
>×</button>
|
>×</button>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<MomentRuleUsage v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" />
|
<MomentRuleUsage
|
||||||
|
v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" :adherence="verdictsByRule(m.name)"
|
||||||
|
/>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
@@ -186,9 +241,14 @@ onMounted(() => store.load(true));
|
|||||||
<span>delivered {{ usage(name)!.delivered }}</span>
|
<span>delivered {{ usage(name)!.delivered }}</span>
|
||||||
<span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span>
|
<span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span>
|
||||||
</template>
|
</template>
|
||||||
|
<span v-if="followed(name)">
|
||||||
|
followed {{ followed(name)!.followed }} of {{ followed(name)!.in_force }} in force
|
||||||
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<MomentRuleUsage v-if="usage(name)" :rules="usage(name)!.by_rule" />
|
<MomentRuleUsage
|
||||||
|
v-if="usage(name)" :rules="usage(name)!.by_rule" :adherence="verdictsByRule(name)"
|
||||||
|
/>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from "vue";
|
||||||
|
import { apiErrorMessage } from "@/api/client";
|
||||||
|
import { getRecordKinds, setRecordKinds } from "@/api/moments";
|
||||||
|
import type { RecordKindsDoor, RecordKindsTable } from "@/api/moments";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The kind×moment table: for each point where a record search fires, which
|
||||||
|
* kinds of record it may consider. A kind left unticked is never pushed
|
||||||
|
* there; a session can still search for it. Each box shows the lines that
|
||||||
|
* door pushed of that kind and how many were opened, so a change is made
|
||||||
|
* against its own evidence. A change saves as soon as it is made.
|
||||||
|
*/
|
||||||
|
const props = defineProps<{ days: number }>();
|
||||||
|
|
||||||
|
const table = ref<RecordKindsTable | null>(null);
|
||||||
|
const failed = ref(false);
|
||||||
|
const saving = ref<string | null>(null);
|
||||||
|
const saveError = ref("");
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
table.value = await getRecordKinds(props.days);
|
||||||
|
failed.value = false;
|
||||||
|
} catch {
|
||||||
|
failed.value = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(door: string, kinds: string[] | null) {
|
||||||
|
saving.value = door;
|
||||||
|
saveError.value = "";
|
||||||
|
try {
|
||||||
|
table.value = await setRecordKinds(door, kinds);
|
||||||
|
} catch (e) {
|
||||||
|
saveError.value = apiErrorMessage(e, "The change could not be saved.");
|
||||||
|
} finally {
|
||||||
|
saving.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(row: RecordKindsDoor, kind: string, on: boolean) {
|
||||||
|
const next = on ? [...row.kinds, kind] : row.kinds.filter((k) => k !== kind);
|
||||||
|
void save(row.door, next);
|
||||||
|
}
|
||||||
|
|
||||||
|
function evidenceText(row: RecordKindsDoor, kind: string): string {
|
||||||
|
const c = row.evidence[kind];
|
||||||
|
return c ? `${c.opened} of ${c.delivered} opened` : "none shown";
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="kinds" aria-labelledby="kinds-title">
|
||||||
|
<h3 id="kinds-title" class="sub-title">Which records each moment considers</h3>
|
||||||
|
<p v-if="failed" class="error-msg">
|
||||||
|
The table could not be loaded.
|
||||||
|
<button type="button" class="btn-text" @click="load">Try again</button>
|
||||||
|
</p>
|
||||||
|
<p v-else-if="!table" class="empty-msg">Loading the table…</p>
|
||||||
|
<template v-else>
|
||||||
|
<p class="field-hint">
|
||||||
|
A search for records runs at each point below. An unticked kind is never shown there;
|
||||||
|
a session can still search for it. Beside each kind: lines shown there over the last
|
||||||
|
{{ table.days }} days, and how many were opened.
|
||||||
|
</p>
|
||||||
|
<p v-if="table.evidence_failed" class="error-msg">
|
||||||
|
The counts could not be read, so they are missing below, not zero.
|
||||||
|
</p>
|
||||||
|
<p v-if="saveError" class="error-msg" role="alert">{{ saveError }}</p>
|
||||||
|
<fieldset
|
||||||
|
v-for="row in table.doors" :key="row.door" class="door"
|
||||||
|
:disabled="saving === row.door"
|
||||||
|
>
|
||||||
|
<legend class="door-head">
|
||||||
|
<span class="door-label">{{ row.label }}</span>
|
||||||
|
<code class="moment-name">{{ row.door }}</code>
|
||||||
|
<span class="door-fires">{{ row.fires }}</span>
|
||||||
|
<span v-if="!row.changed" class="door-default">shipped default</span>
|
||||||
|
</legend>
|
||||||
|
<p v-if="!row.measured" class="door-default">
|
||||||
|
Named by id in the reply that sets a task in progress, so there are no counts for it.
|
||||||
|
</p>
|
||||||
|
<ul class="kind-list">
|
||||||
|
<li v-for="k in table.kinds" :key="k.kind" class="kind-cell">
|
||||||
|
<label class="kind-label">
|
||||||
|
<input
|
||||||
|
type="checkbox" :checked="row.kinds.includes(k.kind)"
|
||||||
|
@change="toggle(row, k.kind, ($event.target as HTMLInputElement).checked)"
|
||||||
|
/>
|
||||||
|
{{ k.label }}
|
||||||
|
</label>
|
||||||
|
<span v-if="!table.evidence_failed && row.measured" class="kind-evidence">{{ evidenceText(row, k.kind) }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<button v-if="row.changed" type="button" class="btn-text door-reset" @click="save(row.door, null)">
|
||||||
|
Back to the shipped default
|
||||||
|
</button>
|
||||||
|
</fieldset>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.kinds { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
|
||||||
|
.door {
|
||||||
|
border: 1px solid var(--fs-border-color);
|
||||||
|
border-radius: var(--fs-radius-md);
|
||||||
|
padding: var(--fs-space-2) var(--fs-space-3);
|
||||||
|
margin: 0;
|
||||||
|
display: flex; flex-direction: column; gap: var(--fs-space-2);
|
||||||
|
}
|
||||||
|
.door:disabled { opacity: var(--fs-disabled-opacity); }
|
||||||
|
.door-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); padding: 0 var(--fs-space-1); }
|
||||||
|
.door-label { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
|
||||||
|
.door-fires,
|
||||||
|
.door-default,
|
||||||
|
.kind-evidence { font-size: var(--fs-size-tiny); color: var(--fs-text-secondary); font-variant-numeric: tabular-nums; }
|
||||||
|
.kind-list {
|
||||||
|
list-style: none; margin: 0; padding: 0;
|
||||||
|
display: grid; grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
|
||||||
|
gap: var(--fs-space-1) var(--fs-space-3);
|
||||||
|
}
|
||||||
|
.kind-cell { display: flex; flex-direction: column; }
|
||||||
|
.kind-label { display: inline-flex; align-items: center; gap: var(--fs-space-1); font-size: var(--fs-size-body-sm); cursor: pointer; }
|
||||||
|
.kind-label input:focus-visible { outline: none; box-shadow: var(--fs-focus-ring); }
|
||||||
|
.door-reset { align-self: flex-start; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<style src="@/assets/moments-shared.css" />
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from "vue";
|
||||||
|
import type { RecordReachPayload, RecordWay, WayCounts } from "@/api/moments";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How records other than rules reached sessions: shown by a hook, found by a
|
||||||
|
* search the session ran itself, or opened with nothing showing them first —
|
||||||
|
* and how many were opened each way. It says, per kind, whether a record is
|
||||||
|
* found by being pushed or by being asked for. One row per kind; open a row
|
||||||
|
* for the doors behind it.
|
||||||
|
*/
|
||||||
|
const props = defineProps<{
|
||||||
|
data: RecordReachPayload | null;
|
||||||
|
failed: boolean;
|
||||||
|
}>();
|
||||||
|
const emit = defineEmits<{ retry: [] }>();
|
||||||
|
|
||||||
|
const rows = computed(() => props.data?.by_kind ?? []);
|
||||||
|
|
||||||
|
const KIND_LABELS: Record<string, string> = {
|
||||||
|
snippet: "Snippets",
|
||||||
|
note: "Notes",
|
||||||
|
lesson: "Lessons",
|
||||||
|
process: "Processes",
|
||||||
|
"task:issue": "Issues",
|
||||||
|
"task:work": "Work tasks",
|
||||||
|
"task:spike": "Spikes",
|
||||||
|
};
|
||||||
|
|
||||||
|
function kindLabel(kind: string): string {
|
||||||
|
return KIND_LABELS[kind] ?? kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each way in reading order. A direct open is opened by definition, so it
|
||||||
|
// shows one number; the others show how many of those delivered were opened.
|
||||||
|
const WAYS: [RecordWay, string][] = [
|
||||||
|
["pushed", "shown by a hook"],
|
||||||
|
["pointed", "named in a pointer"],
|
||||||
|
["asked", "from its own search"],
|
||||||
|
["direct", "opened unshown"],
|
||||||
|
];
|
||||||
|
|
||||||
|
function wayText(way: RecordWay, c: WayCounts): string {
|
||||||
|
return way === "direct" ? `${c.opened}` : `${c.opened} of ${c.delivered}`;
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="reach" aria-labelledby="reach-title">
|
||||||
|
<h3 id="reach-title" class="sub-title">How records reach the work</h3>
|
||||||
|
<p v-if="failed" class="error-msg">
|
||||||
|
Record reach could not be loaded.
|
||||||
|
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
|
||||||
|
</p>
|
||||||
|
<p v-else-if="!data" class="empty-msg">Loading record reach…</p>
|
||||||
|
<p v-else-if="!rows.length" class="empty-msg">
|
||||||
|
No record reached a session in the last {{ data.days }} days from a plugin that reports opens.
|
||||||
|
</p>
|
||||||
|
<template v-else>
|
||||||
|
<p class="field-hint">
|
||||||
|
Records opened, out of those delivered, over the last {{ data.days }} days across
|
||||||
|
{{ data.sessions }} sessions: shown by a hook, named by id in a pointer line,
|
||||||
|
returned by a search the session ran, or opened with nothing showing them first.
|
||||||
|
</p>
|
||||||
|
<div class="reach-totals">
|
||||||
|
<span v-for="[way, label] in WAYS" :key="way">
|
||||||
|
{{ label }} {{ wayText(way, data.totals[way]) }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<ul class="reach-list">
|
||||||
|
<li v-for="r in rows" :key="r.kind" class="reach-kind">
|
||||||
|
<details>
|
||||||
|
<summary class="reach-row">
|
||||||
|
<span class="reach-title">{{ kindLabel(r.kind) }}</span>
|
||||||
|
<span class="reach-counts">
|
||||||
|
<span v-for="[way, label] in WAYS" :key="way" :class="{ 'way-none': !r.ways[way].delivered }">
|
||||||
|
{{ label }} {{ wayText(way, r.ways[way]) }}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</summary>
|
||||||
|
<ul class="reach-sources">
|
||||||
|
<li v-for="s in r.sources" :key="`${s.way}:${s.source}`" class="reach-row">
|
||||||
|
<code class="moment-name">{{ s.source }}</code>
|
||||||
|
<span class="reach-counts">
|
||||||
|
<span>{{ s.way === "direct" ? `${s.opened} opened` : `${s.opened} of ${s.delivered} opened` }}</span>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.reach { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
|
||||||
|
.reach-totals,
|
||||||
|
.reach-counts {
|
||||||
|
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2);
|
||||||
|
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.reach-counts { margin-left: auto; justify-content: flex-end; }
|
||||||
|
.reach-list,
|
||||||
|
.reach-sources { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
|
||||||
|
.reach-sources { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
|
||||||
|
.reach-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
|
||||||
|
.reach-kind summary { cursor: pointer; }
|
||||||
|
.reach-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
|
||||||
|
/* A way that delivered nothing for this kind is a gap, not a zero to read. */
|
||||||
|
.way-none { color: var(--fs-text-tertiary); }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<style src="@/assets/moments-shared.css" />
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from "vue";
|
||||||
|
import { apiGet, apiPut, apiErrorMessage } from "@/api/client";
|
||||||
|
import { useToastStore } from "@/stores/toast";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How many reverse proxies stand in front of Grimoire, checked against the
|
||||||
|
* admin's own request.
|
||||||
|
*
|
||||||
|
* Each proxy appends to X-Forwarded-For, and Grimoire reads the entry this many
|
||||||
|
* in from the right as the visitor's address. Every sign-in rate limit and
|
||||||
|
* audit line keys on that address, and the scheme read the same way decides
|
||||||
|
* whether the session cookie is Secure. Too low a count makes every visitor
|
||||||
|
* read as the proxy, so they share one rate limit and one bad sign-in run
|
||||||
|
* blocks everyone. Behind Cloudflare's proxied DNS the usual count is 2.
|
||||||
|
*/
|
||||||
|
interface ReadoutRow { hops: number; client: string; https: boolean }
|
||||||
|
interface Readout {
|
||||||
|
peer: string;
|
||||||
|
forwarded_for: string[];
|
||||||
|
forwarded_proto: string[];
|
||||||
|
cloudflare: boolean;
|
||||||
|
cloudflare_client: string | null;
|
||||||
|
rows: ReadoutRow[];
|
||||||
|
suggested: number | null;
|
||||||
|
}
|
||||||
|
interface ProxyConfig {
|
||||||
|
hops: number;
|
||||||
|
source: "setting" | "env" | "default";
|
||||||
|
env_hops: number;
|
||||||
|
max_hops: number;
|
||||||
|
readout: Readout;
|
||||||
|
}
|
||||||
|
|
||||||
|
const toast = useToastStore();
|
||||||
|
const config = ref<ProxyConfig | null>(null);
|
||||||
|
const loadError = ref("");
|
||||||
|
const draft = ref<number>(1);
|
||||||
|
const saving = ref(false);
|
||||||
|
const saved = ref(false);
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
loadError.value = "";
|
||||||
|
try {
|
||||||
|
config.value = await apiGet<ProxyConfig>("/api/admin/proxy");
|
||||||
|
draft.value = config.value.hops;
|
||||||
|
} catch (e) {
|
||||||
|
loadError.value = apiErrorMessage(e, "The proxy settings could not be loaded.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function save(hops: number | null) {
|
||||||
|
saving.value = true;
|
||||||
|
saved.value = false;
|
||||||
|
try {
|
||||||
|
config.value = await apiPut<ProxyConfig>("/api/admin/proxy", { hops });
|
||||||
|
draft.value = config.value.hops;
|
||||||
|
saved.value = true;
|
||||||
|
setTimeout(() => (saved.value = false), 2000);
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, "Failed to save the proxy count"), "error");
|
||||||
|
} finally {
|
||||||
|
saving.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const readout = computed(() => config.value?.readout ?? null);
|
||||||
|
const inForce = computed(() => readout.value?.rows.find((r) => r.hops === config.value?.hops) ?? null);
|
||||||
|
|
||||||
|
// The verdict that leads the section. A Cloudflare request names the count to
|
||||||
|
// set, since Cloudflare reports the visitor's address; any other road can only
|
||||||
|
// show the address read and let the admin judge whether it is theirs.
|
||||||
|
const verdict = computed<"set-suggested" | "cloudflare-unmatched" | "check" | null>(() => {
|
||||||
|
const r = readout.value;
|
||||||
|
if (!r || !config.value) return null;
|
||||||
|
if (r.cloudflare && r.suggested !== null && r.suggested !== config.value.hops) return "set-suggested";
|
||||||
|
if (r.cloudflare && r.suggested === null) return "cloudflare-unmatched";
|
||||||
|
return "check";
|
||||||
|
});
|
||||||
|
|
||||||
|
const sourceLabel = computed(() => {
|
||||||
|
const c = config.value;
|
||||||
|
if (!c) return "";
|
||||||
|
if (c.source === "setting") return "Saved here.";
|
||||||
|
if (c.source === "env") return `From TRUSTED_PROXY_HOPS in the environment (${c.env_hops}).`;
|
||||||
|
return "The default.";
|
||||||
|
});
|
||||||
|
|
||||||
|
const draftValid = computed(() =>
|
||||||
|
Number.isInteger(draft.value) && draft.value >= 0 && draft.value <= (config.value?.max_hops ?? 5),
|
||||||
|
);
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="proxy-settings">
|
||||||
|
<p v-if="loadError" class="error-msg">
|
||||||
|
{{ loadError }}
|
||||||
|
<button type="button" class="btn-ghost btn-compact" @click="load">Try again</button>
|
||||||
|
</p>
|
||||||
|
<p v-else-if="!config" class="state-msg">Reading this request…</p>
|
||||||
|
|
||||||
|
<template v-else-if="readout">
|
||||||
|
<div v-if="verdict === 'set-suggested'" class="proxy-warning" role="alert">
|
||||||
|
<p class="proxy-warning-title">Set the proxy count to {{ readout.suggested }}</p>
|
||||||
|
<p class="proxy-warning-body">
|
||||||
|
This request came through Cloudflare, which reports your address as
|
||||||
|
<code>{{ readout.cloudflare_client }}</code>. At {{ config.hops }}, Grimoire reads
|
||||||
|
<code>{{ inForce?.client }}</code> instead, so visitors share Cloudflare's addresses
|
||||||
|
and one sign-in limit.
|
||||||
|
</p>
|
||||||
|
<button type="button" class="btn-primary" :disabled="saving" @click="save(readout.suggested)">
|
||||||
|
Use {{ readout.suggested }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="verdict === 'cloudflare-unmatched'" class="proxy-warning" role="alert">
|
||||||
|
<p class="proxy-warning-title">This request came through Cloudflare</p>
|
||||||
|
<p class="proxy-warning-body">
|
||||||
|
No count reads the address Cloudflare reports for you. Check the forwarding chain below,
|
||||||
|
and that your own proxy passes Cloudflare's <code>X-Forwarded-For</code> on.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p v-else class="proxy-verdict">
|
||||||
|
Grimoire reads this request as coming from <code>{{ inForce?.client || "an unknown address" }}</code>
|
||||||
|
<template v-if="inForce?.https"> over HTTPS</template>. If that is your address, the count
|
||||||
|
is right. If it is your proxy's, raise the count.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="field proxy-field">
|
||||||
|
<label for="proxy-hops">Proxies in front of Grimoire</label>
|
||||||
|
<div class="proxy-input-row">
|
||||||
|
<input
|
||||||
|
id="proxy-hops"
|
||||||
|
v-model.number="draft"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
:max="config.max_hops"
|
||||||
|
step="1"
|
||||||
|
class="fs-input input proxy-hops-input"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-primary"
|
||||||
|
:disabled="saving || !draftValid || draft === config.hops"
|
||||||
|
@click="save(draft)"
|
||||||
|
>
|
||||||
|
{{ saving ? "Saving..." : "Save" }}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
v-if="config.source === 'setting'"
|
||||||
|
type="button"
|
||||||
|
class="btn-ghost"
|
||||||
|
:disabled="saving"
|
||||||
|
@click="save(null)"
|
||||||
|
>
|
||||||
|
Use the environment's ({{ config.env_hops }})
|
||||||
|
</button>
|
||||||
|
<span v-if="saved" class="saved-msg">Saved. It applies to the next request.</span>
|
||||||
|
</div>
|
||||||
|
<p class="field-hint">
|
||||||
|
{{ sourceLabel }} One proxy (Traefik, Nginx, Caddy) is 1. Cloudflare in front of your own
|
||||||
|
proxy is 2. 0 ignores the forwarding headers and uses the connecting address.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<table class="proxy-table">
|
||||||
|
<caption>What each count makes of this request</caption>
|
||||||
|
<thead>
|
||||||
|
<tr><th class="num">Count</th><th>Reads you as</th><th>HTTPS</th><th></th></tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr
|
||||||
|
v-for="row in readout.rows"
|
||||||
|
:key="row.hops"
|
||||||
|
:class="{ 'proxy-row-current': row.hops === config.hops }"
|
||||||
|
>
|
||||||
|
<td class="num">{{ row.hops }}</td>
|
||||||
|
<td><code>{{ row.client || "unknown" }}</code></td>
|
||||||
|
<td>{{ row.https ? "yes" : "no" }}</td>
|
||||||
|
<td class="proxy-row-tags">
|
||||||
|
<span v-if="row.hops === config.hops" class="proxy-tag">in force</span>
|
||||||
|
<span v-if="row.hops === readout.suggested && row.hops !== config.hops" class="proxy-tag proxy-tag-suggested">
|
||||||
|
suggested
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<dl class="proxy-chain">
|
||||||
|
<dt>Connecting address</dt>
|
||||||
|
<dd><code>{{ readout.peer || "unknown" }}</code></dd>
|
||||||
|
<dt>X-Forwarded-For</dt>
|
||||||
|
<dd v-if="readout.forwarded_for.length"><code>{{ readout.forwarded_for.join(", ") }}</code></dd>
|
||||||
|
<dd v-else class="proxy-absent">not sent</dd>
|
||||||
|
<dt>X-Forwarded-Proto</dt>
|
||||||
|
<dd v-if="readout.forwarded_proto.length"><code>{{ readout.forwarded_proto.join(", ") }}</code></dd>
|
||||||
|
<dd v-else class="proxy-absent">not sent</dd>
|
||||||
|
</dl>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.proxy-warning {
|
||||||
|
margin-bottom: var(--fs-space-4);
|
||||||
|
padding: var(--fs-space-3);
|
||||||
|
border: 1px solid var(--fs-warning);
|
||||||
|
border-radius: var(--fs-radius-md);
|
||||||
|
background: color-mix(in srgb, var(--fs-warning) 12%, var(--fs-surface-raised));
|
||||||
|
}
|
||||||
|
.proxy-warning-title {
|
||||||
|
margin: 0 0 var(--fs-space-2);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--fs-warning-fg);
|
||||||
|
}
|
||||||
|
.proxy-warning-body {
|
||||||
|
margin: 0 0 var(--fs-space-3);
|
||||||
|
font-size: var(--fs-size-body-sm);
|
||||||
|
color: var(--fs-text-primary);
|
||||||
|
}
|
||||||
|
.proxy-verdict {
|
||||||
|
margin: 0 0 var(--fs-space-4);
|
||||||
|
font-size: var(--fs-size-body-sm);
|
||||||
|
color: var(--fs-text-primary);
|
||||||
|
}
|
||||||
|
.proxy-field {
|
||||||
|
margin-bottom: var(--fs-space-4);
|
||||||
|
}
|
||||||
|
.proxy-input-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--fs-space-3);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.proxy-hops-input {
|
||||||
|
width: 5rem;
|
||||||
|
}
|
||||||
|
.proxy-table {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 560px;
|
||||||
|
border-collapse: collapse;
|
||||||
|
font-size: var(--fs-size-body-sm);
|
||||||
|
margin-bottom: var(--fs-space-4);
|
||||||
|
}
|
||||||
|
.proxy-table caption {
|
||||||
|
text-align: left;
|
||||||
|
font-size: var(--fs-size-label);
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
margin-bottom: var(--fs-space-2);
|
||||||
|
}
|
||||||
|
.proxy-table th,
|
||||||
|
.proxy-table td {
|
||||||
|
text-align: left;
|
||||||
|
padding: var(--fs-space-1) var(--fs-space-3);
|
||||||
|
border-bottom: 1px solid var(--fs-border-color);
|
||||||
|
}
|
||||||
|
.proxy-table th {
|
||||||
|
font-size: var(--fs-size-tiny);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
color: var(--fs-text-tertiary);
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
.proxy-table .num {
|
||||||
|
text-align: right;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
width: 4rem;
|
||||||
|
}
|
||||||
|
.proxy-row-current td {
|
||||||
|
background: var(--fs-surface-hover);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.proxy-row-tags {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.proxy-tag {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0 var(--fs-space-2);
|
||||||
|
border-radius: var(--fs-radius-pill);
|
||||||
|
font-size: var(--fs-size-tiny);
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
border: 1px solid var(--fs-border-active);
|
||||||
|
}
|
||||||
|
.proxy-tag-suggested {
|
||||||
|
color: var(--fs-warning-fg);
|
||||||
|
border-color: var(--fs-warning);
|
||||||
|
}
|
||||||
|
.proxy-chain {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: max-content 1fr;
|
||||||
|
gap: var(--fs-space-1) var(--fs-space-4);
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--fs-size-body-sm);
|
||||||
|
}
|
||||||
|
.proxy-chain dt {
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
}
|
||||||
|
.proxy-chain dd {
|
||||||
|
margin: 0;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
}
|
||||||
|
.proxy-absent {
|
||||||
|
font-style: italic;
|
||||||
|
color: var(--fs-text-tertiary);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from "vue";
|
||||||
|
import type { AdherenceCounts, AdherencePayload } from "@/api/moments";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the rules in force at each moment were followed there. A rule is in
|
||||||
|
* force at a moment of a session when it was delivered there; each such case
|
||||||
|
* is followed, departed from (with a stated reason), broken, not applicable,
|
||||||
|
* or not judged yet. Verdicts come from a refused act, the session's own
|
||||||
|
* `rule_outcome` / `rule_misfired`, and transcript reviews
|
||||||
|
* (`adherence_to_judge`). One row per rule; open a row for its places.
|
||||||
|
*/
|
||||||
|
const props = defineProps<{
|
||||||
|
data: AdherencePayload | null;
|
||||||
|
failed: boolean;
|
||||||
|
}>();
|
||||||
|
const emit = defineEmits<{ retry: [] }>();
|
||||||
|
|
||||||
|
const rows = computed(() => props.data?.by_rule ?? []);
|
||||||
|
|
||||||
|
// The verdict counts in reading order, each shown only when it is not zero,
|
||||||
|
// so a row says what happened rather than listing zeros.
|
||||||
|
const PARTS: [keyof AdherenceCounts, string][] = [
|
||||||
|
["followed", "followed"],
|
||||||
|
["departed", "departed"],
|
||||||
|
["broken", "broken"],
|
||||||
|
["not_applicable", "not applicable"],
|
||||||
|
["unjudged", "not judged"],
|
||||||
|
];
|
||||||
|
|
||||||
|
function parts(c: AdherenceCounts): { key: string; text: string }[] {
|
||||||
|
return PARTS.filter(([k]) => c[k] > 0).map(([k, label]) => ({ key: k, text: `${label} ${c[k]}` }));
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section class="adherence" aria-labelledby="adherence-title">
|
||||||
|
<h3 id="adherence-title" class="sub-title">Were they followed</h3>
|
||||||
|
<p v-if="failed" class="error-msg">
|
||||||
|
Adherence could not be loaded.
|
||||||
|
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
|
||||||
|
</p>
|
||||||
|
<p v-else-if="!data" class="empty-msg">Loading adherence…</p>
|
||||||
|
<p v-else-if="!rows.length" class="empty-msg">
|
||||||
|
No rule was in force at a moment in the last {{ data.days }} days.
|
||||||
|
</p>
|
||||||
|
<template v-else>
|
||||||
|
<p class="field-hint">
|
||||||
|
Sessions each rule was in force in over the last {{ data.days }} days, and what each was
|
||||||
|
judged. A review fills in the rest from transcripts with <code>adherence_to_judge</code>.
|
||||||
|
</p>
|
||||||
|
<div class="adherence-totals">
|
||||||
|
<span>in force {{ data.totals.in_force }}</span>
|
||||||
|
<span>opened {{ data.totals.opened }}</span>
|
||||||
|
<span v-for="p in parts(data.totals)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
|
||||||
|
</div>
|
||||||
|
<ul class="adherence-list">
|
||||||
|
<li v-for="r in rows" :key="r.rule_id" class="adherence-rule">
|
||||||
|
<details>
|
||||||
|
<summary class="adherence-row">
|
||||||
|
<span class="adherence-title">{{ r.title ?? `Rule ${r.rule_id} (deleted)` }}</span>
|
||||||
|
<span class="adherence-counts">
|
||||||
|
<span>in force {{ r.in_force }}</span>
|
||||||
|
<span>opened {{ r.opened }}</span>
|
||||||
|
<span v-for="p in parts(r)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
|
||||||
|
</span>
|
||||||
|
</summary>
|
||||||
|
<ul class="adherence-places">
|
||||||
|
<li v-for="m in r.by_moment" :key="m.at" class="adherence-row">
|
||||||
|
<code class="moment-name">{{ m.at }}</code>
|
||||||
|
<span class="adherence-counts">
|
||||||
|
<span>in force {{ m.in_force }}</span>
|
||||||
|
<span>opened {{ m.opened }}</span>
|
||||||
|
<span v-for="p in parts(m)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.adherence { display: flex; flex-direction: column; gap: var(--fs-space-2); }
|
||||||
|
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
|
||||||
|
.adherence-totals,
|
||||||
|
.adherence-counts {
|
||||||
|
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2);
|
||||||
|
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
.adherence-counts { margin-left: auto; justify-content: flex-end; }
|
||||||
|
.adherence-list,
|
||||||
|
.adherence-places { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
|
||||||
|
.adherence-places { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
|
||||||
|
.adherence-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
|
||||||
|
.adherence-rule summary { cursor: pointer; }
|
||||||
|
.adherence-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
|
||||||
|
/* Broken is the one count a person acts on, so it is the one that stands out;
|
||||||
|
not judged is a gap in the record, not a fault, and stays quiet. */
|
||||||
|
.v-broken { color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
|
||||||
|
.v-unjudged { color: var(--fs-text-tertiary); font-style: italic; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<style src="@/assets/moments-shared.css" />
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
import { ref, onMounted } from "vue";
|
import { ref, onMounted } from "vue";
|
||||||
import { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client";
|
import { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
import type { TaskLog } from "@/types/task";
|
import type { TaskLog } from "@/types/task";
|
||||||
import { fmtStamp } from "@/utils/dateFormat";
|
import { fmtStamp } from "@/utils/dateFormat";
|
||||||
|
|
||||||
@@ -131,7 +132,7 @@ onMounted(loadLogs);
|
|||||||
<button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">×</button>
|
<button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">×</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="log-content prose" v-html="renderMarkdown(log.content)"></div>
|
<div class="log-content prose" v-html="renderMarkdown(log.content)" v-record-refs></div>
|
||||||
</template>
|
</template>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,215 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from "vue";
|
||||||
|
import { getWeightProposals, judgeWeightProposals } from "@/api/moments";
|
||||||
|
import type {
|
||||||
|
RuleWeightProposals, Verdict, WeightEvidence, WeightProposal, WeightProposalsPayload,
|
||||||
|
} from "@/api/moments";
|
||||||
|
import type { RuleTrigger } from "@/api/rulebooks";
|
||||||
|
import { apiErrorMessage } from "@/api/client";
|
||||||
|
import { useToastStore } from "@/stores/toast";
|
||||||
|
import ConfirmDialog from "@/components/ConfirmDialog.vue";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Suggestions for how strongly a rule arrives and what reaches it, waiting on
|
||||||
|
* a person. A pass read each rule beside what happened when it reached
|
||||||
|
* sessions, and proposed its enforcement (inform, hold, enforce), its salience,
|
||||||
|
* or a typed trigger. Nothing changes until "Apply" is pressed; "Not this"
|
||||||
|
* keeps the value from being proposed again. "Apply all" confirms every
|
||||||
|
* listed suggestion at once, after a dialog that counts what changes. The
|
||||||
|
* same judgment `judge_rule_weights` makes in a session, through the same
|
||||||
|
* service.
|
||||||
|
*/
|
||||||
|
const toast = useToastStore();
|
||||||
|
|
||||||
|
const data = ref<WeightProposalsPayload | null>(null);
|
||||||
|
const failed = ref(false);
|
||||||
|
const busy = ref<string | null>(null);
|
||||||
|
const confirmingAll = ref(false);
|
||||||
|
|
||||||
|
const rules = computed<RuleWeightProposals[]>(() => data.value?.rules ?? []);
|
||||||
|
const proposalCount = computed(() => rules.value.reduce((n, r) => n + r.proposals.length, 0));
|
||||||
|
|
||||||
|
// The dialog names how many rules would start stopping work, since a hold or
|
||||||
|
// an enforce is the change a person notices in their next session.
|
||||||
|
const allSummary = computed(() => {
|
||||||
|
const stopping = rules.value.filter((r) => r.proposals.some(
|
||||||
|
(p) => p.field === "enforcement" && p.value !== "inform",
|
||||||
|
)).length;
|
||||||
|
const changes = `${proposalCount.value} change${proposalCount.value === 1 ? "" : "s"}`;
|
||||||
|
const across = `${rules.value.length} rule${rules.value.length === 1 ? "" : "s"}`;
|
||||||
|
const stops = stopping
|
||||||
|
? ` ${stopping} of them will hold or refuse the acts they govern.`
|
||||||
|
: "";
|
||||||
|
return `${changes} across ${across} take effect at once.${stops}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
// What each enforcement does when the rule arrives — said beside the change,
|
||||||
|
// since "hold" and "enforce" stop work and the person applying one should
|
||||||
|
// know how.
|
||||||
|
const FORCE: Record<string, string> = {
|
||||||
|
inform: "a line beside the work",
|
||||||
|
hold: "the act or reply waits until it has been read once",
|
||||||
|
enforce: "the act it governs is refused, every time",
|
||||||
|
};
|
||||||
|
|
||||||
|
async function load() {
|
||||||
|
try {
|
||||||
|
data.value = await getWeightProposals();
|
||||||
|
failed.value = false;
|
||||||
|
} catch {
|
||||||
|
failed.value = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function key(rule: RuleWeightProposals, p: WeightProposal): string {
|
||||||
|
return `${rule.id}:${p.field}:${p.value}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function triggerText(t: RuleTrigger): string {
|
||||||
|
return `${t.kind} ${t.pattern}${t.moment ? ` at ${t.moment}` : ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function change(rule: RuleWeightProposals, p: WeightProposal): string {
|
||||||
|
if (p.field === "trigger" && p.trigger) return `add trigger ${triggerText(p.trigger)}`;
|
||||||
|
const from = p.field === "enforcement" ? rule.enforcement : rule.salience;
|
||||||
|
return `${p.field} ${from} → ${p.value}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function history(e: WeightEvidence): string {
|
||||||
|
if (!e || e.delivered === undefined) return "";
|
||||||
|
const parts = [`delivered ${e.delivered}`, `opened ${e.opened ?? 0}`];
|
||||||
|
if (e.applied) parts.push(`applied ${e.applied}`);
|
||||||
|
if (e.departed) parts.push(`departed ${e.departed}`);
|
||||||
|
if (e.misfire_days) parts.push(`misfired on ${e.misfire_days} days`);
|
||||||
|
return `${parts.join(" · ")} in ${e.days ?? 90} days`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decide(rule: RuleWeightProposals, p: WeightProposal, verdict: Verdict) {
|
||||||
|
busy.value = key(rule, p);
|
||||||
|
try {
|
||||||
|
const out = await judgeWeightProposals([{
|
||||||
|
rule_id: rule.id, field: p.field, value: p.trigger ?? p.value, verdict,
|
||||||
|
note: verdict === "confirm" ? "Applied in Settings." : "Declined in Settings.",
|
||||||
|
}]);
|
||||||
|
if (out.refused.length) {
|
||||||
|
toast.show(out.refused[0].error, "error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, "Could not record that"), "error");
|
||||||
|
} finally {
|
||||||
|
busy.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyAll() {
|
||||||
|
confirmingAll.value = false;
|
||||||
|
busy.value = "all";
|
||||||
|
try {
|
||||||
|
const out = await judgeWeightProposals(rules.value.flatMap((rule) => rule.proposals.map((p) => ({
|
||||||
|
rule_id: rule.id, field: p.field, value: p.trigger ?? p.value,
|
||||||
|
verdict: "confirm" as Verdict, note: "Applied with Apply all in Settings.",
|
||||||
|
}))));
|
||||||
|
if (out.refused.length) {
|
||||||
|
const first = out.refused[0];
|
||||||
|
toast.show(
|
||||||
|
`${out.judged.length} applied; ${out.refused.length} refused — #${first.rule_id}: ${first.error}`,
|
||||||
|
"error",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
toast.show(`${out.judged.length} applied.`, "success");
|
||||||
|
}
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.show(apiErrorMessage(e, "Could not apply the suggestions"), "error");
|
||||||
|
} finally {
|
||||||
|
busy.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(load);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<section v-if="failed || rules.length" class="proposals" aria-labelledby="weights-title">
|
||||||
|
<h3 id="weights-title" class="sub-title">How strongly rules arrive — waiting on you</h3>
|
||||||
|
<p v-if="failed" class="error-msg">
|
||||||
|
The suggestions could not be loaded.
|
||||||
|
<button type="button" class="btn-text" @click="load">Try again</button>
|
||||||
|
</p>
|
||||||
|
<template v-else>
|
||||||
|
<p class="field-hint">
|
||||||
|
Suggested from each rule's text and what happened when it reached sessions. Inform is a
|
||||||
|
line beside the work; hold makes the act or reply wait until the rule has been read once
|
||||||
|
(file edits are never held); enforce refuses the act it governs. A trigger reaches the
|
||||||
|
rule exactly, by the tool, path, command or word the act carries; a rule with triggers
|
||||||
|
holds or refuses only the acts they match, and elsewhere it is a line.
|
||||||
|
</p>
|
||||||
|
<div class="proposals-bar">
|
||||||
|
<button
|
||||||
|
type="button" class="btn-primary btn-sm"
|
||||||
|
:disabled="busy !== null"
|
||||||
|
@click="confirmingAll = true"
|
||||||
|
>Apply all {{ proposalCount }}</button>
|
||||||
|
</div>
|
||||||
|
<ul class="proposal-list">
|
||||||
|
<li v-for="rule in rules" :key="rule.id" class="proposal-rule">
|
||||||
|
<div class="rule-head">
|
||||||
|
<span class="rule-title">#{{ rule.id }} {{ rule.title }}</span>
|
||||||
|
<span class="rule-mounted">
|
||||||
|
{{ rule.enforcement }} · {{ rule.salience }}
|
||||||
|
<template v-if="rule.mounted.length">
|
||||||
|
· on <code v-for="m in rule.mounted" :key="m" class="moment-name">{{ m }}</code>
|
||||||
|
</template>
|
||||||
|
<template v-if="rule.triggers.length">
|
||||||
|
· triggered by
|
||||||
|
<code v-for="t in rule.triggers" :key="triggerText(t)" class="moment-name">{{ triggerText(t) }}</code>
|
||||||
|
</template>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p class="rule-statement">{{ rule.statement }}</p>
|
||||||
|
<ul class="proposal-items">
|
||||||
|
<li v-for="p in rule.proposals" :key="key(rule, p)" class="proposal-item">
|
||||||
|
<code class="moment-name">{{ change(rule, p) }}</code>
|
||||||
|
<span class="proposal-why">
|
||||||
|
{{ p.why }}
|
||||||
|
<span v-if="p.field === 'enforcement'" class="proposal-source">
|
||||||
|
· {{ FORCE[p.value] }}
|
||||||
|
</span>
|
||||||
|
<span v-if="history(p.evidence)" class="proposal-source">
|
||||||
|
· {{ history(p.evidence) }}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
<span class="proposal-actions">
|
||||||
|
<button
|
||||||
|
type="button" class="btn-primary btn-sm"
|
||||||
|
:disabled="busy !== null"
|
||||||
|
@click="decide(rule, p, 'confirm')"
|
||||||
|
>Apply</button>
|
||||||
|
<button
|
||||||
|
type="button" class="btn-text"
|
||||||
|
:disabled="busy !== null"
|
||||||
|
@click="decide(rule, p, 'reject')"
|
||||||
|
>Not this</button>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</template>
|
||||||
|
<ConfirmDialog
|
||||||
|
v-if="confirmingAll"
|
||||||
|
title="Apply every suggestion?"
|
||||||
|
:message="allSummary"
|
||||||
|
confirm-label="Apply all"
|
||||||
|
:danger="false"
|
||||||
|
@confirm="applyAll"
|
||||||
|
@cancel="confirmingAll = false"
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped src="@/assets/rule-proposals.css" />
|
||||||
|
|
||||||
|
<style src="@/assets/moments-shared.css" />
|
||||||
@@ -6,7 +6,11 @@ import { useMomentsStore } from "@/stores/moments";
|
|||||||
import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue";
|
import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue";
|
||||||
import RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
|
import RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
|
||||||
import { apiErrorMessage } from "@/api/client";
|
import { apiErrorMessage } from "@/api/client";
|
||||||
import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks";
|
import {
|
||||||
|
listRulebooks, listTopics,
|
||||||
|
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
|
||||||
|
type RuleTrigger, type RuleTriggerKind,
|
||||||
|
} from "@/api/rulebooks";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
ruleId: number | null;
|
ruleId: number | null;
|
||||||
@@ -26,6 +30,14 @@ const whenToApply = ref("");
|
|||||||
// followed too faithfully, where a rule mislabelled as a preference is one a
|
// followed too faithfully, where a rule mislabelled as a preference is one a
|
||||||
// session may quietly rewrite.
|
// session may quietly rewrite.
|
||||||
const kind = ref<RuleKind>("rule");
|
const kind = ref<RuleKind>("rule");
|
||||||
|
// The server's defaults: a line beside the work, at normal rank.
|
||||||
|
const enforcement = ref<RuleEnforcement>("inform");
|
||||||
|
const salience = ref<RuleSalience>("normal");
|
||||||
|
// A preference carries no force but `inform`, and the server refuses any
|
||||||
|
// other, so switching kind settles it here rather than as a failed save.
|
||||||
|
watch(kind, (k) => {
|
||||||
|
if (k === "preference") enforcement.value = "inform";
|
||||||
|
});
|
||||||
const systemIds = ref<number[]>([]);
|
const systemIds = ref<number[]>([]);
|
||||||
// The moments this rule is mounted on. Catalog moments are
|
// The moments this rule is mounted on. Catalog moments are
|
||||||
// ticked; a named procedure's moment (`skill.<name>`) is typed, since its
|
// ticked; a named procedure's moment (`skill.<name>`) is typed, since its
|
||||||
@@ -39,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []);
|
|||||||
const procedureMoments = computed(() =>
|
const procedureMoments = computed(() =>
|
||||||
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
|
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
|
||||||
);
|
);
|
||||||
|
// The acts this rule is triggered by, checked exactly on the server.
|
||||||
|
const triggers = ref<RuleTrigger[]>([]);
|
||||||
|
const triggerKind = ref<RuleTriggerKind>("path");
|
||||||
|
const triggerPattern = ref("");
|
||||||
|
const triggerMoment = ref("");
|
||||||
|
const triggerError = ref("");
|
||||||
|
const TRIGGER_KINDS: { value: RuleTriggerKind; label: string; placeholder: string }[] = [
|
||||||
|
{ value: "path", label: "Path", placeholder: "alembic/versions/*.py — a file the act touches" },
|
||||||
|
{ value: "command", label: "Command", placeholder: "git push — the head of a command it runs" },
|
||||||
|
{ value: "tool", label: "Tool", placeholder: "update_task — the tool it calls" },
|
||||||
|
{ value: "keyword", label: "Keyword", placeholder: "migration — a word in what it writes" },
|
||||||
|
];
|
||||||
|
const triggerPlaceholder = computed(
|
||||||
|
() => TRIGGER_KINDS.find((k) => k.value === triggerKind.value)?.placeholder ?? "",
|
||||||
|
);
|
||||||
|
|
||||||
|
function triggerLabel(t: RuleTrigger) {
|
||||||
|
return TRIGGER_KINDS.find((k) => k.value === t.kind)?.label ?? t.kind;
|
||||||
|
}
|
||||||
|
|
||||||
|
function addTrigger() {
|
||||||
|
const pattern = triggerPattern.value.trim().replace(/\s+/g, " ");
|
||||||
|
if (!pattern) return;
|
||||||
|
const moment = triggerMoment.value || undefined;
|
||||||
|
const same = (t: RuleTrigger) =>
|
||||||
|
t.kind === triggerKind.value && t.pattern === pattern && (t.moment ?? "") === (moment ?? "");
|
||||||
|
if (triggers.value.some(same)) {
|
||||||
|
triggerError.value = "This rule already has that trigger.";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
triggerError.value = "";
|
||||||
|
triggers.value.push({ kind: triggerKind.value, pattern, ...(moment ? { moment } : {}) });
|
||||||
|
triggerPattern.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
function removeTrigger(at: number) {
|
||||||
|
triggers.value.splice(at, 1);
|
||||||
|
}
|
||||||
const why = ref("");
|
const why = ref("");
|
||||||
const howToApply = ref("");
|
const howToApply = ref("");
|
||||||
const verifyWith = ref("");
|
const verifyWith = ref("");
|
||||||
@@ -123,8 +173,11 @@ async function load() {
|
|||||||
statement.value = r.statement;
|
statement.value = r.statement;
|
||||||
whenToApply.value = r.when_to_apply || "";
|
whenToApply.value = r.when_to_apply || "";
|
||||||
kind.value = r.kind;
|
kind.value = r.kind;
|
||||||
|
enforcement.value = r.enforcement ?? "inform";
|
||||||
|
salience.value = r.salience ?? "normal";
|
||||||
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
|
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
|
||||||
ruleMoments.value = [...(r.moments ?? [])];
|
ruleMoments.value = [...(r.moments ?? [])];
|
||||||
|
triggers.value = (r.triggers ?? []).map((t) => ({ ...t }));
|
||||||
why.value = r.why || "";
|
why.value = r.why || "";
|
||||||
howToApply.value = r.how_to_apply || "";
|
howToApply.value = r.how_to_apply || "";
|
||||||
verifyWith.value = r.verify_with || "";
|
verifyWith.value = r.verify_with || "";
|
||||||
@@ -135,8 +188,11 @@ async function load() {
|
|||||||
statement.value = "";
|
statement.value = "";
|
||||||
whenToApply.value = props.preset?.whenToApply ?? "";
|
whenToApply.value = props.preset?.whenToApply ?? "";
|
||||||
kind.value = props.preset?.kind ?? "rule";
|
kind.value = props.preset?.kind ?? "rule";
|
||||||
|
enforcement.value = "inform";
|
||||||
|
salience.value = "normal";
|
||||||
systemIds.value = [];
|
systemIds.value = [];
|
||||||
ruleMoments.value = [...(props.preset?.moments ?? [])];
|
ruleMoments.value = [...(props.preset?.moments ?? [])];
|
||||||
|
triggers.value = [];
|
||||||
why.value = "";
|
why.value = "";
|
||||||
howToApply.value = "";
|
howToApply.value = "";
|
||||||
verifyWith.value = "";
|
verifyWith.value = "";
|
||||||
@@ -144,6 +200,9 @@ async function load() {
|
|||||||
}
|
}
|
||||||
procedureDraft.value = "";
|
procedureDraft.value = "";
|
||||||
procedureError.value = "";
|
procedureError.value = "";
|
||||||
|
triggerPattern.value = "";
|
||||||
|
triggerMoment.value = "";
|
||||||
|
triggerError.value = "";
|
||||||
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
|
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,12 +240,16 @@ async function save() {
|
|||||||
statement: statement.value,
|
statement: statement.value,
|
||||||
when_to_apply: whenToApply.value,
|
when_to_apply: whenToApply.value,
|
||||||
kind: kind.value,
|
kind: kind.value,
|
||||||
|
enforcement: enforcement.value,
|
||||||
|
salience: salience.value,
|
||||||
// Always sent, so clearing the last area actually clears it — the server
|
// Always sent, so clearing the last area actually clears it — the server
|
||||||
// reads a list as "these ARE the areas now".
|
// reads a list as "these ARE the areas now".
|
||||||
system_ids: systemIds.value,
|
system_ids: systemIds.value,
|
||||||
// Always sent, for system_ids' reason: the server reads the list as the
|
// Always sent, for system_ids' reason: the server reads the list as the
|
||||||
// whole set, so unticking the last moment actually unmounts the rule.
|
// whole set, so unticking the last moment actually unmounts the rule.
|
||||||
moments: ruleMoments.value,
|
moments: ruleMoments.value,
|
||||||
|
// Always sent, for the same reason: the list is the whole set.
|
||||||
|
triggers: triggers.value,
|
||||||
why: why.value,
|
why: why.value,
|
||||||
how_to_apply: howToApply.value,
|
how_to_apply: howToApply.value,
|
||||||
// Always sent, including empty. The REST door maps "" to NULL, so
|
// Always sent, including empty. The REST door maps "" to NULL, so
|
||||||
@@ -271,6 +334,40 @@ watch(() => props.ruleId, load);
|
|||||||
preference.
|
preference.
|
||||||
</p>
|
</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
<fieldset class="kind arrival">
|
||||||
|
<legend>When it arrives</legend>
|
||||||
|
<template v-if="kind === 'rule'">
|
||||||
|
<label class="kind-opt">
|
||||||
|
<input v-model="enforcement" type="radio" value="inform" />
|
||||||
|
<span><strong>Inform</strong> — a line beside the work. Most rules.</span>
|
||||||
|
</label>
|
||||||
|
<label class="kind-opt">
|
||||||
|
<input v-model="enforcement" type="radio" value="hold" />
|
||||||
|
<span>
|
||||||
|
<strong>Hold</strong> — the reply or command it governs waits until
|
||||||
|
the rule has been read once. File edits are never held. For a rule
|
||||||
|
whose miss costs a rewrite.
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<label class="kind-opt">
|
||||||
|
<input v-model="enforcement" type="radio" value="enforce" />
|
||||||
|
<span>
|
||||||
|
<strong>Enforce</strong> — an act its moment or trigger reaches
|
||||||
|
does not run, every time, until you change the rule. For a hard
|
||||||
|
boundary.
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</template>
|
||||||
|
<p v-else class="field-note">A preference arrives as a line beside the work.</p>
|
||||||
|
<label class="salience">
|
||||||
|
Rank among the rest
|
||||||
|
<select v-model="salience" class="fs-input">
|
||||||
|
<option value="high">High — shown first when a moment is crowded</option>
|
||||||
|
<option value="normal">Normal</option>
|
||||||
|
<option value="low">Low — the first to give way</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
<p v-if="kind === 'preference'" class="kind-drift">
|
<p v-if="kind === 'preference'" class="kind-drift">
|
||||||
Sessions rewrite preferences without asking, which is what makes them
|
Sessions rewrite preferences without asking, which is what makes them
|
||||||
stay current. Every rewrite is kept, and
|
stay current. Every rewrite is kept, and
|
||||||
@@ -342,6 +439,55 @@ watch(() => props.ruleId, load);
|
|||||||
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
|
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="moments triggers">
|
||||||
|
<legend>Acts that trigger it</legend>
|
||||||
|
<p class="field-note intro">
|
||||||
|
Matched exactly against what the work does, not by resemblance: a
|
||||||
|
path it touches, a command it runs, a tool it calls, a word in what it
|
||||||
|
writes. With no moment, the rule arrives on any act that matches.
|
||||||
|
With a moment, it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit where files change without arriving
|
||||||
|
at every edit.
|
||||||
|
</p>
|
||||||
|
<ul v-if="triggers.length" class="trigger-list">
|
||||||
|
<li v-for="(t, i) in triggers" :key="`${t.kind}:${t.pattern}:${t.moment ?? ''}`" class="rule-chip trigger-chip">
|
||||||
|
<span class="trigger-kind">{{ triggerLabel(t) }}</span>
|
||||||
|
<code>{{ t.pattern }}</code>
|
||||||
|
<span v-if="t.moment" class="trigger-at">at <code>{{ t.moment }}</code></span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="chip-remove"
|
||||||
|
:aria-label="`Remove the ${triggerLabel(t).toLowerCase()} trigger ${t.pattern}`"
|
||||||
|
@click="removeTrigger(i)"
|
||||||
|
>×</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-else class="field-note">No triggers: this rule arrives by its moments and by resemblance.</p>
|
||||||
|
<div class="trigger-add">
|
||||||
|
<select v-model="triggerKind" class="fs-input" aria-label="What the trigger matches">
|
||||||
|
<option v-for="k in TRIGGER_KINDS" :key="k.value" :value="k.value">{{ k.label }}</option>
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
v-model="triggerPattern"
|
||||||
|
class="fs-input"
|
||||||
|
aria-label="The pattern the act must match"
|
||||||
|
:placeholder="triggerPlaceholder"
|
||||||
|
@keydown.enter.prevent="addTrigger"
|
||||||
|
/>
|
||||||
|
<select v-model="triggerMoment" class="fs-input" aria-label="Only at this moment">
|
||||||
|
<option value="">Any act</option>
|
||||||
|
<option v-for="m in momentCatalog" :key="m.name" :value="m.name">Only at {{ m.name }}</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-secondary btn-sm"
|
||||||
|
:disabled="!triggerPattern.trim()"
|
||||||
|
@click="addTrigger"
|
||||||
|
>Add</button>
|
||||||
|
</div>
|
||||||
|
<p v-if="triggerError" class="trigger-warning">{{ triggerError }}</p>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
<fieldset v-if="canon.catalog.length" class="areas">
|
<fieldset v-if="canon.catalog.length" class="areas">
|
||||||
<legend>Areas this rule is about</legend>
|
<legend>Areas this rule is about</legend>
|
||||||
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
|
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
|
||||||
@@ -424,13 +570,13 @@ watch(() => props.ruleId, load);
|
|||||||
<ul>
|
<ul>
|
||||||
<li v-for="l in lessons" :key="l.id" class="relation">
|
<li v-for="l in lessons" :key="l.id" class="relation">
|
||||||
<router-link :to="`/lessons/${l.id}`" class="relation-target">{{ l.title }}</router-link>
|
<router-link :to="`/lessons/${l.id}`" class="relation-target">{{ l.title }}</router-link>
|
||||||
<span v-if="l.state === 'suggested'" class="rule-chip">suggested</span>
|
<span v-if="l.state === 'rejected'" class="rule-chip">not an instance</span>
|
||||||
<span v-if="l.note" class="relation-note">{{ l.note }}</span>
|
<span v-if="l.note" class="relation-note">{{ l.note }}</span>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p class="field-note">
|
<p class="field-note">
|
||||||
The situations that keep proving this rule. A confirmed lesson brings the rule along
|
The situations that keep proving this rule. A confirmed lesson brings the rule along
|
||||||
when it surfaces; a suggested one waits for a judgment on the lesson's page.
|
when it surfaces, and arrives with the rule when you open it.
|
||||||
</p>
|
</p>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
@@ -457,7 +603,7 @@ watch(() => props.ruleId, load);
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<!-- `.rule-chip` for the "suggested" marker on a lesson — the chip the rule
|
<!-- `.rule-chip` for the "not an instance" marker on a lesson — the chip the rule
|
||||||
panes already use, loaded here because the slide-over can open with no
|
panes already use, loaded here because the slide-over can open with no
|
||||||
pane that loads it (a link straight to ?rule=N).
|
pane that loads it (a link straight to ?rule=N).
|
||||||
Block 0, as in every pane that loads it: a shared src must sit at
|
Block 0, as in every pane that loads it: a shared src must sit at
|
||||||
@@ -520,6 +666,13 @@ legend { padding: 0 0.35rem; font-size: 0.8rem; color: var(--fs-text-tertiary);
|
|||||||
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
|
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
|
||||||
.procedure-add input { margin-top: 0; }
|
.procedure-add input { margin-top: 0; }
|
||||||
.procedure-add .btn-sm { flex: none; }
|
.procedure-add .btn-sm { flex: none; }
|
||||||
|
.trigger-list { list-style: none; padding: 0; margin: 0 0 var(--fs-space-2); display: flex; flex-wrap: wrap; gap: var(--fs-space-2); }
|
||||||
|
.trigger-chip { display: inline-flex; align-items: center; gap: var(--fs-space-1); }
|
||||||
|
.trigger-kind, .trigger-at { color: var(--fs-text-secondary); font-size: var(--fs-size-tiny); }
|
||||||
|
.trigger-add { display: flex; flex-wrap: wrap; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
|
||||||
|
.trigger-add input { flex: 1 1 14rem; margin-top: 0; }
|
||||||
|
.trigger-add select { flex: none; width: auto; margin-top: 0; }
|
||||||
|
.trigger-add .btn-sm { flex: none; }
|
||||||
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction
|
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction
|
||||||
between the warning HUE and warning text, and this is text. */
|
between the warning HUE and warning text, and this is text. */
|
||||||
.trigger-warning {
|
.trigger-warning {
|
||||||
|
|||||||
@@ -27,6 +27,15 @@ const emit = defineEmits<{
|
|||||||
class="rule-chip rule-chip-preference"
|
class="rule-chip rule-chip-preference"
|
||||||
title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it."
|
title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it."
|
||||||
>preference</span>
|
>preference</span>
|
||||||
|
<!-- Marked only when the rule stops the work: a line beside the work
|
||||||
|
is the default, and marking it on every row would mark nothing. -->
|
||||||
|
<span
|
||||||
|
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
|
||||||
|
class="rule-chip"
|
||||||
|
:title="r.enforcement === 'hold'
|
||||||
|
? 'The reply or command it governs waits until it has been read once'
|
||||||
|
: 'An act it is reached by does not run until the rule changes'"
|
||||||
|
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
|
||||||
<!-- Marked only when something is WRONG: every rule arrives by
|
<!-- Marked only when something is WRONG: every rule arrives by
|
||||||
retrieval now, so "conditional" stopped distinguishing anything.
|
retrieval now, so "conditional" stopped distinguishing anything.
|
||||||
A missing trigger does — it means nothing can retrieve this. -->
|
A missing trigger does — it means nothing can retrieve this. -->
|
||||||
|
|||||||
@@ -51,7 +51,8 @@ export function useAutocomplete(
|
|||||||
// Must be start of line or preceded by whitespace
|
// Must be start of line or preceded by whitespace
|
||||||
if (i === 0 || /\s/.test(text[i - 1])) {
|
if (i === 0 || /\s/.test(text[i - 1])) {
|
||||||
const query = text.slice(i + 1, cursor);
|
const query = text.slice(i + 1, cursor);
|
||||||
if (/^[\w/]*$/.test(query)) {
|
// Digits alone are a record reference being typed (`#4286`), not a tag.
|
||||||
|
if (/^[\w/]*$/.test(query) && !/^\d+$/.test(query)) {
|
||||||
acTriggerStart = i;
|
acTriggerStart = i;
|
||||||
acType = "tag";
|
acType = "tag";
|
||||||
debouncedSearch(query);
|
debouncedSearch(query);
|
||||||
|
|||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import type { ObjectDirective } from "vue";
|
||||||
|
import { apiPost } from "@/api/client";
|
||||||
|
import router from "@/router";
|
||||||
|
import { recordHref } from "@/utils/recordHref";
|
||||||
|
import type { RefSpace } from "@/utils/recordRefs";
|
||||||
|
|
||||||
|
/** v-record-refs — makes the `a.record-ref` links in a v-html body real.
|
||||||
|
*
|
||||||
|
* Put it on the element that holds rendered markdown:
|
||||||
|
* <div class="prose" v-html="renderMarkdown(body)" v-record-refs />
|
||||||
|
*
|
||||||
|
* After each render it asks the server, once for the whole body, what every
|
||||||
|
* referenced id is. Each link then gets the route its kind opens at (a `#N`
|
||||||
|
* may be a task, lesson or snippet), the record's title drawn before its
|
||||||
|
* number — "Fix the cache key #3127" — so a reader knows what is cited
|
||||||
|
* without hovering, its kind, full title and status as a tooltip, and a
|
||||||
|
* "leads nowhere" style when the reader cannot open it: missing, trashed and
|
||||||
|
* not-shared-with-you look the same, on purpose, and keep the bare number.
|
||||||
|
* The stored text stays `#N`; the title is read at render, so an edited
|
||||||
|
* title shows everywhere it is cited.
|
||||||
|
* A plain click navigates in the app; a modified click (new tab) keeps the
|
||||||
|
* browser's own behaviour.
|
||||||
|
*/
|
||||||
|
|
||||||
|
interface NoteInfo { id: number; title: string; is_task: boolean; note_type: string; status: string | null; task_kind: string | null }
|
||||||
|
interface MilestoneInfo { id: number; title: string; project_id: number | null; status: string }
|
||||||
|
interface RuleInfo { id: number; title: string; kind: string }
|
||||||
|
type Resolved = { notes: Record<string, NoteInfo>; milestones: Record<string, MilestoneInfo>; rules: Record<string, RuleInfo> };
|
||||||
|
// `title` is drawn in the link; `label` (kind · title (status)) is its tooltip.
|
||||||
|
type Info = { href: string; title: string; label: string } | null;
|
||||||
|
|
||||||
|
// A short-lived cache: the same body re-renders on every keystroke in a
|
||||||
|
// preview, and a page of work logs cites the same few records again and again.
|
||||||
|
const CACHE_MS = 60_000;
|
||||||
|
const cache = new Map<string, { at: number; info: Info }>();
|
||||||
|
|
||||||
|
const TASK_KIND_LABEL: Record<string, string> = { issue: "Issue", spike: "Spike" };
|
||||||
|
|
||||||
|
function noteInfo(n: NoteInfo): Info {
|
||||||
|
let kind = "Note";
|
||||||
|
if (n.is_task) kind = TASK_KIND_LABEL[n.task_kind ?? ""] ?? "Task";
|
||||||
|
else if (n.note_type === "lesson") kind = "Lesson";
|
||||||
|
else if (n.note_type === "snippet") kind = "Snippet";
|
||||||
|
const state = n.is_task && n.status ? ` (${n.status.replace(/_/g, " ")})` : "";
|
||||||
|
const title = n.title || "Untitled";
|
||||||
|
return { href: recordHref(n), title, label: `${kind} · ${title}${state}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
function milestoneInfo(m: MilestoneInfo): Info {
|
||||||
|
if (m.project_id == null) return null;
|
||||||
|
const title = m.title || "Untitled";
|
||||||
|
return {
|
||||||
|
href: `/projects/${m.project_id}?milestone=${m.id}`,
|
||||||
|
title,
|
||||||
|
label: `Milestone · ${title}${m.status === "done" ? " (done)" : ""}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function ruleInfo(r: RuleInfo): Info {
|
||||||
|
const kind = r.kind === "preference" ? "Preference" : "Rule";
|
||||||
|
const title = r.title || "Untitled";
|
||||||
|
return { href: `/rules?rule=${r.id}`, title, label: `${kind} · ${title}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Titles here are often whole sentences; in running text a reference names its
|
||||||
|
// record in a few words and the tooltip carries the rest.
|
||||||
|
const MAX_TITLE = 60;
|
||||||
|
|
||||||
|
function shorten(title: string): string {
|
||||||
|
if (title.length <= MAX_TITLE) return title;
|
||||||
|
const cut = title.slice(0, MAX_TITLE);
|
||||||
|
const space = cut.lastIndexOf(" ");
|
||||||
|
return (space > MAX_TITLE / 2 ? cut.slice(0, space) : cut).replace(/[\s,.;:—–-]+$/, "") + "…";
|
||||||
|
}
|
||||||
|
|
||||||
|
const BLOCK = "p, li, td, th, blockquote, h1, h2, h3, h4, h5, h6";
|
||||||
|
|
||||||
|
/** Whether the sentence around this link already names the record — a batch
|
||||||
|
* writes `#9 "Step two"`, and a paragraph citing one record twice names it
|
||||||
|
* the first time. A short title is drawn regardless: three letters turn up
|
||||||
|
* in prose by chance. */
|
||||||
|
function alreadyNamed(a: HTMLAnchorElement, shown: string, title: string): boolean {
|
||||||
|
if (title.length < 8) return false;
|
||||||
|
const text = (a.closest(BLOCK) ?? a.parentElement)?.textContent?.toLowerCase() ?? "";
|
||||||
|
return text.includes(title.toLowerCase()) || text.includes(shown.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draw the record's title in the link, its number after it, muted. Set as
|
||||||
|
* text, never as markup: a title is whatever its author typed. */
|
||||||
|
function showTitle(a: HTMLAnchorElement, title: string): boolean {
|
||||||
|
const shown = shorten(title);
|
||||||
|
if (alreadyNamed(a, shown, title)) return false;
|
||||||
|
const name = document.createElement("span");
|
||||||
|
name.className = "record-ref__title";
|
||||||
|
name.textContent = shown;
|
||||||
|
const ref = document.createElement("span");
|
||||||
|
ref.className = "record-ref__id";
|
||||||
|
ref.textContent = a.textContent ?? "";
|
||||||
|
a.replaceChildren(name, " ", ref);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function refKey(space: RefSpace, id: number): string {
|
||||||
|
return `${space}:${id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What each of these references is, from the cache or one server call. */
|
||||||
|
export async function resolveRecordRefs(wanted: { space: RefSpace; id: number }[]): Promise<Map<string, Info>> {
|
||||||
|
const now = Date.now();
|
||||||
|
const out = new Map<string, Info>();
|
||||||
|
const ask: Record<RefSpace, number[]> = { notes: [], milestones: [], rules: [] };
|
||||||
|
for (const w of wanted) {
|
||||||
|
const k = refKey(w.space, w.id);
|
||||||
|
if (out.has(k)) continue;
|
||||||
|
const hit = cache.get(k);
|
||||||
|
if (hit && now - hit.at < CACHE_MS) out.set(k, hit.info);
|
||||||
|
else if (!ask[w.space].includes(w.id)) ask[w.space].push(w.id);
|
||||||
|
}
|
||||||
|
if (ask.notes.length + ask.milestones.length + ask.rules.length === 0) return out;
|
||||||
|
const res = await apiPost<Resolved>("/api/notes/resolve-refs", ask);
|
||||||
|
const store = (space: RefSpace, id: number, info: Info) => {
|
||||||
|
cache.set(refKey(space, id), { at: now, info });
|
||||||
|
out.set(refKey(space, id), info);
|
||||||
|
};
|
||||||
|
for (const id of ask.notes) store("notes", id, res.notes[id] ? noteInfo(res.notes[id]) : null);
|
||||||
|
for (const id of ask.milestones) store("milestones", id, res.milestones[id] ? milestoneInfo(res.milestones[id]) : null);
|
||||||
|
for (const id of ask.rules) store("rules", id, res.rules[id] ? ruleInfo(res.rules[id]) : null);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function unresolvedLinks(el: HTMLElement): HTMLAnchorElement[] {
|
||||||
|
return Array.from(el.querySelectorAll<HTMLAnchorElement>("a.record-ref:not([data-ref-state])"));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decorate(el: HTMLElement) {
|
||||||
|
const links = unresolvedLinks(el);
|
||||||
|
if (!links.length) return;
|
||||||
|
const wanted = links.map((a) => ({ space: a.dataset.refSpace as RefSpace, id: Number(a.dataset.refId) }));
|
||||||
|
let resolved: Map<string, Info>;
|
||||||
|
try {
|
||||||
|
resolved = await resolveRecordRefs(wanted);
|
||||||
|
} catch {
|
||||||
|
// The links keep their provisional routes, which open the right view for
|
||||||
|
// notes, rules and milestones alike; only the titles are missing.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (const a of links) {
|
||||||
|
if (!a.isConnected) continue;
|
||||||
|
const info = resolved.get(refKey(a.dataset.refSpace as RefSpace, Number(a.dataset.refId)));
|
||||||
|
if (info === undefined) continue;
|
||||||
|
if (info === null) {
|
||||||
|
a.dataset.refState = "missing";
|
||||||
|
a.classList.add("record-ref--missing");
|
||||||
|
a.removeAttribute("href");
|
||||||
|
a.setAttribute("aria-disabled", "true");
|
||||||
|
a.title = `${a.textContent} — no record you can open`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
a.dataset.refState = "ok";
|
||||||
|
a.href = info.href;
|
||||||
|
a.title = info.label;
|
||||||
|
const bare = a.textContent;
|
||||||
|
// Drawn with its title, the link's own text is its accessible name; a bare
|
||||||
|
// number needs the label spoken for it.
|
||||||
|
if (!showTitle(a, info.title)) a.setAttribute("aria-label", `${bare}: ${info.label}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const clickHandlers = new WeakMap<HTMLElement, (e: MouseEvent) => void>();
|
||||||
|
|
||||||
|
function onClick(e: MouseEvent) {
|
||||||
|
const a = (e.target as HTMLElement).closest("a.record-ref") as HTMLAnchorElement | null;
|
||||||
|
if (!a) return;
|
||||||
|
if (a.dataset.refState === "missing") {
|
||||||
|
e.preventDefault();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||||
|
const href = a.getAttribute("href");
|
||||||
|
if (!href) return;
|
||||||
|
e.preventDefault();
|
||||||
|
router.push(href);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const vRecordRefs: ObjectDirective<HTMLElement> = {
|
||||||
|
mounted(el) {
|
||||||
|
clickHandlers.set(el, onClick);
|
||||||
|
el.addEventListener("click", onClick);
|
||||||
|
void decorate(el);
|
||||||
|
},
|
||||||
|
updated(el) {
|
||||||
|
void decorate(el);
|
||||||
|
},
|
||||||
|
beforeUnmount(el) {
|
||||||
|
const h = clickHandlers.get(el);
|
||||||
|
if (h) el.removeEventListener("click", h);
|
||||||
|
clickHandlers.delete(el);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -2,7 +2,9 @@ import { Extension } from "@tiptap/core";
|
|||||||
import { Plugin, PluginKey } from "@tiptap/pm/state";
|
import { Plugin, PluginKey } from "@tiptap/pm/state";
|
||||||
import { Decoration, DecorationSet } from "@tiptap/pm/view";
|
import { Decoration, DecorationSet } from "@tiptap/pm/view";
|
||||||
|
|
||||||
const TAG_RE = /(?<=\s|^)#([\w]+(?:\/[\w]+)*)/g;
|
// Digits alone (`#4286`) are a record reference, not a tag, and are left plain
|
||||||
|
// here; the rendered view links them (utils/recordRefs.ts).
|
||||||
|
const TAG_RE = /(?<=\s|^)#(?!\d+(?![\w/-]))([\w]+(?:\/[\w]+)*)/g;
|
||||||
|
|
||||||
export const TagDecoration = Extension.create({
|
export const TagDecoration = Extension.create({
|
||||||
name: "tagDecoration",
|
name: "tagDecoration",
|
||||||
|
|||||||
@@ -123,6 +123,26 @@ const router = createRouter({
|
|||||||
name: "project-view",
|
name: "project-view",
|
||||||
component: () => import("@/views/ProjectView.vue"),
|
component: () => import("@/views/ProjectView.vue"),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// Where a `milestone N` reference leads. A milestone is shown on its
|
||||||
|
// project's board, so this only looks up which project and goes there.
|
||||||
|
path: "/milestones/:id",
|
||||||
|
name: "milestone",
|
||||||
|
component: () => import("@/views/ProjectListView.vue"),
|
||||||
|
beforeEnter: async (to) => {
|
||||||
|
const id = Number(to.params.id);
|
||||||
|
const { resolveRecordRefs } = await import("@/directives/recordRefs");
|
||||||
|
try {
|
||||||
|
const found = (await resolveRecordRefs([{ space: "milestones", id }])).get(`milestones:${id}`);
|
||||||
|
if (found) return found.href;
|
||||||
|
} catch {
|
||||||
|
// Fall through to the projects list with the notice below.
|
||||||
|
}
|
||||||
|
const { useToastStore } = await import("@/stores/toast");
|
||||||
|
useToastStore().show(`No milestone ${id} you can open`, "warning");
|
||||||
|
return { name: "projects" };
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: "/rules",
|
path: "/rules",
|
||||||
name: "rules",
|
name: "rules",
|
||||||
|
|||||||
@@ -111,6 +111,9 @@ export const useRulebooksStore = defineStore("rulebooks", () => {
|
|||||||
// force as the same row re-fetched, or a preference the operator just
|
// force as the same row re-fetched, or a preference the operator just
|
||||||
// created would sit in the list looking like a rule until a reload.
|
// created would sit in the list looking like a rule until a reload.
|
||||||
kind: rule.kind,
|
kind: rule.kind,
|
||||||
|
enforcement: rule.enforcement ?? "inform",
|
||||||
|
// Mirrors rule_brief: present only when raised or lowered.
|
||||||
|
salience: rule.salience && rule.salience !== "normal" ? rule.salience : undefined,
|
||||||
updated_at: rule.updated_at,
|
updated_at: rule.updated_at,
|
||||||
when_to_apply: rule.when_to_apply || undefined,
|
when_to_apply: rule.when_to_apply || undefined,
|
||||||
arose_from_id: rule.arose_from_id ?? undefined,
|
arose_from_id: rule.arose_from_id ?? undefined,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { marked, type RendererThis, type Tokens } from "marked";
|
import { marked, type RendererThis, type Tokens } from "marked";
|
||||||
import DOMPurify from "dompurify";
|
import DOMPurify from "dompurify";
|
||||||
import { linkifyTags, linkifyWikilinks } from "@/utils/tags";
|
import { linkifyTags, linkifyWikilinks } from "@/utils/tags";
|
||||||
|
import { linkifyRecordRefs } from "@/utils/recordRefs";
|
||||||
|
|
||||||
function decodeEntities(text: string): string {
|
function decodeEntities(text: string): string {
|
||||||
const textarea = document.createElement("textarea");
|
const textarea = document.createElement("textarea");
|
||||||
@@ -20,9 +21,11 @@ export function slugify(text: string): string {
|
|||||||
export function stripFirstLineTags(text: string): string {
|
export function stripFirstLineTags(text: string): string {
|
||||||
const match = text.match(/^[ \t]*((?:(?<!\w)#[\w]+(?:\/[\w]+)*[ \t]*)+)\n?/);
|
const match = text.match(/^[ \t]*((?:(?<!\w)#[\w]+(?:\/[\w]+)*[ \t]*)+)\n?/);
|
||||||
if (!match) return text;
|
if (!match) return text;
|
||||||
// Verify every #-token is a tag, not a heading (headings have "# " with space)
|
// Verify every #-token is a tag, not a heading (headings have "# " with
|
||||||
|
// space) and not a record reference: a first line of "#4286 #4290" cites two
|
||||||
|
// records and stays in the body.
|
||||||
const tokens = match[1].trim().split(/\s+/);
|
const tokens = match[1].trim().split(/\s+/);
|
||||||
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t));
|
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t) && !/^#\d+$/.test(t));
|
||||||
if (!allTags) return text;
|
if (!allTags) return text;
|
||||||
return text.slice(match[0].length);
|
return text.slice(match[0].length);
|
||||||
}
|
}
|
||||||
@@ -38,7 +41,7 @@ const headingRenderer = {
|
|||||||
marked.use({ renderer: headingRenderer });
|
marked.use({ renderer: headingRenderer });
|
||||||
|
|
||||||
const PURIFY_OPTS_FULL = {
|
const PURIFY_OPTS_FULL = {
|
||||||
ADD_ATTR: ["data-tag", "data-title", "data-task-index"],
|
ADD_ATTR: ["data-tag", "data-title", "data-task-index", "data-ref-space", "data-ref-id"],
|
||||||
FORCE_BODY: true,
|
FORCE_BODY: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -64,7 +67,7 @@ export function renderMarkdown(text: string, { interactiveCheckboxes = false } =
|
|||||||
}
|
}
|
||||||
|
|
||||||
const withTags = linkifyTags(html);
|
const withTags = linkifyTags(html);
|
||||||
const withLinks = linkifyWikilinks(withTags);
|
const withLinks = linkifyRecordRefs(linkifyWikilinks(withTags));
|
||||||
const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL);
|
const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL);
|
||||||
// marked escapes ' to ' — replace after sanitization to ensure clean rendering
|
// marked escapes ' to ' — replace after sanitization to ensure clean rendering
|
||||||
return sanitized.replace(/'/g, "'");
|
return sanitized.replace(/'/g, "'");
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
/** Record references in rendered prose: `#N`, `milestone N`, `rule N`.
|
||||||
|
*
|
||||||
|
* Three id spaces, three forms:
|
||||||
|
* `#N` a note, task, lesson or snippet (one sequence, the notes table)
|
||||||
|
* `milestone N` a milestone — the form a batch create writes for `{{ref:milestone}}`
|
||||||
|
* `rule N` a rule; `preference N` too, since a preference is a rule
|
||||||
|
* A `#N` after a word that names another numbering ("PR #198", "rule #34",
|
||||||
|
* "step #3") is not a note, and stays plain text.
|
||||||
|
*
|
||||||
|
* The backend reads references with the same patterns and the same word list
|
||||||
|
* (src/grimoire/services/record_refs.py: REF_RE, PROSE_REF_RE, _OTHER_SPACE),
|
||||||
|
* so a backlink, a graph edge and a rendered link agree about what a body
|
||||||
|
* cites. tests/test_record_ref_links.py fails when the two differ.
|
||||||
|
*
|
||||||
|
* linkifyRecordRefs only marks the references up. What each one IS — its
|
||||||
|
* route, its title, whether the reader can open it — is filled in after render
|
||||||
|
* by the v-record-refs directive (directives/recordRefs.ts), which asks the
|
||||||
|
* server once per rendered body.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const NOTE_REF_RE = /(?<![\w&#/])#(\d+)\b/g;
|
||||||
|
export const PROSE_REF_RE = /(?<![\w/])\b(milestone|rule|preference)\s+#?(\d+)\b/gi;
|
||||||
|
|
||||||
|
export const OTHER_SPACE: readonly string[] = [
|
||||||
|
"pr", "prs", "pull", "pulls", "request", "requests", "mr", "mrs",
|
||||||
|
"run", "runs", "ci", "build", "builds", "job", "jobs", "pipeline",
|
||||||
|
"action", "actions", "commit", "github", "gitlab", "gitea", "gh",
|
||||||
|
"rule", "rules", "preference", "preferences", "milestone", "milestones",
|
||||||
|
"system", "systems", "project", "projects", "log", "logs", "topic",
|
||||||
|
"topics", "rulebook", "rulebooks", "step", "steps", "rank", "line",
|
||||||
|
"lines", "page", "item", "option", "version", "port",
|
||||||
|
];
|
||||||
|
const OTHER_SPACE_SET = new Set(OTHER_SPACE);
|
||||||
|
|
||||||
|
const PREV_WORD_RE = /([A-Za-z]+)[\s"'(\[*_:]*$/;
|
||||||
|
|
||||||
|
export type RefSpace = "notes" | "milestones" | "rules";
|
||||||
|
|
||||||
|
export interface RefMatch {
|
||||||
|
start: number;
|
||||||
|
end: number;
|
||||||
|
space: RefSpace;
|
||||||
|
id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function prevWord(before: string): string {
|
||||||
|
const m = PREV_WORD_RE.exec(before);
|
||||||
|
return m ? m[1].toLowerCase() : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every reference in a run of plain text, in order, never overlapping.
|
||||||
|
* `context` is the text that came before this run, for the word in front of
|
||||||
|
* a `#N` that starts the run. */
|
||||||
|
export function findRecordRefs(text: string, context = ""): RefMatch[] {
|
||||||
|
const found: RefMatch[] = [];
|
||||||
|
for (const m of text.matchAll(PROSE_REF_RE)) {
|
||||||
|
const space: RefSpace = m[1].toLowerCase() === "milestone" ? "milestones" : "rules";
|
||||||
|
found.push({ start: m.index!, end: m.index! + m[0].length, space, id: Number(m[2]) });
|
||||||
|
}
|
||||||
|
for (const m of text.matchAll(NOTE_REF_RE)) {
|
||||||
|
const start = m.index!;
|
||||||
|
const end = start + m[0].length;
|
||||||
|
if (found.some((f) => start < f.end && end > f.start)) continue;
|
||||||
|
if (OTHER_SPACE_SET.has(prevWord(context + text.slice(0, start)))) continue;
|
||||||
|
found.push({ start, end, space: "notes", id: Number(m[1]) });
|
||||||
|
}
|
||||||
|
return found.sort((a, b) => a.start - b.start);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a reference opens before the server has said what it is. A note id
|
||||||
|
* may turn out to be a task, lesson or snippet; the directive corrects it. */
|
||||||
|
export function provisionalHref(space: RefSpace, id: number): string {
|
||||||
|
if (space === "milestones") return `/milestones/${id}`;
|
||||||
|
if (space === "rules") return `/rules?rule=${id}`;
|
||||||
|
return `/notes/${id}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Markup a reference is never drawn inside: an existing link (a wikilink, a
|
||||||
|
// markdown link, a tag chip), code, and the tags themselves.
|
||||||
|
const SKIP_RE = /(<a\b[\s\S]*?<\/a>|<code[\s\S]*?<\/code>|<pre[\s\S]*?<\/pre>|<[^>]+>)/gi;
|
||||||
|
|
||||||
|
/** Wrap each record reference in rendered HTML in an `a.record-ref`. */
|
||||||
|
export function linkifyRecordRefs(html: string): string {
|
||||||
|
const parts = html.split(SKIP_RE);
|
||||||
|
let context = "";
|
||||||
|
return parts
|
||||||
|
.map((part, i) => {
|
||||||
|
// Odd indices are markup the split kept; text between them is even.
|
||||||
|
if (i % 2 === 1) return part;
|
||||||
|
const refs = findRecordRefs(part, context);
|
||||||
|
context = (context + part).slice(-80);
|
||||||
|
if (!refs.length) return part;
|
||||||
|
let out = "";
|
||||||
|
let at = 0;
|
||||||
|
for (const r of refs) {
|
||||||
|
out += part.slice(at, r.start);
|
||||||
|
const label = part.slice(r.start, r.end);
|
||||||
|
out += `<a class="record-ref" data-ref-space="${r.space}" data-ref-id="${r.id}" href="${provisionalHref(r.space, r.id)}">${label}</a>`;
|
||||||
|
at = r.end;
|
||||||
|
}
|
||||||
|
return out + part.slice(at);
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
const CODE_FENCE_RE = /```[\s\S]*?```|`[^`\n]+`/g;
|
const CODE_FENCE_RE = /```[\s\S]*?```|`[^`\n]+`/g;
|
||||||
const TAG_RE = /(?<!\w)(?<!&)#([\w][\w-]*(?:\/[\w][\w-]*)*)/g;
|
// A `#` token made only of digits is a record reference (`#3127` names a note,
|
||||||
|
// task, lesson or snippet; utils/recordRefs.ts links it), never a tag. Digits
|
||||||
|
// followed by more of a tag (`#2fa`, `#123-notes`) is still a tag. The backend's
|
||||||
|
// src/grimoire/utils/tags.py holds the same pattern.
|
||||||
|
export const TAG_RE = /(?<!\w)(?<!&)#(?!\d+(?![\w/-]))([\w][\w-]*(?:\/[\w][\w-]*)*)/g;
|
||||||
|
|
||||||
function escapeHtmlAttr(s: string): string {
|
function escapeHtmlAttr(s: string): string {
|
||||||
return s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
return s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { drag } from "d3-drag";
|
|||||||
import { select } from "d3-selection";
|
import { select } from "d3-selection";
|
||||||
import { apiGet } from "@/api/client";
|
import { apiGet } from "@/api/client";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
@@ -26,7 +27,8 @@ interface GraphNode extends SimulationNodeDatum {
|
|||||||
interface GraphEdge {
|
interface GraphEdge {
|
||||||
source: number | string | GraphNode;
|
source: number | string | GraphNode;
|
||||||
target: number | string | GraphNode;
|
target: number | string | GraphNode;
|
||||||
type: "wikilink" | "tag";
|
/** wikilink: `[[title]]`; reference: a `#N` citation; tag: a shared tag. */
|
||||||
|
type: "wikilink" | "reference" | "tag";
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Project {
|
interface Project {
|
||||||
@@ -237,12 +239,14 @@ function initGraph() {
|
|||||||
.append("line")
|
.append("line")
|
||||||
.attr("class", "graph-edge")
|
.attr("class", "graph-edge")
|
||||||
.attr("stroke", (d: any) =>
|
.attr("stroke", (d: any) =>
|
||||||
d.type === "wikilink" ? "var(--fs-accent)" : "var(--fs-text-tertiary)"
|
d.type === "tag" ? "var(--fs-text-tertiary)" : "var(--fs-accent)"
|
||||||
)
|
)
|
||||||
.attr("stroke-opacity", (d: any) => (d.type === "wikilink" ? 0.5 : 0.4))
|
.attr("stroke-opacity", (d: any) => (d.type === "tag" ? 0.4 : 0.5))
|
||||||
.attr("stroke-dasharray", null)
|
// A citation is a looser link than a wikilink: same colour and direction,
|
||||||
.attr("stroke-width", (d: any) => (d.type === "wikilink" ? 1.5 : 1))
|
// drawn dashed so the two read apart.
|
||||||
.attr("marker-end", (d: any) => (d.type === "wikilink" ? "url(#arrow)" : null));
|
.attr("stroke-dasharray", (d: any) => (d.type === "reference" ? "4 3" : null))
|
||||||
|
.attr("stroke-width", (d: any) => (d.type === "tag" ? 1 : 1.5))
|
||||||
|
.attr("marker-end", (d: any) => (d.type === "tag" ? null : "url(#arrow)"));
|
||||||
|
|
||||||
// Node groups
|
// Node groups
|
||||||
const nodeSel = zoomG
|
const nodeSel = zoomG
|
||||||
@@ -559,7 +563,7 @@ onUnmounted(() => {
|
|||||||
<div
|
<div
|
||||||
v-else-if="peekBody"
|
v-else-if="peekBody"
|
||||||
class="prose peek-prose"
|
class="prose peek-prose"
|
||||||
v-html="renderMarkdown(peekBody)"
|
v-html="renderMarkdown(peekBody)" v-record-refs
|
||||||
/>
|
/>
|
||||||
<div v-else class="peek-empty">No content.</div>
|
<div v-else class="peek-empty">No content.</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ import { apiErrorMessage } from "@/api/client";
|
|||||||
import {
|
import {
|
||||||
deleteLesson,
|
deleteLesson,
|
||||||
getLesson,
|
getLesson,
|
||||||
judgeLessonLink,
|
|
||||||
type Lesson,
|
type Lesson,
|
||||||
type LessonRuleLink,
|
type LessonRuleLink,
|
||||||
} from "@/api/lessons";
|
} from "@/api/lessons";
|
||||||
@@ -40,8 +39,10 @@ import UsageBadge from "@/components/UsageBadge.vue";
|
|||||||
import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
|
import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
|
||||||
import { useToastStore } from "@/stores/toast";
|
import { useToastStore } from "@/stores/toast";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
import { canWriteRecord } from "@/utils/permission";
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
import { recordHref } from "@/utils/recordHref";
|
import { recordHref } from "@/utils/recordHref";
|
||||||
|
import { canWriteRecord } from "@/utils/permission";
|
||||||
|
import LessonSituationsPanel from "@/components/LessonSituationsPanel.vue";
|
||||||
|
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -64,13 +65,10 @@ const insightHtml = computed(() =>
|
|||||||
const canWrite = computed(() => canWriteRecord(lesson.value?.permission));
|
const canWrite = computed(() => canWriteRecord(lesson.value?.permission));
|
||||||
|
|
||||||
/** The links by state — each state reads differently. Confirmed links are
|
/** The links by state — each state reads differently. Confirmed links are
|
||||||
* the answer; suggested ones are evidence waiting on a judgment; rejected
|
* the answer; rejected ones are kept so the reason stays readable. */
|
||||||
* ones are kept so the pair is never proposed again, and shown so the reason
|
|
||||||
* stays readable. */
|
|
||||||
const linksIn = (state: LessonRuleLink["state"]) =>
|
const linksIn = (state: LessonRuleLink["state"]) =>
|
||||||
computed(() => (lesson.value?.rules ?? []).filter((r) => r.state === state));
|
computed(() => (lesson.value?.rules ?? []).filter((r) => r.state === state));
|
||||||
const confirmedRules = linksIn("confirmed");
|
const confirmedRules = linksIn("confirmed");
|
||||||
const suggestedRules = linksIn("suggested");
|
|
||||||
const rejectedRules = linksIn("rejected");
|
const rejectedRules = linksIn("rejected");
|
||||||
|
|
||||||
/** A rule opens in the rules view's editor, which takes the rule alone. */
|
/** A rule opens in the rules view's editor, which takes the rule alone. */
|
||||||
@@ -78,36 +76,6 @@ function ruleHref(ruleId: number) {
|
|||||||
return { path: "/rules", query: { rule: String(ruleId) } };
|
return { path: "/rules", query: { rule: String(ruleId) } };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** What a suggestion rests on, in the units it was proposed by: distinct
|
|
||||||
* situations, not raw arrivals — one situation repeated proves nothing. */
|
|
||||||
function evidenceLine(ev: NonNullable<LessonRuleLink["evidence"]>): string {
|
|
||||||
const situations = `${ev.situations} distinct situation${ev.situations === 1 ? "" : "s"}`;
|
|
||||||
const projects = ev.projects > 1 ? `, across ${ev.projects} projects` : "";
|
|
||||||
return `Arrived together in ${situations}${projects}.`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const judging = ref<number | null>(null);
|
|
||||||
|
|
||||||
/** Judge a suggested link from here. Re-reads the lesson rather than editing
|
|
||||||
* the list in place: confirming also clears a "no rule fits" answer, and the
|
|
||||||
* judgment line has to come back from the server to be right. */
|
|
||||||
async function judge(rule: LessonRuleLink, verdict: "confirm" | "reject") {
|
|
||||||
judging.value = rule.id;
|
|
||||||
try {
|
|
||||||
await judgeLessonLink(lessonId.value, rule.id, verdict);
|
|
||||||
lesson.value = await getLesson(lessonId.value);
|
|
||||||
toast.show(
|
|
||||||
verdict === "confirm"
|
|
||||||
? "Linked — the rule can now surface through this lesson"
|
|
||||||
: "Not an instance — this pair will not be suggested again",
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
toast.show(apiErrorMessage(e, "Failed to record the judgment"), "error");
|
|
||||||
} finally {
|
|
||||||
judging.value = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = null;
|
error.value = null;
|
||||||
@@ -171,7 +139,7 @@ onMounted(load);
|
|||||||
<div
|
<div
|
||||||
v-if="insightHtml"
|
v-if="insightHtml"
|
||||||
class="ld-insight markdown-body"
|
class="ld-insight markdown-body"
|
||||||
v-html="insightHtml"
|
v-html="insightHtml" v-record-refs
|
||||||
/>
|
/>
|
||||||
<p v-else class="ld-muted ld-empty">
|
<p v-else class="ld-muted ld-empty">
|
||||||
No detail was recorded — the claim above is the whole lesson.
|
No detail was recorded — the claim above is the whole lesson.
|
||||||
@@ -222,39 +190,6 @@ onMounted(load);
|
|||||||
nobody has said none fits.
|
nobody has said none fits.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<template v-if="suggestedRules.length">
|
|
||||||
<h3 class="ld-sub-label">Suggested</h3>
|
|
||||||
<ul class="ld-sources">
|
|
||||||
<li v-for="r in suggestedRules" :key="r.id">
|
|
||||||
<router-link :to="ruleHref(r.id)" class="ld-link">
|
|
||||||
{{ r.title }}
|
|
||||||
</router-link>
|
|
||||||
<span v-if="r.kind === 'preference'" class="rule-chip rule-chip-preference">
|
|
||||||
preference
|
|
||||||
</span>
|
|
||||||
<p v-if="r.evidence" class="ld-link-note">{{ evidenceLine(r.evidence) }}</p>
|
|
||||||
<div v-if="canWrite" class="ld-judge">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="ld-ghost ld-small"
|
|
||||||
:disabled="judging === r.id"
|
|
||||||
@click="judge(r, 'confirm')"
|
|
||||||
>
|
|
||||||
Confirm
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="ld-ghost ld-small"
|
|
||||||
:disabled="judging === r.id"
|
|
||||||
@click="judge(r, 'reject')"
|
|
||||||
>
|
|
||||||
Not an instance
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<template v-if="rejectedRules.length">
|
<template v-if="rejectedRules.length">
|
||||||
<h3 class="ld-sub-label">Judged not an instance</h3>
|
<h3 class="ld-sub-label">Judged not an instance</h3>
|
||||||
<ul class="ld-sources ld-rejected">
|
<ul class="ld-sources ld-rejected">
|
||||||
@@ -268,6 +203,8 @@ onMounted(load);
|
|||||||
</template>
|
</template>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<LessonSituationsPanel :lesson-id="lesson.id" :can-write="canWrite" />
|
||||||
|
|
||||||
<section v-if="lesson.tags?.length" class="ld-tags">
|
<section v-if="lesson.tags?.length" class="ld-tags">
|
||||||
<TagPill v-for="t in lesson.tags" :key="t" :tag="t" />
|
<TagPill v-for="t in lesson.tags" :key="t" :tag="t" />
|
||||||
</section>
|
</section>
|
||||||
@@ -409,8 +346,6 @@ onMounted(load);
|
|||||||
color: var(--fs-text-tertiary);
|
color: var(--fs-text-tertiary);
|
||||||
}
|
}
|
||||||
.ld-rejected .ld-link { color: var(--fs-text-secondary); }
|
.ld-rejected .ld-link { color: var(--fs-text-secondary); }
|
||||||
.ld-judge { display: flex; gap: var(--fs-space-2); margin-top: var(--fs-space-1); }
|
|
||||||
.ld-small { padding: 0.15rem 0.6rem; font-size: var(--fs-size-label); }
|
|
||||||
.ld-ghost:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
|
.ld-ghost:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
|
||||||
|
|
||||||
.ld-tags { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 1.25rem; }
|
.ld-tags { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 1.25rem; }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { NoteType } from "@/types/note";
|
|||||||
import { useNotesStore } from "@/stores/notes";
|
import { useNotesStore } from "@/stores/notes";
|
||||||
import { useToastStore } from "@/stores/toast";
|
import { useToastStore } from "@/stores/toast";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
import { useAssist, type NoteDraft } from "@/composables/useAssist";
|
import { useAssist, type NoteDraft } from "@/composables/useAssist";
|
||||||
import { useAutoSave } from "@/composables/useAutoSave";
|
import { useAutoSave } from "@/composables/useAutoSave";
|
||||||
import { useEditorGuards } from "@/composables/useEditorGuards";
|
import { useEditorGuards } from "@/composables/useEditorGuards";
|
||||||
@@ -439,7 +440,7 @@ onUnmounted(() => assist.clearSelection());
|
|||||||
<div
|
<div
|
||||||
v-else
|
v-else
|
||||||
class="preview-pane prose"
|
class="preview-pane prose"
|
||||||
v-html="renderedPreview"
|
v-html="renderedPreview" v-record-refs
|
||||||
/>
|
/>
|
||||||
</Transition>
|
</Transition>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ import { onMounted, computed, ref, watch } from "vue";
|
|||||||
import { useRoute, useRouter } from "vue-router";
|
import { useRoute, useRouter } from "vue-router";
|
||||||
import { useNotesStore } from "@/stores/notes";
|
import { useNotesStore } from "@/stores/notes";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
|
import { recordHref } from "@/utils/recordHref";
|
||||||
import { relativeTime } from "@/composables/useRelativeTime";
|
import { relativeTime } from "@/composables/useRelativeTime";
|
||||||
import { apiPost, apiGet, apiPatch } from "@/api/client";
|
import { apiPost, apiGet, apiPatch } from "@/api/client";
|
||||||
import type { Note } from "@/types/note";
|
import type { Note } from "@/types/note";
|
||||||
@@ -14,7 +16,12 @@ import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next";
|
|||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const store = useNotesStore();
|
const store = useNotesStore();
|
||||||
const backlinks = ref<{ type: string; id: number; title: string }[]>([]);
|
/** What links here, and how: a `[[title]]` wikilink or a `#N` reference in a
|
||||||
|
* body or work log. */
|
||||||
|
const backlinks = ref<{
|
||||||
|
type: string; id: number; title: string;
|
||||||
|
is_task?: boolean; note_type?: string; via?: "wikilink" | "reference";
|
||||||
|
}[]>([]);
|
||||||
const converting = ref(false);
|
const converting = ref(false);
|
||||||
const showShare = ref(false);
|
const showShare = ref(false);
|
||||||
|
|
||||||
@@ -259,7 +266,7 @@ async function convertToTask() {
|
|||||||
<div
|
<div
|
||||||
class="body prose"
|
class="body prose"
|
||||||
:class="{ 'prose--checklist': isListNote }"
|
:class="{ 'prose--checklist': isListNote }"
|
||||||
v-html="renderedBody"
|
v-html="renderedBody" v-record-refs
|
||||||
@click="onBodyClick"
|
@click="onBodyClick"
|
||||||
@change="onBodyChange"
|
@change="onBodyChange"
|
||||||
></div>
|
></div>
|
||||||
@@ -274,7 +281,8 @@ async function convertToTask() {
|
|||||||
<router-link
|
<router-link
|
||||||
v-for="link in backlinks"
|
v-for="link in backlinks"
|
||||||
:key="`${link.type}-${link.id}`"
|
:key="`${link.type}-${link.id}`"
|
||||||
:to="`/${link.type === 'note' ? 'notes' : 'tasks'}/${link.id}`"
|
:to="recordHref({ id: link.id, is_task: link.is_task ?? link.type === 'task', note_type: link.note_type })"
|
||||||
|
:title="link.via === 'reference' ? `Cites #${noteId} in its text` : `Links here by title`"
|
||||||
class="backlink-card"
|
class="backlink-card"
|
||||||
>
|
>
|
||||||
<span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
|
<span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, onMounted, watch } from "vue";
|
import { ref, computed, onMounted, watch, nextTick } from "vue";
|
||||||
import { useRoute, useRouter } from "vue-router";
|
import { useRoute, useRouter } from "vue-router";
|
||||||
import { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client";
|
import { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client";
|
||||||
import { useAuthStore } from "@/stores/auth";
|
import { useAuthStore } from "@/stores/auth";
|
||||||
@@ -7,6 +7,7 @@ import { useToastStore } from "@/stores/toast";
|
|||||||
import { useTasksStore } from "@/stores/tasks";
|
import { useTasksStore } from "@/stores/tasks";
|
||||||
import { relativeTime } from "@/composables/useRelativeTime";
|
import { relativeTime } from "@/composables/useRelativeTime";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
import ShareDialog from "@/components/ShareDialog.vue";
|
import ShareDialog from "@/components/ShareDialog.vue";
|
||||||
import KindBadge from "@/components/KindBadge.vue";
|
import KindBadge from "@/components/KindBadge.vue";
|
||||||
import ProjectStatusBadge from "@/components/ProjectStatusBadge.vue";
|
import ProjectStatusBadge from "@/components/ProjectStatusBadge.vue";
|
||||||
@@ -585,8 +586,27 @@ async function saveForgePin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** `?milestone=N` opens the board at that milestone: the Tasks tab, the
|
||||||
|
* milestone expanded and scrolled into view, its header focused. This is
|
||||||
|
* where a `milestone N` reference in any body leads. */
|
||||||
|
async function focusMilestoneFromRoute() {
|
||||||
|
const id = Number(route.query.milestone);
|
||||||
|
if (!id || !milestones.value.some((m) => m.id === id)) return;
|
||||||
|
activeTab.value = "tasks";
|
||||||
|
collapsedMilestones.value.delete(id);
|
||||||
|
await nextTick();
|
||||||
|
const header = document.querySelector<HTMLElement>(
|
||||||
|
`[data-milestone-id="${id}"] .milestone-header`,
|
||||||
|
);
|
||||||
|
header?.scrollIntoView({ block: "start", behavior: "smooth" });
|
||||||
|
header?.focus({ preventScroll: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => route.query.milestone, () => void focusMilestoneFromRoute());
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await loadProject();
|
await loadProject();
|
||||||
|
void focusMilestoneFromRoute();
|
||||||
loadTasks();
|
loadTasks();
|
||||||
loadNotes();
|
loadNotes();
|
||||||
loadDesignSystems();
|
loadDesignSystems();
|
||||||
@@ -985,9 +1005,15 @@ async function confirmDelete() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-for="group in milestoneGroups" :key="group.milestone?.id ?? 'unassigned'" class="milestone-group">
|
<div
|
||||||
|
v-for="group in milestoneGroups"
|
||||||
|
:key="group.milestone?.id ?? 'unassigned'"
|
||||||
|
class="milestone-group"
|
||||||
|
:data-milestone-id="group.milestone?.id"
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
class="milestone-header"
|
class="milestone-header"
|
||||||
|
tabindex="-1"
|
||||||
:class="{ clickable: renamingMilestoneId !== group.milestone?.id }"
|
:class="{ clickable: renamingMilestoneId !== group.milestone?.id }"
|
||||||
:aria-expanded="!collapsedMilestones.has(groupKey(group))"
|
:aria-expanded="!collapsedMilestones.has(groupKey(group))"
|
||||||
@click="renamingMilestoneId !== group.milestone?.id && toggleMilestoneCollapse(groupKey(group))"
|
@click="renamingMilestoneId !== group.milestone?.id && toggleMilestoneCollapse(groupKey(group))"
|
||||||
@@ -1050,7 +1076,7 @@ async function confirmDelete() {
|
|||||||
:class="['ms-plan-rendered', 'markdown-body',
|
:class="['ms-plan-rendered', 'markdown-body',
|
||||||
{ 'ms-plan-clamped': isPlanClamped(group.milestone) }]"
|
{ 'ms-plan-clamped': isPlanClamped(group.milestone) }]"
|
||||||
@click="startEditPlan(group.milestone.id, group.milestone.body)"
|
@click="startEditPlan(group.milestone.id, group.milestone.body)"
|
||||||
v-html="renderMarkdown(group.milestone.body || '')"
|
v-html="renderMarkdown(group.milestone.body || '')" v-record-refs
|
||||||
></div>
|
></div>
|
||||||
<button
|
<button
|
||||||
v-if="isPlanLong(group.milestone)"
|
v-if="isPlanLong(group.milestone)"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { apiGet, apiPost, apiPut, apiDelete, listGroups, createGroup, deleteGrou
|
|||||||
import type { User } from "@/types/auth";
|
import type { User } from "@/types/auth";
|
||||||
import PaginationBar from "@/components/PaginationBar.vue";
|
import PaginationBar from "@/components/PaginationBar.vue";
|
||||||
import MomentsSettings from "@/components/MomentsSettings.vue";
|
import MomentsSettings from "@/components/MomentsSettings.vue";
|
||||||
|
import ReverseProxySettings from "@/components/ReverseProxySettings.vue";
|
||||||
import ReplyShapesSettings from "@/components/ReplyShapesSettings.vue";
|
import ReplyShapesSettings from "@/components/ReplyShapesSettings.vue";
|
||||||
import BackupScheduleSettings from "@/components/BackupScheduleSettings.vue";
|
import BackupScheduleSettings from "@/components/BackupScheduleSettings.vue";
|
||||||
import RestoreBackupDialog from "@/components/RestoreBackupDialog.vue";
|
import RestoreBackupDialog from "@/components/RestoreBackupDialog.vue";
|
||||||
@@ -171,6 +172,42 @@ const kbReplyRuleThreshold = ref("0.8");
|
|||||||
// is raising its bar, which discards the surface's best candidates along with
|
// is raising its bar, which discards the surface's best candidates along with
|
||||||
// its worst. A budget keeps the top of the ranking and drops the tail.
|
// its worst. A budget keeps the top of the ranking and drops the tail.
|
||||||
const kbWritePathTopK = ref("3");
|
const kbWritePathTopK = ref("3");
|
||||||
|
// The most one hook call may inject, in characters (hook_payload.DEFAULT_BUDGET).
|
||||||
|
const kbHookBudget = ref("4500");
|
||||||
|
// How often a record found by resemblance alone may speak, as a percent of
|
||||||
|
// cues that match nothing in particular (cue_gate.RATE_DEFAULT).
|
||||||
|
const kbCueGateRate = ref("10");
|
||||||
|
|
||||||
|
// GatedSurface — one row of /api/retrieval/gate.
|
||||||
|
interface GatedSurface {
|
||||||
|
surface: string;
|
||||||
|
gates: string;
|
||||||
|
bar: number | null;
|
||||||
|
sample: number;
|
||||||
|
calls: number;
|
||||||
|
fired: number;
|
||||||
|
days: number;
|
||||||
|
unreadable?: boolean;
|
||||||
|
}
|
||||||
|
const gatedSurfaces = ref<GatedSurface[]>([]);
|
||||||
|
const gateMinSample = ref(20);
|
||||||
|
|
||||||
|
function gateSummary(g: GatedSurface): string {
|
||||||
|
if (g.unreadable) return "unreadable right now";
|
||||||
|
const spoke = g.calls ? `spoke on ${g.fired} of ${g.calls} calls in ${g.days} days` : "no gated calls yet";
|
||||||
|
if (g.bar === null) return `learning (${g.sample} of ${gateMinSample.value} cues), silent until then; ${spoke}`;
|
||||||
|
return `bar ${g.bar.toFixed(2)} from your last ${g.sample} cues; ${spoke}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadGate() {
|
||||||
|
try {
|
||||||
|
const res = await apiGet<{ surfaces: GatedSurface[]; min_sample: number }>("/api/retrieval/gate");
|
||||||
|
gatedSurfaces.value = res.surfaces ?? [];
|
||||||
|
gateMinSample.value = res.min_sample ?? 20;
|
||||||
|
} catch {
|
||||||
|
gatedSurfaces.value = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
const kbRuleHintTopK = ref("5");
|
const kbRuleHintTopK = ref("5");
|
||||||
const kbToolRuleTopK = ref("5");
|
const kbToolRuleTopK = ref("5");
|
||||||
const kbPromptRuleTopK = ref("3");
|
const kbPromptRuleTopK = ref("3");
|
||||||
@@ -384,6 +421,13 @@ async function saveKbInject() {
|
|||||||
const prK = asK(kbPromptRuleTopK.value, 3);
|
const prK = asK(kbPromptRuleTopK.value, 3);
|
||||||
const ryK = asK(kbReplyRuleTopK.value, 1);
|
const ryK = asK(kbReplyRuleTopK.value, 1);
|
||||||
kbWritePathTopK.value = String(wpK);
|
kbWritePathTopK.value = String(wpK);
|
||||||
|
// Clamped as the server clamps it (hook_payload.HARD_MAX): Claude Code shows
|
||||||
|
// a hook's context past its cap only as a short preview.
|
||||||
|
const budget = Math.min(7500, Math.max(1000, Math.floor(Number(kbHookBudget.value) || 4500)));
|
||||||
|
kbHookBudget.value = String(budget);
|
||||||
|
// Clamped as the server clamps it (cue_gate.RATE_MIN / RATE_MAX).
|
||||||
|
const gateRate = Math.min(50, Math.max(1, Math.floor(Number(kbCueGateRate.value) || 10)));
|
||||||
|
kbCueGateRate.value = String(gateRate);
|
||||||
kbRuleHintTopK.value = String(rhK);
|
kbRuleHintTopK.value = String(rhK);
|
||||||
kbToolRuleTopK.value = String(trK);
|
kbToolRuleTopK.value = String(trK);
|
||||||
kbPromptRuleTopK.value = String(prK);
|
kbPromptRuleTopK.value = String(prK);
|
||||||
@@ -432,6 +476,8 @@ async function saveKbInject() {
|
|||||||
// change the OPERATOR made — which is the one entry the model must not
|
// change the OPERATOR made — which is the one entry the model must not
|
||||||
// quietly tune back.
|
// quietly tune back.
|
||||||
kb_writepath_top_k: String(wpK),
|
kb_writepath_top_k: String(wpK),
|
||||||
|
kb_hook_budget_chars: String(budget),
|
||||||
|
kb_cue_gate_rate: String(gateRate),
|
||||||
kb_rulehint_top_k: String(rhK),
|
kb_rulehint_top_k: String(rhK),
|
||||||
kb_toolrule_top_k: String(trK),
|
kb_toolrule_top_k: String(trK),
|
||||||
kb_promptrule_top_k: String(prK),
|
kb_promptrule_top_k: String(prK),
|
||||||
@@ -453,6 +499,7 @@ async function saveKbInject() {
|
|||||||
// the operator is looking at it to confirm.
|
// the operator is looking at it to confirm.
|
||||||
await loadTuningHistory();
|
await loadTuningHistory();
|
||||||
await loadSurfaces();
|
await loadSurfaces();
|
||||||
|
await loadGate();
|
||||||
} catch {
|
} catch {
|
||||||
toastStore.show('Failed to save auto-inject settings', 'error');
|
toastStore.show('Failed to save auto-inject settings', 'error');
|
||||||
} finally {
|
} finally {
|
||||||
@@ -856,6 +903,12 @@ onMounted(async () => {
|
|||||||
if (allSettings.kb_writepath_threshold !== undefined) {
|
if (allSettings.kb_writepath_threshold !== undefined) {
|
||||||
kbWritePathThreshold.value = allSettings.kb_writepath_threshold;
|
kbWritePathThreshold.value = allSettings.kb_writepath_threshold;
|
||||||
}
|
}
|
||||||
|
if (allSettings.kb_hook_budget_chars !== undefined) {
|
||||||
|
kbHookBudget.value = allSettings.kb_hook_budget_chars;
|
||||||
|
}
|
||||||
|
if (allSettings.kb_cue_gate_rate !== undefined) {
|
||||||
|
kbCueGateRate.value = allSettings.kb_cue_gate_rate;
|
||||||
|
}
|
||||||
if (allSettings.kb_writepath_top_k !== undefined) {
|
if (allSettings.kb_writepath_top_k !== undefined) {
|
||||||
kbWritePathTopK.value = allSettings.kb_writepath_top_k;
|
kbWritePathTopK.value = allSettings.kb_writepath_top_k;
|
||||||
} else if (allSettings.kb_autoinject_top_k !== undefined) {
|
} else if (allSettings.kb_autoinject_top_k !== undefined) {
|
||||||
@@ -878,6 +931,7 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
await loadTuningHistory();
|
await loadTuningHistory();
|
||||||
await loadSurfaces();
|
await loadSurfaces();
|
||||||
|
await loadGate();
|
||||||
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
|
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
|
||||||
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
|
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
|
||||||
}
|
}
|
||||||
@@ -1653,7 +1707,7 @@ async function deleteUser(userId: number) {
|
|||||||
class="fs-input input"
|
class="fs-input input"
|
||||||
style="max-width: 8rem"
|
style="max-width: 8rem"
|
||||||
/>
|
/>
|
||||||
<p class="field-hint">Ceiling on titles surfaced at once (1–10).</p>
|
<p class="field-hint">How many records each prompt is ranked against (1–10); at most two are shown, and only past the resemblance gate below.</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="checkbox-field">
|
<div class="checkbox-field">
|
||||||
<label>
|
<label>
|
||||||
@@ -1694,6 +1748,45 @@ async function deleteUser(userId: number) {
|
|||||||
location, not by resemblance.
|
location, not by resemblance.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="kb-hook-budget">Most context one hook may add (characters)</label>
|
||||||
|
<input
|
||||||
|
id="kb-hook-budget"
|
||||||
|
v-model="kbHookBudget"
|
||||||
|
type="number"
|
||||||
|
min="1000"
|
||||||
|
max="7500"
|
||||||
|
step="500"
|
||||||
|
class="fs-input input"
|
||||||
|
style="max-width: 8rem"
|
||||||
|
/>
|
||||||
|
<p class="field-hint">Everything Grimoire adds beside one prompt, edit or command, from 1,000 to 7,500 characters. Rules go in first, then the reply shape, then records, until this is spent; whatever is left out can arrive on a later call. Claude Code shows a hook's context past its cap only as a short preview, so the ceiling stays well under it.</p>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label for="kb-cue-gate-rate">How often records found by resemblance may speak (%)</label>
|
||||||
|
<input
|
||||||
|
id="kb-cue-gate-rate"
|
||||||
|
v-model="kbCueGateRate"
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="50"
|
||||||
|
step="1"
|
||||||
|
class="fs-input input"
|
||||||
|
style="max-width: 8rem"
|
||||||
|
/>
|
||||||
|
<p class="field-hint">
|
||||||
|
A record or preference matched only by wording is shown when the message
|
||||||
|
resembles it better than all but this share of your recent messages did:
|
||||||
|
at most two lines, and none until {{ gateMinSample }} messages have been seen.
|
||||||
|
</p>
|
||||||
|
<ul v-if="gatedSurfaces.length" class="gate-readout">
|
||||||
|
<li v-for="g in gatedSurfaces" :key="g.surface">
|
||||||
|
<span class="tuning-surface">{{ g.surface }}</span>
|
||||||
|
<span class="gate-gates">{{ g.gates }}</span>
|
||||||
|
<span class="gate-state">{{ gateSummary(g) }}</span>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label for="kb-writepath-topk">Max prior-art lines per edit</label>
|
<label for="kb-writepath-topk">Max prior-art lines per edit</label>
|
||||||
<input
|
<input
|
||||||
@@ -2664,6 +2757,16 @@ async function deleteUser(userId: number) {
|
|||||||
<div v-else class="empty-msg">Nothing asked yet.</div>
|
<div v-else class="empty-msg">Nothing asked yet.</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="settings-section full-width">
|
||||||
|
<h2>Reverse proxy</h2>
|
||||||
|
<p class="section-desc">
|
||||||
|
How many proxies a request passes through before it reaches Grimoire. Sign-in rate
|
||||||
|
limits and the audit log key on the visitor's address, read through this count; if it
|
||||||
|
is too low, every visitor reads as the proxy and one run of bad sign-ins blocks everyone.
|
||||||
|
</p>
|
||||||
|
<ReverseProxySettings />
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="settings-section full-width">
|
<section class="settings-section full-width">
|
||||||
<h2>Application URL</h2>
|
<h2>Application URL</h2>
|
||||||
<p class="section-desc">
|
<p class="section-desc">
|
||||||
@@ -4247,6 +4350,23 @@ async function deleteUser(userId: number) {
|
|||||||
font-family: var(--fs-font-mono);
|
font-family: var(--fs-font-mono);
|
||||||
color: var(--fs-text-primary);
|
color: var(--fs-text-primary);
|
||||||
}
|
}
|
||||||
|
.gate-readout {
|
||||||
|
list-style: none;
|
||||||
|
margin: var(--fs-space-2) 0 0;
|
||||||
|
padding: 0;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--fs-space-1);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
.gate-readout li {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: var(--fs-space-2);
|
||||||
|
}
|
||||||
|
.gate-gates,
|
||||||
|
.gate-state {
|
||||||
|
color: var(--fs-text-secondary);
|
||||||
|
}
|
||||||
.tuning-dial,
|
.tuning-dial,
|
||||||
.tuning-move {
|
.tuning-move {
|
||||||
color: var(--fs-text-secondary);
|
color: var(--fs-text-secondary);
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
import { useToastStore } from "@/stores/toast";
|
import { useToastStore } from "@/stores/toast";
|
||||||
import ConfirmDialog from "@/components/ConfirmDialog.vue";
|
import ConfirmDialog from "@/components/ConfirmDialog.vue";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
import { canWriteRecord } from "@/utils/permission";
|
import { canWriteRecord } from "@/utils/permission";
|
||||||
|
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
@@ -185,7 +186,7 @@ async function confirmDelete() {
|
|||||||
|
|
||||||
<section v-if="snippet.snippet.notes" class="notes">
|
<section v-if="snippet.snippet.notes" class="notes">
|
||||||
<h2 class="notes-heading">Notes</h2>
|
<h2 class="notes-heading">Notes</h2>
|
||||||
<div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" />
|
<div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" v-record-refs />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div v-if="snippet.tags.length" class="tag-row">
|
<div v-if="snippet.tags.length" class="tag-row">
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { useTasksStore } from "@/stores/tasks";
|
|||||||
import { useNotesStore } from "@/stores/notes";
|
import { useNotesStore } from "@/stores/notes";
|
||||||
import { useToastStore } from "@/stores/toast";
|
import { useToastStore } from "@/stores/toast";
|
||||||
import { renderMarkdown } from "@/utils/markdown";
|
import { renderMarkdown } from "@/utils/markdown";
|
||||||
|
import { vRecordRefs } from "@/directives/recordRefs";
|
||||||
import { useAssist } from "@/composables/useAssist";
|
import { useAssist } from "@/composables/useAssist";
|
||||||
import { useAutoSave } from "@/composables/useAutoSave";
|
import { useAutoSave } from "@/composables/useAutoSave";
|
||||||
import { useEditorGuards } from "@/composables/useEditorGuards";
|
import { useEditorGuards } from "@/composables/useEditorGuards";
|
||||||
@@ -538,7 +539,7 @@ useEditorGuards(dirty, save);
|
|||||||
<div
|
<div
|
||||||
v-show="showPreview"
|
v-show="showPreview"
|
||||||
class="preview-pane prose"
|
class="preview-pane prose"
|
||||||
v-html="renderedPreview"
|
v-html="renderedPreview" v-record-refs
|
||||||
/>
|
/>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "grimoire",
|
"name": "grimoire",
|
||||||
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
|
||||||
"version": "2026.11.05.0301",
|
"version": "2026.11.25.0016",
|
||||||
"author": {
|
"author": {
|
||||||
"name": "Bryan Van Deusen"
|
"name": "Bryan Van Deusen"
|
||||||
},
|
},
|
||||||
|
|||||||
+3
-3
@@ -15,7 +15,7 @@ another one means adding files, not moving or rewriting any.
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
|
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
|
||||||
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
|
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
|
||||||
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule or — when the turn closed a task — for missing completion sections). |
|
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). |
|
||||||
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
|
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
|
||||||
|
|
||||||
## Added by each client
|
## Added by each client
|
||||||
@@ -40,9 +40,9 @@ another one means adding files, not moving or rewriting any.
|
|||||||
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
|
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
|
||||||
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
|
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
|
||||||
| `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason; PostToolUse on `enter_project` remembers the project a session without one entered. |
|
| `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason; PostToolUse on `enter_project` remembers the project a session without one entered. |
|
||||||
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). |
|
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session). |
|
||||||
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. |
|
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. |
|
||||||
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check`; blocks once, with the reason the server returns, so the agent judges what it built. |
|
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check` and keeps the `note` it returns for the next prompt, which `grimoire_autoinject.sh` carries as `carry`, so the agent judges what it built. Never blocks. |
|
||||||
| `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. |
|
| `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. |
|
||||||
| `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
|
| `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
|
||||||
| `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. |
|
| `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. |
|
||||||
|
|||||||
+11
-7
@@ -97,7 +97,9 @@ On install you'll be asked for:
|
|||||||
→ `POST /api/plugin/moment`: the rules mounted on the moments the call
|
→ `POST /api/plugin/moment`: the rules mounted on the moments the call
|
||||||
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
|
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
|
||||||
nothing mounted, and Grimoire's own tools, whose responses carry
|
nothing mounted, and Grimoire's own tools, whose responses carry
|
||||||
`moment_rules`.
|
`moment_rules`. A rule set to enforce refuses the call (every time it is
|
||||||
|
reached); one set to hold denies it once until it has been read, never on a
|
||||||
|
file edit.
|
||||||
- `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`,
|
- `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`,
|
||||||
`rule_outcome`, `update_task` and `add_task_log`: they keep the session's
|
`rule_outcome`, `update_task` and `add_task_log`: they keep the session's
|
||||||
ledgers of rules opened and acted on (`get_rule` also reports to
|
ledgers of rules opened and acted on (`get_rule` also reports to
|
||||||
@@ -115,7 +117,8 @@ On install you'll be asked for:
|
|||||||
duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`.
|
duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`.
|
||||||
- `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the
|
- `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the
|
||||||
reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it
|
reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it
|
||||||
once for an unopened rule mounted on the reply moments or matching the reply.
|
once for an unopened rule set to hold (or enforce) that is mounted on the
|
||||||
|
reply moments or matches the reply. A rule set to inform never holds it.
|
||||||
When the turn closed a Grimoire task (`update_task`/`create_task` with status
|
When the turn closed a Grimoire task (`update_task`/`create_task` with status
|
||||||
done), the same request has the server check the reply for the completion
|
done), the same request has the server check the reply for the completion
|
||||||
sections — where the work sits, what needs you, what comes next. If they are
|
sections — where the work sits, what needs you, what comes next. If they are
|
||||||
@@ -127,11 +130,12 @@ On install you'll be asked for:
|
|||||||
write hooks note every definition a write names (and every new file) in a
|
write hooks note every definition a write names (and every new file) in a
|
||||||
session ledger; at the end of the turn this sends them to
|
session ledger; at the end of the turn this sends them to
|
||||||
`GET /api/plugin/shape-check`, which answers with the ones nobody has judged.
|
`GET /api/plugin/shape-check`, which answers with the ones nobody has judged.
|
||||||
If any are, it blocks once with the server's reason, asking the agent that
|
If any are, the server's note rides the next prompt (the prompt hook sends it
|
||||||
wrote them to say what each is — reusable (record a snippet), an instance or
|
as `carry`), asking the agent that wrote them to say what each is — reusable
|
||||||
variant of one, or a one-off — in one `classify_shapes` call. Same discipline
|
(record a snippet), an instance or variant of one, or a one-off — in one
|
||||||
as the report check: never twice, never without a recorded check. Outcomes
|
`classify_shapes` call. It never holds the reply; the stop after that prompt
|
||||||
land under category `plugin`, action `shape_check`.
|
records whether the lines were judged. Outcomes land under category
|
||||||
|
`plugin`, action `shape_check`.
|
||||||
- `skills/` → the universal process-skills, surfaced by description match.
|
- `skills/` → the universal process-skills, surfaced by description match.
|
||||||
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
|
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
|
||||||
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
|
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
|
||||||
|
|||||||
@@ -191,6 +191,7 @@ while IFS= read -r rel_path; do
|
|||||||
reached=1
|
reached=1
|
||||||
body=$(curl -fsS --max-time 8 \
|
body=$(curl -fsS --max-time 8 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
|
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
|
||||||
# A call that was owed and didn't come back is said, once per outage —
|
# A call that was owed and didn't come back is said, once per outage —
|
||||||
# shared marker with the pre-write hook, so one outage is one
|
# shared marker with the pre-write hook, so one outage is one
|
||||||
|
|||||||
@@ -125,6 +125,8 @@ if [ -n "$session_id" ]; then
|
|||||||
[ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}"
|
[ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}"
|
||||||
# What the session actually OPENED, as against what it was shown.
|
# What the session actually OPENED, as against what it was shown.
|
||||||
exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")"
|
exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")"
|
||||||
|
# Which session the rule lines go to, so each is recorded as a delivery.
|
||||||
|
exclude_q="${exclude_q}&session_id=${safe_sid}"
|
||||||
# Which reply shapes it already holds in full: the core is
|
# Which reply shapes it already holds in full: the core is
|
||||||
# sent whole once, and as its one-line reminder on every later turn.
|
# sent whole once, and as its one-line reminder on every later turn.
|
||||||
shapefile=$(grimoire_shapes_file "$safe_sid")
|
shapefile=$(grimoire_shapes_file "$safe_sid")
|
||||||
@@ -132,10 +134,25 @@ if [ -n "$session_id" ]; then
|
|||||||
[ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}"
|
[ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# What the last stop left for this prompt: the definitions its turn wrote
|
||||||
|
# that nobody has judged (grimoire_shape_check.sh). Carried to the server, which
|
||||||
|
# fits it into the one payload, and removed once the server has answered.
|
||||||
|
carry_q=""
|
||||||
|
carry_file=""
|
||||||
|
if [ -n "$session_id" ]; then
|
||||||
|
carry_file="${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}.note"
|
||||||
|
if [ -s "$carry_file" ]; then
|
||||||
|
carry_enc=$(head -c 2000 "$carry_file" 2>/dev/null | grimoire_urlenc) || carry_enc=""
|
||||||
|
[ -n "$carry_enc" ] && carry_q="&carry=${carry_enc}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
body=$(curl -fsS --max-time 5 \
|
body=$(curl -fsS --max-time 5 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}" 2>/dev/null) || exit 0
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
|
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0
|
||||||
[ -n "$body" ] || exit 0
|
[ -n "$body" ] || exit 0
|
||||||
|
[ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
|
||||||
|
|
||||||
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
||||||
context=$(grimoire_json_pick "$body_flat" '.context')
|
context=$(grimoire_json_pick "$body_flat" '.context')
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ task_id=$(printf '%s' "$task_id" | tr -cd '0-9')
|
|||||||
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
|
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
|
||||||
curl -fsS --max-time 4 \
|
curl -fsS --max-time 4 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \
|
"${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \
|
||||||
>/dev/null 2>&1 || true
|
>/dev/null 2>&1 || true
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
@@ -868,6 +868,14 @@ grimoire_config() {
|
|||||||
# garbage Bearer token and 401. Treat it as unset.
|
# garbage Bearer token and 401. Treat it as unset.
|
||||||
case "$url" in *'${'*) url="" ;; esac
|
case "$url" in *'${'*) url="" ;; esac
|
||||||
case "$token" in *'${'*) token="" ;; esac
|
case "$token" in *'${'*) token="" ;; esac
|
||||||
|
# Sent as `X-Grimoire-Plugin` on every request. The server keeps it on each
|
||||||
|
# rule line it delivers, and counts a line toward a rule's open rate only
|
||||||
|
# when it is there: a plugin that sends it also reports every open, so a
|
||||||
|
# line without it is one whose opens were never going to be heard. The hooks
|
||||||
|
# that source this file read it, which shellcheck cannot see from here.
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
plugin_version=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' \
|
||||||
|
"$(dirname "${BASH_SOURCE[0]}")/../.claude-plugin/plugin.json" 2>/dev/null | head -n 1)
|
||||||
[ -n "$url" ] && [ -n "$token" ]
|
[ -n "$url" ] && [ -n "$token" ]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the
|
# Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the
|
||||||
# moment happens.
|
# moment happens — beside the act, or, for a rule set to enforce or hold, in
|
||||||
|
# front of it.
|
||||||
#
|
#
|
||||||
# The other PreToolUse arms search: they turn the act into a query and hope a
|
# The other PreToolUse arms search: they turn the act into a query and hope a
|
||||||
# rule's words resemble it. A mount needs no resemblance. The operator said
|
# rule's words resemble it. A mount needs no resemblance. The operator said
|
||||||
@@ -100,6 +101,7 @@ case "$stamp" in ''|*[!0-9]*) stamp=0 ;; esac
|
|||||||
if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then
|
if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then
|
||||||
listed=$(curl -fsS --max-time 3 \
|
listed=$(curl -fsS --max-time 3 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed=""
|
"${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed=""
|
||||||
{
|
{
|
||||||
printf '%s\n' "$now"
|
printf '%s\n' "$now"
|
||||||
@@ -140,6 +142,7 @@ query="${repo_q}${ledger_q}"
|
|||||||
query=${query#&}
|
query=${query#&}
|
||||||
body=$(printf '%s' "$event" | curl -fsS --max-time 3 \
|
body=$(printf '%s' "$event" | curl -fsS --max-time 3 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
--data-binary @- \
|
--data-binary @- \
|
||||||
"${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0
|
"${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0
|
||||||
@@ -148,6 +151,34 @@ body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
|||||||
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
|
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
|
||||||
grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile"
|
grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile"
|
||||||
|
|
||||||
|
# ── The act itself: refused, held for one read, or let through ───────────
|
||||||
|
#
|
||||||
|
# The server decides and supplies the words (`decision`); this hook only
|
||||||
|
# carries them. A rule set to ENFORCE refuses the call every time it is
|
||||||
|
# reached — the operator drew that line, and it moves when they change the
|
||||||
|
# rule, not when the agent has read it. A rule set to HOLD asks for one read
|
||||||
|
# before the act, once per rule and under the session cap that the act
|
||||||
|
# checkpoint and the reply hold share, so a mis-set rule costs one round trip
|
||||||
|
# rather than a session that cannot move.
|
||||||
|
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
|
||||||
|
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
|
||||||
|
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
|
||||||
|
if [ -n "$d_reason" ]; then
|
||||||
|
case "$d_kind" in
|
||||||
|
enforce)
|
||||||
|
grimoire_json_deny PreToolUse "$d_reason"
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
hold)
|
||||||
|
if [ -n "$d_rule" ] \
|
||||||
|
&& grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$d_rule"; then
|
||||||
|
grimoire_json_deny PreToolUse "$d_reason"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
context=$(grimoire_json_pick "$body_flat" '.context')
|
context=$(grimoire_json_pick "$body_flat" '.context')
|
||||||
[ -n "$context" ] || exit 0
|
[ -n "$context" ] || exit 0
|
||||||
grimoire_json_out PreToolUse "$context"
|
grimoire_json_out PreToolUse "$context"
|
||||||
|
|||||||
@@ -240,6 +240,8 @@ if [ -n "$session_id" ]; then
|
|||||||
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
|
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
|
||||||
# What the session actually OPENED, as against what it was shown.
|
# What the session actually OPENED, as against what it was shown.
|
||||||
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
|
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
|
||||||
|
# Which session the rule lines go to, so each is recorded as a delivery.
|
||||||
|
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Not `|| exit 0`: an unreachable instance must not discard a local finding
|
# Not `|| exit 0`: an unreachable instance must not discard a local finding
|
||||||
@@ -249,6 +251,7 @@ fi
|
|||||||
reached=1
|
reached=1
|
||||||
body=$(curl -fsS --max-time 5 \
|
body=$(curl -fsS --max-time 5 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
|
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
|
||||||
unreached_context=""
|
unreached_context=""
|
||||||
if [ "$reached" = 1 ]; then
|
if [ "$reached" = 1 ]; then
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ while IFS= read -r check; do
|
|||||||
act=${check#*$'\t'}
|
act=${check#*$'\t'}
|
||||||
q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)"
|
q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)"
|
||||||
fi
|
fi
|
||||||
resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" "${base}${q}" 2>/dev/null) || {
|
resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" -H "X-Grimoire-Plugin: ${plugin_version:-}" "${base}${q}" 2>/dev/null) || {
|
||||||
fence_unreached
|
fence_unreached
|
||||||
exit 0
|
exit 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,23 +79,30 @@ printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.opened.
|
|||||||
# answers with one line putting the question to the reader. Nothing is
|
# answers with one line putting the question to the reader. Nothing is
|
||||||
# mounted by this.
|
# mounted by this.
|
||||||
#
|
#
|
||||||
# An open of a rule a hook has just NAMED is not reported. A ranked arm or a
|
# EVERY OPEN IS REPORTED: the server stamps it on this session's latest
|
||||||
# moment line put it in front of the reader, and that explains the open; the
|
# delivery of the rule, which is how an open rate per delivery is measured.
|
||||||
# moment beside it did not, so counting it would propose mounts on whatever
|
#
|
||||||
# moment happened to fire while search was surfacing the rule. The window is
|
# The acts go with it only when the rule was NOT just named by a hook. A
|
||||||
# short for the same reason: a few minutes of agent work reaches many moments.
|
# ranked arm or a moment line put a named rule in front of the reader, and
|
||||||
|
# that explains the open; the moment beside it did not, so counting it would
|
||||||
|
# propose mounts on whatever moment happened to fire while search was
|
||||||
|
# surfacing the rule. The window is short for the same reason: a few minutes
|
||||||
|
# of agent work reaches many moments.
|
||||||
command -v curl >/dev/null 2>&1 || exit 0
|
command -v curl >/dev/null 2>&1 || exit 0
|
||||||
grimoire_config || exit 0
|
grimoire_config || exit 0
|
||||||
|
acts=""
|
||||||
case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in
|
case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in
|
||||||
*",${rule_id},"*) exit 0 ;;
|
*",${rule_id},"*) ;;
|
||||||
esac
|
*)
|
||||||
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
|
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
|
||||||
[ -f "$acts_file" ] || exit 0
|
now=$(date +%s 2>/dev/null) || now=0
|
||||||
now=$(date +%s 2>/dev/null) || exit 0
|
if [ -f "$acts_file" ] && [ "$now" -gt 0 ]; then
|
||||||
acts=$(awk -F '\t' -v since=$((now - 90)) \
|
acts=$(awk -F '\t' -v since=$((now - 90)) \
|
||||||
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
|
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
|
||||||
| tail -n 3 | paste -sd ',' - 2>/dev/null)
|
| tail -n 3 | paste -sd ',' - 2>/dev/null)
|
||||||
[ -n "$acts" ] || exit 0
|
fi
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
|
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
|
||||||
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
||||||
@@ -103,6 +110,7 @@ scope=$(grimoire_scope_query "${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}")
|
|||||||
body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \
|
body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \
|
||||||
| curl -fsS --max-time 3 \
|
| curl -fsS --max-time 3 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
--data-binary @- \
|
--data-binary @- \
|
||||||
"${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0
|
"${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0
|
||||||
|
|||||||
@@ -24,6 +24,16 @@
|
|||||||
# honest. It records that an outcome was declared. The value of that is not the
|
# honest. It records that an outcome was declared. The value of that is not the
|
||||||
# claim itself — it is that the absence of one becomes visible.
|
# claim itself — it is that the absence of one becomes visible.
|
||||||
#
|
#
|
||||||
|
# `rule_misfired` closes the same gap from the other side: the rule arrived
|
||||||
|
# at a moment and did not bear on the work there. It is an answer too, so it
|
||||||
|
# goes in the same ledger.
|
||||||
|
#
|
||||||
|
# BOTH ALSO GO TO THE SERVER, with the session id the MCP call cannot carry,
|
||||||
|
# as an adherence verdict on this session's delivery of the rule: applied is
|
||||||
|
# followed, departed is departed, a misfire is not applicable at the moment it
|
||||||
|
# names (`/api/plugin/rule-verdict`). That is what lets the adherence readout
|
||||||
|
# put "followed" beside "delivered" and "opened" per rule and per moment.
|
||||||
|
#
|
||||||
# EXIT 0, ALWAYS. This decorates a ledger; a bookkeeping failure must never
|
# EXIT 0, ALWAYS. This decorates a ledger; a bookkeeping failure must never
|
||||||
# turn a successful tool call into a hook error.
|
# turn a successful tool call into a hook error.
|
||||||
set -uo pipefail
|
set -uo pipefail
|
||||||
@@ -38,7 +48,7 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
|||||||
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||||
[ -n "$session_id" ] || exit 0
|
[ -n "$session_id" ] || exit 0
|
||||||
|
|
||||||
# The matcher in hooks.json narrows to the rule_outcome tools, but the server
|
# The matcher in hooks.json narrows to the rule_outcome and rule_misfired tools, but the server
|
||||||
# segment of an MCP tool name varies with how the plugin was installed, so the
|
# segment of an MCP tool name varies with how the plugin was installed, so the
|
||||||
# id is read from the field rather than from an assumed tool name — the same
|
# id is read from the field rather than from an assumed tool name — the same
|
||||||
# reasoning grimoire_record_opened.sh gives.
|
# reasoning grimoire_record_opened.sh gives.
|
||||||
@@ -52,4 +62,28 @@ safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
|||||||
|
|
||||||
# Stamped and append-only like its two siblings, so one reader ages them all.
|
# Stamped and append-only like its two siblings, so one reader ages them all.
|
||||||
printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.acted.ids"
|
printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.acted.ids"
|
||||||
|
|
||||||
|
# ── The verdict, to the server ───────────────────────────────────────────
|
||||||
|
command -v curl >/dev/null 2>&1 || exit 0
|
||||||
|
grimoire_config || exit 0
|
||||||
|
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
|
||||||
|
why=$(grimoire_json_pick "$event_flat" '.tool_input.why')
|
||||||
|
outcome=""
|
||||||
|
moment=""
|
||||||
|
case "$tool_name" in
|
||||||
|
*rule_misfired) moment=$(grimoire_json_pick "$event_flat" '.tool_input.moment') ;;
|
||||||
|
*) outcome=$(grimoire_json_pick "$event_flat" '.tool_input.outcome') ;;
|
||||||
|
esac
|
||||||
|
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
|
||||||
|
outcome_esc=$(printf '%s' "$outcome" | grimoire_json_escape) || exit 0
|
||||||
|
moment_esc=$(printf '%s' "$moment" | grimoire_json_escape) || exit 0
|
||||||
|
why_esc=$(printf '%s' "$why" | grimoire_json_escape) || exit 0
|
||||||
|
printf '{"rule_id":%s,"session_id":"%s","outcome":"%s","moment":"%s","why":"%s"}' \
|
||||||
|
"$rule_id" "$sid_esc" "$outcome_esc" "$moment_esc" "$why_esc" \
|
||||||
|
| curl -fsS --max-time 3 \
|
||||||
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
--data-binary @- \
|
||||||
|
"${url%/}/api/plugin/rule-verdict" >/dev/null 2>&1 || true
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
Executable
+74
@@ -0,0 +1,74 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Grimoire — tell the server this session opened a record, or ran a search.
|
||||||
|
#
|
||||||
|
# WHAT THIS ANSWERS
|
||||||
|
#
|
||||||
|
# A hook puts records in front of a session (prior art, the notes menu); the
|
||||||
|
# session also searches for records itself, and opens others it reached on
|
||||||
|
# its own (an id in a task log, a record the operator named). The server
|
||||||
|
# records what each hook pushed against the session. This reports the other
|
||||||
|
# half, from the tool calls themselves:
|
||||||
|
#
|
||||||
|
# - `get_note`, `get_task`, `get_snippet`, `get_lesson`, `get_process` — the
|
||||||
|
# record was opened. The server stamps the delivery it followed, or records
|
||||||
|
# a direct open when nothing delivered it first.
|
||||||
|
# - `search` — the session asked. The server reads what that call returned
|
||||||
|
# from its own log and records those results against the session, so an
|
||||||
|
# open that follows counts as one reached by asking.
|
||||||
|
#
|
||||||
|
# Together they say, per kind of record, how much a session is shown, how
|
||||||
|
# much it asks for, how much it reaches on its own, and what it opens.
|
||||||
|
#
|
||||||
|
# A tool call happened or it did not, and the harness reports it either way:
|
||||||
|
# this asks the session nothing.
|
||||||
|
#
|
||||||
|
# EXIT 0, ALWAYS, silent on outage. This is bookkeeping; a failure here must
|
||||||
|
# never turn a successful tool call into a hook error.
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
# shellcheck source=plugin/hooks/grimoire_defs.sh
|
||||||
|
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
|
||||||
|
|
||||||
|
event=$(cat 2>/dev/null || true)
|
||||||
|
[ -n "$event" ] || exit 0
|
||||||
|
|
||||||
|
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
||||||
|
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||||
|
[ -n "$session_id" ] || exit 0
|
||||||
|
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
|
||||||
|
|
||||||
|
command -v curl >/dev/null 2>&1 || exit 0
|
||||||
|
grimoire_config || exit 0
|
||||||
|
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
|
||||||
|
|
||||||
|
post() {
|
||||||
|
printf '%s' "$2" | curl -fsS --max-time 3 \
|
||||||
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
--data-binary @- \
|
||||||
|
"${url%/}/api/plugin/$1" >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
|
||||||
|
case "$tool_name" in
|
||||||
|
*__search)
|
||||||
|
q=$(grimoire_json_pick "$event_flat" '.tool_input.q')
|
||||||
|
[ -n "$q" ] || exit 0
|
||||||
|
q_esc=$(printf '%s' "$q" | grimoire_json_escape) || exit 0
|
||||||
|
post record-searched "$(printf '{"session_id":"%s","q":"%s"}' "$sid_esc" "$q_esc")"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
# Each getter names its id differently; read whichever is present. A
|
||||||
|
# process opened by name rather than id is left unrecorded.
|
||||||
|
note_id=""
|
||||||
|
for field in note_id task_id snippet_id lesson_id name_or_id; do
|
||||||
|
note_id=$(grimoire_json_pick "$event_flat" ".tool_input.${field}")
|
||||||
|
[ -n "$note_id" ] && break
|
||||||
|
done
|
||||||
|
case "$note_id" in
|
||||||
|
''|*[!0-9]*) exit 0 ;;
|
||||||
|
esac
|
||||||
|
post record-opened "$(printf '{"session_id":"%s","note_id":%s}' "$sid_esc" "$note_id")"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
exit 0
|
||||||
@@ -6,7 +6,9 @@
|
|||||||
# tool call misses it. This hook sends the finished reply to the server, which
|
# tool call misses it. This hook sends the finished reply to the server, which
|
||||||
# checks it twice over: the rules MOUNTED on the reply moments, and the reply
|
# checks it twice over: the rules MOUNTED on the reply moments, and the reply
|
||||||
# text against every rule's trigger, as the backstop for whatever the earlier
|
# text against every rule's trigger, as the backstop for whatever the earlier
|
||||||
# arms missed. An unopened rule from either half holds the reply for one read.
|
# arms missed. An unopened rule set to hold, from either half, holds the reply
|
||||||
|
# for one read; a rule set to inform was delivered before the reply and never
|
||||||
|
# holds it.
|
||||||
#
|
#
|
||||||
# ONE END-OF-TURN REQUEST. When the turn closed a task, the same request
|
# ONE END-OF-TURN REQUEST. When the turn closed a task, the same request
|
||||||
# carries the task ids and the server also checks the reply for the completion
|
# carries the task ids and the server also checks the reply for the completion
|
||||||
@@ -105,6 +107,7 @@ query=${query#&}
|
|||||||
|
|
||||||
answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \
|
answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
--data-binary @- \
|
--data-binary @- \
|
||||||
"${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0
|
"${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0
|
||||||
|
|||||||
@@ -192,6 +192,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then
|
|||||||
local resp meta
|
local resp meta
|
||||||
resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \
|
resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/context${q}" 2>/dev/null)
|
"${url%/}/api/plugin/context${q}" 2>/dev/null)
|
||||||
ctx_rc=$?
|
ctx_rc=$?
|
||||||
meta=${resp##*$'\n'}
|
meta=${resp##*$'\n'}
|
||||||
|
|||||||
@@ -31,13 +31,14 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
|||||||
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||||
[ -n "$session_id" ] || exit 0
|
[ -n "$session_id" ] || exit 0
|
||||||
|
|
||||||
# The moment arm's per-session files (its tool cache and the acts ledger) and
|
# The moment arm's per-session files (its tool cache and the acts ledger), the
|
||||||
# the fence's (the project the session entered, its outage marker) describe a
|
# shape check's (a note waiting for a prompt) and the fence's (the project the
|
||||||
# session that is over, on any exit — a clear included, since the next
|
# session entered, its outage marker) describe a session that is over, on any
|
||||||
# conversation is a new session id.
|
# exit — a clear included, since the next conversation is a new session id.
|
||||||
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
||||||
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
|
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
|
||||||
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* 2>/dev/null || true
|
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* \
|
||||||
|
"${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true
|
||||||
|
|
||||||
reason=$(grimoire_json_pick "$event_flat" '.reason')
|
reason=$(grimoire_json_pick "$event_flat" '.reason')
|
||||||
[ "$reason" = "clear" ] && exit 0
|
[ "$reason" = "clear" ] && exit 0
|
||||||
@@ -48,6 +49,7 @@ grimoire_config || exit 0
|
|||||||
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
|
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
|
||||||
curl -fsS --max-time 4 \
|
curl -fsS --max-time 4 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/release-session?session_id=${sid_enc}" \
|
"${url%/}/api/plugin/release-session?session_id=${sid_enc}" \
|
||||||
>/dev/null 2>&1 || true
|
>/dev/null 2>&1 || true
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
@@ -1,29 +1,31 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent
|
# Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent
|
||||||
# that wrote them.
|
# that wrote them, at the start of its next turn.
|
||||||
#
|
#
|
||||||
# The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every
|
# The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every
|
||||||
# definition a write names to a session ledger, `<sid>.written.ids`
|
# definition a write names to a session ledger, `<sid>.written.ids`
|
||||||
# (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the
|
# (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the
|
||||||
# turn this hook sends that ledger to the instance, which answers with what
|
# turn this hook sends that ledger to the instance, which answers with what
|
||||||
# nobody has judged yet. If anything is, the hook blocks ONCE, in the server's
|
# nobody has judged yet as a `note`. The hook leaves the note for
|
||||||
# words: the agent that built the code is the one participant who knows what
|
# grimoire_autoinject.sh, which carries it into the next prompt's payload: the
|
||||||
# it is, and the end of the turn is the last moment that is still true.
|
# agent that built the code is the one participant who knows what it is, and
|
||||||
|
# the next turn of the same session still does.
|
||||||
#
|
#
|
||||||
# THE SAME DISCIPLINE AS the completion-section check in grimoire_reply_check.sh:
|
# IT NEVER HOLDS THE REPLY. A held reply is rewritten, and a hold on every turn
|
||||||
# - it blocks only on a `reason` the instance returned, which it returns
|
# that wrote code made most replies cost two. The question waits one prompt
|
||||||
# only for a block it RECORDED — an unconfigured or unreachable instance
|
# instead, and is asked inside that prompt's budget.
|
||||||
# never stops a session, and every intervention is one the numbers see;
|
|
||||||
# - never twice for one turn: the stop that follows its own block
|
|
||||||
# (`stop_hook_active` with this hook's marker present) is recorded as
|
|
||||||
# judged_after_block / left_after_block and let through;
|
|
||||||
# - another plugin's block loop is left alone (active, no marker).
|
|
||||||
#
|
#
|
||||||
# THE LEDGER IS CONSUMED, NOT TURN-STAMPED. Everything written since the last
|
# THE STATE, in <TMPDIR>/grimoire-shapecheck:
|
||||||
# stop this hook answered is "this turn". It is emptied once the instance has
|
# <sid>.note — the note, until a prompt carries it (the prompt hook
|
||||||
# answered — after a pass, or after the post-block stop — and KEPT when the
|
# removes it once the instance has answered);
|
||||||
# instance could not be reached, so the question is asked at the next stop
|
# <sid>.asked — the lines that note named. At the first stop after the note
|
||||||
# that can be answered rather than silently dropped.
|
# was carried, they go back as `phase=after`, which records
|
||||||
|
# whether they were judged, and are then forgotten.
|
||||||
|
# A note no prompt has carried yet (two stops in a row) is asked again with
|
||||||
|
# that turn's writes added, so nothing is dropped and nothing is asked twice.
|
||||||
|
#
|
||||||
|
# Silent on outage: the ledger is kept when the instance could not be reached,
|
||||||
|
# so the question is asked at the next stop that can be answered.
|
||||||
#
|
#
|
||||||
# Config (same as the other hooks):
|
# Config (same as the other hooks):
|
||||||
# CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash
|
# CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash
|
||||||
@@ -43,36 +45,33 @@ session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
|||||||
active=$(grimoire_json_pick "$event_flat" '.stop_hook_active')
|
active=$(grimoire_json_pick "$event_flat" '.stop_hook_active')
|
||||||
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
||||||
[ -n "$session_id" ] || exit 0
|
[ -n "$session_id" ] || exit 0
|
||||||
|
# The stop after another hook held the reply: this turn's writes were already
|
||||||
|
# sent at the stop before it.
|
||||||
|
[ "$active" = "true" ] && exit 0
|
||||||
|
|
||||||
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
|
||||||
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
|
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
|
||||||
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
|
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
|
||||||
mkdir -p "$state_dir" 2>/dev/null || true
|
mkdir -p "$state_dir" 2>/dev/null || true
|
||||||
marker="$state_dir/${safe_sid}.blocked"
|
note_file="$state_dir/${safe_sid}.note"
|
||||||
|
asked_file="$state_dir/${safe_sid}.asked"
|
||||||
|
|
||||||
if [ "$active" = "true" ]; then
|
# A note no prompt has carried: its lines join this turn's, asked afresh.
|
||||||
# A Stop hook already blocked this stop. Another plugin's → nothing to add.
|
if [ -f "$note_file" ]; then
|
||||||
[ -f "$marker" ] || exit 0
|
if [ -s "$asked_file" ]; then
|
||||||
phase=after
|
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
|
||||||
else
|
cat "$asked_file" >> "$ledger" 2>/dev/null || true
|
||||||
rm -f "$marker" 2>/dev/null || true
|
fi
|
||||||
phase=check
|
rm -f "$note_file" "$asked_file" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ ! -s "$ledger" ]; then
|
[ -s "$asked_file" ] || [ -s "$ledger" ] || exit 0
|
||||||
rm -f "$marker" 2>/dev/null || true
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
grimoire_config || exit 0
|
grimoire_config || exit 0
|
||||||
|
|
||||||
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
|
|
||||||
# key runs the plugin), and a turn that wrote more than this generated code.
|
|
||||||
written=$(awk '!seen[$0]++' "$ledger" 2>/dev/null | head -n 80)
|
|
||||||
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
|
|
||||||
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
|
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
|
||||||
q="phase=${phase}&written=${written_enc}"
|
scope_q=""
|
||||||
scope=$(grimoire_scope_query "$dir")
|
scope=$(grimoire_scope_query "$dir")
|
||||||
[ -n "$scope" ] && q="${q}&${scope}"
|
[ -n "$scope" ] && scope_q="&${scope}"
|
||||||
# The repo rides along even when a marker names the project: the instance
|
# The repo rides along even when a marker names the project: the instance
|
||||||
# needs it to tell the agent which repo a just-written shape belongs to.
|
# needs it to tell the agent which repo a just-written shape belongs to.
|
||||||
case "$scope" in
|
case "$scope" in
|
||||||
@@ -81,25 +80,41 @@ case "$scope" in
|
|||||||
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
|
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
|
||||||
if [ -n "$remote" ]; then
|
if [ -n "$remote" ]; then
|
||||||
remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc=""
|
remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc=""
|
||||||
[ -n "$remote_enc" ] && q="${q}&repo=${remote_enc}"
|
[ -n "$remote_enc" ] && scope_q="${scope_q}&repo=${remote_enc}"
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
|
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
|
||||||
|
# key runs the plugin), and a turn that wrote more than this generated code.
|
||||||
|
_unique() { awk '!seen[$0]++' "$1" 2>/dev/null | head -n 80; }
|
||||||
|
|
||||||
|
# The note a prompt carried: were its lines judged since?
|
||||||
|
if [ -s "$asked_file" ]; then
|
||||||
|
asked=$(_unique "$asked_file")
|
||||||
|
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc=""
|
||||||
|
if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \
|
||||||
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
|
"${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \
|
||||||
|
>/dev/null 2>&1; then
|
||||||
|
rm -f "$asked_file" 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
[ -s "$ledger" ] || exit 0
|
||||||
|
written=$(_unique "$ledger")
|
||||||
|
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
|
||||||
answer=$(curl -fsS --max-time 4 \
|
answer=$(curl -fsS --max-time 4 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
"${url%/}/api/plugin/shape-check?${q}" 2>/dev/null) || exit 0 # unreachable: keep the ledger
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
|
"${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \
|
||||||
|
|| exit 0 # unreachable: keep the ledger
|
||||||
|
|
||||||
if [ "$phase" = "after" ]; then
|
note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
|
||||||
rm -f "$marker" "$ledger" 2>/dev/null || true
|
if [ -n "$note" ]; then
|
||||||
exit 0
|
printf '%s' "$note" > "$note_file" 2>/dev/null || true
|
||||||
|
printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true
|
||||||
fi
|
fi
|
||||||
|
rm -f "$ledger" 2>/dev/null || true
|
||||||
reason=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.reason')
|
|
||||||
if [ -z "$reason" ]; then
|
|
||||||
rm -f "$ledger" 2>/dev/null || true
|
|
||||||
exit 0
|
|
||||||
fi
|
|
||||||
: > "$marker" 2>/dev/null || true
|
|
||||||
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
|
|
||||||
exit 0
|
exit 0
|
||||||
|
|||||||
@@ -19,7 +19,13 @@ What only Claude Code needs said:
|
|||||||
notes and prior art that resemble what you are doing — and, when a tool call
|
notes and prior art that resemble what you are doing — and, when a tool call
|
||||||
or the reply ending a turn reaches a moment of work, the rules mounted on
|
or the reply ending a turn reaches a moment of work, the rules mounted on
|
||||||
it. Open the ones that apply; using-grimoire says what a quiet turn means and
|
it. Open the ones that apply; using-grimoire says what a quiet turn means and
|
||||||
how to correct a moment that fired wrongly.
|
how to correct a moment that fired wrongly. A line beginning "Also
|
||||||
|
resembling this, not shown" names records by id only, because they matched
|
||||||
|
less clearly than the lines above it: open one when it may bear on the work.
|
||||||
|
- **A rule can hold or refuse a tool call.** A held call names its rule and
|
||||||
|
goes ahead once the rule has been read: read it, then make the call again.
|
||||||
|
A refused call is a boundary the operator drew; it moves when they change
|
||||||
|
the rule, so tell them what the rule said.
|
||||||
- **Compact at clean seams.** Because work is recorded as you go, a compaction
|
- **Compact at clean seams.** Because work is recorded as you go, a compaction
|
||||||
is safe once in-flight state is logged. After finishing a block of work in a
|
is safe once in-flight state is logged. After finishing a block of work in a
|
||||||
long session, log it to Grimoire, then tell the operator it's a good moment to
|
long session, log it to Grimoire, then tell the operator it's a good moment to
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ grimoire_config || exit 0
|
|||||||
|
|
||||||
body=$(curl -fsS --max-time 8 \
|
body=$(curl -fsS --max-time 8 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/processes" 2>/dev/null) || exit 0
|
"${url%/}/api/plugin/processes" 2>/dev/null) || exit 0
|
||||||
[ -n "$body" ] || exit 0
|
[ -n "$body" ] || exit 0
|
||||||
|
|
||||||
|
|||||||
@@ -101,6 +101,8 @@ if [ -n "$session_id" ]; then
|
|||||||
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
|
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
|
||||||
# What the session actually OPENED, as against what it was shown.
|
# What the session actually OPENED, as against what it was shown.
|
||||||
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
|
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
|
||||||
|
# Which session the rule lines go to, so each is recorded as a delivery.
|
||||||
|
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
|
||||||
# The Systems whose rulings were shown in full — shared with the write-path
|
# The Systems whose rulings were shown in full — shared with the write-path
|
||||||
# hook, for the reason the rule file is.
|
# hook, for the reason the rule file is.
|
||||||
rulingsfile="$state_dir/${safe_sid}.rulings.ids"
|
rulingsfile="$state_dir/${safe_sid}.rulings.ids"
|
||||||
@@ -112,6 +114,7 @@ fi
|
|||||||
# than silence. See the header.
|
# than silence. See the header.
|
||||||
body=$(curl -fsS --max-time 5 \
|
body=$(curl -fsS --max-time 5 \
|
||||||
-H "Authorization: Bearer ${token}" \
|
-H "Authorization: Bearer ${token}" \
|
||||||
|
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||||
"${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0
|
"${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0
|
||||||
|
|
||||||
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
||||||
|
|||||||
+10
-1
@@ -82,7 +82,16 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"matcher": "mcp__.*__rule_outcome",
|
"matcher": "mcp__.*__(get_note|get_task|get_snippet|get_lesson|get_process|search)",
|
||||||
|
"hooks": [
|
||||||
|
{
|
||||||
|
"type": "command",
|
||||||
|
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_record_read.sh\""
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"matcher": "mcp__.*__(rule_outcome|rule_misfired)",
|
||||||
"hooks": [
|
"hooks": [
|
||||||
{
|
{
|
||||||
"type": "command",
|
"type": "command",
|
||||||
|
|||||||
@@ -100,10 +100,10 @@ Two constraints on *how* that's achieved:
|
|||||||
**lesson** is what is worth knowing — a better way to think about a
|
**lesson** is what is worth knowing — a better way to think about a
|
||||||
problem, a solution that transfers — and ignoring it costs time. All three
|
problem, a solution that transfers — and ignoring it costs time. All three
|
||||||
are worth reading and all three arrive beside your work; only the first is
|
are worth reading and all three arrive beside your work; only the first is
|
||||||
a mistake to miss. An injected line names which in its opening words —
|
a mistake to miss. A line names which up front (*"Rule 11 …; it binds:"*,
|
||||||
*"Standing rule that may apply…"* against *"Preference that may apply…"* —
|
*"Preference 173 …; how this has been done before:"*) and on first mention
|
||||||
a lesson arrives in the records menu marked `lesson`, under a header that
|
quotes the statement; `get_rule(id)` gives the why and how. A lesson is
|
||||||
says outright that it binds nothing, and every payload carries `kind`.
|
marked `lesson` under a header saying it binds nothing; payloads carry `kind`.
|
||||||
|
|
||||||
**One question sorts them, and it is worth asking out loud: what happens if
|
**One question sorts them, and it is worth asking out loud: what happens if
|
||||||
someone doesn't do this?** *Something breaks, or a boundary is crossed* — a
|
someone doesn't do this?** *Something breaks, or a boundary is crossed* — a
|
||||||
|
|||||||
@@ -5,6 +5,13 @@ moment, when a reply is held for one read, when an action reached the wrong
|
|||||||
moment or none, when a mounted rule arrived and did not apply, and when a line
|
moment or none, when a mounted rule arrived and did not apply, and when a line
|
||||||
proposes mounting or unmounting a rule.
|
proposes mounting or unmounting a rule.
|
||||||
|
|
||||||
|
## Contents
|
||||||
|
- What a moment is
|
||||||
|
- Reading a line that arrived at a moment — and a held or refused call
|
||||||
|
- When the moment is wrong — correct it in the session
|
||||||
|
- When a mounted rule arrives and does not apply
|
||||||
|
- When a line proposes a mount — and how rules are weighed and measured
|
||||||
|
|
||||||
## What a moment is
|
## What a moment is
|
||||||
|
|
||||||
Most rules reach you by resemblance: what you are doing looks like what the
|
Most rules reach you by resemblance: what you are doing looks like what the
|
||||||
@@ -34,6 +41,22 @@ The reply that ends a turn is a moment too. When a rule mounted at
|
|||||||
with its name: open it, then send the reply — unchanged, if it already does
|
with its name: open it, then send the reply — unchanged, if it already does
|
||||||
what the rule asks. The same rule is never held twice.
|
what the rule asks. The same rule is never held twice.
|
||||||
|
|
||||||
|
A call can be held the same way. A rule declared `hold` that the call reaches
|
||||||
|
stops it once, naming the rule: read it, then make the call again — unchanged
|
||||||
|
if the rule does not bear on it, and then `rule_misfired` says so. A rule
|
||||||
|
declared `enforce` refuses the call every time, in its own words: that is a
|
||||||
|
boundary the operator drew, and it moves only when they change the rule, so
|
||||||
|
tell them what you were doing and what the rule said. A rule with triggers of
|
||||||
|
its own holds or refuses only the acts those triggers match; at the rest of
|
||||||
|
its moments it arrives as a line.
|
||||||
|
|
||||||
|
A moment sends a few lines, not every rule mounted there: ordered by
|
||||||
|
enforcement, then salience, then how exactly the act reached the rule, then
|
||||||
|
how often it has been opened there. What did not fit was left out, and a
|
||||||
|
rule already shown this session comes back as a short reminder, then not at
|
||||||
|
all. So a quiet moment means nothing more needed saying there, not that no
|
||||||
|
rule applies — `what_might_apply` asks for the whole list.
|
||||||
|
|
||||||
## When the moment is wrong — correct it in the session
|
## When the moment is wrong — correct it in the session
|
||||||
|
|
||||||
A moment can fire on an action that is not that moment here, or an action can
|
A moment can fire on an action that is not that moment here, or an action can
|
||||||
@@ -89,3 +112,19 @@ The same tool answers proposals from a pass over the rules
|
|||||||
proposes, and only the operator's yes mounts. Writing a NEW rule is different
|
proposes, and only the operator's yes mounts. Writing a NEW rule is different
|
||||||
— its moments are part of writing it, and the
|
— its moments are part of writing it, and the
|
||||||
skill's guide to writing records says how.
|
skill's guide to writing records says how.
|
||||||
|
|
||||||
|
A second pass weighs each rule: how strongly it arrives once reached
|
||||||
|
(`enforcement`: inform, hold or enforce; `salience`), and which typed
|
||||||
|
triggers reach it exactly (`rules_to_weigh`, `propose_rule_weights`,
|
||||||
|
`rule_weight_proposals`, `judge_rule_weights`). It reads each rule beside its
|
||||||
|
delivery history and proposes; the operator confirms each change, in the
|
||||||
|
session or under Settings › Moments.
|
||||||
|
|
||||||
|
Whether a rule was followed where it arrived is measured per rule and per
|
||||||
|
moment (`rule_adherence`, and under Settings › Moments). Your own
|
||||||
|
`rule_outcome` and `rule_misfired` calls are the session's half of that
|
||||||
|
record: each lands as a verdict on the delivery you were answering. A
|
||||||
|
transcript review fills in the rest when the operator asks for one:
|
||||||
|
`adherence_to_judge` lists the rules in force at a moment of a session with
|
||||||
|
no verdict yet, and `judge_adherence` records followed, broken, departed or
|
||||||
|
not applicable, with what the transcript shows.
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ decides how some area of the work must behave; and before filling
|
|||||||
## Contents
|
## Contents
|
||||||
- Where a new rule goes — its home, its trigger, what already covers the moment
|
- Where a new rule goes — its home, its trigger, what already covers the moment
|
||||||
- When it applies — the moments a rule, a preference or a process is for
|
- When it applies — the moments a rule, a preference or a process is for
|
||||||
|
- How strongly it arrives — enforcement, salience, and the act it governs
|
||||||
- A ruling goes on the System it governs
|
- A ruling goes on the System it governs
|
||||||
- A lesson grows each time it proves itself
|
- A lesson grows each time it proves itself
|
||||||
- A lesson names the rule it is an instance of
|
- A lesson names the rule it is an instance of
|
||||||
@@ -33,7 +34,10 @@ departs from a global rule writes its own and links it with
|
|||||||
`relate_rules(kind="overrides")`, which says why. A rule that turns out to be
|
`relate_rules(kind="overrides")`, which says why. A rule that turns out to be
|
||||||
in the wrong home — a project rule that holds everywhere, a global one only a
|
in the wrong home — a project rule that holds everywhere, a global one only a
|
||||||
single project needs — moves with `move_rule`, which keeps its id, history,
|
single project needs — moves with `move_rule`, which keeps its id, history,
|
||||||
areas and edges. Propose the move and make it on a yes.
|
areas and edges. Propose the move and make it on a yes. Editing a rule that
|
||||||
|
lives on another project is curation, not that project's work: the plugin
|
||||||
|
names the rule and asks, and the edit goes ahead on the operator's yes rather
|
||||||
|
than becoming an issue there.
|
||||||
|
|
||||||
**Whichever home it gets, a rule needs `when_to_apply`.** It is the only thing
|
**Whichever home it gets, a rule needs `when_to_apply`.** It is the only thing
|
||||||
that decides whether the rule is ever seen: nothing is preloaded, so a rule
|
that decides whether the rule is ever seen: nothing is preloaded, so a rule
|
||||||
@@ -57,6 +61,35 @@ names the moments the procedure is for, so loading it reaches them and the
|
|||||||
rules mounted there arrive with it. A rule that only applies inside one
|
rules mounted there arrive with it. A rule that only applies inside one
|
||||||
procedure mounts on that procedure's own moment, `skill.<name>`.
|
procedure mounts on that procedure's own moment, `skill.<name>`.
|
||||||
|
|
||||||
|
## How strongly it arrives
|
||||||
|
|
||||||
|
A rule that reaches the work says one of three things, and you declare which
|
||||||
|
(`enforcement` on `create_rule`, `create_project_rule`, `update_rule`):
|
||||||
|
|
||||||
|
- **`inform`** — a line beside the work. The default, and right for most
|
||||||
|
rules: the session reads it and applies it.
|
||||||
|
- **`hold`** — the act or reply it governs waits until the session has read
|
||||||
|
the rule once; then it goes ahead. For a rule whose miss costs a rewrite: a
|
||||||
|
merge style, a release step, a check before a reply.
|
||||||
|
- **`enforce`** — the act is refused, in the rule's own words, every time,
|
||||||
|
and only a change to the rule moves it. For a boundary the operator draws
|
||||||
|
with no exceptions a session may judge. Most hard rules have an exit ("unless
|
||||||
|
the operator asks"), and a rule with an exit is a hold.
|
||||||
|
|
||||||
|
A hold or a refusal stops an act, so give it the act: a `triggers` entry
|
||||||
|
naming the command head (`git push origin main`), the tool (`create_release`)
|
||||||
|
or the path (`alembic/versions/*.py`) it governs. A rule with triggers stops
|
||||||
|
only the acts they match; at the rest of its moments it is a line. Without
|
||||||
|
one, it stops every act its moment reaches — a rule about pushing to `main`
|
||||||
|
mounted on `work.deliver` would hold every push to `dev`.
|
||||||
|
|
||||||
|
**`salience`** (`high`, `normal`, `low`) orders it against rules of the same
|
||||||
|
enforcement when a moment has more to say than fits. A moment sends a few
|
||||||
|
lines, highest first, and drops the rest — so `high` is for the rule that must
|
||||||
|
win a crowded moment, and `low` for one worth seeing but rarely decisive.
|
||||||
|
|
||||||
|
A preference never holds or refuses: it arrives as a line, with a salience.
|
||||||
|
|
||||||
**Before writing one, ask what already covers that moment.**
|
**Before writing one, ask what already covers that moment.**
|
||||||
`what_might_apply("the moment you are about to write a record for")` — fifty
|
`what_might_apply("the moment you are about to write a record for")` — fifty
|
||||||
candidates and no bar, so an existing record cannot hide under a threshold the
|
candidates and no bar, so an existing record cannot hide under a threshold the
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ asyncio_mode = "auto"
|
|||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
markers = [
|
markers = [
|
||||||
"integration: requires a real Postgres database (runs only in the CI integration lane)",
|
"integration: requires a real Postgres database (runs only in the CI integration lane)",
|
||||||
|
"cue_gate: runs with the plugin doors' cue-swap gate on rather than stubbed off",
|
||||||
]
|
]
|
||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
|
|||||||
@@ -781,6 +781,33 @@ def check_version_is_minted(base: str = "origin/main") -> None:
|
|||||||
ok(f"nothing version-relevant changed against {base} — no mint required")
|
ok(f"nothing version-relevant changed against {base} — no mint required")
|
||||||
|
|
||||||
|
|
||||||
|
# The lower of the two caps recorded for a hook's additional context: the docs
|
||||||
|
# give 10,000 characters, and an installed build has been read capping it at
|
||||||
|
# 8,000. Past the cap the model gets only a short preview.
|
||||||
|
HOOK_CONTEXT_CAP = 8_000
|
||||||
|
PAYLOAD_MODULE = ROOT / "src" / "grimoire" / "services" / "hook_payload.py"
|
||||||
|
|
||||||
|
|
||||||
|
def check_payload_bound() -> None:
|
||||||
|
"""The server fits every hook payload under `hook_payload.HARD_MAX`, and
|
||||||
|
that ceiling must sit under Claude Code's cap whatever a user sets."""
|
||||||
|
try:
|
||||||
|
text = PAYLOAD_MODULE.read_text()
|
||||||
|
except OSError:
|
||||||
|
fail(f"no payload assembler at {PAYLOAD_MODULE.relative_to(ROOT)}")
|
||||||
|
return
|
||||||
|
found = re.search(r"^HARD_MAX\s*=\s*([0-9_]+)\s*$", text, re.M)
|
||||||
|
if not found:
|
||||||
|
fail("hook_payload.HARD_MAX is not a literal this check can read")
|
||||||
|
return
|
||||||
|
hard_max = int(found.group(1).replace("_", ""))
|
||||||
|
if hard_max >= HOOK_CONTEXT_CAP:
|
||||||
|
fail(f"hook_payload.HARD_MAX is {hard_max}, at or past Claude Code's "
|
||||||
|
f"{HOOK_CONTEXT_CAP}-character hook context cap")
|
||||||
|
else:
|
||||||
|
ok(f"hook payloads are bounded at {hard_max} characters, under {HOOK_CONTEXT_CAP}")
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument("--no-version", action="store_true",
|
parser.add_argument("--no-version", action="store_true",
|
||||||
@@ -800,6 +827,7 @@ def main() -> int:
|
|||||||
check_fail_open()
|
check_fail_open()
|
||||||
check_local_prior_art_needs_no_instance()
|
check_local_prior_art_needs_no_instance()
|
||||||
check_session_context_reports_its_version()
|
check_session_context_reports_its_version()
|
||||||
|
check_payload_bound()
|
||||||
if not args.no_version:
|
if not args.no_version:
|
||||||
check_version_is_minted(args.base)
|
check_version_is_minted(args.base)
|
||||||
|
|
||||||
|
|||||||
+14
-3
@@ -85,9 +85,9 @@ def create_app() -> Quart:
|
|||||||
|
|
||||||
if os.environ.get("TRUST_PROXY_HEADERS") and not os.environ.get("TRUSTED_PROXY_HOPS"):
|
if os.environ.get("TRUST_PROXY_HEADERS") and not os.environ.get("TRUSTED_PROXY_HOPS"):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"TRUST_PROXY_HEADERS is replaced by TRUSTED_PROXY_HOPS (now %d). Set "
|
"TRUST_PROXY_HEADERS is not used (the starting proxy hop count is %d). "
|
||||||
"TRUSTED_PROXY_HOPS to the number of proxies in front of Grimoire and "
|
"Remove it; set the count in Settings → Config, or TRUSTED_PROXY_HOPS "
|
||||||
"remove TRUST_PROXY_HEADERS.",
|
"to change the starting value.",
|
||||||
Config.TRUSTED_PROXY_HOPS,
|
Config.TRUSTED_PROXY_HOPS,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -198,9 +198,20 @@ def create_app() -> Quart:
|
|||||||
from grimoire.services.logging import start_log_retention_loop
|
from grimoire.services.logging import start_log_retention_loop
|
||||||
from grimoire.services.notifications import start_notification_loop
|
from grimoire.services.notifications import start_notification_loop
|
||||||
|
|
||||||
|
from grimoire.services.rule_deliveries import start_prune_loop as start_rule_delivery_prune
|
||||||
|
|
||||||
start_log_retention_loop()
|
start_log_retention_loop()
|
||||||
start_notification_loop()
|
start_notification_loop()
|
||||||
start_auth_token_retention_loop()
|
start_auth_token_retention_loop()
|
||||||
|
start_rule_delivery_prune()
|
||||||
|
|
||||||
|
# The proxy hop count saved in Settings decides every request's client
|
||||||
|
# address, so it is loaded before serving, under a deadline (a failed
|
||||||
|
# or slow read leaves the environment's count in force), and re-read
|
||||||
|
# on an interval so a save in another worker reaches this one.
|
||||||
|
from grimoire.services import proxy_settings
|
||||||
|
await proxy_settings.load_at_startup()
|
||||||
|
proxy_settings.start_refresh_loop()
|
||||||
|
|
||||||
# Write down any shipped default that moved in this release.
|
# Write down any shipped default that moved in this release.
|
||||||
#
|
#
|
||||||
|
|||||||
@@ -124,8 +124,14 @@ class Config:
|
|||||||
BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/")
|
BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/")
|
||||||
# How many reverse proxies stand in front of the app; the client address
|
# How many reverse proxies stand in front of the app; the client address
|
||||||
# and scheme are read that many entries in from the right of the
|
# and scheme are read that many entries in from the right of the
|
||||||
# forwarding headers (grimoire/proxy.py). 0 trusts no proxy.
|
# forwarding headers (grimoire/proxy.py). 0 trusts no proxy. This is the
|
||||||
|
# install's starting value: a count saved in Settings → Config wins over
|
||||||
|
# it (services/proxy_settings.py).
|
||||||
TRUSTED_PROXY_HOPS: int = _trusted_proxy_hops()
|
TRUSTED_PROXY_HOPS: int = _trusted_proxy_hops()
|
||||||
|
TRUSTED_PROXY_HOPS_FROM_ENV: bool = bool(
|
||||||
|
os.environ.get("TRUSTED_PROXY_HOPS", "").strip()
|
||||||
|
or os.environ.get("TRUST_PROXY_HEADERS", "").strip()
|
||||||
|
)
|
||||||
|
|
||||||
# Git URL of the repo that ships this Grimoire plugin. There is one correct
|
# Git URL of the repo that ships this Grimoire plugin. There is one correct
|
||||||
# value per deployment (the repo serving the plugin), so it's a config
|
# value per deployment (the repo serving the plugin), so it's a config
|
||||||
|
|||||||
@@ -168,6 +168,10 @@ _READ_ONLY_TOOLS = frozenset({
|
|||||||
# rules are unjudged and which proposals wait. Reads of the caller's own
|
# rules are unjudged and which proposals wait. Reads of the caller's own
|
||||||
# rules, as list_rules is.
|
# rules, as list_rules is.
|
||||||
"rules_to_mount", "rule_moment_proposals",
|
"rules_to_mount", "rule_moment_proposals",
|
||||||
|
"lessons_to_situate", "lesson_situation_proposals",
|
||||||
|
"rules_to_weigh", "rule_weight_proposals",
|
||||||
|
# Adherence: the readout, and the queue a transcript review works from.
|
||||||
|
"rule_adherence", "adherence_to_judge",
|
||||||
})
|
})
|
||||||
|
|
||||||
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
|
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
|
||||||
@@ -180,6 +184,7 @@ _WRITE_TOOLS = frozenset({
|
|||||||
# notes, tasks, planning
|
# notes, tasks, planning
|
||||||
"create_note", "update_note", "delete_note",
|
"create_note", "update_note", "delete_note",
|
||||||
"create_lesson", "update_lesson", "delete_lesson", "judge_lesson_link",
|
"create_lesson", "update_lesson", "delete_lesson", "judge_lesson_link",
|
||||||
|
"propose_lesson_situations", "judge_lesson_situations",
|
||||||
"create_task", "update_task", "delete_task", "add_task_log",
|
"create_task", "update_task", "delete_task", "add_task_log",
|
||||||
"create_records", "start_planning",
|
"create_records", "start_planning",
|
||||||
"create_milestone", "update_milestone", "delete_milestone",
|
"create_milestone", "update_milestone", "delete_milestone",
|
||||||
@@ -229,9 +234,14 @@ _WRITE_TOOLS = frozenset({
|
|||||||
# Proposing moments for a rule writes a judgment row; judging one mounts
|
# Proposing moments for a rule writes a judgment row; judging one mounts
|
||||||
# or unmounts the rule.
|
# or unmounts the rule.
|
||||||
"propose_rule_moments", "judge_rule_moments",
|
"propose_rule_moments", "judge_rule_moments",
|
||||||
|
# Proposing a rule's enforcement, salience or triggers writes a judgment
|
||||||
|
# row; judging one changes how the rule arrives.
|
||||||
|
"propose_rule_weights", "judge_rule_weights",
|
||||||
# A misfire report writes a counted row that can become an unmount
|
# A misfire report writes a counted row that can become an unmount
|
||||||
# proposal.
|
# proposal.
|
||||||
"rule_misfired",
|
"rule_misfired",
|
||||||
|
# A transcript review's adherence verdicts, with the evidence it wrote.
|
||||||
|
"judge_adherence",
|
||||||
# A reviewer's verdicts on logged menu lines — rows carrying free
|
# A reviewer's verdicts on logged menu lines — rows carrying free
|
||||||
# prose the agent authored, `rule_outcome`'s reason for being a write.
|
# prose the agent authored, `rule_outcome`'s reason for being a write.
|
||||||
"judge_menu",
|
"judge_menu",
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ from grimoire.services import access as access_svc
|
|||||||
from grimoire.services import dedup as dedup_svc
|
from grimoire.services import dedup as dedup_svc
|
||||||
from grimoire.services import knowledge as knowledge_svc
|
from grimoire.services import knowledge as knowledge_svc
|
||||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
from grimoire.services import lesson_rules as lesson_rules_svc
|
||||||
|
from grimoire.services import lesson_situations as lesson_situations_svc
|
||||||
from grimoire.services import lessons as lessons_svc
|
from grimoire.services import lessons as lessons_svc
|
||||||
from grimoire.services import systems as systems_svc
|
from grimoire.services import systems as systems_svc
|
||||||
from grimoire.services import trash as trash_svc
|
from grimoire.services import trash as trash_svc
|
||||||
@@ -408,12 +409,12 @@ async def judge_lesson_link(
|
|||||||
"""Say whether a lesson is an instance of a rule: `verdict` is "confirm"
|
"""Say whether a lesson is an instance of a rule: `verdict` is "confirm"
|
||||||
or "reject".
|
or "reject".
|
||||||
|
|
||||||
Reach for this when Grimoire proposes a pair — a lesson and a rule that keep
|
Reach for this when you are reading a lesson and recognise the rule it
|
||||||
arriving together in different situations — or whenever you are reading a
|
falls under, or when a lesson you just recorded was offered candidate
|
||||||
lesson and recognise the rule it falls under. Confirming makes the rule
|
rules. Confirming makes the rule reachable through the situation the
|
||||||
reachable through the situation the lesson describes; rejecting records
|
lesson describes, and lists the lesson on the rule when it is opened;
|
||||||
that it is not, so the pair is not proposed again. `note` is the why, and
|
rejecting records that it is not. `note` is the why, and the next reader
|
||||||
the next reader judges the link by it.
|
judges the link by it.
|
||||||
|
|
||||||
Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}.
|
Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}.
|
||||||
"""
|
"""
|
||||||
@@ -451,7 +452,71 @@ async def delete_lesson(lesson_id: int) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def lessons_to_situate(limit: int = 25, offset: int = 0) -> dict:
|
||||||
|
"""The lessons with no situation yet — the pass over the corpus, a page at a time.
|
||||||
|
|
||||||
|
A lesson with no situation arrives only when a prompt's words resemble
|
||||||
|
it. Read each one here and decide WHEN it applies: a moment of work it
|
||||||
|
belongs to, a trigger on the act (a `path` glob, a `command` prefix, a
|
||||||
|
`tool`, a `keyword`), or that none fits. Record the answer with
|
||||||
|
`propose_lesson_situations`. A lesson leaves this list once any answer is
|
||||||
|
recorded, so the next call returns the next unread lessons.
|
||||||
|
|
||||||
|
Each lesson carries its title, its stated `when_to_apply`, the `rules` it
|
||||||
|
is a confirmed instance of with their own moments and triggers (the
|
||||||
|
strongest hint at its situation), and values already `rejected` for it.
|
||||||
|
The page carries the moment `catalog` and the `trigger_kinds`.
|
||||||
|
"""
|
||||||
|
return await lesson_situations_svc.to_situate(current_user_id(), limit=limit, offset=offset)
|
||||||
|
|
||||||
|
|
||||||
|
async def propose_lesson_situations(proposals: list[dict]) -> dict:
|
||||||
|
"""Propose when lessons apply — for the operator to confirm; nothing is delivered by this call.
|
||||||
|
|
||||||
|
Each item is `{"lesson_id": N, "moments": ["work.deliver"], "triggers":
|
||||||
|
[{"kind": "path", "pattern": "alembic/versions/*.py"}], "why": "…"}`.
|
||||||
|
Empty `moments` and `triggers` say no situation fits: the lesson stays
|
||||||
|
reachable by meaning, and leaves the pass's list.
|
||||||
|
|
||||||
|
Propose a moment when the lesson is about that point in the work whatever
|
||||||
|
the work is about; a trigger when it is about a kind of file, command or
|
||||||
|
tool. Keep it to the few points where the lesson changes what is done —
|
||||||
|
a lesson that matches every edit is noise there. `why` is shown to the
|
||||||
|
operator beside the proposal; write it so they can say yes or no without
|
||||||
|
opening the lesson.
|
||||||
|
|
||||||
|
Returns `written`, `skipped` (already recorded, in any state) and
|
||||||
|
`refused` (a bad item, refused alone). Then show the operator what waits
|
||||||
|
(`lesson_situation_proposals`); they judge it in Settings › Moments or
|
||||||
|
through `judge_lesson_situations`.
|
||||||
|
"""
|
||||||
|
return await lesson_situations_svc.propose(current_user_id(), proposals)
|
||||||
|
|
||||||
|
|
||||||
|
async def lesson_situation_proposals(lesson_id: int = 0) -> dict:
|
||||||
|
"""The lesson situations waiting on the operator, grouped by lesson.
|
||||||
|
|
||||||
|
Each proposal has its `id` (what `judge_lesson_situations` takes), its
|
||||||
|
`kind` (`moment` or `trigger`), what it `describes`, and the proposer's
|
||||||
|
`note`. `lesson_id` narrows to one lesson.
|
||||||
|
"""
|
||||||
|
return await lesson_situations_svc.pending(current_user_id(), lesson_id=lesson_id or None)
|
||||||
|
|
||||||
|
|
||||||
|
async def judge_lesson_situations(judgments: list[dict]) -> dict:
|
||||||
|
"""Confirm or reject lesson situations — on the operator's word, since a confirm changes what reaches their sessions.
|
||||||
|
|
||||||
|
Each item is `{"id": N, "verdict": "confirm" | "reject", "note": "why"}`,
|
||||||
|
with the id from `lesson_situation_proposals`. A confirmed situation
|
||||||
|
delivers its lesson when the work reaches it, once per session; a
|
||||||
|
rejected one is never proposed again. Put the operator's reason in `note`.
|
||||||
|
"""
|
||||||
|
return await lesson_situations_svc.judge(current_user_id(), judgments)
|
||||||
|
|
||||||
|
|
||||||
def register(mcp) -> None:
|
def register(mcp) -> None:
|
||||||
for fn in (list_lessons, create_lesson, get_lesson, update_lesson,
|
for fn in (list_lessons, create_lesson, get_lesson, update_lesson,
|
||||||
delete_lesson, judge_lesson_link):
|
delete_lesson, judge_lesson_link, lessons_to_situate,
|
||||||
|
propose_lesson_situations, lesson_situation_proposals,
|
||||||
|
judge_lesson_situations):
|
||||||
mcp.tool(name=fn.__name__)(fn)
|
mcp.tool(name=fn.__name__)(fn)
|
||||||
|
|||||||
@@ -15,7 +15,10 @@ from __future__ import annotations
|
|||||||
from grimoire.mcp._context import current_user_id
|
from grimoire.mcp._context import current_user_id
|
||||||
from grimoire.services import moment_actions as actions_svc
|
from grimoire.services import moment_actions as actions_svc
|
||||||
from grimoire.services import moments as moments_svc
|
from grimoire.services import moments as moments_svc
|
||||||
|
from grimoire.services import record_kinds as record_kinds_svc
|
||||||
from grimoire.services import reply_shapes as shapes_svc
|
from grimoire.services import reply_shapes as shapes_svc
|
||||||
|
from grimoire.services import rule_adherence as adherence_svc
|
||||||
|
from grimoire.services import rule_field_judgments as weights_svc
|
||||||
from grimoire.services import rule_moment_judgments as judgments_svc
|
from grimoire.services import rule_moment_judgments as judgments_svc
|
||||||
|
|
||||||
|
|
||||||
@@ -42,9 +45,18 @@ async def list_moments() -> dict:
|
|||||||
`via: "default"` ships with the product, `via: "install"` is this
|
`via: "default"` ships with the product, `via: "install"` is this
|
||||||
install's own mapping. `removed_defaults` are shipped defaults this install
|
install's own mapping. `removed_defaults` are shipped defaults this install
|
||||||
switched off.
|
switched off.
|
||||||
|
|
||||||
|
`record_kinds` is the kind×moment table: for each point where a record
|
||||||
|
search fires (`message`, the operator's message, and the catalog moments
|
||||||
|
that have one), the kinds of record it may consider, the shipped default,
|
||||||
|
and each kind's lines shown and opened there. A kind left out is never
|
||||||
|
pushed at that point; search for it yourself when you need it. The
|
||||||
|
operator changes the table in Settings › Moments.
|
||||||
"""
|
"""
|
||||||
|
uid = current_user_id()
|
||||||
out = moments_svc.catalog()
|
out = moments_svc.catalog()
|
||||||
out.update(await actions_svc.actions_by_moment(current_user_id()))
|
out.update(await actions_svc.actions_by_moment(uid))
|
||||||
|
out["record_kinds"] = await record_kinds_svc.table(uid)
|
||||||
return out
|
return out
|
||||||
|
|
||||||
|
|
||||||
@@ -232,6 +244,150 @@ async def rule_misfired(rule_id: int, moment: str, why: str,
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict:
|
||||||
|
"""The rules nobody has weighed, each with what happened when it reached a session — a page at a time.
|
||||||
|
|
||||||
|
Weighing a rule is deciding how strongly it arrives once the work reaches
|
||||||
|
it, and what reaches it exactly:
|
||||||
|
|
||||||
|
- `enforcement`: `inform` is a line beside the work, and is right for
|
||||||
|
most rules. `hold` makes the act or reply wait until the rule has been
|
||||||
|
read once in the session (file edits are never held). `enforce` refuses
|
||||||
|
the act the rule governs, in the rule's own words, every time — for a
|
||||||
|
rule whose breach an act commits and that must never be crossed without
|
||||||
|
the operator (pushing to a protected branch, a destructive command). A
|
||||||
|
preference is always `inform`.
|
||||||
|
- `salience`: `high`, `normal` or `low` — how it ranks beside rules of the
|
||||||
|
same enforcement when a moment has more to say than fits.
|
||||||
|
- `triggers`: typed predicates on the act (`tool`, `path`, `command`,
|
||||||
|
`keyword`, optionally scoped to a moment) that reach the rule exactly.
|
||||||
|
Propose one when the rule names the act it governs; an `enforce` rule
|
||||||
|
needs one, or a mount on an act's moment, to have an act to refuse.
|
||||||
|
|
||||||
|
Each rule carries its current `enforcement`, `salience`, `mounted` and
|
||||||
|
`triggers`, and `history` over the last 90 days: `delivered` and `opened`
|
||||||
|
in total and at each place (`places`), `pulled`, `applied`, `departed`
|
||||||
|
and `misfire_days`. Read the history as evidence about the rule's
|
||||||
|
weight, not as the decision: a rule delivered often and rarely opened is
|
||||||
|
either reaching the wrong work (a trigger fixes that) or arriving too
|
||||||
|
loudly for what it asks (lower salience); a rule sessions keep departing
|
||||||
|
from or breaching may need `hold`.
|
||||||
|
|
||||||
|
Record the answer with `propose_rule_weights`. A rule leaves this list as
|
||||||
|
soon as an answer is recorded, so the next call returns the next rules.
|
||||||
|
Returns `rules`, `total_unweighed` and `offset`.
|
||||||
|
"""
|
||||||
|
return await weights_svc.unweighed_rules(current_user_id(), limit=limit, offset=offset)
|
||||||
|
|
||||||
|
|
||||||
|
async def propose_rule_weights(proposals: list[dict]) -> dict:
|
||||||
|
"""Propose rules' enforcement, salience and triggers — for the operator to confirm; nothing changes on this call.
|
||||||
|
|
||||||
|
Each item is
|
||||||
|
`{"rule_id": N, "enforcement": "inform"|"hold"|"enforce",
|
||||||
|
"salience": "high"|"normal"|"low", "triggers": [{"kind": "command",
|
||||||
|
"pattern": "git push", "moment": ""}], "why": "…"}`.
|
||||||
|
|
||||||
|
Give both enforcement and salience for every rule, even where they match
|
||||||
|
what it has: a value equal to the rule's own is recorded as agreed, which
|
||||||
|
is what marks the rule as weighed. A different value waits as a
|
||||||
|
suggestion. `triggers` lists only triggers to add; omit it when none fits.
|
||||||
|
`why` is shown to the operator beside each suggestion: say what in the
|
||||||
|
rule and its history led to it, so they can say yes or no without opening
|
||||||
|
the rule.
|
||||||
|
|
||||||
|
Refused alone, under `refused`, with why: an unknown value, a preference
|
||||||
|
proposed to hold or enforce, and `enforce` on a rule no act reaches.
|
||||||
|
A value the operator already rejected is listed under `skipped`. Then show
|
||||||
|
the operator what is waiting (`rule_weight_proposals`) and let them
|
||||||
|
decide.
|
||||||
|
"""
|
||||||
|
return await weights_svc.propose(current_user_id(), proposals)
|
||||||
|
|
||||||
|
|
||||||
|
async def rule_weight_proposals(rule_id: int = 0) -> dict:
|
||||||
|
"""The enforcement, salience and trigger suggestions waiting on the operator, grouped by rule.
|
||||||
|
|
||||||
|
Each rule carries its current enforcement, salience, mounts and triggers
|
||||||
|
beside its `proposals`: each a `field`, the suggested `value` (a trigger
|
||||||
|
also as `trigger`), `why`, and the delivery history the proposer read
|
||||||
|
(`evidence`). `rule_id` narrows to one rule.
|
||||||
|
"""
|
||||||
|
return await weights_svc.pending(current_user_id(), rule_id=rule_id or None)
|
||||||
|
|
||||||
|
|
||||||
|
async def judge_rule_weights(judgments: list[dict]) -> dict:
|
||||||
|
"""Confirm or reject weight suggestions — on the operator's word, since a confirm changes how the rule arrives.
|
||||||
|
|
||||||
|
Each item is `{"rule_id": N, "field": "enforcement"|"salience"|"trigger",
|
||||||
|
"value": "hold" (or the trigger object), "verdict": "confirm"|"reject",
|
||||||
|
"note": "why"}`. Confirm sets the field on the rule (a trigger is added
|
||||||
|
beside the rule's others); reject records that the value is wrong for this
|
||||||
|
rule, so it is never proposed again. Put the operator's reason in `note`.
|
||||||
|
"""
|
||||||
|
return await weights_svc.judge(current_user_id(), judgments)
|
||||||
|
|
||||||
|
|
||||||
|
async def rule_adherence(days: int = 30, rule_id: int = 0) -> dict:
|
||||||
|
"""Whether the rules in force at each moment were followed there — per rule and per moment.
|
||||||
|
|
||||||
|
A rule is in force at a moment of a session when it was delivered there.
|
||||||
|
For each rule at each place (a moment such as `work.deliver`, or an arm
|
||||||
|
such as `pre_tool_rule`) over the last `days`: `in_force` (sessions it
|
||||||
|
was delivered there in), `opened` (sessions that opened it), and one
|
||||||
|
count per verdict — `followed`, `departed` (read and deliberately not
|
||||||
|
followed, with a reason), `broken` (the work went against it),
|
||||||
|
`not_applicable` (it did not bear on the work there) — and `unjudged`.
|
||||||
|
|
||||||
|
Verdicts come from an `enforce` refusal (the act did not happen), from
|
||||||
|
the session's own `rule_outcome` and `rule_misfired` calls, and from a
|
||||||
|
review of the transcript (`adherence_to_judge` / `judge_adherence`).
|
||||||
|
Returns `by_rule` (each with its places), `by_moment` (each with its
|
||||||
|
rules) and `totals`. `rule_id` narrows to one rule.
|
||||||
|
"""
|
||||||
|
return await adherence_svc.summary(current_user_id(), days=days, rule_id=rule_id or None)
|
||||||
|
|
||||||
|
|
||||||
|
async def adherence_to_judge(session_id: str = "", sessions: int = 3, per_session: int = 40) -> dict:
|
||||||
|
"""The rules that were in force at a moment of a session and have no verdict yet — for a transcript review.
|
||||||
|
|
||||||
|
Grouped by session, most recent first. Each item is one rule at one place
|
||||||
|
in that session: the rule's `statement` and `when_to_apply`, where it
|
||||||
|
arrived (`at`), how often and when (`delivered`, `first_at`, `last_at`),
|
||||||
|
and whether the session `opened` it. `how` says where the session's
|
||||||
|
transcript is kept.
|
||||||
|
|
||||||
|
To review a session: read its transcript around each item's times, see
|
||||||
|
what the work was at that moment, and decide whether it kept the rule.
|
||||||
|
Record the verdicts with `judge_adherence`, quoting or describing what in
|
||||||
|
the transcript shows each one. An item that did not bear on the work
|
||||||
|
there is `not_applicable`; that is a finding about where the rule is
|
||||||
|
delivered, and is as useful as the rest. `unjudged` is the total waiting.
|
||||||
|
`session_id` narrows to one session.
|
||||||
|
"""
|
||||||
|
return await adherence_svc.to_judge(
|
||||||
|
current_user_id(), session_id, sessions=sessions, per_session=per_session,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def judge_adherence(verdicts: list[dict]) -> dict:
|
||||||
|
"""Record a transcript review's verdicts on rules in force at a moment of a session.
|
||||||
|
|
||||||
|
Each item is `{"session_id": "…", "rule_id": N, "at": "work.deliver",
|
||||||
|
"verdict": "followed"|"broken"|"departed"|"not_applicable",
|
||||||
|
"evidence": "…"}`, the `session_id`, `rule_id` and `at` as
|
||||||
|
`adherence_to_judge` listed them. `evidence` is required: what the
|
||||||
|
transcript shows — the act, the reply, or the passage — so a later reader
|
||||||
|
can check the verdict. `departed` is for a session that said why it did
|
||||||
|
not follow the rule; `broken` for work that went against it without one.
|
||||||
|
|
||||||
|
A review replaces the session's own account (a later, closer reading
|
||||||
|
wins), except where an `enforce` rule refused the act, which stands.
|
||||||
|
Returns `judged` and `refused`, each refused item with why.
|
||||||
|
"""
|
||||||
|
return await adherence_svc.judge(current_user_id(), verdicts)
|
||||||
|
|
||||||
|
|
||||||
def register(mcp) -> None:
|
def register(mcp) -> None:
|
||||||
mcp.tool(name="list_moments")(list_moments)
|
mcp.tool(name="list_moments")(list_moments)
|
||||||
mcp.tool(name="list_reply_shapes")(list_reply_shapes)
|
mcp.tool(name="list_reply_shapes")(list_reply_shapes)
|
||||||
@@ -242,3 +398,10 @@ def register(mcp) -> None:
|
|||||||
mcp.tool(name="rule_moment_proposals")(rule_moment_proposals)
|
mcp.tool(name="rule_moment_proposals")(rule_moment_proposals)
|
||||||
mcp.tool(name="judge_rule_moments")(judge_rule_moments)
|
mcp.tool(name="judge_rule_moments")(judge_rule_moments)
|
||||||
mcp.tool(name="rule_misfired")(rule_misfired)
|
mcp.tool(name="rule_misfired")(rule_misfired)
|
||||||
|
mcp.tool(name="rules_to_weigh")(rules_to_weigh)
|
||||||
|
mcp.tool(name="propose_rule_weights")(propose_rule_weights)
|
||||||
|
mcp.tool(name="rule_weight_proposals")(rule_weight_proposals)
|
||||||
|
mcp.tool(name="judge_rule_weights")(judge_rule_weights)
|
||||||
|
mcp.tool(name="rule_adherence")(rule_adherence)
|
||||||
|
mcp.tool(name="adherence_to_judge")(adherence_to_judge)
|
||||||
|
mcp.tool(name="judge_adherence")(judge_adherence)
|
||||||
|
|||||||
@@ -144,7 +144,10 @@ async def create_note(
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
title: Note title (required).
|
title: Note title (required).
|
||||||
body: Markdown content. Supports [[wikilinks]] to other notes by title.
|
body: Markdown content. Cite another record as `#N` (note, task,
|
||||||
|
lesson, snippet), `milestone N` or `rule N`; the web UI links each
|
||||||
|
one, titled on hover, and lists it in the target's backlinks.
|
||||||
|
`[[Title]]` links a note by its title.
|
||||||
tags: List of plain-string tags without # prefix, e.g. ["python", "ideas"].
|
tags: List of plain-string tags without # prefix, e.g. ["python", "ideas"].
|
||||||
project_id: Associate with a project (use 0 for no project / orphan note).
|
project_id: Associate with a project (use 0 for no project / orphan note).
|
||||||
system_ids: Ids of the project's Systems to associate this note with
|
system_ids: Ids of the project's Systems to associate this note with
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone
|
|||||||
from grimoire.mcp._context import current_user_id
|
from grimoire.mcp._context import current_user_id
|
||||||
from grimoire.services import dedup as dedup_svc
|
from grimoire.services import dedup as dedup_svc
|
||||||
from grimoire.services import moments as moments_svc
|
from grimoire.services import moments as moments_svc
|
||||||
|
from grimoire.services import rule_triggers as rule_triggers_svc
|
||||||
from grimoire.services import rulebooks as rulebooks_svc
|
from grimoire.services import rulebooks as rulebooks_svc
|
||||||
from grimoire.services import trash as trash_svc
|
from grimoire.services import trash as trash_svc
|
||||||
from grimoire.services.lesson_rules import confirmed_lesson_counts
|
from grimoire.services.lesson_rules import confirmed_lesson_counts
|
||||||
@@ -342,6 +343,8 @@ async def create_rule(
|
|||||||
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
|
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
|
||||||
system_ids: list[int] | None = None,
|
system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None, force: bool = False,
|
moments: list[str] | None = None, force: bool = False,
|
||||||
|
enforcement: str = "inform", salience: str = "normal",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Create a new rule in a rulebook (a SHARED rule — keep it general).
|
"""Create a new rule in a rulebook (a SHARED rule — keep it general).
|
||||||
|
|
||||||
@@ -530,6 +533,30 @@ async def create_rule(
|
|||||||
constraint expires when the ground under it moves, not on a
|
constraint expires when the ground under it moves, not on a
|
||||||
schedule. Pairs with verify_with; both empty is the normal case.
|
schedule. Pairs with verify_with; both empty is the normal case.
|
||||||
order_index: Display order within the topic (default 0).
|
order_index: Display order within the topic (default 0).
|
||||||
|
enforcement: What this rule does when it arrives. `inform` (the
|
||||||
|
default) puts a line beside the work. `hold` makes the reply or
|
||||||
|
act it governs wait until the session has read the rule once
|
||||||
|
(file edits are never held) — for a rule whose miss costs a
|
||||||
|
rewrite. `enforce` refuses the act it governs, in the rule's own
|
||||||
|
words, every time — for a boundary only the operator moves; it
|
||||||
|
needs a trigger, or a mount on a moment an act reaches, to have
|
||||||
|
an act to refuse. A rule with triggers holds or refuses only the
|
||||||
|
acts they match; reached by its mount alone it is a line. Declare
|
||||||
|
hold or enforce on purpose; most rules inform.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
|
ranks against others of the same enforcement when a moment has
|
||||||
|
more to say than fits.
|
||||||
force: Bypass the near-duplicate gate. By default, a title-identical rule
|
force: Bypass the near-duplicate gate. By default, a title-identical rule
|
||||||
already in this topic BLOCKS creation and returns its id so you update
|
already in this topic BLOCKS creation and returns its id so you update
|
||||||
it instead. Set true only for a genuinely distinct rule. A rule or
|
it instead. Set true only for a genuinely distinct rule. A rule or
|
||||||
@@ -539,6 +566,7 @@ async def create_rule(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
if not force:
|
if not force:
|
||||||
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
|
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
|
||||||
if dup is not None:
|
if dup is not None:
|
||||||
@@ -553,8 +581,9 @@ async def create_rule(
|
|||||||
arose_from_id=arose_from_id,
|
arose_from_id=arose_from_id,
|
||||||
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
||||||
verify_with=verify_with, expires_when=expires_when,
|
verify_with=verify_with, expires_when=expires_when,
|
||||||
|
enforcement=enforcement, salience=salience,
|
||||||
)
|
)
|
||||||
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
||||||
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
|
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
|
||||||
|
|
||||||
@@ -565,6 +594,8 @@ async def create_project_rule(
|
|||||||
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
|
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
|
||||||
system_ids: list[int] | None = None,
|
system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None, force: bool = False,
|
moments: list[str] | None = None, force: bool = False,
|
||||||
|
enforcement: str = "inform", salience: str = "normal",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Create a rule scoped to a single project (no rulebook needed).
|
"""Create a rule scoped to a single project (no rulebook needed).
|
||||||
|
|
||||||
@@ -640,6 +671,30 @@ async def create_project_rule(
|
|||||||
expires_when: The state under which the rule stops being true — see
|
expires_when: The state under which the rule stops being true — see
|
||||||
create_rule. A state, not a date.
|
create_rule. A state, not a date.
|
||||||
order_index: Display order within the project's rule list (default 0).
|
order_index: Display order within the project's rule list (default 0).
|
||||||
|
enforcement: What this rule does when it arrives. `inform` (the
|
||||||
|
default) puts a line beside the work. `hold` makes the reply or
|
||||||
|
act it governs wait until the session has read the rule once
|
||||||
|
(file edits are never held) — for a rule whose miss costs a
|
||||||
|
rewrite. `enforce` refuses the act it governs, in the rule's own
|
||||||
|
words, every time — for a boundary only the operator moves; it
|
||||||
|
needs a trigger, or a mount on a moment an act reaches, to have
|
||||||
|
an act to refuse. A rule with triggers holds or refuses only the
|
||||||
|
acts they match; reached by its mount alone it is a line. Declare
|
||||||
|
hold or enforce on purpose; most rules inform.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
|
ranks against others of the same enforcement when a moment has
|
||||||
|
more to say than fits.
|
||||||
force: Bypass the near-duplicate gate. By default, a title-identical rule
|
force: Bypass the near-duplicate gate. By default, a title-identical rule
|
||||||
already on this project BLOCKS creation and returns its id so you
|
already on this project BLOCKS creation and returns its id so you
|
||||||
update it instead. Set true only for a genuinely distinct rule. An
|
update it instead. Set true only for a genuinely distinct rule. An
|
||||||
@@ -648,6 +703,7 @@ async def create_project_rule(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
derived_title = title.strip() or statement.strip().split(".")[0][:50]
|
derived_title = title.strip() or statement.strip().split(".")[0][:50]
|
||||||
if not force:
|
if not force:
|
||||||
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
|
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
|
||||||
@@ -662,8 +718,9 @@ async def create_project_rule(
|
|||||||
arose_from_id=arose_from_id,
|
arose_from_id=arose_from_id,
|
||||||
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
||||||
verify_with=verify_with, expires_when=expires_when,
|
verify_with=verify_with, expires_when=expires_when,
|
||||||
|
enforcement=enforcement, salience=salience,
|
||||||
)
|
)
|
||||||
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
||||||
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
|
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
|
||||||
|
|
||||||
@@ -675,6 +732,8 @@ async def update_rule(
|
|||||||
moments: list[str] | None = None, arose_from_id: int = 0,
|
moments: list[str] | None = None, arose_from_id: int = 0,
|
||||||
verify_with: str = "", expires_when: str = "", kind: str = "",
|
verify_with: str = "", expires_when: str = "", kind: str = "",
|
||||||
clear_fields: list[str] | None = None,
|
clear_fields: list[str] | None = None,
|
||||||
|
enforcement: str = "", salience: str = "",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged.
|
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged.
|
||||||
|
|
||||||
@@ -735,9 +794,35 @@ async def update_rule(
|
|||||||
expires_when: The state under which the rule stops being true. A
|
expires_when: The state under which the rule stops being true. A
|
||||||
state, not a date. See create_rule.
|
state, not a date. See create_rule.
|
||||||
clear_fields: Names of fields to empty, as above.
|
clear_fields: Names of fields to empty, as above.
|
||||||
|
enforcement: What this rule does when it arrives. `inform` (the
|
||||||
|
default for a new rule) puts a line beside the work. `hold` makes the reply or
|
||||||
|
act it governs wait until the session has read the rule once
|
||||||
|
(file edits are never held) — for a rule whose miss costs a
|
||||||
|
rewrite. `enforce` refuses the act it governs, in the rule's own
|
||||||
|
words, every time — for a boundary only the operator moves; it
|
||||||
|
needs a trigger, or a mount on a moment an act reaches, to have
|
||||||
|
an act to refuse. A rule with triggers holds or refuses only the
|
||||||
|
acts they match; reached by its mount alone it is a line. Declare
|
||||||
|
hold or enforce on purpose; most rules inform.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
|
ranks against others of the same enforcement when a moment has
|
||||||
|
more to say than fits.
|
||||||
|
Omit either to leave it unchanged.
|
||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
fields: dict = {}
|
fields: dict = {}
|
||||||
if title:
|
if title:
|
||||||
fields["title"] = title
|
fields["title"] = title
|
||||||
@@ -759,12 +844,16 @@ async def update_rule(
|
|||||||
fields["expires_when"] = expires_when
|
fields["expires_when"] = expires_when
|
||||||
if order_index >= 0:
|
if order_index >= 0:
|
||||||
fields["order_index"] = order_index
|
fields["order_index"] = order_index
|
||||||
|
if enforcement:
|
||||||
|
fields["enforcement"] = enforcement
|
||||||
|
if salience:
|
||||||
|
fields["salience"] = salience
|
||||||
rule = await rulebooks_svc.update_rule(
|
rule = await rulebooks_svc.update_rule(
|
||||||
rule_id, uid, clear=clear_fields or (), **fields,
|
rule_id, uid, clear=clear_fields or (), **fields,
|
||||||
)
|
)
|
||||||
if rule is None:
|
if rule is None:
|
||||||
raise ValueError(f"rule {rule_id} not found")
|
raise ValueError(f"rule {rule_id} not found")
|
||||||
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
|
|
||||||
|
|
||||||
# ── Preferences ─────────────────────────────────────────────────────────
|
# ── Preferences ─────────────────────────────────────────────────────────
|
||||||
@@ -786,7 +875,8 @@ async def create_preference(
|
|||||||
arose_from_id: int, why: str = "", how_to_apply: str = "",
|
arose_from_id: int, why: str = "", how_to_apply: str = "",
|
||||||
order_index: int = 0, system_ids: list[int] | None = None,
|
order_index: int = 0, system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None,
|
moments: list[str] | None = None,
|
||||||
force: bool = False,
|
force: bool = False, salience: str = "normal",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Record how the operator wants work done. No approval loop — write it.
|
"""Record how the operator wants work done. No approval loop — write it.
|
||||||
|
|
||||||
@@ -860,6 +950,20 @@ async def create_preference(
|
|||||||
done rather than what it is about: a rule on when work counts as
|
done rather than what it is about: a rule on when work counts as
|
||||||
finished belongs at work.finish and reply.report, where nothing
|
finished belongs at work.finish and reply.report, where nothing
|
||||||
said resembles it. Replaces the set; [] clears it.
|
said resembles it. Replaces the set; [] clears it.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
|
ranks against others of the same enforcement when a moment has
|
||||||
|
more to say than fits.
|
||||||
force: Bypass the near-duplicate gate. For a genuinely distinct
|
force: Bypass the near-duplicate gate. For a genuinely distinct
|
||||||
preference, not for one that is "mostly" different — a mostly
|
preference, not for one that is "mostly" different — a mostly
|
||||||
different preference is an update. A RULE that already answers
|
different preference is an update. A RULE that already answers
|
||||||
@@ -869,6 +973,7 @@ async def create_preference(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
if not when_to_apply.strip():
|
if not when_to_apply.strip():
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"when_to_apply is required: a preference with no trigger never "
|
"when_to_apply is required: a preference with no trigger never "
|
||||||
@@ -893,8 +998,9 @@ async def create_preference(
|
|||||||
title=title, statement=statement, when_to_apply=when_to_apply,
|
title=title, statement=statement, when_to_apply=when_to_apply,
|
||||||
kind="preference", arose_from_id=arose_from_id,
|
kind="preference", arose_from_id=arose_from_id,
|
||||||
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
||||||
|
salience=salience,
|
||||||
)
|
)
|
||||||
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
data.update(dedup_svc.overlap_response(overlaps, "preference"))
|
data.update(dedup_svc.overlap_response(overlaps, "preference"))
|
||||||
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
|
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
|
||||||
|
|
||||||
@@ -905,6 +1011,8 @@ async def update_preference(
|
|||||||
how_to_apply: str = "", order_index: int = -1,
|
how_to_apply: str = "", order_index: int = -1,
|
||||||
system_ids: list[int] | None = None,
|
system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None, clear_fields: list[str] | None = None,
|
moments: list[str] | None = None, clear_fields: list[str] | None = None,
|
||||||
|
salience: str = "",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Bring a preference up to date. Doing this mid-work is expected.
|
"""Bring a preference up to date. Doing this mid-work is expected.
|
||||||
|
|
||||||
@@ -959,9 +1067,25 @@ async def update_preference(
|
|||||||
moments: Replaces the moments this preference arrives at (see
|
moments: Replaces the moments this preference arrives at (see
|
||||||
create_preference); omit to leave them alone.
|
create_preference); omit to leave them alone.
|
||||||
when_to_apply: The moment it applies, in session vocabulary. See above.
|
when_to_apply: The moment it applies, in session vocabulary. See above.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
|
ranks against others of the same enforcement when a moment has
|
||||||
|
more to say than fits.
|
||||||
|
Omit to leave it unchanged.
|
||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
if not arose_from_id:
|
if not arose_from_id:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"arose_from_id is required: this edit is the record of how the "
|
"arose_from_id is required: this edit is the record of how the "
|
||||||
@@ -981,12 +1105,14 @@ async def update_preference(
|
|||||||
fields["how_to_apply"] = how_to_apply
|
fields["how_to_apply"] = how_to_apply
|
||||||
if order_index >= 0:
|
if order_index >= 0:
|
||||||
fields["order_index"] = order_index
|
fields["order_index"] = order_index
|
||||||
|
if salience:
|
||||||
|
fields["salience"] = salience
|
||||||
rule = await rulebooks_svc.update_rule(
|
rule = await rulebooks_svc.update_rule(
|
||||||
rule_id, uid, clear=clear_fields or (), **fields,
|
rule_id, uid, clear=clear_fields or (), **fields,
|
||||||
)
|
)
|
||||||
if rule is None:
|
if rule is None:
|
||||||
raise ValueError(f"rule {rule_id} not found")
|
raise ValueError(f"rule {rule_id} not found")
|
||||||
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
|
|
||||||
|
|
||||||
async def rule_history(rule_id: int, version_id: int = 0) -> dict:
|
async def rule_history(rule_id: int, version_id: int = 0) -> dict:
|
||||||
|
|||||||
@@ -528,6 +528,15 @@ async def retrieval_telemetry(
|
|||||||
a ratio of opens would read near zero on an arm that is working.
|
a ratio of opens would read near zero on an arm that is working.
|
||||||
`system_usage_failed: true` means its read broke and the zeros mean nothing.
|
`system_usage_failed: true` means its read broke and the zeros mean nothing.
|
||||||
|
|
||||||
|
`record_reach` — how every non-rule record reached a session, from
|
||||||
|
`record_deliveries`: per kind (`snippet`, `note`, `lesson`, `task:issue`,
|
||||||
|
…), each way it arrived — `pushed` by a hook, `asked` (a result of a
|
||||||
|
`search` the session ran itself), `direct` (opened with nothing
|
||||||
|
delivering it first) — with `delivered` and `opened`, and per door in
|
||||||
|
`sources`. It is the readout that says whether a kind is found by being
|
||||||
|
pushed or by being asked for, which `usage` cannot: a pull there does not
|
||||||
|
say which door led to it. Counts only sessions whose plugin reports opens.
|
||||||
|
|
||||||
`judged` — whether the lines RELATED, from `retrieval_judgments`:
|
`judged` — whether the lines RELATED, from `retrieval_judgments`:
|
||||||
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
|
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
|
||||||
on a sample of logged menus, `within_budget` against `beyond_budget` and
|
on a sample of logged menus, `within_budget` against `beyond_budget` and
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ Sentinels (preserved from existing fable-mcp):
|
|||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
from grimoire.mcp._context import current_user_id
|
from grimoire.mcp._context import current_user_id
|
||||||
from grimoire.mcp.tools import systems as systems_tools
|
from grimoire.mcp.tools import systems as systems_tools
|
||||||
from grimoire.services import access as access_svc
|
from grimoire.services import access as access_svc
|
||||||
@@ -34,6 +36,7 @@ from grimoire.services.notes import minted_kind
|
|||||||
from grimoire.services import placement as placement_svc
|
from grimoire.services import placement as placement_svc
|
||||||
from grimoire.services import planning as planning_svc
|
from grimoire.services import planning as planning_svc
|
||||||
from grimoire.services import record_batch as batch_svc
|
from grimoire.services import record_batch as batch_svc
|
||||||
|
from grimoire.services import record_kinds, record_links
|
||||||
from grimoire.services import rulebooks as rulebooks_svc
|
from grimoire.services import rulebooks as rulebooks_svc
|
||||||
from grimoire.services import systems as systems_svc
|
from grimoire.services import systems as systems_svc
|
||||||
from grimoire.services import task_logs as task_logs_svc
|
from grimoire.services import task_logs as task_logs_svc
|
||||||
@@ -43,6 +46,8 @@ from grimoire.services.record_refs import refuse_guessed_ids
|
|||||||
from grimoire.services.text import elide
|
from grimoire.services.text import elide
|
||||||
from grimoire.services import moment_delivery
|
from grimoire.services import moment_delivery
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# A work log entry is prose, often long — the discipline asks for what was
|
# A work log entry is prose, often long — the discipline asks for what was
|
||||||
# decided and why, not a line of status. Two caps, not one, because the entries
|
# decided and why, not a line of status. Two caps, not one, because the entries
|
||||||
@@ -271,7 +276,9 @@ async def create_task(
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
title: Task title (required).
|
title: Task title (required).
|
||||||
body: Markdown description / notes for the task.
|
body: Markdown description / notes for the task. Cite another record
|
||||||
|
as `#N` (note, task, lesson, snippet), `milestone N` or `rule N`;
|
||||||
|
the web UI links each one and lists it in the target's backlinks.
|
||||||
status: Initial status — one of: todo (default), in_progress, done, cancelled.
|
status: Initial status — one of: todo (default), in_progress, done, cancelled.
|
||||||
priority: One of: low, medium, high, or 'none'. Omit (empty string) to leave unset.
|
priority: One of: low, medium, high, or 'none'. Omit (empty string) to leave unset.
|
||||||
project_id: Associate with a project (0 = no project).
|
project_id: Associate with a project (0 = no project).
|
||||||
@@ -408,6 +415,11 @@ async def update_task(
|
|||||||
reconstructing them, because a remembered milestone title or "next step"
|
reconstructing them, because a remembered milestone title or "next step"
|
||||||
reads exactly like a real one when it is wrong.
|
reads exactly like a real one when it is wrong.
|
||||||
|
|
||||||
|
Setting a task `in_progress` also returns `records_in_area` when the
|
||||||
|
task's areas hold notes or open issues: one line naming them by id with
|
||||||
|
the call that opens each. Read the ones that bear on the work before
|
||||||
|
starting it.
|
||||||
|
|
||||||
Closing a task (done or cancelled) also returns `reply_shape`, the
|
Closing a task (done or cancelled) also returns `reply_shape`, the
|
||||||
default shape of the completion report you are about to write, and
|
default shape of the completion report you are about to write, and
|
||||||
`report_back`: a one-line reminder of what that reply should cover. The
|
`report_back`: a one-line reminder of what that reply should cover. The
|
||||||
@@ -463,11 +475,29 @@ async def update_task(
|
|||||||
# Owed family adoptions filed while the task was open — work now
|
# Owed family adoptions filed while the task was open — work now
|
||||||
# waiting in some project, which the report names.
|
# waiting in some project, which the report names.
|
||||||
await family_adoption_svc.attach_owed_adoptions(uid, data, note)
|
await family_adoption_svc.attach_owed_adoptions(uid, data, note)
|
||||||
|
if status == "in_progress":
|
||||||
|
await _attach_area_records(uid, task_id, data)
|
||||||
return await moment_delivery.attach_moment_rules(
|
return await moment_delivery.attach_moment_rules(
|
||||||
uid, "update_task", {"status": status, "project_id": project_id}, data,
|
uid, "update_task", {"status": status, "project_id": project_id}, data,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _attach_area_records(uid: int, task_id: int, data: dict) -> None:
|
||||||
|
"""Name, by id, what is recorded in the areas of a task being taken up:
|
||||||
|
the `work.start` row of the kind×moment table says which kinds. Absent
|
||||||
|
when the task has no area or nothing is recorded there."""
|
||||||
|
try:
|
||||||
|
kinds = await record_kinds.kinds_for(uid, "work.start")
|
||||||
|
found = await record_links.area_records(uid, task_id, kinds)
|
||||||
|
line = record_kinds.pointer_line(
|
||||||
|
found, "Recorded in this task's areas", capped_at=record_links.AREA_DEPTH,
|
||||||
|
)
|
||||||
|
if line:
|
||||||
|
data["records_in_area"] = line[0].removeprefix("> ")
|
||||||
|
except Exception: # noqa: BLE001 - a decoration never breaks the payload
|
||||||
|
logger.debug("area records for task %s could not be attached", task_id, exc_info=True)
|
||||||
|
|
||||||
|
|
||||||
async def add_task_log(task_id: int, content: str) -> dict:
|
async def add_task_log(task_id: int, content: str) -> dict:
|
||||||
"""Append a timestamped progress log entry to a Grimoire task.
|
"""Append a timestamped progress log entry to a Grimoire task.
|
||||||
|
|
||||||
@@ -482,6 +512,9 @@ async def add_task_log(task_id: int, content: str) -> dict:
|
|||||||
cannot get from the body or the diff is what you tried, what you ruled
|
cannot get from the body or the diff is what you tried, what you ruled
|
||||||
out, and where it actually stands.
|
out, and where it actually stands.
|
||||||
|
|
||||||
|
Records named as `#N`, `milestone N` or `rule N` are links in the web UI,
|
||||||
|
and a `#N` here lists this task in that record's backlinks.
|
||||||
|
|
||||||
A log on an open task also marks it as being worked by this session — its
|
A log on an open task also marks it as being worked by this session — its
|
||||||
`claim`. That is what brings the task and its newest
|
`claim`. That is what brings the task and its newest
|
||||||
entries back to you after a compaction; it lapses by itself once the
|
entries back to you after a compaction; it lapses by itself once the
|
||||||
|
|||||||
@@ -60,6 +60,9 @@ from grimoire.models.retrieval_log import RetrievalLog # noqa: E402, F401
|
|||||||
from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401
|
from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401
|
||||||
from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
|
from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
|
||||||
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
|
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
|
||||||
|
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
|
||||||
|
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
|
||||||
|
from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401
|
||||||
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
|
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
|
||||||
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
|
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
|
||||||
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
|
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
|
||||||
@@ -81,8 +84,10 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
|
|||||||
)
|
)
|
||||||
# After notes and rules: it foreign-keys both.
|
# After notes and rules: it foreign-keys both.
|
||||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
|
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
|
||||||
|
from grimoire.models.lesson_situation import LessonSituation # noqa: E402, F401
|
||||||
# After rules: it foreign-keys them.
|
# After rules: it foreign-keys them.
|
||||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
|
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
|
||||||
|
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
|
||||||
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
|
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
|
||||||
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
|
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
|
||||||
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
|
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from grimoire.models import Base
|
||||||
|
from grimoire.models.base import CreatedAtMixin, iso
|
||||||
|
from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CONFIRMED", "KINDS", "MOMENT", "NONE", "REJECTED", "SITUATION_STATES", "SOURCES",
|
||||||
|
"SUGGESTED", "TRIGGER", "LessonSituation",
|
||||||
|
]
|
||||||
|
|
||||||
|
# The same three states as a lesson's link to a rule. CHECK
|
||||||
|
# ck_lesson_situations_state (migration 0137).
|
||||||
|
SITUATION_STATES = LINK_STATES
|
||||||
|
|
||||||
|
# What a row names. `moment` — a catalog moment key: the lesson arrives when
|
||||||
|
# the work reaches it. `trigger` — a typed predicate on the act (tool, path,
|
||||||
|
# command, keyword), stored as `rule_field_judgments.trigger_value` writes it,
|
||||||
|
# so it is matched exactly as a rule's trigger is. `none` — the lesson was
|
||||||
|
# read and no situation fits it; it is reached by meaning alone, and the row
|
||||||
|
# keeps it out of the next pass's queue. CHECK ck_lesson_situations_kind.
|
||||||
|
MOMENT, TRIGGER, NONE = "moment", "trigger", "none"
|
||||||
|
KINDS = (MOMENT, TRIGGER, NONE)
|
||||||
|
|
||||||
|
# `pass` — an agent read the lesson and proposed; `edit` — a person set the
|
||||||
|
# lesson's situations directly. CHECK ck_lesson_situations_source.
|
||||||
|
SOURCES = ("pass", "edit")
|
||||||
|
|
||||||
|
|
||||||
|
class LessonSituation(Base, CreatedAtMixin):
|
||||||
|
"""When a lesson applies, as something the work can be checked against.
|
||||||
|
|
||||||
|
One row per (lesson, kind, value):
|
||||||
|
|
||||||
|
- ``suggested`` — proposed by a pass. Delivers nothing until judged.
|
||||||
|
- ``confirmed`` — the lesson arrives when this moment is reached or this
|
||||||
|
trigger matches the act, once per session.
|
||||||
|
- ``rejected`` — judged not to be when it applies, kept with the reason
|
||||||
|
so the same value is never proposed again.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "lesson_situations"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
|
lesson_id: Mapped[int] = mapped_column(
|
||||||
|
BigInteger, ForeignKey("notes.id", ondelete="CASCADE"), index=True,
|
||||||
|
)
|
||||||
|
kind: Mapped[str] = mapped_column(Text)
|
||||||
|
value: Mapped[str] = mapped_column(Text, default="", server_default="")
|
||||||
|
state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
|
||||||
|
source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
|
||||||
|
# For a suggestion, what the proposer read in the lesson; for a judgment,
|
||||||
|
# why it was confirmed or rejected.
|
||||||
|
note: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
judged_at: Mapped[datetime | None] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"lesson_id": self.lesson_id,
|
||||||
|
"kind": self.kind,
|
||||||
|
"value": self.value,
|
||||||
|
"state": self.state,
|
||||||
|
"source": self.source,
|
||||||
|
"note": self.note or "",
|
||||||
|
"judged_at": iso(self.judged_at),
|
||||||
|
"created_at": iso(self.created_at),
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, DateTime, Index, Text, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from grimoire.models import Base
|
||||||
|
from grimoire.models.base import iso
|
||||||
|
|
||||||
|
# How a record came to be in front of the session.
|
||||||
|
PUSHED = "pushed" # a hook put it there unasked (auto-inject, the write path, a slot)
|
||||||
|
ASKED = "asked" # it was a result of a search the session ran itself
|
||||||
|
DIRECT = "direct" # it was opened with nothing delivering it first in the session
|
||||||
|
POINTED = "pointed" # named by id in a pointer line, without its title or passage
|
||||||
|
WAYS = (PUSHED, POINTED, ASKED, DIRECT)
|
||||||
|
|
||||||
|
|
||||||
|
class RecordDelivery(Base):
|
||||||
|
"""One record put in front of one session, and whether it was opened.
|
||||||
|
|
||||||
|
The note-side twin of `rule_deliveries`, for every record kind that is not
|
||||||
|
a rule (note, snippet, issue, work task, lesson, process). It answers what
|
||||||
|
`note_usage_events` cannot: a pull there does not say which door led to
|
||||||
|
it, so "was this note opened because a hook pushed it, because the session
|
||||||
|
searched for it, or because the session went to it on its own" has no
|
||||||
|
answer. Here each line is a row against its session, and the open is
|
||||||
|
stamped on the row it followed.
|
||||||
|
|
||||||
|
`way` says how the record arrived (`pushed`, `asked`, `direct`). `source`
|
||||||
|
is the door: the hook arm (`auto_inject`, `write_path_semantic`,
|
||||||
|
`write_path_place`, `lesson_slot`, …), `mcp_search` for a search the
|
||||||
|
session ran, or `direct`. `kind` is the record's kind when it was
|
||||||
|
delivered (`snippet`, `note`, `lesson`, `process`, `task:issue`,
|
||||||
|
`task:work`, …), kept on the row so the readout needs no join and survives
|
||||||
|
the record's deletion.
|
||||||
|
|
||||||
|
A `direct` row is written when a session opens a record that nothing
|
||||||
|
delivered to it within the open window — found through a cross-reference,
|
||||||
|
a task's own id, the operator naming it. It is delivered and opened at the
|
||||||
|
same instant, and it is the measure of records a session reaches without
|
||||||
|
being shown them.
|
||||||
|
|
||||||
|
FK-free on `note_id` and `user_id`, like the other telemetry tables, and
|
||||||
|
pruned after `rule_deliveries.RETAIN_DAYS`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "record_deliveries"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
session_id: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
note_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
kind: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
way: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
source: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
delivered_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now(),
|
||||||
|
)
|
||||||
|
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
# Stamping an open: this session's latest delivery of this record.
|
||||||
|
Index("ix_record_deliveries_session_note", "user_id", "session_id", "note_id", "delivered_at"),
|
||||||
|
Index("ix_record_deliveries_delivered_at", "delivered_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"user_id": self.user_id,
|
||||||
|
"session_id": self.session_id,
|
||||||
|
"note_id": self.note_id,
|
||||||
|
"kind": self.kind,
|
||||||
|
"way": self.way,
|
||||||
|
"source": self.source,
|
||||||
|
"delivered_at": iso(self.delivered_at),
|
||||||
|
"opened_at": iso(self.opened_at),
|
||||||
|
"plugin": self.plugin,
|
||||||
|
}
|
||||||
@@ -74,6 +74,12 @@ class RetrievalLog(Base):
|
|||||||
# [{"id": int, "score": float, "rank": int}, ...], highest-first.
|
# [{"id": int, "score": float, "rank": int}, ...], highest-first.
|
||||||
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
||||||
duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True)
|
duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||||
|
# THE CUE-SWAP GATE, on a surface that has one (`cue_gate`): the score a
|
||||||
|
# line had to reach on this call, and how many lines reached it. Both null
|
||||||
|
# on an ungated surface. A count beside a null bar is a gate that had too
|
||||||
|
# few earlier cues to judge by, so nothing found by resemblance spoke.
|
||||||
|
gate_bar: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||||
|
gate_kept: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||||
|
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index("ix_retrieval_logs_created_at", "created_at"),
|
Index("ix_retrieval_logs_created_at", "created_at"),
|
||||||
@@ -99,4 +105,6 @@ class RetrievalLog(Base):
|
|||||||
"min_score": self.min_score,
|
"min_score": self.min_score,
|
||||||
"result_ids": self.result_ids,
|
"result_ids": self.result_ids,
|
||||||
"duration_ms": self.duration_ms,
|
"duration_ms": self.duration_ms,
|
||||||
|
"gate_bar": self.gate_bar,
|
||||||
|
"gate_kept": self.gate_kept,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, DateTime, Index, Text, UniqueConstraint, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from grimoire.models import Base
|
||||||
|
from grimoire.models.base import iso
|
||||||
|
|
||||||
|
# What happened to a rule that was in force at a moment of a session.
|
||||||
|
FOLLOWED = "followed"
|
||||||
|
DEPARTED = "departed"
|
||||||
|
BROKEN = "broken"
|
||||||
|
NOT_APPLICABLE = "not_applicable"
|
||||||
|
VERDICTS = (FOLLOWED, DEPARTED, BROKEN, NOT_APPLICABLE)
|
||||||
|
|
||||||
|
# Where the verdict came from.
|
||||||
|
REFUSED = "refused" # the act was refused by an `enforce` rule: kept by construction
|
||||||
|
OUTCOME = "outcome" # the session declared it with `rule_outcome`
|
||||||
|
MISFIRE = "misfire" # the session reported it with `rule_misfired`
|
||||||
|
JUDGE = "judge" # a review of the session's transcript
|
||||||
|
SOURCES = (REFUSED, OUTCOME, MISFIRE, JUDGE)
|
||||||
|
|
||||||
|
|
||||||
|
class RuleAdherence(Base):
|
||||||
|
"""Whether a rule in force at a moment of a session was followed there.
|
||||||
|
|
||||||
|
The unit is a rule delivered at one place (`at`: a moment such as
|
||||||
|
`work.deliver`, or an arm such as `pre_tool_rule`) in one session — the
|
||||||
|
same unit `rule_deliveries` records, so every verdict sits on a delivery
|
||||||
|
and the readout can put "followed" beside "delivered" and "opened". A
|
||||||
|
rule delivered ten times at one moment of one session gets one verdict:
|
||||||
|
it was followed there or it was not.
|
||||||
|
|
||||||
|
`verdict` is one of:
|
||||||
|
|
||||||
|
- `followed` — the work kept the rule;
|
||||||
|
- `departed` — the session read it and deliberately did not follow it,
|
||||||
|
with its reason in `evidence`. A departure is an answer, not a fault;
|
||||||
|
- `broken` — the work went against it with no stated reason;
|
||||||
|
- `not_applicable` — the rule arrived but did not bear on what the
|
||||||
|
session was doing there (a misfire).
|
||||||
|
|
||||||
|
`source` says how it is known, strongest first: `refused` (an `enforce`
|
||||||
|
rule refused the act, so the act did not happen), `outcome` and
|
||||||
|
`misfire` (the session said so in a tool call, watched by the plugin),
|
||||||
|
`judge` (a later review read the transcript). A `refused` verdict is a
|
||||||
|
fact and is never replaced; any other is replaced by a later one, so a
|
||||||
|
review can correct a session's own account.
|
||||||
|
|
||||||
|
FK-free on `rule_id` and `user_id` like the other telemetry tables, and
|
||||||
|
pruned with the deliveries it describes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "rule_adherence"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
session_id: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
rule_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
at: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
verdict: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
source: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
evidence: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
judged_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now(),
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("user_id", "session_id", "rule_id", "at",
|
||||||
|
name="uq_rule_adherence_session_rule_at"),
|
||||||
|
Index("ix_rule_adherence_rule_at", "rule_id", "at"),
|
||||||
|
Index("ix_rule_adherence_judged_at", "judged_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"user_id": self.user_id,
|
||||||
|
"session_id": self.session_id,
|
||||||
|
"rule_id": self.rule_id,
|
||||||
|
"at": self.at,
|
||||||
|
"verdict": self.verdict,
|
||||||
|
"source": self.source,
|
||||||
|
"evidence": self.evidence,
|
||||||
|
"judged_at": iso(self.judged_at),
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, DateTime, Index, Text, func
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from grimoire.models import Base
|
||||||
|
from grimoire.models.base import iso
|
||||||
|
|
||||||
|
FULL = "full"
|
||||||
|
REPEAT = "repeat"
|
||||||
|
FORMS = (FULL, REPEAT)
|
||||||
|
|
||||||
|
|
||||||
|
class RuleDelivery(Base):
|
||||||
|
"""One rule line put in front of one session, and whether it was opened after.
|
||||||
|
|
||||||
|
WHAT IT ANSWERS that `rule_usage_events` cannot. A surfaced event and a
|
||||||
|
pulled event are counted separately, so "was THIS delivery opened" has no
|
||||||
|
answer there: a rule opened once in a session reads as pulled whether it
|
||||||
|
was delivered once or twenty times. Here each delivery is a row, and the
|
||||||
|
open is stamped on the delivery it followed — so the open rate per rule,
|
||||||
|
per moment and per arm is a count of rows, and the ordering function reads
|
||||||
|
it as the rule's history at that moment. A delivery made to a session that
|
||||||
|
had already opened the rule is stamped as it is written, with its own
|
||||||
|
time: it reached a reader who had the rule.
|
||||||
|
|
||||||
|
`at` is where the rule was delivered: the moment it was mounted on
|
||||||
|
(`work.finish`) or the arm that found it (`pre_tool_rule`). `form` is
|
||||||
|
whether the line carried the rule's trigger (`full`) or only cited it
|
||||||
|
(`repeat`). Repeats are recorded too: they are deliveries a session can
|
||||||
|
open, and the case for retiring a rule rests on how rarely they are.
|
||||||
|
|
||||||
|
`plugin` is the version of the plugin that asked for the line, from the
|
||||||
|
request's `X-Grimoire-Plugin` header. Only a plugin that sends it reports
|
||||||
|
every open (`grimoire_record_opened.sh`), so a delivery without one was
|
||||||
|
made to a session whose opens never reach the server, and its unstamped
|
||||||
|
`opened_at` says nothing about whether it was read. The open-rate readers
|
||||||
|
count only deliveries that carry it. The server and the plugin ship on
|
||||||
|
different channels (the server from `dev`, the plugin from `main`, and a
|
||||||
|
running session keeps the plugin it started with), so rows from an older
|
||||||
|
plugin keep arriving for as long as such a session lives.
|
||||||
|
|
||||||
|
FK-free on `rule_id` and `user_id`, like the other telemetry tables: the
|
||||||
|
evidence that a rule was delivered forty times and opened never outlives
|
||||||
|
the rule, because it is the case for having deleted it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "rule_deliveries"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
session_id: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
rule_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||||
|
source: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
at: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
form: Mapped[str] = mapped_column(Text, nullable=False)
|
||||||
|
delivered_at: Mapped[datetime] = mapped_column(
|
||||||
|
DateTime(timezone=True), nullable=False, server_default=func.now(),
|
||||||
|
)
|
||||||
|
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
# Stamping an open: this session's latest delivery of this rule.
|
||||||
|
Index("ix_rule_deliveries_session_rule", "user_id", "session_id", "rule_id", "delivered_at"),
|
||||||
|
# History: a batch of rules at one moment.
|
||||||
|
Index("ix_rule_deliveries_rule_at", "rule_id", "at"),
|
||||||
|
Index("ix_rule_deliveries_delivered_at", "delivered_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"id": self.id,
|
||||||
|
"user_id": self.user_id,
|
||||||
|
"session_id": self.session_id,
|
||||||
|
"rule_id": self.rule_id,
|
||||||
|
"source": self.source,
|
||||||
|
"at": self.at,
|
||||||
|
"form": self.form,
|
||||||
|
"delivered_at": iso(self.delivered_at),
|
||||||
|
"opened_at": iso(self.opened_at),
|
||||||
|
"plugin": self.plugin,
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.dialects.postgresql import JSONB
|
||||||
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
|
from grimoire.models import Base
|
||||||
|
from grimoire.models.base import CreatedAtMixin, iso
|
||||||
|
from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"CONFIRMED", "ENFORCEMENT", "FIELDS", "REJECTED", "SALIENCE", "SUGGESTED",
|
||||||
|
"TRIGGER", "RuleFieldJudgment",
|
||||||
|
]
|
||||||
|
|
||||||
|
# The fields of a rule that decide how it arrives once it is reached: what it
|
||||||
|
# does (`enforcement`), how it ranks beside rules of the same force
|
||||||
|
# (`salience`), and the typed predicates that reach it (`trigger`).
|
||||||
|
ENFORCEMENT, SALIENCE, TRIGGER = "enforcement", "salience", "trigger"
|
||||||
|
FIELDS = (ENFORCEMENT, SALIENCE, TRIGGER)
|
||||||
|
|
||||||
|
|
||||||
|
class RuleFieldJudgment(Base, CreatedAtMixin):
|
||||||
|
"""A proposed or judged value for one of a rule's delivery fields.
|
||||||
|
|
||||||
|
The rule row holds the current value; this holds the reasoning behind it
|
||||||
|
and the values that were turned down. One row per (rule, field, value):
|
||||||
|
|
||||||
|
- ``suggested`` — a pass read the rule and its delivery history and
|
||||||
|
proposed this value. Changes nothing until a person confirms it.
|
||||||
|
- ``confirmed`` — the value was judged right. For a proposal equal to
|
||||||
|
what the rule already carries, the pass's agreement is recorded this way,
|
||||||
|
so a rule that was looked at and left alone does not read as one nobody
|
||||||
|
looked at.
|
||||||
|
- ``rejected`` — judged wrong, kept with its reason so it is never
|
||||||
|
proposed again.
|
||||||
|
|
||||||
|
`value` is the enforcement or salience name, or for a trigger
|
||||||
|
`kind<TAB>pattern<TAB>moment` — one string, so the pair is unique.
|
||||||
|
`evidence` is the delivery history the proposer read, as it stood then.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "rule_field_judgments"
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||||
|
rule_id: Mapped[int] = mapped_column(
|
||||||
|
BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), index=True,
|
||||||
|
)
|
||||||
|
field: Mapped[str] = mapped_column(Text)
|
||||||
|
value: Mapped[str] = mapped_column(Text)
|
||||||
|
state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
|
||||||
|
# `pass` — an agent proposed it; `edit` — a person set the field directly.
|
||||||
|
source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
|
||||||
|
note: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
|
evidence: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
|
||||||
|
judged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"rule_id": self.rule_id,
|
||||||
|
"field": self.field,
|
||||||
|
"value": self.value,
|
||||||
|
"state": self.state,
|
||||||
|
"source": self.source,
|
||||||
|
"note": self.note or "",
|
||||||
|
"evidence": self.evidence or {},
|
||||||
|
"judged_at": iso(self.judged_at),
|
||||||
|
"created_at": iso(self.created_at),
|
||||||
|
}
|
||||||
@@ -116,6 +116,15 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
|
|||||||
# Defaults to `rule` so nothing changes force on upgrade.
|
# Defaults to `rule` so nothing changes force on upgrade.
|
||||||
# CHECK ck_rules_kind (migration 0098).
|
# CHECK ck_rules_kind (migration 0098).
|
||||||
kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule")
|
kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule")
|
||||||
|
# WHAT THE RULE DOES WHEN IT ARRIVES, declared by its author rather than
|
||||||
|
# guessed from a score. `enforce`: the act it governs is checked. `hold`:
|
||||||
|
# the reply or act waits for one read of it. `inform`: a line beside the
|
||||||
|
# work, and never a stop. A preference is always `inform` (CHECK
|
||||||
|
# ck_rules_preference_informs). CHECK ck_rules_enforcement (migration 0128).
|
||||||
|
enforcement: Mapped[str] = mapped_column(Text, default="inform", server_default="inform")
|
||||||
|
# How this rule ranks among rules of the same enforcement when a moment has more
|
||||||
|
# to say than fits: `high`, `normal`, `low`. CHECK ck_rules_salience.
|
||||||
|
salience: Mapped[str] = mapped_column(Text, default="normal", server_default="normal")
|
||||||
why: Mapped[str | None] = mapped_column(Text, nullable=True)
|
why: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True)
|
how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||||
# The three fields that tell a CONSTRAINT apart from a NORM (milestone
|
# The three fields that tell a CONSTRAINT apart from a NORM (milestone
|
||||||
@@ -161,6 +170,8 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
|
|||||||
# codebase keeps re-encountering. Twenty bytes buys an answer that
|
# codebase keeps re-encountering. Twenty bytes buys an answer that
|
||||||
# cannot be misread.
|
# cannot be misread.
|
||||||
"kind": self.kind or "rule",
|
"kind": self.kind or "rule",
|
||||||
|
"enforcement": self.enforcement or "inform",
|
||||||
|
"salience": self.salience or "normal",
|
||||||
"why": self.why or "",
|
"why": self.why or "",
|
||||||
"how_to_apply": self.how_to_apply or "",
|
"how_to_apply": self.how_to_apply or "",
|
||||||
"verify_with": self.verify_with or "",
|
"verify_with": self.verify_with or "",
|
||||||
@@ -200,6 +211,22 @@ rule_moments = Table(
|
|||||||
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
|
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# What a rule is TRIGGERED by: a typed predicate on the act itself — the tool
|
||||||
|
# called, a path it touches, the head of a command it runs, or a word in what
|
||||||
|
# it writes — checked in code with no embedding (`services/rule_triggers.py`).
|
||||||
|
# `moment` empty means the trigger fires on any act that matches it; a moment
|
||||||
|
# name makes the rule's mount on that moment conditional on the act matching.
|
||||||
|
rule_triggers = Table(
|
||||||
|
"rule_triggers",
|
||||||
|
Base.metadata,
|
||||||
|
Column("rule_id", BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
|
||||||
|
Column("kind", Text, primary_key=True),
|
||||||
|
Column("pattern", Text, primary_key=True),
|
||||||
|
Column("moment", Text, primary_key=True, default="", server_default=""),
|
||||||
|
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
|
||||||
|
)
|
||||||
|
|
||||||
class RuleRelation(Base, CreatedAtMixin):
|
class RuleRelation(Base, CreatedAtMixin):
|
||||||
"""A typed edge between two rules. Each kind exists because without it a
|
"""A typed edge between two rules. Each kind exists because without it a
|
||||||
rulebook needs a workaround.
|
rulebook needs a workaround.
|
||||||
|
|||||||
+89
-5
@@ -7,9 +7,10 @@ X-Forwarded-Proto, and each proxy on the road APPENDS its entry, so only the
|
|||||||
right-hand end of either header was written by a proxy we trust. Anything to
|
right-hand end of either header was written by a proxy we trust. Anything to
|
||||||
the left of that is whatever the client chose to send.
|
the left of that is whatever the client chose to send.
|
||||||
|
|
||||||
`TRUSTED_PROXY_HOPS` says how many proxies stand in front of the app (default
|
The hop count says how many proxies stand in front of the app. An admin sets
|
||||||
1). The entry read is that many in from the right. Zero trusts no proxy: the
|
it in Settings → Config; until they do, it is `TRUSTED_PROXY_HOPS` from the
|
||||||
headers are ignored and the socket peer is the client.
|
environment (default 1). The entry read is that many in from the right. Zero
|
||||||
|
trusts no proxy: the headers are ignored and the socket peer is the client.
|
||||||
|
|
||||||
Never read X-Forwarded-For or X-Forwarded-Proto anywhere else. The client
|
Never read X-Forwarded-For or X-Forwarded-Proto anywhere else. The client
|
||||||
address keys the rate limits and the audit log, and the scheme decides the
|
address keys the rate limits and the audit log, and the scheme decides the
|
||||||
@@ -43,10 +44,36 @@ def trusted_entry(header: str, hops: int) -> str | None:
|
|||||||
return entries[-min(hops, len(entries))]
|
return entries[-min(hops, len(entries))]
|
||||||
|
|
||||||
|
|
||||||
def _forwarded(name: str) -> str | None:
|
# The count saved in Settings, or None when none is saved. Held here because
|
||||||
|
# every request reads it and the read is synchronous; services/proxy_settings
|
||||||
|
# loads it at startup, refreshes it on an interval in every worker, and sets it
|
||||||
|
# at once in the worker that saved a new one.
|
||||||
|
_saved_hops: int | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def set_saved_hops(hops: int | None) -> None:
|
||||||
|
global _saved_hops
|
||||||
|
_saved_hops = hops
|
||||||
|
|
||||||
|
|
||||||
|
def saved_hops_in_force() -> int | None:
|
||||||
|
"""The count saved in Settings that this worker holds, or None."""
|
||||||
|
return _saved_hops
|
||||||
|
|
||||||
|
|
||||||
|
def trusted_hops() -> int:
|
||||||
|
"""The hop count in force: the one saved in Settings, else the env's."""
|
||||||
|
return Config.TRUSTED_PROXY_HOPS if _saved_hops is None else _saved_hops
|
||||||
|
|
||||||
|
|
||||||
|
def _chain(name: str) -> str:
|
||||||
# Joined, because a header sent twice arrives as two values, and each
|
# Joined, because a header sent twice arrives as two values, and each
|
||||||
# proxy's append may land on either one.
|
# proxy's append may land on either one.
|
||||||
return trusted_entry(",".join(request.headers.getlist(name)), Config.TRUSTED_PROXY_HOPS)
|
return ",".join(request.headers.getlist(name))
|
||||||
|
|
||||||
|
|
||||||
|
def _forwarded(name: str) -> str | None:
|
||||||
|
return trusted_entry(_chain(name), trusted_hops())
|
||||||
|
|
||||||
|
|
||||||
def client_ip() -> str:
|
def client_ip() -> str:
|
||||||
@@ -78,3 +105,60 @@ def apply_https_headers(response) -> None:
|
|||||||
HTTPS; plain HTTP is a supported way to run it."""
|
HTTPS; plain HTTP is a supported way to run it."""
|
||||||
if is_https():
|
if is_https():
|
||||||
response.headers.setdefault("Strict-Transport-Security", HSTS_VALUE)
|
response.headers.setdefault("Strict-Transport-Security", HSTS_VALUE)
|
||||||
|
|
||||||
|
|
||||||
|
# Cloudflare writes the visitor's address here on every request it proxies.
|
||||||
|
# Read only to SUGGEST a hop count in the readout, never to decide one: a
|
||||||
|
# client that reaches the app without Cloudflare can send it too.
|
||||||
|
CLOUDFLARE_CLIENT_HEADER = "CF-Connecting-IP"
|
||||||
|
CLOUDFLARE_MARKERS = (CLOUDFLARE_CLIENT_HEADER, "CF-Ray")
|
||||||
|
READOUT_HOPS = range(0, 4)
|
||||||
|
MAX_HOPS = 5
|
||||||
|
|
||||||
|
|
||||||
|
def readout(peer: str, forwarded_for: str, forwarded_proto: str,
|
||||||
|
cloudflare_client: str | None, scheme: str = "http") -> dict:
|
||||||
|
"""What each hop count would make of one request, so an admin can pick
|
||||||
|
the count that shows their own address. Pure: the request's parts come in
|
||||||
|
as arguments.
|
||||||
|
|
||||||
|
`suggested` is the smallest count that reads the address Cloudflare
|
||||||
|
reports, when the request came through Cloudflare; otherwise None, since
|
||||||
|
only the admin knows which address is theirs.
|
||||||
|
"""
|
||||||
|
def read(hops: int) -> dict:
|
||||||
|
address = trusted_entry(forwarded_for, hops) or peer
|
||||||
|
proto = trusted_entry(forwarded_proto, hops)
|
||||||
|
https = scheme == "https" or (proto or "").lower() == "https"
|
||||||
|
return {"hops": hops, "client": address, "https": https}
|
||||||
|
|
||||||
|
suggested = None
|
||||||
|
if cloudflare_client:
|
||||||
|
suggested = next(
|
||||||
|
(h for h in range(1, MAX_HOPS + 1)
|
||||||
|
if trusted_entry(forwarded_for, h) == cloudflare_client),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"peer": peer,
|
||||||
|
"forwarded_for": [p.strip() for p in forwarded_for.split(",") if p.strip()],
|
||||||
|
"forwarded_proto": [p.strip() for p in forwarded_proto.split(",") if p.strip()],
|
||||||
|
"cloudflare": cloudflare_client is not None,
|
||||||
|
"cloudflare_client": cloudflare_client,
|
||||||
|
"rows": [read(h) for h in READOUT_HOPS],
|
||||||
|
"suggested": suggested,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def request_readout() -> dict:
|
||||||
|
"""`readout` for the current request."""
|
||||||
|
cloudflare = request.headers.get(CLOUDFLARE_CLIENT_HEADER)
|
||||||
|
if cloudflare is None and request.headers.get("CF-Ray"):
|
||||||
|
cloudflare = ""
|
||||||
|
return readout(
|
||||||
|
request.remote_addr or "",
|
||||||
|
_chain("X-Forwarded-For"),
|
||||||
|
_chain("X-Forwarded-Proto"),
|
||||||
|
cloudflare.strip() if cloudflare is not None else None,
|
||||||
|
request.scheme,
|
||||||
|
)
|
||||||
|
|||||||
@@ -2,15 +2,23 @@
|
|||||||
|
|
||||||
IMPORTANT — deployment note:
|
IMPORTANT — deployment note:
|
||||||
Rate limit counters are stored in memory and are lost on process restart.
|
Rate limit counters are stored in memory and are lost on process restart.
|
||||||
The bucket key is the client address from grimoire/proxy.py, read by
|
The bucket key is the client address from grimoire/proxy.py, read by the
|
||||||
TRUSTED_PROXY_HOPS. A hop count that is too low keys every caller on the
|
proxy hop count (Settings → Config). A count that is too low keys every
|
||||||
proxy's address, so they all share one bucket.
|
caller on the proxy's address, so they all share one bucket.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import time
|
import time
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
|
|
||||||
|
# Said beside every "too many attempts" reply, because the one case a person
|
||||||
|
# can't diagnose on their own is everybody being blocked at once: the proxy
|
||||||
|
# count is too low, so every visitor reads as the proxy and shares one bucket.
|
||||||
|
SHARED_ADDRESS_HINT = (
|
||||||
|
"If everyone is being blocked, an admin should check the reverse proxy count "
|
||||||
|
"in Settings → Config: every visitor may be reading as the proxy's address."
|
||||||
|
)
|
||||||
|
|
||||||
_buckets: dict[str, list[float]] = defaultdict(list)
|
_buckets: dict[str, list[float]] = defaultdict(list)
|
||||||
_lock = asyncio.Lock()
|
_lock = asyncio.Lock()
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,11 @@ import json
|
|||||||
|
|
||||||
from quart import Blueprint, Response, g, jsonify, request
|
from quart import Blueprint, Response, g, jsonify, request
|
||||||
|
|
||||||
|
from grimoire import proxy
|
||||||
from grimoire.auth import admin_required, login_required, get_current_user_id
|
from grimoire.auth import admin_required, login_required, get_current_user_id
|
||||||
|
from grimoire.config import Config
|
||||||
from grimoire.proxy import client_ip
|
from grimoire.proxy import client_ip
|
||||||
|
from grimoire.services import proxy_settings
|
||||||
from grimoire.services.auth import (
|
from grimoire.services.auth import (
|
||||||
create_invitation,
|
create_invitation,
|
||||||
delete_user,
|
delete_user,
|
||||||
@@ -260,7 +263,6 @@ async def test_smtp():
|
|||||||
@admin_bp.route("/forge-webhook", methods=["GET"])
|
@admin_bp.route("/forge-webhook", methods=["GET"])
|
||||||
@admin_required
|
@admin_required
|
||||||
async def get_forge_webhook_settings():
|
async def get_forge_webhook_settings():
|
||||||
from grimoire.config import Config
|
|
||||||
from grimoire.routes.webhooks import FORGE_WEBHOOK_SECRET_KEY
|
from grimoire.routes.webhooks import FORGE_WEBHOOK_SECRET_KEY
|
||||||
|
|
||||||
webhook_secret = (
|
webhook_secret = (
|
||||||
@@ -346,6 +348,44 @@ async def update_base_url():
|
|||||||
return jsonify({"status": "ok"})
|
return jsonify({"status": "ok"})
|
||||||
|
|
||||||
|
|
||||||
|
def _proxy_payload() -> dict:
|
||||||
|
return {
|
||||||
|
"hops": proxy.trusted_hops(),
|
||||||
|
"source": proxy_settings.source(),
|
||||||
|
"env_hops": Config.TRUSTED_PROXY_HOPS,
|
||||||
|
"max_hops": proxy.MAX_HOPS,
|
||||||
|
"readout": proxy.request_readout(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route("/proxy", methods=["GET"])
|
||||||
|
@admin_required
|
||||||
|
async def get_proxy_setting():
|
||||||
|
"""The hop count in force, where it came from, and what each count would
|
||||||
|
make of the admin's own request."""
|
||||||
|
return jsonify(_proxy_payload())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route("/proxy", methods=["PUT"])
|
||||||
|
@admin_required
|
||||||
|
async def update_proxy_setting():
|
||||||
|
"""Save the hop count, or `{"hops": null}` to go back to the environment's.
|
||||||
|
It applies to the next request."""
|
||||||
|
data = await request.get_json() or {}
|
||||||
|
raw = data.get("hops")
|
||||||
|
hops = None if raw is None else proxy_settings.parse_hops(raw)
|
||||||
|
if raw is not None and hops is None:
|
||||||
|
return jsonify({"error": f"The proxy count must be a whole number from 0 to {proxy.MAX_HOPS}."}), 400
|
||||||
|
before = proxy.trusted_hops()
|
||||||
|
await proxy_settings.save_hops(hops)
|
||||||
|
uid = get_current_user_id()
|
||||||
|
await log_audit(
|
||||||
|
"proxy_hops_config", user_id=uid, username=g.user.username, ip_address=client_ip(),
|
||||||
|
details={"before": before, "after": proxy.trusted_hops(), "saved": hops},
|
||||||
|
)
|
||||||
|
return jsonify(_proxy_payload())
|
||||||
|
|
||||||
|
|
||||||
@admin_bp.route("/db-maintenance", methods=["GET"])
|
@admin_bp.route("/db-maintenance", methods=["GET"])
|
||||||
@admin_required
|
@admin_required
|
||||||
async def get_db_maintenance():
|
async def get_db_maintenance():
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ from quart import Blueprint, g, jsonify, redirect, request, session
|
|||||||
from grimoire.auth import login_required, get_current_user_id
|
from grimoire.auth import login_required, get_current_user_id
|
||||||
from grimoire.config import Config
|
from grimoire.config import Config
|
||||||
from grimoire.proxy import client_ip
|
from grimoire.proxy import client_ip
|
||||||
from grimoire.rate_limit import is_rate_limited
|
from grimoire.rate_limit import SHARED_ADDRESS_HINT, is_rate_limited
|
||||||
from grimoire.services.auth import (
|
from grimoire.services.auth import (
|
||||||
authenticate,
|
authenticate,
|
||||||
change_password,
|
change_password,
|
||||||
@@ -49,7 +49,7 @@ async def register():
|
|||||||
if not Config.LOCAL_AUTH_ENABLED:
|
if not Config.LOCAL_AUTH_ENABLED:
|
||||||
return jsonify({"error": "Local authentication is disabled. Please use SSO."}), 403
|
return jsonify({"error": "Local authentication is disabled. Please use SSO."}), 403
|
||||||
if await is_rate_limited(f"register:{client_ip()}", max_requests=5, window_seconds=300):
|
if await is_rate_limited(f"register:{client_ip()}", max_requests=5, window_seconds=300):
|
||||||
return jsonify({"error": "Too many registration attempts. Try again later."}), 429
|
return jsonify({"error": f"Too many registration attempts. Try again later. {SHARED_ADDRESS_HINT}"}), 429
|
||||||
if not await is_registration_open():
|
if not await is_registration_open():
|
||||||
return jsonify({"error": "Registration is closed"}), 403
|
return jsonify({"error": "Registration is closed"}), 403
|
||||||
|
|
||||||
@@ -79,7 +79,7 @@ async def login():
|
|||||||
if not Config.LOCAL_AUTH_ENABLED:
|
if not Config.LOCAL_AUTH_ENABLED:
|
||||||
return jsonify({"error": "Local authentication is disabled. Please use SSO."}), 403
|
return jsonify({"error": "Local authentication is disabled. Please use SSO."}), 403
|
||||||
if await is_rate_limited(f"login:{client_ip()}", max_requests=10, window_seconds=60):
|
if await is_rate_limited(f"login:{client_ip()}", max_requests=10, window_seconds=60):
|
||||||
return jsonify({"error": "Too many login attempts. Try again later."}), 429
|
return jsonify({"error": f"Too many login attempts. Try again later. {SHARED_ADDRESS_HINT}"}), 429
|
||||||
data = await request.get_json()
|
data = await request.get_json()
|
||||||
username = (data.get("username") or "").strip()
|
username = (data.get("username") or "").strip()
|
||||||
password = data.get("password") or ""
|
password = data.get("password") or ""
|
||||||
@@ -235,7 +235,7 @@ async def forgot_password():
|
|||||||
@auth_bp.route("/reset-password", methods=["POST"])
|
@auth_bp.route("/reset-password", methods=["POST"])
|
||||||
async def reset_password():
|
async def reset_password():
|
||||||
if await is_rate_limited(f"reset:{client_ip()}", max_requests=10, window_seconds=60):
|
if await is_rate_limited(f"reset:{client_ip()}", max_requests=10, window_seconds=60):
|
||||||
return jsonify({"error": "Too many attempts. Try again later."}), 429
|
return jsonify({"error": f"Too many attempts. Try again later. {SHARED_ADDRESS_HINT}"}), 429
|
||||||
data = await request.get_json()
|
data = await request.get_json()
|
||||||
token = (data.get("token") or "").strip()
|
token = (data.get("token") or "").strip()
|
||||||
new_password = data.get("new_password") or ""
|
new_password = data.get("new_password") or ""
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ from grimoire.routes.utils import not_found, parse_pagination
|
|||||||
from grimoire.services import dedup as dedup_svc
|
from grimoire.services import dedup as dedup_svc
|
||||||
from grimoire.services import knowledge as knowledge_svc
|
from grimoire.services import knowledge as knowledge_svc
|
||||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
from grimoire.services import lesson_rules as lesson_rules_svc
|
||||||
|
from grimoire.services import lesson_situations as lesson_situations_svc
|
||||||
from grimoire.services import lessons as lessons_svc
|
from grimoire.services import lessons as lessons_svc
|
||||||
from grimoire.services import systems as systems_svc
|
from grimoire.services import systems as systems_svc
|
||||||
from grimoire.services import trash as trash_svc
|
from grimoire.services import trash as trash_svc
|
||||||
@@ -358,6 +359,78 @@ async def judge_lesson_link_route(lesson_id: int, rule_id: int):
|
|||||||
return jsonify(link)
|
return jsonify(link)
|
||||||
|
|
||||||
|
|
||||||
|
# ── when a lesson applies (services/lesson_situations.py) ───────────────────
|
||||||
|
|
||||||
|
|
||||||
|
@lessons_bp.route("/situations/proposals", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def lesson_situation_proposals_route():
|
||||||
|
"""The situations a pass proposed and a person has not judged, grouped
|
||||||
|
by lesson, with how many lessons are situated, have none, or are unread
|
||||||
|
— `lesson_situation_proposals` from the browser."""
|
||||||
|
uid = get_current_user_id()
|
||||||
|
out = await lesson_situations_svc.pending(uid)
|
||||||
|
out["counts"] = await lesson_situations_svc.counts(uid)
|
||||||
|
return jsonify(out)
|
||||||
|
|
||||||
|
|
||||||
|
@lessons_bp.route("/situations/judge", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
async def judge_lesson_situations_route():
|
||||||
|
"""Confirm or reject proposals: `{"judgments": [{id, verdict, note}]}`.
|
||||||
|
A confirm changes what reaches the user's sessions."""
|
||||||
|
data = await request.get_json(silent=True)
|
||||||
|
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
|
||||||
|
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
|
||||||
|
try:
|
||||||
|
return jsonify(await lesson_situations_svc.judge(get_current_user_id(), data["judgments"]))
|
||||||
|
except ValueError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 400
|
||||||
|
|
||||||
|
|
||||||
|
@lessons_bp.route("/<int:lesson_id>/situations", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def lesson_situations_route(lesson_id: int):
|
||||||
|
"""A lesson's live situations and waiting proposals, with the moment
|
||||||
|
catalog and trigger kinds its page offers for adding one."""
|
||||||
|
from grimoire.services import moments as moments_svc
|
||||||
|
from grimoire.services import rule_triggers
|
||||||
|
|
||||||
|
return jsonify({
|
||||||
|
"situations": await lesson_situations_svc.for_lesson(get_current_user_id(), lesson_id),
|
||||||
|
"catalog": [{"name": m["name"], "means": m["means"]}
|
||||||
|
for m in moments_svc.catalog()["moments"]],
|
||||||
|
"trigger_kinds": list(rule_triggers.KINDS),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@lessons_bp.route("/<int:lesson_id>/situations", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
async def add_lesson_situation_route(lesson_id: int):
|
||||||
|
"""Make one situation live on a lesson. Body: `{"moment": "work.deliver"}`
|
||||||
|
or `{"trigger": {"kind", "pattern"}}`."""
|
||||||
|
data = await request.get_json(silent=True) or {}
|
||||||
|
trigger = data.get("trigger") if isinstance(data, dict) else None
|
||||||
|
try:
|
||||||
|
return jsonify(await lesson_situations_svc.add(
|
||||||
|
get_current_user_id(), lesson_id,
|
||||||
|
moment=str(data.get("moment") or "") if isinstance(data, dict) else "",
|
||||||
|
trigger=trigger if isinstance(trigger, dict) else None,
|
||||||
|
)), 201
|
||||||
|
except ValueError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 400
|
||||||
|
|
||||||
|
|
||||||
|
@lessons_bp.route("/situations/<int:situation_id>", methods=["DELETE"])
|
||||||
|
@login_required
|
||||||
|
async def remove_lesson_situation_route(situation_id: int):
|
||||||
|
"""Take a situation off its lesson; kept as rejected so it is not proposed again."""
|
||||||
|
try:
|
||||||
|
return jsonify(await lesson_situations_svc.remove(get_current_user_id(), situation_id))
|
||||||
|
except ValueError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 400
|
||||||
|
|
||||||
|
|
||||||
@lessons_bp.route("/<int:lesson_id>", methods=["DELETE"])
|
@lessons_bp.route("/<int:lesson_id>", methods=["DELETE"])
|
||||||
@login_required
|
@login_required
|
||||||
async def delete_lesson_route(lesson_id: int):
|
async def delete_lesson_route(lesson_id: int):
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from quart import Blueprint, jsonify, request
|
|||||||
|
|
||||||
from grimoire.auth import login_required, get_current_user_id
|
from grimoire.auth import login_required, get_current_user_id
|
||||||
from grimoire.routes.utils import not_found, parse_iso_date, parse_pagination
|
from grimoire.routes.utils import not_found, parse_iso_date, parse_pagination
|
||||||
|
from grimoire.services import record_refs
|
||||||
from grimoire.services.access import can_write_note
|
from grimoire.services.access import can_write_note
|
||||||
from grimoire.services.notes import (
|
from grimoire.services.notes import (
|
||||||
build_note_graph,
|
build_note_graph,
|
||||||
@@ -194,6 +195,37 @@ async def resolve_title_route():
|
|||||||
return jsonify(note.to_dict())
|
return jsonify(note.to_dict())
|
||||||
|
|
||||||
|
|
||||||
|
@notes_bp.route("/resolve-refs", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
async def resolve_refs_route():
|
||||||
|
"""What the record references in a rendered body point at.
|
||||||
|
|
||||||
|
Body: {"notes": [ids], "milestones": [ids], "rules": [ids]}. Answers the
|
||||||
|
same three keys, each a map of id -> {title, kind fields}, holding only the
|
||||||
|
records the caller may read. An id left out of the answer is drawn as a
|
||||||
|
reference that leads nowhere. The web UI calls this once per rendered body
|
||||||
|
to give each `#N`, `milestone N` and `rule N` link its route and its title.
|
||||||
|
"""
|
||||||
|
uid = get_current_user_id()
|
||||||
|
data = await request.get_json(silent=True) or {}
|
||||||
|
spaces: dict[str, list[int]] = {}
|
||||||
|
for key in ("notes", "milestones", "rules"):
|
||||||
|
raw = data.get(key) or []
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
return jsonify({"error": f"{key} must be a list of ids"}), 400
|
||||||
|
try:
|
||||||
|
spaces[key] = [int(i) for i in raw]
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return jsonify({"error": f"{key} must be a list of ids"}), 400
|
||||||
|
if sum(len(v) for v in spaces.values()) > record_refs.RESOLVE_LIMIT:
|
||||||
|
return jsonify({
|
||||||
|
"error": f"at most {record_refs.RESOLVE_LIMIT} references per call",
|
||||||
|
}), 400
|
||||||
|
resolved = await record_refs.resolve_refs(uid, **spaces)
|
||||||
|
# JSON object keys are strings; say so here rather than in every caller.
|
||||||
|
return jsonify({k: {str(i): v for i, v in m.items()} for k, m in resolved.items()})
|
||||||
|
|
||||||
|
|
||||||
@notes_bp.route("/duplicates", methods=["GET"])
|
@notes_bp.route("/duplicates", methods=["GET"])
|
||||||
@login_required
|
@login_required
|
||||||
async def find_duplicate_records_route():
|
async def find_duplicate_records_route():
|
||||||
|
|||||||
+226
-31
@@ -14,12 +14,15 @@ from quart import Blueprint, g, jsonify, request
|
|||||||
|
|
||||||
from grimoire.auth import admin_required, get_current_user_id, login_required
|
from grimoire.auth import admin_required, get_current_user_id, login_required
|
||||||
from grimoire.config import Config
|
from grimoire.config import Config
|
||||||
from grimoire.services import lesson_rules as lesson_rules_svc
|
from grimoire.services import hook_payload as hook_payload_svc
|
||||||
from grimoire.services import moment_delivery as moment_delivery_svc
|
from grimoire.services import moment_delivery as moment_delivery_svc
|
||||||
from grimoire.services import plugin_context as plugin_ctx_svc
|
from grimoire.services import plugin_context as plugin_ctx_svc
|
||||||
from grimoire.services import reply_shapes as reply_shapes_svc
|
from grimoire.services import reply_shapes as reply_shapes_svc
|
||||||
from grimoire.services import repo_bindings as repo_bindings_svc
|
from grimoire.services import repo_bindings as repo_bindings_svc
|
||||||
|
from grimoire.services import rule_adherence as rule_adherence_svc
|
||||||
from grimoire.services import report_check as report_check_svc
|
from grimoire.services import report_check as report_check_svc
|
||||||
|
from grimoire.services import record_deliveries as record_deliveries_svc
|
||||||
|
from grimoire.services import rule_deliveries as rule_deliveries_svc
|
||||||
from grimoire.services import rule_moment_judgments as judgments_svc
|
from grimoire.services import rule_moment_judgments as judgments_svc
|
||||||
from grimoire.services import shape_check as shape_check_svc
|
from grimoire.services import shape_check as shape_check_svc
|
||||||
from grimoire.services import task_claims as task_claims_svc
|
from grimoire.services import task_claims as task_claims_svc
|
||||||
@@ -36,6 +39,38 @@ plugin_bp = Blueprint("plugin", __name__, url_prefix="/api/plugin")
|
|||||||
_MARKETPLACE_KEY = "plugin_marketplace_url"
|
_MARKETPLACE_KEY = "plugin_marketplace_url"
|
||||||
|
|
||||||
|
|
||||||
|
@plugin_bp.before_request
|
||||||
|
async def _bind_delivery_session() -> None:
|
||||||
|
"""Bind the session this request delivers to, for the delivery record.
|
||||||
|
|
||||||
|
A hook names it as `session_id` in the query, or carries it in the event
|
||||||
|
it posts (`/moment` sends the PreToolUse event whole). A request that
|
||||||
|
names none records no deliveries and reads no delivery history. The
|
||||||
|
plugin's version comes in the `X-Grimoire-Plugin` header and is kept on
|
||||||
|
each delivery, which is how the open-rate readers tell a session that
|
||||||
|
did not open a rule from one whose plugin never said.
|
||||||
|
"""
|
||||||
|
sid = request.args.get("session_id") or ""
|
||||||
|
if not sid and request.method == "POST":
|
||||||
|
body = await request.get_json(silent=True)
|
||||||
|
if isinstance(body, dict):
|
||||||
|
sid = str(body.get("session_id") or "")
|
||||||
|
rule_deliveries_svc.bind_session(sid, request.headers.get("X-Grimoire-Plugin"))
|
||||||
|
|
||||||
|
|
||||||
|
@plugin_bp.after_request
|
||||||
|
async def _flush_deliveries(response):
|
||||||
|
"""Write any rule and record deliveries a door rendered without fitting a
|
||||||
|
payload.
|
||||||
|
|
||||||
|
A door that fits its payload (`hook_payload.fit`) has already written the
|
||||||
|
lines it kept and dropped the rest, so this finds nothing left for it.
|
||||||
|
"""
|
||||||
|
rule_deliveries_svc.flush()
|
||||||
|
record_deliveries_svc.flush()
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
def _int_list(raw: str | None) -> list[int]:
|
def _int_list(raw: str | None) -> list[int]:
|
||||||
"""A comma-separated id list from the query string; non-ints dropped."""
|
"""A comma-separated id list from the query string; non-ints dropped."""
|
||||||
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
|
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
|
||||||
@@ -94,6 +129,11 @@ async def session_context():
|
|||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
# The longest carried note a prompt takes: the shape check's note names a
|
||||||
|
# few definitions and the call that lists the rest.
|
||||||
|
_CARRY_CHARS = 3000
|
||||||
|
|
||||||
|
|
||||||
@plugin_bp.get("/retrieve")
|
@plugin_bp.get("/retrieve")
|
||||||
@login_required
|
@login_required
|
||||||
@memoized_query_embeddings
|
@memoized_query_embeddings
|
||||||
@@ -137,11 +177,17 @@ async def autoinject_retrieve():
|
|||||||
one-line reminder when present; the hook's
|
one-line reminder when present; the hook's
|
||||||
ledger is swept on compaction, which is how the
|
ledger is swept on compaction, which is how the
|
||||||
full core comes back after one.
|
full core comes back after one.
|
||||||
|
carry (opt) — a note the session's last stop left for this
|
||||||
|
prompt: the definitions its turn wrote that
|
||||||
|
nobody has judged (/shape-check's `note`).
|
||||||
|
Fitted after the reply shape, before the records.
|
||||||
|
|
||||||
THE TURN'S REPLY SHAPE COMES FIRST. Every turn ends
|
ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules
|
||||||
in a reply and this is the last point before it is written, so the core
|
this prompt reaches and those mounted on `reply.report`, then the turn's
|
||||||
shape and whatever is mounted on `reply.report` lead the payload. Fresh
|
reply shape, then the records menu. Every turn ends in a reply and this
|
||||||
shape keys come back as `shape_keys` for the ledger.
|
is the last point before it is written, so the shape rides every call;
|
||||||
|
what does not fit is left off the ledgers and can arrive on a later call.
|
||||||
|
Shape keys sent in full come back as `shape_keys` for the ledger.
|
||||||
|
|
||||||
TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query
|
TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query
|
||||||
but nothing else: the notes menu can be disabled, thresholded and top-k'd
|
but nothing else: the notes menu can be disabled, thresholded and top-k'd
|
||||||
@@ -168,13 +214,6 @@ async def autoinject_retrieve():
|
|||||||
result = await plugin_ctx_svc.build_autoinject_hint(
|
result = await plugin_ctx_svc.build_autoinject_hint(
|
||||||
g.user.id, q, project_id=project_id, exclude_ids=exclude_ids, context=ctx,
|
g.user.id, q, project_id=project_id, exclude_ids=exclude_ids, context=ctx,
|
||||||
)
|
)
|
||||||
# The one place both arms' lines meet, so the one place a lesson and a
|
|
||||||
# rule arriving TOGETHER can be counted. Keyed on the operator's
|
|
||||||
# prompt — the situation — and fails open to "".
|
|
||||||
proposal = await lesson_rules_svc.co_surfaced(
|
|
||||||
g.user.id, result.get("lesson_ids") or [], rules.get("shown_rule_ids") or [],
|
|
||||||
arm="p", situation=q, project_id=project_id or None,
|
|
||||||
)
|
|
||||||
# The reply mounts go through the same rule ledger; a rule the prompt arm
|
# The reply mounts go through the same rule ledger; a rule the prompt arm
|
||||||
# just named is not quoted a second time by the turn's delivery.
|
# just named is not quoted a second time by the turn's delivery.
|
||||||
turn = await moment_delivery_svc.deliver_for_turn(
|
turn = await moment_delivery_svc.deliver_for_turn(
|
||||||
@@ -182,12 +221,34 @@ async def autoinject_retrieve():
|
|||||||
project_id=project_id,
|
project_id=project_id,
|
||||||
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
|
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
|
||||||
held=frozenset(held_rule_ids),
|
held=frozenset(held_rule_ids),
|
||||||
|
record=False,
|
||||||
)
|
)
|
||||||
blocks = [b for b in (turn["context"], rules["context"], result["context"], proposal) if b]
|
# One payload, in the one order: the rules, then the reply shape, then
|
||||||
result["context"] = "\n\n".join(blocks)
|
# what the last turn left unjudged, then the records menu, fitted to the
|
||||||
result["rule_ids"] = list(dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]))
|
# budget.
|
||||||
result["shape_keys"] = [k for k, form in turn["shape_forms"].items()
|
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
|
||||||
if form == reply_shapes_svc.FULL]
|
turn_parts = (
|
||||||
|
[*turn["rule_parts"], *turn["shape_parts"]] if "shape_parts" in turn
|
||||||
|
else [hook_payload_svc.Part(text=turn.get("context") or "", ids={
|
||||||
|
hook_payload_svc.RULE: tuple(turn.get("rule_ids") or ()),
|
||||||
|
hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()),
|
||||||
|
})]
|
||||||
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, [
|
||||||
|
*hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}),
|
||||||
|
*turn_parts,
|
||||||
|
*([hook_payload_svc.Part(text=carry)] if carry else []),
|
||||||
|
*hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}),
|
||||||
|
])
|
||||||
|
shapes = set(fitted.ids(hook_payload_svc.SHAPE))
|
||||||
|
forms = {k: f for k, f in turn["shape_forms"].items() if k in shapes}
|
||||||
|
await reply_shapes_svc.record_delivery(g.user.id, forms, via="turn")
|
||||||
|
result["context"] = fitted.context
|
||||||
|
result["note_ids"] = fitted.keep_only(hook_payload_svc.NOTE, result.get("note_ids"))
|
||||||
|
result["rule_ids"] = fitted.keep_only(
|
||||||
|
hook_payload_svc.RULE, dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]),
|
||||||
|
)
|
||||||
|
result["shape_keys"] = [k for k, form in forms.items() if form == reply_shapes_svc.FULL]
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@@ -265,6 +326,15 @@ async def pre_tool_rules():
|
|||||||
cwd=(request.args.get("cwd") or "").strip(),
|
cwd=(request.args.get("cwd") or "").strip(),
|
||||||
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
||||||
)
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, {
|
||||||
|
hook_payload_svc.RULE: "rule_ids", hook_payload_svc.RULING: "ruling_system_ids",
|
||||||
|
}))
|
||||||
|
result["context"] = fitted.context
|
||||||
|
result["rule_ids"] = fitted.keep_only(hook_payload_svc.RULE, result.get("rule_ids"))
|
||||||
|
if "ruling_system_ids" in result:
|
||||||
|
result["ruling_system_ids"] = fitted.keep_only(
|
||||||
|
hook_payload_svc.RULING, result["ruling_system_ids"],
|
||||||
|
)
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@@ -301,15 +371,24 @@ async def moment():
|
|||||||
`moments` (the names reached). A lookup, not a ranked search: no
|
`moments` (the names reached). A lookup, not a ranked search: no
|
||||||
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
|
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
|
||||||
|
|
||||||
A moment that carries a default reply shape brings it too,
|
A moment that carries a default reply shape brings it too, after the
|
||||||
ahead of the rules: in full unless `shapes_seen` names it, then as its
|
rules: in full unless `shapes_seen` names it, then as its reminder. The
|
||||||
reminder. `shape_keys` are the ones sent in full, for the hook's ledger.
|
payload is fitted to the user's budget (`hook_payload`), and `shape_keys`
|
||||||
|
are the ones sent in full and kept, for the hook's ledger.
|
||||||
|
|
||||||
|
`decision` is the answer for the act itself (`retrieval_pipeline.
|
||||||
|
act_decision`): `{}` when it goes ahead; `kind: "enforce"` when a rule set
|
||||||
|
to enforce refuses it — the hook denies the call with `reason`, every
|
||||||
|
time; `kind: "hold"` when an unopened rule set to hold asks for one read
|
||||||
|
first — the hook denies once per rule and session, under the act
|
||||||
|
checkpoint's cap. A write is never held, only refused.
|
||||||
"""
|
"""
|
||||||
event = await request.get_json(silent=True) or {}
|
event = await request.get_json(silent=True) or {}
|
||||||
tool = str(event.get("tool_name") or "").strip()
|
tool = str(event.get("tool_name") or "").strip()
|
||||||
tool_input = event.get("tool_input")
|
tool_input = event.get("tool_input")
|
||||||
if not tool:
|
if not tool:
|
||||||
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": []})
|
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": [],
|
||||||
|
"decision": {}})
|
||||||
project_id, _repo, _unbound = await _project_scope()
|
project_id, _repo, _unbound = await _project_scope()
|
||||||
reached, result = await moment_delivery_svc.deliver_for_act(
|
reached, result = await moment_delivery_svc.deliver_for_act(
|
||||||
g.user.id, tool, tool_input if isinstance(tool_input, dict) else {},
|
g.user.id, tool, tool_input if isinstance(tool_input, dict) else {},
|
||||||
@@ -320,13 +399,28 @@ async def moment():
|
|||||||
shapes, forms = moment_delivery_svc.shapes_for_act(
|
shapes, forms = moment_delivery_svc.shapes_for_act(
|
||||||
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
|
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
|
||||||
)
|
)
|
||||||
|
# Lessons recorded for this situation, after the rules: each once per
|
||||||
|
# session, and booked in the record ledger only if its line is kept.
|
||||||
|
lesson_lines, lesson_ids = await moment_delivery_svc.lessons_for_act(
|
||||||
|
g.user.id, reached, tool, tool_input if isinstance(tool_input, dict) else {},
|
||||||
|
)
|
||||||
|
record_deliveries_svc.record(g.user.id, lesson_ids, "lesson_situation")
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, [
|
||||||
|
*hook_payload_svc.rule_parts(result.lines, result.rule_per_line(), block="rules"),
|
||||||
|
*(hook_payload_svc.Part(text=text, block="lessons", ids={hook_payload_svc.NOTE: (lid,)})
|
||||||
|
for text, lid in zip(lesson_lines, lesson_ids, strict=True)),
|
||||||
|
*(hook_payload_svc.Part(text=block, ids={hook_payload_svc.SHAPE: (key,)})
|
||||||
|
for block, key in zip(shapes, forms, strict=False)),
|
||||||
|
])
|
||||||
|
kept_shapes = set(fitted.ids(hook_payload_svc.SHAPE))
|
||||||
|
forms = {k: f for k, f in forms.items() if k in kept_shapes}
|
||||||
await reply_shapes_svc.record_delivery(g.user.id, forms, via="hook")
|
await reply_shapes_svc.record_delivery(g.user.id, forms, via="hook")
|
||||||
context = "\n\n".join(b for b in ("\n\n".join(shapes), "\n".join(result.lines)) if b)
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
"context": context,
|
"context": fitted.context,
|
||||||
"rule_ids": result.rule_ids,
|
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
|
||||||
"moments": [hit["moment"] for hit in reached],
|
"moments": [hit["moment"] for hit in reached],
|
||||||
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
|
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
|
||||||
|
"decision": result.decision,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@@ -336,7 +430,10 @@ async def rule_opened():
|
|||||||
"""A session opened a rule shortly after these acts.
|
"""A session opened a rule shortly after these acts.
|
||||||
|
|
||||||
Body: `{"rule_id", "session_id", "acts": [<PreToolUse event>, ...]}` —
|
Body: `{"rule_id", "session_id", "acts": [<PreToolUse event>, ...]}` —
|
||||||
the calls the plugin saw in the window before the `get_rule`. Each is
|
the calls the plugin saw in the window before the `get_rule`. Every open
|
||||||
|
is first stamped on this session's latest delivery of the rule, which is
|
||||||
|
how the open rate per delivery is measured; `acts` is empty when the
|
||||||
|
rule was one a hook had just named, which explains the open by itself. Each is
|
||||||
resolved to its moments, and the open is counted as evidence that the
|
resolved to its moments, and the open is counted as evidence that the
|
||||||
rule belongs on them; once a pair has repeated across enough distinct
|
rule belongs on them; once a pair has repeated across enough distinct
|
||||||
sessions, `context` carries the line asking the reader to offer the
|
sessions, `context` carries the line asking the reader to offer the
|
||||||
@@ -349,8 +446,13 @@ async def rule_opened():
|
|||||||
rule_id = int(data.get("rule_id") or 0)
|
rule_id = int(data.get("rule_id") or 0)
|
||||||
except (TypeError, ValueError):
|
except (TypeError, ValueError):
|
||||||
rule_id = 0
|
rule_id = 0
|
||||||
|
if rule_id > 0:
|
||||||
|
# The open, against the delivery it followed — whatever the acts say.
|
||||||
|
await rule_deliveries_svc.mark_opened(
|
||||||
|
g.user.id, str(data.get("session_id") or ""), rule_id,
|
||||||
|
)
|
||||||
acts = data.get("acts")
|
acts = data.get("acts")
|
||||||
if rule_id <= 0 or not isinstance(acts, list):
|
if rule_id <= 0 or not isinstance(acts, list) or not acts:
|
||||||
return jsonify({"moments": [], "context": ""})
|
return jsonify({"moments": [], "context": ""})
|
||||||
project_id, _repo, _unbound = await _project_scope()
|
project_id, _repo, _unbound = await _project_scope()
|
||||||
return jsonify(await judgments_svc.opened_after(
|
return jsonify(await judgments_svc.opened_after(
|
||||||
@@ -359,6 +461,84 @@ async def rule_opened():
|
|||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
|
@plugin_bp.post("/record-opened")
|
||||||
|
@login_required
|
||||||
|
async def record_opened():
|
||||||
|
"""A session opened a record (a note, snippet, task, lesson or process).
|
||||||
|
|
||||||
|
Body: `{"session_id", "note_id"}`, posted by the plugin after a `get_note`,
|
||||||
|
`get_task`, `get_snippet`, `get_lesson` or `get_process` call. The open is
|
||||||
|
stamped on this session's latest delivery of the record; with none, it
|
||||||
|
is recorded as `direct`, a record reached without being shown. Answers
|
||||||
|
`{"way"}`: how the open was counted, or "" when it was not.
|
||||||
|
"""
|
||||||
|
data = await request.get_json(silent=True) or {}
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return jsonify({"way": ""})
|
||||||
|
try:
|
||||||
|
note_id = int(data.get("note_id") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
note_id = 0
|
||||||
|
if note_id <= 0:
|
||||||
|
return jsonify({"way": ""})
|
||||||
|
way = await record_deliveries_svc.mark_opened(
|
||||||
|
g.user.id, str(data.get("session_id") or ""), note_id,
|
||||||
|
plugin=rule_deliveries_svc.current_plugin(),
|
||||||
|
)
|
||||||
|
return jsonify({"way": way})
|
||||||
|
|
||||||
|
|
||||||
|
@plugin_bp.post("/record-searched")
|
||||||
|
@login_required
|
||||||
|
async def record_searched():
|
||||||
|
"""A session ran `search` itself.
|
||||||
|
|
||||||
|
Body: `{"session_id", "q"}`, posted by the plugin after the call. The
|
||||||
|
results that call returned, read from the server's own log of it, are
|
||||||
|
recorded against the session as `asked`, so an open that follows counts
|
||||||
|
as one the session reached by asking. Answers `{"recorded"}`.
|
||||||
|
"""
|
||||||
|
data = await request.get_json(silent=True) or {}
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return jsonify({"recorded": 0})
|
||||||
|
recorded = await record_deliveries_svc.from_search(
|
||||||
|
g.user.id, str(data.get("session_id") or ""), str(data.get("q") or ""),
|
||||||
|
plugin=rule_deliveries_svc.current_plugin(),
|
||||||
|
)
|
||||||
|
return jsonify({"recorded": recorded})
|
||||||
|
|
||||||
|
|
||||||
|
@plugin_bp.post("/rule-verdict")
|
||||||
|
@login_required
|
||||||
|
async def rule_verdict():
|
||||||
|
"""A session said what a rule it was delivered did there.
|
||||||
|
|
||||||
|
Body: `{"session_id", "rule_id", "outcome"?, "moment"?, "why"?}`, posted
|
||||||
|
by the plugin after a `rule_outcome` call (`outcome`: applied or
|
||||||
|
departed) or a `rule_misfired` call (`moment`: where it arrived and did
|
||||||
|
not apply). The verdict lands on this session's latest delivery of the
|
||||||
|
rule — at that moment, for a misfire — and is the adherence readout's
|
||||||
|
evidence that the rule was followed, departed from, or did not bear on
|
||||||
|
the work. A rule the session was never delivered records nothing.
|
||||||
|
Returns `{"recorded", "at"}`.
|
||||||
|
"""
|
||||||
|
data = await request.get_json(silent=True) or {}
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return jsonify({"recorded": False, "at": ""})
|
||||||
|
try:
|
||||||
|
rule_id = int(data.get("rule_id") or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
rule_id = 0
|
||||||
|
if rule_id <= 0:
|
||||||
|
return jsonify({"recorded": False, "at": ""})
|
||||||
|
return jsonify(await rule_adherence_svc.from_session(
|
||||||
|
g.user.id, str(data.get("session_id") or ""), rule_id,
|
||||||
|
outcome=str(data.get("outcome") or ""),
|
||||||
|
misfired_at=str(data.get("moment") or ""),
|
||||||
|
why=str(data.get("why") or ""),
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
@plugin_bp.post("/reply-rules")
|
@plugin_bp.post("/reply-rules")
|
||||||
@login_required
|
@login_required
|
||||||
@memoized_query_embeddings
|
@memoized_query_embeddings
|
||||||
@@ -512,6 +692,19 @@ async def write_path_prior_art():
|
|||||||
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
|
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
|
||||||
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
|
||||||
)
|
)
|
||||||
|
fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, {
|
||||||
|
hook_payload_svc.NOTE: "note_ids", hook_payload_svc.SYNC: "sync_note_ids",
|
||||||
|
hook_payload_svc.DERIVE: "derive_keys", hook_payload_svc.RULE: "rule_ids",
|
||||||
|
hook_payload_svc.RULING: "ruling_system_ids",
|
||||||
|
}))
|
||||||
|
result["context"] = fitted.context
|
||||||
|
for key, kind in (
|
||||||
|
("note_ids", hook_payload_svc.NOTE), ("sync_note_ids", hook_payload_svc.SYNC),
|
||||||
|
("derive_keys", hook_payload_svc.DERIVE), ("rule_ids", hook_payload_svc.RULE),
|
||||||
|
("ruling_system_ids", hook_payload_svc.RULING),
|
||||||
|
):
|
||||||
|
if key in result:
|
||||||
|
result[key] = fitted.keep_only(kind, result[key])
|
||||||
return jsonify(result)
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
@@ -545,9 +738,11 @@ async def shape_check():
|
|||||||
The client's write hooks keep a ledger of the definitions each turn wrote;
|
The client's write hooks keep a ledger of the definitions each turn wrote;
|
||||||
its Stop hook sends them here. The server decides which carry no judgment
|
its Stop hook sends them here. The server decides which carry no judgment
|
||||||
— against the ledger and the project's recorded snippets — records the
|
— against the ledger and the project's recorded snippets — records the
|
||||||
outcome, and for a block returns the `reason` the agent is sent back with.
|
outcome, and returns the `note` the agent reads at the start of its next
|
||||||
A hook blocks only on a reason it received, so only on a block that was
|
turn. Nothing here holds the reply: the question rides the next prompt,
|
||||||
recorded, and never on the stop that follows one (`phase=after`).
|
in the same session, while the code is still in view. `phase=after` is
|
||||||
|
the stop after that prompt, sent with the lines the note named, and
|
||||||
|
records whether they were judged.
|
||||||
|
|
||||||
A GET like every plugin endpoint: a read-scoped key runs the plugin, and
|
A GET like every plugin endpoint: a read-scoped key runs the plugin, and
|
||||||
this records telemetry the way /reply-rules records its section check. It changes no ledger
|
this records telemetry the way /reply-rules records its section check. It changes no ledger
|
||||||
@@ -594,8 +789,8 @@ async def shape_check():
|
|||||||
)
|
)
|
||||||
body["outcome"] = outcome
|
body["outcome"] = outcome
|
||||||
body["unjudged"] = unjudged
|
body["unjudged"] = unjudged
|
||||||
if outcome == "blocked":
|
if outcome == "noted":
|
||||||
body["reason"] = shape_check_svc.block_reason(
|
body["note"] = shape_check_svc.note_text(
|
||||||
unjudged, project_id=project_id, repo=repo_key or repo,
|
unjudged, project_id=project_id, repo=repo_key or repo,
|
||||||
)
|
)
|
||||||
return jsonify(body)
|
return jsonify(body)
|
||||||
|
|||||||
@@ -21,6 +21,10 @@ from grimoire.auth import get_current_user_id, login_required
|
|||||||
from grimoire.services import moment_actions as moment_actions_svc
|
from grimoire.services import moment_actions as moment_actions_svc
|
||||||
from grimoire.services import moments as moments_svc
|
from grimoire.services import moments as moments_svc
|
||||||
from grimoire.services import reply_shapes as shapes_svc
|
from grimoire.services import reply_shapes as shapes_svc
|
||||||
|
from grimoire.services import record_deliveries as record_deliveries_svc
|
||||||
|
from grimoire.services import record_kinds as record_kinds_svc
|
||||||
|
from grimoire.services import rule_adherence as adherence_svc
|
||||||
|
from grimoire.services import rule_field_judgments as weights_svc
|
||||||
from grimoire.services import rule_moment_judgments as judgments_svc
|
from grimoire.services import rule_moment_judgments as judgments_svc
|
||||||
from grimoire.services import rulebooks as rulebooks_svc
|
from grimoire.services import rulebooks as rulebooks_svc
|
||||||
from grimoire.services.retrieval_telemetry import moment_usage
|
from grimoire.services.retrieval_telemetry import moment_usage
|
||||||
@@ -57,6 +61,24 @@ async def get_surfaces_route():
|
|||||||
return jsonify({"surfaces": surfaces, "total": len(surfaces)})
|
return jsonify({"surfaces": surfaces, "total": len(surfaces)})
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/gate", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def get_gate_route():
|
||||||
|
"""The cue-swap gate on each surface it holds: the rate it speaks at, the
|
||||||
|
bar that rate comes to on the user's own recent cues, and how often each
|
||||||
|
surface actually spoke over the last week."""
|
||||||
|
from grimoire.services import cue_gate
|
||||||
|
from grimoire.services import retrieval_pipeline as rp
|
||||||
|
|
||||||
|
uid = get_current_user_id()
|
||||||
|
surfaces = [(arm.source, "records") for arm in rp.NOTE_ARMS if arm.gated] + [
|
||||||
|
(arm.source, "preferences") for arm in rp.RULE_ARMS if arm.gates_preferences
|
||||||
|
]
|
||||||
|
rows = await cue_gate.readout(uid, surfaces)
|
||||||
|
return jsonify({"surfaces": rows, "rate": rows[0]["rate"] if rows else cue_gate.RATE_DEFAULT,
|
||||||
|
"lines": cue_gate.LINES, "min_sample": cue_gate.MIN_SAMPLE})
|
||||||
|
|
||||||
|
|
||||||
@retrieval_bp.route("/surfaces/<surface>", methods=["PUT"])
|
@retrieval_bp.route("/surfaces/<surface>", methods=["PUT"])
|
||||||
@login_required
|
@login_required
|
||||||
async def tune_surface_route(surface: str):
|
async def tune_surface_route(surface: str):
|
||||||
@@ -220,3 +242,90 @@ async def judge_moment_proposals_route():
|
|||||||
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
|
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
|
||||||
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
|
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
|
||||||
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
|
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/adherence", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def adherence_route():
|
||||||
|
"""Whether the rules in force at each moment were followed there —
|
||||||
|
`rule_adherence`'s payload, from the same service. `?days=` sets the
|
||||||
|
window (default 30); `?rule_id=` narrows to one rule."""
|
||||||
|
try:
|
||||||
|
days = int(request.args.get("days") or adherence_svc.SUMMARY_DAYS)
|
||||||
|
rule_id = int(request.args.get("rule_id") or 0)
|
||||||
|
except ValueError:
|
||||||
|
return jsonify({"error": "days and rule_id must be whole numbers"}), 400
|
||||||
|
return jsonify(await adherence_svc.summary(
|
||||||
|
get_current_user_id(), days=days, rule_id=rule_id or None,
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/record-kinds", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def record_kinds_route():
|
||||||
|
"""The kind×moment table: which kinds of record each door's search may
|
||||||
|
consider, the shipped default beside each, and each cell's lines and
|
||||||
|
opens over `?days=` (default 30)."""
|
||||||
|
try:
|
||||||
|
days = max(1, min(int(request.args.get("days") or 30), 365))
|
||||||
|
except ValueError:
|
||||||
|
return jsonify({"error": "days must be a whole number"}), 400
|
||||||
|
return jsonify(await record_kinds_svc.table(get_current_user_id(), days=days))
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/record-kinds", methods=["PUT"])
|
||||||
|
@login_required
|
||||||
|
async def set_record_kinds_route():
|
||||||
|
"""Set one door's kinds. Body: `{"door", "kinds": [...]}`, or
|
||||||
|
`{"door", "kinds": null}` to put the door back to its shipped default.
|
||||||
|
Answers with the whole table."""
|
||||||
|
data = await request.get_json(silent=True) or {}
|
||||||
|
if not isinstance(data, dict) or not isinstance(data.get("door"), str):
|
||||||
|
return jsonify({"error": "door is required"}), 400
|
||||||
|
kinds = data.get("kinds")
|
||||||
|
if kinds is not None and (
|
||||||
|
not isinstance(kinds, list) or not all(isinstance(k, str) for k in kinds)
|
||||||
|
):
|
||||||
|
return jsonify({"error": "kinds must be a list of kinds, or null"}), 400
|
||||||
|
try:
|
||||||
|
return jsonify(await record_kinds_svc.set_kinds(get_current_user_id(), data["door"], kinds))
|
||||||
|
except ValueError as e:
|
||||||
|
return jsonify({"error": str(e)}), 400
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/record-reach", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def record_reach_route():
|
||||||
|
"""How non-rule records reached this user's sessions: per kind, pushed by
|
||||||
|
a hook, returned by the session's own search, or opened directly, and how
|
||||||
|
many were opened each way. `?days=` sets the window (default 30)."""
|
||||||
|
try:
|
||||||
|
days = int(request.args.get("days") or 30)
|
||||||
|
except ValueError:
|
||||||
|
return jsonify({"error": "days must be a whole number"}), 400
|
||||||
|
return jsonify(await record_deliveries_svc.summary(get_current_user_id(), days=days))
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/weights/proposals", methods=["GET"])
|
||||||
|
@login_required
|
||||||
|
async def weight_proposals_route():
|
||||||
|
"""The enforcement, salience and trigger suggestions waiting on a judgment
|
||||||
|
— `rule_weight_proposals`' payload, from the same service. `?rule_id=`
|
||||||
|
narrows to one rule."""
|
||||||
|
try:
|
||||||
|
rule_id = int(request.args.get("rule_id") or 0)
|
||||||
|
except ValueError:
|
||||||
|
return jsonify({"error": "rule_id must be a whole number"}), 400
|
||||||
|
return jsonify(await weights_svc.pending(get_current_user_id(), rule_id=rule_id or None))
|
||||||
|
|
||||||
|
|
||||||
|
@retrieval_bp.route("/weights/proposals/judge", methods=["POST"])
|
||||||
|
@login_required
|
||||||
|
async def judge_weight_proposals_route():
|
||||||
|
"""Confirm or reject suggestions: `{"judgments": [{rule_id, field, value,
|
||||||
|
verdict, note}]}` — `judge_rule_weights` from the browser. A confirm
|
||||||
|
changes the rule."""
|
||||||
|
data = await request.get_json(silent=True)
|
||||||
|
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
|
||||||
|
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
|
||||||
|
return jsonify(await weights_svc.judge(get_current_user_id(), data["judgments"]))
|
||||||
|
|||||||
@@ -18,6 +18,18 @@ from grimoire.services.rule_usage import (
|
|||||||
rulebooks_bp = Blueprint("rulebooks", __name__, url_prefix="/api")
|
rulebooks_bp = Blueprint("rulebooks", __name__, url_prefix="/api")
|
||||||
|
|
||||||
|
|
||||||
|
def _declared_or_refusal(data: dict):
|
||||||
|
"""The request's enforcement and salience, validated before any write, so
|
||||||
|
a bad value is a 400 naming the choices rather than a half-made rule."""
|
||||||
|
try:
|
||||||
|
return (
|
||||||
|
rulebooks_svc.require_enforcement(data.get("enforcement"), data.get("kind")),
|
||||||
|
rulebooks_svc.require_salience(data.get("salience")),
|
||||||
|
), None
|
||||||
|
except ValueError as exc:
|
||||||
|
return None, (jsonify({"error": str(exc)}), 400)
|
||||||
|
|
||||||
|
|
||||||
def _moments_or_refusal(data: dict):
|
def _moments_or_refusal(data: dict):
|
||||||
"""The request's `moments`, validated BEFORE any write — so an unknown
|
"""The request's `moments`, validated BEFORE any write — so an unknown
|
||||||
name is a 400 and not a rule created without the mounts it asked for.
|
name is a 400 and not a rule created without the mounts it asked for.
|
||||||
@@ -28,6 +40,17 @@ def _moments_or_refusal(data: dict):
|
|||||||
return None, (jsonify({"error": str(exc)}), 400)
|
return None, (jsonify({"error": str(exc)}), 400)
|
||||||
|
|
||||||
|
|
||||||
|
def _triggers_or_refusal(data: dict):
|
||||||
|
"""The request's `triggers`, validated before any write, as `moments` is.
|
||||||
|
Absent means "leave them alone" (None)."""
|
||||||
|
from grimoire.services.rule_triggers import require_triggers
|
||||||
|
|
||||||
|
try:
|
||||||
|
return require_triggers(data.get("triggers")), None
|
||||||
|
except ValueError as exc:
|
||||||
|
return None, (jsonify({"error": str(exc)}), 400)
|
||||||
|
|
||||||
|
|
||||||
# ── Rulebooks ───────────────────────────────────────────────────────────
|
# ── Rulebooks ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@rulebooks_bp.get("/rulebooks")
|
@rulebooks_bp.get("/rulebooks")
|
||||||
@@ -184,6 +207,13 @@ async def create_rule(topic_id: int):
|
|||||||
moments, refused = _moments_or_refusal(data)
|
moments, refused = _moments_or_refusal(data)
|
||||||
if refused:
|
if refused:
|
||||||
return refused
|
return refused
|
||||||
|
triggers, refused = _triggers_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
declared, refused = _declared_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
enforcement, salience = declared
|
||||||
try:
|
try:
|
||||||
rule = await rulebooks_svc.create_rule(
|
rule = await rulebooks_svc.create_rule(
|
||||||
topic_id=topic_id,
|
topic_id=topic_id,
|
||||||
@@ -202,11 +232,12 @@ async def create_rule(topic_id: int):
|
|||||||
arose_from_id=data.get("arose_from_id", 0) or 0,
|
arose_from_id=data.get("arose_from_id", 0) or 0,
|
||||||
verify_with=data.get("verify_with", ""),
|
verify_with=data.get("verify_with", ""),
|
||||||
expires_when=data.get("expires_when", ""),
|
expires_when=data.get("expires_when", ""),
|
||||||
|
enforcement=enforcement, salience=salience,
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return jsonify({"error": str(exc)}), 404
|
return jsonify({"error": str(exc)}), 404
|
||||||
return jsonify(await rulebooks_svc.rule_detail(
|
return jsonify(await rulebooks_svc.rule_detail(
|
||||||
get_current_user_id(), rule, data.get("system_ids"), moments,
|
get_current_user_id(), rule, data.get("system_ids"), moments, triggers=triggers,
|
||||||
)), 201
|
)), 201
|
||||||
|
|
||||||
|
|
||||||
@@ -234,7 +265,7 @@ async def update_rule(rule_id: int):
|
|||||||
k: v for k, v in data.items()
|
k: v for k, v in data.items()
|
||||||
if k in ("title", "statement", "why", "how_to_apply", "order_index",
|
if k in ("title", "statement", "why", "how_to_apply", "order_index",
|
||||||
"when_to_apply", "kind", "arose_from_id",
|
"when_to_apply", "kind", "arose_from_id",
|
||||||
"verify_with", "expires_when")
|
"verify_with", "expires_when", "enforcement", "salience")
|
||||||
}
|
}
|
||||||
# No clear_fields here: a form sends "" for an emptied input, and the
|
# No clear_fields here: a form sends "" for an emptied input, and the
|
||||||
# service normalises "" to NULL for every nullable text column. The MCP
|
# service normalises "" to NULL for every nullable text column. The MCP
|
||||||
@@ -243,11 +274,17 @@ async def update_rule(rule_id: int):
|
|||||||
moments, refused = _moments_or_refusal(data)
|
moments, refused = _moments_or_refusal(data)
|
||||||
if refused:
|
if refused:
|
||||||
return refused
|
return refused
|
||||||
|
triggers, refused = _triggers_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
try:
|
||||||
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
|
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
|
||||||
|
except ValueError as exc:
|
||||||
|
return jsonify({"error": str(exc)}), 400
|
||||||
if rule is None:
|
if rule is None:
|
||||||
return jsonify({"error": "rule not found"}), 404
|
return jsonify({"error": "rule not found"}), 404
|
||||||
return jsonify(await rulebooks_svc.rule_detail(
|
return jsonify(await rulebooks_svc.rule_detail(
|
||||||
uid, rule, data.get("system_ids"), moments,
|
uid, rule, data.get("system_ids"), moments, triggers=triggers,
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
@@ -425,6 +462,13 @@ async def create_project_rule(project_id: int):
|
|||||||
moments, refused = _moments_or_refusal(data)
|
moments, refused = _moments_or_refusal(data)
|
||||||
if refused:
|
if refused:
|
||||||
return refused
|
return refused
|
||||||
|
triggers, refused = _triggers_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
declared, refused = _declared_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
enforcement, salience = declared
|
||||||
try:
|
try:
|
||||||
rule = await rulebooks_svc.create_project_rule(
|
rule = await rulebooks_svc.create_project_rule(
|
||||||
project_id=project_id,
|
project_id=project_id,
|
||||||
@@ -443,11 +487,12 @@ async def create_project_rule(project_id: int):
|
|||||||
arose_from_id=data.get("arose_from_id", 0) or 0,
|
arose_from_id=data.get("arose_from_id", 0) or 0,
|
||||||
verify_with=data.get("verify_with", ""),
|
verify_with=data.get("verify_with", ""),
|
||||||
expires_when=data.get("expires_when", ""),
|
expires_when=data.get("expires_when", ""),
|
||||||
|
enforcement=enforcement, salience=salience,
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return jsonify({"error": str(exc)}), 404
|
return jsonify({"error": str(exc)}), 404
|
||||||
return jsonify(await rulebooks_svc.rule_detail(
|
return jsonify(await rulebooks_svc.rule_detail(
|
||||||
get_current_user_id(), rule, data.get("system_ids"), moments,
|
get_current_user_id(), rule, data.get("system_ids"), moments, triggers=triggers,
|
||||||
)), 201
|
)), 201
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user