Compare commits
33
Commits
0216634bd4
...
dev
@@ -28,10 +28,10 @@ services:
|
||||
environment:
|
||||
DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}"
|
||||
LOG_LEVEL: "${LOG_LEVEL:-INFO}"
|
||||
# Behind an HTTPS reverse proxy:
|
||||
# Port 5000 is published straight to clients, so no proxy is trusted.
|
||||
# Behind a reverse proxy, set 1 (one per proxy) and BASE_URL:
|
||||
TRUSTED_PROXY_HOPS: "0"
|
||||
# BASE_URL: "https://grimoire.example.com"
|
||||
# SECURE_COOKIES: "true"
|
||||
# TRUST_PROXY_HEADERS: "true"
|
||||
volumes:
|
||||
- app_data:/data
|
||||
depends_on:
|
||||
@@ -75,8 +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 |
|
||||
| `SECURE_COOKIES` | Over HTTPS | `true` when Grimoire is served over HTTPS |
|
||||
| `TRUST_PROXY_HEADERS` | Behind a proxy | `true` to read the client address from the proxy's headers |
|
||||
| `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 |
|
||||
|
||||
@@ -97,7 +96,7 @@ docker compose up -d
|
||||
|
||||
Database migrations run when the app starts, and the key stays in its volume. Claude Code updates the plugin from its marketplace; run `/reload-plugins` after an update.
|
||||
|
||||
**Settings → Data → Scheduled backups** writes a daily backup of the database to a folder or an S3-compatible bucket, and `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](docs/backups.md).
|
||||
**Settings → Data → Scheduled backups** writes a daily backup of the database to a folder or an S3-compatible bucket, and Settings → Data → Restore from Backup rolls the instance back to one, or brings a new instance back from it. See [Backups](docs/backups.md).
|
||||
|
||||
## Features
|
||||
|
||||
@@ -132,7 +131,7 @@ The full list is in [Features](docs/features.md).
|
||||
|
||||
| What you see | Why | Fix |
|
||||
|--------------|-----|-----|
|
||||
| `SECRET_KEY is set to the public placeholder` at startup | `SECURE_COOKIES=true` while `SECRET_KEY` is `dev-secret-change-me` | Remove `SECRET_KEY`, or set a real one |
|
||||
| `SECRET_KEY is set to the public placeholder` at startup | `SECRET_KEY` is `dev-secret-change-me` or `change-me-in-production` | Remove `SECRET_KEY`, or set a real one |
|
||||
| Settings asks for forge tokens or the backup secret again | The instance's key changed: the `app_data` volume was replaced, or `SECRET_KEY` was set or removed | Enter them again, or restore the previous key |
|
||||
| `Can't locate revision identified by '…'` at startup | An older image is running against a database a newer one has already migrated | Run the newer image; migrations only move forward |
|
||||
| The plugin's tools are missing in Claude Code | The plugin isn't installed, or Claude Code hasn't reloaded it | `/plugin` to install or update it, then `/reload-plugins` |
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
"""instance identity — the id lineage a backup carries
|
||||
|
||||
Revision ID: 0127
|
||||
Revises: 0126
|
||||
Create Date: 2026-11-05
|
||||
|
||||
One row naming this database's id lineage. Every full backup carries it, a
|
||||
restore into a fresh instance adopts it (the restore keeps the original ids),
|
||||
and rolling a live instance back requires the backup's to match, so a backup's
|
||||
ids never land on unrelated rows. Made here with a random value, so every
|
||||
instance has one before its first account exists.
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0127"
|
||||
down_revision = "0126"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"instance_identity",
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("instance_id", sa.Text(), nullable=False),
|
||||
sa.Column(
|
||||
"created_at", sa.DateTime(timezone=True), nullable=False,
|
||||
server_default=sa.func.now(),
|
||||
),
|
||||
sa.CheckConstraint("id = 1", name="ck_instance_identity_single_row"),
|
||||
)
|
||||
op.execute(
|
||||
"INSERT INTO instance_identity (id, instance_id) VALUES (1, gen_random_uuid()::text)"
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("instance_identity")
|
||||
@@ -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")
|
||||
@@ -8,8 +8,9 @@ services:
|
||||
# a Docker secret and sets SECRET_KEY_FILE to its path).
|
||||
SECRET_KEY: "${SECRET_KEY}"
|
||||
LOG_LEVEL: "${LOG_LEVEL:-INFO}"
|
||||
TRUST_PROXY_HEADERS: "true"
|
||||
SECURE_COOKIES: "true"
|
||||
# Proxies in front of the app (Traefik = 1). The client address and
|
||||
# HTTPS are read from that far in from the right of X-Forwarded-*.
|
||||
TRUSTED_PROXY_HOPS: "1"
|
||||
volumes:
|
||||
- app_data:/data
|
||||
networks:
|
||||
|
||||
+3
-3
@@ -13,10 +13,10 @@ services:
|
||||
environment:
|
||||
DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}"
|
||||
LOG_LEVEL: "${LOG_LEVEL:-INFO}"
|
||||
# Behind an HTTPS reverse proxy:
|
||||
# Port 5000 is published straight to clients, so no proxy is trusted.
|
||||
# Behind a reverse proxy, set 1 (one per proxy) and BASE_URL:
|
||||
TRUSTED_PROXY_HOPS: "0"
|
||||
# BASE_URL: "https://grimoire.example.com"
|
||||
# SECURE_COOKIES: "true"
|
||||
# TRUST_PROXY_HEADERS: "true"
|
||||
volumes:
|
||||
- app_data:/data
|
||||
depends_on:
|
||||
|
||||
@@ -251,6 +251,7 @@ These serve the plugin's hooks.
|
||||
| POST | `/api/plugin/rule-opened` | Records that a session opened a rule it was shown |
|
||||
| GET | `/api/plugin/shape-check` | The end-of-turn question about what this turn wrote |
|
||||
| GET | `/api/plugin/claim-session` · `/release-session` | Bind a session to its task claims / release them at session end |
|
||||
| GET | `/api/plugin/write-scope` | Which projects a pending act would change (a directory, or an MCP call's `tool` and `input`), and whether a session in its own project may do it. Filing an issue elsewhere is allowed; every other cross-project write is answered `allowed: false` with the reason the operator is asked |
|
||||
| GET | `/api/plugin/processes` | Stored Processes for skill-stub sync |
|
||||
| GET | `/api/plugin/prior-art` | Write-path hint for the plugin hooks (params: `path`, `code`, `repo`, `shapes`, `exclude_ids`, `exclude_sync_ids`, `exclude_derive`); returns `context`, `note_ids`, `sync_note_ids`, `stamped`, `divergence`, `derive`, `derive_keys` |
|
||||
| GET / POST | `/api/projects/<id>/coverage`, `…/coverage/refresh` | Shape-ledger accounting (`pattern_coverage` line, counts, `derive_groups` — css groups carry `consumers`, `derive_new`, `unused_css`, `divergence`, `recheck`) |
|
||||
@@ -272,12 +273,15 @@ These serve the plugin's hooks.
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/api/admin/backup` | Export backup (format v4; `?scope=user` for own data) |
|
||||
| POST | `/api/admin/restore` | Restore from a backup |
|
||||
| GET | `/api/admin/restore/sources` | The backups at the backup destination, newest first |
|
||||
| POST | `/api/admin/restore/preview` | What restoring a backup (`?source=<name>` or an uploaded file) would change; 409 with the reason when it can't apply here |
|
||||
| POST | `/api/admin/restore?confirm=rollback` | Put the whole instance back to that backup, after saving the current state |
|
||||
| GET / DELETE | `/api/admin/users` · `/api/admin/users/:id` | List / delete users |
|
||||
| GET / PUT | `/api/admin/registration` | Get / toggle registration |
|
||||
| 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 |
|
||||
|
||||
@@ -69,10 +69,10 @@ Every database wait on startup has a deadline. Migrations wait for the database
|
||||
|
||||
## Authentication
|
||||
|
||||
- **Sessions**: `HttpOnly`, `SameSite=Lax` cookies, `Secure` when `SECURE_COOKIES=true`. Changing a password bumps the user's session version and signs out their other sessions.
|
||||
- **Sessions**: `HttpOnly`, `SameSite=Lax` cookies, `Secure` on a request the trusted proxy reports as HTTPS, which also gets HSTS (`grimoire/proxy.py`). Changing a password bumps the user's session version and signs out their other sessions.
|
||||
- **API keys**: `Authorization: Bearer fmcp_...`, stored hashed. A `read` key may only call read endpoints and read MCP tools.
|
||||
- **OIDC** single sign-on with PKCE, optionally replacing local logins ([SSO / OAuth](sso-oauth.md)).
|
||||
- **Rate limits** on register, login and forgot-password, per client IP (`TRUST_PROXY_HEADERS` reads the IP from the proxy's headers).
|
||||
- **Rate limits** on register, login and forgot-password, per client IP, read from `X-Forwarded-For` by `TRUSTED_PROXY_HOPS`.
|
||||
|
||||
Credentials Grimoire stores for outside services (forge tokens, the backup destination's S3 secret) are sealed under a key derived from `SECRET_KEY`, which the instance makes on first start and keeps in `/data/secret_key` unless one is set.
|
||||
|
||||
@@ -87,7 +87,7 @@ Credentials Grimoire stores for outside services (forge tokens, the backup desti
|
||||
│ ├── routes/ REST blueprints
|
||||
│ ├── mcp/ MCP server and its tool modules
|
||||
│ ├── services/ shared logic
|
||||
│ └── restore.py `python -m grimoire.restore` for a fresh instance
|
||||
│ └── restore.py `python -m grimoire.restore`: the restore, from the command line
|
||||
├── frontend/src/ views, components, stores, composables, api client
|
||||
├── plugin/ Claude Code hooks, skills and commands
|
||||
├── scripts/ CI checks and the plugin version minter
|
||||
|
||||
+52
-21
@@ -88,9 +88,12 @@ You need four things:
|
||||
- **Access key.**
|
||||
- **Secret key.**
|
||||
|
||||
Grimoire uploads and lists; it never deletes. A key that may **only add
|
||||
objects** is therefore enough, and it is the safer key to hand out: a stolen
|
||||
one cannot wipe the history.
|
||||
Grimoire uploads and lists, and reads a backup back when you restore from the
|
||||
bucket; it never deletes. A key that may **add and read objects but not
|
||||
delete them** is therefore enough, and it is the safer key to hand out: a
|
||||
stolen one cannot wipe the history. A key that may only add objects still
|
||||
takes backups; restore then works by uploading a file or from the command
|
||||
line.
|
||||
|
||||
The secret is stored encrypted, under a key derived from `SECRET_KEY`. It is
|
||||
never shown again, and never included in a backup. If an instance's
|
||||
@@ -122,8 +125,10 @@ keeps service backups as "backup targets". Either destination works with it.
|
||||
1. On Archives' **Backups** page, make a target for Grimoire, named `grimoire`
|
||||
for example.
|
||||
2. Choose how Grimoire's files arrive:
|
||||
- **S3**: turn on the S3 way in for the target and make an **append-only**
|
||||
S3 key. In Grimoire, choose **An S3 bucket**:
|
||||
- **S3**: turn on the S3 way in for the target and make an S3 key that
|
||||
may add and read objects but not delete them (an **append-only** key
|
||||
takes backups too, but then Grimoire can't restore from the bucket). In
|
||||
Grimoire, choose **An S3 bucket**:
|
||||
- address: Archives' backup address (`http://<archives>:8081`);
|
||||
- bucket: the target's name;
|
||||
- access key and secret key: the key you just made.
|
||||
@@ -139,26 +144,52 @@ keeps service backups as "backup targets". Either destination works with it.
|
||||
|
||||
## Restoring
|
||||
|
||||
### Into a fresh instance
|
||||
A restore puts the **whole instance** back to the moment a backup was taken,
|
||||
for every user:
|
||||
|
||||
Start Grimoire on an empty database, copy the backup file into the container,
|
||||
and run:
|
||||
- records edited since go back to how they were;
|
||||
- records deleted since come back;
|
||||
- anything made since is removed.
|
||||
|
||||
It matches records by their ids, so a live instance only restores a backup **of
|
||||
its own**. Each instance has an id, and every backup records the one it came
|
||||
from. A backup from another instance, or one made before backups recorded it,
|
||||
only goes into a new, empty instance, which takes it as it is.
|
||||
|
||||
Before changing anything, the restore saves the current state as one more
|
||||
backup. It goes to the backup destination when scheduled backups are on, and
|
||||
otherwise to `/data/pre-restore`. The result says which file it is, so a
|
||||
restore can itself be undone.
|
||||
|
||||
What a backup doesn't carry stays as it is wherever its owner survives the
|
||||
restore: API keys, forge connections, sharing, logs, and the destination's S3
|
||||
secret. The trash isn't in backups, so anything in the trash when the backup
|
||||
was taken is gone afterwards. Everyone is signed out, and search is rebuilt.
|
||||
|
||||
### From the web
|
||||
|
||||
**Settings → Data → Restore from Backup** lists the backups at the backup
|
||||
destination. You can pick one of those, or upload a `.tar` or the JSON
|
||||
**Full Backup** download (uploads are held to the server's request-size
|
||||
limit). The restore then shows what would change: when the backup was taken,
|
||||
and how many accounts, projects, plans, notes and rules there are now and will
|
||||
be afterwards. Type `roll back` to run it. Then sign in again.
|
||||
|
||||
To read backups back from an S3 bucket, the key needs read access as well as
|
||||
write. Grimoire never deletes from the bucket.
|
||||
|
||||
### From the command line
|
||||
|
||||
For a file with no size limit, or a new instance with no backup destination
|
||||
yet, copy the file into the container and run:
|
||||
|
||||
```sh
|
||||
docker exec -it grimoire python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar
|
||||
```
|
||||
|
||||
- The command refuses a database that already has an account. A restore
|
||||
re-creates everything with new ids, so on a live instance it would add a
|
||||
second copy instead of replacing anything.
|
||||
- Nothing limits the file's size.
|
||||
- It also reads the JSON from the admin **Full Backup** download.
|
||||
It prints what would change and stops. Add `--yes` to restore. It reads the
|
||||
JSON download too. Afterwards, **restart Grimoire** so the search indexes are
|
||||
rebuilt.
|
||||
|
||||
Afterwards, **restart Grimoire** so the search indexes are rebuilt. Then issue
|
||||
new API keys, add forge connections again, and set up any sharing.
|
||||
|
||||
### From the web
|
||||
|
||||
**Settings → Data → Restore from Backup** takes the `.tar` as well as the
|
||||
JSON download. The upload is held to the server's request-size limit. For a
|
||||
bigger file, use the command above.
|
||||
After restoring into a new instance, issue new API keys, add forge connections
|
||||
again, and set up any sharing: none of them travel in a backup.
|
||||
|
||||
+14
-8
@@ -14,8 +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 |
|
||||
| `SECURE_COOKIES` | `false` | `true` when Grimoire is served over HTTPS |
|
||||
| `TRUST_PROXY_HEADERS` | `false` | `true` behind a reverse proxy, to read the client IP from `X-Forwarded-For` / `X-Real-IP` |
|
||||
| `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 |
|
||||
@@ -77,7 +76,7 @@ docker compose -f docker-compose.dev.yml up --build
|
||||
|
||||
### Docker Swarm
|
||||
|
||||
[`docker-compose.prod.yml`](../docker-compose.prod.yml) is a stack file: the app and database on a private overlay network, with `SECURE_COOKIES` and `TRUST_PROXY_HEADERS` on. A Swarm can move the app to another node, away from a node-local `/data` volume, so the stack sets its own key: provide `DB_PASSWORD` and `SECRET_KEY` in the environment (or mount a Docker secret and set `SECRET_KEY_FILE`):
|
||||
[`docker-compose.prod.yml`](../docker-compose.prod.yml) is a stack file: the app and database on a private overlay network, trusting one proxy (`TRUSTED_PROXY_HOPS: "1"`). A Swarm can move the app to another node, away from a node-local `/data` volume, so the stack sets its own key: provide `DB_PASSWORD` and `SECRET_KEY` in the environment (or mount a Docker secret and set `SECRET_KEY_FILE`):
|
||||
|
||||
```bash
|
||||
DB_PASSWORD=... SECRET_KEY=... docker stack deploy -c docker-compose.prod.yml grimoire
|
||||
@@ -96,13 +95,16 @@ 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 `SECURE_COOKIES=true`, `TRUST_PROXY_HEADERS=true` and `BASE_URL`.
|
||||
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 / {
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
@@ -112,12 +114,16 @@ location / {
|
||||
}
|
||||
```
|
||||
|
||||
With `TRUST_PROXY_HEADERS=true`, make sure the proxy replaces any `X-Forwarded-For` the client sends.
|
||||
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.
|
||||
|
||||
A hop count higher than the real number of proxies lets a client choose its own address, so count them. With `0`, the headers are ignored and the socket peer is the client: use it when clients reach port 5000 directly.
|
||||
|
||||
## 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 `dev-secret-change-me` when `SECURE_COOKIES=true`.
|
||||
- **`SECURE_COOKIES=true`** whenever Grimoire is served over HTTPS.
|
||||
- **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`).
|
||||
- **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.
|
||||
|
||||
+4
-3
@@ -66,6 +66,7 @@ Saved procedures, such as a drift audit or a DRY pass. The plugin syncs each one
|
||||
The whole store is reachable through the MCP endpoint at `/mcp`, authenticated with an API key. The Claude Code plugin in this repo adds:
|
||||
|
||||
- hooks for session start, each prompt, before and after tool calls, the end of a turn, compaction and session end, all failing open if Grimoire is unreachable;
|
||||
- a project fence: a session belongs to the project its starting directory is bound to. Toward any other project it can read anything and file an issue. Editing that project's files, committing or pushing in its repo, or changing its records first asks you, in every permission mode;
|
||||
- skills for the working practices: using Grimoire, writing plans, systematic debugging, verification, brainstorming, reporting back, reusing code, shape accounting and family canon;
|
||||
- your stored processes as skills.
|
||||
|
||||
@@ -85,8 +86,8 @@ Share a project, note or task with users or groups, as viewer, editor or admin.
|
||||
## Export and backup
|
||||
|
||||
- **Personal export**: your notes and tasks as a Markdown ZIP (with YAML frontmatter) or JSON.
|
||||
- **Admin backup and restore**, with ids remapped so a backup restores onto another instance.
|
||||
- **Scheduled backups**: a daily, dated, uncompressed tar to a folder or an S3-compatible bucket, laid out so a deduplicating tool such as restic stores only what changed. `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](backups.md).
|
||||
- **Admin backup and restore**: a restore rolls the whole instance back to one of its own backups, after saving the current state, or brings a new instance back from any backup.
|
||||
- **Scheduled backups**: a daily, dated, uncompressed tar to a folder or an S3-compatible bucket, laid out so a deduplicating tool such as restic stores only what changed. Restoring is in Settings, or `python -m grimoire.restore`. See [Backups](backups.md).
|
||||
|
||||
## Sign-in
|
||||
|
||||
@@ -102,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 |
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { apiGet, apiPost, apiPut } from "@/api/client";
|
||||
import { apiGet, apiPost, apiPostRaw, apiPut } from "@/api/client";
|
||||
|
||||
/**
|
||||
* Scheduled backups — `/api/admin/backups`. One dated,
|
||||
@@ -71,3 +71,72 @@ export function checkBackupDestination(
|
||||
export function runBackupNow(): Promise<{ status: string }> {
|
||||
return apiPost<{ status: string }>("/api/admin/backups/run", {});
|
||||
}
|
||||
|
||||
|
||||
// ── Restore: put the whole instance back to a full backup ─────────────────
|
||||
|
||||
export interface StoredBackup {
|
||||
name: string;
|
||||
size_bytes: number;
|
||||
}
|
||||
|
||||
export interface RestoreCount {
|
||||
kind: string;
|
||||
now: number;
|
||||
after: number;
|
||||
}
|
||||
|
||||
export interface RestorePreview {
|
||||
/** "fresh": an empty instance takes the backup. "rollback": this instance
|
||||
* goes back to its own earlier backup. */
|
||||
mode: "fresh" | "rollback";
|
||||
exported_at: string | null;
|
||||
counts: RestoreCount[];
|
||||
}
|
||||
|
||||
export interface RestoreResult extends RestorePreview {
|
||||
status: "ok";
|
||||
restored: Record<string, number>;
|
||||
safety_backup: { file: string; size_bytes: number; where: string; note?: string };
|
||||
}
|
||||
|
||||
/** A backup at the destination, by name, or a file picked from this computer. */
|
||||
export type RestoreFrom = { source: string } | { file: File };
|
||||
|
||||
// Reading, checking and writing the whole store is slow by design; bounded,
|
||||
// but in minutes.
|
||||
const RESTORE_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
|
||||
export function listRestoreSources(): Promise<{ backups: StoredBackup[]; error?: string }> {
|
||||
return apiGet("/api/admin/restore/sources", { timeoutMs: 60_000 });
|
||||
}
|
||||
|
||||
async function restoreCall<T>(path: string, from: RestoreFrom, query: Record<string, string> = {}): Promise<T> {
|
||||
const params = new URLSearchParams(query);
|
||||
if ("source" in from) {
|
||||
params.set("source", from.source);
|
||||
return apiPostRaw<T>(`${path}?${params}`, null, null, { timeoutMs: RESTORE_TIMEOUT_MS });
|
||||
}
|
||||
const qs = params.toString() ? `?${params}` : "";
|
||||
const isTar = from.file.name.toLowerCase().endsWith(".tar");
|
||||
// The JSON download is parsed first, so a damaged file fails here, before
|
||||
// the upload.
|
||||
const body = isTar ? from.file : JSON.stringify(JSON.parse(await from.file.text()));
|
||||
return apiPostRaw<T>(`${path}${qs}`, body, isTar ? "application/x-tar" : "application/json",
|
||||
{ timeoutMs: RESTORE_TIMEOUT_MS });
|
||||
}
|
||||
|
||||
export function previewRestore(from: RestoreFrom): Promise<RestorePreview> {
|
||||
return restoreCall<RestorePreview>("/api/admin/restore/preview", from);
|
||||
}
|
||||
|
||||
export function restoreBackup(from: RestoreFrom): Promise<RestoreResult> {
|
||||
return restoreCall<RestoreResult>("/api/admin/restore", from, { confirm: "rollback" });
|
||||
}
|
||||
|
||||
/** When a backup named `grimoire-20261015T020000Z.tar` was taken. */
|
||||
export function backupTakenAt(name: string): Date | null {
|
||||
const m = /(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/.exec(name);
|
||||
if (!m) return null;
|
||||
return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]));
|
||||
}
|
||||
|
||||
@@ -156,6 +156,15 @@ export function apiPost<T>(path: string, body: unknown, opts?: RequestOpts): Pro
|
||||
return request<T>(path, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) }, opts);
|
||||
}
|
||||
|
||||
/** A POST whose body is sent as it is (a file, or text already serialised),
|
||||
* under the same deadline and error handling as every other call. */
|
||||
export function apiPostRaw<T>(
|
||||
path: string, body: BodyInit | null, contentType: string | null, opts?: RequestOpts,
|
||||
): Promise<T> {
|
||||
const headers = contentType ? { "Content-Type": contentType } : undefined;
|
||||
return request<T>(path, { method: "POST", headers, body }, opts);
|
||||
}
|
||||
|
||||
export function apiPut<T>(path: string, body: unknown, opts?: RequestOpts): Promise<T> {
|
||||
return request<T>(path, { method: "PUT", headers: JSON_HEADERS, body: JSON.stringify(body) }, opts);
|
||||
}
|
||||
|
||||
@@ -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,278 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Restore: put the whole instance back to a full backup.
|
||||
*
|
||||
* Choose a backup (one at the backup destination, or a file from this
|
||||
* computer), see what it would change, type the confirmation, run it. On a
|
||||
* live instance this is a rollback to the instance's own earlier backup; on a
|
||||
* new, empty one it takes the backup in. Either way the server backs up the
|
||||
* current state first and signs everyone out afterwards.
|
||||
*/
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { apiErrorMessage } from "@/api/client";
|
||||
import {
|
||||
backupTakenAt, listRestoreSources, previewRestore, restoreBackup,
|
||||
type RestoreFrom, type RestorePreview, type RestoreResult, type StoredBackup,
|
||||
} from "@/api/backups";
|
||||
import { formatBytes } from "@/utils/bytes";
|
||||
|
||||
const emit = defineEmits<{ close: [] }>();
|
||||
|
||||
const CONFIRM_WORDS = "roll back";
|
||||
|
||||
type Step = "choose" | "checking" | "preview" | "running" | "done";
|
||||
const step = ref<Step>("choose");
|
||||
const sources = ref<StoredBackup[]>([]);
|
||||
const sourcesError = ref("");
|
||||
const sourcesLoading = ref(true);
|
||||
const chosen = ref<RestoreFrom | null>(null);
|
||||
const chosenLabel = ref("");
|
||||
const preview = ref<RestorePreview | null>(null);
|
||||
const result = ref<RestoreResult | null>(null);
|
||||
const error = ref("");
|
||||
const typed = ref("");
|
||||
const fileInput = ref<HTMLInputElement | null>(null);
|
||||
|
||||
const confirmed = computed(() => typed.value.trim().toLowerCase() === CONFIRM_WORDS);
|
||||
|
||||
function when(value: Date | string | null | undefined): string {
|
||||
if (!value) return "an unknown date";
|
||||
const date = typeof value === "string" ? new Date(value) : value;
|
||||
return Number.isNaN(date.getTime()) ? "an unknown date" : date.toLocaleString();
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const answer = await listRestoreSources();
|
||||
sources.value = answer.backups;
|
||||
sourcesError.value = answer.error ?? "";
|
||||
} catch (e) {
|
||||
sourcesError.value = apiErrorMessage(e, "Could not list the backups at the destination.");
|
||||
} finally {
|
||||
sourcesLoading.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
async function check(from: RestoreFrom, label: string) {
|
||||
chosen.value = from;
|
||||
chosenLabel.value = label;
|
||||
error.value = "";
|
||||
typed.value = "";
|
||||
step.value = "checking";
|
||||
try {
|
||||
preview.value = await previewRestore(from);
|
||||
step.value = "preview";
|
||||
} catch (e) {
|
||||
error.value = apiErrorMessage(e, "That backup could not be read.");
|
||||
step.value = "choose";
|
||||
}
|
||||
}
|
||||
|
||||
function pickFile(event: Event) {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (fileInput.value) fileInput.value.value = "";
|
||||
if (file) check({ file }, file.name);
|
||||
}
|
||||
|
||||
async function run() {
|
||||
if (!chosen.value || !confirmed.value) return;
|
||||
error.value = "";
|
||||
step.value = "running";
|
||||
try {
|
||||
result.value = await restoreBackup(chosen.value);
|
||||
step.value = "done";
|
||||
} catch (e) {
|
||||
error.value = apiErrorMessage(e, "The restore failed. Nothing was changed.");
|
||||
step.value = "preview";
|
||||
}
|
||||
}
|
||||
|
||||
function finish() {
|
||||
// Every session ended with the restore, this one included.
|
||||
window.location.assign("/login");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<teleport to="body">
|
||||
<div class="modal-overlay" @click="step === 'running' || step === 'done' ? null : emit('close')">
|
||||
<div class="modal-card restore-card" @click.stop>
|
||||
<template v-if="step === 'choose' || step === 'checking'">
|
||||
<h3 class="modal-title">Restore from a backup</h3>
|
||||
<p class="modal-message">
|
||||
Puts the whole instance back to the moment the backup was taken, for every user.
|
||||
You'll see what changes before anything happens.
|
||||
</p>
|
||||
<p v-if="error" class="restore-error" role="alert">{{ error }}</p>
|
||||
|
||||
<h4 class="restore-subhead">At the backup destination</h4>
|
||||
<p v-if="sourcesLoading" class="restore-muted">Looking for backups…</p>
|
||||
<p v-else-if="sourcesError" class="restore-muted">{{ sourcesError }}</p>
|
||||
<p v-else-if="!sources.length" class="restore-muted">No backups there yet.</p>
|
||||
<ul v-else class="restore-sources">
|
||||
<li v-for="b in sources" :key="b.name">
|
||||
<button
|
||||
class="restore-source"
|
||||
:disabled="step === 'checking'"
|
||||
@click="check({ source: b.name }, when(backupTakenAt(b.name)))"
|
||||
>
|
||||
<span>{{ when(backupTakenAt(b.name)) }}</span>
|
||||
<span class="restore-muted">{{ formatBytes(b.size_bytes) }}</span>
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<h4 class="restore-subhead">From this computer</h4>
|
||||
<p class="restore-muted">
|
||||
A backup file (.tar) or the Full Backup download (.json). Uploads are size-limited;
|
||||
a large file restores from the destination above, or with
|
||||
<code>python -m grimoire.restore</code>.
|
||||
</p>
|
||||
<div class="modal-actions restore-actions-left">
|
||||
<button class="modal-btn" :disabled="step === 'checking'" @click="fileInput?.click()">
|
||||
Choose a file…
|
||||
</button>
|
||||
<input ref="fileInput" type="file" accept=".json,.tar" class="hidden-file-input" @change="pickFile" />
|
||||
</div>
|
||||
|
||||
<p v-if="step === 'checking'" class="restore-muted">Reading {{ chosenLabel }}…</p>
|
||||
<div class="modal-actions">
|
||||
<button class="modal-btn" @click="emit('close')">Cancel</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="(step === 'preview' || step === 'running') && preview">
|
||||
<h3 class="modal-title">
|
||||
{{ preview.mode === "rollback" ? "Roll back to this backup?" : "Restore this backup?" }}
|
||||
</h3>
|
||||
<p class="modal-message">
|
||||
<template v-if="preview.mode === 'rollback'">
|
||||
Everything goes back to {{ when(preview.exported_at) }}, for every user. Anything made
|
||||
since is removed, edits since are undone, and records deleted since come back.
|
||||
</template>
|
||||
<template v-else>
|
||||
This instance has no records yet, so it takes the backup from {{ when(preview.exported_at) }} as it is.
|
||||
</template>
|
||||
The current state is backed up first, and everyone is signed out afterwards.
|
||||
</p>
|
||||
<table class="restore-counts">
|
||||
<thead><tr><th></th><th>Now</th><th>After</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="c in preview.counts" :key="c.kind">
|
||||
<td>{{ c.kind }}</td><td>{{ c.now }}</td><td>{{ c.after }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p v-if="error" class="restore-error" role="alert">{{ error }}</p>
|
||||
<label class="restore-confirm">
|
||||
Type <strong>{{ CONFIRM_WORDS }}</strong> to continue
|
||||
<input v-model="typed" class="fs-input input" :disabled="step === 'running'" autocomplete="off" />
|
||||
</label>
|
||||
<div class="modal-actions">
|
||||
<button class="modal-btn" :disabled="step === 'running'" @click="step = 'choose'">Back</button>
|
||||
<button
|
||||
class="modal-btn modal-btn-danger"
|
||||
:disabled="!confirmed || step === 'running'"
|
||||
@click="run"
|
||||
>{{ step === "running" ? "Restoring…" : preview.mode === "rollback" ? "Roll back" : "Restore" }}</button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="step === 'done' && result">
|
||||
<h3 class="modal-title">Restored</h3>
|
||||
<p class="modal-message">
|
||||
The instance is back to {{ when(result.exported_at) }}.
|
||||
The state it replaced was saved as <code>{{ result.safety_backup.file }}</code>
|
||||
in {{ result.safety_backup.where }}.
|
||||
<template v-if="result.safety_backup.note"> {{ result.safety_backup.note }}</template>
|
||||
Search is being rebuilt in the background. Everyone has been signed out, so sign in again.
|
||||
</p>
|
||||
<div class="modal-actions">
|
||||
<button class="modal-btn modal-btn-primary" @click="finish">Sign in again</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</teleport>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.restore-card {
|
||||
max-width: 34rem;
|
||||
max-height: 85vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.restore-subhead {
|
||||
margin: 1rem 0 0.4rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
.restore-muted {
|
||||
font-size: 0.85rem;
|
||||
color: var(--fs-text-secondary);
|
||||
margin: 0 0 0.5rem;
|
||||
}
|
||||
.restore-error {
|
||||
font-size: 0.85rem;
|
||||
color: var(--fs-action-destructive);
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
.restore-sources {
|
||||
list-style: none;
|
||||
margin: 0 0 0.5rem;
|
||||
padding: 0;
|
||||
max-height: 14rem;
|
||||
overflow-y: auto;
|
||||
border: 1px solid var(--fs-border-color);
|
||||
border-radius: var(--fs-radius-sm);
|
||||
}
|
||||
.restore-source {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: 0.45rem 0.7rem;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--fs-border-color);
|
||||
background: none;
|
||||
color: var(--fs-text-primary);
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.restore-sources li:last-child .restore-source {
|
||||
border-bottom: none;
|
||||
}
|
||||
.restore-source:hover:not(:disabled) {
|
||||
background: var(--fs-surface-hover);
|
||||
}
|
||||
.restore-actions-left {
|
||||
justify-content: flex-start;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.restore-counts {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.875rem;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
.restore-counts th,
|
||||
.restore-counts td {
|
||||
text-align: right;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-bottom: 1px solid var(--fs-border-color);
|
||||
}
|
||||
.restore-counts th:first-child,
|
||||
.restore-counts td:first-child {
|
||||
text-align: left;
|
||||
}
|
||||
.hidden-file-input {
|
||||
display: none;
|
||||
}
|
||||
.restore-confirm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.875rem;
|
||||
margin: 0 0 1rem;
|
||||
}
|
||||
</style>
|
||||
@@ -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,96 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* The end of a server-paged list: asks for the next page as the reader nears
|
||||
* it, in place of a "Load more" button. The parent keeps the paging — what the
|
||||
* next page is keyed on, whether one is in flight, whether the last one
|
||||
* failed — and this owns the observing.
|
||||
*
|
||||
* <ScrollSentinel :cursor="more ? String(rows.length) : ''"
|
||||
* :loading="loadingMore" :failed="moreFailed" @more="loadMore" />
|
||||
*
|
||||
* An empty cursor means the list is complete, and nothing renders.
|
||||
*/
|
||||
import { onBeforeUnmount, ref, watch } from "vue";
|
||||
|
||||
const props = defineProps<{ cursor: string; loading: boolean; failed?: boolean }>();
|
||||
const emit = defineEmits<{ more: [] }>();
|
||||
|
||||
const sentinel = ref<HTMLElement | null>(null);
|
||||
const visible = ref(false);
|
||||
|
||||
// One request per page. The observer reports every crossing, and a short last
|
||||
// page leaves the sentinel on screen for good, so the cursor last asked for is
|
||||
// remembered: a page is asked for once, and a failed one is not retried on
|
||||
// every scroll, because a failure leaves the cursor where it was. Only
|
||||
// Try again asks for it again.
|
||||
let asked = "";
|
||||
|
||||
function pump() {
|
||||
if (!visible.value || props.loading || props.failed || !props.cursor) return;
|
||||
if (props.cursor === asked) return;
|
||||
asked = props.cursor;
|
||||
emit("more");
|
||||
}
|
||||
|
||||
function retry() {
|
||||
asked = props.cursor;
|
||||
emit("more");
|
||||
}
|
||||
|
||||
let observer: IntersectionObserver | undefined;
|
||||
|
||||
function observe(el: HTMLElement | null) {
|
||||
observer?.disconnect();
|
||||
observer = undefined;
|
||||
if (!el) {
|
||||
// Visibility and the cursor asked for go with the element. A list that
|
||||
// starts over must not inherit "the end is on screen" from the one it
|
||||
// replaced, and an offset cursor repeats from list to list, so "50" asked
|
||||
// of the old list must not stop the new one asking for its own "50".
|
||||
visible.value = false;
|
||||
asked = "";
|
||||
return;
|
||||
}
|
||||
observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
visible.value = entries.some((e) => e.isIntersecting);
|
||||
pump();
|
||||
},
|
||||
// Extends the watched area a screen below the viewport, so the next page is
|
||||
// asked for before the reader reaches the end rather than when they do.
|
||||
{ rootMargin: "0px 0px 100% 0px" },
|
||||
);
|
||||
observer.observe(el);
|
||||
}
|
||||
|
||||
// flush: "post": the template ref is only set once the DOM is patched.
|
||||
watch(sentinel, observe, { flush: "post" });
|
||||
|
||||
// A page that lands without pushing the end off screen gives the observer
|
||||
// nothing new to report, so carry on from the props, or the list stops early.
|
||||
watch([() => props.cursor, () => props.loading, () => props.failed], pump);
|
||||
|
||||
onBeforeUnmount(() => observer?.disconnect());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="cursor" class="sentinel">
|
||||
<!-- The one case with a button: an observer re-firing on a failure would be
|
||||
a request loop. -->
|
||||
<p v-if="failed" class="sentinel-note sentinel-failed" role="alert">
|
||||
Couldn’t load more.
|
||||
<button type="button" class="btn-secondary btn-sm" @click="retry">Try again</button>
|
||||
</p>
|
||||
<template v-else>
|
||||
<div ref="sentinel" class="sentinel-mark" aria-hidden="true"></div>
|
||||
<p v-if="loading" class="sentinel-note" role="status">Loading more…</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.sentinel { grid-column: 1 / -1; padding: 0.75rem 0; text-align: center; }
|
||||
.sentinel-mark { height: 1px; }
|
||||
.sentinel-note { margin: 0; font-size: 0.8rem; color: var(--fs-text-tertiary); }
|
||||
.sentinel-failed { display: flex; align-items: center; justify-content: center; gap: 0.75rem; }
|
||||
</style>
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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, ">");
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
type FamilyIdea, type IdeaSnapshot, type IdeaStatus,
|
||||
} from "@/api/family";
|
||||
import FamilyAdoptionMatrix from "@/components/FamilyAdoptionMatrix.vue";
|
||||
import ScrollSentinel from "@/components/ScrollSentinel.vue";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { fmtStamp } from "@/utils/dateFormat";
|
||||
import { recordHref } from "@/utils/recordHref";
|
||||
@@ -36,6 +37,8 @@ const loading = ref(true);
|
||||
const failed = ref(false);
|
||||
const moreDecisions = ref(false);
|
||||
const loadingMore = ref(false);
|
||||
const moreFailed = ref(false);
|
||||
const decisionOffset = ref(0);
|
||||
|
||||
// One pending reversal at a time: which row, which act, and its reason.
|
||||
const pending = ref<{ kind: "undo" | "retire"; id: number } | null>(null);
|
||||
@@ -63,7 +66,9 @@ async function load() {
|
||||
criteria.value = ideaData.criteria;
|
||||
conflictOrder.value = ideaData.conflict_order ?? [];
|
||||
decisions.value = log;
|
||||
decisionOffset.value = log.length;
|
||||
moreDecisions.value = log.length === PAGE;
|
||||
moreFailed.value = false;
|
||||
} catch {
|
||||
// Said out loud: a log that failed to load must not read as "nothing
|
||||
// has been decided".
|
||||
@@ -73,14 +78,20 @@ async function load() {
|
||||
}
|
||||
}
|
||||
|
||||
// Older decisions load as the log is scrolled. The log is offset-paged, so a
|
||||
// decision recorded since the first page shifts the rest down by one; a row
|
||||
// already shown is skipped, and the offset still counts what the server sent.
|
||||
async function loadMore() {
|
||||
loadingMore.value = true;
|
||||
moreFailed.value = false;
|
||||
try {
|
||||
const next = await listFamilyDecisions(PAGE, decisions.value.length);
|
||||
decisions.value.push(...next);
|
||||
const next = await listFamilyDecisions(PAGE, decisionOffset.value);
|
||||
const shown = new Set(decisions.value.map((d) => d.id));
|
||||
decisions.value.push(...next.filter((d) => !shown.has(d.id)));
|
||||
decisionOffset.value += next.length;
|
||||
moreDecisions.value = next.length === PAGE;
|
||||
} catch (e: unknown) {
|
||||
toast.show(apiErrorMessage(e, "Could not load more decisions"), "error");
|
||||
} catch {
|
||||
moreFailed.value = true;
|
||||
} finally {
|
||||
loadingMore.value = false;
|
||||
}
|
||||
@@ -343,9 +354,12 @@ onMounted(load);
|
||||
</form>
|
||||
</li>
|
||||
</ul>
|
||||
<button v-if="moreDecisions" class="btn-secondary btn-sm" :disabled="loadingMore" @click="loadMore">
|
||||
{{ loadingMore ? "Loading…" : "Older decisions" }}
|
||||
</button>
|
||||
<ScrollSentinel
|
||||
:cursor="moreDecisions ? String(decisionOffset) : ''"
|
||||
:loading="loadingMore"
|
||||
:failed="moreFailed"
|
||||
@more="loadMore"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
</main>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";
|
||||
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { apiGet } from "@/api/client";
|
||||
import type { TaskKind, TaskStatus, TaskPriority } from "@/types/note";
|
||||
@@ -10,6 +10,7 @@ import UsageBadge from "@/components/UsageBadge.vue";
|
||||
import NoteSweepPane from "@/components/NoteSweepPane.vue";
|
||||
import StatusBadge from "@/components/StatusBadge.vue";
|
||||
import PriorityBadge from "@/components/PriorityBadge.vue";
|
||||
import ScrollSentinel from "@/components/ScrollSentinel.vue";
|
||||
import GraphView from "@/views/GraphView.vue";
|
||||
import {
|
||||
FileText,
|
||||
@@ -193,7 +194,7 @@ function onClickOutsideNewNote(e: MouseEvent) {
|
||||
|
||||
const ID_BATCH = 100; // IDs fetched per server round-trip
|
||||
const INITIAL_CONTENT = 50; // items loaded on first render
|
||||
const CONTENT_PAGE = 24; // items loaded per sentinel trigger
|
||||
const CONTENT_PAGE = 24; // items loaded each time the end of the feed nears
|
||||
const REFILL_THRESHOLD = 48; // fetch more IDs when queue drops below this
|
||||
|
||||
const items = ref<KnowledgeItem[]>([]);
|
||||
@@ -214,11 +215,21 @@ const totalKnowledge = ref(0); // total matching items on server
|
||||
const allIdsFetched = ref(false); // no more ID pages to fetch
|
||||
const idsFetching = ref(false); // ID batch request in-flight
|
||||
const contentFetching = ref(false); // content batch request in-flight
|
||||
const sentinelVisible = ref(false); // updated by IntersectionObserver
|
||||
const moreFailed = ref(false); // the last page asked for did not load
|
||||
|
||||
const loading = computed(() => idsFetching.value || contentFetching.value);
|
||||
|
||||
let fetchGen = 0; // incremented on each reset to invalidate stale responses
|
||||
const feedGen = ref(0); // fetchGen, readable by the template
|
||||
|
||||
// What the next page is keyed on: the feed it belongs to and how many of its ids
|
||||
// have been loaded. Ids, not items: a batch can return fewer records than it
|
||||
// asked for, and the feed must still move on. Empty once every id is loaded.
|
||||
const nextCursor = computed(() =>
|
||||
idQueue.value.length > 0 || !allIdsFetched.value
|
||||
? `${feedGen.value}:${idOffset.value - idQueue.value.length}`
|
||||
: "",
|
||||
);
|
||||
|
||||
function buildFilterParams(): URLSearchParams {
|
||||
const p = new URLSearchParams();
|
||||
@@ -244,7 +255,9 @@ async function fetchIdBatch(gen: number) {
|
||||
idOffset.value += data.ids.length;
|
||||
totalKnowledge.value = data.total;
|
||||
if (!data.has_more) allIdsFetched.value = true;
|
||||
} catch { /* silent */ }
|
||||
} catch {
|
||||
if (gen === fetchGen) moreFailed.value = true;
|
||||
}
|
||||
finally { if (gen === fetchGen) idsFetching.value = false; }
|
||||
}
|
||||
|
||||
@@ -262,26 +275,38 @@ async function loadNextContent(gen: number, count: number) {
|
||||
if (idQueue.value.length < REFILL_THRESHOLD && !allIdsFetched.value && !idsFetching.value) {
|
||||
fetchIdBatch(gen);
|
||||
}
|
||||
} catch { /* silent */ }
|
||||
} catch {
|
||||
// The ids go back to the front of the queue, so Try again asks for the
|
||||
// same records rather than skipping past them.
|
||||
if (gen === fetchGen) {
|
||||
idQueue.value.unshift(...toLoad);
|
||||
moreFailed.value = true;
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if (gen === fetchGen) contentFetching.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// The next page of the feed: more ids first when the queue has run dry.
|
||||
async function loadMore() {
|
||||
const gen = fetchGen;
|
||||
moreFailed.value = false;
|
||||
if (idQueue.value.length === 0) await fetchIdBatch(gen);
|
||||
if (gen !== fetchGen) return;
|
||||
contentFetching.value = false;
|
||||
// Sentinel may still be visible if new items didn't push it off screen
|
||||
await nextTick();
|
||||
if (sentinelVisible.value && idQueue.value.length > 0 && gen === fetchGen) {
|
||||
loadNextContent(gen, CONTENT_PAGE);
|
||||
}
|
||||
}
|
||||
await loadNextContent(gen, CONTENT_PAGE);
|
||||
}
|
||||
|
||||
async function reset() {
|
||||
fetchGen++;
|
||||
feedGen.value = fetchGen;
|
||||
const gen = fetchGen;
|
||||
items.value = [];
|
||||
idQueue.value = [];
|
||||
idOffset.value = 0;
|
||||
totalKnowledge.value = 0;
|
||||
allIdsFetched.value = false;
|
||||
moreFailed.value = false;
|
||||
await fetchIdBatch(gen);
|
||||
if (gen !== fetchGen) return;
|
||||
await loadNextContent(gen, INITIAL_CONTENT);
|
||||
@@ -294,23 +319,16 @@ async function fetchTags() {
|
||||
} catch { /* silent */ }
|
||||
}
|
||||
|
||||
async function resetAndReobserve() {
|
||||
await reset();
|
||||
await nextTick();
|
||||
setupObserver();
|
||||
}
|
||||
|
||||
function onSearchInput() {
|
||||
if (searchDebounce) clearTimeout(searchDebounce);
|
||||
searchDebounce = setTimeout(() => resetAndReobserve(), 380);
|
||||
searchDebounce = setTimeout(() => reset(), 380);
|
||||
}
|
||||
|
||||
watch([activeType, sortMode], () => resetAndReobserve());
|
||||
// Closing the sweep remounts the feed, and with it the scroll sentinel — a
|
||||
// fresh element the old observer is not watching. Without this the list loads
|
||||
// its first page and then never loads another.
|
||||
watch(sweepActive, (open) => { if (!open) resetAndReobserve(); });
|
||||
watch(activeTag, () => { fetchCounts(); resetAndReobserve(); });
|
||||
watch([activeType, sortMode], () => reset());
|
||||
// Closing the sweep starts the feed over, so a note confirmed in the sweep is
|
||||
// shown as it now stands.
|
||||
watch(sweepActive, (open) => { if (!open) reset(); });
|
||||
watch(activeTag, () => { fetchCounts(); reset(); });
|
||||
|
||||
// ─── Today bar ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -377,24 +395,6 @@ function formatDate(iso: string): string {
|
||||
return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
|
||||
}
|
||||
|
||||
// ─── Sentinel observer ────────────────────────────────────────────────────────
|
||||
|
||||
const sentinelEl = ref<HTMLElement | null>(null);
|
||||
let observer: IntersectionObserver | null = null;
|
||||
|
||||
function setupObserver() {
|
||||
observer?.disconnect();
|
||||
if (!sentinelEl.value) return;
|
||||
observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
sentinelVisible.value = entry.isIntersecting;
|
||||
if (entry.isIntersecting) loadNextContent(fetchGen, CONTENT_PAGE);
|
||||
},
|
||||
{ root: null, rootMargin: "200px" }
|
||||
);
|
||||
observer.observe(sentinelEl.value);
|
||||
}
|
||||
|
||||
// ─── Lifecycle ────────────────────────────────────────────────────────────────
|
||||
|
||||
onMounted(async () => {
|
||||
@@ -403,14 +403,11 @@ onMounted(async () => {
|
||||
fetchTags();
|
||||
fetchCounts();
|
||||
fetchTodayBar();
|
||||
await nextTick();
|
||||
setupObserver();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', onClickOutsideNewNote);
|
||||
if (searchDebounce) clearTimeout(searchDebounce);
|
||||
observer?.disconnect();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -583,10 +580,7 @@ onUnmounted(() => {
|
||||
</div>
|
||||
|
||||
<!-- The whole feed stands down while the sweep is open: two answers
|
||||
to two different questions on one screen is neither. Wrapped
|
||||
rather than given an extra v-if branch, because the scroll
|
||||
sentinel lives inside the grid and the observer must not be left
|
||||
holding a ref to something that never renders. -->
|
||||
to two different questions on one screen is neither. -->
|
||||
<template v-if="!sweepActive">
|
||||
<!-- Loading / empty -->
|
||||
<div v-if="loading && items.length === 0" class="knowledge-empty">Loading…</div>
|
||||
@@ -675,10 +669,12 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sentinel — IntersectionObserver triggers next content batch -->
|
||||
<div ref="sentinelEl" class="scroll-sentinel">
|
||||
<span v-if="contentFetching" class="sentinel-loading">Loading…</span>
|
||||
</div>
|
||||
<ScrollSentinel
|
||||
:cursor="nextCursor"
|
||||
:loading="loading"
|
||||
:failed="moreFailed"
|
||||
@more="loadMore"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -1115,19 +1111,6 @@ onUnmounted(() => {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
/* ── Sentinel ────────────────────────────────────────────── */
|
||||
.scroll-sentinel {
|
||||
grid-column: 1 / -1;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.sentinel-loading {
|
||||
font-size: 0.8rem;
|
||||
color: var(--fs-text-tertiary);
|
||||
}
|
||||
|
||||
/* ── Graph panel ─────────────────────────────────────────── */
|
||||
.graph-panel {
|
||||
width: 500px;
|
||||
|
||||
@@ -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,8 +9,10 @@ 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";
|
||||
import { formatBytes } from "@/utils/bytes";
|
||||
import { fmtDate, fmtLogStamp } from "@/utils/dateFormat";
|
||||
import { fetchVersion, type VersionPayload } from "@/api/version";
|
||||
@@ -170,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");
|
||||
@@ -383,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);
|
||||
@@ -431,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),
|
||||
@@ -452,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 {
|
||||
@@ -467,7 +515,7 @@ const confirmNewPassword = ref("");
|
||||
const changingPassword = ref(false);
|
||||
const invalidatingSessions = ref(false);
|
||||
const exporting = ref(false);
|
||||
const restoring = ref(false);
|
||||
const showRestore = ref(false);
|
||||
// Backup, export and restore walk the whole store, so they are slow BY DESIGN
|
||||
// and the client's ordinary 30s default would cut them off mid-work. They are
|
||||
// still bounded — every wait has a deadline, not necessarily a short one — and
|
||||
@@ -509,7 +557,6 @@ async function copyCommit() {
|
||||
commitCopied.value = true;
|
||||
setTimeout(() => { commitCopied.value = false; }, 2000);
|
||||
}
|
||||
const restoreFileInput = ref<HTMLInputElement | null>(null);
|
||||
|
||||
// Migrate stored "admin" → "config"; unknown tabs fall back to "general"
|
||||
const VALID_TABS = new Set(["general", "account", "notifications", "integrations", "data", "apikeys", "config", "users", "logs", "groups", "areas", "platforms"]);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1079,10 +1133,6 @@ async function exportNotes(format: "markdown" | "json") {
|
||||
}
|
||||
}
|
||||
|
||||
function triggerRestoreUpload() {
|
||||
restoreFileInput.value?.click();
|
||||
}
|
||||
|
||||
async function saveNotifications() {
|
||||
savingNotifications.value = true;
|
||||
notificationsSaved.value = false;
|
||||
@@ -1279,42 +1329,6 @@ async function runDbMaintenanceNow() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleRestoreFile(event: Event) {
|
||||
const file = (event.target as HTMLInputElement).files?.[0];
|
||||
if (!file) return;
|
||||
restoring.value = true;
|
||||
try {
|
||||
// The scheduled backup's .tar goes up as it is; the JSON download is
|
||||
// parsed first so a damaged file fails here, before the upload.
|
||||
const isTar = file.name.toLowerCase().endsWith(".tar");
|
||||
const res = await fetch("/api/admin/restore", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": isTar ? "application/x-tar" : "application/json" },
|
||||
body: isTar ? file : JSON.stringify(JSON.parse(await file.text())),
|
||||
signal: bulkDeadline(),
|
||||
});
|
||||
if (res.status === 413) {
|
||||
throw new Error(
|
||||
"the file is bigger than the web upload allows. Restore it with " +
|
||||
"`python -m grimoire.restore <file>` inside the Grimoire container instead.",
|
||||
);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({ error: `Error ${res.status}` }));
|
||||
throw new Error((body as Record<string, string>).error || `Error ${res.status}`);
|
||||
}
|
||||
const result = await res.json();
|
||||
toastStore.show(
|
||||
`Restored ${result.stats?.users ?? 0} users, ${result.stats?.notes ?? 0} notes, ${result.stats?.conversations ?? 0} conversations`
|
||||
);
|
||||
} catch (e) {
|
||||
toastStore.show("Restore failed: " + (e as Error).message, "error");
|
||||
} finally {
|
||||
restoring.value = false;
|
||||
if (restoreFileInput.value) restoreFileInput.value.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function testSearch() {
|
||||
const q = searchQuery.value.trim();
|
||||
if (!q) return;
|
||||
@@ -1693,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>
|
||||
@@ -1734,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
|
||||
@@ -2429,17 +2482,11 @@ async function deleteUser(userId: number) {
|
||||
<button class="btn-secondary" @click="exportData('full')" :disabled="exporting">
|
||||
{{ exporting ? "Exporting..." : "Full Backup" }}
|
||||
</button>
|
||||
<button class="btn-secondary btn-warn" @click="triggerRestoreUpload" :disabled="restoring">
|
||||
{{ restoring ? "Restoring..." : "Restore from Backup" }}
|
||||
<button class="btn-secondary btn-warn" @click="showRestore = true">
|
||||
Restore from Backup
|
||||
</button>
|
||||
<input
|
||||
ref="restoreFileInput"
|
||||
type="file"
|
||||
accept=".json,.tar"
|
||||
class="hidden-file-input"
|
||||
@change="handleRestoreFile"
|
||||
/>
|
||||
</div>
|
||||
<RestoreBackupDialog v-if="showRestore" @close="showRestore = false" />
|
||||
</section>
|
||||
<section class="settings-section full-width">
|
||||
<h2>Scheduled backups</h2>
|
||||
@@ -2710,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">
|
||||
@@ -3597,7 +3654,6 @@ async function deleteUser(userId: number) {
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.hidden-file-input { display: none; }
|
||||
|
||||
/* Checkboxes */
|
||||
.checkbox-field { margin-bottom: 1rem; }
|
||||
@@ -4294,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.10.26.2029",
|
||||
"version": "2026.11.23.0005",
|
||||
"author": {
|
||||
"name": "Bryan Van Deusen"
|
||||
},
|
||||
|
||||
+4
-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), `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
|
||||
@@ -39,9 +39,10 @@ another one means adding files, not moving or rewriting any.
|
||||
| `hooks/grimoire_prior_art.sh` | PreToolUse on editor writes: `GET /api/plugin/prior-art`. |
|
||||
| `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_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_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`). 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. |
|
||||
|
||||
+25
-7
@@ -79,11 +79,27 @@ On install you'll be asked for:
|
||||
message, as a short menu of titles and matched passages.
|
||||
- `hooks/hooks.json` → PreToolUse hook on `Bash` (`hooks/grimoire_tool_rules.sh`)
|
||||
→ `GET /api/plugin/tool-rules`: the rules that match the command about to run.
|
||||
- `hooks/hooks.json` → PreToolUse hook on editor writes, `Bash` and Grimoire's
|
||||
tools (`hooks/grimoire_project_fence.sh`) → `GET /api/plugin/write-scope`:
|
||||
holds a session to its own project. A session belongs to the project its
|
||||
starting directory resolves to (a `.grimoire` marker, else the git remote's
|
||||
binding), or, started outside any, to the first project it enters. Editing
|
||||
another project's files, a git commit, push, merge, rebase, pull, tag or
|
||||
reset in its repo (from `git -C`, after `cd`, or in a worktree of it), and a
|
||||
Grimoire write that lands in another project each stop on a permission
|
||||
prompt naming that project, in every permission mode. Filing an issue there
|
||||
(`create_task(kind="issue")`) and every read go ahead. An edit in the
|
||||
session's own repo never calls the server. It can't see a non-git shell
|
||||
write into another repo (`sed -i`, a redirect), but it fences that repo's
|
||||
commit and push. When the instance doesn't answer, the act goes ahead and
|
||||
the hook says so once per outage.
|
||||
- `hooks/hooks.json` → PreToolUse hook on every tool (`hooks/grimoire_moment.sh`)
|
||||
→ `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
|
||||
@@ -101,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
|
||||
@@ -113,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
|
||||
|
||||
@@ -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,24 @@ 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
|
||||
"${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')
|
||||
|
||||
@@ -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
|
||||
@@ -148,6 +149,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
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env bash
|
||||
# Grimoire — hold a session to its own project.
|
||||
#
|
||||
# A session belongs to the project its starting directory resolves to
|
||||
# (CLAUDE_PROJECT_DIR: a `.grimoire` marker, else the git remote's binding). A
|
||||
# session that starts outside any project belongs to the first project it
|
||||
# enters. Toward any other project a session may read anything and file an
|
||||
# issue. Every other write stops on a permission prompt naming the other
|
||||
# project, so the operator decides:
|
||||
# - editing a file in another project's repo (Write, Edit, MultiEdit,
|
||||
# NotebookEdit);
|
||||
# - a git command that changes history or a remote there (commit, push,
|
||||
# merge, rebase, pull, cherry-pick, revert, tag, am, reset, worktree add),
|
||||
# wherever it runs from: `git -C DIR`, `cd DIR && git …`, or the shell's
|
||||
# current directory;
|
||||
# - a Grimoire write that lands in another project.
|
||||
#
|
||||
# `ask`, not `deny`. Which projects a session may change is the operator's
|
||||
# call, and `ask` puts it to them each time, in every permission mode,
|
||||
# bypassPermissions included.
|
||||
#
|
||||
# The server says where an act lands (GET /api/plugin/write-scope). Two cases
|
||||
# never reach it:
|
||||
# - a directory that resolves the same way as the session's own, which is
|
||||
# nearly every edit;
|
||||
# - a tool named like a read (READ_PREFIXES in services/write_scope.py, held
|
||||
# equal to FENCE_READ_PREFIXES below by tests/test_write_scope.py).
|
||||
#
|
||||
# What it can't see: a non-git write from the shell (`sed -i`, a redirect)
|
||||
# into another repo. That repo's commit and push are still fenced.
|
||||
#
|
||||
# EXIT 0, ALWAYS. When the server doesn't answer, the act goes ahead and the
|
||||
# hook says once per outage that it couldn't check.
|
||||
#
|
||||
# Run as PostToolUse on enter_project, it records the project a session
|
||||
# without one has entered, and says nothing.
|
||||
set -uo pipefail
|
||||
|
||||
# shellcheck source=plugin/hooks/grimoire_defs.sh
|
||||
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
|
||||
|
||||
FENCE_READ_PREFIXES="get_ list_ search find_ enter_project what_might_apply resolve_design_system"
|
||||
FENCE_GIT_WRITES="commit push merge rebase pull cherry-pick revert tag am reset"
|
||||
|
||||
event=$(cat 2>/dev/null || true)
|
||||
[ -n "$event" ] || exit 0
|
||||
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
|
||||
[ -n "$event_flat" ] || exit 0
|
||||
|
||||
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
|
||||
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
|
||||
hook_event=$(grimoire_json_pick "$event_flat" '.hook_event_name')
|
||||
cwd=$(grimoire_json_pick "$event_flat" '.cwd')
|
||||
# Its own directory, which no compaction sweeps: the project a session
|
||||
# entered stays its project for the whole session.
|
||||
state_dir="${TMPDIR:-/tmp}/grimoire-fence"
|
||||
safe_sid=$(printf '%s' "${session_id:-none}" | tr -c 'A-Za-z0-9._-' '_')
|
||||
entered_file="$state_dir/${safe_sid}.entered"
|
||||
|
||||
# ── PostToolUse on enter_project: remember the first project entered ─────
|
||||
if [ "$hook_event" = "PostToolUse" ]; then
|
||||
case "$tool_name" in
|
||||
*__enter_project)
|
||||
pid=$(grimoire_json_pick "$event_flat" '.tool_input.project_id' | tr -cd '0-9')
|
||||
if [ -n "$pid" ] && [ -n "$session_id" ] && [ ! -s "$entered_file" ]; then
|
||||
mkdir -p "$state_dir" 2>/dev/null || true
|
||||
printf '%s' "$pid" > "$entered_file" 2>/dev/null || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The nearest directory at or above $1 that exists. A Write may create the
|
||||
# directories its file goes in.
|
||||
fence_existing_dir() {
|
||||
local d="$1" depth=0
|
||||
while [ -n "$d" ] && [ ! -d "$d" ] && [ "$depth" -lt 40 ]; do
|
||||
d=$(dirname -- "$d" 2>/dev/null) || return 0
|
||||
depth=$((depth + 1))
|
||||
done
|
||||
[ -d "$d" ] && printf '%s' "$d"
|
||||
}
|
||||
|
||||
# "DIR<TAB>SUBCOMMAND" for each git command in the shell command $1 that
|
||||
# changes history or a remote, with DIR resolved from $2: `cd` moves it for
|
||||
# the segments after, `git -C` for that one command. Segments split on ; && ||
|
||||
# | and newlines, and a quoted separator inside a message splits too; the
|
||||
# words after it are read as a command only if they start with cd or git.
|
||||
fence_git_targets() {
|
||||
printf '%s\n' "$1" | awk -v start="$2" -v home="${HOME:-}" -v writes="$FENCE_GIT_WRITES" '
|
||||
function unq(w) { gsub(/^["\047(]+|["\047)]+$/, "", w); return w }
|
||||
function at(base, p) {
|
||||
if (p ~ /^\//) return p
|
||||
if (p == "~") return home
|
||||
if (p ~ /^~\//) return home substr(p, 2)
|
||||
return base "/" p
|
||||
}
|
||||
BEGIN { dir = start; n = split(writes, w, " "); for (i = 1; i <= n; i++) iswrite[w[i]] = 1 }
|
||||
{
|
||||
line = $0
|
||||
gsub(/&&|\|\||;|\|/, "\n", line)
|
||||
m = split(line, segs, "\n")
|
||||
for (s = 1; s <= m; s++) {
|
||||
k = split(segs[s], t, /[ \t]+/)
|
||||
i = 1
|
||||
while (i <= k && (t[i] == "" || t[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/)) i++
|
||||
if (i > k) continue
|
||||
cmd = unq(t[i])
|
||||
if (cmd == "cd") {
|
||||
if (i + 1 <= k && t[i + 1] != "") dir = at(dir, unq(t[i + 1]))
|
||||
continue
|
||||
}
|
||||
if (cmd != "git" && cmd !~ /\/git$/) continue
|
||||
gdir = dir; i++
|
||||
while (i <= k && t[i] ~ /^-/) {
|
||||
if (t[i] == "-C" && i + 1 <= k) { gdir = at(gdir, unq(t[i + 1])); i += 2; continue }
|
||||
if (t[i] == "-c" || t[i] == "--git-dir" || t[i] == "--work-tree") { i += 2; continue }
|
||||
i++
|
||||
}
|
||||
if (i > k) continue
|
||||
sub_ = unq(t[i])
|
||||
if (sub_ == "worktree") { if (i + 1 <= k && unq(t[i + 1]) == "add") print gdir "\tworktree add"; continue }
|
||||
if (sub_ in iswrite) print gdir "\t" sub_
|
||||
}
|
||||
}' 2>/dev/null || true
|
||||
}
|
||||
|
||||
# The short scalar arguments of the MCP call, as a JSON object of strings:
|
||||
# ids, kind, status, a repo url, and arrays of ids. Long text (bodies, code) is
|
||||
# left out; nothing that says where a write lands is long.
|
||||
fence_tool_input() {
|
||||
printf '%s\n' "$event_flat" | awk -F'\t' '
|
||||
function add(k, v) { if (!(k in seen)) { seen[k] = 1; order[++n] = k } }
|
||||
$2 ~ /^\.tool_input\.[A-Za-z_]+$/ && $3 != "null" && length($3) <= 200 {
|
||||
k = substr($2, 13); add(k); val[k] = "\"" $3 "\""
|
||||
}
|
||||
$2 ~ /^\.tool_input\.[A-Za-z_]+\[[0-9]+\]$/ && $3 != "null" && length($3) <= 200 {
|
||||
k = substr($2, 13); sub(/\[.*$/, "", k); add(k)
|
||||
# Tested before assigning: mawk creates arr[k] as soon as it is the
|
||||
# target, so the test inside the assignment would always be true.
|
||||
item = "\"" $3 "\""
|
||||
if (k in arr) item = arr[k] "," item
|
||||
arr[k] = item
|
||||
}
|
||||
END {
|
||||
printf "{"
|
||||
for (i = 1; i <= n; i++) {
|
||||
k = order[i]
|
||||
printf "%s\"%s\":%s", (i > 1 ? "," : ""), k, ((k in arr) ? "[" arr[k] "]" : val[k])
|
||||
}
|
||||
printf "}"
|
||||
}' 2>/dev/null || printf '{}'
|
||||
}
|
||||
|
||||
grimoire_config || exit 0
|
||||
command -v curl >/dev/null 2>&1 || exit 0
|
||||
|
||||
project_dir=${CLAUDE_PROJECT_DIR:-$PWD}
|
||||
session_scope=$(grimoire_scope_query "$project_dir")
|
||||
entered=$(cat "$entered_file" 2>/dev/null | tr -cd '0-9')
|
||||
# No project to hold the session to: started outside any, and entered none.
|
||||
[ -n "$session_scope" ] || [ -n "$entered" ] || exit 0
|
||||
|
||||
# Each check this act needs: "SCOPE<TAB>ACT" for a directory, or a single
|
||||
# "tool" line for a Grimoire call.
|
||||
checks=""
|
||||
case "$tool_name" in
|
||||
Write|Edit|MultiEdit|NotebookEdit)
|
||||
path=$(grimoire_json_pick "$event_flat" '.tool_input.file_path')
|
||||
[ -n "$path" ] || path=$(grimoire_json_pick "$event_flat" '.tool_input.notebook_path')
|
||||
[ -n "$path" ] || exit 0
|
||||
case "$path" in /*) ;; *) path="${cwd:-$PWD}/$path" ;; esac
|
||||
dir=$(fence_existing_dir "$(dirname -- "$path")")
|
||||
[ -n "$dir" ] || exit 0
|
||||
scope=$(grimoire_scope_query "$dir")
|
||||
[ -n "$scope" ] && [ "$scope" != "$session_scope" ] || exit 0
|
||||
checks=$(printf '%s\t%s' "$scope" "Editing a file in")
|
||||
;;
|
||||
Bash)
|
||||
command=$(grimoire_json_pick "$event_flat" '.tool_input.command')
|
||||
case "$command" in *git*) ;; *) exit 0 ;; esac
|
||||
while IFS=$'\t' read -r gdir gsub; do
|
||||
[ -n "$gdir" ] || continue
|
||||
[ -d "$gdir" ] || continue
|
||||
scope=$(grimoire_scope_query "$gdir")
|
||||
[ -n "$scope" ] && [ "$scope" != "$session_scope" ] || continue
|
||||
checks="${checks}${checks:+$'\n'}${scope}"$'\t'"git ${gsub} in"
|
||||
done <<EOF
|
||||
$(fence_git_targets "$command" "${cwd:-$PWD}")
|
||||
EOF
|
||||
[ -n "$checks" ] || exit 0
|
||||
;;
|
||||
mcp__*)
|
||||
short=${tool_name##*__}
|
||||
for prefix in $FENCE_READ_PREFIXES; do
|
||||
case "$short" in "$prefix"*) exit 0 ;; esac
|
||||
done
|
||||
checks="tool"
|
||||
;;
|
||||
*) exit 0 ;;
|
||||
esac
|
||||
|
||||
base="${url%/}/api/plugin/write-scope?"
|
||||
[ -n "$session_scope" ] && base="${base}${session_scope}&"
|
||||
[ -n "$entered" ] && base="${base}fallback_project_id=${entered}&"
|
||||
|
||||
fence_unreached() {
|
||||
local marker="$state_dir/${safe_sid}.fence.unreached" now last
|
||||
mkdir -p "$state_dir" 2>/dev/null || true
|
||||
now=$(date +%s 2>/dev/null) || now=0
|
||||
if [ -f "$marker" ]; then
|
||||
last=$(cat "$marker" 2>/dev/null) || last=0
|
||||
case "$last" in ''|*[!0-9]*) last=0 ;; esac
|
||||
[ $((now - last)) -lt 600 ] && return 0
|
||||
fi
|
||||
printf '%s' "$now" > "$marker" 2>/dev/null || true
|
||||
grimoire_json_out "PreToolUse" "> Grimoire did not answer the project fence check, so this act went ahead without being checked against the session's project. If it changes another project's files or records, stop and file an issue there instead. Said once per outage."
|
||||
}
|
||||
|
||||
while IFS= read -r check; do
|
||||
[ -n "$check" ] || continue
|
||||
if [ "$check" = "tool" ]; then
|
||||
input=$(fence_tool_input | grimoire_urlenc)
|
||||
q="tool=$(printf '%s' "$short" | grimoire_urlenc)&input=${input}"
|
||||
else
|
||||
scope=${check%%$'\t'*}
|
||||
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) || {
|
||||
fence_unreached
|
||||
exit 0
|
||||
}
|
||||
rm -f "$state_dir/${safe_sid}.fence.unreached" 2>/dev/null || true
|
||||
flat=$(printf '%s' "$resp" | grimoire_json_flat)
|
||||
if [ "$(grimoire_json_pick "$flat" '.allowed')" = "false" ]; then
|
||||
reason=$(grimoire_json_pick "$flat" '.reason')
|
||||
esc=$(printf '%s' "$reason" | grimoire_json_escape) || exit 0
|
||||
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"%s"}}\n' "$esc"
|
||||
exit 0
|
||||
fi
|
||||
done <<EOF
|
||||
$checks
|
||||
EOF
|
||||
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')
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -31,11 +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)
|
||||
# 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}".* 2>/dev/null || true
|
||||
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
|
||||
"${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
|
||||
|
||||
@@ -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,39 @@ 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}" \
|
||||
"${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
|
||||
"${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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -25,6 +25,15 @@
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit|NotebookEdit|Bash|mcp__.*grimoire.*",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [
|
||||
@@ -89,6 +98,15 @@
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_claim_session.sh\""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "mcp__.*__enter_project",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreCompact": [
|
||||
|
||||
@@ -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
|
||||
@@ -277,11 +277,12 @@ bound — confine the session to it:
|
||||
- **Pass that `project_id` to every read** (`search`, `list_tasks`,
|
||||
`list_notes`). An unscoped read bleeds every other project's work into your
|
||||
context.
|
||||
- **Only reference or offer work on the in-scope project.** Don't surface,
|
||||
suggest, or start work on other projects unless the operator explicitly widens
|
||||
scope.
|
||||
- If something clearly belongs to a *different* project, say so and **ask before
|
||||
switching** — never silently operate cross-project.
|
||||
- **Only reference or offer work on the in-scope project**, unless the
|
||||
operator explicitly widens scope; work that belongs elsewhere, say so and ask.
|
||||
- **Cross-project, the one change to make is filing an issue**:
|
||||
`create_task(project_id=<theirs>, kind="issue")` with how you found it and the
|
||||
evidence. Reading there is fine; editing its files, committing or pushing in
|
||||
its repo, or changing its records is the operator's call, and the plugin asks.
|
||||
|
||||
## Read these when the moment comes
|
||||
|
||||
|
||||
@@ -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]
|
||||
|
||||
+45
-5
@@ -395,6 +395,13 @@ SMOKE_EVENTS: dict[str, str] = {
|
||||
{"session_id": "smoke", "cwd": ".", "hook_event_name": "SessionEnd",
|
||||
"reason": "prompt_input_exit"}
|
||||
),
|
||||
# The project fence. A Grimoire write is the one act that always asks the
|
||||
# server, so it is what reaches the network in the unreachable case: there
|
||||
# the act goes ahead and the hook says once that it couldn't check.
|
||||
"grimoire_project_fence.sh": json.dumps(
|
||||
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PreToolUse",
|
||||
"tool_name": "mcp__grimoire__update_task", "tool_input": {"task_id": 1}}
|
||||
),
|
||||
# The shared library is sourced, never run; executed bare it defines
|
||||
# functions and exits — silent by construction.
|
||||
"grimoire_defs.sh": "",
|
||||
@@ -415,9 +422,14 @@ STATIC_EMITTERS = {
|
||||
# would look like a leak; it is the opposite.
|
||||
"grimoire_precompact_preserve.sh": "preservation instructions present",
|
||||
}
|
||||
# The hooks that say so when a configured instance does not answer.
|
||||
OUTAGE_SPEAKERS = {"grimoire_prior_art.sh", "grimoire_after_write.sh"}
|
||||
OUTAGE_LINE = "> Grimoire did not answer the prior-art check"
|
||||
# The hooks that say so when a configured instance does not answer, each with
|
||||
# the line it says it in.
|
||||
_PRIOR_ART_OUTAGE = "> Grimoire did not answer the prior-art check"
|
||||
OUTAGE_LINES = {
|
||||
"grimoire_prior_art.sh": _PRIOR_ART_OUTAGE,
|
||||
"grimoire_after_write.sh": _PRIOR_ART_OUTAGE,
|
||||
"grimoire_project_fence.sh": "> Grimoire did not answer the project fence check",
|
||||
}
|
||||
|
||||
|
||||
def _run_hook(script: Path, event: str, env_extra: dict[str, str]) -> subprocess.CompletedProcess:
|
||||
@@ -464,13 +476,13 @@ def check_fail_open() -> None:
|
||||
f"output must survive having no credentials ({what})")
|
||||
else:
|
||||
ok(f"{rel} [{label}]: exit 0, {what}")
|
||||
elif out and label == "unreachable" and script.name in OUTAGE_SPEAKERS:
|
||||
elif out and label == "unreachable" and script.name in OUTAGE_LINES:
|
||||
# The only thing allowed here is the outage line itself.
|
||||
try:
|
||||
ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
ctx = ""
|
||||
if ctx.startswith(OUTAGE_LINE):
|
||||
if ctx.startswith(OUTAGE_LINES[script.name]):
|
||||
ok(f"{rel} [{label}]: exit 0, says the instance did not answer")
|
||||
else:
|
||||
fail(f"{rel} [{label}]: emitted output with no working instance "
|
||||
@@ -769,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",
|
||||
@@ -788,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)
|
||||
|
||||
|
||||
+24
-10
@@ -6,7 +6,8 @@ from pathlib import Path
|
||||
|
||||
from quart import Quart, g, jsonify, make_response, request, send_from_directory
|
||||
|
||||
from grimoire.config import PLACEHOLDER_SECRET_KEYS, SECRET_KEY_FILENAME, Config
|
||||
from grimoire.config import SECRET_KEY_FILENAME, Config
|
||||
from grimoire.proxy import PerRequestSecureSession, apply_https_headers
|
||||
from grimoire.routes.admin import admin_bp
|
||||
from grimoire.routes.api import api
|
||||
from grimoire.routes.auth import auth_bp
|
||||
@@ -61,13 +62,13 @@ def create_app() -> Quart:
|
||||
app.secret_key = Config.SECRET_KEY
|
||||
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
||||
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
||||
app.config["SESSION_COOKIE_SECURE"] = Config.SECURE_COOKIES
|
||||
# Secure is decided per request, from the trusted proxy's X-Forwarded-Proto.
|
||||
app.session_interface = PerRequestSecureSession()
|
||||
|
||||
if Config.SECRET_KEY in PLACEHOLDER_SECRET_KEYS:
|
||||
if os.environ.get("SECURE_COOKIES"):
|
||||
logger.warning(
|
||||
"SECRET_KEY is set to a public placeholder, so session cookies are insecure. "
|
||||
"Remove it to let the instance keep its own key in %s, or set a real one.",
|
||||
Config.DATA_DIR,
|
||||
"SECURE_COOKIES is not used: the session cookie is Secure on every request "
|
||||
"the trusted proxy reports as HTTPS. Remove it from the environment."
|
||||
)
|
||||
if Config.SECRET_KEY_SOURCE == "ephemeral":
|
||||
logger.warning(
|
||||
@@ -82,11 +83,12 @@ def create_app() -> Quart:
|
||||
Config.DATA_DIR, SECRET_KEY_FILENAME,
|
||||
)
|
||||
|
||||
if not Config.TRUST_PROXY_HEADERS:
|
||||
if os.environ.get("TRUST_PROXY_HEADERS") and not os.environ.get("TRUSTED_PROXY_HOPS"):
|
||||
logger.warning(
|
||||
"TRUST_PROXY_HEADERS is not set. If this instance is behind a reverse proxy "
|
||||
"(nginx, Caddy, Traefik) set TRUST_PROXY_HEADERS=true so rate limiting uses "
|
||||
"real client IPs rather than the proxy IP."
|
||||
"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,
|
||||
)
|
||||
|
||||
app.register_blueprint(admin_bp)
|
||||
@@ -159,6 +161,7 @@ def create_app() -> Quart:
|
||||
except Exception:
|
||||
logger.debug("Failed to log usage", exc_info=True)
|
||||
|
||||
apply_https_headers(response)
|
||||
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
||||
response.headers.setdefault("X-Frame-Options", "DENY")
|
||||
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
@@ -195,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.
|
||||
#
|
||||
|
||||
+34
-6
@@ -85,6 +85,21 @@ def _secret_key() -> tuple[str, str]:
|
||||
return secrets.token_hex(32), "ephemeral"
|
||||
|
||||
|
||||
def _trusted_proxy_hops() -> int:
|
||||
"""TRUSTED_PROXY_HOPS, default 1. The older TRUST_PROXY_HEADERS switch is
|
||||
still read when the hop count is unset: false means 0 hops. A value that
|
||||
is not a whole number reads as -1, which validate() refuses."""
|
||||
raw = os.environ.get("TRUSTED_PROXY_HOPS", "").strip()
|
||||
if raw:
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return -1
|
||||
if os.environ.get("TRUST_PROXY_HEADERS", "").strip().lower() in ("0", "false", "no"):
|
||||
return 0
|
||||
return 1
|
||||
|
||||
|
||||
class Config:
|
||||
DATABASE_URL: str = _read_secret(
|
||||
"DATABASE_URL",
|
||||
@@ -95,7 +110,6 @@ class Config:
|
||||
# shipped compose file, beside the model cache and diagnostics.
|
||||
DATA_DIR: str = os.environ.get("DATA_DIR", "/data")
|
||||
SECRET_KEY, SECRET_KEY_SOURCE = _secret_key()
|
||||
SECURE_COOKIES: bool = os.environ.get("SECURE_COOKIES", "").lower() in ("1", "true", "yes")
|
||||
LOG_LEVEL: str = os.environ.get("LOG_LEVEL", "INFO")
|
||||
LOG_RETENTION_DAYS: int = int(os.environ.get("LOG_RETENTION_DAYS", "90"))
|
||||
|
||||
@@ -108,7 +122,16 @@ class Config:
|
||||
SMTP_FROM_NAME: str = os.environ.get("SMTP_FROM_NAME", "Fabled Grimoire")
|
||||
SMTP_USE_TLS: bool = os.environ.get("SMTP_USE_TLS", "true").lower() in ("1", "true", "yes")
|
||||
BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/")
|
||||
TRUST_PROXY_HEADERS: bool = os.environ.get("TRUST_PROXY_HEADERS", "").lower() in ("1", "true", "yes")
|
||||
# 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. 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
|
||||
@@ -163,11 +186,16 @@ class Config:
|
||||
errors.append(f"SMTP_PORT={cls.SMTP_PORT} must be between 1 and 65535")
|
||||
if cls.oidc_enabled() and not cls.BASE_URL.startswith(("http://", "https://")):
|
||||
errors.append(f"BASE_URL='{cls.BASE_URL}' must start with http:// or https:// when OIDC is enabled")
|
||||
if cls.SECRET_KEY == "dev-secret-change-me" and cls.SECURE_COOKIES:
|
||||
if cls.TRUSTED_PROXY_HOPS < 0:
|
||||
errors.append(
|
||||
"SECRET_KEY is set to the public placeholder 'dev-secret-change-me' but "
|
||||
"SECURE_COOKIES=true indicates a production deployment. Remove SECRET_KEY "
|
||||
"to let the instance keep its own key in DATA_DIR, or set a real one."
|
||||
f"TRUSTED_PROXY_HOPS={os.environ.get('TRUSTED_PROXY_HOPS')!r} must be a whole "
|
||||
"number of proxies, 0 or more"
|
||||
)
|
||||
if cls.SECRET_KEY in PLACEHOLDER_SECRET_KEYS:
|
||||
errors.append(
|
||||
f"SECRET_KEY is set to the public placeholder {cls.SECRET_KEY!r}, so anyone "
|
||||
"could forge a session. Remove SECRET_KEY to let the instance keep its own "
|
||||
"key in DATA_DIR, or set a real one."
|
||||
)
|
||||
if errors:
|
||||
raise ValueError("Configuration errors:\n" + "\n".join(f" - {e}" for e in errors))
|
||||
|
||||
@@ -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,25 @@ 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 for one read of it — for a rule whose miss
|
||||
costs a rewrite. `enforce` checks the act itself — for a hard
|
||||
boundary. 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 +561,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 +576,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 +589,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 +666,25 @@ 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 for one read of it — for a rule whose miss
|
||||
costs a rewrite. `enforce` checks the act itself — for a hard
|
||||
boundary. 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 +693,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 +708,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 +722,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 +784,30 @@ 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 for one read of it — for a rule whose miss
|
||||
costs a rewrite. `enforce` checks the act itself — for a hard
|
||||
boundary. 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 +829,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 +860,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 +935,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 +958,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 +983,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 +996,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 +1052,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 +1090,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:
|
||||
|
||||
@@ -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,7 @@ 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.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
|
||||
@@ -94,3 +95,4 @@ from grimoire.models.family import ( # noqa: E402, F401
|
||||
FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform,
|
||||
FamilyIdeaReference, Platform, ProjectPlatform,
|
||||
)
|
||||
from grimoire.models.instance import InstanceIdentity # noqa: E402, F401
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, Integer, Text, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from grimoire.models import Base
|
||||
|
||||
|
||||
class InstanceIdentity(Base):
|
||||
"""The one row naming this database's id lineage.
|
||||
|
||||
Two stores with the same instance id number their rows the same way: one
|
||||
is the other, or a restore of it made with the original ids kept. That is
|
||||
what lets a backup roll a live instance back by id, and what refuses a
|
||||
backup whose ids would land on unrelated rows. Made by the migration, so
|
||||
an instance has it before anyone registers.
|
||||
"""
|
||||
|
||||
__tablename__ = "instance_identity"
|
||||
__table_args__ = (CheckConstraint("id = 1", name="ck_instance_identity_single_row"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
|
||||
instance_id: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
@@ -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,69 @@
|
||||
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.
|
||||
|
||||
`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.
|
||||
|
||||
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)
|
||||
|
||||
__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),
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
"""What the trusted reverse proxy says about a request: who sent it, and
|
||||
whether it arrived over HTTPS.
|
||||
|
||||
Grimoire serves plain HTTP; TLS ends at the operator's proxy. The proxy
|
||||
reports the client's address in X-Forwarded-For and the scheme in
|
||||
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.
|
||||
|
||||
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
|
||||
session cookie's Secure flag and HSTS. A second reader is a second trust rule.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from quart import has_request_context, request
|
||||
from quart.sessions import SecureCookieSessionInterface
|
||||
|
||||
from grimoire.config import Config
|
||||
|
||||
# HSTS for a year, sent only on a request the trusted proxy says is HTTPS.
|
||||
# No includeSubDomains or preload: the app does not own the operator's domain.
|
||||
HSTS_VALUE = "max-age=31536000"
|
||||
|
||||
|
||||
def trusted_entry(header: str, hops: int) -> str | None:
|
||||
"""The entry `hops` in from the right of a forwarding header.
|
||||
|
||||
A header shorter than that is read at its leftmost entry, the one the
|
||||
first proxy wrote. A road with fewer proxies than the count (a LAN road
|
||||
beside a Cloudflare one) still reads right that way. None when no proxy
|
||||
is trusted or there is no header. Pure, so the trust boundary is
|
||||
testable without a request."""
|
||||
if hops <= 0:
|
||||
return None
|
||||
entries = [part.strip() for part in header.split(",") if part.strip()]
|
||||
if not entries:
|
||||
return None
|
||||
return entries[-min(hops, len(entries))]
|
||||
|
||||
|
||||
# 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 ",".join(request.headers.getlist(name))
|
||||
|
||||
|
||||
def _forwarded(name: str) -> str | None:
|
||||
return trusted_entry(_chain(name), trusted_hops())
|
||||
|
||||
|
||||
def client_ip() -> str:
|
||||
"""The caller's address, as the trusted proxy saw it."""
|
||||
if not has_request_context():
|
||||
return ""
|
||||
return (_forwarded("X-Forwarded-For") or request.remote_addr or "")[:64]
|
||||
|
||||
|
||||
def is_https() -> bool:
|
||||
"""Whether this request arrived over HTTPS, by the trusted proxy's word."""
|
||||
if not has_request_context():
|
||||
return False
|
||||
if request.scheme == "https":
|
||||
return True
|
||||
return (_forwarded("X-Forwarded-Proto") or "").lower() == "https"
|
||||
|
||||
|
||||
class PerRequestSecureSession(SecureCookieSessionInterface):
|
||||
"""The session cookie is Secure exactly when the request is HTTPS, so a
|
||||
public deployment gets it and a plain-HTTP one keeps working."""
|
||||
|
||||
def get_cookie_secure(self, app) -> bool:
|
||||
return is_https()
|
||||
|
||||
|
||||
def apply_https_headers(response) -> None:
|
||||
"""HSTS on an HTTPS request, and only then. The app never redirects to
|
||||
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.
|
||||
When deployed behind a reverse proxy (nginx, Caddy, Traefik) you MUST set
|
||||
TRUST_PROXY_HEADERS=true so that the real client IP is used as the bucket key
|
||||
rather than the proxy's IP (which would cause all users to 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()
|
||||
|
||||
|
||||
+79
-29
@@ -1,20 +1,26 @@
|
||||
"""Restore a Grimoire backup into an empty instance, from the command line.
|
||||
"""Restore a Grimoire backup from the command line.
|
||||
|
||||
python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar
|
||||
python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar --yes
|
||||
|
||||
This is how a fresh instance is brought back after losing the old one. Run it
|
||||
inside the Grimoire container, which already has the database settings and has
|
||||
already migrated the schema on start. It reads either the scheduled backup's
|
||||
tar (services/backup_file.py) or the JSON the admin download produces.
|
||||
Run it inside the Grimoire container, which already has the database settings
|
||||
and has migrated the schema on start. It reads the scheduled backup's tar
|
||||
(services/backup_file.py) or the JSON the admin download produces, and nothing
|
||||
limits the file's size.
|
||||
|
||||
It refuses a database that already holds an account. A restore re-creates
|
||||
every user, project and record from the file with new ids; into a live
|
||||
instance it would add a second copy of everything rather than replace it.
|
||||
(Settings → Backup & Restore still offers the upload for that case, on
|
||||
purpose and with its own warning.)
|
||||
It does what Settings → Restore does (services/backup.py replace_from_backup):
|
||||
- **A new, empty instance** takes the backup as it is.
|
||||
- **A live instance** rolls back to a backup of its own: everything goes back
|
||||
to the moment the backup was taken, for every user.
|
||||
- A backup from another instance, or one made before backups recorded their
|
||||
instance, only goes into an empty instance.
|
||||
|
||||
Unlike the upload, nothing limits the file's size here, so this is also the
|
||||
way in for a backup too big for the web upload.
|
||||
Without --yes it only says what would change. With --yes it first saves the
|
||||
current state as a backup (to the backup destination, or DATA_DIR/pre-restore),
|
||||
then restores. Everyone is signed out afterwards.
|
||||
|
||||
A backup in the oldest (v1) format is copied into an empty instance with new
|
||||
ids instead, as before.
|
||||
|
||||
Afterwards, restart Grimoire: search indexes are not part of a backup and are
|
||||
rebuilt from the restored records at startup.
|
||||
@@ -48,9 +54,39 @@ async def _account_count() -> int:
|
||||
return (await session.execute(select(func.count()).select_from(User))).scalar_one()
|
||||
|
||||
|
||||
async def run(path: Path) -> int:
|
||||
from grimoire.models import engine
|
||||
async def _restore_v1(payload: dict) -> int:
|
||||
from grimoire.services.backup import restore_full_backup
|
||||
|
||||
accounts = await _account_count()
|
||||
if accounts:
|
||||
print(
|
||||
f"This database already holds {accounts} account(s). A backup in the oldest "
|
||||
"format is copied in with new ids rather than replacing anything, so it only "
|
||||
"goes into an empty instance. Start Grimoire on an empty database and run "
|
||||
"this again.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 3
|
||||
stats = await restore_full_backup(payload)
|
||||
print(json.dumps({"restored": stats}, indent=2, default=str))
|
||||
return 0
|
||||
|
||||
|
||||
def _print_preview(preview: dict) -> None:
|
||||
taken = preview.get("exported_at") or "an unknown date"
|
||||
if preview["mode"] == "rollback":
|
||||
print(f"This rolls the whole instance back to {taken}, for every user. Anything "
|
||||
"made since is removed, edits since are undone, records deleted since come back.")
|
||||
else:
|
||||
print(f"This instance has no records yet; it takes the backup from {taken} as it is.")
|
||||
for count in preview["counts"]:
|
||||
print(f" {count['kind']:<24} now {count['now']:>7} after {count['after']:>7}")
|
||||
|
||||
|
||||
async def run(path: Path, *, yes: bool = False) -> int:
|
||||
from grimoire.models import engine
|
||||
from grimoire.services import backup_job
|
||||
from grimoire.services.backup import RestoreRefused, replace_preview
|
||||
from grimoire.services.backup_file import ArchiveError
|
||||
|
||||
try:
|
||||
@@ -63,20 +99,29 @@ async def run(path: Path) -> int:
|
||||
print(f"{path} isn't a backup this Grimoire can read: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
accounts = await _account_count()
|
||||
if accounts:
|
||||
print(
|
||||
f"This database already holds {accounts} account(s). A restore adds a second "
|
||||
"copy of everything rather than replacing it, so it only runs into an empty "
|
||||
"instance. Start Grimoire on an empty database and run this again.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if (payload.get("version") or 1) < 2:
|
||||
code = await _restore_v1(payload)
|
||||
else:
|
||||
try:
|
||||
_print_preview(await replace_preview(payload))
|
||||
if not yes:
|
||||
print("Nothing was changed. Run it again with --yes to restore.",
|
||||
file=sys.stderr)
|
||||
return 4
|
||||
result = await backup_job.rollback_to_backup(payload)
|
||||
except RestoreRefused as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
return 3
|
||||
|
||||
stats = await restore_full_backup(payload)
|
||||
print(json.dumps({"restored": stats}, indent=2, default=str))
|
||||
print("Restored. Restart Grimoire so the search indexes are rebuilt.", file=sys.stderr)
|
||||
return 0
|
||||
safety = result["safety_backup"]
|
||||
print(json.dumps({"restored": result["restored"], "safety_backup": safety},
|
||||
indent=2, default=str))
|
||||
print(f"The state it replaced is saved as {safety['file']} in {safety['where']}.",
|
||||
file=sys.stderr)
|
||||
code = 0
|
||||
if code == 0:
|
||||
print("Restored. Restart Grimoire so the search indexes are rebuilt; "
|
||||
"everyone signs in again.", file=sys.stderr)
|
||||
return code
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
@@ -84,11 +129,16 @@ async def run(path: Path) -> int:
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="python -m grimoire.restore",
|
||||
description="Restore a Grimoire backup (.tar or .json) into an empty instance.",
|
||||
description=(
|
||||
"Restore a Grimoire backup (.tar or .json): into an empty instance, or "
|
||||
"roll this instance back to a backup of its own."
|
||||
),
|
||||
)
|
||||
parser.add_argument("file", type=Path, help="the backup file")
|
||||
parser.add_argument("--yes", action="store_true",
|
||||
help="restore; without it, only say what would change")
|
||||
args = parser.parse_args(argv)
|
||||
return asyncio.run(run(args.file))
|
||||
return asyncio.run(run(args.file, yes=args.yes))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+154
-34
@@ -3,7 +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,
|
||||
@@ -16,7 +20,6 @@ from grimoire.services.auth import (
|
||||
from grimoire.services.backup import (
|
||||
export_full_backup,
|
||||
export_user_backup,
|
||||
restore_full_backup,
|
||||
)
|
||||
from grimoire.services.email import SMTP_SETTING_KEYS, get_base_url, get_smtp_config, is_smtp_configured, send_test_email
|
||||
from grimoire.services.logging import get_logs, get_log_stats, log_audit
|
||||
@@ -46,7 +49,7 @@ async def backup():
|
||||
else:
|
||||
data = await export_user_backup(uid)
|
||||
|
||||
await log_audit("backup", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"scope": scope})
|
||||
await log_audit("backup", user_id=uid, username=g.user.username, ip_address=client_ip(), details={"scope": scope})
|
||||
return Response(
|
||||
json.dumps(data, indent=2, default=str),
|
||||
content_type="application/json",
|
||||
@@ -56,31 +59,111 @@ async def backup():
|
||||
)
|
||||
|
||||
|
||||
async def _restore_payload() -> tuple[dict | None, tuple | None]:
|
||||
"""The backup a restore request names: `?source=<file>` at the backup
|
||||
destination, or the uploaded file (the JSON download as
|
||||
application/json, or the tar as the raw body; held to the request-size
|
||||
limit, which is why the destination is the way in for a large one).
|
||||
Returns (payload, None) or (None, an error response)."""
|
||||
import io
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from grimoire.services import backup_destination as dest
|
||||
from grimoire.services.backup_file import ArchiveError, read_archive
|
||||
|
||||
source = request.args.get("source")
|
||||
try:
|
||||
if source:
|
||||
config = await dest.load_config()
|
||||
secret, _ = await dest.load_secret()
|
||||
with tempfile.TemporaryDirectory(prefix="grimoire-restore-") as staging:
|
||||
path = await dest.open_backup(config, secret, source, Path(staging))
|
||||
|
||||
def load() -> dict:
|
||||
with open(path, "rb") as f:
|
||||
return read_archive(f)
|
||||
data = await asyncio.to_thread(load)
|
||||
elif request.mimetype == "application/json":
|
||||
data = await request.get_json()
|
||||
else:
|
||||
data = read_archive(io.BytesIO(await request.get_data()))
|
||||
except dest.DestinationError as exc:
|
||||
return None, (jsonify({"error": str(exc)}), 400)
|
||||
except ArchiveError as exc:
|
||||
return None, (jsonify({"error": f"That file isn't a Grimoire backup: {exc}"}), 400)
|
||||
if not isinstance(data, dict) or not data:
|
||||
return None, (jsonify({"error": "No backup data provided"}), 400)
|
||||
return data, None
|
||||
|
||||
|
||||
@admin_bp.route("/restore/sources", methods=["GET"])
|
||||
@admin_required
|
||||
async def restore_sources():
|
||||
"""The backups at the backup destination, newest first, to restore from
|
||||
without uploading one."""
|
||||
from grimoire.services import backup_destination as dest
|
||||
|
||||
config = await dest.load_config()
|
||||
secret, _ = await dest.load_secret()
|
||||
try:
|
||||
backups = await asyncio.wait_for(dest.list_backups(config, secret), _BACKUP_CHECK_TIMEOUT)
|
||||
except dest.DestinationError as exc:
|
||||
return jsonify({"backups": [], "error": str(exc)})
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
return jsonify({"backups": [], "error": (
|
||||
f"The destination didn't answer within {int(_BACKUP_CHECK_TIMEOUT)} seconds."
|
||||
)})
|
||||
return jsonify({"backups": [{"name": b.name, "size_bytes": b.size_bytes} for b in backups]})
|
||||
|
||||
|
||||
@admin_bp.route("/restore/preview", methods=["POST"])
|
||||
@admin_required
|
||||
async def restore_preview():
|
||||
"""What restoring this backup would do, changing nothing: fresh or
|
||||
rollback, when it was taken, and the counts now and after. 409 with the
|
||||
reason when it can't be restored here."""
|
||||
from grimoire.services.backup import RestoreRefused, replace_preview
|
||||
|
||||
data, error = await _restore_payload()
|
||||
if error:
|
||||
return error
|
||||
try:
|
||||
return jsonify(await replace_preview(data))
|
||||
except RestoreRefused as exc:
|
||||
return jsonify({"error": str(exc)}), 409
|
||||
|
||||
|
||||
@admin_bp.route("/restore", methods=["POST"])
|
||||
@admin_required
|
||||
async def restore():
|
||||
"""Restore from an uploaded backup: the JSON download (application/json)
|
||||
or the scheduled backup's tar (sent as the raw body). The upload is held
|
||||
to the app's request-size limit; `python -m grimoire.restore` has none, and
|
||||
is the way in for a bigger file or a fresh instance."""
|
||||
if request.mimetype == "application/json":
|
||||
data = await request.get_json()
|
||||
else:
|
||||
import io
|
||||
|
||||
from grimoire.services.backup_file import ArchiveError, read_archive
|
||||
"""Put the whole instance back to a full backup (services/backup.py
|
||||
replace_from_backup), after backing up what it replaces. `?confirm=rollback`
|
||||
is required: this removes everything made since the backup, for every
|
||||
user. Every session ends, the caller's included; search is rebuilt in the
|
||||
background."""
|
||||
from grimoire.services import backup_job as job
|
||||
from grimoire.services.backup import RestoreRefused
|
||||
|
||||
if request.args.get("confirm") != "rollback":
|
||||
return jsonify({"error": "Restoring replaces the whole instance; confirm it first."}), 400
|
||||
data, error = await _restore_payload()
|
||||
if error:
|
||||
return error
|
||||
try:
|
||||
data = read_archive(io.BytesIO(await request.get_data()))
|
||||
except ArchiveError as exc:
|
||||
return jsonify({"error": f"That file isn't a Grimoire backup: {exc}"}), 400
|
||||
if not data:
|
||||
return jsonify({"error": "No backup data provided"}), 400
|
||||
|
||||
stats = await restore_full_backup(data)
|
||||
result = await job.rollback_to_backup(data)
|
||||
except RestoreRefused as exc:
|
||||
return jsonify({"error": str(exc)}), 409
|
||||
except job.BackupBusy:
|
||||
return jsonify({"error": "A backup is running. Restore once it has finished."}), 409
|
||||
job.start_reindex_after_restore()
|
||||
uid = get_current_user_id()
|
||||
await log_audit("restore", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"stats": stats})
|
||||
return jsonify({"status": "ok", "stats": stats})
|
||||
await log_audit(
|
||||
"restore", user_id=uid, username=g.user.username, ip_address=client_ip(),
|
||||
details={"mode": result["mode"], "exported_at": result.get("exported_at"),
|
||||
"safety_backup": result["safety_backup"], "stats": result["restored"]},
|
||||
)
|
||||
return jsonify({"status": "ok", **result})
|
||||
|
||||
|
||||
@admin_bp.route("/users", methods=["GET"])
|
||||
@@ -100,7 +183,7 @@ async def remove_user(user_id: int):
|
||||
deleted = await delete_user(user_id)
|
||||
if not deleted:
|
||||
return jsonify({"error": "User not found"}), 404
|
||||
await log_audit("user_delete", user_id=current_uid, username=g.user.username, ip_address=request.remote_addr, details={"deleted_user_id": user_id})
|
||||
await log_audit("user_delete", user_id=current_uid, username=g.user.username, ip_address=client_ip(), details={"deleted_user_id": user_id})
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
@@ -121,7 +204,7 @@ async def toggle_registration():
|
||||
|
||||
uid = get_current_user_id()
|
||||
await set_registration_open(uid, bool(open_val))
|
||||
await log_audit("registration_toggle", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"open": bool(open_val)})
|
||||
await log_audit("registration_toggle", user_id=uid, username=g.user.username, ip_address=client_ip(), details={"open": bool(open_val)})
|
||||
return jsonify({"status": "ok", "open": bool(open_val)})
|
||||
|
||||
|
||||
@@ -151,7 +234,7 @@ async def update_smtp():
|
||||
|
||||
if settings_to_save:
|
||||
await set_settings_batch(uid, settings_to_save)
|
||||
await log_audit("smtp_config", user_id=uid, username=g.user.username, ip_address=request.remote_addr)
|
||||
await log_audit("smtp_config", user_id=uid, username=g.user.username, ip_address=client_ip())
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
@@ -166,7 +249,7 @@ async def test_smtp():
|
||||
uid = get_current_user_id()
|
||||
try:
|
||||
await send_test_email(recipient)
|
||||
await log_audit("smtp_test", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"recipient": recipient})
|
||||
await log_audit("smtp_test", user_id=uid, username=g.user.username, ip_address=client_ip(), details={"recipient": recipient})
|
||||
return jsonify({"status": "ok"})
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)}), 500
|
||||
@@ -180,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 = (
|
||||
@@ -209,7 +291,7 @@ async def update_forge_webhook_settings():
|
||||
# The secret is deliberately absent from the audit detail.
|
||||
await log_audit(
|
||||
"forge_webhook_config", user_id=uid, username=g.user.username,
|
||||
ip_address=request.remote_addr, details={},
|
||||
ip_address=client_ip(), details={},
|
||||
)
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
@@ -262,10 +344,48 @@ async def update_base_url():
|
||||
return jsonify({"error": "Base URL must use http or https"}), 400
|
||||
uid = get_current_user_id()
|
||||
await set_setting(uid, "base_url", url)
|
||||
await log_audit("base_url_config", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"base_url": url})
|
||||
await log_audit("base_url_config", user_id=uid, username=g.user.username, ip_address=client_ip(), details={"base_url": 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():
|
||||
@@ -310,7 +430,7 @@ async def update_db_maintenance():
|
||||
uid = get_current_user_id()
|
||||
await log_audit(
|
||||
"db_maintenance_config", user_id=uid, username=g.user.username,
|
||||
ip_address=request.remote_addr, details={"enabled": enabled, "hour": hour},
|
||||
ip_address=client_ip(), details={"enabled": enabled, "hour": hour},
|
||||
)
|
||||
return jsonify({"status": "ok", "enabled": enabled, "hour": hour})
|
||||
|
||||
@@ -323,7 +443,7 @@ async def run_db_maintenance_now():
|
||||
uid = get_current_user_id()
|
||||
await log_audit(
|
||||
"db_maintenance_run", user_id=uid, username=g.user.username,
|
||||
ip_address=request.remote_addr,
|
||||
ip_address=client_ip(),
|
||||
)
|
||||
summary = await run_maintenance()
|
||||
return jsonify(summary)
|
||||
@@ -389,7 +509,7 @@ async def update_backups():
|
||||
uid = get_current_user_id()
|
||||
await log_audit(
|
||||
"backup_config", user_id=uid, username=g.user.username,
|
||||
ip_address=request.remote_addr,
|
||||
ip_address=client_ip(),
|
||||
details={**config.to_dict(), "secret_changed": bool(
|
||||
data.get("clear_s3_secret") or (isinstance(secret, str) and secret and secret != SECRET_MASK)
|
||||
)},
|
||||
@@ -439,7 +559,7 @@ async def run_backup_now():
|
||||
return jsonify({"error": "A backup is already running."}), 409
|
||||
uid = get_current_user_id()
|
||||
await log_audit("backup_run", user_id=uid, username=g.user.username,
|
||||
ip_address=request.remote_addr, details={})
|
||||
ip_address=client_ip(), details={})
|
||||
return jsonify({"status": "started"}), 202
|
||||
|
||||
|
||||
@@ -463,7 +583,7 @@ async def create_invite():
|
||||
"invitation_created",
|
||||
user_id=uid,
|
||||
username=g.user.username,
|
||||
ip_address=request.remote_addr,
|
||||
ip_address=client_ip(),
|
||||
details={"invited_email": email},
|
||||
)
|
||||
return jsonify({"status": "ok"}), 201
|
||||
@@ -497,7 +617,7 @@ async def delete_invitation(invitation_id: int):
|
||||
"invitation_revoked",
|
||||
user_id=uid,
|
||||
username=g.user.username,
|
||||
ip_address=request.remote_addr,
|
||||
ip_address=client_ip(),
|
||||
details={"invitation_id": invitation_id},
|
||||
)
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
+24
-32
@@ -8,7 +8,8 @@ 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.rate_limit import is_rate_limited
|
||||
from grimoire.proxy import client_ip
|
||||
from grimoire.rate_limit import SHARED_ADDRESS_HINT, is_rate_limited
|
||||
from grimoire.services.auth import (
|
||||
authenticate,
|
||||
change_password,
|
||||
@@ -43,21 +44,12 @@ from grimoire.services.oauth import (
|
||||
auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth")
|
||||
|
||||
|
||||
def _client_ip() -> str:
|
||||
if Config.TRUST_PROXY_HEADERS:
|
||||
for header in ("X-Forwarded-For", "X-Real-IP"):
|
||||
val = request.headers.get(header, "").split(",")[0].strip()
|
||||
if val:
|
||||
return val
|
||||
return request.remote_addr or ""
|
||||
|
||||
|
||||
@auth_bp.route("/register", methods=["POST"])
|
||||
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
|
||||
if await is_rate_limited(f"register:{client_ip()}", max_requests=5, window_seconds=300):
|
||||
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
|
||||
|
||||
@@ -78,7 +70,7 @@ async def register():
|
||||
|
||||
session["user_id"] = user.id
|
||||
session["session_version"] = user.session_version
|
||||
await log_audit("register", user_id=user.id, username=user.username, ip_address=_client_ip())
|
||||
await log_audit("register", user_id=user.id, username=user.username, ip_address=client_ip())
|
||||
return jsonify(user.to_dict()), 201
|
||||
|
||||
|
||||
@@ -86,8 +78,8 @@ async def register():
|
||||
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
|
||||
if await is_rate_limited(f"login:{client_ip()}", max_requests=10, window_seconds=60):
|
||||
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 ""
|
||||
@@ -97,22 +89,22 @@ async def login():
|
||||
|
||||
user = await authenticate(username, password)
|
||||
if not user:
|
||||
await log_audit("login_failed", username=username, ip_address=_client_ip())
|
||||
await log_audit("login_failed", username=username, ip_address=client_ip())
|
||||
# Try to notify the actual user about the failed attempt
|
||||
target_user = await get_user_by_username(username)
|
||||
if target_user:
|
||||
asyncio.create_task(notify_security_event(
|
||||
target_user.id, "login_failed",
|
||||
{"ip_address": _client_ip(), "username": username},
|
||||
{"ip_address": client_ip(), "username": username},
|
||||
))
|
||||
return jsonify({"error": "Invalid username or password"}), 401
|
||||
|
||||
session["user_id"] = user.id
|
||||
session["session_version"] = user.session_version
|
||||
await log_audit("login", user_id=user.id, username=user.username, ip_address=_client_ip())
|
||||
await log_audit("login", user_id=user.id, username=user.username, ip_address=client_ip())
|
||||
asyncio.create_task(notify_security_event(
|
||||
user.id, "login",
|
||||
{"ip_address": _client_ip()},
|
||||
{"ip_address": client_ip()},
|
||||
))
|
||||
return jsonify(user.to_dict())
|
||||
|
||||
@@ -122,10 +114,10 @@ async def logout():
|
||||
uid = session.get("user_id")
|
||||
if uid:
|
||||
user = await get_user_by_id(uid)
|
||||
await log_audit("logout", user_id=uid, username=user.username if user else None, ip_address=_client_ip())
|
||||
await log_audit("logout", user_id=uid, username=user.username if user else None, ip_address=client_ip())
|
||||
asyncio.create_task(notify_security_event(
|
||||
uid, "logout",
|
||||
{"ip_address": _client_ip()},
|
||||
{"ip_address": client_ip()},
|
||||
))
|
||||
session.clear()
|
||||
return jsonify({"status": "ok"})
|
||||
@@ -159,10 +151,10 @@ async def update_password():
|
||||
|
||||
# Keep the current session alive with the new version (other sessions are now invalidated)
|
||||
session["session_version"] = new_version
|
||||
await log_audit("password_change", user_id=uid, username=g.user.username, ip_address=_client_ip())
|
||||
await log_audit("password_change", user_id=uid, username=g.user.username, ip_address=client_ip())
|
||||
asyncio.create_task(notify_security_event(
|
||||
uid, "password_change",
|
||||
{"ip_address": _client_ip()},
|
||||
{"ip_address": client_ip()},
|
||||
))
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
@@ -178,7 +170,7 @@ async def invalidate_sessions_route():
|
||||
uid = get_current_user_id()
|
||||
new_version = await invalidate_other_sessions(uid)
|
||||
session["session_version"] = new_version
|
||||
await log_audit("sessions_invalidated", user_id=uid, username=g.user.username, ip_address=_client_ip())
|
||||
await log_audit("sessions_invalidated", user_id=uid, username=g.user.username, ip_address=client_ip())
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
@@ -208,14 +200,14 @@ async def update_email():
|
||||
return jsonify({"error": "Email already in use by another account"}), 409
|
||||
|
||||
await update_user_email(uid, new_email)
|
||||
await log_audit("email_change", user_id=uid, username=user.username, ip_address=_client_ip())
|
||||
await log_audit("email_change", user_id=uid, username=user.username, ip_address=client_ip())
|
||||
updated = await get_user_by_id(uid)
|
||||
return jsonify(updated.to_dict())
|
||||
|
||||
|
||||
@auth_bp.route("/forgot-password", methods=["POST"])
|
||||
async def forgot_password():
|
||||
if await is_rate_limited(f"forgot:{_client_ip()}", max_requests=5, window_seconds=300):
|
||||
if await is_rate_limited(f"forgot:{client_ip()}", max_requests=5, window_seconds=300):
|
||||
return jsonify({"status": "ok"})
|
||||
data = await request.get_json()
|
||||
email = (data.get("email") or "").strip().lower()
|
||||
@@ -234,7 +226,7 @@ async def forgot_password():
|
||||
"password_reset_requested",
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
ip_address=_client_ip(),
|
||||
ip_address=client_ip(),
|
||||
)
|
||||
|
||||
return jsonify({"status": "ok"})
|
||||
@@ -242,8 +234,8 @@ 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
|
||||
if await is_rate_limited(f"reset:{client_ip()}", max_requests=10, window_seconds=60):
|
||||
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 ""
|
||||
@@ -261,7 +253,7 @@ async def reset_password():
|
||||
if user:
|
||||
await log_audit(
|
||||
"password_reset_completed",
|
||||
user_id=user.id, username=user.username, ip_address=_client_ip(),
|
||||
user_id=user.id, username=user.username, ip_address=client_ip(),
|
||||
)
|
||||
if user.email:
|
||||
asyncio.create_task(send_password_reset_success_email(user.email))
|
||||
@@ -304,7 +296,7 @@ async def register_with_invite():
|
||||
"register_with_invite",
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
ip_address=_client_ip(),
|
||||
ip_address=client_ip(),
|
||||
)
|
||||
return jsonify(user.to_dict()), 201
|
||||
|
||||
@@ -371,5 +363,5 @@ async def oauth_callback():
|
||||
user = await find_or_create_oauth_user(sub, email, preferred_username)
|
||||
session["user_id"] = user.id
|
||||
session["session_version"] = user.session_version
|
||||
await log_audit("oauth_login", user_id=user.id, username=user.username, ip_address=_client_ip())
|
||||
await log_audit("oauth_login", user_id=user.id, username=user.username, ip_address=client_ip())
|
||||
return redirect("/")
|
||||
|
||||
@@ -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():
|
||||
|
||||
+196
-23
@@ -8,19 +8,25 @@ fmcp_<key>` API key (a read-scoped key suffices for this GET).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
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 report_check as report_check_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
|
||||
from grimoire.services import write_scope as write_scope_svc
|
||||
from grimoire.services.access import can_read_project
|
||||
from grimoire.services.embeddings import memoized_query_embeddings
|
||||
from grimoire.services.settings import get_admin_setting, set_setting
|
||||
|
||||
@@ -32,6 +38,33 @@ 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.
|
||||
"""
|
||||
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)
|
||||
|
||||
|
||||
@plugin_bp.after_request
|
||||
async def _flush_deliveries(response):
|
||||
"""Write any rule 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()
|
||||
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()]
|
||||
@@ -90,6 +123,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
|
||||
@@ -133,11 +171,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
|
||||
@@ -178,12 +222,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)
|
||||
|
||||
|
||||
@@ -261,6 +328,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)
|
||||
|
||||
|
||||
@@ -297,15 +373,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 {},
|
||||
@@ -316,13 +401,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,
|
||||
})
|
||||
|
||||
|
||||
@@ -332,7 +424,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
|
||||
@@ -345,8 +440,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(
|
||||
@@ -508,6 +608,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)
|
||||
|
||||
|
||||
@@ -541,9 +654,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
|
||||
@@ -590,8 +705,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)
|
||||
@@ -626,6 +741,64 @@ async def claim_session():
|
||||
return jsonify({"claim": claim})
|
||||
|
||||
|
||||
@plugin_bp.get("/write-scope")
|
||||
@login_required
|
||||
async def write_scope():
|
||||
"""May this session do this act? Asked by `grimoire_project_fence.sh`
|
||||
before a file edit, a git command or a Grimoire write.
|
||||
|
||||
A session belongs to the project its starting directory resolves to
|
||||
(`repo` / `project_id`, as every plugin endpoint reads them), or when
|
||||
that resolves to none, to `fallback_project_id`: the first project the
|
||||
session entered. The act is
|
||||
either a directory (`target_repo` / `target_project_id`) or an MCP call
|
||||
(`tool`, with `input` as a JSON object of the call's short arguments: the
|
||||
ids, kind and status that say where it writes). `act` words the act for the
|
||||
reason, e.g. "git push in".
|
||||
|
||||
Returns `{allowed, session_project, targets, issue, reason}` from
|
||||
services/write_scope.check_act. A GET, so a read-scoped key still fences
|
||||
file edits and git commands.
|
||||
"""
|
||||
session_project, _repo, _unbound = await _project_scope()
|
||||
if not session_project:
|
||||
# A session that started outside any project belongs to the first one
|
||||
# it entered; the hook remembers it.
|
||||
try:
|
||||
session_project = int(request.args.get("fallback_project_id") or 0)
|
||||
except ValueError:
|
||||
session_project = 0
|
||||
if session_project and not await can_read_project(g.user.id, session_project):
|
||||
session_project = 0
|
||||
tool = (request.args.get("tool") or "").strip()
|
||||
if tool.startswith("mcp__"):
|
||||
tool = tool.rsplit("__", 1)[-1]
|
||||
args: dict = {}
|
||||
if tool:
|
||||
try:
|
||||
parsed = json.loads(request.args.get("input") or "{}")
|
||||
except ValueError:
|
||||
return jsonify({"error": "input must be a JSON object"}), 400
|
||||
if not isinstance(parsed, dict):
|
||||
return jsonify({"error": "input must be a JSON object"}), 400
|
||||
args = parsed
|
||||
target_project = 0
|
||||
if not tool:
|
||||
try:
|
||||
target_project = int(request.args.get("target_project_id") or 0)
|
||||
except ValueError:
|
||||
target_project = 0
|
||||
target_repo = (request.args.get("target_repo") or "").strip()
|
||||
if not target_project and target_repo:
|
||||
target_project = await repo_bindings_svc.resolve_project(g.user.id, target_repo) or 0
|
||||
result = await write_scope_svc.check_act(
|
||||
g.user.id, session_project, tool=tool, args=args,
|
||||
target_project=target_project, act=(request.args.get("act") or "")[:80],
|
||||
)
|
||||
result["session_project"] = session_project or None
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@plugin_bp.get("/release-session")
|
||||
@login_required
|
||||
async def release_session():
|
||||
|
||||
@@ -57,6 +57,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):
|
||||
|
||||
@@ -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))
|
||||
|
||||
+367
-42
@@ -23,6 +23,7 @@ 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_moment_judgment import RuleMomentJudgment
|
||||
@@ -111,7 +112,11 @@ logger = logging.getLogger(__name__)
|
||||
# v26 user_profiles: what each user wrote on their Profile page.
|
||||
# v27 drops user_profiles with the Profile page. Older archives carrying the
|
||||
# section still restore — the key is simply not read.
|
||||
BACKUP_VERSION = 27
|
||||
# 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.
|
||||
# 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.
|
||||
BACKUP_VERSION = 29
|
||||
|
||||
# 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
|
||||
@@ -156,6 +161,7 @@ _BACKED_UP = [
|
||||
"moment_mappings",
|
||||
"rule_moments",
|
||||
"rule_moment_judgments",
|
||||
"rule_triggers",
|
||||
# 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
|
||||
@@ -181,6 +187,10 @@ _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",
|
||||
# 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.
|
||||
@@ -195,6 +205,9 @@ _NOT_INCLUDED = [
|
||||
# rebuilt from the repo archive by every coverage sync, and carries no
|
||||
# judgment — the first refresh after a restore recreates it exactly.
|
||||
"code_shape_consumers",
|
||||
# Not a section: the full backup carries the one value in its header as
|
||||
# `instance_id`, and a restore decides from it rather than copying a row.
|
||||
"instance_identity",
|
||||
]
|
||||
|
||||
|
||||
@@ -793,6 +806,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."""
|
||||
@@ -954,6 +976,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,
|
||||
@@ -979,7 +1002,10 @@ async def export_full_backup() -> dict:
|
||||
runs, which only works when unchanged rows serialise to the same bytes in
|
||||
the same place.
|
||||
"""
|
||||
from grimoire.services.instance import get_instance_id
|
||||
|
||||
async with async_session() as session:
|
||||
instance_id = await get_instance_id(session)
|
||||
users =(await session.execute(select(User).order_by(User.id))).scalars().all()
|
||||
projects = (await session.execute(select(Project).order_by(Project.id))).scalars().all()
|
||||
milestones = (await session.execute(select(Milestone).order_by(Milestone.id))).scalars().all()
|
||||
@@ -1007,6 +1033,12 @@ 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()
|
||||
@@ -1077,6 +1109,7 @@ async def export_full_backup() -> dict:
|
||||
return {
|
||||
"version": BACKUP_VERSION,
|
||||
"scope": "full",
|
||||
"instance_id": instance_id,
|
||||
"exported_at": datetime.now(timezone.utc).isoformat(),
|
||||
"_security_notice": (
|
||||
"This backup contains hashed passwords. "
|
||||
@@ -1098,6 +1131,7 @@ 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_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
@@ -1259,6 +1293,11 @@ 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 []
|
||||
@@ -1385,6 +1424,7 @@ 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_relations": _rule_relation_rows(rule_relations),
|
||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
||||
@@ -1708,6 +1748,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
|
||||
@@ -2319,6 +2368,41 @@ async def _restore_v1(data: dict) -> dict:
|
||||
return stats
|
||||
|
||||
|
||||
# Columns the restore writes in a LATER pass, once the rows they point at
|
||||
# exist: a note's parent and origin, a project's design system and inception.
|
||||
# A rollback clears them before overwriting a row in place, so a pointer the
|
||||
# backup does not have cannot survive from the current row.
|
||||
_SECOND_PASS_COLUMNS: dict[type, tuple[str, ...]] = {
|
||||
Note: ("parent_id", "arose_from_id"),
|
||||
Project: ("design_system_id", "inception"),
|
||||
}
|
||||
|
||||
|
||||
async def _place(session, obj, source_id: int | None, keep_ids: bool) -> int:
|
||||
"""Write one identity-table row and return the id it now has.
|
||||
|
||||
Copy-in: insert, and the database picks the id. Rollback: the row takes
|
||||
`source_id`, the id it had in the backup, and is merged, so a row with
|
||||
that id is overwritten in place (keeping what references it from outside
|
||||
the backup: API keys, shares, forge connections) and a missing one is
|
||||
inserted. A rolled-back row is live: out of the trash, and with no
|
||||
second-pass pointer left from the current row.
|
||||
"""
|
||||
if not keep_ids or source_id is None:
|
||||
session.add(obj)
|
||||
await session.flush()
|
||||
return obj.id
|
||||
obj.id = source_id
|
||||
if hasattr(obj, "deleted_at"):
|
||||
obj.deleted_at = None
|
||||
obj.deleted_batch_id = None
|
||||
for column in _SECOND_PASS_COLUMNS.get(type(obj), ()):
|
||||
setattr(obj, column, None)
|
||||
merged = await session.merge(obj)
|
||||
await session.flush()
|
||||
return merged.id
|
||||
|
||||
|
||||
async def _restore_v2(data: dict) -> dict:
|
||||
"""Restore v2/v3 backup with full FK re-mapping.
|
||||
|
||||
@@ -2333,6 +2417,25 @@ async def _restore_v2(data: dict) -> dict:
|
||||
and the id-map bookkeeping, which is the part a split would only make
|
||||
harder to read.
|
||||
"""
|
||||
async with async_session() as session:
|
||||
stats = await _load_v2(session, data, _Maps(), keep_ids=False)
|
||||
await session.commit()
|
||||
|
||||
logger.info("Restored v2/v3 backup: %s", stats)
|
||||
return stats
|
||||
|
||||
|
||||
async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dict[str, int]:
|
||||
"""Write a v2+ payload's rows into `session`, parents first, through the
|
||||
`_build_*` helpers and `maps`. Commits nothing; the caller owns the
|
||||
transaction.
|
||||
|
||||
`keep_ids=False` is the copy-in restore: every row gets a new id and
|
||||
`maps` records old → new. `keep_ids=True` is the rollback
|
||||
(`replace_from_backup`): the identity tables keep the id the row had in
|
||||
the backup, so a row this store already holds is overwritten in place, and
|
||||
`maps` maps each id to itself.
|
||||
"""
|
||||
stats: dict[str, int] = {
|
||||
"users": 0, "projects": 0, "milestones": 0, "notes": 0,
|
||||
"task_logs": 0, "note_drafts": 0, "note_versions": 0,
|
||||
@@ -2344,6 +2447,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
"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_relations": 0, "rule_versions": 0,
|
||||
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
|
||||
"lesson_no_rule": 0, "moment_mappings": 0,
|
||||
@@ -2352,15 +2456,11 @@ async def _restore_v2(data: dict) -> dict:
|
||||
"family_adoptions": 0, "family_decisions": 0,
|
||||
}
|
||||
|
||||
async with async_session() as session:
|
||||
maps = _Maps()
|
||||
|
||||
# 1. Users
|
||||
for u_data in data.get("users", []):
|
||||
user = _build_user(u_data, maps)
|
||||
session.add(user)
|
||||
await session.flush()
|
||||
maps.users[u_data["id"]] = user.id
|
||||
maps.users[u_data["id"]] = await _place(session, user, u_data["id"], keep_ids)
|
||||
stats["users"] += 1
|
||||
|
||||
# 2. Projects
|
||||
@@ -2368,9 +2468,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
proj = _build_project(p_data, maps)
|
||||
if proj is None:
|
||||
continue
|
||||
session.add(proj)
|
||||
await session.flush()
|
||||
maps.projects[p_data["id"]] = proj.id
|
||||
maps.projects[p_data["id"]] = await _place(session, proj, p_data["id"], keep_ids)
|
||||
stats["projects"] += 1
|
||||
|
||||
# 3. Milestones
|
||||
@@ -2378,9 +2476,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
ms = _build_milestone(m_data, maps)
|
||||
if ms is None:
|
||||
continue
|
||||
session.add(ms)
|
||||
await session.flush()
|
||||
maps.milestones[m_data["id"]] = ms.id
|
||||
maps.milestones[m_data["id"]] = await _place(session, ms, m_data["id"], keep_ids)
|
||||
stats["milestones"] += 1
|
||||
|
||||
# 4a. Notes — first pass (no parent_id yet)
|
||||
@@ -2390,13 +2486,12 @@ async def _restore_v2(data: dict) -> dict:
|
||||
note = _build_note(n_data, maps)
|
||||
if note is None:
|
||||
continue
|
||||
session.add(note)
|
||||
await session.flush()
|
||||
maps.notes[n_data["id"]] = note.id
|
||||
note_id = await _place(session, note, n_data["id"], keep_ids)
|
||||
maps.notes[n_data["id"]] = note_id
|
||||
if n_data.get("parent_id"):
|
||||
notes_with_parents.append((note.id, n_data["parent_id"]))
|
||||
notes_with_parents.append((note_id, n_data["parent_id"]))
|
||||
if n_data.get("arose_from_id"):
|
||||
notes_with_origins.append((note.id, n_data["arose_from_id"]))
|
||||
notes_with_origins.append((note_id, n_data["arose_from_id"]))
|
||||
stats["notes"] += 1
|
||||
|
||||
# 4b. Patch the note->note edges. Deferred for the same reason
|
||||
@@ -2473,9 +2568,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
rb = _build_rulebook(rb_data, maps)
|
||||
if rb is None:
|
||||
continue
|
||||
session.add(rb)
|
||||
await session.flush()
|
||||
maps.rulebooks[rb_data["id"]] = rb.id
|
||||
maps.rulebooks[rb_data["id"]] = await _place(session, rb, rb_data["id"], keep_ids)
|
||||
stats["rulebooks"] += 1
|
||||
|
||||
# 10. Topics (v3)
|
||||
@@ -2483,9 +2576,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
topic = _build_topic(t_data, maps)
|
||||
if topic is None:
|
||||
continue
|
||||
session.add(topic)
|
||||
await session.flush()
|
||||
maps.topics[t_data["id"]] = topic.id
|
||||
maps.topics[t_data["id"]] = await _place(session, topic, t_data["id"], keep_ids)
|
||||
stats["rulebook_topics"] += 1
|
||||
|
||||
# 11. Rules (v3) — topic-rule (topic_id) XOR project-rule (project_id)
|
||||
@@ -2493,9 +2584,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
rule = _build_rule(r_data, maps)
|
||||
if rule is None:
|
||||
continue # orphaned — its parent didn't restore
|
||||
session.add(rule)
|
||||
await session.flush()
|
||||
maps.rules[r_data["id"]] = rule.id
|
||||
maps.rules[r_data["id"]] = await _place(session, rule, r_data["id"], keep_ids)
|
||||
stats["rules"] += 1
|
||||
|
||||
# 12-14. Rulebook subscriptions, rule and topic suppressions (v3-v14)
|
||||
@@ -2556,6 +2645,18 @@ async def _restore_v2(data: dict) -> dict:
|
||||
))
|
||||
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", []):
|
||||
@@ -2643,10 +2744,10 @@ async def _restore_v2(data: dict) -> dict:
|
||||
decision = _build_family_decision(fd, maps)
|
||||
if decision is None:
|
||||
continue
|
||||
session.add(decision)
|
||||
await session.flush()
|
||||
if fd.get("id"):
|
||||
maps.decisions[int(fd["id"])] = decision.id
|
||||
source_id = int(fd["id"]) if fd.get("id") else None
|
||||
decision_id = await _place(session, decision, source_id, keep_ids)
|
||||
if source_id:
|
||||
maps.decisions[source_id] = decision_id
|
||||
stats["family_decisions"] += 1
|
||||
|
||||
# A rule's edit history. Must come after the rules themselves — the
|
||||
@@ -2664,9 +2765,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
system = _build_system(sy_data, maps)
|
||||
if system is None:
|
||||
continue
|
||||
session.add(system)
|
||||
await session.flush()
|
||||
maps.systems[sy_data["id"]] = system.id
|
||||
maps.systems[sy_data["id"]] = await _place(session, system, sy_data["id"], keep_ids)
|
||||
stats["systems"] += 1
|
||||
|
||||
# 16. Record<->system links
|
||||
@@ -2691,9 +2790,7 @@ async def _restore_v2(data: dict) -> dict:
|
||||
design = _build_design_system(ds_data, maps)
|
||||
if design is None:
|
||||
continue
|
||||
session.add(design)
|
||||
await session.flush()
|
||||
maps.design_systems[ds_data["id"]] = design.id
|
||||
maps.design_systems[ds_data["id"]] = await _place(session, design, ds_data["id"], keep_ids)
|
||||
stats["design_systems"] += 1
|
||||
|
||||
# 18. Design tokens
|
||||
@@ -2742,10 +2839,10 @@ async def _restore_v2(data: dict) -> dict:
|
||||
shape = _build_code_shape(cs_data, maps)
|
||||
if shape is None:
|
||||
continue
|
||||
session.add(shape)
|
||||
await session.flush()
|
||||
if cs_data.get("id"):
|
||||
maps.shapes[int(cs_data["id"])] = shape.id
|
||||
source_id = int(cs_data["id"]) if cs_data.get("id") else None
|
||||
shape_id = await _place(session, shape, source_id, keep_ids)
|
||||
if source_id:
|
||||
maps.shapes[source_id] = shape_id
|
||||
stats["code_shapes"] += 1
|
||||
|
||||
# v8: the ledger's history rides its shapes.
|
||||
@@ -2797,7 +2894,235 @@ async def _restore_v2(data: dict) -> dict:
|
||||
choices["design_system_id"] = maps.design_systems.get(ds) if ds else None
|
||||
proj.inception = {**inception, "choices": choices}
|
||||
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
# ── Rollback: put this store back to a full backup ─────────────────────────
|
||||
|
||||
|
||||
class RestoreRefused(Exception):
|
||||
"""Why a rollback will not run, in words an operator can act on."""
|
||||
|
||||
|
||||
# Tables whose rows are pointed at BY ID, from inside the backup and from
|
||||
# tables it does not carry (API keys, shares, forge connections, embeddings).
|
||||
# A rollback keeps each row the backup holds under the same id, overwriting it
|
||||
# in place, and removes the rest. Each is written through `_place`.
|
||||
_IDENTITY_TABLES = (
|
||||
"users", "projects", "milestones", "notes", "rulebooks", "rulebook_topics",
|
||||
"rules", "systems", "design_systems", "code_shapes", "family_decisions",
|
||||
)
|
||||
# Global vocabularies matched on slug, seeded by migrations: a rollback adds
|
||||
# what the backup names and removes nothing.
|
||||
_CATALOG_TABLES = ("canonical_systems", "platforms")
|
||||
# Rebuilt from the records. A rolled-back record's text may be older than its
|
||||
# vectors, which would then look current while encoding text the record no
|
||||
# longer holds, so a rollback clears them and the backfills rebuild them.
|
||||
_DERIVED_TABLES = (
|
||||
"note_embeddings", "rule_embeddings", "milestone_embeddings",
|
||||
"system_embeddings", "code_shape_consumers",
|
||||
)
|
||||
|
||||
|
||||
async def _count(session, model) -> int:
|
||||
from sqlalchemy import func
|
||||
return (await session.execute(select(func.count()).select_from(model))).scalar_one()
|
||||
|
||||
|
||||
async def _is_fresh(session) -> bool:
|
||||
"""No records yet, and at most the one account that is doing the
|
||||
restore. Trashed records count: they are still this instance's."""
|
||||
if await _count(session, User) > 1:
|
||||
return False
|
||||
for model in (Project, Note, Rule, Rulebook):
|
||||
if await _count(session, model):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _ids_in(data: dict, table: str) -> list[int]:
|
||||
return sorted({int(row["id"]) for row in data.get(table) or [] if row.get("id")})
|
||||
|
||||
|
||||
async def _clear_for_rollback(session, data: dict) -> None:
|
||||
"""Remove what the backup does not hold, before its rows are written.
|
||||
|
||||
Removing first, not after, is what lets a name the backup gives one id
|
||||
(a username, a slug) be free when it is written: the row holding it now
|
||||
under another id is gone by then. Everything foreign-keyed to a removed
|
||||
row with ON DELETE CASCADE goes with it, which is only ever a row the
|
||||
backup does not hold either, or one this rollback rewrites.
|
||||
"""
|
||||
from sqlalchemy import BigInteger, any_, bindparam, not_
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
|
||||
from grimoire.models import Base
|
||||
|
||||
tables = Base.metadata.tables
|
||||
for name in _DERIVED_TABLES:
|
||||
await session.execute(tables[name].delete())
|
||||
|
||||
# Every other backed-up table is replaced whole: nothing outside the
|
||||
# backup points at its rows, and their ids carry no meaning of their own.
|
||||
keep_whole = set(_IDENTITY_TABLES) | set(_CATALOG_TABLES) | {"settings"}
|
||||
for table in reversed(Base.metadata.sorted_tables):
|
||||
if table.name in _BACKED_UP and table.name not in keep_whole:
|
||||
await session.execute(table.delete())
|
||||
# Settings the backup never carries (the backup secret, the run history)
|
||||
# are this instance's own and stay.
|
||||
settings_t = tables["settings"]
|
||||
await session.execute(
|
||||
settings_t.delete().where(settings_t.c.key.notin_(sorted(_SETTINGS_NOT_EXPORTED)))
|
||||
)
|
||||
|
||||
for name in reversed(_IDENTITY_TABLES):
|
||||
table = tables[name]
|
||||
keep = _ids_in(data, name)
|
||||
doomed = (
|
||||
not_(table.c.id == any_(bindparam(f"keep_{name}", keep, type_=ARRAY(BigInteger))))
|
||||
if keep else table.c.id.isnot(None)
|
||||
)
|
||||
# A reference from outside the backup with no ON DELETE (a share's
|
||||
# granted_by) would refuse the delete: those rows go first.
|
||||
for other in Base.metadata.sorted_tables:
|
||||
if other.name in _BACKED_UP:
|
||||
continue
|
||||
for fk in other.foreign_keys:
|
||||
if fk.column.table is table and not fk.ondelete:
|
||||
await session.execute(
|
||||
other.delete().where(fk.parent.in_(select(table.c.id).where(doomed)))
|
||||
)
|
||||
await session.execute(table.delete().where(doomed))
|
||||
|
||||
|
||||
async def _reset_sequences(session) -> None:
|
||||
"""Point every id sequence past the highest id now in its table, so the
|
||||
next insert does not collide with a restored row."""
|
||||
from sqlalchemy import text
|
||||
|
||||
from grimoire.models import Base
|
||||
|
||||
for name in _BACKED_UP:
|
||||
table = Base.metadata.tables[name]
|
||||
if "id" not in table.c:
|
||||
continue
|
||||
await session.execute(text(
|
||||
f"SELECT setval(pg_get_serial_sequence('{name}', 'id'), "
|
||||
f"COALESCE((SELECT MAX(id) FROM {name}), 0) + 1, false) "
|
||||
f"WHERE pg_get_serial_sequence('{name}', 'id') IS NOT NULL"
|
||||
))
|
||||
|
||||
|
||||
def _refuse_unless_full(data: dict) -> None:
|
||||
if (data.get("version") or 1) < 2 or data.get("scope", "full") != "full":
|
||||
raise RestoreRefused(
|
||||
"This file isn't a full backup of the instance (it is a single user's "
|
||||
"export, or a very old format), so it can't put the whole instance back."
|
||||
)
|
||||
|
||||
|
||||
async def _replace_mode(session, data: dict) -> str:
|
||||
""""fresh" or "rollback", or RestoreRefused saying why neither applies."""
|
||||
from grimoire.services.instance import get_instance_id
|
||||
|
||||
_refuse_unless_full(data)
|
||||
if await _is_fresh(session):
|
||||
return "fresh"
|
||||
backup_instance = data.get("instance_id")
|
||||
if not backup_instance:
|
||||
raise RestoreRefused(
|
||||
"This backup was made before backups recorded which instance they "
|
||||
"came from, so it can only be restored into a new, empty instance."
|
||||
)
|
||||
if backup_instance != await get_instance_id(session):
|
||||
raise RestoreRefused(
|
||||
"This backup comes from a different Grimoire instance. Rolling back "
|
||||
"matches records by id, and its ids belong to that instance, so it "
|
||||
"can only be restored into a new, empty instance."
|
||||
)
|
||||
return "rollback"
|
||||
|
||||
|
||||
async def check_replace(data: dict) -> str:
|
||||
"""Whether `data` can replace this store, without changing anything:
|
||||
"fresh" or "rollback", or RestoreRefused with the reason."""
|
||||
async with async_session() as session:
|
||||
return await _replace_mode(session, data)
|
||||
|
||||
|
||||
# What the restore preview counts, now and in the backup: the kinds a person
|
||||
# recognises, not every table.
|
||||
_PREVIEW_KINDS = (
|
||||
("users", "Accounts"), ("projects", "Projects"), ("milestones", "Plans"),
|
||||
("notes", "Notes and tasks"), ("rules", "Rules and preferences"),
|
||||
)
|
||||
|
||||
|
||||
async def replace_preview(data: dict) -> dict:
|
||||
"""What replacing this store with `data` would do, changing nothing: the
|
||||
mode, when the backup was taken, and per kind how many there are now and
|
||||
how many there will be. RestoreRefused when it can't be applied here."""
|
||||
from grimoire.models import Base
|
||||
|
||||
async with async_session() as session:
|
||||
mode = await _replace_mode(session, data)
|
||||
counts = []
|
||||
for table, label in _PREVIEW_KINDS:
|
||||
now = await _count(session, Base.metadata.tables[table])
|
||||
counts.append({"kind": label, "now": now, "after": len(data.get(table) or [])})
|
||||
return {"mode": mode, "exported_at": data.get("exported_at"), "counts": counts}
|
||||
|
||||
|
||||
async def replace_from_backup(data: dict) -> dict:
|
||||
"""Put this store back to a full backup, in one transaction.
|
||||
|
||||
On a live instance the backup must come from this instance (the same
|
||||
instance id): every row then keeps the id it had in the backup, a row the
|
||||
backup holds is overwritten in place, and one it does not hold is
|
||||
removed. Records edited since go back, deleted ones return, ones made
|
||||
since are gone. A fresh instance (no records, at most the restoring
|
||||
account) takes any full backup the same way and adopts its instance id.
|
||||
|
||||
What the backup does not carry stays where its owner survives: API keys,
|
||||
forge connections, shares, logs, the backup destination's secret. Every
|
||||
session is signed out, because each account is now the backup's. Search
|
||||
vectors are cleared, so `reindex_after_restore` has to run afterwards.
|
||||
|
||||
Raises RestoreRefused, with nothing changed, when the backup cannot be
|
||||
applied here. Any failure part-way rolls the transaction back.
|
||||
"""
|
||||
from sqlalchemy import update
|
||||
|
||||
from grimoire.services.instance import adopt_instance_id
|
||||
|
||||
async with async_session() as session:
|
||||
mode = await _replace_mode(session, data)
|
||||
await _clear_for_rollback(session, data)
|
||||
stats = await _load_v2(session, data, _Maps(), keep_ids=True)
|
||||
await _reset_sequences(session)
|
||||
await session.execute(update(User).values(session_version=User.session_version + 1))
|
||||
if mode == "fresh" and data.get("instance_id"):
|
||||
await adopt_instance_id(session, data["instance_id"])
|
||||
await session.commit()
|
||||
|
||||
logger.info("Restored v2/v3 backup: %s", stats)
|
||||
return stats
|
||||
logger.info("Replaced the store from a backup (%s): %s", mode, stats)
|
||||
return {"mode": mode, "restored": stats, "exported_at": data.get("exported_at")}
|
||||
|
||||
|
||||
async def reindex_after_restore() -> None:
|
||||
"""Rebuild the search vectors a rollback cleared. Long-running; start it
|
||||
in the background (the startup backfill does the same after a restart)."""
|
||||
from grimoire.services.embeddings import (
|
||||
backfill_milestone_embeddings, backfill_note_embeddings,
|
||||
backfill_rule_embeddings, backfill_system_embeddings,
|
||||
)
|
||||
|
||||
for backfill in (
|
||||
backfill_note_embeddings, backfill_rule_embeddings,
|
||||
backfill_milestone_embeddings, backfill_system_embeddings,
|
||||
):
|
||||
try:
|
||||
await backfill()
|
||||
except Exception:
|
||||
logger.exception("reindex after restore: %s failed", backfill.__name__)
|
||||
|
||||
@@ -4,8 +4,9 @@ Two kinds of destination, both instance-wide and set by an admin:
|
||||
|
||||
- **folder**: a directory inside the container, usually a mounted share. A
|
||||
backup service that watches the share (or a person) takes it from there.
|
||||
- **s3**: any S3-compatible bucket, addressed by path. Grimoire only puts and
|
||||
lists, so an append-only key is enough.
|
||||
- **s3**: any S3-compatible bucket, addressed by path. Grimoire puts and
|
||||
lists, and reads one back for a restore, so a key that can add and read
|
||||
objects is enough; it never needs to delete.
|
||||
|
||||
Either way Grimoire ADDS one dated file per run and never removes one: keeping
|
||||
and thinning the history is the destination's job (services/backup_file.py
|
||||
@@ -28,7 +29,7 @@ from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from grimoire.services import backup_file
|
||||
from grimoire.services.backup_s3 import S3Error, S3Target, list_objects, put_file
|
||||
from grimoire.services.backup_s3 import S3Error, S3Target, get_file, list_objects, put_file
|
||||
from grimoire.services.secrets import seal, unseal
|
||||
from grimoire.services.settings import get_admin_setting, set_admin_setting
|
||||
|
||||
@@ -260,3 +261,62 @@ async def check_destination(
|
||||
|
||||
def _count_backups(folder: Path) -> int:
|
||||
return sum(1 for name in os.listdir(folder) if backup_file.is_backup_name(name))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StoredBackup:
|
||||
name: str
|
||||
size_bytes: int
|
||||
|
||||
|
||||
def _taken_order(name: str) -> str:
|
||||
# The timestamp after the prefix, so grimoire- and scribe- names interleave
|
||||
# by when they were taken.
|
||||
return name.split("-", 1)[-1]
|
||||
|
||||
|
||||
async def list_backups(config: BackupConfig, secret: str | None, limit: int = 50) -> list[StoredBackup]:
|
||||
"""The backups at the destination, newest first."""
|
||||
if config.destination == "folder":
|
||||
folder = Path(config.folder_path)
|
||||
if not folder.is_dir():
|
||||
raise DestinationError(f"{folder} isn't there, or isn't a folder.")
|
||||
|
||||
def scan() -> list[StoredBackup]:
|
||||
return [
|
||||
StoredBackup(entry.name, entry.stat().st_size)
|
||||
for entry in os.scandir(folder)
|
||||
if entry.is_file() and backup_file.is_backup_name(entry.name)
|
||||
]
|
||||
found = await asyncio.to_thread(scan)
|
||||
else:
|
||||
problems = config.problems(has_secret=bool(secret))
|
||||
if problems:
|
||||
raise DestinationError(" ".join(problems))
|
||||
try:
|
||||
objects = await list_objects(s3_target(config, secret or ""))
|
||||
except S3Error as exc:
|
||||
raise DestinationError(str(exc)) from None
|
||||
found = [StoredBackup(o.key, o.size) for o in objects if backup_file.is_backup_name(o.key)]
|
||||
return sorted(found, key=lambda b: _taken_order(b.name), reverse=True)[:limit]
|
||||
|
||||
|
||||
async def open_backup(config: BackupConfig, secret: str | None, name: str, staging: Path) -> Path:
|
||||
"""A local path to the backup `name` at the destination: the file itself
|
||||
in a folder, or a download into `staging` from a bucket. Only a name the
|
||||
scheduled backup writes is accepted, so the request can't reach any other
|
||||
file or object."""
|
||||
if Path(name).name != name or not backup_file.is_backup_name(name):
|
||||
raise DestinationError(f"{name!r} isn't the name of a Grimoire backup.")
|
||||
if config.destination == "folder":
|
||||
path = Path(config.folder_path) / name
|
||||
if not path.is_file():
|
||||
raise DestinationError(f"{name} isn't in {config.folder_path}.")
|
||||
return path
|
||||
target = s3_target(config, secret or "")
|
||||
path = staging / name
|
||||
try:
|
||||
await get_file(target, name, path)
|
||||
except S3Error as exc:
|
||||
raise DestinationError(str(exc)) from None
|
||||
return path
|
||||
|
||||
@@ -24,11 +24,14 @@ import os
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
from grimoire.services.backup_destination import (
|
||||
DestinationError, deliver, load_config, load_secret,
|
||||
)
|
||||
from grimoire.services.backup_file import write_archive
|
||||
from grimoire.services.scheduler import ScheduledJob
|
||||
from grimoire.services.settings import get_admin_setting, set_admin_setting
|
||||
|
||||
@@ -45,6 +48,9 @@ STALE_AFTER = timedelta(hours=26)
|
||||
# has none, and a run that never returns holds the lock — every later backup
|
||||
# would be skipped as "already running", silently, forever.
|
||||
RUN_DEADLINE = timedelta(minutes=60)
|
||||
# Under DATA_DIR: where a rollback keeps the backup of what it replaced when
|
||||
# no backup destination takes it.
|
||||
PRE_RESTORE_DIR = "pre-restore"
|
||||
|
||||
_LOCK = asyncio.Lock()
|
||||
_TASKS: set[asyncio.Task] = set()
|
||||
@@ -155,6 +161,66 @@ async def _export_and_deliver(config, secret, started):
|
||||
)
|
||||
|
||||
|
||||
async def save_state_before_restore() -> dict:
|
||||
"""Back up the store as it is now, before a rollback replaces it, and say
|
||||
where the file went: the backup destination when backups are on and it
|
||||
takes the file, otherwise DATA_DIR/pre-restore. Raises when neither takes
|
||||
it, so a rollback never runs without a way back."""
|
||||
from grimoire.config import Config
|
||||
from grimoire.services.backup import export_full_backup
|
||||
|
||||
at = datetime.now(timezone.utc)
|
||||
app_version = os.environ.get("APP_VERSION", "dev")
|
||||
payload = await export_full_backup()
|
||||
note = None
|
||||
config = await load_config()
|
||||
if config.enabled:
|
||||
secret, _ = await load_secret()
|
||||
try:
|
||||
delivered = await asyncio.wait_for(
|
||||
deliver(payload, config, secret, at, app_version=app_version),
|
||||
RUN_DEADLINE.total_seconds(),
|
||||
)
|
||||
return {"file": delivered.name, "size_bytes": delivered.size_bytes,
|
||||
"where": delivered.where}
|
||||
except (DestinationError, TimeoutError, asyncio.TimeoutError) as exc:
|
||||
note = (f"The backup destination didn't take it ({exc or 'it timed out'}), "
|
||||
"so it was kept on the instance instead.")
|
||||
folder = Path(Config.DATA_DIR) / PRE_RESTORE_DIR
|
||||
path = await asyncio.to_thread(write_archive, payload, folder, at, app_version=app_version)
|
||||
saved = {"file": path.name, "size_bytes": path.stat().st_size, "where": str(folder)}
|
||||
if note:
|
||||
saved["note"] = note
|
||||
return saved
|
||||
|
||||
|
||||
async def rollback_to_backup(data: dict) -> dict:
|
||||
"""Roll the store back to a full backup, after backing up what it
|
||||
replaces. Refuses (RestoreRefused) before writing anything when the backup
|
||||
can't be applied here, and raises BackupBusy while a backup is running:
|
||||
a backup taken during a rollback would mix the two states."""
|
||||
from grimoire.services.backup import check_replace, replace_from_backup
|
||||
|
||||
await check_replace(data)
|
||||
if _LOCK.locked():
|
||||
raise BackupBusy()
|
||||
async with _LOCK:
|
||||
safety = await save_state_before_restore()
|
||||
result = await replace_from_backup(data)
|
||||
result["safety_backup"] = safety
|
||||
logger.info("rollback: the state it replaced is in %s/%s", safety["where"], safety["file"])
|
||||
return result
|
||||
|
||||
|
||||
def start_reindex_after_restore() -> None:
|
||||
"""Rebuild the search vectors a rollback cleared, in the background."""
|
||||
from grimoire.services.backup import reindex_after_restore
|
||||
|
||||
task = asyncio.get_running_loop().create_task(reindex_after_restore())
|
||||
_TASKS.add(task)
|
||||
task.add_done_callback(_TASKS.discard)
|
||||
|
||||
|
||||
def start_backup_now() -> None:
|
||||
"""Start a manual backup in the background (the request returns at once;
|
||||
the page reads progress from `is_running` and the run list). Raises
|
||||
|
||||
@@ -4,9 +4,10 @@ path-style addressing (endpoint/bucket/key), and the two calls a backup needs.
|
||||
The signing is checked against AWS's published SigV4 examples in
|
||||
tests/test_services_backup_s3.py.
|
||||
|
||||
Grimoire puts and lists; it never deletes. The bucket keeps the history and
|
||||
thins it on its own policy, so a key that may only add objects is enough —
|
||||
and is the safer key to hand a service, because a stolen one cannot wipe the
|
||||
Grimoire puts and lists, and reads a backup back when an admin restores from
|
||||
the bucket; it never deletes. The bucket keeps the history and thins it on
|
||||
its own policy, so a key that may only add and read objects is enough — and
|
||||
is the safer key to hand a service, because a stolen one cannot wipe the
|
||||
history it writes into.
|
||||
|
||||
Written by hand rather than with boto3: two calls don't justify a large
|
||||
@@ -171,6 +172,28 @@ async def put_file(target: S3Target, key: str, path: Path, *,
|
||||
raise S3Error(f"Upload of {key} refused: {_says(response)}")
|
||||
|
||||
|
||||
async def get_file(target: S3Target, key: str, path: Path, *,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
now: datetime | None = None) -> None:
|
||||
"""Download one object to `path`, streamed to disk."""
|
||||
url = target.url(key)
|
||||
headers = sign("GET", url, {}, EMPTY_SHA256, target.access_key, target.secret_key,
|
||||
target.region, now or datetime.now(timezone.utc))
|
||||
try:
|
||||
async with httpx.AsyncClient(verify=target.verify_tls,
|
||||
timeout=UPLOAD_TIMEOUT_SECONDS,
|
||||
transport=transport) as client:
|
||||
async with client.stream("GET", url, headers=headers) as response:
|
||||
if response.status_code != 200:
|
||||
await response.aread()
|
||||
raise S3Error(f"Reading {key} refused: {_says(response)}")
|
||||
with open(path, "wb") as f:
|
||||
async for chunk in response.aiter_bytes(CHUNK):
|
||||
f.write(chunk)
|
||||
except httpx.HTTPError as exc:
|
||||
raise _reach_error(target, exc) from None
|
||||
|
||||
|
||||
async def list_objects(target: S3Target, prefix: str = "", limit: int = 1000, *,
|
||||
transport: httpx.AsyncBaseTransport | None = None,
|
||||
now: datetime | None = None) -> list[StoredObject]:
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,153 @@
|
||||
"""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 lines delivered."""
|
||||
from grimoire.services import rule_deliveries
|
||||
|
||||
fitted = assemble(list(parts), await payload_budget(user_id))
|
||||
rule_deliveries.flush(set(fitted.ids(RULE)))
|
||||
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)
|
||||
]
|
||||
@@ -0,0 +1,46 @@
|
||||
"""This instance's id lineage (models/instance.py says what it means)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.instance import InstanceIdentity
|
||||
|
||||
|
||||
async def _read_or_make(session: AsyncSession) -> str:
|
||||
current = (await session.execute(select(InstanceIdentity.instance_id))).scalar_one_or_none()
|
||||
if current:
|
||||
return current
|
||||
# The migration makes the row; this covers a schema built some other way.
|
||||
await session.execute(
|
||||
insert(InstanceIdentity)
|
||||
.values(id=1, instance_id=str(uuid.uuid4()))
|
||||
.on_conflict_do_nothing(index_elements=["id"])
|
||||
)
|
||||
return (await session.execute(select(InstanceIdentity.instance_id))).scalar_one()
|
||||
|
||||
|
||||
async def get_instance_id(session: AsyncSession | None = None) -> str:
|
||||
"""This instance's id. Inside `session` when given, so a caller's
|
||||
transaction sees the same value it may be about to change."""
|
||||
if session is not None:
|
||||
return await _read_or_make(session)
|
||||
async with async_session() as own:
|
||||
value = await _read_or_make(own)
|
||||
await own.commit()
|
||||
return value
|
||||
|
||||
|
||||
async def adopt_instance_id(session: AsyncSession, value: str) -> None:
|
||||
"""Take a backup's id as this instance's own, inside the caller's
|
||||
transaction: after a restore that kept the backup's original ids, this
|
||||
store and the one the backup came from number their rows the same way."""
|
||||
await session.execute(
|
||||
insert(InstanceIdentity)
|
||||
.values(id=1, instance_id=value)
|
||||
.on_conflict_do_update(index_elements=["id"], set_={"instance_id": value})
|
||||
)
|
||||
@@ -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,15 @@ 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_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,
|
||||
)
|
||||
|
||||
|
||||
@@ -49,6 +53,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 +65,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 +112,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 +181,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 +192,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 +212,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 +272,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 +373,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()})
|
||||
|
||||
@@ -986,33 +986,80 @@ async def get_notes_by_ids(user_id: int, note_ids: list[int]) -> dict[int, Note]
|
||||
|
||||
|
||||
async def get_backlinks(user_id: int, note_id: int) -> list[dict]:
|
||||
note = await get_note(user_id, note_id)
|
||||
if note is None:
|
||||
return []
|
||||
"""The records that link to this one, among those the caller may read.
|
||||
|
||||
title = note.title
|
||||
if not title:
|
||||
Two ways to link: a `[[title]]` wikilink, and a `#N` reference in a body or
|
||||
in a task's work log (most cross-references agents write are the second).
|
||||
Each row says which one it was in `via`. A record reached both ways is
|
||||
listed once, as a wikilink.
|
||||
"""
|
||||
from grimoire.models.task_log import TaskLog
|
||||
from grimoire.services.access import readable_notes_clause
|
||||
from grimoire.services.record_refs import referenced
|
||||
|
||||
found = await get_note_for_user(user_id, note_id)
|
||||
if found is None:
|
||||
return []
|
||||
note, _ = found
|
||||
readable = readable_notes_clause(user_id)
|
||||
rows: dict[int, dict] = {}
|
||||
|
||||
def _row(n: Note, via: str) -> dict:
|
||||
return {
|
||||
"type": "task" if n.is_task else "note",
|
||||
"id": n.id,
|
||||
"title": n.title,
|
||||
"is_task": n.is_task,
|
||||
"note_type": n.note_type or "note",
|
||||
"via": via,
|
||||
}
|
||||
|
||||
async with async_session() as session:
|
||||
escaped = title.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
pattern = f"%[[{escaped}]]%"
|
||||
pattern_alias = f"%[[{escaped}|%"
|
||||
|
||||
results = await session.execute(
|
||||
select(Note.id, Note.title, Note.status).where(
|
||||
Note.user_id == user_id,
|
||||
if note.title:
|
||||
escaped = note.title.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
linking = (await session.execute(
|
||||
select(Note).where(
|
||||
readable,
|
||||
Note.id != note_id,
|
||||
Note.deleted_at.is_(None),
|
||||
or_(Note.body.like(pattern), Note.body.like(pattern_alias)),
|
||||
or_(Note.body.like(f"%[[{escaped}]]%"),
|
||||
Note.body.like(f"%[[{escaped}|%")),
|
||||
)
|
||||
)
|
||||
backlinks: list[dict] = []
|
||||
for row in results.fetchall():
|
||||
link_type = "task" if row[2] is not None else "note"
|
||||
backlinks.append({"type": link_type, "id": row[0], "title": row[1]})
|
||||
)).scalars().all()
|
||||
for n in linking:
|
||||
rows[n.id] = _row(n, "wikilink")
|
||||
|
||||
return backlinks
|
||||
# LIKE narrows to bodies holding the digits after a `#`; `referenced`
|
||||
# then reads each one the way the renderer does, so `#12` does not
|
||||
# count as a link to 1, and "PR #12" is not a link at all.
|
||||
needle = f"%#{note_id}%"
|
||||
citing = (await session.execute(
|
||||
select(Note).where(
|
||||
readable,
|
||||
Note.id != note_id,
|
||||
Note.deleted_at.is_(None),
|
||||
Note.body.like(needle),
|
||||
)
|
||||
)).scalars().all()
|
||||
for n in citing:
|
||||
if n.id not in rows and note_id in referenced(n.body)["notes"]:
|
||||
rows[n.id] = _row(n, "reference")
|
||||
|
||||
logged = (await session.execute(
|
||||
select(Note, TaskLog.content)
|
||||
.join(TaskLog, TaskLog.task_id == Note.id)
|
||||
.where(
|
||||
readable,
|
||||
Note.id != note_id,
|
||||
Note.deleted_at.is_(None),
|
||||
TaskLog.content.like(needle),
|
||||
)
|
||||
)).all()
|
||||
for n, content in logged:
|
||||
if n.id not in rows and note_id in referenced(content)["notes"]:
|
||||
rows[n.id] = _row(n, "reference")
|
||||
|
||||
return list(rows.values())
|
||||
|
||||
|
||||
_WIKILINK_RE = re.compile(r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]')
|
||||
@@ -1071,6 +1118,22 @@ async def build_note_graph(
|
||||
edge_set.add(pair)
|
||||
edges.append({"source": n.id, "target": target_id, "type": "wikilink"})
|
||||
|
||||
# `#N` reference edges, read the way the renderer links them. Only between
|
||||
# records already on the graph: a reference to something outside it (another
|
||||
# project, a record the caller cannot read) has no node to end at.
|
||||
from grimoire.services.record_refs import referenced
|
||||
|
||||
on_graph = {n.id for n in notes}
|
||||
for n in notes:
|
||||
if not n.body:
|
||||
continue
|
||||
for target_id in sorted(referenced(n.body)["notes"]):
|
||||
if target_id in on_graph and target_id != n.id:
|
||||
pair = (n.id, target_id)
|
||||
if pair not in edge_set:
|
||||
edge_set.add(pair)
|
||||
edges.append({"source": n.id, "target": target_id, "type": "reference"})
|
||||
|
||||
# Build tag nodes + note→tag edges
|
||||
if include_shared_tags:
|
||||
tag_to_ids: dict[str, list[int]] = {}
|
||||
|
||||
@@ -17,9 +17,10 @@ from __future__ import annotations
|
||||
import logging
|
||||
import re
|
||||
import textwrap
|
||||
|
||||
from dataclasses import replace
|
||||
|
||||
from grimoire.services import design_systems as design_systems_svc
|
||||
from grimoire.services import cue_gate, hook_payload
|
||||
from grimoire.services import knowledge as knowledge_svc
|
||||
from grimoire.services import notes as notes_svc
|
||||
from grimoire.services import projects as projects_svc
|
||||
@@ -451,6 +452,22 @@ _NO_SUBJECT_WORDS = frozenset("""
|
||||
""".split())
|
||||
|
||||
|
||||
# A TURN THE HARNESS WROTE. Claude Code delivers a background task's
|
||||
# completion, a slash command's expansion and a local command's output as if
|
||||
# the operator had typed them. None is a question about anything, so none is
|
||||
# searched: the plugin skips them before calling, and the server refuses them
|
||||
# too, for a plugin that predates the skip.
|
||||
_HARNESS_OPENINGS = (
|
||||
"<task-notification>", "<agent-message>", "<agent-message ",
|
||||
"<command-name>", "<command-message>", "<command-args>",
|
||||
"<local-command-stdout>", "<local-command-stderr>", "<local-command-caveat>",
|
||||
)
|
||||
|
||||
|
||||
def is_harness_turn(prompt: str) -> bool:
|
||||
return (prompt or "").lstrip().startswith(_HARNESS_OPENINGS)
|
||||
|
||||
|
||||
def _has_subject(prompt: str) -> bool:
|
||||
"""Does the operator's message name anything a record could be about?
|
||||
|
||||
@@ -646,7 +663,7 @@ async def build_autoinject_hint(
|
||||
cfg = await get_autoinject_config(user_id)
|
||||
empty = {"context": "", "note_ids": [], "config": cfg}
|
||||
q = (query or "").strip()
|
||||
if not cfg["enabled"] or not q:
|
||||
if not cfg["enabled"] or not q or is_harness_turn(q):
|
||||
return empty
|
||||
# RECORDS NAMED BY NUMBER, read from the operator's own words before
|
||||
# the query is enriched: a number in the assistant's reply is not one the
|
||||
@@ -711,27 +728,37 @@ async def build_autoinject_hint(
|
||||
|
||||
lines: list[str] = []
|
||||
note_ids: list[int] = []
|
||||
# The same menu as parts, one per record, for a door that fits its payload
|
||||
# to a budget (`hook_payload`): a block's header rides its first kept record.
|
||||
parts: list[hook_payload.Part] = []
|
||||
named_header = ""
|
||||
# FIRST, because the operator said which record they meant and everything
|
||||
# after this block is a guess at what else might bear on it. The header
|
||||
# says these were found by NUMBER: the parser reads "with 4448" as a
|
||||
# reference, and the reader is the one placed to notice it was a quantity.
|
||||
if named:
|
||||
lines.append(
|
||||
named_header = (
|
||||
"> Named in your message — the records with those numbers, looked "
|
||||
"up by id rather than matched. Open any in full with `get_note(id)`; "
|
||||
"a line marked `seen` is already in your context:"
|
||||
)
|
||||
lines.append(named_header)
|
||||
for note in named:
|
||||
nid = int(note.id)
|
||||
note_ids.append(nid)
|
||||
# The OPENING under the line, not a passage: nothing matched here, so
|
||||
# there is no passage to keep, and what the reader needs is what the
|
||||
# record IS — which is where a record says it.
|
||||
lines.extend(menu_entry(
|
||||
entry = menu_entry(
|
||||
nid, kind=_record_kind(note),
|
||||
name=_menu_name(note.title, note.note_type, note.data, note.body),
|
||||
systems=systems.get(nid), seen=nid in already, stale=nid in stale,
|
||||
shared_by=_shared_by(note), under=_named_opening(note.body),
|
||||
)
|
||||
lines.extend(entry)
|
||||
parts.append(hook_payload.Part(
|
||||
text="\n".join(entry), block="named", header=named_header,
|
||||
ids={hook_payload.NOTE: (nid,)},
|
||||
))
|
||||
|
||||
# "records", not "notes" — the menu can hold snippets, processes and tasks
|
||||
@@ -740,6 +767,7 @@ async def build_autoinject_hint(
|
||||
# A repeat is shown again with a marker rather than withheld, so the header
|
||||
# says what the marker means, once, rather than each repeated line having
|
||||
# to explain itself.
|
||||
head_at = len(lines)
|
||||
if kept:
|
||||
lines.append(
|
||||
"> Possibly relevant from your Grimoire records — open any in full with "
|
||||
@@ -771,6 +799,7 @@ async def build_autoinject_hint(
|
||||
"what you are doing and use your judgement — a lesson is not a "
|
||||
"rule and binds nothing."
|
||||
)
|
||||
kept_header = "\n".join(lines[head_at:])
|
||||
|
||||
for score, note in kept:
|
||||
nid = int(note.id)
|
||||
@@ -789,11 +818,16 @@ async def build_autoinject_hint(
|
||||
(chunks.get(nid) or {}).get("text"), name,
|
||||
)
|
||||
who = _shared_by(note)
|
||||
lines.extend(menu_entry(
|
||||
entry = menu_entry(
|
||||
nid, kind=_record_kind(note), name=name, systems=systems.get(nid),
|
||||
seen=nid in already, stale=nid in stale, score=score,
|
||||
shared_by=f"{who}, treat as a suggestion" if who else "",
|
||||
under=passage,
|
||||
)
|
||||
lines.extend(entry)
|
||||
parts.append(hook_payload.Part(
|
||||
text="\n".join(entry), block="kept", header=kept_header,
|
||||
ids={hook_payload.NOTE: (nid,)},
|
||||
))
|
||||
|
||||
# A lookup, not a ranking, so it writes no retrieval_logs row — there is no
|
||||
@@ -818,7 +852,7 @@ async def build_autoinject_hint(
|
||||
]
|
||||
return {
|
||||
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
|
||||
"lesson_ids": lesson_ids,
|
||||
"lesson_ids": lesson_ids, "parts": parts,
|
||||
}
|
||||
|
||||
|
||||
@@ -829,9 +863,15 @@ def _note_io() -> rp.NoteIO:
|
||||
search=semantic_search_notes,
|
||||
record_retrieval=record_retrieval,
|
||||
record_surfaced=record_surfaced,
|
||||
gate=_gate_for,
|
||||
)
|
||||
|
||||
|
||||
async def _gate_for(user_id: int, source: str, project_id):
|
||||
"""`cue_gate.gate_for`, read at call time like the rest of the door's IO."""
|
||||
return await cue_gate.gate_for(user_id, source, project_id)
|
||||
|
||||
|
||||
async def _rules_via_lessons(
|
||||
user_id: int, query: str, *, project_id: int | None, skip: set[int],
|
||||
held: set[int], where: str,
|
||||
@@ -886,6 +926,7 @@ async def _rule_moment(
|
||||
skip=set(moment.exclude) | set(result.shown_rule_ids),
|
||||
held=set(moment.held), where=moment.where,
|
||||
)
|
||||
result.line_rule_ids = [*result.rule_per_line(), *ids]
|
||||
result.lines.extend(lines)
|
||||
result.rule_ids.extend(ids)
|
||||
return result
|
||||
@@ -919,7 +960,7 @@ async def build_prompt_rule_hint(
|
||||
THE OUTPUT IS DELIBERATELY NOT QUOTED, where the notes menu is, and the
|
||||
two share no header. A note line is a bare title and needs the menu's header to say what
|
||||
it is doing there, while a rule line names itself in its opening words
|
||||
("Standing rule that may apply…" / "Preference that may apply…"). Leaving
|
||||
("Rule N …; it binds" / "Preference N …; how this has been done before"). Leaving
|
||||
rules unquoted separates the two claims visually with no extra prose, and
|
||||
matches how a rule line already renders on both act arms.
|
||||
|
||||
@@ -932,7 +973,7 @@ async def build_prompt_rule_hint(
|
||||
"""
|
||||
out: dict = {"context": "", "rule_ids": []}
|
||||
q = (query or "").strip()
|
||||
if not q:
|
||||
if not q or is_harness_turn(q):
|
||||
return out
|
||||
# The same enrichment the notes arm gets. A rule is meant to
|
||||
# arrive while the work it governs is under way, not once the operator
|
||||
@@ -944,6 +985,7 @@ async def build_prompt_rule_hint(
|
||||
# the bound project's own. An unbound session (project_id 0) gets
|
||||
# global rules only — this surface speaks unasked, and a whole-rulebook
|
||||
# answer is only right for someone who asked the whole rulebook.
|
||||
# A rule that reaches the session at an act is left for that act.
|
||||
result = await _rule_moment(
|
||||
rp.PROMPT_RULE,
|
||||
rp.RuleMoment(
|
||||
@@ -951,6 +993,7 @@ async def build_prompt_rule_hint(
|
||||
where="to this request",
|
||||
exclude=frozenset(exclude_rule_ids or []),
|
||||
held=frozenset(held_rule_ids or []),
|
||||
elsewhere=await _routed_for(user_id, project_id),
|
||||
),
|
||||
floor=await floor_for(user_id, "prompt_rule"),
|
||||
budget=await budget_for(user_id, "prompt_rule"),
|
||||
@@ -958,6 +1001,9 @@ async def build_prompt_rule_hint(
|
||||
if result.lines:
|
||||
out["context"] = "\n".join(result.lines)
|
||||
out["rule_ids"] = result.rule_ids
|
||||
out["parts"] = hook_payload.rule_parts(
|
||||
result.lines, result.rule_per_line(), block="rules",
|
||||
)
|
||||
# Every rule LINE the direct arm showed, repeats and the reserved
|
||||
# slot included — for the soft-link recorder. Distinct
|
||||
# from `rule_ids`, which is telemetry's fresh-only cut.
|
||||
@@ -967,6 +1013,18 @@ async def build_prompt_rule_hint(
|
||||
return out
|
||||
|
||||
|
||||
async def _routed_for(user_id: int, project_id: int) -> frozenset[int]:
|
||||
"""The rules that arrive at an act (`moment_delivery.routed_to_acts`);
|
||||
empty when they cannot be read, so the prompt arm delivers as before."""
|
||||
from grimoire.services import moment_delivery
|
||||
|
||||
try:
|
||||
return await moment_delivery.routed_to_acts(user_id, project_id or None)
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks the prompt
|
||||
logger.debug("act-routed rules unreadable", exc_info=True)
|
||||
return frozenset()
|
||||
|
||||
|
||||
def _rule_io() -> rp.RuleIO:
|
||||
"""The ranker and recorders the rule arms report to, read at call time.
|
||||
|
||||
@@ -974,10 +1032,17 @@ def _rule_io() -> rp.RuleIO:
|
||||
the pipeline reports to whatever this module's `semantic_search_rules`,
|
||||
`record_retrieval` and `record_rule_surfaced` are at the moment it runs.
|
||||
"""
|
||||
from grimoire.services import rule_deliveries
|
||||
|
||||
bound = rule_deliveries.bound()
|
||||
return rp.RuleIO(
|
||||
search=semantic_search_rules,
|
||||
record_retrieval=record_retrieval,
|
||||
record_rule_surfaced=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,
|
||||
gate=_gate_for,
|
||||
)
|
||||
|
||||
|
||||
@@ -1575,6 +1640,7 @@ async def build_write_path_hint(
|
||||
# The direct band, then a rule reached through a linked lesson,
|
||||
# composed by `_rule_moment` exactly as the other two rule builders are.
|
||||
rule_lines: list[str] = []
|
||||
rule_line_ids: list[int] = []
|
||||
rule_ids: list[int] = []
|
||||
shown_rule_ids: list[int] = []
|
||||
checkpoint: dict = {}
|
||||
@@ -1591,6 +1657,7 @@ async def build_write_path_hint(
|
||||
checkpoint_floor=cfg["checkpoint_threshold"],
|
||||
)
|
||||
rule_lines = result.lines
|
||||
rule_line_ids = result.rule_per_line()
|
||||
rule_ids.extend(result.rule_ids)
|
||||
# Every rule line the band showed, repeats included — what the
|
||||
# soft-link recorder pairs with this response's lessons.
|
||||
@@ -1599,6 +1666,25 @@ async def build_write_path_hint(
|
||||
except Exception:
|
||||
logger.debug("write-path rule arm failed", exc_info=True)
|
||||
|
||||
# The payload as parts, for the door that fits it to a budget: the rules,
|
||||
# then the rulings and design system that bind, then the prior art.
|
||||
binding: list[hook_payload.Part] = []
|
||||
if rulings["lines"]:
|
||||
binding.append(hook_payload.Part(
|
||||
text="\n".join(rulings["lines"]),
|
||||
ids={hook_payload.RULING: tuple(rulings["system_ids"])},
|
||||
))
|
||||
if design_text:
|
||||
binding.append(hook_payload.Part(
|
||||
text=design_text,
|
||||
ids={hook_payload.DERIVE: (design_dedup,)} if design_dedup else {},
|
||||
))
|
||||
parts = [
|
||||
*hook_payload.rule_parts(rule_lines, rule_line_ids, block="rules"),
|
||||
*binding,
|
||||
*(hook_payload.Part(text=line) for line in staleness),
|
||||
]
|
||||
|
||||
if (not staleness and not synced and not menu and not suggested
|
||||
and not divergence and not derive and not rule_lines):
|
||||
if design_text or rulings["lines"]:
|
||||
@@ -1607,6 +1693,7 @@ async def build_write_path_hint(
|
||||
"context": "\n".join(rulings["lines"] + ([design_text] if design_text else [])),
|
||||
"derive_keys": [design_dedup] if design_dedup else [],
|
||||
"ruling_system_ids": rulings["system_ids"],
|
||||
"parts": parts,
|
||||
}
|
||||
return empty
|
||||
|
||||
@@ -1633,12 +1720,13 @@ async def build_write_path_hint(
|
||||
if design_text:
|
||||
lines.append(design_text)
|
||||
sync_note_ids: list[int] = []
|
||||
sync_header = ""
|
||||
if synced:
|
||||
# The sync framing. Deliberately imperative about the record —
|
||||
# the reuse claim ("start from this shape") is still implied by the
|
||||
# title being right there, but the load-bearing sentence is the one no
|
||||
# other surface says: keeping the record true is part of THIS edit.
|
||||
lines.append(
|
||||
sync_header = (
|
||||
f"> Recorded in Grimoire AT `{path}` — the snippet(s) below record "
|
||||
"the file this edit is changing. Reuse/extend the recorded shape "
|
||||
"rather than writing a parallel one; and if this edit changes what "
|
||||
@@ -1647,10 +1735,18 @@ async def build_write_path_hint(
|
||||
"`verify_snippet(id, status=\"ok\", commit_sha=…)` after confirming "
|
||||
"it still holds. Open with `get_snippet(id)` (shown once per session):"
|
||||
)
|
||||
lines.append(sync_header)
|
||||
for item in synced:
|
||||
sync_note_ids.append(int(item["id"]))
|
||||
lines.append(_prior_art_line(item, "records this file", _owner_of(item)))
|
||||
sid = int(item["id"])
|
||||
sync_note_ids.append(sid)
|
||||
line = _prior_art_line(item, "records this file", _owner_of(item))
|
||||
lines.append(line)
|
||||
parts.append(hook_payload.Part(
|
||||
text=line, block="synced", header=sync_header,
|
||||
ids={hook_payload.SYNC: (sid,), hook_payload.NOTE: (sid,)},
|
||||
))
|
||||
|
||||
menu_at = len(lines)
|
||||
if menu:
|
||||
lines.append(
|
||||
f"> Prior art already recorded in Grimoire for `{path}` — open one with "
|
||||
@@ -1685,10 +1781,17 @@ async def build_write_path_hint(
|
||||
"shape of a solution to adapt, not code to copy."
|
||||
)
|
||||
|
||||
menu_header = "\n".join(lines[menu_at:])
|
||||
note_ids: list[int] = list(sync_note_ids)
|
||||
for item, marker, owner, foreign_lang in rendered:
|
||||
note_ids.append(int(item["id"]))
|
||||
lines.append(_prior_art_line(item, marker, owner, foreign_lang))
|
||||
nid = int(item["id"])
|
||||
note_ids.append(nid)
|
||||
entry = [_prior_art_line(item, marker, owner, foreign_lang)]
|
||||
lines.append(entry[0])
|
||||
parts.append(hook_payload.Part(
|
||||
text=entry[0], block="menu", header=menu_header,
|
||||
ids={hook_payload.NOTE: (nid,)},
|
||||
))
|
||||
# Only the semantically-matched lines carry a passage. The records-this-
|
||||
# file lines came from a LOCATION lookup — nothing was matched, so there
|
||||
# is no matching passage and the body's opening would be a fabricated
|
||||
@@ -1705,15 +1808,23 @@ async def build_write_path_hint(
|
||||
)
|
||||
if passage:
|
||||
lines.append(f"> ↳ {passage}")
|
||||
entry.append(f"> ↳ {passage}")
|
||||
parts[-1] = replace(parts[-1], text="\n".join(entry))
|
||||
|
||||
if suggested:
|
||||
lines.append(_suggest_line(path, suggested))
|
||||
parts.append(hook_payload.Part(text=lines[-1]))
|
||||
if divergence:
|
||||
lines.append(_divergence_line(path, divergence))
|
||||
parts.append(hook_payload.Part(text=lines[-1]))
|
||||
if derive:
|
||||
lines.append(_derive_line(path, derive))
|
||||
parts.append(hook_payload.Part(
|
||||
text=lines[-1], ids={hook_payload.DERIVE: tuple(d["key"] for d in derive)},
|
||||
))
|
||||
if copies:
|
||||
lines.append(_copy_line(copies))
|
||||
parts.append(hook_payload.Part(text=lines[-1]))
|
||||
|
||||
# Split by arm, which is the whole reason this table exists. The place arm
|
||||
# carries no score and so has no home in retrieval_logs, yet it fires on
|
||||
@@ -1752,9 +1863,11 @@ async def build_write_path_hint(
|
||||
)
|
||||
if proposal:
|
||||
lines.append(proposal)
|
||||
parts.append(hook_payload.Part(text=proposal))
|
||||
|
||||
return {
|
||||
"context": "\n".join(lines),
|
||||
"parts": parts,
|
||||
"note_ids": note_ids,
|
||||
"sync_note_ids": sync_note_ids,
|
||||
"config": cfg,
|
||||
@@ -1849,6 +1962,9 @@ async def build_tool_rule_hint(
|
||||
out["context"] = "\n".join(result.lines)
|
||||
out["rule_ids"] = result.rule_ids
|
||||
out["checkpoint"] = result.checkpoint
|
||||
out["parts"] = hook_payload.rule_parts(
|
||||
result.lines, result.rule_per_line(), block="rules",
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("pre-tool rule arm failed", exc_info=True)
|
||||
|
||||
@@ -1869,6 +1985,10 @@ async def build_tool_rule_hint(
|
||||
rulings["lines"] + ([out["context"]] if out.get("context") else [])
|
||||
)
|
||||
out["ruling_system_ids"] = rulings["system_ids"]
|
||||
out["parts"] = [hook_payload.Part(
|
||||
text="\n".join(rulings["lines"]),
|
||||
ids={hook_payload.RULING: tuple(rulings["system_ids"])},
|
||||
), *out.get("parts", [])]
|
||||
except Exception:
|
||||
logger.debug("pre-tool rulings arm failed", exc_info=True)
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""The reverse-proxy hop count an admin saves in Settings → Config.
|
||||
|
||||
How many proxies stand in front of the app decides which address every rate
|
||||
limit and audit line sees, and whether a request counts as HTTPS
|
||||
(grimoire/proxy.py). Behind Cloudflare's proxied DNS the right count is 2; at
|
||||
the default of 1 every visitor reads as a Cloudflare edge address and they
|
||||
share one sign-in rate limit. So the count is set where an admin can find it
|
||||
and check it against their own request, not only in the environment.
|
||||
|
||||
Precedence: the saved count, then `TRUSTED_PROXY_HOPS` from the environment,
|
||||
then 1. Saving None removes the saved count, so the environment's applies
|
||||
again.
|
||||
|
||||
It is one instance-wide value, kept on the first admin account like the other
|
||||
instance settings. Every worker holds it in proxy.py, loads it at startup and
|
||||
re-reads it every REFRESH_SECONDS, so a save in one worker reaches the others
|
||||
within that interval; the worker that saved applies it at once.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from grimoire import proxy
|
||||
from grimoire.config import Config
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.setting import Setting
|
||||
from grimoire.models.user import User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SETTING_KEY = "trusted_proxy_hops"
|
||||
REFRESH_SECONDS = 30
|
||||
# The load at startup runs inside the lifespan hook, and a hook that does not
|
||||
# return is a worker that never serves (db_maintenance_scheduler explains the
|
||||
# outage that taught this). One indexed row answers in milliseconds, so the
|
||||
# deadline only fires when the database is already in trouble.
|
||||
STARTUP_READ_TIMEOUT = 3.0
|
||||
|
||||
|
||||
def parse_hops(raw) -> int | None:
|
||||
"""A hop count from 0 to proxy.MAX_HOPS, or None for anything else. A
|
||||
bool is refused, though Python counts it as an int."""
|
||||
if isinstance(raw, bool):
|
||||
return None
|
||||
if isinstance(raw, str):
|
||||
raw = raw.strip()
|
||||
if not raw.isdigit():
|
||||
return None
|
||||
raw = int(raw)
|
||||
if not isinstance(raw, int) or not 0 <= raw <= proxy.MAX_HOPS:
|
||||
return None
|
||||
return raw
|
||||
|
||||
|
||||
def _admin_rows():
|
||||
return (
|
||||
select(Setting)
|
||||
.join(User, Setting.user_id == User.id)
|
||||
.where(User.role == "admin", Setting.key == SETTING_KEY)
|
||||
)
|
||||
|
||||
|
||||
async def saved_hops() -> int | None:
|
||||
"""The count saved in Settings, or None when there is none (or what is
|
||||
stored can't be read as one)."""
|
||||
async with async_session() as session:
|
||||
row = (await session.execute(_admin_rows().order_by(Setting.user_id))).scalars().first()
|
||||
return parse_hops(row.value) if row else None
|
||||
|
||||
|
||||
async def save_hops(hops: int | None) -> None:
|
||||
"""Save the count, or remove it with None. Any copy on another admin's
|
||||
account goes too, so exactly one value is ever read back."""
|
||||
async with async_session() as session:
|
||||
admin_ids = select(User.id).where(User.role == "admin")
|
||||
await session.execute(
|
||||
delete(Setting).where(Setting.key == SETTING_KEY, Setting.user_id.in_(admin_ids))
|
||||
)
|
||||
if hops is not None:
|
||||
first_admin = (
|
||||
await session.execute(select(User.id).where(User.role == "admin").order_by(User.id))
|
||||
).scalars().first()
|
||||
if first_admin is None:
|
||||
raise ValueError("there is no admin account to keep the setting on")
|
||||
session.add(Setting(user_id=first_admin, key=SETTING_KEY, value=str(hops)))
|
||||
await session.commit()
|
||||
proxy.set_saved_hops(hops)
|
||||
|
||||
|
||||
async def refresh() -> None:
|
||||
"""Load the saved count into this worker. A failed read keeps the value
|
||||
it already had: an unreachable database must not switch the trust rule."""
|
||||
try:
|
||||
proxy.set_saved_hops(await saved_hops())
|
||||
except Exception:
|
||||
logger.debug("could not re-read the saved proxy hop count", exc_info=True)
|
||||
|
||||
|
||||
async def load_at_startup() -> None:
|
||||
"""`refresh`, bounded for the lifespan hook. On a timeout the environment's
|
||||
count stays in force until the next refresh reaches the database."""
|
||||
try:
|
||||
await asyncio.wait_for(refresh(), timeout=STARTUP_READ_TIMEOUT)
|
||||
except (TimeoutError, asyncio.TimeoutError):
|
||||
logger.warning(
|
||||
"reading the saved proxy hop count exceeded %.1fs; starting with %d "
|
||||
"from the environment until the database answers",
|
||||
STARTUP_READ_TIMEOUT, Config.TRUSTED_PROXY_HOPS,
|
||||
)
|
||||
|
||||
|
||||
_refresh_task = None
|
||||
|
||||
|
||||
def start_refresh_loop() -> None:
|
||||
global _refresh_task
|
||||
if _refresh_task is None or _refresh_task.done():
|
||||
from grimoire.services.background import start_periodic
|
||||
_refresh_task = start_periodic(REFRESH_SECONDS, refresh, label="proxy_hops_refresh")
|
||||
|
||||
|
||||
def source() -> str:
|
||||
"""Where the count in force came from: "setting", "env" or "default"."""
|
||||
if proxy.saved_hops_in_force() is not None:
|
||||
return "setting"
|
||||
return "env" if Config.TRUSTED_PROXY_HOPS_FROM_ENV else "default"
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Record references written into prose: refusing guessed ids, resolving placeholders, reading the ids a message names.
|
||||
"""Record references written into prose: refusing guessed ids, resolving placeholders, reading the ids a message names, and saying what a body links to.
|
||||
|
||||
THE DEFECT THIS EXISTS FOR
|
||||
|
||||
@@ -41,6 +41,7 @@ restores and internal writers that legitimately carry numbers from elsewhere.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
@@ -209,6 +210,128 @@ def _prev_word(before: str) -> str:
|
||||
return m.group(1).lower() if m else ""
|
||||
|
||||
|
||||
# ── References written into a record's prose ───────────────────────────────
|
||||
#
|
||||
# What a body, a work log or a plan names, read the way the web UI links it.
|
||||
# `frontend/src/utils/recordRefs.ts` holds the same patterns and the same word
|
||||
# list, and tests/test_record_ref_links.py reads that file and fails when its
|
||||
# patterns or words differ from these.
|
||||
#
|
||||
# Three id spaces, three forms:
|
||||
# `#N` a note, task, lesson or snippet (one sequence, the notes table)
|
||||
# `milestone N` a milestone — what `{{ref:milestone}}` renders as
|
||||
# `rule N` a rule; `preference N` too, since preferences are rules
|
||||
# A `#N` after a word that names another numbering ("PR #198", "rule #34",
|
||||
# "step #3") is not a note: `_OTHER_SPACE` above decides, exactly as it does for
|
||||
# the numbers an operator names in a message.
|
||||
|
||||
PROSE_REF_RE = re.compile(r"(?<![\w/])\b(milestone|rule|preference)\s+#?(\d+)\b", re.IGNORECASE)
|
||||
|
||||
# Fenced and inline code: a pasted log or a snippet of source names nothing.
|
||||
_CODE_RE = re.compile(r"```[\s\S]*?```|`[^`\n]+`")
|
||||
|
||||
|
||||
def referenced(*texts: str | None) -> dict[str, set[int]]:
|
||||
"""Every record these texts link to, by id space: notes, milestones, rules."""
|
||||
out: dict[str, set[int]] = {"notes": set(), "milestones": set(), "rules": set()}
|
||||
for text in texts:
|
||||
if not text:
|
||||
continue
|
||||
text = _CODE_RE.sub(" ", text)
|
||||
for m in PROSE_REF_RE.finditer(text):
|
||||
space = "milestones" if m.group(1).lower() == "milestone" else "rules"
|
||||
out[space].add(int(m.group(2)))
|
||||
for m in REF_RE.finditer(text):
|
||||
if _prev_word(text[:m.start()]) not in _OTHER_SPACE:
|
||||
out["notes"].add(int(m.group(1)))
|
||||
return out
|
||||
|
||||
|
||||
# How many references one resolve call answers. A long plan cites a few dozen;
|
||||
# past this the caller is listing, not rendering, and gets a 400 at the door.
|
||||
RESOLVE_LIMIT = 200
|
||||
|
||||
|
||||
async def resolve_refs(
|
||||
user_id: int,
|
||||
*,
|
||||
notes: Iterable[int] = (),
|
||||
milestones: Iterable[int] = (),
|
||||
rules: Iterable[int] = (),
|
||||
) -> dict[str, dict[int, dict]]:
|
||||
"""What each referenced id IS, for the records this user may read.
|
||||
|
||||
An id that is missing, trashed or not readable is simply absent, and the
|
||||
caller shows it as a reference that leads nowhere. The answer never says
|
||||
which of the three it was: "not shared with you" and "does not exist" must
|
||||
read the same, or the resolver becomes a way to probe other people's ids.
|
||||
|
||||
No pull is recorded. Hovering a link is not choosing to read the record;
|
||||
the view it opens records that, the same as any other way of arriving.
|
||||
"""
|
||||
from grimoire.models.milestone import Milestone
|
||||
from grimoire.services import rulebooks as rulebooks_svc
|
||||
from grimoire.services.access import can_read_project, readable_notes_clause
|
||||
|
||||
out: dict[str, dict[int, dict]] = {"notes": {}, "milestones": {}, "rules": {}}
|
||||
note_ids = sorted({int(i) for i in notes})
|
||||
milestone_ids = sorted({int(i) for i in milestones})
|
||||
rule_ids = sorted({int(i) for i in rules})
|
||||
|
||||
async with async_session() as session:
|
||||
if note_ids:
|
||||
rows = (await session.execute(
|
||||
select(Note).where(
|
||||
Note.id.in_(note_ids),
|
||||
Note.deleted_at.is_(None),
|
||||
readable_notes_clause(user_id),
|
||||
)
|
||||
)).scalars().all()
|
||||
for n in rows:
|
||||
out["notes"][n.id] = {
|
||||
"id": n.id,
|
||||
"title": n.title or "",
|
||||
"is_task": n.is_task,
|
||||
"note_type": n.note_type or "note",
|
||||
"status": n.status,
|
||||
"task_kind": n.task_kind if n.is_task else None,
|
||||
}
|
||||
if milestone_ids:
|
||||
rows = (await session.execute(
|
||||
select(Milestone).where(
|
||||
Milestone.id.in_(milestone_ids), Milestone.deleted_at.is_(None),
|
||||
)
|
||||
)).scalars().all()
|
||||
readable_projects: dict[int, bool] = {}
|
||||
for ms in rows:
|
||||
if ms.user_id != user_id:
|
||||
pid = ms.project_id
|
||||
if pid is None:
|
||||
continue
|
||||
if pid not in readable_projects:
|
||||
readable_projects[pid] = await can_read_project(user_id, pid)
|
||||
if not readable_projects[pid]:
|
||||
continue
|
||||
out["milestones"][ms.id] = {
|
||||
"id": ms.id,
|
||||
"title": ms.title or "",
|
||||
"project_id": ms.project_id,
|
||||
"status": ms.status,
|
||||
}
|
||||
|
||||
# One lookup per rule: readability runs through rulebook ownership and
|
||||
# project ownership, which `get_rule` already resolves. A body names a few.
|
||||
for rid in rule_ids:
|
||||
rule = await rulebooks_svc.get_rule(rid, user_id)
|
||||
if rule is not None:
|
||||
out["rules"][rule.id] = {
|
||||
"id": rule.id,
|
||||
"title": rule.title or "",
|
||||
"kind": getattr(rule, "kind", None) or "rule",
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _next_word(after: str) -> str:
|
||||
m = _NEXT_WORD_RE.match(after)
|
||||
return m.group(1).lower() if m else ""
|
||||
|
||||
@@ -35,6 +35,7 @@ import time
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable
|
||||
|
||||
from grimoire.services import cue_gate, rule_order
|
||||
from grimoire.services.lessons import LESSON_NOTE_TYPE, claim_line
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -104,12 +105,11 @@ def checkpoint_for(
|
||||
floor; only a hit the corpus is confident about is allowed to stop
|
||||
anything.
|
||||
|
||||
2. IT IS A RULE, NEVER A PREFERENCE. A preference says how something has
|
||||
been done before and following it is what keeps work consistent; a rule
|
||||
says what happens if you do not. Stopping an act over a preference
|
||||
would assert a force the record explicitly does not claim, and
|
||||
`_rule_hint_line` already keeps that distinction in the one word that
|
||||
names it.
|
||||
2. IT IS A RULE DECLARED TO HOLD (`rule_order.holds`): `hold` or
|
||||
`enforce`, never `inform`, never a preference. A preference says how
|
||||
something has been done before; an `inform` rule asked to be put beside
|
||||
the work. Stopping an act over either would assert a force the record
|
||||
does not claim.
|
||||
|
||||
3. THE SESSION HAS NOT OPENED IT. `held` is observable — a PostToolUse
|
||||
hook watches for the `get_rule` call — so this is a recorded
|
||||
@@ -133,7 +133,7 @@ def checkpoint_for(
|
||||
score, rule = kept[0]
|
||||
if score < floor:
|
||||
return {}
|
||||
if getattr(rule, "kind", "") == "preference":
|
||||
if not rule_order.holds(rule):
|
||||
return {}
|
||||
if rule.id in held:
|
||||
return {}
|
||||
@@ -184,139 +184,67 @@ def checkpoint_reason(checkpoint: dict) -> str:
|
||||
)
|
||||
|
||||
|
||||
# How much of a rule's statement a first mention carries. A statement past it
|
||||
# is cut at a sentence boundary and the line says where the rest is.
|
||||
STATEMENT_CHARS = 600
|
||||
# The register clause, the one place a line says how much force it carries.
|
||||
RULE_FORCE = "it binds"
|
||||
PREFERENCE_FORCE = "how this has been done before"
|
||||
|
||||
|
||||
def _statement_excerpt(rule) -> str:
|
||||
"""The rule's own words, up to STATEMENT_CHARS, cut where a sentence ends."""
|
||||
text = getattr(rule, "statement", "")
|
||||
text = " ".join(text.split()) if isinstance(text, str) else ""
|
||||
if len(text) <= STATEMENT_CHARS:
|
||||
return text
|
||||
cut = text[:STATEMENT_CHARS]
|
||||
stop = max(cut.rfind(". "), cut.rfind("; "), cut.rfind(": "))
|
||||
return (cut[: stop + 1] if stop > STATEMENT_CHARS // 2 else cut.rstrip()) + " …"
|
||||
|
||||
|
||||
def _rule_hint_line(
|
||||
rule, *, where: str, seen: bool, held: bool = False, compact: bool = False,
|
||||
) -> str:
|
||||
"""One rule hint line — both arms, both tails, both kinds.
|
||||
"""One rule line, for every arm and both kinds.
|
||||
|
||||
THREE INDEPENDENT AXES. `compact` joins `kind` and `seen`, and like them
|
||||
it reads none of the others: it says how much ROOM this line
|
||||
gets, which is a fact about its rank among today's hits rather than about
|
||||
the rule. A compact line is still a full claim that the rule may apply —
|
||||
it simply cites the rule instead of quoting its trigger. Crucially it
|
||||
still carries the `seen` tail, so the three axes stay genuinely
|
||||
independent: shortening a line must not decide what it says about whether
|
||||
the session is holding the rule.
|
||||
A first mention carries the rule itself — its title, why it is here, and
|
||||
its statement — so the reader has what the rule says without a second
|
||||
call. A repeat, or a lower-ranked line (`compact`), is a reference: the
|
||||
rule's number and title. Every line ends by saying where this session
|
||||
stands with the rule and where its full text is.
|
||||
|
||||
WHY THE LATER LINES ARE QUIETER. A full line runs ~143 tokens once the
|
||||
trigger is rendered, so five full lines cost ~568 tokens before every Bash
|
||||
call. Top-full-plus-references costs ~299 — about 2x a single full line,
|
||||
for four more rules. The token budget forbids four voices at full volume,
|
||||
not four voices.
|
||||
Written as statements about the rule, never as instructions to the
|
||||
reader: a line beside the work reports what applies, and the reader
|
||||
decides what to do with it.
|
||||
|
||||
The top hit keeps the full rendering because it is the one the ranker is
|
||||
most confident about, and a reader who acts on exactly one line should
|
||||
have acted on that one.
|
||||
|
||||
TWO INDEPENDENT AXES. `kind` decides the head, `seen` decides the tail,
|
||||
and neither reads the other. A preference and a rule differ in force; a
|
||||
repeat and a first surfacing differ in whether the session already holds
|
||||
the line. Those are unrelated facts, and keeping them unrelated in the
|
||||
code is what lets a new kind join without reopening the repeat question.
|
||||
|
||||
ONE FUNCTION BECAUSE THE TAILS MUST NOT DRIFT. The two arms phrase their
|
||||
heads differently ("may apply here" vs "may apply to this Bash call") and
|
||||
that difference is deliberate. Everything after it must not differ: an
|
||||
arm modelled on its sibling rather than sharing with it inherits its
|
||||
defects, and two copies of a two-branch string is how one branch gets
|
||||
fixed and the other does not.
|
||||
|
||||
WHY A REPEAT GETS A LINE AT ALL. Dropping a hit whose id is already on the
|
||||
session's exclusion ledger is correct only while the session still HOLDS
|
||||
what it was told, and a compaction breaks exactly that: the earlier
|
||||
injection is summarized away while the id stays on the ledger, so the rule
|
||||
would be absent from context AND unreachable for the rest of the session.
|
||||
The same holds, more slowly, for a session that simply stops holding a
|
||||
line it read an hour ago.
|
||||
|
||||
Only ONE CLAUSE of a first-surfacing line is false on a repeat — the claim that
|
||||
the rule is not in the session's loaded set. So only that clause changes.
|
||||
Title, trigger and pull pointer are identical either way, the statement is
|
||||
never injected either way, and a repeat therefore costs the same ~40 tokens
|
||||
as a first surfacing and no more.
|
||||
|
||||
DELIBERATELY NOT ASKING THE SESSION WHETHER IT HOLDS THE RULE. A model
|
||||
asked "do you still hold rule N?" will say yes, and the claim is
|
||||
unverifiable self-report about its own context. The answer is also not
|
||||
needed: the line is cheap enough to always emit and carries its own remedy
|
||||
in both branches. Removing the question removes the fragility rather than
|
||||
managing it.
|
||||
Three independent axes:
|
||||
- `kind` moves the noun and the register clause: a rule binds, a
|
||||
preference says how this has been done before.
|
||||
- the ledger moves the closing clause: first mention, named earlier and
|
||||
not opened (`seen`), or opened earlier (`held`). The server cannot know
|
||||
what the reader still holds, only what it named and what was opened.
|
||||
- `compact`, or any repeat, drops the statement and keeps the rest.
|
||||
"""
|
||||
trigger = (rule.when_to_apply or "").strip()
|
||||
preference = rule.kind == "preference"
|
||||
# KIND CHANGES THE HEAD; `seen` CHANGES THE TAIL. The two axes are
|
||||
# independent and stay that way, which is what lets the repeat logic above
|
||||
# survive a second kind without being reasoned about again: whether a
|
||||
# record is already on the ledger has nothing to do with how much force it
|
||||
# carries, so the seen-branch is shared verbatim.
|
||||
#
|
||||
# The noun is the whole of the visual difference, and that is deliberate.
|
||||
# A reader skimming an injected block gets one word to place the register \u2014
|
||||
# so it is the SECOND word that moves, and it is the word naming force.
|
||||
# Everything structural after it is identical, so the three kinds read as
|
||||
# one set rather than three formats (the lesson voice is written against
|
||||
# these two; they are one paragraph, not three).
|
||||
noun = "Preference" if preference else "Standing rule"
|
||||
# The only other place force is asserted. A rule's line tells the reader
|
||||
# not to dismiss it unread, because dismissing a rule unread is how the
|
||||
# thing it prevents happens. A preference makes no such claim: it says
|
||||
# where to find how this has been done, and following it is what keeps
|
||||
# things consistent rather than what keeps them correct.
|
||||
reason = (
|
||||
"for how this has been done before" if preference
|
||||
else "before deciding it does not apply"
|
||||
)
|
||||
# THREE STATES, BECAUSE TWO OF THEM MUST NOT BE TOLD THE SAME THING.
|
||||
#
|
||||
# `seen` means an arm NAMED this rule earlier. It does not mean the session
|
||||
# read it — the line is a teaser, and a teaser skimmed past leaves nothing
|
||||
# behind, least of all after a compaction summarises the turn it arrived
|
||||
# in. "You saw it earlier this session" would assert something about the
|
||||
# reader's context that the server has no way to know.
|
||||
#
|
||||
# `held` is the observable half: a PostToolUse hook watches for the
|
||||
# `get_rule` call itself, so this is a recorded EVENT rather than a claim.
|
||||
# That distinction is what keeps the non-goal above intact — the objection
|
||||
# was to asking a model about its own context, not to noticing what it did.
|
||||
#
|
||||
# The middle state is the honest one: named, not opened. It gets the full
|
||||
# invitation, because a session that skipped
|
||||
# the teaser is in almost the same position as one that never saw it.
|
||||
noun = "Preference" if preference else "Rule"
|
||||
force = PREFERENCE_FORCE if preference else RULE_FORCE
|
||||
if held:
|
||||
tail = (
|
||||
f"You opened it earlier this session; pull it with "
|
||||
f"get_rule({rule.id}) again if you no longer hold it."
|
||||
)
|
||||
state = "Opened earlier this session"
|
||||
elif seen:
|
||||
tail = (
|
||||
f"Mentioned earlier this session but not opened — read it with "
|
||||
f"get_rule({rule.id}) {reason}."
|
||||
)
|
||||
state = "Named earlier this session, not opened"
|
||||
else:
|
||||
tail = (
|
||||
f"Read it with get_rule({rule.id}) {reason}; it is not in this "
|
||||
"session's loaded set."
|
||||
)
|
||||
if compact:
|
||||
# THE TRIGGER GOES; THE TAIL STAYS. Only one of the two is expensive \u2014
|
||||
# a trigger runs 300-400 characters, the tail about 100 \u2014
|
||||
# so dropping the trigger is nearly the whole saving and dropping the
|
||||
# tail would be mostly sacrifice.
|
||||
#
|
||||
# It would also destroy the one thing a repeat line exists to say. The
|
||||
# tail is what tells a reader whether they were already told this and
|
||||
# may no longer be holding it, and that is the entire difference they
|
||||
# can act on; a reference with no tail reads as a first surfacing
|
||||
# whether it is one or not.
|
||||
# test_a_rule_the_session_already_holds_is_referenced_not_re_offered
|
||||
# pins this.
|
||||
state = "First mention this session"
|
||||
tail = f"{state}; full text: get_rule({rule.id})."
|
||||
if compact or seen or held:
|
||||
return f"Also relevant: {noun} {rule.id} \u201c{rule.title}\u201d ({force}). {tail}"
|
||||
statement = _statement_excerpt(rule)
|
||||
if statement and statement[-1] not in ".!?…":
|
||||
statement += "."
|
||||
return (
|
||||
f"Also \u2014 {noun.lower()} \u201c{rule.title}\u201d. {tail}"
|
||||
)
|
||||
return (
|
||||
f"{noun} that may apply {where} \u2014 \u201c{rule.title}\u201d"
|
||||
+ (f" ({trigger})" if trigger else "")
|
||||
+ f". {tail}"
|
||||
f"{noun} {rule.id} \u201c{rule.title}\u201d may apply {where}; "
|
||||
+ (f"{force}: {statement}" if statement else f"{force}.")
|
||||
+ f" {tail}"
|
||||
)
|
||||
|
||||
|
||||
@@ -445,6 +373,12 @@ class RuleArm:
|
||||
kind: str | None = None
|
||||
"""Ask the ranker for one record kind only ("preference"), or every kind."""
|
||||
|
||||
gates_preferences: bool = False
|
||||
"""A preference this arm found by resemblance alone speaks only past the
|
||||
cue-swap gate (`cue_gate`). A rule binds, so a missed rule costs a mistake
|
||||
and is never gated here; a preference guides, and an unrelated one beside
|
||||
the work costs the reader's attention on every call."""
|
||||
|
||||
stop_only: bool = False
|
||||
"""The door shows nothing but the stop (the reply moment).
|
||||
|
||||
@@ -480,7 +414,7 @@ RULE_FLOOR_DEFAULT = 0.70
|
||||
# preference.
|
||||
PROMPT_RULE = RuleArm(
|
||||
"prompt_rule", band=False, compact_tail=False, checkpoint=False,
|
||||
preference_slot=True,
|
||||
preference_slot=True, gates_preferences=True,
|
||||
tuning=Surface(
|
||||
name="prompt_rule",
|
||||
floor_key=RULE_FLOOR_KEY,
|
||||
@@ -495,7 +429,7 @@ PROMPT_RULE = RuleArm(
|
||||
)
|
||||
PRE_TOOL_RULE = RuleArm(
|
||||
"pre_tool_rule", band=True, compact_tail=True, checkpoint=True,
|
||||
preference_slot=True,
|
||||
preference_slot=True, gates_preferences=True,
|
||||
tuning=Surface(
|
||||
name="pre_tool_rule",
|
||||
floor_key=RULE_FLOOR_KEY,
|
||||
@@ -510,7 +444,7 @@ PRE_TOOL_RULE = RuleArm(
|
||||
)
|
||||
WRITE_PATH_RULE = RuleArm(
|
||||
"write_path_rule", band=True, compact_tail=True, checkpoint=True,
|
||||
preference_slot=True,
|
||||
preference_slot=True, gates_preferences=True,
|
||||
tuning=Surface(
|
||||
name="write_path_rule",
|
||||
floor_key=RULE_FLOOR_KEY,
|
||||
@@ -576,6 +510,18 @@ class RuleIO:
|
||||
|
||||
record_retrieval: Callable[..., Any]
|
||||
record_rule_surfaced: Callable[..., Any]
|
||||
history: Callable[..., Any] | None = None
|
||||
"""`rule_deliveries.history`: `{rule_id: open rate}` for (rule, at) pairs.
|
||||
None leaves every rule's history unknown."""
|
||||
record_delivery: Callable[..., Any] | None = None
|
||||
"""`rule_deliveries.record`: each line shown, against the session the
|
||||
door bound. None records nothing."""
|
||||
retired: Callable[..., Any] | None = None
|
||||
"""`rule_deliveries.retired`: the repeats this session has already had
|
||||
its one reminder of. None retires nothing."""
|
||||
gate: Callable[..., Any] | None = None
|
||||
"""`cue_gate.gate_for`: the bar a line found by resemblance must reach.
|
||||
None, or a call returning None, leaves the arm ungated."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -598,6 +544,12 @@ class RuleMoment:
|
||||
held: frozenset[int] = frozenset()
|
||||
"""Rules the session has OPENED."""
|
||||
|
||||
elsewhere: frozenset[int] = frozenset()
|
||||
"""Rules that arrive at an act — mounted on a moment a tool call reaches,
|
||||
or triggered by a tool, path or command — and so are not delivered here
|
||||
by resemblance. A reminder read at the act is the one acted on; the same
|
||||
line at the prompt competes with the request it came beside."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class RuleResult:
|
||||
@@ -616,6 +568,18 @@ class RuleResult:
|
||||
|
||||
checkpoint: dict = field(default_factory=dict)
|
||||
|
||||
decision: dict = field(default_factory=dict)
|
||||
"""The moment arm's answer for the act itself, empty when the act goes
|
||||
ahead: `{"kind": "enforce" | "hold", "rule_ids", "reason"}`. See
|
||||
`act_decision`."""
|
||||
|
||||
line_rule_ids: list[int] = field(default_factory=list)
|
||||
"""The rule behind each of `lines`, in order, when a caller added lines
|
||||
of its own after the arm's; empty means `shown_rule_ids` lines up."""
|
||||
|
||||
def rule_per_line(self) -> list[int]:
|
||||
return list(self.line_rule_ids or self.shown_rule_ids)
|
||||
|
||||
|
||||
# ── The stages ───────────────────────────────────────────────────────────
|
||||
|
||||
@@ -633,9 +597,35 @@ def _telemetry_failed(source: str) -> None:
|
||||
logger.debug("retrieval telemetry failed for %s", source, exc_info=True)
|
||||
|
||||
|
||||
def _gate_preferences(kept: list, gate) -> list:
|
||||
"""`kept` without the preferences the gate turned away; rules untouched."""
|
||||
if gate is None:
|
||||
return kept
|
||||
return [(score, rule) for score, rule in kept
|
||||
if getattr(rule, "kind", None) != "preference" or gate.passes(score)]
|
||||
|
||||
|
||||
def _gate_fields(gate, kept: int) -> dict:
|
||||
"""The call row's record of the gate: its bar and how many lines passed."""
|
||||
if gate is None:
|
||||
return {}
|
||||
return {"gate_bar": gate.bar, "gate_kept": kept}
|
||||
|
||||
|
||||
async def _gate(io, user_id: int, source: str, project_id) -> Any:
|
||||
"""This arm's gate, or None when the door has none or it cannot be read."""
|
||||
if io.gate is None:
|
||||
return None
|
||||
try:
|
||||
return await io.gate(user_id, source, project_id or None)
|
||||
except Exception: # noqa: BLE001 - an unreadable gate leaves the arm as it was
|
||||
logger.debug("cue gate unreadable for %s", source, exc_info=True)
|
||||
return None
|
||||
|
||||
|
||||
async def _ranked(
|
||||
io: RuleIO, moment: RuleMoment, *, source: str, floor: float, limit: int,
|
||||
band: bool = False, kind: str | None = None,
|
||||
band: bool = False, kind: str | None = None, gate=None,
|
||||
) -> tuple[list, list, list]:
|
||||
"""Search, band, split fresh from repeats, and log the call — every call.
|
||||
|
||||
@@ -664,7 +654,14 @@ async def _ranked(
|
||||
# this done" asserts a force the record does not have.
|
||||
hits = [(score, rule) for score, rule in hits
|
||||
if getattr(rule, "kind", None) == kind]
|
||||
if moment.elsewhere:
|
||||
hits = [(score, rule) for score, rule in hits if rule.id not in moment.elsewhere]
|
||||
kept = _rule_band(hits) if band else hits
|
||||
# The gate is part of the cut, like the band: what it turns away is not
|
||||
# shown, so it is not in the row's results either.
|
||||
gated = _gate_preferences(kept, gate)
|
||||
passed = sum(1 for _s, r in gated if getattr(r, "kind", None) == "preference")
|
||||
kept = gated
|
||||
fresh = [(score, rule) for score, rule in kept if rule.id not in moment.exclude]
|
||||
try:
|
||||
io.record_retrieval(
|
||||
@@ -676,6 +673,7 @@ async def _ranked(
|
||||
best_available_id=report.get("best_available_id"),
|
||||
searched=bool(report.get("searched", True)),
|
||||
suppressed=len(hits) - len(fresh),
|
||||
**_gate_fields(gate, passed),
|
||||
)
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(source)
|
||||
@@ -683,7 +681,7 @@ async def _ranked(
|
||||
|
||||
|
||||
async def _reserve_slot_for_preference(
|
||||
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float,
|
||||
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float, gate=None,
|
||||
) -> tuple[list, int | None]:
|
||||
"""Guarantee a preference one slot, if one clears the bar.
|
||||
|
||||
@@ -734,12 +732,12 @@ async def _reserve_slot_for_preference(
|
||||
# ITS OWN SOURCE, and both sides of the trade logged. A slot whose query
|
||||
# is not logged beside the hit it pushed out can never be judged against
|
||||
# what it displaced.
|
||||
found, _kept, _fresh = await _ranked(
|
||||
_found, kept, _fresh = await _ranked(
|
||||
io, moment, source=PREFERENCE_SLOT_SOURCE, floor=floor, limit=1,
|
||||
kind="preference",
|
||||
kind="preference", gate=gate,
|
||||
)
|
||||
seen = {rule.id for _s, rule in hits}
|
||||
slot = [(s, r) for s, r in found
|
||||
slot = [(s, r) for s, r in kept
|
||||
if r.kind == "preference" and r.id not in seen][:1]
|
||||
if not slot:
|
||||
return hits, None
|
||||
@@ -773,6 +771,55 @@ async def _reserve_slot_for_preference(
|
||||
# ── The pipeline ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _record_delivery(io, moment: RuleMoment, source: str, shown: list[tuple[int, str, bool]]) -> None:
|
||||
"""Record each line shown — `(rule_id, at, was_a_repeat)` — as a delivery."""
|
||||
if io.record_delivery is None or not shown:
|
||||
return
|
||||
try:
|
||||
io.record_delivery(moment.user_id, None, source, [
|
||||
(rid, at, "repeat" if repeat else "full") for rid, at, repeat in shown
|
||||
])
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(source)
|
||||
|
||||
|
||||
async def _retired(io, moment: RuleMoment, rules) -> set[int]:
|
||||
"""The rules to leave out because this session has had its reminder.
|
||||
|
||||
A rule's life in a session is one full line, one reminder, then silence,
|
||||
so a long session is not re-pointed at the same rule on every call. Only
|
||||
a repeat can be retired; a rule the session opened keeps its own line,
|
||||
and a rule that holds stays armed until it is opened. {} when the door
|
||||
keeps no deliveries or the read fails.
|
||||
"""
|
||||
if io.retired is None:
|
||||
return set()
|
||||
ids = [
|
||||
rule.id for rule in rules
|
||||
if rule.id in moment.exclude and rule.id not in moment.held
|
||||
and getattr(rule, "enforcement", "inform") != "hold"
|
||||
]
|
||||
if not ids:
|
||||
return set()
|
||||
try:
|
||||
return set(await io.retired(moment.user_id, ids) or ())
|
||||
except Exception: # noqa: BLE001 - a lifecycle read never withholds a fresh line
|
||||
logger.debug("rule retirement unreadable", exc_info=True)
|
||||
return set()
|
||||
|
||||
|
||||
async def _history(io, moment: RuleMoment, pairs: list[tuple[int, str]]) -> dict[int, float]:
|
||||
"""Each rule's open rate where it is about to be delivered; {} when the
|
||||
door has no history to read or the read fails — unknown, never an error."""
|
||||
if io.history is None or not pairs:
|
||||
return {}
|
||||
try:
|
||||
return await io.history(moment.user_id, pairs) or {}
|
||||
except Exception: # noqa: BLE001 - history orders lines, it never withholds them
|
||||
logger.debug("rule delivery history unreadable", exc_info=True)
|
||||
return {}
|
||||
|
||||
|
||||
async def run_rule_arm(
|
||||
arm: RuleArm, moment: RuleMoment, *, floor: float, budget: int, io: RuleIO,
|
||||
checkpoint_floor: float = 0.0,
|
||||
@@ -783,9 +830,13 @@ async def run_rule_arm(
|
||||
surfacing rows → checkpoint. Fails open to an empty result.
|
||||
"""
|
||||
try:
|
||||
gate = (
|
||||
await _gate(io, moment.user_id, arm.source, moment.project_id)
|
||||
if arm.gates_preferences else None
|
||||
)
|
||||
_hits, kept, fresh = await _ranked(
|
||||
io, moment, source=arm.source, floor=floor, limit=budget,
|
||||
band=arm.band, kind=arm.kind,
|
||||
band=arm.band, kind=arm.kind, gate=gate,
|
||||
)
|
||||
shown = kept
|
||||
if arm.preference_slot:
|
||||
@@ -795,12 +846,29 @@ async def run_rule_arm(
|
||||
# preference ranked below that window is invisible to it while a
|
||||
# kind-filtered query finds it at once.
|
||||
shown, _slot_id = await _reserve_slot_for_preference(
|
||||
io, moment, shown, floor=floor,
|
||||
io, moment, shown, floor=floor, gate=gate,
|
||||
)
|
||||
# A repeat already reminded once this session says nothing more.
|
||||
gone = await _retired(io, moment, [rule for _s, rule in shown])
|
||||
if gone:
|
||||
shown = [(s, rule) for s, rule in shown if rule.id not in gone]
|
||||
# `shown`, not `fresh`: a call whose only hit is a repeat
|
||||
# still has something to say, it just says it differently.
|
||||
if not shown:
|
||||
return RuleResult()
|
||||
# Into the one delivery order: a rule that holds outranks one that
|
||||
# informs whatever their scores, and score breaks the last tie.
|
||||
history = await _history(io, moment, [(rule.id, arm.source) for _s, rule in shown])
|
||||
shown = [
|
||||
c.extra for c in rule_order.ordered(
|
||||
rule_order.Candidate(
|
||||
rule=rule, specificity=rule_order.BY_RESEMBLANCE,
|
||||
opened_rate=history.get(rule.id), similarity=score,
|
||||
seen=rule.id in moment.exclude, extra=(score, rule),
|
||||
)
|
||||
for score, rule in shown
|
||||
)
|
||||
]
|
||||
|
||||
lines = [
|
||||
_rule_hint_line(
|
||||
@@ -836,6 +904,11 @@ async def run_rule_arm(
|
||||
)
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(source)
|
||||
# A stop-only arm shows its lines to nobody: only a hold speaks.
|
||||
if not arm.stop_only:
|
||||
_record_delivery(io, moment, source, [
|
||||
(rule.id, source, rule.id in moment.exclude) for _s, rule in shown
|
||||
])
|
||||
return RuleResult(
|
||||
lines=lines, rule_ids=rule_ids,
|
||||
shown_rule_ids=[rule.id for _score, rule in shown],
|
||||
@@ -1062,6 +1135,10 @@ class NoteArm:
|
||||
a record shared one-to-one with the operator."""
|
||||
|
||||
slots: tuple[NoteSlot, ...] = ()
|
||||
gated: bool = False
|
||||
"""Its lines speak only past the cue-swap gate (`cue_gate`), and at most
|
||||
`cue_gate.LINES` of them, slots included."""
|
||||
|
||||
withholds: bool = False
|
||||
"""A menu sits above this arm in the same response, and what it lists is
|
||||
kept out of the search (`exclude_ids`) — same-call duplication, which is a
|
||||
@@ -1073,6 +1150,7 @@ class NoteArm:
|
||||
|
||||
AUTO_INJECT = NoteArm(
|
||||
"auto_inject", surfaced_as="auto_inject", slots=(REUSE_SLOT, LESSON_SLOT),
|
||||
gated=True,
|
||||
tuning=Surface(
|
||||
name="auto_inject",
|
||||
floor_key="kb_autoinject_threshold",
|
||||
@@ -1095,7 +1173,7 @@ AUTO_INJECT = NoteArm(
|
||||
WRITE_PATH = NoteArm(
|
||||
"write_path", surfaced_as="write_path_semantic",
|
||||
note_type=("snippet", "note", LESSON_NOTE_TYPE), task_kind="issue",
|
||||
withholds=True,
|
||||
withholds=True, gated=True,
|
||||
tuning=Surface(
|
||||
name="write_path",
|
||||
floor_key="kb_writepath_threshold",
|
||||
@@ -1148,6 +1226,8 @@ class NoteIO:
|
||||
|
||||
record_retrieval: Callable[..., Any]
|
||||
record_surfaced: Callable[..., Any]
|
||||
gate: Callable[..., Any] | None = None
|
||||
"""`cue_gate.gate_for`, for a gated arm. None leaves the arm ungated."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -1193,6 +1273,9 @@ class NoteResult:
|
||||
slot_ids: dict = field(default_factory=dict)
|
||||
"""{slot source: the id it spent}."""
|
||||
|
||||
gate: Any = None
|
||||
"""The `cue_gate.Gate` this call's lines were held to, or None."""
|
||||
|
||||
|
||||
def _note_band(hits: list) -> list:
|
||||
"""The top hit, plus every hit within `_NOTE_BAND` of it.
|
||||
@@ -1209,7 +1292,7 @@ def _note_band(hits: list) -> list:
|
||||
|
||||
async def _reserve_note_slot(
|
||||
io: NoteIO, arm: NoteArm, slot: NoteSlot, moment: NoteMoment, menu: list,
|
||||
*, floor: float, budget: int, shown: set[int],
|
||||
*, floor: float, budget: int, shown: set[int], capped: bool = False,
|
||||
) -> tuple[list, int | None]:
|
||||
"""Guarantee `slot.kinds` one line, if one clears the arm's own bar.
|
||||
|
||||
@@ -1238,6 +1321,10 @@ async def _reserve_note_slot(
|
||||
"""
|
||||
if any(_record_kind(n) in slot.kinds for _s, n in menu):
|
||||
return menu, None
|
||||
# Under the gate the budget is a ceiling for every line, so a slot that
|
||||
# only extends has no room once the menu is full.
|
||||
if capped and not slot.evicts and len(menu) >= budget:
|
||||
return menu, None
|
||||
|
||||
t0 = time.perf_counter()
|
||||
report: dict = {}
|
||||
@@ -1308,6 +1395,10 @@ async def run_note_arm(
|
||||
band → reserved slots → surfacing rows. Fails open to an empty result.
|
||||
"""
|
||||
try:
|
||||
gate = (
|
||||
await _gate(io, moment.user_id, arm.source, moment.project_id)
|
||||
if arm.gated else None
|
||||
)
|
||||
t0 = time.perf_counter()
|
||||
report: dict = {}
|
||||
scored = moment.in_menu & moment.still_scored
|
||||
@@ -1339,6 +1430,12 @@ async def run_note_arm(
|
||||
(s, n) for s, n in hits
|
||||
if int(n.id) not in moment.seen and int(n.id) not in moment.named
|
||||
]
|
||||
# What the gate lets through, counted before the band and the slots so
|
||||
# the row says how often this arm spoke at all.
|
||||
passed = (
|
||||
min(cue_gate.LINES, sum(1 for s, _n in hits if gate.passes(s)))
|
||||
if gate is not None else 0
|
||||
)
|
||||
source = arm.source
|
||||
try:
|
||||
io.record_retrieval(
|
||||
@@ -1357,21 +1454,34 @@ async def run_note_arm(
|
||||
searched=bool(report.get("searched", True)),
|
||||
suppressed=len(hits) - len(fresh),
|
||||
duration_ms=(time.perf_counter() - t0) * 1000.0,
|
||||
**_gate_fields(gate, passed),
|
||||
)
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(source)
|
||||
result = NoteResult(answered=answered, chunks=report.get("best_chunk") or {})
|
||||
result = NoteResult(
|
||||
answered=answered, chunks=report.get("best_chunk") or {}, gate=gate,
|
||||
)
|
||||
if not hits:
|
||||
return result
|
||||
|
||||
menu = _note_band(hits)
|
||||
if gate is not None:
|
||||
# ABSTAIN BY DEFAULT. A line speaks only past the gate, and at most
|
||||
# the top few do; a cue whose best match is ordinary for this
|
||||
# reader gets nothing, slots included — a slot's candidate scores
|
||||
# no higher than the best hit, so it could not pass either.
|
||||
menu = [(s, n) for s, n in menu if gate.passes(s)][:cue_gate.LINES]
|
||||
if not menu:
|
||||
return result
|
||||
floor = max(floor, gate.bar)
|
||||
budget = min(budget, cue_gate.LINES)
|
||||
# The slots are told about the named records as if already shown, so
|
||||
# a slot that picks one does not book a surfacing the lookup booked.
|
||||
shown = set(moment.seen | moment.named)
|
||||
for slot in arm.slots:
|
||||
menu, slot_id = await _reserve_note_slot(
|
||||
io, arm, slot, moment, menu, floor=floor, budget=budget,
|
||||
shown=shown,
|
||||
shown=shown, capped=gate is not None,
|
||||
)
|
||||
if slot_id is not None:
|
||||
result.slot_ids[slot.source] = slot_id
|
||||
@@ -1597,6 +1707,12 @@ class MomentIO:
|
||||
"""`rulebooks.rules_on_moments`, or a stand-in with its signature."""
|
||||
|
||||
record_rule_surfaced: Callable[..., Any]
|
||||
history: Callable[..., Any] | None = None
|
||||
"""As on `RuleIO`."""
|
||||
record_delivery: Callable[..., Any] | None = None
|
||||
"""As on `RuleIO`."""
|
||||
retired: Callable[..., Any] | None = None
|
||||
"""As on `RuleIO`."""
|
||||
|
||||
|
||||
def _reached_by(hit: dict) -> str:
|
||||
@@ -1606,7 +1722,7 @@ def _reached_by(hit: dict) -> str:
|
||||
|
||||
async def run_moment_arm(
|
||||
reached: list[dict], moment: RuleMoment, *, io: MomentIO,
|
||||
limit: int = MOMENT_RULE_LIMIT,
|
||||
limit: int = MOMENT_RULE_LIMIT, board: Any = None,
|
||||
) -> RuleResult:
|
||||
"""Deliver the rules mounted on the moments this act reached.
|
||||
|
||||
@@ -1617,30 +1733,71 @@ async def run_moment_arm(
|
||||
`unmap_action`. Fresh rules come first and carry their
|
||||
trigger; a rule the session was already shown is cited, not repeated in
|
||||
full. Fails open to an empty result.
|
||||
|
||||
`board` is `rule_triggers.board`'s answer for this act: a conditional
|
||||
mount whose condition the act missed is dropped, one it met ranks as
|
||||
triggered, and a rule an unscoped trigger fired joins the mounted ones
|
||||
with its trigger named as what reached it. None means no triggers.
|
||||
"""
|
||||
try:
|
||||
names = [hit["moment"] for hit in reached]
|
||||
if not names:
|
||||
return RuleResult()
|
||||
pairs = await io.lookup(moment.user_id, names, moment.project_id or None)
|
||||
if not pairs:
|
||||
fired = list(board.fired) if board is not None else []
|
||||
if not names and not fired:
|
||||
return RuleResult()
|
||||
pairs = await io.lookup(moment.user_id, names, moment.project_id or None) if names else []
|
||||
by_moment = {hit["moment"]: hit for hit in reached}
|
||||
# Stable: catalog order within each half, fresh half first.
|
||||
shown = sorted(pairs, key=lambda pair: pair[0].id in moment.exclude)[:limit]
|
||||
# (rule, at, where, specificity) for every candidate line.
|
||||
cands = []
|
||||
for rule, at in pairs or []:
|
||||
if board is not None and (rule.id, at) in board.gated:
|
||||
continue
|
||||
met = board is not None and (rule.id, at) in board.matched
|
||||
cands.append((rule, at, f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
|
||||
rule_order.BY_TRIGGER if met else rule_order.BY_MOUNT))
|
||||
taken = {c[0].id for c in cands}
|
||||
for rule, trig in fired:
|
||||
if rule.id in taken:
|
||||
continue
|
||||
taken.add(rule.id)
|
||||
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
|
||||
rule_order.BY_TRIGGER))
|
||||
# Read before retirement: a rule that enforces does so on every act it
|
||||
# reaches, however often this session has been shown it.
|
||||
decision = act_decision(
|
||||
[(rule, at, where) for rule, at, where, _s in cands], held=moment.held,
|
||||
)
|
||||
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
|
||||
if gone:
|
||||
cands = [c for c in cands if c[0].id not in gone]
|
||||
if not cands:
|
||||
return RuleResult(decision=decision)
|
||||
# The one delivery order (services/rule_order.py), then the cap — so
|
||||
# what a crowded moment drops is the lowest-ranked, not the last
|
||||
# mounted. Ties keep catalog order.
|
||||
history = await _history(io, moment, [(rule.id, at) for rule, at, _w, _s in cands])
|
||||
shown = [
|
||||
c.extra for c in rule_order.ordered(
|
||||
rule_order.Candidate(
|
||||
rule=rule, specificity=spec,
|
||||
opened_rate=history.get(rule.id),
|
||||
seen=rule.id in moment.exclude, extra=(rule, at, where),
|
||||
)
|
||||
for rule, at, where, spec in cands
|
||||
)
|
||||
][:limit]
|
||||
|
||||
lines = []
|
||||
for rule, at in shown:
|
||||
for rule, at, where in shown:
|
||||
seen = rule.id in moment.exclude
|
||||
lines.append(_rule_hint_line(
|
||||
rule,
|
||||
where=f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
|
||||
where=where,
|
||||
seen=seen, held=rule.id in moment.held,
|
||||
# A repeat is cited rather than quoted: the session was told
|
||||
# which moment brought it the first time.
|
||||
compact=seen,
|
||||
))
|
||||
fresh = [(rule, at) for rule, at in shown if rule.id not in moment.exclude]
|
||||
fresh = [(rule, at) for rule, at, _where in shown if rule.id not in moment.exclude]
|
||||
rule_ids = [rule.id for rule, _at in fresh]
|
||||
if rule_ids:
|
||||
try:
|
||||
@@ -1651,11 +1808,90 @@ async def run_moment_arm(
|
||||
)
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
_telemetry_failed(MOMENT_RULE_SOURCE)
|
||||
_record_delivery(io, moment, MOMENT_RULE_SOURCE, [
|
||||
(rule.id, at, rule.id in moment.exclude) for rule, at, _where in shown
|
||||
])
|
||||
return RuleResult(
|
||||
lines=lines, rule_ids=rule_ids,
|
||||
shown_rule_ids=[rule.id for rule, _at in shown],
|
||||
shown=[(None, rule) for rule, _at in shown],
|
||||
shown_rule_ids=[rule.id for rule, _at, _where in shown],
|
||||
shown=[(None, rule) for rule, _at, _where in shown],
|
||||
decision=decision,
|
||||
)
|
||||
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
||||
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
|
||||
return RuleResult()
|
||||
|
||||
|
||||
def act_decision(reached: list[tuple], *, held: frozenset[int] = frozenset()) -> dict:
|
||||
"""What the act itself is told, from the rules its moments and triggers reached.
|
||||
|
||||
`reached` is `(rule, at, where)` for every rule the act reached, in any
|
||||
order. Sync and pure, so it can be read against a fixed list.
|
||||
|
||||
- A rule declared `enforce` REFUSES the act, every time it is reached:
|
||||
`{"kind": "enforce", ...}` with the rules' own words as the reason. It
|
||||
is a boundary the operator drew, and the act is the place it is drawn —
|
||||
reaching it by mount or trigger is a structural fact, never a
|
||||
resemblance. Opening the rule does not lift it; changing the rule does.
|
||||
- Otherwise the first rule declared `hold` that the session has not
|
||||
opened HOLDS the act for one read: `{"kind": "hold", ...}`. The client
|
||||
holds a rule once per session and caps holds per session, as at the act
|
||||
checkpoint.
|
||||
- Otherwise `{}`: the act goes ahead, with any lines beside it.
|
||||
|
||||
A preference never refuses or holds (`rule_order.force`).
|
||||
"""
|
||||
enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"]
|
||||
if enforced:
|
||||
return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced],
|
||||
"reason": enforce_reason(enforced)}
|
||||
for rule, at, where in reached:
|
||||
if rule_order.force(rule) == "hold" and rule.id not in held:
|
||||
return {"kind": "hold", "rule_ids": [rule.id],
|
||||
"reason": hold_reason(rule, at=at, where=where)}
|
||||
return {}
|
||||
|
||||
|
||||
def enforce_reason(enforced: list[tuple]) -> str:
|
||||
"""The text the agent reads instead of the act running, for an `enforce` rule.
|
||||
|
||||
Says which rule drew the line and where, gives its own words, and names
|
||||
who can move it: the operator, by changing the rule. A rule reached by
|
||||
the wrong act is a misfire the reader can record in one call.
|
||||
"""
|
||||
parts = []
|
||||
for rule, at, where in enforced:
|
||||
statement = _statement_excerpt(rule)
|
||||
parts.append(
|
||||
f"“{rule.title}” (Rule {rule.id}, {where})"
|
||||
+ (f": {statement}" if statement else "")
|
||||
)
|
||||
first_rule, first_at, _w = enforced[0]
|
||||
noun = "a rule" if len(enforced) == 1 else "rules"
|
||||
return (
|
||||
f"Not run: this act reaches {noun} the operator set to enforce. "
|
||||
+ " · ".join(parts)
|
||||
+ ". An enforced rule stops the act rather than sitting beside it, and "
|
||||
"opening it does not lift it. If the operator has asked for this act, "
|
||||
"tell them which rule stopped it: they lift it by changing the rule's "
|
||||
"enforcement or its trigger. If the rule has nothing to do with this "
|
||||
f"act, rule_misfired({first_rule.id}, \"{first_at}\", why) records that."
|
||||
)
|
||||
|
||||
|
||||
def hold_reason(rule, *, at: str, where: str) -> str:
|
||||
"""The text the agent reads instead of the act running, for a `hold` rule.
|
||||
|
||||
A practice on the act checkpoint's model: one read, then the act may be
|
||||
re-submitted unchanged.
|
||||
"""
|
||||
trigger = (getattr(rule, "when_to_apply", "") or "").strip()
|
||||
return (
|
||||
f"Held for one read. “{rule.title}” (Rule {rule.id}, {where}) is set to "
|
||||
f"hold the work it governs, and this session has not opened it"
|
||||
+ (f" — it applies when {trigger}" if trigger else "")
|
||||
+ f". Read it with get_rule({rule.id}), then re-submit this call — "
|
||||
"unchanged if the rule does not apply, which is a judgement only you "
|
||||
"can make. If it has nothing to do with this act, "
|
||||
f"rule_misfired({rule.id}, \"{at}\", why) records that."
|
||||
)
|
||||
|
||||
@@ -12,8 +12,8 @@ Settings UI all enumerate THIS table rather than hard-coding special cases.
|
||||
WHAT A FLOOR IS, AND WHAT IT IS NOT
|
||||
|
||||
It is not a relevance judgement. Relevance is decided by the reader, which is
|
||||
the only participant that can read a trigger against a situation — and the
|
||||
injected line says so out loud ("read it before deciding it does not apply").
|
||||
the only participant that can read a rule against a situation, which is why
|
||||
the injected line carries the rule's statement rather than a verdict.
|
||||
|
||||
A floor answers the cheaper question: *is this worth ranking at all*. `k` is
|
||||
what binds, and `k` is a BUDGET — how much of this surface's attention a
|
||||
|
||||
@@ -152,6 +152,8 @@ def _build_payload(
|
||||
suppressed: int | None = None,
|
||||
best_available: float | None = None,
|
||||
best_available_id: int | None = None,
|
||||
gate_bar: float | None = None,
|
||||
gate_kept: int | None = None,
|
||||
) -> dict:
|
||||
"""Reduce a retrieval call to a flat, JSON-safe RetrievalLog payload.
|
||||
|
||||
@@ -200,6 +202,14 @@ def _build_payload(
|
||||
),
|
||||
"result_ids": items,
|
||||
"duration_ms": (round(duration_ms, 2) if duration_ms is not None else None),
|
||||
# The cue-swap gate, on a gated surface: the bar a line had to reach
|
||||
# and how many did. Null bar with a count means the gate could not
|
||||
# judge yet and nothing spoke; both null means the surface is ungated.
|
||||
"gate_bar": (
|
||||
None if gate_bar is None or gate_bar == float("-inf")
|
||||
else round(float(gate_bar), 5)
|
||||
),
|
||||
"gate_kept": None if gate_kept is None else int(gate_kept),
|
||||
}
|
||||
|
||||
|
||||
@@ -239,6 +249,8 @@ def record_retrieval(
|
||||
best_available: float | None = None,
|
||||
best_available_id: int | None = None,
|
||||
searched: bool = True,
|
||||
gate_bar: float | None = None,
|
||||
gate_kept: int | None = None,
|
||||
) -> None:
|
||||
"""Fire-and-forget: record one retrieval call.
|
||||
|
||||
@@ -292,6 +304,8 @@ def record_retrieval(
|
||||
suppressed=suppressed,
|
||||
best_available=best_available,
|
||||
best_available_id=best_available_id,
|
||||
gate_bar=gate_bar,
|
||||
gate_kept=gate_kept,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("retrieval telemetry payload build failed", exc_info=True)
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
"""Each rule line a session is shown, whether it was opened after, and what
|
||||
that history says about where a rule is worth delivering.
|
||||
|
||||
Three calls, one table (`rule_deliveries`):
|
||||
|
||||
- `record` — from the plugin doors that know the session: every line an arm
|
||||
rendered, full or repeat. Within a bound request the rows wait in a buffer
|
||||
until the door's payload is assembled, and `flush` writes only the lines
|
||||
that made it into the payload (`hook_payload.fit`).
|
||||
- `mark_opened` — the session opened a rule: the latest unopened delivery of
|
||||
it in that session gets the stamp. An open with no delivery behind it (the
|
||||
agent looked a rule up unprompted) stamps nothing.
|
||||
- `history` — for the ordering function: each rule's smoothed open rate at
|
||||
the place it is about to be delivered, over the last `HISTORY_DAYS`.
|
||||
|
||||
Deliveries are kept `RETAIN_DAYS` and pruned daily: enough history to rank on
|
||||
and to read adherence from, without a row per tool call accumulating forever.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from contextvars import ContextVar
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import and_, case, delete, func, select, tuple_, update
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.rule_delivery import FORMS, FULL, REPEAT, RuleDelivery
|
||||
from grimoire.services import rule_order
|
||||
from grimoire.services.background import spawn
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
HISTORY_DAYS = 90
|
||||
RETAIN_DAYS = 180
|
||||
# An open counts against a delivery made within this window before it; an
|
||||
# older one was read by a context that is long gone.
|
||||
OPEN_WINDOW = timedelta(hours=6)
|
||||
_SESSION_MAX = 200
|
||||
_UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
|
||||
|
||||
# The session a plugin request is delivering to, bound once per request by the
|
||||
# plugin routes so the arms several calls deep record against it without every
|
||||
# signature between carrying it. Unbound (the MCP door, a test) records nothing.
|
||||
_session: ContextVar[str] = ContextVar("rule_delivery_session", default="")
|
||||
# Rows rendered during the bound request, written by `flush`.
|
||||
_pending: ContextVar[list | None] = ContextVar("rule_delivery_pending", default=None)
|
||||
|
||||
|
||||
def bind_session(session_id: str | None) -> None:
|
||||
_session.set(_clean_session(session_id))
|
||||
_pending.set([])
|
||||
|
||||
|
||||
def flush(kept: set[int] | None = None) -> None:
|
||||
"""Write this request's buffered rows: those for rules in `kept`, or all
|
||||
of them when `kept` is None. Rows for a line the payload left out are
|
||||
dropped, since the session was never shown it."""
|
||||
rows = _pending.get()
|
||||
if not rows:
|
||||
return
|
||||
_pending.set([])
|
||||
if kept is not None:
|
||||
rows = [r for r in rows if r["rule_id"] in kept]
|
||||
if rows:
|
||||
spawn(_insert(rows), site="rule_delivery_write")
|
||||
|
||||
|
||||
def bound() -> bool:
|
||||
"""Whether this request delivers to a known session — the doors that
|
||||
record deliveries are the ones that read their history back."""
|
||||
return bool(_session.get())
|
||||
|
||||
|
||||
def _clean_session(session_id: str | None) -> str:
|
||||
# The plugin's own filename-safe form of the id, so a hook that sends the
|
||||
# raw id and one that sends the safe one name the same session.
|
||||
return _UNSAFE.sub("_", (session_id or "").strip())[:_SESSION_MAX]
|
||||
|
||||
|
||||
def record(
|
||||
user_id: int, session_id: str | None, source: str,
|
||||
lines: list[tuple[int, str, str]],
|
||||
) -> None:
|
||||
"""Record delivered lines: `(rule_id, at, form)` each. A no-op without a
|
||||
session, since an open could never be tied back. `session_id` None means
|
||||
the one bound for this request, whose rows wait for `flush`."""
|
||||
sid = _clean_session(_session.get() if session_id is None else session_id)
|
||||
if not sid or not lines:
|
||||
return
|
||||
try:
|
||||
rows = [
|
||||
{"user_id": int(user_id), "session_id": sid, "rule_id": int(rid),
|
||||
"source": source, "at": str(at or source), "form": form if form in FORMS else FULL}
|
||||
for rid, at, form in lines
|
||||
]
|
||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||
logger.debug("rule delivery payload build failed", exc_info=True)
|
||||
return
|
||||
pending = _pending.get() if session_id is None else None
|
||||
if pending is not None:
|
||||
pending.extend(rows)
|
||||
return
|
||||
spawn(_insert(rows), site="rule_delivery_write")
|
||||
|
||||
|
||||
async def _insert(rows: list[dict]) -> None:
|
||||
async with async_session() as session:
|
||||
session.add_all(RuleDelivery(**row) for row in rows)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def mark_opened(user_id: int, session_id: str | None, rule_id: int) -> bool:
|
||||
"""Stamp the latest unopened delivery of this rule in this session.
|
||||
|
||||
Returns whether a delivery was stamped. Only that one: a rule delivered
|
||||
five times and opened once was opened after the fifth line, and the four
|
||||
before it were passed over.
|
||||
"""
|
||||
sid = _clean_session(session_id)
|
||||
if not sid or not rule_id:
|
||||
return False
|
||||
now = datetime.now(timezone.utc)
|
||||
async with async_session() as session:
|
||||
latest = (await session.execute(
|
||||
select(RuleDelivery.id)
|
||||
.where(
|
||||
RuleDelivery.user_id == user_id,
|
||||
RuleDelivery.session_id == sid,
|
||||
RuleDelivery.rule_id == rule_id,
|
||||
RuleDelivery.opened_at.is_(None),
|
||||
RuleDelivery.delivered_at >= now - OPEN_WINDOW,
|
||||
)
|
||||
.order_by(RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc())
|
||||
.limit(1)
|
||||
)).scalar_one_or_none()
|
||||
if latest is None:
|
||||
return False
|
||||
await session.execute(
|
||||
update(RuleDelivery).where(RuleDelivery.id == latest).values(opened_at=now)
|
||||
)
|
||||
await session.commit()
|
||||
return True
|
||||
|
||||
|
||||
async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float]:
|
||||
"""`{rule_id: smoothed open rate}` at each pair's place, for this user.
|
||||
|
||||
A rule with no delivery there is left out, which the ordering reads as
|
||||
unknown rather than as never opened.
|
||||
"""
|
||||
wanted = list(dict.fromkeys((int(rid), str(at)) for rid, at in pairs))
|
||||
if not wanted:
|
||||
return {}
|
||||
since = datetime.now(timezone.utc) - timedelta(days=HISTORY_DAYS)
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(
|
||||
RuleDelivery.rule_id, RuleDelivery.at,
|
||||
func.count(RuleDelivery.id),
|
||||
func.sum(case((RuleDelivery.opened_at.is_not(None), 1), else_=0)),
|
||||
)
|
||||
.where(
|
||||
RuleDelivery.user_id == user_id,
|
||||
RuleDelivery.delivered_at >= since,
|
||||
tuple_(RuleDelivery.rule_id, RuleDelivery.at).in_(wanted),
|
||||
)
|
||||
.group_by(RuleDelivery.rule_id, RuleDelivery.at)
|
||||
)).all()
|
||||
return {
|
||||
int(rid): rule_order.opened_rate(int(delivered), int(opened or 0))
|
||||
for rid, _at, delivered, opened in rows
|
||||
}
|
||||
|
||||
|
||||
async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
|
||||
"""Which of these rules this session has already been reminded of.
|
||||
|
||||
A rule's life in a session is one full line, then one reminder, then
|
||||
silence: retired is "the latest delivery of it in the bound session was a
|
||||
reminder". A full delivery re-arms it, which is what happens once the
|
||||
plugin's ledger forgets it (after a compaction, or as it ages out): the
|
||||
next line is full again, then one reminder, then silence again.
|
||||
"""
|
||||
sid = _session.get()
|
||||
wanted = sorted({int(r) for r in rule_ids})
|
||||
if not sid or not wanted:
|
||||
return set()
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(RuleDelivery.rule_id, RuleDelivery.form)
|
||||
.where(
|
||||
RuleDelivery.user_id == user_id,
|
||||
RuleDelivery.session_id == sid,
|
||||
RuleDelivery.rule_id.in_(wanted),
|
||||
)
|
||||
.distinct(RuleDelivery.rule_id)
|
||||
.order_by(RuleDelivery.rule_id, RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc())
|
||||
)).all()
|
||||
return {int(rid) for rid, form in rows if form == REPEAT}
|
||||
|
||||
|
||||
async def prune(retain_days: int = RETAIN_DAYS) -> int:
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
|
||||
async with async_session() as session:
|
||||
result = await session.execute(
|
||||
delete(RuleDelivery).where(and_(RuleDelivery.delivered_at < cutoff))
|
||||
)
|
||||
await session.commit()
|
||||
return int(result.rowcount or 0)
|
||||
|
||||
|
||||
_prune_task = None
|
||||
|
||||
|
||||
async def _prune_tick() -> None:
|
||||
try:
|
||||
removed = await prune()
|
||||
if removed:
|
||||
logger.info("Rule delivery retention: deleted %d row(s)", removed)
|
||||
except Exception:
|
||||
logger.exception("Rule delivery retention failed")
|
||||
|
||||
|
||||
def start_prune_loop() -> None:
|
||||
global _prune_task
|
||||
if _prune_task is None or _prune_task.done():
|
||||
from grimoire.services.background import start_periodic
|
||||
_prune_task = start_periodic(86400, _prune_tick, label="rule_delivery_retention") # daily
|
||||
@@ -0,0 +1,103 @@
|
||||
"""The one order in which rules reach a moment.
|
||||
|
||||
Every arm that puts rules in front of a session — the rules mounted on a
|
||||
moment, the rules a typed trigger matched, the rules a semantic search found —
|
||||
ranks what it has the same way, so a crowded moment drops the same rules
|
||||
whichever arm brought them:
|
||||
|
||||
1. **enforcement** — `enforce`, then `hold`, then `inform`. A rule that stops
|
||||
the work is never the one cut to make room for a line beside it.
|
||||
2. **salience** — `high`, `normal`, `low`, as the rule's author declared it.
|
||||
3. **specificity** — how narrowly the rule was reached. A trigger that named
|
||||
this command or this path says more than a mount on the whole moment, and a
|
||||
mount says more than a resemblance.
|
||||
4. **news** — at the same rank, a rule this session has not been shown yet
|
||||
comes before one it has, so a cap cuts a reminder rather than a first
|
||||
mention.
|
||||
5. **history** — how often this rule was opened when delivered at this
|
||||
moment before. A rule sessions keep opening here outranks one they keep
|
||||
passing over.
|
||||
6. **similarity** — the search score, when there is one. Last, because it is
|
||||
the one signal that says what the work resembles rather than what it is.
|
||||
|
||||
Each key is a declared or recorded fact, read in that order, so the outcome
|
||||
can be explained line by line: "it outranked that one because it holds".
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
ENFORCEMENT_RANK = {"enforce": 0, "hold": 1, "inform": 2}
|
||||
SALIENCE_RANK = {"high": 0, "normal": 1, "low": 2}
|
||||
|
||||
|
||||
def force(rule: Any) -> str:
|
||||
"""What this rule does when it arrives: `enforce`, `hold` or `inform`.
|
||||
|
||||
A preference is always `inform`, whatever the field says: it records how
|
||||
work is liked, and claims no force that could stop it.
|
||||
"""
|
||||
if getattr(rule, "kind", None) == "preference":
|
||||
return "inform"
|
||||
value = getattr(rule, "enforcement", None)
|
||||
return value if value in ENFORCEMENT_RANK else "inform"
|
||||
|
||||
|
||||
def holds(rule: Any) -> bool:
|
||||
"""Whether this rule may make a reply or an act wait for one read.
|
||||
|
||||
Only a rule declared `hold` or `enforce` may. Every other rule is a line
|
||||
beside the work: holding the work on a rule nobody declared as one that
|
||||
holds made each reply after a write cost a rewrite, for rules that asked
|
||||
only to be read.
|
||||
"""
|
||||
return force(rule) in ("enforce", "hold")
|
||||
|
||||
# How narrowly a rule was reached, larger is narrower.
|
||||
BY_RESEMBLANCE = 0
|
||||
BY_MOUNT = 1
|
||||
BY_TRIGGER = 2
|
||||
|
||||
# A rule with no delivery history at a moment ranks as if half its deliveries
|
||||
# there were opened: unknown is neither proof of use nor of neglect.
|
||||
UNKNOWN_HISTORY = 0.5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Candidate:
|
||||
"""One rule an arm could deliver, with what it knows about how it got here."""
|
||||
|
||||
rule: Any
|
||||
specificity: int = BY_RESEMBLANCE
|
||||
opened_rate: float | None = None
|
||||
"""Share of this rule's earlier deliveries at this moment that were opened."""
|
||||
similarity: float | None = None
|
||||
seen: bool = False
|
||||
"""Already shown to this session."""
|
||||
extra: Any = None
|
||||
"""Whatever the arm needs back with the rule — the moment it was mounted
|
||||
on, its score pair — carried through the sort untouched."""
|
||||
|
||||
|
||||
def order_key(c: Candidate) -> tuple:
|
||||
rule = c.rule
|
||||
return (
|
||||
ENFORCEMENT_RANK.get(getattr(rule, "enforcement", None) or "inform", 2),
|
||||
SALIENCE_RANK.get(getattr(rule, "salience", None) or "normal", 1),
|
||||
-c.specificity,
|
||||
c.seen,
|
||||
-(UNKNOWN_HISTORY if c.opened_rate is None else c.opened_rate),
|
||||
-(c.similarity or 0.0),
|
||||
)
|
||||
|
||||
|
||||
def ordered(candidates: Iterable[Candidate]) -> list[Candidate]:
|
||||
"""The candidates in delivery order. Stable: ties keep the arm's own order."""
|
||||
return sorted(candidates, key=order_key)
|
||||
|
||||
|
||||
def opened_rate(delivered: int, opened: int) -> float:
|
||||
"""A smoothed open rate, so one delivery opened once does not read as certainty."""
|
||||
return (opened + 1) / (delivered + 2)
|
||||
@@ -0,0 +1,289 @@
|
||||
"""A rule's triggers: typed predicates on the act, checked in code.
|
||||
|
||||
A mount says WHEN a rule applies (a moment of work); a trigger says WHAT act
|
||||
it applies to, in terms the act itself carries, so it is matched exactly and
|
||||
never by resemblance:
|
||||
|
||||
- `tool` — the tool called, as its key (`bash`, `write`, `update_task`); a
|
||||
`*` in the pattern matches any run of characters (`*_task`).
|
||||
- `path` — a file the act touches (`file_path`, `path`, `notebook_path`),
|
||||
against a glob: `*` within one directory, `**` across directories, `?` one
|
||||
character. A glob without a leading `/` matches from any directory, so
|
||||
`migrations/*.py` matches `/repo/alembic/migrations/0001.py`.
|
||||
- `command` — the head of a command the act runs, segment by segment, the way
|
||||
moment mappings match it: `git push` matches `git push origin dev` and
|
||||
`make && git push`, not `git pushx`.
|
||||
- `keyword` — a word or phrase in the command, the content written or the
|
||||
reply, matched whole and case-insensitively.
|
||||
|
||||
A trigger with no moment delivers its rule on any act that matches it. A
|
||||
trigger scoped to a moment makes the rule's mount on that moment conditional:
|
||||
the mount delivers only on an act that matches one of its triggers there, so
|
||||
a rule about migrations can sit on `work.change` without arriving at every
|
||||
edit. Where no act is known (the turn's own reply), only keyword triggers can
|
||||
be checked, against the reply text.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from sqlalchemy import delete, select
|
||||
|
||||
from grimoire.models import async_session
|
||||
from grimoire.services import moment_actions
|
||||
|
||||
TOOL, PATH, COMMAND, KEYWORD = "tool", "path", "command", "keyword"
|
||||
KINDS = (TOOL, PATH, COMMAND, KEYWORD)
|
||||
PATTERN_MAX = 200
|
||||
TRIGGERS_MAX = 20
|
||||
|
||||
# The input fields a path trigger reads, across the file tools.
|
||||
PATH_FIELDS = ("file_path", "path", "notebook_path")
|
||||
# The input fields a keyword trigger reads.
|
||||
TEXT_FIELDS = ("command", "content", "new_string", "query", "prompt")
|
||||
# The tools a path, command or keyword trigger can be reached through — what
|
||||
# the plugin's catch-all hook must forward for such a trigger to be checked.
|
||||
PATH_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit", "read"})
|
||||
COMMAND_TOOLS = moment_actions.COMMAND_TOOLS
|
||||
KEYWORD_TOOLS = COMMAND_TOOLS | frozenset({"write", "edit", "multiedit", "notebookedit"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Trigger:
|
||||
kind: str
|
||||
pattern: str
|
||||
moment: str = ""
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
out = {"kind": self.kind, "pattern": self.pattern}
|
||||
if self.moment:
|
||||
out["moment"] = self.moment
|
||||
return out
|
||||
|
||||
def describe(self) -> str:
|
||||
"""How a delivered line names what fired: "path `alembic/**`"."""
|
||||
return f"{self.kind} `{self.pattern}`"
|
||||
|
||||
@property
|
||||
def key(self) -> str:
|
||||
"""Where a trigger delivers, for the delivery record and its history."""
|
||||
return f"{self.kind}:{self.pattern}"
|
||||
|
||||
|
||||
# ── validation ───────────────────────────────────────────────────────────
|
||||
|
||||
def require_trigger(raw) -> Trigger:
|
||||
"""One trigger, normalised, or a refusal that says what is accepted."""
|
||||
from grimoire.services.moments import require_moment
|
||||
|
||||
if not isinstance(raw, dict):
|
||||
raise ValueError("a trigger is {kind, pattern, moment?}")
|
||||
kind = str(raw.get("kind") or "").strip().lower()
|
||||
if kind not in KINDS:
|
||||
raise ValueError(f"unknown trigger kind {raw.get('kind')!r}. Kinds are: {', '.join(KINDS)}")
|
||||
pattern = " ".join(str(raw.get("pattern") or "").split())
|
||||
if not pattern:
|
||||
raise ValueError(f"a {kind} trigger needs a pattern")
|
||||
if len(pattern) > PATTERN_MAX:
|
||||
raise ValueError(f"a trigger pattern is at most {PATTERN_MAX} characters")
|
||||
if kind == TOOL:
|
||||
pattern = moment_actions.tool_key(pattern)
|
||||
elif kind in (COMMAND, KEYWORD):
|
||||
pattern = pattern.lower()
|
||||
moment = str(raw.get("moment") or "").strip()
|
||||
return Trigger(kind, pattern, require_moment(moment) if moment else "")
|
||||
|
||||
|
||||
def require_triggers(raw) -> list[Trigger] | None:
|
||||
"""A rule's triggers, or the first refusal. None leaves them alone; a
|
||||
list, [] included, is the whole set after the write. All are checked
|
||||
before any is stored."""
|
||||
if raw is None:
|
||||
return None
|
||||
if not isinstance(raw, list):
|
||||
raise ValueError("triggers is a list of {kind, pattern, moment?}")
|
||||
out = list(dict.fromkeys(require_trigger(item) for item in raw))
|
||||
if len(out) > TRIGGERS_MAX:
|
||||
raise ValueError(f"a rule carries at most {TRIGGERS_MAX} triggers")
|
||||
return out
|
||||
|
||||
|
||||
# ── matching ─────────────────────────────────────────────────────────────
|
||||
|
||||
def _glob(pattern: str) -> re.Pattern:
|
||||
out, i = [], 0
|
||||
while i < len(pattern):
|
||||
if pattern.startswith("**/", i):
|
||||
out.append("(?:.*/)?")
|
||||
i += 3
|
||||
elif pattern.startswith("**", i):
|
||||
out.append(".*")
|
||||
i += 2
|
||||
elif pattern[i] == "*":
|
||||
out.append("[^/]*")
|
||||
i += 1
|
||||
elif pattern[i] == "?":
|
||||
out.append("[^/]")
|
||||
i += 1
|
||||
else:
|
||||
out.append(re.escape(pattern[i]))
|
||||
i += 1
|
||||
body = "".join(out)
|
||||
anchor = "^" if pattern.startswith("/") else "(?:^|/)"
|
||||
return re.compile(anchor + body + "$")
|
||||
|
||||
|
||||
def _tool_glob(pattern: str) -> re.Pattern:
|
||||
return re.compile("^" + ".*".join(re.escape(p) for p in pattern.split("*")) + "$")
|
||||
|
||||
|
||||
def _texts(tool_input: dict) -> list[str]:
|
||||
return [v for k in TEXT_FIELDS if isinstance(v := tool_input.get(k), str)]
|
||||
|
||||
|
||||
def _has_phrase(text: str, phrase: str) -> bool:
|
||||
return re.search(r"(?<!\w)" + re.escape(phrase) + r"(?!\w)", text, re.IGNORECASE) is not None
|
||||
|
||||
|
||||
def matches(trigger: Trigger, tool: str | None, tool_input: dict | None, text: str = "") -> bool:
|
||||
"""Whether this act — or, with no tool, this text — fires the trigger."""
|
||||
tool_input = tool_input if isinstance(tool_input, dict) else {}
|
||||
if trigger.kind == KEYWORD:
|
||||
return any(_has_phrase(t, trigger.pattern) for t in [text, *_texts(tool_input)] if t)
|
||||
if not tool:
|
||||
return False
|
||||
if trigger.kind == TOOL:
|
||||
return _tool_glob(trigger.pattern).match(moment_actions.tool_key(tool)) is not None
|
||||
if trigger.kind == PATH:
|
||||
rx = _glob(trigger.pattern)
|
||||
return any(isinstance(p := tool_input.get(f), str) and rx.search(p) for f in PATH_FIELDS)
|
||||
if trigger.kind == COMMAND:
|
||||
command = tool_input.get(moment_actions.COMMAND_FIELD)
|
||||
return moment_actions.action_matches(
|
||||
moment_actions.Action(tool=tool, match=trigger.pattern, moment=""),
|
||||
tool, {moment_actions.COMMAND_FIELD: command},
|
||||
) if isinstance(command, str) else False
|
||||
return False
|
||||
|
||||
|
||||
def tools_for(trigger: Trigger) -> set[str]:
|
||||
"""The tool keys an act must be made through for this trigger to fire.
|
||||
A tool pattern with a `*` cannot be listed, and reaches nothing here."""
|
||||
if trigger.kind == TOOL:
|
||||
return set() if "*" in trigger.pattern else {trigger.pattern}
|
||||
if trigger.kind == PATH:
|
||||
return set(PATH_TOOLS)
|
||||
if trigger.kind == COMMAND:
|
||||
return set(COMMAND_TOOLS)
|
||||
return set(KEYWORD_TOOLS)
|
||||
|
||||
|
||||
# ── storage ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def set_rule_triggers(rule_id: int, triggers: list[Trigger]) -> None:
|
||||
"""Replace a rule's triggers with these. The caller has checked write access."""
|
||||
from grimoire.models.rulebook import rule_triggers as t
|
||||
|
||||
async with async_session() as session:
|
||||
await session.execute(delete(t).where(t.c.rule_id == rule_id))
|
||||
if triggers:
|
||||
await session.execute(t.insert(), [
|
||||
{"rule_id": rule_id, "kind": tr.kind, "pattern": tr.pattern, "moment": tr.moment}
|
||||
for tr in triggers
|
||||
])
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def list_rule_triggers(rule_ids: list[int]) -> dict[int, list[dict]]:
|
||||
"""Each rule's triggers, unscoped first, in a stable order."""
|
||||
from grimoire.models.rulebook import rule_triggers as t
|
||||
|
||||
if not rule_ids:
|
||||
return {}
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
select(t.c.rule_id, t.c.kind, t.c.pattern, t.c.moment)
|
||||
.where(t.c.rule_id.in_(rule_ids))
|
||||
.order_by(t.c.rule_id, t.c.moment, t.c.kind, t.c.pattern)
|
||||
)).all()
|
||||
out: dict[int, list[dict]] = {}
|
||||
for rule_id, kind, pattern, moment in rows:
|
||||
out.setdefault(rule_id, []).append(Trigger(kind, pattern, moment or "").to_dict())
|
||||
return out
|
||||
|
||||
|
||||
async def _in_scope(user_id: int, project_id: int | None, *, everywhere: bool = False):
|
||||
"""Every live rule with a trigger that this caller may be shown here, with
|
||||
its triggers: `[(Rule, [Trigger, ...])]`."""
|
||||
from grimoire.models.rulebook import Rule
|
||||
from grimoire.models.rulebook import rule_triggers as t
|
||||
from grimoire.services.rule_scope import joined_to_homes, rule_home
|
||||
|
||||
home = await rule_home(user_id, project_id, everywhere=everywhere)
|
||||
async with async_session() as session:
|
||||
rows = (await session.execute(
|
||||
joined_to_homes(
|
||||
select(Rule, t.c.kind, t.c.pattern, t.c.moment)
|
||||
.select_from(t)
|
||||
.join(Rule, Rule.id == t.c.rule_id)
|
||||
)
|
||||
.where(Rule.deleted_at.is_(None), home)
|
||||
.order_by(Rule.id, t.c.kind, t.c.pattern)
|
||||
)).all()
|
||||
by_rule: dict[int, tuple] = {}
|
||||
for rule, kind, pattern, moment in rows:
|
||||
by_rule.setdefault(rule.id, (rule, []))[1].append(Trigger(kind, pattern, moment or ""))
|
||||
return list(by_rule.values())
|
||||
|
||||
|
||||
# ── the eligibility board ────────────────────────────────────────────────
|
||||
|
||||
@dataclass
|
||||
class Board:
|
||||
"""What the triggers say about one act, for the moment arm.
|
||||
|
||||
`gated` — (rule_id, moment) mounts that are conditional and whose
|
||||
condition this act did not meet: not delivered. `matched` — conditional
|
||||
mounts this act met: delivered as triggered. `fired` — rules an unscoped
|
||||
trigger delivers on this act, each with the trigger that fired.
|
||||
"""
|
||||
|
||||
gated: set[tuple[int, str]] = field(default_factory=set)
|
||||
matched: set[tuple[int, str]] = field(default_factory=set)
|
||||
fired: list[tuple[object, Trigger]] = field(default_factory=list)
|
||||
|
||||
|
||||
async def board(
|
||||
user_id: int, project_id: int | None, *,
|
||||
tool: str | None = None, tool_input: dict | None = None, text: str = "",
|
||||
) -> Board:
|
||||
"""Check every in-scope trigger against this act (or this text)."""
|
||||
out = Board()
|
||||
for rule, triggers in await _in_scope(user_id, project_id):
|
||||
first_unscoped = None
|
||||
for trig in triggers:
|
||||
hit = matches(trig, tool, tool_input, text)
|
||||
if trig.moment:
|
||||
pair = (rule.id, trig.moment)
|
||||
if hit:
|
||||
out.matched.add(pair)
|
||||
out.gated.discard(pair)
|
||||
elif pair not in out.matched:
|
||||
out.gated.add(pair)
|
||||
elif hit and first_unscoped is None:
|
||||
first_unscoped = trig
|
||||
if first_unscoped is not None:
|
||||
out.fired.append((rule, first_unscoped))
|
||||
return out
|
||||
|
||||
|
||||
async def reachable_tools(user_id: int) -> set[str]:
|
||||
"""The tool keys a call to which could fire an unscoped trigger, in any
|
||||
home — a superset, for the plugin's catch-all filter."""
|
||||
keys: set[str] = set()
|
||||
for _rule, triggers in await _in_scope(user_id, None, everywhere=True):
|
||||
for trig in triggers:
|
||||
if not trig.moment:
|
||||
keys |= tools_for(trig)
|
||||
return keys
|
||||
@@ -273,6 +273,38 @@ RELATION_KINDS = ("co_surfaces", "overrides", "elaborates")
|
||||
# Migration 0098's CHECK. `rule` binds; `preference` is how the operator
|
||||
# wants work done — see the model comment for why both live on one table.
|
||||
KINDS = ("rule", "preference")
|
||||
# Migration 0128's CHECKs, strongest first — the order the ordering function
|
||||
# ranks them in (services/rule_order.py).
|
||||
ENFORCEMENTS = ("enforce", "hold", "inform")
|
||||
SALIENCES = ("high", "normal", "low")
|
||||
|
||||
|
||||
def require_enforcement(enforcement: str | None, kind: str | None) -> str:
|
||||
"""The enforcement a rule of this kind may carry, or a refusal naming the choices.
|
||||
|
||||
Unlike `kind`, an unknown enforcement is refused rather than mapped: there is no
|
||||
safe direction to fall in. Mapped up, a typo turns a line into a stop;
|
||||
mapped down, it turns a stop into a line. A preference is always `inform`
|
||||
— it says how work is liked done, and a stop would claim a force it does
|
||||
not have.
|
||||
"""
|
||||
clean = (enforcement or "inform").strip().lower()
|
||||
if clean not in ENFORCEMENTS:
|
||||
raise ValueError(f"enforcement must be one of {', '.join(ENFORCEMENTS)}, got {enforcement!r}")
|
||||
if (kind or "rule") == "preference" and clean != "inform":
|
||||
raise ValueError(
|
||||
"a preference's enforcement is always `inform`: it says how work is liked "
|
||||
"done, and holding or enforcing it would make it a rule. Record it "
|
||||
"as a rule if it must stop the work."
|
||||
)
|
||||
return clean
|
||||
|
||||
|
||||
def require_salience(salience: str | None) -> str:
|
||||
clean = (salience or "normal").strip().lower()
|
||||
if clean not in SALIENCES:
|
||||
raise ValueError(f"salience must be one of {', '.join(SALIENCES)}, got {salience!r}")
|
||||
return clean
|
||||
|
||||
|
||||
# The rule columns that are nullable, and therefore the ones where EMPTY has
|
||||
@@ -339,8 +371,14 @@ def rule_brief(rule: Rule, **extra) -> dict:
|
||||
# one, and the assumption it would reach for — "this binds" — is the
|
||||
# expensive one to get wrong in the other direction. Say it outright.
|
||||
"kind": rule.kind or "rule",
|
||||
# Unconditional for the same reason as `kind`: whether a rule stops
|
||||
# the work is never something a reader should have to assume.
|
||||
"enforcement": rule.enforcement or "inform",
|
||||
"updated_at": rule.updated_at.date().isoformat() if rule.updated_at else None,
|
||||
}
|
||||
# Salience is attached only when the author raised or lowered it.
|
||||
if (rule.salience or "normal") != "normal":
|
||||
out["salience"] = rule.salience
|
||||
# Attached only when present: never a null key that reads as a
|
||||
# capability the record doesn't have.
|
||||
if rule.when_to_apply:
|
||||
@@ -432,9 +470,9 @@ async def co_surfaced_partners(user_id: int, rule_ids: list[int]) -> list[Rule]:
|
||||
|
||||
async def rule_detail(
|
||||
user_id: int, rule: Rule, system_ids: list[int] | None = None,
|
||||
moments: list[str] | None = None,
|
||||
moments: list[str] | None = None, triggers: list | None = None,
|
||||
) -> dict:
|
||||
"""The full record, with its areas, moments and edges attached.
|
||||
"""The full record, with its areas, moments, triggers and edges attached.
|
||||
|
||||
ONE seam for both doors and every write path, so create, update and get
|
||||
cannot disagree about what a rule looks like coming back — the same
|
||||
@@ -444,15 +482,21 @@ async def rule_detail(
|
||||
`system_ids=None` / `moments=None` mean "leave them alone"; a list
|
||||
(including []) REPLACES them. Doors validate `moments` with
|
||||
`moments.require_moments` BEFORE their create, so an unknown name is
|
||||
refused without leaving a rule behind.
|
||||
refused without leaving a rule behind; `triggers` the same way, with
|
||||
`rule_triggers.require_triggers`, and it replaces them the same way.
|
||||
"""
|
||||
from grimoire.services import rule_triggers
|
||||
|
||||
if system_ids is not None:
|
||||
await set_rule_systems(rule.id, user_id, system_ids)
|
||||
if moments is not None:
|
||||
await set_rule_moments(rule.id, user_id, moments)
|
||||
if triggers is not None:
|
||||
await rule_triggers.set_rule_triggers(rule.id, triggers)
|
||||
data = rule.to_dict()
|
||||
systems = (await list_rule_systems([rule.id])).get(rule.id, [])
|
||||
mounted = (await list_rule_moments([rule.id])).get(rule.id, [])
|
||||
triggered = (await rule_triggers.list_rule_triggers([rule.id])).get(rule.id, [])
|
||||
relations = (await list_rule_relations([rule.id])).get(rule.id, [])
|
||||
# Attached only when present: an empty key reads as a capability
|
||||
# the record has and isn't using, which is a different claim.
|
||||
@@ -460,6 +504,8 @@ async def rule_detail(
|
||||
data["systems"] = systems
|
||||
if mounted:
|
||||
data["moments"] = mounted
|
||||
if triggered:
|
||||
data["triggers"] = triggered
|
||||
if relations:
|
||||
data["relations"] = relations
|
||||
# The concrete situations judged (or proposed) to be instances of this
|
||||
@@ -506,8 +552,12 @@ async def create_rule(
|
||||
why: str = "", how_to_apply: str = "", order_index: int = 0,
|
||||
when_to_apply: str = "", arose_from_id: int = 0,
|
||||
verify_with: str = "", expires_when: str = "", kind: str = "rule",
|
||||
enforcement: str = "inform", salience: str = "normal",
|
||||
) -> Rule:
|
||||
_require_trigger(when_to_apply)
|
||||
kind = _valid_kind(kind)
|
||||
enforcement = require_enforcement(enforcement, kind)
|
||||
salience = require_salience(salience)
|
||||
async with async_session() as session:
|
||||
await _assert_topic_owned(session, topic_id, user_id)
|
||||
rule = Rule(
|
||||
@@ -515,7 +565,7 @@ async def create_rule(
|
||||
title=title,
|
||||
statement=statement,
|
||||
when_to_apply=when_to_apply or None,
|
||||
kind=_valid_kind(kind),
|
||||
kind=kind, enforcement=enforcement, salience=salience,
|
||||
why=why or None,
|
||||
how_to_apply=how_to_apply or None,
|
||||
verify_with=verify_with or None,
|
||||
@@ -535,6 +585,7 @@ async def create_project_rule(
|
||||
why: str = "", how_to_apply: str = "", order_index: int = 0,
|
||||
when_to_apply: str = "", arose_from_id: int = 0,
|
||||
verify_with: str = "", expires_when: str = "", kind: str = "rule",
|
||||
enforcement: str = "inform", salience: str = "normal",
|
||||
) -> Rule:
|
||||
"""Create a rule scoped to a single project (no rulebook ceremony).
|
||||
|
||||
@@ -544,6 +595,9 @@ async def create_project_rule(
|
||||
constraint enforces exactly-one of (topic_id, project_id).
|
||||
"""
|
||||
_require_trigger(when_to_apply)
|
||||
kind = _valid_kind(kind)
|
||||
enforcement = require_enforcement(enforcement, kind)
|
||||
salience = require_salience(salience)
|
||||
async with async_session() as session:
|
||||
await _assert_project_owned(session, project_id, user_id)
|
||||
rule = Rule(
|
||||
@@ -551,7 +605,7 @@ async def create_project_rule(
|
||||
title=title,
|
||||
statement=statement,
|
||||
when_to_apply=when_to_apply or None,
|
||||
kind=_valid_kind(kind),
|
||||
kind=kind, enforcement=enforcement, salience=salience,
|
||||
why=why or None,
|
||||
how_to_apply=how_to_apply or None,
|
||||
verify_with=verify_with or None,
|
||||
@@ -691,7 +745,7 @@ async def update_rule(
|
||||
allowed = {
|
||||
"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",
|
||||
}
|
||||
check_before = rule.verify_with
|
||||
# A create-time guard is worth nothing if an edit can undo it, and
|
||||
@@ -719,6 +773,11 @@ async def update_rule(
|
||||
continue
|
||||
if key == "kind":
|
||||
value = _valid_kind(value)
|
||||
elif key == "salience":
|
||||
value = require_salience(value)
|
||||
elif key == "enforcement":
|
||||
# Checked against the kind after the loop, which may change it.
|
||||
value = (value or "").strip().lower() or "inform"
|
||||
elif key in NULLABLE_RULE_TEXT:
|
||||
value = value or None
|
||||
elif key == "arose_from_id":
|
||||
@@ -731,6 +790,12 @@ async def update_rule(
|
||||
# rule wrongly vouched for costs the thing the sweep exists to catch.
|
||||
if rule.verify_with != check_before:
|
||||
rule.verified_at = None
|
||||
# A rule turned into a preference without naming an enforcement drops to
|
||||
# `inform`, since a preference carries no other. Named explicitly
|
||||
# alongside the new kind, a stronger enforcement is refused instead.
|
||||
if rule.kind == "preference" and "enforcement" not in fields:
|
||||
rule.enforcement = "inform"
|
||||
rule.enforcement = require_enforcement(rule.enforcement, rule.kind)
|
||||
if trigger_before and not (rule.when_to_apply or "").strip():
|
||||
raise ValueError(
|
||||
"when_to_apply cannot be cleared: it is how this rule arrives, "
|
||||
|
||||
@@ -33,15 +33,21 @@ from sqlalchemy import select
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.app_log import AppLog
|
||||
|
||||
# check — the turn's first stop: block if anything is unjudged.
|
||||
# after — the stop that follows a block: never block again, only record
|
||||
# whether the agent answered.
|
||||
# check — a turn's stop: note what is unjudged, for the next prompt.
|
||||
# after — the stop after the note was read: record whether the agent
|
||||
# answered it.
|
||||
PHASES = ("check", "after")
|
||||
OUTCOMES = ("passed", "blocked", "judged_after_block", "left_after_block")
|
||||
# `blocked` and its two answers are the outcomes of the end-of-turn hold this
|
||||
# check once was; they stay readable so a window spanning both still sums.
|
||||
OUTCOMES = ("passed", "noted", "judged_after_note", "left_after_note",
|
||||
"blocked", "judged_after_block", "left_after_block")
|
||||
ASKED = ("noted", "blocked")
|
||||
LEFT = ("left_after_note", "left_after_block")
|
||||
|
||||
# How many shapes the reason names before "+N more". Enough to judge a normal
|
||||
# turn in one call; a turn that wrote more than this generated something.
|
||||
_LISTED = 25
|
||||
# How many shapes the note names before "+N more". It rides the next prompt
|
||||
# inside the payload budget, so it names the first few and the call that
|
||||
# lists the rest.
|
||||
_LISTED = 8
|
||||
|
||||
|
||||
def _evidence_note(evidence: dict) -> str:
|
||||
@@ -62,8 +68,9 @@ def _evidence_note(evidence: dict) -> str:
|
||||
return f" ({'; '.join(parts)})" if parts else ""
|
||||
|
||||
|
||||
def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
|
||||
"""What the agent is told at the end of a turn that wrote unjudged shapes.
|
||||
def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str:
|
||||
"""What the agent reads at the start of the turn after one that wrote
|
||||
unjudged shapes.
|
||||
|
||||
Phrased as a practice: what to decide and the one
|
||||
call that records it, not a prohibition. The reusing-code skill owns the
|
||||
@@ -81,10 +88,10 @@ def block_reason(unjudged: list[dict], *, project_id: int, repo: str) -> str:
|
||||
lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)")
|
||||
repo_arg = f', repo="{repo}"' if repo else ""
|
||||
return (
|
||||
f"This turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
|
||||
f"Your last turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} "
|
||||
"that nobody has judged yet. You built them, so you know what each one is — "
|
||||
"record it now, while that is still true, so the next session starts from your "
|
||||
"answer instead of rebuilding it:\n"
|
||||
"record it alongside this turn's work, while that is still true, so the next "
|
||||
"session starts from your answer instead of rebuilding it:\n"
|
||||
+ "\n".join(lines)
|
||||
+ "\n\nFor each: something another part of the code should reuse → record it "
|
||||
"with create_snippet (name, code, when to reach for it, location); built from a "
|
||||
@@ -122,11 +129,11 @@ async def record_shape_check(
|
||||
|
||||
|
||||
def outcome_for(phase: str, unjudged: list[dict]) -> str:
|
||||
"""The recorded outcome: a first stop blocks or passes; the stop after a
|
||||
block records whether the agent answered, and never blocks."""
|
||||
"""The recorded outcome: a turn's stop notes or passes; the stop after
|
||||
the note was read records whether the agent answered it."""
|
||||
if phase == "after":
|
||||
return "left_after_block" if unjudged else "judged_after_block"
|
||||
return "blocked" if unjudged else "passed"
|
||||
return "left_after_note" if unjudged else "judged_after_note"
|
||||
return "noted" if unjudged else "passed"
|
||||
|
||||
|
||||
def parse_written(raw: str, *, cap: int = 200) -> list[tuple[str, str, str]]:
|
||||
@@ -158,14 +165,14 @@ WINDOW_DAYS = 7
|
||||
def summarise(outcomes: list[str]) -> dict:
|
||||
"""{checked, asked, left} from a list of recorded outcomes.
|
||||
|
||||
`checked` is turns the question was put to (a first stop that wrote
|
||||
something): passed + blocked. `asked` is the blocked ones. `left` is
|
||||
asks the agent walked past — the stop after a block that still had
|
||||
unjudged shapes. That last number is the slip this check exists to make
|
||||
visible."""
|
||||
checked = sum(1 for o in outcomes if o in ("passed", "blocked"))
|
||||
asked = sum(1 for o in outcomes if o == "blocked")
|
||||
left = sum(1 for o in outcomes if o == "left_after_block")
|
||||
`checked` is turns the question was put to (a stop after a turn that
|
||||
wrote something): passed + asked. `asked` is the ones that found
|
||||
something unjudged. `left` is asks the agent walked past — answered by a
|
||||
stop that still had unjudged shapes. That last number is the slip this
|
||||
check exists to make visible."""
|
||||
checked = sum(1 for o in outcomes if o == "passed" or o in ASKED)
|
||||
asked = sum(1 for o in outcomes if o in ASKED)
|
||||
left = sum(1 for o in outcomes if o in LEFT)
|
||||
return {"checked": checked, "asked": asked, "left": left}
|
||||
|
||||
|
||||
|
||||
@@ -258,6 +258,46 @@ def _event(row: CodeShape, event: str, at: datetime, *, commit: str = "") -> Cod
|
||||
)
|
||||
|
||||
|
||||
async def provisional_row(
|
||||
session, *, project_id: int, repo_key: str, path: str, symbol: str, kind: str,
|
||||
) -> CodeShape:
|
||||
"""The row for a shape a caller met before any live row for it existed:
|
||||
a shape being written this turn, or one judged ahead of the sync.
|
||||
|
||||
The identity (project, repo, path, symbol, kind) is unique, so "no live
|
||||
row" does not mean "no row". A VANISHED row under the identity is revived
|
||||
and keeps its standing judgment, as a sync revives a shape that comes
|
||||
back. The next sync then confirms it, or stamps it vanished again until
|
||||
the code reaches the bound ref. With no row at all, a provisional one is
|
||||
inserted inside a savepoint. If a concurrent request inserts the same
|
||||
identity first, the savepoint rolls back and that request's row is used.
|
||||
The caller's transaction survives either way.
|
||||
"""
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
def _same():
|
||||
return select(CodeShape).where(
|
||||
CodeShape.project_id == project_id, CodeShape.repo_key == repo_key,
|
||||
CodeShape.path == path, CodeShape.symbol == symbol, CodeShape.kind == kind,
|
||||
)
|
||||
|
||||
row = (await session.execute(_same())).scalars().first()
|
||||
if row is None:
|
||||
try:
|
||||
async with session.begin_nested():
|
||||
row = CodeShape(project_id=project_id, repo_key=repo_key,
|
||||
path=path, symbol=symbol, kind=kind)
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
return row
|
||||
except IntegrityError:
|
||||
row = (await session.execute(_same())).scalars().one()
|
||||
if row.vanished_at is not None:
|
||||
row.vanished_at = None
|
||||
session.add(_event(row, "reappeared", datetime.now(timezone.utc)))
|
||||
return row
|
||||
|
||||
|
||||
async def _judge(
|
||||
session, row: CodeShape, *, status: str, snippet_id: int | None,
|
||||
by: str | None, reason: str | None, at: datetime, reason_code: str | None = None,
|
||||
@@ -726,11 +766,10 @@ async def classify_shapes(
|
||||
if not matches and repo_key and item.get("status") != "unclassified":
|
||||
path = (item.get("path") or "").strip()
|
||||
symbol = (item.get("symbol") or "").strip()
|
||||
row = CodeShape(
|
||||
project_id=project_id, repo_key=repo_key, path=path,
|
||||
row = await provisional_row(
|
||||
session, project_id=project_id, repo_key=repo_key, path=path,
|
||||
symbol=symbol, kind=kind or snippet_kind(symbol, ""),
|
||||
)
|
||||
session.add(row)
|
||||
by_key.setdefault((path, symbol), []).append(row)
|
||||
matches = [row]
|
||||
provisional += 1
|
||||
@@ -1655,13 +1694,13 @@ async def suggest_write_path_instances(
|
||||
if row is None:
|
||||
if not repo_key:
|
||||
continue
|
||||
row = CodeShape(
|
||||
project_id=project_id, repo_key=repo_key,
|
||||
# It may be a vanished row coming back, with its judgment.
|
||||
row = await provisional_row(
|
||||
session, project_id=project_id, repo_key=repo_key,
|
||||
path=path, symbol=name, kind=kind,
|
||||
)
|
||||
session.add(row)
|
||||
by_key[(name, kind)] = row
|
||||
elif not (row.status in _MECHANICAL_TODO or row.classified_by == "hook"):
|
||||
if not (row.status in _MECHANICAL_TODO or row.classified_by == "hook"):
|
||||
continue # a judgment — or the canon itself — stands
|
||||
# A proposal, never a status: the writer decides.
|
||||
row.proposed_snippet_id = sid
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Which project a write lands in, so a session can be held to its own.
|
||||
|
||||
A Claude Code session belongs to one project: the one its starting directory
|
||||
is bound to. Toward any other project it may read anything and file an issue,
|
||||
and every other write waits for the operator. The plugin's PreToolUse hook
|
||||
enforces that, because only the hook knows which session is acting: the MCP
|
||||
endpoint is stateless and sees nothing but the caller's key. This module
|
||||
answers the hook's one question: given the session's project and a pending
|
||||
act, which projects would the act change, and may it go ahead?
|
||||
|
||||
An act is either a directory (a file edit or a git command; the hook resolves
|
||||
it to a repo or a `.grimoire` marker) or an MCP tool call. For a tool call,
|
||||
`WRITE_TARGETS` says, for every write tool, which of its arguments locate the
|
||||
write. That means the record or project the write changes, never one it only
|
||||
mentions: `arose_from_id` on a new task points at another task without
|
||||
changing it. tests/test_write_scope.py holds the table to the registered tools,
|
||||
so a new write tool can't be added without saying where it writes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
|
||||
# How an argument locates the project a write lands in.
|
||||
PROJECT = "project" # a project id
|
||||
NOTE = "note" # a task, note, lesson, snippet or process: its project
|
||||
MILESTONE = "milestone" # a milestone: its project
|
||||
SYSTEM = "system" # a System: its project
|
||||
RULE = "rule" # a project rule: its project. A global rule: none
|
||||
RELATION = "relation" # a rule relation: the projects of its two rules
|
||||
TRASH = "trash" # a deleted batch: every project its rows belong to
|
||||
REPO = "repo" # a repo remote: the project it is bound to
|
||||
DECISION = "decision" # a family decision: its project, else its idea's home
|
||||
|
||||
LOCATORS = frozenset({PROJECT, NOTE, MILESTONE, SYSTEM, RULE, RELATION, TRASH, REPO, DECISION})
|
||||
|
||||
# Every write tool, and the arguments that locate its write. An empty entry is
|
||||
# a write that lands in no project:
|
||||
# - install-level settings (moment mappings, retrieval dials);
|
||||
# - user-level records (processes, design systems, rulebooks, topics, global
|
||||
# rules and preferences);
|
||||
# - judgments the system asks a session for in any project (a rule's outcome,
|
||||
# a lesson-to-rule link, moment proposals, a menu verdict). Those describe how
|
||||
# the corpus is retrieved; they don't change another project's work.
|
||||
WRITE_TARGETS: dict[str, dict[str, str]] = {
|
||||
# notes, tasks, planning
|
||||
"create_note": {"project_id": PROJECT},
|
||||
"update_note": {"note_id": NOTE, "project_id": PROJECT},
|
||||
"delete_note": {"note_id": NOTE},
|
||||
"mark_note_verified": {"note_id": NOTE},
|
||||
"create_lesson": {"project_id": PROJECT},
|
||||
"update_lesson": {"lesson_id": NOTE},
|
||||
"delete_lesson": {"lesson_id": NOTE},
|
||||
"judge_lesson_link": {},
|
||||
"create_task": {"project_id": PROJECT, "milestone_id": MILESTONE, "parent_id": NOTE},
|
||||
"update_task": {"task_id": NOTE, "project_id": PROJECT, "milestone_id": MILESTONE},
|
||||
"delete_task": {"task_id": NOTE},
|
||||
"add_task_log": {"task_id": NOTE},
|
||||
"create_records": {"project_id": PROJECT, "milestone_id": MILESTONE},
|
||||
"start_planning": {"project_id": PROJECT},
|
||||
"create_milestone": {"project_id": PROJECT},
|
||||
"update_milestone": {"milestone_id": MILESTONE, "project_id": PROJECT},
|
||||
"delete_milestone": {"milestone_id": MILESTONE},
|
||||
# projects, Systems, repos
|
||||
"create_project": {},
|
||||
"update_project": {"project_id": PROJECT},
|
||||
"delete_project": {"project_id": PROJECT},
|
||||
"decide_project_inception": {"project_id": PROJECT},
|
||||
"set_project_platforms": {"project_id": PROJECT},
|
||||
"create_system": {"project_id": PROJECT},
|
||||
"update_system": {"system_id": SYSTEM},
|
||||
"delete_system": {"system_id": SYSTEM},
|
||||
"map_system_to_canonical": {"system_id": SYSTEM},
|
||||
# Binding a repo changes the project it's bound to and, when it was bound
|
||||
# elsewhere, the project it leaves.
|
||||
"bind_repo": {"project_id": PROJECT, "repo_url": REPO},
|
||||
"unbind_repo": {"repo_url": REPO},
|
||||
# family canon. An idea is a record in its home project; an adoption is a
|
||||
# project's answer; a conflict is between the two projects it names.
|
||||
"propose_family_idea": {"note_id": NOTE},
|
||||
"promote_family_idea": {"note_id": NOTE},
|
||||
"retire_family_idea": {"note_id": NOTE},
|
||||
"revise_family_idea": {"note_id": NOTE},
|
||||
"set_family_references": {"note_id": NOTE},
|
||||
"set_family_topic": {"note_id": NOTE},
|
||||
"undo_family_decision": {"decision_id": DECISION},
|
||||
"assess_family_adoption": {"project_id": PROJECT},
|
||||
"resolve_family_conflict": {"canon_project_id": PROJECT, "other_project_id": PROJECT},
|
||||
# snippets, processes, the shape ledger
|
||||
"create_snippet": {"project_id": PROJECT},
|
||||
"update_snippet": {"snippet_id": NOTE, "project_id": PROJECT},
|
||||
"delete_snippet": {"snippet_id": NOTE},
|
||||
"verify_snippet": {"snippet_id": NOTE},
|
||||
"merge_snippets": {"target_id": NOTE, "source_ids": NOTE},
|
||||
"unmerge_snippet": {"survivor_id": NOTE, "source_id": NOTE},
|
||||
"create_process": {},
|
||||
"update_process": {"process_id": NOTE},
|
||||
"delete_process": {"process_id": NOTE},
|
||||
"classify_shapes": {"project_id": PROJECT},
|
||||
"classify_shapes_by_rule": {"project_id": PROJECT},
|
||||
"confirm_shape_proposals": {"project_id": PROJECT},
|
||||
"refresh_pattern_coverage": {"project_id": PROJECT},
|
||||
"move_path": {"project_id": PROJECT},
|
||||
# design systems belong to their owner, not to a project; choosing one for
|
||||
# a project is that project's write.
|
||||
"create_design_system": {},
|
||||
"update_design_system": {},
|
||||
"delete_design_system": {},
|
||||
"create_design_token": {},
|
||||
"update_design_token": {},
|
||||
"delete_design_token": {},
|
||||
"set_project_design_system": {"project_id": PROJECT},
|
||||
# rules
|
||||
"create_rulebook": {},
|
||||
"update_rulebook": {},
|
||||
"delete_rulebook": {},
|
||||
"create_topic": {},
|
||||
"update_topic": {},
|
||||
"delete_topic": {},
|
||||
"create_rule": {},
|
||||
"create_preference": {},
|
||||
"create_project_rule": {"project_id": PROJECT},
|
||||
"update_rule": {"rule_id": RULE},
|
||||
"update_preference": {"rule_id": RULE},
|
||||
"move_rule": {"rule_id": RULE, "project_id": PROJECT},
|
||||
"delete_rule": {"rule_id": RULE},
|
||||
"mark_rule_verified": {"rule_id": RULE},
|
||||
"relate_rules": {"from_rule_id": RULE, "to_rule_id": RULE},
|
||||
"unrelate_rules": {"relation_id": RELATION},
|
||||
"rule_outcome": {},
|
||||
# moments and retrieval: install-level, and judgments asked for anywhere
|
||||
"tune_retrieval": {},
|
||||
"migrate_retrieval_floor": {},
|
||||
"map_action": {},
|
||||
"unmap_action": {},
|
||||
"propose_rule_moments": {},
|
||||
"judge_rule_moments": {},
|
||||
"rule_misfired": {},
|
||||
"judge_menu": {},
|
||||
# trash: a batch can hold rows from several projects
|
||||
"restore": {"deleted_batch_id": TRASH},
|
||||
"purge_trash": {"deleted_batch_id": TRASH},
|
||||
}
|
||||
|
||||
# Argument names that would locate a write wherever they appear. The guard test
|
||||
# requires every write tool parameter with one of these names to be declared
|
||||
# above, or listed in REFERENCES below, so a tool that gains one can't write
|
||||
# past the fence unnoticed.
|
||||
LOCATOR_NAMES = frozenset({
|
||||
"project_id", "task_id", "note_id", "lesson_id", "snippet_id", "process_id",
|
||||
"milestone_id", "system_id", "rule_id", "deleted_batch_id",
|
||||
})
|
||||
|
||||
# Arguments with a locating name that only point at a record, with why each one
|
||||
# doesn't say where the write lands.
|
||||
REFERENCES: dict[str, dict[str, str]] = {
|
||||
"classify_shapes_by_rule": {
|
||||
"snippet_id": "the canon the shapes are judged against; the rows written are project_id's",
|
||||
},
|
||||
"confirm_shape_proposals": {
|
||||
"snippet_id": "narrows which proposals to confirm; the rows written are project_id's",
|
||||
},
|
||||
"judge_lesson_link": {
|
||||
"lesson_id": "a judgment on a lesson-to-rule pairing the system asked for",
|
||||
"rule_id": "a judgment on a lesson-to-rule pairing the system asked for",
|
||||
},
|
||||
"rule_outcome": {
|
||||
"rule_id": "telemetry on what a rule changed in this session's own work",
|
||||
},
|
||||
"rule_misfired": {
|
||||
"rule_id": "telemetry on a moment that fired a rule in this session",
|
||||
"project_id": "the project the misfire happened in, recorded with the report",
|
||||
},
|
||||
}
|
||||
|
||||
# Tool-name prefixes the plugin's fence answers without asking the server: every
|
||||
# tool named this way reads. tests/test_write_scope.py holds the hook's copy of
|
||||
# this list equal to it, and holds every write tool to a name outside it.
|
||||
READ_PREFIXES = (
|
||||
"get_", "list_", "search", "find_", "enter_project", "what_might_apply",
|
||||
"resolve_design_system",
|
||||
)
|
||||
|
||||
# The one write a session may make in another project: filing an issue there,
|
||||
# as a new open task outside any plan of theirs.
|
||||
ISSUE_STATUSES = frozenset({"", "todo"})
|
||||
|
||||
|
||||
def is_issue_filing(tool: str, args: dict) -> bool:
|
||||
"""True for create_task(kind="issue") that opens a fresh, unplanned issue."""
|
||||
if tool != "create_task":
|
||||
return False
|
||||
if str(args.get("kind") or "") != "issue":
|
||||
return False
|
||||
if str(args.get("status") or "") not in ISSUE_STATUSES:
|
||||
return False
|
||||
return not _positive_ints(args.get("milestone_id")) and not _positive_ints(args.get("parent_id"))
|
||||
|
||||
|
||||
def _positive_ints(value) -> list[int]:
|
||||
"""The ids an argument names. 0 and negative values mean "none" or "leave
|
||||
unchanged" across the tools (update_task's project_id=-1 clears), so only
|
||||
positive ids locate anything."""
|
||||
values = value if isinstance(value, (list, tuple)) else [value]
|
||||
out = []
|
||||
for v in values:
|
||||
try:
|
||||
n = int(v)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if n > 0:
|
||||
out.append(n)
|
||||
return out
|
||||
|
||||
|
||||
async def _projects_of(user_id: int, kind: str, value) -> set[int]:
|
||||
"""The projects the argument `value` of locator `kind` lands in."""
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.family import FamilyDecision
|
||||
from grimoire.models.milestone import Milestone
|
||||
from grimoire.models.note import Note
|
||||
from grimoire.models.rulebook import Rule, RuleRelation
|
||||
from grimoire.models.system import System
|
||||
from grimoire.services import repo_bindings
|
||||
|
||||
if kind == REPO:
|
||||
found = await repo_bindings.resolve_project(user_id, str(value or ""))
|
||||
return {found} if found else set()
|
||||
if kind == TRASH:
|
||||
batch = str(value or "").strip()
|
||||
if not batch:
|
||||
return set()
|
||||
async with async_session() as session:
|
||||
found: set[int] = set()
|
||||
for model in (Note, Milestone, System, Rule):
|
||||
rows = await session.execute(
|
||||
select(model.project_id).where(model.deleted_batch_id == batch)
|
||||
)
|
||||
found.update(p for p in rows.scalars() if p)
|
||||
return found
|
||||
ids = _positive_ints(value)
|
||||
if not ids:
|
||||
return set()
|
||||
if kind == PROJECT:
|
||||
return set(ids)
|
||||
async with async_session() as session:
|
||||
if kind == RELATION:
|
||||
rows = await session.execute(
|
||||
select(Rule.project_id)
|
||||
.join(RuleRelation, or_(RuleRelation.from_rule_id == Rule.id,
|
||||
RuleRelation.to_rule_id == Rule.id))
|
||||
.where(RuleRelation.id.in_(ids))
|
||||
)
|
||||
return {p for p in rows.scalars() if p}
|
||||
if kind == DECISION:
|
||||
rows = await session.execute(
|
||||
select(FamilyDecision.project_id, Note.project_id)
|
||||
.join(Note, Note.id == FamilyDecision.idea_id)
|
||||
.where(FamilyDecision.id.in_(ids))
|
||||
)
|
||||
return {own or home for own, home in rows.all() if own or home}
|
||||
model = {NOTE: Note, MILESTONE: Milestone, SYSTEM: System, RULE: Rule}[kind]
|
||||
rows = await session.execute(select(model.project_id).where(model.id.in_(ids)))
|
||||
return {p for p in rows.scalars() if p}
|
||||
|
||||
|
||||
async def tool_targets(user_id: int, tool: str, args: dict) -> set[int]:
|
||||
"""Every project the MCP call `tool(**args)` would change. Empty for a
|
||||
read, a write that lands in no project, and a tool this server doesn't
|
||||
have."""
|
||||
found: set[int] = set()
|
||||
for name, kind in WRITE_TARGETS.get(tool, {}).items():
|
||||
if name in args:
|
||||
found |= await _projects_of(user_id, kind, args[name])
|
||||
return found
|
||||
|
||||
|
||||
async def _titles(ids: list[int]) -> dict[int, str]:
|
||||
from grimoire.models import async_session
|
||||
from grimoire.models.project import Project
|
||||
|
||||
if not ids:
|
||||
return {}
|
||||
async with async_session() as session:
|
||||
rows = await session.execute(select(Project.id, Project.title).where(Project.id.in_(ids)))
|
||||
return {pid: title for pid, title in rows.all()}
|
||||
|
||||
|
||||
def _named(project_id: int, titles: dict[int, str]) -> str:
|
||||
title = titles.get(project_id)
|
||||
return f"{title} (project {project_id})" if title else f"project {project_id}"
|
||||
|
||||
|
||||
async def check_act(
|
||||
user_id: int, session_project: int, *, tool: str = "", args: dict | None = None,
|
||||
target_project: int = 0, act: str = "",
|
||||
) -> dict:
|
||||
"""May a session in `session_project` do this act?
|
||||
|
||||
The act is an MCP call (`tool` with `args`) or a directory already
|
||||
resolved to `target_project`; `act` words it for the reason ("git push
|
||||
in", "Editing a file in"). Returns:
|
||||
- `allowed`: False when the act would change another project and isn't the
|
||||
one cross-project write allowed;
|
||||
- `targets`: the other projects, as {id, title};
|
||||
- `issue`: the act is that allowed write, filing an issue;
|
||||
- `reason`: what the operator reads in the prompt, and the session after.
|
||||
|
||||
A session with no project is held to nothing. A target the caller can't
|
||||
read is left out: the write itself is refused there, so there is nothing
|
||||
to ask about, and naming it would tell the caller where a record lives.
|
||||
"""
|
||||
from grimoire.services.access import can_read_project
|
||||
|
||||
args = args or {}
|
||||
if tool:
|
||||
landing = await tool_targets(user_id, tool, args)
|
||||
else:
|
||||
landing = {target_project} if target_project else set()
|
||||
others = [
|
||||
p for p in sorted(landing)
|
||||
if p != session_project and await can_read_project(user_id, p)
|
||||
]
|
||||
if not session_project or not others:
|
||||
return {"allowed": True, "targets": [], "issue": False, "reason": ""}
|
||||
titles = await _titles([session_project, *others])
|
||||
targets = [{"id": p, "title": titles.get(p, "")} for p in others]
|
||||
if tool and is_issue_filing(tool, args):
|
||||
return {"allowed": True, "targets": targets, "issue": True, "reason": ""}
|
||||
there = ", ".join(_named(p, titles) for p in others)
|
||||
what = act.strip() or (f"{tool} changes" if tool else "This changes")
|
||||
first = others[0]
|
||||
reason = (
|
||||
f"This session belongs to {_named(session_project, titles)}. {what} {there}, "
|
||||
f"a different project. From here, the one change to make there is filing an "
|
||||
f"issue: create_task(project_id={first}, kind=\"issue\") with how it was found "
|
||||
f"and the evidence. Approve only if this session should change {there} itself."
|
||||
)
|
||||
return {"allowed": False, "targets": targets, "issue": False, "reason": reason}
|
||||
@@ -1,11 +1,15 @@
|
||||
import re
|
||||
|
||||
_CODE_FENCE_RE = re.compile(r"```[\s\S]*?```|`[^`\n]+`")
|
||||
_TAG_RE = re.compile(r"(?<!\w)#([\w][\w-]*(?:/[\w][\w-]*)*)")
|
||||
# A `#` token made only of digits is a record reference (`#3127` names note
|
||||
# 3127, see services/record_refs.py), never a tag. Digits followed by more of a
|
||||
# tag (`#2fa`, `#123-notes`) is still a tag. frontend/src/utils/tags.ts holds the
|
||||
# same pattern.
|
||||
_TAG_RE = re.compile(r"(?<!\w)#(?!\d+(?![\w/-]))([\w][\w-]*(?:/[\w][\w-]*)*)")
|
||||
|
||||
|
||||
def extract_tags(body: str) -> list[str]:
|
||||
"""Extract #tags from body text, ignoring code blocks."""
|
||||
"""Extract #tags from body text, ignoring code blocks and record references."""
|
||||
cleaned = _CODE_FENCE_RE.sub("", body)
|
||||
tags = _TAG_RE.findall(cleaned)
|
||||
return sorted(set(tags))
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user