Compare commits
34
Commits
85093c859b
...
dev
@@ -75,7 +75,7 @@ Everything is optional. Set these in the environment or in a `.env` file beside
|
||||
| Variable | When | What it does |
|
||||
|----------|------|--------------|
|
||||
| `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 |
|
||||
| `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")
|
||||
@@ -281,6 +281,7 @@ These serve the plugin's hooks.
|
||||
| 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 / 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 |
|
||||
| POST / GET / DELETE | `/api/admin/invitations` (+ `/:id`) | Create / list / revoke invite links |
|
||||
| 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) |
|
||||
| `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 |
|
||||
| `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_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 |
|
||||
@@ -95,7 +95,11 @@ Back up the database with **Settings → Data → Scheduled backups** ([Backups]
|
||||
|
||||
## 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
|
||||
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.
|
||||
|
||||
@@ -119,7 +123,7 @@ A hop count higher than the real number of proxies lets a client choose its own
|
||||
## 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`).
|
||||
- **`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.
|
||||
- **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.
|
||||
|
||||
+1
-1
@@ -103,7 +103,7 @@ Email and password, plus optional OIDC single sign-on (Authentik, Keycloak, ...)
|
||||
| Integrations | SearXNG, git forge connections |
|
||||
| Data | Export, backup and restore, scheduled backups (admin) |
|
||||
| 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 |
|
||||
| Platforms (admin) | The platform catalogue family canon is grouped by |
|
||||
| Users (admin) | Registration, invites, users |
|
||||
|
||||
+172
-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
|
||||
@@ -180,3 +181,173 @@ export function getProposals(ruleId?: number): Promise<ProposalsPayload> {
|
||||
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
|
||||
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;
|
||||
/** 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" | "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";
|
||||
|
||||
/**
|
||||
* 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 —
|
||||
* "Adjust this" on a reply shape opens a preference mounted on that shape's
|
||||
* moment. The editor applies it once, when creating. */
|
||||
@@ -70,6 +91,8 @@ export interface Rule {
|
||||
title: string;
|
||||
statement: string;
|
||||
kind: RuleKind;
|
||||
enforcement: RuleEnforcement;
|
||||
salience: RuleSalience;
|
||||
/** WHEN this rule fires — the trigger, not the instruction. */
|
||||
when_to_apply: string;
|
||||
why: string;
|
||||
@@ -94,6 +117,8 @@ export interface Rule {
|
||||
/** The moments this rule arrives at whenever they happen,
|
||||
* in catalog order. Present only when the rule is mounted. */
|
||||
moments?: string[];
|
||||
/** Present only when the rule has triggers. */
|
||||
triggers?: RuleTrigger[];
|
||||
relations?: RuleRelation[];
|
||||
/** The lessons that point at this rule — the concrete
|
||||
* situations judged instances of it, plus any suggested and awaiting a
|
||||
@@ -113,6 +138,10 @@ export interface RuleHeader {
|
||||
topic_id: number | null;
|
||||
/** Unconditional on the wire (services.rulebooks.rule_brief). */
|
||||
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. */
|
||||
updated_at: string | null;
|
||||
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
|
||||
* different force, and the person writing it is the one who knows which. */
|
||||
kind: RuleKind;
|
||||
enforcement: RuleEnforcement;
|
||||
salience: RuleSalience;
|
||||
when_to_apply: string;
|
||||
why: string;
|
||||
how_to_apply: string;
|
||||
@@ -224,6 +255,8 @@ export interface RuleWrite {
|
||||
system_ids: number[];
|
||||
/** Replaces the set; [] unmounts the rule from every moment. */
|
||||
moments: string[];
|
||||
/** Replaces the set; [] clears every trigger. */
|
||||
triggers: RuleTrigger[];
|
||||
arose_from_id: number | null;
|
||||
verify_with: string;
|
||||
expires_when: string;
|
||||
|
||||
@@ -147,6 +147,45 @@
|
||||
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 */
|
||||
.prose ul[data-type="taskList"] {
|
||||
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);
|
||||
}
|
||||
@@ -158,33 +158,6 @@ onMounted(load);
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.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 scoped src="@/assets/rule-proposals.css" />
|
||||
|
||||
<style src="@/assets/moments-shared.css" />
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
<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.
|
||||
* The moment's own counts cannot say this once two rules are mounted there.
|
||||
* Closed by default: the counts in the row above are what most visits want.
|
||||
* Which rules a moment delivered, whether an agent went on to read each, and
|
||||
* — where a verdict exists — whether it was followed there. The moment's own
|
||||
* 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>
|
||||
|
||||
<template>
|
||||
@@ -19,6 +33,7 @@ defineProps<{ rules: MomentRuleUsage[] }>();
|
||||
<span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'">
|
||||
{{ r.opened ? "opened" : "not opened" }}
|
||||
</span>
|
||||
<span v-if="adherence[r.rule_id]" class="delivered-count">{{ verdicts(adherence[r.rule_id]) }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</details>
|
||||
|
||||
@@ -3,7 +3,12 @@ import { computed, onMounted, ref } from "vue";
|
||||
import { useMomentsStore } from "@/stores/moments";
|
||||
import MomentProposals from "@/components/MomentProposals.vue";
|
||||
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
|
||||
import type { MomentAction, MomentUsage } from "@/api/moments";
|
||||
import WeightProposals from "@/components/WeightProposals.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";
|
||||
|
||||
/**
|
||||
@@ -31,6 +36,42 @@ function usage(moment: string): MomentUsage | 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
|
||||
// only once something is mounted on it or has been delivered at it — the
|
||||
// catalog cannot list procedures it has never heard of.
|
||||
@@ -101,7 +142,10 @@ async function addMapping() {
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => store.load(true));
|
||||
onMounted(async () => {
|
||||
await store.load(true);
|
||||
await Promise.all([loadAdherence(), loadReach()]);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -126,6 +170,10 @@ onMounted(() => store.load(true));
|
||||
</p>
|
||||
|
||||
<MomentProposals />
|
||||
<WeightProposals />
|
||||
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
|
||||
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
|
||||
<RecordKinds :days="days" />
|
||||
|
||||
<ul class="moment-list">
|
||||
<li v-for="m in catalog" :key="m.name" class="moment-row">
|
||||
@@ -142,6 +190,9 @@ onMounted(() => store.load(true));
|
||||
last {{ fmtDate(usage(m.name)!.last_delivered_at!) }}
|
||||
</span>
|
||||
</template>
|
||||
<span v-if="followed(m.name)">
|
||||
followed {{ followed(m.name)!.followed }} of {{ followed(m.name)!.in_force }} in force
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<p class="moment-desc">{{ m.means }}</p>
|
||||
@@ -168,7 +219,9 @@ onMounted(() => store.load(true));
|
||||
>×</button>
|
||||
</span>
|
||||
</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>
|
||||
</ul>
|
||||
|
||||
@@ -186,9 +239,14 @@ onMounted(() => store.load(true));
|
||||
<span>delivered {{ usage(name)!.delivered }}</span>
|
||||
<span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span>
|
||||
</template>
|
||||
<span v-if="followed(name)">
|
||||
followed {{ followed(name)!.followed }} of {{ followed(name)!.in_force }} in force
|
||||
</span>
|
||||
</span>
|
||||
</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>
|
||||
</ul>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<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>
|
||||
<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" 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,115 @@
|
||||
<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"],
|
||||
["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, 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 { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import type { TaskLog } from "@/types/task";
|
||||
import { fmtStamp } from "@/utils/dateFormat";
|
||||
|
||||
@@ -131,7 +132,7 @@ onMounted(loadLogs);
|
||||
<button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">×</button>
|
||||
</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>
|
||||
</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 RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
|
||||
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<{
|
||||
ruleId: number | null;
|
||||
@@ -26,6 +30,14 @@ const whenToApply = ref("");
|
||||
// followed too faithfully, where a rule mislabelled as a preference is one a
|
||||
// session may quietly rewrite.
|
||||
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[]>([]);
|
||||
// The moments this rule is mounted on. Catalog moments are
|
||||
// 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(() =>
|
||||
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 howToApply = ref("");
|
||||
const verifyWith = ref("");
|
||||
@@ -123,8 +173,11 @@ async function load() {
|
||||
statement.value = r.statement;
|
||||
whenToApply.value = r.when_to_apply || "";
|
||||
kind.value = r.kind;
|
||||
enforcement.value = r.enforcement ?? "inform";
|
||||
salience.value = r.salience ?? "normal";
|
||||
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
|
||||
ruleMoments.value = [...(r.moments ?? [])];
|
||||
triggers.value = (r.triggers ?? []).map((t) => ({ ...t }));
|
||||
why.value = r.why || "";
|
||||
howToApply.value = r.how_to_apply || "";
|
||||
verifyWith.value = r.verify_with || "";
|
||||
@@ -135,8 +188,11 @@ async function load() {
|
||||
statement.value = "";
|
||||
whenToApply.value = props.preset?.whenToApply ?? "";
|
||||
kind.value = props.preset?.kind ?? "rule";
|
||||
enforcement.value = "inform";
|
||||
salience.value = "normal";
|
||||
systemIds.value = [];
|
||||
ruleMoments.value = [...(props.preset?.moments ?? [])];
|
||||
triggers.value = [];
|
||||
why.value = "";
|
||||
howToApply.value = "";
|
||||
verifyWith.value = "";
|
||||
@@ -144,6 +200,9 @@ async function load() {
|
||||
}
|
||||
procedureDraft.value = "";
|
||||
procedureError.value = "";
|
||||
triggerPattern.value = "";
|
||||
triggerMoment.value = "";
|
||||
triggerError.value = "";
|
||||
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
|
||||
}
|
||||
|
||||
@@ -181,12 +240,16 @@ async function save() {
|
||||
statement: statement.value,
|
||||
when_to_apply: whenToApply.value,
|
||||
kind: kind.value,
|
||||
enforcement: enforcement.value,
|
||||
salience: salience.value,
|
||||
// Always sent, so clearing the last area actually clears it — the server
|
||||
// reads a list as "these ARE the areas now".
|
||||
system_ids: systemIds.value,
|
||||
// Always sent, for system_ids' reason: the server reads the list as the
|
||||
// whole set, so unticking the last moment actually unmounts the rule.
|
||||
moments: ruleMoments.value,
|
||||
// Always sent, for the same reason: the list is the whole set.
|
||||
triggers: triggers.value,
|
||||
why: why.value,
|
||||
how_to_apply: howToApply.value,
|
||||
// Always sent, including empty. The REST door maps "" to NULL, so
|
||||
@@ -271,6 +334,40 @@ watch(() => props.ruleId, load);
|
||||
preference.
|
||||
</p>
|
||||
</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">
|
||||
Sessions rewrite preferences without asking, which is what makes them
|
||||
stay current. Every rewrite is kept, and
|
||||
@@ -342,6 +439,55 @@ watch(() => props.ruleId, load);
|
||||
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
|
||||
</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">
|
||||
<legend>Areas this rule is about</legend>
|
||||
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
|
||||
@@ -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 input { margin-top: 0; }
|
||||
.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
|
||||
between the warning HUE and warning text, and this is text. */
|
||||
.trigger-warning {
|
||||
|
||||
@@ -27,6 +27,15 @@ const emit = defineEmits<{
|
||||
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."
|
||||
>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
|
||||
retrieval now, so "conditional" stopped distinguishing anything.
|
||||
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
|
||||
if (i === 0 || /\s/.test(text[i - 1])) {
|
||||
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;
|
||||
acType = "tag";
|
||||
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 { 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({
|
||||
name: "tagDecoration",
|
||||
|
||||
@@ -123,6 +123,26 @@ const router = createRouter({
|
||||
name: "project-view",
|
||||
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",
|
||||
name: "rules",
|
||||
|
||||
@@ -111,6 +111,9 @@ export const useRulebooksStore = defineStore("rulebooks", () => {
|
||||
// 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.
|
||||
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,
|
||||
when_to_apply: rule.when_to_apply || undefined,
|
||||
arose_from_id: rule.arose_from_id ?? undefined,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { marked, type RendererThis, type Tokens } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { linkifyTags, linkifyWikilinks } from "@/utils/tags";
|
||||
import { linkifyRecordRefs } from "@/utils/recordRefs";
|
||||
|
||||
function decodeEntities(text: string): string {
|
||||
const textarea = document.createElement("textarea");
|
||||
@@ -20,9 +21,11 @@ export function slugify(text: string): string {
|
||||
export function stripFirstLineTags(text: string): string {
|
||||
const match = text.match(/^[ \t]*((?:(?<!\w)#[\w]+(?:\/[\w]+)*[ \t]*)+)\n?/);
|
||||
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 allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t));
|
||||
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t) && !/^#\d+$/.test(t));
|
||||
if (!allTags) return text;
|
||||
return text.slice(match[0].length);
|
||||
}
|
||||
@@ -38,7 +41,7 @@ const headingRenderer = {
|
||||
marked.use({ renderer: headingRenderer });
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
@@ -64,7 +67,7 @@ export function renderMarkdown(text: string, { interactiveCheckboxes = false } =
|
||||
}
|
||||
|
||||
const withTags = linkifyTags(html);
|
||||
const withLinks = linkifyWikilinks(withTags);
|
||||
const withLinks = linkifyRecordRefs(linkifyWikilinks(withTags));
|
||||
const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL);
|
||||
// marked escapes ' to ' — replace after sanitization to ensure clean rendering
|
||||
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 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 {
|
||||
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 { apiGet } from "@/api/client";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
@@ -26,7 +27,8 @@ interface GraphNode extends SimulationNodeDatum {
|
||||
interface GraphEdge {
|
||||
source: 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 {
|
||||
@@ -237,12 +239,14 @@ function initGraph() {
|
||||
.append("line")
|
||||
.attr("class", "graph-edge")
|
||||
.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-dasharray", null)
|
||||
.attr("stroke-width", (d: any) => (d.type === "wikilink" ? 1.5 : 1))
|
||||
.attr("marker-end", (d: any) => (d.type === "wikilink" ? "url(#arrow)" : null));
|
||||
.attr("stroke-opacity", (d: any) => (d.type === "tag" ? 0.4 : 0.5))
|
||||
// A citation is a looser link than a wikilink: same colour and direction,
|
||||
// drawn dashed so the two read apart.
|
||||
.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
|
||||
const nodeSel = zoomG
|
||||
@@ -559,7 +563,7 @@ onUnmounted(() => {
|
||||
<div
|
||||
v-else-if="peekBody"
|
||||
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>
|
||||
|
||||
@@ -40,6 +40,7 @@ import UsageBadge from "@/components/UsageBadge.vue";
|
||||
import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { canWriteRecord } from "@/utils/permission";
|
||||
import { recordHref } from "@/utils/recordHref";
|
||||
|
||||
@@ -171,7 +172,7 @@ onMounted(load);
|
||||
<div
|
||||
v-if="insightHtml"
|
||||
class="ld-insight markdown-body"
|
||||
v-html="insightHtml"
|
||||
v-html="insightHtml" v-record-refs
|
||||
/>
|
||||
<p v-else class="ld-muted ld-empty">
|
||||
No detail was recorded — the claim above is the whole lesson.
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { NoteType } from "@/types/note";
|
||||
import { useNotesStore } from "@/stores/notes";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { useAssist, type NoteDraft } from "@/composables/useAssist";
|
||||
import { useAutoSave } from "@/composables/useAutoSave";
|
||||
import { useEditorGuards } from "@/composables/useEditorGuards";
|
||||
@@ -439,7 +440,7 @@ onUnmounted(() => assist.clearSelection());
|
||||
<div
|
||||
v-else
|
||||
class="preview-pane prose"
|
||||
v-html="renderedPreview"
|
||||
v-html="renderedPreview" v-record-refs
|
||||
/>
|
||||
</Transition>
|
||||
</template>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { onMounted, computed, ref, watch } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { useNotesStore } from "@/stores/notes";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { recordHref } from "@/utils/recordHref";
|
||||
import { relativeTime } from "@/composables/useRelativeTime";
|
||||
import { apiPost, apiGet, apiPatch } from "@/api/client";
|
||||
import type { Note } from "@/types/note";
|
||||
@@ -14,7 +16,12 @@ import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next";
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
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 showShare = ref(false);
|
||||
|
||||
@@ -259,7 +266,7 @@ async function convertToTask() {
|
||||
<div
|
||||
class="body prose"
|
||||
:class="{ 'prose--checklist': isListNote }"
|
||||
v-html="renderedBody"
|
||||
v-html="renderedBody" v-record-refs
|
||||
@click="onBodyClick"
|
||||
@change="onBodyChange"
|
||||
></div>
|
||||
@@ -274,7 +281,8 @@ async function convertToTask() {
|
||||
<router-link
|
||||
v-for="link in backlinks"
|
||||
: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"
|
||||
>
|
||||
<span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<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 { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
@@ -7,6 +7,7 @@ import { useToastStore } from "@/stores/toast";
|
||||
import { useTasksStore } from "@/stores/tasks";
|
||||
import { relativeTime } from "@/composables/useRelativeTime";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import ShareDialog from "@/components/ShareDialog.vue";
|
||||
import KindBadge from "@/components/KindBadge.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 () => {
|
||||
await loadProject();
|
||||
void focusMilestoneFromRoute();
|
||||
loadTasks();
|
||||
loadNotes();
|
||||
loadDesignSystems();
|
||||
@@ -985,9 +1005,15 @@ async function confirmDelete() {
|
||||
</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
|
||||
class="milestone-header"
|
||||
tabindex="-1"
|
||||
:class="{ clickable: renamingMilestoneId !== group.milestone?.id }"
|
||||
:aria-expanded="!collapsedMilestones.has(groupKey(group))"
|
||||
@click="renamingMilestoneId !== group.milestone?.id && toggleMilestoneCollapse(groupKey(group))"
|
||||
@@ -1050,7 +1076,7 @@ async function confirmDelete() {
|
||||
:class="['ms-plan-rendered', 'markdown-body',
|
||||
{ 'ms-plan-clamped': isPlanClamped(group.milestone) }]"
|
||||
@click="startEditPlan(group.milestone.id, group.milestone.body)"
|
||||
v-html="renderMarkdown(group.milestone.body || '')"
|
||||
v-html="renderMarkdown(group.milestone.body || '')" v-record-refs
|
||||
></div>
|
||||
<button
|
||||
v-if="isPlanLong(group.milestone)"
|
||||
|
||||
@@ -9,6 +9,7 @@ import { apiGet, apiPost, apiPut, apiDelete, listGroups, createGroup, deleteGrou
|
||||
import type { User } from "@/types/auth";
|
||||
import PaginationBar from "@/components/PaginationBar.vue";
|
||||
import MomentsSettings from "@/components/MomentsSettings.vue";
|
||||
import ReverseProxySettings from "@/components/ReverseProxySettings.vue";
|
||||
import ReplyShapesSettings from "@/components/ReplyShapesSettings.vue";
|
||||
import BackupScheduleSettings from "@/components/BackupScheduleSettings.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
|
||||
// its worst. A budget keeps the top of the ranking and drops the tail.
|
||||
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 kbToolRuleTopK = ref("5");
|
||||
const kbPromptRuleTopK = ref("3");
|
||||
@@ -384,6 +421,13 @@ async function saveKbInject() {
|
||||
const prK = asK(kbPromptRuleTopK.value, 3);
|
||||
const ryK = asK(kbReplyRuleTopK.value, 1);
|
||||
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);
|
||||
kbToolRuleTopK.value = String(trK);
|
||||
kbPromptRuleTopK.value = String(prK);
|
||||
@@ -432,6 +476,8 @@ async function saveKbInject() {
|
||||
// change the OPERATOR made — which is the one entry the model must not
|
||||
// quietly tune back.
|
||||
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_toolrule_top_k: String(trK),
|
||||
kb_promptrule_top_k: String(prK),
|
||||
@@ -453,6 +499,7 @@ async function saveKbInject() {
|
||||
// the operator is looking at it to confirm.
|
||||
await loadTuningHistory();
|
||||
await loadSurfaces();
|
||||
await loadGate();
|
||||
} catch {
|
||||
toastStore.show('Failed to save auto-inject settings', 'error');
|
||||
} finally {
|
||||
@@ -856,6 +903,12 @@ onMounted(async () => {
|
||||
if (allSettings.kb_writepath_threshold !== undefined) {
|
||||
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) {
|
||||
kbWritePathTopK.value = allSettings.kb_writepath_top_k;
|
||||
} else if (allSettings.kb_autoinject_top_k !== undefined) {
|
||||
@@ -878,6 +931,7 @@ onMounted(async () => {
|
||||
}
|
||||
await loadTuningHistory();
|
||||
await loadSurfaces();
|
||||
await loadGate();
|
||||
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
|
||||
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
|
||||
}
|
||||
@@ -1653,7 +1707,7 @@ async function deleteUser(userId: number) {
|
||||
class="fs-input input"
|
||||
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 class="checkbox-field">
|
||||
<label>
|
||||
@@ -1694,6 +1748,45 @@ async function deleteUser(userId: number) {
|
||||
location, not by resemblance.
|
||||
</p>
|
||||
</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">
|
||||
<label for="kb-writepath-topk">Max prior-art lines per edit</label>
|
||||
<input
|
||||
@@ -2664,6 +2757,16 @@ async function deleteUser(userId: number) {
|
||||
<div v-else class="empty-msg">Nothing asked yet.</div>
|
||||
</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">
|
||||
<h2>Application URL</h2>
|
||||
<p class="section-desc">
|
||||
@@ -4247,6 +4350,23 @@ async function deleteUser(userId: number) {
|
||||
font-family: var(--fs-font-mono);
|
||||
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-move {
|
||||
color: var(--fs-text-secondary);
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import ConfirmDialog from "@/components/ConfirmDialog.vue";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { canWriteRecord } from "@/utils/permission";
|
||||
|
||||
const route = useRoute();
|
||||
@@ -185,7 +186,7 @@ async function confirmDelete() {
|
||||
|
||||
<section v-if="snippet.snippet.notes" class="notes">
|
||||
<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>
|
||||
|
||||
<div v-if="snippet.tags.length" class="tag-row">
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTasksStore } from "@/stores/tasks";
|
||||
import { useNotesStore } from "@/stores/notes";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { vRecordRefs } from "@/directives/recordRefs";
|
||||
import { useAssist } from "@/composables/useAssist";
|
||||
import { useAutoSave } from "@/composables/useAutoSave";
|
||||
import { useEditorGuards } from "@/composables/useEditorGuards";
|
||||
@@ -538,7 +539,7 @@ useEditorGuards(dirty, save);
|
||||
<div
|
||||
v-show="showPreview"
|
||||
class="preview-pane prose"
|
||||
v-html="renderedPreview"
|
||||
v-html="renderedPreview" v-record-refs
|
||||
/>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"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).",
|
||||
"version": "2026.11.05.0301",
|
||||
"version": "2026.11.24.1827",
|
||||
"author": {
|
||||
"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 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. |
|
||||
|
||||
## 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_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_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_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_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. |
|
||||
|
||||
+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
|
||||
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
|
||||
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`,
|
||||
`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
|
||||
@@ -115,7 +117,8 @@ On install you'll be asked for:
|
||||
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
|
||||
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
|
||||
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
|
||||
@@ -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
|
||||
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.
|
||||
If any are, it blocks once with the server's reason, asking the agent that
|
||||
wrote them to say what each is — reusable (record a snippet), an instance or
|
||||
variant of one, or a one-off — in one `classify_shapes` call. Same discipline
|
||||
as the report check: never twice, never without a recorded check. Outcomes
|
||||
land under category `plugin`, action `shape_check`.
|
||||
If any are, the server's note rides the next prompt (the prompt hook sends it
|
||||
as `carry`), asking the agent that wrote them to say what each is — reusable
|
||||
(record a snippet), an instance or variant of one, or a one-off — in one
|
||||
`classify_shapes` call. It never holds the reply; the stop after that prompt
|
||||
records whether the lines were judged. Outcomes land under category
|
||||
`plugin`, action `shape_check`.
|
||||
- `skills/` → the universal process-skills, surfaced by description match.
|
||||
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
|
||||
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
|
||||
|
||||
@@ -191,6 +191,7 @@ while IFS= read -r rel_path; do
|
||||
reached=1
|
||||
body=$(curl -fsS --max-time 8 \
|
||||
-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; }
|
||||
# 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
|
||||
|
||||
@@ -125,6 +125,8 @@ if [ -n "$session_id" ]; then
|
||||
[ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}"
|
||||
# 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")"
|
||||
# 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
|
||||
# sent whole once, and as its one-line reminder on every later turn.
|
||||
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}"
|
||||
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 \
|
||||
-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 "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
|
||||
|
||||
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
|
||||
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
|
||||
curl -fsS --max-time 4 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||
"${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \
|
||||
>/dev/null 2>&1 || true
|
||||
exit 0
|
||||
|
||||
@@ -868,6 +868,14 @@ grimoire_config() {
|
||||
# garbage Bearer token and 401. Treat it as unset.
|
||||
case "$url" in *'${'*) url="" ;; 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" ]
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# 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
|
||||
# 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
|
||||
listed=$(curl -fsS --max-time 3 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||
"${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed=""
|
||||
{
|
||||
printf '%s\n' "$now"
|
||||
@@ -140,6 +142,7 @@ query="${repo_q}${ledger_q}"
|
||||
query=${query#&}
|
||||
body=$(printf '%s' "$event" | 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/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" '.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')
|
||||
[ -n "$context" ] || exit 0
|
||||
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}"
|
||||
# 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")"
|
||||
# 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
|
||||
|
||||
# Not `|| exit 0`: an unreachable instance must not discard a local finding
|
||||
@@ -249,6 +251,7 @@ fi
|
||||
reached=1
|
||||
body=$(curl -fsS --max-time 5 \
|
||||
-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; }
|
||||
unreached_context=""
|
||||
if [ "$reached" = 1 ]; then
|
||||
|
||||
@@ -228,7 +228,7 @@ while IFS= read -r check; do
|
||||
act=${check#*$'\t'}
|
||||
q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)"
|
||||
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
|
||||
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
|
||||
# mounted by this.
|
||||
#
|
||||
# An open of a rule a hook has just NAMED is not reported. A ranked arm or a
|
||||
# moment line put it 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.
|
||||
# EVERY OPEN IS REPORTED: the server stamps it on this session's latest
|
||||
# delivery of the rule, which is how an open rate per delivery is measured.
|
||||
#
|
||||
# The acts go with it only when the rule was NOT just named by a hook. A
|
||||
# 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
|
||||
grimoire_config || exit 0
|
||||
acts=""
|
||||
case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in
|
||||
*",${rule_id},"*) exit 0 ;;
|
||||
esac
|
||||
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
|
||||
[ -f "$acts_file" ] || exit 0
|
||||
now=$(date +%s 2>/dev/null) || exit 0
|
||||
acts=$(awk -F '\t' -v since=$((now - 90)) \
|
||||
*",${rule_id},"*) ;;
|
||||
*)
|
||||
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
|
||||
now=$(date +%s 2>/dev/null) || now=0
|
||||
if [ -f "$acts_file" ] && [ "$now" -gt 0 ]; then
|
||||
acts=$(awk -F '\t' -v since=$((now - 90)) \
|
||||
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 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
|
||||
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" \
|
||||
| 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-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
|
||||
# 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
|
||||
# turn a successful tool call into a hook error.
|
||||
set -uo pipefail
|
||||
@@ -38,7 +48,7 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
||||
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||
[ -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
|
||||
# id is read from the field rather than from an assumed tool name — the same
|
||||
# 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.
|
||||
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
|
||||
|
||||
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
|
||||
# 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
|
||||
# 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
|
||||
# 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 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data-binary @- \
|
||||
"${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
|
||||
resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||
"${url%/}/api/plugin/context${q}" 2>/dev/null)
|
||||
ctx_rc=$?
|
||||
meta=${resp##*$'\n'}
|
||||
|
||||
@@ -31,13 +31,14 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
||||
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||
[ -n "$session_id" ] || exit 0
|
||||
|
||||
# The moment arm's per-session files (its tool cache and the acts ledger) and
|
||||
# the fence's (the project the session entered, its outage marker) describe a
|
||||
# session that is over, on any exit — a clear included, since the next
|
||||
# conversation is a new session id.
|
||||
# The moment arm's per-session files (its tool cache and the acts ledger), the
|
||||
# shape check's (a note waiting for a prompt) and the fence's (the project the
|
||||
# session entered, its outage marker) describe a session that is over, on any
|
||||
# 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._-' '_')
|
||||
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" = "clear" ] && exit 0
|
||||
@@ -48,6 +49,7 @@ grimoire_config || exit 0
|
||||
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
|
||||
curl -fsS --max-time 4 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||
"${url%/}/api/plugin/release-session?session_id=${sid_enc}" \
|
||||
>/dev/null 2>&1 || true
|
||||
exit 0
|
||||
|
||||
@@ -1,29 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
# 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
|
||||
# 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
|
||||
# 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
|
||||
# words: the agent that built the code is the one participant who knows what
|
||||
# it is, and the end of the turn is the last moment that is still true.
|
||||
# nobody has judged yet as a `note`. The hook leaves the note for
|
||||
# grimoire_autoinject.sh, which carries it into the next prompt's payload: the
|
||||
# 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 blocks only on a `reason` the instance returned, which it returns
|
||||
# only for a block it RECORDED — an unconfigured or unreachable instance
|
||||
# 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).
|
||||
# IT NEVER HOLDS THE REPLY. A held reply is rewritten, and a hold on every turn
|
||||
# that wrote code made most replies cost two. The question waits one prompt
|
||||
# instead, and is asked inside that prompt's budget.
|
||||
#
|
||||
# THE LEDGER IS CONSUMED, NOT TURN-STAMPED. Everything written since the last
|
||||
# stop this hook answered is "this turn". It is emptied once the instance has
|
||||
# answered — after a pass, or after the post-block stop — and KEPT when the
|
||||
# instance could not be reached, so the question is asked at the next stop
|
||||
# that can be answered rather than silently dropped.
|
||||
# THE STATE, in <TMPDIR>/grimoire-shapecheck:
|
||||
# <sid>.note — the note, until a prompt carries it (the prompt hook
|
||||
# removes it once the instance has answered);
|
||||
# <sid>.asked — the lines that note named. At the first stop after the note
|
||||
# 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):
|
||||
# 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')
|
||||
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
||||
[ -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._-' '_')
|
||||
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
|
||||
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
|
||||
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 Stop hook already blocked this stop. Another plugin's → nothing to add.
|
||||
[ -f "$marker" ] || exit 0
|
||||
phase=after
|
||||
else
|
||||
rm -f "$marker" 2>/dev/null || true
|
||||
phase=check
|
||||
# A note no prompt has carried: its lines join this turn's, asked afresh.
|
||||
if [ -f "$note_file" ]; then
|
||||
if [ -s "$asked_file" ]; then
|
||||
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
|
||||
cat "$asked_file" >> "$ledger" 2>/dev/null || true
|
||||
fi
|
||||
rm -f "$note_file" "$asked_file" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if [ ! -s "$ledger" ]; then
|
||||
rm -f "$marker" 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
[ -s "$asked_file" ] || [ -s "$ledger" ] || 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}}"
|
||||
q="phase=${phase}&written=${written_enc}"
|
||||
scope_q=""
|
||||
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
|
||||
# needs it to tell the agent which repo a just-written shape belongs to.
|
||||
case "$scope" in
|
||||
@@ -81,25 +80,41 @@ case "$scope" in
|
||||
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
|
||||
if [ -n "$remote" ]; then
|
||||
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
|
||||
;;
|
||||
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 \
|
||||
-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
|
||||
rm -f "$marker" "$ledger" 2>/dev/null || true
|
||||
exit 0
|
||||
note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
|
||||
if [ -n "$note" ]; then
|
||||
printf '%s' "$note" > "$note_file" 2>/dev/null || true
|
||||
printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
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)"
|
||||
rm -f "$ledger" 2>/dev/null || true
|
||||
exit 0
|
||||
|
||||
@@ -20,6 +20,10 @@ What only Claude Code needs said:
|
||||
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
|
||||
how to correct a moment that fired wrongly.
|
||||
- **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
|
||||
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
|
||||
|
||||
@@ -32,6 +32,7 @@ grimoire_config || exit 0
|
||||
|
||||
body=$(curl -fsS --max-time 8 \
|
||||
-H "Authorization: Bearer ${token}" \
|
||||
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
|
||||
"${url%/}/api/plugin/processes" 2>/dev/null) || 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}"
|
||||
# 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")"
|
||||
# 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
|
||||
# hook, for the reason the rule file is.
|
||||
rulingsfile="$state_dir/${safe_sid}.rulings.ids"
|
||||
@@ -112,6 +114,7 @@ fi
|
||||
# than silence. See the header.
|
||||
body=$(curl -fsS --max-time 5 \
|
||||
-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
|
||||
|
||||
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": [
|
||||
{
|
||||
"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
|
||||
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
|
||||
a mistake to miss. An injected line names which in its opening words —
|
||||
*"Standing rule that may apply…"* against *"Preference that may apply…"* —
|
||||
a lesson arrives in the records menu marked `lesson`, under a header that
|
||||
says outright that it binds nothing, and every payload carries `kind`.
|
||||
a mistake to miss. A line names which up front (*"Rule 11 …; it binds:"*,
|
||||
*"Preference 173 …; how this has been done before:"*) and on first mention
|
||||
quotes the statement; `get_rule(id)` gives the why and how. A lesson is
|
||||
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
|
||||
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
|
||||
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
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
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
|
||||
— its moments are part of writing it, and the
|
||||
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
|
||||
- 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
|
||||
- How strongly it arrives — enforcement, salience, and the act it governs
|
||||
- A ruling goes on the System it governs
|
||||
- A lesson grows each time it proves itself
|
||||
- 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
|
||||
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,
|
||||
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
|
||||
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
|
||||
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.**
|
||||
`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
|
||||
|
||||
@@ -50,6 +50,7 @@ asyncio_mode = "auto"
|
||||
testpaths = ["tests"]
|
||||
markers = [
|
||||
"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]
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
# 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:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--no-version", action="store_true",
|
||||
@@ -800,6 +827,7 @@ def main() -> int:
|
||||
check_fail_open()
|
||||
check_local_prior_art_needs_no_instance()
|
||||
check_session_context_reports_its_version()
|
||||
check_payload_bound()
|
||||
if not args.no_version:
|
||||
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"):
|
||||
logger.warning(
|
||||
"TRUST_PROXY_HEADERS is replaced by TRUSTED_PROXY_HOPS (now %d). Set "
|
||||
"TRUSTED_PROXY_HOPS to the number of proxies in front of Grimoire and "
|
||||
"remove TRUST_PROXY_HEADERS.",
|
||||
"TRUST_PROXY_HEADERS is not used (the starting proxy hop count is %d). "
|
||||
"Remove it; set the count in Settings → Config, or TRUSTED_PROXY_HOPS "
|
||||
"to change the starting value.",
|
||||
Config.TRUSTED_PROXY_HOPS,
|
||||
)
|
||||
|
||||
@@ -198,9 +198,20 @@ def create_app() -> Quart:
|
||||
from grimoire.services.logging import start_log_retention_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_notification_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.
|
||||
#
|
||||
|
||||
@@ -124,8 +124,14 @@ class Config:
|
||||
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
|
||||
# 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_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
|
||||
# value per deployment (the repo serving the plugin), so it's a config
|
||||
|
||||
@@ -168,6 +168,9 @@ _READ_ONLY_TOOLS = frozenset({
|
||||
# rules are unjudged and which proposals wait. Reads of the caller's own
|
||||
# rules, as list_rules is.
|
||||
"rules_to_mount", "rule_moment_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
|
||||
@@ -229,9 +232,14 @@ _WRITE_TOOLS = frozenset({
|
||||
# Proposing moments for a rule writes a judgment row; judging one mounts
|
||||
# or unmounts the rule.
|
||||
"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
|
||||
# proposal.
|
||||
"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
|
||||
# prose the agent authored, `rule_outcome`'s reason for being a write.
|
||||
"judge_menu",
|
||||
|
||||
@@ -15,7 +15,10 @@ from __future__ import annotations
|
||||
from grimoire.mcp._context import current_user_id
|
||||
from grimoire.services import moment_actions as actions_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 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
|
||||
|
||||
|
||||
@@ -42,9 +45,18 @@ async def list_moments() -> dict:
|
||||
`via: "default"` ships with the product, `via: "install"` is this
|
||||
install's own mapping. `removed_defaults` are shipped defaults this install
|
||||
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.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
|
||||
|
||||
|
||||
@@ -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:
|
||||
mcp.tool(name="list_moments")(list_moments)
|
||||
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="judge_rule_moments")(judge_rule_moments)
|
||||
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:
|
||||
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"].
|
||||
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
|
||||
|
||||
@@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from grimoire.mcp._context import current_user_id
|
||||
from grimoire.services import dedup as dedup_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 trash as trash_svc
|
||||
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 = "",
|
||||
system_ids: list[int] | None = None,
|
||||
moments: list[str] | None = None, force: bool = False,
|
||||
enforcement: str = "inform", salience: str = "normal",
|
||||
triggers: list[dict] | None = None,
|
||||
) -> dict:
|
||||
"""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
|
||||
schedule. Pairs with verify_with; both empty is the normal case.
|
||||
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
|
||||
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
|
||||
@@ -539,6 +566,7 @@ async def create_rule(
|
||||
"""
|
||||
uid = current_user_id()
|
||||
moments = moments_svc.require_moments(moments)
|
||||
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||
if not force:
|
||||
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
|
||||
if dup is not None:
|
||||
@@ -553,8 +581,9 @@ async def create_rule(
|
||||
arose_from_id=arose_from_id,
|
||||
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
||||
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"))
|
||||
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 = "",
|
||||
system_ids: list[int] | None = None,
|
||||
moments: list[str] | None = None, force: bool = False,
|
||||
enforcement: str = "inform", salience: str = "normal",
|
||||
triggers: list[dict] | None = None,
|
||||
) -> dict:
|
||||
"""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
|
||||
create_rule. A state, not a date.
|
||||
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
|
||||
already on this project BLOCKS creation and returns its id so you
|
||||
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()
|
||||
moments = moments_svc.require_moments(moments)
|
||||
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||
derived_title = title.strip() or statement.strip().split(".")[0][:50]
|
||||
if not force:
|
||||
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,
|
||||
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
||||
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"))
|
||||
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,
|
||||
verify_with: str = "", expires_when: str = "", kind: str = "",
|
||||
clear_fields: list[str] | None = None,
|
||||
enforcement: str = "", salience: str = "",
|
||||
triggers: list[dict] | None = None,
|
||||
) -> dict:
|
||||
"""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
|
||||
state, not a date. See create_rule.
|
||||
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()
|
||||
moments = moments_svc.require_moments(moments)
|
||||
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||
fields: dict = {}
|
||||
if title:
|
||||
fields["title"] = title
|
||||
@@ -759,12 +844,16 @@ async def update_rule(
|
||||
fields["expires_when"] = expires_when
|
||||
if order_index >= 0:
|
||||
fields["order_index"] = order_index
|
||||
if enforcement:
|
||||
fields["enforcement"] = enforcement
|
||||
if salience:
|
||||
fields["salience"] = salience
|
||||
rule = await rulebooks_svc.update_rule(
|
||||
rule_id, uid, clear=clear_fields or (), **fields,
|
||||
)
|
||||
if rule is None:
|
||||
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 ─────────────────────────────────────────────────────────
|
||||
@@ -786,7 +875,8 @@ async def create_preference(
|
||||
arose_from_id: int, why: str = "", how_to_apply: str = "",
|
||||
order_index: int = 0, system_ids: list[int] | None = None,
|
||||
moments: list[str] | None = None,
|
||||
force: bool = False,
|
||||
force: bool = False, salience: str = "normal",
|
||||
triggers: list[dict] | None = None,
|
||||
) -> dict:
|
||||
"""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
|
||||
finished belongs at work.finish and reply.report, where nothing
|
||||
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
|
||||
preference, not for one that is "mostly" different — a mostly
|
||||
different preference is an update. A RULE that already answers
|
||||
@@ -869,6 +973,7 @@ async def create_preference(
|
||||
"""
|
||||
uid = current_user_id()
|
||||
moments = moments_svc.require_moments(moments)
|
||||
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||
if not when_to_apply.strip():
|
||||
raise ValueError(
|
||||
"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,
|
||||
kind="preference", arose_from_id=arose_from_id,
|
||||
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"))
|
||||
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,
|
||||
system_ids: list[int] | None = None,
|
||||
moments: list[str] | None = None, clear_fields: list[str] | None = None,
|
||||
salience: str = "",
|
||||
triggers: list[dict] | None = None,
|
||||
) -> dict:
|
||||
"""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
|
||||
create_preference); omit to leave them alone.
|
||||
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()
|
||||
moments = moments_svc.require_moments(moments)
|
||||
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||
if not arose_from_id:
|
||||
raise ValueError(
|
||||
"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
|
||||
if order_index >= 0:
|
||||
fields["order_index"] = order_index
|
||||
if salience:
|
||||
fields["salience"] = salience
|
||||
rule = await rulebooks_svc.update_rule(
|
||||
rule_id, uid, clear=clear_fields or (), **fields,
|
||||
)
|
||||
if rule is None:
|
||||
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:
|
||||
|
||||
@@ -528,6 +528,15 @@ async def retrieval_telemetry(
|
||||
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.
|
||||
|
||||
`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`:
|
||||
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
|
||||
on a sample of logged menus, `within_budget` against `beyond_budget` and
|
||||
|
||||
@@ -271,7 +271,9 @@ async def create_task(
|
||||
|
||||
Args:
|
||||
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.
|
||||
priority: One of: low, medium, high, or 'none'. Omit (empty string) to leave unset.
|
||||
project_id: Associate with a project (0 = no project).
|
||||
@@ -482,6 +484,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
|
||||
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
|
||||
`claim`. That is what brings the task and its newest
|
||||
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.note_usage import NoteUsageEvent # 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.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
|
||||
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
|
||||
@@ -83,6 +86,7 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
|
||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
|
||||
# After rules: it foreign-keys them.
|
||||
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.forge_connection import ForgeConnection # noqa: E402, F401
|
||||
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
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
|
||||
WAYS = (PUSHED, 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.
|
||||
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
|
||||
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__ = (
|
||||
Index("ix_retrieval_logs_created_at", "created_at"),
|
||||
@@ -99,4 +105,6 @@ class RetrievalLog(Base):
|
||||
"min_score": self.min_score,
|
||||
"result_ids": self.result_ids,
|
||||
"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.
|
||||
# CHECK ck_rules_kind (migration 0098).
|
||||
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)
|
||||
how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
# 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
|
||||
# cannot be misread.
|
||||
"kind": self.kind or "rule",
|
||||
"enforcement": self.enforcement or "inform",
|
||||
"salience": self.salience or "normal",
|
||||
"why": self.why or "",
|
||||
"how_to_apply": self.how_to_apply 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)),
|
||||
)
|
||||
|
||||
|
||||
# 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):
|
||||
"""A typed edge between two rules. Each kind exists because without it a
|
||||
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
|
||||
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
|
||||
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.
|
||||
The hop count says how many proxies stand in front of the app. An admin sets
|
||||
it in Settings → Config; until they do, it is `TRUSTED_PROXY_HOPS` from the
|
||||
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
|
||||
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))]
|
||||
|
||||
|
||||
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
|
||||
# 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:
|
||||
@@ -78,3 +105,60 @@ def apply_https_headers(response) -> None:
|
||||
HTTPS; plain HTTP is a supported way to run it."""
|
||||
if is_https():
|
||||
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:
|
||||
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
|
||||
TRUSTED_PROXY_HOPS. A hop count that is too low keys every caller on the
|
||||
proxy's address, so they all share one bucket.
|
||||
The bucket key is the client address from grimoire/proxy.py, read by the
|
||||
proxy hop count (Settings → Config). A count that is too low keys every
|
||||
caller on the proxy's address, so they all share one bucket.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
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)
|
||||
_lock = asyncio.Lock()
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@ import json
|
||||
|
||||
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.config import Config
|
||||
from grimoire.proxy import client_ip
|
||||
from grimoire.services import proxy_settings
|
||||
from grimoire.services.auth import (
|
||||
create_invitation,
|
||||
delete_user,
|
||||
@@ -260,7 +263,6 @@ async def test_smtp():
|
||||
@admin_bp.route("/forge-webhook", methods=["GET"])
|
||||
@admin_required
|
||||
async def get_forge_webhook_settings():
|
||||
from grimoire.config import Config
|
||||
from grimoire.routes.webhooks import FORGE_WEBHOOK_SECRET_KEY
|
||||
|
||||
webhook_secret = (
|
||||
@@ -346,6 +348,44 @@ async def update_base_url():
|
||||
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_required
|
||||
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.config import Config
|
||||
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 (
|
||||
authenticate,
|
||||
change_password,
|
||||
@@ -49,7 +49,7 @@ async def register():
|
||||
if not Config.LOCAL_AUTH_ENABLED:
|
||||
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):
|
||||
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():
|
||||
return jsonify({"error": "Registration is closed"}), 403
|
||||
|
||||
@@ -79,7 +79,7 @@ async def login():
|
||||
if not Config.LOCAL_AUTH_ENABLED:
|
||||
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):
|
||||
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()
|
||||
username = (data.get("username") or "").strip()
|
||||
password = data.get("password") or ""
|
||||
@@ -235,7 +235,7 @@ async def forgot_password():
|
||||
@auth_bp.route("/reset-password", methods=["POST"])
|
||||
async def reset_password():
|
||||
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()
|
||||
token = (data.get("token") or "").strip()
|
||||
new_password = data.get("new_password") or ""
|
||||
|
||||
@@ -6,6 +6,7 @@ from quart import Blueprint, jsonify, request
|
||||
|
||||
from grimoire.auth import login_required, get_current_user_id
|
||||
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.notes import (
|
||||
build_note_graph,
|
||||
@@ -194,6 +195,37 @@ async def resolve_title_route():
|
||||
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"])
|
||||
@login_required
|
||||
async def find_duplicate_records_route():
|
||||
|
||||
+219
-23
@@ -14,12 +14,16 @@ from quart import Blueprint, g, jsonify, request
|
||||
|
||||
from grimoire.auth import admin_required, get_current_user_id, login_required
|
||||
from grimoire.config import Config
|
||||
from grimoire.services import hook_payload as hook_payload_svc
|
||||
from grimoire.services import lesson_rules as lesson_rules_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 reply_shapes as reply_shapes_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 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 shape_check as shape_check_svc
|
||||
from grimoire.services import task_claims as task_claims_svc
|
||||
@@ -36,6 +40,38 @@ plugin_bp = Blueprint("plugin", __name__, url_prefix="/api/plugin")
|
||||
_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]:
|
||||
"""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()]
|
||||
@@ -94,6 +130,11 @@ async def session_context():
|
||||
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")
|
||||
@login_required
|
||||
@memoized_query_embeddings
|
||||
@@ -137,11 +178,17 @@ async def autoinject_retrieve():
|
||||
one-line reminder when present; the hook's
|
||||
ledger is swept on compaction, which is how the
|
||||
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
|
||||
in a reply and this is the last point before it is written, so the core
|
||||
shape and whatever is mounted on `reply.report` lead the payload. Fresh
|
||||
shape keys come back as `shape_keys` for the ledger.
|
||||
ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules
|
||||
this prompt reaches and those mounted on `reply.report`, then the turn's
|
||||
reply shape, then the records menu. Every turn ends in a reply and this
|
||||
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
|
||||
but nothing else: the notes menu can be disabled, thresholded and top-k'd
|
||||
@@ -182,12 +229,35 @@ async def autoinject_retrieve():
|
||||
project_id=project_id,
|
||||
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
|
||||
held=frozenset(held_rule_ids),
|
||||
record=False,
|
||||
)
|
||||
blocks = [b for b in (turn["context"], rules["context"], result["context"], proposal) if b]
|
||||
result["context"] = "\n\n".join(blocks)
|
||||
result["rule_ids"] = list(dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]))
|
||||
result["shape_keys"] = [k for k, form in turn["shape_forms"].items()
|
||||
if form == reply_shapes_svc.FULL]
|
||||
# One payload, in the one order: the rules, then the reply shape, then
|
||||
# what the last turn left unjudged, then the records menu, then the
|
||||
# lesson-rule proposal, fitted to the budget.
|
||||
carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS]
|
||||
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"}),
|
||||
*([hook_payload_svc.Part(text=proposal)] if proposal else []),
|
||||
])
|
||||
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)
|
||||
|
||||
|
||||
@@ -265,6 +335,15 @@ async def pre_tool_rules():
|
||||
cwd=(request.args.get("cwd") or "").strip(),
|
||||
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)
|
||||
|
||||
|
||||
@@ -301,15 +380,24 @@ async def moment():
|
||||
`moments` (the names reached). A lookup, not a ranked search: no
|
||||
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
|
||||
|
||||
A moment that carries a default reply shape brings it too,
|
||||
ahead of the rules: in full unless `shapes_seen` names it, then as its
|
||||
reminder. `shape_keys` are the ones sent in full, for the hook's ledger.
|
||||
A moment that carries a default reply shape brings it too, after the
|
||||
rules: in full unless `shapes_seen` names it, then as its reminder. The
|
||||
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 {}
|
||||
tool = str(event.get("tool_name") or "").strip()
|
||||
tool_input = event.get("tool_input")
|
||||
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()
|
||||
reached, result = await moment_delivery_svc.deliver_for_act(
|
||||
g.user.id, tool, tool_input if isinstance(tool_input, dict) else {},
|
||||
@@ -320,13 +408,20 @@ async def moment():
|
||||
shapes, forms = moment_delivery_svc.shapes_for_act(
|
||||
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
|
||||
)
|
||||
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=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")
|
||||
context = "\n\n".join(b for b in ("\n\n".join(shapes), "\n".join(result.lines)) if b)
|
||||
return jsonify({
|
||||
"context": context,
|
||||
"rule_ids": result.rule_ids,
|
||||
"context": fitted.context,
|
||||
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
|
||||
"moments": [hit["moment"] for hit in reached],
|
||||
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
|
||||
"decision": result.decision,
|
||||
})
|
||||
|
||||
|
||||
@@ -336,7 +431,10 @@ async def rule_opened():
|
||||
"""A session opened a rule shortly after these acts.
|
||||
|
||||
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
|
||||
rule belongs on them; once a pair has repeated across enough distinct
|
||||
sessions, `context` carries the line asking the reader to offer the
|
||||
@@ -349,8 +447,13 @@ async def rule_opened():
|
||||
rule_id = int(data.get("rule_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
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")
|
||||
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": ""})
|
||||
project_id, _repo, _unbound = await _project_scope()
|
||||
return jsonify(await judgments_svc.opened_after(
|
||||
@@ -359,6 +462,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")
|
||||
@login_required
|
||||
@memoized_query_embeddings
|
||||
@@ -512,6 +693,19 @@ async def write_path_prior_art():
|
||||
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
|
||||
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)
|
||||
|
||||
|
||||
@@ -545,9 +739,11 @@ async def shape_check():
|
||||
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
|
||||
— 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.
|
||||
A hook blocks only on a reason it received, so only on a block that was
|
||||
recorded, and never on the stop that follows one (`phase=after`).
|
||||
outcome, and returns the `note` the agent reads at the start of its next
|
||||
turn. Nothing here holds the reply: the question rides the next prompt,
|
||||
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
|
||||
this records telemetry the way /reply-rules records its section check. It changes no ledger
|
||||
@@ -594,8 +790,8 @@ async def shape_check():
|
||||
)
|
||||
body["outcome"] = outcome
|
||||
body["unjudged"] = unjudged
|
||||
if outcome == "blocked":
|
||||
body["reason"] = shape_check_svc.block_reason(
|
||||
if outcome == "noted":
|
||||
body["note"] = shape_check_svc.note_text(
|
||||
unjudged, project_id=project_id, repo=repo_key or repo,
|
||||
)
|
||||
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 moments as moments_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 rulebooks as rulebooks_svc
|
||||
from grimoire.services.retrieval_telemetry import moment_usage
|
||||
@@ -57,6 +61,24 @@ async def get_surfaces_route():
|
||||
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"])
|
||||
@login_required
|
||||
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):
|
||||
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
|
||||
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")
|
||||
|
||||
|
||||
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):
|
||||
"""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.
|
||||
@@ -28,6 +40,17 @@ def _moments_or_refusal(data: dict):
|
||||
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_bp.get("/rulebooks")
|
||||
@@ -184,6 +207,13 @@ async def create_rule(topic_id: int):
|
||||
moments, refused = _moments_or_refusal(data)
|
||||
if 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:
|
||||
rule = await rulebooks_svc.create_rule(
|
||||
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,
|
||||
verify_with=data.get("verify_with", ""),
|
||||
expires_when=data.get("expires_when", ""),
|
||||
enforcement=enforcement, salience=salience,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 404
|
||||
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
|
||||
|
||||
|
||||
@@ -234,7 +265,7 @@ async def update_rule(rule_id: int):
|
||||
k: v for k, v in data.items()
|
||||
if k in ("title", "statement", "why", "how_to_apply", "order_index",
|
||||
"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
|
||||
# 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)
|
||||
if refused:
|
||||
return refused
|
||||
triggers, refused = _triggers_or_refusal(data)
|
||||
if refused:
|
||||
return refused
|
||||
try:
|
||||
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
if rule is None:
|
||||
return jsonify({"error": "rule not found"}), 404
|
||||
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)
|
||||
if 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:
|
||||
rule = await rulebooks_svc.create_project_rule(
|
||||
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,
|
||||
verify_with=data.get("verify_with", ""),
|
||||
expires_when=data.get("expires_when", ""),
|
||||
enforcement=enforcement, salience=salience,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 404
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -95,6 +95,10 @@ async def update_settings_route():
|
||||
|
||||
if to_save:
|
||||
await set_settings_batch(uid, to_save)
|
||||
# The gate caches its bar for a few minutes; a new rate takes at once.
|
||||
from grimoire.services import cue_gate
|
||||
if cue_gate.RATE_KEY in data:
|
||||
cue_gate.forget(uid)
|
||||
|
||||
settings = await get_all_settings(uid)
|
||||
return jsonify(_masked(settings))
|
||||
|
||||
@@ -23,8 +23,10 @@ from grimoire.models.family import (
|
||||
)
|
||||
from grimoire.models.rulebook import (
|
||||
RuleRelation, rule_moments as rule_moments_t, rule_systems as rule_systems_t,
|
||||
rule_triggers as rule_triggers_t,
|
||||
)
|
||||
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
|
||||
from grimoire.models.rule_field_judgment import RuleFieldJudgment
|
||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
||||
from grimoire.models.code_shape import CodeShape, CodeShapeEvent, CodeShapeUse
|
||||
from grimoire.models.project import Project
|
||||
@@ -113,7 +115,12 @@ logger = logging.getLogger(__name__)
|
||||
# section still restore — the key is simply not read.
|
||||
# v28 instance_id in the header: the id lineage of the store the backup came
|
||||
# from. A live instance rolls back only to a backup with its own id.
|
||||
BACKUP_VERSION = 28
|
||||
# v29 rule_triggers: the typed predicates on the act that deliver a rule or
|
||||
# make its mount conditional. Nothing in the rule's text records them.
|
||||
# v30 rule_field_judgments: suggested, agreed and rejected values for a rule's
|
||||
# enforcement, salience and triggers. Lose them and a weighed corpus reads
|
||||
# as unweighed, and every rejected value is proposed again.
|
||||
BACKUP_VERSION = 30
|
||||
|
||||
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
|
||||
# below, these two lists must together account for the entire schema — which is
|
||||
@@ -158,6 +165,8 @@ _BACKED_UP = [
|
||||
"moment_mappings",
|
||||
"rule_moments",
|
||||
"rule_moment_judgments",
|
||||
"rule_triggers",
|
||||
"rule_field_judgments",
|
||||
# Family canon. `platforms` is global like
|
||||
# canonical_systems and rides every export for the same reason: the rows
|
||||
# below name platforms by slug, and a partial catalog restores partial
|
||||
@@ -183,6 +192,15 @@ _NOT_INCLUDED = [
|
||||
"app_logs", "notifications",
|
||||
"invitation_tokens", "password_reset_tokens",
|
||||
"retrieval_logs",
|
||||
# Per-session delivery rows, keyed by session ids that mean nothing on
|
||||
# another instance and pruned after months anyway. The ordering reads
|
||||
# them as history; a restored instance rebuilds it within weeks.
|
||||
"rule_deliveries",
|
||||
# Adherence verdicts on those deliveries, keyed by the same session ids
|
||||
# and pruned with them.
|
||||
"rule_adherence",
|
||||
# The same per-session ledger for every other record kind.
|
||||
"record_deliveries",
|
||||
# Verdicts on retrieval_logs rows, so they go where their subject
|
||||
# goes: a restore that carried a judgment of a call it did not carry would
|
||||
# leave a verdict on nothing. A sample, re-takeable by the review pass.
|
||||
@@ -261,6 +279,8 @@ _COLUMN_EXCLUSIONS: dict[str, set[str]] = {
|
||||
"lesson_rule_links": {"id"},
|
||||
# The same shape: the (rule, moment) pair is the row.
|
||||
"rule_moment_judgments": {"id"},
|
||||
# And again: the (rule, field, value) triple is the row.
|
||||
"rule_field_judgments": {"id"},
|
||||
# Keyed by the lesson itself; nothing to exclude, every column travels.
|
||||
"lesson_no_rule": set(),
|
||||
"note_usage_events": {"id"},
|
||||
@@ -368,6 +388,7 @@ _IMPORT_COLUMN_EXCLUSIONS: dict[str, set[str]] = {
|
||||
"rule_relations": {"id", "created_at"},
|
||||
"lesson_rule_links": {"id"},
|
||||
"rule_moment_judgments": {"id"},
|
||||
"rule_field_judgments": {"id"},
|
||||
"lesson_no_rule": set(),
|
||||
"note_usage_events": {"id"},
|
||||
"rule_usage_events": {"id"},
|
||||
@@ -798,6 +819,15 @@ def _rule_moment_rows(rows) -> list[dict]:
|
||||
return [{"rule_id": rule_id, "moment": moment} for rule_id, moment in rows]
|
||||
|
||||
|
||||
def _rule_trigger_rows(rows) -> list[dict]:
|
||||
"""A rule's triggers. Kind, pattern and moment mean the same on every
|
||||
install, so only the rule id needs remapping on the way back in."""
|
||||
return [
|
||||
{"rule_id": rule_id, "kind": kind, "pattern": pattern, "moment": moment or ""}
|
||||
for rule_id, kind, pattern, moment in rows
|
||||
]
|
||||
|
||||
|
||||
def _rule_moment_judgment_rows(rows) -> list[dict]:
|
||||
"""Proposals and judgments about a rule's moments (v23). The rule id is a
|
||||
SOURCE id, remapped at restore; the moment is a catalog name."""
|
||||
@@ -813,6 +843,21 @@ def _rule_moment_judgment_rows(rows) -> list[dict]:
|
||||
]
|
||||
|
||||
|
||||
def _rule_field_judgment_rows(rows) -> list[dict]:
|
||||
"""Suggested, agreed and rejected values for a rule's enforcement,
|
||||
salience and triggers (v30). The rule id is a SOURCE id, remapped at
|
||||
restore."""
|
||||
return [
|
||||
{
|
||||
"rule_id": r.rule_id, "field": r.field, "value": r.value, "state": r.state,
|
||||
"source": r.source, "note": r.note, "evidence": r.evidence,
|
||||
"judged_at": r.judged_at.isoformat() if r.judged_at else None,
|
||||
"created_at": r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def _rule_system_rows(rows) -> list[dict]:
|
||||
"""A rule's area tags, carried by canonical SLUG for the same reason the
|
||||
Systems are: the catalog is global and its ids are per-install."""
|
||||
@@ -959,6 +1004,7 @@ def _rule_rows(rows) -> list[dict]:
|
||||
"title": r.title, "statement": r.statement, "why": r.why,
|
||||
"how_to_apply": r.how_to_apply, "order_index": r.order_index,
|
||||
"when_to_apply": r.when_to_apply, "kind": r.kind,
|
||||
"enforcement": r.enforcement, "salience": r.salience,
|
||||
"verify_with": r.verify_with, "expires_when": r.expires_when,
|
||||
"verified_at": r.verified_at.isoformat() if r.verified_at else None,
|
||||
"arose_from_id": r.arose_from_id,
|
||||
@@ -1015,9 +1061,18 @@ async def export_full_backup() -> dict:
|
||||
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||
.order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||
)).all()
|
||||
rule_trigger_rows = (await session.execute(
|
||||
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
|
||||
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
|
||||
.order_by(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
|
||||
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
|
||||
)).all()
|
||||
rule_moment_judgments = (await session.execute(
|
||||
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
|
||||
)).scalars().all()
|
||||
rule_field_judgments = (await session.execute(
|
||||
select(RuleFieldJudgment).order_by(RuleFieldJudgment.id)
|
||||
)).scalars().all()
|
||||
rule_relations = (await session.execute(select(RuleRelation).order_by(RuleRelation.id))).scalars().all()
|
||||
lesson_rule_links = (await session.execute(select(LessonRuleLink).order_by(LessonRuleLink.id))).scalars().all()
|
||||
lesson_no_rule = (await session.execute(select(LessonNoRule).order_by(LessonNoRule.lesson_id))).scalars().all()
|
||||
@@ -1107,7 +1162,9 @@ async def export_full_backup() -> dict:
|
||||
"canonical_systems": _canonical_system_rows(canonical_systems),
|
||||
"rule_systems": _rule_system_rows(rule_system_rows),
|
||||
"rule_moments": _rule_moment_rows(rule_moment_rows),
|
||||
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
|
||||
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
|
||||
"rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
|
||||
"rule_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
|
||||
@@ -1268,9 +1325,18 @@ async def export_user_backup(user_id: int) -> dict:
|
||||
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||
.where(rule_moments_t.c.rule_id.in_(_rule_ids))
|
||||
)).all() if _rule_ids else []
|
||||
rule_trigger_rows = (await session.execute(
|
||||
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
|
||||
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
|
||||
.where(rule_triggers_t.c.rule_id.in_(_rule_ids))
|
||||
)).all() if _rule_ids else []
|
||||
rule_moment_judgments = (await session.execute(
|
||||
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
|
||||
)).scalars().all() if _rule_ids else []
|
||||
rule_field_judgments = (await session.execute(
|
||||
select(RuleFieldJudgment).where(RuleFieldJudgment.rule_id.in_(_rule_ids))
|
||||
.order_by(RuleFieldJudgment.id)
|
||||
)).scalars().all() if _rule_ids else []
|
||||
# Scoped through the RULE, not the version's user_id. That column is
|
||||
# the ACTOR, so filtering on it would carry the
|
||||
# versions this user wrote on someone ELSE's rule and drop the ones
|
||||
@@ -1394,7 +1460,9 @@ async def export_user_backup(user_id: int) -> dict:
|
||||
"canonical_systems": _canonical_system_rows(canonical_systems),
|
||||
"rule_systems": _rule_system_rows(rule_system_rows),
|
||||
"rule_moments": _rule_moment_rows(rule_moment_rows),
|
||||
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
|
||||
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
|
||||
"rule_field_judgments": _rule_field_judgment_rows(rule_field_judgments),
|
||||
"rule_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
"lesson_no_rule": _lesson_no_rule_rows(lesson_no_rule),
|
||||
@@ -1717,6 +1785,15 @@ def _build_rule(row: dict, maps: _Maps) -> Rule | None:
|
||||
# way would restore an old backup with things that had always bound
|
||||
# quietly not binding.
|
||||
kind=row.get("kind") or "rule",
|
||||
# An archive from before these columns restores every rule as it
|
||||
# behaved then: a line beside the work, at normal rank. A preference
|
||||
# is always `inform`, whatever the archive says, since the CHECK would
|
||||
# refuse anything else and take the whole restore down with it.
|
||||
enforcement=(
|
||||
"inform" if (row.get("kind") or "rule") == "preference"
|
||||
else (row.get("enforcement") if row.get("enforcement") in ("enforce", "hold", "inform") else "inform")
|
||||
),
|
||||
salience=row.get("salience") if row.get("salience") in ("high", "normal", "low") else "normal",
|
||||
verify_with=row.get("verify_with") or None,
|
||||
expires_when=row.get("expires_when") or None,
|
||||
# Restored as-is, NOT reset to null. `verified_at` records when someone
|
||||
@@ -1817,6 +1894,25 @@ def _build_rule_moment_judgment(row: dict, maps: _Maps) -> RuleMomentJudgment |
|
||||
)
|
||||
|
||||
|
||||
def _build_rule_field_judgment(row: dict, maps: _Maps) -> RuleFieldJudgment | None:
|
||||
"""Skipped when its rule did not restore, for the reason a moment
|
||||
judgment is."""
|
||||
rule = maps.rules.get(row.get("rule_id", 0))
|
||||
if rule is None or not row.get("field") or row.get("value") is None:
|
||||
return None
|
||||
return RuleFieldJudgment(
|
||||
rule_id=rule,
|
||||
field=row["field"],
|
||||
value=row["value"],
|
||||
state=row.get("state") or "suggested",
|
||||
source=row.get("source") or "pass",
|
||||
note=row.get("note") or None,
|
||||
evidence=row.get("evidence"),
|
||||
judged_at=_dt_or_none(row.get("judged_at")),
|
||||
created_at=_dt(row.get("created_at")),
|
||||
)
|
||||
|
||||
|
||||
def _build_platform(row: dict, maps: _Maps) -> Platform | None:
|
||||
"""Matched on SLUG, like a canonical system: this install seeded the
|
||||
standard platforms from its migrations, so the common case creates nothing
|
||||
@@ -2407,6 +2503,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
||||
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
|
||||
"code_shape_uses": 0, "canonical_systems": 0,
|
||||
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
|
||||
"rule_triggers": 0, "rule_field_judgments": 0,
|
||||
"rule_relations": 0, "rule_versions": 0,
|
||||
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
|
||||
"lesson_no_rule": 0, "moment_mappings": 0,
|
||||
@@ -2604,6 +2701,18 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
||||
))
|
||||
stats["rule_moments"] += 1
|
||||
|
||||
# A rule's triggers (v29), the same join-table shape; archives before
|
||||
# v29 carry none.
|
||||
for rt in data.get("rule_triggers", []):
|
||||
mapped_rule = maps.rules.get(rt.get("rule_id", 0))
|
||||
kind, pattern = rt.get("kind"), rt.get("pattern")
|
||||
if mapped_rule is None or kind not in ("tool", "path", "command", "keyword") or not pattern:
|
||||
continue
|
||||
await session.execute(rule_triggers_t.insert().values(
|
||||
rule_id=mapped_rule, kind=kind, pattern=pattern, moment=rt.get("moment") or "",
|
||||
))
|
||||
stats["rule_triggers"] += 1
|
||||
|
||||
# Proposals and judgments about those mounts (v23); archives before
|
||||
# v23 carry none, and every rule restores unjudged.
|
||||
for rj in data.get("rule_moment_judgments", []):
|
||||
@@ -2613,6 +2722,15 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
|
||||
session.add(judgment)
|
||||
stats["rule_moment_judgments"] += 1
|
||||
|
||||
# Weighed values for each rule (v30); archives before v30 carry none, and
|
||||
# every rule restores unweighed.
|
||||
for rf in data.get("rule_field_judgments", []):
|
||||
weighed = _build_rule_field_judgment(rf, maps)
|
||||
if weighed is None:
|
||||
continue
|
||||
session.add(weighed)
|
||||
stats["rule_field_judgments"] += 1
|
||||
|
||||
for rr in data.get("rule_relations", []):
|
||||
relation = _build_rule_relation(rr, maps)
|
||||
if relation is None:
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
"""When a record found by resemblance alone may speak: the cue-swap gate.
|
||||
|
||||
WHY A FIXED BAR CANNOT DO THIS
|
||||
|
||||
Every message resembles something in a store of any size. The best score that
|
||||
N unrelated records reach against a message keeps rising as N grows, so a
|
||||
similarity bar that is quiet on a small store fires on nearly every message on
|
||||
a large one: the bar measures the store, not the message. (*The Price of Scale
|
||||
in Proactive Memory Recall*, arXiv 2610.34507: a cosine bar tuned to 5% false
|
||||
alarms on 8 memories hit 84–100% at 2,048, and a cross-encoder fared no
|
||||
better.) A floor tuned on one install says nothing about another, or about the
|
||||
same install a year later.
|
||||
|
||||
WHAT THE GATE ASKS INSTEAD
|
||||
|
||||
Not "is this score high" but "is this message's best match unusual for this
|
||||
reader". The comparison set is the best score each of the user's own recent
|
||||
messages reached on the same surface and scope — already in `retrieval_logs`
|
||||
as `best_available_score`, measured before any bar. A line may speak only when
|
||||
its score beats all but `rate` of them: a conformal test whose null is the
|
||||
user's other cues against (very nearly) the same store. Because the null is
|
||||
drawn from the same store, the bar rises with the store by construction, and
|
||||
on cues that match nothing in particular it fires at about `rate` however large
|
||||
the store grows.
|
||||
|
||||
The recent messages include relevant ones, so the comparison set runs high
|
||||
and the gate errs toward silence. That is the intended direction: injected
|
||||
retrieval has measured below no memory at all in three independent benchmarks,
|
||||
so a missed line costs less than a wrong one,
|
||||
and every record stays one `search` away.
|
||||
|
||||
TOO FEW CUES TO JUDGE BY IS SILENCE. Until `MIN_SAMPLE` messages have been
|
||||
searched on a surface, nothing found by resemblance is shown there. The
|
||||
searches still run and are still logged, so the gate calibrates itself within
|
||||
a session or so; records reached by number, path or moment are not gated.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from grimoire.services.settings import get_setting
|
||||
|
||||
RATE_KEY = "kb_cue_gate_rate"
|
||||
# Percent of cues a gated surface may speak on when they match nothing in
|
||||
# particular. The paper's cue-swap gate fired on 6–8% against 57% for the
|
||||
# deployed similarity bar; 10 sits just above it so a store whose cues are
|
||||
# mostly relevant is not muted outright.
|
||||
RATE_DEFAULT = 10
|
||||
RATE_MIN, RATE_MAX = 1, 50
|
||||
|
||||
# At most this many lines found by resemblance per call, whatever the arm's
|
||||
# search width: the top one or two, and the reader asks for more.
|
||||
LINES = 2
|
||||
|
||||
SAMPLE = 200
|
||||
MIN_SAMPLE = 20
|
||||
WINDOW_DAYS = 30
|
||||
_TTL_SECONDS = 300.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Gate:
|
||||
"""The bar one surface's lines must reach on this call."""
|
||||
|
||||
bar: float | None
|
||||
"""None when there are too few cues to judge by: nothing passes."""
|
||||
|
||||
sample: int
|
||||
rate: int
|
||||
scope: str = "project"
|
||||
""""project" when the comparison set is this project's own cues, "all"
|
||||
when there were too few and the user's cues everywhere stood in."""
|
||||
|
||||
def passes(self, score: float) -> bool:
|
||||
return self.bar is not None and float(score) >= self.bar
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
return {"bar": None if self.bar is None else round(self.bar, 4),
|
||||
"sample": self.sample, "rate": self.rate, "scope": self.scope,
|
||||
"calibrated": self.bar is not None}
|
||||
|
||||
|
||||
OPEN = Gate(bar=-math.inf, sample=0, rate=100, scope="open")
|
||||
"""Everything passes — for a caller that has no gate to apply."""
|
||||
|
||||
|
||||
def clamp_rate(raw) -> int:
|
||||
try:
|
||||
n = int(float(raw))
|
||||
except (TypeError, ValueError):
|
||||
return RATE_DEFAULT
|
||||
return max(RATE_MIN, min(RATE_MAX, n))
|
||||
|
||||
|
||||
def conformal_bar(null_scores, rate: int) -> float | None:
|
||||
"""The score a cue must reach to beat all but `rate`% of `null_scores`.
|
||||
|
||||
With K cues sorted ascending, a score at or above the k-th, where
|
||||
k = ceil((K + 1) * (1 - rate / 100)), has a conformal p-value of at most
|
||||
`rate`%. None when K is too small for any score to get there.
|
||||
"""
|
||||
scores = sorted(float(s) for s in null_scores if s is not None)
|
||||
k = math.ceil((len(scores) + 1) * (1 - rate / 100.0))
|
||||
if len(scores) < MIN_SAMPLE or k > len(scores) or k < 1:
|
||||
return None
|
||||
return scores[k - 1]
|
||||
|
||||
|
||||
_cache: dict[tuple, tuple[float, Gate]] = {}
|
||||
|
||||
|
||||
async def _null_scores(user_id: int, source: str, project_id: int | None,
|
||||
*, any_project: bool) -> list[float]:
|
||||
from sqlalchemy import select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.retrieval_log import RetrievalLog
|
||||
|
||||
since = datetime.now(timezone.utc) - timedelta(days=WINDOW_DAYS)
|
||||
stmt = (
|
||||
select(RetrievalLog.best_available_score)
|
||||
.where(
|
||||
RetrievalLog.source == source,
|
||||
RetrievalLog.user_id == user_id,
|
||||
RetrievalLog.created_at >= since,
|
||||
RetrievalLog.best_available_score.isnot(None),
|
||||
)
|
||||
.order_by(RetrievalLog.created_at.desc())
|
||||
.limit(SAMPLE)
|
||||
)
|
||||
if not any_project:
|
||||
stmt = stmt.where(RetrievalLog.project_id.is_not_distinct_from(project_id))
|
||||
async with async_session() as session:
|
||||
return [float(s) for (s,) in (await session.execute(stmt)).all()]
|
||||
|
||||
|
||||
async def gate_for(user_id: int, source: str, project_id: int | None) -> Gate:
|
||||
"""This surface's gate for this user and scope, cached for a few minutes.
|
||||
|
||||
The comparison set moves by one cue per call, so re-reading it on every
|
||||
call buys nothing: a bar five minutes old is the same bar. A read that
|
||||
fails is a gate that cannot judge, which is silence.
|
||||
"""
|
||||
project_id = project_id or None
|
||||
key = (user_id, source, project_id)
|
||||
hit = _cache.get(key)
|
||||
now = time.monotonic()
|
||||
if hit and now - hit[0] < _TTL_SECONDS:
|
||||
return hit[1]
|
||||
try:
|
||||
rate = clamp_rate(await get_setting(user_id, RATE_KEY, str(RATE_DEFAULT)))
|
||||
except Exception: # noqa: BLE001 - a settings read never costs the gate
|
||||
rate = RATE_DEFAULT
|
||||
try:
|
||||
scores = await _null_scores(user_id, source, project_id, any_project=False)
|
||||
scope = "project"
|
||||
if len(scores) < MIN_SAMPLE and project_id is not None:
|
||||
scores = await _null_scores(user_id, source, project_id, any_project=True)
|
||||
scope = "all"
|
||||
gate = Gate(bar=conformal_bar(scores, rate), sample=len(scores),
|
||||
rate=rate, scope=scope)
|
||||
except Exception: # noqa: BLE001 - an unreadable gate is a quiet one
|
||||
gate = Gate(bar=None, sample=0, rate=rate, scope="unreadable")
|
||||
_cache[key] = (now, gate)
|
||||
return gate
|
||||
|
||||
|
||||
def forget(user_id: int | None = None) -> None:
|
||||
"""Drop cached gates — after the rate setting changes, so it takes at once."""
|
||||
if user_id is None:
|
||||
_cache.clear()
|
||||
return
|
||||
for key in [k for k in _cache if k[0] == user_id]:
|
||||
_cache.pop(key, None)
|
||||
|
||||
|
||||
async def readout(user_id: int, surfaces: list[tuple[str, str]], *, days: int = 7) -> list[dict]:
|
||||
"""Each gated surface as Settings shows it: the bar it holds lines to now,
|
||||
from the user's cues on every project, and how often it spoke lately.
|
||||
|
||||
`surfaces` is `(source, what it gates)` pairs. `fired` counts calls in the
|
||||
last `days` where at least one line passed; `calls` every gated call.
|
||||
"""
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.retrieval_log import RetrievalLog
|
||||
|
||||
try:
|
||||
rate = clamp_rate(await get_setting(user_id, RATE_KEY, str(RATE_DEFAULT)))
|
||||
except Exception: # noqa: BLE001 - a settings read never costs the readout
|
||||
rate = RATE_DEFAULT
|
||||
since = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
out: list[dict] = []
|
||||
for source, gates in surfaces:
|
||||
row = {"surface": source, "gates": gates, "rate": rate, "bar": None,
|
||||
"sample": 0, "calls": 0, "fired": 0, "days": days}
|
||||
try:
|
||||
scores = await _null_scores(user_id, source, None, any_project=True)
|
||||
bar = conformal_bar(scores, rate)
|
||||
row["bar"] = None if bar is None else round(bar, 4)
|
||||
row["sample"] = len(scores)
|
||||
async with async_session() as session:
|
||||
calls, fired = (await session.execute(
|
||||
select(func.count(),
|
||||
func.count().filter(RetrievalLog.gate_kept > 0))
|
||||
.where(RetrievalLog.user_id == user_id,
|
||||
RetrievalLog.source == source,
|
||||
RetrievalLog.created_at >= since,
|
||||
RetrievalLog.gate_kept.isnot(None))
|
||||
)).one()
|
||||
row["calls"], row["fired"] = int(calls or 0), int(fired or 0)
|
||||
except Exception: # noqa: BLE001 - one unreadable surface leaves the rest
|
||||
row["unreadable"] = True
|
||||
out.append(row)
|
||||
return out
|
||||
@@ -917,9 +917,14 @@ async def semantic_search_notes(
|
||||
demote_superseded: bool = True,
|
||||
system_id: int | None = None,
|
||||
report: dict | None = None,
|
||||
record_kinds: Sequence[str] | None = None,
|
||||
) -> list[tuple[float, Note]]:
|
||||
"""Return up to *limit* (score, note) pairs most relevant to *query*.
|
||||
|
||||
`record_kinds` narrows to the kinds of the kind×moment table
|
||||
(`record_kinds`: `snippet`, `task:issue`, …), the vocabulary the
|
||||
injected arms filter by. It composes with every other filter.
|
||||
|
||||
Scores are cosine similarities in [-1, 1]; only notes at or above
|
||||
*threshold* are returned, sorted highest-first.
|
||||
|
||||
@@ -1086,6 +1091,9 @@ async def semantic_search_notes(
|
||||
stmt = stmt.where(
|
||||
or_(Note.status.is_(None), Note.task_kind.in_(tkinds))
|
||||
)
|
||||
if record_kinds is not None:
|
||||
from grimoire.services.record_kinds import kinds_clause
|
||||
stmt = stmt.where(kinds_clause(record_kinds))
|
||||
if exclude_ids:
|
||||
stmt = stmt.where(NoteEmbedding.note_id.notin_(exclude_ids))
|
||||
# OVER-FETCH when a re-rank follows, so the demotion can actually
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""What one hook call puts in front of the session, fitted to a budget.
|
||||
|
||||
Every plugin door that injects context builds its payload as `Part`s in one
|
||||
priority order: rules first, then the reply shape, then prior art and the
|
||||
rest. `assemble` keeps parts in that order while they fit and leaves out
|
||||
whole any that do not. A part's ids leave with it, so the plugin's ledgers
|
||||
mark only what the session was actually shown and a trimmed record can still
|
||||
arrive on a later call. `fit` is the one call a door makes: it reads the
|
||||
user's budget, assembles, and records the rule deliveries that made it in.
|
||||
|
||||
Claude Code caps a hook's additional context: its docs give 10,000
|
||||
characters, past which the model gets a 2,000-character preview it is not
|
||||
asked to open, and an installed build has been read capping it at 8,000.
|
||||
`HARD_MAX` sits under the lower figure whatever the setting says, with room
|
||||
for the lines a hook adds on its own side.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
HARD_MAX = 7500
|
||||
MIN_BUDGET = 1000
|
||||
# Fits the full core reply shape (about 2,300 characters) beside two full rule
|
||||
# lines (up to about 750 each) with room for a few records.
|
||||
DEFAULT_BUDGET = 4500
|
||||
BUDGET_KEY = "kb_hook_budget_chars"
|
||||
|
||||
# The id kinds a part can carry, each the source of one response list.
|
||||
RULE = "rule"
|
||||
SHAPE = "shape"
|
||||
NOTE = "note"
|
||||
SYNC = "sync"
|
||||
DERIVE = "derive"
|
||||
RULING = "ruling"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Part:
|
||||
"""One unit the assembler keeps or drops whole.
|
||||
|
||||
Parts sharing a `block` print as consecutive lines, and the block's
|
||||
`header` prints once, before its first kept part, and is charged to it.
|
||||
A part with no block is a block of its own. Blocks are separated by a
|
||||
blank line.
|
||||
"""
|
||||
|
||||
text: str
|
||||
block: str = ""
|
||||
header: str = ""
|
||||
ids: dict[str, tuple] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Fitted:
|
||||
context: str = ""
|
||||
kept: list[Part] = field(default_factory=list)
|
||||
dropped: list[Part] = field(default_factory=list)
|
||||
|
||||
def ids(self, kind: str) -> list:
|
||||
"""The ids of this kind on kept parts, in payload order."""
|
||||
return list(dict.fromkeys(i for p in self.kept for i in p.ids.get(kind, ())))
|
||||
|
||||
def keep_only(self, kind: str, values) -> list:
|
||||
"""`values` filtered to those a kept part carries, order preserved."""
|
||||
kept = set(self.ids(kind))
|
||||
return [v for v in (values or []) if v in kept]
|
||||
|
||||
|
||||
def clamp(budget) -> int:
|
||||
try:
|
||||
n = int(budget)
|
||||
except (TypeError, ValueError):
|
||||
n = DEFAULT_BUDGET
|
||||
return max(MIN_BUDGET, min(HARD_MAX, n))
|
||||
|
||||
|
||||
async def payload_budget(user_id: int) -> int:
|
||||
from grimoire.services.settings import get_setting
|
||||
|
||||
try:
|
||||
return clamp(await get_setting(user_id, BUDGET_KEY, str(DEFAULT_BUDGET)))
|
||||
except Exception: # noqa: BLE001 - a settings read never costs the payload
|
||||
return DEFAULT_BUDGET
|
||||
|
||||
|
||||
def assemble(parts, budget: int) -> Fitted:
|
||||
"""Keep `parts` in order while the joined payload stays within `budget`.
|
||||
|
||||
A part that does not fit is skipped, not a stopping point: a smaller,
|
||||
lower-priority part after it may still fit.
|
||||
"""
|
||||
budget = clamp(budget)
|
||||
blocks: list[tuple[object, list[str]]] = []
|
||||
started: set = set()
|
||||
used = 0
|
||||
out = Fitted()
|
||||
for part in parts:
|
||||
text = (part.text or "").strip("\n")
|
||||
if not text.strip():
|
||||
continue
|
||||
key = part.block or id(part)
|
||||
lines = [text]
|
||||
if part.header and key not in started:
|
||||
lines.insert(0, part.header)
|
||||
joins_last = bool(blocks) and blocks[-1][0] == key
|
||||
sep = 1 if joins_last else (2 if blocks else 0)
|
||||
cost = sep + len("\n".join(lines))
|
||||
if used + cost > budget:
|
||||
out.dropped.append(part)
|
||||
continue
|
||||
used += cost
|
||||
if joins_last:
|
||||
blocks[-1][1].extend(lines)
|
||||
else:
|
||||
blocks.append((key, lines))
|
||||
started.add(key)
|
||||
out.kept.append(part)
|
||||
out.context = "\n\n".join("\n".join(lines) for _key, lines in blocks)
|
||||
return out
|
||||
|
||||
|
||||
async def fit(user_id: int, parts) -> Fitted:
|
||||
"""Assemble under this user's budget and record the rule and record lines
|
||||
delivered."""
|
||||
from grimoire.services import record_deliveries, rule_deliveries
|
||||
|
||||
fitted = assemble(list(parts), await payload_budget(user_id))
|
||||
rule_deliveries.flush(set(fitted.ids(RULE)))
|
||||
record_deliveries.flush(set(fitted.ids(NOTE)))
|
||||
return fitted
|
||||
|
||||
|
||||
def parts_of(result: dict, ids: dict[str, str]) -> list[Part]:
|
||||
"""A builder result's parts, removed from it so it can be serialised.
|
||||
|
||||
A result that carries none is one part: its whole `context`, holding
|
||||
every id its `ids` map names (`{kind: result key}`).
|
||||
"""
|
||||
parts = result.pop("parts", None)
|
||||
if parts is not None:
|
||||
return list(parts)
|
||||
text = result.get("context") or ""
|
||||
if not text:
|
||||
return []
|
||||
return [Part(text=text, ids={
|
||||
kind: tuple(result.get(key) or ()) for kind, key in ids.items()
|
||||
})]
|
||||
|
||||
|
||||
def rule_parts(lines: list[str], rule_ids: list[int], *, block: str) -> list[Part]:
|
||||
"""One part per rule line, each carrying the rule it names."""
|
||||
return [
|
||||
Part(text=line, block=block, ids={RULE: (rid,)} if rid else {})
|
||||
for line, rid in zip(lines, list(rule_ids) + [0] * (len(lines) - len(rule_ids)), strict=False)
|
||||
]
|
||||
@@ -91,8 +91,10 @@ PROCESS_SKILL_PREFIX = "grimoire-proc-"
|
||||
PROCESS_MOMENTS_FIELD = "moments"
|
||||
PROCESS = "process"
|
||||
|
||||
_SEGMENT_SPLIT = re.compile(r"&&|\|\||[;|\n]")
|
||||
_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=\S*\s+")
|
||||
# `<<WORD`, `<<-WORD`, `<<'WORD'`, `<<"WORD"`: a heredoc whose body follows
|
||||
# the line and ends at a line holding only WORD (`<<<` is a here-string).
|
||||
_HEREDOC = re.compile(r"""<<(-?)[ \t]*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2""")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -169,14 +171,83 @@ def _squash(text: str) -> str:
|
||||
|
||||
|
||||
def _segments(command: str) -> list[str]:
|
||||
out = []
|
||||
for part in _SEGMENT_SPLIT.split(command or ""):
|
||||
seg = part.strip().lstrip("(").strip()
|
||||
"""The commands a shell line runs, each from its head.
|
||||
|
||||
Split where the shell separates commands (`&&`, `||`, `;`, `|`, a
|
||||
newline) — but only outside quotes, and never inside a heredoc's body. A
|
||||
quoted argument and the text a heredoc feeds a program are data, not
|
||||
commands: `grep "a && git push"` runs grep, and a script written with
|
||||
`cat <<EOF` that contains `curl` reaches no host.
|
||||
"""
|
||||
text = command or ""
|
||||
out: list[str] = []
|
||||
buf: list[str] = []
|
||||
heredocs: list[tuple[str, bool]] = []
|
||||
|
||||
def flush() -> None:
|
||||
seg = "".join(buf).strip().lstrip("(").strip()
|
||||
buf.clear()
|
||||
while _ENV_ASSIGN.match(seg):
|
||||
seg = _ENV_ASSIGN.sub("", seg, count=1)
|
||||
seg = _squash(seg)
|
||||
if seg:
|
||||
out.append(seg)
|
||||
|
||||
i, n, quote = 0, len(text), ""
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if quote:
|
||||
if c == "\\" and quote == '"' and i + 1 < n:
|
||||
buf.append(text[i:i + 2])
|
||||
i += 2
|
||||
continue
|
||||
buf.append(c)
|
||||
if c == quote:
|
||||
quote = ""
|
||||
i += 1
|
||||
continue
|
||||
if c == "\\" and i + 1 < n:
|
||||
# A backslash-newline continues the line; anything else is escaped.
|
||||
if text[i + 1] != "\n":
|
||||
buf.append(text[i:i + 2])
|
||||
i += 2
|
||||
continue
|
||||
if c in "'\"":
|
||||
quote = c
|
||||
buf.append(c)
|
||||
i += 1
|
||||
continue
|
||||
if text.startswith("<<", i) and not text.startswith("<<<", i):
|
||||
m = _HEREDOC.match(text, i)
|
||||
if m:
|
||||
heredocs.append((m.group(3), m.group(1) == "-"))
|
||||
buf.append(m.group(0))
|
||||
i = m.end()
|
||||
continue
|
||||
if text.startswith("&&", i) or text.startswith("||", i):
|
||||
flush()
|
||||
i += 2
|
||||
continue
|
||||
if c in ";|":
|
||||
flush()
|
||||
i += 1
|
||||
continue
|
||||
if c == "\n":
|
||||
flush()
|
||||
i += 1
|
||||
# The bodies of this line's heredocs, in order, are skipped whole.
|
||||
for word, tabs in heredocs:
|
||||
while i < n:
|
||||
end = text.find("\n", i)
|
||||
line = text[i:end if end != -1 else n]
|
||||
i = end + 1 if end != -1 else n
|
||||
if (line.lstrip("\t") if tabs else line) == word:
|
||||
break
|
||||
heredocs.clear()
|
||||
continue
|
||||
buf.append(c)
|
||||
i += 1
|
||||
flush()
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from grimoire.services import moment_actions, reply_shapes
|
||||
from grimoire.services import hook_payload, moment_actions, reply_shapes, rule_order
|
||||
from grimoire.services import retrieval_pipeline as rp
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -24,11 +24,16 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
def _io() -> rp.MomentIO:
|
||||
"""Resolved at CALL time, so a test patching either module's name is seen."""
|
||||
from grimoire.services import rule_usage, rulebooks
|
||||
from grimoire.services import rule_adherence, rule_deliveries, rule_usage, rulebooks
|
||||
|
||||
bound = rule_deliveries.bound()
|
||||
return rp.MomentIO(
|
||||
lookup=rulebooks.rules_on_moments,
|
||||
record_rule_surfaced=rule_usage.record_rule_surfaced,
|
||||
history=rule_deliveries.history if bound else None,
|
||||
record_delivery=rule_deliveries.record if bound else None,
|
||||
retired=rule_deliveries.retired if bound else None,
|
||||
record_refusal=rule_adherence.note_refused if bound else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -49,6 +54,8 @@ async def reachable_tools(user_id: int) -> list[str]:
|
||||
# request whether or not anything is mounted on it: the shape is product,
|
||||
# so every install has it.
|
||||
shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY}
|
||||
from grimoire.services import rule_triggers
|
||||
|
||||
mounted = set(await rulebooks.mounted_moments(user_id))
|
||||
wanted = mounted | shaped
|
||||
mappings = await moment_actions.list_mappings(user_id)
|
||||
@@ -59,19 +66,45 @@ async def reachable_tools(user_id: int) -> list[str]:
|
||||
}
|
||||
if mounted:
|
||||
keys.add(moment_actions.SKILL_TOOL)
|
||||
# A rule triggered with no moment is reached by whatever tool its trigger
|
||||
# can match, whatever moments those calls reach.
|
||||
try:
|
||||
keys |= await rule_triggers.reachable_tools(user_id)
|
||||
except Exception: # noqa: BLE001 - the mounts' tools are still worth listing
|
||||
logger.debug("rule trigger tools unreadable", exc_info=True)
|
||||
return sorted(keys)
|
||||
|
||||
|
||||
async def _board(user_id: int, project_id: int | None, **act):
|
||||
"""The triggers' answer for this act; None when it cannot be read, which
|
||||
delivers the mounts unconditionally rather than not at all."""
|
||||
from grimoire.services import rule_triggers
|
||||
|
||||
try:
|
||||
return await rule_triggers.board(user_id, project_id or None, **act)
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
||||
logger.debug("rule triggers unreadable", exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def deliver_moments(
|
||||
user_id: int, reached: list[dict], *, project_id: int | None = None,
|
||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||
board=None, text: str = "",
|
||||
) -> rp.RuleResult:
|
||||
"""The mounted rules for moments already known to have happened."""
|
||||
"""The mounted rules for moments already known to have happened.
|
||||
|
||||
With no `board`, one is built from `text` alone: no act is known here, so
|
||||
only keyword triggers can be checked, and a mount conditional on any other
|
||||
kind does not deliver.
|
||||
"""
|
||||
if board is None:
|
||||
board = await _board(user_id, project_id, text=text)
|
||||
return await rp.run_moment_arm(
|
||||
reached,
|
||||
rp.RuleMoment(user_id=user_id, query="", project_id=project_id,
|
||||
exclude=exclude, held=held),
|
||||
io=_io(),
|
||||
io=_io(), board=board,
|
||||
)
|
||||
|
||||
|
||||
@@ -80,16 +113,52 @@ async def deliver_for_act(
|
||||
project_id: int | None = None,
|
||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||
) -> tuple[list[dict], rp.RuleResult]:
|
||||
"""Which moments this act reached, and the mounted rules they deliver."""
|
||||
"""Which moments this act reached, and the rules its mounts and triggers
|
||||
deliver. An act that reaches no moment can still fire a trigger."""
|
||||
reached = await moment_actions.moments_for(user_id, tool, tool_input or {})
|
||||
if not reached:
|
||||
return [], rp.RuleResult()
|
||||
board = await _board(user_id, project_id, tool=tool, tool_input=tool_input or {})
|
||||
if not reached and not (board and board.fired):
|
||||
return reached, rp.RuleResult()
|
||||
result = await deliver_moments(
|
||||
user_id, reached, project_id=project_id, exclude=exclude, held=held,
|
||||
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
|
||||
)
|
||||
# A write is never held for a read: a recall aid does not stand in the
|
||||
# way of the work. A rule set to enforce still refuses one — that is a
|
||||
# boundary the operator drew, not a reminder.
|
||||
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
|
||||
result.decision = {}
|
||||
return reached, result
|
||||
|
||||
|
||||
# The file-writing tools, as tool keys: a `hold` rule never holds these.
|
||||
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
|
||||
|
||||
|
||||
async def routed_to_acts(user_id: int, project_id: int | None = None) -> frozenset[int]:
|
||||
"""The rules that arrive at an act, so the prompt arm leaves them there.
|
||||
|
||||
A rule mounted on a moment some action is mapped to (every moment but the
|
||||
reply moments), or carrying a `tool`, `path` or `command` trigger, reaches
|
||||
the session at the call it governs. Delivered at the prompt too, it would
|
||||
arrive twice, and the first time beside a request it competes with. A
|
||||
keyword trigger can also match a reply, so it does not count.
|
||||
"""
|
||||
from grimoire.services import rule_triggers, rulebooks
|
||||
|
||||
mappings = await moment_actions.list_mappings(user_id)
|
||||
act_moments = sorted({
|
||||
action.moment for action, _via in moment_actions.effective_actions(mappings)
|
||||
if not action.moment.startswith("reply.")
|
||||
})
|
||||
out = {rule.id for rule, _at in await rulebooks.rules_on_moments(
|
||||
user_id, act_moments, project_id or None,
|
||||
)} if act_moments else set()
|
||||
for rule, triggers in await rule_triggers._in_scope(user_id, project_id or None):
|
||||
if any(t.kind in ("tool", "path", "command") and not t.moment for t in triggers):
|
||||
out.add(rule.id)
|
||||
return frozenset(out)
|
||||
|
||||
|
||||
def shapes_for_act(reached: list[dict], seen: frozenset[str] = frozenset()) -> tuple[list[str], dict[str, str]]:
|
||||
"""The default reply shapes riding the moments this act reached.
|
||||
|
||||
@@ -113,6 +182,7 @@ _REACHED_BY_TURN = "the reply this turn will end with"
|
||||
async def deliver_for_turn(
|
||||
user_id: int, *, seen: frozenset[str] = frozenset(), project_id: int | None = None,
|
||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||
record: bool = True,
|
||||
) -> dict:
|
||||
"""What every turn carries before its reply is written.
|
||||
|
||||
@@ -123,10 +193,17 @@ async def deliver_for_turn(
|
||||
the reply exists, which is too late to shape it and is kept as the
|
||||
backstop; this is the point before.
|
||||
|
||||
Returns `{context, rule_ids, shape_forms}`. Fails open to the core alone,
|
||||
and the core itself never fails: it is a constant.
|
||||
Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts}`; the
|
||||
parts are for a door that fits its payload, which passes `record=False`
|
||||
and records the shapes it kept. Fails open to the core alone, and the
|
||||
core itself never fails: it is a constant.
|
||||
"""
|
||||
blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen)
|
||||
shape_parts = [
|
||||
hook_payload.Part(text=block, ids={hook_payload.SHAPE: (key,)})
|
||||
for block, key in zip(blocks, forms, strict=False)
|
||||
]
|
||||
rule_parts: list[hook_payload.Part] = []
|
||||
rule_ids: list[int] = []
|
||||
try:
|
||||
reached = [{"moment": "reply.report", "tool": "", "match": _REACHED_BY_TURN,
|
||||
@@ -136,10 +213,17 @@ async def deliver_for_turn(
|
||||
)
|
||||
blocks.extend(result.lines)
|
||||
rule_ids = result.rule_ids
|
||||
rule_parts = hook_payload.rule_parts(
|
||||
result.lines, result.rule_per_line(), block="rules",
|
||||
)
|
||||
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
||||
logger.debug("reply.report mounts not delivered for the turn", exc_info=True)
|
||||
if record:
|
||||
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
||||
return {"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms}
|
||||
return {
|
||||
"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms,
|
||||
"shape_parts": shape_parts, "rule_parts": rule_parts,
|
||||
}
|
||||
|
||||
|
||||
async def attach_moment_rules(
|
||||
@@ -189,8 +273,8 @@ async def attach_moment_rules(
|
||||
# your end" gets said — so it is checked twice over: the rules MOUNTED on the
|
||||
# reply moments (deterministic, somebody said they belong here), and the
|
||||
# reply text against every rule's trigger (the backstop for whatever the
|
||||
# earlier arms missed). An unopened rule from either half HOLDS the reply for
|
||||
# one read, in these words; the hook never holds the rewrite.
|
||||
# earlier arms missed). An unopened rule set to hold, from either half, HOLDS
|
||||
# the reply for one read, in these words; the hook never holds the rewrite.
|
||||
|
||||
# The reply's head and tail. The embedder reads ~512 tokens, and the part of
|
||||
# a report that asks something of the reader — "let me know if it works" —
|
||||
@@ -290,10 +374,15 @@ async def reply_hold(
|
||||
room = pc.CHECKPOINT_SESSION_CAP - len(stopped)
|
||||
out: list[dict] = []
|
||||
|
||||
# The mounted half: deterministic, so every unopened RULE on these
|
||||
# moments holds. A preference claims no such force.
|
||||
# The mounted half: deterministic, so every unopened rule on these
|
||||
# moments that is declared to hold (`hold` or `enforce`) holds. An
|
||||
# `inform` rule was put in front of the turn before the reply was
|
||||
# written, and a preference claims no force. A mount conditional on
|
||||
# a trigger holds only when the reply meets it.
|
||||
board = await _board(user_id, project_id, text=reply)
|
||||
gated = board.gated if board is not None else set()
|
||||
for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None):
|
||||
if rule.id in skip or rule.kind == "preference":
|
||||
if rule.id in skip or not rule_order.holds(rule) or (rule.id, at) in gated:
|
||||
continue
|
||||
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
|
||||
"trigger": (rule.when_to_apply or "").strip()})
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user