Compare commits

...
91 Commits
Author SHA1 Message Date
bvandeusen 359766b370 Merge pull request 'Suite review, first batch: test groups smallest first, covers named before the sync reads them' (#238) 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 32s
CI & Build / Python tests (push) Successful in 2m5s
CI & Build / integration (push) Successful in 2m31s
CI & Build / Build & push image (push) Successful in 18s
2026-12-01 06:41:21 -05:00
bvandeusenandClaude Opus 5.5 f4f036c8a7 fix(8249): a redundant verdict can name a cover the sync has not read yet
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 / Python tests (push) Successful in 2m7s
CI & Build / integration (push) Successful in 2m41s
CI & Build / Build & push image (push) Successful in 25s
A test is usually rewritten in the same change that removes the one it
replaces, so the cover is new to the ledger when the verdict is recorded,
and the next refresh retires the removed test. classify_shapes refused such
a cover as matching no live shape. With a bound `repo` the cover now
resolves the way the judged shape already does, as a provisional row the
next sync adopts; without one it is refused as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 02:58:35 -05:00
bvandeusenandClaude Opus 5.5 251f5cb286 Revert the deliberate break: the kind filter and the planning route are back
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python tests (push) Successful in 2m6s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 2m28s
CI & Build / Build & push image (push) Successful in 18s
The break (a16a0ef) went red exactly where it should, in CI run 11227:
- test_routes_planning::test_starting_a_plan_is_routed_on_the_app;
- test_integration_task_kind_list [issue] and [work]; the all-kinds case
  stayed green, as it must.
Nothing else failed (unit 1 failed / 3771 passed, database 2 failed / 478
passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 02:57:34 -05:00
bvandeusenandClaude Opus 5.5 a16a0ef3cd test(8249): DELIBERATE BREAK, the kind filter and the planning route removed to watch their tests fail
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Failing after 1m47s
CI & Build / integration (push) Failing after 2m44s
CI & Build / Build & push image (push) Skipped
Reverted by the next commit. CI must go red on test_integration_task_kind_list
(issue and work rows) and test_routes_planning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 02:51:13 -05:00
bvandeusenandClaude Opus 5.5 fc1e30588e test(8249): task kinds are proven by a listing, not by a signature
Review of the small test groups. Four tests pinned an argument list or a
function existing where the behaviour was untested or tested elsewhere:
- test_routes_planning: the signature check and the callable check become
  one check that POST /api/tasks/planning is routed on the app.
- test_routes_tasks_kind: both signature checks go; create_note and
  list_notes are called with task_kind by tests that would fail without it,
  and the blueprint check is covered by the planning route check.
- test_list_notes_filters_by_task_kind asserted only that the call did not
  raise. It is replaced by a database test that lists issues, work and all
  kinds and checks the rows and the count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 02:51:13 -05:00
bvandeusenandClaude Opus 5.5 7c7a1a7ab9 fix(8249): test groups come smallest first, and a big one is read as a feature area
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 2m14s
CI & Build / integration (push) Successful in 2m28s
CI & Build / Build & push image (push) Successful in 35s
A group is the set of tests reaching the same code from different files. A
test that drives a feature through its one entry point reaches exactly that
entry point whatever it checks, so the largest groups are a feature tested
from many files, not copies. Listing them first buried the two- and
three-test groups where one-for-one duplicates are. The readout, the tool and
the panel now list smallest first; each group says copies or area and how
many files it spans, and the panel tells an area to fold its scattered cases
into one file. Plugin 2026.12.01.0748.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 02:49:06 -05:00
bvandeusen 9e6d6c4d67 Merge pull request 'Pointers once a session; the code index knows what each test guards; a reviewing-tests skill' (#237) 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 35s
CI & Build / Python tests (push) Successful in 2m24s
CI & Build / integration (push) Successful in 2m27s
CI & Build / Build & push image (push) Successful in 18s
2026-11-30 23:24:22 -05:00
bvandeusenandClaude Opus 5.5 70ca2e8a11 feat(8248): the plugin ships a reviewing-tests skill: one verdict per test, deliberate breaks, every removal listed
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Successful in 2m15s
CI & Build / integration (push) Successful in 2m11s
CI & Build / Build & push image (push) Successful in 23s
The skill is the subtraction pass a suite never gets. It reviews against the
project's own test standard when one is recorded, takes before numbers from a
real run, works area by area with keep / merge / rewrite / move / remove,
records removals in the ledger (redundant with covered_by, unused) and kept
groups with review_test_group, breaks three to five protected behaviours per
area to prove the survivors fail, and lands each area as its own change.
It reaches work.verify. Plugin 2026.12.01.0344.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:44:18 -05:00
bvandeusenandClaude Opus 5.5 dc9e88aa6d feat(8247): a test case is accounted for by what it guards, and the coverage line counts the suite by it
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m24s
CI & Build / integration (push) Successful in 2m22s
CI & Build / Build & push image (push) Successful in 43s
A refresh now stamps a test case `test` when it is linked to something it
guards, and withdraws the stamp when its links go; a judgment always wins. A
test case linked to nothing stays in the todo, because nothing says what it is
for. Specs written as it()/test() calls get one ledger row per file, read
whole. The coverage line and card count tests linked, guarding nothing found,
and redundant, and the end-of-turn question no longer asks the writer to call
a test case a one-off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:57:57 -05:00
bvandeusenandClaude Opus 5.5 ebd9d8fbb8 fix(8246): a test's weak signals stay out of the backup, as declared
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Successful in 2m24s
CI & Build / integration (push) Successful in 2m17s
CI & Build / Build & push image (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:26:04 -05:00
bvandeusenandClaude Opus 5.5 865465ce8f feat(8246): the code index links each test to what it guards, and can say redundant or unused
CI & Build / Plugin hooks (push) Successful in 20s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 41s
CI & Build / Python tests (push) Failing after 2m8s
CI & Build / integration (push) Successful in 2m24s
CI & Build / Build & push image (push) Skipped
Every coverage refresh now reads, for each test in a bound repo, which product
shapes its body exercises: through module aliases and imports, following test
helpers, with mocked names left out and shapes most test files reach dropped as
hubs. Tests in different files that guard exactly the same set form a group.
The project page lists the groups and a person can mark one test redundant,
naming the test that covers it, or keep them all with a reason. Agents get
test_guard_groups and review_test_group, and classify_shapes takes the two new
removal verdicts, redundant (with covered_by) and unused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 21:17:48 -05:00
bvandeusenandClaude Opus 5.5 134dd68274 test(8241): the pointer test reuses the auto-inject menu harness instead of copying it
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Plugin hooks (push) Successful in 20s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m28s
CI & Build / integration (push) Successful in 2m16s
CI & Build / Build & push image (push) Successful in 20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:40:44 -05:00
bvandeusenandClaude Opus 5.5 9f6f04e898 fix(8241,8242): a pointer line names a record once a session, and a place delivery is booked once
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python tests (push) Successful in 2m5s
CI & Build / integration (push) Successful in 1m57s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Build & push image (push) Successful in 20s
The plugin ledger of what a session has seen holds only records given a line,
so a record named by id came back on every edit and message (one handoff note
35 times in a session). Every pointer line now goes through _point, which asks
the server delivery ledger what this session was already shown or pointed at
and leaves those out. Snippets beside an edited file were booked both pushed
(via record_surfaced) and pointed; record_surfaced now leaves write_path_place
to its door.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:33:13 -05:00
bvandeusen fedd3ff881 Merge pull request 'Fast exact search, cross-project knowledge, delivered rulings, short MCP instructions' (#236) from dev into main
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m15s
CI & Build / integration (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 16s
2026-11-28 18:24:23 -05:00
bvandeusenandClaude Opus 5.5 ddbfbabcd2 refactor(8211): the MCP instructions carry only what no response or skill delivers
CI & Build / Python lint (push) Successful in 1s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python tests (push) Successful in 2m16s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Successful in 21s
569 characters, from 1,600: what Grimoire is, enter_project first, ask
what_might_apply before a consequential act, search before building, the force
of each record kind, and that responses say what to do next. The rest is
enforced in responses or stated in a skill. The budget drops to 800, and the
guidance registry stops requiring index words for the topics that left.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 18:15:07 -05:00
bvandeusenandClaude Opus 5.5 ff47a2b08b fix(8205,8206): the new test helper no longer shadows _system, and using-grimoire fits its 350 lines
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 2m9s
CI & Build / integration (push) Successful in 2m11s
CI & Build / Build & push image (push) Successful in 31s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:55:37 -05:00
bvandeusenandClaude Opus 5.5 9e3767f375 docs(8206): a ruling says what a constraint is for and not for, and the comment names it
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / Python lint (push) Successful in 7s
CI & Build / Python tests (push) Failing after 1m58s
CI & Build / Build & push image (push) Canceled after 0s
CI & Build / integration (push) Canceled after 2m9s
writing-records: the for/not-for form, naming a System's files so its
rulings reach an edit, and the comment at a constraint naming its ruling.
using-grimoire: read the area's rulings before changing a filter, gate or
default, and take a change that would undo one to the operator. The project
filter in embeddings now names its ruling, and the docstring that stretched
its reason to every kind is corrected. Plugin version minted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:50:11 -05:00
bvandeusenandClaude Opus 5.5 3e87df6c84 feat(8205): a System with rulings and no file patterns is flagged
CI & Build / TypeScript typecheck (push) Canceled after 0s
CI & Build / Plugin hooks (push) Canceled after 0s
CI & Build / Python lint (push) Canceled after 0s
CI & Build / Python tests (push) Canceled after 0s
CI & Build / integration (push) Canceled after 0s
CI & Build / Build & push image (push) Canceled after 0s
Its rulings reach no session: delivery is by path_patterns alone. enter_project
carries rulings_undelivered (absent when none) with the fix call, the Systems
list reads ruling_count, and the System card says so with a button to name
its files. A System without rulings is not flagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:49:24 -05:00
bvandeusenandClaude Opus 5.5 98a959de4f test(8191): the route list names the reach endpoint
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 2m11s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:25:01 -05:00
bvandeusenandClaude Opus 5.5 30aa5cf1c6 feat(8191): knowledge reaches a session from every project, ranked below its own and labelled
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 2m0s
CI & Build / Build & push image (push) Canceled after 0s
CI & Build / integration (push) Canceled after 2m7s
A per-kind reach beside the kind-by-moment table (setting record_reach,
default snippet/note/process/lesson) widens the passive note arms and their
slots to the user's other projects. A record from elsewhere gives up 0.05
before the floor and the ranking, and its line names the project. Work kinds
stay in their project, the visibility clause is unchanged, and an explicit
project search still means that project. Settings > Moments edits the reach.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:20:31 -05:00
bvandeusenandClaude Opus 5.5 163d32859f fix(8192): a gated arm's declines include the calls its cue gate withheld
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m10s
CI & Build / integration (push) Successful in 2m15s
CI & Build / Build & push image (push) Successful in 21s
#8192 "The cannot_decline warning reads the result count from before the cue
gate, so a gated arm can never show a decline", step 3 of milestone 669.

auto_inject logs its ranked results before the cue gate decides, so a call
the gate silenced still reads as a hit, and cannot_decline fired on an arm
whose gate withholds most calls (since 11-23, gate_kept = 0 on 55 of 69,
40 of 44 and 71 of 84 calls a day, with result_count never 0).

The readout gains a `gate` block per source (gated_calls, declined_by_gate),
null where no row carried a gate decision, and cannot_decline counts
zero_result_calls plus declined_by_gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:15:53 -05:00
bvandeusenandClaude Opus 5.5 deb991b2cc test(8190): read attstorage as text; asyncpg returns the one-byte "char" type as bytes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:15:53 -05:00
bvandeusenandClaude Opus 5.5 efba891f5e perf(8190): the exact search reads vectors from the row and text only for the winners
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 / Python tests (push) Successful in 2m7s
CI & Build / integration (push) Failing after 2m15s
CI & Build / Build & push image (push) Skipped
Step 1 of milestone 669 "Knowledge reaches every project, work stays in its
own: a fast exact search, cross-project recall ranked and labelled", for
#6834 "auto_inject p90 latency has climbed since 10-23".

A search with no project in scope took about 1 s, because it ranked about
26k chunks exactly. Two costs on that path, neither of which changes a result:

- pgvector's vector type defaults to EXTERNAL storage, and a chunk row
  (about 1.5 KB of vector plus its text) is over the 2 KB toast threshold,
  so every vector sat in TOAST and each distance paid a lookup (151k buffer
  hits for 26k rows). Migration 0139 sets STORAGE MAIN on the four
  embedding tables and rewrites the existing rows once.
- The materialized scope carried every chunk's text beside its distance and
  spilled the sort to disk. It now carries the id, chunk index and distance,
  and the text is joined back for the rows that survive the cut.

Measured on the live corpus: 1,151 ms as before, 393 ms with the text out of
the scope, before the storage change.

The HNSW index stays out of the ranking. With pgvector 0.8's iterative
scan it returned 7 to 60 of the true 144 nearest chunks under a narrow
scope, at every setting tried.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 16:10:00 -05:00
bvandeusenandClaude Opus 5.5 6cb61cdf84 licence(7023): the Claude Code plugin is MIT; the server stays AGPL-3.0-only
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Successful in 2m20s
CI & Build / Python lint (push) Successful in 2s
CI & Build / integration (push) Successful in 2m15s
CI & Build / Build & push image (push) Successful in 21s
The operator settled the split on 2026-11-09. The server is AGPL-3.0-only.
The plugin is a client adapter that people install into their own tooling,
so it is MIT. plugin/ now carries its own LICENSE, the manifest declares
MIT, and the README's Licence section names both. Plugin version minted
2026.11.28.1705.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:05:12 -05:00
bvandeusen d54a6a9492 Merge pull request 'Gate stops are recorded: every time a rule, the checkpoint, the fence or the reply hold stops work' (#235) 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 33s
CI & Build / Python tests (push) Successful in 2m5s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Successful in 16s
2026-11-27 23:46:04 -05:00
bvandeusenandClaude Opus 5.5 1e5f95bce2 test(8141): the rewrite test counts reply requests, not the gate report beside them
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Successful in 2m13s
CI & Build / integration (push) Successful in 2m29s
CI & Build / Build & push image (push) Successful in 32s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:37:42 -05:00
bvandeusenandClaude Opus 5.5 82ffd9a235 feat(8141): a rule holding the finished reply is recorded as a gate stop too
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m49s
CI & Build / integration (push) Successful in 2m4s
CI & Build / Build & push image (push) Skipped
The end-of-turn reply hold was the one gate the gate_stops table left out.
The server applies the per-session cap before anything holds and the Stop
hook blocks on every reason it is given, so the hook reports each held rule
after blocking, as the tool-call gates do: gate `reply`, tool `reply`, and
where the rule was reached (`rule_at`, new beside `rule_ids` in the
/reply-rules answer: the moment it is mounted on, or `reply_rule` for the
backstop). A section hold names no rule and stays counted by report_check.
Opening the rule clears the stop, and rule_misfired marks it, unchanged.

The readout, the telemetry docstring and the Settings panel name the new gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:32:46 -05:00
bvandeusenandClaude Opus 5.5 9b781d57de test(8141): the gate-stops readout is one of the retrieval endpoints
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 2m14s
CI & Build / integration (push) Successful in 2m18s
CI & Build / Build & push image (push) Successful in 44s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:18:49 -05:00
bvandeusenandClaude Opus 5.5 4ed9cd7d41 chore(plugin): mint the version for the gate-stop hooks
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Failing after 1m50s
CI & Build / integration (push) Successful in 2m17s
CI & Build / Build & push image (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:12:19 -05:00
bvandeusenandClaude Opus 5.5 65f1be80b6 feat(8141): every gate that stops a tool call is recorded, with what followed
A rule set to enforce or hold, the act checkpoint and the project fence
stopped work and left no record. The hook that makes each stop now reports
it to POST /api/plugin/gate-stop; the hook decides, not the server, because
the per-rule and per-session caps are kept in the plugin.

- gate_stops table (migration 0138): gate, outcome (stopped / let_through /
  asked), rule, where it was reached, tool, target project, call id.
- An open of the rule stamps the stop as cleared (rule-opened). A fenced
  call that then runs stamps ran: grimoire_fence_ran.sh, a PostToolUse on
  the fenced tools, matches the call id the fence left pending. That is
  the operator's yes.
- A hold or checkpoint the spent session budget lets through is reported
  as let_through; the per-rule once is not.
- The readout: by gate and by rule, stops, cleared by a read, misfired
  (rule_misfired after it), let through by the cap, ran. In
  retrieval_telemetry as `gates`, at /api/retrieval/gate-stops, and on the
  Moments settings page ("When a rule stopped the work").
- act_decision carries `at`, the moment the deciding rule was reached at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:12:14 -05:00
bvandeusenandClaude Opus 5.5 706f49a12a fix(fence): the cross-project permission prompt says what changes and where first, in plain words
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python tests (push) Successful in 2m2s
CI & Build / integration (push) Successful in 2m40s
CI & Build / Build & push image (push) Successful in 25s
The first line names the act and the project it lands in against the one the
session works in; the second says when to approve; the agent's issue-filing
call moves to a last line in parentheses. Tool names are spelled out and
project ids dropped from the operator's text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:56:19 -05:00
bvandeusenandClaude Opus 5.5 2903b090a1 fix(8139): the carried lines go to the after phase without a trailing newline
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 / Python tests (push) Successful in 2m3s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 26s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:51:00 -05:00
bvandeusenandClaude Opus 5.5 de55b73075 fix(8140): family triggers open only records that can carry an idea, and enter_project names a project's unevaluated candidates
CI & Build / Python lint (push) Successful in 7s
CI & Build / TypeScript typecheck (push) Successful in 43s
CI & Build / Plugin hooks (push) Successful in 49s
CI & Build / Python tests (push) Failing after 2m12s
CI & Build / integration (push) Successful in 2m41s
CI & Build / Build & push image (push) Skipped
Tasks, non-knowledge kinds and records titled for their own project are never
opened as candidates by the citation or repeat trigger; a lineage word inside
a quoted title no longer reads as lineage. The family line counts and names
this project's own candidates that only the system has decided on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:41:09 -05:00
bvandeusenandClaude Opus 5.5 55f53de92d fix(8139): a shape the agent walked past at the end-of-turn check is named again in its next notes
The after phase answers `left`, the asked lines still unjudged; the Stop hook
carries them as `earlier=` into the next checks, each up to two more asks, and
the note names them apart from the last turn's writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 09:41:09 -05:00
bvandeusen 6560dabe5b Merge pull request 'Telemetry reads take a closed window; enter_project records the family line' (#234) from dev into main
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Successful in 2m8s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 24s
2026-11-27 02:38:15 -05:00
bvandeusenandClaude Opus 5.5 69f3adae2c test(8118): the family-line integration test writes as a real user
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / integration (push) Successful in 2m15s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Successful in 2m12s
CI & Build / Build & push image (push) Successful in 22s
app_logs.user_id references users(id) in migration 0010 (the model does
not declare the key), so an invented user id made every entry write fail,
silently by design, and the readout counted zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:12:59 -05:00
bvandeusenandClaude Opus 5.5 577a8e8621 feat(8118,8119): telemetry reads take a closed window, and every enter_project records whether it carried the family line
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / integration (push) Failing after 2m15s
CI & Build / Python tests (push) Successful in 2m23s
CI & Build / Build & push image (push) Skipped
#8119: retrieval_telemetry and list_rules(with_usage) take `since` and
`until` (ISO date or datetime) besides `days`. Every windowed count is
bounded at both ends: sources, note/rule/system/moment usage, record
reach, judged lines and the floor-moved check. A review read after its
period can now keep a later deploy out of its counts. A bad bound is
refused rather than widened.

#8118: enter_project writes one AppLog row (family / enter_project) per
entry: the project, whether the family line was shown, its counts, and
whether the readout failed. It is spawned, so the handshake does not wait.
retrieval_telemetry gains a `family_line` block: per project, entries,
entries that carried the line, first and last shown, and the latest
counts. Review #5132's "did the project's sessions see the line" is now
answerable from this deploy on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:01:19 -05:00
bvandeusenandClaude Opus 5.5 0e946ffac8 docs(7832): the place arm is described as snippets beside the file, named by id
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 1s
CI & Build / Python tests (push) Successful in 2m32s
CI & Build / integration (push) Successful in 2m31s
CI & Build / Build & push image (push) Successful in 22s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:20:10 -05:00
bvandeusen bed78751c0 Merge pull request 'Records reach an edit and a message by structure first; resemblance offers notes (#7832)' (#233) 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 43s
CI & Build / Python tests (push) Successful in 2m0s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 19s
2026-11-25 12:58:37 -05:00
bvandeusenandClaude Opus 5.5 7c6b3fbc04 fix(7832): the edit search tests state notes-by-default, and the plugin version is minted for the static context change
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Successful in 2m10s
CI & Build / integration (push) Successful in 2m21s
CI & Build / Build & push image (push) Successful in 33s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:21:06 -05:00
bvandeusenandClaude Opus 5.5 4c69f9c163 feat(7832): records reach an edit and a message by structure first; resemblance offers notes
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Failing after 12s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Failing after 1m39s
CI & Build / integration (push) Successful in 2m17s
CI & Build / Build & push image (push) Skipped
The kind×moment table's first measured defaults (baseline note #7892):

- The edit door splits in two rows. work.change is what is recorded where
  the edit is (snippets beside the file, issues naming it or open in its
  area); work.change.similar is what the code resembles, notes by default.
  Issues and snippets no longer reach an edit by resemblance.
- Snippets recorded beside the file are named by id in an "Also recorded
  beside this file" pointer line instead of taking menu lines.
- The message door leaves lessons and issues out by default: a lesson
  arrives at its confirmed situation, an issue through its area or its id.
  Its lesson slot runs only for a user who turns lessons back on.
- The static context teaches the new pointer line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 12:17:29 -05:00
bvandeusen e21c52a5e7 Merge pull request 'A lesson recorded for reply.report reaches the turn before the reply (#7883)' (#232) 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 33s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m23s
CI & Build / Build & push image (push) Successful in 18s
2026-11-25 11:52:55 -05:00
bvandeusenandClaude Opus 5.5 07c4a716bd fix(7883): a lesson recorded for reply.report reaches the turn before the reply, and reply.ask is not offered to a lesson
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 2m0s
CI & Build / Python tests (push) Successful in 3m48s
CI & Build / Build & push image (push) Successful in 20s
Situated lessons arrived only at tool acts and in MCP replies, so a lesson
given a reply moment was accepted and never shown. The per-turn delivery now
carries lessons confirmed on reply.report, once per session, between the
turn's rules and its reply shape. reply.ask is known only after the reply is
written, so lesson_situations refuses it and leaves it out of the catalog the
pass and the lesson page offer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 10:48:12 -05:00
bvandeusen 5be37b05ac Merge pull request 'Records reach work just in time: pointer lines and lessons by situation (milestone 642, steps 5–6)' (#231) from dev into main
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m57s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Successful in 17s
2026-11-25 09:39:15 -05:00
bvandeusenandClaude Opus 5.5 5bde619511 fix(7836): lesson situations travel in backups, and the edit door test states the new intent
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m5s
CI & Build / integration (push) Successful in 2m12s
CI & Build / Build & push image (push) Successful in 33s
- backup v31 carries lesson_situations (full and per-user export, restored
  through the note map);
- the lesson surfacing test now pins that the edit door's search leaves
  lessons to their situation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:18:45 -05:00
bvandeusenandClaude Opus 5.5 c22e8e1844 feat(7836): a lesson arrives at the situation confirmed for it, once per session
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Skipped
Each lesson can carry its situation: a moment of work (work.deliver,
work.finish, ...) or a typed trigger on the act (path, command, tool,
keyword, matched as rule triggers are). A pass proposes, a person judges:

- lesson_situations (migration 0137): one row per lesson, kind and value,
  suggested / confirmed / rejected; `none` records that no situation fits;
- MCP: lessons_to_situate, propose_lesson_situations,
  lesson_situation_proposals, judge_lesson_situations;
- Settings > Moments lists waiting proposals with Apply / Not this /
  Apply all; a lesson page lists its situations and lets a writer add one
  or take one off (kept as rejected, never proposed again).

Delivery: the moment doors (the plugin catch-all hook and MCP replies) add
the lessons whose confirmed moment the act reached or whose trigger it
matches. The plugin door shows each once per session, using the record
ledger, and records it as pushed (source lesson_situation); the tool filter
now includes the tools a lesson trigger listens on.

The edit door no longer finds lessons by meaning: lesson leaves the
work.change default kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:10:23 -05:00
bvandeusenandClaude Opus 5.5 ff3fca6a94 test(7836): the client's link states are pinned to what a read returns
CI & Build / TypeScript typecheck (push) Canceled after 0s
CI & Build / Plugin hooks (push) Canceled after 0s
CI & Build / Python lint (push) Canceled after 0s
CI & Build / Python tests (push) Canceled after 0s
CI & Build / integration (push) Canceled after 0s
CI & Build / Build & push image (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:07:32 -05:00
bvandeusenandClaude Opus 5.5 1a8c02bfe5 feat(7836): lessons and rules are no longer paired by arriving together
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Failing after 1m40s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Skipped
The co-arrival recorder counted a lesson and a rule shown in one response
as evidence that the lesson is an instance of the rule, and asked the
reader to judge the pair once three situations had gathered. Two records
that resemble the same prompts arrive together whether or not one is an
instance of the other, and the outcome bore that out (2,317 pairs
suggested, 23 confirmed). It no longer runs:

- neither the prompt door nor the write path records co-arrivals or
  carries a proposal line;
- a rule read lists the lessons judged against it, confirmed first, and a
  lesson read the rules it was judged against: suggested rows stay in the
  table and no read shows them;
- the lesson page and the rule editor drop the suggested section.

The situation-counting helpers stay; rule moment judgments use them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:02:10 -05:00
bvandeusenandClaude Opus 5.5 2f93a4f7b5 test(7835): a record past the write path's margin is pinned to the pointer, not to silence
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 2s
CI & Build / integration (push) Successful in 2m28s
CI & Build / Python tests (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 40s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:24:34 -05:00
bvandeusenandClaude Opus 5.5 b68aefc109 feat(7835): what resembles the work but is not shown is named by id in one pointer line
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Failing after 2m1s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / integration (push) Successful in 2m20s
CI & Build / Build & push image (push) Skipped
A pointer before a payload:
- the notes arms fetch a few results past the menu; those that cleared
  the floor but were held back by the gate, the band or the budget are
  named by id per kind, with the call that opens each kind, in one line
  ("Also resembling this, not shown: ...") at the message and the write
  path;
- they are recorded in the record ledger as `pointed`, so an open that
  follows is counted apart from pushed lines;
- setting a task in progress returns records_in_area: the notes and open
  issues tagged to the task's areas, by id (a work.start row in the
  kind x moment table says which kinds; it answers in a tool reply, so it
  is shown as unmeasured).

The static context says what a pointer line means. Plugin version minted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 19:16:01 -05:00
bvandeusenandClaude Opus 5.5 a2e474f401 feat(7834): issues linked to the file being written arrive before anything found by meaning
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m53s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 30s
Before a write, the write path now looks up issues by structure:
- an issue whose body or a log names the file (any status: a closed one
  is the record of what was already tried there);
- an open issue tagged to an area whose path patterns cover the file.

At most two, listed first, withheld from the search by meaning, which
fills only what is left and only past the gate. Measured under
write_path_linked. The lookups follow the kind x moment table: no issue
lookup when issues are off at work.change, no nearby-snippet lookup when
snippets are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:58:59 -05:00
bvandeusen 312d838661 Merge pull request 'Records reach work: the record ledger and the kind×moment table (milestone 642, steps 1 and 3)' (#230) from dev into main
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Successful in 2m6s
CI & Build / integration (push) Successful in 2m2s
CI & Build / Build & push image (push) Successful in 17s
2026-11-24 14:40:00 -05:00
bvandeusenandClaude Opus 5.5 1363936ed7 test(7833): the write path is pinned to the kinds its door considers, not the retired fixed lists
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 / Python tests (push) Successful in 2m4s
CI & Build / integration (push) Successful in 2m14s
CI & Build / Build & push image (push) Successful in 39s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:32:28 -05:00
bvandeusenandClaude Opus 5.5 9cbdfb205c feat(7833): each moment declares which kinds of record its search may consider, editable in Settings > Moments
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m35s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Skipped
The kind x moment table (services/record_kinds.py):
- every record search fires at a door: the operator message, or a
  catalog moment (work.change for the write path);
- each door considers a set of kinds (snippet, note, lesson, process,
  task:issue/work/spike/plan); a kind left out is never searched there;
- the shipped defaults are today's behaviour; a user's change is stored
  per door, and putting a door back removes it.

Both note arms read it, replacing their fixed kind lists, and a reserved
slot whose kind is turned off is not reserved. The review re-run
searches the same kinds. Settings > Moments shows and edits the table,
with each cell's lines shown and opens from the record ledger.
list_moments returns it as record_kinds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:24:53 -05:00
bvandeusenandClaude Opus 5.5 b0fab00fe2 feat(7831): every record a session is shown, asks for or opens on its own is recorded per session, by kind
CI & Build / Plugin hooks (push) Successful in 18s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m6s
CI & Build / Build & push image (push) Successful in 32s
A ledger beside the rule deliveries (record_deliveries, migration 0136):
- every note, snippet, issue, lesson or process line a plugin door pushes
  is recorded against the session, only when the payload kept it;
- a search the session runs itself records its results as asked, matched
  to the server log of that call;
- an open is stamped on the delivery it followed, or recorded as direct
  when nothing showed the record first.

The plugin reports opens and searches from the tool calls
(grimoire_record_read.sh). The readout is in retrieval_telemetry
(record_reach), at /api/retrieval/record-reach, and in Settings > Moments
as "How records reach the work". Plugin 2026.11.24.1827.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 13:27:13 -05:00
bvandeusen 029b5867ed Merge pull request 'A rule the session already read counts as opened when it arrives again' (#229) from dev into main
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m15s
CI & Build / integration (push) Successful in 2m32s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Build & push image (push) Successful in 22s
2026-11-24 07:24:33 -05:00
bvandeusenandClaude Opus 5.5 394f83427d fix(7735): the read-already backfill touches only the rows the readers count
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Successful in 2m1s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 17s
Rows without a plugin version are skipped by every open-rate reader and are
most of the table, so the correlated lookup runs on the rows recorded since
0133 only. Keeps the migration cheap on the live table, not just in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 07:10:01 -05:00
bvandeusenandClaude Opus 5.5 78fa165e67 fix(7735): a rule the session already read counts as opened when it arrives again
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 2m2s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Successful in 34s
A delivery to a session that opened the rule within the open window is
stamped opened as it is written, and migration 0135 stamps the rows already
recorded the same way. The adherence readout, the ordering open rate and the
weighing pass read one definition: a rule read early in a long session is not
counted unread each time it is delivered later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 07:06:18 -05:00
bvandeusen 6eb47f72f9 Merge pull request 'Adherence per rule and per moment; Apply all; quoted text and heredocs are not commands; the instruction surfaces teach enforcement and salience' (#228) 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 35s
CI & Build / Python tests (push) Successful in 2m9s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Successful in 18s
2026-11-23 18:21:44 -05:00
bvandeusenandClaude Opus 5.5 c486524b48 fix(7734): rule curation across projects is taught with the other rule-editing guidance, keeping SKILL.md inside its budget
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m7s
CI & Build / integration (push) Successful in 2m17s
CI & Build / Build & push image (push) Successful in 23s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 18:05:52 -05:00
bvandeusenandClaude Opus 5.5 6f0368e770 feat(7734): the instruction surfaces teach how strongly a rule arrives, what a held or refused call means, and what a quiet moment means
CI & Build / TypeScript typecheck (push) Successful in 40s
CI & Build / Plugin hooks (push) Successful in 20s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Failing after 2m0s
CI & Build / integration (push) Successful in 2m28s
CI & Build / Build & push image (push) Skipped
- writing-records.md: a new section on declaring enforcement (inform, hold,
  enforce), the trigger a hold or refusal needs to name its act, and
  salience. A rule with an exit is a hold; a rule with triggers stops only
  the acts they match.
- moments.md: a held call is read and made again (unchanged if the rule does
  not bear on it, with rule_misfired); a refused call is the operator's
  boundary and moves only when they change the rule; a moment sends a few
  lines in one order and drops the rest, so a quiet moment is not an empty
  rulebook.
- The static context says a rule can hold or refuse a tool call.
- create_rule, create_project_rule and update_rule describe enforce as a
  refusal every time that needs an act, and trigger-only holds.
- The cross-project guard words a rule edit on another project as the
  operator's curation, naming the rule, and no longer suggests filing an
  issue in its place.

_INSTRUCTIONS is at its 1,600-character cap and is left alone: holds and
refusals explain themselves when they fire. The guidance ownership test
registers the three new topics. Plugin 2026.11.23.2259.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:59:55 -05:00
bvandeusenandClaude Opus 5.5 cbe4b25dad fix(639): quoted text and heredoc bodies are not commands when an act is matched to a moment
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python lint (push) Canceled after 0s
CI & Build / Python tests (push) Canceled after 0s
CI & Build / integration (push) Canceled after 0s
CI & Build / Build & push image (push) Canceled after 0s
CI & Build / Plugin hooks (push) Canceled after 2s
A Bash command was split into segments on every `&&`, `||`, `;`, `|` and
newline, including those inside quotes and the lines of a heredoc. A script
written with `python3 - <<EOF` that mentioned curl reached env.reach, and a
grep for "a && git push" reached work.deliver. The splitter now reads the
line as the shell does: separators inside quotes are text, a heredoc's body
is skipped through its end word (`<<-` strips leading tabs), and a
backslash-newline continues the line. Command triggers use the same split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:57:41 -05:00
bvandeusenandClaude Opus 5.5 5f55bd1575 fix(7733): the route census lists /adherence, and the moments skill opens with its contents
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m38s
CI & Build / integration (push) Successful in 2m38s
CI & Build / Build & push image (push) Successful in 42s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:34:11 -05:00
bvandeusenandClaude Opus 5.5 b4bdd7798c feat(7733): adherence is measured per rule and per moment, and shown
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Skipped
A rule is in force at a moment of a session when it was delivered there.
Each (session, rule, place) now carries at most one verdict (rule_adherence,
migration 0134): followed, departed, broken or not applicable, with where it
came from:

- an enforce rule refusing the act: followed, recorded by the moment arm, and
  never replaced;
- the session's own rule_outcome (applied, departed) and rule_misfired calls,
  which the plugin's outcome hook now also posts with the session id
  (/api/plugin/rule-verdict) onto the delivery being answered;
- a transcript review: adherence_to_judge lists what has no verdict yet, by
  session, and judge_adherence records verdicts with their evidence.

rule_adherence (MCP) and /api/retrieval/adherence give the readout: sessions
in force, opened and each verdict per rule and per place. Settings > Moments
shows it in a "Were they followed" panel, beside each moment's delivered and
opened counts, and per rule inside each moment.

Verdicts are pruned with their deliveries and left out of backups like them.
Plugin 2026.11.23.2227.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:28:23 -05:00
bvandeusenandClaude Opus 5.5 e70b2c2c00 feat(7733): Apply all confirms every waiting weight suggestion at once, after a dialog that counts what changes
CI & Build / Python lint (push) Successful in 1s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m15s
CI & Build / Build & push image (push) Successful in 35s
The dialog names how many changes across how many rules, and how many of
those rules will start holding or refusing the acts they govern. A refused
item is reported in a toast; the rest still apply.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 17:19:59 -05:00
bvandeusen 2996ae793d Merge pull request 'Open rates count only deliveries whose plugin reports opens; a rule with triggers holds only the acts they match' (#227) 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 34s
CI & Build / Python tests (push) Successful in 2m11s
CI & Build / integration (push) Successful in 2m23s
CI & Build / Build & push image (push) Successful in 19s
2026-11-23 16:12:35 -05:00
bvandeusenandClaude Opus 5.5 2794fd97f0 fix(7733): shellcheck reads plugin_version as set for the hooks that source grimoire_defs.sh
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m5s
CI & Build / integration (push) Successful in 2m17s
CI & Build / Build & push image (push) Successful in 36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 16:00:16 -05:00
bvandeusenandClaude Opus 5.5 738bd24d6e fix(7733): a rule with triggers holds or refuses only the acts they match
CI & Build / Plugin hooks (push) Failing after 19s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m31s
CI & Build / integration (push) Successful in 2m18s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Build & push image (push) Canceled after 27s
Rules 2, 4, 10 and 153 are set to hold and mounted on work.deliver. A
push to dev therefore stopped four times in a row, once for each of them,
although none of them governs a push to dev: their triggers (git push
origin main, git tag, pytest, pull_request_write) name the acts they do
govern.

A rule that has triggers now stops an act only when one of them matched it.
Reached by its moment alone, it is a line beside the work. A rule with no
triggers still holds wherever it is mounted, because the mount is all that
says where it applies. A mounted rule whose unscoped trigger also matched
now counts as reached by the trigger, so it ranks as triggered and may
stop the act.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:53:36 -05:00
bvandeusenandClaude Opus 5.5 e0621713d4 fix(7733): a rule's open rate counts only deliveries whose plugin reports opens
CI & Build / TypeScript typecheck (push) Canceled after 0s
CI & Build / Plugin hooks (push) Canceled after 0s
CI & Build / Python lint (push) Canceled after 0s
CI & Build / Python tests (push) Canceled after 0s
CI & Build / integration (push) Canceled after 0s
CI & Build / Build & push image (push) Canceled after 0s
Each rule line a hook delivers now records the plugin version that asked for
it (the X-Grimoire-Plugin header every hook request sends). The open rate
used to order rules, and the delivery history the weighing pass reads,
count only deliveries that carry one.

A plugin before 2026.11.22.2312 never reported an open of a rule a hook had
just named, so every delivery made to such a session read as unopened. The
server shipped delivery recording from dev on 2026-11-22. The plugin ships
from main, and a running session keeps the plugin it started with, so those
sessions kept arriving. They are why opens read about 1 in 600. Existing
rows have no version and drop out of the rate; nothing is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:52:42 -05:00
bvandeusen 177c206216 Merge pull request 'Milestone 639 steps 5–6: enforced rules refuse the act, only hold rules hold, and a pass weighs each rule' (#226) from dev into main
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python tests (push) Successful in 2m1s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Successful in 16s
2026-11-23 13:21:22 -05:00
bvandeusenandClaude Opus 5.5 3a11c11543 fix(7732): the weighing tools declare that they write to no project, as the moment pass does
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 1m58s
CI & Build / integration (push) Successful in 2m2s
CI & Build / Build & push image (push) Successful in 39s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:10:58 -05:00
bvandeusenandClaude Opus 5.5 619612732f feat(7732): a pass weighs each rule — enforcement, salience and triggers proposed from its text and delivery history, confirmed by the operator
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 2m9s
CI & Build / Build & push image (push) Skipped
Adds rule_field_judgments (migration 0132), the rules_to_weigh / propose_rule_weights / rule_weight_proposals / judge_rule_weights tools, the routes and the Settings › Moments panel that confirms them. A value equal to the rule's own is recorded as agreed; a different one waits; enforce is refused for a rule no act reaches; a direct edit answers a waiting suggestion. Backup v30 carries the judgments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:05:38 -05:00
bvandeusenandClaude Opus 5.5 78c945e7c3 fix(7731): the stop after a note sends its lines without a trailing newline, as the check does
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 2m7s
CI & Build / integration (push) Successful in 2m23s
CI & Build / Build & push image (push) Successful in 43s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:31:37 -05:00
bvandeusenandClaude Opus 5.5 7d46ce0229 feat(7731): enforced rules refuse the act, only hold rules hold, and the shape question rides the next prompt
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m45s
CI & Build / integration (push) Successful in 2m10s
CI & Build / Build & push image (push) Skipped
- A rule set to enforce, reached by a mount or a trigger, refuses the tool
  call in its own words every time (`act_decision`, `/moment` returns
  `decision`, grimoire_moment.sh denies). Opening it does not lift it.
- A rule set to hold denies the call once until read, under the act
  checkpoint's per-rule and per-session guard; file writes are never held.
- The reply hold, the reply backstop and the act checkpoint hold only on rules
  declared hold or enforce (`rule_order.holds`). An inform rule is a line
  beside the work.
- The prompt arm leaves rules that arrive at an act (mounted on a non-reply
  moment, or with a tool/path/command trigger) to that act.
- The end-of-turn shape check no longer blocks: its note is kept for the next
  prompt, carried as `carry` into the one fitted payload, and the stop after
  that prompt records whether the lines were judged (noted /
  judged_after_note / left_after_note).
- Rule editor and list copy say what hold and enforce now do. Plugin
  2026.11.23.0005.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:22:56 -05:00
bvandeusen 8798b5c59a Merge pull request 'Milestone 639 steps 3–4: one assembler per hook under a budget; prior art and preferences behind a cue-swap gate' (#225) from dev into main
CI & Build / integration (push) Successful in 2m16s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 31s
CI & Build / Python tests (push) Successful in 1m50s
CI & Build / Build & push image (push) Successful in 19s
2026-11-23 00:10:34 -05:00
bvandeusenandClaude Opus 5.5 6b4c24e336 test(7730): the retrieval route inventory includes the gate readout
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python tests (push) Successful in 2m9s
CI & Build / integration (push) Successful in 2m21s
CI & Build / Build & push image (push) Successful in 42s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:11:46 -05:00
bvandeusenandClaude Opus 5.5 4a65f5ddfd feat(7730): prior art and preferences speak only past a cue-swap gate, at most two lines
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python tests (push) Failing after 1m35s
CI & Build / integration (push) Successful in 2m1s
CI & Build / Build & push image (push) Skipped
A record or preference found by resemblance alone is shown only when the
message's score beats all but a set share (default 10%) of the user's own
recent cues on that surface and project. The comparison set is the
best_available_score already logged per call, so the bar rises with the
store by construction and a fixed floor no longer decides. Too few cues to
judge by is silence; the searches still run and calibrate the gate.

- cue_gate: conformal bar, per (user, surface, project) with a user-wide
  fallback, cached five minutes; readout for Settings.
- Notes arms (auto_inject, write_path) abstain unless the top line passes,
  show at most two lines, and hold slots to the same bar and cap.
- Rule arms hold preference lines to the gate; rules are not gated.
- retrieval_logs gains gate_bar and gate_kept (migration 0131).
- Turns the harness wrote are refused server-side as well as in the plugin.
- Settings: the rate field and a per-surface readout of bar and how often
  each surface spoke; GET /api/retrieval/gate.
- Replay test: on unrelated cues a fixed bar tuned to 5% on a 32-record
  store fires ~97% on 2,048 records; the gate stays near 10% at both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 21:05:02 -05:00
bvandeusenandClaude Opus 5.5 05831149b8 fix(7729): a rule with no statement keeps its full line, and the delivery test flushes like a door
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 1m56s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 33s
A first mention whose rule had an empty statement fell through to the
reference form and lost its "may apply <where>" — for a trigger-fired rule,
the very clause that says which trigger fired. The full form now renders
with or without a statement. The integration helper flushes the request
buffer, as a door does once its payload is fitted. using-grimoire trimmed
back to its 350-line budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 19:12:06 -05:00
bvandeusenandClaude Opus 5.5 a16dee4080 feat(7729): one assembler per hook — rule statements first, then the reply shape, then records, under a budget
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m47s
CI & Build / integration (push) Failing after 2m0s
CI & Build / Build & push image (push) Skipped
A rule line on first mention now carries the rule's own statement, written as
a statement about the rule ("Rule 11 … may apply here; it binds: …") rather
than an instruction to go read it; a repeat or lower-ranked line is a
reference ("Also relevant: Rule 11 …"). Every line ends with where the session
stands with the rule and get_rule(id) for the full text.

services/hook_payload.py fits every injecting door's payload (prompt,
pre-tool rules, moment, write path) to the user's budget: parts in one order,
kept while they fit, dropped whole otherwise. A dropped part's ids leave the
response lists, so the plugin ledgers mark only what was shown, and rule
deliveries are buffered per request and written only for kept lines.

Budget: Settings, default 4,500 characters (the full core reply shape is
2,343 and a full rule line up to ~750, so 3,000 would have crowded the shape
out of most turns), clamped to 1,000-7,500 — under the lower of the two
recorded hook caps (10,000 in the docs, 8,000 read from an installed build).
check_plugin asserts the ceiling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 19:04:58 -05:00
bvandeusen 2326e04665 Merge pull request 'Milestone 639 step 2: typed rules, one delivery order, per-delivery records, triggers, lifecycle' (#224) from dev into main
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m58s
CI & Build / integration (push) Successful in 2m14s
CI & Build / Build & push image (push) Successful in 23s
2026-11-22 18:51:03 -05:00
bvandeusenandClaude Opus 5.5 97d79927b5 fix(7728): trigger chips reuse the shared rule chip, and the export test pins rule_triggers
CI & Build / Python lint (push) Successful in 1s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 38s
The editor styled its trigger list through `.trigger-list .rule-chip`,
which re-spells the shared chip the guard keeps in one stylesheet; the
row now adds its own `.trigger-chip` for layout. The full-export test now
asserts the v29 rule_triggers section is present.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:33:28 -05:00
bvandeusenandClaude Opus 5.5 c9e64450ba feat(7728): typed triggers on a rule, and a rule says its piece once per session
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 22s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Skipped
Triggers (migration 0130, table rule_triggers): a rule can name the act it
applies to, as a tool, a path glob, a command head or a keyword, checked
exactly against the act rather than by resemblance. With no moment a
trigger delivers its rule on any matching act, even one that reaches no
moment; scoped to a moment, it makes the rule's mount there conditional
on the act matching. A triggered line ranks above a mounted one in the
delivery order and names the trigger that fired. Writable through every
MCP and REST rule door, carried by backup (version 29), and edited in the
rule editor under "Acts that trigger it". The plugin's catch-all hook is
told which tools a trigger can reach.

Lifecycle: a rule's life in a session is one full line, one reminder,
then silence. A repeat whose latest delivery in the session was already a
reminder is left out of both rule arms. A rule that holds stays armed
until it is opened, an opened rule keeps its line, and a full delivery
(after a compaction or once the ledger ages it out) re-arms it. Read from
the delivery records, so it needs no new plugin ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:24:39 -05:00
bvandeusenandClaude Opus 5.5 7df478550f test(7728): the pre-tool hook and route agree that session_id is sent and bound
CI & Build / TypeScript typecheck (push) Canceled after 0s
CI & Build / Plugin hooks (push) Canceled after 0s
CI & Build / Python lint (push) Canceled after 0s
CI & Build / Python tests (push) Canceled after 0s
CI & Build / integration (push) Canceled after 0s
CI & Build / Build & push image (push) Canceled after 0s
The hook now names its session for the delivery record, and the plugin
blueprint binds it before every handler. The contract test pins both.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:18:52 -05:00
bvandeusenandClaude Opus 5.5 61873b184b feat(7728): one delivery order for rules, and each delivery recorded with whether it was opened
CI & Build / TypeScript typecheck (push) Successful in 41s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m41s
CI & Build / integration (push) Successful in 1m59s
CI & Build / Build & push image (push) Skipped
Every rule arm now ranks what it delivers with one function
(services/rule_order.py): enforcement, then salience, then how narrowly
the rule was reached, then first mention before reminder, then the
rule's own open rate at that moment, then similarity. A crowded moment
drops the same rules whichever arm brought them, and a rule that holds
is never cut for a line beside it.

The open rate comes from a new table, rule_deliveries (migration 0129):
one row per rule line a plugin session is shown, full or repeat, with the
open stamped on the latest delivery it followed. The plugin routes bind
the session per request; the prompt, pre-tool and write-path hooks now
send it, and the opened hook reports every open, with its acts only when
no hook had just named the rule. Rows are pruned daily after 180 days.

Also fixes the TypeScript check: the store's list row now carries the
new enforcement field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:13:16 -05:00
bvandeusenandClaude Opus 5.5 61077752b9 feat(7728): a rule declares its enforcement and salience
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Failing after 21s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / integration (push) Successful in 2m2s
CI & Build / Build & push image (push) Skipped
A rule now carries what it does when it arrives, declared by its author
rather than guessed from a score: enforce (the act is checked), hold (the
reply or act waits for one read) or inform (a line beside the work, the
default). And a salience, high, normal or low, for ranking among rules of
the same enforcement at a crowded moment. A preference is always inform.

Migration 0128 adds both with CHECKs. Every door carries them: the
service, the MCP create and update tools, REST, backup and restore, and
the rule editor, which also marks holding and enforced rules in the list.
Unknown values are refused rather than mapped. Nothing reads them yet
beyond the record; the ordering function and the lifecycle come next in
this step, and step 5 decides who holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:05:45 -05:00
bvandeusen 0b4463026c Merge pull request 'Record references link to what they cite, by title' (#223) 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 34s
CI & Build / Python tests (push) Successful in 1m50s
CI & Build / integration (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 17s
2026-11-22 17:58:22 -05:00
bvandeusenandClaude Opus 5.5 da7c43aa8a feat(7741): a record reference shows the title of what it cites, before its number
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m48s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 36s
A cited #N, milestone N or rule N in a rendered body now reads as the
record's title followed by its number, muted, so a reader knows what is
cited without hovering. The stored text stays #N and the title is read at
render: every existing record benefits and an edited title shows wherever
it is cited. Titles past 60 characters are shortened at a word, with the
full kind, title and status in the tooltip. A reference whose paragraph
already names the record (a batch writes #9 "Step two") keeps the bare
number, as does one the reader cannot open.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 17:49:30 -05:00
bvandeusenandClaude Opus 5.5 08fdabd5e9 test(7736): the range case no longer puts "steps" before the first id
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m50s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Successful in 43s
"step" is in the other-numbering word list ("step #3" is a position in
a plan), so "steps #5110" correctly stays plain. The case now tests the
range alone, and a second case pins the "step #3" reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:18:40 -05:00
bvandeusenandClaude Opus 5.5 38bc25a2b7 fix(7736): #N in a body links to the record it names, not to a tag
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / Python tests (push) Failing after 1m37s
CI & Build / integration (push) Successful in 2m11s
CI & Build / Build & push image (push) Skipped
A purely numeric #N is a record reference everywhere now. The tag
patterns (frontend utils/tags.ts, the editor decoration, the first-line
tag strip, tag autocomplete, backend utils/tags.py) leave digits alone,
so #3127 is no longer drawn as a tag chip linking to /notes?tag=3127.

- utils/recordRefs.ts links #N, milestone N and rule N in rendered
  markdown, with the same patterns and other-numbering word list as
  services/record_refs.py. A drift test reads the TS source and fails
  when the two differ.
- v-record-refs (directives/recordRefs.ts) asks POST
  /api/notes/resolve-refs once per body for what each id is. A link
  gets the route for its kind (task, lesson, snippet, note, milestone,
  rule) and its kind and title on hover. One the reader cannot open is
  drawn as a dead reference, and missing vs not shared read the same.
  Applied on every surface that renders markdown.
- /milestones/:id finds the project and opens its board at that
  milestone (?milestone= expands it, scrolls to it and focuses it).
- Backlinks include records that cite #N in a body or a work log,
  through readable_notes_clause instead of an owner-only filter, and
  route by kind. The graph draws #N citations as dashed reference edges.
- create_note, create_task and add_task_log say which forms link.

There were no numeric tags to clean up: tags are stored only from the
explicit field, and none of the 200 most used is numeric.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 14:15:15 -05:00
bvandeusen 7e733ab966 Merge pull request 'Release: a verdict on a vanished shape revives its row' (#222) from dev into main
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 1m47s
CI & Build / TypeScript typecheck (push) Successful in 31s
CI & Build / integration (push) Successful in 2m11s
CI & Build / Build & push image (push) Successful in 18s
2026-11-05 16:51:10 -05:00
bvandeusenandClaude Opus 5.5 6be44013bb fix(6872): a verdict or write-path stamp on a vanished shape revives its row instead of inserting a duplicate
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m46s
CI & Build / integration (push) Successful in 1m42s
CI & Build / Build & push image (push) Successful in 18s
classify_shapes(repo=...) and the write-path hook looked only at live rows,
so a shape whose row had vanished got a second provisional row under the
same (project, repo, path, symbol, kind). The unique constraint refused it,
and the whole classify batch was lost as a tool error.

provisional_row() now finds the row under that identity, vanished or not.
A vanished row is revived with a reappeared event and keeps its judgment.
A new row is inserted inside a savepoint, so a concurrent insert of the
same identity falls back to that row instead of failing the transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:02:13 -05:00
223 changed files with 17515 additions and 1317 deletions
+2
View File
@@ -148,3 +148,5 @@ docker compose -f docker-compose.dev.yml up --build
## Licence
Fabled Grimoire is free software under the [GNU Affero General Public License v3.0 only](LICENSE) (`AGPL-3.0-only`). If you run a modified version for other people over a network, the licence requires you to offer them its source.
The Claude Code plugin in [`plugin/`](plugin/) is a separate work under the [MIT License](plugin/LICENSE) (`MIT`), so you can adapt it inside your own tooling freely.
+48
View File
@@ -0,0 +1,48 @@
"""rule enforcement and salience — what a rule does when it arrives, and how much it outranks
Revision ID: 0128
Revises: 0127
Create Date: 2026-11-22
Two declared columns on a rule, read by the one function that orders what
reaches a moment:
- `enforcement`: `enforce` (the act itself is checked), `hold` (the reply or act
waits for one read), `inform` (a line beside the work). Every existing rule
starts as `inform`; declaring which ones hold is the author's call.
- `salience`: `high`, `normal`, `low` — the author's ranking among rules of
the same enforcement.
"""
import sqlalchemy as sa
from alembic import op
revision = "0128"
down_revision = "0127"
branch_labels = None
depends_on = None
_ENFORCEMENTS = ("enforce", "hold", "inform")
_SALIENCES = ("high", "normal", "low")
def _in_list(column: str, values: tuple[str, ...]) -> str:
return f"{column} IN ({', '.join(repr(v) for v in values)})"
def upgrade() -> None:
op.add_column("rules", sa.Column("enforcement", sa.Text(), nullable=False, server_default="inform"))
op.add_column("rules", sa.Column("salience", sa.Text(), nullable=False, server_default="normal"))
op.create_check_constraint("ck_rules_enforcement", "rules", _in_list("enforcement", _ENFORCEMENTS))
op.create_check_constraint("ck_rules_salience", "rules", _in_list("salience", _SALIENCES))
# A preference claims no force: it is how work is liked done, not a bar.
op.create_check_constraint(
"ck_rules_preference_informs", "rules", "kind <> 'preference' OR enforcement = 'inform'",
)
def downgrade() -> None:
op.drop_constraint("ck_rules_preference_informs", "rules", type_="check")
op.drop_constraint("ck_rules_salience", "rules", type_="check")
op.drop_constraint("ck_rules_enforcement", "rules", type_="check")
op.drop_column("rules", "salience")
op.drop_column("rules", "enforcement")
+42
View File
@@ -0,0 +1,42 @@
"""rule deliveries — each rule line a session was shown, and whether it was opened after
Revision ID: 0129
Revises: 0128
Create Date: 2026-11-22
One row per rule line delivered to a session, with the open stamped on the
delivery it followed. The open rate per rule and moment is read from it, both
for the ordering of what reaches a moment and for the adherence readout.
"""
import sqlalchemy as sa
from alembic import op
revision = "0129"
down_revision = "0128"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_deliveries",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("rule_id", sa.BigInteger(), nullable=False),
sa.Column("source", sa.Text(), nullable=False),
sa.Column("at", sa.Text(), nullable=False),
sa.Column("form", sa.Text(), nullable=False),
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint("form IN ('full', 'repeat')", name="ck_rule_deliveries_form"),
)
op.create_index("ix_rule_deliveries_session_rule", "rule_deliveries",
["user_id", "session_id", "rule_id", "delivered_at"])
op.create_index("ix_rule_deliveries_rule_at", "rule_deliveries", ["rule_id", "at"])
op.create_index("ix_rule_deliveries_delivered_at", "rule_deliveries", ["delivered_at"])
def downgrade() -> None:
op.drop_table("rule_deliveries")
+38
View File
@@ -0,0 +1,38 @@
"""rule triggers — typed predicates on the act that deliver a rule, checked in code
Revision ID: 0130
Revises: 0129
Create Date: 2026-11-22
A trigger is a kind (tool, path, command, keyword) and a pattern, optionally
scoped to a moment. Unscoped, it delivers the rule on any act that matches;
scoped, it makes the rule's mount on that moment conditional on the act
matching. Matched in code against the act, never by embedding.
"""
import sqlalchemy as sa
from alembic import op
revision = "0130"
down_revision = "0129"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_triggers",
sa.Column("rule_id", sa.BigInteger(),
sa.ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
sa.Column("kind", sa.Text(), primary_key=True),
sa.Column("pattern", sa.Text(), primary_key=True),
sa.Column("moment", sa.Text(), primary_key=True, server_default=""),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=True),
sa.CheckConstraint(
"kind IN ('tool', 'path', 'command', 'keyword')", name="ck_rule_triggers_kind",
),
sa.CheckConstraint("length(pattern) > 0", name="ck_rule_triggers_pattern"),
)
def downgrade() -> None:
op.drop_table("rule_triggers")
+28
View File
@@ -0,0 +1,28 @@
"""retrieval_logs records the cue-swap gate: its bar and how many lines passed
Revision ID: 0131
Revises: 0130
Create Date: 2026-11-23
A gated surface shows a line found by resemblance only when its score beats
most of the user's own recent cues on that surface. Each call row keeps the
bar it was held to and how many lines reached it, so how often a surface
speaks can be read back, per surface, as the store grows.
"""
import sqlalchemy as sa
from alembic import op
revision = "0131"
down_revision = "0130"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("retrieval_logs", sa.Column("gate_bar", sa.Float(), nullable=True))
op.add_column("retrieval_logs", sa.Column("gate_kept", sa.Integer(), nullable=True))
def downgrade() -> None:
op.drop_column("retrieval_logs", "gate_kept")
op.drop_column("retrieval_logs", "gate_bar")
@@ -0,0 +1,51 @@
"""rule field judgments — proposed and judged enforcement, salience and triggers
Revision ID: 0132
Revises: 0131
Create Date: 2026-11-23
A pass reads each rule with its delivery history and proposes how strongly it
should arrive and what should reach it; a person confirms or rejects each
value. One row per (rule, field, value), so a rejected value is never proposed
again and a rule the pass agreed with reads as looked at.
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0132"
down_revision = "0131"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_field_judgments",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("rule_id", sa.BigInteger(),
sa.ForeignKey("rules.id", ondelete="CASCADE"), nullable=False),
sa.Column("field", sa.Text(), nullable=False),
sa.Column("value", sa.Text(), nullable=False),
sa.Column("state", sa.Text(), nullable=False, server_default="suggested"),
sa.Column("source", sa.Text(), nullable=False, server_default="pass"),
sa.Column("note", sa.Text(), nullable=True),
sa.Column("evidence", postgresql.JSONB(), nullable=True),
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
sa.CheckConstraint(
"field IN ('enforcement', 'salience', 'trigger')", name="ck_rule_field_judgments_field",
),
sa.CheckConstraint(
"state IN ('suggested', 'confirmed', 'rejected')", name="ck_rule_field_judgments_state",
),
sa.CheckConstraint("source IN ('pass', 'edit')", name="ck_rule_field_judgments_source"),
)
op.create_index("ix_rule_field_judgments_rule_id", "rule_field_judgments", ["rule_id"])
def downgrade() -> None:
op.drop_index("ix_rule_field_judgments_rule_id", table_name="rule_field_judgments")
op.drop_table("rule_field_judgments")
@@ -0,0 +1,26 @@
"""rule deliveries record the plugin version that asked for the line
Revision ID: 0133
Revises: 0132
Create Date: 2026-11-23
Only a plugin that sends its version reports every open, so the open-rate
readers count only deliveries that carry one. Existing rows stay null: they
were made while sessions ran a plugin that did not report opens of the rules
a hook had named, so their missing opens are not evidence.
"""
import sqlalchemy as sa
from alembic import op
revision = "0133"
down_revision = "0132"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("rule_deliveries", sa.Column("plugin", sa.Text(), nullable=True))
def downgrade() -> None:
op.drop_column("rule_deliveries", "plugin")
+43
View File
@@ -0,0 +1,43 @@
"""rule adherence: whether a rule in force at a moment of a session was followed
Revision ID: 0134
Revises: 0133
Create Date: 2026-11-23
One verdict per rule, per place it was delivered, per session — the unit
`rule_deliveries` records — from an `enforce` refusal, the session's own
`rule_outcome` / `rule_misfired`, or a transcript review.
"""
import sqlalchemy as sa
from alembic import op
revision = "0134"
down_revision = "0133"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"rule_adherence",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("rule_id", sa.BigInteger(), nullable=False),
sa.Column("at", sa.Text(), nullable=False),
sa.Column("verdict", sa.Text(), nullable=False),
sa.Column("source", sa.Text(), nullable=False),
sa.Column("evidence", sa.Text(), nullable=True),
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.UniqueConstraint("user_id", "session_id", "rule_id", "at",
name="uq_rule_adherence_session_rule_at"),
)
op.create_index("ix_rule_adherence_rule_at", "rule_adherence", ["rule_id", "at"])
op.create_index("ix_rule_adherence_judged_at", "rule_adherence", ["judged_at"])
def downgrade() -> None:
op.drop_index("ix_rule_adherence_judged_at", table_name="rule_adherence")
op.drop_index("ix_rule_adherence_rule_at", table_name="rule_adherence")
op.drop_table("rule_adherence")
@@ -0,0 +1,48 @@
"""a delivery of a rule the session had already opened counts as opened
Revision ID: 0135
Revises: 0134
Create Date: 2026-11-24
From now on a line for a rule the session has opened in the last six hours
is stamped opened as it is written (`rule_deliveries._read_already`). This
stamps the deliveries already recorded the same way, so the open rates, the
adherence readout and the weighing pass read one definition across old and
new rows: a rule read early in a session is not counted unread each time it
arrives again. The stamp is the delivery's own time. Only rows that carry a
plugin version are touched: every reader skips the others
(`rule_deliveries.REPORTS_OPENS`), and they are most of the table, so the
lookup runs on the few rows recorded since 0133 rather than on all of them.
Not reversible: the downgrade leaves the stamps, which the earlier code reads
as ordinary opens.
"""
from alembic import op
revision = "0135"
down_revision = "0134"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"""
UPDATE rule_deliveries d
SET opened_at = d.delivered_at
WHERE d.opened_at IS NULL
AND d.plugin IS NOT NULL
AND EXISTS (
SELECT 1 FROM rule_deliveries e
WHERE e.user_id = d.user_id
AND e.session_id = d.session_id
AND e.rule_id = d.rule_id
AND e.opened_at IS NOT NULL
AND e.opened_at <= d.delivered_at
AND e.opened_at >= d.delivered_at - INTERVAL '6 hours'
)
"""
)
def downgrade() -> None:
pass
@@ -0,0 +1,44 @@
"""record deliveries: each non-rule record put in front of a session, and whether it was opened
Revision ID: 0136
Revises: 0135
Create Date: 2026-11-24
The note-side twin of `rule_deliveries`. A row per record a hook pushed, a
search the session ran returned, or the session opened with nothing
delivering it first, so opens can be told apart by the way the record
arrived.
"""
import sqlalchemy as sa
from alembic import op
revision = "0136"
down_revision = "0135"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"record_deliveries",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("note_id", sa.BigInteger(), nullable=False),
sa.Column("kind", sa.Text(), nullable=False),
sa.Column("way", sa.Text(), nullable=False),
sa.Column("source", sa.Text(), nullable=False),
sa.Column("delivered_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("opened_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("plugin", sa.Text(), nullable=True),
)
op.create_index("ix_record_deliveries_session_note", "record_deliveries",
["user_id", "session_id", "note_id", "delivered_at"])
op.create_index("ix_record_deliveries_delivered_at", "record_deliveries", ["delivered_at"])
def downgrade() -> None:
op.drop_index("ix_record_deliveries_delivered_at", table_name="record_deliveries")
op.drop_index("ix_record_deliveries_session_note", table_name="record_deliveries")
op.drop_table("record_deliveries")
@@ -0,0 +1,58 @@
"""lesson_situations — when a lesson applies, as moments and triggers
Revision ID: 0137
Revises: 0136
Create Date: 2026-11-25
One row per (lesson, kind, value). `kind` is `moment` (a catalog moment
key), `trigger` (a typed predicate on the act, in rule_field_judgments'
trigger_value form) or `none` (no situation fits; value ''). `state` is
`suggested` while a pass's proposal waits, `confirmed` or `rejected` once a
person judges it; only confirmed rows deliver. CASCADE on the lesson: a
situation of a record that no longer exists says nothing. No backfill: no
lesson had a situation before this table.
"""
import sqlalchemy as sa
from alembic import op
revision = "0137"
down_revision = "0136"
branch_labels = None
depends_on = None
# One place each, so the CHECKs and the model's tuples cannot drift (a new
# value later means DROP + ADD CONSTRAINT in the same migration).
_KINDS = ("moment", "trigger", "none")
_STATES = ("suggested", "confirmed", "rejected")
_SOURCES = ("pass", "edit")
def _in(values) -> str:
return "(" + ", ".join(f"'{v}'" for v in values) + ")"
def upgrade() -> None:
op.create_table(
"lesson_situations",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("lesson_id", sa.BigInteger(), sa.ForeignKey("notes.id", ondelete="CASCADE"), nullable=False),
sa.Column("kind", sa.Text(), nullable=False),
sa.Column("value", sa.Text(), nullable=False, server_default=""),
sa.Column("state", sa.Text(), nullable=False, server_default="suggested"),
sa.Column("source", sa.Text(), nullable=False, server_default="pass"),
sa.Column("note", sa.Text(), nullable=True),
sa.Column("judged_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
sa.UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"),
)
op.create_check_constraint("ck_lesson_situations_kind", "lesson_situations", "kind IN " + _in(_KINDS))
op.create_check_constraint("ck_lesson_situations_state", "lesson_situations", "state IN " + _in(_STATES))
op.create_check_constraint("ck_lesson_situations_source", "lesson_situations", "source IN " + _in(_SOURCES))
op.create_index("ix_lesson_situations_lesson_id", "lesson_situations", ["lesson_id"])
def downgrade() -> None:
op.drop_index("ix_lesson_situations_lesson_id", table_name="lesson_situations")
for name in ("source", "state", "kind"):
op.drop_constraint(f"ck_lesson_situations_{name}", "lesson_situations", type_="check")
op.drop_table("lesson_situations")
+49
View File
@@ -0,0 +1,49 @@
"""gate stops: each time a Grimoire gate stood in front of a tool call
Revision ID: 0138
Revises: 0137
Create Date: 2026-11-27
A row per stop the plugin made: a moment rule set to enforce or hold, the
act checkpoint, or the project fence asking the operator. With whether the
session then opened the rule (`cleared_at`) and whether the stopped call ran
after all (`ran_at`), so how often each gate stops work, for which rule, and
whether it cleared the way it is meant to can be read.
"""
import sqlalchemy as sa
from alembic import op
revision = "0138"
down_revision = "0137"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"gate_stops",
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("gate", sa.Text(), nullable=False),
sa.Column("outcome", sa.Text(), nullable=False),
sa.Column("rule_id", sa.BigInteger(), nullable=True),
sa.Column("tool", sa.Text(), nullable=False),
sa.Column("at", sa.Text(), nullable=True),
sa.Column("target", sa.Text(), nullable=True),
sa.Column("call_id", sa.Text(), nullable=True),
sa.Column("stopped_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("cleared_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("ran_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("plugin", sa.Text(), nullable=True),
)
op.create_index("ix_gate_stops_session_rule", "gate_stops",
["user_id", "session_id", "rule_id", "stopped_at"])
op.create_index("ix_gate_stops_stopped_at", "gate_stops", ["stopped_at"])
def downgrade() -> None:
op.drop_index("ix_gate_stops_stopped_at", table_name="gate_stops")
op.drop_index("ix_gate_stops_session_rule", table_name="gate_stops")
op.drop_table("gate_stops")
@@ -0,0 +1,42 @@
"""embedding vectors stored inline, not in TOAST
Revision ID: 0139
Revises: 0138
Create Date: 2026-11-28
Every semantic search ranks its in-scope chunks exactly, one distance per
chunk (see embeddings._rank_scoped). pgvector's `vector` type defaults to
EXTERNAL storage, and a chunk row (a 384-dimension vector, about 1.5 KB, plus
the chunk's text) is over Postgres's 2 KB toast threshold, so the vector was
moved out of line and every distance paid a TOAST lookup: several buffer
reads per chunk, on every search.
`STORAGE MAIN` keeps the vector in the row. When a row is still too wide, the
chunk text (EXTENDED) is compressed or moved out instead, which costs nothing
on the ranking path: the text is read only for the rows a search returns.
A storage change applies to rows written after it, so the existing rows are
rewritten once. Casting through `real[]` produces a fresh value, which the
row is stored with under the new setting; assigning the column to itself
would keep the old out-of-line pointer.
"""
from alembic import op
revision = "0139"
down_revision = "0138"
branch_labels = None
depends_on = None
TABLES = ("note_embeddings", "rule_embeddings", "milestone_embeddings", "system_embeddings")
def upgrade() -> None:
for table in TABLES:
op.execute(f"ALTER TABLE {table} ALTER COLUMN embedding SET STORAGE MAIN")
op.execute(f"UPDATE {table} SET embedding = embedding::real[]::vector")
def downgrade() -> None:
# Rows already inline stay inline; new rows follow the type's default.
for table in TABLES:
op.execute(f"ALTER TABLE {table} ALTER COLUMN embedding SET STORAGE EXTERNAL")
+63
View File
@@ -0,0 +1,63 @@
"""code_shape_guards, code_shape_guard_reviews, and the removal verdicts
Revision ID: 0140
Revises: 0139
Create Date: 2026-12-01
What each test guards, read by the coverage sync from the repo archive, so
the ledger can show tests that guard the same thing from different files:
- code_shape_guards: test shape -> guarded shape, or -> a repo path.
Mechanical, rebuilt by every sync, not backed up.
- code_shape_guard_reviews: a group judged to be distinct behaviours.
- code_shapes.covered_by_id: the shape a `redundant` row is covered by.
- code_shapes.test_signals: a test's weak-test signals from the last sync.
The statuses `redundant` and `unused` need no schema change: status is a
plain text column.
"""
import sqlalchemy as sa
from alembic import op
revision = "0140"
down_revision = "0139"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column("code_shapes", sa.Column(
"covered_by_id", sa.Integer(),
sa.ForeignKey("code_shapes.id", ondelete="SET NULL"), nullable=True,
))
op.add_column("code_shapes", sa.Column(
"test_signals", sa.Text(), nullable=False, server_default="",
))
op.create_table(
"code_shape_guards",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("test_id", sa.Integer(), sa.ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=False),
sa.Column("guarded_id", sa.Integer(), sa.ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=True),
sa.Column("path", sa.Text(), nullable=True),
sa.Column("basis", sa.Text(), nullable=False, server_default="static"),
)
op.create_index("ix_code_shape_guards_test", "code_shape_guards", ["test_id"])
op.create_index("ix_code_shape_guards_guarded", "code_shape_guards", ["guarded_id"])
op.create_table(
"code_shape_guard_reviews",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("project_id", sa.Integer(), sa.ForeignKey("projects.id", ondelete="CASCADE"), nullable=False),
sa.Column("group_key", sa.Text(), nullable=False),
sa.Column("verdict", sa.Text(), nullable=False, server_default="distinct"),
sa.Column("reason", sa.Text(), nullable=False, server_default=""),
sa.Column("reviewed_by", sa.Text(), nullable=False),
sa.Column("reviewed_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")),
sa.UniqueConstraint("project_id", "group_key", name="uq_code_shape_guard_reviews_group"),
)
def downgrade() -> None:
op.drop_table("code_shape_guard_reviews")
op.drop_index("ix_code_shape_guards_guarded", table_name="code_shape_guards")
op.drop_index("ix_code_shape_guards_test", table_name="code_shape_guards")
op.drop_table("code_shape_guards")
op.drop_column("code_shapes", "test_signals")
op.drop_column("code_shapes", "covered_by_id")
+4
View File
@@ -114,6 +114,10 @@ endpoint at `/mcp`, not these REST routes.
| GET | `/api/lessons/rule-candidates` | Rules a draft lesson resembles, before it is saved |
| GET | `/api/lessons/taught-by/:record_id` | Lessons drawn from one record |
| PUT | `/api/lessons/:id/rules/:rule_id` | Confirm or reject a lesson → rule link |
| GET / POST | `/api/lessons/:id/situations` | A lesson's situations (moments and triggers it arrives at); add one |
| DELETE | `/api/lessons/situations/:situation_id` | Take a situation off its lesson |
| GET | `/api/lessons/situations/proposals` | Situations a pass proposed, waiting on a judgment, with counts |
| POST | `/api/lessons/situations/judge` | Confirm or reject proposed situations |
## Design systems
+80 -9
View File
@@ -1,7 +1,7 @@
import type { RecordUsage } from "@/types/usage";
import { apiGet, apiPost, apiPut, apiPatch, apiDelete } from "@/api/client";
import type { RuleKind } from "@/api/rulebooks";
import type { RuleKind, RuleTrigger } from "@/api/rulebooks";
/** Where a lesson stands on "which rule is this an instance of?"
* (`services/lesson_rules.py`: LINKED / NO_RULE / UNJUDGED). Three answers,
@@ -11,8 +11,8 @@ import type { RuleKind } from "@/api/rulebooks";
* another one fits. */
export type RuleJudgment = "linked" | "no_rule" | "unjudged";
/** A link's state (`models/lesson_rule_link.py` LINK_STATES). */
export type LinkState = "suggested" | "confirmed" | "rejected";
/** A judged link's state; the reads list only these two. */
export type LinkState = "confirmed" | "rejected";
/** One link from a lesson to a rule, in the reader's view: only rules the
* reader owns are listed (`rules_for_lessons`). */
@@ -20,14 +20,11 @@ export interface LessonRuleLink {
id: number;
title: string;
kind: RuleKind;
/** `suggested` carries nothing in retrieval until it is judged; only
* `confirmed` changes what surfaces; `rejected` is kept so the pair is
* never proposed again. */
/** `confirmed` changes what surfaces; `rejected` is kept so the reason
* stays readable. */
state: LinkState;
/** Why it was confirmed or rejected. */
note: string;
/** What a suggestion rests on — sent on suggested links only. */
evidence?: { situations: number; projects: number; co_surfaced: number };
}
/** A lesson: a transferable insight, retrievable by the SITUATION it applies
@@ -79,7 +76,7 @@ export interface Lesson {
updated_at: string | null;
systems?: { id: number; name: string }[];
usage?: RecordUsage;
/** The rules this lesson points at, confirmed first, then suggested, then
/** The rules this lesson was judged against, confirmed first, then
* rejected. Absent (with `rule_judgment`) when the links could not be read
* — which is "not attached", never "no rule". */
rules?: LessonRuleLink[];
@@ -232,3 +229,77 @@ export function lessonsTaughtBy(
`/api/lessons/taught-by/${recordId}`,
);
}
// ── when a lesson applies (services/lesson_situations.py) ────────────────
/** `moment` — a catalog moment; `trigger` — a typed predicate on the act. */
export type SituationKind = "moment" | "trigger";
/** One situation of a lesson: live (`confirmed`) or waiting on a person
* (`suggested`). `describes` is how it reads in the line a session sees. */
export interface LessonSituation {
id: number;
lesson_id: number;
kind: SituationKind;
value: string;
state: "suggested" | "confirmed";
source: "pass" | "edit";
note: string;
describes: string;
trigger?: RuleTrigger;
}
export interface LessonSituationProposals {
lessons: {
lesson_id: number;
title: string;
when_to_apply: string;
proposals: LessonSituation[];
}[];
total: number;
/** Readable lessons by where they stand: arriving at a situation, read
* and found to have none, waiting on a judgment, or not yet read. */
counts: { situated: number; none_fits: number; waiting: number; unsituated: number };
}
export interface LessonSituationsPayload {
situations: LessonSituation[];
catalog: { name: string; means: string }[];
trigger_kinds: RuleTrigger["kind"][];
}
export interface SituationJudgment {
id: number;
verdict: "confirm" | "reject";
note?: string;
}
export function getLessonSituationProposals(): Promise<LessonSituationProposals> {
return apiGet("/api/lessons/situations/proposals");
}
/** A confirm makes the lesson arrive at that situation, once per session; a
* reject stops the value being proposed again. */
export function judgeLessonSituations(
judgments: SituationJudgment[],
): Promise<{ judged: LessonSituation[] }> {
return apiPost("/api/lessons/situations/judge", { judgments });
}
export function getLessonSituations(lessonId: number): Promise<LessonSituationsPayload> {
return apiGet(`/api/lessons/${lessonId}/situations`);
}
/** Make one situation live: a moment, or a trigger. */
export function addLessonSituation(
lessonId: number,
body: { moment: string } | { trigger: RuleTrigger },
): Promise<LessonSituation> {
return apiPost(`/api/lessons/${lessonId}/situations`, body);
}
/** Take a situation off its lesson; kept as rejected so it is not proposed
* again. `apiDelete` discards the body. */
export function removeLessonSituation(situationId: number): Promise<void> {
return apiDelete(`/api/lessons/situations/${situationId}`);
}
+230 -1
View File
@@ -1,4 +1,5 @@
import { apiGet, apiPost, apiDelete } from "@/api/client";
import { apiGet, apiPost, apiPut, apiDelete } from "@/api/client";
import type { RuleEnforcement, RuleSalience, RuleTrigger } from "@/api/rulebooks";
/**
* The moments of work rules mount on, and the actions that
@@ -180,3 +181,231 @@ export function getProposals(ruleId?: number): Promise<ProposalsPayload> {
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
return apiPost("/api/retrieval/moments/proposals/judge", { judgments });
}
/**
* Suggestions for how strongly a rule arrives (`enforcement`, `salience`) and
* which typed triggers reach it, from a pass that read the rule beside its
* delivery history. Nothing changes until a person confirms one.
* `GET /api/retrieval/weights/proposals`, the payload the
* `rule_weight_proposals` MCP tool returns.
*/
export type WeightField = "enforcement" | "salience" | "trigger";
/** What happened when the rule reached a session, over `days`. */
export interface WeightEvidence {
days?: number;
delivered?: number;
opened?: number;
places?: { at: string; delivered: number; opened: number }[];
pulled?: number;
applied?: number;
departed?: number;
misfire_days?: number;
}
export interface WeightProposal {
field: WeightField;
/** The enforcement or salience name; for a trigger, its stored form. */
value: string;
trigger?: RuleTrigger;
why: string;
source: "pass" | "edit";
evidence: WeightEvidence;
created_at: string | null;
}
export interface RuleWeightProposals {
id: number;
title: string;
kind: string;
statement: string;
when_to_apply: string;
home: "global" | "project";
enforcement: RuleEnforcement;
salience: RuleSalience;
mounted: string[];
triggers: RuleTrigger[];
proposals: WeightProposal[];
}
export interface WeightProposalsPayload {
rules: RuleWeightProposals[];
total: number;
}
export interface WeightJudgment {
rule_id: number;
field: WeightField;
value: string | RuleTrigger;
verdict: Verdict;
note?: string;
}
export interface WeightJudgeResult {
judged: { rule_id: number; field: WeightField; value: string; state: string }[];
refused: { rule_id: number; field?: string; error: string }[];
}
/** One rule at one place, or a sum of them: how many sessions it was in
* force in, opened in, and what each was judged. */
export interface AdherenceCounts {
in_force: number;
opened: number;
followed: number;
/** Read and deliberately not followed, with a stated reason. */
departed: number;
broken: number;
not_applicable: number;
unjudged: number;
}
export interface RuleAdherenceRow extends AdherenceCounts {
rule_id: number;
/** Null for a rule deleted since. */
title: string | null;
by_moment: (AdherenceCounts & { at: string })[];
}
export interface MomentAdherenceRow extends AdherenceCounts {
/** A moment (`work.deliver`) or an arm (`pre_tool_rule`). */
at: string;
by_rule: (AdherenceCounts & { rule_id: number; title: string | null })[];
}
export interface AdherencePayload {
days: number;
totals: AdherenceCounts;
by_rule: RuleAdherenceRow[];
by_moment: MomentAdherenceRow[];
}
/** One door of the kind×moment table: where a record search fires, and
* the kinds of record it may consider. */
export interface RecordKindsDoor {
/** A catalog moment, or `message` for the operator's message. */
door: string;
label: string;
fires: string;
kinds: string[];
default: string[];
/** The user changed this door; otherwise it follows the shipped default. */
changed: boolean;
/** Its lines are recorded per session; a door that answers in a tool
* reply is not, so it has no counts. */
measured: boolean;
/** Lines this door pushed of each kind, and how many were opened. */
evidence: Record<string, WayCounts>;
}
/** Which kinds a door may offer from the user's other projects. */
export interface RecordKindsReach {
kinds: string[];
default: string[];
changed: boolean;
}
export interface RecordKindsTable {
days: number;
evidence_failed: boolean;
reach: RecordKindsReach;
kinds: { kind: string; label: string }[];
doors: RecordKindsDoor[];
}
export function getRecordKinds(days = 30): Promise<RecordKindsTable> {
return apiGet(`/api/retrieval/record-kinds?days=${days}`);
}
/** `kinds: null` puts the door back to its shipped default. */
export function setRecordKinds(door: string, kinds: string[] | null): Promise<RecordKindsTable> {
return apiPut("/api/retrieval/record-kinds", { door, kinds });
}
/** `kinds: null` puts the reach back to its shipped default. */
export function setRecordKindsReach(kinds: string[] | null): Promise<RecordKindsTable> {
return apiPut("/api/retrieval/record-kinds/reach", { kinds });
}
/** How a record arrived in front of a session. */
export type RecordWay = "pushed" | "pointed" | "asked" | "direct";
export interface WayCounts {
delivered: number;
opened: number;
}
export interface RecordReachKind {
/** `snippet`, `note`, `lesson`, `process`, or `task:<kind>`. */
kind: string;
ways: Record<RecordWay, WayCounts>;
sources: { way: RecordWay; source: string; delivered: number; opened: number }[];
}
export interface RecordReachPayload {
days: number;
sessions: number;
totals: Record<RecordWay, WayCounts>;
by_kind: RecordReachKind[];
}
/** How non-rule records reached sessions: pushed, asked for, or opened directly. */
export function getRecordReach(days = 30): Promise<RecordReachPayload> {
return apiGet(`/api/retrieval/record-reach?days=${days}`);
}
/** The gates that can stop a tool call. */
export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply";
export interface GateCounts {
/** Calls denied, or for the fence, put to the operator. */
stops: number;
/** Calls a hold would have stopped, let through because the session's
* stop budget was spent. */
let_through: number;
/** Stops the session cleared by opening the rule. */
cleared: number;
/** Stops whose rule the session then reported as a misfire. */
misfired: number;
/** Stopped calls that ran after all; for the fence, the operator's yes. */
ran: number;
}
export interface GateRuleRow extends GateCounts {
rule_id: number;
gate: GateName;
/** The moment or arm the rule was reached at. */
at: string | null;
title: string | null;
sessions: number;
last_stopped_at: string | null;
}
export interface GateStopsPayload {
days: number;
by_gate: Record<GateName, GateCounts & { sessions: number }>;
by_rule: GateRuleRow[];
fence: { tool: string; target: string | null; asks: number; ran: number }[];
/** The first stop ever recorded; null when none has been. */
complete_from: string | null;
covers_window: boolean | null;
}
/** How often each gate stood in front of a tool call, and what followed. */
export function getGateStops(days = 30): Promise<GateStopsPayload> {
return apiGet(`/api/retrieval/gate-stops?days=${days}`);
}
/** Whether the rules in force at each moment were followed there. */
export function getAdherence(days = 30): Promise<AdherencePayload> {
return apiGet(`/api/retrieval/adherence?days=${days}`);
}
export function getWeightProposals(ruleId?: number): Promise<WeightProposalsPayload> {
return apiGet(`/api/retrieval/weights/proposals${ruleId ? `?rule_id=${ruleId}` : ""}`);
}
/** A confirm sets the field on the rule (a trigger is added beside its
* others); a reject stops that value being proposed again. */
export function judgeWeightProposals(judgments: WeightJudgment[]): Promise<WeightJudgeResult> {
return apiPost("/api/retrieval/weights/proposals/judge", { judgments });
}
+36 -3
View File
@@ -54,6 +54,27 @@ export interface RulebookTopic {
*/
export type RuleKind = "rule" | "preference";
/**
* What a rule does when it arrives, declared by its author. `inform` puts a
* line beside the work; `hold` makes the reply or command it governs wait for
* one read; `enforce` refuses an act its moment or trigger reaches. A
* preference is always `inform`.
*/
export type RuleEnforcement = "enforce" | "hold" | "inform";
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
export type RuleSalience = "high" | "normal" | "low";
/** What a trigger is matched against on the act: the tool called, a path it
* touches, the head of a command it runs, or a word in what it writes. */
export type RuleTriggerKind = "tool" | "path" | "command" | "keyword";
/** A typed predicate on the act, checked exactly. With no `moment` it
* delivers the rule on any matching act; with one, it makes the rule's
* mount on that moment conditional on the act matching. */
export interface RuleTrigger {
kind: RuleTriggerKind;
pattern: string;
moment?: string;
}
/** A new record opened from somewhere that already knows what it is for —
* "Adjust this" on a reply shape opens a preference mounted on that shape's
* moment. The editor applies it once, when creating. */
@@ -70,6 +91,8 @@ export interface Rule {
title: string;
statement: string;
kind: RuleKind;
enforcement: RuleEnforcement;
salience: RuleSalience;
/** WHEN this rule fires — the trigger, not the instruction. */
when_to_apply: string;
why: string;
@@ -94,10 +117,12 @@ 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
* judgment. Readable lessons only; omitted when there are none. */
/** The lessons judged against this rule — confirmed instances of it
* first, then those judged not to be. Readable lessons only; omitted when
* there are none. */
lessons?: { id: number; title: string; state: LinkState; note: string }[];
}
@@ -113,6 +138,10 @@ export interface RuleHeader {
topic_id: number | null;
/** Unconditional on the wire (services.rulebooks.rule_brief). */
kind: RuleKind;
/** Unconditional on the wire, like `kind`. */
enforcement: RuleEnforcement;
/** Present only when raised or lowered from `normal`. */
salience?: RuleSalience;
/** A date (YYYY-MM-DD), not a timestamp. */
updated_at: string | null;
when_to_apply?: string;
@@ -217,6 +246,8 @@ export interface RuleWrite {
/** Writable from the editor: a preference is not a lesser rule, it is a
* different force, and the person writing it is the one who knows which. */
kind: RuleKind;
enforcement: RuleEnforcement;
salience: RuleSalience;
when_to_apply: string;
why: string;
how_to_apply: string;
@@ -224,6 +255,8 @@ export interface RuleWrite {
system_ids: number[];
/** Replaces the set; [] unmounts the rule from every moment. */
moments: string[];
/** Replaces the set; [] clears every trigger. */
triggers: RuleTrigger[];
arose_from_id: number | null;
verify_with: string;
expires_when: string;
+6
View File
@@ -21,6 +21,12 @@ export interface System {
* everything under it. Empty means the area has not named its files.
*/
path_patterns: string[];
/**
* How many rulings the description carries. With no `path_patterns`,
* none of them is delivered: rulings reach a session when a command or
* edit touches the area's files. Present on the list read only.
*/
ruling_count?: number;
open_issue_count: number;
/**
* How often this area's rulings were shown to a session because its files
+39
View File
@@ -147,6 +147,45 @@
text-decoration: none;
}
/* A record reference — `#4286`, `milestone 639`, `rule 34`. Reads as a link in
running text rather than a chip: a work log cites a dozen of them, and a row
of pills would drown the sentence they sit in. */
.record-ref {
color: var(--fs-wikilink);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--fs-wikilink) 40%, transparent);
text-underline-offset: 0.15em;
font-variant-numeric: tabular-nums;
border-radius: var(--fs-radius-sm);
cursor: pointer;
}
.record-ref:hover {
text-decoration-color: currentColor;
}
/* Drawn with its title: the title reads as the link, the number after it is
the citation, quieter and never split across lines. */
.record-ref__id {
color: var(--fs-text-secondary);
font-size: 0.85em;
white-space: nowrap;
}
.record-ref:focus-visible {
outline: none;
box-shadow: var(--fs-focus-ring);
}
/* One the reader cannot open: missing, trashed or not shared. Still legible —
the number is part of the sentence — but plainly not a way through. */
.record-ref--missing {
color: var(--fs-text-tertiary-fg);
text-decoration-style: dashed;
text-decoration-color: var(--fs-text-tertiary);
cursor: default;
}
/* Task list */
.prose ul[data-type="taskList"] {
list-style: none;
+30
View File
@@ -0,0 +1,30 @@
/* A proposal about a rule waiting on a person — the panels under
Settings › Moments that list mount proposals and weight suggestions.
Loaded scoped by each, so these class names stay local to the panels. */
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.proposals-bar { display: flex; justify-content: flex-end; }
.proposal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-rule {
padding: var(--fs-space-3);
background: var(--fs-surface-page);
border: 1px dashed var(--fs-border-color);
border-radius: var(--fs-radius-md);
}
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.proposal-reasons {
flex-basis: 100%;
margin: 0;
padding-left: var(--fs-space-4);
font-size: var(--fs-size-tiny);
color: var(--fs-text-tertiary);
}
+124
View File
@@ -0,0 +1,124 @@
<script setup lang="ts">
import { computed } from "vue";
import type { GateCounts, GateName, GateStopsPayload } from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat";
/**
* Every time Grimoire stood in front of the work instead of commenting
* beside it: a rule set to enforce or hold, the checkpoint on a command, the
* project fence asking the operator, or a rule holding the finished reply. Per gate and per rule, how often it
* stopped work and what followed — the rule opened (the stop cleared the way
* it is meant to), the rule reported as a misfire (a stop at the wrong
* moment), or a hold let through because the session's stop budget was
* spent.
*/
const props = defineProps<{
data: GateStopsPayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const GATES: [GateName, string][] = [
["enforce", "Refused (enforce)"],
["hold", "Held for a read (hold)"],
["checkpoint", "Command checkpoint"],
["fence", "Project fence"],
["reply", "Reply held for a read"],
];
const any = computed(() =>
!!props.data && GATES.some(([g]) => (props.data!.by_gate[g]?.stops ?? 0) + (props.data!.by_gate[g]?.let_through ?? 0) > 0),
);
function gateText(gate: GateName, c: GateCounts): string[] {
if (gate === "fence") return [`asked ${c.stops}`, `approved ${c.ran}`];
const parts = [`stopped ${c.stops}`, `cleared by a read ${c.cleared}`, `misfired ${c.misfired}`];
// An enforced refusal has no cap, and the reply's cap is applied by the
// server before anything holds, so neither can let a call through.
if (gate === "hold" || gate === "checkpoint") parts.push(`let through by the cap ${c.let_through}`);
return parts;
}
</script>
<template>
<section class="gates" aria-labelledby="gates-title">
<h3 id="gates-title" class="sub-title">When a rule stopped the work</h3>
<p v-if="failed" class="error-msg">
Gate stops could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading gate stops…</p>
<p v-else-if="!any" class="empty-msg">
No gate stopped a tool call in the last {{ data.days }} days.
<template v-if="data.complete_from === null">
None has ever been recorded: a session reports its stops once its plugin is updated.
</template>
</p>
<template v-else>
<p class="field-hint">
Over the last {{ data.days }} days. “Cleared by a read” means the session opened the rule
after the stop; “misfired” means it then reported the rule as not applying there; “let
through by the cap” counts calls a hold would have stopped once the session’s budget of
stops was spent.
<template v-if="data.covers_window === false">
Recording began {{ fmtDate(data.complete_from!) }}, so earlier days are missing, not quiet.
</template>
</p>
<ul class="gate-list">
<li v-for="[gate, label] in GATES" :key="gate" class="gate-row">
<span class="gate-title">{{ label }}</span>
<span class="gate-counts" :class="{ 'way-none': !data.by_gate[gate]?.stops && !data.by_gate[gate]?.let_through }">
<span v-for="t in gateText(gate, data.by_gate[gate])" :key="t">{{ t }}</span>
</span>
</li>
</ul>
<details v-if="data.by_rule.length" class="gate-detail">
<summary>By rule</summary>
<ul class="gate-list">
<li v-for="r in data.by_rule" :key="`${r.rule_id}:${r.gate}:${r.at}`" class="gate-row">
<span class="gate-title">
Rule {{ r.rule_id }}<template v-if="r.title"> “{{ r.title }}”</template>
</span>
<code class="moment-name">{{ r.gate }}<template v-if="r.at"> · {{ r.at }}</template></code>
<span class="gate-counts">
<span v-for="t in gateText(r.gate, r)" :key="t">{{ t }}</span>
<span>{{ r.sessions }} {{ r.sessions === 1 ? "session" : "sessions" }}</span>
<span v-if="r.last_stopped_at" class="stat-when">last {{ fmtDate(r.last_stopped_at) }}</span>
</span>
</li>
</ul>
</details>
<details v-if="data.fence.length" class="gate-detail">
<summary>Fence asks by tool</summary>
<ul class="gate-list">
<li v-for="f in data.fence" :key="`${f.tool}:${f.target}`" class="gate-row">
<code class="moment-name">{{ f.tool }}</code>
<span v-if="f.target" class="gate-title">into project {{ f.target }}</span>
<span class="gate-counts">
<span>asked {{ f.asks }}</span>
<span>approved {{ f.ran }}</span>
</span>
</li>
</ul>
</details>
</template>
</section>
</template>
<style scoped>
.gates { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.gate-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.gate-detail .gate-list { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.gate-detail summary { cursor: pointer; font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); }
.gate-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.gate-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
.gate-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2); margin-left: auto; justify-content: flex-end;
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary); font-variant-numeric: tabular-nums;
}
/* A gate that stopped nothing is a gap, not a zero to read. */
.way-none { color: var(--fs-text-tertiary); }
</style>
<style src="@/assets/moments-shared.css" />
@@ -0,0 +1,160 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import {
getLessonSituationProposals, judgeLessonSituations,
type LessonSituation, type LessonSituationProposals,
} from "@/api/lessons";
import { apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import ConfirmDialog from "@/components/ConfirmDialog.vue";
/**
* When each lesson applies, waiting on a person. A pass read each lesson
* beside the rules it is an instance of and proposed the moments of work, or
* the triggers on an act (a path, a command, a tool, a word), at which it
* should arrive. A lesson with a confirmed situation arrives there, once per
* session, instead of whenever an edit's words resemble it. Nothing changes
* until "Apply" is pressed; "Not this" keeps the value from being proposed
* again. The same judgment `judge_lesson_situations` makes in a session.
*/
const toast = useToastStore();
const data = ref<LessonSituationProposals | null>(null);
const failed = ref(false);
const busy = ref<number | "all" | null>(null);
const confirmingAll = ref(false);
const lessons = computed(() => data.value?.lessons ?? []);
const counts = computed(() => data.value?.counts);
const allIds = computed(() => lessons.value.flatMap((l) => l.proposals.map((p) => p.id)));
const allSummary = computed(() => {
const n = allIds.value.length;
const across = `${lessons.value.length} lesson${lessons.value.length === 1 ? "" : "s"}`;
return `${n} situation${n === 1 ? "" : "s"} across ${across} take effect at once: each lesson `
+ "will arrive when its situation is reached, once per session.";
});
async function load() {
try {
data.value = await getLessonSituationProposals();
failed.value = false;
} catch {
failed.value = true;
}
}
async function decide(p: LessonSituation, verdict: "confirm" | "reject") {
busy.value = p.id;
try {
await judgeLessonSituations([{
id: p.id, verdict,
note: verdict === "confirm" ? "Applied in Settings." : "Declined in Settings.",
}]);
await load();
} catch (e) {
toast.show(apiErrorMessage(e, "Could not record that"), "error");
} finally {
busy.value = null;
}
}
async function applyAll() {
confirmingAll.value = false;
busy.value = "all";
try {
const out = await judgeLessonSituations(allIds.value.map((id) => ({
id, verdict: "confirm" as const, note: "Applied with Apply all in Settings.",
})));
toast.show(`${out.judged.length} applied.`, "success");
await load();
} catch (e) {
toast.show(apiErrorMessage(e, "Could not apply the suggestions"), "error");
} finally {
busy.value = null;
}
}
onMounted(load);
</script>
<template>
<section class="proposals" aria-labelledby="lesson-situations-title">
<h3 id="lesson-situations-title" class="sub-title">When lessons arrive</h3>
<p v-if="failed" class="error-msg">
The lesson situations could not be loaded.
<button type="button" class="btn-text" @click="load">Try again</button>
</p>
<template v-else-if="data">
<p class="field-hint">
A lesson with a situation arrives when the work reaches it — a moment like delivering or
finishing, or an act on a path, command or tool — once per session. A lesson without one
is found only when a message resembles it.
<template v-if="counts">
{{ counts.situated }} arrive by situation, {{ counts.none_fits }} were read and fit none,
{{ counts.waiting }} wait on you, and {{ counts.unsituated }} have not been read.
</template>
</p>
<p v-if="!lessons.length" class="field-hint empty-note">
Nothing is waiting. A session proposes situations with <code>lessons_to_situate</code> and
<code>propose_lesson_situations</code>; they appear here to apply or decline.
</p>
<template v-else>
<div class="proposals-bar">
<button
type="button" class="btn-primary btn-sm"
:disabled="busy !== null"
@click="confirmingAll = true"
>Apply all {{ allIds.length }}</button>
</div>
<ul class="proposal-list">
<li v-for="lesson in lessons" :key="lesson.lesson_id" class="proposal-rule">
<div class="rule-head">
<router-link :to="`/lessons/${lesson.lesson_id}`" class="rule-title">
#{{ lesson.lesson_id }} {{ lesson.title }}
</router-link>
</div>
<p v-if="lesson.when_to_apply" class="rule-statement">
When to apply: {{ lesson.when_to_apply }}
</p>
<ul class="proposal-items">
<li v-for="p in lesson.proposals" :key="p.id" class="proposal-item">
<code class="moment-name">{{ p.describes }}</code>
<span class="proposal-why">{{ p.note }}</span>
<span class="proposal-actions">
<button
type="button" class="btn-primary btn-sm"
:disabled="busy !== null"
@click="decide(p, 'confirm')"
>Apply</button>
<button
type="button" class="btn-text"
:disabled="busy !== null"
@click="decide(p, 'reject')"
>Not this</button>
</span>
</li>
</ul>
</li>
</ul>
</template>
</template>
<ConfirmDialog
v-if="confirmingAll"
title="Apply every situation?"
:message="allSummary"
confirm-label="Apply all"
:danger="false"
@confirm="applyAll"
@cancel="confirmingAll = false"
/>
</section>
</template>
<style scoped src="@/assets/rule-proposals.css" />
<style src="@/assets/moments-shared.css" />
<style scoped>
.empty-note { margin: 0; }
</style>
@@ -0,0 +1,230 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import {
addLessonSituation, getLessonSituations, judgeLessonSituations, removeLessonSituation,
type LessonSituation, type LessonSituationsPayload,
} from "@/api/lessons";
import type { RuleTrigger } from "@/api/rulebooks";
import { apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
/**
* When a lesson arrives. A situation is a moment of work (delivering,
* finishing, …) or a trigger on an act (a path, a command, a tool, a word);
* the lesson is shown to a session when its work reaches one, once per
* session. Proposals from a pass wait here and in Settings › Moments until
* applied or declined. A writer can add a situation directly or take one off;
* one taken off is not proposed again.
*/
const props = defineProps<{ lessonId: number; canWrite: boolean }>();
const toast = useToastStore();
const data = ref<LessonSituationsPayload | null>(null);
const failed = ref(false);
const busy = ref(false);
// The add form: what kind of situation, then a moment or a pattern.
const what = ref<"moment" | RuleTrigger["kind"]>("moment");
const moment = ref("");
const pattern = ref("");
// Placeholders are generic shapes, never anyone's own paths or commands.
const PLACEHOLDER: Record<string, string> = {
path: "e.g. migrations/**/*.py",
command: "e.g. git push",
tool: "e.g. edit",
keyword: "e.g. release",
};
const live = computed(() => (data.value?.situations ?? []).filter((s) => s.state === "confirmed"));
const waiting = computed(() => (data.value?.situations ?? []).filter((s) => s.state === "suggested"));
const canAdd = computed(() =>
what.value === "moment" ? !!moment.value : pattern.value.trim().length > 0,
);
async function load() {
try {
data.value = await getLessonSituations(props.lessonId);
failed.value = false;
} catch {
failed.value = true;
}
}
async function run(action: () => Promise<unknown>, done: string, failure: string) {
busy.value = true;
try {
await action();
toast.show(done, "success");
await load();
} catch (e) {
toast.show(apiErrorMessage(e, failure), "error");
} finally {
busy.value = false;
}
}
function add() {
const body = what.value === "moment"
? { moment: moment.value }
: { trigger: { kind: what.value, pattern: pattern.value.trim() } };
return run(async () => {
await addLessonSituation(props.lessonId, body);
moment.value = "";
pattern.value = "";
}, "The lesson now arrives there", "Could not add that situation");
}
function remove(s: LessonSituation) {
return run(() => removeLessonSituation(s.id), "Taken off", "Could not take that off");
}
function judge(s: LessonSituation, verdict: "confirm" | "reject") {
return run(
() => judgeLessonSituations([{
id: s.id, verdict, note: verdict === "confirm" ? "Applied on the lesson." : "Declined on the lesson.",
}]),
verdict === "confirm" ? "Applied" : "Declined",
"Could not record that",
);
}
onMounted(load);
watch(() => props.lessonId, load);
</script>
<template>
<section class="ls-panel" aria-labelledby="ls-title">
<h2 id="ls-title" class="ls-label">When it arrives</h2>
<p v-if="failed" class="ls-muted">
The situations could not be loaded.
<button type="button" class="ls-text-btn" @click="load">Try again</button>
</p>
<template v-else-if="data">
<ul v-if="live.length" class="ls-list">
<li v-for="s in live" :key="s.id" class="ls-item">
<code class="ls-value">{{ s.describes }}</code>
<button
v-if="canWrite" type="button" class="ls-text-btn"
:disabled="busy" :aria-label="`Take off ${s.describes}`"
@click="remove(s)"
>Take off</button>
</li>
</ul>
<p v-else class="ls-muted">
No situation yet — the lesson is found only when a message resembles it.
</p>
<template v-if="waiting.length">
<h3 class="ls-sub">Proposed</h3>
<ul class="ls-list">
<li v-for="s in waiting" :key="s.id" class="ls-item">
<code class="ls-value">{{ s.describes }}</code>
<span v-if="s.note" class="ls-note">{{ s.note }}</span>
<span v-if="canWrite" class="ls-actions">
<button type="button" class="ls-btn" :disabled="busy" @click="judge(s, 'confirm')">Apply</button>
<button type="button" class="ls-text-btn" :disabled="busy" @click="judge(s, 'reject')">Not this</button>
</span>
</li>
</ul>
</template>
<form v-if="canWrite" class="ls-add" @submit.prevent="add">
<label class="ls-field">
<span class="ls-field-label">Arrive at</span>
<select v-model="what" class="ls-input" :disabled="busy">
<option value="moment">a moment of work</option>
<option v-for="k in data.trigger_kinds" :key="k" :value="k">a {{ k }}</option>
</select>
</label>
<label v-if="what === 'moment'" class="ls-field ls-grow">
<span class="ls-field-label">Moment</span>
<select v-model="moment" class="ls-input" :disabled="busy">
<option value="" disabled>Choose a moment</option>
<option v-for="m in data.catalog" :key="m.name" :value="m.name">
{{ m.name }} — {{ m.means }}
</option>
</select>
</label>
<label v-else class="ls-field ls-grow">
<span class="ls-field-label">Pattern</span>
<input
v-model="pattern" class="ls-input" type="text" maxlength="200"
:placeholder="PLACEHOLDER[what]" :disabled="busy"
>
</label>
<button type="submit" class="ls-btn" :disabled="busy || !canAdd">Add</button>
</form>
</template>
</section>
</template>
<style scoped>
.ls-panel {
margin-top: 1.75rem;
padding-top: 1rem;
border-top: 1px solid var(--fs-border-color);
}
.ls-label {
margin: 0 0 0.5rem;
font-size: 0.72rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--fs-text-tertiary);
}
.ls-sub {
margin: var(--fs-space-3) 0 var(--fs-space-1);
font-size: var(--fs-size-label);
font-weight: var(--fs-weight-medium);
color: var(--fs-text-tertiary);
}
.ls-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.ls-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: 0.9rem; }
.ls-value { font-size: var(--fs-size-label); color: var(--fs-text-primary); }
.ls-note { flex: 1 1 14rem; color: var(--fs-text-secondary); font-size: var(--fs-size-label); }
.ls-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
.ls-muted { margin: 0; color: var(--fs-text-secondary); font-size: 0.88rem; }
.ls-add {
display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--fs-space-2);
margin-top: var(--fs-space-3);
}
.ls-field { display: flex; flex-direction: column; gap: var(--fs-space-1); }
.ls-grow { flex: 1 1 14rem; }
.ls-field-label { font-size: var(--fs-size-label); color: var(--fs-text-tertiary); }
.ls-input {
padding: 0.4rem 0.6rem;
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-sm);
background: var(--fs-surface-raised);
color: var(--fs-text-primary);
font: inherit;
font-size: 0.88rem;
}
.ls-btn {
padding: 0.4rem 0.9rem;
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-sm);
background: transparent;
color: var(--fs-text-primary);
font: inherit;
font-size: 0.88rem;
cursor: pointer;
}
.ls-text-btn {
padding: 0;
border: none;
background: none;
color: var(--fs-text-secondary);
font: inherit;
font-size: var(--fs-size-label);
text-decoration: underline;
cursor: pointer;
}
.ls-input:focus-visible,
.ls-btn:focus-visible,
.ls-text-btn:focus-visible { outline: none; box-shadow: var(--fs-focus-ring); }
.ls-btn:disabled,
.ls-text-btn:disabled,
.ls-input:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
</style>
+1 -28
View File
@@ -158,33 +158,6 @@ onMounted(load);
</section>
</template>
<style scoped>
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.proposal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-rule {
padding: var(--fs-space-3);
background: var(--fs-surface-page);
border: 1px dashed var(--fs-border-color);
border-radius: var(--fs-radius-md);
}
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.proposal-reasons {
flex-basis: 100%;
margin: 0;
padding-left: var(--fs-space-4);
font-size: var(--fs-size-tiny);
color: var(--fs-text-tertiary);
}
</style>
<style scoped src="@/assets/rule-proposals.css" />
<style src="@/assets/moments-shared.css" />
+20 -5
View File
@@ -1,12 +1,26 @@
<script setup lang="ts">
import type { MomentRuleUsage } from "@/api/moments";
import type { AdherenceCounts, MomentRuleUsage } from "@/api/moments";
/**
* Which rules a moment delivered, and whether an agent went on to read each.
* The moment's own counts cannot say this once two rules are mounted there.
* Closed by default: the counts in the row above are what most visits want.
* Which rules a moment delivered, whether an agent went on to read each, and
* — where a verdict exists — whether it was followed there. The moment's own
* counts cannot say this once two rules are mounted there. Closed by default:
* the counts in the row above are what most visits want.
*/
defineProps<{ rules: MomentRuleUsage[] }>();
withDefaults(defineProps<{
rules: MomentRuleUsage[];
/** This moment's adherence per rule id, from the adherence readout. */
adherence?: Record<number, AdherenceCounts>;
}>(), { adherence: () => ({}) });
function verdicts(c: AdherenceCounts | undefined): string {
if (!c) return "";
const parts = [`followed ${c.followed} of ${c.in_force}`];
if (c.broken) parts.push(`broken ${c.broken}`);
if (c.departed) parts.push(`departed ${c.departed}`);
if (c.not_applicable) parts.push(`not applicable ${c.not_applicable}`);
return parts.join(" · ");
}
</script>
<template>
@@ -19,6 +33,7 @@ defineProps<{ rules: MomentRuleUsage[] }>();
<span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'">
{{ r.opened ? "opened" : "not opened" }}
</span>
<span v-if="adherence[r.rule_id]" class="delivered-count">{{ verdicts(adherence[r.rule_id]) }}</span>
</li>
</ul>
</details>
+81 -4
View File
@@ -3,7 +3,16 @@ import { computed, onMounted, ref } from "vue";
import { useMomentsStore } from "@/stores/moments";
import MomentProposals from "@/components/MomentProposals.vue";
import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
import type { MomentAction, MomentUsage } from "@/api/moments";
import WeightProposals from "@/components/WeightProposals.vue";
import LessonSituationProposals from "@/components/LessonSituationProposals.vue";
import RecordKinds from "@/components/RecordKinds.vue";
import RecordReach from "@/components/RecordReach.vue";
import GateStops from "@/components/GateStops.vue";
import RuleAdherence from "@/components/RuleAdherence.vue";
import { getAdherence, getGateStops, getRecordReach } from "@/api/moments";
import type {
AdherencePayload, GateStopsPayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload,
} from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat";
/**
@@ -31,6 +40,55 @@ function usage(moment: string): MomentUsage | null {
return data.value?.usage.by_moment[moment] ?? null;
}
// Adherence is read on its own, so a failure there leaves the catalog and the
// delivery counts standing and says so in its own panel.
const adherence = ref<AdherencePayload | null>(null);
const adherenceFailed = ref(false);
async function loadAdherence() {
try {
adherence.value = await getAdherence(days.value);
adherenceFailed.value = false;
} catch {
adherenceFailed.value = true;
}
}
// How records other than rules reach sessions, read on its own for the same
// reason as adherence.
const reach = ref<RecordReachPayload | null>(null);
const reachFailed = ref(false);
async function loadReach() {
try {
reach.value = await getRecordReach(days.value);
reachFailed.value = false;
} catch {
reachFailed.value = true;
}
}
// When a gate stopped a tool call, read on its own for the same reason.
const gates = ref<GateStopsPayload | null>(null);
const gatesFailed = ref(false);
async function loadGates() {
try {
gates.value = await getGateStops(days.value);
gatesFailed.value = false;
} catch {
gatesFailed.value = true;
}
}
function followed(moment: string): MomentAdherenceRow | null {
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
}
function verdictsByRule(moment: string): Record<number, MomentAdherenceRow["by_rule"][number]> {
return Object.fromEntries((followed(moment)?.by_rule ?? []).map((r) => [r.rule_id, r]));
}
// A named procedure is its own moment (`skill.<name>`), so it appears here
// only once something is mounted on it or has been delivered at it — the
// catalog cannot list procedures it has never heard of.
@@ -101,7 +159,10 @@ async function addMapping() {
}
}
onMounted(() => store.load(true));
onMounted(async () => {
await store.load(true);
await Promise.all([loadAdherence(), loadReach(), loadGates()]);
});
</script>
<template>
@@ -126,6 +187,12 @@ onMounted(() => store.load(true));
</p>
<MomentProposals />
<WeightProposals />
<LessonSituationProposals />
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
<GateStops :data="gates" :failed="gatesFailed" @retry="loadGates" />
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
<RecordKinds :days="days" />
<ul class="moment-list">
<li v-for="m in catalog" :key="m.name" class="moment-row">
@@ -142,6 +209,9 @@ onMounted(() => store.load(true));
last {{ fmtDate(usage(m.name)!.last_delivered_at!) }}
</span>
</template>
<span v-if="followed(m.name)">
followed {{ followed(m.name)!.followed }} of {{ followed(m.name)!.in_force }} in force
</span>
</span>
</div>
<p class="moment-desc">{{ m.means }}</p>
@@ -168,7 +238,9 @@ onMounted(() => store.load(true));
>×</button>
</span>
</div>
<MomentRuleUsage v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" />
<MomentRuleUsage
v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" :adherence="verdictsByRule(m.name)"
/>
</li>
</ul>
@@ -186,9 +258,14 @@ onMounted(() => store.load(true));
<span>delivered {{ usage(name)!.delivered }}</span>
<span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span>
</template>
<span v-if="followed(name)">
followed {{ followed(name)!.followed }} of {{ followed(name)!.in_force }} in force
</span>
</span>
</div>
<MomentRuleUsage v-if="usage(name)" :rules="usage(name)!.by_rule" />
<MomentRuleUsage
v-if="usage(name)" :rules="usage(name)!.by_rule" :adherence="verdictsByRule(name)"
/>
</li>
</ul>
</template>
+185
View File
@@ -0,0 +1,185 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { apiErrorMessage } from "@/api/client";
import { getRecordKinds, setRecordKinds, setRecordKindsReach } from "@/api/moments";
import type { RecordKindsDoor, RecordKindsTable } from "@/api/moments";
/**
* The kind×moment table: for each point where a record search fires, which
* kinds of record it may consider. A kind left unticked is never pushed
* there; a session can still search for it. Each box shows the lines that
* door pushed of that kind and how many were opened, so a change is made
* against its own evidence. A change saves as soon as it is made.
*
* Above the doors: which kinds may also come from the user's other projects.
* Knowledge crosses by default and work stays in its project; a record from
* elsewhere ranks a little below this project's own and says where it is from.
*/
const props = defineProps<{ days: number }>();
const table = ref<RecordKindsTable | null>(null);
const failed = ref(false);
const saving = ref<string | null>(null);
const saveError = ref("");
async function load() {
try {
table.value = await getRecordKinds(props.days);
failed.value = false;
} catch {
failed.value = true;
}
}
async function save(door: string, kinds: string[] | null) {
saving.value = door;
saveError.value = "";
try {
table.value = await setRecordKinds(door, kinds);
} catch (e) {
saveError.value = apiErrorMessage(e, "The change could not be saved.");
} finally {
saving.value = null;
}
}
function toggle(row: RecordKindsDoor, kind: string, on: boolean) {
const next = on ? [...row.kinds, kind] : row.kinds.filter((k) => k !== kind);
void save(row.door, next);
}
const REACH = "reach";
async function saveReach(kinds: string[] | null) {
saving.value = REACH;
saveError.value = "";
try {
table.value = await setRecordKindsReach(kinds);
} catch (e) {
saveError.value = apiErrorMessage(e, "The change could not be saved.");
} finally {
saving.value = null;
}
}
function toggleReach(kind: string, on: boolean) {
if (!table.value) return;
const now = table.value.reach.kinds;
void saveReach(on ? [...now, kind] : now.filter((k) => k !== kind));
}
function evidenceText(row: RecordKindsDoor, kind: string): string {
const c = row.evidence[kind];
return c ? `${c.opened} of ${c.delivered} opened` : "none shown";
}
onMounted(load);
</script>
<template>
<section class="kinds" aria-labelledby="kinds-title">
<h3 id="kinds-title" class="sub-title">Which records each moment considers</h3>
<p v-if="failed" class="error-msg">
The table could not be loaded.
<button type="button" class="btn-text" @click="load">Try again</button>
</p>
<p v-else-if="!table" class="empty-msg">Loading the table…</p>
<template v-else>
<p class="field-hint">
A search for records runs at each point below. An unticked kind is never shown there;
a session can still search for it. Beside each kind: lines shown there over the last
{{ table.days }} days, and how many were opened.
</p>
<p v-if="table.evidence_failed" class="error-msg">
The counts could not be read, so they are missing below, not zero.
</p>
<p v-if="saveError" class="error-msg" role="alert">{{ saveError }}</p>
<fieldset class="door" :disabled="saving === REACH">
<legend class="door-head">
<span class="door-label">Also from your other projects</span>
<span class="door-fires">at every point below, while a session works in a project</span>
<span v-if="!table.reach.changed" class="door-default">shipped default</span>
</legend>
<p class="field-hint">
A ticked kind is offered from any project you can see, not only the one the session is in.
Such a record has to be a little closer to be shown, ranks below an equally close one from
the session's project, and its line names the project it came from. An unticked kind is
offered only from the session's own project. A search the session runs itself, for one
project, still means that project.
</p>
<ul class="kind-list">
<li v-for="k in table.kinds" :key="k.kind" class="kind-cell">
<label class="kind-label">
<input
type="checkbox" :checked="table.reach.kinds.includes(k.kind)"
@change="toggleReach(k.kind, ($event.target as HTMLInputElement).checked)"
/>
{{ k.label }}
</label>
</li>
</ul>
<button v-if="table.reach.changed" type="button" class="btn-text door-reset" @click="saveReach(null)">
Back to the shipped default
</button>
</fieldset>
<fieldset
v-for="row in table.doors" :key="row.door" class="door"
:disabled="saving === row.door"
>
<legend class="door-head">
<span class="door-label">{{ row.label }}</span>
<code class="moment-name">{{ row.door }}</code>
<span class="door-fires">{{ row.fires }}</span>
<span v-if="!row.changed" class="door-default">shipped default</span>
</legend>
<p v-if="!row.measured" class="door-default">
Named by id in the reply that sets a task in progress, so there are no counts for it.
</p>
<ul class="kind-list">
<li v-for="k in table.kinds" :key="k.kind" class="kind-cell">
<label class="kind-label">
<input
type="checkbox" :checked="row.kinds.includes(k.kind)"
@change="toggle(row, k.kind, ($event.target as HTMLInputElement).checked)"
/>
{{ k.label }}
</label>
<span v-if="!table.evidence_failed && row.measured" class="kind-evidence">{{ evidenceText(row, k.kind) }}</span>
</li>
</ul>
<button v-if="row.changed" type="button" class="btn-text door-reset" @click="save(row.door, null)">
Back to the shipped default
</button>
</fieldset>
</template>
</section>
</template>
<style scoped>
.kinds { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.door {
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-md);
padding: var(--fs-space-2) var(--fs-space-3);
margin: 0;
display: flex; flex-direction: column; gap: var(--fs-space-2);
}
.door:disabled { opacity: var(--fs-disabled-opacity); }
.door-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); padding: 0 var(--fs-space-1); }
.door-label { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
.door-fires,
.door-default,
.kind-evidence { font-size: var(--fs-size-tiny); color: var(--fs-text-secondary); font-variant-numeric: tabular-nums; }
.kind-list {
list-style: none; margin: 0; padding: 0;
display: grid; grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr));
gap: var(--fs-space-1) var(--fs-space-3);
}
.kind-cell { display: flex; flex-direction: column; }
.kind-label { display: inline-flex; align-items: center; gap: var(--fs-space-1); font-size: var(--fs-size-body-sm); cursor: pointer; }
.kind-label input:focus-visible { outline: none; box-shadow: var(--fs-focus-ring); }
.door-reset { align-self: flex-start; }
</style>
<style src="@/assets/moments-shared.css" />
+116
View File
@@ -0,0 +1,116 @@
<script setup lang="ts">
import { computed } from "vue";
import type { RecordReachPayload, RecordWay, WayCounts } from "@/api/moments";
/**
* How records other than rules reached sessions: shown by a hook, found by a
* search the session ran itself, or opened with nothing showing them first —
* and how many were opened each way. It says, per kind, whether a record is
* found by being pushed or by being asked for. One row per kind; open a row
* for the doors behind it.
*/
const props = defineProps<{
data: RecordReachPayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const rows = computed(() => props.data?.by_kind ?? []);
const KIND_LABELS: Record<string, string> = {
snippet: "Snippets",
note: "Notes",
lesson: "Lessons",
process: "Processes",
"task:issue": "Issues",
"task:work": "Work tasks",
"task:spike": "Spikes",
};
function kindLabel(kind: string): string {
return KIND_LABELS[kind] ?? kind;
}
// Each way in reading order. A direct open is opened by definition, so it
// shows one number; the others show how many of those delivered were opened.
const WAYS: [RecordWay, string][] = [
["pushed", "shown by a hook"],
["pointed", "named in a pointer"],
["asked", "from its own search"],
["direct", "opened unshown"],
];
function wayText(way: RecordWay, c: WayCounts): string {
return way === "direct" ? `${c.opened}` : `${c.opened} of ${c.delivered}`;
}
</script>
<template>
<section class="reach" aria-labelledby="reach-title">
<h3 id="reach-title" class="sub-title">How records reach the work</h3>
<p v-if="failed" class="error-msg">
Record reach could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading record reach…</p>
<p v-else-if="!rows.length" class="empty-msg">
No record reached a session in the last {{ data.days }} days from a plugin that reports opens.
</p>
<template v-else>
<p class="field-hint">
Records opened, out of those delivered, over the last {{ data.days }} days across
{{ data.sessions }} sessions: shown by a hook, named by id in a pointer line,
returned by a search the session ran, or opened with nothing showing them first.
</p>
<div class="reach-totals">
<span v-for="[way, label] in WAYS" :key="way">
{{ label }} {{ wayText(way, data.totals[way]) }}
</span>
</div>
<ul class="reach-list">
<li v-for="r in rows" :key="r.kind" class="reach-kind">
<details>
<summary class="reach-row">
<span class="reach-title">{{ kindLabel(r.kind) }}</span>
<span class="reach-counts">
<span v-for="[way, label] in WAYS" :key="way" :class="{ 'way-none': !r.ways[way].delivered }">
{{ label }} {{ wayText(way, r.ways[way]) }}
</span>
</span>
</summary>
<ul class="reach-sources">
<li v-for="s in r.sources" :key="`${s.way}:${s.source}`" class="reach-row">
<code class="moment-name">{{ s.source }}</code>
<span class="reach-counts">
<span>{{ s.way === "direct" ? `${s.opened} opened` : `${s.opened} of ${s.delivered} opened` }}</span>
</span>
</li>
</ul>
</details>
</li>
</ul>
</template>
</section>
</template>
<style scoped>
.reach { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.reach-totals,
.reach-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2);
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary);
font-variant-numeric: tabular-nums;
}
.reach-counts { margin-left: auto; justify-content: flex-end; }
.reach-list,
.reach-sources { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.reach-sources { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.reach-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.reach-kind summary { cursor: pointer; }
.reach-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
/* A way that delivered nothing for this kind is a gap, not a zero to read. */
.way-none { color: var(--fs-text-tertiary); }
</style>
<style src="@/assets/moments-shared.css" />
+107
View File
@@ -0,0 +1,107 @@
<script setup lang="ts">
import { computed } from "vue";
import type { AdherenceCounts, AdherencePayload } from "@/api/moments";
/**
* Whether the rules in force at each moment were followed there. A rule is in
* force at a moment of a session when it was delivered there; each such case
* is followed, departed from (with a stated reason), broken, not applicable,
* or not judged yet. Verdicts come from a refused act, the session's own
* `rule_outcome` / `rule_misfired`, and transcript reviews
* (`adherence_to_judge`). One row per rule; open a row for its places.
*/
const props = defineProps<{
data: AdherencePayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const rows = computed(() => props.data?.by_rule ?? []);
// The verdict counts in reading order, each shown only when it is not zero,
// so a row says what happened rather than listing zeros.
const PARTS: [keyof AdherenceCounts, string][] = [
["followed", "followed"],
["departed", "departed"],
["broken", "broken"],
["not_applicable", "not applicable"],
["unjudged", "not judged"],
];
function parts(c: AdherenceCounts): { key: string; text: string }[] {
return PARTS.filter(([k]) => c[k] > 0).map(([k, label]) => ({ key: k, text: `${label} ${c[k]}` }));
}
</script>
<template>
<section class="adherence" aria-labelledby="adherence-title">
<h3 id="adherence-title" class="sub-title">Were they followed</h3>
<p v-if="failed" class="error-msg">
Adherence could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading adherence…</p>
<p v-else-if="!rows.length" class="empty-msg">
No rule was in force at a moment in the last {{ data.days }} days.
</p>
<template v-else>
<p class="field-hint">
Sessions each rule was in force in over the last {{ data.days }} days, and what each was
judged. A review fills in the rest from transcripts with <code>adherence_to_judge</code>.
</p>
<div class="adherence-totals">
<span>in force {{ data.totals.in_force }}</span>
<span>opened {{ data.totals.opened }}</span>
<span v-for="p in parts(data.totals)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
</div>
<ul class="adherence-list">
<li v-for="r in rows" :key="r.rule_id" class="adherence-rule">
<details>
<summary class="adherence-row">
<span class="adherence-title">{{ r.title ?? `Rule ${r.rule_id} (deleted)` }}</span>
<span class="adherence-counts">
<span>in force {{ r.in_force }}</span>
<span>opened {{ r.opened }}</span>
<span v-for="p in parts(r)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
</span>
</summary>
<ul class="adherence-places">
<li v-for="m in r.by_moment" :key="m.at" class="adherence-row">
<code class="moment-name">{{ m.at }}</code>
<span class="adherence-counts">
<span>in force {{ m.in_force }}</span>
<span>opened {{ m.opened }}</span>
<span v-for="p in parts(m)" :key="p.key" :class="`v-${p.key}`">{{ p.text }}</span>
</span>
</li>
</ul>
</details>
</li>
</ul>
</template>
</section>
</template>
<style scoped>
.adherence { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.adherence-totals,
.adherence-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2);
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary);
font-variant-numeric: tabular-nums;
}
.adherence-counts { margin-left: auto; justify-content: flex-end; }
.adherence-list,
.adherence-places { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.adherence-places { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.adherence-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.adherence-rule summary { cursor: pointer; }
.adherence-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
/* Broken is the one count a person acts on, so it is the one that stands out;
not judged is a gap in the record, not a fault, and stays quiet. */
.v-broken { color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.v-unjudged { color: var(--fs-text-tertiary); font-style: italic; }
</style>
<style src="@/assets/moments-shared.css" />
@@ -80,6 +80,11 @@ function rulingsShown(system: System): number {
return system.usage?.surfaced_count ?? 0;
}
/** Rulings with no files to deliver them on: none reaches a session. */
function rulingsUndelivered(system: System): boolean {
return (system.ruling_count ?? 0) > 0 && system.path_patterns.length === 0;
}
function rulingsTitle(system: System): string {
const u = system.usage;
if (!u) return "";
@@ -498,6 +503,12 @@ async function confirmDelete() {
>rulings shown {{ rulingsShown(system) }}×</span>
</div>
<p v-if="system.description" class="system-description">{{ system.description }}</p>
<p v-if="rulingsUndelivered(system)" class="system-undelivered">
<span class="usage-tag usage-dead">rulings not delivered</span>
{{ system.ruling_count === 1 ? "Its ruling reaches" : `Its ${system.ruling_count} rulings reach` }}
no session: a ruling is shown when a session touches the area's files, and this area names none.
<button type="button" class="btn-text" @click="startEdit(system)">Name its files</button>
</p>
<ul v-if="system.path_patterns.length" class="system-paths" aria-label="Files">
<li v-for="pattern in system.path_patterns" :key="pattern" class="system-path">{{ pattern }}</li>
</ul>
@@ -700,6 +711,12 @@ async function confirmDelete() {
.system-form-actions { display: flex; gap: 0.4rem; }
.system-paths-input { font-family: var(--fs-font-mono); font-size: 0.8rem; }
.system-undelivered {
margin: var(--fs-space-2) 0 0;
font-size: var(--fs-size-body-sm);
color: var(--fs-text-secondary);
}
/* The area's files. Mono because they are paths to be read
character for character; small because they qualify the card, not lead it. */
.system-paths {
+2 -1
View File
@@ -2,6 +2,7 @@
import { ref, onMounted } from "vue";
import { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import type { TaskLog } from "@/types/task";
import { fmtStamp } from "@/utils/dateFormat";
@@ -131,7 +132,7 @@ onMounted(loadLogs);
<button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">&times;</button>
</div>
</div>
<div class="log-content prose" v-html="renderMarkdown(log.content)"></div>
<div class="log-content prose" v-html="renderMarkdown(log.content)" v-record-refs></div>
</template>
</div>
+250
View File
@@ -0,0 +1,250 @@
<script setup lang="ts">
/**
* Tests that guard the same thing from different files — the coverage card's
* merge-or-remove queue. Each group lists what its tests exercise and, per
* test, weak-test signals read from its body. A group is a candidate, not a
* verdict: the reviewer either marks one test redundant (naming the test in
* the group that covers it) or keeps them all, with a reason either way.
*/
import { ref, onMounted, watch } from "vue";
import { apiGet, apiPost, apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
interface ShapeRef {
id: number;
path: string;
symbol: string;
}
interface GroupTest extends ShapeRef {
status: string;
signals: string[];
}
interface Group {
key: string;
kind: "copies" | "area";
files: number;
guards: ShapeRef[];
tests: GroupTest[];
}
const props = defineProps<{ projectId: number; canWrite: boolean }>();
const emit = defineEmits<{ (e: "changed"): void }>();
const toast = useToastStore();
const groups = ref<Group[]>([]);
const count = ref(0);
const loading = ref(false);
const error = ref<string | null>(null);
const open = ref(false);
// One form at a time: keeping a whole group, or marking one test redundant.
const activeKey = ref<string | null>(null);
const mode = ref<"keep" | "redundant">("keep");
const testId = ref<number | null>(null);
const coverId = ref<number | null>(null);
const reason = ref("");
const saving = ref(false);
const SIGNAL_HELP: Record<string, string> = {
signature: "Checks how the code is declared (its parameters), not what it does",
"mock-only": "Asserts only that mocks were called",
"source-text": "Reads source code as text",
};
async function load() {
loading.value = true;
error.value = null;
try {
const res = await apiGet<{ count: number; groups: Group[] }>(
`/api/projects/${props.projectId}/test-guards`,
);
groups.value = res.groups;
count.value = res.count;
} catch (e) {
error.value = apiErrorMessage(e, "Could not load the test groups");
} finally {
loading.value = false;
}
}
function startKeep(g: Group) {
activeKey.value = g.key;
mode.value = "keep";
reason.value = "";
}
function startRedundant(g: Group, t: GroupTest) {
activeKey.value = g.key;
mode.value = "redundant";
testId.value = t.id;
coverId.value = g.tests.find((x) => x.id !== t.id)?.id ?? null;
reason.value = "";
}
function cancel() {
activeKey.value = null;
reason.value = "";
}
async function submit(g: Group) {
if (!reason.value.trim() || saving.value) return;
saving.value = true;
try {
if (mode.value === "keep") {
await apiPost(`/api/projects/${props.projectId}/test-guards/review`, {
test_ids: g.tests.map((t) => t.id),
reason: reason.value.trim(),
});
toast.show("Group kept — it leaves the list until a test joins or leaves it");
} else {
await apiPost(`/api/projects/${props.projectId}/test-guards/redundant`, {
test_id: testId.value,
covered_by_id: coverId.value,
reason: reason.value.trim(),
});
toast.show("Marked redundant — delete the test, and the next refresh retires its row");
}
cancel();
await load();
emit("changed");
} catch (e) {
toast.show(apiErrorMessage(e, "Could not record the verdict"), "error");
} finally {
saving.value = false;
}
}
function label(s: ShapeRef): string {
return `${s.path.split("/").pop()} · ${s.symbol}`;
}
onMounted(load);
watch(() => props.projectId, load);
</script>
<template>
<div class="tg">
<button
type="button"
class="btn-ghost btn-inline tg-toggle"
:aria-expanded="open"
aria-controls="tg-groups"
@click="open = !open"
>
{{ open ? "▾" : "▸" }} Tests guarding the same thing
<span class="tg-count">{{ count }}</span>
</button>
<div v-if="open" id="tg-groups" class="tg-body">
<p class="tg-intro">
Tests in different files that exercise exactly the same code. Read them:
if one checks nothing the other doesn't, mark it redundant and delete it;
if each checks something of its own, keep them all and say what.
</p>
<p v-if="loading" class="tg-note">Loading…</p>
<p v-else-if="error" class="tg-error" role="alert">{{ error }}</p>
<p v-else-if="!groups.length" class="tg-note">
No tests guard the same thing from different files.
</p>
<ul v-else class="tg-list">
<li v-for="g in groups" :key="g.key" class="tg-group">
<p v-if="g.kind === 'area'" class="tg-kind">
One feature tested from {{ g.files }} files: fold the scattered
cases into its own test file, and remove only what another test covers.
</p>
<div class="tg-guards">
<span class="tg-label">Guard</span>
<code v-for="s in g.guards" :key="s.id" :title="s.path">{{ s.symbol }}</code>
</div>
<ul class="tg-tests">
<li v-for="t in g.tests" :key="t.id" class="tg-test">
<code :title="t.path">{{ label(t) }}</code>
<span
v-for="sig in t.signals"
:key="sig"
class="tg-signal"
:title="SIGNAL_HELP[sig] || sig"
>{{ sig }}</span>
<button
v-if="canWrite"
type="button"
class="btn-ghost btn-inline"
@click="startRedundant(g, t)"
>Redundant…</button>
</li>
</ul>
<button
v-if="canWrite && activeKey !== g.key"
type="button"
class="btn-ghost btn-inline"
@click="startKeep(g)"
>Keep all…</button>
<form v-if="activeKey === g.key" class="tg-form" @submit.prevent="submit(g)">
<label v-if="mode === 'redundant'" class="tg-field">
<span>Covered by</span>
<select v-model="coverId">
<option
v-for="t in g.tests.filter((x) => x.id !== testId)"
:key="t.id"
:value="t.id"
>{{ label(t) }}</option>
</select>
</label>
<label class="tg-field">
<span>{{ mode === "keep"
? "What each test checks that the others don't"
: "What the covering test checks that this one also checked" }}</span>
<textarea v-model="reason" rows="2" required></textarea>
</label>
<div class="tg-actions">
<button type="submit" class="btn-primary btn-compact" :disabled="!reason.trim() || saving">
{{ mode === "keep" ? "Keep all" : "Mark redundant" }}
</button>
<button type="button" class="btn-ghost btn-compact" @click="cancel">Cancel</button>
</div>
</form>
</li>
</ul>
<p v-if="count > groups.length" class="tg-note">
Showing {{ groups.length }} of {{ count }}, smallest first: the
smallest groups are the likeliest copies.
</p>
</div>
</div>
</template>
<style scoped>
.tg { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.tg-toggle { align-self: flex-start; }
.tg-count {
margin-left: var(--fs-space-1);
padding: 0 var(--fs-space-2);
border-radius: var(--fs-radius-pill);
border: 1px solid var(--fs-border-color);
color: var(--fs-text-secondary);
}
.tg-body { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.tg-intro, .tg-note { color: var(--fs-text-tertiary); margin: 0; }
.tg-error { color: var(--fs-status-cancelled-fg); margin: 0; }
.tg-list, .tg-tests { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.tg-group {
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-md);
padding: var(--fs-space-2) var(--fs-space-3);
display: flex;
flex-direction: column;
gap: var(--fs-space-2);
}
.tg-guards, .tg-test { display: flex; flex-wrap: wrap; align-items: center; gap: var(--fs-space-2); }
.tg-label { color: var(--fs-text-tertiary); }
.tg-kind { margin: 0; color: var(--fs-text-secondary); }
code { font-family: var(--fs-font-mono); color: var(--fs-text-primary); }
.tg-signal {
padding: 0 var(--fs-space-2);
border-radius: var(--fs-radius-pill);
background: var(--fs-status-todo-bg);
color: var(--fs-status-todo-fg);
}
.tg-form { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.tg-field { display: flex; flex-direction: column; gap: var(--fs-space-1); color: var(--fs-text-secondary); }
.tg-actions { display: flex; gap: var(--fs-space-2); }
</style>
+215
View File
@@ -0,0 +1,215 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { getWeightProposals, judgeWeightProposals } from "@/api/moments";
import type {
RuleWeightProposals, Verdict, WeightEvidence, WeightProposal, WeightProposalsPayload,
} from "@/api/moments";
import type { RuleTrigger } from "@/api/rulebooks";
import { apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import ConfirmDialog from "@/components/ConfirmDialog.vue";
/**
* Suggestions for how strongly a rule arrives and what reaches it, waiting on
* a person. A pass read each rule beside what happened when it reached
* sessions, and proposed its enforcement (inform, hold, enforce), its salience,
* or a typed trigger. Nothing changes until "Apply" is pressed; "Not this"
* keeps the value from being proposed again. "Apply all" confirms every
* listed suggestion at once, after a dialog that counts what changes. The
* same judgment `judge_rule_weights` makes in a session, through the same
* service.
*/
const toast = useToastStore();
const data = ref<WeightProposalsPayload | null>(null);
const failed = ref(false);
const busy = ref<string | null>(null);
const confirmingAll = ref(false);
const rules = computed<RuleWeightProposals[]>(() => data.value?.rules ?? []);
const proposalCount = computed(() => rules.value.reduce((n, r) => n + r.proposals.length, 0));
// The dialog names how many rules would start stopping work, since a hold or
// an enforce is the change a person notices in their next session.
const allSummary = computed(() => {
const stopping = rules.value.filter((r) => r.proposals.some(
(p) => p.field === "enforcement" && p.value !== "inform",
)).length;
const changes = `${proposalCount.value} change${proposalCount.value === 1 ? "" : "s"}`;
const across = `${rules.value.length} rule${rules.value.length === 1 ? "" : "s"}`;
const stops = stopping
? ` ${stopping} of them will hold or refuse the acts they govern.`
: "";
return `${changes} across ${across} take effect at once.${stops}`;
});
// What each enforcement does when the rule arrives — said beside the change,
// since "hold" and "enforce" stop work and the person applying one should
// know how.
const FORCE: Record<string, string> = {
inform: "a line beside the work",
hold: "the act or reply waits until it has been read once",
enforce: "the act it governs is refused, every time",
};
async function load() {
try {
data.value = await getWeightProposals();
failed.value = false;
} catch {
failed.value = true;
}
}
function key(rule: RuleWeightProposals, p: WeightProposal): string {
return `${rule.id}:${p.field}:${p.value}`;
}
function triggerText(t: RuleTrigger): string {
return `${t.kind} ${t.pattern}${t.moment ? ` at ${t.moment}` : ""}`;
}
function change(rule: RuleWeightProposals, p: WeightProposal): string {
if (p.field === "trigger" && p.trigger) return `add trigger ${triggerText(p.trigger)}`;
const from = p.field === "enforcement" ? rule.enforcement : rule.salience;
return `${p.field} ${from} → ${p.value}`;
}
function history(e: WeightEvidence): string {
if (!e || e.delivered === undefined) return "";
const parts = [`delivered ${e.delivered}`, `opened ${e.opened ?? 0}`];
if (e.applied) parts.push(`applied ${e.applied}`);
if (e.departed) parts.push(`departed ${e.departed}`);
if (e.misfire_days) parts.push(`misfired on ${e.misfire_days} days`);
return `${parts.join(" · ")} in ${e.days ?? 90} days`;
}
async function decide(rule: RuleWeightProposals, p: WeightProposal, verdict: Verdict) {
busy.value = key(rule, p);
try {
const out = await judgeWeightProposals([{
rule_id: rule.id, field: p.field, value: p.trigger ?? p.value, verdict,
note: verdict === "confirm" ? "Applied in Settings." : "Declined in Settings.",
}]);
if (out.refused.length) {
toast.show(out.refused[0].error, "error");
return;
}
await load();
} catch (e) {
toast.show(apiErrorMessage(e, "Could not record that"), "error");
} finally {
busy.value = null;
}
}
async function applyAll() {
confirmingAll.value = false;
busy.value = "all";
try {
const out = await judgeWeightProposals(rules.value.flatMap((rule) => rule.proposals.map((p) => ({
rule_id: rule.id, field: p.field, value: p.trigger ?? p.value,
verdict: "confirm" as Verdict, note: "Applied with Apply all in Settings.",
}))));
if (out.refused.length) {
const first = out.refused[0];
toast.show(
`${out.judged.length} applied; ${out.refused.length} refused — #${first.rule_id}: ${first.error}`,
"error",
);
} else {
toast.show(`${out.judged.length} applied.`, "success");
}
await load();
} catch (e) {
toast.show(apiErrorMessage(e, "Could not apply the suggestions"), "error");
} finally {
busy.value = null;
}
}
onMounted(load);
</script>
<template>
<section v-if="failed || rules.length" class="proposals" aria-labelledby="weights-title">
<h3 id="weights-title" class="sub-title">How strongly rules arrive — waiting on you</h3>
<p v-if="failed" class="error-msg">
The suggestions could not be loaded.
<button type="button" class="btn-text" @click="load">Try again</button>
</p>
<template v-else>
<p class="field-hint">
Suggested from each rule's text and what happened when it reached sessions. Inform is a
line beside the work; hold makes the act or reply wait until the rule has been read once
(file edits are never held); enforce refuses the act it governs. A trigger reaches the
rule exactly, by the tool, path, command or word the act carries; a rule with triggers
holds or refuses only the acts they match, and elsewhere it is a line.
</p>
<div class="proposals-bar">
<button
type="button" class="btn-primary btn-sm"
:disabled="busy !== null"
@click="confirmingAll = true"
>Apply all {{ proposalCount }}</button>
</div>
<ul class="proposal-list">
<li v-for="rule in rules" :key="rule.id" class="proposal-rule">
<div class="rule-head">
<span class="rule-title">#{{ rule.id }} {{ rule.title }}</span>
<span class="rule-mounted">
{{ rule.enforcement }} · {{ rule.salience }}
<template v-if="rule.mounted.length">
· on <code v-for="m in rule.mounted" :key="m" class="moment-name">{{ m }}</code>
</template>
<template v-if="rule.triggers.length">
· triggered by
<code v-for="t in rule.triggers" :key="triggerText(t)" class="moment-name">{{ triggerText(t) }}</code>
</template>
</span>
</div>
<p class="rule-statement">{{ rule.statement }}</p>
<ul class="proposal-items">
<li v-for="p in rule.proposals" :key="key(rule, p)" class="proposal-item">
<code class="moment-name">{{ change(rule, p) }}</code>
<span class="proposal-why">
{{ p.why }}
<span v-if="p.field === 'enforcement'" class="proposal-source">
· {{ FORCE[p.value] }}
</span>
<span v-if="history(p.evidence)" class="proposal-source">
· {{ history(p.evidence) }}
</span>
</span>
<span class="proposal-actions">
<button
type="button" class="btn-primary btn-sm"
:disabled="busy !== null"
@click="decide(rule, p, 'confirm')"
>Apply</button>
<button
type="button" class="btn-text"
:disabled="busy !== null"
@click="decide(rule, p, 'reject')"
>Not this</button>
</span>
</li>
</ul>
</li>
</ul>
</template>
<ConfirmDialog
v-if="confirmingAll"
title="Apply every suggestion?"
:message="allSummary"
confirm-label="Apply all"
:danger="false"
@confirm="applyAll"
@cancel="confirmingAll = false"
/>
</section>
</template>
<style scoped src="@/assets/rule-proposals.css" />
<style src="@/assets/moments-shared.css" />
@@ -6,7 +6,11 @@ import { useMomentsStore } from "@/stores/moments";
import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue";
import RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
import { apiErrorMessage } from "@/api/client";
import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks";
import {
listRulebooks, listTopics,
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
type RuleTrigger, type RuleTriggerKind,
} from "@/api/rulebooks";
const props = defineProps<{
ruleId: number | null;
@@ -26,6 +30,14 @@ const whenToApply = ref("");
// followed too faithfully, where a rule mislabelled as a preference is one a
// session may quietly rewrite.
const kind = ref<RuleKind>("rule");
// The server's defaults: a line beside the work, at normal rank.
const enforcement = ref<RuleEnforcement>("inform");
const salience = ref<RuleSalience>("normal");
// A preference carries no force but `inform`, and the server refuses any
// other, so switching kind settles it here rather than as a failed save.
watch(kind, (k) => {
if (k === "preference") enforcement.value = "inform";
});
const systemIds = ref<number[]>([]);
// The moments this rule is mounted on. Catalog moments are
// ticked; a named procedure's moment (`skill.<name>`) is typed, since its
@@ -39,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []);
const procedureMoments = computed(() =>
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
);
// The acts this rule is triggered by, checked exactly on the server.
const triggers = ref<RuleTrigger[]>([]);
const triggerKind = ref<RuleTriggerKind>("path");
const triggerPattern = ref("");
const triggerMoment = ref("");
const triggerError = ref("");
const TRIGGER_KINDS: { value: RuleTriggerKind; label: string; placeholder: string }[] = [
{ value: "path", label: "Path", placeholder: "alembic/versions/*.py — a file the act touches" },
{ value: "command", label: "Command", placeholder: "git push — the head of a command it runs" },
{ value: "tool", label: "Tool", placeholder: "update_task — the tool it calls" },
{ value: "keyword", label: "Keyword", placeholder: "migration — a word in what it writes" },
];
const triggerPlaceholder = computed(
() => TRIGGER_KINDS.find((k) => k.value === triggerKind.value)?.placeholder ?? "",
);
function triggerLabel(t: RuleTrigger) {
return TRIGGER_KINDS.find((k) => k.value === t.kind)?.label ?? t.kind;
}
function addTrigger() {
const pattern = triggerPattern.value.trim().replace(/\s+/g, " ");
if (!pattern) return;
const moment = triggerMoment.value || undefined;
const same = (t: RuleTrigger) =>
t.kind === triggerKind.value && t.pattern === pattern && (t.moment ?? "") === (moment ?? "");
if (triggers.value.some(same)) {
triggerError.value = "This rule already has that trigger.";
return;
}
triggerError.value = "";
triggers.value.push({ kind: triggerKind.value, pattern, ...(moment ? { moment } : {}) });
triggerPattern.value = "";
}
function removeTrigger(at: number) {
triggers.value.splice(at, 1);
}
const why = ref("");
const howToApply = ref("");
const verifyWith = ref("");
@@ -123,8 +173,11 @@ async function load() {
statement.value = r.statement;
whenToApply.value = r.when_to_apply || "";
kind.value = r.kind;
enforcement.value = r.enforcement ?? "inform";
salience.value = r.salience ?? "normal";
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
ruleMoments.value = [...(r.moments ?? [])];
triggers.value = (r.triggers ?? []).map((t) => ({ ...t }));
why.value = r.why || "";
howToApply.value = r.how_to_apply || "";
verifyWith.value = r.verify_with || "";
@@ -135,8 +188,11 @@ async function load() {
statement.value = "";
whenToApply.value = props.preset?.whenToApply ?? "";
kind.value = props.preset?.kind ?? "rule";
enforcement.value = "inform";
salience.value = "normal";
systemIds.value = [];
ruleMoments.value = [...(props.preset?.moments ?? [])];
triggers.value = [];
why.value = "";
howToApply.value = "";
verifyWith.value = "";
@@ -144,6 +200,9 @@ async function load() {
}
procedureDraft.value = "";
procedureError.value = "";
triggerPattern.value = "";
triggerMoment.value = "";
triggerError.value = "";
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
}
@@ -181,12 +240,16 @@ async function save() {
statement: statement.value,
when_to_apply: whenToApply.value,
kind: kind.value,
enforcement: enforcement.value,
salience: salience.value,
// Always sent, so clearing the last area actually clears it — the server
// reads a list as "these ARE the areas now".
system_ids: systemIds.value,
// Always sent, for system_ids' reason: the server reads the list as the
// whole set, so unticking the last moment actually unmounts the rule.
moments: ruleMoments.value,
// Always sent, for the same reason: the list is the whole set.
triggers: triggers.value,
why: why.value,
how_to_apply: howToApply.value,
// Always sent, including empty. The REST door maps "" to NULL, so
@@ -271,6 +334,40 @@ watch(() => props.ruleId, load);
preference.
</p>
</fieldset>
<fieldset class="kind arrival">
<legend>When it arrives</legend>
<template v-if="kind === 'rule'">
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="inform" />
<span><strong>Inform</strong> — a line beside the work. Most rules.</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="hold" />
<span>
<strong>Hold</strong> — the reply or command it governs waits until
the rule has been read once. File edits are never held. For a rule
whose miss costs a rewrite.
</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="enforce" />
<span>
<strong>Enforce</strong> — an act its moment or trigger reaches
does not run, every time, until you change the rule. For a hard
boundary.
</span>
</label>
</template>
<p v-else class="field-note">A preference arrives as a line beside the work.</p>
<label class="salience">
Rank among the rest
<select v-model="salience" class="fs-input">
<option value="high">High — shown first when a moment is crowded</option>
<option value="normal">Normal</option>
<option value="low">Low — the first to give way</option>
</select>
</label>
</fieldset>
<p v-if="kind === 'preference'" class="kind-drift">
Sessions rewrite preferences without asking, which is what makes them
stay current. Every rewrite is kept, and
@@ -342,6 +439,55 @@ watch(() => props.ruleId, load);
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
</fieldset>
<fieldset class="moments triggers">
<legend>Acts that trigger it</legend>
<p class="field-note intro">
Matched exactly against what the work does, not by resemblance: a
path it touches, a command it runs, a tool it calls, a word in what it
writes. With no moment, the rule arrives on any act that matches.
With a moment, it arrives at that moment only when the act matches,
so a rule about migrations can sit where files change without arriving
at every edit.
</p>
<ul v-if="triggers.length" class="trigger-list">
<li v-for="(t, i) in triggers" :key="`${t.kind}:${t.pattern}:${t.moment ?? ''}`" class="rule-chip trigger-chip">
<span class="trigger-kind">{{ triggerLabel(t) }}</span>
<code>{{ t.pattern }}</code>
<span v-if="t.moment" class="trigger-at">at <code>{{ t.moment }}</code></span>
<button
type="button"
class="chip-remove"
:aria-label="`Remove the ${triggerLabel(t).toLowerCase()} trigger ${t.pattern}`"
@click="removeTrigger(i)"
>×</button>
</li>
</ul>
<p v-else class="field-note">No triggers: this rule arrives by its moments and by resemblance.</p>
<div class="trigger-add">
<select v-model="triggerKind" class="fs-input" aria-label="What the trigger matches">
<option v-for="k in TRIGGER_KINDS" :key="k.value" :value="k.value">{{ k.label }}</option>
</select>
<input
v-model="triggerPattern"
class="fs-input"
aria-label="The pattern the act must match"
:placeholder="triggerPlaceholder"
@keydown.enter.prevent="addTrigger"
/>
<select v-model="triggerMoment" class="fs-input" aria-label="Only at this moment">
<option value="">Any act</option>
<option v-for="m in momentCatalog" :key="m.name" :value="m.name">Only at {{ m.name }}</option>
</select>
<button
type="button"
class="btn-secondary btn-sm"
:disabled="!triggerPattern.trim()"
@click="addTrigger"
>Add</button>
</div>
<p v-if="triggerError" class="trigger-warning">{{ triggerError }}</p>
</fieldset>
<fieldset v-if="canon.catalog.length" class="areas">
<legend>Areas this rule is about</legend>
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
@@ -424,13 +570,13 @@ watch(() => props.ruleId, load);
<ul>
<li v-for="l in lessons" :key="l.id" class="relation">
<router-link :to="`/lessons/${l.id}`" class="relation-target">{{ l.title }}</router-link>
<span v-if="l.state === 'suggested'" class="rule-chip">suggested</span>
<span v-if="l.state === 'rejected'" class="rule-chip">not an instance</span>
<span v-if="l.note" class="relation-note">{{ l.note }}</span>
</li>
</ul>
<p class="field-note">
The situations that keep proving this rule. A confirmed lesson brings the rule along
when it surfaces; a suggested one waits for a judgment on the lesson's page.
when it surfaces, and arrives with the rule when you open it.
</p>
</section>
@@ -457,7 +603,7 @@ watch(() => props.ruleId, load);
</div>
</template>
<!-- `.rule-chip` for the "suggested" marker on a lesson — the chip the rule
<!-- `.rule-chip` for the "not an instance" marker on a lesson — the chip the rule
panes already use, loaded here because the slide-over can open with no
pane that loads it (a link straight to ?rule=N).
Block 0, as in every pane that loads it: a shared src must sit at
@@ -520,6 +666,13 @@ legend { padding: 0 0.35rem; font-size: 0.8rem; color: var(--fs-text-tertiary);
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
.procedure-add input { margin-top: 0; }
.procedure-add .btn-sm { flex: none; }
.trigger-list { list-style: none; padding: 0; margin: 0 0 var(--fs-space-2); display: flex; flex-wrap: wrap; gap: var(--fs-space-2); }
.trigger-chip { display: inline-flex; align-items: center; gap: var(--fs-space-1); }
.trigger-kind, .trigger-at { color: var(--fs-text-secondary); font-size: var(--fs-size-tiny); }
.trigger-add { display: flex; flex-wrap: wrap; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
.trigger-add input { flex: 1 1 14rem; margin-top: 0; }
.trigger-add select { flex: none; width: auto; margin-top: 0; }
.trigger-add .btn-sm { flex: none; }
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction
between the warning HUE and warning text, and this is text. */
.trigger-warning {
@@ -27,6 +27,15 @@ const emit = defineEmits<{
class="rule-chip rule-chip-preference"
title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it."
>preference</span>
<!-- Marked only when the rule stops the work: a line beside the work
is the default, and marking it on every row would mark nothing. -->
<span
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
class="rule-chip"
:title="r.enforcement === 'hold'
? 'The reply or command it governs waits until it has been read once'
: 'An act it is reached by does not run until the rule changes'"
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
<!-- Marked only when something is WRONG: every rule arrives by
retrieval now, so "conditional" stopped distinguishing anything.
A missing trigger does — it means nothing can retrieve this. -->
+2 -1
View File
@@ -51,7 +51,8 @@ export function useAutocomplete(
// Must be start of line or preceded by whitespace
if (i === 0 || /\s/.test(text[i - 1])) {
const query = text.slice(i + 1, cursor);
if (/^[\w/]*$/.test(query)) {
// Digits alone are a record reference being typed (`#4286`), not a tag.
if (/^[\w/]*$/.test(query) && !/^\d+$/.test(query)) {
acTriggerStart = i;
acType = "tag";
debouncedSearch(query);
+199
View File
@@ -0,0 +1,199 @@
import type { ObjectDirective } from "vue";
import { apiPost } from "@/api/client";
import router from "@/router";
import { recordHref } from "@/utils/recordHref";
import type { RefSpace } from "@/utils/recordRefs";
/** v-record-refs — makes the `a.record-ref` links in a v-html body real.
*
* Put it on the element that holds rendered markdown:
* <div class="prose" v-html="renderMarkdown(body)" v-record-refs />
*
* After each render it asks the server, once for the whole body, what every
* referenced id is. Each link then gets the route its kind opens at (a `#N`
* may be a task, lesson or snippet), the record's title drawn before its
* number — "Fix the cache key #3127" — so a reader knows what is cited
* without hovering, its kind, full title and status as a tooltip, and a
* "leads nowhere" style when the reader cannot open it: missing, trashed and
* not-shared-with-you look the same, on purpose, and keep the bare number.
* The stored text stays `#N`; the title is read at render, so an edited
* title shows everywhere it is cited.
* A plain click navigates in the app; a modified click (new tab) keeps the
* browser's own behaviour.
*/
interface NoteInfo { id: number; title: string; is_task: boolean; note_type: string; status: string | null; task_kind: string | null }
interface MilestoneInfo { id: number; title: string; project_id: number | null; status: string }
interface RuleInfo { id: number; title: string; kind: string }
type Resolved = { notes: Record<string, NoteInfo>; milestones: Record<string, MilestoneInfo>; rules: Record<string, RuleInfo> };
// `title` is drawn in the link; `label` (kind · title (status)) is its tooltip.
type Info = { href: string; title: string; label: string } | null;
// A short-lived cache: the same body re-renders on every keystroke in a
// preview, and a page of work logs cites the same few records again and again.
const CACHE_MS = 60_000;
const cache = new Map<string, { at: number; info: Info }>();
const TASK_KIND_LABEL: Record<string, string> = { issue: "Issue", spike: "Spike" };
function noteInfo(n: NoteInfo): Info {
let kind = "Note";
if (n.is_task) kind = TASK_KIND_LABEL[n.task_kind ?? ""] ?? "Task";
else if (n.note_type === "lesson") kind = "Lesson";
else if (n.note_type === "snippet") kind = "Snippet";
const state = n.is_task && n.status ? ` (${n.status.replace(/_/g, " ")})` : "";
const title = n.title || "Untitled";
return { href: recordHref(n), title, label: `${kind} · ${title}${state}` };
}
function milestoneInfo(m: MilestoneInfo): Info {
if (m.project_id == null) return null;
const title = m.title || "Untitled";
return {
href: `/projects/${m.project_id}?milestone=${m.id}`,
title,
label: `Milestone · ${title}${m.status === "done" ? " (done)" : ""}`,
};
}
function ruleInfo(r: RuleInfo): Info {
const kind = r.kind === "preference" ? "Preference" : "Rule";
const title = r.title || "Untitled";
return { href: `/rules?rule=${r.id}`, title, label: `${kind} · ${title}` };
}
// Titles here are often whole sentences; in running text a reference names its
// record in a few words and the tooltip carries the rest.
const MAX_TITLE = 60;
function shorten(title: string): string {
if (title.length <= MAX_TITLE) return title;
const cut = title.slice(0, MAX_TITLE);
const space = cut.lastIndexOf(" ");
return (space > MAX_TITLE / 2 ? cut.slice(0, space) : cut).replace(/[\s,.;:—–-]+$/, "") + "…";
}
const BLOCK = "p, li, td, th, blockquote, h1, h2, h3, h4, h5, h6";
/** Whether the sentence around this link already names the record — a batch
* writes `#9 "Step two"`, and a paragraph citing one record twice names it
* the first time. A short title is drawn regardless: three letters turn up
* in prose by chance. */
function alreadyNamed(a: HTMLAnchorElement, shown: string, title: string): boolean {
if (title.length < 8) return false;
const text = (a.closest(BLOCK) ?? a.parentElement)?.textContent?.toLowerCase() ?? "";
return text.includes(title.toLowerCase()) || text.includes(shown.toLowerCase());
}
/** Draw the record's title in the link, its number after it, muted. Set as
* text, never as markup: a title is whatever its author typed. */
function showTitle(a: HTMLAnchorElement, title: string): boolean {
const shown = shorten(title);
if (alreadyNamed(a, shown, title)) return false;
const name = document.createElement("span");
name.className = "record-ref__title";
name.textContent = shown;
const ref = document.createElement("span");
ref.className = "record-ref__id";
ref.textContent = a.textContent ?? "";
a.replaceChildren(name, " ", ref);
return true;
}
function refKey(space: RefSpace, id: number): string {
return `${space}:${id}`;
}
/** What each of these references is, from the cache or one server call. */
export async function resolveRecordRefs(wanted: { space: RefSpace; id: number }[]): Promise<Map<string, Info>> {
const now = Date.now();
const out = new Map<string, Info>();
const ask: Record<RefSpace, number[]> = { notes: [], milestones: [], rules: [] };
for (const w of wanted) {
const k = refKey(w.space, w.id);
if (out.has(k)) continue;
const hit = cache.get(k);
if (hit && now - hit.at < CACHE_MS) out.set(k, hit.info);
else if (!ask[w.space].includes(w.id)) ask[w.space].push(w.id);
}
if (ask.notes.length + ask.milestones.length + ask.rules.length === 0) return out;
const res = await apiPost<Resolved>("/api/notes/resolve-refs", ask);
const store = (space: RefSpace, id: number, info: Info) => {
cache.set(refKey(space, id), { at: now, info });
out.set(refKey(space, id), info);
};
for (const id of ask.notes) store("notes", id, res.notes[id] ? noteInfo(res.notes[id]) : null);
for (const id of ask.milestones) store("milestones", id, res.milestones[id] ? milestoneInfo(res.milestones[id]) : null);
for (const id of ask.rules) store("rules", id, res.rules[id] ? ruleInfo(res.rules[id]) : null);
return out;
}
function unresolvedLinks(el: HTMLElement): HTMLAnchorElement[] {
return Array.from(el.querySelectorAll<HTMLAnchorElement>("a.record-ref:not([data-ref-state])"));
}
async function decorate(el: HTMLElement) {
const links = unresolvedLinks(el);
if (!links.length) return;
const wanted = links.map((a) => ({ space: a.dataset.refSpace as RefSpace, id: Number(a.dataset.refId) }));
let resolved: Map<string, Info>;
try {
resolved = await resolveRecordRefs(wanted);
} catch {
// The links keep their provisional routes, which open the right view for
// notes, rules and milestones alike; only the titles are missing.
return;
}
for (const a of links) {
if (!a.isConnected) continue;
const info = resolved.get(refKey(a.dataset.refSpace as RefSpace, Number(a.dataset.refId)));
if (info === undefined) continue;
if (info === null) {
a.dataset.refState = "missing";
a.classList.add("record-ref--missing");
a.removeAttribute("href");
a.setAttribute("aria-disabled", "true");
a.title = `${a.textContent} — no record you can open`;
continue;
}
a.dataset.refState = "ok";
a.href = info.href;
a.title = info.label;
const bare = a.textContent;
// Drawn with its title, the link's own text is its accessible name; a bare
// number needs the label spoken for it.
if (!showTitle(a, info.title)) a.setAttribute("aria-label", `${bare}: ${info.label}`);
}
}
const clickHandlers = new WeakMap<HTMLElement, (e: MouseEvent) => void>();
function onClick(e: MouseEvent) {
const a = (e.target as HTMLElement).closest("a.record-ref") as HTMLAnchorElement | null;
if (!a) return;
if (a.dataset.refState === "missing") {
e.preventDefault();
return;
}
if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const href = a.getAttribute("href");
if (!href) return;
e.preventDefault();
router.push(href);
}
export const vRecordRefs: ObjectDirective<HTMLElement> = {
mounted(el) {
clickHandlers.set(el, onClick);
el.addEventListener("click", onClick);
void decorate(el);
},
updated(el) {
void decorate(el);
},
beforeUnmount(el) {
const h = clickHandlers.get(el);
if (h) el.removeEventListener("click", h);
clickHandlers.delete(el);
},
};
+3 -1
View File
@@ -2,7 +2,9 @@ import { Extension } from "@tiptap/core";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
const TAG_RE = /(?<=\s|^)#([\w]+(?:\/[\w]+)*)/g;
// Digits alone (`#4286`) are a record reference, not a tag, and are left plain
// here; the rendered view links them (utils/recordRefs.ts).
const TAG_RE = /(?<=\s|^)#(?!\d+(?![\w/-]))([\w]+(?:\/[\w]+)*)/g;
export const TagDecoration = Extension.create({
name: "tagDecoration",
+20
View File
@@ -123,6 +123,26 @@ const router = createRouter({
name: "project-view",
component: () => import("@/views/ProjectView.vue"),
},
{
// Where a `milestone N` reference leads. A milestone is shown on its
// project's board, so this only looks up which project and goes there.
path: "/milestones/:id",
name: "milestone",
component: () => import("@/views/ProjectListView.vue"),
beforeEnter: async (to) => {
const id = Number(to.params.id);
const { resolveRecordRefs } = await import("@/directives/recordRefs");
try {
const found = (await resolveRecordRefs([{ space: "milestones", id }])).get(`milestones:${id}`);
if (found) return found.href;
} catch {
// Fall through to the projects list with the notice below.
}
const { useToastStore } = await import("@/stores/toast");
useToastStore().show(`No milestone ${id} you can open`, "warning");
return { name: "projects" };
},
},
{
path: "/rules",
name: "rules",
+3
View File
@@ -111,6 +111,9 @@ export const useRulebooksStore = defineStore("rulebooks", () => {
// force as the same row re-fetched, or a preference the operator just
// created would sit in the list looking like a rule until a reload.
kind: rule.kind,
enforcement: rule.enforcement ?? "inform",
// Mirrors rule_brief: present only when raised or lowered.
salience: rule.salience && rule.salience !== "normal" ? rule.salience : undefined,
updated_at: rule.updated_at,
when_to_apply: rule.when_to_apply || undefined,
arose_from_id: rule.arose_from_id ?? undefined,
+7 -4
View File
@@ -1,6 +1,7 @@
import { marked, type RendererThis, type Tokens } from "marked";
import DOMPurify from "dompurify";
import { linkifyTags, linkifyWikilinks } from "@/utils/tags";
import { linkifyRecordRefs } from "@/utils/recordRefs";
function decodeEntities(text: string): string {
const textarea = document.createElement("textarea");
@@ -20,9 +21,11 @@ export function slugify(text: string): string {
export function stripFirstLineTags(text: string): string {
const match = text.match(/^[ \t]*((?:(?<!\w)#[\w]+(?:\/[\w]+)*[ \t]*)+)\n?/);
if (!match) return text;
// Verify every #-token is a tag, not a heading (headings have "# " with space)
// Verify every #-token is a tag, not a heading (headings have "# " with
// space) and not a record reference: a first line of "#4286 #4290" cites two
// records and stays in the body.
const tokens = match[1].trim().split(/\s+/);
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t));
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t) && !/^#\d+$/.test(t));
if (!allTags) return text;
return text.slice(match[0].length);
}
@@ -38,7 +41,7 @@ const headingRenderer = {
marked.use({ renderer: headingRenderer });
const PURIFY_OPTS_FULL = {
ADD_ATTR: ["data-tag", "data-title", "data-task-index"],
ADD_ATTR: ["data-tag", "data-title", "data-task-index", "data-ref-space", "data-ref-id"],
FORCE_BODY: true,
};
@@ -64,7 +67,7 @@ export function renderMarkdown(text: string, { interactiveCheckboxes = false } =
}
const withTags = linkifyTags(html);
const withLinks = linkifyWikilinks(withTags);
const withLinks = linkifyRecordRefs(linkifyWikilinks(withTags));
const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL);
// marked escapes ' to &#39; — replace after sanitization to ensure clean rendering
return sanitized.replace(/&#39;/g, "'");
+104
View File
@@ -0,0 +1,104 @@
/** Record references in rendered prose: `#N`, `milestone N`, `rule N`.
*
* Three id spaces, three forms:
* `#N` a note, task, lesson or snippet (one sequence, the notes table)
* `milestone N` a milestone — the form a batch create writes for `{{ref:milestone}}`
* `rule N` a rule; `preference N` too, since a preference is a rule
* A `#N` after a word that names another numbering ("PR #198", "rule #34",
* "step #3") is not a note, and stays plain text.
*
* The backend reads references with the same patterns and the same word list
* (src/grimoire/services/record_refs.py: REF_RE, PROSE_REF_RE, _OTHER_SPACE),
* so a backlink, a graph edge and a rendered link agree about what a body
* cites. tests/test_record_ref_links.py fails when the two differ.
*
* linkifyRecordRefs only marks the references up. What each one IS — its
* route, its title, whether the reader can open it — is filled in after render
* by the v-record-refs directive (directives/recordRefs.ts), which asks the
* server once per rendered body.
*/
export const NOTE_REF_RE = /(?<![\w&#/])#(\d+)\b/g;
export const PROSE_REF_RE = /(?<![\w/])\b(milestone|rule|preference)\s+#?(\d+)\b/gi;
export const OTHER_SPACE: readonly string[] = [
"pr", "prs", "pull", "pulls", "request", "requests", "mr", "mrs",
"run", "runs", "ci", "build", "builds", "job", "jobs", "pipeline",
"action", "actions", "commit", "github", "gitlab", "gitea", "gh",
"rule", "rules", "preference", "preferences", "milestone", "milestones",
"system", "systems", "project", "projects", "log", "logs", "topic",
"topics", "rulebook", "rulebooks", "step", "steps", "rank", "line",
"lines", "page", "item", "option", "version", "port",
];
const OTHER_SPACE_SET = new Set(OTHER_SPACE);
const PREV_WORD_RE = /([A-Za-z]+)[\s"'(\[*_:]*$/;
export type RefSpace = "notes" | "milestones" | "rules";
export interface RefMatch {
start: number;
end: number;
space: RefSpace;
id: number;
}
function prevWord(before: string): string {
const m = PREV_WORD_RE.exec(before);
return m ? m[1].toLowerCase() : "";
}
/** Every reference in a run of plain text, in order, never overlapping.
* `context` is the text that came before this run, for the word in front of
* a `#N` that starts the run. */
export function findRecordRefs(text: string, context = ""): RefMatch[] {
const found: RefMatch[] = [];
for (const m of text.matchAll(PROSE_REF_RE)) {
const space: RefSpace = m[1].toLowerCase() === "milestone" ? "milestones" : "rules";
found.push({ start: m.index!, end: m.index! + m[0].length, space, id: Number(m[2]) });
}
for (const m of text.matchAll(NOTE_REF_RE)) {
const start = m.index!;
const end = start + m[0].length;
if (found.some((f) => start < f.end && end > f.start)) continue;
if (OTHER_SPACE_SET.has(prevWord(context + text.slice(0, start)))) continue;
found.push({ start, end, space: "notes", id: Number(m[1]) });
}
return found.sort((a, b) => a.start - b.start);
}
/** Where a reference opens before the server has said what it is. A note id
* may turn out to be a task, lesson or snippet; the directive corrects it. */
export function provisionalHref(space: RefSpace, id: number): string {
if (space === "milestones") return `/milestones/${id}`;
if (space === "rules") return `/rules?rule=${id}`;
return `/notes/${id}`;
}
// Markup a reference is never drawn inside: an existing link (a wikilink, a
// markdown link, a tag chip), code, and the tags themselves.
const SKIP_RE = /(<a\b[\s\S]*?<\/a>|<code[\s\S]*?<\/code>|<pre[\s\S]*?<\/pre>|<[^>]+>)/gi;
/** Wrap each record reference in rendered HTML in an `a.record-ref`. */
export function linkifyRecordRefs(html: string): string {
const parts = html.split(SKIP_RE);
let context = "";
return parts
.map((part, i) => {
// Odd indices are markup the split kept; text between them is even.
if (i % 2 === 1) return part;
const refs = findRecordRefs(part, context);
context = (context + part).slice(-80);
if (!refs.length) return part;
let out = "";
let at = 0;
for (const r of refs) {
out += part.slice(at, r.start);
const label = part.slice(r.start, r.end);
out += `<a class="record-ref" data-ref-space="${r.space}" data-ref-id="${r.id}" href="${provisionalHref(r.space, r.id)}">${label}</a>`;
at = r.end;
}
return out + part.slice(at);
})
.join("");
}
+5 -1
View File
@@ -1,5 +1,9 @@
const CODE_FENCE_RE = /```[\s\S]*?```|`[^`\n]+`/g;
const TAG_RE = /(?<!\w)(?<!&)#([\w][\w-]*(?:\/[\w][\w-]*)*)/g;
// A `#` token made only of digits is a record reference (`#3127` names a note,
// task, lesson or snippet; utils/recordRefs.ts links it), never a tag. Digits
// followed by more of a tag (`#2fa`, `#123-notes`) is still a tag. The backend's
// src/grimoire/utils/tags.py holds the same pattern.
export const TAG_RE = /(?<!\w)(?<!&)#(?!\d+(?![\w/-]))([\w][\w-]*(?:\/[\w][\w-]*)*)/g;
function escapeHtmlAttr(s: string): string {
return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+11 -7
View File
@@ -8,6 +8,7 @@ import { drag } from "d3-drag";
import { select } from "d3-selection";
import { apiGet } from "@/api/client";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
const router = useRouter();
@@ -26,7 +27,8 @@ interface GraphNode extends SimulationNodeDatum {
interface GraphEdge {
source: number | string | GraphNode;
target: number | string | GraphNode;
type: "wikilink" | "tag";
/** wikilink: `[[title]]`; reference: a `#N` citation; tag: a shared tag. */
type: "wikilink" | "reference" | "tag";
}
interface Project {
@@ -237,12 +239,14 @@ function initGraph() {
.append("line")
.attr("class", "graph-edge")
.attr("stroke", (d: any) =>
d.type === "wikilink" ? "var(--fs-accent)" : "var(--fs-text-tertiary)"
d.type === "tag" ? "var(--fs-text-tertiary)" : "var(--fs-accent)"
)
.attr("stroke-opacity", (d: any) => (d.type === "wikilink" ? 0.5 : 0.4))
.attr("stroke-dasharray", null)
.attr("stroke-width", (d: any) => (d.type === "wikilink" ? 1.5 : 1))
.attr("marker-end", (d: any) => (d.type === "wikilink" ? "url(#arrow)" : null));
.attr("stroke-opacity", (d: any) => (d.type === "tag" ? 0.4 : 0.5))
// A citation is a looser link than a wikilink: same colour and direction,
// drawn dashed so the two read apart.
.attr("stroke-dasharray", (d: any) => (d.type === "reference" ? "4 3" : null))
.attr("stroke-width", (d: any) => (d.type === "tag" ? 1 : 1.5))
.attr("marker-end", (d: any) => (d.type === "tag" ? null : "url(#arrow)"));
// Node groups
const nodeSel = zoomG
@@ -559,7 +563,7 @@ onUnmounted(() => {
<div
v-else-if="peekBody"
class="prose peek-prose"
v-html="renderMarkdown(peekBody)"
v-html="renderMarkdown(peekBody)" v-record-refs
/>
<div v-else class="peek-empty">No content.</div>
</div>
+7 -72
View File
@@ -30,7 +30,6 @@ import { apiErrorMessage } from "@/api/client";
import {
deleteLesson,
getLesson,
judgeLessonLink,
type Lesson,
type LessonRuleLink,
} from "@/api/lessons";
@@ -40,8 +39,10 @@ import UsageBadge from "@/components/UsageBadge.vue";
import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown";
import { canWriteRecord } from "@/utils/permission";
import { vRecordRefs } from "@/directives/recordRefs";
import { recordHref } from "@/utils/recordHref";
import { canWriteRecord } from "@/utils/permission";
import LessonSituationsPanel from "@/components/LessonSituationsPanel.vue";
const route = useRoute();
const router = useRouter();
@@ -64,13 +65,10 @@ const insightHtml = computed(() =>
const canWrite = computed(() => canWriteRecord(lesson.value?.permission));
/** The links by state — each state reads differently. Confirmed links are
* the answer; suggested ones are evidence waiting on a judgment; rejected
* ones are kept so the pair is never proposed again, and shown so the reason
* stays readable. */
* the answer; rejected ones are kept so the reason stays readable. */
const linksIn = (state: LessonRuleLink["state"]) =>
computed(() => (lesson.value?.rules ?? []).filter((r) => r.state === state));
const confirmedRules = linksIn("confirmed");
const suggestedRules = linksIn("suggested");
const rejectedRules = linksIn("rejected");
/** A rule opens in the rules view's editor, which takes the rule alone. */
@@ -78,36 +76,6 @@ function ruleHref(ruleId: number) {
return { path: "/rules", query: { rule: String(ruleId) } };
}
/** What a suggestion rests on, in the units it was proposed by: distinct
* situations, not raw arrivals — one situation repeated proves nothing. */
function evidenceLine(ev: NonNullable<LessonRuleLink["evidence"]>): string {
const situations = `${ev.situations} distinct situation${ev.situations === 1 ? "" : "s"}`;
const projects = ev.projects > 1 ? `, across ${ev.projects} projects` : "";
return `Arrived together in ${situations}${projects}.`;
}
const judging = ref<number | null>(null);
/** Judge a suggested link from here. Re-reads the lesson rather than editing
* the list in place: confirming also clears a "no rule fits" answer, and the
* judgment line has to come back from the server to be right. */
async function judge(rule: LessonRuleLink, verdict: "confirm" | "reject") {
judging.value = rule.id;
try {
await judgeLessonLink(lessonId.value, rule.id, verdict);
lesson.value = await getLesson(lessonId.value);
toast.show(
verdict === "confirm"
? "Linked — the rule can now surface through this lesson"
: "Not an instance — this pair will not be suggested again",
);
} catch (e) {
toast.show(apiErrorMessage(e, "Failed to record the judgment"), "error");
} finally {
judging.value = null;
}
}
async function load() {
loading.value = true;
error.value = null;
@@ -171,7 +139,7 @@ onMounted(load);
<div
v-if="insightHtml"
class="ld-insight markdown-body"
v-html="insightHtml"
v-html="insightHtml" v-record-refs
/>
<p v-else class="ld-muted ld-empty">
No detail was recorded — the claim above is the whole lesson.
@@ -222,39 +190,6 @@ onMounted(load);
nobody has said none fits.
</p>
<template v-if="suggestedRules.length">
<h3 class="ld-sub-label">Suggested</h3>
<ul class="ld-sources">
<li v-for="r in suggestedRules" :key="r.id">
<router-link :to="ruleHref(r.id)" class="ld-link">
{{ r.title }}
</router-link>
<span v-if="r.kind === 'preference'" class="rule-chip rule-chip-preference">
preference
</span>
<p v-if="r.evidence" class="ld-link-note">{{ evidenceLine(r.evidence) }}</p>
<div v-if="canWrite" class="ld-judge">
<button
type="button"
class="ld-ghost ld-small"
:disabled="judging === r.id"
@click="judge(r, 'confirm')"
>
Confirm
</button>
<button
type="button"
class="ld-ghost ld-small"
:disabled="judging === r.id"
@click="judge(r, 'reject')"
>
Not an instance
</button>
</div>
</li>
</ul>
</template>
<template v-if="rejectedRules.length">
<h3 class="ld-sub-label">Judged not an instance</h3>
<ul class="ld-sources ld-rejected">
@@ -268,6 +203,8 @@ onMounted(load);
</template>
</section>
<LessonSituationsPanel :lesson-id="lesson.id" :can-write="canWrite" />
<section v-if="lesson.tags?.length" class="ld-tags">
<TagPill v-for="t in lesson.tags" :key="t" :tag="t" />
</section>
@@ -409,8 +346,6 @@ onMounted(load);
color: var(--fs-text-tertiary);
}
.ld-rejected .ld-link { color: var(--fs-text-secondary); }
.ld-judge { display: flex; gap: var(--fs-space-2); margin-top: var(--fs-space-1); }
.ld-small { padding: 0.15rem 0.6rem; font-size: var(--fs-size-label); }
.ld-ghost:disabled { opacity: var(--fs-disabled-opacity); cursor: default; }
.ld-tags { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 1.25rem; }
+2 -1
View File
@@ -5,6 +5,7 @@ import type { NoteType } from "@/types/note";
import { useNotesStore } from "@/stores/notes";
import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { useAssist, type NoteDraft } from "@/composables/useAssist";
import { useAutoSave } from "@/composables/useAutoSave";
import { useEditorGuards } from "@/composables/useEditorGuards";
@@ -439,7 +440,7 @@ onUnmounted(() => assist.clearSelection());
<div
v-else
class="preview-pane prose"
v-html="renderedPreview"
v-html="renderedPreview" v-record-refs
/>
</Transition>
</template>
+11 -3
View File
@@ -3,6 +3,8 @@ import { onMounted, computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useNotesStore } from "@/stores/notes";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { recordHref } from "@/utils/recordHref";
import { relativeTime } from "@/composables/useRelativeTime";
import { apiPost, apiGet, apiPatch } from "@/api/client";
import type { Note } from "@/types/note";
@@ -14,7 +16,12 @@ import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next";
const route = useRoute();
const router = useRouter();
const store = useNotesStore();
const backlinks = ref<{ type: string; id: number; title: string }[]>([]);
/** What links here, and how: a `[[title]]` wikilink or a `#N` reference in a
* body or work log. */
const backlinks = ref<{
type: string; id: number; title: string;
is_task?: boolean; note_type?: string; via?: "wikilink" | "reference";
}[]>([]);
const converting = ref(false);
const showShare = ref(false);
@@ -259,7 +266,7 @@ async function convertToTask() {
<div
class="body prose"
:class="{ 'prose--checklist': isListNote }"
v-html="renderedBody"
v-html="renderedBody" v-record-refs
@click="onBodyClick"
@change="onBodyChange"
></div>
@@ -274,7 +281,8 @@ async function convertToTask() {
<router-link
v-for="link in backlinks"
:key="`${link.type}-${link.id}`"
:to="`/${link.type === 'note' ? 'notes' : 'tasks'}/${link.id}`"
:to="recordHref({ id: link.id, is_task: link.is_task ?? link.type === 'task', note_type: link.note_type })"
:title="link.via === 'reference' ? `Cites #${noteId} in its text` : `Links here by title`"
class="backlink-card"
>
<span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
+55 -4
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ref, computed, onMounted, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client";
import { useAuthStore } from "@/stores/auth";
@@ -7,6 +7,7 @@ import { useToastStore } from "@/stores/toast";
import { useTasksStore } from "@/stores/tasks";
import { relativeTime } from "@/composables/useRelativeTime";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import ShareDialog from "@/components/ShareDialog.vue";
import KindBadge from "@/components/KindBadge.vue";
import ProjectStatusBadge from "@/components/ProjectStatusBadge.vue";
@@ -17,6 +18,7 @@ import { canWriteRecord } from "@/utils/permission";
import ProjectRulesTab from "@/components/rules/ProjectRulesTab.vue";
import SystemsSection from "@/components/SystemsSection.vue";
import InceptionCard from "@/components/InceptionCard.vue";
import TestGuardReview from "@/components/TestGuardReview.vue";
import { fmtDate } from "@/utils/dateFormat";
import type { InceptionDecision, InceptionRecord } from "@/api/inception";
import {
@@ -497,6 +499,10 @@ interface Coverage {
divergent?: number;
divergence?: Divergence[];
recheck?: number;
// Same-guard test groups awaiting a verdict (TestGuardReview).
test_groups?: number;
// The suite by what it protects.
tests?: { linked: number; unlinked: number; redundant: number } | null;
}
interface Divergence {
path: string;
@@ -585,8 +591,27 @@ async function saveForgePin() {
}
}
/** `?milestone=N` opens the board at that milestone: the Tasks tab, the
* milestone expanded and scrolled into view, its header focused. This is
* where a `milestone N` reference in any body leads. */
async function focusMilestoneFromRoute() {
const id = Number(route.query.milestone);
if (!id || !milestones.value.some((m) => m.id === id)) return;
activeTab.value = "tasks";
collapsedMilestones.value.delete(id);
await nextTick();
const header = document.querySelector<HTMLElement>(
`[data-milestone-id="${id}"] .milestone-header`,
);
header?.scrollIntoView({ block: "start", behavior: "smooth" });
header?.focus({ preventScroll: true });
}
watch(() => route.query.milestone, () => void focusMilestoneFromRoute());
onMounted(async () => {
await loadProject();
void focusMilestoneFromRoute();
loadTasks();
loadNotes();
loadDesignSystems();
@@ -814,7 +839,7 @@ async function confirmDelete() {
</div>
<div v-if="coverage.counts" class="coverage-gaps">
<span
v-for="k in ['canonical', 'instance', 'variant', 'exempt', 'scoped']"
v-for="k in ['canonical', 'instance', 'variant', 'exempt', 'redundant', 'unused', 'scoped', 'test']"
:key="k"
>
<span v-if="coverage.counts[k]" class="coverage-gap-chip">
@@ -868,6 +893,26 @@ async function confirmDelete() {
{{ coverage.recheck }} to recheck
</span>
</div>
<div
v-if="coverage.tests && (coverage.tests.linked || coverage.tests.unlinked || coverage.tests.redundant)"
class="coverage-gaps"
title="Each test case is linked to the code it exercises. Linked tests are accounted for by what they guard; a test linked to nothing is in the todo until someone says what it protects."
>
<span class="coverage-gaps-label">Tests:</span>
<span class="coverage-gap-chip">{{ coverage.tests.linked }} linked</span>
<span v-if="coverage.tests.unlinked" class="coverage-gap-chip">
{{ coverage.tests.unlinked }} guarding nothing found
</span>
<span v-if="coverage.tests.redundant" class="coverage-gap-chip">
{{ coverage.tests.redundant }} redundant
</span>
</div>
<TestGuardReview
v-if="coverage.test_groups"
:project-id="projectId"
:can-write="!!project && canWriteRecord(project.permission)"
@changed="loadCoverage"
/>
</template>
<p v-else class="coverage-empty">
Not measured yet — Refresh reads the bound repo's definitions into
@@ -985,9 +1030,15 @@ async function confirmDelete() {
</div>
</div>
<div v-for="group in milestoneGroups" :key="group.milestone?.id ?? 'unassigned'" class="milestone-group">
<div
v-for="group in milestoneGroups"
:key="group.milestone?.id ?? 'unassigned'"
class="milestone-group"
:data-milestone-id="group.milestone?.id"
>
<div
class="milestone-header"
tabindex="-1"
:class="{ clickable: renamingMilestoneId !== group.milestone?.id }"
:aria-expanded="!collapsedMilestones.has(groupKey(group))"
@click="renamingMilestoneId !== group.milestone?.id && toggleMilestoneCollapse(groupKey(group))"
@@ -1050,7 +1101,7 @@ async function confirmDelete() {
:class="['ms-plan-rendered', 'markdown-body',
{ 'ms-plan-clamped': isPlanClamped(group.milestone) }]"
@click="startEditPlan(group.milestone.id, group.milestone.body)"
v-html="renderMarkdown(group.milestone.body || '')"
v-html="renderMarkdown(group.milestone.body || '')" v-record-refs
></div>
<button
v-if="isPlanLong(group.milestone)"
+110 -1
View File
@@ -172,6 +172,42 @@ const kbReplyRuleThreshold = ref("0.8");
// is raising its bar, which discards the surface's best candidates along with
// its worst. A budget keeps the top of the ranking and drops the tail.
const kbWritePathTopK = ref("3");
// The most one hook call may inject, in characters (hook_payload.DEFAULT_BUDGET).
const kbHookBudget = ref("4500");
// How often a record found by resemblance alone may speak, as a percent of
// cues that match nothing in particular (cue_gate.RATE_DEFAULT).
const kbCueGateRate = ref("10");
// GatedSurface — one row of /api/retrieval/gate.
interface GatedSurface {
surface: string;
gates: string;
bar: number | null;
sample: number;
calls: number;
fired: number;
days: number;
unreadable?: boolean;
}
const gatedSurfaces = ref<GatedSurface[]>([]);
const gateMinSample = ref(20);
function gateSummary(g: GatedSurface): string {
if (g.unreadable) return "unreadable right now";
const spoke = g.calls ? `spoke on ${g.fired} of ${g.calls} calls in ${g.days} days` : "no gated calls yet";
if (g.bar === null) return `learning (${g.sample} of ${gateMinSample.value} cues), silent until then; ${spoke}`;
return `bar ${g.bar.toFixed(2)} from your last ${g.sample} cues; ${spoke}`;
}
async function loadGate() {
try {
const res = await apiGet<{ surfaces: GatedSurface[]; min_sample: number }>("/api/retrieval/gate");
gatedSurfaces.value = res.surfaces ?? [];
gateMinSample.value = res.min_sample ?? 20;
} catch {
gatedSurfaces.value = [];
}
}
const kbRuleHintTopK = ref("5");
const kbToolRuleTopK = ref("5");
const kbPromptRuleTopK = ref("3");
@@ -385,6 +421,13 @@ async function saveKbInject() {
const prK = asK(kbPromptRuleTopK.value, 3);
const ryK = asK(kbReplyRuleTopK.value, 1);
kbWritePathTopK.value = String(wpK);
// Clamped as the server clamps it (hook_payload.HARD_MAX): Claude Code shows
// a hook's context past its cap only as a short preview.
const budget = Math.min(7500, Math.max(1000, Math.floor(Number(kbHookBudget.value) || 4500)));
kbHookBudget.value = String(budget);
// Clamped as the server clamps it (cue_gate.RATE_MIN / RATE_MAX).
const gateRate = Math.min(50, Math.max(1, Math.floor(Number(kbCueGateRate.value) || 10)));
kbCueGateRate.value = String(gateRate);
kbRuleHintTopK.value = String(rhK);
kbToolRuleTopK.value = String(trK);
kbPromptRuleTopK.value = String(prK);
@@ -433,6 +476,8 @@ async function saveKbInject() {
// change the OPERATOR made — which is the one entry the model must not
// quietly tune back.
kb_writepath_top_k: String(wpK),
kb_hook_budget_chars: String(budget),
kb_cue_gate_rate: String(gateRate),
kb_rulehint_top_k: String(rhK),
kb_toolrule_top_k: String(trK),
kb_promptrule_top_k: String(prK),
@@ -454,6 +499,7 @@ async function saveKbInject() {
// the operator is looking at it to confirm.
await loadTuningHistory();
await loadSurfaces();
await loadGate();
} catch {
toastStore.show('Failed to save auto-inject settings', 'error');
} finally {
@@ -857,6 +903,12 @@ onMounted(async () => {
if (allSettings.kb_writepath_threshold !== undefined) {
kbWritePathThreshold.value = allSettings.kb_writepath_threshold;
}
if (allSettings.kb_hook_budget_chars !== undefined) {
kbHookBudget.value = allSettings.kb_hook_budget_chars;
}
if (allSettings.kb_cue_gate_rate !== undefined) {
kbCueGateRate.value = allSettings.kb_cue_gate_rate;
}
if (allSettings.kb_writepath_top_k !== undefined) {
kbWritePathTopK.value = allSettings.kb_writepath_top_k;
} else if (allSettings.kb_autoinject_top_k !== undefined) {
@@ -879,6 +931,7 @@ onMounted(async () => {
}
await loadTuningHistory();
await loadSurfaces();
await loadGate();
if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
}
@@ -1654,7 +1707,7 @@ async function deleteUser(userId: number) {
class="fs-input input"
style="max-width: 8rem"
/>
<p class="field-hint">Ceiling on titles surfaced at once (1–10).</p>
<p class="field-hint">How many records each prompt is ranked against (1–10); at most two are shown, and only past the resemblance gate below.</p>
</div>
<div class="checkbox-field">
<label>
@@ -1695,6 +1748,45 @@ async function deleteUser(userId: number) {
location, not by resemblance.
</p>
</div>
<div class="field">
<label for="kb-hook-budget">Most context one hook may add (characters)</label>
<input
id="kb-hook-budget"
v-model="kbHookBudget"
type="number"
min="1000"
max="7500"
step="500"
class="fs-input input"
style="max-width: 8rem"
/>
<p class="field-hint">Everything Grimoire adds beside one prompt, edit or command, from 1,000 to 7,500 characters. Rules go in first, then the reply shape, then records, until this is spent; whatever is left out can arrive on a later call. Claude Code shows a hook's context past its cap only as a short preview, so the ceiling stays well under it.</p>
</div>
<div class="field">
<label for="kb-cue-gate-rate">How often records found by resemblance may speak (%)</label>
<input
id="kb-cue-gate-rate"
v-model="kbCueGateRate"
type="number"
min="1"
max="50"
step="1"
class="fs-input input"
style="max-width: 8rem"
/>
<p class="field-hint">
A record or preference matched only by wording is shown when the message
resembles it better than all but this share of your recent messages did:
at most two lines, and none until {{ gateMinSample }} messages have been seen.
</p>
<ul v-if="gatedSurfaces.length" class="gate-readout">
<li v-for="g in gatedSurfaces" :key="g.surface">
<span class="tuning-surface">{{ g.surface }}</span>
<span class="gate-gates">{{ g.gates }}</span>
<span class="gate-state">{{ gateSummary(g) }}</span>
</li>
</ul>
</div>
<div class="field">
<label for="kb-writepath-topk">Max prior-art lines per edit</label>
<input
@@ -4258,6 +4350,23 @@ async function deleteUser(userId: number) {
font-family: var(--fs-font-mono);
color: var(--fs-text-primary);
}
.gate-readout {
list-style: none;
margin: var(--fs-space-2) 0 0;
padding: 0;
display: grid;
gap: var(--fs-space-1);
font-size: 0.8rem;
}
.gate-readout li {
display: flex;
flex-wrap: wrap;
gap: var(--fs-space-2);
}
.gate-gates,
.gate-state {
color: var(--fs-text-secondary);
}
.tuning-dial,
.tuning-move {
color: var(--fs-text-secondary);
+2 -1
View File
@@ -10,6 +10,7 @@ import {
import { useToastStore } from "@/stores/toast";
import ConfirmDialog from "@/components/ConfirmDialog.vue";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { canWriteRecord } from "@/utils/permission";
const route = useRoute();
@@ -185,7 +186,7 @@ async function confirmDelete() {
<section v-if="snippet.snippet.notes" class="notes">
<h2 class="notes-heading">Notes</h2>
<div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" />
<div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" v-record-refs />
</section>
<div v-if="snippet.tags.length" class="tag-row">
+2 -1
View File
@@ -5,6 +5,7 @@ import { useTasksStore } from "@/stores/tasks";
import { useNotesStore } from "@/stores/notes";
import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { useAssist } from "@/composables/useAssist";
import { useAutoSave } from "@/composables/useAutoSave";
import { useEditorGuards } from "@/composables/useEditorGuards";
@@ -538,7 +539,7 @@ useEditorGuards(dirty, save);
<div
v-show="showPreview"
class="preview-pane prose"
v-html="renderedPreview"
v-html="renderedPreview" v-record-refs
/>
</template>
+3 -3
View File
@@ -1,11 +1,11 @@
{
"name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.11.05.0301",
"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, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.12.01.0748",
"author": {
"name": "Bryan Van Deusen"
},
"license": "AGPL-3.0-only",
"license": "MIT",
"mcpServers": {
"grimoire": {
"type": "http",
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Bryan Van Deusen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+8 -7
View File
@@ -14,8 +14,8 @@ another one means adding files, not moving or rewriting any.
| Piece | Where | What it is |
|---|---|---|
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule or — when the turn closed a task — for missing completion sections). |
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — only what no response or skill delivers: enter the project, ask before a consequential act, search before building, the force of each record kind (≤800 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). |
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
## Added by each client
@@ -38,11 +38,12 @@ another one means adding files, not moving or rewriting any.
| `hooks/grimoire_autoinject.sh` | UserPromptSubmit: `GET /api/plugin/retrieve` for the message. |
| `hooks/grimoire_prior_art.sh` | PreToolUse on editor writes: `GET /api/plugin/prior-art`. |
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
| `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason; PostToolUse on `enter_project` remembers the project a session without one entered. |
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). |
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. |
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check`; blocks once, with the reason the server returns, so the agent judges what it built. |
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`; denies the call on its `checkpoint`, under the same caps, and reports it to `POST /api/plugin/gate-stop`. |
| `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason, and each ask reported to `POST /api/plugin/gate-stop` with the tool call's id; PostToolUse on `enter_project` remembers the project a session without one entered. |
| `hooks/grimoire_fence_ran.sh` | PostToolUse on the tools the fence checks: when the call that ran is the one the fence asked about, `POST /api/plugin/gate-ran`, the operator's yes. Exits at once when no ask is pending. |
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session), and reports each stop, and each hold the session's budget let through, to `POST /api/plugin/gate-stop`. |
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite; reports each rule that held to `POST /api/plugin/gate-stop`. |
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check` and keeps the `note` it returns for the next prompt, which `grimoire_autoinject.sh` carries as `carry`, so the agent judges what it built. Never blocks. |
| `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. |
| `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
| `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. |
+13 -8
View File
@@ -17,7 +17,8 @@ instance into a first-class Claude Code extension:
any client's package would ship: using-grimoire, writing-plans, reporting-back
(reply to the operator in a shape that says where the work stands),
systematic-debugging, verification, brainstorming, reusing-code (record and
recall reusable code as snippets), shape-accounting and family-canon.
recall reusable code as snippets), shape-accounting, family-canon and
reviewing-tests (give every test one verdict and prove the survivors fail).
Replaces superpowers.
- **Your Grimoire Processes as skills** — saved Processes are synced into local
`~/.claude/skills/grimoire-proc-*` stubs that auto-surface by relevance; the
@@ -97,7 +98,9 @@ On install you'll be asked for:
→ `POST /api/plugin/moment`: the rules mounted on the moments the call
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
nothing mounted, and Grimoire's own tools, whose responses carry
`moment_rules`.
`moment_rules`. A rule set to enforce refuses the call (every time it is
reached); one set to hold denies it once until it has been read, never on a
file edit.
- `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`,
`rule_outcome`, `update_task` and `add_task_log`: they keep the session's
ledgers of rules opened and acted on (`get_rule` also reports to
@@ -115,7 +118,8 @@ On install you'll be asked for:
duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`.
- `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the
reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it
once for an unopened rule mounted on the reply moments or matching the reply.
once for an unopened rule set to hold (or enforce) that is mounted on the
reply moments or matches the reply. A rule set to inform never holds it.
When the turn closed a Grimoire task (`update_task`/`create_task` with status
done), the same request has the server check the reply for the completion
sections — where the work sits, what needs you, what comes next. If they are
@@ -127,11 +131,12 @@ On install you'll be asked for:
write hooks note every definition a write names (and every new file) in a
session ledger; at the end of the turn this sends them to
`GET /api/plugin/shape-check`, which answers with the ones nobody has judged.
If any are, it blocks once with the server's reason, asking the agent that
wrote them to say what each is — reusable (record a snippet), an instance or
variant of one, or a one-off — in one `classify_shapes` call. Same discipline
as the report check: never twice, never without a recorded check. Outcomes
land under category `plugin`, action `shape_check`.
If any are, the server's note rides the next prompt (the prompt hook sends it
as `carry`), asking the agent that wrote them to say what each is — reusable
(record a snippet), an instance or variant of one, or a one-off — in one
`classify_shapes` call. It never holds the reply; the stop after that prompt
records whether the lines were judged. Outcomes land under category
`plugin`, action `shape_check`.
- `skills/` → the universal process-skills, surfaced by description match.
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
+1
View File
@@ -191,6 +191,7 @@ while IFS= read -r rel_path; do
reached=1
body=$(curl -fsS --max-time 8 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
# A call that was owed and didn't come back is said, once per outage —
# shared marker with the pre-write hook, so one outage is one
+18 -1
View File
@@ -125,6 +125,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown.
exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
exclude_q="${exclude_q}&session_id=${safe_sid}"
# Which reply shapes it already holds in full: the core is
# sent whole once, and as its one-line reminder on every later turn.
shapefile=$(grimoire_shapes_file "$safe_sid")
@@ -132,10 +134,25 @@ if [ -n "$session_id" ]; then
[ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}"
fi
# What the last stop left for this prompt: the definitions its turn wrote
# that nobody has judged (grimoire_shape_check.sh). Carried to the server, which
# fits it into the one payload, and removed once the server has answered.
carry_q=""
carry_file=""
if [ -n "$session_id" ]; then
carry_file="${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}.note"
if [ -s "$carry_file" ]; then
carry_enc=$(head -c 2000 "$carry_file" 2>/dev/null | grimoire_urlenc) || carry_enc=""
[ -n "$carry_enc" ] && carry_q="&carry=${carry_enc}"
fi
fi
body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}" 2>/dev/null) || exit 0
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0
[ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
context=$(grimoire_json_pick "$body_flat" '.context')
+1
View File
@@ -41,6 +41,7 @@ task_id=$(printf '%s' "$task_id" | tr -cd '0-9')
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \
>/dev/null 2>&1 || true
exit 0
+54
View File
@@ -868,6 +868,14 @@ grimoire_config() {
# garbage Bearer token and 401. Treat it as unset.
case "$url" in *'${'*) url="" ;; esac
case "$token" in *'${'*) token="" ;; esac
# Sent as `X-Grimoire-Plugin` on every request. The server keeps it on each
# rule line it delivers, and counts a line toward a rule's open rate only
# when it is there: a plugin that sends it also reports every open, so a
# line without it is one whose opens were never going to be heard. The hooks
# that source this file read it, which shellcheck cannot see from here.
# shellcheck disable=SC2034
plugin_version=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' \
"$(dirname "${BASH_SOURCE[0]}")/../.claude-plugin/plugin.json" 2>/dev/null | head -n 1)
[ -n "$url" ] && [ -n "$token" ]
}
@@ -1073,6 +1081,52 @@ grimoire_checkpoint_allowed() {
return 0
}
grimoire_gate_report() {
# $1 session id, $2 gate (enforce|hold|checkpoint|fence), $3 outcome
# (stopped|let_through|asked), $4 tool name, $5 rule id or "", $6 where the
# rule was reached (a moment or an arm) or "", $7 the target project or "",
# $8 the tool call's id or "".
#
# Tells the server a gate stood in front of this call. The hook reports it,
# not the server, because whether a hold actually stops is decided here, by
# `grimoire_checkpoint_allowed`'s caps. Needs `url`, `token` and
# `plugin_version` from grimoire_config. Short deadline and silent: it runs
# only on a stop, and a stop the server never heard of costs one row, while
# a hook that hangs costs the call it was deciding.
local sid="${1:-}" gate="${2:-}" outcome="${3:-}" tool="${4:-}" rule rest="" v pair
[ -n "$sid" ] && [ -n "$gate" ] && [ -n "$outcome" ] && [ -n "$tool" ] || return 0
[ -n "${url:-}" ] && [ -n "${token:-}" ] || return 0
command -v curl >/dev/null 2>&1 || return 0
rule=$(printf '%s' "${5:-}" | tr -cd '0-9')
for pair in "at=${6:-}" "target=${7:-}" "call_id=${8:-}"; do
v=${pair#*=}
[ -n "$v" ] || continue
rest="${rest},\"${pair%%=*}\":\"$(printf '%s' "$v" | grimoire_json_escape)\""
done
printf '{"session_id":"%s","gate":"%s","outcome":"%s","tool":"%s","rule_id":%s%s}' \
"$(printf '%s' "$sid" | grimoire_json_escape)" "$gate" "$outcome" \
"$(printf '%s' "$tool" | grimoire_json_escape)" "${rule:-null}" "$rest" \
| curl -fsS --max-time 2 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/gate-stop" >/dev/null 2>&1 || true
return 0
}
grimoire_checkpoint_spent() {
# $1 ledger file, $2 rule id. True when `grimoire_checkpoint_allowed` just
# refused because the SESSION's budget is spent, as against this rule
# having held an act already. Only the first is a call the cap let through;
# the second is the per-rule once, working as meant.
local f="$1" id
id=$(printf '%s' "${2:-}" | tr -cd '0-9')
[ -n "$f" ] && [ -n "$id" ] && [ -f "$f" ] || return 1
grep -qx "$id" "$f" 2>/dev/null && return 1
return 0
}
grimoire_json_deny() {
# $1 hook event name, $2 the reason the agent reads INSTEAD of the result.
#
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Grimoire — the operator's answer to a project fence ask, read from what ran.
#
# grimoire_project_fence.sh asks the operator before an act lands in another
# project, reports the ask to the server, and leaves the tool call's id in
# `grimoire-fence/<sid>.fence.pending`. The answer itself never reaches a
# hook, but Claude Code sends PostToolUse only for a call that ran. So when
# this fires for the pending call, the operator said yes, and the server is
# told (POST /api/plugin/gate-ran). An ask that is never followed by this was
# declined, or the call failed.
#
# Registered PostToolUse on the tools the fence checks. Nearly every call has
# no ask pending, so the first thing it does is look for a pending file, and
# with none it exits before reading the event.
#
# EXIT 0, ALWAYS, and silent: it decorates a record.
set -uo pipefail
fence_dir="${TMPDIR:-/tmp}/grimoire-fence"
pending=""
for pending in "$fence_dir"/*.fence.pending; do
[ -e "$pending" ] && break
done
[ -e "$pending" ] || exit 0
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
event=$(cat 2>/dev/null || true)
[ -n "$event" ] || exit 0
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
[ -n "$session_id" ] && [ -n "$call_id" ] || exit 0
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
pending_file="$fence_dir/${safe_sid}.fence.pending"
[ -s "$pending_file" ] || exit 0
[ "$(cat "$pending_file" 2>/dev/null)" = "$call_id" ] || exit 0
rm -f "$pending_file" 2>/dev/null || true
grimoire_config || exit 0
command -v curl >/dev/null 2>&1 || exit 0
printf '{"session_id":"%s","call_id":"%s"}' \
"$(printf '%s' "$session_id" | grimoire_json_escape)" \
"$(printf '%s' "$call_id" | grimoire_json_escape)" \
| curl -fsS --max-time 2 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/gate-ran" >/dev/null 2>&1 || true
exit 0
+43 -1
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the
# moment happens.
# moment happens — beside the act, or, for a rule set to enforce or hold, in
# front of it.
#
# The other PreToolUse arms search: they turn the act into a query and hope a
# rule's words resemble it. A mount needs no resemblance. The operator said
@@ -100,6 +101,7 @@ case "$stamp" in ''|*[!0-9]*) stamp=0 ;; esac
if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then
listed=$(curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed=""
{
printf '%s\n' "$now"
@@ -140,6 +142,7 @@ query="${repo_q}${ledger_q}"
query=${query#&}
body=$(printf '%s' "$event" | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0
@@ -148,6 +151,45 @@ body_flat=$(printf '%s' "$body" | grimoire_json_flat)
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile"
# ── The act itself: refused, held for one read, or let through ───────────
#
# The server decides and supplies the words (`decision`); this hook only
# carries them. A rule set to ENFORCE refuses the call every time it is
# reached — the operator drew that line, and it moves when they change the
# rule, not when the agent has read it. A rule set to HOLD asks for one read
# before the act, once per rule and under the session cap that the act
# checkpoint and the reply hold share, so a mis-set rule costs one round trip
# rather than a session that cannot move.
#
# Every stop is reported (`grimoire_gate_report`), and so is a hold the
# session's budget let through, so how often each gate stops work, and
# whether the cap is what lets calls past, can be read on the server.
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
d_at=$(grimoire_json_pick "$body_flat" '.decision.at')
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
if [ -n "$d_reason" ]; then
case "$d_kind" in
enforce)
grimoire_json_deny PreToolUse "$d_reason"
grimoire_gate_report "$session_id" enforce stopped "$tool_key" "$d_rule" "$d_at" "" "$call_id"
exit 0
;;
hold)
stops="$state_dir/${safe_sid}.checkpoint.ids"
if [ -n "$d_rule" ] && grimoire_checkpoint_allowed "$stops" "$d_rule"; then
grimoire_json_deny PreToolUse "$d_reason"
grimoire_gate_report "$session_id" hold stopped "$tool_key" "$d_rule" "$d_at" "" "$call_id"
exit 0
fi
if [ -n "$d_rule" ] && grimoire_checkpoint_spent "$stops" "$d_rule"; then
grimoire_gate_report "$session_id" hold let_through "$tool_key" "$d_rule" "$d_at" "" "$call_id"
fi
;;
esac
fi
context=$(grimoire_json_pick "$body_flat" '.context')
[ -n "$context" ] || exit 0
grimoire_json_out PreToolUse "$context"
+3
View File
@@ -240,6 +240,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
fi
# Not `|| exit 0`: an unreachable instance must not discard a local finding
@@ -249,6 +251,7 @@ fi
reached=1
body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
unreached_context=""
if [ "$reached" = 1 ]; then
+19 -1
View File
@@ -34,6 +34,12 @@
#
# Run as PostToolUse on enter_project, it records the project a session
# without one has entered, and says nothing.
#
# EVERY ASK IS REPORTED (POST /api/plugin/gate-stop), with the tool call's
# id, which is left in `<sid>.fence.pending`. The operator's answer never
# reaches a hook, but a PostToolUse arrives only for a call that ran, so
# grimoire_fence_ran.sh reports the matching call as run: the operator said
# yes. An ask with no run after it was declined, or the call failed.
set -uo pipefail
# shellcheck source=plugin/hooks/grimoire_defs.sh
@@ -56,6 +62,8 @@ cwd=$(grimoire_json_pick "$event_flat" '.cwd')
state_dir="${TMPDIR:-/tmp}/grimoire-fence"
safe_sid=$(printf '%s' "${session_id:-none}" | tr -c 'A-Za-z0-9._-' '_')
entered_file="$state_dir/${safe_sid}.entered"
pending_file="$state_dir/${safe_sid}.fence.pending"
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
# ── PostToolUse on enter_project: remember the first project entered ─────
if [ "$hook_event" = "PostToolUse" ]; then
@@ -228,7 +236,7 @@ while IFS= read -r check; do
act=${check#*$'\t'}
q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)"
fi
resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" "${base}${q}" 2>/dev/null) || {
resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" -H "X-Grimoire-Plugin: ${plugin_version:-}" "${base}${q}" 2>/dev/null) || {
fence_unreached
exit 0
}
@@ -238,6 +246,16 @@ while IFS= read -r check; do
reason=$(grimoire_json_pick "$flat" '.reason')
esc=$(printf '%s' "$reason" | grimoire_json_escape) || exit 0
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"%s"}}\n' "$esc"
# The ask, and the call it is about, so the run that follows a yes can
# be matched to it. `at` is what the act was: the tool for a Grimoire
# call, the act phrase ("git push in") for a file or a git command.
if [ "$check" = "tool" ]; then fence_at="$short"; fence_tool="$short"; else fence_at="$act"; fence_tool="$tool_name"; fi
if [ -n "$call_id" ] && [ -n "$session_id" ]; then
mkdir -p "$state_dir" 2>/dev/null || true
printf '%s' "$call_id" > "$pending_file" 2>/dev/null || true
fi
grimoire_gate_report "$session_id" fence asked "$fence_tool" "" "$fence_at" \
"$(grimoire_json_pick "$flat" '.targets[0].id')" "$call_id"
exit 0
fi
done <<EOF
+20 -12
View File
@@ -79,23 +79,30 @@ printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.opened.
# answers with one line putting the question to the reader. Nothing is
# mounted by this.
#
# An open of a rule a hook has just NAMED is not reported. A ranked arm or a
# moment line put it in front of the reader, and that explains the open; the
# moment beside it did not, so counting it would propose mounts on whatever
# moment happened to fire while search was surfacing the rule. The window is
# short for the same reason: a few minutes of agent work reaches many moments.
# EVERY OPEN IS REPORTED: the server stamps it on this session's latest
# delivery of the rule, which is how an open rate per delivery is measured.
#
# The acts go with it only when the rule was NOT just named by a hook. A
# ranked arm or a moment line put a named rule in front of the reader, and
# that explains the open; the moment beside it did not, so counting it would
# propose mounts on whatever moment happened to fire while search was
# surfacing the rule. The window is short for the same reason: a few minutes
# of agent work reaches many moments.
command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0
acts=""
case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in
*",${rule_id},"*) exit 0 ;;
esac
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
[ -f "$acts_file" ] || exit 0
now=$(date +%s 2>/dev/null) || exit 0
acts=$(awk -F '\t' -v since=$((now - 90)) \
*",${rule_id},"*) ;;
*)
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
now=$(date +%s 2>/dev/null) || now=0
if [ -f "$acts_file" ] && [ "$now" -gt 0 ]; then
acts=$(awk -F '\t' -v since=$((now - 90)) \
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
| tail -n 3 | paste -sd ',' - 2>/dev/null)
[ -n "$acts" ] || exit 0
fi
;;
esac
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
@@ -103,6 +110,7 @@ scope=$(grimoire_scope_query "${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}")
body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \
| curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0
+35 -1
View File
@@ -24,6 +24,16 @@
# honest. It records that an outcome was declared. The value of that is not the
# claim itself — it is that the absence of one becomes visible.
#
# `rule_misfired` closes the same gap from the other side: the rule arrived
# at a moment and did not bear on the work there. It is an answer too, so it
# goes in the same ledger.
#
# BOTH ALSO GO TO THE SERVER, with the session id the MCP call cannot carry,
# as an adherence verdict on this session's delivery of the rule: applied is
# followed, departed is departed, a misfire is not applicable at the moment it
# names (`/api/plugin/rule-verdict`). That is what lets the adherence readout
# put "followed" beside "delivered" and "opened" per rule and per moment.
#
# EXIT 0, ALWAYS. This decorates a ledger; a bookkeeping failure must never
# turn a successful tool call into a hook error.
set -uo pipefail
@@ -38,7 +48,7 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0
# The matcher in hooks.json narrows to the rule_outcome tools, but the server
# The matcher in hooks.json narrows to the rule_outcome and rule_misfired tools, but the server
# segment of an MCP tool name varies with how the plugin was installed, so the
# id is read from the field rather than from an assumed tool name — the same
# reasoning grimoire_record_opened.sh gives.
@@ -52,4 +62,28 @@ safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
# Stamped and append-only like its two siblings, so one reader ages them all.
printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.acted.ids"
# ── The verdict, to the server ───────────────────────────────────────────
command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
why=$(grimoire_json_pick "$event_flat" '.tool_input.why')
outcome=""
moment=""
case "$tool_name" in
*rule_misfired) moment=$(grimoire_json_pick "$event_flat" '.tool_input.moment') ;;
*) outcome=$(grimoire_json_pick "$event_flat" '.tool_input.outcome') ;;
esac
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
outcome_esc=$(printf '%s' "$outcome" | grimoire_json_escape) || exit 0
moment_esc=$(printf '%s' "$moment" | grimoire_json_escape) || exit 0
why_esc=$(printf '%s' "$why" | grimoire_json_escape) || exit 0
printf '{"rule_id":%s,"session_id":"%s","outcome":"%s","moment":"%s","why":"%s"}' \
"$rule_id" "$sid_esc" "$outcome_esc" "$moment_esc" "$why_esc" \
| curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/rule-verdict" >/dev/null 2>&1 || true
exit 0
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Grimoire — tell the server this session opened a record, or ran a search.
#
# WHAT THIS ANSWERS
#
# A hook puts records in front of a session (prior art, the notes menu); the
# session also searches for records itself, and opens others it reached on
# its own (an id in a task log, a record the operator named). The server
# records what each hook pushed against the session. This reports the other
# half, from the tool calls themselves:
#
# - `get_note`, `get_task`, `get_snippet`, `get_lesson`, `get_process` — the
# record was opened. The server stamps the delivery it followed, or records
# a direct open when nothing delivered it first.
# - `search` — the session asked. The server reads what that call returned
# from its own log and records those results against the session, so an
# open that follows counts as one reached by asking.
#
# Together they say, per kind of record, how much a session is shown, how
# much it asks for, how much it reaches on its own, and what it opens.
#
# A tool call happened or it did not, and the harness reports it either way:
# this asks the session nothing.
#
# EXIT 0, ALWAYS, silent on outage. This is bookkeeping; a failure here must
# never turn a successful tool call into a hook error.
set -uo pipefail
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
event=$(cat 2>/dev/null || true)
[ -n "$event" ] || exit 0
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
post() {
printf '%s' "$2" | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/$1" >/dev/null 2>&1 || true
}
case "$tool_name" in
*__search)
q=$(grimoire_json_pick "$event_flat" '.tool_input.q')
[ -n "$q" ] || exit 0
q_esc=$(printf '%s' "$q" | grimoire_json_escape) || exit 0
post record-searched "$(printf '{"session_id":"%s","q":"%s"}' "$sid_esc" "$q_esc")"
;;
*)
# Each getter names its id differently; read whichever is present. A
# process opened by name rather than id is left unrecorded.
note_id=""
for field in note_id task_id snippet_id lesson_id name_or_id; do
note_id=$(grimoire_json_pick "$event_flat" ".tool_input.${field}")
[ -n "$note_id" ] && break
done
case "$note_id" in
''|*[!0-9]*) exit 0 ;;
esac
post record-opened "$(printf '{"session_id":"%s","note_id":%s}' "$sid_esc" "$note_id")"
;;
esac
exit 0
+15 -1
View File
@@ -6,7 +6,9 @@
# tool call misses it. This hook sends the finished reply to the server, which
# checks it twice over: the rules MOUNTED on the reply moments, and the reply
# text against every rule's trigger, as the backstop for whatever the earlier
# arms missed. An unopened rule from either half holds the reply for one read.
# arms missed. An unopened rule set to hold, from either half, holds the reply
# for one read; a rule set to inform was delivered before the reply and never
# holds it.
#
# ONE END-OF-TURN REQUEST. When the turn closed a task, the same request
# carries the task ids and the server also checks the reply for the completion
@@ -105,6 +107,7 @@ query=${query#&}
answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0
@@ -123,4 +126,15 @@ done
grimoire_json_list "$answer_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
# Each rule that held the reply, reported as a gate stop with where it was
# reached, as the tool-call gates report theirs. The server already applied
# the per-session cap, so a reason here is a hold. A section hold names no
# rule and is counted by its own check (`report_check`).
i=0
for id in $(grimoire_json_list "$answer_flat" '.rule_ids'); do
grimoire_gate_report "$session_id" reply stopped reply "$id" \
"$(grimoire_json_pick "$answer_flat" ".rule_at[$i]")" "" ""
i=$((i + 1))
done
exit 0
+1
View File
@@ -192,6 +192,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then
local resp meta
resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/context${q}" 2>/dev/null)
ctx_rc=$?
meta=${resp##*$'\n'}
+7 -5
View File
@@ -31,13 +31,14 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0
# The moment arm's per-session files (its tool cache and the acts ledger) and
# the fence's (the project the session entered, its outage marker) describe a
# session that is over, on any exit — a clear included, since the next
# conversation is a new session id.
# The moment arm's per-session files (its tool cache and the acts ledger), the
# shape check's (a note waiting for a prompt) and the fence's (the project the
# session entered, its outage marker) describe a session that is over, on any
# exit — a clear included, since the next conversation is a new session id.
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* 2>/dev/null || true
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* \
"${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true
reason=$(grimoire_json_pick "$event_flat" '.reason')
[ "$reason" = "clear" ] && exit 0
@@ -48,6 +49,7 @@ grimoire_config || exit 0
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/release-session?session_id=${sid_enc}" \
>/dev/null 2>&1 || true
exit 0
+128 -48
View File
@@ -1,29 +1,40 @@
#!/usr/bin/env bash
# Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent
# that wrote them.
# that wrote them, at the start of its next turn.
#
# The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every
# definition a write names to a session ledger, `<sid>.written.ids`
# (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the
# turn this hook sends that ledger to the instance, which answers with what
# nobody has judged yet. If anything is, the hook blocks ONCE, in the server's
# words: the agent that built the code is the one participant who knows what
# it is, and the end of the turn is the last moment that is still true.
# nobody has judged yet as a `note`. The hook leaves the note for
# grimoire_autoinject.sh, which carries it into the next prompt's payload: the
# agent that built the code is the one participant who knows what it is, and
# the next turn of the same session still does.
#
# THE SAME DISCIPLINE AS the completion-section check in grimoire_reply_check.sh:
# - it blocks only on a `reason` the instance returned, which it returns
# only for a block it RECORDED — an unconfigured or unreachable instance
# never stops a session, and every intervention is one the numbers see;
# - never twice for one turn: the stop that follows its own block
# (`stop_hook_active` with this hook's marker present) is recorded as
# judged_after_block / left_after_block and let through;
# - another plugin's block loop is left alone (active, no marker).
# IT NEVER HOLDS THE REPLY. A held reply is rewritten, and a hold on every turn
# that wrote code made most replies cost two. The question waits one prompt
# instead, and is asked inside that prompt's budget.
#
# THE LEDGER IS CONSUMED, NOT TURN-STAMPED. Everything written since the last
# stop this hook answered is "this turn". It is emptied once the instance has
# answered — after a pass, or after the post-block stop — and KEPT when the
# instance could not be reached, so the question is asked at the next stop
# that can be answered rather than silently dropped.
# THE STATE, in <TMPDIR>/grimoire-shapecheck:
# <sid>.note — the note, until a prompt carries it (the prompt hook
# removes it once the instance has answered);
# <sid>.asked — the lines that note named. At the first stop after the note
# was carried, they go back as `phase=after`, which records
# whether they were judged;
# <sid>.asked_earlier — the same, for the carried lines the note named
# apart from this turn's;
# <sid>.earlier — what the after phase said is still unjudged, as
# `N<TAB>path<TAB>kind<TAB>name`, N the asks walked past.
# These ride the next check as `earlier=`, so a shape the
# agent moved on from is named again rather than surviving
# only as a count. A line walked past more than
# GRIMOIRE_EARLIER_MAX times is dropped: past that the
# repeat is noise, and the coverage line still counts it.
# A note no prompt has carried yet (two stops in a row) is asked again with
# that turn's writes added, so nothing is dropped and nothing is asked twice.
#
# Silent on outage: the ledger is kept when the instance could not be reached,
# so the question is asked at the next stop that can be answered.
#
# Config (same as the other hooks):
# CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash
@@ -43,36 +54,39 @@ session_id=$(grimoire_json_pick "$event_flat" '.session_id')
active=$(grimoire_json_pick "$event_flat" '.stop_hook_active')
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
[ -n "$session_id" ] || exit 0
# The stop after another hook held the reply: this turn's writes were already
# sent at the stop before it.
[ "$active" = "true" ] && exit 0
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
mkdir -p "$state_dir" 2>/dev/null || true
marker="$state_dir/${safe_sid}.blocked"
note_file="$state_dir/${safe_sid}.note"
asked_file="$state_dir/${safe_sid}.asked"
asked_earlier_file="$state_dir/${safe_sid}.asked_earlier"
earlier_file="$state_dir/${safe_sid}.earlier"
# Each walked-past shape is asked this many more times, then dropped.
earlier_max="${GRIMOIRE_EARLIER_MAX:-2}"
if [ "$active" = "true" ]; then
# A Stop hook already blocked this stop. Another plugin's → nothing to add.
[ -f "$marker" ] || exit 0
phase=after
else
rm -f "$marker" 2>/dev/null || true
phase=check
# A note no prompt has carried: its lines join this turn's, asked afresh. Its
# carried lines are still in <sid>.earlier, so they ride the next check too.
if [ -f "$note_file" ]; then
if [ -s "$asked_file" ]; then
mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
cat "$asked_file" >> "$ledger" 2>/dev/null || true
fi
rm -f "$note_file" "$asked_file" "$asked_earlier_file" 2>/dev/null || true
fi
if [ ! -s "$ledger" ]; then
rm -f "$marker" 2>/dev/null || true
exit 0
fi
[ -s "$asked_file" ] || [ -s "$asked_earlier_file" ] || [ -s "$ledger" ] \
|| [ -s "$earlier_file" ] || exit 0
grimoire_config || exit 0
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
# key runs the plugin), and a turn that wrote more than this generated code.
written=$(awk '!seen[$0]++' "$ledger" 2>/dev/null | head -n 80)
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
q="phase=${phase}&written=${written_enc}"
scope_q=""
scope=$(grimoire_scope_query "$dir")
[ -n "$scope" ] && q="${q}&${scope}"
[ -n "$scope" ] && scope_q="&${scope}"
# The repo rides along even when a marker names the project: the instance
# needs it to tell the agent which repo a just-written shape belongs to.
case "$scope" in
@@ -81,25 +95,91 @@ case "$scope" in
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
if [ -n "$remote" ]; then
remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc=""
[ -n "$remote_enc" ] && q="${q}&repo=${remote_enc}"
[ -n "$remote_enc" ] && scope_q="${scope_q}&repo=${remote_enc}"
fi
;;
esac
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
# key runs the plugin), and a turn that wrote more than this generated code.
_unique() { awk '!seen[$0]++' "$1" 2>/dev/null | head -n 80; }
# The note a prompt carried: were its lines judged since? What is still
# unjudged comes back as `left`, and becomes the carried set, each line's
# walked-past count one higher than it was.
if [ -s "$asked_file" ] || [ -s "$asked_earlier_file" ]; then
asked=""
[ -s "$asked_file" ] && asked=$(_unique "$asked_file")
asked_q=""
if [ -n "$asked" ]; then
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc=""
asked_q="&written=${asked_enc}"
fi
if [ -s "$asked_earlier_file" ]; then
prior=$(_unique "$asked_earlier_file")
prior_enc=$(printf '%s' "$prior" | grimoire_urlenc) || prior_enc=""
[ -n "$prior_enc" ] && asked_q="${asked_q}&earlier=${prior_enc}"
fi
if after=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=after${asked_q}${scope_q}" 2>/dev/null); then
rm -f "$asked_file" "$asked_earlier_file" 2>/dev/null || true
left_file="$state_dir/${safe_sid}.left"
grimoire_json_pick "$(printf '%s' "$after" | grimoire_json_flat)" '.left' \
> "$left_file" 2>/dev/null || true
prev="$earlier_file"
[ -f "$prev" ] || prev=/dev/null
awk -F'\t' -v max="$earlier_max" '
FILENAME == ARGV[1] { if (NF == 4) seen[$2 "\t" $3 "\t" $4] = $1; next }
NF == 3 {
n = (($0 in seen) ? seen[$0] : 0) + 1
if (n <= max) print n "\t" $0
}' "$prev" "$left_file" > "${earlier_file}.new" 2>/dev/null || true
mv -f "${earlier_file}.new" "$earlier_file" 2>/dev/null || true
[ -s "$earlier_file" ] || rm -f "$earlier_file" 2>/dev/null || true
rm -f "$left_file" 2>/dev/null || true
fi
fi
written=""
[ -s "$ledger" ] && written=$(_unique "$ledger")
# The carried lines, minus any this turn wrote again (those are this turn's).
earlier=""
if [ -s "$earlier_file" ]; then
mine_file="$state_dir/${safe_sid}.mine"
printf '%s\n' "$written" > "$mine_file" 2>/dev/null || true
earlier=$(awk -F'\t' '
FILENAME == ARGV[1] { if (NF == 3) mine[$0] = 1; next }
NF == 4 { line = $2 "\t" $3 "\t" $4; if (!(line in mine) && !seen[line]++) print line }
' "$mine_file" "$earlier_file" 2>/dev/null | head -n 40)
rm -f "$mine_file" 2>/dev/null || true
fi
[ -n "$written" ] || [ -n "$earlier" ] || exit 0
check_q=""
if [ -n "$written" ]; then
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
check_q="&written=${written_enc}"
fi
if [ -n "$earlier" ]; then
earlier_enc=$(printf '%s' "$earlier" | grimoire_urlenc) || earlier_enc=""
[ -n "$earlier_enc" ] && check_q="${check_q}&earlier=${earlier_enc}"
fi
answer=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/shape-check?${q}" 2>/dev/null) || exit 0 # unreachable: keep the ledger
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=check${check_q}${scope_q}" 2>/dev/null) \
|| exit 0 # unreachable: keep the ledger
if [ "$phase" = "after" ]; then
rm -f "$marker" "$ledger" 2>/dev/null || true
exit 0
note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
if [ -n "$note" ]; then
printf '%s' "$note" > "$note_file" 2>/dev/null || true
[ -n "$written" ] && printf '%s\n' "$written" > "$asked_file" 2>/dev/null
[ -n "$earlier" ] && printf '%s\n' "$earlier" > "$asked_earlier_file" 2>/dev/null
else
# Nothing unjudged, the carried lines included: they were answered.
rm -f "$earlier_file" 2>/dev/null || true
fi
reason=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.reason')
if [ -z "$reason" ]; then
rm -f "$ledger" 2>/dev/null || true
exit 0
fi
: > "$marker" 2>/dev/null || true
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
rm -f "$ledger" 2>/dev/null || true
exit 0
+10 -2
View File
@@ -6,7 +6,7 @@ once, in the **`using-grimoire`** skill: reach for it at the start of the sessio
and whenever you are unsure what Grimoire expects. Each tool's contract is in its
description, and the process skills (writing-plans, reporting-back,
reusing-code, systematic-debugging, verification, brainstorming,
shape-accounting, family-canon) carry their arcs.
shape-accounting, family-canon, reviewing-tests) carry their arcs.
What only Claude Code needs said:
@@ -19,7 +19,15 @@ What only Claude Code needs said:
notes and prior art that resemble what you are doing — and, when a tool call
or the reply ending a turn reaches a moment of work, the rules mounted on
it. Open the ones that apply; using-grimoire says what a quiet turn means and
how to correct a moment that fired wrongly.
how to correct a moment that fired wrongly. A line beginning "Also
resembling this, not shown" names records by id only, because they matched
less clearly than the lines above it: open one when it may bear on the work.
"Also recorded beside this file" names the snippets recorded in the same
folder as the file being written, by id, for the same judgement.
- **A rule can hold or refuse a tool call.** A held call names its rule and
goes ahead once the rule has been read: read it, then make the call again.
A refused call is a boundary the operator drew; it moves when they change
the rule, so tell them what the rule said.
- **Compact at clean seams.** Because work is recorded as you go, a compaction
is safe once in-flight state is logged. After finishing a block of work in a
long session, log it to Grimoire, then tell the operator it's a good moment to
+1
View File
@@ -32,6 +32,7 @@ grimoire_config || exit 0
body=$(curl -fsS --max-time 8 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/processes" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0
+13 -1
View File
@@ -101,6 +101,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
# The Systems whose rulings were shown in full — shared with the write-path
# hook, for the reason the rule file is.
rulingsfile="$state_dir/${safe_sid}.rulings.ids"
@@ -112,6 +114,7 @@ fi
# than silence. See the header.
body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
@@ -150,13 +153,22 @@ fi
# It cannot recur. `grimoire_checkpoint_allowed` holds at most one act per rule
# and at most five per session, so the worst case of a mis-set floor is a noisy
# session rather than one that cannot move.
#
# Each stop is reported to the server, and so is a checkpoint the session's
# budget let through: the cap is decided here, so only this hook knows.
cp_rule=$(grimoire_json_pick "$body_flat" '.checkpoint.rule_id')
cp_reason=$(grimoire_json_pick "$body_flat" '.checkpoint.reason')
if [ -n "$cp_rule" ] && [ -n "$cp_reason" ] && [ -n "$session_id" ]; then
if grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$cp_rule"; then
stops="$state_dir/${safe_sid}.checkpoint.ids"
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
if grimoire_checkpoint_allowed "$stops" "$cp_rule"; then
grimoire_json_deny PreToolUse "$cp_reason"
grimoire_gate_report "$session_id" checkpoint stopped "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id"
exit 0
fi
if grimoire_checkpoint_spent "$stops" "$cp_rule"; then
grimoire_gate_report "$session_id" checkpoint let_through "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id"
fi
fi
[ -n "$context" ] || exit 0
+19 -1
View File
@@ -82,7 +82,16 @@
]
},
{
"matcher": "mcp__.*__rule_outcome",
"matcher": "mcp__.*__(get_note|get_task|get_snippet|get_lesson|get_process|search)",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_record_read.sh\""
}
]
},
{
"matcher": "mcp__.*__(rule_outcome|rule_misfired)",
"hooks": [
{
"type": "command",
@@ -107,6 +116,15 @@
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
}
]
},
{
"matcher": "Write|Edit|MultiEdit|NotebookEdit|Bash|mcp__.*grimoire.*",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_fence_ran.sh\""
}
]
}
],
"PreCompact": [
+4
View File
@@ -45,6 +45,10 @@ face, and if so write the note that carries the idea.
enter_project's `family` key counts what this project owes the family:
`unassessed`, `owed`, `needs_recheck`, each with the call that lists them.
It also names this project's own records that a trigger proposed and nobody
evaluated (`candidates`): you hold their context, so evaluate each as above,
or `retire_family_idea` one that is not an idea at all (a task, a note about
this project alone).
Answer an idea **when your work reaches its area**, not as a chore list at
session start — the count is there so it is never invisible, not so it
preempts the operator's task.
+97
View File
@@ -0,0 +1,97 @@
---
name: reviewing-tests
description: Use when a test suite needs reviewing rather than growing — the operator asks to review, prune or tighten tests, CI is slow and the suite only ever grows, the coverage line counts test groups guarding the same thing or tests guarding nothing found, or a project's test standard asks for a review. Triggers on "review the tests", "prune the suite", "too many tests", "redundant tests", "CI is slow", "test standard". Gives each test one verdict, proves the survivors still fail, and lists every removal with its reason.
metadata:
moments: work.verify
---
# Reviewing a test suite
Every change adds tests and nothing removes them, so a suite left alone only
grows: each test costs every CI run, forever, whether or not it still
protects anything. A review is the subtraction pass. It gives every test one
verdict, keeps the ones that earn their place, and leaves a record good
enough that any removal can be argued back.
## The standard comes from the project, not from this skill
Look for the project's own test standard first: a family idea it has
adopted (`enter_project` lists ideas under `family`; `get_family_adoption`
reads the project's answer), a rule, or a note — `search` for "test
standard" in the project. Review against it, and use the test levels it
names (unit, database, web, …) for "move" below. With no standard recorded,
the verdicts below are the floor; agree the project's levels with the
operator before moving any test, and offer to record them so the next review
starts from them.
## Before: the numbers you will compare against
Write these into the review's task before touching anything:
- tests **collected**, from a real run's summary (not files, not a grep: a
file that fails to collect reads exactly like a pass);
- lines of test code;
- CI time, from the last few green runs on the main working branch;
- the coverage line's test figures: linked, guarding nothing found,
redundant, and the number of groups guarding the same thing.
## Area by area
Take one area at a time, the project's Systems or its test directories, and
finish it before starting the next. In each area:
1. **Read what the ledger already knows.** `list_shapes(path=<area>)` lists
the test cases; a `test` status means the refresh linked it to something
it guards, `unclassified` means it is linked to nothing. `test_guard_groups`
lists tests in different files that guard exactly the same thing, each
with its `signals`: `signature` (pins how code is declared), `mock-only`
(asserts only that mocks were called), `source-text` (reads source as
text). Signals point at what to read first; they never decide a verdict.
Groups come smallest first. A `copies` group (three tests or fewer) is
where one-for-one duplicates hide. An `area` group is one feature
tested from several files, since every test that drives a feature
through its entry point reaches the same code. Read it as one area: fold
the scattered cases into the feature's own file, and remove only what
another test already checks.
2. **Read every test** and give it one verdict:
- **keep** — it protects something a user or caller relies on, and
nothing else in the suite protects it;
- **merge** — it checks one case of a behaviour other tests also check:
fold them into one table of cases;
- **rewrite** — the subject is right and the check is weak: it pins a
name, a signature or a mock call where it should pin an outcome;
- **move** — it sits at a level the project's standard puts elsewhere;
- **remove** — another test checks everything it checks
(`redundant`, naming that test), or what it protects no longer matters
to anyone (`unused`).
3. **Record the verdicts where they are kept.** Removals go in the ledger:
`classify_shapes` with `status="redundant"` and `covered_by` {path,
symbol} for a test another covers, `status="unused"` for one nothing
needs, a reason on each. A group judged to be distinct behaviours goes to
`review_test_group` with what each test checks that the others don't. A
test linked to nothing and kept says what it guards in an `exempt` reason.
4. **Break what the survivors claim to protect.** Choose three to five
behaviours the kept tests guard, break each one deliberately in the
product code, and confirm the tests go red; then revert. Run them where
the project's own rules say tests run. A test that stays green while its
behaviour is broken protects nothing, whatever its name says: rewrite it
or remove it.
5. **Land the area as one change** that does nothing but this review, so it
can be reverted alone. Behaviour changes found on the way are their own
issues, never folded in.
## After
- Rerun the same numbers and put them beside the baseline in the review's
task.
- List every removed test with its verdict and reason, in that task's log.
The list is what lets someone argue one back.
- A test is never removed to make a red build green. A failing test is a
finding about the code until a reading says otherwise.
## Report
Lead with the numbers (tests, lines, CI time, before and after), then the
removals by area with their reasons, then what the deliberate breaks proved
and anything they caught. A test found guarding a real bug's absence that
nobody knew about is the most valuable line in the report; say so plainly.
+20 -2
View File
@@ -24,6 +24,10 @@ row carries a status:
unreachable from any other file). Accounted for without a
judgment; still proposed against, grouped and flagged; any judgment you
make overrides it. Not the todo.
- `redundant` — should be removed: `covered_by` names the shape that already
does its job. **Reason required.** Delete the code; the next sync retires
the row.
- `unused` — should be removed: nothing needs it. **Reason required.**
- `unclassified` — nobody has judged it yet. **This is the todo list.**
## The loop
@@ -53,8 +57,11 @@ unjudged.
The ledger is filled from your answers, given while you still know them. When
a turn wrote definitions nobody has judged, the plugin's Stop hook lists them
once — with whatever the machinery holds as evidence — and you classify them
in one `classify_shapes(project_id, repo=…, …)` call (the `reusing-code` skill
— with whatever the machinery holds as evidence — and you classify them
in one `classify_shapes(project_id, repo=…, …)` call. What you move on from is
named again in your next few notes, marked as written earlier in the session,
because nothing else names a shape after that (the coverage line only counts
it) (the `reusing-code` skill
says what each verdict means). `repo` lets a verdict land on a shape the sync
has not read yet. So a project worked this way stays accounted as it grows,
and an audit pass is a CHECK that the reflex held — the coverage line names
@@ -178,6 +185,17 @@ Three questions the ledger answers mechanically:
one and record the verdict with `classify_shapes` — `instance` if it is,
otherwise what it actually is.
## Tests that guard the same thing
Every refresh links each test to the shapes its body exercises (mocks
excluded), and the coverage line's "N test groups guarding the same thing —
test_guard_groups" counts tests in different files that guard exactly the
same set. A group is a candidate: read the tests, then mark one `redundant`
with the test that covers it, or `review_test_group` with what each checks
that the others don't. Each test's `signals` (signature, mock-only,
source-text) are evidence for that reading, never a verdict.
A whole-suite pass is its own procedure: the reviewing-tests skill.
## What this buys
Divergence becomes mechanical: when button B appears where button A is canon,
+8 -8
View File
@@ -55,10 +55,10 @@ Two constraints on *how* that's achieved:
`project_id` so results stay scoped.
**Code tells you what a thing does, not what was wanted.** A limit, a
default or a fallback found by reading the work is a past session's choice
until a record says the operator made it. Before presenting one as a
safeguard or a known cost, read the `Rulings` on the System it belongs to;
when none speaks to it, call it unconfirmed rather than settled.
default or a filter found in the work is a past session's choice until a
record says the operator made it. Before relying on one or changing it,
read the `Rulings` on its System; none speaking to it means unconfirmed,
and a change that would undo what a ruling says it is for goes to them.
2. **Rules are binding, and they reach you by retrieval.** No call loads the
operator's rules and no standing set is handed to a session. A rule arrives
@@ -100,10 +100,10 @@ Two constraints on *how* that's achieved:
**lesson** is what is worth knowing — a better way to think about a
problem, a solution that transfers — and ignoring it costs time. All three
are worth reading and all three arrive beside your work; only the first is
a mistake to miss. An injected line names which in its opening words —
*"Standing rule that may apply…"* against *"Preference that may apply…"* —
a lesson arrives in the records menu marked `lesson`, under a header that
says outright that it binds nothing, and every payload carries `kind`.
a mistake to miss. A line names which up front (*"Rule 11 …; it binds:"*,
*"Preference 173 …; how this has been done before:"*) and on first mention
quotes the statement; `get_rule(id)` gives the why and how. A lesson is
marked `lesson` under a header saying it binds nothing; payloads carry `kind`.
**One question sorts them, and it is worth asking out loud: what happens if
someone doesn't do this?** *Something breaks, or a boundary is crossed* — a
+39
View File
@@ -5,6 +5,13 @@ moment, when a reply is held for one read, when an action reached the wrong
moment or none, when a mounted rule arrived and did not apply, and when a line
proposes mounting or unmounting a rule.
## Contents
- What a moment is
- Reading a line that arrived at a moment — and a held or refused call
- When the moment is wrong — correct it in the session
- When a mounted rule arrives and does not apply
- When a line proposes a mount — and how rules are weighed and measured
## What a moment is
Most rules reach you by resemblance: what you are doing looks like what the
@@ -34,6 +41,22 @@ The reply that ends a turn is a moment too. When a rule mounted at
with its name: open it, then send the reply — unchanged, if it already does
what the rule asks. The same rule is never held twice.
A call can be held the same way. A rule declared `hold` that the call reaches
stops it once, naming the rule: read it, then make the call again — unchanged
if the rule does not bear on it, and then `rule_misfired` says so. A rule
declared `enforce` refuses the call every time, in its own words: that is a
boundary the operator drew, and it moves only when they change the rule, so
tell them what you were doing and what the rule said. A rule with triggers of
its own holds or refuses only the acts those triggers match; at the rest of
its moments it arrives as a line.
A moment sends a few lines, not every rule mounted there: ordered by
enforcement, then salience, then how exactly the act reached the rule, then
how often it has been opened there. What did not fit was left out, and a
rule already shown this session comes back as a short reminder, then not at
all. So a quiet moment means nothing more needed saying there, not that no
rule applies — `what_might_apply` asks for the whole list.
## When the moment is wrong — correct it in the session
A moment can fire on an action that is not that moment here, or an action can
@@ -89,3 +112,19 @@ The same tool answers proposals from a pass over the rules
proposes, and only the operator's yes mounts. Writing a NEW rule is different
— its moments are part of writing it, and the
skill's guide to writing records says how.
A second pass weighs each rule: how strongly it arrives once reached
(`enforcement`: inform, hold or enforce; `salience`), and which typed
triggers reach it exactly (`rules_to_weigh`, `propose_rule_weights`,
`rule_weight_proposals`, `judge_rule_weights`). It reads each rule beside its
delivery history and proposes; the operator confirms each change, in the
session or under Settings › Moments.
Whether a rule was followed where it arrived is measured per rule and per
moment (`rule_adherence`, and under Settings › Moments). Your own
`rule_outcome` and `rule_misfired` calls are the session's half of that
record: each lands as a verdict on the delivery you were answering. A
transcript review fills in the rest when the operator asks for one:
`adherence_to_judge` lists the rules in force at a moment of a session with
no verdict yet, and `judge_adherence` records followed, broken, departed or
not applicable, with what the transcript shows.
@@ -10,6 +10,7 @@ decides how some area of the work must behave; and before filling
## Contents
- Where a new rule goes — its home, its trigger, what already covers the moment
- When it applies — the moments a rule, a preference or a process is for
- How strongly it arrives — enforcement, salience, and the act it governs
- A ruling goes on the System it governs
- A lesson grows each time it proves itself
- A lesson names the rule it is an instance of
@@ -33,7 +34,10 @@ departs from a global rule writes its own and links it with
`relate_rules(kind="overrides")`, which says why. A rule that turns out to be
in the wrong home — a project rule that holds everywhere, a global one only a
single project needs — moves with `move_rule`, which keeps its id, history,
areas and edges. Propose the move and make it on a yes.
areas and edges. Propose the move and make it on a yes. Editing a rule that
lives on another project is curation, not that project's work: the plugin
names the rule and asks, and the edit goes ahead on the operator's yes rather
than becoming an issue there.
**Whichever home it gets, a rule needs `when_to_apply`.** It is the only thing
that decides whether the rule is ever seen: nothing is preloaded, so a rule
@@ -57,6 +61,35 @@ names the moments the procedure is for, so loading it reaches them and the
rules mounted there arrive with it. A rule that only applies inside one
procedure mounts on that procedure's own moment, `skill.<name>`.
## How strongly it arrives
A rule that reaches the work says one of three things, and you declare which
(`enforcement` on `create_rule`, `create_project_rule`, `update_rule`):
- **`inform`** — a line beside the work. The default, and right for most
rules: the session reads it and applies it.
- **`hold`** — the act or reply it governs waits until the session has read
the rule once; then it goes ahead. For a rule whose miss costs a rewrite: a
merge style, a release step, a check before a reply.
- **`enforce`** — the act is refused, in the rule's own words, every time,
and only a change to the rule moves it. For a boundary the operator draws
with no exceptions a session may judge. Most hard rules have an exit ("unless
the operator asks"), and a rule with an exit is a hold.
A hold or a refusal stops an act, so give it the act: a `triggers` entry
naming the command head (`git push origin main`), the tool (`create_release`)
or the path (`alembic/versions/*.py`) it governs. A rule with triggers stops
only the acts they match; at the rest of its moments it is a line. Without
one, it stops every act its moment reaches — a rule about pushing to `main`
mounted on `work.deliver` would hold every push to `dev`.
**`salience`** (`high`, `normal`, `low`) orders it against rules of the same
enforcement when a moment has more to say than fits. A moment sends a few
lines, highest first, and drops the rest — so `high` is for the rule that must
win a crowded moment, and `low` for one worth seeing but rarely decisive.
A preference never holds or refuses: it arrives as a line, with a salience.
**Before writing one, ask what already covers that moment.**
`what_might_apply("the moment you are about to write a record for")` — fifty
candidates and no bar, so an existing record cannot hide under a threshold the
@@ -112,10 +145,29 @@ one line each — the statement, who decided, when, and the record it came from:
Rulings
- Failed work is retried until it succeeds; no attempt limit. (Operator, 2026-09-19, #1234; restated 2026-10-02, #1290)
**A ruling about a constraint says what it is for, and what it is not for.** A
filter, a gate or a default outlives the reason it was made, and a later session
widens or narrows it by reading the code, which shows what it does and never
why. "Searches stay in their project" reads as a rule about every record; "a
search keeps other projects' open work out — it is not there to keep knowledge
in" can be re-judged when the reason changes. Write the *for* and the *not for*:
- The project filter keeps other projects' open work out of a session — not knowledge, which crosses with a label. (Operator, 2026-11-28, #1300)
The description arrives with every record filed under that System, so a ruling
there reaches each session working in the area without having to win a search.
Once the System names its files (`path_patterns`), its rulings also arrive with
the first command or edit in a session that touches them.
**Name the System's files** (`path_patterns`, globs from the repo root) so its
rulings also arrive with the first command or edit in a session that touches
them. That is the delivery that reaches someone changing the code; a System with
rulings and no files reaches nobody that way, and `enter_project` names it under
`rulings_undelivered`.
**The comment at the constraint names its ruling.** The code is where the next
change starts, and a reader there may have no Grimoire at all: give the reason
in the comment as a present-tense fact, and name the System and the ruling it
comes from, so the reason is one lookup away and the comment is not the only
copy.
A quote inside a work log does not: it surfaces only when a query happens to
match it, and the passage that matches is usually the prose around it — often a
session's *reading* of the ruling rather than the ruling.
+1
View File
@@ -50,6 +50,7 @@ asyncio_mode = "auto"
testpaths = ["tests"]
markers = [
"integration: requires a real Postgres database (runs only in the CI integration lane)",
"cue_gate: runs with the plugin doors' cue-swap gate on rather than stubbed off",
]
[tool.ruff]
+35
View File
@@ -402,6 +402,13 @@ SMOKE_EVENTS: dict[str, str] = {
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PreToolUse",
"tool_name": "mcp__grimoire__update_task", "tool_input": {"task_id": 1}}
),
# The fence's after-call half: with no ask pending it exits before
# reading anything, which is the case on nearly every call.
"grimoire_fence_ran.sh": json.dumps(
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PostToolUse",
"tool_name": "Bash", "tool_use_id": "toolu_smoke",
"tool_input": {"command": "true"}, "tool_response": {}}
),
# The shared library is sourced, never run; executed bare it defines
# functions and exits — silent by construction.
"grimoire_defs.sh": "",
@@ -781,6 +788,33 @@ def check_version_is_minted(base: str = "origin/main") -> None:
ok(f"nothing version-relevant changed against {base} — no mint required")
# The lower of the two caps recorded for a hook's additional context: the docs
# give 10,000 characters, and an installed build has been read capping it at
# 8,000. Past the cap the model gets only a short preview.
HOOK_CONTEXT_CAP = 8_000
PAYLOAD_MODULE = ROOT / "src" / "grimoire" / "services" / "hook_payload.py"
def check_payload_bound() -> None:
"""The server fits every hook payload under `hook_payload.HARD_MAX`, and
that ceiling must sit under Claude Code's cap whatever a user sets."""
try:
text = PAYLOAD_MODULE.read_text()
except OSError:
fail(f"no payload assembler at {PAYLOAD_MODULE.relative_to(ROOT)}")
return
found = re.search(r"^HARD_MAX\s*=\s*([0-9_]+)\s*$", text, re.M)
if not found:
fail("hook_payload.HARD_MAX is not a literal this check can read")
return
hard_max = int(found.group(1).replace("_", ""))
if hard_max >= HOOK_CONTEXT_CAP:
fail(f"hook_payload.HARD_MAX is {hard_max}, at or past Claude Code's "
f"{HOOK_CONTEXT_CAP}-character hook context cap")
else:
ok(f"hook payloads are bounded at {hard_max} characters, under {HOOK_CONTEXT_CAP}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--no-version", action="store_true",
@@ -800,6 +834,7 @@ def main() -> int:
check_fail_open()
check_local_prior_art_needs_no_instance()
check_session_context_reports_its_version()
check_payload_bound()
if not args.no_version:
check_version_is_minted(args.base)
+3
View File
@@ -198,9 +198,12 @@ 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
+35 -34
View File
@@ -29,42 +29,33 @@ from quart import Quart
# not: a tool's own contract (its description carries it), and stance — who
# judges, how to report, what a missed rule means. Those fire mid-work, not at
# the start; the skills state them and in-band responses (`placement`,
# `report_back`) cue them at the moment they apply. A new topic gets a line
# here only if it is a session-start practice.
# `report_back`) cue them at the moment they apply.
#
# BUDGET: at most 1,600 characters (test_instructions_fit_the_fold). Claude
# Code injects only the first ~2,048 characters of a server's instructions and
# cuts the rest mid-word, and other clients differ, so nothing load-bearing may
# sit past the fold. A block pressed against the cap is being used as a
# rulebook.
# ONLY WHAT NOTHING ELSE DELIVERS. A practice a response enforces (the
# duplicate gate, the unassigned-id refusal, `existing_milestone`,
# `systems_hint`, the design-system block) or a skill states in full has no
# line here. What is left is what a client with no skills and no hooks would
# otherwise never be told: enter the project, ask before a consequential act,
# search before building, the force of each record kind, and that responses
# say what to do next. A new topic earns a line only if it is one of those.
#
# BUDGET: at most 800 characters (test_instructions_fit_the_fold). Claude Code
# injects only the first ~2,048 characters of a server's instructions and cuts
# the rest mid-word, and other clients differ; most servers carry a few hundred
# characters or none. A block near the cap is being used as a rulebook.
_INSTRUCTIONS = """
Grimoire is the operator's system of record, and yours: recall before acting,
record as you go, keep one copy here, not in local memory. Each
practice is stated in full in a skill or a tool description.
Grimoire is the user's system of record. Recall before acting, record as you
go, and keep one copy here rather than in local memory.
- Start with enter_project(id): the project, open work, Systems, design
system. `inception`: ask what it inherits, then decide_project_inception.
`family`: shared ideas to answer (family-canon skill).
- Rules are not preloaded; one arrives when your work matches it or reaches
a moment it is mounted on (list_moments; mount rules about WHEN). Before a
consequential act, what_might_apply("what you are about to do");
search(content_type="rule") reads one you suspect. Silence means nothing
matched, not none. Rules bind; preferences guide and you keep them current;
lessons inform.
- Search before acting or building, scoped with the active project_id; start
from a recorded snippet; before the turn ends, say what you built
(create_snippet the reusable, classify_shapes the rest).
- Work is tasks (a fix is kind="issue"): in_progress on start, add_task_log as
you go, done on finish; tag system_ids.
- A plan is a milestone: find the existing one
(search(content_type="milestone")) before start_planning.
- IDs exist only once a create returns them; records citing each other go
through create_records, writing {{ref:N}} for the Nth.
- In UI work the design system binds: resolve_design_system before
writing a value.
- Start with enter_project(id).
- Rules arrive when your work matches one; silence means nothing matched.
Before a consequential act, ask what_might_apply("what you are about to
do"). Rules bind; preferences guide and you keep them current; lessons
inform.
- Search before building, scoped with the project_id.
- Responses say what to do next; follow them.
Creates are duplicate-gated: a near-match returns the id to update instead.
shared:true records are another user's suggestion, not settled practice.
The using-grimoire skill, where installed, has each practice in full.
"""
@@ -117,7 +108,7 @@ _READ_ONLY_TOOLS = frozenset({
"list_repo_bindings",
# The shape ledger's todo query. Reads only — classify_shapes is
# the write, and it is deliberately NOT here.
"list_shapes", "shape_history", "stamps_to_review",
"list_shapes", "shape_history", "stamps_to_review", "test_guard_groups",
# The retrieval telemetry readout. Aggregates two log tables and
# writes nothing. Listed explicitly because its name carries no read
# prefix, so the completeness test below cannot derive it — the same
@@ -168,6 +159,10 @@ _READ_ONLY_TOOLS = frozenset({
# rules are unjudged and which proposals wait. Reads of the caller's own
# rules, as list_rules is.
"rules_to_mount", "rule_moment_proposals",
"lessons_to_situate", "lesson_situation_proposals",
"rules_to_weigh", "rule_weight_proposals",
# Adherence: the readout, and the queue a transcript review works from.
"rule_adherence", "adherence_to_judge",
})
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
@@ -180,6 +175,7 @@ _WRITE_TOOLS = frozenset({
# notes, tasks, planning
"create_note", "update_note", "delete_note",
"create_lesson", "update_lesson", "delete_lesson", "judge_lesson_link",
"propose_lesson_situations", "judge_lesson_situations",
"create_task", "update_task", "delete_task", "add_task_log",
"create_records", "start_planning",
"create_milestone", "update_milestone", "delete_milestone",
@@ -200,7 +196,7 @@ _WRITE_TOOLS = frozenset({
"merge_snippets", "unmerge_snippet",
"create_process", "update_process", "delete_process",
"classify_shapes", "classify_shapes_by_rule", "confirm_shape_proposals",
"refresh_pattern_coverage", "move_path",
"refresh_pattern_coverage", "move_path", "review_test_group",
# design systems
"create_design_system", "update_design_system", "delete_design_system",
"create_design_token", "update_design_token", "delete_design_token",
@@ -229,9 +225,14 @@ _WRITE_TOOLS = frozenset({
# Proposing moments for a rule writes a judgment row; judging one mounts
# or unmounts the rule.
"propose_rule_moments", "judge_rule_moments",
# Proposing a rule's enforcement, salience or triggers writes a judgment
# row; judging one changes how the rule arrives.
"propose_rule_weights", "judge_rule_weights",
# A misfire report writes a counted row that can become an unmount
# proposal.
"rule_misfired",
# A transcript review's adherence verdicts, with the evidence it wrote.
"judge_adherence",
# A reviewer's verdicts on logged menu lines — rows carrying free
# prose the agent authored, `rule_outcome`'s reason for being a write.
"judge_menu",
+75 -7
View File
@@ -14,6 +14,7 @@ from grimoire.services import access as access_svc
from grimoire.services import dedup as dedup_svc
from grimoire.services import knowledge as knowledge_svc
from grimoire.services import lesson_rules as lesson_rules_svc
from grimoire.services import lesson_situations as lesson_situations_svc
from grimoire.services import lessons as lessons_svc
from grimoire.services import systems as systems_svc
from grimoire.services import trash as trash_svc
@@ -408,12 +409,12 @@ async def judge_lesson_link(
"""Say whether a lesson is an instance of a rule: `verdict` is "confirm"
or "reject".
Reach for this when Grimoire proposes a pair — a lesson and a rule that keep
arriving together in different situations — or whenever you are reading a
lesson and recognise the rule it falls under. Confirming makes the rule
reachable through the situation the lesson describes; rejecting records
that it is not, so the pair is not proposed again. `note` is the why, and
the next reader judges the link by it.
Reach for this when you are reading a lesson and recognise the rule it
falls under, or when a lesson you just recorded was offered candidate
rules. Confirming makes the rule reachable through the situation the
lesson describes, and lists the lesson on the rule when it is opened;
rejecting records that it is not. `note` is the why, and the next reader
judges the link by it.
Returns the link: {lesson_id, rule_id, state, note, evidence, judged_at}.
"""
@@ -451,7 +452,74 @@ async def delete_lesson(lesson_id: int) -> dict:
}
async def lessons_to_situate(limit: int = 25, offset: int = 0) -> dict:
"""The lessons with no situation yet — the pass over the corpus, a page at a time.
A lesson with no situation arrives only when a prompt's words resemble
it. Read each one here and decide WHEN it applies: a moment of work it
belongs to, a trigger on the act (a `path` glob, a `command` prefix, a
`tool`, a `keyword`), or that none fits. Record the answer with
`propose_lesson_situations`. A lesson leaves this list once any answer is
recorded, so the next call returns the next unread lessons.
Each lesson carries its title, its stated `when_to_apply`, the `rules` it
is a confirmed instance of with their own moments and triggers (the
strongest hint at its situation), and values already `rejected` for it.
The page carries the `catalog` of moments a lesson can arrive at and the
`trigger_kinds`. A lesson about writing a reply (a report, a proposal, a
question put to the operator) goes on `reply.report`, which arrives
before every reply is written.
"""
return await lesson_situations_svc.to_situate(current_user_id(), limit=limit, offset=offset)
async def propose_lesson_situations(proposals: list[dict]) -> dict:
"""Propose when lessons apply — for the operator to confirm; nothing is delivered by this call.
Each item is `{"lesson_id": N, "moments": ["work.deliver"], "triggers":
[{"kind": "path", "pattern": "alembic/versions/*.py"}], "why": "…"}`.
Empty `moments` and `triggers` say no situation fits: the lesson stays
reachable by meaning, and leaves the pass's list.
Propose a moment when the lesson is about that point in the work whatever
the work is about; a trigger when it is about a kind of file, command or
tool. Keep it to the few points where the lesson changes what is done —
a lesson that matches every edit is noise there. `why` is shown to the
operator beside the proposal; write it so they can say yes or no without
opening the lesson.
Returns `written`, `skipped` (already recorded, in any state) and
`refused` (a bad item, refused alone). Then show the operator what waits
(`lesson_situation_proposals`); they judge it in Settings › Moments or
through `judge_lesson_situations`.
"""
return await lesson_situations_svc.propose(current_user_id(), proposals)
async def lesson_situation_proposals(lesson_id: int = 0) -> dict:
"""The lesson situations waiting on the operator, grouped by lesson.
Each proposal has its `id` (what `judge_lesson_situations` takes), its
`kind` (`moment` or `trigger`), what it `describes`, and the proposer's
`note`. `lesson_id` narrows to one lesson.
"""
return await lesson_situations_svc.pending(current_user_id(), lesson_id=lesson_id or None)
async def judge_lesson_situations(judgments: list[dict]) -> dict:
"""Confirm or reject lesson situations — on the operator's word, since a confirm changes what reaches their sessions.
Each item is `{"id": N, "verdict": "confirm" | "reject", "note": "why"}`,
with the id from `lesson_situation_proposals`. A confirmed situation
delivers its lesson when the work reaches it, once per session; a
rejected one is never proposed again. Put the operator's reason in `note`.
"""
return await lesson_situations_svc.judge(current_user_id(), judgments)
def register(mcp) -> None:
for fn in (list_lessons, create_lesson, get_lesson, update_lesson,
delete_lesson, judge_lesson_link):
delete_lesson, judge_lesson_link, lessons_to_situate,
propose_lesson_situations, lesson_situation_proposals,
judge_lesson_situations):
mcp.tool(name=fn.__name__)(fn)
+167 -1
View File
@@ -15,7 +15,10 @@ from __future__ import annotations
from grimoire.mcp._context import current_user_id
from grimoire.services import moment_actions as actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import record_kinds as record_kinds_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import rule_adherence as adherence_svc
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
@@ -42,9 +45,21 @@ async def list_moments() -> dict:
`via: "default"` ships with the product, `via: "install"` is this
install's own mapping. `removed_defaults` are shipped defaults this install
switched off.
`record_kinds` is the kind×moment table: for each point where a record
search fires (`message`, the operator's message, and the catalog moments
that have one), the kinds of record it may consider, the shipped default,
and each kind's lines shown and opened there. A kind left out is never
pushed at that point; search for it yourself when you need it. Its
`reach` lists the kinds that may also come from the operator's other
projects (knowledge by default, never open work): such a line ends
`from <project>`, so weigh it as experience from that project rather than
a fact about this one. The operator changes the table in Settings › Moments.
"""
uid = current_user_id()
out = moments_svc.catalog()
out.update(await actions_svc.actions_by_moment(current_user_id()))
out.update(await actions_svc.actions_by_moment(uid))
out["record_kinds"] = await record_kinds_svc.table(uid)
return out
@@ -232,6 +247,150 @@ async def rule_misfired(rule_id: int, moment: str, why: str,
)
async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict:
"""The rules nobody has weighed, each with what happened when it reached a session — a page at a time.
Weighing a rule is deciding how strongly it arrives once the work reaches
it, and what reaches it exactly:
- `enforcement`: `inform` is a line beside the work, and is right for
most rules. `hold` makes the act or reply wait until the rule has been
read once in the session (file edits are never held). `enforce` refuses
the act the rule governs, in the rule's own words, every time — for a
rule whose breach an act commits and that must never be crossed without
the operator (pushing to a protected branch, a destructive command). A
preference is always `inform`.
- `salience`: `high`, `normal` or `low` — how it ranks beside rules of the
same enforcement when a moment has more to say than fits.
- `triggers`: typed predicates on the act (`tool`, `path`, `command`,
`keyword`, optionally scoped to a moment) that reach the rule exactly.
Propose one when the rule names the act it governs; an `enforce` rule
needs one, or a mount on an act's moment, to have an act to refuse.
Each rule carries its current `enforcement`, `salience`, `mounted` and
`triggers`, and `history` over the last 90 days: `delivered` and `opened`
in total and at each place (`places`), `pulled`, `applied`, `departed`
and `misfire_days`. Read the history as evidence about the rule's
weight, not as the decision: a rule delivered often and rarely opened is
either reaching the wrong work (a trigger fixes that) or arriving too
loudly for what it asks (lower salience); a rule sessions keep departing
from or breaching may need `hold`.
Record the answer with `propose_rule_weights`. A rule leaves this list as
soon as an answer is recorded, so the next call returns the next rules.
Returns `rules`, `total_unweighed` and `offset`.
"""
return await weights_svc.unweighed_rules(current_user_id(), limit=limit, offset=offset)
async def propose_rule_weights(proposals: list[dict]) -> dict:
"""Propose rules' enforcement, salience and triggers — for the operator to confirm; nothing changes on this call.
Each item is
`{"rule_id": N, "enforcement": "inform"|"hold"|"enforce",
"salience": "high"|"normal"|"low", "triggers": [{"kind": "command",
"pattern": "git push", "moment": ""}], "why": "…"}`.
Give both enforcement and salience for every rule, even where they match
what it has: a value equal to the rule's own is recorded as agreed, which
is what marks the rule as weighed. A different value waits as a
suggestion. `triggers` lists only triggers to add; omit it when none fits.
`why` is shown to the operator beside each suggestion: say what in the
rule and its history led to it, so they can say yes or no without opening
the rule.
Refused alone, under `refused`, with why: an unknown value, a preference
proposed to hold or enforce, and `enforce` on a rule no act reaches.
A value the operator already rejected is listed under `skipped`. Then show
the operator what is waiting (`rule_weight_proposals`) and let them
decide.
"""
return await weights_svc.propose(current_user_id(), proposals)
async def rule_weight_proposals(rule_id: int = 0) -> dict:
"""The enforcement, salience and trigger suggestions waiting on the operator, grouped by rule.
Each rule carries its current enforcement, salience, mounts and triggers
beside its `proposals`: each a `field`, the suggested `value` (a trigger
also as `trigger`), `why`, and the delivery history the proposer read
(`evidence`). `rule_id` narrows to one rule.
"""
return await weights_svc.pending(current_user_id(), rule_id=rule_id or None)
async def judge_rule_weights(judgments: list[dict]) -> dict:
"""Confirm or reject weight suggestions — on the operator's word, since a confirm changes how the rule arrives.
Each item is `{"rule_id": N, "field": "enforcement"|"salience"|"trigger",
"value": "hold" (or the trigger object), "verdict": "confirm"|"reject",
"note": "why"}`. Confirm sets the field on the rule (a trigger is added
beside the rule's others); reject records that the value is wrong for this
rule, so it is never proposed again. Put the operator's reason in `note`.
"""
return await weights_svc.judge(current_user_id(), judgments)
async def rule_adherence(days: int = 30, rule_id: int = 0) -> dict:
"""Whether the rules in force at each moment were followed there — per rule and per moment.
A rule is in force at a moment of a session when it was delivered there.
For each rule at each place (a moment such as `work.deliver`, or an arm
such as `pre_tool_rule`) over the last `days`: `in_force` (sessions it
was delivered there in), `opened` (sessions that opened it), and one
count per verdict — `followed`, `departed` (read and deliberately not
followed, with a reason), `broken` (the work went against it),
`not_applicable` (it did not bear on the work there) — and `unjudged`.
Verdicts come from an `enforce` refusal (the act did not happen), from
the session's own `rule_outcome` and `rule_misfired` calls, and from a
review of the transcript (`adherence_to_judge` / `judge_adherence`).
Returns `by_rule` (each with its places), `by_moment` (each with its
rules) and `totals`. `rule_id` narrows to one rule.
"""
return await adherence_svc.summary(current_user_id(), days=days, rule_id=rule_id or None)
async def adherence_to_judge(session_id: str = "", sessions: int = 3, per_session: int = 40) -> dict:
"""The rules that were in force at a moment of a session and have no verdict yet — for a transcript review.
Grouped by session, most recent first. Each item is one rule at one place
in that session: the rule's `statement` and `when_to_apply`, where it
arrived (`at`), how often and when (`delivered`, `first_at`, `last_at`),
and whether the session `opened` it. `how` says where the session's
transcript is kept.
To review a session: read its transcript around each item's times, see
what the work was at that moment, and decide whether it kept the rule.
Record the verdicts with `judge_adherence`, quoting or describing what in
the transcript shows each one. An item that did not bear on the work
there is `not_applicable`; that is a finding about where the rule is
delivered, and is as useful as the rest. `unjudged` is the total waiting.
`session_id` narrows to one session.
"""
return await adherence_svc.to_judge(
current_user_id(), session_id, sessions=sessions, per_session=per_session,
)
async def judge_adherence(verdicts: list[dict]) -> dict:
"""Record a transcript review's verdicts on rules in force at a moment of a session.
Each item is `{"session_id": "…", "rule_id": N, "at": "work.deliver",
"verdict": "followed"|"broken"|"departed"|"not_applicable",
"evidence": "…"}`, the `session_id`, `rule_id` and `at` as
`adherence_to_judge` listed them. `evidence` is required: what the
transcript shows — the act, the reply, or the passage — so a later reader
can check the verdict. `departed` is for a session that said why it did
not follow the rule; `broken` for work that went against it without one.
A review replaces the session's own account (a later, closer reading
wins), except where an `enforce` rule refused the act, which stands.
Returns `judged` and `refused`, each refused item with why.
"""
return await adherence_svc.judge(current_user_id(), verdicts)
def register(mcp) -> None:
mcp.tool(name="list_moments")(list_moments)
mcp.tool(name="list_reply_shapes")(list_reply_shapes)
@@ -242,3 +401,10 @@ def register(mcp) -> None:
mcp.tool(name="rule_moment_proposals")(rule_moment_proposals)
mcp.tool(name="judge_rule_moments")(judge_rule_moments)
mcp.tool(name="rule_misfired")(rule_misfired)
mcp.tool(name="rules_to_weigh")(rules_to_weigh)
mcp.tool(name="propose_rule_weights")(propose_rule_weights)
mcp.tool(name="rule_weight_proposals")(rule_weight_proposals)
mcp.tool(name="judge_rule_weights")(judge_rule_weights)
mcp.tool(name="rule_adherence")(rule_adherence)
mcp.tool(name="adherence_to_judge")(adherence_to_judge)
mcp.tool(name="judge_adherence")(judge_adherence)
+4 -1
View File
@@ -144,7 +144,10 @@ async def create_note(
Args:
title: Note title (required).
body: Markdown content. Supports [[wikilinks]] to other notes by title.
body: Markdown content. Cite another record as `#N` (note, task,
lesson, snippet), `milestone N` or `rule N`; the web UI links each
one, titled on hover, and lists it in the target's backlinks.
`[[Title]]` links a note by its title.
tags: List of plain-string tags without # prefix, e.g. ["python", "ideas"].
project_id: Associate with a project (use 0 for no project / orphan note).
system_ids: Ids of the project's Systems to associate this note with
+38 -1
View File
@@ -128,6 +128,12 @@ async def enter_project(project_id: int) -> dict:
create it with create_system rather than leaving the area unmodelled. Read
a subsystem's accumulated records with list_system_records. Each is id and name; get_system has the charter.
`rulings_undelivered`, present only when it applies, lists Systems that
carry rulings but name no files. A ruling reaches a session when a
command or edit touches its System's files, so these rulings reach
nobody. Name each area's files with
`update_system(id, path_patterns=[...])`, globs from the repo root.
`platforms` is what the project is built on or ships as
— Android app, container image, Go, … — each with how it is known
(`declared` by a person, `detected` from a bound repo). They decide which
@@ -140,7 +146,10 @@ async def enter_project(project_id: int) -> dict:
version (`needs_recheck`) — each with the list_family_adoptions call that
lists them. Answer an unassessed idea when your work reaches its area
(get_family_adoption, then assess_family_adoption, or classify the code
against it); the family-canon skill has the order.
against it); the family-canon skill has the order. It also counts this
project's own records that a trigger proposed as family ideas and nobody
has evaluated (`candidates`), naming them: this project's session holds
their context, so it is the one asked to promote or retire each.
`inception` appears ONLY when the project is yours and
nobody has decided what it inherits: it carries the current defaults
@@ -278,6 +287,7 @@ async def enter_project(project_id: int) -> dict:
},
"pattern_coverage": coverage_svc.coverage_line(coverage) if coverage else None,
"systems": [{"id": s.id, "name": s.name} for s in systems],
**_rulings_undelivered(systems),
"platforms": platforms,
"design_system": design_system,
"milestone_summary": milestone_summary,
@@ -311,13 +321,21 @@ async def enter_project(project_id: int) -> dict:
out["systems_bootstrap"] = systems_bootstrap
# Family canon: counts only, attached when one is
# non-zero. A readout must never fail the handshake it rides on.
family_failed = False
try:
family = await family_adoption_svc.family_readout(uid, project_id)
except Exception:
logger.warning("family readout failed for project %s", project_id, exc_info=True)
family = None
family_failed = True
if family:
out["family"] = family
# Every entry is recorded, with or without the line, so a later review
# can say whether a project's sessions saw what it owes
# (retrieval_telemetry's `family_line`). In the background, so the
# handshake never waits on its own telemetry.
spawn(family_adoption_svc.record_entry(uid, project_id, family, failed=family_failed),
site="family_entry_record")
if inception_ask:
out["inception"] = inception_ask
# The core reply shape: for a client with no prompt hook,
@@ -355,6 +373,25 @@ async def get_project(project_id: int) -> dict:
return data
def _rulings_undelivered(systems) -> dict:
"""`{"rulings_undelivered": {...}}` when some System's rulings reach no
session, else nothing: the key is absent, not empty, so its presence is
the signal."""
from grimoire.services import system_rulings
missing = system_rulings.undelivered(systems)
if not missing:
return {}
return {"rulings_undelivered": {
"systems": missing,
"why": (
"A System's rulings are shown when a command or edit touches its "
"files. These name no files, so their rulings reach no session."
),
"fix": "update_system(id, path_patterns=[...]) with the area's files as globs from the repo root",
}}
def _inception_choices(design_system_id, seed_systems, platforms=None) -> dict | None:
"""The tool args → an inception choices object, or None when no inception
arg was given at all (a bare create stays undecided and enter_project
+153 -10
View File
@@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone
from grimoire.mcp._context import current_user_id
from grimoire.services import dedup as dedup_svc
from grimoire.services import moments as moments_svc
from grimoire.services import rule_triggers as rule_triggers_svc
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services import trash as trash_svc
from grimoire.services.lesson_rules import confirmed_lesson_counts
@@ -207,7 +208,7 @@ def _rule_summary(r, moments: list[str] | None = None) -> dict:
async def list_rules(
rulebook_id: int = 0, topic_id: int = 0, project_id: int = 0,
with_usage: bool = False, days: int = 0,
with_usage: bool = False, days: int = 0, since: str = "", until: str = "",
) -> dict:
"""List rules — filter by rulebook, topic, and/or project.
@@ -222,6 +223,11 @@ async def list_rules(
them.
days: with `with_usage`, count only the last N days; 0 = everything
recorded.
since, until: with `with_usage`, count only events in [since, until),
each an ISO date or datetime (a bare `until` date covers that
whole day). They replace `days`. Use them for a review read after
its period, so a later deploy stays out of the counts. An
unparseable bound is refused with `error`.
rulebook_id and topic_id AND-combine; project_id lists a project's rules
on its own. Ownership-scoped.
@@ -234,6 +240,16 @@ async def list_rules(
ones that surface and get opened.
"""
uid = current_user_id()
window_since = window_until = None
if with_usage and (since or until):
from grimoire.services.retrieval_telemetry import resolve_window
try:
window_since, window_until = resolve_window(days or 30, since or None, until or None)
except ValueError as exc:
return {"error": str(exc)}
if not since and not days:
# An end with no start or count means everything up to that end.
window_since = None
rows = await rulebooks_svc.list_rules(
user_id=uid,
rulebook_id=rulebook_id or None,
@@ -245,10 +261,12 @@ async def list_rules(
mounted = await rulebooks_svc.list_rule_moments(ids)
rules = [_rule_summary(r, mounted.get(r.id)) for r in rows]
if with_usage:
since = (
if window_until is not None:
usage = await usage_for_rules(ids, since=window_since, until=window_until)
else:
usage = await usage_for_rules(ids, since=(
datetime.now(timezone.utc) - timedelta(days=days) if days > 0 else None
)
usage = await usage_for_rules(ids, since=since)
))
lessons = await confirmed_lesson_counts(uid, ids)
for row in rules:
row["usage"] = usage.get(row["id"], empty_rule_usage())
@@ -342,6 +360,8 @@ async def create_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict:
"""Create a new rule in a rulebook (a SHARED rule — keep it general).
@@ -530,6 +550,30 @@ async def create_rule(
constraint expires when the ground under it moves, not on a
schedule. Pairs with verify_with; both empty is the normal case.
order_index: Display order within the topic (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. Declare
hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule
already in this topic BLOCKS creation and returns its id so you update
it instead. Set true only for a genuinely distinct rule. A rule or
@@ -539,6 +583,7 @@ async def create_rule(
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not force:
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
if dup is not None:
@@ -553,8 +598,9 @@ async def create_rule(
arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
@@ -565,6 +611,8 @@ async def create_project_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict:
"""Create a rule scoped to a single project (no rulebook needed).
@@ -640,6 +688,30 @@ async def create_project_rule(
expires_when: The state under which the rule stops being true — see
create_rule. A state, not a date.
order_index: Display order within the project's rule list (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. Declare
hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule
already on this project BLOCKS creation and returns its id so you
update it instead. Set true only for a genuinely distinct rule. An
@@ -648,6 +720,7 @@ async def create_project_rule(
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
derived_title = title.strip() or statement.strip().split(".")[0][:50]
if not force:
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
@@ -662,8 +735,9 @@ async def create_project_rule(
arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
@@ -675,6 +749,8 @@ async def update_rule(
moments: list[str] | None = None, arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "",
clear_fields: list[str] | None = None,
enforcement: str = "", salience: str = "",
triggers: list[dict] | None = None,
) -> dict:
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged.
@@ -735,9 +811,35 @@ async def update_rule(
expires_when: The state under which the rule stops being true. A
state, not a date. See create_rule.
clear_fields: Names of fields to empty, as above.
enforcement: What this rule does when it arrives. `inform` (the
default for a new rule) puts a line beside the work. `hold` makes the reply or
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. Declare
hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit either to leave it unchanged.
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
fields: dict = {}
if title:
fields["title"] = title
@@ -759,12 +861,16 @@ async def update_rule(
fields["expires_when"] = expires_when
if order_index >= 0:
fields["order_index"] = order_index
if enforcement:
fields["enforcement"] = enforcement
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields,
)
if rule is None:
raise ValueError(f"rule {rule_id} not found")
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
# ── Preferences ─────────────────────────────────────────────────────────
@@ -786,7 +892,8 @@ async def create_preference(
arose_from_id: int, why: str = "", how_to_apply: str = "",
order_index: int = 0, system_ids: list[int] | None = None,
moments: list[str] | None = None,
force: bool = False,
force: bool = False, salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict:
"""Record how the operator wants work done. No approval loop — write it.
@@ -860,6 +967,20 @@ async def create_preference(
done rather than what it is about: a rule on when work counts as
finished belongs at work.finish and reply.report, where nothing
said resembles it. Replaces the set; [] clears it.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. For a genuinely distinct
preference, not for one that is "mostly" different — a mostly
different preference is an update. A RULE that already answers
@@ -869,6 +990,7 @@ async def create_preference(
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not when_to_apply.strip():
raise ValueError(
"when_to_apply is required: a preference with no trigger never "
@@ -893,8 +1015,9 @@ async def create_preference(
title=title, statement=statement, when_to_apply=when_to_apply,
kind="preference", arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index,
salience=salience,
)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "preference"))
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
@@ -905,6 +1028,8 @@ async def update_preference(
how_to_apply: str = "", order_index: int = -1,
system_ids: list[int] | None = None,
moments: list[str] | None = None, clear_fields: list[str] | None = None,
salience: str = "",
triggers: list[dict] | None = None,
) -> dict:
"""Bring a preference up to date. Doing this mid-work is expected.
@@ -959,9 +1084,25 @@ async def update_preference(
moments: Replaces the moments this preference arrives at (see
create_preference); omit to leave them alone.
when_to_apply: The moment it applies, in session vocabulary. See above.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit to leave it unchanged.
"""
uid = current_user_id()
moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not arose_from_id:
raise ValueError(
"arose_from_id is required: this edit is the record of how the "
@@ -981,12 +1122,14 @@ async def update_preference(
fields["how_to_apply"] = how_to_apply
if order_index >= 0:
fields["order_index"] = order_index
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields,
)
if rule is None:
raise ValueError(f"rule {rule_id} not found")
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
async def rule_history(rule_id: int, version_id: int = 0) -> dict:
+67 -3
View File
@@ -361,7 +361,7 @@ async def search(
async def retrieval_telemetry(
days: int = 30, near_miss_samples: int = 0,
days: int = 30, near_miss_samples: int = 0, since: str = "", until: str = "",
) -> dict:
"""What the retrieval telemetry says about YOUR surfaces, over a window.
@@ -439,6 +439,12 @@ async def retrieval_telemetry(
Read a null as "unknown", never as a zero: an artifact read as a
measurement mis-scopes the surface.
`gate` is the cue gate's share, on an arm that has one: `gated_calls`
carried a gate decision and `declined_by_gate` returned ranked results
the gate then withheld. Such an arm logs `result_count` before the gate
decides, so its declines are `zero_result_calls` plus `declined_by_gate`.
`null` when no row in the window carried a gate decision.
`usage` — NOTES ONLY, from `note_usage_events`, at the per-note grain
`retrieval_logs` cannot be indexed at: `surfaced` (ranked surfacings — a
scored surface CHOSE the record), `ambient` (the rest), `pulled` split into
@@ -528,6 +534,37 @@ async def retrieval_telemetry(
a ratio of opens would read near zero on an arm that is working.
`system_usage_failed: true` means its read broke and the zeros mean nothing.
`record_reach` — how every non-rule record reached a session, from
`record_deliveries`: per kind (`snippet`, `note`, `lesson`, `task:issue`,
…), each way it arrived — `pushed` by a hook, `asked` (a result of a
`search` the session ran itself), `direct` (opened with nothing
delivering it first) — with `delivered` and `opened`, and per door in
`sources`. It is the readout that says whether a kind is found by being
pushed or by being asked for, which `usage` cannot: a pull there does not
say which door led to it. Counts only sessions whose plugin reports opens.
`gates` — every time a Grimoire gate stood in front of a tool call, from
`gate_stops`, as the plugin hook that made the stop reported it. In
`by_gate`, for each of `enforce` and `hold` (a moment rule's
enforcement), `checkpoint` (the act checkpoint on a command), `fence`
(the project fence asking the operator) and `reply` (a rule holding the
finished reply for one read), it gives:
- `stops`: calls denied or put to the operator;
- `cleared`: stops the session cleared by opening the rule, which is how
a hold is meant to clear;
- `misfired`: stops whose rule the session then reported with
`rule_misfired`, a stop at the wrong moment;
- `let_through`: calls a hold would have stopped, let through because
the session's stop budget was spent;
- `ran`: stopped calls that ran after all. For the fence that is the
operator's yes; an ask without it was declined, or the call failed.
`by_rule` gives the same per rule and place, most stops first. `fence`
gives the asks per tool and target project. Read `misfired` and
`let_through` before changing a rule's enforcement. A rule that stops
work and is then called a misfire has the wrong moment or trigger; a
budget that keeps letting calls through is spent on rules that stop
too often. `gates_failed: true` means the read broke.
`judged` — whether the lines RELATED, from `retrieval_judgments`:
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
on a sample of logged menus, `within_budget` against `beyond_budget` and
@@ -583,7 +620,9 @@ async def retrieval_telemetry(
Only ever raised for unbidden arms known to log unconditionally: a
search returning a list every time is doing its job, and an arm whose
zeros were never written would flag a LOGGING bug while pointing you at
a threshold.
a threshold. A gated arm's declines include the calls its cue gate
withheld (`gate.declined_by_gate`), since it logs its ranked results
before the gate decides.
- `band_hugs_floor` — the weakest tenth of what an arm returns sits on
its floor. The bar is doing the selecting and the score is not, so
moving that floor changes how MUCH you get, not how good it is.
@@ -650,16 +689,41 @@ async def retrieval_telemetry(
from an empty window, which would otherwise read as every counter at
zero.
`family_line` — how often each project was entered and how often the
entry carried the family line, from the `enter_project` rows: per
project, `entries`, `entries_with_line`, the first and last time the line
was shown, and the counts it showed most recently. It answers "did this
project's sessions see the family canon it owes", which no other block
can.
A CLOSED WINDOW FOR A REVIEW READ LATE. `days` counts back from now, so
a review read two weeks after its period also counts whatever shipped
since. Pass `since` and `until` to fix both ends to the period under
review; the response's `since` and `until` name the window that was used.
Args:
days: window size, default 30. Clamped to at least 1.
days: window size, default 30. Clamped to at least 1. Ignored when
`since` is given.
near_miss_samples: 0-20, default 0. How many of each source's highest
scoring DECLINES to list by record, with the query that asked.
Pass it when you are about to move a threshold; leave it off
otherwise. See the near-miss section above for why a percentile
alone cannot settle a bar.
since: start of the window, an ISO date or datetime (UTC when no
zone is given). Empty = `days` before `until`.
until: end of the window, exclusive. A bare date covers that whole
day. Empty = now. An unparseable bound, or `since` not before
`until`, is refused with `error`.
"""
from grimoire.services.retrieval_telemetry import resolve_window
try:
start, end = resolve_window(days, since or None, until or None)
except ValueError as exc:
return {"error": str(exc)}
return await retrieval_summary(
current_user_id(), days=days, near_miss_samples=near_miss_samples,
since=start, until=end,
)
+77 -4
View File
@@ -26,6 +26,11 @@ async def classify_shapes(
- `variant` of snippet N — a deliberate, named departure. `reason`
(the why) is REQUIRED; it is the record.
- `exempt` — judged genuinely one-off. `reason` REQUIRED.
- `redundant` — should be removed: another shape already does its
job. `covered_by` {path, symbol} names that shape and `reason` says
why it covers this one — for a test, what the covering test checks
that this one also checked. test_guard_groups lists the candidates.
- `unused` — should be removed: nothing needs it. `reason` REQUIRED.
- `canonical` of snippet N — this row IS the snippet's reference
(rarely set by hand; the coverage sync stamps these mechanically).
- `unclassified` — withdraw a judgment; the shape rejoins the todo.
@@ -38,7 +43,7 @@ async def classify_shapes(
Args:
project_id: The project whose ledger is being judged.
classifications: Objects of {path, symbol, status, kind?, snippet_id?,
idea_id?, reason?, reason_code?}. path+symbol name the shape exactly as
idea_id?, reason?, reason_code?, covered_by?}. path+symbol name the shape exactly as
list_shapes shows it; kind ("sym"/"css") narrows when one file
defines both. snippet_id is required for canonical/instance/
variant — or idea_id, a family idea: the shape is then judged
@@ -46,7 +51,7 @@ async def classify_shapes(
language, or its first reference when none is in that language
(an idea is shared across languages: a Python shape can be an
instance of an idea whose reference is Go). reason is required
for variant/exempt. reason_code is
for variant/exempt/redundant/unused. reason_code is
an OPTIONAL index beside the prose (one of: scoped-css,
one-off-handler, test-helper, convention-plumbing, pure-helper,
generated, script, typed-record) so the ledger can be filtered
@@ -106,7 +111,11 @@ async def list_shapes(
(fed by the coverage refresh). Filters compose:
Args:
status: canonical | instance | variant | exempt | scoped | unclassified.
status: canonical | instance | variant | exempt | redundant | unused |
scoped | test | unclassified. `test` is the sync's stamp on a
test case linked to what it guards; a test case linked to
nothing stays `unclassified`. `redundant`/`unused` are the removal
verdicts: the row stays until the code goes.
`scoped` is the sync's mechanical stamp on one-offs by
construction (a Vue component's scoped <style> rules and its
<script setup> functions): accounted for, not judged, still
@@ -440,10 +449,74 @@ async def move_path(project_id: int, from_path: str, to_path: str) -> dict:
return out
async def test_guard_groups(project_id: int, top: int = 10) -> dict:
"""Tests that guard exactly the same thing from different files — the
suite's merge-or-remove queue.
Each coverage refresh reads, for every test in the project's bound repos
(a definition named test* in a test file), which product shapes its body
reaches — directly or through test helpers, mocks excluded — and groups
tests whose sets match exactly across files. Within one file a shared
subject is a table of cases, so it never forms a group.
Groups come smallest first, each with a `kind`. "copies" (three tests
or fewer) is where one test most often checks nothing another does not.
"area" is one feature tested from several files: a test that drives a
feature through its entry point reaches exactly that entry point,
whatever behaviour it checks, so the group gathers the feature's
tests. Its usual verdict is to fold the scattered files' cases into
the feature's own test file, and to remove only the ones another
test already covers.
A group is a candidate, not a verdict. Read the tests, then either:
- classify_shapes one of them `redundant` with `covered_by` naming the
test that checks everything it checks, and a reason — then delete it;
- review_test_group with the reason each test earns its place, which
takes the group out of this list until a test joins or leaves it.
Each test carries `signals`, weak-test evidence from its body (never a
verdict on its own): `signature` pins how the code is declared,
`mock-only` asserts only that mocks were called, `source-text` reads
source as text.
Args:
project_id: The project whose suite to read.
top: How many groups to return, smallest first; `count` says how many
there are.
Returns {"count": N, "groups": [{"key", "kind", "files",
"guards": [{id, path, symbol}],
"tests": [{id, path, symbol, status, signals}]}]}.
"""
from grimoire.services import access
from grimoire.services import test_guards
uid = current_user_id()
if not await access.can_read_project(uid, project_id):
raise ValueError(f"project {project_id} not found")
return await test_guards.guard_groups(project_id, top=max(0, min(top, 100)))
async def review_test_group(project_id: int, test_ids: list[int], reason: str) -> dict:
"""Record that a group from test_guard_groups guards distinct behaviours
and every test in it stays. The group leaves the list until a test joins
or leaves it.
Args:
project_id: The project the tests belong to.
test_ids: The group's test ids, as test_guard_groups lists them.
reason: What each test checks that the others do not. Required.
"""
from grimoire.services import test_guards
uid = current_user_id()
return await test_guards.review_group(uid, project_id, test_ids, reason=reason, by="agent")
def register(mcp) -> None:
for fn in (
classify_shapes, classify_shapes_by_rule, list_shapes,
refresh_pattern_coverage, confirm_shape_proposals, shape_history,
stamps_to_review, move_path,
stamps_to_review, move_path, test_guard_groups, review_test_group,
):
mcp.tool(name=fn.__name__)(fn)
+34 -1
View File
@@ -18,6 +18,8 @@ Sentinels (preserved from existing fable-mcp):
"""
from __future__ import annotations
import logging
from grimoire.mcp._context import current_user_id
from grimoire.mcp.tools import systems as systems_tools
from grimoire.services import access as access_svc
@@ -34,6 +36,7 @@ from grimoire.services.notes import minted_kind
from grimoire.services import placement as placement_svc
from grimoire.services import planning as planning_svc
from grimoire.services import record_batch as batch_svc
from grimoire.services import record_kinds, record_links
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services import systems as systems_svc
from grimoire.services import task_logs as task_logs_svc
@@ -43,6 +46,8 @@ from grimoire.services.record_refs import refuse_guessed_ids
from grimoire.services.text import elide
from grimoire.services import moment_delivery
logger = logging.getLogger(__name__)
# A work log entry is prose, often long — the discipline asks for what was
# decided and why, not a line of status. Two caps, not one, because the entries
@@ -271,7 +276,9 @@ async def create_task(
Args:
title: Task title (required).
body: Markdown description / notes for the task.
body: Markdown description / notes for the task. Cite another record
as `#N` (note, task, lesson, snippet), `milestone N` or `rule N`;
the web UI links each one and lists it in the target's backlinks.
status: Initial status — one of: todo (default), in_progress, done, cancelled.
priority: One of: low, medium, high, or 'none'. Omit (empty string) to leave unset.
project_id: Associate with a project (0 = no project).
@@ -408,6 +415,11 @@ async def update_task(
reconstructing them, because a remembered milestone title or "next step"
reads exactly like a real one when it is wrong.
Setting a task `in_progress` also returns `records_in_area` when the
task's areas hold notes or open issues: one line naming them by id with
the call that opens each. Read the ones that bear on the work before
starting it.
Closing a task (done or cancelled) also returns `reply_shape`, the
default shape of the completion report you are about to write, and
`report_back`: a one-line reminder of what that reply should cover. The
@@ -463,11 +475,29 @@ async def update_task(
# Owed family adoptions filed while the task was open — work now
# waiting in some project, which the report names.
await family_adoption_svc.attach_owed_adoptions(uid, data, note)
if status == "in_progress":
await _attach_area_records(uid, task_id, data)
return await moment_delivery.attach_moment_rules(
uid, "update_task", {"status": status, "project_id": project_id}, data,
)
async def _attach_area_records(uid: int, task_id: int, data: dict) -> None:
"""Name, by id, what is recorded in the areas of a task being taken up:
the `work.start` row of the kind×moment table says which kinds. Absent
when the task has no area or nothing is recorded there."""
try:
kinds = await record_kinds.kinds_for(uid, "work.start")
found = await record_links.area_records(uid, task_id, kinds)
line = record_kinds.pointer_line(
found, "Recorded in this task's areas", capped_at=record_links.AREA_DEPTH,
)
if line:
data["records_in_area"] = line[0].removeprefix("> ")
except Exception: # noqa: BLE001 - a decoration never breaks the payload
logger.debug("area records for task %s could not be attached", task_id, exc_info=True)
async def add_task_log(task_id: int, content: str) -> dict:
"""Append a timestamped progress log entry to a Grimoire task.
@@ -482,6 +512,9 @@ async def add_task_log(task_id: int, content: str) -> dict:
cannot get from the body or the diff is what you tried, what you ruled
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
+10 -1
View File
@@ -60,6 +60,10 @@ from grimoire.models.retrieval_log import RetrievalLog # noqa: E402, F401
from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401
from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401
from grimoire.models.gate_stop import GateStop # 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
@@ -81,11 +85,16 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
)
# After notes and rules: it foreign-keys both.
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
from grimoire.models.lesson_situation import LessonSituation # noqa: E402, F401
# After rules: it foreign-keys them.
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
from grimoire.models.code_shape import ( # noqa: E402, F401
CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeGuard, CodeShapeGuardReview,
CodeShapeUse,
)
from grimoire.models.system import System, RecordSystem # noqa: E402, F401
from grimoire.models.design_system import DesignSystem, DesignToken # noqa: E402, F401
# After notes, projects and rulebook topics: family canon foreign-keys all
+96 -2
View File
@@ -23,8 +23,24 @@ from grimoire.models.base import TimestampMixin, iso
# accounted for without a human judging them, so `exempt` keeps meaning "a
# person looked"; the proposer, derive grouping and divergence still see them,
# and any judgment (instance/variant/exempt) overrides the stamp.
SHAPE_STATUSES = ("canonical", "instance", "variant", "exempt", "scoped", "unclassified")
SHAPE_CLASSIFIERS = ("agent", "audit", "hook", "mechanical", "import")
#
# `redundant` and `unused` are the two verdicts that say a shape should GO:
# redundant names the shape that already covers it (`covered_by_id` — for a
# test, the test that guards the same thing more fully), unused says nothing
# needs it. Both take a reason. The row stays until the code is removed and
# the next sync marks it vanished, which is how the verdict is carried out.
#
# `test` is the sync's mechanical stamp on a test case that is linked to
# something it guards (services/test_guards): accounted for by what it
# protects, without anyone judging it one-off. A test case linked to nothing
# stays `unclassified`, the todo, because nothing says what it is for. Any
# judgment overrides the stamp, and losing every link withdraws it.
SHAPE_STATUSES = (
"canonical", "instance", "variant", "exempt", "redundant", "unused",
"scoped", "test", "unclassified",
)
# `person` is a judgment made in the web UI.
SHAPE_CLASSIFIERS = ("agent", "audit", "hook", "mechanical", "import", "person")
# The reason catalogue: an OPTIONAL code beside the prose reason on
# variant/exempt rows, so the ledger can be filtered and aggregated by kind
@@ -147,6 +163,13 @@ class CodeShape(Base, TimestampMixin):
diverges_from: Mapped[int | None] = mapped_column(
BigInteger, ForeignKey("notes.id", ondelete="SET NULL"), nullable=True
)
# A `redundant` row's cover: the shape that does its job already.
covered_by_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("code_shapes.id", ondelete="SET NULL"), nullable=True
)
# A test's weak-test signals from the last sync (services/test_guards
# SIGNALS), comma-separated; evidence for a reviewer, never a verdict.
test_signals: Mapped[str] = mapped_column(Text, default="")
@property
def proposal(self) -> dict | None:
@@ -184,6 +207,8 @@ class CodeShape(Base, TimestampMixin):
"classified_sha": self.classified_sha,
"recheck_at": iso(self.recheck_at),
"diverges_from": self.diverges_from,
"covered_by_id": self.covered_by_id,
"test_signals": [x for x in (self.test_signals or "").split(",") if x],
"created_at": iso(self.created_at),
"updated_at": iso(self.updated_at),
}
@@ -213,6 +238,8 @@ class CodeShape(Base, TimestampMixin):
out["diverges_from"] = self.diverges_from
if self.recheck_at is not None:
out["recheck"] = True
if self.covered_by_id is not None:
out["covered_by_id"] = self.covered_by_id
return out
@@ -366,3 +393,70 @@ class CodeShapeEvent(Base):
"commit": self.commit,
"at": iso(self.at),
}
# How a guard edge was established. `static` is the coverage sync's read of
# a test's body (services/test_guards.link_tests); the vocabulary is a list
# so a later basis has a name without a schema change.
GUARD_BASES = ("static",)
class CodeShapeGuard(Base):
"""One guard edge: a test shape -> what it exercises. Either another
shape (`guarded_id`) or, when the test names a repo file in a string
(reads its source, runs a script), that file's `path`.
Mechanical and fully recomputable: every coverage sync rebuilds a repo's
edges from its archive, so the table is not backed up (see
services/backup._NOT_INCLUDED). Cascades with both shapes.
"""
__tablename__ = "code_shape_guards"
__table_args__ = (
Index("ix_code_shape_guards_test", "test_id"),
Index("ix_code_shape_guards_guarded", "guarded_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
test_id: Mapped[int] = mapped_column(
Integer, ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=False
)
guarded_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=True
)
path: Mapped[str | None] = mapped_column(Text, nullable=True)
basis: Mapped[str] = mapped_column(Text, nullable=False, default="static")
class CodeShapeGuardReview(Base):
"""A reviewed group of tests that guard the same thing, judged to be
distinct behaviours worth keeping. Keyed by its members
(test_guards.group_key), so a test joining or leaving the group puts it
back in front of a reviewer. A judgment, so it is backed up."""
__tablename__ = "code_shape_guard_reviews"
__table_args__ = (
UniqueConstraint("project_id", "group_key", name="uq_code_shape_guard_reviews_group"),
)
id: Mapped[int] = mapped_column(primary_key=True)
project_id: Mapped[int] = mapped_column(
Integer, ForeignKey("projects.id", ondelete="CASCADE"), nullable=False
)
group_key: Mapped[str] = mapped_column(Text, nullable=False)
verdict: Mapped[str] = mapped_column(Text, nullable=False, default="distinct")
reason: Mapped[str] = mapped_column(Text, nullable=False, default="")
reviewed_by: Mapped[str] = mapped_column(Text, nullable=False)
reviewed_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc)
)
def to_dict(self) -> dict:
return {
"project_id": self.project_id,
"group_key": self.group_key,
"verdict": self.verdict,
"reason": self.reason,
"reviewed_by": self.reviewed_by,
"reviewed_at": iso(self.reviewed_at),
}
+3 -1
View File
@@ -10,7 +10,9 @@ from grimoire.models import Base
# native pgvector `vector(384)` (see migration 0067) so similarity is ranked in
# Postgres by `<=>` rather than by a full-table Python cosine scan. The semantic
# searches rank the CALLER'S in-scope chunks exactly rather than through the
# HNSW index, which ranks before it filters (see embeddings._rank_scoped).
# HNSW index, which ranks before it filters (see embeddings._rank_scoped). The
# column is stored inline (`STORAGE MAIN`, migration 0139), so that exact pass
# reads each vector from its row rather than from TOAST.
EMBEDDING_DIM = 384
+90
View File
@@ -0,0 +1,90 @@
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
# The gates that can stop a tool call, as the plugin hooks name them.
ENFORCE = "enforce" # a moment rule set to enforce: refused every time
HOLD = "hold" # a moment rule set to hold: one read before the act
CHECKPOINT = "checkpoint" # the act checkpoint on a command (tool-rules)
FENCE = "fence" # the project fence: the operator is asked
REPLY = "reply" # a rule holding the finished reply for one read
GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY)
# What the hook did with it.
STOPPED = "stopped" # the call was denied, the reason shown instead
LET_THROUGH = "let_through" # would have held, but the session cap was spent
ASKED = "asked" # the fence put the call to the operator
OUTCOMES = (STOPPED, LET_THROUGH, ASKED)
class GateStop(Base):
"""One time a Grimoire gate stood in front of a tool call.
WHY IT EXISTS. A rule set to enforce or hold, the act checkpoint, the
project fence and the hold on a finished reply (the Stop hook, `tool` =
"reply") are the only places Grimoire stops work rather than
commenting on it, and a stop that fires at the wrong moment costs a
round trip every time. Whether the plugin actually stops a call is
decided client-side (the per-rule and per-session caps in
`grimoire_checkpoint_allowed`), so the server's own decision is not the
record: the hook reports what it did, here.
`cleared_at` is stamped when the session opened the rule after the stop,
which is how a hold is meant to clear. `ran_at` is stamped when the
stopped call ran after all, which for the fence means the operator said
yes (the harness reports a PostToolUse only for a call that ran); the
tool call's own id (`call_id`) ties the two. A fence ask with no `ran_at`
was declined, or the call failed.
`at` is the moment the rule was reached at, or the arm that found it.
`target` is the project a fenced act would have landed in.
FK-free, like the other telemetry tables: the record that a rule kept
stopping work outlives the rule, since it is the case for changing it.
"""
__tablename__ = "gate_stops"
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)
gate: Mapped[str] = mapped_column(Text, nullable=False)
outcome: Mapped[str] = mapped_column(Text, nullable=False)
rule_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
tool: Mapped[str] = mapped_column(Text, nullable=False)
at: Mapped[str | None] = mapped_column(Text, nullable=True)
target: Mapped[str | None] = mapped_column(Text, nullable=True)
call_id: Mapped[str | None] = mapped_column(Text, nullable=True)
stopped_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
cleared_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
ran_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
Index("ix_gate_stops_session_rule", "user_id", "session_id", "rule_id", "stopped_at"),
Index("ix_gate_stops_stopped_at", "stopped_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"gate": self.gate,
"outcome": self.outcome,
"rule_id": self.rule_id,
"tool": self.tool,
"at": self.at,
"target": self.target,
"call_id": self.call_id,
"stopped_at": iso(self.stopped_at),
"cleared_at": iso(self.cleared_at),
"ran_at": iso(self.ran_at),
"plugin": self.plugin,
}
+77
View File
@@ -0,0 +1,77 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import CreatedAtMixin, iso
from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
__all__ = [
"CONFIRMED", "KINDS", "MOMENT", "NONE", "REJECTED", "SITUATION_STATES", "SOURCES",
"SUGGESTED", "TRIGGER", "LessonSituation",
]
# The same three states as a lesson's link to a rule. CHECK
# ck_lesson_situations_state (migration 0137).
SITUATION_STATES = LINK_STATES
# What a row names. `moment` — a catalog moment key: the lesson arrives when
# the work reaches it. `trigger` — a typed predicate on the act (tool, path,
# command, keyword), stored as `rule_field_judgments.trigger_value` writes it,
# so it is matched exactly as a rule's trigger is. `none` — the lesson was
# read and no situation fits it; it is reached by meaning alone, and the row
# keeps it out of the next pass's queue. CHECK ck_lesson_situations_kind.
MOMENT, TRIGGER, NONE = "moment", "trigger", "none"
KINDS = (MOMENT, TRIGGER, NONE)
# `pass` — an agent read the lesson and proposed; `edit` — a person set the
# lesson's situations directly. CHECK ck_lesson_situations_source.
SOURCES = ("pass", "edit")
class LessonSituation(Base, CreatedAtMixin):
"""When a lesson applies, as something the work can be checked against.
One row per (lesson, kind, value):
- ``suggested`` — proposed by a pass. Delivers nothing until judged.
- ``confirmed`` — the lesson arrives when this moment is reached or this
trigger matches the act, once per session.
- ``rejected`` — judged not to be when it applies, kept with the reason
so the same value is never proposed again.
"""
__tablename__ = "lesson_situations"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
lesson_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("notes.id", ondelete="CASCADE"), index=True,
)
kind: Mapped[str] = mapped_column(Text)
value: Mapped[str] = mapped_column(Text, default="", server_default="")
state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
# For a suggestion, what the proposer read in the lesson; for a judgment,
# why it was confirmed or rejected.
note: Mapped[str | None] = mapped_column(Text, nullable=True)
judged_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True,
)
__table_args__ = (
UniqueConstraint("lesson_id", "kind", "value", name="uq_lesson_situations_value"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"lesson_id": self.lesson_id,
"kind": self.kind,
"value": self.value,
"state": self.state,
"source": self.source,
"note": self.note or "",
"judged_at": iso(self.judged_at),
"created_at": iso(self.created_at),
}
+79
View File
@@ -0,0 +1,79 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
# How a record came to be in front of the session.
PUSHED = "pushed" # a hook put it there unasked (auto-inject, the write path, a slot)
ASKED = "asked" # it was a result of a search the session ran itself
DIRECT = "direct" # it was opened with nothing delivering it first in the session
POINTED = "pointed" # named by id in a pointer line, without its title or passage
WAYS = (PUSHED, POINTED, ASKED, DIRECT)
class RecordDelivery(Base):
"""One record put in front of one session, and whether it was opened.
The note-side twin of `rule_deliveries`, for every record kind that is not
a rule (note, snippet, issue, work task, lesson, process). It answers what
`note_usage_events` cannot: a pull there does not say which door led to
it, so "was this note opened because a hook pushed it, because the session
searched for it, or because the session went to it on its own" has no
answer. Here each line is a row against its session, and the open is
stamped on the row it followed.
`way` says how the record arrived (`pushed`, `asked`, `direct`). `source`
is the door: the hook arm (`auto_inject`, `write_path_semantic`,
`write_path_place`, `lesson_slot`, …), `mcp_search` for a search the
session ran, or `direct`. `kind` is the record's kind when it was
delivered (`snippet`, `note`, `lesson`, `process`, `task:issue`,
`task:work`, …), kept on the row so the readout needs no join and survives
the record's deletion.
A `direct` row is written when a session opens a record that nothing
delivered to it within the open window — found through a cross-reference,
a task's own id, the operator naming it. It is delivered and opened at the
same instant, and it is the measure of records a session reaches without
being shown them.
FK-free on `note_id` and `user_id`, like the other telemetry tables, and
pruned after `rule_deliveries.RETAIN_DAYS`.
"""
__tablename__ = "record_deliveries"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
note_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
kind: Mapped[str] = mapped_column(Text, nullable=False)
way: Mapped[str] = mapped_column(Text, nullable=False)
source: Mapped[str] = mapped_column(Text, nullable=False)
delivered_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
# Stamping an open: this session's latest delivery of this record.
Index("ix_record_deliveries_session_note", "user_id", "session_id", "note_id", "delivered_at"),
Index("ix_record_deliveries_delivered_at", "delivered_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"note_id": self.note_id,
"kind": self.kind,
"way": self.way,
"source": self.source,
"delivered_at": iso(self.delivered_at),
"opened_at": iso(self.opened_at),
"plugin": self.plugin,
}
+8
View File
@@ -74,6 +74,12 @@ class RetrievalLog(Base):
# [{"id": int, "score": float, "rank": int}, ...], highest-first.
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True)
# THE CUE-SWAP GATE, on a surface that has one (`cue_gate`): the score a
# line had to reach on this call, and how many lines reached it. Both null
# on an ungated surface. A count beside a null bar is a gate that had too
# few earlier cues to judge by, so nothing found by resemblance spoke.
gate_bar: Mapped[float | None] = mapped_column(Float, nullable=True)
gate_kept: Mapped[int | None] = mapped_column(Integer, nullable=True)
__table_args__ = (
Index("ix_retrieval_logs_created_at", "created_at"),
@@ -99,4 +105,6 @@ class RetrievalLog(Base):
"min_score": self.min_score,
"result_ids": self.result_ids,
"duration_ms": self.duration_ms,
"gate_bar": self.gate_bar,
"gate_kept": self.gate_kept,
}

Some files were not shown because too many files have changed in this diff Show More