Compare commits

..
89 Commits
Author SHA1 Message Date
bvandeusen b23275d5f3 Merge pull request 'Release: the proxy hop count is set in Settings → Config' (#221) from dev into main
CI & Build / Python tests (push) Successful in 1m54s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 2m18s
CI & Build / Build & push image (push) Successful in 18s
2026-11-05 10:29:51 -05:00
bvandeusen 85093c859b Merge pull request 'Restore rolls back to a backup; a session can only file issues in another project' (#220) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 31s
CI & Build / Python tests (push) Successful in 1m44s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Successful in 30s
2026-11-05 09:29:54 -05:00
bvandeusen 0216634bd4 Merge pull request 'dev → main: a name defined in two packages counts only in the canon's own (#6495)' (#219) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / integration (push) Successful in 1m28s
CI & Build / Python tests (push) Successful in 2m13s
CI & Build / Build & push image (push) Successful in 1m24s
2026-10-26 22:26:20 -04:00
bvandeusen 67ea21b787 Merge pull request 'dev → main: drop cross-project hook uses edges (#6483), plain-word calls need no space (#6477)' (#218) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 1m1s
CI & Build / Python tests (push) Successful in 1m35s
CI & Build / Build & push image (push) Successful in 31s
2026-10-26 19:16:24 -04:00
bvandeusen f4eb535285 Merge pull request 'dev → main: by-name canon matching resolves (#6477), five unused Vue components removed (#6480)' (#217) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 1m8s
CI & Build / Python tests (push) Successful in 1m44s
CI & Build / Build & push image (push) Successful in 28s
2026-10-26 17:49:07 -04:00
bvandeusen 6e71badf11 Merge pull request 'Moment proposals count only unexplained opens; the shape check hears every definition' (#216) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / integration (push) Successful in 1m1s
CI & Build / Python tests (push) Successful in 1m38s
CI & Build / Build & push image (push) Successful in 19s
2026-10-26 16:34:11 -04:00
bvandeusen a7f3e0e972 Merge pull request 'dev → main: rule-arm review, moment usage by rule, no-subject auto-inject, copy check, S3 test wording' (#215) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m2s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 17s
2026-10-22 20:26:40 -04:00
bvandeusen db62985966 Merge pull request 'Grimoire keeps its own SECRET_KEY, docker-compose.yml is the deploy compose, a repo rename moves its snippets; logo, README, licence' (#214) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m5s
CI & Build / Python tests (push) Successful in 2m4s
CI & Build / Build & push image (push) Successful in 21s
2026-10-22 16:42:33 -04:00
bvandeusen 9a1513070d Merge pull request 'A moved file or directory keeps its shape judgments and snippet locations' (#213) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m4s
CI & Build / Python tests (push) Successful in 2m4s
CI & Build / Build & push image (push) Successful in 14s
2026-10-22 15:29:37 -04:00
bvandeusen b12d9ba396 Scribe is renamed Fabled Grimoire
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 1m3s
CI & Build / Python tests (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 14s
2026-10-22 14:20:16 -04:00
bvandeusen b69bc47e65 Merge pull request 'Backups carry the Profile page (user_profiles)' (#211) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m7s
CI & Build / Python tests (push) Successful in 1m53s
CI & Build / Build & push image (push) Successful in 23s
2026-10-15 20:00:32 -04:00
bvandeusen cef173c0a6 Scheduled backups to a folder or S3 bucket, and forge tokens sealed at rest (milestone 523)
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m11s
CI & Build / Python tests (push) Successful in 1m57s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Build & push image (push) Successful in 14s
2026-10-15 18:19:26 -04:00
bvandeusen a9bfe13631 Merge pull request 'Reply shapes ride the moments (milestone 500, steps 1–5)' (#209) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m8s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 17s
2026-10-09 16:40:04 -04:00
bvandeusen f15542d6cb Merge pull request 'Merge dev → main: family precedents say their reason once; the repeat trigger compares like with like' (#208) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / integration (push) Successful in 1m37s
CI & Build / TypeScript typecheck (push) Successful in 58s
CI & Build / Python tests (push) Successful in 2m20s
CI & Build / Build & push image (push) Successful in 22s
2026-10-06 19:00:18 -04:00
bvandeusen b3c0cc5548 Merge pull request 'Merge dev → main: a family idea links to the rule topic holding its norms' (#207) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / integration (push) Successful in 1m26s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / Python tests (push) Successful in 2m10s
CI & Build / Build & push image (push) Successful in 1m7s
2026-10-06 18:00:52 -04:00
bvandeusen ecbadf51ce Merge pull request 'Merge dev: family canon, milestone 463 steps 1-6' (#206) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m13s
CI & Build / Python tests (push) Successful in 1m57s
CI & Build / Build & push image (push) Successful in 30s
2026-10-06 14:11:28 -04:00
bvandeusen d4de0b9b54 Merge pull request 'Merge dev: scope-then-rank searches (#4958, #4961), CI gate on integration, milestone 456 steps 4-6' (#205) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / integration (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m52s
CI & Build / Build & push image (push) Successful in 18s
2026-10-05 22:23:48 -04:00
bvandeusen 25c1c778f1 Merge pull request 'Moments: skills teach moments, and a mount that misfires proposes its own removal (milestone 458 steps 8, 7b)' (#204) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m53s
CI & Build / Build & push image (push) Successful in 26s
2026-10-05 18:29:53 -04:00
bvandeusen 2b52afcd72 Merge pull request 'Mount the corpus by proposal: a pass and an open-after-moment signal (milestone 458 step 7)' (#203) from dev into main
CI & Build / Python lint (push) Successful in 5s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / integration (push) Successful in 1m12s
CI & Build / Build & push image (push) Successful in 22s
2026-10-05 16:31:42 -04:00
bvandeusen 2db9e0c0c1 Merge pull request 'Skills and processes declare their moments, and the UI for moments (milestone 458 steps 5–6)' (#202) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m9s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / Build & push image (push) Successful in 19s
2026-10-05 15:41:56 -04:00
bvandeusen 9fc2df080d Merge pull request 'Rules mount on moments, and one retrieval pipeline (milestones 458 steps 1–4, 456 steps 1–3)' (#201) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m54s
CI & Build / Build & push image (push) Successful in 19s
2026-10-05 12:41:56 -04:00
bvandeusen 802ead748b Merge pull request 'Rules never-opened advice per corpus (#4798); a lesson's name is one line (#4797)' (#200) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / integration (push) Successful in 53s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m45s
CI & Build / Build & push image (push) Successful in 22s
2026-10-03 23:11:18 -04:00
bvandeusen 8b9ff0c5c1 Merge pull request 'Auto-inject looks up records named by number (#4796)' (#199) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m47s
CI & Build / Build & push image (push) Successful in 18s
2026-10-03 22:16:01 -04:00
bvandeusen a19c344770 Merge pull request 'No heading-only chunks, agent-message skip, refusals reach the agent (#4784, #4785, #4794)' (#198) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m14s
CI & Build / Python tests (push) Successful in 2m2s
CI & Build / Build & push image (push) Successful in 18s
2026-10-03 21:47:03 -04:00
bvandeusen c389ed61d2 Merge pull request 'The review drops records written after the call it re-runs (#4773)' (#197) from dev into main
CI & Build / Python lint (push) Successful in 5s
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 1m5s
CI & Build / Build & push image (push) Successful in 23s
2026-10-03 20:37:08 -04:00
bvandeusen c50c1beb83 Merge pull request 'A review pass judges whether injected lines related (#4772)' (#196) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 57s
CI & Build / integration (push) Successful in 1m19s
CI & Build / Python tests (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 19s
2026-10-03 18:17:49 -04:00
bvandeusen b4c637a7df Merge pull request 'Rulings readout and the prior-art 500 fix' (#195) from dev into main
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 59s
CI & Build / integration (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m43s
CI & Build / Build & push image (push) Successful in 20s
2026-10-03 08:57:36 -04:00
bvandeusen a24f6b6b41 Merge pull request 'Rulings reach the work they govern — milestone 444 steps 3-4' (#194) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m11s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 20s
2026-10-03 08:29:25 -04:00
bvandeusen 6477c20664 Merge pull request 'Milestone 444 steps 1-2: an operator's ruling lives on the System it governs, and code is read as behaviour, not intent' (#193) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m46s
CI & Build / Build & push image (push) Successful in 18s
2026-10-02 19:46:50 -04:00
bvandeusen f94ff9e8fc Merge pull request 'The web lesson editor records which rule a lesson is an instance of (milestone 440, #4658)' (#192) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m43s
CI & Build / Build & push image (push) Successful in 17s
2026-10-01 16:54:34 -04:00
bvandeusen 6024230fa9 Merge pull request 'Milestone 440 steps 4, 5, 7: rules surface through their lessons, convergence named at the write, both records show the link' (#191) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m50s
CI & Build / Build & push image (push) Successful in 19s
2026-10-01 16:06:03 -04:00
bvandeusen c08655914f Merge pull request 'Soft links: a lesson and a rule arriving together are proposed as a link (milestone 440 step 3, #4637)' (#190) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 56s
CI & Build / Python tests (push) Successful in 1m44s
CI & Build / Build & push image (push) Successful in 21s
2026-10-01 14:59:30 -04:00
bvandeusen 6ba40c9e10 Merge pull request 'Lessons point at rules (milestone 440 steps 1–2) + the away-from-home usage readout' (#189) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 58s
CI & Build / integration (push) Successful in 57s
CI & Build / Python tests (push) Successful in 1m40s
CI & Build / Build & push image (push) Successful in 21s
2026-10-01 13:48:01 -04:00
bvandeusen d7641e57a8 Merge pull request 'Shapes are judged when they are written (milestone 439 steps 1–6) + #4608 fixes' (#188) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / integration (push) Successful in 56s
CI & Build / TypeScript typecheck (push) Successful in 57s
CI & Build / Python tests (push) Successful in 1m45s
CI & Build / Build & push image (push) Successful in 17s
2026-10-01 08:55:10 -04:00
bvandeusen 33c0f2c95d Merge pull request 'Server instructions orient the workflow; using-scribe splits into reference files (#4389, #4398)' (#187) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m1s
CI & Build / Python tests (push) Successful in 1m46s
CI & Build / Build & push image (push) Successful in 14s
2026-09-24 11:30:02 -04:00
bvandeusen 779efb2e74 Merge pull request 'dev → main: MCP SDK v2 port, create-gate thresholds in Settings' (#186) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / integration (push) Successful in 52s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m38s
CI & Build / Build & push image (push) Successful in 16s
2026-09-24 07:31:51 -04:00
bvandeusen f385d9075b Merge pull request 'dev → main: task claims (milestone 381), embedding model stamp, dedup copy band, sweep-shared.css' (#185) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 51s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 13s
2026-09-24 06:57:12 -04:00
bvandeusen eb6912c722 Merge pull request 'Snippets gain notes; when_to_use is the situation it is ranked on (#4378)' (#184) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / integration (push) Successful in 54s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m43s
CI & Build / Build & push image (push) Successful in 17s
CI & Build / Plugin hooks (push) Successful in 12s
2026-09-23 18:00:35 -04:00
bvandeusen 14734ebe46 Merge pull request 'dev → main: auto-inject reads the conversation, startup names its failure, menu lines carry metadata, titles are names' (#183) from dev into main
CI & Build / integration (push) Successful in 50s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 17s
2026-09-23 16:57:42 -04:00
bvandeusen bf2871ffb4 Merge pull request 'Shape ledger: a semantic miss is not evidence; floors sized for the reader (#4208, #4306)' (#182) from dev into main
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / integration (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 18s
2026-09-22 09:50:33 -04:00
bvandeusen 3530ed5e87 Merge pull request 'dev → main: the meaning check reads new shapes first, and its miss withdraws an early flag (#4208)' (#181) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / integration (push) Successful in 50s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 14s
2026-09-22 08:14:50 -04:00
bvandeusen cc791de0e5 Merge pull request 'dev → main: rule overlap check, design-guidance write arm, usage chip seam, divergence meaning gate' (#180) from dev into main
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / integration (push) Successful in 51s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 16s
2026-09-22 07:48:53 -04:00
bvandeusen 05a55dc566 Merge pull request #179 from bvandeusen/dev
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 14s
CI & Build / integration (push) Successful in 50s
fix(lessons): a multi-paragraph trigger no longer grows a copy of itself on every edit (#4272)
2026-09-21 16:52:23 -04:00
bvandeusen a928171943 Merge pull request 'fix(systems): System tagging works from whichever door wrote the record, as whoever wrote it (#4249)' (#178) from dev into main
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 56s
CI & Build / Python tests (push) Successful in 1m43s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Build & push image (push) Successful in 14s
2026-09-21 16:13:10 -04:00
bvandeusen fa6c4e1ef8 Merge pull request 'fix(telemetry): silence is only an answer where the ledger was watching (#4268)' (#177) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / Python tests (push) Successful in 1m39s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 1m1s
CI & Build / Build & push image (push) Successful in 15s
2026-09-21 15:26:33 -04:00
bvandeusen c1c5debef8 Merge pull request 'fix: a backfill reads text when it embeds, not when it scanned (#4264)' (#176) from dev into main
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m2s
CI & Build / Python tests (push) Successful in 1m39s
CI & Build / Python lint (push) Successful in 4s
CI & Build / Build & push image (push) Successful in 15s
2026-09-21 14:06:34 -04:00
bvandeusen 888379ada2 Merge pull request 'Retrieval: the passage that matched, every kind searchable, work logs and charters findable' (#175) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m3s
CI & Build / Python tests (push) Successful in 1m36s
CI & Build / Build & push image (push) Successful in 13s
2026-09-21 12:39:18 -04:00
bvandeusen b2ff93abea Merge pull request 'Rule outcomes, the contract hint, and four extractor/backup fixes' (#174) from dev into main
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m35s
CI & Build / Build & push image (push) Successful in 17s
2026-09-21 06:31:10 -04:00
bvandeusen e2de5ad5f6 Merge pull request #173: the ledger stops asserting on thin evidence, and the agent is the judge
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m3s
CI & Build / Python tests (push) Successful in 1m47s
CI & Build / Build & push image (push) Successful in 14s
2026-09-20 23:07:04 -04:00
bvandeusen 92ffd14462 Merge pull request 'retrieval_telemetry says what is wrong (#3431)' (#172) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 50s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 17s
2026-09-20 21:03:53 -04:00
bvandeusen 8c916da058 Merge pull request 'The hooks need no jq, and the prompt boundary retrieves against prompts' (#171) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 52s
CI & Build / TypeScript typecheck (push) Successful in 57s
CI & Build / Python tests (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 14s
2026-09-20 18:50:03 -04:00
bvandeusen 0c8e109602 Merge pull request 'Lessons: the accretion reflex, and telemetry that can see across projects (#4195, #4196, #3735)' (#170) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m43s
CI & Build / Build & push image (push) Successful in 15s
2026-09-19 23:36:31 -04:00
bvandeusen b131e2b04c Merge pull request 'Lessons step 7 — a lesson is readable, writable and browsable by a human (#3734)' (#169) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 51s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m35s
CI & Build / Build & push image (push) Successful in 15s
2026-09-19 16:12:39 -04:00
bvandeusen 1135445e3f Merge pull request 'A rule proposal has five answers, and three of them route' (#168) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 50s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 15s
2026-09-19 13:34:51 -04:00
bvandeusen 25d8655ad4 Merge pull request 'Lessons reach the session that needs them, every kind is a full citizen, and a slow disk no longer takes the instance down' (#167) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 48s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m30s
CI & Build / Build & push image (push) Successful in 14s
2026-09-19 12:02:16 -04:00
bvandeusen adeaec88c5 Merge pull request #166 from bvandeusen/dev
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 51s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m32s
CI & Build / Build & push image (push) Successful in 13s
Plugin reply shape, preferences UI, cited-record status, and the lesson kind

Merged to ship the plugin: the marketplace checkout tracks main, so
#4153's reply-shape rewrite and #4154's "a record you only mention is a
record to read" could not reach a session from dev. Manifest moves
2026.09.18.0436 -> 2026.09.18.1606, so the executing cache refreshes.

Riding along: #4154 (next_step on milestone summaries, status in the
injected kind marker), #3895 (preferences writable + drift visible), and
milestone 385 steps 2-3 (#3729, #3730) which are inert until a lesson can
be written in step 4.

CI 7023 green on 1361ed7, all six jobs.
2026-09-18 16:33:56 -04:00
bvandeusen 3ac77261a1 Merge pull request #165 from bvandeusen/dev
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 49s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 13s
A recognized retrieval miss has a route, and the record comes first (#4133)

Closes milestone 416 at 9/9. CI 6999 green on 104c1d6.
2026-09-18 00:48:49 -04:00
bvandeusen f324be6b5a Merge pull request 'The wide net becomes a pull, and a tuned number carries the space it was measured in' (#164) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 51s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m41s
CI & Build / Build & push image (push) Successful in 19s
2026-09-17 18:50:50 -04:00
bvandeusen d9e512e9b4 Every ledger is cleared on a compact, and a retrieval floor becomes something the model maintains (#163)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 48s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m32s
CI & Build / Build & push image (push) Successful in 16s
2026-09-17 12:01:42 -04:00
bvandeusen 91cfa8da97 Merge pull request 'A rule must say when it applies; the ledger says what was read, not what was shown' (#162) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 49s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 14s
2026-09-16 17:50:08 -04:00
bvandeusen 8f3f36e6fc Merge pull request 'A directory names its project; a compaction is told what to keep; list rows say what a record is' (#161) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 49s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m32s
CI & Build / Build & push image (push) Successful in 30s
2026-09-16 08:57:45 -04:00
bvandeusen 0ac250194f Merge pull request 'Plan gate default 0.80, and an "Approval requested" reply section' (#160) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Failing after 15s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 14s
2026-09-15 15:23:01 -04:00
bvandeusen c2c92a8421 Merge pull request 'Milestone 415: an existing plan is found before a new one is made' (#159) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m38s
CI & Build / Build & push image (push) Successful in 18s
2026-09-15 14:23:31 -04:00
bvandeusen 790abdb68c Merge pull request 'Milestone 414 steps 1–3: a rule is global or belongs to one project, and retrieval honours which; #3191 read-scope fix' (#158) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 16s
2026-09-15 12:49:19 -04:00
bvandeusen b0346acd00 Merge pull request 'enter_project becomes a small primer instead of a 222k-character dump' (#157) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 47s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 15s
2026-09-14 22:12:17 -04:00
bvandeusen 0b52f894d8 Merge pull request 'Reply shapes reach the reply, a Stop hook checks completion reports, and hook pipes keep their output' (#156) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / integration (push) Successful in 48s
CI & Build / TypeScript typecheck (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m42s
CI & Build / Build & push image (push) Successful in 15s
2026-09-14 18:57:06 -04:00
bvandeusen d3375be77f Merge pull request 'Guidance by ownership, placement and report-back, and no more guessed record ids' (#155) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 14s
2026-09-14 14:16:14 -04:00
bvandeusen b7e648226b Merge pull request 'The two new retrieval bars get their Settings controls' (#154) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / Plugin hooks (push) Successful in 7s
CI & Build / integration (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m29s
CI & Build / Build & push image (push) Successful in 16s
2026-09-11 20:58:50 -04:00
bvandeusen de9431ec39 Merge pull request 'Migration 0099 matched inside words and mangled rows it rewrote' (#153) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 56s
CI & Build / TypeScript typecheck (push) Successful in 1m1s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 14s
2026-09-11 20:18:02 -04:00
bvandeusen a552deb689 Merge pull request 'Retire the always-on tier — every rule arrives by retrieval (milestone 394)' (#152) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 52s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / Python tests (push) Successful in 1m29s
CI & Build / Build & push image (push) Successful in 13s
2026-09-11 16:43:20 -04:00
bvandeusen 6da39e0298 Merge pull request 'The prompt-boundary rule arm, and a slot a preference cannot lose (#3852, #3894)' (#151) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / integration (push) Successful in 52s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m25s
CI & Build / Build & push image (push) Successful in 26s
2026-09-11 11:11:59 -04:00
bvandeusen 5f77fc29c1 Merge pull request 'Preferences — a rule kind that Scribe keeps up to date (#3849 steps 1–3)' (#150) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 58s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m27s
CI & Build / Build & push image (push) Successful in 24s
2026-09-10 23:34:16 -04:00
bvandeusen d8017f9b96 Merge pull request 'A surfaced rule stops going permanently quiet (#3750, #3751, #3752)' (#149) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 43s
CI & Build / integration (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m18s
CI & Build / Build & push image (push) Successful in 24s
2026-09-09 22:44:28 -04:00
bvandeusen a9fa8bddb6 Merge pull request 'Record WHAT the bar turned away, not only how close it came (#3807)' (#148) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 26s
CI & Build / integration (push) Successful in 47s
CI & Build / Python tests (push) Successful in 1m25s
CI & Build / Build & push image (push) Successful in 24s
2026-09-09 21:34:56 -04:00
bvandeusen cd910e32a0 Merge pull request 'A search that never ran is not a decline' (#147) from dev into main
CI & Build / Python lint (push) Successful in 6s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 42s
CI & Build / integration (push) Successful in 49s
CI & Build / Python tests (push) Successful in 1m22s
CI & Build / Build & push image (push) Successful in 16s
2026-09-09 13:36:43 -04:00
bvandeusen 1c4ace5199 Merge pull request 'write_path stops reporting records it withheld itself as near misses' (#146) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / integration (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m8s
CI & Build / Build & push image (push) Successful in 14s
2026-09-09 00:44:44 -04:00
bvandeusen 6495236569 Merge pull request 'A repeat is not a rejection, and a compaction is not knowledge' (#145) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 42s
CI & Build / Python tests (push) Successful in 1m9s
CI & Build / Build & push image (push) Successful in 15s
2026-09-09 00:13:01 -04:00
bvandeusen 53df6742cb Merge pull request 'Milestone 379 closes: the readout can now say what it did not measure' (#144) from dev into main
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / Python tests (push) Successful in 1m3s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / integration (push) Successful in 39s
CI & Build / Build & push image (push) Successful in 15s
2026-09-08 16:06:14 -04:00
bvandeusen be08edcd7e Merge pull request 'Telemetry coverage, and the rule arms stop filtering to one tier' (#143) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / integration (push) Successful in 34s
CI & Build / TypeScript typecheck (push) Successful in 24s
CI & Build / Python tests (push) Successful in 1m4s
CI & Build / Build & push image (push) Successful in 13s
2026-09-08 11:11:40 -04:00
bvandeusen 4a85220aea Merge pull request 'feat(rules): the rule arms stop filtering the corpus to one tier (#3702)' (#142) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / TypeScript typecheck (push) Successful in 39s
CI & Build / integration (push) Successful in 40s
CI & Build / Python tests (push) Successful in 1m13s
CI & Build / Build & push image (push) Successful in 19s
2026-09-08 00:31:12 -04:00
bvandeusen 14ff41faf5 Merge pull request 'feat(rules): rule creation becomes propose-then-approve (#3557)' (#141) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / TypeScript typecheck (push) Successful in 22s
CI & Build / integration (push) Successful in 30s
CI & Build / Python tests (push) Successful in 1m2s
CI & Build / Build & push image (push) Successful in 19s
2026-09-04 22:01:47 -04:00
bvandeusen 67df41ae00 Merge pull request 'feat(rules): the instruction surfaces say to RETRIEVE a rule, not only to receive one (#3523)' (#140) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m5s
CI & Build / TypeScript typecheck (push) Successful in 3m18s
CI & Build / Build & push image (push) Successful in 16s
2026-09-03 22:07:10 -04:00
bvandeusen 0915c48bb0 Merge pull request 'feat(telemetry): tell a ranker decline from a repeat before the observation window opens (#3497)' (#139) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 30s
CI & Build / Python tests (push) Successful in 1m6s
CI & Build / TypeScript typecheck (push) Successful in 5m20s
CI & Build / Build & push image (push) Successful in 17s
2026-09-03 21:23:01 -04:00
bvandeusen aea7b63b62 Merge pull request 'fix(telemetry): both rule arms logged only their hits, so the clear-rate could only read 100% (#3497)' (#138) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 30s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m5s
CI & Build / Build & push image (push) Successful in 17s
2026-09-03 07:19:08 -04:00
bvandeusen 5b02908dfd dev → main: rules become measurable at the preload, and retrievable at the tool call (#137)
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 29s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m6s
CI & Build / Build & push image (push) Successful in 17s
2026-09-02 23:41:09 -04:00
bvandeusen 34cd389371 dev → main: rule usage telemetry, the plugin's derived version (#136)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 23s
CI & Build / integration (push) Successful in 30s
CI & Build / Python tests (push) Successful in 1m5s
CI & Build / Build & push image (push) Successful in 16s
2026-09-02 18:52:20 -04:00
bvandeusen b267037911 Two milestones: a note can carry its own check (317), and a rule keeps what it used to say (323) (#135)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m37s
CI & Build / Build & push image (push) Successful in 29s
2026-08-31 00:01:15 -04:00
bvandeusen 93d660b710 Tool disambiguators, kind badges, and a badge layer that clears AA (#3123, #3124, #3132)
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 31s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m17s
CI & Build / Build & push image (push) Successful in 15s
2026-08-27 21:28:48 -04:00
bvandeusen 056c7c75da A task's kind is correctable — the Kind select stops lying (#3129)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 7s
CI & Build / integration (push) Successful in 28s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m6s
CI & Build / Build & push image (push) Successful in 15s
2026-08-27 18:05:16 -04:00
86 changed files with 350 additions and 4712 deletions
-48
View File
@@ -1,48 +0,0 @@
"""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")
-42
View File
@@ -1,42 +0,0 @@
"""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")
-38
View File
@@ -1,38 +0,0 @@
"""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")
-28
View File
@@ -1,28 +0,0 @@
"""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")
-32
View File
@@ -54,26 +54,6 @@ 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 act it governs wait for one
* read; `enforce` checks the act itself. 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. */
@@ -90,8 +70,6 @@ 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;
@@ -116,8 +94,6 @@ 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
@@ -137,10 +113,6 @@ 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;
@@ -245,8 +217,6 @@ 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;
@@ -254,8 +224,6 @@ 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;
-39
View File
@@ -147,45 +147,6 @@
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;
+1 -2
View File
@@ -2,7 +2,6 @@
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";
@@ -132,7 +131,7 @@ onMounted(loadLogs);
<button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">&times;</button>
</div>
</div>
<div class="log-content prose" v-html="renderMarkdown(log.content)" v-record-refs></div>
<div class="log-content prose" v-html="renderMarkdown(log.content)"></div>
</template>
</div>
@@ -6,11 +6,7 @@ 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 RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
type RuleTrigger, type RuleTriggerKind,
} from "@/api/rulebooks";
import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks";
const props = defineProps<{
ruleId: number | null;
@@ -30,14 +26,6 @@ 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
@@ -51,44 +39,6 @@ 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("");
@@ -173,11 +123,8 @@ 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 || "";
@@ -188,11 +135,8 @@ 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 = "";
@@ -200,9 +144,6 @@ async function load() {
}
procedureDraft.value = "";
procedureError.value = "";
triggerPattern.value = "";
triggerMoment.value = "";
triggerError.value = "";
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
}
@@ -240,16 +181,12 @@ 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
@@ -334,38 +271,6 @@ 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 act it governs waits for one
read of it. 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> — the act itself is checked. 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
@@ -437,55 +342,6 @@ 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">
@@ -664,13 +520,6 @@ 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,15 +27,6 @@ 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 act it governs waits for one read of it'
: 'The act it governs is checked against it'"
>{{ 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. -->
+1 -2
View File
@@ -51,8 +51,7 @@ 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);
// Digits alone are a record reference being typed (`#4286`), not a tag.
if (/^[\w/]*$/.test(query) && !/^\d+$/.test(query)) {
if (/^[\w/]*$/.test(query)) {
acTriggerStart = i;
acType = "tag";
debouncedSearch(query);
-199
View File
@@ -1,199 +0,0 @@
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);
},
};
+1 -3
View File
@@ -2,9 +2,7 @@ import { Extension } from "@tiptap/core";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
// 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;
const TAG_RE = /(?<=\s|^)#([\w]+(?:\/[\w]+)*)/g;
export const TagDecoration = Extension.create({
name: "tagDecoration",
-20
View File
@@ -123,26 +123,6 @@ 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",
-3
View File
@@ -111,9 +111,6 @@ 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,
+4 -7
View File
@@ -1,7 +1,6 @@
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");
@@ -21,11 +20,9 @@ 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) and not a record reference: a first line of "#4286 #4290" cites two
// records and stays in the body.
// Verify every #-token is a tag, not a heading (headings have "# " with space)
const tokens = match[1].trim().split(/\s+/);
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t) && !/^#\d+$/.test(t));
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t));
if (!allTags) return text;
return text.slice(match[0].length);
}
@@ -41,7 +38,7 @@ const headingRenderer = {
marked.use({ renderer: headingRenderer });
const PURIFY_OPTS_FULL = {
ADD_ATTR: ["data-tag", "data-title", "data-task-index", "data-ref-space", "data-ref-id"],
ADD_ATTR: ["data-tag", "data-title", "data-task-index"],
FORCE_BODY: true,
};
@@ -67,7 +64,7 @@ export function renderMarkdown(text: string, { interactiveCheckboxes = false } =
}
const withTags = linkifyTags(html);
const withLinks = linkifyRecordRefs(linkifyWikilinks(withTags));
const withLinks = linkifyWikilinks(withTags);
const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL);
// marked escapes ' to &#39; — replace after sanitization to ensure clean rendering
return sanitized.replace(/&#39;/g, "'");
-104
View File
@@ -1,104 +0,0 @@
/** 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
View File
@@ -1,9 +1,5 @@
const CODE_FENCE_RE = /```[\s\S]*?```|`[^`\n]+`/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;
const TAG_RE = /(?<!\w)(?<!&)#([\w][\w-]*(?:\/[\w][\w-]*)*)/g;
function escapeHtmlAttr(s: string): string {
return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+7 -11
View File
@@ -8,7 +8,6 @@ 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();
@@ -27,8 +26,7 @@ interface GraphNode extends SimulationNodeDatum {
interface GraphEdge {
source: number | string | GraphNode;
target: number | string | GraphNode;
/** wikilink: `[[title]]`; reference: a `#N` citation; tag: a shared tag. */
type: "wikilink" | "reference" | "tag";
type: "wikilink" | "tag";
}
interface Project {
@@ -239,14 +237,12 @@ function initGraph() {
.append("line")
.attr("class", "graph-edge")
.attr("stroke", (d: any) =>
d.type === "tag" ? "var(--fs-text-tertiary)" : "var(--fs-accent)"
d.type === "wikilink" ? "var(--fs-accent)" : "var(--fs-text-tertiary)"
)
.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)"));
.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));
// Node groups
const nodeSel = zoomG
@@ -563,7 +559,7 @@ onUnmounted(() => {
<div
v-else-if="peekBody"
class="prose peek-prose"
v-html="renderMarkdown(peekBody)" v-record-refs
v-html="renderMarkdown(peekBody)"
/>
<div v-else class="peek-empty">No content.</div>
</div>
+1 -2
View File
@@ -40,7 +40,6 @@ 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";
@@ -172,7 +171,7 @@ onMounted(load);
<div
v-if="insightHtml"
class="ld-insight markdown-body"
v-html="insightHtml" v-record-refs
v-html="insightHtml"
/>
<p v-else class="ld-muted ld-empty">
No detail was recorded — the claim above is the whole lesson.
+1 -2
View File
@@ -5,7 +5,6 @@ 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";
@@ -440,7 +439,7 @@ onUnmounted(() => assist.clearSelection());
<div
v-else
class="preview-pane prose"
v-html="renderedPreview" v-record-refs
v-html="renderedPreview"
/>
</Transition>
</template>
+3 -11
View File
@@ -3,8 +3,6 @@ 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";
@@ -16,12 +14,7 @@ import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next";
const route = useRoute();
const router = useRouter();
const store = useNotesStore();
/** 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 backlinks = ref<{ type: string; id: number; title: string }[]>([]);
const converting = ref(false);
const showShare = ref(false);
@@ -266,7 +259,7 @@ async function convertToTask() {
<div
class="body prose"
:class="{ 'prose--checklist': isListNote }"
v-html="renderedBody" v-record-refs
v-html="renderedBody"
@click="onBodyClick"
@change="onBodyChange"
></div>
@@ -281,8 +274,7 @@ async function convertToTask() {
<router-link
v-for="link in backlinks"
:key="`${link.type}-${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`"
:to="`/${link.type === 'note' ? 'notes' : 'tasks'}/${link.id}`"
class="backlink-card"
>
<span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
+3 -29
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from "vue";
import { ref, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client";
import { useAuthStore } from "@/stores/auth";
@@ -7,7 +7,6 @@ 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";
@@ -586,27 +585,8 @@ 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();
@@ -1005,15 +985,9 @@ async function confirmDelete() {
</div>
</div>
<div
v-for="group in milestoneGroups"
:key="group.milestone?.id ?? 'unassigned'"
class="milestone-group"
:data-milestone-id="group.milestone?.id"
>
<div v-for="group in milestoneGroups" :key="group.milestone?.id ?? 'unassigned'" class="milestone-group">
<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))"
@@ -1076,7 +1050,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-record-refs
v-html="renderMarkdown(group.milestone.body || '')"
></div>
<button
v-if="isPlanLong(group.milestone)"
+1 -110
View File
@@ -172,42 +172,6 @@ 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");
@@ -421,13 +385,6 @@ 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);
@@ -476,8 +433,6 @@ 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),
@@ -499,7 +454,6 @@ 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 {
@@ -903,12 +857,6 @@ 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) {
@@ -931,7 +879,6 @@ onMounted(async () => {
}
await loadTuningHistory();
await loadSurfaces();
await loadGate();
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
}
@@ -1707,7 +1654,7 @@ async function deleteUser(userId: number) {
class="fs-input input"
style="max-width: 8rem"
/>
<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>
<p class="field-hint">Ceiling on titles surfaced at once (1–10).</p>
</div>
<div class="checkbox-field">
<label>
@@ -1748,45 +1695,6 @@ 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
@@ -4350,23 +4258,6 @@ 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);
+1 -2
View File
@@ -10,7 +10,6 @@ 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();
@@ -186,7 +185,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)" v-record-refs />
<div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" />
</section>
<div v-if="snippet.tags.length" class="tag-row">
+1 -2
View File
@@ -5,7 +5,6 @@ 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";
@@ -539,7 +538,7 @@ useEditorGuards(dirty, save);
<div
v-show="showPreview"
class="preview-pane prose"
v-html="renderedPreview" v-record-refs
v-html="renderedPreview"
/>
</template>
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.23.0004",
"version": "2026.11.05.0301",
"author": {
"name": "Bryan Van Deusen"
},
-2
View File
@@ -125,8 +125,6 @@ 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")
-2
View File
@@ -240,8 +240,6 @@ 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
+12 -19
View File
@@ -79,30 +79,23 @@ 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.
#
# 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.
# 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.
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},"*) ;;
*)
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)) \
*",${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)) \
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
| tail -n 3 | paste -sd ',' - 2>/dev/null)
fi
;;
esac
[ -n "$acts" ] || exit 0
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
-2
View File
@@ -101,8 +101,6 @@ 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"
+4 -4
View File
@@ -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. 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`.
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`.
**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
-1
View File
@@ -50,7 +50,6 @@ 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]
-28
View File
@@ -781,33 +781,6 @@ 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",
@@ -827,7 +800,6 @@ 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)
-3
View File
@@ -198,12 +198,9 @@ 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
+1 -4
View File
@@ -144,10 +144,7 @@ async def create_note(
Args:
title: Note title (required).
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.
body: Markdown content. Supports [[wikilinks]] to other notes by 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
+6 -117
View File
@@ -15,7 +15,6 @@ 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
@@ -343,8 +342,6 @@ 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).
@@ -533,25 +530,6 @@ 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
@@ -561,7 +539,6 @@ 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:
@@ -576,9 +553,8 @@ 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, triggers=triggers)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
@@ -589,8 +565,6 @@ 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).
@@ -666,25 +640,6 @@ 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
@@ -693,7 +648,6 @@ 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)
@@ -708,9 +662,8 @@ 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, triggers=triggers)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
@@ -722,8 +675,6 @@ 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.
@@ -784,30 +735,9 @@ 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
@@ -829,16 +759,12 @@ 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, triggers=triggers)
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
# ── Preferences ─────────────────────────────────────────────────────────
@@ -860,8 +786,7 @@ 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, salience: str = "normal",
triggers: list[dict] | None = None,
force: bool = False,
) -> dict:
"""Record how the operator wants work done. No approval loop — write it.
@@ -935,20 +860,6 @@ 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
@@ -958,7 +869,6 @@ 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 "
@@ -983,9 +893,8 @@ 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, triggers=triggers)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data.update(dedup_svc.overlap_response(overlaps, "preference"))
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
@@ -996,8 +905,6 @@ 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.
@@ -1052,25 +959,9 @@ 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 "
@@ -1090,14 +981,12 @@ 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, triggers=triggers)
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
async def rule_history(rule_id: int, version_id: int = 0) -> dict:
+1 -6
View File
@@ -271,9 +271,7 @@ async def create_task(
Args:
title: Task title (required).
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.
body: Markdown description / notes for the task.
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).
@@ -484,9 +482,6 @@ 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
-1
View File
@@ -60,7 +60,6 @@ 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
-8
View File
@@ -74,12 +74,6 @@ 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"),
@@ -105,6 +99,4 @@ 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,
}
-69
View File
@@ -1,69 +0,0 @@
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),
}
-27
View File
@@ -116,15 +116,6 @@ 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
@@ -170,8 +161,6 @@ 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 "",
@@ -211,22 +200,6 @@ 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.
-32
View File
@@ -6,7 +6,6 @@ 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,
@@ -195,37 +194,6 @@ 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():
+17 -105
View File
@@ -14,14 +14,12 @@ 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
@@ -38,33 +36,6 @@ 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()]
@@ -167,12 +138,10 @@ async def autoinject_retrieve():
ledger is swept on compaction, which is how the
full core comes back after one.
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.
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.
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
@@ -213,32 +182,12 @@ async def autoinject_retrieve():
project_id=project_id,
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
held=frozenset(held_rule_ids),
record=False,
)
# One payload, in the one order: the rules, then the reply shape, then
# the records menu, then the lesson-rule proposal, fitted to the budget.
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.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]
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]
return jsonify(result)
@@ -316,15 +265,6 @@ 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)
@@ -361,10 +301,9 @@ 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, 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.
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.
"""
event = await request.get_json(silent=True) or {}
tool = str(event.get("tool_name") or "").strip()
@@ -381,17 +320,11 @@ 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": fitted.context,
"rule_ids": fitted.keep_only(hook_payload_svc.RULE, result.rule_ids),
"context": context,
"rule_ids": 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],
})
@@ -403,10 +336,7 @@ 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`. 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
the calls the plugin saw in the window before the `get_rule`. 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
@@ -419,13 +349,8 @@ 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) or not acts:
if rule_id <= 0 or not isinstance(acts, list):
return jsonify({"moments": [], "context": ""})
project_id, _repo, _unbound = await _project_scope()
return jsonify(await judgments_svc.opened_after(
@@ -587,19 +512,6 @@ 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)
-18
View File
@@ -57,24 +57,6 @@ 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):
+4 -49
View File
@@ -18,18 +18,6 @@ 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.
@@ -40,17 +28,6 @@ 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")
@@ -207,13 +184,6 @@ 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,
@@ -232,12 +202,11 @@ 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, triggers=triggers,
get_current_user_id(), rule, data.get("system_ids"), moments,
)), 201
@@ -265,7 +234,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", "enforcement", "salience")
"verify_with", "expires_when")
}
# No clear_fields here: a form sends "" for an emptied input, and the
# service normalises "" to NULL for every nullable text column. The MCP
@@ -274,17 +243,11 @@ 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, triggers=triggers,
uid, rule, data.get("system_ids"), moments,
))
@@ -462,13 +425,6 @@ 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,
@@ -487,12 +443,11 @@ 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, triggers=triggers,
get_current_user_id(), rule, data.get("system_ids"), moments,
)), 201
-4
View File
@@ -95,10 +95,6 @@ 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))
+1 -54
View File
@@ -23,7 +23,6 @@ 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
@@ -114,9 +113,7 @@ logger = logging.getLogger(__name__)
# section still restore — the key is simply not read.
# v28 instance_id in the header: the id lineage of the store the backup came
# from. A live instance rolls back only to a backup with its own id.
# 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
BACKUP_VERSION = 28
# 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
@@ -161,7 +158,6 @@ _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
@@ -187,10 +183,6 @@ _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.
@@ -806,15 +798,6 @@ 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."""
@@ -976,7 +959,6 @@ 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,
@@ -1033,12 +1015,6 @@ 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()
@@ -1131,7 +1107,6 @@ 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),
@@ -1293,11 +1268,6 @@ 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 []
@@ -1424,7 +1394,6 @@ 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),
@@ -1748,15 +1717,6 @@ 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
@@ -2447,7 +2407,6 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
"rule_triggers": 0,
"rule_relations": 0, "rule_versions": 0,
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
"lesson_no_rule": 0, "moment_mappings": 0,
@@ -2645,18 +2604,6 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
))
stats["rule_moments"] += 1
# A rule's triggers (v29), the same join-table shape; archives before
# v29 carry none.
for rt in data.get("rule_triggers", []):
mapped_rule = maps.rules.get(rt.get("rule_id", 0))
kind, pattern = rt.get("kind"), rt.get("pattern")
if mapped_rule is None or kind not in ("tool", "path", "command", "keyword") or not pattern:
continue
await session.execute(rule_triggers_t.insert().values(
rule_id=mapped_rule, kind=kind, pattern=pattern, moment=rt.get("moment") or "",
))
stats["rule_triggers"] += 1
# Proposals and judgments about those mounts (v23); archives before
# v23 carry none, and every rule restores unjudged.
for rj in data.get("rule_moment_judgments", []):
-219
View File
@@ -1,219 +0,0 @@
"""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
-153
View File
@@ -1,153 +0,0 @@
"""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)
]
+13 -65
View File
@@ -16,7 +16,7 @@ from __future__ import annotations
import logging
from grimoire.services import hook_payload, moment_actions, reply_shapes
from grimoire.services import moment_actions, reply_shapes
from grimoire.services import retrieval_pipeline as rp
logger = logging.getLogger(__name__)
@@ -24,15 +24,11 @@ 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_deliveries, rule_usage, rulebooks
from grimoire.services import 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,
)
@@ -53,8 +49,6 @@ 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)
@@ -65,45 +59,19 @@ 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.
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)
"""The mounted rules for moments already known to have happened."""
return await rp.run_moment_arm(
reached,
rp.RuleMoment(user_id=user_id, query="", project_id=project_id,
exclude=exclude, held=held),
io=_io(), board=board,
io=_io(),
)
@@ -112,14 +80,12 @@ 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 rules its mounts and triggers
deliver. An act that reaches no moment can still fire a trigger."""
"""Which moments this act reached, and the mounted rules they deliver."""
reached = await moment_actions.moments_for(user_id, tool, tool_input or {})
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()
if not reached:
return [], rp.RuleResult()
result = await deliver_moments(
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
user_id, reached, project_id=project_id, exclude=exclude, held=held,
)
return reached, result
@@ -147,7 +113,6 @@ _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.
@@ -158,17 +123,10 @@ 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, 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.
Returns `{context, rule_ids, shape_forms}`. 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,
@@ -178,17 +136,10 @@ 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,
"shape_parts": shape_parts, "rule_parts": rule_parts,
}
return {"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms}
async def attach_moment_rules(
@@ -340,12 +291,9 @@ async def reply_hold(
out: list[dict] = []
# The mounted half: deterministic, so every unopened RULE on these
# moments holds. A preference claims no such 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()
# moments holds. A preference claims no such force.
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" or (rule.id, at) in gated:
if rule.id in skip or rule.kind == "preference":
continue
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
"trigger": (rule.when_to_apply or "").strip()})
+18 -81
View File
@@ -986,80 +986,33 @@ 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]:
"""The records that link to this one, among those the caller may read.
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:
note = await get_note(user_id, note_id)
if note 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,
}
title = note.title
if not title:
return []
async with async_session() as session:
if note.title:
escaped = note.title.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
linking = (await session.execute(
select(Note).where(
readable,
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,
Note.id != note_id,
Note.deleted_at.is_(None),
or_(Note.body.like(f"%[[{escaped}]]%"),
Note.body.like(f"%[[{escaped}|%")),
or_(Note.body.like(pattern), Note.body.like(pattern_alias)),
)
)).scalars().all()
for n in linking:
rows[n.id] = _row(n, "wikilink")
# 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")
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]})
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())
return backlinks
_WIKILINK_RE = re.compile(r'\[\[([^\]|]+)(?:\|[^\]]+)?\]\]')
@@ -1118,22 +1071,6 @@ 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]] = {}
+13 -119
View File
@@ -17,10 +17,9 @@ 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
@@ -452,22 +451,6 @@ _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?
@@ -663,7 +646,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 or is_harness_turn(q):
if not cfg["enabled"] or not 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
@@ -728,37 +711,27 @@ 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:
named_header = (
lines.append(
"> 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.
entry = menu_entry(
lines.extend(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
@@ -767,7 +740,6 @@ 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 "
@@ -799,7 +771,6 @@ 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)
@@ -818,16 +789,11 @@ async def build_autoinject_hint(
(chunks.get(nid) or {}).get("text"), name,
)
who = _shared_by(note)
entry = menu_entry(
lines.extend(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
@@ -852,7 +818,7 @@ async def build_autoinject_hint(
]
return {
"context": "\n".join(lines), "note_ids": note_ids, "config": cfg,
"lesson_ids": lesson_ids, "parts": parts,
"lesson_ids": lesson_ids,
}
@@ -863,15 +829,9 @@ 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,
@@ -926,7 +886,6 @@ 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
@@ -960,7 +919,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
("Rule N …; it binds" / "Preference N …; how this has been done before"). Leaving
("Standing rule that may apply…" / "Preference that may apply…"). Leaving
rules unquoted separates the two claims visually with no extra prose, and
matches how a rule line already renders on both act arms.
@@ -973,7 +932,7 @@ async def build_prompt_rule_hint(
"""
out: dict = {"context": "", "rule_ids": []}
q = (query or "").strip()
if not q or is_harness_turn(q):
if not 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
@@ -999,9 +958,6 @@ 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.
@@ -1018,17 +974,10 @@ 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,
)
@@ -1626,7 +1575,6 @@ 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 = {}
@@ -1643,7 +1591,6 @@ 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.
@@ -1652,25 +1599,6 @@ 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"]:
@@ -1679,7 +1607,6 @@ 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
@@ -1706,13 +1633,12 @@ 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.
sync_header = (
lines.append(
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 "
@@ -1721,18 +1647,10 @@ 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:
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,)},
))
sync_note_ids.append(int(item["id"]))
lines.append(_prior_art_line(item, "records this file", _owner_of(item)))
menu_at = len(lines)
if menu:
lines.append(
f"> Prior art already recorded in Grimoire for `{path}` — open one with "
@@ -1767,17 +1685,10 @@ 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:
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,)},
))
note_ids.append(int(item["id"]))
lines.append(_prior_art_line(item, marker, owner, foreign_lang))
# 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
@@ -1794,23 +1705,15 @@ 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
@@ -1849,11 +1752,9 @@ 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,
@@ -1948,9 +1849,6 @@ 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)
@@ -1971,10 +1869,6 @@ 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
+1 -124
View File
@@ -1,4 +1,4 @@
"""Record references written into prose: refusing guessed ids, resolving placeholders, reading the ids a message names, and saying what a body links to.
"""Record references written into prose: refusing guessed ids, resolving placeholders, reading the ids a message names.
THE DEFECT THIS EXISTS FOR
@@ -41,7 +41,6 @@ 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
@@ -210,128 +209,6 @@ 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 ""
+147 -290
View File
@@ -35,7 +35,6 @@ 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__)
@@ -185,67 +184,139 @@ 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 line, for every arm and both kinds.
"""One rule hint line — both arms, both tails, both kinds.
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.
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.
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.
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.
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.
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.
"""
trigger = (rule.when_to_apply or "").strip()
preference = rule.kind == "preference"
noun = "Preference" if preference else "Rule"
force = PREFERENCE_FORCE if preference else RULE_FORCE
# 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.
if held:
state = "Opened earlier this session"
tail = (
f"You opened it earlier this session; pull it with "
f"get_rule({rule.id}) again if you no longer hold it."
)
elif seen:
state = "Named earlier this session, not opened"
tail = (
f"Mentioned earlier this session but not opened — read it with "
f"get_rule({rule.id}) {reason}."
)
else:
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 += "."
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.
return (
f"{noun} {rule.id} \u201c{rule.title}\u201d may apply {where}; "
+ (f"{force}: {statement}" if statement else f"{force}.")
+ f" {tail}"
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}"
)
@@ -374,12 +445,6 @@ 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).
@@ -415,7 +480,7 @@ RULE_FLOOR_DEFAULT = 0.70
# preference.
PROMPT_RULE = RuleArm(
"prompt_rule", band=False, compact_tail=False, checkpoint=False,
preference_slot=True, gates_preferences=True,
preference_slot=True,
tuning=Surface(
name="prompt_rule",
floor_key=RULE_FLOOR_KEY,
@@ -430,7 +495,7 @@ PROMPT_RULE = RuleArm(
)
PRE_TOOL_RULE = RuleArm(
"pre_tool_rule", band=True, compact_tail=True, checkpoint=True,
preference_slot=True, gates_preferences=True,
preference_slot=True,
tuning=Surface(
name="pre_tool_rule",
floor_key=RULE_FLOOR_KEY,
@@ -445,7 +510,7 @@ PRE_TOOL_RULE = RuleArm(
)
WRITE_PATH_RULE = RuleArm(
"write_path_rule", band=True, compact_tail=True, checkpoint=True,
preference_slot=True, gates_preferences=True,
preference_slot=True,
tuning=Surface(
name="write_path_rule",
floor_key=RULE_FLOOR_KEY,
@@ -511,18 +576,6 @@ 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)
@@ -563,13 +616,6 @@ class RuleResult:
checkpoint: dict = field(default_factory=dict)
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 ───────────────────────────────────────────────────────────
@@ -587,35 +633,9 @@ 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, gate=None,
band: bool = False, kind: str | None = None,
) -> tuple[list, list, list]:
"""Search, band, split fresh from repeats, and log the call — every call.
@@ -645,11 +665,6 @@ async def _ranked(
hits = [(score, rule) for score, rule in hits
if getattr(rule, "kind", None) == kind]
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(
@@ -661,7 +676,6 @@ 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)
@@ -669,7 +683,7 @@ async def _ranked(
async def _reserve_slot_for_preference(
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float, gate=None,
io: RuleIO, moment: RuleMoment, hits: list, *, floor: float,
) -> tuple[list, int | None]:
"""Guarantee a preference one slot, if one clears the bar.
@@ -720,12 +734,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", gate=gate,
kind="preference",
)
seen = {rule.id for _s, rule in hits}
slot = [(s, r) for s, r in kept
slot = [(s, r) for s, r in found
if r.kind == "preference" and r.id not in seen][:1]
if not slot:
return hits, None
@@ -759,55 +773,6 @@ 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,
@@ -818,13 +783,9 @@ 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, gate=gate,
band=arm.band, kind=arm.kind,
)
shown = kept
if arm.preference_slot:
@@ -834,29 +795,12 @@ 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, gate=gate,
io, moment, shown, floor=floor,
)
# 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(
@@ -892,11 +836,6 @@ 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],
@@ -1123,10 +1062,6 @@ 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
@@ -1138,7 +1073,6 @@ 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",
@@ -1161,7 +1095,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, gated=True,
withholds=True,
tuning=Surface(
name="write_path",
floor_key="kb_writepath_threshold",
@@ -1214,8 +1148,6 @@ 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)
@@ -1261,9 +1193,6 @@ 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.
@@ -1280,7 +1209,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], capped: bool = False,
*, floor: float, budget: int, shown: set[int],
) -> tuple[list, int | None]:
"""Guarantee `slot.kinds` one line, if one clears the arm's own bar.
@@ -1309,10 +1238,6 @@ 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 = {}
@@ -1383,10 +1308,6 @@ 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
@@ -1418,12 +1339,6 @@ 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(
@@ -1442,34 +1357,21 @@ 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 {}, gate=gate,
)
result = NoteResult(answered=answered, chunks=report.get("best_chunk") or {})
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, capped=gate is not None,
shown=shown,
)
if slot_id is not None:
result.slot_ids[slot.source] = slot_id
@@ -1695,12 +1597,6 @@ 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:
@@ -1710,7 +1606,7 @@ def _reached_by(hit: dict) -> str:
async def run_moment_arm(
reached: list[dict], moment: RuleMoment, *, io: MomentIO,
limit: int = MOMENT_RULE_LIMIT, board: Any = None,
limit: int = MOMENT_RULE_LIMIT,
) -> RuleResult:
"""Deliver the rules mounted on the moments this act reached.
@@ -1721,66 +1617,30 @@ 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]
fired = list(board.fired) if board is not None else []
if not names and not fired:
if not names:
return RuleResult()
pairs = await io.lookup(moment.user_id, names, moment.project_id or None)
if not pairs:
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}
# (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))
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()
# 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]
# Stable: catalog order within each half, fresh half first.
shown = sorted(pairs, key=lambda pair: pair[0].id in moment.exclude)[:limit]
lines = []
for rule, at, where in shown:
for rule, at in shown:
seen = rule.id in moment.exclude
lines.append(_rule_hint_line(
rule,
where=where,
where=f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
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, _where in shown if rule.id not in moment.exclude]
fresh = [(rule, at) for rule, at in shown if rule.id not in moment.exclude]
rule_ids = [rule.id for rule, _at in fresh]
if rule_ids:
try:
@@ -1791,13 +1651,10 @@ 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, _where in shown],
shown=[(None, rule) for rule, _at, _where in shown],
shown_rule_ids=[rule.id for rule, _at in shown],
shown=[(None, rule) for rule, _at in shown],
)
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
+2 -2
View File
@@ -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 rule against a situation, which is why
the injected line carries the rule's statement rather than a verdict.
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").
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,8 +152,6 @@ 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.
@@ -202,14 +200,6 @@ 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),
}
@@ -249,8 +239,6 @@ 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.
@@ -304,8 +292,6 @@ 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)
-230
View File
@@ -1,230 +0,0 @@
"""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
-80
View File
@@ -1,80 +0,0 @@
"""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}
# 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)
-289
View File
@@ -1,289 +0,0 @@
"""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
+6 -71
View File
@@ -273,38 +273,6 @@ 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
@@ -371,14 +339,8 @@ 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:
@@ -470,9 +432,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, triggers: list | None = None,
moments: list[str] | None = None,
) -> dict:
"""The full record, with its areas, moments, triggers and edges attached.
"""The full record, with its areas, moments 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
@@ -482,21 +444,15 @@ 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; `triggers` the same way, with
`rule_triggers.require_triggers`, and it replaces them the same way.
refused without leaving a rule behind.
"""
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.
@@ -504,8 +460,6 @@ 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
@@ -552,12 +506,8 @@ 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(
@@ -565,7 +515,7 @@ async def create_rule(
title=title,
statement=statement,
when_to_apply=when_to_apply or None,
kind=kind, enforcement=enforcement, salience=salience,
kind=_valid_kind(kind),
why=why or None,
how_to_apply=how_to_apply or None,
verify_with=verify_with or None,
@@ -585,7 +535,6 @@ 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).
@@ -595,9 +544,6 @@ 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(
@@ -605,7 +551,7 @@ async def create_project_rule(
title=title,
statement=statement,
when_to_apply=when_to_apply or None,
kind=kind, enforcement=enforcement, salience=salience,
kind=_valid_kind(kind),
why=why or None,
how_to_apply=how_to_apply or None,
verify_with=verify_with or None,
@@ -745,7 +691,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", "enforcement", "salience",
"verify_with", "expires_when",
}
check_before = rule.verify_with
# A create-time guard is worth nothing if an edit can undo it, and
@@ -773,11 +719,6 @@ 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":
@@ -790,12 +731,6 @@ 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, "
+7 -46
View File
@@ -258,46 +258,6 @@ 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,
@@ -766,10 +726,11 @@ 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 = await provisional_row(
session, project_id=project_id, repo_key=repo_key, path=path,
row = CodeShape(
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
@@ -1694,13 +1655,13 @@ async def suggest_write_path_instances(
if row is None:
if not repo_key:
continue
# It may be a vanished row coming back, with its judgment.
row = await provisional_row(
session, project_id=project_id, repo_key=repo_key,
row = CodeShape(
project_id=project_id, repo_key=repo_key,
path=path, symbol=name, kind=kind,
)
session.add(row)
by_key[(name, kind)] = row
if not (row.status in _MECHANICAL_TODO or row.classified_by == "hook"):
elif 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
+2 -6
View File
@@ -1,15 +1,11 @@
import re
_CODE_FENCE_RE = re.compile(r"```[\s\S]*?```|`[^`\n]+`")
# 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-]*)*)")
_TAG_RE = re.compile(r"(?<!\w)#([\w][\w-]*(?:/[\w][\w-]*)*)")
def extract_tags(body: str) -> list[str]:
"""Extract #tags from body text, ignoring code blocks and record references."""
"""Extract #tags from body text, ignoring code blocks."""
cleaned = _CODE_FENCE_RE.sub("", body)
tags = _TAG_RE.findall(cleaned)
return sorted(set(tags))
-53
View File
@@ -273,23 +273,6 @@ def _no_moment_delivery(request):
yield
@pytest.fixture(autouse=True)
def _no_rule_triggers(request):
"""Stub the database read behind a rule's triggers.
Every act the moment door sees checks the in-scope triggers, which is a
read; stubbed to "no rule carries a trigger" so a unit test of mounts sees
mounts only. The matching itself is pure and tested unstubbed in
tests/test_rule_triggers.py; the read against Postgres in
tests/test_integration_rule_triggers.py, which this skips.
"""
if request.node.get_closest_marker("integration"):
yield
return
with patch("grimoire.services.rule_triggers._in_scope", AsyncMock(return_value=[])):
yield
@pytest.fixture(autouse=True)
def _no_rule_arm():
"""Stub the write-path hint's standing-RULES arm.
@@ -347,39 +330,3 @@ def _default_gate_bars():
with patch("grimoire.services.dedup._gate_setting", AsyncMock(side_effect=_default)):
yield
@pytest.fixture(autouse=True)
def _default_payload_budget(request):
"""Stub the settings read behind a hook payload's budget.
Every injecting plugin door fits its payload through `hook_payload.fit`,
which reads the user's budget; stubbed to the default so a unit test of a
door needs no database. The integration lane reads the real setting.
"""
if request.node.get_closest_marker("integration"):
yield
return
from grimoire.services import hook_payload
with patch.object(hook_payload, "payload_budget",
AsyncMock(return_value=hook_payload.DEFAULT_BUDGET)):
yield
@pytest.fixture(autouse=True)
def _ungated_doors(request):
"""Leave the plugin doors' cue-swap gate off unless a test asks for it.
The gate reads the user's earlier cues from `retrieval_logs`, which a
test that is about something else has not written, so with it on every
door would abstain. A test of the gate marks itself `cue_gate`, or calls
`cue_gate` directly.
"""
if request.node.get_closest_marker("cue_gate"):
yield
return
from grimoire.services import plugin_context
with patch.object(plugin_context, "_gate_for", AsyncMock(return_value=None)):
yield
+1 -4
View File
@@ -290,9 +290,6 @@ def fake_rule(**attrs) -> MagicMock:
# claim to carry a check and rule_brief would stamp a MagicMock date
# onto all of them. Most rules have none — that is the default here.
"verify_with": None, "expires_when": None, "verified_at": None,
# A MagicMock here would read as a declared enforcement and a raised
# salience on every stand-in; the defaults are what a new rule gets.
"enforcement": "inform", "salience": "normal",
"order_index": 0, "created_at": _now(), "updated_at": _now(),
}, attrs)
@@ -310,7 +307,7 @@ def plain_rule_detail():
stubbing the seam slightly differently is a test asserting something
slightly different than it appears to.
"""
async def _detail(_uid, rule, _system_ids=None, _moments=None, **_kw):
async def _detail(_uid, rule, _system_ids=None, _moments=None):
return rule.to_dict()
return patch("grimoire.mcp.tools.rulebooks.rulebooks_svc.rule_detail", _detail)
-181
View File
@@ -1,181 +0,0 @@
"""The cue-swap gate: when a record found by resemblance alone may speak.
The property it exists for is pinned by replay: on cues that match nothing in
particular, a fixed similarity bar fires more and more often as the store
grows, while the gate fires at about its rate on a small store and a large
one alike. Then the arms that take it: a notes menu abstains unless its top
line is unusual for this reader and shows at most two lines; a preference
found by resemblance is held to the gate while a rule is not.
"""
from __future__ import annotations
import random
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from grimoire.services import cue_gate
from grimoire.services import retrieval_pipeline as rp
from grimoire.services.cue_gate import Gate, conformal_bar
from tests.helpers import fake_note
# ── the statistic ──────────────────────────────────────────────────────────
def test_too_few_cues_to_judge_by_is_no_bar():
assert conformal_bar([0.5] * (cue_gate.MIN_SAMPLE - 1), 10) is None
assert Gate(bar=None, sample=3, rate=10).passes(0.99) is False
def test_the_bar_beats_all_but_the_rate_of_earlier_cues():
scores = [i / 100 for i in range(100)] # 0.00 … 0.99
# k = ceil(101 * 0.9) = 91, so the bar is the 91st smallest: 0.90.
assert conformal_bar(scores, 10) == pytest.approx(0.90)
assert conformal_bar(scores, 50) == pytest.approx(0.50)
def test_the_rate_setting_is_clamped():
assert cue_gate.clamp_rate("0") == cue_gate.RATE_MIN
assert cue_gate.clamp_rate("90") == cue_gate.RATE_MAX
assert cue_gate.clamp_rate("x") == cue_gate.RATE_DEFAULT
def _best_of(store_size: int, rng: random.Random) -> float:
"""The best score a cue that matches nothing reaches against a store:
the maximum of `store_size` unrelated resemblances."""
return max(0.45 + 0.05 * rng.gauss(0, 1) for _ in range(store_size))
def test_on_unrelated_cues_a_fixed_bar_fires_more_as_the_store_grows_and_the_gate_does_not():
rng = random.Random(7)
small, large, calibration, trials, rate = 32, 2048, 200, 400, 10
def cues(n, count):
return [_best_of(n, rng) for _ in range(count)]
# A fixed bar tuned to fire on 5% of unrelated cues against the small store.
tuned = sorted(cues(small, 1000))[949]
fired = {}
for n in (small, large):
bar = conformal_bar(cues(n, calibration), rate)
test = cues(n, trials)
fired[n] = (
sum(s >= tuned for s in test) / trials,
sum(s >= bar for s in test) / trials,
)
fixed_small, gate_small = fired[small]
fixed_large, gate_large = fired[large]
assert fixed_small < 0.10 and fixed_large > 0.80, fired
assert gate_small <= 0.16 and gate_large <= 0.16, fired
assert abs(gate_small - gate_large) < 0.08, fired
# ── the notes arm ──────────────────────────────────────────────────────────
def _note(nid, score):
return score, fake_note(id=nid, title=f"record {nid}", user_id=1)
def _note_io(hits, gate):
async def search(_uid, _q, **kw):
return [] if kw.get("note_type") else list(hits)
return rp.NoteIO(search=search, record_retrieval=MagicMock(),
record_surfaced=MagicMock(), gate=AsyncMock(return_value=gate))
async def _menu(hits, gate, budget=4):
io = _note_io(hits, gate)
result = await rp.run_note_arm(
rp.AUTO_INJECT, rp.NoteMoment(user_id=1, query="q", project_id=2),
floor=0.5, budget=budget, io=io,
)
return result, io
@pytest.mark.asyncio
async def test_a_menu_speaks_only_past_the_gate_and_at_most_two_lines():
hits = [_note(1, 0.86), _note(2, 0.85), _note(3, 0.84), _note(4, 0.83)]
result, io = await _menu(hits, Gate(bar=0.80, sample=200, rate=10))
assert [int(n.id) for _s, n in result.menu] == [1, 2]
(row,) = [c.kwargs for c in io.record_retrieval.call_args_list
if c.kwargs["source"] == "auto_inject"]
assert row["gate_bar"] == 0.80 and row["gate_kept"] == 2
# The searched candidates are still the row's results: they are what the
# next call's comparison set and any floor review read.
assert len(row["results"]) == 4
@pytest.mark.asyncio
async def test_a_cue_whose_best_match_is_ordinary_gets_nothing():
hits = [_note(1, 0.79), _note(2, 0.75)]
result, io = await _menu(hits, Gate(bar=0.80, sample=200, rate=10))
assert result.menu == []
io.record_surfaced.assert_not_called()
(row,) = [c.kwargs for c in io.record_retrieval.call_args_list]
assert row["gate_kept"] == 0
@pytest.mark.asyncio
async def test_an_uncalibrated_gate_is_silence_and_no_gate_is_the_old_menu():
hits = [_note(1, 0.95), _note(2, 0.90)]
quiet, _ = await _menu(hits, Gate(bar=None, sample=4, rate=10))
assert quiet.menu == []
ungated, _ = await _menu(hits, None)
assert [int(n.id) for _s, n in ungated.menu] == [1, 2]
# ── preferences on the rule arms ──────────────────────────────────────────
def _rule(rid, kind):
return SimpleNamespace(id=rid, title=f"{kind} {rid}", kind=kind, statement="Said plainly.",
when_to_apply="when", enforcement="inform", salience="normal")
@pytest.mark.asyncio
async def test_a_preference_found_by_resemblance_is_held_to_the_gate_and_a_rule_is_not():
hits = [(0.78, _rule(1, "rule")), (0.77, _rule(2, "preference")), (0.92, _rule(3, "preference"))]
hits.sort(key=lambda h: -h[0])
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock(),
gate=AsyncMock(return_value=Gate(bar=0.85, sample=200, rate=10)))
result = await rp.run_rule_arm(
rp.PROMPT_RULE, rp.RuleMoment(user_id=1, query="q", project_id=2, where="here"),
floor=0.5, budget=5, io=io,
)
assert sorted(result.shown_rule_ids) == [1, 3]
row = io.record_retrieval.call_args_list[0].kwargs
assert row["gate_bar"] == 0.85 and row["gate_kept"] == 1
def test_the_reply_backstop_takes_no_gate():
assert rp.REPLY_RULE.gates_preferences is False
assert all(arm.gates_preferences for arm in (rp.PROMPT_RULE, rp.PRE_TOOL_RULE, rp.WRITE_PATH_RULE))
assert rp.AUTO_INJECT.gated and rp.WRITE_PATH.gated
# ── turns the harness wrote ───────────────────────────────────────────────
def test_a_turn_the_harness_wrote_is_not_searched():
from grimoire.services.plugin_context import is_harness_turn
assert is_harness_turn(" <task-notification><task-id>x</task-id>")
assert is_harness_turn("<command-name>/compact</command-name>")
assert not is_harness_turn("merge it and redeploy")
@pytest.mark.asyncio
async def test_the_prompt_menu_refuses_a_harness_turn(monkeypatch):
from grimoire.services import plugin_context
monkeypatch.setattr(plugin_context, "get_autoinject_config", AsyncMock(
return_value={"enabled": True, "threshold": 0.55, "top_k": 3}))
search = AsyncMock(return_value=[])
monkeypatch.setattr(plugin_context, "semantic_search_notes", search)
out = await plugin_context.build_autoinject_hint(1, "<task-notification>done</task-notification>")
assert out["context"] == "" and not search.called
-110
View File
@@ -1,110 +0,0 @@
"""A hook payload fitted to a budget: what is kept, in what order, what its
ids say, and which rule deliveries are recorded."""
import contextvars
from unittest.mock import MagicMock, patch
from grimoire.services import hook_payload as hp
from grimoire.services import rule_deliveries
from grimoire.services.hook_payload import Part
def _p(text, **kw):
return Part(text=text, **kw)
def test_parts_are_kept_in_order_and_the_payload_stays_within_the_budget():
parts = [_p("a" * 600, ids={hp.RULE: (1,)}), _p("b" * 600, ids={hp.RULE: (2,)}),
_p("c" * 600, ids={hp.NOTE: (9,)})]
fitted = hp.assemble(parts, 1300)
assert len(fitted.context) <= 1300
assert fitted.ids(hp.RULE) == [1, 2] and fitted.ids(hp.NOTE) == []
assert fitted.context.index("a") < fitted.context.index("b")
def test_a_part_that_does_not_fit_is_skipped_and_a_smaller_later_one_still_fits():
parts = [_p("r" * 500), _p("S" * 2000, ids={hp.SHAPE: ("core",)}), _p("n" * 300, ids={hp.NOTE: (4,)})]
fitted = hp.assemble(parts, 1000)
assert "S" not in fitted.context
assert fitted.ids(hp.SHAPE) == [] and fitted.ids(hp.NOTE) == [4]
def test_a_blocks_header_prints_once_before_its_first_kept_part_and_is_charged():
head = "> Possibly relevant:"
parts = [_p("> - #1 one", block="menu", header=head, ids={hp.NOTE: (1,)}),
_p("> - #2 two", block="menu", header=head, ids={hp.NOTE: (2,)})]
fitted = hp.assemble(parts, 5000)
assert fitted.context == f"{head}\n> - #1 one\n> - #2 two"
# The header counts against the part it rides: one that fits alone does
# not fit once its block's header is added.
long_head, line = "h" * 600, "x" * 500
tight = hp.assemble([_p(line, block="m", header=long_head, ids={hp.NOTE: (1,)})], 1000)
assert tight.context == "" and tight.ids(hp.NOTE) == []
def test_separate_blocks_are_separated_by_a_blank_line():
fitted = hp.assemble([_p("rule", block="rules"), _p("shape")], 5000)
assert fitted.context == "rule\n\nshape"
def test_keep_only_filters_a_response_list_to_what_was_shown():
fitted = hp.assemble([_p("x" * 400, ids={hp.RULE: (3,)}), _p("y" * 9000, ids={hp.RULE: (5,)})], 2000)
assert fitted.keep_only(hp.RULE, [5, 3, 7]) == [3]
def test_the_budget_is_bounded_under_the_hook_context_cap():
assert hp.HARD_MAX < 8_000
assert hp.clamp(50_000) == hp.HARD_MAX
assert hp.clamp(10) == hp.MIN_BUDGET
assert hp.clamp("not a number") == hp.DEFAULT_BUDGET
assert hp.MIN_BUDGET <= hp.DEFAULT_BUDGET <= hp.HARD_MAX
def test_a_result_without_parts_is_one_part_carrying_all_its_ids():
result = {"context": "whole", "rule_ids": [1, 2]}
parts = hp.parts_of(result, {hp.RULE: "rule_ids"})
assert parts == [Part(text="whole", ids={hp.RULE: (1, 2)})]
assert hp.parts_of({"context": ""}, {}) == []
own = {"context": "c", "parts": [_p("p")]}
assert hp.parts_of(own, {}) == [_p("p")] and "parts" not in own
def test_rule_parts_pair_each_line_with_its_rule():
parts = hp.rule_parts(["one", "two"], [11, 34], block="rules")
assert [p.ids[hp.RULE] for p in parts] == [(11,), (34,)]
# ── the delivery record ────────────────────────────────────────────────
# Each runs in a copy of the context, so the session it binds ends with it.
def test_a_bound_request_records_only_the_rule_lines_that_were_kept():
contextvars.copy_context().run(_bound_request_records_only_kept)
def _bound_request_records_only_kept():
spawned = MagicMock()
with patch.object(rule_deliveries, "spawn", spawned), \
patch.object(rule_deliveries, "_insert", lambda rows: rows):
rule_deliveries.bind_session("s-1")
rule_deliveries.record(1, None, "pre_tool_rule", [(11, "pre_tool_rule", "full"),
(34, "pre_tool_rule", "full")])
assert not spawned.called, "a bound request's rows wait for the payload"
rule_deliveries.flush({11})
rows = spawned.call_args.args[0]
assert [r["rule_id"] for r in rows] == [11]
spawned.reset_mock()
rule_deliveries.flush()
assert not spawned.called, "the buffer is spent once flushed"
def test_a_session_named_outright_records_at_once():
contextvars.copy_context().run(_named_session_records_at_once)
def _named_session_records_at_once():
spawned = MagicMock()
with patch.object(rule_deliveries, "spawn", spawned), \
patch.object(rule_deliveries, "_insert", lambda rows: rows):
rule_deliveries.bind_session("s-2")
rule_deliveries.record(1, "other", "x", [(5, "x", "full")])
assert spawned.called
-71
View File
@@ -1,71 +0,0 @@
"""Real-Postgres tests for the cue-swap gate: its comparison set is the user's
own recent cues on one surface and scope, read from `retrieval_logs`."""
import pytest
from sqlalchemy import delete
from grimoire.models import async_session
from grimoire.models.retrieval_log import RetrievalLog
from grimoire.services import cue_gate
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
SOURCE = "auto_inject"
async def _user() -> int:
async with async_session() as s:
user = await ensure_user(s, "cue_gate_owner")
uid = user.id
await s.commit()
await s.execute(delete(RetrievalLog).where(RetrievalLog.user_id == uid))
await s.commit()
cue_gate.forget(uid)
return uid
async def _cues(uid, scores, *, project_id=None, source=SOURCE):
async with async_session() as s:
for score in scores:
s.add(RetrievalLog(user_id=uid, source=source, query="q", project_id=project_id,
result_count=0, result_ids=[], best_available_score=score))
await s.commit()
async def test_the_bar_is_read_from_this_users_cues_on_this_surface_and_project():
uid = await _user()
await _cues(uid, [i / 100 for i in range(100)], project_id=5)
# Another surface's cues and another project's do not move it.
await _cues(uid, [0.99] * 50, project_id=5, source="write_path")
await _cues(uid, [0.99] * 50, project_id=6)
gate = await cue_gate.gate_for(uid, SOURCE, 5)
assert gate.scope == "project" and gate.sample == 100
assert gate.bar == pytest.approx(0.90)
assert gate.passes(0.91) and not gate.passes(0.89)
async def test_a_project_with_too_few_cues_borrows_the_users_cues_everywhere():
uid = await _user()
await _cues(uid, [0.5] * 30, project_id=7)
await _cues(uid, [0.6] * 5, project_id=8)
gate = await cue_gate.gate_for(uid, SOURCE, 8)
assert gate.scope == "all" and gate.sample == 35
async def test_with_too_few_cues_anywhere_nothing_passes():
uid = await _user()
await _cues(uid, [0.5] * 5)
gate = await cue_gate.gate_for(uid, SOURCE, None)
assert gate.bar is None and not gate.passes(0.99)
async def test_the_readout_counts_how_often_a_surface_spoke():
uid = await _user()
await _cues(uid, [0.5] * 25)
async with async_session() as s:
for kept in (0, 0, 2, 1):
s.add(RetrievalLog(user_id=uid, source=SOURCE, query="q", result_count=0,
result_ids=[], gate_bar=0.8, gate_kept=kept))
await s.commit()
(row,) = await cue_gate.readout(uid, [(SOURCE, "records")])
assert row["calls"] == 4 and row["fired"] == 2 and row["sample"] == 25
-106
View File
@@ -1,106 +0,0 @@
"""Real-Postgres proof that a reference resolves only to what the reader may open, and that backlinks follow `#N`.
What mocks cannot show: the access clause applied in SQL to a shared project,
the LIKE prefilter not admitting `#12` as a link to 1, and a citation in a work
log reaching the cited record's backlinks.
"""
import pytest
import pytest_asyncio
from grimoire.models import async_session
from grimoire.models.milestone import Milestone
from grimoire.models.note import Note
from grimoire.models.project import Project
from grimoire.models.share import ProjectShare
from grimoire.models.task_log import TaskLog
from grimoire.services.notes import get_backlinks
from grimoire.services.record_refs import resolve_refs
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine", "_no_embedding")]
@pytest_asyncio.fixture
async def world():
async with async_session() as s:
owner = await ensure_user(s, "ref_links_owner")
reader = await ensure_user(s, "ref_links_reader")
stranger = await ensure_user(s, "ref_links_stranger")
shared = Project(user_id=owner.id, title="Shared project")
private = Project(user_id=owner.id, title="Private project")
s.add_all([shared, private])
await s.flush()
s.add(ProjectShare(project_id=shared.id, shared_with_user_id=reader.id,
permission="viewer", invited_by=owner.id))
target = Note(user_id=owner.id, project_id=shared.id, title="Target", body="")
hidden = Note(user_id=owner.id, project_id=private.id, title="Hidden", body="")
lesson = Note(user_id=owner.id, project_id=shared.id, title="A lesson",
body="", note_type="lesson")
ms_shared = Milestone(user_id=owner.id, project_id=shared.id, title="Shared plan")
ms_private = Milestone(user_id=owner.id, project_id=private.id, title="Private plan")
s.add_all([target, hidden, lesson, ms_shared, ms_private])
await s.flush()
ids = {
"owner": owner.id, "reader": reader.id, "stranger": stranger.id,
"shared": shared.id, "target": target.id, "hidden": hidden.id,
"lesson": lesson.id, "ms_shared": ms_shared.id, "ms_private": ms_private.id,
}
await s.commit()
return ids
async def test_the_owner_resolves_every_kind_with_its_route_fields(world):
out = await resolve_refs(
world["owner"],
notes=[world["target"], world["lesson"], world["hidden"]],
milestones=[world["ms_shared"], world["ms_private"]],
)
assert set(out["notes"]) == {world["target"], world["lesson"], world["hidden"]}
assert out["notes"][world["lesson"]]["note_type"] == "lesson"
assert out["notes"][world["target"]]["is_task"] is False
assert out["milestones"][world["ms_shared"]]["project_id"] == world["shared"]
async def test_a_collaborator_resolves_the_shared_project_and_nothing_else(world):
out = await resolve_refs(
world["reader"],
notes=[world["target"], world["hidden"]],
milestones=[world["ms_shared"], world["ms_private"]],
)
assert set(out["notes"]) == {world["target"]}
assert set(out["milestones"]) == {world["ms_shared"]}
async def test_unreadable_and_nonexistent_ids_read_the_same(world):
"""Absent either way, so the resolver cannot be used to probe for ids."""
out = await resolve_refs(world["stranger"], notes=[world["target"], 2_000_000_000])
assert out["notes"] == {}
async def test_backlinks_follow_references_in_bodies_and_work_logs(world):
t = world["target"]
async with async_session() as s:
citing = Note(user_id=world["owner"], project_id=world["shared"],
title="Cites it", body=f"Builds on #{t}.")
logged = Note(user_id=world["owner"], project_id=world["shared"],
title="Logs it", body="", status="todo")
other_space = Note(user_id=world["owner"], project_id=world["shared"],
title="Other numbering", body=f"See PR #{t}.")
longer = Note(user_id=world["owner"], project_id=world["shared"],
title="Longer id", body=f"See #{t}0.")
s.add_all([citing, logged, other_space, longer])
await s.flush()
s.add(TaskLog(task_id=logged.id, user_id=world["owner"], content=f"Fixed with #{t} in mind."))
ids = {"citing": citing.id, "logged": logged.id}
await s.commit()
rows = await get_backlinks(world["owner"], t)
by_id = {r["id"]: r for r in rows}
assert set(by_id) == {ids["citing"], ids["logged"]}
assert by_id[ids["citing"]]["via"] == "reference"
assert by_id[ids["logged"]]["is_task"] is True
# The collaborator sees the same backlinks, since every record is in the
# project shared with them; a stranger cannot open the target at all.
assert {r["id"] for r in await get_backlinks(world["reader"], t)} == set(by_id)
assert await get_backlinks(world["stranger"], t) == []
-130
View File
@@ -1,130 +0,0 @@
"""Real-Postgres tests for `rule_deliveries`: a delivery recorded against a
session, the open stamped on the one it followed, and the history read back."""
import asyncio
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select, update
from grimoire.models import async_session
from grimoire.models.rule_delivery import RuleDelivery
from grimoire.services import background, rule_deliveries
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_100_001
OTHER = 9_100_002
async def _user() -> int:
async with async_session() as s:
user = await ensure_user(s, "rule_delivery_owner")
uid = user.id
await s.commit()
await s.execute(delete(RuleDelivery).where(RuleDelivery.user_id == uid))
await s.commit()
return uid
async def _rows(uid: int) -> list[RuleDelivery]:
async with async_session() as s:
return list((await s.execute(
select(RuleDelivery).where(RuleDelivery.user_id == uid).order_by(RuleDelivery.id)
)).scalars().all())
async def _record(uid, sid, source, lines):
# A bound request's rows wait for the door's payload; flushing all of
# them is what a door does when every line it rendered was kept.
rule_deliveries.record(uid, sid, source, lines)
rule_deliveries.flush()
await background.drain()
async def test_an_open_is_stamped_on_the_sessions_latest_delivery_only():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full")])
await asyncio.sleep(0.01)
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "repeat")])
await _record(uid, "s-2", "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
rows = await _rows(uid)
opened = [(r.session_id, r.form) for r in rows if r.opened_at is not None]
assert opened == [("s-1", "repeat")]
# A second open with nothing left unopened in the session stamps the earlier one.
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is True
assert await rule_deliveries.mark_opened(uid, "s-1", RULE) is False
async def test_an_open_with_no_delivery_behind_it_stamps_nothing():
uid = await _user()
assert await rule_deliveries.mark_opened(uid, "s-1", OTHER) is False
assert await rule_deliveries.mark_opened(uid, "", RULE) is False
async def test_without_a_session_nothing_is_recorded():
uid = await _user()
rule_deliveries.bind_session("")
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
assert await _rows(uid) == []
async def test_a_bound_session_is_the_one_recorded():
uid = await _user()
rule_deliveries.bind_session("bound s/3")
await _record(uid, None, "prompt_rule", [(RULE, "prompt_rule", "full")])
# The plugin's filename-safe form, so the raw and safe ids agree.
assert [r.session_id for r in await _rows(uid)] == ["bound_s_3"]
rule_deliveries.bind_session("")
async def test_history_is_the_smoothed_open_rate_at_each_place():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full")] * 3
+ [(RULE, "work.deliver", "full"), (OTHER, "work.finish", "full")])
await rule_deliveries.mark_opened(uid, "s-1", RULE) # one of the five RULE rows
history = await rule_deliveries.history(uid, [(RULE, "work.finish"), (OTHER, "work.finish")])
rows = await _rows(uid)
stamped_at = next(r.at for r in rows if r.opened_at is not None)
finish_opened = 1 if stamped_at == "work.finish" else 0
assert history[RULE] == pytest.approx((finish_opened + 1) / (3 + 2))
assert history[OTHER] == pytest.approx(1 / 3)
# A place with no delivery is unknown, not zero.
assert await rule_deliveries.history(uid, [(RULE, "reply.report")]) == {}
async def test_old_deliveries_are_pruned():
uid = await _user()
await _record(uid, "s-1", "moment_rule", [(RULE, "work.finish", "full"), (OTHER, "work.finish", "full")])
async with async_session() as s:
await s.execute(
update(RuleDelivery)
.where(RuleDelivery.user_id == uid, RuleDelivery.rule_id == RULE)
.values(delivered_at=datetime.now(timezone.utc) - timedelta(days=rule_deliveries.RETAIN_DAYS + 1))
)
await s.commit()
assert await rule_deliveries.prune() >= 1
assert [r.rule_id for r in await _rows(uid)] == [OTHER]
async def test_a_rule_retires_after_its_reminder_and_a_full_line_re_arms_it():
uid = await _user()
rule_deliveries.bind_session("s-life")
try:
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.retired(uid, [RULE]) == set()
await asyncio.sleep(0.01)
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "repeat")])
assert await rule_deliveries.retired(uid, [RULE, OTHER]) == {RULE}
await asyncio.sleep(0.01)
# The ledger forgot it (a compaction): the next line is full, and re-arms it.
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
assert await rule_deliveries.retired(uid, [RULE]) == set()
# Another session's reminder retires nothing here.
await _record(uid, "s-other", "moment_rule", [(OTHER, "work.finish", "repeat")])
assert await rule_deliveries.retired(uid, [OTHER]) == set()
finally:
rule_deliveries.bind_session("")
-116
View File
@@ -1,116 +0,0 @@
"""Real-Postgres tests for `rules.enforcement` and `rules.salience` (migration 0128).
The CHECKs are what a mock cannot show: an unknown value refused, a preference
refused anything but `inform`, and a row written without either reading back
as the defaults every existing rule took on upgrade.
"""
import pytest
import pytest_asyncio
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from grimoire.models import async_session
from grimoire.models.rulebook import Rule, Rulebook
from grimoire.services import rulebooks as rulebooks_svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
OWNER_USERNAME = "rule_enforcement_owner"
@pytest_asyncio.fixture
async def topic_id():
# Purged at setup, not teardown: the write path's detached embedding task
# would deadlock against a teardown deleting the rulebook.
async with async_session() as s:
owner = await ensure_user(s, OWNER_USERNAME)
uid = owner.id
await s.commit()
for book in (await s.execute(
select(Rulebook).where(Rulebook.owner_user_id == uid)
)).scalars().all():
await s.delete(book)
await s.commit()
book = await rulebooks_svc.create_rulebook(uid, "Enforcement fixtures")
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
return uid, topic.id
async def _write_raw(topic: int, **kw) -> int:
"""Straight to the model, around the service's own checks, to reach the CHECKs."""
async with async_session() as s:
rule = Rule(topic_id=topic, title=kw.pop("title", "t"), statement="s", **kw)
s.add(rule)
await s.commit()
return rule.id
async def _read(rule_id: int) -> Rule:
async with async_session() as s:
return (await s.execute(select(Rule).where(Rule.id == rule_id))).scalar_one()
async def test_a_rule_written_without_either_reads_back_as_the_defaults(topic_id):
_uid, topic = topic_id
rule = await _read(await _write_raw(topic))
assert (rule.enforcement, rule.salience) == ("inform", "normal")
async def test_an_unknown_enforcement_is_refused_by_the_database(topic_id):
_uid, topic = topic_id
with pytest.raises(IntegrityError):
await _write_raw(topic, enforcement="block")
async def test_an_unknown_salience_is_refused_by_the_database(topic_id):
_uid, topic = topic_id
with pytest.raises(IntegrityError):
await _write_raw(topic, salience="urgent")
async def test_a_preference_that_holds_is_refused_by_the_database(topic_id):
_uid, topic = topic_id
with pytest.raises(IntegrityError):
await _write_raw(topic, kind="preference", enforcement="hold")
async def test_the_service_writes_a_declared_hold_and_reads_it_back(topic_id):
uid, topic = topic_id
rule = await rulebooks_svc.create_rule(
topic, uid, "Holds", "Read before replying", when_to_apply="about to reply",
enforcement="hold", salience="high",
)
back = await _read(rule.id)
assert (back.enforcement, back.salience) == ("hold", "high")
assert rulebooks_svc.rule_brief(back)["enforcement"] == "hold"
assert rulebooks_svc.rule_brief(back)["salience"] == "high"
async def test_the_service_refuses_a_preference_that_holds(topic_id):
uid, topic = topic_id
with pytest.raises(ValueError, match="always `inform`"):
await rulebooks_svc.create_rule(
topic, uid, "Pref", "Prefer x", when_to_apply="when x",
kind="preference", enforcement="hold",
)
async def test_a_rule_turned_into_a_preference_drops_to_inform(topic_id):
uid, topic = topic_id
rule = await rulebooks_svc.create_rule(
topic, uid, "Becomes a preference", "Do x", when_to_apply="when x",
enforcement="enforce",
)
updated = await rulebooks_svc.update_rule(rule.id, uid, kind="preference")
assert (updated.kind, updated.enforcement) == ("preference", "inform")
async def test_naming_a_hold_alongside_the_preference_kind_is_refused(topic_id):
uid, topic = topic_id
rule = await rulebooks_svc.create_rule(
topic, uid, "Stays a rule", "Do y", when_to_apply="when y",
)
with pytest.raises(ValueError, match="always `inform`"):
await rulebooks_svc.update_rule(rule.id, uid, kind="preference", enforcement="hold")
assert (await _read(rule.id)).kind == "rule"
-107
View File
@@ -1,107 +0,0 @@
"""Real-Postgres tests for `rule_triggers` (migration 0130): stored through the
rule's own write path, read back on the record, scoped like every rule read,
and checked against an act by the moment door."""
import pytest
import pytest_asyncio
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from grimoire.models import async_session
from grimoire.models.rulebook import Rulebook, rule_triggers
from grimoire.services import moment_delivery
from grimoire.services import rule_triggers as rt
from grimoire.services import rulebooks as rulebooks_svc
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
OWNER_USERNAME = "rule_trigger_owner"
@pytest_asyncio.fixture
async def topic_id():
# Purged at setup, not teardown: the write path's detached embedding task
# would deadlock against a teardown deleting the rulebook.
async with async_session() as s:
owner = await ensure_user(s, OWNER_USERNAME)
uid = owner.id
await s.commit()
for book in (await s.execute(
select(Rulebook).where(Rulebook.owner_user_id == uid)
)).scalars().all():
await s.delete(book)
await s.commit()
book = await rulebooks_svc.create_rulebook(uid, "Trigger fixtures")
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
return uid, topic.id
async def _rule(uid, topic, title, triggers, moments=None):
rule = await rulebooks_svc.create_rule(
topic_id=topic, user_id=uid, title=title, statement="s",
when_to_apply="when the fixture's act happens",
)
return await rulebooks_svc.rule_detail(
uid, rule, None, moments, triggers=rt.require_triggers(triggers),
)
async def test_triggers_are_stored_with_the_rule_and_replaced_as_a_set(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Migrations are reviewed", [
{"kind": "path", "pattern": "alembic/versions/*.py"},
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
])
assert data["triggers"] == [
{"kind": "path", "pattern": "alembic/versions/*.py"},
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
]
rule = await rulebooks_svc.get_rule(data["id"], uid)
again = await rulebooks_svc.rule_detail(uid, rule, triggers=[])
assert "triggers" not in again
# None leaves them alone.
await rulebooks_svc.rule_detail(uid, rule, triggers=rt.require_triggers([{"kind": "tool", "pattern": "bash"}]))
kept = await rulebooks_svc.rule_detail(uid, rule)
assert kept["triggers"] == [{"kind": "tool", "pattern": "bash"}]
async def test_an_unknown_kind_is_refused_by_the_database(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Raw kind", [])
async with async_session() as s:
with pytest.raises(IntegrityError):
await s.execute(rule_triggers.insert().values(
rule_id=data["id"], kind="regex", pattern="x", moment="",
))
await s.commit()
async def test_an_act_fires_an_unscoped_trigger_with_no_moment_reached(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Notebooks keep outputs cleared",
[{"kind": "path", "pattern": "*.ipynb"}])
reached, result = await moment_delivery.deliver_for_act(
uid, "Read", {"file_path": "/r/analysis/one.ipynb"},
)
assert data["id"] in result.shown_rule_ids
assert any("path `*.ipynb`" in line for line in result.lines)
_, quiet = await moment_delivery.deliver_for_act(uid, "Read", {"file_path": "/r/a.py"})
assert data["id"] not in quiet.shown_rule_ids
async def test_a_conditional_mount_arrives_only_when_the_act_meets_it(topic_id):
uid, topic = topic_id
data = await _rule(uid, topic, "Schema changes get a migration",
[{"kind": "path", "pattern": "models/*.py", "moment": "work.change"}],
moments=["work.change"])
_, missed = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/views/a.py"})
assert data["id"] not in missed.shown_rule_ids
_, met = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/models/a.py"})
assert data["id"] in met.shown_rule_ids
async def test_the_reachable_tools_include_what_a_trigger_can_match(topic_id):
uid, topic = topic_id
await _rule(uid, topic, "Task closes carry a report",
[{"kind": "tool", "pattern": "update_task"}])
assert "update_task" in await moment_delivery.reachable_tools(uid)
-75
View File
@@ -1252,81 +1252,6 @@ async def test_a_shape_written_this_turn_is_judged_before_the_sync_sees_it(seede
assert row.vanished_at is None and row.last_seen_commit == "c2"
async def _rows_at(pid: int, path: str) -> list[CodeShape]:
"""Every row at ``path``, vanished ones included: what the identity
constraint sees."""
async with async_session() as s:
return list((await s.execute(select(CodeShape).where(
CodeShape.project_id == pid, CodeShape.path == path,
))).scalars().all())
@pytest.mark.integration
async def test_judging_a_vanished_shape_revives_its_row(seeded):
"""A verdict with `repo` on a shape whose row has vanished lands on that
row and brings it back. It does not insert a second row under the same
identity, which the database refuses, taking the whole batch with it."""
from grimoire.services import repo_bindings as repo_bindings_svc
owner, pid, sid = seeded["owner"], seeded["pid"], seeded["snippet"]
await repo_bindings_svc.set_binding(owner, REPO, pid)
await sync_repo_shapes(
pid, REPO, [s for s in SHAPES if s[0] != "src/util.py"], seen_marker="c1",
)
[gone] = await _rows_at(pid, "src/util.py")
assert gone.vanished_at is not None
out = await classify_shapes(owner, pid, [
{"path": "src/util.py", "symbol": "helper", "kind": "sym", "status": "exempt",
"reason": "the module's own parse step", "reason_code": "pure-helper"},
{"path": "src/app.py", "symbol": "make_app", "status": "instance", "snippet_id": sid},
], repo=REPO)
assert out["classified"] == 2 and out["unmatched"] == []
[row] = await _rows_at(pid, "src/util.py")
assert row.id == gone.id and row.vanished_at is None
assert (row.status, row.reason_code) == ("exempt", "pure-helper")
@pytest.mark.integration
async def test_a_write_path_stamp_on_a_vanished_shape_revives_its_row(seeded):
"""The write-path hook meets a shape being written again after a sync
stamped it vanished. Its suggestion lands on the existing row, with no
second insert, and a standing verdict on that row still stands."""
from datetime import datetime, timezone
from grimoire.services.shape_ledger import suggest_write_path_instances
owner, pid, sid = seeded["owner"], seeded["pid"], seeded["snippet"]
pulled = {sid: datetime.now(timezone.utc)}
code = "def helper():\n return factory()\n"
await sync_repo_shapes(
pid, REPO, [s for s in SHAPES if s[0] != "src/util.py"], seen_marker="c1",
)
suggested = await suggest_write_path_instances(
owner, pid, path="src/util.py", shapes=[("sym", "helper")],
code=code, pulled=pulled, repo_key=REPO,
)
assert [s["symbol"] for s in suggested] == ["helper"]
[row] = await _rows_at(pid, "src/util.py")
assert row.vanished_at is None and row.proposed_snippet_id == sid
# A verdict on the row, then another vanish: the next stamp leaves it be.
await classify_shapes(owner, pid, [
{"path": "src/util.py", "symbol": "helper", "status": "exempt", "reason": "local"},
])
await sync_repo_shapes(
pid, REPO, [s for s in SHAPES if s[0] != "src/util.py"], seen_marker="c2",
)
assert await suggest_write_path_instances(
owner, pid, path="src/util.py", shapes=[("sym", "helper")],
code=code, pulled=pulled, repo_key=REPO,
) == []
[row] = await _rows_at(pid, "src/util.py")
assert row.status == "exempt" and row.classified_by == "agent"
@pytest.mark.integration
async def test_unjudged_is_what_nobody_read(seeded):
"""The end-of-turn question: a shape with no row, an unclassified one, a
+2 -2
View File
@@ -30,7 +30,7 @@ _CFG = {"enabled": True, "threshold": 0.55, "top_k": 3}
# The phrase the rule arms use. A lesson line that acquired it would be a rule
# with a different table, which is the thing this milestone exists to avoid.
_BINDING_PHRASE = "it binds"
_BINDING_PHRASE = "before deciding it does not apply"
async def _menu(main_hits, *, lesson_hits=None, reuse_hits=None, cfg=None,
@@ -284,5 +284,5 @@ def test_the_surfacing_guards_can_fail():
assert [42] != []
# A header that borrowed the binding voice.
assert _BINDING_PHRASE in (
"Rule 9 “CI polling” may apply here; it binds: CI is polled by the agent."
"Read it with get_rule(9) before deciding it does not apply."
)
+2 -2
View File
@@ -462,7 +462,7 @@ async def test_an_unshaped_act_through_a_tool_carries_no_shape():
assert "reply_shape" not in out
async def test_the_route_puts_the_rules_ahead_of_the_shape_and_returns_its_key():
async def test_the_route_puts_the_shape_ahead_of_the_rules_and_returns_its_key():
from grimoire.routes import plugin as routes
deliver = AsyncMock(return_value=(ASK, rp.RuleResult(lines=["a line"], rule_ids=[5])))
@@ -473,7 +473,7 @@ async def test_the_route_puts_the_rules_ahead_of_the_shape_and_returns_its_key()
with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver):
body = await (await routes.moment.__wrapped__()).get_json()
assert body["shape_keys"] == ["asks"]
assert body["context"].index("a line") < body["context"].index("Who decides what")
assert body["context"].index("Who decides what") < body["context"].index("a line")
async with app.test_request_context("/api/plugin/moment", method="POST", json=event,
query_string={"shapes_seen": "asks"}):
-108
View File
@@ -1,108 +0,0 @@
"""What a body cites, and that the web UI and the backend read it the same way.
A `#N` in prose names a note, task, lesson or snippet; `milestone N` and
`rule N` name records in their own id spaces. The backend reads these for
backlinks and graph edges (services/record_refs.referenced); the web UI links
them (frontend/src/utils/recordRefs.ts). A token made only of digits is never a
tag, on either side.
There is no frontend test runner, so the TS half is held to the Python half by
reading its source: the two patterns and the word list must be the same text.
"""
from __future__ import annotations
import re
from pathlib import Path
import pytest
from grimoire.services import record_refs
from grimoire.services.record_refs import referenced
from grimoire.utils.tags import extract_tags
FRONTEND = Path(__file__).resolve().parents[1] / "frontend" / "src"
REFS_TS = FRONTEND / "utils" / "recordRefs.ts"
TAGS_TS = FRONTEND / "utils" / "tags.ts"
def _refs(notes=(), milestones=(), rules=()):
return {"notes": set(notes), "milestones": set(milestones), "rules": set(rules)}
@pytest.mark.parametrize(("text", "expected"), [
("see #123", _refs(notes={123})),
("shipped #5110–#5119", _refs(notes={5110, 5119})),
# "step" names a position in a plan ("step #3"), the same reading the
# message parser uses, so a #N right after it stays plain.
("step #3 of the plan", _refs()),
("(#4286) and #4290.", _refs(notes={4286, 4290})),
("#v2 is a tag", _refs()),
("a colour #123abc", _refs()),
("inline `#12` is code", _refs()),
("```\nlog line #77\n```\nafter #78", _refs(notes={78})),
("PR #198 and run #4", _refs()),
("rule #34 and rule 10", _refs(rules={34, 10})),
("preference 12 holds", _refs(rules={12})),
("part of milestone 639", _refs(milestones={639})),
('Part of milestone 7 "Ship it"; next is #9 "Step two".', _refs(notes={9}, milestones={7})),
("an entity &#123; and a path a/#9", _refs()),
("", _refs()),
])
def test_referenced_reads_what_the_ui_links(text, expected):
assert referenced(text) == expected
def test_referenced_ignores_none_among_texts():
assert referenced(None, "#5", None) == _refs(notes={5})
@pytest.mark.parametrize(("body", "tags"), [
("#123", []),
("cites (#4286)", []),
("#5110–#5119", []),
("#v2 #123abc #2fa", ["123abc", "2fa", "v2"]),
("#123-notes and #12/x", ["12/x", "123-notes"]),
("#python #review", ["python", "review"]),
])
def test_a_token_of_digits_alone_is_never_a_tag(body, tags):
assert extract_tags(body) == tags
# ── The TS reader is the same text as the Python one ───────────────────────
def _ts_regex(src: str, name: str) -> str:
m = re.search(rf"export const {name} = /(.+?)/[gimsuy]*;", src)
assert m, f"{name} is no longer a regex literal in {REFS_TS.name}"
return m.group(1)
def test_the_ui_reads_note_references_with_the_backend_pattern():
src = REFS_TS.read_text()
assert _ts_regex(src, "NOTE_REF_RE") == record_refs.REF_RE.pattern
def test_the_ui_reads_milestone_and_rule_references_with_the_backend_pattern():
src = REFS_TS.read_text()
assert _ts_regex(src, "PROSE_REF_RE") == record_refs.PROSE_REF_RE.pattern
# Python compiles it IGNORECASE; the literal must carry `i` too.
assert re.search(r"export const PROSE_REF_RE = /.+?/[gmsuy]*i[gmsuy]*;", src)
assert record_refs.PROSE_REF_RE.flags & re.IGNORECASE
def test_the_ui_skips_the_same_other_numberings():
src = REFS_TS.read_text()
m = re.search(r"export const OTHER_SPACE: readonly string\[\] = \[(.*?)\];", src, re.S)
assert m, f"OTHER_SPACE is no longer a string-array literal in {REFS_TS.name}"
words = set(re.findall(r'"([a-z]+)"', m.group(1)))
assert words == set(record_refs._OTHER_SPACE)
def test_both_tag_patterns_leave_digits_alone_to_the_reference_reader():
from grimoire.utils import tags as tags_py
guard = r"#(?!\d+(?![\w/-]))"
assert guard in tags_py._TAG_RE.pattern
ts = TAGS_TS.read_text()
m = re.search(r"export const TAG_RE = /(.+?)/g;", ts)
assert m, f"TAG_RE is no longer a regex literal in {TAGS_TS.name}"
assert guard in m.group(1)
+4 -4
View File
@@ -1,8 +1,8 @@
"""The core reply shape rides every turn.
Every turn ends in a reply, and the operator's prompt is the last point before
it is written, so the per-turn retrieval carries the core shape after the
rules and ahead of the records menu: in full the first time a session sees it, as its one-line
it is written, so the per-turn retrieval carries the core shape ahead of
everything else: in full the first time a session sees it, as its one-line
reminder after that, and in full again once a compaction has swept the
ledger. What is pinned here is that round trip across the shell/Python seam —
the route's order and keys, and the hook's ledger.
@@ -49,10 +49,10 @@ async def _retrieve(query_string, turn_context="CORE SHAPE"):
return await resp.get_json(), turn
async def test_the_turns_shape_follows_the_rules_and_its_key_comes_back():
async def test_the_turns_shape_leads_the_payload_and_its_key_comes_back():
body, _turn = await _retrieve({"q": "fix the flaky thing"})
ctx = body["context"]
assert ctx.index("RULE LINE") < ctx.index("CORE SHAPE") < ctx.index("NOTES MENU")
assert ctx.index("CORE SHAPE") < ctx.index("RULE LINE") < ctx.index("NOTES MENU")
assert body["shape_keys"] == ["core"]
# Both arms' fresh rules reach the shared ledger.
assert body["rule_ids"] == [11, 173]
-1
View File
@@ -40,7 +40,6 @@ def test_every_endpoint_is_reachable_on_the_app():
assert rules == {
"/api/retrieval/surfaces",
"/api/retrieval/surfaces/<surface>",
"/api/retrieval/gate",
"/api/retrieval/tuning-history",
"/api/retrieval/moments",
"/api/retrieval/moments/mappings",
+13 -12
View File
@@ -107,13 +107,15 @@ def test_the_band_is_computed_from_scores_not_from_the_ledger():
assert [r.id for _s, r in kept] == [1, 2]
def test_the_leading_line_carries_the_statement_on_a_first_mention():
"""Rank 0 on a first mention says what the rule says; a repeat cites it."""
rule = fake_rule(id=4, title="dev is home", when_to_apply=_TRIGGER)
first = _rule_hint_line(rule, where="to this Bash call", seen=False)
assert rule.statement in first and "get_rule(4)" in first
again = _rule_hint_line(rule, where="to this Bash call", seen=True)
assert rule.statement not in again and "get_rule(4)" in again
@pytest.mark.parametrize("seen", [False, True])
def test_the_leading_line_carries_the_trigger(seen):
"""Rank 0 gets the full rendering, on either tail."""
line = _rule_hint_line(
fake_rule(id=4, title="dev is home", when_to_apply=_TRIGGER),
where="to this Bash call", seen=seen, compact=False,
)
assert _TRIGGER in line
assert "get_rule(4)" in line
@pytest.mark.parametrize("seen", [False, True])
@@ -159,12 +161,12 @@ def test_shortening_a_line_does_not_decide_what_it_says_about_holding():
assert len({fresh, named, held}) == 3, (
"the compact branch collapsed two holding states into one line"
)
assert "First mention" in fresh
assert "not in this session's loaded set" in fresh
assert "not opened" in named
assert "Opened earlier" in held
assert "no longer hold it" in held
# The claim that most needs to survive shortening: a line the session never
# opened must not imply it did, however little room the line was given.
assert "Opened earlier" not in named
assert "no longer hold it" not in named
def test_a_compact_line_is_materially_shorter_than_a_full_one():
@@ -186,8 +188,7 @@ def test_a_compact_line_is_materially_shorter_than_a_full_one():
"the next step feels like shipping it, and whenever an earlier merge "
"this session reads like standing permission for the next one."
)
rule = fake_rule(id=4, title="dev is home", when_to_apply=long_trigger,
statement=long_trigger)
rule = fake_rule(id=4, title="dev is home", when_to_apply=long_trigger)
full = _rule_hint_line(rule, where="here", seen=False, compact=False)
compact = _rule_hint_line(rule, where="here", seen=False, compact=True)
assert len(compact) * 2 < len(full)
+2 -2
View File
@@ -103,7 +103,7 @@ async def test_an_unknown_moment_is_refused_before_anything_is_written():
async def test_the_door_hands_rule_detail_the_normalised_moments():
seen = {}
async def detail(_uid, rule, _system_ids=None, moments=None, **_kw):
async def detail(_uid, rule, _system_ids=None, moments=None):
seen["moments"] = moments
return rule.to_dict()
@@ -119,7 +119,7 @@ async def test_the_door_hands_rule_detail_the_normalised_moments():
async def test_omitting_moments_leaves_the_mounts_alone():
seen = {}
async def detail(_uid, rule, _system_ids=None, moments="unset", **_kw):
async def detail(_uid, rule, _system_ids=None, moments="unset"):
seen["moments"] = moments
return rule.to_dict()
+4 -6
View File
@@ -166,9 +166,7 @@ def test_an_open_of_a_rule_a_hook_just_named_is_not_reported(sandbox):
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env)
assert out.stdout == ""
# The open is reported for the delivery record, with no acts to count.
assert json.loads((tmp / "curl.body").read_text()) == {
"rule_id": 11, "session_id": "s1", "acts": []}
assert not (tmp / "curl.log").exists()
# The open itself is still recorded.
assert (named / "s1.opened.ids").read_text().startswith("11\t")
# A rule no hook named is still reported.
@@ -178,7 +176,7 @@ def test_an_open_of_a_rule_a_hook_just_named_is_not_reported(sandbox):
assert json.loads((tmp / "curl.body").read_text())["rule_id"] == 1
def test_an_open_with_nothing_in_the_window_sends_only_the_open(sandbox):
def test_an_open_with_nothing_in_the_window_sends_nothing(sandbox):
tmp, env = sandbox
ledger = tmp / "grimoire-moment"
ledger.mkdir()
@@ -187,9 +185,9 @@ def test_an_open_with_nothing_in_the_window_sends_only_the_open(sandbox):
)
out = _run("grimoire_record_opened.sh",
{"session_id": "s1", "tool_name": "mcp__grimoire__get_rule",
"tool_input": {"rule_id": 11}}, env, FAKE_CURL_REPLY='{"moments":[],"context":""}')
"tool_input": {"rule_id": 11}}, env)
assert out.stdout == ""
assert json.loads((tmp / "curl.body").read_text())["acts"] == []
assert not (tmp / "curl.log").exists()
def test_session_end_removes_the_sessions_moment_files_and_no_others(sandbox):
+3 -3
View File
@@ -48,7 +48,7 @@ def _rule(rid=156, kind="rule"):
def test_a_rule_never_surfaced_is_offered_as_new():
line = _rule_hint_line(_rule(), where="here", seen=False, held=False)
assert "First mention this session" in line
assert "not in this session's loaded set" in line
def test_a_rule_named_but_not_opened_says_so_and_still_invites():
@@ -65,7 +65,7 @@ def test_a_rule_named_but_not_opened_says_so_and_still_invites():
def test_a_rule_the_session_opened_is_described_as_opened():
line = _rule_hint_line(_rule(), where="here", seen=True, held=True)
assert "Opened earlier this session" in line
assert "opened it earlier" in line
assert "get_rule(156)" in line
@@ -85,7 +85,7 @@ def test_held_outranks_seen_regardless_of_kind():
the two together is how one of them gets forgotten."""
for kind in ("rule", "preference"):
line = _rule_hint_line(_rule(kind=kind), where="here", seen=True, held=True)
assert "Opened earlier this session" in line
assert "opened it earlier" in line
# ── the recorder ───────────────────────────────────────────────────────────
-174
View File
@@ -1,174 +0,0 @@
"""The one delivery order, key by key, and both rule arms reading it."""
import dataclasses
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from grimoire.services import retrieval_pipeline as rp
from grimoire.services import rule_order as ro
def _r(rid, enforcement="inform", salience="normal"):
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
enforcement=enforcement, salience=salience)
def _ids(cands):
return [c.rule.id for c in ro.ordered(cands)]
def test_a_rule_that_stops_the_work_outranks_any_line_beside_it():
cands = [ro.Candidate(_r(1), similarity=0.95),
ro.Candidate(_r(2, "hold"), similarity=0.71),
ro.Candidate(_r(3, "enforce"), similarity=0.70)]
assert _ids(cands) == [3, 2, 1]
def test_salience_decides_between_rules_of_the_same_enforcement():
cands = [ro.Candidate(_r(1, salience="low")), ro.Candidate(_r(2)),
ro.Candidate(_r(3, salience="high"))]
assert _ids(cands) == [3, 2, 1]
def test_a_trigger_outranks_a_mount_and_a_mount_outranks_a_resemblance():
cands = [ro.Candidate(_r(1), specificity=ro.BY_RESEMBLANCE, similarity=0.9),
ro.Candidate(_r(2), specificity=ro.BY_MOUNT),
ro.Candidate(_r(3), specificity=ro.BY_TRIGGER)]
assert _ids(cands) == [3, 2, 1]
def test_a_first_mention_outranks_a_reminder_at_the_same_rank():
cands = [ro.Candidate(_r(1), seen=True), ro.Candidate(_r(2))]
assert _ids(cands) == [2, 1]
def test_history_breaks_the_tie_before_similarity_does():
cands = [ro.Candidate(_r(1), opened_rate=0.1, similarity=0.9),
ro.Candidate(_r(2), opened_rate=0.8, similarity=0.7),
ro.Candidate(_r(3), similarity=0.99)]
# Unknown history ranks between them, as an even chance.
assert _ids(cands) == [2, 3, 1]
def test_ties_keep_the_arms_own_order():
cands = [ro.Candidate(_r(i)) for i in (4, 2, 9)]
assert _ids(cands) == [4, 2, 9]
def test_a_rule_with_no_declared_fields_reads_as_inform_normal():
bare = SimpleNamespace(id=1)
assert ro.order_key(ro.Candidate(bare))[:2] == (2, 1)
@pytest.mark.parametrize(("delivered", "opened", "rate"), [(0, 0, 0.5), (1, 1, 2 / 3), (10, 0, 1 / 12)])
def test_the_open_rate_is_smoothed(delivered, opened, rate):
assert ro.opened_rate(delivered, opened) == pytest.approx(rate)
PUSH = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}]
@pytest.mark.asyncio
async def test_the_moment_arm_delivers_in_that_order_before_its_cap():
pairs = [(_r(i), "work.deliver") for i in range(1, 11)] + [(_r(99, "hold"), "work.deliver")]
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
)
# The holding rule was mounted last and still leads; the cap cut ordinary ones.
assert result.shown_rule_ids[0] == 99
assert len(result.shown_rule_ids) == rp.MOMENT_RULE_LIMIT
@pytest.mark.asyncio
async def test_the_semantic_arm_delivers_in_that_order():
hits = [(0.91, _r(1)), (0.74, _r(2, "hold"))]
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock())
result = await rp.run_rule_arm(
rp.PROMPT_RULE, rp.RuleMoment(user_id=1, query="q", project_id=2, where="here"),
floor=0.5, budget=5, io=io,
)
assert result.shown_rule_ids[:2] == [2, 1]
@pytest.mark.asyncio
async def test_each_line_shown_is_recorded_as_a_delivery_with_its_form():
recorded = MagicMock()
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish")]
await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2, exclude=frozenset({6})),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
record_delivery=recorded),
)
_uid, _sid, source, lines = recorded.call_args.args
assert source == rp.MOMENT_RULE_SOURCE
assert lines == [(5, "work.finish", "full"), (6, "work.finish", "repeat")]
@pytest.mark.asyncio
async def test_history_reorders_rules_of_equal_rank_and_a_failed_read_is_unknown():
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish")]
async def history(_uid, _pairs):
return {6: 0.9, 5: 0.1}
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
history=history),
)
assert result.shown_rule_ids == [6, 5]
async def broken(_uid, _pairs):
raise RuntimeError("no database")
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
history=broken),
)
assert result.shown_rule_ids == [5, 6]
@pytest.mark.asyncio
async def test_a_repeat_already_reminded_once_is_retired_unless_it_holds_or_was_opened():
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish"), (_r(7, "hold"), "work.finish"),
(_r(8), "work.finish")]
asked = {}
async def retired(_uid, ids):
asked["ids"] = sorted(ids)
return set(ids)
result = await rp.run_moment_arm(
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2,
exclude=frozenset({6, 7, 8}), held=frozenset({8})),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
retired=retired),
)
# Only the unopened, non-holding repeat is asked about, and only it goes.
assert asked["ids"] == [6]
assert sorted(result.shown_rule_ids) == [5, 7, 8]
@pytest.mark.asyncio
async def test_the_semantic_arm_retires_the_same_way_and_a_failed_read_retires_nothing():
hits = [(0.91, _r(1)), (0.80, _r(2))]
async def retired(_uid, ids):
return {2}
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
record_rule_surfaced=MagicMock(), retired=retired)
moment = rp.RuleMoment(user_id=1, query="q", project_id=2, where="here", exclude=frozenset({2}))
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
assert result.shown_rule_ids == [1]
async def broken(_uid, ids):
raise RuntimeError("no database")
io = dataclasses.replace(io, retired=broken)
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
assert sorted(result.shown_rule_ids) == [1, 2]
-152
View File
@@ -1,152 +0,0 @@
"""A rule's triggers: what each kind matches, what is refused, and how the
moment arm reads the board they build."""
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from grimoire.services import retrieval_pipeline as rp
from grimoire.services import rule_order
from grimoire.services import rule_triggers as rt
from grimoire.services.rule_triggers import Trigger
def T(kind, pattern, moment=""):
return rt.require_trigger({"kind": kind, "pattern": pattern, "moment": moment})
# ── matching, kind by kind ──────────────────────────────────────────────
@pytest.mark.parametrize(("pattern", "path", "hit"), [
("alembic/versions/*.py", "/repo/alembic/versions/0130_x.py", True),
("alembic/versions/*.py", "alembic/versions/0130_x.py", True),
("alembic/versions/*.py", "/repo/alembic/versions/sub/0130.py", False),
("frontend/**/*.vue", "/r/frontend/src/components/A.vue", True),
("frontend/**/*.vue", "/r/frontend/A.vue", True),
("*.md", "/r/docs/README.md", True),
("/etc/*.conf", "/etc/nginx.conf", True),
("/etc/*.conf", "/srv/etc/nginx.conf", False),
("versions/*.py", "/repo/myversions/x.py", False),
])
def test_a_path_glob_matches_from_any_directory_unless_anchored(pattern, path, hit):
assert rt.matches(T("path", pattern), "Write", {"file_path": path}) is hit
def test_a_path_trigger_reads_every_file_field_and_needs_an_act():
trig = T("path", "*.ipynb")
assert rt.matches(trig, "NotebookEdit", {"notebook_path": "/a/b.ipynb"})
assert rt.matches(trig, "Glob", {"path": "/a/b.ipynb"})
assert not rt.matches(trig, None, None, text="b.ipynb")
@pytest.mark.parametrize(("command", "hit"), [
("git push origin dev", True),
("make test && git push", True),
("FOO=1 git push", True),
("git pushx", False),
("echo git push", False),
])
def test_a_command_trigger_matches_the_head_of_any_segment(command, hit):
assert rt.matches(T("command", "git push"), "Bash", {"command": command}) is hit
def test_a_tool_trigger_matches_the_key_with_or_without_a_server_prefix():
assert rt.matches(T("tool", "update_task"), "mcp__plugin_grimoire_grimoire__update_task", {})
assert rt.matches(T("tool", "*_task"), "mcp__x__create_task", {})
assert not rt.matches(T("tool", "update_task"), "mcp__x__get_task", {})
def test_a_keyword_matches_a_whole_word_in_what_the_act_writes_or_the_reply():
trig = T("keyword", "migration")
assert rt.matches(trig, "Edit", {"new_string": "add a Migration for it"})
assert rt.matches(trig, None, None, text="this migration is done")
assert not rt.matches(trig, "Edit", {"new_string": "migrations"})
assert not rt.matches(trig, "Write", {"file_path": "migration.py"})
# ── validation ──────────────────────────────────────────────────────────
def test_validation_normalises_and_refuses_what_could_never_fire():
assert T("tool", "mcp__x__Update_Task") == Trigger("tool", "update_task")
assert T("command", " Git Push ") == Trigger("command", "git push")
assert T("path", "src/**", " Work.Change ") == Trigger("path", "src/**", "work.change")
for bad in ({"kind": "regex", "pattern": "x"}, {"kind": "path", "pattern": " "},
{"kind": "path", "pattern": "x", "moment": "work.finished"}, "path:x"):
with pytest.raises(ValueError):
rt.require_trigger(bad)
def test_a_set_is_deduplicated_capped_and_none_leaves_it_alone():
assert rt.require_triggers(None) is None
assert rt.require_triggers([]) == []
same = {"kind": "path", "pattern": "a/*"}
assert rt.require_triggers([same, same]) == [Trigger("path", "a/*")]
with pytest.raises(ValueError, match="at most"):
rt.require_triggers([{"kind": "keyword", "pattern": f"w{i}"} for i in range(rt.TRIGGERS_MAX + 1)])
def test_each_kind_names_the_tools_the_catch_all_hook_must_forward():
assert rt.tools_for(T("tool", "update_task")) == {"update_task"}
assert rt.tools_for(T("tool", "*_task")) == set()
assert rt.tools_for(T("command", "git push")) == {"bash"}
assert "write" in rt.tools_for(T("path", "a/*")) and "edit" in rt.tools_for(T("path", "a/*"))
# ── the board ───────────────────────────────────────────────────────────
def _r(rid, enforcement="inform"):
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
enforcement=enforcement, salience="normal")
async def test_the_board_gates_a_conditional_mount_the_act_missed(monkeypatch):
scoped = _r(1)
free = _r(2)
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
(scoped, [T("path", "alembic/**", "work.change")]),
(free, [T("command", "git push"), T("keyword", "deploy")]),
]))
edit = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/src/app.py"})
assert edit.gated == {(1, "work.change")} and not edit.matched and not edit.fired
mig = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/alembic/v/1.py"})
assert mig.matched == {(1, "work.change")} and not mig.gated
push = await rt.board(1, 2, tool="Bash", tool_input={"command": "git push"})
assert [(r.id, t.kind) for r, t in push.fired] == [(2, "command")]
# ── the arm reading it ──────────────────────────────────────────────────
CHANGE = [{"moment": "work.change", "tool": "Edit", "match": "", "via": "default"}]
async def _arm(pairs, board, reached=CHANGE, **kw):
return await rp.run_moment_arm(
reached, rp.RuleMoment(user_id=1, query="", project_id=2, **kw),
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
board=board,
)
async def test_a_gated_mount_is_not_delivered_and_a_met_one_ranks_as_triggered():
pairs = [(_r(1), "work.change"), (_r(2), "work.change")]
result = await _arm(pairs, rt.Board(gated={(1, "work.change")}))
assert result.shown_rule_ids == [2]
result = await _arm(pairs, rt.Board(matched={(2, "work.change")}))
assert result.shown_rule_ids == [2, 1]
async def test_an_unscoped_trigger_delivers_with_no_moment_reached_and_says_what_fired():
board = rt.Board(fired=[(_r(7), T("path", "alembic/**"))])
result = await _arm([], board, reached=[])
assert result.shown_rule_ids == [7]
assert "path `alembic/**`" in result.lines[0]
async def test_a_rule_both_mounted_and_fired_is_delivered_once():
board = rt.Board(fired=[(_r(1), T("command", "git push"))])
result = await _arm([(_r(1), "work.change")], board)
assert result.shown_rule_ids == [1]
def test_triggered_outranks_mounted_in_the_one_order():
assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE
+25 -31
View File
@@ -721,8 +721,7 @@ def test_the_hook_and_the_route_agree_on_every_parameter_name():
sent = set(re.findall(r"[?&]([a-z_]+)=", hook))
# `root` and `cwd`: where the command runs, so the paths it
# names can be made repo-relative for the rulings arm.
# `session_id`: which session the lines go to, for the delivery record.
assert sent == {"tool", "command", "exclude_rule_ids", "root", "cwd", "session_id"}, sent
assert sent == {"tool", "command", "exclude_rule_ids", "root", "cwd"}, sent
# The project-scope key is the shared helper's to choose: the hook
# splices in `grimoire_scope_query`'s output, which is `repo=` inside a git
@@ -764,12 +763,6 @@ def test_the_hook_and_the_route_agree_on_every_parameter_name():
assert f'request.args.get("{arg}")' in handler, (
f"the hook sends {arg!r} and the route never reads it"
)
# The session is bound for every plugin route at once, before the handler.
binder = route.split("async def _bind_delivery_session")[1].split("\n@plugin_bp")[0]
assert "@plugin_bp.before_request" in route.split("async def _bind_delivery_session")[0][-80:]
assert 'request.args.get("session_id")' in binder, (
"the hook sends session_id and no route reads it"
)
# ── The CALL log is unconditional; the SURFACING log is not ───────────
@@ -1149,14 +1142,14 @@ _HELD = fake_rule(
statement="Every wait on something that can fail to answer carries a deadline.",
when_to_apply="writing any call that crosses a process boundary",
)
_FRESH_TAIL = "First mention this session"
_FRESH_TAIL = "not in this session's loaded set"
# `seen` WITHOUT `held` is the middle state: an arm named this rule earlier,
# and the session never opened it. Every test below drives the arms with
# `exclude_rule_ids` alone — the naming ledger — so this is the tail they
# produce, and it must not claim the session read a teaser nobody opened.
_SEEN_TAIL = "Named earlier this session, not opened"
_SEEN_TAIL = "Mentioned earlier this session but not opened"
# The third state, reached only when the opened ledger names the rule too.
_HELD_TAIL = "Opened earlier this session"
_HELD_TAIL = "You opened it earlier this session"
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
@@ -1235,8 +1228,8 @@ _PREF = fake_rule(
statement="Advance one investigative step per turn.",
when_to_apply="during hard debugging",
)
_RULE_FORCE = "it binds"
_PREF_FORCE = "how this has been done before"
_RULE_FORCE = "before deciding it does not apply"
_PREF_FORCE = "for how this has been done before"
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
@@ -1251,7 +1244,7 @@ async def test_a_preference_does_not_speak_in_the_rules_voice(source, run):
"""
ctx = (await run([(0.81, _PREF)], MagicMock()))["context"]
assert "Preference 177" in ctx, (
assert "Preference that may apply" in ctx, (
f"{source} announced a preference as something else. The noun is the "
f"one word a skimming reader gets to place the register, so it is the "
f"word that has to move. Context was: {ctx!r}"
@@ -1297,7 +1290,7 @@ async def test_kind_and_seen_do_not_read_each_other(source, run):
)
# And the head still differs in the seen case — a repeat of a preference
# is still a preference.
assert "Preference 177" in pref_seen, (
assert "Preference that may apply" in pref_seen, (
f"{source} lost the preference register on a repeat, so a preference "
f"seen twice reads as a rule the second time"
)
@@ -1305,24 +1298,25 @@ async def test_kind_and_seen_do_not_read_each_other(source, run):
@pytest.mark.parametrize(("source", "run"), _ARMS, ids=["write_path", "pre_tool", "prompt"])
@pytest.mark.asyncio
async def test_a_first_mention_carries_the_statement_and_a_repeat_does_not(source, run):
"""What a line is for, pinned on both branches.
async def test_neither_tail_injects_the_rule_statement(source, run):
"""The budget, pinned on both branches.
A first mention carries the rule's own words, so the reader has what it
says without a second call. A repeat is a reference: the session was
handed the statement already, and quoting it again on every call is the
cost this line is built to avoid.
A reference costs the same ~40 tokens as a first surfacing precisely
because neither carries the statement. If a repeat ever starts inlining the
body "since we are re-showing it anyway", this arm stops being cheap enough
to always emit — and always emitting is the whole mechanism.
"""
fresh = (await run([(0.81, _HELD)], MagicMock()))["context"]
assert _HELD.statement in fresh, (
f"{source} named the rule without saying what it says"
for excluded in ([], [156]):
ctx = (await run([(0.81, _HELD)], MagicMock(),
exclude_rule_ids=excluded))["context"]
assert _HELD.statement not in ctx, (
f"{source} inlined the rule statement (excluded={excluded!r}); the "
f"line carries title, trigger and a pull pointer and nothing more"
)
repeat = (await run([(0.81, _HELD)], MagicMock(), exclude_rule_ids=[156]))["context"]
assert _HELD.statement not in repeat, (
f"{source} quoted the statement again on a repeat"
assert _HELD.title in ctx and "process boundary" in ctx, (
"the line dropped the title or the trigger — those are what let a "
"reader decide whether to pull without pulling"
)
for ctx in (fresh, repeat):
assert _HELD.title in ctx and "get_rule(156)" in ctx
# ── What a reference IS in the telemetry: nothing new ──────────────────────
@@ -1448,7 +1442,7 @@ async def test_a_preference_that_lost_the_ranking_still_gets_a_line():
"dropped — which is the outcome with no symptom: the rules that won "
"are legitimate hits and nothing in the telemetry looks wrong"
)
assert "Preference 140" in out["context"]
assert "Preference that may apply" in out["context"]
@pytest.mark.asyncio
@@ -1465,7 +1459,7 @@ async def test_the_slot_is_not_spent_when_a_preference_already_placed():
"reserved line for a kind already represented is noise the general "
"ranking had already decided against"
)
assert out["context"].count("Preference 140") == 1
assert out["context"].count("Preference that may apply") == 1
@pytest.mark.asyncio
+1 -1
View File
@@ -76,7 +76,7 @@ async def test_a_matching_linked_lesson_brings_its_rule_in_rule_voice():
)
lines, ids = await _run(stack)
assert ids == [7]
assert lines[0].startswith("Rule ")
assert lines[0].startswith("Standing rule")
assert "Reached through lesson #41" in lines[0]
assert log.call_args.kwargs["source"] == "rule_via_lesson"
assert surfaced.call_args.kwargs == {"user_id": 1, "rule_ids": [7], "source": "rule_via_lesson"}
+5 -9
View File
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
"""The bump is the point of the test — a payload section added without
moving the version produces backups that are structurally different and
indistinguishable by inspection."""
assert backup.BACKUP_VERSION == 29
assert backup.BACKUP_VERSION == 28
def _exportable_note(**over):
@@ -483,7 +483,7 @@ def test_the_column_guard_covers_every_table_with_a_row_helper():
# REAL table names, as _BACKED_UP holds them — not the shorter keys the
# payload uses for the same sections. Getting this wrong is what the guard
# caught on its own first run.
join_tables = {"rule_systems", "rule_moments", "rule_triggers"}
join_tables = {"rule_systems", "rule_moments"}
covered = set(_column_guard_targets()) | join_tables
assert set(backup._BACKED_UP) - covered == set()
# And no stale entries: every declaration must name a real target.
@@ -588,8 +588,6 @@ async def test_export_full_backup_contains_every_declared_section():
"system_usage_events",
# v23: proposals and judgments about a rule's moments.
"rule_moment_judgments",
# v29: the acts that trigger a rule.
"rule_triggers",
# v25: family canon.
"platforms", "project_platforms", "family_ideas",
"family_idea_platforms", "family_idea_references",
@@ -626,15 +624,13 @@ def test_rule_rows_carry_the_verification_fields():
row = SimpleNamespace(
id=1, topic_id=2, project_id=None, title="t", statement="s",
why="w", how_to_apply="h", order_index=0,
when_to_apply="when", kind="rule", enforcement="hold", salience="high",
when_to_apply="when", kind="rule",
verify_with="cat some/file", expires_when="the file grows a shell",
verified_at=checked, arose_from_id=99,
created_at=checked, updated_at=checked,
)
out = backup._rule_rows([row])[0]
assert (out["enforcement"], out["salience"]) == ("hold", "high")
assert out["verify_with"] == "cat some/file"
assert out["expires_when"] == "the file grows a shell"
assert out["verified_at"] == checked.isoformat()
@@ -654,7 +650,7 @@ def test_rule_rows_keep_an_unverified_rule_unverified():
row = SimpleNamespace(
id=1, topic_id=2, project_id=None, title="t", statement="s",
why=None, how_to_apply=None, order_index=0,
when_to_apply=None, kind="rule", enforcement="inform", salience="normal",
when_to_apply=None, kind="rule",
verify_with=None, expires_when=None, verified_at=None,
arose_from_id=None,
created_at=datetime(2026, 8, 27, tzinfo=timezone.utc),
@@ -684,7 +680,7 @@ def test_rule_rows_carry_the_kind_so_a_preference_does_not_restore_as_a_rule():
row = SimpleNamespace(
id=1, topic_id=2, project_id=None, title="t", statement="s",
why=None, how_to_apply=None, order_index=0,
when_to_apply="when", kind="preference", enforcement="inform", salience="normal",
when_to_apply="when", kind="preference",
verify_with=None, expires_when=None, verified_at=None,
arose_from_id=None, created_at=stamp, updated_at=stamp,
)