Compare commits

...
148 Commits
Author SHA1 Message Date
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
bvandeusen b23275d5f3 Merge pull request 'Release: the proxy hop count is set in Settings → Config' (#221) from dev into main
CI & Build / Python tests (push) Successful in 1m54s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 2m18s
CI & Build / Build & push image (push) Successful in 18s
2026-11-05 10:29:51 -05:00
bvandeusenandClaude Opus 5.5 219bfeac42 docs(6868): the proxy count is set in Settings, with the env var as the starting value
Configuration, the README env table and the features page say Settings
-> Config -> Reverse proxy is where the count is checked and set,
that a saved count wins over TRUSTED_PROXY_HOPS, that Cloudflare in
front of your own proxy is 2, and what a too-low count does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 10:03:22 -05:00
bvandeusenandClaude Opus 5.5 d2267b615f feat(6867): Settings → Config has a Reverse proxy section that shows which count is right
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 1m46s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Successful in 33s
The section opens with a verdict on the admin's own request: the
address Grimoire reads them as, or, through Cloudflare, the count to set
with a button that sets it. Below it are the count with where it came
from, a table of what counts 0-3 would read, and the raw forwarding
chain. A saved count can be cleared back to the environment's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:59:05 -05:00
bvandeusenandClaude Opus 5.5 753a6ccb31 feat(6866): the proxy hop count is an admin setting, and the server shows what each count reads
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 2m1s
CI & Build / Build & push image (push) Successful in 20s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python tests (push) Successful in 1m47s
An admin can save how many reverse proxies stand in front of Grimoire.
A saved count wins over TRUSTED_PROXY_HOPS, which stays the starting
value. Each worker loads it at startup (under a deadline) and re-reads
it every 30s; the worker that saves applies it at once.

GET/PUT /api/admin/proxy returns the count, where it came from, and a
readout of the admin's own request: the socket peer, the forwarding
chains, what counts 0-3 would read, and the count that reads
Cloudflare's visitor when Cloudflare's headers are present. Saves are
audit-logged. A "too many attempts" reply now says where to look when
everyone is being blocked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 09:55:42 -05:00
bvandeusen 85093c859b Merge pull request 'Restore rolls back to a backup; a session can only file issues in another project' (#220) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 31s
CI & Build / Python tests (push) Successful in 1m44s
CI & Build / integration (push) Successful in 1m58s
CI & Build / Build & push image (push) Successful in 30s
2026-11-05 09:29:54 -05:00
bvandeusenandClaude Opus 5.5 49b5ceee41 docs(6856): the scope section says the cross-project rule in fewer lines, so using-grimoire fits its 350-line budget
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m52s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Successful in 17s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:01:22 -05:00
bvandeusenandClaude Opus 5.5 8f8263b347 docs(6856): the plugin's guidance and the docs say what a session may do in another project
CI & Build / TypeScript typecheck (push) Successful in 31s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / Python tests (push) Failing after 1m29s
CI & Build / integration (push) Successful in 2m21s
CI & Build / Build & push image (push) Skipped
using-grimoire, which owns cross-project conduct, now says the one change
to make toward another project is filing an issue with how it was found
and the evidence, and that the plugin asks before anything more. The
features page describes the fence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:52:09 -05:00
bvandeusenandClaude Opus 5.5 ddcac96542 fix(6855): the fence keeps its files where no compaction sweeps them, and builds id lists under mawk
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python tests (push) Successful in 1m52s
CI & Build / integration (push) Successful in 2m21s
CI & Build / Build & push image (push) Successful in 22s
The project a session entered now lives in grimoire-fence, which the
compaction clear never visits, and session end removes it. Arrays of ids
in a tool's input were sent as [,"3","4"] under mawk, which creates an
array element as soon as it is assigned to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:51:34 -05:00
bvandeusenandClaude Opus 5.5 805fda5cb1 feat(6855): the plugin asks before a session writes to a project other than its own
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) Failing after 1m27s
CI & Build / Build & push image (push) Skipped
CI & Build / integration (push) Successful in 2m1s
plugin/hooks/grimoire_project_fence.sh runs as PreToolUse on editor writes,
Bash and Grimoire's tools. A session belongs to the project its starting
directory resolves to (CLAUDE_PROJECT_DIR: a .grimoire marker, else the git
remote's binding). A session that starts outside any project belongs to the
first one it enters, which PostToolUse on enter_project records.

These acts stop on permissionDecision "ask", with the server's reason naming
the other project:
- an edit in another project's repo or a worktree of it;
- a git commit, push, merge, rebase, pull, cherry-pick, revert, tag, am, reset
  or worktree add there, found through git -C, a cd before it, or the shell's
  current directory;
- a Grimoire write that lands in another project.

A live probe showed "ask" holds in bypassPermissions. Filing an issue and
every read go ahead. An edit or git command in the session's own repo, and any
tool named like a read, never calls the server. Grimoire writes send only
their short arguments, so the URL stays small.

When the instance doesn't answer, the act goes ahead and the hook says once
per outage that it couldn't check. check_plugin.py now holds one outage line
per hook and has a smoke event for the fence.

GET /api/plugin/write-scope takes fallback_project_id for the entered project.

tests/test_project_fence.py drives the hook against real git repos and a
stand-in server. tests/test_write_scope.py holds the hook's
FENCE_READ_PREFIXES equal to services/write_scope.READ_PREFIXES. The plugin
README and PACKAGING describe the fence, and the plugin is minted to
2026.11.05.0245.

Milestone 583, step 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:45:37 -05:00
bvandeusenandClaude Opus 5.5 16b1d68ebd fix(6854): the locating arguments that only point are declared as references, and the plugin version is minted
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / Python tests (push) Successful in 1m43s
CI & Build / integration (push) Successful in 2m2s
CI & Build / Build & push image (push) Successful in 22s
The guard caught seven write-tool arguments with a locating name that are not
where the write lands:
- snippet_id on classify_shapes_by_rule and confirm_shape_proposals names the
  canon, not the rows written;
- rule_outcome, rule_misfired and judge_lesson_link record judgments.

REFERENCES lists each one with its reason, and the guard reads it.
READ_PREFIXES names the tool prefixes the fence answers without the server,
and a test holds every write tool to a name outside them.

plugin.json is minted to 2026.11.05.0242 for the PACKAGING.md row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:42:14 -05:00
bvandeusenandClaude Opus 5.5 55f0f96016 feat(6854): the server says which project a pending act would change, and whether this session may do it
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Failing after 1m23s
CI & Build / Build & push image (push) Skipped
CI & Build / Plugin hooks (push) Failing after 11s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 1m53s
GET /api/plugin/write-scope answers the plugin's fence. The session's project
comes from repo / project_id, as every plugin endpoint reads it. The act is
either:
- a directory (target_repo / target_project_id), for a file edit or a git
  command; or
- an MCP call (tool, plus input: the call's short arguments).

It returns allowed, the other projects the act would change, and the reason
the operator is asked. It is a GET so a read-scoped key still fences file
edits and git.

services/write_scope.WRITE_TARGETS lists every write tool with the arguments
that locate its write: a project id, or a task, note, milestone, System, rule,
relation, trash batch, repo or family decision, each traced to its project. A
write that lands in no project (install settings, user-level records, the
judgments a session is asked for anywhere) has an empty entry. The one
cross-project write allowed is create_task(kind="issue") as a new, unplanned,
open issue. A project the caller cannot read is never named.

tests/test_write_scope.py:
- requires an entry for every write tool;
- requires every declared argument to exist on the tool;
- refuses a locating argument (project_id, task_id, milestone_id and the
  rest) that a write tool takes without declaring it.

The integration test traces each locator from real rows.

Milestone 583, step 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 21:39:03 -05:00
bvandeusenandClaude Opus 5.5 373f5bd454 feat(6839): the decision log and the knowledge feed load as you scroll, through one ScrollSentinel
CI & Build / Python lint (push) Successful in 2s
CI & Build / Python tests (push) Successful in 1m38s
CI & Build / integration (push) Successful in 2m9s
CI & Build / Build & push image (push) Successful in 36s
CI & Build / Plugin hooks (push) Successful in 17s
CI & Build / TypeScript typecheck (push) Successful in 33s
ScrollSentinel sits at the foot of a server-paged list and asks for the
next page a screen before the reader reaches it. It asks once per cursor,
forgets the cursor when its element goes, and shows Try again on a failed
page instead of retrying in a loop.

FamilyView's decision log loses its "Older decisions" button. A failed
page shows in place rather than as a toast, and rows already shown are
skipped when a new decision shifts the offset.

KnowledgeView drops its inline IntersectionObserver for the component.
The cursor is the ids consumed, not the items rendered, so a batch that
returns fewer records than it asked for still moves the feed on. A failed
batch puts its ids back and offers Try again, where it used to fail
silently and stop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:14:41 -05:00
bvandeusenandClaude Opus 5.5 846c87629f test(6849): the restore command previews without --yes and rolls back from the tar with it
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 1m39s
CI & Build / integration (push) Successful in 1m51s
CI & Build / Build & push image (push) Successful in 16s
Two integration tests in test_integration_backup_rollback.py drive
grimoire.restore.run on the scheduled backup's tar, written from a full
export of this instance:
- without --yes it exits 4 and nothing changes;
- with --yes it takes the safety backup, then puts back the edited and the
  deleted task and removes the new one.

The file-restore test that expected a refusal "because the database has
accounts" now names the reason it actually refuses: on a live instance, a
backup that records no instance id can't be rolled back to.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:12:30 -05:00
bvandeusenandClaude Opus 5.5 37be3b0bff feat(6849): the command-line restore uses the same rollback, and the docs say how restore works now
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 31s
CI & Build / Python tests (push) Successful in 1m39s
CI & Build / integration (push) Successful in 1m49s
CI & Build / Build & push image (push) Successful in 31s
python -m grimoire.restore <file> prints what the restore would change (the
same preview as Settings) and stops. With --yes it runs
backup_job.rollback_to_backup: the current state is saved first, then the
whole instance goes back to the backup. An empty instance takes any full
backup. A live one only takes a backup of its own, and otherwise exits 3 with
the reason. A v1 backup keeps the copy-in path into an empty instance.

docs/backups.md Restoring is rewritten:
- what a restore puts back and removes;
- the same-instance rule;
- the safety backup;
- what survives;
- the web and command-line ways in.

Its S3 key advice now asks for read as well as write when restoring from the
bucket. README, features, architecture and the API reference follow.

Milestone 582, step 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:08:31 -05:00
bvandeusenandClaude Opus 5.5 1f5e963c35 feat(6848): Settings restore rolls back, from the destination or a file, after a preview
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / Python lint (push) Successful in 1s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m42s
CI & Build / integration (push) Successful in 1m48s
CI & Build / Build & push image (push) Canceled after 22s
The web restore no longer copies a backup in beside the live data.

- GET /api/admin/restore/sources lists the backups at the backup destination,
  newest first.
- POST /api/admin/restore/preview says what a restore would do, changing
  nothing: fresh or rollback, when the backup was taken, and counts now and
  after per kind. A backup that cannot apply here gets a 409 with the reason.
- POST /api/admin/restore?confirm=rollback runs backup_job.rollback_to_backup:
  safety backup, replace, then search rebuilt in the background.

Each takes ?source=<name> (a backup at the destination) or an upload. The
destination path exists because uploads are held to the request-size limit,
and a real instance's backup is far over it. backup_s3.get_file downloads
from a bucket. backup_destination.list_backups/open_backup only accept names
the scheduled backup writes, so a request cannot reach any other file.

Settings -> Data -> Restore from Backup opens RestoreBackupDialog. The dialog:
1. Pick a backup at the destination or a file.
2. Read the preview.
3. Type "roll back".
4. Run it. The dialog then says where the replaced state was saved, and sends
   the user to sign in again.

Closes #6840. Milestone 582, step 4.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:06:07 -05:00
bvandeusenandClaude Opus 5.5 34f8d7060b feat(6847): a rollback first backs up the state it replaces
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 35s
CI & Build / integration (push) Successful in 1m49s
CI & Build / Python tests (push) Successful in 1m40s
CI & Build / Build & push image (push) Successful in 24s
backup_job.rollback_to_backup:
1. Checks the backup can apply here (backup.check_replace, which shares
   _replace_mode with replace_from_backup), refusing before anything is written.
2. Takes the backup lock, so no scheduled backup runs during the rollback.
3. Saves the current store with save_state_before_restore.
4. Replaces the store.

The safety file goes to the backup destination when backups are on and it
takes it. Otherwise it goes to DATA_DIR/pre-restore, with a note when the
destination refused. If neither takes it the rollback does not run. The
result names where the file went.

Milestone 582, step 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:02:26 -05:00
bvandeusenandClaude Opus 5.5 8806ab85b4 feat(6846): replace_from_backup rolls the store back to a full backup by id
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 1m38s
CI & Build / integration (push) Successful in 2m1s
CI & Build / Build & push image (push) Successful in 20s
One transaction:
- Refuse unless the backup is a full one and, on a live instance, carries
  this instance's id. A fresh instance (no records, at most the restoring
  account) takes any full backup and adopts its id.
- Clear first: search vectors and the CSS consumer map (derived); every
  backed-up table nothing outside the backup points at, whole; the settings
  the backup carries; and the identity-table rows the backup lacks. A share
  granted by a removed user goes before the user.
- Write the backup through the same _build_* helpers as the copy-in restore,
  now _load_v2(keep_ids=...). Identity tables (users, projects, milestones,
  notes, rulebooks, topics, rules, systems, design systems, code shapes,
  family decisions) go through _place. That keeps the backup's id and
  merges, so API keys, shares and forge connections of a surviving row stay.
- Reset id sequences past the restored max, and sign every session out.

reindex_after_restore runs the four embedding backfills afterwards. A unit
guard checks that no row kept for outside references cascades from a table
replaced whole. Integration tests cover edits, deletions and new rows put
back, a surviving API key, sessions ending, fresh ids afterwards, foreign or
id-less backups refused, a user export refused, a failure part-way changing
nothing, and a fresh instance adopting the id.

Milestone 582, step 2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:59:48 -05:00
bvandeusenandClaude Opus 5.5 6d8db0bb65 feat(6845): every instance has an id lineage, and every full backup carries it
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / Python tests (push) Successful in 1m37s
CI & Build / integration (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 22s
instance_identity is one row made by migration 0127 with a random id, so an
instance has it before its first account. A full backup carries it in its
header as instance_id (the tar manifest header and the JSON top level);
BACKUP_VERSION is 28. The table rides in _NOT_INCLUDED: a restore decides from
the header value rather than copying a row.

Two stores with the same id number their rows the same way. That is what lets
a later step roll a live instance back by original id, refuse a backup whose
ids would land on unrelated rows, and have a fresh-instance restore adopt the
backup's id (adopt_instance_id).

Milestone 582, step 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:53:45 -05:00
bvandeusenandClaude Opus 5.5 3c01e17559 test(6838): give the test request its socket peer the way Quart reads it
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 1m38s
CI & Build / integration (push) Successful in 2m16s
CI & Build / Build & push image (push) Successful in 38s
Quart takes remote_addr from a Remote-Addr header its ASGI layer writes from
the scope (replacing any the client sent). A test request context does not
read scope_base for it, so the two socket-peer tests saw an empty address.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:37:28 -05:00
bvandeusenandClaude Opus 5.5 dbd6d5b8b5 feat(6838): read the client address and HTTPS from the trusted proxy hop
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python tests (push) Failing after 1m20s
CI & Build / integration (push) Successful in 2m27s
CI & Build / Build & push image (push) Skipped
grimoire/proxy.py is the one reader of X-Forwarded-For and X-Forwarded-Proto.
It takes the entry TRUSTED_PROXY_HOPS in from the right (default 1; a shorter
header reads its leftmost entry; 0 trusts no proxy), so an entry a client puts
left of the proxy's is never believed. Before this, with TRUST_PROXY_HEADERS
on, the leftmost X-Forwarded-For entry keyed the login, register, forgot and
reset rate limits and the audit log, and a client could choose it.

The session cookie is Secure, and HSTS (max-age=31536000) is sent, exactly
when the request is HTTPS by the trusted proxy's word. Plain HTTP is
untouched and nothing redirects. SECURE_COOKIES is gone (a startup warning says
so when it is still set); TRUST_PROXY_HEADERS=false still maps to 0 hops, with
a warning to move to TRUSTED_PROXY_HOPS. Admin audit lines now use the same
client address instead of the socket peer.

The placeholder-key refusal keyed on SECURE_COOKIES, so it now refuses either
placeholder key outright; the instance makes its own key when none is set.

Family idea #5004 (IsHTTPS, trusted-hop X-Forwarded-Proto), canon v2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:32:20 -05:00
bvandeusen 0216634bd4 Merge pull request 'dev → main: a name defined in two packages counts only in the canon's own (#6495)' (#219) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 15s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / integration (push) Successful in 1m28s
CI & Build / Python tests (push) Successful in 2m13s
CI & Build / Build & push image (push) Successful in 1m24s
2026-10-26 22:26:20 -04:00
bvandeusenandClaude Opus 5.5 b87178d261 fix(6495): a name defined in two packages counts only in the canon's own
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / integration (push) Successful in 1m22s
CI & Build / TypeScript typecheck (push) Successful in 37s
CI & Build / Python tests (push) Successful in 1m59s
CI & Build / Build & push image (push) Successful in 43s
A by-name reference edge could not tell two definitions of one name apart:
in a Go repo that defines `file` as importRun.file (internal/files, the
canon) and as sftpRun.file (internal/replication), a mirror test calling
`m.file(` was recorded as a use of the canon.

names_canon now takes defined_at, every repo path that defines each name,
in place of the shape file's own names. The own-file rule is unchanged.
When the repo also defines the canon's name somewhere the canon is not
recorded, a mention counts only from the canon's own package: the
directory of a file location exactly, or under a directory location.
A name defined once resolves as before. Proposer version 8 -> 9, so the
next coverage refresh re-reads every row and replaces its reference edges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 20:05:09 -04:00
bvandeusen 67ea21b787 Merge pull request 'dev → main: drop cross-project hook uses edges (#6483), plain-word calls need no space (#6477)' (#218) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / integration (push) Successful in 1m1s
CI & Build / Python tests (push) Successful in 1m35s
CI & Build / Build & push image (push) Successful in 31s
2026-10-26 19:16:24 -04:00
bvandeusenandClaude Opus 5.5 2a6d9080ba fix(6477): a plain-word call needs the parenthesis right after the word
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m37s
CI & Build / Build & push image (push) Successful in 26s
Read against Fabled Archives after the cleanup: of the 9 rows still linked
to snippet #5448 (symbol `file`), all but one matched prose in a comment,
"a file (not a directory)", "the file (ScanWaiting". The only real call
was `r.file(ctx, ...)`. Formatted code never puts a space before a call's
parenthesis and prose does, so the plain-word test is now `word(` with no
whitespace. _PROPOSER_VERSION 8 re-reads every row once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 19:07:03 -04:00
bvandeusenandClaude Opus 5.5 3e2227e8c5 fix(6483): drop the cross-project uses edges the write path wrote
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m41s
CI & Build / Build & push image (push) Successful in 19s
Migration 0125 removed the proposer's cross-project `reference` edges, but
the write path records its by-name evidence with basis `hook`, so those
survived it. A hook edge across projects is impossible for the same reason a
reference edge is, and the write path now applies the same by-name test
(names_canon), so 0126 removes the ones written before. Judged edges keep
their own basis and are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 18:29:54 -04:00
bvandeusen f4eb535285 Merge pull request 'dev → main: by-name canon matching resolves (#6477), five unused Vue components removed (#6480)' (#217) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 1m8s
CI & Build / Python tests (push) Successful in 1m44s
CI & Build / Build & push image (push) Successful in 28s
2026-10-26 17:49:07 -04:00
bvandeusenandClaude Opus 5.5 cdb71e64c4 fix(6477): a body uses a canon by name only when the name can resolve to it
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 43s
CI & Build / integration (push) Successful in 1m36s
CI & Build / Python tests (push) Successful in 2m7s
CI & Build / Build & push image (push) Successful in 42s
The proposer's reference basis, and every uses edge it writes, counted any
word-bounded mention of a canon's symbol. Three holes made that wrong at
scale (snippet #5448, symbol `file`, held 2,161 uses edges):

- Go, Rust, Kotlin, Swift, Dart, C, C#, Ruby and PHP were outside the
  language-family maps, so their canons read as "unknown, no gate" and were
  matched in every Python, TS and CSS body.
- Canons in other projects were matched by name, though one repo never
  calls a function defined in another's.
- A plain word (`file`, `seen`) or a module's own helper (`_run`) matched
  wherever it appeared.

names_canon is now the one by-name test, used by match_canon,
reference_canons and the write-path hint: same project, not a name the file
defines itself (unless the canon is recorded there), no generic verb with or
without a leading underscore, and a bare lowercase word only where it is
called. The write path keeps the payload's own names in play, since a
redefinition of a pulled canon is the copy it exists to flag.

Repair: record_uses only adds, so replace_reference_uses now makes a row's
machine-written reference edges exactly what the current rule finds,
leaving judged and hook edges alone. _PROPOSER_VERSION 7 re-reads every row
on its project's next refresh. Migration 0125 deletes the cross-project
reference edges already stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 17:41:21 -04:00
bvandeusenandClaude Opus 5.5 0b98a3a5cd chore(6480): remove five Vue components nothing imports
HistoryPanel, InlineAssistPanel, NoteCard, WorkspaceNoteEditor and
WorkspaceTaskPanel had no importer, lazy import or global registration
anywhere in frontend/src. The features they served were replaced; token
sweeps kept restyling them because they match a glob. The two doc comments
that named HistoryPanel.vue now name VersionHistorySection.vue, the note
history that is live.

SearchBar.vue stays: it is the recorded home of snippet #2961 "SearchBar -
the search input recipe", and the two live search boxes are judged variants
of it. Deleting it would leave the recipe pointing at nothing.

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

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

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

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

Closes milestone 416 at 9/9. CI 6999 green on 104c1d6.
2026-09-18 00:48:49 -04:00
bvandeusen f324be6b5a Merge pull request 'The wide net becomes a pull, and a tuned number carries the space it was measured in' (#164) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 51s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m41s
CI & Build / Build & push image (push) Successful in 19s
2026-09-17 18:50:50 -04:00
bvandeusen d9e512e9b4 Every ledger is cleared on a compact, and a retrieval floor becomes something the model maintains (#163)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 48s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m32s
CI & Build / Build & push image (push) Successful in 16s
2026-09-17 12:01:42 -04:00
bvandeusen 91cfa8da97 Merge pull request 'A rule must say when it applies; the ledger says what was read, not what was shown' (#162) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 49s
CI & Build / TypeScript typecheck (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 14s
2026-09-16 17:50:08 -04:00
bvandeusen 8f3f36e6fc Merge pull request 'A directory names its project; a compaction is told what to keep; list rows say what a record is' (#161) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 49s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m32s
CI & Build / Build & push image (push) Successful in 30s
2026-09-16 08:57:45 -04:00
bvandeusen 0ac250194f Merge pull request 'Plan gate default 0.80, and an "Approval requested" reply section' (#160) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Failing after 15s
CI & Build / TypeScript typecheck (push) Successful in 52s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 14s
2026-09-15 15:23:01 -04:00
bvandeusen c2c92a8421 Merge pull request 'Milestone 415: an existing plan is found before a new one is made' (#159) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m38s
CI & Build / Build & push image (push) Successful in 18s
2026-09-15 14:23:31 -04:00
bvandeusen 790abdb68c Merge pull request 'Milestone 414 steps 1–3: a rule is global or belongs to one project, and retrieval honours which; #3191 read-scope fix' (#158) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 55s
CI & Build / integration (push) Successful in 1m0s
CI & Build / Python tests (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 16s
2026-09-15 12:49:19 -04:00
bvandeusen b0346acd00 Merge pull request 'enter_project becomes a small primer instead of a 222k-character dump' (#157) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 47s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m31s
CI & Build / Build & push image (push) Successful in 15s
2026-09-14 22:12:17 -04:00
bvandeusen 0b52f894d8 Merge pull request 'Reply shapes reach the reply, a Stop hook checks completion reports, and hook pipes keep their output' (#156) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / integration (push) Successful in 48s
CI & Build / TypeScript typecheck (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m42s
CI & Build / Build & push image (push) Successful in 15s
2026-09-14 18:57:06 -04:00
bvandeusen d3375be77f Merge pull request 'Guidance by ownership, placement and report-back, and no more guessed record ids' (#155) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m34s
CI & Build / Build & push image (push) Successful in 14s
2026-09-14 14:16:14 -04:00
bvandeusen b7e648226b Merge pull request 'The two new retrieval bars get their Settings controls' (#154) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / Plugin hooks (push) Successful in 7s
CI & Build / integration (push) Successful in 59s
CI & Build / Python tests (push) Successful in 1m29s
CI & Build / Build & push image (push) Successful in 16s
2026-09-11 20:58:50 -04:00
bvandeusen de9431ec39 Merge pull request 'Migration 0099 matched inside words and mangled rows it rewrote' (#153) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 56s
CI & Build / TypeScript typecheck (push) Successful in 1m1s
CI & Build / Python tests (push) Successful in 1m33s
CI & Build / Build & push image (push) Successful in 14s
2026-09-11 20:18:02 -04:00
bvandeusen a552deb689 Merge pull request 'Retire the always-on tier — every rule arrives by retrieval (milestone 394)' (#152) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / integration (push) Successful in 52s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / Python tests (push) Successful in 1m29s
CI & Build / Build & push image (push) Successful in 13s
2026-09-11 16:43:20 -04:00
bvandeusen 6da39e0298 Merge pull request 'The prompt-boundary rule arm, and a slot a preference cannot lose (#3852, #3894)' (#151) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / integration (push) Successful in 52s
CI & Build / TypeScript typecheck (push) Successful in 54s
CI & Build / Python tests (push) Successful in 1m25s
CI & Build / Build & push image (push) Successful in 26s
2026-09-11 11:11:59 -04:00
bvandeusen 5f77fc29c1 Merge pull request 'Preferences — a rule kind that Scribe keeps up to date (#3849 steps 1–3)' (#150) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 58s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m27s
CI & Build / Build & push image (push) Successful in 24s
2026-09-10 23:34:16 -04:00
bvandeusen d8017f9b96 Merge pull request 'A surfaced rule stops going permanently quiet (#3750, #3751, #3752)' (#149) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 43s
CI & Build / integration (push) Successful in 53s
CI & Build / Python tests (push) Successful in 1m18s
CI & Build / Build & push image (push) Successful in 24s
2026-09-09 22:44:28 -04:00
bvandeusen a9fa8bddb6 Merge pull request 'Record WHAT the bar turned away, not only how close it came (#3807)' (#148) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 26s
CI & Build / integration (push) Successful in 47s
CI & Build / Python tests (push) Successful in 1m25s
CI & Build / Build & push image (push) Successful in 24s
2026-09-09 21:34:56 -04:00
bvandeusen cd910e32a0 Merge pull request 'A search that never ran is not a decline' (#147) from dev into main
CI & Build / Python lint (push) Successful in 6s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / TypeScript typecheck (push) Successful in 42s
CI & Build / integration (push) Successful in 49s
CI & Build / Python tests (push) Successful in 1m22s
CI & Build / Build & push image (push) Successful in 16s
2026-09-09 13:36:43 -04:00
bvandeusen 1c4ace5199 Merge pull request 'write_path stops reporting records it withheld itself as near misses' (#146) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / integration (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m8s
CI & Build / Build & push image (push) Successful in 14s
2026-09-09 00:44:44 -04:00
bvandeusen 6495236569 Merge pull request 'A repeat is not a rejection, and a compaction is not knowledge' (#145) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / integration (push) Successful in 42s
CI & Build / Python tests (push) Successful in 1m9s
CI & Build / Build & push image (push) Successful in 15s
2026-09-09 00:13:01 -04:00
bvandeusen 53df6742cb Merge pull request 'Milestone 379 closes: the readout can now say what it did not measure' (#144) from dev into main
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / Python tests (push) Successful in 1m3s
CI & Build / Python lint (push) Successful in 3s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / integration (push) Successful in 39s
CI & Build / Build & push image (push) Successful in 15s
2026-09-08 16:06:14 -04:00
bvandeusen be08edcd7e Merge pull request 'Telemetry coverage, and the rule arms stop filtering to one tier' (#143) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 13s
CI & Build / integration (push) Successful in 34s
CI & Build / TypeScript typecheck (push) Successful in 24s
CI & Build / Python tests (push) Successful in 1m4s
CI & Build / Build & push image (push) Successful in 13s
2026-09-08 11:11:40 -04:00
bvandeusen 4a85220aea Merge pull request 'feat(rules): the rule arms stop filtering the corpus to one tier (#3702)' (#142) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / TypeScript typecheck (push) Successful in 39s
CI & Build / integration (push) Successful in 40s
CI & Build / Python tests (push) Successful in 1m13s
CI & Build / Build & push image (push) Successful in 19s
2026-09-08 00:31:12 -04:00
bvandeusen 14ff41faf5 Merge pull request 'feat(rules): rule creation becomes propose-then-approve (#3557)' (#141) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 8s
CI & Build / TypeScript typecheck (push) Successful in 22s
CI & Build / integration (push) Successful in 30s
CI & Build / Python tests (push) Successful in 1m2s
CI & Build / Build & push image (push) Successful in 19s
2026-09-04 22:01:47 -04:00
bvandeusen 67df41ae00 Merge pull request 'feat(rules): the instruction surfaces say to RETRIEVE a rule, not only to receive one (#3523)' (#140) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 32s
CI & Build / Python tests (push) Successful in 1m5s
CI & Build / TypeScript typecheck (push) Successful in 3m18s
CI & Build / Build & push image (push) Successful in 16s
2026-09-03 22:07:10 -04:00
bvandeusen 0915c48bb0 Merge pull request 'feat(telemetry): tell a ranker decline from a repeat before the observation window opens (#3497)' (#139) from dev into main
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 30s
CI & Build / Python tests (push) Successful in 1m6s
CI & Build / TypeScript typecheck (push) Successful in 5m20s
CI & Build / Build & push image (push) Successful in 17s
2026-09-03 21:23:01 -04:00
bvandeusen aea7b63b62 Merge pull request 'fix(telemetry): both rule arms logged only their hits, so the clear-rate could only read 100% (#3497)' (#138) from dev into main
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 9s
CI & Build / integration (push) Successful in 30s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m5s
CI & Build / Build & push image (push) Successful in 17s
2026-09-03 07:19:08 -04:00
bvandeusen 5b02908dfd dev → main: rules become measurable at the preload, and retrievable at the tool call (#137)
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 29s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m6s
CI & Build / Build & push image (push) Successful in 17s
2026-09-02 23:41:09 -04:00
bvandeusen 34cd389371 dev → main: rule usage telemetry, the plugin's derived version (#136)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / TypeScript typecheck (push) Successful in 23s
CI & Build / integration (push) Successful in 30s
CI & Build / Python tests (push) Successful in 1m5s
CI & Build / Build & push image (push) Successful in 16s
2026-09-02 18:52:20 -04:00
bvandeusen b267037911 Two milestones: a note can carry its own check (317), and a rule keeps what it used to say (323) (#135)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 11s
CI & Build / TypeScript typecheck (push) Successful in 38s
CI & Build / integration (push) Successful in 55s
CI & Build / Python tests (push) Successful in 1m37s
CI & Build / Build & push image (push) Successful in 29s
2026-08-31 00:01:15 -04:00
bvandeusen 93d660b710 Tool disambiguators, kind badges, and a badge layer that clears AA (#3123, #3124, #3132)
CI & Build / Python lint (push) Successful in 4s
CI & Build / Plugin hooks (push) Successful in 10s
CI & Build / integration (push) Successful in 31s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m17s
CI & Build / Build & push image (push) Successful in 15s
2026-08-27 21:28:48 -04:00
bvandeusen 056c7c75da A task's kind is correctable — the Kind select stops lying (#3129)
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 7s
CI & Build / integration (push) Successful in 28s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 1m6s
CI & Build / Build & push image (push) Successful in 15s
2026-08-27 18:05:16 -04:00
183 changed files with 13407 additions and 3498 deletions
+6 -7
View File
@@ -28,10 +28,10 @@ services:
environment: environment:
DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}"
LOG_LEVEL: "${LOG_LEVEL:-INFO}" LOG_LEVEL: "${LOG_LEVEL:-INFO}"
# Behind an HTTPS reverse proxy: # Port 5000 is published straight to clients, so no proxy is trusted.
# Behind a reverse proxy, set 1 (one per proxy) and BASE_URL:
TRUSTED_PROXY_HOPS: "0"
# BASE_URL: "https://grimoire.example.com" # BASE_URL: "https://grimoire.example.com"
# SECURE_COOKIES: "true"
# TRUST_PROXY_HEADERS: "true"
volumes: volumes:
- app_data:/data - app_data:/data
depends_on: depends_on:
@@ -75,8 +75,7 @@ Everything is optional. Set these in the environment or in a `.env` file beside
| Variable | When | What it does | | Variable | When | What it does |
|----------|------|--------------| |----------|------|--------------|
| `BASE_URL` | Behind a proxy | The public URL, used in email links and SSO redirects | | `BASE_URL` | Behind a proxy | The public URL, used in email links and SSO redirects |
| `SECURE_COOKIES` | Over HTTPS | `true` when Grimoire is served over HTTPS | | `TRUSTED_PROXY_HOPS` | Rarely | The starting count of reverse proxies in front of Grimoire (default `1`; the compose file above sets `0` because it publishes the port directly). Check and change it in **Settings → Config → Reverse proxy**, which shows what each count reads for your own request; behind Cloudflare it is usually `2` |
| `TRUST_PROXY_HEADERS` | Behind a proxy | `true` to read the client address from the proxy's headers |
| `POSTGRES_PASSWORD` | Before the first start | The database password (defaults to `grimoire`; the database is reachable only inside the compose network). Postgres takes it once, when the volume is created | | `POSTGRES_PASSWORD` | Before the first start | The database password (defaults to `grimoire`; the database is reachable only inside the compose network). Postgres takes it once, when the volume is created |
| `SECRET_KEY` | Rarely | A key you manage yourself, instead of the one Grimoire keeps. It wins over the kept key; remove it to go back | | `SECRET_KEY` | Rarely | A key you manage yourself, instead of the one Grimoire keeps. It wins over the kept key; remove it to go back |
@@ -97,7 +96,7 @@ docker compose up -d
Database migrations run when the app starts, and the key stays in its volume. Claude Code updates the plugin from its marketplace; run `/reload-plugins` after an update. Database migrations run when the app starts, and the key stays in its volume. Claude Code updates the plugin from its marketplace; run `/reload-plugins` after an update.
**Settings → Data → Scheduled backups** writes a daily backup of the database to a folder or an S3-compatible bucket, and `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](docs/backups.md). **Settings → Data → Scheduled backups** writes a daily backup of the database to a folder or an S3-compatible bucket, and Settings → Data → Restore from Backup rolls the instance back to one, or brings a new instance back from it. See [Backups](docs/backups.md).
## Features ## Features
@@ -132,7 +131,7 @@ The full list is in [Features](docs/features.md).
| What you see | Why | Fix | | What you see | Why | Fix |
|--------------|-----|-----| |--------------|-----|-----|
| `SECRET_KEY is set to the public placeholder` at startup | `SECURE_COOKIES=true` while `SECRET_KEY` is `dev-secret-change-me` | Remove `SECRET_KEY`, or set a real one | | `SECRET_KEY is set to the public placeholder` at startup | `SECRET_KEY` is `dev-secret-change-me` or `change-me-in-production` | Remove `SECRET_KEY`, or set a real one |
| Settings asks for forge tokens or the backup secret again | The instance's key changed: the `app_data` volume was replaced, or `SECRET_KEY` was set or removed | Enter them again, or restore the previous key | | Settings asks for forge tokens or the backup secret again | The instance's key changed: the `app_data` volume was replaced, or `SECRET_KEY` was set or removed | Enter them again, or restore the previous key |
| `Can't locate revision identified by '…'` at startup | An older image is running against a database a newer one has already migrated | Run the newer image; migrations only move forward | | `Can't locate revision identified by '…'` at startup | An older image is running against a database a newer one has already migrated | Run the newer image; migrations only move forward |
| The plugin's tools are missing in Claude Code | The plugin isn't installed, or Claude Code hasn't reloaded it | `/plugin` to install or update it, then `/reload-plugins` | | The plugin's tools are missing in Claude Code | The plugin isn't installed, or Claude Code hasn't reloaded it | `/plugin` to install or update it, then `/reload-plugins` |
@@ -0,0 +1,35 @@
"""drop machine-written uses edges that cross projects
Revision ID: 0125
Revises: 0124
Create Date: 2026-10-26
A `uses` edge with basis `reference` is the proposer's by-name reading: the
shape's body names a canon's symbol. A body never calls a function defined in
another project's repository, so such an edge across projects is a common
word matched, not a call. The proposer no longer writes them, and this removes
the ones it wrote before. Edges a person or an audit judged keep their own
basis and are left alone. Rows within one project are re-read on the next
coverage refresh, which replaces their reference edges under the same rule.
Downgrade restores nothing: the removed edges were never facts.
"""
from alembic import op
revision = "0125"
down_revision = "0124"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"DELETE FROM code_shape_uses u USING code_shapes s, notes n "
"WHERE u.shape_id = s.id AND u.snippet_id = n.id "
"AND u.basis = 'reference' "
"AND n.project_id IS NOT NULL AND n.project_id <> s.project_id"
)
def downgrade() -> None:
pass
@@ -0,0 +1,34 @@
"""drop write-path uses edges that cross projects
Revision ID: 0126
Revises: 0125
Create Date: 2026-10-26
The write path records a `uses` edge with basis `hook` when a session pulled a
snippet and then wrote code naming its symbol. That is by-name evidence, like
the proposer's `reference` edges 0125 removed, and a body never calls a
function defined in another project's repository. The write path now applies
the same by-name test, so it writes no such edge; this removes the ones it
wrote before. Judged edges keep their own basis and are left alone.
Downgrade restores nothing: the removed edges were never facts.
"""
from alembic import op
revision = "0126"
down_revision = "0125"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute(
"DELETE FROM code_shape_uses u USING code_shapes s, notes n "
"WHERE u.shape_id = s.id AND u.snippet_id = n.id "
"AND u.basis = 'hook' "
"AND n.project_id IS NOT NULL AND n.project_id <> s.project_id"
)
def downgrade() -> None:
pass
@@ -0,0 +1,39 @@
"""instance identity — the id lineage a backup carries
Revision ID: 0127
Revises: 0126
Create Date: 2026-11-05
One row naming this database's id lineage. Every full backup carries it, a
restore into a fresh instance adopts it (the restore keeps the original ids),
and rolling a live instance back requires the backup's to match, so a backup's
ids never land on unrelated rows. Made here with a random value, so every
instance has one before its first account exists.
"""
import sqlalchemy as sa
from alembic import op
revision = "0127"
down_revision = "0126"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"instance_identity",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("instance_id", sa.Text(), nullable=False),
sa.Column(
"created_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now(),
),
sa.CheckConstraint("id = 1", name="ck_instance_identity_single_row"),
)
op.execute(
"INSERT INTO instance_identity (id, instance_id) VALUES (1, gen_random_uuid()::text)"
)
def downgrade() -> None:
op.drop_table("instance_identity")
+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
+3 -2
View File
@@ -8,8 +8,9 @@ services:
# a Docker secret and sets SECRET_KEY_FILE to its path). # a Docker secret and sets SECRET_KEY_FILE to its path).
SECRET_KEY: "${SECRET_KEY}" SECRET_KEY: "${SECRET_KEY}"
LOG_LEVEL: "${LOG_LEVEL:-INFO}" LOG_LEVEL: "${LOG_LEVEL:-INFO}"
TRUST_PROXY_HEADERS: "true" # Proxies in front of the app (Traefik = 1). The client address and
SECURE_COOKIES: "true" # HTTPS are read from that far in from the right of X-Forwarded-*.
TRUSTED_PROXY_HOPS: "1"
volumes: volumes:
- app_data:/data - app_data:/data
networks: networks:
+3 -3
View File
@@ -13,10 +13,10 @@ services:
environment: environment:
DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}" DATABASE_URL: "postgresql+asyncpg://${POSTGRES_USER:-grimoire}:${POSTGRES_PASSWORD:-grimoire}@db:5432/${POSTGRES_DB:-grimoire}"
LOG_LEVEL: "${LOG_LEVEL:-INFO}" LOG_LEVEL: "${LOG_LEVEL:-INFO}"
# Behind an HTTPS reverse proxy: # Port 5000 is published straight to clients, so no proxy is trusted.
# Behind a reverse proxy, set 1 (one per proxy) and BASE_URL:
TRUSTED_PROXY_HOPS: "0"
# BASE_URL: "https://grimoire.example.com" # BASE_URL: "https://grimoire.example.com"
# SECURE_COOKIES: "true"
# TRUST_PROXY_HEADERS: "true"
volumes: volumes:
- app_data:/data - app_data:/data
depends_on: depends_on:
+5 -1
View File
@@ -251,6 +251,7 @@ These serve the plugin's hooks.
| POST | `/api/plugin/rule-opened` | Records that a session opened a rule it was shown | | POST | `/api/plugin/rule-opened` | Records that a session opened a rule it was shown |
| GET | `/api/plugin/shape-check` | The end-of-turn question about what this turn wrote | | GET | `/api/plugin/shape-check` | The end-of-turn question about what this turn wrote |
| GET | `/api/plugin/claim-session` · `/release-session` | Bind a session to its task claims / release them at session end | | GET | `/api/plugin/claim-session` · `/release-session` | Bind a session to its task claims / release them at session end |
| GET | `/api/plugin/write-scope` | Which projects a pending act would change (a directory, or an MCP call's `tool` and `input`), and whether a session in its own project may do it. Filing an issue elsewhere is allowed; every other cross-project write is answered `allowed: false` with the reason the operator is asked |
| GET | `/api/plugin/processes` | Stored Processes for skill-stub sync | | GET | `/api/plugin/processes` | Stored Processes for skill-stub sync |
| GET | `/api/plugin/prior-art` | Write-path hint for the plugin hooks (params: `path`, `code`, `repo`, `shapes`, `exclude_ids`, `exclude_sync_ids`, `exclude_derive`); returns `context`, `note_ids`, `sync_note_ids`, `stamped`, `divergence`, `derive`, `derive_keys` | | GET | `/api/plugin/prior-art` | Write-path hint for the plugin hooks (params: `path`, `code`, `repo`, `shapes`, `exclude_ids`, `exclude_sync_ids`, `exclude_derive`); returns `context`, `note_ids`, `sync_note_ids`, `stamped`, `divergence`, `derive`, `derive_keys` |
| GET / POST | `/api/projects/<id>/coverage`, `…/coverage/refresh` | Shape-ledger accounting (`pattern_coverage` line, counts, `derive_groups` — css groups carry `consumers`, `derive_new`, `unused_css`, `divergence`, `recheck`) | | GET / POST | `/api/projects/<id>/coverage`, `…/coverage/refresh` | Shape-ledger accounting (`pattern_coverage` line, counts, `derive_groups` — css groups carry `consumers`, `derive_new`, `unused_css`, `divergence`, `recheck`) |
@@ -272,12 +273,15 @@ These serve the plugin's hooks.
| Method | Path | Description | | Method | Path | Description |
|--------|------|-------------| |--------|------|-------------|
| GET | `/api/admin/backup` | Export backup (format v4; `?scope=user` for own data) | | GET | `/api/admin/backup` | Export backup (format v4; `?scope=user` for own data) |
| POST | `/api/admin/restore` | Restore from a backup | | GET | `/api/admin/restore/sources` | The backups at the backup destination, newest first |
| POST | `/api/admin/restore/preview` | What restoring a backup (`?source=<name>` or an uploaded file) would change; 409 with the reason when it can't apply here |
| POST | `/api/admin/restore?confirm=rollback` | Put the whole instance back to that backup, after saving the current state |
| GET / DELETE | `/api/admin/users` · `/api/admin/users/:id` | List / delete users | | GET / DELETE | `/api/admin/users` · `/api/admin/users/:id` | List / delete users |
| GET / PUT | `/api/admin/registration` | Get / toggle registration | | GET / PUT | `/api/admin/registration` | Get / toggle registration |
| GET / PUT | `/api/admin/smtp` · POST `/api/admin/smtp/test` | SMTP config + test email | | GET / PUT | `/api/admin/smtp` · POST `/api/admin/smtp/test` | SMTP config + test email |
| GET | `/api/admin/logs` · `/api/admin/logs/stats` | Log entries + category counts | | GET | `/api/admin/logs` · `/api/admin/logs/stats` | Log entries + category counts |
| GET / PUT | `/api/admin/base-url` | Get / set the public base URL | | GET / PUT | `/api/admin/base-url` | Get / set the public base URL |
| GET / PUT | `/api/admin/proxy` | Get / set how many reverse proxies stand in front of Grimoire (`{"hops": n}`, or `null` for the environment's count), with what each count would read for this request |
| GET / PUT | `/api/admin/db-maintenance` (+ `/health`, POST `/run`) | VACUUM schedule, health, manual run | | GET / PUT | `/api/admin/db-maintenance` (+ `/health`, POST `/run`) | VACUUM schedule, health, manual run |
| POST / GET / DELETE | `/api/admin/invitations` (+ `/:id`) | Create / list / revoke invite links | | POST / GET / DELETE | `/api/admin/invitations` (+ `/:id`) | Create / list / revoke invite links |
| GET / PUT | `/api/admin/backups` | Scheduled backups: destination, schedule and recent runs | | GET / PUT | `/api/admin/backups` | Scheduled backups: destination, schedule and recent runs |
+3 -3
View File
@@ -69,10 +69,10 @@ Every database wait on startup has a deadline. Migrations wait for the database
## Authentication ## Authentication
- **Sessions**: `HttpOnly`, `SameSite=Lax` cookies, `Secure` when `SECURE_COOKIES=true`. Changing a password bumps the user's session version and signs out their other sessions. - **Sessions**: `HttpOnly`, `SameSite=Lax` cookies, `Secure` on a request the trusted proxy reports as HTTPS, which also gets HSTS (`grimoire/proxy.py`). Changing a password bumps the user's session version and signs out their other sessions.
- **API keys**: `Authorization: Bearer fmcp_...`, stored hashed. A `read` key may only call read endpoints and read MCP tools. - **API keys**: `Authorization: Bearer fmcp_...`, stored hashed. A `read` key may only call read endpoints and read MCP tools.
- **OIDC** single sign-on with PKCE, optionally replacing local logins ([SSO / OAuth](sso-oauth.md)). - **OIDC** single sign-on with PKCE, optionally replacing local logins ([SSO / OAuth](sso-oauth.md)).
- **Rate limits** on register, login and forgot-password, per client IP (`TRUST_PROXY_HEADERS` reads the IP from the proxy's headers). - **Rate limits** on register, login and forgot-password, per client IP, read from `X-Forwarded-For` by `TRUSTED_PROXY_HOPS`.
Credentials Grimoire stores for outside services (forge tokens, the backup destination's S3 secret) are sealed under a key derived from `SECRET_KEY`, which the instance makes on first start and keeps in `/data/secret_key` unless one is set. Credentials Grimoire stores for outside services (forge tokens, the backup destination's S3 secret) are sealed under a key derived from `SECRET_KEY`, which the instance makes on first start and keeps in `/data/secret_key` unless one is set.
@@ -87,7 +87,7 @@ Credentials Grimoire stores for outside services (forge tokens, the backup desti
│ ├── routes/ REST blueprints │ ├── routes/ REST blueprints
│ ├── mcp/ MCP server and its tool modules │ ├── mcp/ MCP server and its tool modules
│ ├── services/ shared logic │ ├── services/ shared logic
│ └── restore.py `python -m grimoire.restore` for a fresh instance │ └── restore.py `python -m grimoire.restore`: the restore, from the command line
├── frontend/src/ views, components, stores, composables, api client ├── frontend/src/ views, components, stores, composables, api client
├── plugin/ Claude Code hooks, skills and commands ├── plugin/ Claude Code hooks, skills and commands
├── scripts/ CI checks and the plugin version minter ├── scripts/ CI checks and the plugin version minter
+52 -21
View File
@@ -88,9 +88,12 @@ You need four things:
- **Access key.** - **Access key.**
- **Secret key.** - **Secret key.**
Grimoire uploads and lists; it never deletes. A key that may **only add Grimoire uploads and lists, and reads a backup back when you restore from the
objects** is therefore enough, and it is the safer key to hand out: a stolen bucket; it never deletes. A key that may **add and read objects but not
one cannot wipe the history. delete them** is therefore enough, and it is the safer key to hand out: a
stolen one cannot wipe the history. A key that may only add objects still
takes backups; restore then works by uploading a file or from the command
line.
The secret is stored encrypted, under a key derived from `SECRET_KEY`. It is The secret is stored encrypted, under a key derived from `SECRET_KEY`. It is
never shown again, and never included in a backup. If an instance's never shown again, and never included in a backup. If an instance's
@@ -122,8 +125,10 @@ keeps service backups as "backup targets". Either destination works with it.
1. On Archives' **Backups** page, make a target for Grimoire, named `grimoire` 1. On Archives' **Backups** page, make a target for Grimoire, named `grimoire`
for example. for example.
2. Choose how Grimoire's files arrive: 2. Choose how Grimoire's files arrive:
- **S3**: turn on the S3 way in for the target and make an **append-only** - **S3**: turn on the S3 way in for the target and make an S3 key that
S3 key. In Grimoire, choose **An S3 bucket**: may add and read objects but not delete them (an **append-only** key
takes backups too, but then Grimoire can't restore from the bucket). In
Grimoire, choose **An S3 bucket**:
- address: Archives' backup address (`http://<archives>:8081`); - address: Archives' backup address (`http://<archives>:8081`);
- bucket: the target's name; - bucket: the target's name;
- access key and secret key: the key you just made. - access key and secret key: the key you just made.
@@ -139,26 +144,52 @@ keeps service backups as "backup targets". Either destination works with it.
## Restoring ## Restoring
### Into a fresh instance A restore puts the **whole instance** back to the moment a backup was taken,
for every user:
Start Grimoire on an empty database, copy the backup file into the container, - records edited since go back to how they were;
and run: - records deleted since come back;
- anything made since is removed.
It matches records by their ids, so a live instance only restores a backup **of
its own**. Each instance has an id, and every backup records the one it came
from. A backup from another instance, or one made before backups recorded it,
only goes into a new, empty instance, which takes it as it is.
Before changing anything, the restore saves the current state as one more
backup. It goes to the backup destination when scheduled backups are on, and
otherwise to `/data/pre-restore`. The result says which file it is, so a
restore can itself be undone.
What a backup doesn't carry stays as it is wherever its owner survives the
restore: API keys, forge connections, sharing, logs, and the destination's S3
secret. The trash isn't in backups, so anything in the trash when the backup
was taken is gone afterwards. Everyone is signed out, and search is rebuilt.
### From the web
**Settings → Data → Restore from Backup** lists the backups at the backup
destination. You can pick one of those, or upload a `.tar` or the JSON
**Full Backup** download (uploads are held to the server's request-size
limit). The restore then shows what would change: when the backup was taken,
and how many accounts, projects, plans, notes and rules there are now and will
be afterwards. Type `roll back` to run it. Then sign in again.
To read backups back from an S3 bucket, the key needs read access as well as
write. Grimoire never deletes from the bucket.
### From the command line
For a file with no size limit, or a new instance with no backup destination
yet, copy the file into the container and run:
```sh ```sh
docker exec -it grimoire python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar docker exec -it grimoire python -m grimoire.restore /backups/grimoire-20261015T020000Z.tar
``` ```
- The command refuses a database that already has an account. A restore It prints what would change and stops. Add `--yes` to restore. It reads the
re-creates everything with new ids, so on a live instance it would add a JSON download too. Afterwards, **restart Grimoire** so the search indexes are
second copy instead of replacing anything. rebuilt.
- Nothing limits the file's size.
- It also reads the JSON from the admin **Full Backup** download.
Afterwards, **restart Grimoire** so the search indexes are rebuilt. Then issue After restoring into a new instance, issue new API keys, add forge connections
new API keys, add forge connections again, and set up any sharing. again, and set up any sharing: none of them travel in a backup.
### From the web
**Settings → Data → Restore from Backup** takes the `.tar` as well as the
JSON download. The upload is held to the server's request-size limit. For a
bigger file, use the command above.
+14 -8
View File
@@ -14,8 +14,7 @@ Any variable marked *secret* can also be read from a file: set `<NAME>_FILE` to
| `SECRET_KEY` *(secret)* | kept in `DATA_DIR` | Signs sessions and seals stored credentials. Unset, the instance makes its own on first start and keeps it in `DATA_DIR/secret_key`. Set it only to manage the key yourself; it wins over the kept one (see below) | | `SECRET_KEY` *(secret)* | kept in `DATA_DIR` | Signs sessions and seals stored credentials. Unset, the instance makes its own on first start and keeps it in `DATA_DIR/secret_key`. Set it only to manage the key yourself; it wins over the kept one (see below) |
| `DATA_DIR` | `/data` | Where the instance keeps its own `SECRET_KEY`. Mount a volume here | | `DATA_DIR` | `/data` | Where the instance keeps its own `SECRET_KEY`. Mount a volume here |
| `BASE_URL` | `http://localhost:5000` | Public URL, used in email links and OIDC redirects | | `BASE_URL` | `http://localhost:5000` | Public URL, used in email links and OIDC redirects |
| `SECURE_COOKIES` | `false` | `true` when Grimoire is served over HTTPS | | `TRUSTED_PROXY_HOPS` | `1` | The starting count of reverse proxies in front of Grimoire. **Settings → Config → Reverse proxy** is where the count is checked and set, and a count saved there wins over this. The client address and the scheme are read that many entries in from the right of `X-Forwarded-For` and `X-Forwarded-Proto`; `0` ignores both headers. See [Behind a reverse proxy](#behind-a-reverse-proxy) |
| `TRUST_PROXY_HEADERS` | `false` | `true` behind a reverse proxy, to read the client IP from `X-Forwarded-For` / `X-Real-IP` |
| `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR` | | `LOG_LEVEL` | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR` |
| `LOG_RETENTION_DAYS` | `90` | Days of app logs to keep | | `LOG_RETENTION_DAYS` | `90` | Days of app logs to keep |
| `FASTEMBED_CACHE_DIR` | `/data/fastembed-cache` | Where the embedding model is stored after its first download | | `FASTEMBED_CACHE_DIR` | `/data/fastembed-cache` | Where the embedding model is stored after its first download |
@@ -77,7 +76,7 @@ docker compose -f docker-compose.dev.yml up --build
### Docker Swarm ### Docker Swarm
[`docker-compose.prod.yml`](../docker-compose.prod.yml) is a stack file: the app and database on a private overlay network, with `SECURE_COOKIES` and `TRUST_PROXY_HEADERS` on. A Swarm can move the app to another node, away from a node-local `/data` volume, so the stack sets its own key: provide `DB_PASSWORD` and `SECRET_KEY` in the environment (or mount a Docker secret and set `SECRET_KEY_FILE`): [`docker-compose.prod.yml`](../docker-compose.prod.yml) is a stack file: the app and database on a private overlay network, trusting one proxy (`TRUSTED_PROXY_HOPS: "1"`). A Swarm can move the app to another node, away from a node-local `/data` volume, so the stack sets its own key: provide `DB_PASSWORD` and `SECRET_KEY` in the environment (or mount a Docker secret and set `SECRET_KEY_FILE`):
```bash ```bash
DB_PASSWORD=... SECRET_KEY=... docker stack deploy -c docker-compose.prod.yml grimoire DB_PASSWORD=... SECRET_KEY=... docker stack deploy -c docker-compose.prod.yml grimoire
@@ -96,13 +95,16 @@ Back up the database with **Settings → Data → Scheduled backups** ([Backups]
## Behind a reverse proxy ## Behind a reverse proxy
Grimoire doesn't terminate TLS. Put it behind Nginx, Traefik or Caddy, forward to port 5000, and keep port 5000 off the internet. Set `SECURE_COOKIES=true`, `TRUST_PROXY_HEADERS=true` and `BASE_URL`. Grimoire doesn't terminate TLS. Put it behind Nginx, Traefik or Caddy, forward to port 5000, and keep port 5000 off the internet. Set `BASE_URL`, then set the proxy count to the number of proxies a request passes through: one proxy is `1`, the default; Cloudflare's proxied DNS in front of your own proxy is `2`.
**Settings → Config → Reverse proxy** sets the count and checks it against your own request. It shows the address Grimoire reads you as, and what each count from 0 to 3 would read. Pick the count that shows your own address. When a request comes through Cloudflare, the section names the count that reads the address Cloudflare reports, with a button that sets it. `TRUSTED_PROXY_HOPS` in the environment is only the starting value: a count saved in Settings wins, and **Use the environment's** goes back to it.
A count that is too low makes every visitor read as the proxy, so they share one sign-in rate limit and a few bad sign-ins block everyone. The "too many attempts" message says so and points here. The block on sign-ins lifts after a minute; an admin who is already signed in can fix the count at once.
```nginx ```nginx
location / { location / {
proxy_pass http://127.0.0.1:5000; proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
@@ -112,12 +114,16 @@ location / {
} }
``` ```
With `TRUST_PROXY_HEADERS=true`, make sure the proxy replaces any `X-Forwarded-For` the client sends. Each proxy appends its entry to `X-Forwarded-For` and `X-Forwarded-Proto`, so Grimoire reads the entry that many in from the right: the one your own proxy wrote. Whatever a client puts to the left of it is ignored. A header with fewer entries than that (a LAN road with one proxy beside a Cloudflare road with two) is read at its leftmost entry, the one the first proxy wrote.
When that entry says `https`, the session cookie is marked `Secure` and the response carries `Strict-Transport-Security: max-age=31536000`. Over plain HTTP neither is sent, and Grimoire never redirects to HTTPS, so a LAN install keeps working.
A hop count higher than the real number of proxies lets a client choose its own address, so count them. With `0`, the headers are ignored and the socket peer is the client: use it when clients reach port 5000 directly.
## Security checklist ## Security checklist
- **Keep the key.** Forge tokens and the backup destination's S3 secret are sealed under a key derived from `SECRET_KEY`, so a copy of the database alone can't read them. Unset, the instance makes a random key and keeps it in `/data/secret_key`, readable by its owner only; keep that volume. If the key changes (say, a restore onto an instance with a different key), Settings marks those credentials and asks for them again; nothing else breaks. The app warns at startup when `SECRET_KEY` is a public placeholder or `/data` is not a mounted volume, and refuses to start with `dev-secret-change-me` when `SECURE_COOKIES=true`. - **Keep the key.** Forge tokens and the backup destination's S3 secret are sealed under a key derived from `SECRET_KEY`, so a copy of the database alone can't read them. Unset, the instance makes a random key and keeps it in `/data/secret_key`, readable by its owner only; keep that volume. If the key changes (say, a restore onto an instance with a different key), Settings marks those credentials and asks for them again; nothing else breaks. The app warns at startup when `SECRET_KEY` is a public placeholder or `/data` is not a mounted volume, and refuses to start with a placeholder key (`dev-secret-change-me`, `change-me-in-production`).
- **`SECURE_COOKIES=true`** whenever Grimoire is served over HTTPS. - **The proxy count** (Settings → Config → Reverse proxy) matches the number of proxies in front of Grimoire, so rate limits and the audit log see the real client and the cookie is `Secure` over HTTPS. The section shows whether it does.
- **Registration** is open only for the first account. Invite people, or open it briefly from Settings. - **Registration** is open only for the first account. Invite people, or open it briefly from Settings.
- **Signing everyone else out**: changing a password ends that user's other sessions; Settings → Account has a button for it too. - **Signing everyone else out**: changing a password ends that user's other sessions; Settings → Account has a button for it too.
- **API keys** are per user, shown once, and can be read-only. Revoke any you no longer use under Settings → MCP Access. - **API keys** are per user, shown once, and can be read-only. Revoke any you no longer use under Settings → MCP Access.
+4 -3
View File
@@ -66,6 +66,7 @@ Saved procedures, such as a drift audit or a DRY pass. The plugin syncs each one
The whole store is reachable through the MCP endpoint at `/mcp`, authenticated with an API key. The Claude Code plugin in this repo adds: The whole store is reachable through the MCP endpoint at `/mcp`, authenticated with an API key. The Claude Code plugin in this repo adds:
- hooks for session start, each prompt, before and after tool calls, the end of a turn, compaction and session end, all failing open if Grimoire is unreachable; - hooks for session start, each prompt, before and after tool calls, the end of a turn, compaction and session end, all failing open if Grimoire is unreachable;
- a project fence: a session belongs to the project its starting directory is bound to. Toward any other project it can read anything and file an issue. Editing that project's files, committing or pushing in its repo, or changing its records first asks you, in every permission mode;
- skills for the working practices: using Grimoire, writing plans, systematic debugging, verification, brainstorming, reporting back, reusing code, shape accounting and family canon; - skills for the working practices: using Grimoire, writing plans, systematic debugging, verification, brainstorming, reporting back, reusing code, shape accounting and family canon;
- your stored processes as skills. - your stored processes as skills.
@@ -85,8 +86,8 @@ Share a project, note or task with users or groups, as viewer, editor or admin.
## Export and backup ## Export and backup
- **Personal export**: your notes and tasks as a Markdown ZIP (with YAML frontmatter) or JSON. - **Personal export**: your notes and tasks as a Markdown ZIP (with YAML frontmatter) or JSON.
- **Admin backup and restore**, with ids remapped so a backup restores onto another instance. - **Admin backup and restore**: a restore rolls the whole instance back to one of its own backups, after saving the current state, or brings a new instance back from any backup.
- **Scheduled backups**: a daily, dated, uncompressed tar to a folder or an S3-compatible bucket, laid out so a deduplicating tool such as restic stores only what changed. `python -m grimoire.restore` brings a fresh instance back from one. See [Backups](backups.md). - **Scheduled backups**: a daily, dated, uncompressed tar to a folder or an S3-compatible bucket, laid out so a deduplicating tool such as restic stores only what changed. Restoring is in Settings, or `python -m grimoire.restore`. See [Backups](backups.md).
## Sign-in ## Sign-in
@@ -102,7 +103,7 @@ Email and password, plus optional OIDC single sign-on (Authentik, Keycloak, ...)
| Integrations | SearXNG, git forge connections | | Integrations | SearXNG, git forge connections |
| Data | Export, backup and restore, scheduled backups (admin) | | Data | Export, backup and restore, scheduled backups (admin) |
| MCP Access | API keys and the command to connect Claude | | MCP Access | API keys and the command to connect Claude |
| Config (admin) | What's running, application URL, plugin marketplace, database maintenance, SMTP, forge webhook | | Config (admin) | What's running, reverse proxy count (checked against your own request), application URL, plugin marketplace, database maintenance, SMTP, forge webhook |
| Shared areas (admin) | The canonical areas systems map to | | Shared areas (admin) | The canonical areas systems map to |
| Platforms (admin) | The platform catalogue family canon is grouped by | | Platforms (admin) | The platform catalogue family canon is grouped by |
| Users (admin) | Registration, invites, users | | Users (admin) | Registration, invites, users |
+70 -1
View File
@@ -1,4 +1,4 @@
import { apiGet, apiPost, apiPut } from "@/api/client"; import { apiGet, apiPost, apiPostRaw, apiPut } from "@/api/client";
/** /**
* Scheduled backups — `/api/admin/backups`. One dated, * Scheduled backups — `/api/admin/backups`. One dated,
@@ -71,3 +71,72 @@ export function checkBackupDestination(
export function runBackupNow(): Promise<{ status: string }> { export function runBackupNow(): Promise<{ status: string }> {
return apiPost<{ status: string }>("/api/admin/backups/run", {}); return apiPost<{ status: string }>("/api/admin/backups/run", {});
} }
// ── Restore: put the whole instance back to a full backup ─────────────────
export interface StoredBackup {
name: string;
size_bytes: number;
}
export interface RestoreCount {
kind: string;
now: number;
after: number;
}
export interface RestorePreview {
/** "fresh": an empty instance takes the backup. "rollback": this instance
* goes back to its own earlier backup. */
mode: "fresh" | "rollback";
exported_at: string | null;
counts: RestoreCount[];
}
export interface RestoreResult extends RestorePreview {
status: "ok";
restored: Record<string, number>;
safety_backup: { file: string; size_bytes: number; where: string; note?: string };
}
/** A backup at the destination, by name, or a file picked from this computer. */
export type RestoreFrom = { source: string } | { file: File };
// Reading, checking and writing the whole store is slow by design; bounded,
// but in minutes.
const RESTORE_TIMEOUT_MS = 10 * 60 * 1000;
export function listRestoreSources(): Promise<{ backups: StoredBackup[]; error?: string }> {
return apiGet("/api/admin/restore/sources", { timeoutMs: 60_000 });
}
async function restoreCall<T>(path: string, from: RestoreFrom, query: Record<string, string> = {}): Promise<T> {
const params = new URLSearchParams(query);
if ("source" in from) {
params.set("source", from.source);
return apiPostRaw<T>(`${path}?${params}`, null, null, { timeoutMs: RESTORE_TIMEOUT_MS });
}
const qs = params.toString() ? `?${params}` : "";
const isTar = from.file.name.toLowerCase().endsWith(".tar");
// The JSON download is parsed first, so a damaged file fails here, before
// the upload.
const body = isTar ? from.file : JSON.stringify(JSON.parse(await from.file.text()));
return apiPostRaw<T>(`${path}${qs}`, body, isTar ? "application/x-tar" : "application/json",
{ timeoutMs: RESTORE_TIMEOUT_MS });
}
export function previewRestore(from: RestoreFrom): Promise<RestorePreview> {
return restoreCall<RestorePreview>("/api/admin/restore/preview", from);
}
export function restoreBackup(from: RestoreFrom): Promise<RestoreResult> {
return restoreCall<RestoreResult>("/api/admin/restore", from, { confirm: "rollback" });
}
/** When a backup named `grimoire-20261015T020000Z.tar` was taken. */
export function backupTakenAt(name: string): Date | null {
const m = /(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/.exec(name);
if (!m) return null;
return new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]));
}
+9
View File
@@ -156,6 +156,15 @@ export function apiPost<T>(path: string, body: unknown, opts?: RequestOpts): Pro
return request<T>(path, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) }, opts); return request<T>(path, { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(body) }, opts);
} }
/** A POST whose body is sent as it is (a file, or text already serialised),
* under the same deadline and error handling as every other call. */
export function apiPostRaw<T>(
path: string, body: BodyInit | null, contentType: string | null, opts?: RequestOpts,
): Promise<T> {
const headers = contentType ? { "Content-Type": contentType } : undefined;
return request<T>(path, { method: "POST", headers, body }, opts);
}
export function apiPut<T>(path: string, body: unknown, opts?: RequestOpts): Promise<T> { export function apiPut<T>(path: string, body: unknown, opts?: RequestOpts): Promise<T> {
return request<T>(path, { method: "PUT", headers: JSON_HEADERS, body: JSON.stringify(body) }, opts); return request<T>(path, { method: "PUT", headers: JSON_HEADERS, body: JSON.stringify(body) }, opts);
} }
+113
View File
@@ -1,4 +1,5 @@
import { apiGet, apiPost, apiDelete } from "@/api/client"; import { apiGet, apiPost, apiDelete } from "@/api/client";
import type { RuleEnforcement, RuleSalience, RuleTrigger } from "@/api/rulebooks";
/** /**
* The moments of work rules mount on, and the actions that * The moments of work rules mount on, and the actions that
@@ -180,3 +181,115 @@ export function getProposals(ruleId?: number): Promise<ProposalsPayload> {
export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> { export function judgeProposals(judgments: MomentJudgment[]): Promise<JudgeResult> {
return apiPost("/api/retrieval/moments/proposals/judge", { judgments }); return apiPost("/api/retrieval/moments/proposals/judge", { judgments });
} }
/**
* Suggestions for how strongly a rule arrives (`enforcement`, `salience`) and
* which typed triggers reach it, from a pass that read the rule beside its
* delivery history. Nothing changes until a person confirms one.
* `GET /api/retrieval/weights/proposals`, the payload the
* `rule_weight_proposals` MCP tool returns.
*/
export type WeightField = "enforcement" | "salience" | "trigger";
/** What happened when the rule reached a session, over `days`. */
export interface WeightEvidence {
days?: number;
delivered?: number;
opened?: number;
places?: { at: string; delivered: number; opened: number }[];
pulled?: number;
applied?: number;
departed?: number;
misfire_days?: number;
}
export interface WeightProposal {
field: WeightField;
/** The enforcement or salience name; for a trigger, its stored form. */
value: string;
trigger?: RuleTrigger;
why: string;
source: "pass" | "edit";
evidence: WeightEvidence;
created_at: string | null;
}
export interface RuleWeightProposals {
id: number;
title: string;
kind: string;
statement: string;
when_to_apply: string;
home: "global" | "project";
enforcement: RuleEnforcement;
salience: RuleSalience;
mounted: string[];
triggers: RuleTrigger[];
proposals: WeightProposal[];
}
export interface WeightProposalsPayload {
rules: RuleWeightProposals[];
total: number;
}
export interface WeightJudgment {
rule_id: number;
field: WeightField;
value: string | RuleTrigger;
verdict: Verdict;
note?: string;
}
export interface WeightJudgeResult {
judged: { rule_id: number; field: WeightField; value: string; state: string }[];
refused: { rule_id: number; field?: string; error: string }[];
}
/** One rule at one place, or a sum of them: how many sessions it was in
* force in, opened in, and what each was judged. */
export interface AdherenceCounts {
in_force: number;
opened: number;
followed: number;
/** Read and deliberately not followed, with a stated reason. */
departed: number;
broken: number;
not_applicable: number;
unjudged: number;
}
export interface RuleAdherenceRow extends AdherenceCounts {
rule_id: number;
/** Null for a rule deleted since. */
title: string | null;
by_moment: (AdherenceCounts & { at: string })[];
}
export interface MomentAdherenceRow extends AdherenceCounts {
/** A moment (`work.deliver`) or an arm (`pre_tool_rule`). */
at: string;
by_rule: (AdherenceCounts & { rule_id: number; title: string | null })[];
}
export interface AdherencePayload {
days: number;
totals: AdherenceCounts;
by_rule: RuleAdherenceRow[];
by_moment: MomentAdherenceRow[];
}
/** 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 });
}
+33
View File
@@ -54,6 +54,27 @@ export interface RulebookTopic {
*/ */
export type RuleKind = "rule" | "preference"; export type RuleKind = "rule" | "preference";
/**
* What a rule does when it arrives, declared by its author. `inform` puts a
* line beside the work; `hold` makes the reply or command it governs wait for
* one read; `enforce` refuses an act its moment or trigger reaches. A
* preference is always `inform`.
*/
export type RuleEnforcement = "enforce" | "hold" | "inform";
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
export type RuleSalience = "high" | "normal" | "low";
/** What a trigger is matched against on the act: the tool called, a path it
* touches, the head of a command it runs, or a word in what it writes. */
export type RuleTriggerKind = "tool" | "path" | "command" | "keyword";
/** A typed predicate on the act, checked exactly. With no `moment` it
* delivers the rule on any matching act; with one, it makes the rule's
* mount on that moment conditional on the act matching. */
export interface RuleTrigger {
kind: RuleTriggerKind;
pattern: string;
moment?: string;
}
/** A new record opened from somewhere that already knows what it is for — /** A new record opened from somewhere that already knows what it is for —
* "Adjust this" on a reply shape opens a preference mounted on that shape's * "Adjust this" on a reply shape opens a preference mounted on that shape's
* moment. The editor applies it once, when creating. */ * moment. The editor applies it once, when creating. */
@@ -70,6 +91,8 @@ export interface Rule {
title: string; title: string;
statement: string; statement: string;
kind: RuleKind; kind: RuleKind;
enforcement: RuleEnforcement;
salience: RuleSalience;
/** WHEN this rule fires — the trigger, not the instruction. */ /** WHEN this rule fires — the trigger, not the instruction. */
when_to_apply: string; when_to_apply: string;
why: string; why: string;
@@ -94,6 +117,8 @@ export interface Rule {
/** The moments this rule arrives at whenever they happen, /** The moments this rule arrives at whenever they happen,
* in catalog order. Present only when the rule is mounted. */ * in catalog order. Present only when the rule is mounted. */
moments?: string[]; moments?: string[];
/** Present only when the rule has triggers. */
triggers?: RuleTrigger[];
relations?: RuleRelation[]; relations?: RuleRelation[];
/** The lessons that point at this rule — the concrete /** The lessons that point at this rule — the concrete
* situations judged instances of it, plus any suggested and awaiting a * situations judged instances of it, plus any suggested and awaiting a
@@ -113,6 +138,10 @@ export interface RuleHeader {
topic_id: number | null; topic_id: number | null;
/** Unconditional on the wire (services.rulebooks.rule_brief). */ /** Unconditional on the wire (services.rulebooks.rule_brief). */
kind: RuleKind; kind: RuleKind;
/** Unconditional on the wire, like `kind`. */
enforcement: RuleEnforcement;
/** Present only when raised or lowered from `normal`. */
salience?: RuleSalience;
/** A date (YYYY-MM-DD), not a timestamp. */ /** A date (YYYY-MM-DD), not a timestamp. */
updated_at: string | null; updated_at: string | null;
when_to_apply?: string; when_to_apply?: string;
@@ -217,6 +246,8 @@ export interface RuleWrite {
/** Writable from the editor: a preference is not a lesser rule, it is a /** Writable from the editor: a preference is not a lesser rule, it is a
* different force, and the person writing it is the one who knows which. */ * different force, and the person writing it is the one who knows which. */
kind: RuleKind; kind: RuleKind;
enforcement: RuleEnforcement;
salience: RuleSalience;
when_to_apply: string; when_to_apply: string;
why: string; why: string;
how_to_apply: string; how_to_apply: string;
@@ -224,6 +255,8 @@ export interface RuleWrite {
system_ids: number[]; system_ids: number[];
/** Replaces the set; [] unmounts the rule from every moment. */ /** Replaces the set; [] unmounts the rule from every moment. */
moments: string[]; moments: string[];
/** Replaces the set; [] clears every trigger. */
triggers: RuleTrigger[];
arose_from_id: number | null; arose_from_id: number | null;
verify_with: string; verify_with: string;
expires_when: string; expires_when: string;
+39
View File
@@ -147,6 +147,45 @@
text-decoration: none; text-decoration: none;
} }
/* A record reference — `#4286`, `milestone 639`, `rule 34`. Reads as a link in
running text rather than a chip: a work log cites a dozen of them, and a row
of pills would drown the sentence they sit in. */
.record-ref {
color: var(--fs-wikilink);
text-decoration: underline;
text-decoration-color: color-mix(in srgb, var(--fs-wikilink) 40%, transparent);
text-underline-offset: 0.15em;
font-variant-numeric: tabular-nums;
border-radius: var(--fs-radius-sm);
cursor: pointer;
}
.record-ref:hover {
text-decoration-color: currentColor;
}
/* Drawn with its title: the title reads as the link, the number after it is
the citation, quieter and never split across lines. */
.record-ref__id {
color: var(--fs-text-secondary);
font-size: 0.85em;
white-space: nowrap;
}
.record-ref:focus-visible {
outline: none;
box-shadow: var(--fs-focus-ring);
}
/* One the reader cannot open: missing, trashed or not shared. Still legible —
the number is part of the sentence — but plainly not a way through. */
.record-ref--missing {
color: var(--fs-text-tertiary-fg);
text-decoration-style: dashed;
text-decoration-color: var(--fs-text-tertiary);
cursor: default;
}
/* Task list */ /* Task list */
.prose ul[data-type="taskList"] { .prose ul[data-type="taskList"] {
list-style: none; list-style: none;
+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);
}
-466
View File
@@ -1,466 +0,0 @@
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { apiGet, pinNoteVersion, unpinNoteVersion } from "@/api/client";
import DiffView from "@/components/DiffView.vue";
import { computeDiff, type DiffLine } from "@/utils/diff";
import { fmtStamp } from "@/utils/dateFormat";
interface NoteVersion {
id: number;
note_id: number;
title: string;
tags: string[];
body?: string;
pin_kind: "auto" | "manual" | null;
pin_label: string | null;
created_at: string;
}
const props = defineProps<{
noteId: number;
currentBody: string;
}>();
const emit = defineEmits<{
(e: 'restore', body: string, tags: string[]): void;
(e: 'close'): void;
}>();
const versions = ref<NoteVersion[]>([]);
const selectedVersion = ref<NoteVersion | null>(null);
const loading = ref(false);
const loadingDetail = ref(false);
const diff = computed<DiffLine[]>(() => {
if (!selectedVersion.value?.body) return [];
return computeDiff(props.currentBody, selectedVersion.value.body);
});
async function loadVersions() {
loading.value = true;
try {
const data = await apiGet<{ versions: NoteVersion[] }>(
`/api/notes/${props.noteId}/versions`
);
versions.value = data.versions;
if (versions.value.length > 0) {
await selectVersionItem(versions.value[0]);
}
} catch {
// silent
} finally {
loading.value = false;
}
}
async function selectVersionItem(v: NoteVersion) {
if (v.body !== undefined) {
selectedVersion.value = v;
return;
}
loadingDetail.value = true;
try {
const full = await apiGet<NoteVersion>(
`/api/notes/${props.noteId}/versions/${v.id}`
);
// Cache body back onto list item
const listItem = versions.value.find(x => x.id === v.id);
if (listItem) listItem.body = full.body;
selectedVersion.value = full;
} catch {
// silent
} finally {
loadingDetail.value = false;
}
}
function restore() {
if (!selectedVersion.value?.body) return;
emit('restore', selectedVersion.value.body, selectedVersion.value.tags ?? []);
}
// ── Pin / unpin / edit-label state ──────────────────────────────────────────
const editingLabel = ref(false);
const draftLabel = ref("");
const pinSaving = ref(false);
function startEditLabel() {
if (!selectedVersion.value) return;
draftLabel.value = selectedVersion.value.pin_label ?? "";
editingLabel.value = true;
}
function cancelEditLabel() {
editingLabel.value = false;
draftLabel.value = "";
}
async function savePin() {
if (!selectedVersion.value || pinSaving.value) return;
pinSaving.value = true;
try {
const updated = await pinNoteVersion(
props.noteId, selectedVersion.value.id, draftLabel.value || null,
);
// Reflect server state in the local list + selected version.
const idx = versions.value.findIndex(v => v.id === updated.id);
if (idx >= 0) {
versions.value[idx].pin_kind = updated.pin_kind;
versions.value[idx].pin_label = updated.pin_label;
}
if (selectedVersion.value) {
selectedVersion.value.pin_kind = updated.pin_kind;
selectedVersion.value.pin_label = updated.pin_label;
}
editingLabel.value = false;
} catch {
// silent — leaving the form open lets the user retry
} finally {
pinSaving.value = false;
}
}
async function unpinSelected() {
if (!selectedVersion.value || pinSaving.value) return;
pinSaving.value = true;
try {
await unpinNoteVersion(props.noteId, selectedVersion.value.id);
const idx = versions.value.findIndex(v => v.id === selectedVersion.value!.id);
if (idx >= 0) {
versions.value[idx].pin_kind = null;
versions.value[idx].pin_label = null;
}
if (selectedVersion.value) {
selectedVersion.value.pin_kind = null;
selectedVersion.value.pin_label = null;
}
} catch {
// silent
} finally {
pinSaving.value = false;
}
}
onMounted(loadVersions);
</script>
<template>
<teleport to="body">
<div class="modal-overlay" @click.self="emit('close')">
<div class="modal-card history-modal">
<div class="history-header">
<h3 class="history-title">Version History</h3>
<button class="history-close" aria-label="Close version history" @click="emit('close')">&times;</button>
</div>
<div class="history-body">
<!-- Left: version list -->
<div class="history-list">
<div v-if="loading" class="history-empty">Loading...</div>
<div v-else-if="!versions.length" class="history-empty">No versions yet.</div>
<div
v-for="v in versions"
:key="v.id"
:class="['history-item', { selected: selectedVersion?.id === v.id }]"
@click="selectVersionItem(v)"
>
<div class="history-item-title">
<span
v-if="v.pin_kind === 'manual'"
class="pin-badge pin-badge-manual"
:title="v.pin_label || 'Pinned'"
aria-label="manually pinned"
>●</span>
<span
v-else-if="v.pin_kind === 'auto'"
class="pin-badge pin-badge-auto"
:title="v.pin_label || 'Auto-pinned (stable)'"
aria-label="auto-pinned"
>◐</span>
{{ v.title || 'Untitled' }}
</div>
<div
v-if="v.pin_kind === 'manual' && v.pin_label"
class="history-item-label"
>{{ v.pin_label }}</div>
<div class="history-item-date">{{ fmtStamp(v.created_at) }}</div>
</div>
</div>
<!-- Right: diff -->
<div class="history-diff">
<div v-if="loadingDetail" class="history-empty">Loading version...</div>
<div v-else-if="!selectedVersion" class="history-empty">Select a version to compare.</div>
<template v-else>
<div class="version-pin-controls">
<!-- Label editor -->
<div v-if="editingLabel" class="pin-label-form">
<input
v-model="draftLabel"
maxlength="500"
type="text"
class="pin-label-input"
placeholder="Optional label (e.g. 'post-network-refresh runbook')"
/>
<button class="btn-pin-save" :disabled="pinSaving" @click="savePin">
{{ pinSaving ? "Saving…" : "Save" }}
</button>
<button class="btn-pin-cancel" @click="cancelEditLabel">Cancel</button>
</div>
<!-- Default: kind-aware action row -->
<div v-else class="pin-actions">
<span v-if="selectedVersion.pin_kind === 'manual'" class="pin-state">
<span class="pin-badge pin-badge-manual">●</span>
Manually pinned{{ selectedVersion.pin_label ? `: ${selectedVersion.pin_label}` : '' }}
</span>
<span v-else-if="selectedVersion.pin_kind === 'auto'" class="pin-state">
<span class="pin-badge pin-badge-auto">◐</span>
Auto-pinned{{ selectedVersion.pin_label ? `: ${selectedVersion.pin_label}` : '' }}
</span>
<button
v-if="selectedVersion.pin_kind === null"
class="btn-pin"
:disabled="pinSaving"
@click="startEditLabel"
>Pin version</button>
<button
v-else-if="selectedVersion.pin_kind === 'manual'"
class="btn-pin-edit"
:disabled="pinSaving"
@click="startEditLabel"
>Edit label</button>
<button
v-else
class="btn-pin"
:disabled="pinSaving"
@click="startEditLabel"
>Pin permanently</button>
<button
v-if="selectedVersion.pin_kind === 'manual'"
class="btn-unpin"
:disabled="pinSaving"
@click="unpinSelected"
>Unpin</button>
</div>
</div>
<DiffView :diff="diff" />
</template>
</div>
</div>
<div class="history-footer">
<button
class="btn-primary"
:disabled="!selectedVersion?.body"
@click="restore"
>Restore this version</button>
<button class="modal-btn" @click="emit('close')">Close</button>
</div>
</div>
</div>
</teleport>
</template>
<style scoped>
.history-modal {
max-width: 900px;
width: 95%;
height: 80vh;
max-height: 700px;
display: flex;
flex-direction: column;
padding: 0;
}
.history-header {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.9rem 1.25rem;
border-bottom: 1px solid var(--fs-border-color);
}
.history-title {
margin: 0;
font-size: 1rem;
}
.history-close {
background: none;
border: none;
font-size: 1.25rem;
cursor: pointer;
color: var(--fs-text-tertiary);
line-height: 1;
padding: 0.1rem 0.3rem;
}
.history-close:hover { color: var(--fs-text-primary); }
.history-body {
flex: 1;
min-height: 0;
display: flex;
overflow: hidden;
}
.history-list {
width: 220px;
flex-shrink: 0;
border-right: 1px solid var(--fs-border-color);
overflow-y: auto;
}
.history-item {
padding: 0.6rem 0.9rem;
cursor: pointer;
border-left: 3px solid transparent;
border-bottom: 1px solid var(--fs-border-color);
}
.history-item:hover { background: var(--fs-surface-raised); }
.history-item.selected {
border-left-color: var(--fs-accent);
background: var(--fs-surface-raised);
}
.history-item-title {
font-size: 0.85rem;
font-weight: 500;
color: var(--fs-text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.history-item-date {
font-size: 0.75rem;
color: var(--fs-text-tertiary);
margin-top: 0.15rem;
}
.history-diff {
flex: 1;
min-width: 0;
overflow: hidden;
display: flex;
flex-direction: column;
padding: 0.5rem;
}
.history-empty {
padding: 1rem;
font-size: 0.85rem;
color: var(--fs-text-tertiary);
}
.history-footer {
flex-shrink: 0;
display: flex;
gap: 0.5rem;
justify-content: flex-end;
padding: 0.75rem 1.25rem;
border-top: 1px solid var(--fs-border-color);
}
/* ── Pin badges + label rendering ───────────────────────────────────────── */
.pin-badge {
display: inline-block;
width: 0.7rem;
text-align: center;
margin-right: 0.35rem;
font-size: 0.85em;
line-height: 1;
}
.pin-badge-manual { color: var(--fs-accent); }
.pin-badge-auto { color: var(--fs-text-tertiary); }
.history-item-label {
font-size: 0.72rem;
color: var(--fs-accent);
font-style: italic;
margin-top: 0.15rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* ── Pin controls above the diff ────────────────────────────────────────── */
.version-pin-controls {
padding: 0.4rem 0.5rem 0.5rem;
border-bottom: 1px solid var(--fs-border-color);
font-size: 0.82rem;
}
.pin-actions {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.pin-state {
font-style: italic;
color: var(--fs-text-tertiary);
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.btn-pin, .btn-pin-edit, .btn-unpin {
padding: 0.25rem 0.7rem;
font-size: 0.78rem;
background: transparent;
color: inherit;
border: 1px solid var(--fs-border-color);
border-radius: 999px;
cursor: pointer;
}
.btn-pin:hover:not(:disabled), .btn-pin-edit:hover:not(:disabled) {
background: rgba(99, 102, 241, 0.12);
border-color: var(--fs-accent);
}
.btn-unpin:hover:not(:disabled) {
background: rgba(239, 68, 68, 0.10);
border-color: rgba(239, 68, 68, 0.5);
}
.pin-label-form {
display: flex;
gap: 0.4rem;
align-items: center;
}
.pin-label-input {
flex: 1;
padding: 0.3rem 0.5rem;
font-size: 0.85rem;
background: var(--fs-surface-page);
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-sm);
color: inherit;
}
.pin-label-input:focus {
outline: none;
border-color: var(--fs-accent);
}
.btn-pin-save, .btn-pin-cancel {
padding: 0.3rem 0.7rem;
font-size: 0.78rem;
background: transparent;
color: inherit;
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-sm);
cursor: pointer;
}
.btn-pin-save:hover:not(:disabled) {
background: rgba(99, 102, 241, 0.12);
border-color: var(--fs-accent);
}
.btn-pin-save:disabled, .btn-pin-cancel:disabled,
.btn-pin:disabled, .btn-pin-edit:disabled, .btn-unpin:disabled {
opacity: 0.5;
cursor: progress;
}
</style>
@@ -1,258 +0,0 @@
<script setup lang="ts">
import { ref, computed } from "vue";
import { renderMarkdown } from "@/utils/markdown";
import type { DiffLine } from "@/composables/useAssist";
const props = defineProps<{
phase: "streaming" | "review";
label: string;
streamingText: string;
diff: DiffLine[];
proposedText: string;
}>();
const emit = defineEmits<{
accept: [];
reject: [];
cancel: [];
}>();
const showFullText = ref(false);
const renderedStreaming = computed(() => renderMarkdown(props.streamingText));
const renderedProposed = computed(() => renderMarkdown(props.proposedText));
const markers: Record<DiffLine["type"], string> = {
equal: " ",
delete: "−",
insert: "+",
};
</script>
<template>
<!-- ── Streaming ───────────────────────────────────────────────── -->
<div v-if="phase === 'streaming'" class="iap iap-streaming">
<div class="iap-header">
<span class="iap-pulse"></span>
<span class="iap-label">{{ label }}</span>
<button class="iap-btn-cancel" @click="emit('cancel')">Cancel</button>
</div>
<div class="iap-stream-preview prose" v-html="renderedStreaming"></div>
<div v-if="!streamingText" class="iap-waiting">Waiting for model…</div>
</div>
<!-- ── Review ─────────────────────────────────────────────────── -->
<div v-else-if="phase === 'review'" class="iap iap-review">
<div class="iap-header">
<span class="iap-review-title">Proposed changes</span>
<button class="iap-btn-toggle" @click="showFullText = !showFullText">
{{ showFullText ? "Show diff" : "Show full text" }}
</button>
<div class="iap-actions">
<button class="iap-btn-accept" @click="emit('accept')">✓ Accept</button>
<button class="iap-btn-reject" @click="emit('reject')">✗ Reject</button>
</div>
</div>
<!-- Diff view -->
<div v-if="!showFullText" class="iap-diff">
<div
v-for="(line, i) in diff"
:key="i"
:class="['iap-diff-line', `iap-diff-${line.type}`]"
>
<span class="iap-diff-marker">{{ markers[line.type] }}</span>
<span class="iap-diff-text">{{ line.text }}</span>
</div>
<div v-if="!diff.length" class="iap-diff-empty">No changes.</div>
</div>
<!-- Full text view -->
<div v-else class="iap-full-text prose" v-html="renderedProposed"></div>
</div>
</template>
<style scoped>
.iap {
border-radius: var(--fs-radius-sm);
margin-bottom: 0.75rem;
overflow: hidden;
border: 1px solid var(--fs-border-color);
background: var(--fs-surface-page);
}
/* ── Header ── */
.iap-header {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.45rem 0.75rem;
font-size: 0.85rem;
border-bottom: 1px solid var(--fs-border-color);
background: var(--fs-surface-raised);
}
/* ── Streaming ── */
.iap-streaming {
border-color: var(--fs-accent);
}
.iap-streaming .iap-header {
background: color-mix(in srgb, var(--fs-accent) 8%, var(--fs-surface-raised));
}
.iap-pulse {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--fs-accent);
flex-shrink: 0;
animation: iap-pulse 1.2s ease-in-out infinite;
}
@keyframes iap-pulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.4; transform: scale(0.8); }
}
.iap-label {
flex: 1;
font-weight: 500;
color: var(--fs-text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.iap-btn-cancel {
background: none;
border: 1px solid var(--fs-border-color);
color: var(--fs-text-secondary);
border-radius: var(--fs-radius-sm);
padding: 0.15rem 0.5rem;
cursor: pointer;
font-size: 0.8rem;
font-family: inherit;
flex-shrink: 0;
}
.iap-btn-cancel:hover {
border-color: var(--fs-error);
color: var(--fs-error);
}
.iap-stream-preview {
padding: 0.75rem;
font-size: 0.9rem;
min-height: 2.5rem;
max-height: 320px;
overflow-y: auto;
}
.iap-waiting {
padding: 0.75rem;
font-size: 0.85rem;
color: var(--fs-text-tertiary);
}
/* ── Review ── */
.iap-review-title {
flex: 1;
font-weight: 600;
color: var(--fs-text-primary);
}
.iap-btn-toggle {
background: none;
border: 1px solid var(--fs-border-color);
color: var(--fs-text-secondary);
border-radius: var(--fs-radius-sm);
padding: 0.15rem 0.5rem;
cursor: pointer;
font-size: 0.78rem;
font-family: inherit;
}
.iap-btn-toggle:hover {
border-color: var(--fs-accent);
color: var(--fs-accent);
}
.iap-actions {
display: flex;
gap: 0.35rem;
}
.iap-btn-accept,
.iap-btn-reject {
border: none;
border-radius: var(--fs-radius-sm);
padding: 0.2rem 0.65rem;
cursor: pointer;
font-size: 0.8rem;
font-family: inherit;
font-weight: var(--fs-weight-medium);
}
.iap-btn-accept {
background: var(--fs-success);
color: var(--fs-text-on-action);
}
.iap-btn-accept:hover { opacity: 0.85; }
.iap-btn-reject {
background: var(--fs-surface-raised);
color: var(--fs-text-secondary);
border: 1px solid var(--fs-border-color);
}
.iap-btn-reject:hover {
border-color: var(--fs-error);
color: var(--fs-error);
}
/* ── Diff ── */
.iap-diff {
font-family: ui-monospace, "Cascadia Code", "Fira Mono", monospace;
font-size: 0.82rem;
line-height: 1.6;
max-height: 440px;
overflow-y: auto;
padding: 0.4rem 0;
}
.iap-diff-line {
display: flex;
gap: 0.5rem;
padding: 0 0.75rem;
white-space: pre-wrap;
word-break: break-word;
}
.iap-diff-equal { color: var(--fs-text-tertiary); }
.iap-diff-delete {
background: color-mix(in srgb, var(--fs-error) 10%, transparent);
color: var(--fs-error-fg);
}
.iap-diff-insert {
background: color-mix(in srgb, var(--fs-success) 10%, transparent);
color: var(--fs-success-fg);
}
.iap-diff-marker {
width: 1ch;
flex-shrink: 0;
font-weight: 700;
user-select: none;
}
.iap-diff-empty {
padding: 0.75rem;
color: var(--fs-text-tertiary);
font-size: 0.85rem;
font-family: inherit;
}
/* ── Full text ── */
.iap-full-text {
padding: 0.75rem;
font-size: 0.9rem;
max-height: 440px;
overflow-y: auto;
}
</style>
+1 -28
View File
@@ -158,33 +158,6 @@ onMounted(load);
</section> </section>
</template> </template>
<style scoped> <style scoped src="@/assets/rule-proposals.css" />
.proposals { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.proposal-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-rule {
padding: var(--fs-space-3);
background: var(--fs-surface-page);
border: 1px dashed var(--fs-border-color);
border-radius: var(--fs-radius-md);
}
.rule-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.rule-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); font-weight: var(--fs-weight-medium); }
.rule-mounted { display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-1); font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.rule-statement { margin: var(--fs-space-1) 0 var(--fs-space-2); font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); line-height: var(--fs-leading-body); }
.proposal-items { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-2); }
.proposal-item { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); font-size: var(--fs-size-body-sm); }
.proposal-why { flex: 1 1 16rem; color: var(--fs-text-secondary); }
.proposal-source { color: var(--fs-text-tertiary); font-size: var(--fs-size-tiny); }
.proposal-actions { display: inline-flex; gap: var(--fs-space-2); margin-left: auto; }
.proposal-kind { font-size: var(--fs-size-tiny); color: var(--fs-text-tertiary); }
.proposal-reasons {
flex-basis: 100%;
margin: 0;
padding-left: var(--fs-space-4);
font-size: var(--fs-size-tiny);
color: var(--fs-text-tertiary);
}
</style>
<style src="@/assets/moments-shared.css" /> <style src="@/assets/moments-shared.css" />
+20 -5
View File
@@ -1,12 +1,26 @@
<script setup lang="ts"> <script setup lang="ts">
import type { MomentRuleUsage } from "@/api/moments"; import type { AdherenceCounts, MomentRuleUsage } from "@/api/moments";
/** /**
* Which rules a moment delivered, and whether an agent went on to read each. * Which rules a moment delivered, whether an agent went on to read each, and
* The moment's own counts cannot say this once two rules are mounted there. * — where a verdict exists — whether it was followed there. The moment's own
* Closed by default: the counts in the row above are what most visits want. * counts cannot say this once two rules are mounted there. Closed by default:
* the counts in the row above are what most visits want.
*/ */
defineProps<{ rules: MomentRuleUsage[] }>(); withDefaults(defineProps<{
rules: MomentRuleUsage[];
/** This moment's adherence per rule id, from the adherence readout. */
adherence?: Record<number, AdherenceCounts>;
}>(), { adherence: () => ({}) });
function verdicts(c: AdherenceCounts | undefined): string {
if (!c) return "";
const parts = [`followed ${c.followed} of ${c.in_force}`];
if (c.broken) parts.push(`broken ${c.broken}`);
if (c.departed) parts.push(`departed ${c.departed}`);
if (c.not_applicable) parts.push(`not applicable ${c.not_applicable}`);
return parts.join(" · ");
}
</script> </script>
<template> <template>
@@ -19,6 +33,7 @@ defineProps<{ rules: MomentRuleUsage[] }>();
<span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'"> <span :class="r.opened ? 'delivered-opened' : 'delivered-unopened'">
{{ r.opened ? "opened" : "not opened" }} {{ r.opened ? "opened" : "not opened" }}
</span> </span>
<span v-if="adherence[r.rule_id]" class="delivered-count">{{ verdicts(adherence[r.rule_id]) }}</span>
</li> </li>
</ul> </ul>
</details> </details>
+44 -4
View File
@@ -3,7 +3,10 @@ import { computed, onMounted, ref } from "vue";
import { useMomentsStore } from "@/stores/moments"; import { useMomentsStore } from "@/stores/moments";
import MomentProposals from "@/components/MomentProposals.vue"; import MomentProposals from "@/components/MomentProposals.vue";
import MomentRuleUsage from "@/components/MomentRuleUsage.vue"; import MomentRuleUsage from "@/components/MomentRuleUsage.vue";
import type { MomentAction, MomentUsage } from "@/api/moments"; import WeightProposals from "@/components/WeightProposals.vue";
import RuleAdherence from "@/components/RuleAdherence.vue";
import { getAdherence } from "@/api/moments";
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage } from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat"; import { fmtDate } from "@/utils/dateFormat";
/** /**
@@ -31,6 +34,28 @@ function usage(moment: string): MomentUsage | null {
return data.value?.usage.by_moment[moment] ?? null; return data.value?.usage.by_moment[moment] ?? null;
} }
// Adherence is read on its own, so a failure there leaves the catalog and the
// delivery counts standing and says so in its own panel.
const adherence = ref<AdherencePayload | null>(null);
const adherenceFailed = ref(false);
async function loadAdherence() {
try {
adherence.value = await getAdherence(days.value);
adherenceFailed.value = false;
} catch {
adherenceFailed.value = true;
}
}
function followed(moment: string): MomentAdherenceRow | null {
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
}
function verdictsByRule(moment: string): Record<number, MomentAdherenceRow["by_rule"][number]> {
return Object.fromEntries((followed(moment)?.by_rule ?? []).map((r) => [r.rule_id, r]));
}
// A named procedure is its own moment (`skill.<name>`), so it appears here // A named procedure is its own moment (`skill.<name>`), so it appears here
// only once something is mounted on it or has been delivered at it — the // only once something is mounted on it or has been delivered at it — the
// catalog cannot list procedures it has never heard of. // catalog cannot list procedures it has never heard of.
@@ -101,7 +126,10 @@ async function addMapping() {
} }
} }
onMounted(() => store.load(true)); onMounted(async () => {
await store.load(true);
await loadAdherence();
});
</script> </script>
<template> <template>
@@ -126,6 +154,8 @@ onMounted(() => store.load(true));
</p> </p>
<MomentProposals /> <MomentProposals />
<WeightProposals />
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
<ul class="moment-list"> <ul class="moment-list">
<li v-for="m in catalog" :key="m.name" class="moment-row"> <li v-for="m in catalog" :key="m.name" class="moment-row">
@@ -142,6 +172,9 @@ onMounted(() => store.load(true));
last {{ fmtDate(usage(m.name)!.last_delivered_at!) }} last {{ fmtDate(usage(m.name)!.last_delivered_at!) }}
</span> </span>
</template> </template>
<span v-if="followed(m.name)">
followed {{ followed(m.name)!.followed }} of {{ followed(m.name)!.in_force }} in force
</span>
</span> </span>
</div> </div>
<p class="moment-desc">{{ m.means }}</p> <p class="moment-desc">{{ m.means }}</p>
@@ -168,7 +201,9 @@ onMounted(() => store.load(true));
>×</button> >×</button>
</span> </span>
</div> </div>
<MomentRuleUsage v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" /> <MomentRuleUsage
v-if="usage(m.name)" :rules="usage(m.name)!.by_rule" :adherence="verdictsByRule(m.name)"
/>
</li> </li>
</ul> </ul>
@@ -186,9 +221,14 @@ onMounted(() => store.load(true));
<span>delivered {{ usage(name)!.delivered }}</span> <span>delivered {{ usage(name)!.delivered }}</span>
<span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span> <span>opened {{ usage(name)!.opened }} of {{ usage(name)!.rules }}</span>
</template> </template>
<span v-if="followed(name)">
followed {{ followed(name)!.followed }} of {{ followed(name)!.in_force }} in force
</span>
</span> </span>
</div> </div>
<MomentRuleUsage v-if="usage(name)" :rules="usage(name)!.by_rule" /> <MomentRuleUsage
v-if="usage(name)" :rules="usage(name)!.by_rule" :adherence="verdictsByRule(name)"
/>
</li> </li>
</ul> </ul>
</template> </template>
-168
View File
@@ -1,168 +0,0 @@
<script setup lang="ts">
import { useRouter } from "vue-router";
import type { Note } from "@/types/note";
import TagPill from "@/components/TagPill.vue";
import { relativeTime } from "@/composables/useRelativeTime";
import { renderPreview } from "@/utils/markdown";
const props = defineProps<{ note: Note; compact?: boolean }>();
const emit = defineEmits<{ "tag-click": [tag: string] }>();
const router = useRouter();
function onTagClick(tag: string) {
emit("tag-click", tag);
}
function goEdit() {
router.push(`/notes/${props.note.id}/edit`);
}
</script>
<template>
<router-link :to="`/notes/${note.id}`" :class="['note-card', { compact }]">
<!-- Compact: single row -->
<template v-if="compact">
<span class="note-title-compact">{{ note.title || "Untitled" }}</span>
<div class="note-tags-compact">
<TagPill
v-for="tag in note.tags.slice(0, 3)"
:key="tag"
:tag="tag"
@click.stop="onTagClick(tag)"
/>
</div>
<span class="timestamp-compact">{{ relativeTime(note.updated_at) }}</span>
</template>
<!-- Full: original layout -->
<template v-else>
<div class="note-top">
<h3 class="note-title">{{ note.title || "Untitled" }}</h3>
<button class="btn-edit" title="Edit" @click.prevent.stop="goEdit">Edit</button>
</div>
<div v-if="note.body" class="note-preview prose" v-html="renderPreview(note.body)"></div>
<div class="note-meta">
<TagPill
v-for="tag in note.tags"
:key="tag"
:tag="tag"
@click.stop="onTagClick(tag)"
/>
<span class="timestamp">{{ relativeTime(note.updated_at) }}</span>
</div>
</template>
</router-link>
</template>
<style scoped>
.note-card {
display: block;
padding: 1rem;
border-radius: var(--fs-radius-lg);
text-decoration: none;
color: inherit;
background: var(--fs-surface-raised);
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06), 0 0 0 1px color-mix(in srgb, var(--fs-accent) 6%, transparent);
transition: box-shadow 0.2s, transform 0.18s ease;
}
.note-card:hover {
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.10), 0 0 0 1px color-mix(in srgb, var(--fs-accent) 14.0%, transparent);
transform: translateY(-2px);
}
/* Compact single-row layout */
.note-card.compact {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.45rem 0.75rem;
background: var(--fs-surface-raised);
box-shadow: none;
border-radius: 0;
border-bottom: 1px solid var(--fs-border-color);
transform: none !important;
}
.note-card.compact:first-child {
border-top: 1px solid var(--fs-border-color);
}
.note-card.compact:hover {
box-shadow: none;
background: color-mix(in srgb, var(--fs-accent) 4%, transparent);
transform: none;
}
.note-title-compact {
font-size: 0.9rem;
font-weight: 500;
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.note-tags-compact {
display: flex;
gap: 0.3rem;
flex-shrink: 0;
}
.timestamp-compact {
font-size: 0.72rem;
color: var(--fs-text-tertiary);
flex-shrink: 0;
white-space: nowrap;
}
/* Full layout */
.note-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 0.25rem;
}
.note-title {
margin: 0;
font-size: 1.1rem;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.btn-edit {
flex-shrink: 0;
padding: 0.25rem 0.6rem;
font-size: 0.8rem;
background: var(--fs-surface-raised);
color: var(--fs-text-secondary);
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-sm);
cursor: pointer;
transition: color 0.15s, border-color 0.15s;
}
.btn-edit:hover {
color: var(--fs-accent);
border-color: var(--fs-accent);
}
.note-preview {
margin: 0 0 0.5rem;
color: var(--fs-text-secondary);
font-size: 0.9rem;
max-height: 7.5em;
overflow: hidden;
position: relative;
-webkit-mask-image: linear-gradient(to bottom, black 60%, transparent 100%);
mask-image: linear-gradient(to bottom, black 60%, transparent 100%);
}
.note-meta {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.timestamp {
margin-left: auto;
font-size: 0.75rem;
color: var(--fs-text-tertiary);
}
</style>
@@ -0,0 +1,278 @@
<script setup lang="ts">
/**
* Restore: put the whole instance back to a full backup.
*
* Choose a backup (one at the backup destination, or a file from this
* computer), see what it would change, type the confirmation, run it. On a
* live instance this is a rollback to the instance's own earlier backup; on a
* new, empty one it takes the backup in. Either way the server backs up the
* current state first and signs everyone out afterwards.
*/
import { computed, onMounted, ref } from "vue";
import { apiErrorMessage } from "@/api/client";
import {
backupTakenAt, listRestoreSources, previewRestore, restoreBackup,
type RestoreFrom, type RestorePreview, type RestoreResult, type StoredBackup,
} from "@/api/backups";
import { formatBytes } from "@/utils/bytes";
const emit = defineEmits<{ close: [] }>();
const CONFIRM_WORDS = "roll back";
type Step = "choose" | "checking" | "preview" | "running" | "done";
const step = ref<Step>("choose");
const sources = ref<StoredBackup[]>([]);
const sourcesError = ref("");
const sourcesLoading = ref(true);
const chosen = ref<RestoreFrom | null>(null);
const chosenLabel = ref("");
const preview = ref<RestorePreview | null>(null);
const result = ref<RestoreResult | null>(null);
const error = ref("");
const typed = ref("");
const fileInput = ref<HTMLInputElement | null>(null);
const confirmed = computed(() => typed.value.trim().toLowerCase() === CONFIRM_WORDS);
function when(value: Date | string | null | undefined): string {
if (!value) return "an unknown date";
const date = typeof value === "string" ? new Date(value) : value;
return Number.isNaN(date.getTime()) ? "an unknown date" : date.toLocaleString();
}
onMounted(async () => {
try {
const answer = await listRestoreSources();
sources.value = answer.backups;
sourcesError.value = answer.error ?? "";
} catch (e) {
sourcesError.value = apiErrorMessage(e, "Could not list the backups at the destination.");
} finally {
sourcesLoading.value = false;
}
});
async function check(from: RestoreFrom, label: string) {
chosen.value = from;
chosenLabel.value = label;
error.value = "";
typed.value = "";
step.value = "checking";
try {
preview.value = await previewRestore(from);
step.value = "preview";
} catch (e) {
error.value = apiErrorMessage(e, "That backup could not be read.");
step.value = "choose";
}
}
function pickFile(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0];
if (fileInput.value) fileInput.value.value = "";
if (file) check({ file }, file.name);
}
async function run() {
if (!chosen.value || !confirmed.value) return;
error.value = "";
step.value = "running";
try {
result.value = await restoreBackup(chosen.value);
step.value = "done";
} catch (e) {
error.value = apiErrorMessage(e, "The restore failed. Nothing was changed.");
step.value = "preview";
}
}
function finish() {
// Every session ended with the restore, this one included.
window.location.assign("/login");
}
</script>
<template>
<teleport to="body">
<div class="modal-overlay" @click="step === 'running' || step === 'done' ? null : emit('close')">
<div class="modal-card restore-card" @click.stop>
<template v-if="step === 'choose' || step === 'checking'">
<h3 class="modal-title">Restore from a backup</h3>
<p class="modal-message">
Puts the whole instance back to the moment the backup was taken, for every user.
You'll see what changes before anything happens.
</p>
<p v-if="error" class="restore-error" role="alert">{{ error }}</p>
<h4 class="restore-subhead">At the backup destination</h4>
<p v-if="sourcesLoading" class="restore-muted">Looking for backups…</p>
<p v-else-if="sourcesError" class="restore-muted">{{ sourcesError }}</p>
<p v-else-if="!sources.length" class="restore-muted">No backups there yet.</p>
<ul v-else class="restore-sources">
<li v-for="b in sources" :key="b.name">
<button
class="restore-source"
:disabled="step === 'checking'"
@click="check({ source: b.name }, when(backupTakenAt(b.name)))"
>
<span>{{ when(backupTakenAt(b.name)) }}</span>
<span class="restore-muted">{{ formatBytes(b.size_bytes) }}</span>
</button>
</li>
</ul>
<h4 class="restore-subhead">From this computer</h4>
<p class="restore-muted">
A backup file (.tar) or the Full Backup download (.json). Uploads are size-limited;
a large file restores from the destination above, or with
<code>python -m grimoire.restore</code>.
</p>
<div class="modal-actions restore-actions-left">
<button class="modal-btn" :disabled="step === 'checking'" @click="fileInput?.click()">
Choose a file…
</button>
<input ref="fileInput" type="file" accept=".json,.tar" class="hidden-file-input" @change="pickFile" />
</div>
<p v-if="step === 'checking'" class="restore-muted">Reading {{ chosenLabel }}…</p>
<div class="modal-actions">
<button class="modal-btn" @click="emit('close')">Cancel</button>
</div>
</template>
<template v-else-if="(step === 'preview' || step === 'running') && preview">
<h3 class="modal-title">
{{ preview.mode === "rollback" ? "Roll back to this backup?" : "Restore this backup?" }}
</h3>
<p class="modal-message">
<template v-if="preview.mode === 'rollback'">
Everything goes back to {{ when(preview.exported_at) }}, for every user. Anything made
since is removed, edits since are undone, and records deleted since come back.
</template>
<template v-else>
This instance has no records yet, so it takes the backup from {{ when(preview.exported_at) }} as it is.
</template>
The current state is backed up first, and everyone is signed out afterwards.
</p>
<table class="restore-counts">
<thead><tr><th></th><th>Now</th><th>After</th></tr></thead>
<tbody>
<tr v-for="c in preview.counts" :key="c.kind">
<td>{{ c.kind }}</td><td>{{ c.now }}</td><td>{{ c.after }}</td>
</tr>
</tbody>
</table>
<p v-if="error" class="restore-error" role="alert">{{ error }}</p>
<label class="restore-confirm">
Type <strong>{{ CONFIRM_WORDS }}</strong> to continue
<input v-model="typed" class="fs-input input" :disabled="step === 'running'" autocomplete="off" />
</label>
<div class="modal-actions">
<button class="modal-btn" :disabled="step === 'running'" @click="step = 'choose'">Back</button>
<button
class="modal-btn modal-btn-danger"
:disabled="!confirmed || step === 'running'"
@click="run"
>{{ step === "running" ? "Restoring…" : preview.mode === "rollback" ? "Roll back" : "Restore" }}</button>
</div>
</template>
<template v-else-if="step === 'done' && result">
<h3 class="modal-title">Restored</h3>
<p class="modal-message">
The instance is back to {{ when(result.exported_at) }}.
The state it replaced was saved as <code>{{ result.safety_backup.file }}</code>
in {{ result.safety_backup.where }}.
<template v-if="result.safety_backup.note"> {{ result.safety_backup.note }}</template>
Search is being rebuilt in the background. Everyone has been signed out, so sign in again.
</p>
<div class="modal-actions">
<button class="modal-btn modal-btn-primary" @click="finish">Sign in again</button>
</div>
</template>
</div>
</div>
</teleport>
</template>
<style scoped>
.restore-card {
max-width: 34rem;
max-height: 85vh;
overflow-y: auto;
}
.restore-subhead {
margin: 1rem 0 0.4rem;
font-size: 0.9rem;
}
.restore-muted {
font-size: 0.85rem;
color: var(--fs-text-secondary);
margin: 0 0 0.5rem;
}
.restore-error {
font-size: 0.85rem;
color: var(--fs-action-destructive);
margin: 0 0 0.75rem;
}
.restore-sources {
list-style: none;
margin: 0 0 0.5rem;
padding: 0;
max-height: 14rem;
overflow-y: auto;
border: 1px solid var(--fs-border-color);
border-radius: var(--fs-radius-sm);
}
.restore-source {
display: flex;
justify-content: space-between;
width: 100%;
padding: 0.45rem 0.7rem;
border: none;
border-bottom: 1px solid var(--fs-border-color);
background: none;
color: var(--fs-text-primary);
font: inherit;
font-size: 0.875rem;
text-align: left;
cursor: pointer;
}
.restore-sources li:last-child .restore-source {
border-bottom: none;
}
.restore-source:hover:not(:disabled) {
background: var(--fs-surface-hover);
}
.restore-actions-left {
justify-content: flex-start;
margin-bottom: 1rem;
}
.restore-counts {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
margin: 0 0 1rem;
}
.restore-counts th,
.restore-counts td {
text-align: right;
padding: 0.25rem 0.5rem;
border-bottom: 1px solid var(--fs-border-color);
}
.restore-counts th:first-child,
.restore-counts td:first-child {
text-align: left;
}
.hidden-file-input {
display: none;
}
.restore-confirm {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-size: 0.875rem;
margin: 0 0 1rem;
}
</style>
@@ -0,0 +1,309 @@
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { apiGet, apiPut, apiErrorMessage } from "@/api/client";
import { useToastStore } from "@/stores/toast";
/**
* How many reverse proxies stand in front of Grimoire, checked against the
* admin's own request.
*
* Each proxy appends to X-Forwarded-For, and Grimoire reads the entry this many
* in from the right as the visitor's address. Every sign-in rate limit and
* audit line keys on that address, and the scheme read the same way decides
* whether the session cookie is Secure. Too low a count makes every visitor
* read as the proxy, so they share one rate limit and one bad sign-in run
* blocks everyone. Behind Cloudflare's proxied DNS the usual count is 2.
*/
interface ReadoutRow { hops: number; client: string; https: boolean }
interface Readout {
peer: string;
forwarded_for: string[];
forwarded_proto: string[];
cloudflare: boolean;
cloudflare_client: string | null;
rows: ReadoutRow[];
suggested: number | null;
}
interface ProxyConfig {
hops: number;
source: "setting" | "env" | "default";
env_hops: number;
max_hops: number;
readout: Readout;
}
const toast = useToastStore();
const config = ref<ProxyConfig | null>(null);
const loadError = ref("");
const draft = ref<number>(1);
const saving = ref(false);
const saved = ref(false);
async function load() {
loadError.value = "";
try {
config.value = await apiGet<ProxyConfig>("/api/admin/proxy");
draft.value = config.value.hops;
} catch (e) {
loadError.value = apiErrorMessage(e, "The proxy settings could not be loaded.");
}
}
async function save(hops: number | null) {
saving.value = true;
saved.value = false;
try {
config.value = await apiPut<ProxyConfig>("/api/admin/proxy", { hops });
draft.value = config.value.hops;
saved.value = true;
setTimeout(() => (saved.value = false), 2000);
} catch (e) {
toast.show(apiErrorMessage(e, "Failed to save the proxy count"), "error");
} finally {
saving.value = false;
}
}
const readout = computed(() => config.value?.readout ?? null);
const inForce = computed(() => readout.value?.rows.find((r) => r.hops === config.value?.hops) ?? null);
// The verdict that leads the section. A Cloudflare request names the count to
// set, since Cloudflare reports the visitor's address; any other road can only
// show the address read and let the admin judge whether it is theirs.
const verdict = computed<"set-suggested" | "cloudflare-unmatched" | "check" | null>(() => {
const r = readout.value;
if (!r || !config.value) return null;
if (r.cloudflare && r.suggested !== null && r.suggested !== config.value.hops) return "set-suggested";
if (r.cloudflare && r.suggested === null) return "cloudflare-unmatched";
return "check";
});
const sourceLabel = computed(() => {
const c = config.value;
if (!c) return "";
if (c.source === "setting") return "Saved here.";
if (c.source === "env") return `From TRUSTED_PROXY_HOPS in the environment (${c.env_hops}).`;
return "The default.";
});
const draftValid = computed(() =>
Number.isInteger(draft.value) && draft.value >= 0 && draft.value <= (config.value?.max_hops ?? 5),
);
onMounted(load);
</script>
<template>
<div class="proxy-settings">
<p v-if="loadError" class="error-msg">
{{ loadError }}
<button type="button" class="btn-ghost btn-compact" @click="load">Try again</button>
</p>
<p v-else-if="!config" class="state-msg">Reading this request&hellip;</p>
<template v-else-if="readout">
<div v-if="verdict === 'set-suggested'" class="proxy-warning" role="alert">
<p class="proxy-warning-title">Set the proxy count to {{ readout.suggested }}</p>
<p class="proxy-warning-body">
This request came through Cloudflare, which reports your address as
<code>{{ readout.cloudflare_client }}</code>. At {{ config.hops }}, Grimoire reads
<code>{{ inForce?.client }}</code> instead, so visitors share Cloudflare's addresses
and one sign-in limit.
</p>
<button type="button" class="btn-primary" :disabled="saving" @click="save(readout.suggested)">
Use {{ readout.suggested }}
</button>
</div>
<div v-else-if="verdict === 'cloudflare-unmatched'" class="proxy-warning" role="alert">
<p class="proxy-warning-title">This request came through Cloudflare</p>
<p class="proxy-warning-body">
No count reads the address Cloudflare reports for you. Check the forwarding chain below,
and that your own proxy passes Cloudflare's <code>X-Forwarded-For</code> on.
</p>
</div>
<p v-else class="proxy-verdict">
Grimoire reads this request as coming from <code>{{ inForce?.client || "an unknown address" }}</code>
<template v-if="inForce?.https"> over HTTPS</template>. If that is your address, the count
is right. If it is your proxy's, raise the count.
</p>
<div class="field proxy-field">
<label for="proxy-hops">Proxies in front of Grimoire</label>
<div class="proxy-input-row">
<input
id="proxy-hops"
v-model.number="draft"
type="number"
min="0"
:max="config.max_hops"
step="1"
class="fs-input input proxy-hops-input"
/>
<button
type="button"
class="btn-primary"
:disabled="saving || !draftValid || draft === config.hops"
@click="save(draft)"
>
{{ saving ? "Saving..." : "Save" }}
</button>
<button
v-if="config.source === 'setting'"
type="button"
class="btn-ghost"
:disabled="saving"
@click="save(null)"
>
Use the environment's ({{ config.env_hops }})
</button>
<span v-if="saved" class="saved-msg">Saved. It applies to the next request.</span>
</div>
<p class="field-hint">
{{ sourceLabel }} One proxy (Traefik, Nginx, Caddy) is 1. Cloudflare in front of your own
proxy is 2. 0 ignores the forwarding headers and uses the connecting address.
</p>
</div>
<table class="proxy-table">
<caption>What each count makes of this request</caption>
<thead>
<tr><th class="num">Count</th><th>Reads you as</th><th>HTTPS</th><th></th></tr>
</thead>
<tbody>
<tr
v-for="row in readout.rows"
:key="row.hops"
:class="{ 'proxy-row-current': row.hops === config.hops }"
>
<td class="num">{{ row.hops }}</td>
<td><code>{{ row.client || "unknown" }}</code></td>
<td>{{ row.https ? "yes" : "no" }}</td>
<td class="proxy-row-tags">
<span v-if="row.hops === config.hops" class="proxy-tag">in force</span>
<span v-if="row.hops === readout.suggested && row.hops !== config.hops" class="proxy-tag proxy-tag-suggested">
suggested
</span>
</td>
</tr>
</tbody>
</table>
<dl class="proxy-chain">
<dt>Connecting address</dt>
<dd><code>{{ readout.peer || "unknown" }}</code></dd>
<dt>X-Forwarded-For</dt>
<dd v-if="readout.forwarded_for.length"><code>{{ readout.forwarded_for.join(", ") }}</code></dd>
<dd v-else class="proxy-absent">not sent</dd>
<dt>X-Forwarded-Proto</dt>
<dd v-if="readout.forwarded_proto.length"><code>{{ readout.forwarded_proto.join(", ") }}</code></dd>
<dd v-else class="proxy-absent">not sent</dd>
</dl>
</template>
</div>
</template>
<style scoped>
.proxy-warning {
margin-bottom: var(--fs-space-4);
padding: var(--fs-space-3);
border: 1px solid var(--fs-warning);
border-radius: var(--fs-radius-md);
background: color-mix(in srgb, var(--fs-warning) 12%, var(--fs-surface-raised));
}
.proxy-warning-title {
margin: 0 0 var(--fs-space-2);
font-weight: 600;
color: var(--fs-warning-fg);
}
.proxy-warning-body {
margin: 0 0 var(--fs-space-3);
font-size: var(--fs-size-body-sm);
color: var(--fs-text-primary);
}
.proxy-verdict {
margin: 0 0 var(--fs-space-4);
font-size: var(--fs-size-body-sm);
color: var(--fs-text-primary);
}
.proxy-field {
margin-bottom: var(--fs-space-4);
}
.proxy-input-row {
display: flex;
align-items: center;
gap: var(--fs-space-3);
flex-wrap: wrap;
}
.proxy-hops-input {
width: 5rem;
}
.proxy-table {
width: 100%;
max-width: 560px;
border-collapse: collapse;
font-size: var(--fs-size-body-sm);
margin-bottom: var(--fs-space-4);
}
.proxy-table caption {
text-align: left;
font-size: var(--fs-size-label);
color: var(--fs-text-secondary);
margin-bottom: var(--fs-space-2);
}
.proxy-table th,
.proxy-table td {
text-align: left;
padding: var(--fs-space-1) var(--fs-space-3);
border-bottom: 1px solid var(--fs-border-color);
}
.proxy-table th {
font-size: var(--fs-size-tiny);
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--fs-text-tertiary);
font-weight: 500;
}
.proxy-table .num {
text-align: right;
font-variant-numeric: tabular-nums;
width: 4rem;
}
.proxy-row-current td {
background: var(--fs-surface-hover);
font-weight: 600;
}
.proxy-row-tags {
white-space: nowrap;
}
.proxy-tag {
display: inline-block;
padding: 0 var(--fs-space-2);
border-radius: var(--fs-radius-pill);
font-size: var(--fs-size-tiny);
font-weight: 500;
color: var(--fs-text-secondary);
border: 1px solid var(--fs-border-active);
}
.proxy-tag-suggested {
color: var(--fs-warning-fg);
border-color: var(--fs-warning);
}
.proxy-chain {
display: grid;
grid-template-columns: max-content 1fr;
gap: var(--fs-space-1) var(--fs-space-4);
margin: 0;
font-size: var(--fs-size-body-sm);
}
.proxy-chain dt {
color: var(--fs-text-secondary);
}
.proxy-chain dd {
margin: 0;
overflow-wrap: anywhere;
}
.proxy-absent {
font-style: italic;
color: var(--fs-text-tertiary);
}
</style>
+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" />
@@ -0,0 +1,96 @@
<script setup lang="ts">
/**
* The end of a server-paged list: asks for the next page as the reader nears
* it, in place of a "Load more" button. The parent keeps the paging — what the
* next page is keyed on, whether one is in flight, whether the last one
* failed — and this owns the observing.
*
* <ScrollSentinel :cursor="more ? String(rows.length) : ''"
* :loading="loadingMore" :failed="moreFailed" @more="loadMore" />
*
* An empty cursor means the list is complete, and nothing renders.
*/
import { onBeforeUnmount, ref, watch } from "vue";
const props = defineProps<{ cursor: string; loading: boolean; failed?: boolean }>();
const emit = defineEmits<{ more: [] }>();
const sentinel = ref<HTMLElement | null>(null);
const visible = ref(false);
// One request per page. The observer reports every crossing, and a short last
// page leaves the sentinel on screen for good, so the cursor last asked for is
// remembered: a page is asked for once, and a failed one is not retried on
// every scroll, because a failure leaves the cursor where it was. Only
// Try again asks for it again.
let asked = "";
function pump() {
if (!visible.value || props.loading || props.failed || !props.cursor) return;
if (props.cursor === asked) return;
asked = props.cursor;
emit("more");
}
function retry() {
asked = props.cursor;
emit("more");
}
let observer: IntersectionObserver | undefined;
function observe(el: HTMLElement | null) {
observer?.disconnect();
observer = undefined;
if (!el) {
// Visibility and the cursor asked for go with the element. A list that
// starts over must not inherit "the end is on screen" from the one it
// replaced, and an offset cursor repeats from list to list, so "50" asked
// of the old list must not stop the new one asking for its own "50".
visible.value = false;
asked = "";
return;
}
observer = new IntersectionObserver(
(entries) => {
visible.value = entries.some((e) => e.isIntersecting);
pump();
},
// Extends the watched area a screen below the viewport, so the next page is
// asked for before the reader reaches the end rather than when they do.
{ rootMargin: "0px 0px 100% 0px" },
);
observer.observe(el);
}
// flush: "post": the template ref is only set once the DOM is patched.
watch(sentinel, observe, { flush: "post" });
// A page that lands without pushing the end off screen gives the observer
// nothing new to report, so carry on from the props, or the list stops early.
watch([() => props.cursor, () => props.loading, () => props.failed], pump);
onBeforeUnmount(() => observer?.disconnect());
</script>
<template>
<div v-if="cursor" class="sentinel">
<!-- The one case with a button: an observer re-firing on a failure would be
a request loop. -->
<p v-if="failed" class="sentinel-note sentinel-failed" role="alert">
Couldn’t load more.
<button type="button" class="btn-secondary btn-sm" @click="retry">Try again</button>
</p>
<template v-else>
<div ref="sentinel" class="sentinel-mark" aria-hidden="true"></div>
<p v-if="loading" class="sentinel-note" role="status">Loading more…</p>
</template>
</div>
</template>
<style scoped>
.sentinel { grid-column: 1 / -1; padding: 0.75rem 0; text-align: center; }
.sentinel-mark { height: 1px; }
.sentinel-note { margin: 0; font-size: 0.8rem; color: var(--fs-text-tertiary); }
.sentinel-failed { display: flex; align-items: center; justify-content: center; gap: 0.75rem; }
</style>
+2 -1
View File
@@ -2,6 +2,7 @@
import { ref, onMounted } from "vue"; import { ref, onMounted } from "vue";
import { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client"; import { apiGet, apiPost, apiPatch, apiDelete } from "@/api/client";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import type { TaskLog } from "@/types/task"; import type { TaskLog } from "@/types/task";
import { fmtStamp } from "@/utils/dateFormat"; import { fmtStamp } from "@/utils/dateFormat";
@@ -131,7 +132,7 @@ onMounted(loadLogs);
<button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">&times;</button> <button class="btn-text" aria-label="Delete log entry" @click="deleteLog(log)">&times;</button>
</div> </div>
</div> </div>
<div class="log-content prose" v-html="renderMarkdown(log.content)"></div> <div class="log-content prose" v-html="renderMarkdown(log.content)" v-record-refs></div>
</template> </template>
</div> </div>
+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" />
@@ -1,683 +0,0 @@
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue";
import type { Editor } from "@tiptap/vue-3";
import { apiGet, apiPatch, apiPost, apiDelete } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import { useAutoSave } from "@/composables/useAutoSave";
import { useTagSuggestions } from "@/composables/useTagSuggestions";
import { useNotesStore } from "@/stores/notes";
import TiptapEditor from "@/components/TiptapEditor.vue";
import TagInput from "@/components/TagInput.vue";
import MarkdownToolbar from "@/components/MarkdownToolbar.vue";
import WordCount from "@/components/WordCount.vue";
import { Trash2, X } from "lucide-vue-next";
import { relativeTimeOrDate } from "@/composables/useRelativeTime";
const props = defineProps<{
projectId: number;
activeNoteId: number | null;
}>();
const emit = defineEmits<{ "note-loaded": [id: number] }>();
interface NoteItem {
id: number;
title: string;
tags: string[];
updated_at: string;
}
const toast = useToastStore();
const notesStore = useNotesStore();
// List state
const projectNotes = ref<NoteItem[]>([]);
const listLoading = ref(false);
const deletingId = ref<number | null>(null);
const pendingDelete = ref<number | null>(null);
const searchQuery = ref("");
const filteredNotes = computed(() => {
const q = searchQuery.value.trim().toLowerCase();
if (!q) return projectNotes.value;
return projectNotes.value.filter(
(n) => n.title.toLowerCase().includes(q) || n.tags?.some((t) => t.toLowerCase().includes(q))
);
});
function matchedTags(note: NoteItem): string[] {
const q = searchQuery.value.trim().toLowerCase();
if (!q) return [];
return (note.tags ?? []).filter(
(t) => t.toLowerCase().includes(q) && !note.title.toLowerCase().includes(q)
);
}
// Editor state
const editingId = ref<number | null>(null);
const noteTitle = ref("");
const noteBody = ref("");
const noteTags = ref<string[]>([]);
const dirty = ref(false);
const saving = ref(false);
const tagSuggestions = useTagSuggestions(noteTitle, noteBody, noteTags, () => { dirty.value = true; });
// New note inline creation
const showNewNoteInput = ref(false);
const newNoteTitle = ref("");
const creatingNote = ref(false);
const newNoteTitleRef = ref<HTMLInputElement | null>(null);
function _noteKey(pid: number) { return `workspace_note_${pid}`; }
async function startNewNote() {
showNewNoteInput.value = true;
newNoteTitle.value = "";
await nextTick();
newNoteTitleRef.value?.focus();
}
function cancelNewNote() {
showNewNoteInput.value = false;
newNoteTitle.value = "";
}
async function createNote() {
const title = newNoteTitle.value.trim();
if (!title || creatingNote.value) return;
creatingNote.value = true;
try {
const note = await apiPost<{ id: number; title: string; body: string; tags: string[]; updated_at: string }>(
"/api/notes",
{ title, project_id: props.projectId, body: "", is_task: false }
);
showNewNoteInput.value = false;
newNoteTitle.value = "";
await loadProjectNotes();
await openNote(note.id);
} catch {
toast.show("Failed to create note", "error");
} finally {
creatingNote.value = false;
}
}
// TipTap editor ref
const titleRef = ref<HTMLInputElement | null>(null);
const editorRef = ref<InstanceType<typeof TiptapEditor> | null>(null);
const tiptapEditor = computed<Editor | null>(() =>
(editorRef.value?.editor as Editor | undefined) ?? null
);
// Link suggestions
interface LinkSuggestion { note_id: number; title: string; count: number; }
const linkSuggestions = ref<LinkSuggestion[]>([]);
let linkCheckTimer: ReturnType<typeof setTimeout> | null = null;
async function fetchLinkSuggestions() {
if (!editingId.value || !noteBody.value) { linkSuggestions.value = []; return; }
try {
const res = await apiPost<{ suggestions: LinkSuggestion[] }>('/api/notes/link-suggestions', {
body: noteBody.value,
project_id: props.projectId,
exclude_note_id: editingId.value,
});
linkSuggestions.value = res.suggestions;
} catch {
linkSuggestions.value = [];
}
}
function scheduleLinkCheck() {
if (linkCheckTimer) clearTimeout(linkCheckTimer);
linkCheckTimer = setTimeout(fetchLinkSuggestions, 2500);
}
function applyWikilinkToText(text: string, title: string): string {
const escaped = title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const parts = text.split(/(\[\[[^\]]*\]\])/);
const pattern = new RegExp(`\\b${escaped}\\b`, 'gi');
return parts.map((part, i) =>
i % 2 === 0 ? part.replace(pattern, `[[${title}]]`) : part
).join('');
}
function applyLink(s: LinkSuggestion) {
noteBody.value = applyWikilinkToText(noteBody.value, s.title);
dirty.value = true;
linkSuggestions.value = linkSuggestions.value.filter(x => x.note_id !== s.note_id);
}
function applyAllLinks() {
let text = noteBody.value;
for (const s of linkSuggestions.value) text = applyWikilinkToText(text, s.title);
noteBody.value = text;
dirty.value = true;
linkSuggestions.value = [];
}
async function loadProjectNotes() {
listLoading.value = true;
try {
const data = await apiGet<{ notes: NoteItem[] }>(
`/api/projects/${props.projectId}/notes?type=note&limit=200`
);
projectNotes.value = data.notes ?? [];
} catch {
toast.show("Failed to load notes", "error");
} finally {
listLoading.value = false;
}
}
async function openNote(id: number) {
try {
const note = await apiGet<{ id: number; title: string; body: string; tags: string[]; updated_at: string }>(
`/api/notes/${id}`
);
editingId.value = note.id;
noteTitle.value = note.title;
noteBody.value = note.body ?? "";
noteTags.value = note.tags ?? [];
dirty.value = false;
tagSuggestions.dismissTagSuggestions();
linkSuggestions.value = [];
localStorage.setItem(_noteKey(props.projectId), String(id));
fetchLinkSuggestions();
emit("note-loaded", note.id);
} catch {
toast.show("Failed to load note", "error");
}
}
async function saveNote() {
if (!editingId.value) return;
saving.value = true;
try {
await apiPatch(`/api/notes/${editingId.value}`, {
title: noteTitle.value,
body: noteBody.value,
tags: noteTags.value,
});
dirty.value = false;
const idx = projectNotes.value.findIndex((n) => n.id === editingId.value);
if (idx !== -1) {
projectNotes.value[idx] = {
...projectNotes.value[idx],
title: noteTitle.value,
tags: noteTags.value,
updated_at: new Date().toISOString(),
};
projectNotes.value.sort((a, b) =>
new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime()
);
}
} catch {
toast.show("Failed to save note", "error");
} finally {
saving.value = false;
}
}
function requestDelete(id: number, e: Event) {
e.stopPropagation();
if (deletingId.value === id) {
confirmDelete(id);
} else {
deletingId.value = id;
}
}
function cancelDelete(e: Event) {
e.stopPropagation();
deletingId.value = null;
}
async function confirmDelete(id: number) {
pendingDelete.value = id;
try {
await apiDelete(`/api/notes/${id}`);
projectNotes.value = projectNotes.value.filter((n) => n.id !== id);
if (editingId.value === id) {
editingId.value = null;
noteTitle.value = "";
noteBody.value = "";
localStorage.removeItem(_noteKey(props.projectId));
}
} catch {
toast.show("Failed to delete note", "error");
} finally {
pendingDelete.value = null;
deletingId.value = null;
}
}
watch(noteTitle, () => { dirty.value = true; });
watch(noteBody, () => { dirty.value = true; if (editingId.value) scheduleLinkCheck(); });
watch(noteTags, () => { dirty.value = true; });
watch(
() => props.activeNoteId,
async (id) => {
if (id) {
await openNote(id);
await loadProjectNotes();
}
}
);
useAutoSave(dirty, saving, saveNote, 60_000);
onMounted(async () => {
await loadProjectNotes();
const stored = localStorage.getItem(_noteKey(props.projectId));
if (stored) {
const id = Number(stored);
if (projectNotes.value.find((n) => n.id === id)) {
openNote(id).catch(() => {});
}
}
});
onUnmounted(() => { if (linkCheckTimer) clearTimeout(linkCheckTimer); });
defineExpose({ reload: loadProjectNotes });
</script>
<template>
<div class="ws-note-editor">
<!-- Left rail: always-visible note list -->
<div class="note-rail">
<div class="rail-header">
<template v-if="showNewNoteInput">
<input
ref="newNoteTitleRef"
v-model="newNoteTitle"
class="new-note-input"
placeholder="Note title..."
:disabled="creatingNote"
@keydown.enter="createNote"
@keydown.escape="cancelNewNote"
/>
<button class="btn-primary btn-inline" :disabled="creatingNote || !newNoteTitle.trim()" @click="createNote">
{{ creatingNote ? '…' : '+' }}
</button>
<button class="btn-text" aria-label="Cancel new note" @click="cancelNewNote"><X :size="16" /></button>
</template>
<template v-else>
<span class="rail-title">Notes</span>
<button class="btn-ghost btn-inline" @click="startNewNote" title="New note">+ New</button>
</template>
</div>
<div class="rail-search">
<input
v-model="searchQuery"
class="rail-search-input"
placeholder="Search…"
type="search"
aria-label="Search notes"
/>
<button v-if="searchQuery" class="btn-text btn-search-clear" aria-label="Clear search" @click="searchQuery = ''"><X :size="16" /></button>
</div>
<div v-if="listLoading" class="rail-state">Loading…</div>
<ul v-else class="note-list">
<li
v-for="note in filteredNotes"
:key="note.id"
:class="['note-row', { active: editingId === note.id }]"
@click="openNote(note.id)"
>
<div class="note-row-main">
<span class="note-row-title">{{ note.title || 'Untitled' }}</span>
<span class="note-row-age">{{ relativeTimeOrDate(note.updated_at) }}</span>
</div>
<div v-if="note.tags?.length" class="note-row-tags">
<span
v-for="tag in note.tags.slice(0, 2)"
:key="tag"
:class="['note-tag-pill', { 'tag-match': matchedTags(note).includes(tag) }]"
>#{{ tag }}</span>
<span v-if="note.tags.length > 2" class="note-tag-more">+{{ note.tags.length - 2 }}</span>
</div>
<div class="note-row-actions" @click.stop>
<template v-if="deletingId === note.id">
<button class="btn-danger-outline btn-inline" :disabled="pendingDelete === note.id" @click="requestDelete(note.id, $event)">
{{ pendingDelete === note.id ? '…' : 'Delete?' }}
</button>
<button class="btn-text" aria-label="Cancel delete" @click="cancelDelete($event)"><X :size="16" /></button>
</template>
<button v-else class="btn-text" title="Delete note" @click="requestDelete(note.id, $event)">
<Trash2 :size="16" />
</button>
</div>
</li>
<li v-if="filteredNotes.length === 0" class="rail-state">
{{ searchQuery.trim() ? 'No matches.' : 'No notes yet.' }}
</li>
</ul>
</div>
<!-- Right pane: editor -->
<div class="note-editor-pane">
<template v-if="editingId">
<div class="panel-header">
<div class="editor-header-right">
<WordCount :body="noteBody" />
<span v-if="dirty && !saving" class="unsaved">Unsaved</span>
<span v-if="saving" class="saving-txt">Saving…</span>
<button class="btn-primary btn-compact" :disabled="saving || !dirty" @click="saveNote">Save</button>
</div>
</div>
<div class="note-title-row">
<input
ref="titleRef"
v-model="noteTitle"
class="note-title-input"
placeholder="Note title"
@keydown.ctrl.s.prevent="saveNote"
@keydown.ctrl.e.prevent="editorRef?.editor?.commands.focus()"
/>
</div>
<div class="tag-row">
<TagInput v-model="noteTags" :fetchTags="(q: string) => notesStore.fetchAllTags(q)" />
<button
class="btn-ghost btn-compact"
:disabled="tagSuggestions.suggestingTags.value"
title="Auto-suggest tags from title and body"
@click="tagSuggestions.fetchTagSuggestions()"
>
{{ tagSuggestions.suggestingTags.value ? '…' : 'Suggest' }}
</button>
</div>
<div v-if="tagSuggestions.suggestedTags.value.length" class="tag-suggestions">
<span class="tag-suggestions-label">Suggested:</span>
<button
v-for="tag in tagSuggestions.suggestedTags.value"
:key="tag"
:class="['btn-tag-suggestion', { applied: tagSuggestions.appliedTags.value.has(tag) }]"
@click="tagSuggestions.applyTagSuggestion(tag)"
>#{{ tag }}{{ tagSuggestions.appliedTags.value.has(tag) ? ' ✓' : '' }}</button>
<button class="btn-text" aria-label="Dismiss tag suggestions" @click="tagSuggestions.dismissTagSuggestions()"><X :size="16" /></button>
</div>
<div class="toolbar-row">
<MarkdownToolbar :editor="tiptapEditor" />
</div>
<div v-if="linkSuggestions.length" class="link-suggest-strip">
<span class="link-suggest-label">Links:</span>
<span v-for="s in linkSuggestions" :key="s.note_id" class="link-suggest-chip" :title="`Appears ${s.count}× unlinked`">
<button class="btn-chip-link" @click="applyLink(s)">[[{{ s.title }}]]</button>
</span>
<button class="btn-ghost btn-inline" @click="applyAllLinks" title="Link all suggestions">All</button>
<button class="btn-text" aria-label="Dismiss link suggestions" @click="linkSuggestions = []"><X :size="16" /></button>
</div>
<div class="editor-area" @keydown.ctrl.s.prevent="saveNote" @keydown.ctrl.e.prevent="editorRef?.editor?.commands.focus()">
<TiptapEditor ref="editorRef" v-model="noteBody" @escape="titleRef?.focus()" />
</div>
</template>
<div v-else class="editor-empty-state">
<p>Select a note or create a new one</p>
</div>
</div>
</div>
</template>
<style scoped>
.ws-note-editor {
display: flex;
flex-direction: row;
height: 100%;
overflow: hidden;
background: var(--fs-surface-hover);
border-left: 1px solid var(--fs-border-color);
}
/* ── Left rail ── */
.note-rail {
width: 200px;
flex-shrink: 0;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--fs-surface-raised);
}
.rail-header {
display: flex;
align-items: center;
gap: 0.3rem;
padding: 0.5rem 0.6rem;
border-bottom: 1px solid var(--fs-border-color);
flex-shrink: 0;
}
.rail-title {
color: var(--fs-text-tertiary);
text-transform: uppercase;
letter-spacing: 0.04em;
font-size: 0.72rem;
font-weight: 500;
flex: 1;
}
.rail-search-input {
flex: 1;
background: transparent;
border: none;
font-size: 0.78rem;
color: var(--fs-text-primary);
min-width: 0;
padding: 0;
}
.rail-search-input:focus { outline: none; }
.rail-search-input::-webkit-search-cancel-button { display: none; }
/* Sits inside the search field: no padding, and must not flex. */
.btn-search-clear { padding: 0; flex-shrink: 0; }
.rail-state {
padding: 1rem 0.65rem;
font-size: 0.78rem;
color: var(--fs-text-tertiary);
}
/* Note list */
.note-list {
list-style: none;
margin: 0;
padding: 0;
overflow-y: auto;
flex: 1;
}
.note-row {
display: flex;
flex-direction: column;
padding: 0.4rem 0.6rem;
border-bottom: 1px solid color-mix(in srgb, var(--fs-border-color) 60%, transparent);
cursor: pointer;
gap: 0.15rem;
border-right: 2px solid transparent;
transition: background 0.12s;
}
.note-row:hover { background: color-mix(in srgb, var(--fs-accent) 5%, var(--fs-surface-hover)); }
.note-row.active {
background: color-mix(in srgb, var(--fs-accent) 8%, var(--fs-surface-hover));
border-right-color: var(--fs-accent);
}
.note-row-main {
display: flex;
align-items: baseline;
gap: 0.25rem;
}
.note-row-title {
flex: 1;
font-size: 0.78rem;
font-weight: 500;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fs-text-primary);
}
.note-row-age {
font-size: 0.62rem;
color: var(--fs-text-tertiary);
white-space: nowrap;
flex-shrink: 0;
}
.note-row-tags {
display: flex;
gap: 0.15rem;
overflow: hidden;
}
.note-tag-pill {
font-size: 0.58rem;
color: var(--fs-accent-fg);
background: color-mix(in srgb, var(--fs-accent) 10%, transparent);
border-radius: 999px;
padding: 0 0.3rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 5rem;
}
.note-tag-pill.tag-match {
background: color-mix(in srgb, var(--fs-accent) 22%, transparent);
outline: 1px solid var(--fs-accent);
}
.note-tag-more {
font-size: 0.58rem;
color: var(--fs-text-tertiary);
white-space: nowrap;
}
.note-row-actions {
display: flex;
gap: 0.2rem;
align-items: center;
}
/* Editor UI */
.panel-header {
display: flex;
align-items: center;
padding: 0.5rem 0.75rem;
flex-shrink: 0;
gap: 0.5rem;
}
.editor-header-right {
display: flex;
align-items: center;
gap: 0.5rem;
margin-left: auto;
}
.unsaved { font-size: 0.72rem; color: var(--fs-text-tertiary); }
.saving-txt { font-size: 0.72rem; color: var(--fs-accent); }
/* Moss action-primary per Hybrid */
.note-title-input {
width: 100%;
background: transparent;
border: none;
font-size: 1.4rem;
font-weight: 500;
line-height: 1.25;
color: var(--fs-text-primary);
padding: 0;
font-family: 'Fraunces', serif;
letter-spacing: -0.01em;
}
.note-title-input:focus { outline: none; }
.note-title-input::placeholder {
color: var(--fs-text-tertiary);
}
.tag-row {
display: flex;
align-items: flex-start;
gap: 0.4rem;
padding: 0.4rem 0.6rem;
flex-shrink: 0;
}
.tag-row > :first-child { flex: 1; min-width: 0; }
.tag-suggestions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.3rem;
padding: 0.35rem 0.6rem;
background: color-mix(in srgb, var(--fs-accent) 5%, var(--fs-surface-hover));
flex-shrink: 0;
}
.tag-suggestions-label { font-size: 0.72rem; color: var(--fs-text-tertiary); flex-shrink: 0; }
.btn-tag-suggestion {
background: none;
border: 1px solid var(--fs-border-color);
border-radius: 999px;
padding: 0.15rem 0.55rem;
font-size: 0.75rem;
color: var(--fs-text-primary);
cursor: pointer;
}
.btn-tag-suggestion:hover { border-color: var(--fs-accent); color: var(--fs-accent); }
.btn-tag-suggestion.applied {
background: color-mix(in srgb, var(--fs-accent) 15%, transparent);
border-color: var(--fs-accent);
color: var(--fs-accent-fg);
}
.link-suggest-strip {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.25rem;
padding: 0.3rem 0.6rem;
background: color-mix(in srgb, var(--fs-accent) 5%, var(--fs-surface-hover));
flex-shrink: 0;
}
.link-suggest-label {
font-size: 0.7rem;
color: var(--fs-text-tertiary);
flex-shrink: 0;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.link-suggest-chip { display: inline-flex; }
.btn-chip-link {
background: none;
border: 1px solid var(--fs-accent);
border-radius: 999px;
padding: 0.1rem 0.45rem;
font-size: 0.7rem;
color: var(--fs-accent);
cursor: pointer;
font-family: monospace;
white-space: nowrap;
}
.btn-chip-link:hover { background: color-mix(in srgb, var(--fs-accent) 15%, transparent); }
</style>
@@ -1,618 +0,0 @@
<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { RouterLink } from "vue-router";
import { apiGet, apiPatch, apiPost, apiDelete } from "@/api/client";
import { useToastStore } from "@/stores/toast";
import TaskLogSection from "@/components/TaskLogSection.vue";
import KindBadge from "@/components/KindBadge.vue";
import type { TaskKind } from "@/types/note";
import { renderMarkdown } from "@/utils/markdown";
import { Trash2, X } from "lucide-vue-next";
import { relativeTimeOrDate } from "@/composables/useRelativeTime";
const props = defineProps<{ projectId: number }>();
const toast = useToastStore();
interface Milestone {
id: number;
title: string;
status: string;
order_index: number;
}
interface Task {
id: number;
title: string;
status: string;
priority: string;
milestone_id: number | null;
due_date: string | null;
updated_at: string;
body?: string;
task_kind?: TaskKind;
}
const tasks = ref<Task[]>([]);
const milestones = ref<Milestone[]>([]);
const loading = ref(false);
// Detail slide-over
const activeTask = ref<Task | null>(null);
const taskBody = ref("");
const loadingBody = ref(false);
// Collapsed milestone groups (set of milestone IDs, null = "No Milestone" group)
const collapsedGroups = ref<Set<number | null>>(new Set());
// New task quick-add
const newTaskTitle = ref("");
const addingTask = ref(false);
const STATUS_CYCLE: Record<string, string> = {
todo: "in_progress",
in_progress: "done",
done: "todo",
};
const STATUS_ICON: Record<string, string> = {
todo: "○",
in_progress: "▶",
done: "✓",
};
const PRIORITY_CLASS: Record<string, string> = {
high: "priority-high",
medium: "priority-medium",
low: "priority-low",
};
function isRowOverdue(task: Task): boolean {
if (!task.due_date || task.status === "done") return false;
return task.due_date < new Date().toISOString().slice(0, 10);
}
// Group tasks by milestone, "No Milestone" first
const groupedTasks = computed(() => {
const noMs = tasks.value.filter((t) => t.milestone_id === null);
const msGroups = milestones.value.map((ms) => ({
milestone: ms,
tasks: tasks.value.filter((t) => t.milestone_id === ms.id),
}));
return { noMilestone: noMs, milestoneGroups: msGroups };
});
async function loadAll() {
loading.value = true;
try {
const [tasksRes, msRes] = await Promise.all([
apiGet<{ notes: Task[] }>(`/api/projects/${props.projectId}/notes?type=task&limit=200`),
apiGet<{ milestones: Milestone[] }>(`/api/projects/${props.projectId}/milestones`),
]);
tasks.value = tasksRes.notes ?? [];
milestones.value = msRes.milestones ?? [];
} catch {
toast.show("Failed to load tasks", "error");
} finally {
loading.value = false;
}
}
async function cycleStatus(task: Task, e: Event) {
e.stopPropagation();
const next = STATUS_CYCLE[task.status] ?? "todo";
try {
await apiPatch(`/api/tasks/${task.id}/status`, { status: next });
task.status = next;
if (activeTask.value?.id === task.id) activeTask.value.status = next;
} catch {
toast.show("Failed to update status", "error");
}
}
function toggleGroup(key: number | null) {
if (collapsedGroups.value.has(key)) {
collapsedGroups.value.delete(key);
} else {
collapsedGroups.value.add(key);
}
}
async function openTask(task: Task) {
activeTask.value = task;
taskBody.value = task.body ?? "";
loadingBody.value = true;
try {
const full = await apiGet<Task>(`/api/tasks/${task.id}`);
taskBody.value = full.body ?? "";
// Update cached task so re-opens don't re-fetch if unchanged
task.body = full.body;
} catch {
// Non-critical — body just won't show
} finally {
loadingBody.value = false;
}
}
function closeTask() {
activeTask.value = null;
taskBody.value = "";
deleteConfirmPending.value = false;
}
async function addTask() {
const title = newTaskTitle.value.trim();
if (!title) return;
addingTask.value = true;
try {
const task = await apiPost<Task>("/api/tasks", {
title,
project_id: props.projectId,
status: "todo",
});
tasks.value.unshift(task);
newTaskTitle.value = "";
} catch {
toast.show("Failed to create task", "error");
} finally {
addingTask.value = false;
}
}
const deletingTask = ref(false);
const deleteConfirmPending = ref(false);
const changingMilestone = ref(false);
async function setMilestone(milestoneId: number | null) {
if (!activeTask.value) return;
changingMilestone.value = true;
try {
await apiPatch(`/api/notes/${activeTask.value.id}`, { milestone_id: milestoneId });
activeTask.value.milestone_id = milestoneId;
// Update in tasks list too
const t = tasks.value.find((x) => x.id === activeTask.value!.id);
if (t) t.milestone_id = milestoneId;
} catch {
toast.show("Failed to update milestone", "error");
} finally {
changingMilestone.value = false;
}
}
async function deleteActiveTask() {
if (!activeTask.value) return;
if (!deleteConfirmPending.value) {
deleteConfirmPending.value = true;
return;
}
deletingTask.value = true;
try {
await apiDelete(`/api/tasks/${activeTask.value.id}`);
tasks.value = tasks.value.filter((t) => t.id !== activeTask.value!.id);
activeTask.value = null;
deleteConfirmPending.value = false;
} catch {
toast.show("Failed to delete task", "error");
} finally {
deletingTask.value = false;
}
}
function cancelDeleteTask() {
deleteConfirmPending.value = false;
}
onMounted(loadAll);
defineExpose({ reload: loadAll });
</script>
<template>
<div class="ws-task-panel">
<!-- Task list — always visible, shrinks when detail is open -->
<div :class="['task-list-view', { 'has-detail': !!activeTask }]">
<div class="panel-header">
<span class="panel-title">Tasks</span>
</div>
<div class="task-add">
<input
v-model="newTaskTitle"
class="task-add-input"
placeholder="New task..."
@keydown.enter="addTask"
/>
<button class="btn-primary btn-inline btn-add" :disabled="addingTask || !newTaskTitle.trim()" @click="addTask">+</button>
</div>
<div v-if="loading" class="state-msg">Loading...</div>
<div v-else class="groups-scroll">
<!-- No Milestone group (always first) -->
<div class="ms-group">
<button class="ms-group-header" @click="toggleGroup(null)">
<span class="ms-chevron">{{ collapsedGroups.has(null) ? '▶' : '▼' }}</span>
<span class="ms-name">No Milestone</span>
<span class="ms-count">{{ groupedTasks.noMilestone.length }}</span>
</button>
<ul v-show="!collapsedGroups.has(null)" class="task-items">
<li
v-for="task in groupedTasks.noMilestone"
:key="task.id"
:class="['task-row', { 'task-active': activeTask?.id === task.id }]"
@click="openTask(task)"
>
<button :class="['status-dot', `status-${task.status}`]" :title="`${task.status} — click to cycle`" @click="cycleStatus(task, $event)">{{ STATUS_ICON[task.status] ?? '○' }}</button>
<span v-if="task.priority && task.priority !== 'none'" :class="['priority-dot', PRIORITY_CLASS[task.priority] ?? '']"></span>
<span class="task-title" :class="{ done: task.status === 'done' }">{{ task.title }}</span>
<KindBadge :kind="task.task_kind" />
<span v-if="task.due_date" :class="['task-due', { overdue: isRowOverdue(task) }]">{{ task.due_date }}</span>
<span class="task-age">{{ relativeTimeOrDate(task.updated_at) }}</span>
</li>
<li v-if="groupedTasks.noMilestone.length === 0" class="empty-group">No tasks</li>
</ul>
</div>
<!-- Milestone groups -->
<div v-for="{ milestone, tasks: msTasks } in groupedTasks.milestoneGroups" :key="milestone.id" class="ms-group">
<button class="ms-group-header" @click="toggleGroup(milestone.id)">
<span class="ms-chevron">{{ collapsedGroups.has(milestone.id) ? '▶' : '▼' }}</span>
<span class="ms-name">{{ milestone.title }}</span>
<span :class="['ms-status', `ms-status-${milestone.status}`]">{{ milestone.status.replace('_',' ') }}</span>
<span class="ms-count">{{ msTasks.length }}</span>
</button>
<ul v-show="!collapsedGroups.has(milestone.id)" class="task-items">
<li
v-for="task in msTasks"
:key="task.id"
:class="['task-row', { 'task-active': activeTask?.id === task.id }]"
@click="openTask(task)"
>
<button :class="['status-dot', `status-${task.status}`]" :title="`${task.status} — click to cycle`" @click="cycleStatus(task, $event)">{{ STATUS_ICON[task.status] ?? '○' }}</button>
<span v-if="task.priority && task.priority !== 'none'" :class="['priority-dot', PRIORITY_CLASS[task.priority] ?? '']"></span>
<span class="task-title" :class="{ done: task.status === 'done' }">{{ task.title }}</span>
<KindBadge :kind="task.task_kind" />
<span v-if="task.due_date" :class="['task-due', { overdue: isRowOverdue(task) }]">{{ task.due_date }}</span>
<span class="task-age">{{ relativeTimeOrDate(task.updated_at) }}</span>
</li>
<li v-if="msTasks.length === 0" class="empty-group">No tasks</li>
</ul>
</div>
</div>
</div>
<!-- Detail pane — bottom split when a task is selected -->
<Transition name="detail-fade">
<div v-if="activeTask" class="task-detail">
<div class="detail-header">
<RouterLink :to="`/tasks/${activeTask.id}/edit`" target="_blank" class="btn-text btn-edit-task" title="Open full editor">Edit ↗</RouterLink>
<span :class="['status-cycler', `status-${activeTask.status}`]" @click="cycleStatus(activeTask, $event)" title="Click to cycle status">
{{ STATUS_ICON[activeTask.status] ?? "○" }} {{ activeTask.status.replace("_", " ") }}
</span>
<template v-if="deleteConfirmPending">
<button class="btn-danger-outline btn-inline btn-delete-confirm" :disabled="deletingTask" @click="deleteActiveTask">{{ deletingTask ? '...' : 'Delete?' }}</button>
<button class="btn-text" aria-label="Cancel delete" @click="cancelDeleteTask"><X :size="16" /></button>
</template>
<button v-else class="btn-text btn-delete-task" title="Delete task" @click="deleteActiveTask">
<Trash2 :size="16" />
</button>
<button class="btn-text btn-close-detail" @click="closeTask" aria-label="Close detail"><X :size="16" /></button>
</div>
<h3 class="detail-title">{{ activeTask.title }}</h3>
<div class="detail-meta">
<span v-if="activeTask.priority && activeTask.priority !== 'none'" class="meta-chip priority">{{ activeTask.priority }}</span>
<span v-if="activeTask.due_date" class="meta-chip due">Due {{ activeTask.due_date }}</span>
<select
class="milestone-select"
:value="activeTask.milestone_id ?? ''"
:disabled="changingMilestone"
@change="setMilestone(($event.target as HTMLSelectElement).value === '' ? null : Number(($event.target as HTMLSelectElement).value))"
>
<option value="">No Milestone</option>
<option v-for="ms in milestones" :key="ms.id" :value="ms.id">{{ ms.title }}</option>
</select>
</div>
<div v-if="taskBody || loadingBody" class="detail-body">
<div v-if="loadingBody" class="body-loading">…</div>
<div v-else class="prose" v-html="renderMarkdown(taskBody)" />
</div>
<div class="detail-log">
<TaskLogSection :task-id="activeTask.id" />
</div>
</div>
</Transition>
</div>
</template>
<style scoped>
.ws-task-panel {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
background: var(--fs-surface-hover);
border-right: 1px solid var(--fs-border-color);
}
/* ── List view ── */
.task-list-view {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
.task-list-view.has-detail {
flex: 0 0 44%;
}
.task-active {
background: color-mix(in srgb, var(--fs-accent) 6%, var(--fs-surface-hover)) !important;
}
.panel-header {
padding: 0.6rem 0.75rem;
border-bottom: 1px solid var(--fs-border-color);
flex-shrink: 0;
}
.panel-title {
color: var(--fs-text-tertiary);
text-transform: uppercase;
letter-spacing: 0.04em;
font-size: 0.75rem;
font-weight: 500;
}
.task-add {
display: flex;
gap: 0.4rem;
padding: 0.45rem 0.6rem;
border-bottom: 1px solid var(--fs-border-color);
flex-shrink: 0;
}
.task-add-input {
flex: 1;
background: var(--fs-surface-page);
border: 1px solid var(--fs-border-color);
border-radius: 5px;
padding: 0.28rem 0.5rem;
font-size: 0.83rem;
color: var(--fs-text-primary);
}
.task-add-input:focus { outline: none; border-color: var(--fs-accent); }
.btn-add { font-size: 1rem; } /* a '+' glyph, not a label */
.groups-scroll {
flex: 1;
overflow-y: auto;
}
.ms-group {
border-bottom: 1px solid var(--fs-border-color);
}
.ms-group-header {
display: flex;
align-items: center;
gap: 0.4rem;
width: 100%;
padding: 0.4rem 0.65rem;
background: var(--fs-surface-raised);
border: none;
cursor: pointer;
text-align: left;
font-size: 0.8rem;
color: var(--fs-text-primary);
}
.ms-group-header:hover { background: color-mix(in srgb, var(--fs-accent) 8%, var(--fs-surface-hover)); }
.ms-chevron { font-size: 0.6rem; color: var(--fs-text-tertiary); width: 0.8rem; }
.ms-name { flex: 1; font-weight: 500; font-size: 0.8rem; }
.ms-count { font-size: 0.72rem; color: var(--fs-text-tertiary); background: var(--fs-surface-page); border-radius: 10px; padding: 0 0.4rem; }
.ms-status {
font-size: 0.68rem;
padding: 0.1rem 0.4rem;
border-radius: 10px;
text-transform: capitalize;
}
.ms-status-active { background: color-mix(in srgb, var(--fs-accent) 15%, transparent); color: var(--fs-accent-fg); }
.ms-status-completed { background: color-mix(in srgb, var(--fs-success) 15%, transparent); color: var(--fs-success-fg); }
.task-items {
list-style: none;
margin: 0;
padding: 0;
}
.task-row {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.35rem 0.65rem 0.35rem 1.4rem;
cursor: pointer;
border-bottom: 1px solid color-mix(in srgb, var(--fs-border-color) 50%, transparent);
}
.task-row:hover { background: color-mix(in srgb, var(--fs-accent) 5%, var(--fs-surface-hover)); }
.task-row:last-child { border-bottom: none; }
.status-dot {
flex-shrink: 0;
width: 1.35rem;
height: 1.35rem;
border-radius: 50%;
border: 1.5px solid var(--fs-border-color);
background: none;
cursor: pointer;
font-size: 0.62rem;
display: flex;
align-items: center;
justify-content: center;
}
.status-dot.status-in_progress { border-color: var(--fs-accent); color: var(--fs-accent); }
.status-dot.status-done { border-color: var(--fs-success); color: var(--fs-success); }
.task-title {
flex: 1;
font-size: 0.83rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--fs-text-primary);
}
.task-title.done { text-decoration: line-through; color: var(--fs-text-tertiary); }
.task-age {
font-size: 0.68rem;
color: var(--fs-text-tertiary);
white-space: nowrap;
flex-shrink: 0;
}
.empty-group { padding: 0.4rem 1.4rem; font-size: 0.78rem; color: var(--fs-text-tertiary); }
.state-msg { padding: 1.5rem; text-align: center; font-size: 0.85rem; color: var(--fs-text-tertiary); }
/* ── Detail pane (bottom split) ── */
.task-detail {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
background: var(--fs-surface-hover);
border-top: 2px solid var(--fs-border-color);
}
.detail-header {
display: flex;
align-items: center;
gap: 0.6rem;
padding: 0.6rem 0.75rem;
border-bottom: 1px solid var(--fs-border-color);
flex-shrink: 0;
}
/* An interactive CYCLER, not a chip: it is clickable, outlined and
transparent. It shared a name with the task chip and was never the same
shape (#3132). */
.status-cycler {
padding: 0.2rem 0.55rem;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 500;
cursor: pointer;
border: 1.5px solid var(--fs-border-color);
background: none;
text-transform: capitalize;
user-select: none;
margin-left: auto;
}
.status-cycler.status-in_progress { border-color: var(--fs-accent); color: var(--fs-accent-fg); background: color-mix(in srgb, var(--fs-accent) 10%, transparent); }
.status-cycler.status-done { border-color: var(--fs-success); color: var(--fs-success-fg); background: color-mix(in srgb, var(--fs-success) 10%, transparent); }
.btn-edit-task { margin-left: 0.25rem; }
.btn-edit-task:hover { text-decoration: underline; }
.detail-body {
padding: 0.5rem 0.75rem 0.5rem;
border-bottom: 1px solid var(--fs-border-color);
flex-shrink: 0;
max-height: 40%;
overflow-y: auto;
}
.body-loading {
font-size: 0.8rem;
color: var(--fs-text-tertiary);
}
.detail-body .prose {
font-size: 0.83rem;
line-height: 1.5;
color: var(--fs-text-primary);
}
.btn-delete-task { margin-left: 0.25rem; }
.btn-delete-task:hover { color: var(--fs-action-destructive); }
.btn-delete-confirm { margin-left: 0.25rem; }
.detail-meta {
display: flex;
gap: 0.4rem;
padding: 0 0.75rem 0.5rem;
flex-shrink: 0;
}
.meta-chip {
font-size: 0.72rem;
padding: 0.15rem 0.5rem;
border-radius: 10px;
background: var(--fs-surface-page);
border: 1px solid var(--fs-border-color);
color: var(--fs-text-tertiary);
text-transform: capitalize;
}
.milestone-select {
font-size: 0.72rem;
padding: 0.15rem 0.4rem;
border-radius: 10px;
background: var(--fs-surface-page);
border: 1px solid var(--fs-border-color);
color: var(--fs-text-tertiary);
cursor: pointer;
max-width: 140px;
}
.milestone-select:disabled { opacity: 0.5; cursor: default; }
.milestone-select:focus { outline: none; border-color: var(--fs-accent); }
.detail-log {
flex: 1;
overflow-y: auto;
padding: 0 0.6rem 0.6rem;
border-top: 1px solid var(--fs-border-color);
}
/* Detail fade transition */
.detail-fade-enter-active,
.detail-fade-leave-active { transition: opacity 0.15s; }
.detail-fade-enter-from,
.detail-fade-leave-to { opacity: 0; }
/* Priority dots on task rows */
.priority-dot {
width: 6px;
height: 6px;
border-radius: 2px;
flex-shrink: 0;
}
.priority-high { background: #ef4444; }
.priority-medium { background: #f59e0b; }
.priority-low { background: #3b82f6; }
/* Due date on task rows */
.task-due {
font-size: 0.65rem;
color: var(--fs-text-tertiary);
white-space: nowrap;
flex-shrink: 0;
}
.task-due.overdue {
color: var(--fs-error);
font-weight: 500;
}
/* Close detail button */
.btn-close-detail { margin-left: 0.2rem; }
</style>
@@ -6,7 +6,11 @@ import { useMomentsStore } from "@/stores/moments";
import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue"; import RuleHistoryPanel from "@/components/rules/RuleHistoryPanel.vue";
import RuleHomePicker from "@/components/rules/RuleHomePicker.vue"; import RuleHomePicker from "@/components/rules/RuleHomePicker.vue";
import { apiErrorMessage } from "@/api/client"; import { apiErrorMessage } from "@/api/client";
import { listRulebooks, listTopics, type Rule, type RuleKind, type RulePreset } from "@/api/rulebooks"; import {
listRulebooks, listTopics,
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
type RuleTrigger, type RuleTriggerKind,
} from "@/api/rulebooks";
const props = defineProps<{ const props = defineProps<{
ruleId: number | null; ruleId: number | null;
@@ -26,6 +30,14 @@ const whenToApply = ref("");
// followed too faithfully, where a rule mislabelled as a preference is one a // followed too faithfully, where a rule mislabelled as a preference is one a
// session may quietly rewrite. // session may quietly rewrite.
const kind = ref<RuleKind>("rule"); const kind = ref<RuleKind>("rule");
// The server's defaults: a line beside the work, at normal rank.
const enforcement = ref<RuleEnforcement>("inform");
const salience = ref<RuleSalience>("normal");
// A preference carries no force but `inform`, and the server refuses any
// other, so switching kind settles it here rather than as a failed save.
watch(kind, (k) => {
if (k === "preference") enforcement.value = "inform";
});
const systemIds = ref<number[]>([]); const systemIds = ref<number[]>([]);
// The moments this rule is mounted on. Catalog moments are // The moments this rule is mounted on. Catalog moments are
// ticked; a named procedure's moment (`skill.<name>`) is typed, since its // ticked; a named procedure's moment (`skill.<name>`) is typed, since its
@@ -39,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []);
const procedureMoments = computed(() => const procedureMoments = computed(() =>
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)), ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
); );
// The acts this rule is triggered by, checked exactly on the server.
const triggers = ref<RuleTrigger[]>([]);
const triggerKind = ref<RuleTriggerKind>("path");
const triggerPattern = ref("");
const triggerMoment = ref("");
const triggerError = ref("");
const TRIGGER_KINDS: { value: RuleTriggerKind; label: string; placeholder: string }[] = [
{ value: "path", label: "Path", placeholder: "alembic/versions/*.py — a file the act touches" },
{ value: "command", label: "Command", placeholder: "git push — the head of a command it runs" },
{ value: "tool", label: "Tool", placeholder: "update_task — the tool it calls" },
{ value: "keyword", label: "Keyword", placeholder: "migration — a word in what it writes" },
];
const triggerPlaceholder = computed(
() => TRIGGER_KINDS.find((k) => k.value === triggerKind.value)?.placeholder ?? "",
);
function triggerLabel(t: RuleTrigger) {
return TRIGGER_KINDS.find((k) => k.value === t.kind)?.label ?? t.kind;
}
function addTrigger() {
const pattern = triggerPattern.value.trim().replace(/\s+/g, " ");
if (!pattern) return;
const moment = triggerMoment.value || undefined;
const same = (t: RuleTrigger) =>
t.kind === triggerKind.value && t.pattern === pattern && (t.moment ?? "") === (moment ?? "");
if (triggers.value.some(same)) {
triggerError.value = "This rule already has that trigger.";
return;
}
triggerError.value = "";
triggers.value.push({ kind: triggerKind.value, pattern, ...(moment ? { moment } : {}) });
triggerPattern.value = "";
}
function removeTrigger(at: number) {
triggers.value.splice(at, 1);
}
const why = ref(""); const why = ref("");
const howToApply = ref(""); const howToApply = ref("");
const verifyWith = ref(""); const verifyWith = ref("");
@@ -123,8 +173,11 @@ async function load() {
statement.value = r.statement; statement.value = r.statement;
whenToApply.value = r.when_to_apply || ""; whenToApply.value = r.when_to_apply || "";
kind.value = r.kind; kind.value = r.kind;
enforcement.value = r.enforcement ?? "inform";
salience.value = r.salience ?? "normal";
systemIds.value = (r.systems ?? []).map((sys) => sys.id); systemIds.value = (r.systems ?? []).map((sys) => sys.id);
ruleMoments.value = [...(r.moments ?? [])]; ruleMoments.value = [...(r.moments ?? [])];
triggers.value = (r.triggers ?? []).map((t) => ({ ...t }));
why.value = r.why || ""; why.value = r.why || "";
howToApply.value = r.how_to_apply || ""; howToApply.value = r.how_to_apply || "";
verifyWith.value = r.verify_with || ""; verifyWith.value = r.verify_with || "";
@@ -135,8 +188,11 @@ async function load() {
statement.value = ""; statement.value = "";
whenToApply.value = props.preset?.whenToApply ?? ""; whenToApply.value = props.preset?.whenToApply ?? "";
kind.value = props.preset?.kind ?? "rule"; kind.value = props.preset?.kind ?? "rule";
enforcement.value = "inform";
salience.value = "normal";
systemIds.value = []; systemIds.value = [];
ruleMoments.value = [...(props.preset?.moments ?? [])]; ruleMoments.value = [...(props.preset?.moments ?? [])];
triggers.value = [];
why.value = ""; why.value = "";
howToApply.value = ""; howToApply.value = "";
verifyWith.value = ""; verifyWith.value = "";
@@ -144,6 +200,9 @@ async function load() {
} }
procedureDraft.value = ""; procedureDraft.value = "";
procedureError.value = ""; procedureError.value = "";
triggerPattern.value = "";
triggerMoment.value = "";
triggerError.value = "";
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]); await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
} }
@@ -181,12 +240,16 @@ async function save() {
statement: statement.value, statement: statement.value,
when_to_apply: whenToApply.value, when_to_apply: whenToApply.value,
kind: kind.value, kind: kind.value,
enforcement: enforcement.value,
salience: salience.value,
// Always sent, so clearing the last area actually clears it — the server // Always sent, so clearing the last area actually clears it — the server
// reads a list as "these ARE the areas now". // reads a list as "these ARE the areas now".
system_ids: systemIds.value, system_ids: systemIds.value,
// Always sent, for system_ids' reason: the server reads the list as the // Always sent, for system_ids' reason: the server reads the list as the
// whole set, so unticking the last moment actually unmounts the rule. // whole set, so unticking the last moment actually unmounts the rule.
moments: ruleMoments.value, moments: ruleMoments.value,
// Always sent, for the same reason: the list is the whole set.
triggers: triggers.value,
why: why.value, why: why.value,
how_to_apply: howToApply.value, how_to_apply: howToApply.value,
// Always sent, including empty. The REST door maps "" to NULL, so // Always sent, including empty. The REST door maps "" to NULL, so
@@ -271,6 +334,40 @@ watch(() => props.ruleId, load);
preference. preference.
</p> </p>
</fieldset> </fieldset>
<fieldset class="kind arrival">
<legend>When it arrives</legend>
<template v-if="kind === 'rule'">
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="inform" />
<span><strong>Inform</strong> — a line beside the work. Most rules.</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="hold" />
<span>
<strong>Hold</strong> — the reply or command it governs waits until
the rule has been read once. File edits are never held. For a rule
whose miss costs a rewrite.
</span>
</label>
<label class="kind-opt">
<input v-model="enforcement" type="radio" value="enforce" />
<span>
<strong>Enforce</strong> — an act its moment or trigger reaches
does not run, every time, until you change the rule. For a hard
boundary.
</span>
</label>
</template>
<p v-else class="field-note">A preference arrives as a line beside the work.</p>
<label class="salience">
Rank among the rest
<select v-model="salience" class="fs-input">
<option value="high">High — shown first when a moment is crowded</option>
<option value="normal">Normal</option>
<option value="low">Low — the first to give way</option>
</select>
</label>
</fieldset>
<p v-if="kind === 'preference'" class="kind-drift"> <p v-if="kind === 'preference'" class="kind-drift">
Sessions rewrite preferences without asking, which is what makes them Sessions rewrite preferences without asking, which is what makes them
stay current. Every rewrite is kept, and stay current. Every rewrite is kept, and
@@ -342,6 +439,55 @@ watch(() => props.ruleId, load);
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p> <p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
</fieldset> </fieldset>
<fieldset class="moments triggers">
<legend>Acts that trigger it</legend>
<p class="field-note intro">
Matched exactly against what the work does, not by resemblance: a
path it touches, a command it runs, a tool it calls, a word in what it
writes. With no moment, the rule arrives on any act that matches.
With a moment, it arrives at that moment only when the act matches,
so a rule about migrations can sit where files change without arriving
at every edit.
</p>
<ul v-if="triggers.length" class="trigger-list">
<li v-for="(t, i) in triggers" :key="`${t.kind}:${t.pattern}:${t.moment ?? ''}`" class="rule-chip trigger-chip">
<span class="trigger-kind">{{ triggerLabel(t) }}</span>
<code>{{ t.pattern }}</code>
<span v-if="t.moment" class="trigger-at">at <code>{{ t.moment }}</code></span>
<button
type="button"
class="chip-remove"
:aria-label="`Remove the ${triggerLabel(t).toLowerCase()} trigger ${t.pattern}`"
@click="removeTrigger(i)"
>×</button>
</li>
</ul>
<p v-else class="field-note">No triggers: this rule arrives by its moments and by resemblance.</p>
<div class="trigger-add">
<select v-model="triggerKind" class="fs-input" aria-label="What the trigger matches">
<option v-for="k in TRIGGER_KINDS" :key="k.value" :value="k.value">{{ k.label }}</option>
</select>
<input
v-model="triggerPattern"
class="fs-input"
aria-label="The pattern the act must match"
:placeholder="triggerPlaceholder"
@keydown.enter.prevent="addTrigger"
/>
<select v-model="triggerMoment" class="fs-input" aria-label="Only at this moment">
<option value="">Any act</option>
<option v-for="m in momentCatalog" :key="m.name" :value="m.name">Only at {{ m.name }}</option>
</select>
<button
type="button"
class="btn-secondary btn-sm"
:disabled="!triggerPattern.trim()"
@click="addTrigger"
>Add</button>
</div>
<p v-if="triggerError" class="trigger-warning">{{ triggerError }}</p>
</fieldset>
<fieldset v-if="canon.catalog.length" class="areas"> <fieldset v-if="canon.catalog.length" class="areas">
<legend>Areas this rule is about</legend> <legend>Areas this rule is about</legend>
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt"> <label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
@@ -520,6 +666,13 @@ legend { padding: 0 0.35rem; font-size: 0.8rem; color: var(--fs-text-tertiary);
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); } .procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
.procedure-add input { margin-top: 0; } .procedure-add input { margin-top: 0; }
.procedure-add .btn-sm { flex: none; } .procedure-add .btn-sm { flex: none; }
.trigger-list { list-style: none; padding: 0; margin: 0 0 var(--fs-space-2); display: flex; flex-wrap: wrap; gap: var(--fs-space-2); }
.trigger-chip { display: inline-flex; align-items: center; gap: var(--fs-space-1); }
.trigger-kind, .trigger-at { color: var(--fs-text-secondary); font-size: var(--fs-size-tiny); }
.trigger-add { display: flex; flex-wrap: wrap; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
.trigger-add input { flex: 1 1 14rem; margin-top: 0; }
.trigger-add select { flex: none; width: auto; margin-top: 0; }
.trigger-add .btn-sm { flex: none; }
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction /* --fs-warning-fg, not --fs-warning: the token set draws the distinction
between the warning HUE and warning text, and this is text. */ between the warning HUE and warning text, and this is text. */
.trigger-warning { .trigger-warning {
@@ -4,9 +4,9 @@
* full. Not on the list row: a history entry point there would compete with * full. Not on the list row: a history entry point there would compete with
* the row's actual job. * the row's actual job.
* *
* A SIBLING OF HistoryPanel.vue, NOT A REUSE OF IT, and the reason is in its * A SIBLING OF VersionHistorySection.vue (a note's history), NOT A REUSE OF
* props: `noteId` + `currentBody`, a `NoteVersion` carrying tags and pin * IT, and the reason is in its props: `noteId` + `currentBody`, a note
* columns, a fetch of /api/notes/…, a `restore` emit, and pin/unpin buttons. * version carrying tags, a fetch of /api/notes/…, and a `restore` emit.
* Every one of those is note-shaped. Rules have no tags, no pins, and * Every one of those is note-shaped. Rules have no tags, no pins, and
* deliberately no restore, and a rule's text is EIGHT fields rather than one * deliberately no restore, and a rule's text is EIGHT fields rather than one
* body — which changes the central question from "what changed" to "which * body — which changes the central question from "what changed" to "which
@@ -27,6 +27,15 @@ const emit = defineEmits<{
class="rule-chip rule-chip-preference" class="rule-chip rule-chip-preference"
title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it." title="How you want work done. It does not bind, and Grimoire updates it as the work teaches it."
>preference</span> >preference</span>
<!-- Marked only when the rule stops the work: a line beside the work
is the default, and marking it on every row would mark nothing. -->
<span
v-if="r.enforcement === 'hold' || r.enforcement === 'enforce'"
class="rule-chip"
:title="r.enforcement === 'hold'
? 'The reply or command it governs waits until it has been read once'
: 'An act it is reached by does not run until the rule changes'"
>{{ r.enforcement === "hold" ? "holds" : "enforced" }}</span>
<!-- Marked only when something is WRONG: every rule arrives by <!-- Marked only when something is WRONG: every rule arrives by
retrieval now, so "conditional" stopped distinguishing anything. retrieval now, so "conditional" stopped distinguishing anything.
A missing trigger does — it means nothing can retrieve this. --> A missing trigger does — it means nothing can retrieve this. -->
+2 -1
View File
@@ -51,7 +51,8 @@ export function useAutocomplete(
// Must be start of line or preceded by whitespace // Must be start of line or preceded by whitespace
if (i === 0 || /\s/.test(text[i - 1])) { if (i === 0 || /\s/.test(text[i - 1])) {
const query = text.slice(i + 1, cursor); const query = text.slice(i + 1, cursor);
if (/^[\w/]*$/.test(query)) { // Digits alone are a record reference being typed (`#4286`), not a tag.
if (/^[\w/]*$/.test(query) && !/^\d+$/.test(query)) {
acTriggerStart = i; acTriggerStart = i;
acType = "tag"; acType = "tag";
debouncedSearch(query); debouncedSearch(query);
+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 { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view"; import { Decoration, DecorationSet } from "@tiptap/pm/view";
const TAG_RE = /(?<=\s|^)#([\w]+(?:\/[\w]+)*)/g; // Digits alone (`#4286`) are a record reference, not a tag, and are left plain
// here; the rendered view links them (utils/recordRefs.ts).
const TAG_RE = /(?<=\s|^)#(?!\d+(?![\w/-]))([\w]+(?:\/[\w]+)*)/g;
export const TagDecoration = Extension.create({ export const TagDecoration = Extension.create({
name: "tagDecoration", name: "tagDecoration",
+20
View File
@@ -123,6 +123,26 @@ const router = createRouter({
name: "project-view", name: "project-view",
component: () => import("@/views/ProjectView.vue"), component: () => import("@/views/ProjectView.vue"),
}, },
{
// Where a `milestone N` reference leads. A milestone is shown on its
// project's board, so this only looks up which project and goes there.
path: "/milestones/:id",
name: "milestone",
component: () => import("@/views/ProjectListView.vue"),
beforeEnter: async (to) => {
const id = Number(to.params.id);
const { resolveRecordRefs } = await import("@/directives/recordRefs");
try {
const found = (await resolveRecordRefs([{ space: "milestones", id }])).get(`milestones:${id}`);
if (found) return found.href;
} catch {
// Fall through to the projects list with the notice below.
}
const { useToastStore } = await import("@/stores/toast");
useToastStore().show(`No milestone ${id} you can open`, "warning");
return { name: "projects" };
},
},
{ {
path: "/rules", path: "/rules",
name: "rules", name: "rules",
+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 // force as the same row re-fetched, or a preference the operator just
// created would sit in the list looking like a rule until a reload. // created would sit in the list looking like a rule until a reload.
kind: rule.kind, kind: rule.kind,
enforcement: rule.enforcement ?? "inform",
// Mirrors rule_brief: present only when raised or lowered.
salience: rule.salience && rule.salience !== "normal" ? rule.salience : undefined,
updated_at: rule.updated_at, updated_at: rule.updated_at,
when_to_apply: rule.when_to_apply || undefined, when_to_apply: rule.when_to_apply || undefined,
arose_from_id: rule.arose_from_id ?? undefined, arose_from_id: rule.arose_from_id ?? undefined,
+1 -1
View File
@@ -2,7 +2,7 @@
* Line diff — one copy, for every surface that shows what changed. * Line diff — one copy, for every surface that shows what changed.
* *
* WHY THIS FILE EXISTS. The one LCS diff walk, shared by `useAssist.ts`, * WHY THIS FILE EXISTS. The one LCS diff walk, shared by `useAssist.ts`,
* `HistoryPanel.vue`, `VersionHistorySection.vue` and the rule edit history. * `VersionHistorySection.vue` and the rule edit history.
* A copy per consumer means a fix has to be found in N places by someone who * A copy per consumer means a fix has to be found in N places by someone who
* does not know N. * does not know N.
*/ */
+7 -4
View File
@@ -1,6 +1,7 @@
import { marked, type RendererThis, type Tokens } from "marked"; import { marked, type RendererThis, type Tokens } from "marked";
import DOMPurify from "dompurify"; import DOMPurify from "dompurify";
import { linkifyTags, linkifyWikilinks } from "@/utils/tags"; import { linkifyTags, linkifyWikilinks } from "@/utils/tags";
import { linkifyRecordRefs } from "@/utils/recordRefs";
function decodeEntities(text: string): string { function decodeEntities(text: string): string {
const textarea = document.createElement("textarea"); const textarea = document.createElement("textarea");
@@ -20,9 +21,11 @@ export function slugify(text: string): string {
export function stripFirstLineTags(text: string): string { export function stripFirstLineTags(text: string): string {
const match = text.match(/^[ \t]*((?:(?<!\w)#[\w]+(?:\/[\w]+)*[ \t]*)+)\n?/); const match = text.match(/^[ \t]*((?:(?<!\w)#[\w]+(?:\/[\w]+)*[ \t]*)+)\n?/);
if (!match) return text; if (!match) return text;
// Verify every #-token is a tag, not a heading (headings have "# " with space) // Verify every #-token is a tag, not a heading (headings have "# " with
// space) and not a record reference: a first line of "#4286 #4290" cites two
// records and stays in the body.
const tokens = match[1].trim().split(/\s+/); const tokens = match[1].trim().split(/\s+/);
const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t)); const allTags = tokens.every((t) => /^#[\w]+(?:\/[\w]+)*$/.test(t) && !/^#\d+$/.test(t));
if (!allTags) return text; if (!allTags) return text;
return text.slice(match[0].length); return text.slice(match[0].length);
} }
@@ -38,7 +41,7 @@ const headingRenderer = {
marked.use({ renderer: headingRenderer }); marked.use({ renderer: headingRenderer });
const PURIFY_OPTS_FULL = { const PURIFY_OPTS_FULL = {
ADD_ATTR: ["data-tag", "data-title", "data-task-index"], ADD_ATTR: ["data-tag", "data-title", "data-task-index", "data-ref-space", "data-ref-id"],
FORCE_BODY: true, FORCE_BODY: true,
}; };
@@ -64,7 +67,7 @@ export function renderMarkdown(text: string, { interactiveCheckboxes = false } =
} }
const withTags = linkifyTags(html); const withTags = linkifyTags(html);
const withLinks = linkifyWikilinks(withTags); const withLinks = linkifyRecordRefs(linkifyWikilinks(withTags));
const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL); const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL);
// marked escapes ' to &#39; — replace after sanitization to ensure clean rendering // marked escapes ' to &#39; — replace after sanitization to ensure clean rendering
return sanitized.replace(/&#39;/g, "'"); 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 CODE_FENCE_RE = /```[\s\S]*?```|`[^`\n]+`/g;
const TAG_RE = /(?<!\w)(?<!&)#([\w][\w-]*(?:\/[\w][\w-]*)*)/g; // A `#` token made only of digits is a record reference (`#3127` names a note,
// task, lesson or snippet; utils/recordRefs.ts links it), never a tag. Digits
// followed by more of a tag (`#2fa`, `#123-notes`) is still a tag. The backend's
// src/grimoire/utils/tags.py holds the same pattern.
export const TAG_RE = /(?<!\w)(?<!&)#(?!\d+(?![\w/-]))([\w][\w-]*(?:\/[\w][\w-]*)*)/g;
function escapeHtmlAttr(s: string): string { function escapeHtmlAttr(s: string): string {
return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+21 -7
View File
@@ -19,6 +19,7 @@ import {
type FamilyIdea, type IdeaSnapshot, type IdeaStatus, type FamilyIdea, type IdeaSnapshot, type IdeaStatus,
} from "@/api/family"; } from "@/api/family";
import FamilyAdoptionMatrix from "@/components/FamilyAdoptionMatrix.vue"; import FamilyAdoptionMatrix from "@/components/FamilyAdoptionMatrix.vue";
import ScrollSentinel from "@/components/ScrollSentinel.vue";
import { useToastStore } from "@/stores/toast"; import { useToastStore } from "@/stores/toast";
import { fmtStamp } from "@/utils/dateFormat"; import { fmtStamp } from "@/utils/dateFormat";
import { recordHref } from "@/utils/recordHref"; import { recordHref } from "@/utils/recordHref";
@@ -36,6 +37,8 @@ const loading = ref(true);
const failed = ref(false); const failed = ref(false);
const moreDecisions = ref(false); const moreDecisions = ref(false);
const loadingMore = ref(false); const loadingMore = ref(false);
const moreFailed = ref(false);
const decisionOffset = ref(0);
// One pending reversal at a time: which row, which act, and its reason. // One pending reversal at a time: which row, which act, and its reason.
const pending = ref<{ kind: "undo" | "retire"; id: number } | null>(null); const pending = ref<{ kind: "undo" | "retire"; id: number } | null>(null);
@@ -63,7 +66,9 @@ async function load() {
criteria.value = ideaData.criteria; criteria.value = ideaData.criteria;
conflictOrder.value = ideaData.conflict_order ?? []; conflictOrder.value = ideaData.conflict_order ?? [];
decisions.value = log; decisions.value = log;
decisionOffset.value = log.length;
moreDecisions.value = log.length === PAGE; moreDecisions.value = log.length === PAGE;
moreFailed.value = false;
} catch { } catch {
// Said out loud: a log that failed to load must not read as "nothing // Said out loud: a log that failed to load must not read as "nothing
// has been decided". // has been decided".
@@ -73,14 +78,20 @@ async function load() {
} }
} }
// Older decisions load as the log is scrolled. The log is offset-paged, so a
// decision recorded since the first page shifts the rest down by one; a row
// already shown is skipped, and the offset still counts what the server sent.
async function loadMore() { async function loadMore() {
loadingMore.value = true; loadingMore.value = true;
moreFailed.value = false;
try { try {
const next = await listFamilyDecisions(PAGE, decisions.value.length); const next = await listFamilyDecisions(PAGE, decisionOffset.value);
decisions.value.push(...next); const shown = new Set(decisions.value.map((d) => d.id));
decisions.value.push(...next.filter((d) => !shown.has(d.id)));
decisionOffset.value += next.length;
moreDecisions.value = next.length === PAGE; moreDecisions.value = next.length === PAGE;
} catch (e: unknown) { } catch {
toast.show(apiErrorMessage(e, "Could not load more decisions"), "error"); moreFailed.value = true;
} finally { } finally {
loadingMore.value = false; loadingMore.value = false;
} }
@@ -343,9 +354,12 @@ onMounted(load);
</form> </form>
</li> </li>
</ul> </ul>
<button v-if="moreDecisions" class="btn-secondary btn-sm" :disabled="loadingMore" @click="loadMore"> <ScrollSentinel
{{ loadingMore ? "Loading…" : "Older decisions" }} :cursor="moreDecisions ? String(decisionOffset) : ''"
</button> :loading="loadingMore"
:failed="moreFailed"
@more="loadMore"
/>
</section> </section>
</template> </template>
</main> </main>
+11 -7
View File
@@ -8,6 +8,7 @@ import { drag } from "d3-drag";
import { select } from "d3-selection"; import { select } from "d3-selection";
import { apiGet } from "@/api/client"; import { apiGet } from "@/api/client";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
const router = useRouter(); const router = useRouter();
@@ -26,7 +27,8 @@ interface GraphNode extends SimulationNodeDatum {
interface GraphEdge { interface GraphEdge {
source: number | string | GraphNode; source: number | string | GraphNode;
target: number | string | GraphNode; target: number | string | GraphNode;
type: "wikilink" | "tag"; /** wikilink: `[[title]]`; reference: a `#N` citation; tag: a shared tag. */
type: "wikilink" | "reference" | "tag";
} }
interface Project { interface Project {
@@ -237,12 +239,14 @@ function initGraph() {
.append("line") .append("line")
.attr("class", "graph-edge") .attr("class", "graph-edge")
.attr("stroke", (d: any) => .attr("stroke", (d: any) =>
d.type === "wikilink" ? "var(--fs-accent)" : "var(--fs-text-tertiary)" d.type === "tag" ? "var(--fs-text-tertiary)" : "var(--fs-accent)"
) )
.attr("stroke-opacity", (d: any) => (d.type === "wikilink" ? 0.5 : 0.4)) .attr("stroke-opacity", (d: any) => (d.type === "tag" ? 0.4 : 0.5))
.attr("stroke-dasharray", null) // A citation is a looser link than a wikilink: same colour and direction,
.attr("stroke-width", (d: any) => (d.type === "wikilink" ? 1.5 : 1)) // drawn dashed so the two read apart.
.attr("marker-end", (d: any) => (d.type === "wikilink" ? "url(#arrow)" : null)); .attr("stroke-dasharray", (d: any) => (d.type === "reference" ? "4 3" : null))
.attr("stroke-width", (d: any) => (d.type === "tag" ? 1 : 1.5))
.attr("marker-end", (d: any) => (d.type === "tag" ? null : "url(#arrow)"));
// Node groups // Node groups
const nodeSel = zoomG const nodeSel = zoomG
@@ -559,7 +563,7 @@ onUnmounted(() => {
<div <div
v-else-if="peekBody" v-else-if="peekBody"
class="prose peek-prose" class="prose peek-prose"
v-html="renderMarkdown(peekBody)" v-html="renderMarkdown(peekBody)" v-record-refs
/> />
<div v-else class="peek-empty">No content.</div> <div v-else class="peek-empty">No content.</div>
</div> </div>
+50 -67
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from "vue"; import { ref, computed, watch, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import { apiGet } from "@/api/client"; import { apiGet } from "@/api/client";
import type { TaskKind, TaskStatus, TaskPriority } from "@/types/note"; import type { TaskKind, TaskStatus, TaskPriority } from "@/types/note";
@@ -10,6 +10,7 @@ import UsageBadge from "@/components/UsageBadge.vue";
import NoteSweepPane from "@/components/NoteSweepPane.vue"; import NoteSweepPane from "@/components/NoteSweepPane.vue";
import StatusBadge from "@/components/StatusBadge.vue"; import StatusBadge from "@/components/StatusBadge.vue";
import PriorityBadge from "@/components/PriorityBadge.vue"; import PriorityBadge from "@/components/PriorityBadge.vue";
import ScrollSentinel from "@/components/ScrollSentinel.vue";
import GraphView from "@/views/GraphView.vue"; import GraphView from "@/views/GraphView.vue";
import { import {
FileText, FileText,
@@ -193,7 +194,7 @@ function onClickOutsideNewNote(e: MouseEvent) {
const ID_BATCH = 100; // IDs fetched per server round-trip const ID_BATCH = 100; // IDs fetched per server round-trip
const INITIAL_CONTENT = 50; // items loaded on first render const INITIAL_CONTENT = 50; // items loaded on first render
const CONTENT_PAGE = 24; // items loaded per sentinel trigger const CONTENT_PAGE = 24; // items loaded each time the end of the feed nears
const REFILL_THRESHOLD = 48; // fetch more IDs when queue drops below this const REFILL_THRESHOLD = 48; // fetch more IDs when queue drops below this
const items = ref<KnowledgeItem[]>([]); const items = ref<KnowledgeItem[]>([]);
@@ -214,11 +215,21 @@ const totalKnowledge = ref(0); // total matching items on server
const allIdsFetched = ref(false); // no more ID pages to fetch const allIdsFetched = ref(false); // no more ID pages to fetch
const idsFetching = ref(false); // ID batch request in-flight const idsFetching = ref(false); // ID batch request in-flight
const contentFetching = ref(false); // content batch request in-flight const contentFetching = ref(false); // content batch request in-flight
const sentinelVisible = ref(false); // updated by IntersectionObserver const moreFailed = ref(false); // the last page asked for did not load
const loading = computed(() => idsFetching.value || contentFetching.value); const loading = computed(() => idsFetching.value || contentFetching.value);
let fetchGen = 0; // incremented on each reset to invalidate stale responses let fetchGen = 0; // incremented on each reset to invalidate stale responses
const feedGen = ref(0); // fetchGen, readable by the template
// What the next page is keyed on: the feed it belongs to and how many of its ids
// have been loaded. Ids, not items: a batch can return fewer records than it
// asked for, and the feed must still move on. Empty once every id is loaded.
const nextCursor = computed(() =>
idQueue.value.length > 0 || !allIdsFetched.value
? `${feedGen.value}:${idOffset.value - idQueue.value.length}`
: "",
);
function buildFilterParams(): URLSearchParams { function buildFilterParams(): URLSearchParams {
const p = new URLSearchParams(); const p = new URLSearchParams();
@@ -244,7 +255,9 @@ async function fetchIdBatch(gen: number) {
idOffset.value += data.ids.length; idOffset.value += data.ids.length;
totalKnowledge.value = data.total; totalKnowledge.value = data.total;
if (!data.has_more) allIdsFetched.value = true; if (!data.has_more) allIdsFetched.value = true;
} catch { /* silent */ } } catch {
if (gen === fetchGen) moreFailed.value = true;
}
finally { if (gen === fetchGen) idsFetching.value = false; } finally { if (gen === fetchGen) idsFetching.value = false; }
} }
@@ -262,26 +275,38 @@ async function loadNextContent(gen: number, count: number) {
if (idQueue.value.length < REFILL_THRESHOLD && !allIdsFetched.value && !idsFetching.value) { if (idQueue.value.length < REFILL_THRESHOLD && !allIdsFetched.value && !idsFetching.value) {
fetchIdBatch(gen); fetchIdBatch(gen);
} }
} catch { /* silent */ } } catch {
// The ids go back to the front of the queue, so Try again asks for the
// same records rather than skipping past them.
if (gen === fetchGen) {
idQueue.value.unshift(...toLoad);
moreFailed.value = true;
}
}
finally { finally {
if (gen === fetchGen) contentFetching.value = false;
}
}
// The next page of the feed: more ids first when the queue has run dry.
async function loadMore() {
const gen = fetchGen;
moreFailed.value = false;
if (idQueue.value.length === 0) await fetchIdBatch(gen);
if (gen !== fetchGen) return; if (gen !== fetchGen) return;
contentFetching.value = false; await loadNextContent(gen, CONTENT_PAGE);
// Sentinel may still be visible if new items didn't push it off screen
await nextTick();
if (sentinelVisible.value && idQueue.value.length > 0 && gen === fetchGen) {
loadNextContent(gen, CONTENT_PAGE);
}
}
} }
async function reset() { async function reset() {
fetchGen++; fetchGen++;
feedGen.value = fetchGen;
const gen = fetchGen; const gen = fetchGen;
items.value = []; items.value = [];
idQueue.value = []; idQueue.value = [];
idOffset.value = 0; idOffset.value = 0;
totalKnowledge.value = 0; totalKnowledge.value = 0;
allIdsFetched.value = false; allIdsFetched.value = false;
moreFailed.value = false;
await fetchIdBatch(gen); await fetchIdBatch(gen);
if (gen !== fetchGen) return; if (gen !== fetchGen) return;
await loadNextContent(gen, INITIAL_CONTENT); await loadNextContent(gen, INITIAL_CONTENT);
@@ -294,23 +319,16 @@ async function fetchTags() {
} catch { /* silent */ } } catch { /* silent */ }
} }
async function resetAndReobserve() {
await reset();
await nextTick();
setupObserver();
}
function onSearchInput() { function onSearchInput() {
if (searchDebounce) clearTimeout(searchDebounce); if (searchDebounce) clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => resetAndReobserve(), 380); searchDebounce = setTimeout(() => reset(), 380);
} }
watch([activeType, sortMode], () => resetAndReobserve()); watch([activeType, sortMode], () => reset());
// Closing the sweep remounts the feed, and with it the scroll sentinel — a // Closing the sweep starts the feed over, so a note confirmed in the sweep is
// fresh element the old observer is not watching. Without this the list loads // shown as it now stands.
// its first page and then never loads another. watch(sweepActive, (open) => { if (!open) reset(); });
watch(sweepActive, (open) => { if (!open) resetAndReobserve(); }); watch(activeTag, () => { fetchCounts(); reset(); });
watch(activeTag, () => { fetchCounts(); resetAndReobserve(); });
// ─── Today bar ──────────────────────────────────────────────────────────────── // ─── Today bar ────────────────────────────────────────────────────────────────
@@ -377,24 +395,6 @@ function formatDate(iso: string): string {
return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }); return d.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" });
} }
// ─── Sentinel observer ────────────────────────────────────────────────────────
const sentinelEl = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;
function setupObserver() {
observer?.disconnect();
if (!sentinelEl.value) return;
observer = new IntersectionObserver(
([entry]) => {
sentinelVisible.value = entry.isIntersecting;
if (entry.isIntersecting) loadNextContent(fetchGen, CONTENT_PAGE);
},
{ root: null, rootMargin: "200px" }
);
observer.observe(sentinelEl.value);
}
// ─── Lifecycle ──────────────────────────────────────────────────────────────── // ─── Lifecycle ────────────────────────────────────────────────────────────────
onMounted(async () => { onMounted(async () => {
@@ -403,14 +403,11 @@ onMounted(async () => {
fetchTags(); fetchTags();
fetchCounts(); fetchCounts();
fetchTodayBar(); fetchTodayBar();
await nextTick();
setupObserver();
}); });
onUnmounted(() => { onUnmounted(() => {
document.removeEventListener('click', onClickOutsideNewNote); document.removeEventListener('click', onClickOutsideNewNote);
if (searchDebounce) clearTimeout(searchDebounce); if (searchDebounce) clearTimeout(searchDebounce);
observer?.disconnect();
}); });
</script> </script>
@@ -583,10 +580,7 @@ onUnmounted(() => {
</div> </div>
<!-- The whole feed stands down while the sweep is open: two answers <!-- The whole feed stands down while the sweep is open: two answers
to two different questions on one screen is neither. Wrapped to two different questions on one screen is neither. -->
rather than given an extra v-if branch, because the scroll
sentinel lives inside the grid and the observer must not be left
holding a ref to something that never renders. -->
<template v-if="!sweepActive"> <template v-if="!sweepActive">
<!-- Loading / empty --> <!-- Loading / empty -->
<div v-if="loading && items.length === 0" class="knowledge-empty">Loading…</div> <div v-if="loading && items.length === 0" class="knowledge-empty">Loading…</div>
@@ -675,10 +669,12 @@ onUnmounted(() => {
</div> </div>
</div> </div>
<!-- Sentinel — IntersectionObserver triggers next content batch --> <ScrollSentinel
<div ref="sentinelEl" class="scroll-sentinel"> :cursor="nextCursor"
<span v-if="contentFetching" class="sentinel-loading">Loading…</span> :loading="loading"
</div> :failed="moreFailed"
@more="loadMore"
/>
</div> </div>
</template> </template>
</div> </div>
@@ -1115,19 +1111,6 @@ onUnmounted(() => {
opacity: 0.85; opacity: 0.85;
} }
/* ── Sentinel ────────────────────────────────────────────── */
.scroll-sentinel {
grid-column: 1 / -1;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.sentinel-loading {
font-size: 0.8rem;
color: var(--fs-text-tertiary);
}
/* ── Graph panel ─────────────────────────────────────────── */ /* ── Graph panel ─────────────────────────────────────────── */
.graph-panel { .graph-panel {
width: 500px; width: 500px;
+2 -1
View File
@@ -40,6 +40,7 @@ import UsageBadge from "@/components/UsageBadge.vue";
import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight"; import { DEAD_WEIGHT_ADVICE } from "@/utils/deadWeight";
import { useToastStore } from "@/stores/toast"; import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { canWriteRecord } from "@/utils/permission"; import { canWriteRecord } from "@/utils/permission";
import { recordHref } from "@/utils/recordHref"; import { recordHref } from "@/utils/recordHref";
@@ -171,7 +172,7 @@ onMounted(load);
<div <div
v-if="insightHtml" v-if="insightHtml"
class="ld-insight markdown-body" class="ld-insight markdown-body"
v-html="insightHtml" v-html="insightHtml" v-record-refs
/> />
<p v-else class="ld-muted ld-empty"> <p v-else class="ld-muted ld-empty">
No detail was recorded — the claim above is the whole lesson. No detail was recorded — the claim above is the whole lesson.
+2 -1
View File
@@ -5,6 +5,7 @@ import type { NoteType } from "@/types/note";
import { useNotesStore } from "@/stores/notes"; import { useNotesStore } from "@/stores/notes";
import { useToastStore } from "@/stores/toast"; import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { useAssist, type NoteDraft } from "@/composables/useAssist"; import { useAssist, type NoteDraft } from "@/composables/useAssist";
import { useAutoSave } from "@/composables/useAutoSave"; import { useAutoSave } from "@/composables/useAutoSave";
import { useEditorGuards } from "@/composables/useEditorGuards"; import { useEditorGuards } from "@/composables/useEditorGuards";
@@ -439,7 +440,7 @@ onUnmounted(() => assist.clearSelection());
<div <div
v-else v-else
class="preview-pane prose" class="preview-pane prose"
v-html="renderedPreview" v-html="renderedPreview" v-record-refs
/> />
</Transition> </Transition>
</template> </template>
+11 -3
View File
@@ -3,6 +3,8 @@ import { onMounted, computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router"; import { useRoute, useRouter } from "vue-router";
import { useNotesStore } from "@/stores/notes"; import { useNotesStore } from "@/stores/notes";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { recordHref } from "@/utils/recordHref";
import { relativeTime } from "@/composables/useRelativeTime"; import { relativeTime } from "@/composables/useRelativeTime";
import { apiPost, apiGet, apiPatch } from "@/api/client"; import { apiPost, apiGet, apiPatch } from "@/api/client";
import type { Note } from "@/types/note"; import type { Note } from "@/types/note";
@@ -14,7 +16,12 @@ import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next";
const route = useRoute(); const route = useRoute();
const router = useRouter(); const router = useRouter();
const store = useNotesStore(); const store = useNotesStore();
const backlinks = ref<{ type: string; id: number; title: string }[]>([]); /** What links here, and how: a `[[title]]` wikilink or a `#N` reference in a
* body or work log. */
const backlinks = ref<{
type: string; id: number; title: string;
is_task?: boolean; note_type?: string; via?: "wikilink" | "reference";
}[]>([]);
const converting = ref(false); const converting = ref(false);
const showShare = ref(false); const showShare = ref(false);
@@ -259,7 +266,7 @@ async function convertToTask() {
<div <div
class="body prose" class="body prose"
:class="{ 'prose--checklist': isListNote }" :class="{ 'prose--checklist': isListNote }"
v-html="renderedBody" v-html="renderedBody" v-record-refs
@click="onBodyClick" @click="onBodyClick"
@change="onBodyChange" @change="onBodyChange"
></div> ></div>
@@ -274,7 +281,8 @@ async function convertToTask() {
<router-link <router-link
v-for="link in backlinks" v-for="link in backlinks"
:key="`${link.type}-${link.id}`" :key="`${link.type}-${link.id}`"
:to="`/${link.type === 'note' ? 'notes' : 'tasks'}/${link.id}`" :to="recordHref({ id: link.id, is_task: link.is_task ?? link.type === 'task', note_type: link.note_type })"
:title="link.via === 'reference' ? `Cites #${noteId} in its text` : `Links here by title`"
class="backlink-card" class="backlink-card"
> >
<span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span> <span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
+29 -3
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue"; import { ref, computed, onMounted, watch, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router"; import { useRoute, useRouter } from "vue-router";
import { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client"; import { apiGet, apiPatch, apiDelete, apiPost, apiPut, apiErrorMessage } from "@/api/client";
import { useAuthStore } from "@/stores/auth"; import { useAuthStore } from "@/stores/auth";
@@ -7,6 +7,7 @@ import { useToastStore } from "@/stores/toast";
import { useTasksStore } from "@/stores/tasks"; import { useTasksStore } from "@/stores/tasks";
import { relativeTime } from "@/composables/useRelativeTime"; import { relativeTime } from "@/composables/useRelativeTime";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import ShareDialog from "@/components/ShareDialog.vue"; import ShareDialog from "@/components/ShareDialog.vue";
import KindBadge from "@/components/KindBadge.vue"; import KindBadge from "@/components/KindBadge.vue";
import ProjectStatusBadge from "@/components/ProjectStatusBadge.vue"; import ProjectStatusBadge from "@/components/ProjectStatusBadge.vue";
@@ -585,8 +586,27 @@ async function saveForgePin() {
} }
} }
/** `?milestone=N` opens the board at that milestone: the Tasks tab, the
* milestone expanded and scrolled into view, its header focused. This is
* where a `milestone N` reference in any body leads. */
async function focusMilestoneFromRoute() {
const id = Number(route.query.milestone);
if (!id || !milestones.value.some((m) => m.id === id)) return;
activeTab.value = "tasks";
collapsedMilestones.value.delete(id);
await nextTick();
const header = document.querySelector<HTMLElement>(
`[data-milestone-id="${id}"] .milestone-header`,
);
header?.scrollIntoView({ block: "start", behavior: "smooth" });
header?.focus({ preventScroll: true });
}
watch(() => route.query.milestone, () => void focusMilestoneFromRoute());
onMounted(async () => { onMounted(async () => {
await loadProject(); await loadProject();
void focusMilestoneFromRoute();
loadTasks(); loadTasks();
loadNotes(); loadNotes();
loadDesignSystems(); loadDesignSystems();
@@ -985,9 +1005,15 @@ async function confirmDelete() {
</div> </div>
</div> </div>
<div v-for="group in milestoneGroups" :key="group.milestone?.id ?? 'unassigned'" class="milestone-group"> <div
v-for="group in milestoneGroups"
:key="group.milestone?.id ?? 'unassigned'"
class="milestone-group"
:data-milestone-id="group.milestone?.id"
>
<div <div
class="milestone-header" class="milestone-header"
tabindex="-1"
:class="{ clickable: renamingMilestoneId !== group.milestone?.id }" :class="{ clickable: renamingMilestoneId !== group.milestone?.id }"
:aria-expanded="!collapsedMilestones.has(groupKey(group))" :aria-expanded="!collapsedMilestones.has(groupKey(group))"
@click="renamingMilestoneId !== group.milestone?.id && toggleMilestoneCollapse(groupKey(group))" @click="renamingMilestoneId !== group.milestone?.id && toggleMilestoneCollapse(groupKey(group))"
@@ -1050,7 +1076,7 @@ async function confirmDelete() {
:class="['ms-plan-rendered', 'markdown-body', :class="['ms-plan-rendered', 'markdown-body',
{ 'ms-plan-clamped': isPlanClamped(group.milestone) }]" { 'ms-plan-clamped': isPlanClamped(group.milestone) }]"
@click="startEditPlan(group.milestone.id, group.milestone.body)" @click="startEditPlan(group.milestone.id, group.milestone.body)"
v-html="renderMarkdown(group.milestone.body || '')" v-html="renderMarkdown(group.milestone.body || '')" v-record-refs
></div> ></div>
<button <button
v-if="isPlanLong(group.milestone)" v-if="isPlanLong(group.milestone)"
+126 -53
View File
@@ -9,8 +9,10 @@ import { apiGet, apiPost, apiPut, apiDelete, listGroups, createGroup, deleteGrou
import type { User } from "@/types/auth"; import type { User } from "@/types/auth";
import PaginationBar from "@/components/PaginationBar.vue"; import PaginationBar from "@/components/PaginationBar.vue";
import MomentsSettings from "@/components/MomentsSettings.vue"; import MomentsSettings from "@/components/MomentsSettings.vue";
import ReverseProxySettings from "@/components/ReverseProxySettings.vue";
import ReplyShapesSettings from "@/components/ReplyShapesSettings.vue"; import ReplyShapesSettings from "@/components/ReplyShapesSettings.vue";
import BackupScheduleSettings from "@/components/BackupScheduleSettings.vue"; import BackupScheduleSettings from "@/components/BackupScheduleSettings.vue";
import RestoreBackupDialog from "@/components/RestoreBackupDialog.vue";
import { formatBytes } from "@/utils/bytes"; import { formatBytes } from "@/utils/bytes";
import { fmtDate, fmtLogStamp } from "@/utils/dateFormat"; import { fmtDate, fmtLogStamp } from "@/utils/dateFormat";
import { fetchVersion, type VersionPayload } from "@/api/version"; import { fetchVersion, type VersionPayload } from "@/api/version";
@@ -170,6 +172,42 @@ const kbReplyRuleThreshold = ref("0.8");
// is raising its bar, which discards the surface's best candidates along with // is raising its bar, which discards the surface's best candidates along with
// its worst. A budget keeps the top of the ranking and drops the tail. // its worst. A budget keeps the top of the ranking and drops the tail.
const kbWritePathTopK = ref("3"); const kbWritePathTopK = ref("3");
// The most one hook call may inject, in characters (hook_payload.DEFAULT_BUDGET).
const kbHookBudget = ref("4500");
// How often a record found by resemblance alone may speak, as a percent of
// cues that match nothing in particular (cue_gate.RATE_DEFAULT).
const kbCueGateRate = ref("10");
// GatedSurface — one row of /api/retrieval/gate.
interface GatedSurface {
surface: string;
gates: string;
bar: number | null;
sample: number;
calls: number;
fired: number;
days: number;
unreadable?: boolean;
}
const gatedSurfaces = ref<GatedSurface[]>([]);
const gateMinSample = ref(20);
function gateSummary(g: GatedSurface): string {
if (g.unreadable) return "unreadable right now";
const spoke = g.calls ? `spoke on ${g.fired} of ${g.calls} calls in ${g.days} days` : "no gated calls yet";
if (g.bar === null) return `learning (${g.sample} of ${gateMinSample.value} cues), silent until then; ${spoke}`;
return `bar ${g.bar.toFixed(2)} from your last ${g.sample} cues; ${spoke}`;
}
async function loadGate() {
try {
const res = await apiGet<{ surfaces: GatedSurface[]; min_sample: number }>("/api/retrieval/gate");
gatedSurfaces.value = res.surfaces ?? [];
gateMinSample.value = res.min_sample ?? 20;
} catch {
gatedSurfaces.value = [];
}
}
const kbRuleHintTopK = ref("5"); const kbRuleHintTopK = ref("5");
const kbToolRuleTopK = ref("5"); const kbToolRuleTopK = ref("5");
const kbPromptRuleTopK = ref("3"); const kbPromptRuleTopK = ref("3");
@@ -383,6 +421,13 @@ async function saveKbInject() {
const prK = asK(kbPromptRuleTopK.value, 3); const prK = asK(kbPromptRuleTopK.value, 3);
const ryK = asK(kbReplyRuleTopK.value, 1); const ryK = asK(kbReplyRuleTopK.value, 1);
kbWritePathTopK.value = String(wpK); kbWritePathTopK.value = String(wpK);
// Clamped as the server clamps it (hook_payload.HARD_MAX): Claude Code shows
// a hook's context past its cap only as a short preview.
const budget = Math.min(7500, Math.max(1000, Math.floor(Number(kbHookBudget.value) || 4500)));
kbHookBudget.value = String(budget);
// Clamped as the server clamps it (cue_gate.RATE_MIN / RATE_MAX).
const gateRate = Math.min(50, Math.max(1, Math.floor(Number(kbCueGateRate.value) || 10)));
kbCueGateRate.value = String(gateRate);
kbRuleHintTopK.value = String(rhK); kbRuleHintTopK.value = String(rhK);
kbToolRuleTopK.value = String(trK); kbToolRuleTopK.value = String(trK);
kbPromptRuleTopK.value = String(prK); kbPromptRuleTopK.value = String(prK);
@@ -431,6 +476,8 @@ async function saveKbInject() {
// change the OPERATOR made — which is the one entry the model must not // change the OPERATOR made — which is the one entry the model must not
// quietly tune back. // quietly tune back.
kb_writepath_top_k: String(wpK), kb_writepath_top_k: String(wpK),
kb_hook_budget_chars: String(budget),
kb_cue_gate_rate: String(gateRate),
kb_rulehint_top_k: String(rhK), kb_rulehint_top_k: String(rhK),
kb_toolrule_top_k: String(trK), kb_toolrule_top_k: String(trK),
kb_promptrule_top_k: String(prK), kb_promptrule_top_k: String(prK),
@@ -452,6 +499,7 @@ async function saveKbInject() {
// the operator is looking at it to confirm. // the operator is looking at it to confirm.
await loadTuningHistory(); await loadTuningHistory();
await loadSurfaces(); await loadSurfaces();
await loadGate();
} catch { } catch {
toastStore.show('Failed to save auto-inject settings', 'error'); toastStore.show('Failed to save auto-inject settings', 'error');
} finally { } finally {
@@ -467,7 +515,7 @@ const confirmNewPassword = ref("");
const changingPassword = ref(false); const changingPassword = ref(false);
const invalidatingSessions = ref(false); const invalidatingSessions = ref(false);
const exporting = ref(false); const exporting = ref(false);
const restoring = ref(false); const showRestore = ref(false);
// Backup, export and restore walk the whole store, so they are slow BY DESIGN // Backup, export and restore walk the whole store, so they are slow BY DESIGN
// and the client's ordinary 30s default would cut them off mid-work. They are // and the client's ordinary 30s default would cut them off mid-work. They are
// still bounded — every wait has a deadline, not necessarily a short one — and // still bounded — every wait has a deadline, not necessarily a short one — and
@@ -509,7 +557,6 @@ async function copyCommit() {
commitCopied.value = true; commitCopied.value = true;
setTimeout(() => { commitCopied.value = false; }, 2000); setTimeout(() => { commitCopied.value = false; }, 2000);
} }
const restoreFileInput = ref<HTMLInputElement | null>(null);
// Migrate stored "admin" → "config"; unknown tabs fall back to "general" // Migrate stored "admin" → "config"; unknown tabs fall back to "general"
const VALID_TABS = new Set(["general", "account", "notifications", "integrations", "data", "apikeys", "config", "users", "logs", "groups", "areas", "platforms"]); const VALID_TABS = new Set(["general", "account", "notifications", "integrations", "data", "apikeys", "config", "users", "logs", "groups", "areas", "platforms"]);
@@ -856,6 +903,12 @@ onMounted(async () => {
if (allSettings.kb_writepath_threshold !== undefined) { if (allSettings.kb_writepath_threshold !== undefined) {
kbWritePathThreshold.value = allSettings.kb_writepath_threshold; kbWritePathThreshold.value = allSettings.kb_writepath_threshold;
} }
if (allSettings.kb_hook_budget_chars !== undefined) {
kbHookBudget.value = allSettings.kb_hook_budget_chars;
}
if (allSettings.kb_cue_gate_rate !== undefined) {
kbCueGateRate.value = allSettings.kb_cue_gate_rate;
}
if (allSettings.kb_writepath_top_k !== undefined) { if (allSettings.kb_writepath_top_k !== undefined) {
kbWritePathTopK.value = allSettings.kb_writepath_top_k; kbWritePathTopK.value = allSettings.kb_writepath_top_k;
} else if (allSettings.kb_autoinject_top_k !== undefined) { } else if (allSettings.kb_autoinject_top_k !== undefined) {
@@ -878,6 +931,7 @@ onMounted(async () => {
} }
await loadTuningHistory(); await loadTuningHistory();
await loadSurfaces(); await loadSurfaces();
await loadGate();
if (allSettings.kb_duplicate_threshold_snippet !== undefined) { if (allSettings.kb_duplicate_threshold_snippet !== undefined) {
kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet; kbDupThresholdSnippet.value = allSettings.kb_duplicate_threshold_snippet;
} }
@@ -1079,10 +1133,6 @@ async function exportNotes(format: "markdown" | "json") {
} }
} }
function triggerRestoreUpload() {
restoreFileInput.value?.click();
}
async function saveNotifications() { async function saveNotifications() {
savingNotifications.value = true; savingNotifications.value = true;
notificationsSaved.value = false; notificationsSaved.value = false;
@@ -1279,42 +1329,6 @@ async function runDbMaintenanceNow() {
} }
} }
async function handleRestoreFile(event: Event) {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
restoring.value = true;
try {
// The scheduled backup's .tar goes up as it is; the JSON download is
// parsed first so a damaged file fails here, before the upload.
const isTar = file.name.toLowerCase().endsWith(".tar");
const res = await fetch("/api/admin/restore", {
method: "POST",
headers: { "Content-Type": isTar ? "application/x-tar" : "application/json" },
body: isTar ? file : JSON.stringify(JSON.parse(await file.text())),
signal: bulkDeadline(),
});
if (res.status === 413) {
throw new Error(
"the file is bigger than the web upload allows. Restore it with " +
"`python -m grimoire.restore <file>` inside the Grimoire container instead.",
);
}
if (!res.ok) {
const body = await res.json().catch(() => ({ error: `Error ${res.status}` }));
throw new Error((body as Record<string, string>).error || `Error ${res.status}`);
}
const result = await res.json();
toastStore.show(
`Restored ${result.stats?.users ?? 0} users, ${result.stats?.notes ?? 0} notes, ${result.stats?.conversations ?? 0} conversations`
);
} catch (e) {
toastStore.show("Restore failed: " + (e as Error).message, "error");
} finally {
restoring.value = false;
if (restoreFileInput.value) restoreFileInput.value.value = "";
}
}
async function testSearch() { async function testSearch() {
const q = searchQuery.value.trim(); const q = searchQuery.value.trim();
if (!q) return; if (!q) return;
@@ -1693,7 +1707,7 @@ async function deleteUser(userId: number) {
class="fs-input input" class="fs-input input"
style="max-width: 8rem" style="max-width: 8rem"
/> />
<p class="field-hint">Ceiling on titles surfaced at once (1–10).</p> <p class="field-hint">How many records each prompt is ranked against (1–10); at most two are shown, and only past the resemblance gate below.</p>
</div> </div>
<div class="checkbox-field"> <div class="checkbox-field">
<label> <label>
@@ -1734,6 +1748,45 @@ async function deleteUser(userId: number) {
location, not by resemblance. location, not by resemblance.
</p> </p>
</div> </div>
<div class="field">
<label for="kb-hook-budget">Most context one hook may add (characters)</label>
<input
id="kb-hook-budget"
v-model="kbHookBudget"
type="number"
min="1000"
max="7500"
step="500"
class="fs-input input"
style="max-width: 8rem"
/>
<p class="field-hint">Everything Grimoire adds beside one prompt, edit or command, from 1,000 to 7,500 characters. Rules go in first, then the reply shape, then records, until this is spent; whatever is left out can arrive on a later call. Claude Code shows a hook's context past its cap only as a short preview, so the ceiling stays well under it.</p>
</div>
<div class="field">
<label for="kb-cue-gate-rate">How often records found by resemblance may speak (%)</label>
<input
id="kb-cue-gate-rate"
v-model="kbCueGateRate"
type="number"
min="1"
max="50"
step="1"
class="fs-input input"
style="max-width: 8rem"
/>
<p class="field-hint">
A record or preference matched only by wording is shown when the message
resembles it better than all but this share of your recent messages did:
at most two lines, and none until {{ gateMinSample }} messages have been seen.
</p>
<ul v-if="gatedSurfaces.length" class="gate-readout">
<li v-for="g in gatedSurfaces" :key="g.surface">
<span class="tuning-surface">{{ g.surface }}</span>
<span class="gate-gates">{{ g.gates }}</span>
<span class="gate-state">{{ gateSummary(g) }}</span>
</li>
</ul>
</div>
<div class="field"> <div class="field">
<label for="kb-writepath-topk">Max prior-art lines per edit</label> <label for="kb-writepath-topk">Max prior-art lines per edit</label>
<input <input
@@ -2429,17 +2482,11 @@ async function deleteUser(userId: number) {
<button class="btn-secondary" @click="exportData('full')" :disabled="exporting"> <button class="btn-secondary" @click="exportData('full')" :disabled="exporting">
{{ exporting ? "Exporting..." : "Full Backup" }} {{ exporting ? "Exporting..." : "Full Backup" }}
</button> </button>
<button class="btn-secondary btn-warn" @click="triggerRestoreUpload" :disabled="restoring"> <button class="btn-secondary btn-warn" @click="showRestore = true">
{{ restoring ? "Restoring..." : "Restore from Backup" }} Restore from Backup
</button> </button>
<input
ref="restoreFileInput"
type="file"
accept=".json,.tar"
class="hidden-file-input"
@change="handleRestoreFile"
/>
</div> </div>
<RestoreBackupDialog v-if="showRestore" @close="showRestore = false" />
</section> </section>
<section class="settings-section full-width"> <section class="settings-section full-width">
<h2>Scheduled backups</h2> <h2>Scheduled backups</h2>
@@ -2710,6 +2757,16 @@ async function deleteUser(userId: number) {
<div v-else class="empty-msg">Nothing asked yet.</div> <div v-else class="empty-msg">Nothing asked yet.</div>
</section> </section>
<section class="settings-section full-width">
<h2>Reverse proxy</h2>
<p class="section-desc">
How many proxies a request passes through before it reaches Grimoire. Sign-in rate
limits and the audit log key on the visitor's address, read through this count; if it
is too low, every visitor reads as the proxy and one run of bad sign-ins blocks everyone.
</p>
<ReverseProxySettings />
</section>
<section class="settings-section full-width"> <section class="settings-section full-width">
<h2>Application URL</h2> <h2>Application URL</h2>
<p class="section-desc"> <p class="section-desc">
@@ -3597,7 +3654,6 @@ async function deleteUser(userId: number) {
flex-wrap: wrap; flex-wrap: wrap;
gap: 0.5rem; gap: 0.5rem;
} }
.hidden-file-input { display: none; }
/* Checkboxes */ /* Checkboxes */
.checkbox-field { margin-bottom: 1rem; } .checkbox-field { margin-bottom: 1rem; }
@@ -4294,6 +4350,23 @@ async function deleteUser(userId: number) {
font-family: var(--fs-font-mono); font-family: var(--fs-font-mono);
color: var(--fs-text-primary); color: var(--fs-text-primary);
} }
.gate-readout {
list-style: none;
margin: var(--fs-space-2) 0 0;
padding: 0;
display: grid;
gap: var(--fs-space-1);
font-size: 0.8rem;
}
.gate-readout li {
display: flex;
flex-wrap: wrap;
gap: var(--fs-space-2);
}
.gate-gates,
.gate-state {
color: var(--fs-text-secondary);
}
.tuning-dial, .tuning-dial,
.tuning-move { .tuning-move {
color: var(--fs-text-secondary); color: var(--fs-text-secondary);
+2 -1
View File
@@ -10,6 +10,7 @@ import {
import { useToastStore } from "@/stores/toast"; import { useToastStore } from "@/stores/toast";
import ConfirmDialog from "@/components/ConfirmDialog.vue"; import ConfirmDialog from "@/components/ConfirmDialog.vue";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { canWriteRecord } from "@/utils/permission"; import { canWriteRecord } from "@/utils/permission";
const route = useRoute(); const route = useRoute();
@@ -185,7 +186,7 @@ async function confirmDelete() {
<section v-if="snippet.snippet.notes" class="notes"> <section v-if="snippet.snippet.notes" class="notes">
<h2 class="notes-heading">Notes</h2> <h2 class="notes-heading">Notes</h2>
<div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" /> <div class="prose" v-html="renderMarkdown(snippet.snippet.notes)" v-record-refs />
</section> </section>
<div v-if="snippet.tags.length" class="tag-row"> <div v-if="snippet.tags.length" class="tag-row">
+2 -1
View File
@@ -5,6 +5,7 @@ import { useTasksStore } from "@/stores/tasks";
import { useNotesStore } from "@/stores/notes"; import { useNotesStore } from "@/stores/notes";
import { useToastStore } from "@/stores/toast"; import { useToastStore } from "@/stores/toast";
import { renderMarkdown } from "@/utils/markdown"; import { renderMarkdown } from "@/utils/markdown";
import { vRecordRefs } from "@/directives/recordRefs";
import { useAssist } from "@/composables/useAssist"; import { useAssist } from "@/composables/useAssist";
import { useAutoSave } from "@/composables/useAutoSave"; import { useAutoSave } from "@/composables/useAutoSave";
import { useEditorGuards } from "@/composables/useEditorGuards"; import { useEditorGuards } from "@/composables/useEditorGuards";
@@ -538,7 +539,7 @@ useEditorGuards(dirty, save);
<div <div
v-show="showPreview" v-show="showPreview"
class="preview-pane prose" class="preview-pane prose"
v-html="renderedPreview" v-html="renderedPreview" v-record-refs
/> />
</template> </template>
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "name": "grimoire",
"description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).",
"version": "2026.10.26.2029", "version": "2026.11.23.2305",
"author": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+4 -3
View File
@@ -15,7 +15,7 @@ another one means adding files, not moving or rewriting any.
|---|---|---| |---|---|---|
| **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. | | **The skills** | `plugin/skills/*/SKILL.md` | Agent Skills (the open SKILL.md format). They state every Grimoire reflex in full and name no client. `tests/test_guidance_ownership.py` fails if a skill names a particular client, or references anything outside its own folder. Every client package ships this folder verbatim. |
| **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. | | **The MCP server** | `<base URL>/mcp` | HTTP, `Authorization: Bearer <fmcp_ key>`. Its `_INSTRUCTIONS` is a client-neutral orientation — the workflow across tools (≤1,600 chars); each tool's description carries its contract; in-band responses (`placement`, `report_back`, `systems_hint`, the duplicate gate, the guessed-id refusal) fire in every client. |
| **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule or — when the turn closed a task — for missing completion sections). | | **The adapter API** | `<base URL>/api/plugin/*` | Endpoints any client's hooks can call with the same key. `GET`, so read scope is enough: `context` (live session state), `retrieve` (rules, preferences and notes for a message), `prior-art` (records and shape-ledger hints for code being written), `tool-rules` (rules for a command about to run), `moment-tools` (which tools reach a mounted moment), `shape-check` (definitions written this turn that nobody has judged), `claim-session` / `release-session` (task claims), `write-scope` (which project a pending write lands in, and whether this session may make it), `processes` (stored Processes to expose as skills). `POST`, so write scope: `moment` (rules mounted on the moments a tool call reaches), `rule-opened` (a rule was read), `reply-rules` (the finished reply, held for an unopened rule set to hold or — when the turn closed a task — for missing completion sections). |
| **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. | | **The API key** | Grimoire → Settings → MCP Access | One `fmcp_` key per install. Write scope covers the MCP tools and every hook; a read key runs only the `GET` hooks. |
## Added by each client ## Added by each client
@@ -39,9 +39,10 @@ another one means adding files, not moving or rewriting any.
| `hooks/grimoire_prior_art.sh` | PreToolUse on editor writes: `GET /api/plugin/prior-art`. | | `hooks/grimoire_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_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. | | `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). | | `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason; PostToolUse on `enter_project` remembers the project a session without one entered. |
| `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session). |
| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. | | `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. |
| `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check`; blocks once, with the reason the server returns, so the agent judges what it built. | | `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.written.ids` ledger) to `GET /api/plugin/shape-check` and keeps the `note` it returns for the next prompt, which `grimoire_autoinject.sh` carries as `carry`, so the agent judges what it built. Never blocks. |
| `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. | | `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. |
| `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. | | `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. |
| `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. | | `hooks/grimoire_claim_session.sh` | PostToolUse on `update_task` / `add_task_log`: `GET /api/plugin/claim-session`, so the task comes back after a compaction. |
+25 -7
View File
@@ -79,11 +79,27 @@ On install you'll be asked for:
message, as a short menu of titles and matched passages. message, as a short menu of titles and matched passages.
- `hooks/hooks.json` → PreToolUse hook on `Bash` (`hooks/grimoire_tool_rules.sh`) - `hooks/hooks.json` → PreToolUse hook on `Bash` (`hooks/grimoire_tool_rules.sh`)
→ `GET /api/plugin/tool-rules`: the rules that match the command about to run. → `GET /api/plugin/tool-rules`: the rules that match the command about to run.
- `hooks/hooks.json` → PreToolUse hook on editor writes, `Bash` and Grimoire's
tools (`hooks/grimoire_project_fence.sh`) → `GET /api/plugin/write-scope`:
holds a session to its own project. A session belongs to the project its
starting directory resolves to (a `.grimoire` marker, else the git remote's
binding), or, started outside any, to the first project it enters. Editing
another project's files, a git commit, push, merge, rebase, pull, tag or
reset in its repo (from `git -C`, after `cd`, or in a worktree of it), and a
Grimoire write that lands in another project each stop on a permission
prompt naming that project, in every permission mode. Filing an issue there
(`create_task(kind="issue")`) and every read go ahead. An edit in the
session's own repo never calls the server. It can't see a non-git shell
write into another repo (`sed -i`, a redirect), but it fences that repo's
commit and push. When the instance doesn't answer, the act goes ahead and
the hook says so once per outage.
- `hooks/hooks.json` → PreToolUse hook on every tool (`hooks/grimoire_moment.sh`) - `hooks/hooks.json` → PreToolUse hook on every tool (`hooks/grimoire_moment.sh`)
→ `POST /api/plugin/moment`: the rules mounted on the moments the call → `POST /api/plugin/moment`: the rules mounted on the moments the call
reaches. It skips tools that `GET /api/plugin/moment-tools` says reach reaches. It skips tools that `GET /api/plugin/moment-tools` says reach
nothing mounted, and Grimoire's own tools, whose responses carry nothing mounted, and Grimoire's own tools, whose responses carry
`moment_rules`. `moment_rules`. A rule set to enforce refuses the call (every time it is
reached); one set to hold denies it once until it has been read, never on a
file edit.
- `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`, - `hooks/hooks.json` → PostToolUse hooks on Grimoire's `get_rule`,
`rule_outcome`, `update_task` and `add_task_log`: they keep the session's `rule_outcome`, `update_task` and `add_task_log`: they keep the session's
ledgers of rules opened and acted on (`get_rule` also reports to ledgers of rules opened and acted on (`get_rule` also reports to
@@ -101,7 +117,8 @@ On install you'll be asked for:
duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`. duplicate arm and the outage line are shared in `hooks/grimoire_defs.sh`.
- `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the - `hooks/hooks.json` → Stop hook (`hooks/grimoire_reply_check.sh`): sends the
reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it reply that ends the turn to `POST /api/plugin/reply-rules`, which holds it
once for an unopened rule mounted on the reply moments or matching the reply. once for an unopened rule set to hold (or enforce) that is mounted on the
reply moments or matches the reply. A rule set to inform never holds it.
When the turn closed a Grimoire task (`update_task`/`create_task` with status When the turn closed a Grimoire task (`update_task`/`create_task` with status
done), the same request has the server check the reply for the completion done), the same request has the server check the reply for the completion
sections — where the work sits, what needs you, what comes next. If they are sections — where the work sits, what needs you, what comes next. If they are
@@ -113,11 +130,12 @@ On install you'll be asked for:
write hooks note every definition a write names (and every new file) in a write hooks note every definition a write names (and every new file) in a
session ledger; at the end of the turn this sends them to session ledger; at the end of the turn this sends them to
`GET /api/plugin/shape-check`, which answers with the ones nobody has judged. `GET /api/plugin/shape-check`, which answers with the ones nobody has judged.
If any are, it blocks once with the server's reason, asking the agent that If any are, the server's note rides the next prompt (the prompt hook sends it
wrote them to say what each is — reusable (record a snippet), an instance or as `carry`), asking the agent that wrote them to say what each is — reusable
variant of one, or a one-off — in one `classify_shapes` call. Same discipline (record a snippet), an instance or variant of one, or a one-off — in one
as the report check: never twice, never without a recorded check. Outcomes `classify_shapes` call. It never holds the reply; the stop after that prompt
land under category `plugin`, action `shape_check`. records whether the lines were judged. Outcomes land under category
`plugin`, action `shape_check`.
- `skills/` → the universal process-skills, surfaced by description match. - `skills/` → the universal process-skills, surfaced by description match.
- `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync` - `hooks/grimoire_sync_processes.sh` (a 2nd SessionStart hook) + the `/grimoire:sync`
command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire command → generate `~/.claude/skills/grimoire-proc-*` stubs from your Grimoire
+1
View File
@@ -191,6 +191,7 @@ while IFS= read -r rel_path; do
reached=1 reached=1
body=$(curl -fsS --max-time 8 \ body=$(curl -fsS --max-time 8 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; } "${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
# A call that was owed and didn't come back is said, once per outage — # A call that was owed and didn't come back is said, once per outage —
# shared marker with the pre-write hook, so one outage is one # shared marker with the pre-write hook, so one outage is one
+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}" [ -n "$rule_seen" ] && exclude_q="${exclude_q}&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown. # What the session actually OPENED, as against what it was shown.
exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")" exclude_q="${exclude_q}$(grimoire_held_query "$rule_state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
exclude_q="${exclude_q}&session_id=${safe_sid}"
# Which reply shapes it already holds in full: the core is # Which reply shapes it already holds in full: the core is
# sent whole once, and as its one-line reminder on every later turn. # sent whole once, and as its one-line reminder on every later turn.
shapefile=$(grimoire_shapes_file "$safe_sid") shapefile=$(grimoire_shapes_file "$safe_sid")
@@ -132,10 +134,25 @@ if [ -n "$session_id" ]; then
[ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}" [ -n "$shapes_seen" ] && exclude_q="${exclude_q}&shapes_seen=${shapes_seen}"
fi fi
# What the last stop left for this prompt: the definitions its turn wrote
# that nobody has judged (grimoire_shape_check.sh). Carried to the server, which
# fits it into the one payload, and removed once the server has answered.
carry_q=""
carry_file=""
if [ -n "$session_id" ]; then
carry_file="${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}.note"
if [ -s "$carry_file" ]; then
carry_enc=$(head -c 2000 "$carry_file" 2>/dev/null | grimoire_urlenc) || carry_enc=""
[ -n "$carry_enc" ] && carry_q="&carry=${carry_enc}"
fi
fi
body=$(curl -fsS --max-time 5 \ body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}" 2>/dev/null) || exit 0 -H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/retrieve?q=${q_enc}${ctx_q}${repo_q}${exclude_q}${carry_q}" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0 [ -n "$body" ] || exit 0
[ -n "$carry_q" ] && rm -f "$carry_file" 2>/dev/null
body_flat=$(printf '%s' "$body" | grimoire_json_flat) body_flat=$(printf '%s' "$body" | grimoire_json_flat)
context=$(grimoire_json_pick "$body_flat" '.context') context=$(grimoire_json_pick "$body_flat" '.context')
+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 sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
curl -fsS --max-time 4 \ curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \ "${url%/}/api/plugin/claim-session?task_id=${task_id}&session_id=${sid_enc}" \
>/dev/null 2>&1 || true >/dev/null 2>&1 || true
exit 0 exit 0
+8
View File
@@ -868,6 +868,14 @@ grimoire_config() {
# garbage Bearer token and 401. Treat it as unset. # garbage Bearer token and 401. Treat it as unset.
case "$url" in *'${'*) url="" ;; esac case "$url" in *'${'*) url="" ;; esac
case "$token" in *'${'*) token="" ;; esac case "$token" in *'${'*) token="" ;; esac
# Sent as `X-Grimoire-Plugin` on every request. The server keeps it on each
# rule line it delivers, and counts a line toward a rule's open rate only
# when it is there: a plugin that sends it also reports every open, so a
# line without it is one whose opens were never going to be heard. The hooks
# that source this file read it, which shellcheck cannot see from here.
# shellcheck disable=SC2034
plugin_version=$(sed -n 's/^ *"version": *"\([^"]*\)".*/\1/p' \
"$(dirname "${BASH_SOURCE[0]}")/../.claude-plugin/plugin.json" 2>/dev/null | head -n 1)
[ -n "$url" ] && [ -n "$token" ] [ -n "$url" ] && [ -n "$token" ]
} }
+32 -1
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the # Grimoire — PreToolUse moment arm: rules MOUNTED on a moment arrive when the
# moment happens. # moment happens — beside the act, or, for a rule set to enforce or hold, in
# front of it.
# #
# The other PreToolUse arms search: they turn the act into a query and hope a # The other PreToolUse arms search: they turn the act into a query and hope a
# rule's words resemble it. A mount needs no resemblance. The operator said # rule's words resemble it. A mount needs no resemblance. The operator said
@@ -100,6 +101,7 @@ case "$stamp" in ''|*[!0-9]*) stamp=0 ;; esac
if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then if [ "$now" -eq 0 ] || [ $((now - stamp)) -gt 300 ]; then
listed=$(curl -fsS --max-time 3 \ listed=$(curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed="" "${url%/}/api/plugin/moment-tools" 2>/dev/null) || listed=""
{ {
printf '%s\n' "$now" printf '%s\n' "$now"
@@ -140,6 +142,7 @@ query="${repo_q}${ledger_q}"
query=${query#&} query=${query#&}
body=$(printf '%s' "$event" | curl -fsS --max-time 3 \ body=$(printf '%s' "$event" | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary @- \ --data-binary @- \
"${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/moment${query:+?$query}" 2>/dev/null) || exit 0
@@ -148,6 +151,34 @@ body_flat=$(printf '%s' "$body" | grimoire_json_flat)
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile" grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile" grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefile"
# ── The act itself: refused, held for one read, or let through ───────────
#
# The server decides and supplies the words (`decision`); this hook only
# carries them. A rule set to ENFORCE refuses the call every time it is
# reached — the operator drew that line, and it moves when they change the
# rule, not when the agent has read it. A rule set to HOLD asks for one read
# before the act, once per rule and under the session cap that the act
# checkpoint and the reply hold share, so a mis-set rule costs one round trip
# rather than a session that cannot move.
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
if [ -n "$d_reason" ]; then
case "$d_kind" in
enforce)
grimoire_json_deny PreToolUse "$d_reason"
exit 0
;;
hold)
if [ -n "$d_rule" ] \
&& grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$d_rule"; then
grimoire_json_deny PreToolUse "$d_reason"
exit 0
fi
;;
esac
fi
context=$(grimoire_json_pick "$body_flat" '.context') context=$(grimoire_json_pick "$body_flat" '.context')
[ -n "$context" ] || exit 0 [ -n "$context" ] || exit 0
grimoire_json_out PreToolUse "$context" grimoire_json_out PreToolUse "$context"
+3
View File
@@ -240,6 +240,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}" [ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown. # What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")" rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
fi fi
# Not `|| exit 0`: an unreachable instance must not discard a local finding # Not `|| exit 0`: an unreachable instance must not discard a local finding
@@ -249,6 +251,7 @@ fi
reached=1 reached=1
body=$(curl -fsS --max-time 5 \ body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; } "${url%/}/api/plugin/prior-art?path=${path_enc}&code=${code_enc}${repo_q}${exclude_q}${sync_exclude_q}${derive_exclude_q}${rule_exclude_q}${rulings_q}${shapes_q}" 2>/dev/null) || { body=""; reached=0; }
unreached_context="" unreached_context=""
if [ "$reached" = 1 ]; then if [ "$reached" = 1 ]; then
+246
View File
@@ -0,0 +1,246 @@
#!/usr/bin/env bash
# Grimoire — hold a session to its own project.
#
# A session belongs to the project its starting directory resolves to
# (CLAUDE_PROJECT_DIR: a `.grimoire` marker, else the git remote's binding). A
# session that starts outside any project belongs to the first project it
# enters. Toward any other project a session may read anything and file an
# issue. Every other write stops on a permission prompt naming the other
# project, so the operator decides:
# - editing a file in another project's repo (Write, Edit, MultiEdit,
# NotebookEdit);
# - a git command that changes history or a remote there (commit, push,
# merge, rebase, pull, cherry-pick, revert, tag, am, reset, worktree add),
# wherever it runs from: `git -C DIR`, `cd DIR && git …`, or the shell's
# current directory;
# - a Grimoire write that lands in another project.
#
# `ask`, not `deny`. Which projects a session may change is the operator's
# call, and `ask` puts it to them each time, in every permission mode,
# bypassPermissions included.
#
# The server says where an act lands (GET /api/plugin/write-scope). Two cases
# never reach it:
# - a directory that resolves the same way as the session's own, which is
# nearly every edit;
# - a tool named like a read (READ_PREFIXES in services/write_scope.py, held
# equal to FENCE_READ_PREFIXES below by tests/test_write_scope.py).
#
# What it can't see: a non-git write from the shell (`sed -i`, a redirect)
# into another repo. That repo's commit and push are still fenced.
#
# EXIT 0, ALWAYS. When the server doesn't answer, the act goes ahead and the
# hook says once per outage that it couldn't check.
#
# Run as PostToolUse on enter_project, it records the project a session
# without one has entered, and says nothing.
set -uo pipefail
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
FENCE_READ_PREFIXES="get_ list_ search find_ enter_project what_might_apply resolve_design_system"
FENCE_GIT_WRITES="commit push merge rebase pull cherry-pick revert tag am reset"
event=$(cat 2>/dev/null || true)
[ -n "$event" ] || exit 0
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
[ -n "$event_flat" ] || exit 0
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
hook_event=$(grimoire_json_pick "$event_flat" '.hook_event_name')
cwd=$(grimoire_json_pick "$event_flat" '.cwd')
# Its own directory, which no compaction sweeps: the project a session
# entered stays its project for the whole session.
state_dir="${TMPDIR:-/tmp}/grimoire-fence"
safe_sid=$(printf '%s' "${session_id:-none}" | tr -c 'A-Za-z0-9._-' '_')
entered_file="$state_dir/${safe_sid}.entered"
# ── PostToolUse on enter_project: remember the first project entered ─────
if [ "$hook_event" = "PostToolUse" ]; then
case "$tool_name" in
*__enter_project)
pid=$(grimoire_json_pick "$event_flat" '.tool_input.project_id' | tr -cd '0-9')
if [ -n "$pid" ] && [ -n "$session_id" ] && [ ! -s "$entered_file" ]; then
mkdir -p "$state_dir" 2>/dev/null || true
printf '%s' "$pid" > "$entered_file" 2>/dev/null || true
fi
;;
esac
exit 0
fi
# The nearest directory at or above $1 that exists. A Write may create the
# directories its file goes in.
fence_existing_dir() {
local d="$1" depth=0
while [ -n "$d" ] && [ ! -d "$d" ] && [ "$depth" -lt 40 ]; do
d=$(dirname -- "$d" 2>/dev/null) || return 0
depth=$((depth + 1))
done
[ -d "$d" ] && printf '%s' "$d"
}
# "DIR<TAB>SUBCOMMAND" for each git command in the shell command $1 that
# changes history or a remote, with DIR resolved from $2: `cd` moves it for
# the segments after, `git -C` for that one command. Segments split on ; && ||
# | and newlines, and a quoted separator inside a message splits too; the
# words after it are read as a command only if they start with cd or git.
fence_git_targets() {
printf '%s\n' "$1" | awk -v start="$2" -v home="${HOME:-}" -v writes="$FENCE_GIT_WRITES" '
function unq(w) { gsub(/^["\047(]+|["\047)]+$/, "", w); return w }
function at(base, p) {
if (p ~ /^\//) return p
if (p == "~") return home
if (p ~ /^~\//) return home substr(p, 2)
return base "/" p
}
BEGIN { dir = start; n = split(writes, w, " "); for (i = 1; i <= n; i++) iswrite[w[i]] = 1 }
{
line = $0
gsub(/&&|\|\||;|\|/, "\n", line)
m = split(line, segs, "\n")
for (s = 1; s <= m; s++) {
k = split(segs[s], t, /[ \t]+/)
i = 1
while (i <= k && (t[i] == "" || t[i] ~ /^[A-Za-z_][A-Za-z0-9_]*=/)) i++
if (i > k) continue
cmd = unq(t[i])
if (cmd == "cd") {
if (i + 1 <= k && t[i + 1] != "") dir = at(dir, unq(t[i + 1]))
continue
}
if (cmd != "git" && cmd !~ /\/git$/) continue
gdir = dir; i++
while (i <= k && t[i] ~ /^-/) {
if (t[i] == "-C" && i + 1 <= k) { gdir = at(gdir, unq(t[i + 1])); i += 2; continue }
if (t[i] == "-c" || t[i] == "--git-dir" || t[i] == "--work-tree") { i += 2; continue }
i++
}
if (i > k) continue
sub_ = unq(t[i])
if (sub_ == "worktree") { if (i + 1 <= k && unq(t[i + 1]) == "add") print gdir "\tworktree add"; continue }
if (sub_ in iswrite) print gdir "\t" sub_
}
}' 2>/dev/null || true
}
# The short scalar arguments of the MCP call, as a JSON object of strings:
# ids, kind, status, a repo url, and arrays of ids. Long text (bodies, code) is
# left out; nothing that says where a write lands is long.
fence_tool_input() {
printf '%s\n' "$event_flat" | awk -F'\t' '
function add(k, v) { if (!(k in seen)) { seen[k] = 1; order[++n] = k } }
$2 ~ /^\.tool_input\.[A-Za-z_]+$/ && $3 != "null" && length($3) <= 200 {
k = substr($2, 13); add(k); val[k] = "\"" $3 "\""
}
$2 ~ /^\.tool_input\.[A-Za-z_]+\[[0-9]+\]$/ && $3 != "null" && length($3) <= 200 {
k = substr($2, 13); sub(/\[.*$/, "", k); add(k)
# Tested before assigning: mawk creates arr[k] as soon as it is the
# target, so the test inside the assignment would always be true.
item = "\"" $3 "\""
if (k in arr) item = arr[k] "," item
arr[k] = item
}
END {
printf "{"
for (i = 1; i <= n; i++) {
k = order[i]
printf "%s\"%s\":%s", (i > 1 ? "," : ""), k, ((k in arr) ? "[" arr[k] "]" : val[k])
}
printf "}"
}' 2>/dev/null || printf '{}'
}
grimoire_config || exit 0
command -v curl >/dev/null 2>&1 || exit 0
project_dir=${CLAUDE_PROJECT_DIR:-$PWD}
session_scope=$(grimoire_scope_query "$project_dir")
entered=$(cat "$entered_file" 2>/dev/null | tr -cd '0-9')
# No project to hold the session to: started outside any, and entered none.
[ -n "$session_scope" ] || [ -n "$entered" ] || exit 0
# Each check this act needs: "SCOPE<TAB>ACT" for a directory, or a single
# "tool" line for a Grimoire call.
checks=""
case "$tool_name" in
Write|Edit|MultiEdit|NotebookEdit)
path=$(grimoire_json_pick "$event_flat" '.tool_input.file_path')
[ -n "$path" ] || path=$(grimoire_json_pick "$event_flat" '.tool_input.notebook_path')
[ -n "$path" ] || exit 0
case "$path" in /*) ;; *) path="${cwd:-$PWD}/$path" ;; esac
dir=$(fence_existing_dir "$(dirname -- "$path")")
[ -n "$dir" ] || exit 0
scope=$(grimoire_scope_query "$dir")
[ -n "$scope" ] && [ "$scope" != "$session_scope" ] || exit 0
checks=$(printf '%s\t%s' "$scope" "Editing a file in")
;;
Bash)
command=$(grimoire_json_pick "$event_flat" '.tool_input.command')
case "$command" in *git*) ;; *) exit 0 ;; esac
while IFS=$'\t' read -r gdir gsub; do
[ -n "$gdir" ] || continue
[ -d "$gdir" ] || continue
scope=$(grimoire_scope_query "$gdir")
[ -n "$scope" ] && [ "$scope" != "$session_scope" ] || continue
checks="${checks}${checks:+$'\n'}${scope}"$'\t'"git ${gsub} in"
done <<EOF
$(fence_git_targets "$command" "${cwd:-$PWD}")
EOF
[ -n "$checks" ] || exit 0
;;
mcp__*)
short=${tool_name##*__}
for prefix in $FENCE_READ_PREFIXES; do
case "$short" in "$prefix"*) exit 0 ;; esac
done
checks="tool"
;;
*) exit 0 ;;
esac
base="${url%/}/api/plugin/write-scope?"
[ -n "$session_scope" ] && base="${base}${session_scope}&"
[ -n "$entered" ] && base="${base}fallback_project_id=${entered}&"
fence_unreached() {
local marker="$state_dir/${safe_sid}.fence.unreached" now last
mkdir -p "$state_dir" 2>/dev/null || true
now=$(date +%s 2>/dev/null) || now=0
if [ -f "$marker" ]; then
last=$(cat "$marker" 2>/dev/null) || last=0
case "$last" in ''|*[!0-9]*) last=0 ;; esac
[ $((now - last)) -lt 600 ] && return 0
fi
printf '%s' "$now" > "$marker" 2>/dev/null || true
grimoire_json_out "PreToolUse" "> Grimoire did not answer the project fence check, so this act went ahead without being checked against the session's project. If it changes another project's files or records, stop and file an issue there instead. Said once per outage."
}
while IFS= read -r check; do
[ -n "$check" ] || continue
if [ "$check" = "tool" ]; then
input=$(fence_tool_input | grimoire_urlenc)
q="tool=$(printf '%s' "$short" | grimoire_urlenc)&input=${input}"
else
scope=${check%%$'\t'*}
act=${check#*$'\t'}
q="target_${scope}&act=$(printf '%s' "$act" | grimoire_urlenc)"
fi
resp=$(curl -fsS --max-time 4 -H "Authorization: Bearer ${token}" -H "X-Grimoire-Plugin: ${plugin_version:-}" "${base}${q}" 2>/dev/null) || {
fence_unreached
exit 0
}
rm -f "$state_dir/${safe_sid}.fence.unreached" 2>/dev/null || true
flat=$(printf '%s' "$resp" | grimoire_json_flat)
if [ "$(grimoire_json_pick "$flat" '.allowed')" = "false" ]; then
reason=$(grimoire_json_pick "$flat" '.reason')
esc=$(printf '%s' "$reason" | grimoire_json_escape) || exit 0
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"%s"}}\n' "$esc"
exit 0
fi
done <<EOF
$checks
EOF
exit 0
+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 # answers with one line putting the question to the reader. Nothing is
# mounted by this. # mounted by this.
# #
# An open of a rule a hook has just NAMED is not reported. A ranked arm or a # EVERY OPEN IS REPORTED: the server stamps it on this session's latest
# moment line put it in front of the reader, and that explains the open; the # delivery of the rule, which is how an open rate per delivery is measured.
# moment beside it did not, so counting it would propose mounts on whatever #
# moment happened to fire while search was surfacing the rule. The window is # The acts go with it only when the rule was NOT just named by a hook. A
# short for the same reason: a few minutes of agent work reaches many moments. # ranked arm or a moment line put a named rule in front of the reader, and
# that explains the open; the moment beside it did not, so counting it would
# propose mounts on whatever moment happened to fire while search was
# surfacing the rule. The window is short for the same reason: a few minutes
# of agent work reaches many moments.
command -v curl >/dev/null 2>&1 || exit 0 command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0 grimoire_config || exit 0
acts=""
case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in case ",$(grimoire_rules_live "$state_dir/${safe_sid}.rules.ids")," in
*",${rule_id},"*) exit 0 ;; *",${rule_id},"*) ;;
esac *)
acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts" acts_file="${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}.acts"
[ -f "$acts_file" ] || exit 0 now=$(date +%s 2>/dev/null) || now=0
now=$(date +%s 2>/dev/null) || exit 0 if [ -f "$acts_file" ] && [ "$now" -gt 0 ]; then
acts=$(awk -F '\t' -v since=$((now - 90)) \ acts=$(awk -F '\t' -v since=$((now - 90)) \
'$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \ '$1 + 0 >= since { sub(/^[^\t]*\t/, ""); print }' "$acts_file" 2>/dev/null \
| tail -n 3 | paste -sd ',' - 2>/dev/null) | tail -n 3 | paste -sd ',' - 2>/dev/null)
[ -n "$acts" ] || exit 0 fi
;;
esac
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0 sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd') event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
@@ -103,6 +110,7 @@ scope=$(grimoire_scope_query "${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}")
body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \ body=$(printf '{"rule_id":%s,"session_id":"%s","acts":[%s]}' "$rule_id" "$sid_esc" "$acts" \
| curl -fsS --max-time 3 \ | curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary @- \ --data-binary @- \
"${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/rule-opened${scope:+?$scope}" 2>/dev/null) || exit 0
+35 -1
View File
@@ -24,6 +24,16 @@
# honest. It records that an outcome was declared. The value of that is not the # honest. It records that an outcome was declared. The value of that is not the
# claim itself — it is that the absence of one becomes visible. # claim itself — it is that the absence of one becomes visible.
# #
# `rule_misfired` closes the same gap from the other side: the rule arrived
# at a moment and did not bear on the work there. It is an answer too, so it
# goes in the same ledger.
#
# BOTH ALSO GO TO THE SERVER, with the session id the MCP call cannot carry,
# as an adherence verdict on this session's delivery of the rule: applied is
# followed, departed is departed, a misfire is not applicable at the moment it
# names (`/api/plugin/rule-verdict`). That is what lets the adherence readout
# put "followed" beside "delivered" and "opened" per rule and per moment.
#
# EXIT 0, ALWAYS. This decorates a ledger; a bookkeeping failure must never # EXIT 0, ALWAYS. This decorates a ledger; a bookkeeping failure must never
# turn a successful tool call into a hook error. # turn a successful tool call into a hook error.
set -uo pipefail set -uo pipefail
@@ -38,7 +48,7 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id') session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0 [ -n "$session_id" ] || exit 0
# The matcher in hooks.json narrows to the rule_outcome tools, but the server # The matcher in hooks.json narrows to the rule_outcome and rule_misfired tools, but the server
# segment of an MCP tool name varies with how the plugin was installed, so the # segment of an MCP tool name varies with how the plugin was installed, so the
# id is read from the field rather than from an assumed tool name — the same # id is read from the field rather than from an assumed tool name — the same
# reasoning grimoire_record_opened.sh gives. # reasoning grimoire_record_opened.sh gives.
@@ -52,4 +62,28 @@ safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
# Stamped and append-only like its two siblings, so one reader ages them all. # Stamped and append-only like its two siblings, so one reader ages them all.
printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.acted.ids" printf '%s\n' "$rule_id" | grimoire_rules_append "$state_dir/${safe_sid}.acted.ids"
# ── The verdict, to the server ───────────────────────────────────────────
command -v curl >/dev/null 2>&1 || exit 0
grimoire_config || exit 0
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
why=$(grimoire_json_pick "$event_flat" '.tool_input.why')
outcome=""
moment=""
case "$tool_name" in
*rule_misfired) moment=$(grimoire_json_pick "$event_flat" '.tool_input.moment') ;;
*) outcome=$(grimoire_json_pick "$event_flat" '.tool_input.outcome') ;;
esac
sid_esc=$(printf '%s' "$session_id" | grimoire_json_escape) || exit 0
outcome_esc=$(printf '%s' "$outcome" | grimoire_json_escape) || exit 0
moment_esc=$(printf '%s' "$moment" | grimoire_json_escape) || exit 0
why_esc=$(printf '%s' "$why" | grimoire_json_escape) || exit 0
printf '{"rule_id":%s,"session_id":"%s","outcome":"%s","moment":"%s","why":"%s"}' \
"$rule_id" "$sid_esc" "$outcome_esc" "$moment_esc" "$why_esc" \
| curl -fsS --max-time 3 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/rule-verdict" >/dev/null 2>&1 || true
exit 0 exit 0
+4 -1
View File
@@ -6,7 +6,9 @@
# tool call misses it. This hook sends the finished reply to the server, which # tool call misses it. This hook sends the finished reply to the server, which
# checks it twice over: the rules MOUNTED on the reply moments, and the reply # checks it twice over: the rules MOUNTED on the reply moments, and the reply
# text against every rule's trigger, as the backstop for whatever the earlier # text against every rule's trigger, as the backstop for whatever the earlier
# arms missed. An unopened rule from either half holds the reply for one read. # arms missed. An unopened rule set to hold, from either half, holds the reply
# for one read; a rule set to inform was delivered before the reply and never
# holds it.
# #
# ONE END-OF-TURN REQUEST. When the turn closed a task, the same request # ONE END-OF-TURN REQUEST. When the turn closed a task, the same request
# carries the task ids and the server also checks the reply for the completion # carries the task ids and the server also checks the reply for the completion
@@ -105,6 +107,7 @@ query=${query#&}
answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \ answer=$(printf '{"reply":"%s"%s}' "$reply_esc" "$closing" | curl -fsS --max-time 6 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
--data-binary @- \ --data-binary @- \
"${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/reply-rules${query:+?$query}" 2>/dev/null) || exit 0
+1
View File
@@ -192,6 +192,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then
local resp meta local resp meta
resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \ resp=$(curl -sS --max-time "$1" -w '\n%{http_code} %{time_total}' \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/context${q}" 2>/dev/null) "${url%/}/api/plugin/context${q}" 2>/dev/null)
ctx_rc=$? ctx_rc=$?
meta=${resp##*$'\n'} meta=${resp##*$'\n'}
+8 -4
View File
@@ -31,11 +31,14 @@ event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id') session_id=$(grimoire_json_pick "$event_flat" '.session_id')
[ -n "$session_id" ] || exit 0 [ -n "$session_id" ] || exit 0
# The moment arm's per-session files (its tool cache and the acts ledger) # The moment arm's per-session files (its tool cache and the acts ledger), the
# describe a session that is over, on any exit — a clear # shape check's (a note waiting for a prompt) and the fence's (the project the
# included, since the next conversation is a new session id. # 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._-' '_') safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* 2>/dev/null || true rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \
"${TMPDIR:-/tmp}/grimoire-fence/${safe_sid}".* \
"${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true
reason=$(grimoire_json_pick "$event_flat" '.reason') reason=$(grimoire_json_pick "$event_flat" '.reason')
[ "$reason" = "clear" ] && exit 0 [ "$reason" = "clear" ] && exit 0
@@ -46,6 +49,7 @@ grimoire_config || exit 0
sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0 sid_enc=$(printf '%s' "$session_id" | grimoire_urlenc) || exit 0
curl -fsS --max-time 4 \ curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/release-session?session_id=${sid_enc}" \ "${url%/}/api/plugin/release-session?session_id=${sid_enc}" \
>/dev/null 2>&1 || true >/dev/null 2>&1 || true
exit 0 exit 0
+63 -48
View File
@@ -1,29 +1,31 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent # Grimoire plugin — Stop hook: the turn's new shapes are judged by the agent
# that wrote them. # that wrote them, at the start of its next turn.
# #
# The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every # The write hooks (grimoire_prior_art.sh, grimoire_after_write.sh) append every
# definition a write names to a session ledger, `<sid>.written.ids` # definition a write names to a session ledger, `<sid>.written.ids`
# (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the # (`path<TAB>kind<TAB>name`, see grimoire_written_append). At the end of the
# turn this hook sends that ledger to the instance, which answers with what # turn this hook sends that ledger to the instance, which answers with what
# nobody has judged yet. If anything is, the hook blocks ONCE, in the server's # nobody has judged yet as a `note`. The hook leaves the note for
# words: the agent that built the code is the one participant who knows what # grimoire_autoinject.sh, which carries it into the next prompt's payload: the
# it is, and the end of the turn is the last moment that is still true. # agent that built the code is the one participant who knows what it is, and
# the next turn of the same session still does.
# #
# THE SAME DISCIPLINE AS the completion-section check in grimoire_reply_check.sh: # IT NEVER HOLDS THE REPLY. A held reply is rewritten, and a hold on every turn
# - it blocks only on a `reason` the instance returned, which it returns # that wrote code made most replies cost two. The question waits one prompt
# only for a block it RECORDED — an unconfigured or unreachable instance # instead, and is asked inside that prompt's budget.
# never stops a session, and every intervention is one the numbers see;
# - never twice for one turn: the stop that follows its own block
# (`stop_hook_active` with this hook's marker present) is recorded as
# judged_after_block / left_after_block and let through;
# - another plugin's block loop is left alone (active, no marker).
# #
# THE LEDGER IS CONSUMED, NOT TURN-STAMPED. Everything written since the last # THE STATE, in <TMPDIR>/grimoire-shapecheck:
# stop this hook answered is "this turn". It is emptied once the instance has # <sid>.note — the note, until a prompt carries it (the prompt hook
# answered — after a pass, or after the post-block stop — and KEPT when the # removes it once the instance has answered);
# instance could not be reached, so the question is asked at the next stop # <sid>.asked — the lines that note named. At the first stop after the note
# that can be answered rather than silently dropped. # was carried, they go back as `phase=after`, which records
# whether they were judged, and are then forgotten.
# A note no prompt has carried yet (two stops in a row) is asked again with
# that turn's writes added, so nothing is dropped and nothing is asked twice.
#
# Silent on outage: the ledger is kept when the instance could not be reached,
# so the question is asked at the next stop that can be answered.
# #
# Config (same as the other hooks): # Config (same as the other hooks):
# CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash # CLAUDE_PLUGIN_OPTION_API_ENDPOINT base URL, no trailing slash
@@ -43,36 +45,33 @@ session_id=$(grimoire_json_pick "$event_flat" '.session_id')
active=$(grimoire_json_pick "$event_flat" '.stop_hook_active') active=$(grimoire_json_pick "$event_flat" '.stop_hook_active')
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd') event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
[ -n "$session_id" ] || exit 0 [ -n "$session_id" ] || exit 0
# The stop after another hook held the reply: this turn's writes were already
# sent at the stop before it.
[ "$active" = "true" ] && exit 0
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_') safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids" ledger="${TMPDIR:-/tmp}/grimoire-priorart/${safe_sid}.written.ids"
state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck" state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck"
mkdir -p "$state_dir" 2>/dev/null || true mkdir -p "$state_dir" 2>/dev/null || true
marker="$state_dir/${safe_sid}.blocked" note_file="$state_dir/${safe_sid}.note"
asked_file="$state_dir/${safe_sid}.asked"
if [ "$active" = "true" ]; then # A note no prompt has carried: its lines join this turn's, asked afresh.
# A Stop hook already blocked this stop. Another plugin's → nothing to add. if [ -f "$note_file" ]; then
[ -f "$marker" ] || exit 0 if [ -s "$asked_file" ]; then
phase=after mkdir -p "$(dirname "$ledger")" 2>/dev/null || true
else cat "$asked_file" >> "$ledger" 2>/dev/null || true
rm -f "$marker" 2>/dev/null || true fi
phase=check rm -f "$note_file" "$asked_file" 2>/dev/null || true
fi fi
if [ ! -s "$ledger" ]; then [ -s "$asked_file" ] || [ -s "$ledger" ] || exit 0
rm -f "$marker" 2>/dev/null || true
exit 0
fi
grimoire_config || exit 0 grimoire_config || exit 0
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
# key runs the plugin), and a turn that wrote more than this generated code.
written=$(awk '!seen[$0]++' "$ledger" 2>/dev/null | head -n 80)
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}" dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}"
q="phase=${phase}&written=${written_enc}" scope_q=""
scope=$(grimoire_scope_query "$dir") scope=$(grimoire_scope_query "$dir")
[ -n "$scope" ] && q="${q}&${scope}" [ -n "$scope" ] && scope_q="&${scope}"
# The repo rides along even when a marker names the project: the instance # The repo rides along even when a marker names the project: the instance
# needs it to tell the agent which repo a just-written shape belongs to. # needs it to tell the agent which repo a just-written shape belongs to.
case "$scope" in case "$scope" in
@@ -81,25 +80,41 @@ case "$scope" in
remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true) remote=$(git -C "$dir" remote get-url origin 2>/dev/null || true)
if [ -n "$remote" ]; then if [ -n "$remote" ]; then
remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc="" remote_enc=$(printf '%s' "$remote" | grimoire_urlenc) || remote_enc=""
[ -n "$remote_enc" ] && q="${q}&repo=${remote_enc}" [ -n "$remote_enc" ] && scope_q="${scope_q}&repo=${remote_enc}"
fi fi
;; ;;
esac esac
# Unique lines, oldest first, capped: the request stays a GET (a read-scoped
# key runs the plugin), and a turn that wrote more than this generated code.
_unique() { awk '!seen[$0]++' "$1" 2>/dev/null | head -n 80; }
# The note a prompt carried: were its lines judged since?
if [ -s "$asked_file" ]; then
asked=$(_unique "$asked_file")
asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc=""
if [ -n "$asked_enc" ] && curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \
>/dev/null 2>&1; then
rm -f "$asked_file" 2>/dev/null || true
fi
fi
[ -s "$ledger" ] || exit 0
written=$(_unique "$ledger")
written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0
answer=$(curl -fsS --max-time 4 \ answer=$(curl -fsS --max-time 4 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
"${url%/}/api/plugin/shape-check?${q}" 2>/dev/null) || exit 0 # unreachable: keep the ledger -H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \
|| exit 0 # unreachable: keep the ledger
if [ "$phase" = "after" ]; then note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note')
rm -f "$marker" "$ledger" 2>/dev/null || true if [ -n "$note" ]; then
exit 0 printf '%s' "$note" > "$note_file" 2>/dev/null || true
printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true
fi fi
rm -f "$ledger" 2>/dev/null || true
reason=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.reason')
if [ -z "$reason" ]; then
rm -f "$ledger" 2>/dev/null || true
exit 0
fi
: > "$marker" 2>/dev/null || true
printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)"
exit 0 exit 0
+4
View File
@@ -20,6 +20,10 @@ What only Claude Code needs said:
or the reply ending a turn reaches a moment of work, the rules mounted on or the reply ending a turn reaches a moment of work, the rules mounted on
it. Open the ones that apply; using-grimoire says what a quiet turn means and it. Open the ones that apply; using-grimoire says what a quiet turn means and
how to correct a moment that fired wrongly. how to correct a moment that fired wrongly.
- **A rule can hold or refuse a tool call.** A held call names its rule and
goes ahead once the rule has been read: read it, then make the call again.
A refused call is a boundary the operator drew; it moves when they change
the rule, so tell them what the rule said.
- **Compact at clean seams.** Because work is recorded as you go, a compaction - **Compact at clean seams.** Because work is recorded as you go, a compaction
is safe once in-flight state is logged. After finishing a block of work in a is safe once in-flight state is logged. After finishing a block of work in a
long session, log it to Grimoire, then tell the operator it's a good moment to long session, log it to Grimoire, then tell the operator it's a good moment to
+1
View File
@@ -32,6 +32,7 @@ grimoire_config || exit 0
body=$(curl -fsS --max-time 8 \ body=$(curl -fsS --max-time 8 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/processes" 2>/dev/null) || exit 0 "${url%/}/api/plugin/processes" 2>/dev/null) || exit 0
[ -n "$body" ] || exit 0 [ -n "$body" ] || exit 0
+3
View File
@@ -101,6 +101,8 @@ if [ -n "$session_id" ]; then
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}" [ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown. # What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")" rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
# The Systems whose rulings were shown in full — shared with the write-path # The Systems whose rulings were shown in full — shared with the write-path
# hook, for the reason the rule file is. # hook, for the reason the rule file is.
rulingsfile="$state_dir/${safe_sid}.rulings.ids" rulingsfile="$state_dir/${safe_sid}.rulings.ids"
@@ -112,6 +114,7 @@ fi
# than silence. See the header. # than silence. See the header.
body=$(curl -fsS --max-time 5 \ body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \ -H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0 "${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0
body_flat=$(printf '%s' "$body" | grimoire_json_flat) body_flat=$(printf '%s' "$body" | grimoire_json_flat)
+19 -1
View File
@@ -25,6 +25,15 @@
} }
], ],
"PreToolUse": [ "PreToolUse": [
{
"matcher": "Write|Edit|MultiEdit|NotebookEdit|Bash|mcp__.*grimoire.*",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
}
]
},
{ {
"matcher": "Write|Edit", "matcher": "Write|Edit",
"hooks": [ "hooks": [
@@ -73,7 +82,7 @@
] ]
}, },
{ {
"matcher": "mcp__.*__rule_outcome", "matcher": "mcp__.*__(rule_outcome|rule_misfired)",
"hooks": [ "hooks": [
{ {
"type": "command", "type": "command",
@@ -89,6 +98,15 @@
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_claim_session.sh\"" "command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_claim_session.sh\""
} }
] ]
},
{
"matcher": "mcp__.*__enter_project",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
}
]
} }
], ],
"PreCompact": [ "PreCompact": [
+10 -9
View File
@@ -100,10 +100,10 @@ Two constraints on *how* that's achieved:
**lesson** is what is worth knowing — a better way to think about a **lesson** is what is worth knowing — a better way to think about a
problem, a solution that transfers — and ignoring it costs time. All three problem, a solution that transfers — and ignoring it costs time. All three
are worth reading and all three arrive beside your work; only the first is are worth reading and all three arrive beside your work; only the first is
a mistake to miss. An injected line names which in its opening words — a mistake to miss. A line names which up front (*"Rule 11 …; it binds:"*,
*"Standing rule that may apply…"* against *"Preference that may apply…"* — *"Preference 173 …; how this has been done before:"*) and on first mention
a lesson arrives in the records menu marked `lesson`, under a header that quotes the statement; `get_rule(id)` gives the why and how. A lesson is
says outright that it binds nothing, and every payload carries `kind`. marked `lesson` under a header saying it binds nothing; payloads carry `kind`.
**One question sorts them, and it is worth asking out loud: what happens if **One question sorts them, and it is worth asking out loud: what happens if
someone doesn't do this?** *Something breaks, or a boundary is crossed* — a someone doesn't do this?** *Something breaks, or a boundary is crossed* — a
@@ -277,11 +277,12 @@ bound — confine the session to it:
- **Pass that `project_id` to every read** (`search`, `list_tasks`, - **Pass that `project_id` to every read** (`search`, `list_tasks`,
`list_notes`). An unscoped read bleeds every other project's work into your `list_notes`). An unscoped read bleeds every other project's work into your
context. context.
- **Only reference or offer work on the in-scope project.** Don't surface, - **Only reference or offer work on the in-scope project**, unless the
suggest, or start work on other projects unless the operator explicitly widens operator explicitly widens scope; work that belongs elsewhere, say so and ask.
scope. - **Cross-project, the one change to make is filing an issue**:
- If something clearly belongs to a *different* project, say so and **ask before `create_task(project_id=<theirs>, kind="issue")` with how you found it and the
switching** — never silently operate cross-project. evidence. Reading there is fine; editing its files, committing or pushing in
its repo, or changing its records is the operator's call, and the plugin asks.
## Read these when the moment comes ## Read these when the moment comes
+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 moment or none, when a mounted rule arrived and did not apply, and when a line
proposes mounting or unmounting a rule. proposes mounting or unmounting a rule.
## Contents
- What a moment is
- Reading a line that arrived at a moment — and a held or refused call
- When the moment is wrong — correct it in the session
- When a mounted rule arrives and does not apply
- When a line proposes a mount — and how rules are weighed and measured
## What a moment is ## What a moment is
Most rules reach you by resemblance: what you are doing looks like what the Most rules reach you by resemblance: what you are doing looks like what the
@@ -34,6 +41,22 @@ The reply that ends a turn is a moment too. When a rule mounted at
with its name: open it, then send the reply — unchanged, if it already does with its name: open it, then send the reply — unchanged, if it already does
what the rule asks. The same rule is never held twice. what the rule asks. The same rule is never held twice.
A call can be held the same way. A rule declared `hold` that the call reaches
stops it once, naming the rule: read it, then make the call again — unchanged
if the rule does not bear on it, and then `rule_misfired` says so. A rule
declared `enforce` refuses the call every time, in its own words: that is a
boundary the operator drew, and it moves only when they change the rule, so
tell them what you were doing and what the rule said. A rule with triggers of
its own holds or refuses only the acts those triggers match; at the rest of
its moments it arrives as a line.
A moment sends a few lines, not every rule mounted there: ordered by
enforcement, then salience, then how exactly the act reached the rule, then
how often it has been opened there. What did not fit was left out, and a
rule already shown this session comes back as a short reminder, then not at
all. So a quiet moment means nothing more needed saying there, not that no
rule applies — `what_might_apply` asks for the whole list.
## When the moment is wrong — correct it in the session ## When the moment is wrong — correct it in the session
A moment can fire on an action that is not that moment here, or an action can A moment can fire on an action that is not that moment here, or an action can
@@ -89,3 +112,19 @@ The same tool answers proposals from a pass over the rules
proposes, and only the operator's yes mounts. Writing a NEW rule is different proposes, and only the operator's yes mounts. Writing a NEW rule is different
— its moments are part of writing it, and the — its moments are part of writing it, and the
skill's guide to writing records says how. skill's guide to writing records says how.
A second pass weighs each rule: how strongly it arrives once reached
(`enforcement`: inform, hold or enforce; `salience`), and which typed
triggers reach it exactly (`rules_to_weigh`, `propose_rule_weights`,
`rule_weight_proposals`, `judge_rule_weights`). It reads each rule beside its
delivery history and proposes; the operator confirms each change, in the
session or under Settings › Moments.
Whether a rule was followed where it arrived is measured per rule and per
moment (`rule_adherence`, and under Settings › Moments). Your own
`rule_outcome` and `rule_misfired` calls are the session's half of that
record: each lands as a verdict on the delivery you were answering. A
transcript review fills in the rest when the operator asks for one:
`adherence_to_judge` lists the rules in force at a moment of a session with
no verdict yet, and `judge_adherence` records followed, broken, departed or
not applicable, with what the transcript shows.
@@ -10,6 +10,7 @@ decides how some area of the work must behave; and before filling
## Contents ## Contents
- Where a new rule goes — its home, its trigger, what already covers the moment - Where a new rule goes — its home, its trigger, what already covers the moment
- When it applies — the moments a rule, a preference or a process is for - When it applies — the moments a rule, a preference or a process is for
- How strongly it arrives — enforcement, salience, and the act it governs
- A ruling goes on the System it governs - A ruling goes on the System it governs
- A lesson grows each time it proves itself - A lesson grows each time it proves itself
- A lesson names the rule it is an instance of - A lesson names the rule it is an instance of
@@ -33,7 +34,10 @@ departs from a global rule writes its own and links it with
`relate_rules(kind="overrides")`, which says why. A rule that turns out to be `relate_rules(kind="overrides")`, which says why. A rule that turns out to be
in the wrong home — a project rule that holds everywhere, a global one only a in the wrong home — a project rule that holds everywhere, a global one only a
single project needs — moves with `move_rule`, which keeps its id, history, single project needs — moves with `move_rule`, which keeps its id, history,
areas and edges. Propose the move and make it on a yes. areas and edges. Propose the move and make it on a yes. Editing a rule that
lives on another project is curation, not that project's work: the plugin
names the rule and asks, and the edit goes ahead on the operator's yes rather
than becoming an issue there.
**Whichever home it gets, a rule needs `when_to_apply`.** It is the only thing **Whichever home it gets, a rule needs `when_to_apply`.** It is the only thing
that decides whether the rule is ever seen: nothing is preloaded, so a rule that decides whether the rule is ever seen: nothing is preloaded, so a rule
@@ -57,6 +61,35 @@ names the moments the procedure is for, so loading it reaches them and the
rules mounted there arrive with it. A rule that only applies inside one rules mounted there arrive with it. A rule that only applies inside one
procedure mounts on that procedure's own moment, `skill.<name>`. procedure mounts on that procedure's own moment, `skill.<name>`.
## How strongly it arrives
A rule that reaches the work says one of three things, and you declare which
(`enforcement` on `create_rule`, `create_project_rule`, `update_rule`):
- **`inform`** — a line beside the work. The default, and right for most
rules: the session reads it and applies it.
- **`hold`** — the act or reply it governs waits until the session has read
the rule once; then it goes ahead. For a rule whose miss costs a rewrite: a
merge style, a release step, a check before a reply.
- **`enforce`** — the act is refused, in the rule's own words, every time,
and only a change to the rule moves it. For a boundary the operator draws
with no exceptions a session may judge. Most hard rules have an exit ("unless
the operator asks"), and a rule with an exit is a hold.
A hold or a refusal stops an act, so give it the act: a `triggers` entry
naming the command head (`git push origin main`), the tool (`create_release`)
or the path (`alembic/versions/*.py`) it governs. A rule with triggers stops
only the acts they match; at the rest of its moments it is a line. Without
one, it stops every act its moment reaches — a rule about pushing to `main`
mounted on `work.deliver` would hold every push to `dev`.
**`salience`** (`high`, `normal`, `low`) orders it against rules of the same
enforcement when a moment has more to say than fits. A moment sends a few
lines, highest first, and drops the rest — so `high` is for the rule that must
win a crowded moment, and `low` for one worth seeing but rarely decisive.
A preference never holds or refuses: it arrives as a line, with a salience.
**Before writing one, ask what already covers that moment.** **Before writing one, ask what already covers that moment.**
`what_might_apply("the moment you are about to write a record for")` — fifty `what_might_apply("the moment you are about to write a record for")` — fifty
candidates and no bar, so an existing record cannot hide under a threshold the candidates and no bar, so an existing record cannot hide under a threshold the
+1
View File
@@ -50,6 +50,7 @@ asyncio_mode = "auto"
testpaths = ["tests"] testpaths = ["tests"]
markers = [ markers = [
"integration: requires a real Postgres database (runs only in the CI integration lane)", "integration: requires a real Postgres database (runs only in the CI integration lane)",
"cue_gate: runs with the plugin doors' cue-swap gate on rather than stubbed off",
] ]
[tool.ruff] [tool.ruff]
+45 -5
View File
@@ -395,6 +395,13 @@ SMOKE_EVENTS: dict[str, str] = {
{"session_id": "smoke", "cwd": ".", "hook_event_name": "SessionEnd", {"session_id": "smoke", "cwd": ".", "hook_event_name": "SessionEnd",
"reason": "prompt_input_exit"} "reason": "prompt_input_exit"}
), ),
# The project fence. A Grimoire write is the one act that always asks the
# server, so it is what reaches the network in the unreachable case: there
# the act goes ahead and the hook says once that it couldn't check.
"grimoire_project_fence.sh": json.dumps(
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PreToolUse",
"tool_name": "mcp__grimoire__update_task", "tool_input": {"task_id": 1}}
),
# The shared library is sourced, never run; executed bare it defines # The shared library is sourced, never run; executed bare it defines
# functions and exits — silent by construction. # functions and exits — silent by construction.
"grimoire_defs.sh": "", "grimoire_defs.sh": "",
@@ -415,9 +422,14 @@ STATIC_EMITTERS = {
# would look like a leak; it is the opposite. # would look like a leak; it is the opposite.
"grimoire_precompact_preserve.sh": "preservation instructions present", "grimoire_precompact_preserve.sh": "preservation instructions present",
} }
# The hooks that say so when a configured instance does not answer. # The hooks that say so when a configured instance does not answer, each with
OUTAGE_SPEAKERS = {"grimoire_prior_art.sh", "grimoire_after_write.sh"} # the line it says it in.
OUTAGE_LINE = "> Grimoire did not answer the prior-art check" _PRIOR_ART_OUTAGE = "> Grimoire did not answer the prior-art check"
OUTAGE_LINES = {
"grimoire_prior_art.sh": _PRIOR_ART_OUTAGE,
"grimoire_after_write.sh": _PRIOR_ART_OUTAGE,
"grimoire_project_fence.sh": "> Grimoire did not answer the project fence check",
}
def _run_hook(script: Path, event: str, env_extra: dict[str, str]) -> subprocess.CompletedProcess: def _run_hook(script: Path, event: str, env_extra: dict[str, str]) -> subprocess.CompletedProcess:
@@ -464,13 +476,13 @@ def check_fail_open() -> None:
f"output must survive having no credentials ({what})") f"output must survive having no credentials ({what})")
else: else:
ok(f"{rel} [{label}]: exit 0, {what}") ok(f"{rel} [{label}]: exit 0, {what}")
elif out and label == "unreachable" and script.name in OUTAGE_SPEAKERS: elif out and label == "unreachable" and script.name in OUTAGE_LINES:
# The only thing allowed here is the outage line itself. # The only thing allowed here is the outage line itself.
try: try:
ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"] ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"]
except (ValueError, KeyError, TypeError): except (ValueError, KeyError, TypeError):
ctx = "" ctx = ""
if ctx.startswith(OUTAGE_LINE): if ctx.startswith(OUTAGE_LINES[script.name]):
ok(f"{rel} [{label}]: exit 0, says the instance did not answer") ok(f"{rel} [{label}]: exit 0, says the instance did not answer")
else: else:
fail(f"{rel} [{label}]: emitted output with no working instance " fail(f"{rel} [{label}]: emitted output with no working instance "
@@ -769,6 +781,33 @@ def check_version_is_minted(base: str = "origin/main") -> None:
ok(f"nothing version-relevant changed against {base} — no mint required") ok(f"nothing version-relevant changed against {base} — no mint required")
# The lower of the two caps recorded for a hook's additional context: the docs
# give 10,000 characters, and an installed build has been read capping it at
# 8,000. Past the cap the model gets only a short preview.
HOOK_CONTEXT_CAP = 8_000
PAYLOAD_MODULE = ROOT / "src" / "grimoire" / "services" / "hook_payload.py"
def check_payload_bound() -> None:
"""The server fits every hook payload under `hook_payload.HARD_MAX`, and
that ceiling must sit under Claude Code's cap whatever a user sets."""
try:
text = PAYLOAD_MODULE.read_text()
except OSError:
fail(f"no payload assembler at {PAYLOAD_MODULE.relative_to(ROOT)}")
return
found = re.search(r"^HARD_MAX\s*=\s*([0-9_]+)\s*$", text, re.M)
if not found:
fail("hook_payload.HARD_MAX is not a literal this check can read")
return
hard_max = int(found.group(1).replace("_", ""))
if hard_max >= HOOK_CONTEXT_CAP:
fail(f"hook_payload.HARD_MAX is {hard_max}, at or past Claude Code's "
f"{HOOK_CONTEXT_CAP}-character hook context cap")
else:
ok(f"hook payloads are bounded at {hard_max} characters, under {HOOK_CONTEXT_CAP}")
def main() -> int: def main() -> int:
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--no-version", action="store_true", parser.add_argument("--no-version", action="store_true",
@@ -788,6 +827,7 @@ def main() -> int:
check_fail_open() check_fail_open()
check_local_prior_art_needs_no_instance() check_local_prior_art_needs_no_instance()
check_session_context_reports_its_version() check_session_context_reports_its_version()
check_payload_bound()
if not args.no_version: if not args.no_version:
check_version_is_minted(args.base) check_version_is_minted(args.base)
+24 -10
View File
@@ -6,7 +6,8 @@ from pathlib import Path
from quart import Quart, g, jsonify, make_response, request, send_from_directory from quart import Quart, g, jsonify, make_response, request, send_from_directory
from grimoire.config import PLACEHOLDER_SECRET_KEYS, SECRET_KEY_FILENAME, Config from grimoire.config import SECRET_KEY_FILENAME, Config
from grimoire.proxy import PerRequestSecureSession, apply_https_headers
from grimoire.routes.admin import admin_bp from grimoire.routes.admin import admin_bp
from grimoire.routes.api import api from grimoire.routes.api import api
from grimoire.routes.auth import auth_bp from grimoire.routes.auth import auth_bp
@@ -61,13 +62,13 @@ def create_app() -> Quart:
app.secret_key = Config.SECRET_KEY app.secret_key = Config.SECRET_KEY
app.config["SESSION_COOKIE_HTTPONLY"] = True app.config["SESSION_COOKIE_HTTPONLY"] = True
app.config["SESSION_COOKIE_SAMESITE"] = "Lax" app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
app.config["SESSION_COOKIE_SECURE"] = Config.SECURE_COOKIES # Secure is decided per request, from the trusted proxy's X-Forwarded-Proto.
app.session_interface = PerRequestSecureSession()
if Config.SECRET_KEY in PLACEHOLDER_SECRET_KEYS: if os.environ.get("SECURE_COOKIES"):
logger.warning( logger.warning(
"SECRET_KEY is set to a public placeholder, so session cookies are insecure. " "SECURE_COOKIES is not used: the session cookie is Secure on every request "
"Remove it to let the instance keep its own key in %s, or set a real one.", "the trusted proxy reports as HTTPS. Remove it from the environment."
Config.DATA_DIR,
) )
if Config.SECRET_KEY_SOURCE == "ephemeral": if Config.SECRET_KEY_SOURCE == "ephemeral":
logger.warning( logger.warning(
@@ -82,11 +83,12 @@ def create_app() -> Quart:
Config.DATA_DIR, SECRET_KEY_FILENAME, Config.DATA_DIR, SECRET_KEY_FILENAME,
) )
if not Config.TRUST_PROXY_HEADERS: if os.environ.get("TRUST_PROXY_HEADERS") and not os.environ.get("TRUSTED_PROXY_HOPS"):
logger.warning( logger.warning(
"TRUST_PROXY_HEADERS is not set. If this instance is behind a reverse proxy " "TRUST_PROXY_HEADERS is not used (the starting proxy hop count is %d). "
"(nginx, Caddy, Traefik) set TRUST_PROXY_HEADERS=true so rate limiting uses " "Remove it; set the count in Settings → Config, or TRUSTED_PROXY_HOPS "
"real client IPs rather than the proxy IP." "to change the starting value.",
Config.TRUSTED_PROXY_HOPS,
) )
app.register_blueprint(admin_bp) app.register_blueprint(admin_bp)
@@ -159,6 +161,7 @@ def create_app() -> Quart:
except Exception: except Exception:
logger.debug("Failed to log usage", exc_info=True) logger.debug("Failed to log usage", exc_info=True)
apply_https_headers(response)
response.headers.setdefault("X-Content-Type-Options", "nosniff") response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "DENY") response.headers.setdefault("X-Frame-Options", "DENY")
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin") response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
@@ -195,9 +198,20 @@ def create_app() -> Quart:
from grimoire.services.logging import start_log_retention_loop from grimoire.services.logging import start_log_retention_loop
from grimoire.services.notifications import start_notification_loop from grimoire.services.notifications import start_notification_loop
from grimoire.services.rule_deliveries import start_prune_loop as start_rule_delivery_prune
start_log_retention_loop() start_log_retention_loop()
start_notification_loop() start_notification_loop()
start_auth_token_retention_loop() start_auth_token_retention_loop()
start_rule_delivery_prune()
# The proxy hop count saved in Settings decides every request's client
# address, so it is loaded before serving, under a deadline (a failed
# or slow read leaves the environment's count in force), and re-read
# on an interval so a save in another worker reaches this one.
from grimoire.services import proxy_settings
await proxy_settings.load_at_startup()
proxy_settings.start_refresh_loop()
# Write down any shipped default that moved in this release. # Write down any shipped default that moved in this release.
# #
+34 -6
View File
@@ -85,6 +85,21 @@ def _secret_key() -> tuple[str, str]:
return secrets.token_hex(32), "ephemeral" return secrets.token_hex(32), "ephemeral"
def _trusted_proxy_hops() -> int:
"""TRUSTED_PROXY_HOPS, default 1. The older TRUST_PROXY_HEADERS switch is
still read when the hop count is unset: false means 0 hops. A value that
is not a whole number reads as -1, which validate() refuses."""
raw = os.environ.get("TRUSTED_PROXY_HOPS", "").strip()
if raw:
try:
return int(raw)
except ValueError:
return -1
if os.environ.get("TRUST_PROXY_HEADERS", "").strip().lower() in ("0", "false", "no"):
return 0
return 1
class Config: class Config:
DATABASE_URL: str = _read_secret( DATABASE_URL: str = _read_secret(
"DATABASE_URL", "DATABASE_URL",
@@ -95,7 +110,6 @@ class Config:
# shipped compose file, beside the model cache and diagnostics. # shipped compose file, beside the model cache and diagnostics.
DATA_DIR: str = os.environ.get("DATA_DIR", "/data") DATA_DIR: str = os.environ.get("DATA_DIR", "/data")
SECRET_KEY, SECRET_KEY_SOURCE = _secret_key() SECRET_KEY, SECRET_KEY_SOURCE = _secret_key()
SECURE_COOKIES: bool = os.environ.get("SECURE_COOKIES", "").lower() in ("1", "true", "yes")
LOG_LEVEL: str = os.environ.get("LOG_LEVEL", "INFO") LOG_LEVEL: str = os.environ.get("LOG_LEVEL", "INFO")
LOG_RETENTION_DAYS: int = int(os.environ.get("LOG_RETENTION_DAYS", "90")) LOG_RETENTION_DAYS: int = int(os.environ.get("LOG_RETENTION_DAYS", "90"))
@@ -108,7 +122,16 @@ class Config:
SMTP_FROM_NAME: str = os.environ.get("SMTP_FROM_NAME", "Fabled Grimoire") SMTP_FROM_NAME: str = os.environ.get("SMTP_FROM_NAME", "Fabled Grimoire")
SMTP_USE_TLS: bool = os.environ.get("SMTP_USE_TLS", "true").lower() in ("1", "true", "yes") SMTP_USE_TLS: bool = os.environ.get("SMTP_USE_TLS", "true").lower() in ("1", "true", "yes")
BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/") BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/")
TRUST_PROXY_HEADERS: bool = os.environ.get("TRUST_PROXY_HEADERS", "").lower() in ("1", "true", "yes") # How many reverse proxies stand in front of the app; the client address
# and scheme are read that many entries in from the right of the
# forwarding headers (grimoire/proxy.py). 0 trusts no proxy. This is the
# install's starting value: a count saved in Settings → Config wins over
# it (services/proxy_settings.py).
TRUSTED_PROXY_HOPS: int = _trusted_proxy_hops()
TRUSTED_PROXY_HOPS_FROM_ENV: bool = bool(
os.environ.get("TRUSTED_PROXY_HOPS", "").strip()
or os.environ.get("TRUST_PROXY_HEADERS", "").strip()
)
# Git URL of the repo that ships this Grimoire plugin. There is one correct # Git URL of the repo that ships this Grimoire plugin. There is one correct
# value per deployment (the repo serving the plugin), so it's a config # value per deployment (the repo serving the plugin), so it's a config
@@ -163,11 +186,16 @@ class Config:
errors.append(f"SMTP_PORT={cls.SMTP_PORT} must be between 1 and 65535") errors.append(f"SMTP_PORT={cls.SMTP_PORT} must be between 1 and 65535")
if cls.oidc_enabled() and not cls.BASE_URL.startswith(("http://", "https://")): if cls.oidc_enabled() and not cls.BASE_URL.startswith(("http://", "https://")):
errors.append(f"BASE_URL='{cls.BASE_URL}' must start with http:// or https:// when OIDC is enabled") errors.append(f"BASE_URL='{cls.BASE_URL}' must start with http:// or https:// when OIDC is enabled")
if cls.SECRET_KEY == "dev-secret-change-me" and cls.SECURE_COOKIES: if cls.TRUSTED_PROXY_HOPS < 0:
errors.append( errors.append(
"SECRET_KEY is set to the public placeholder 'dev-secret-change-me' but " f"TRUSTED_PROXY_HOPS={os.environ.get('TRUSTED_PROXY_HOPS')!r} must be a whole "
"SECURE_COOKIES=true indicates a production deployment. Remove SECRET_KEY " "number of proxies, 0 or more"
"to let the instance keep its own key in DATA_DIR, or set a real one." )
if cls.SECRET_KEY in PLACEHOLDER_SECRET_KEYS:
errors.append(
f"SECRET_KEY is set to the public placeholder {cls.SECRET_KEY!r}, so anyone "
"could forge a session. Remove SECRET_KEY to let the instance keep its own "
"key in DATA_DIR, or set a real one."
) )
if errors: if errors:
raise ValueError("Configuration errors:\n" + "\n".join(f" - {e}" for e in errors)) raise ValueError("Configuration errors:\n" + "\n".join(f" - {e}" for e in errors))
+8
View File
@@ -168,6 +168,9 @@ _READ_ONLY_TOOLS = frozenset({
# rules are unjudged and which proposals wait. Reads of the caller's own # rules are unjudged and which proposals wait. Reads of the caller's own
# rules, as list_rules is. # rules, as list_rules is.
"rules_to_mount", "rule_moment_proposals", "rules_to_mount", "rule_moment_proposals",
"rules_to_weigh", "rule_weight_proposals",
# Adherence: the readout, and the queue a transcript review works from.
"rule_adherence", "adherence_to_judge",
}) })
# Every tool that WRITES, by name. Nothing reads this set at runtime — a tool # Every tool that WRITES, by name. Nothing reads this set at runtime — a tool
@@ -229,9 +232,14 @@ _WRITE_TOOLS = frozenset({
# Proposing moments for a rule writes a judgment row; judging one mounts # Proposing moments for a rule writes a judgment row; judging one mounts
# or unmounts the rule. # or unmounts the rule.
"propose_rule_moments", "judge_rule_moments", "propose_rule_moments", "judge_rule_moments",
# Proposing a rule's enforcement, salience or triggers writes a judgment
# row; judging one changes how the rule arrives.
"propose_rule_weights", "judge_rule_weights",
# A misfire report writes a counted row that can become an unmount # A misfire report writes a counted row that can become an unmount
# proposal. # proposal.
"rule_misfired", "rule_misfired",
# A transcript review's adherence verdicts, with the evidence it wrote.
"judge_adherence",
# A reviewer's verdicts on logged menu lines — rows carrying free # A reviewer's verdicts on logged menu lines — rows carrying free
# prose the agent authored, `rule_outcome`'s reason for being a write. # prose the agent authored, `rule_outcome`'s reason for being a write.
"judge_menu", "judge_menu",
+153
View File
@@ -16,6 +16,8 @@ from grimoire.mcp._context import current_user_id
from grimoire.services import moment_actions as actions_svc from grimoire.services import moment_actions as actions_svc
from grimoire.services import moments as moments_svc from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import rule_adherence as adherence_svc
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc from grimoire.services import rule_moment_judgments as judgments_svc
@@ -232,6 +234,150 @@ async def rule_misfired(rule_id: int, moment: str, why: str,
) )
async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict:
"""The rules nobody has weighed, each with what happened when it reached a session — a page at a time.
Weighing a rule is deciding how strongly it arrives once the work reaches
it, and what reaches it exactly:
- `enforcement`: `inform` is a line beside the work, and is right for
most rules. `hold` makes the act or reply wait until the rule has been
read once in the session (file edits are never held). `enforce` refuses
the act the rule governs, in the rule's own words, every time — for a
rule whose breach an act commits and that must never be crossed without
the operator (pushing to a protected branch, a destructive command). A
preference is always `inform`.
- `salience`: `high`, `normal` or `low` — how it ranks beside rules of the
same enforcement when a moment has more to say than fits.
- `triggers`: typed predicates on the act (`tool`, `path`, `command`,
`keyword`, optionally scoped to a moment) that reach the rule exactly.
Propose one when the rule names the act it governs; an `enforce` rule
needs one, or a mount on an act's moment, to have an act to refuse.
Each rule carries its current `enforcement`, `salience`, `mounted` and
`triggers`, and `history` over the last 90 days: `delivered` and `opened`
in total and at each place (`places`), `pulled`, `applied`, `departed`
and `misfire_days`. Read the history as evidence about the rule's
weight, not as the decision: a rule delivered often and rarely opened is
either reaching the wrong work (a trigger fixes that) or arriving too
loudly for what it asks (lower salience); a rule sessions keep departing
from or breaching may need `hold`.
Record the answer with `propose_rule_weights`. A rule leaves this list as
soon as an answer is recorded, so the next call returns the next rules.
Returns `rules`, `total_unweighed` and `offset`.
"""
return await weights_svc.unweighed_rules(current_user_id(), limit=limit, offset=offset)
async def propose_rule_weights(proposals: list[dict]) -> dict:
"""Propose rules' enforcement, salience and triggers — for the operator to confirm; nothing changes on this call.
Each item is
`{"rule_id": N, "enforcement": "inform"|"hold"|"enforce",
"salience": "high"|"normal"|"low", "triggers": [{"kind": "command",
"pattern": "git push", "moment": ""}], "why": "…"}`.
Give both enforcement and salience for every rule, even where they match
what it has: a value equal to the rule's own is recorded as agreed, which
is what marks the rule as weighed. A different value waits as a
suggestion. `triggers` lists only triggers to add; omit it when none fits.
`why` is shown to the operator beside each suggestion: say what in the
rule and its history led to it, so they can say yes or no without opening
the rule.
Refused alone, under `refused`, with why: an unknown value, a preference
proposed to hold or enforce, and `enforce` on a rule no act reaches.
A value the operator already rejected is listed under `skipped`. Then show
the operator what is waiting (`rule_weight_proposals`) and let them
decide.
"""
return await weights_svc.propose(current_user_id(), proposals)
async def rule_weight_proposals(rule_id: int = 0) -> dict:
"""The enforcement, salience and trigger suggestions waiting on the operator, grouped by rule.
Each rule carries its current enforcement, salience, mounts and triggers
beside its `proposals`: each a `field`, the suggested `value` (a trigger
also as `trigger`), `why`, and the delivery history the proposer read
(`evidence`). `rule_id` narrows to one rule.
"""
return await weights_svc.pending(current_user_id(), rule_id=rule_id or None)
async def judge_rule_weights(judgments: list[dict]) -> dict:
"""Confirm or reject weight suggestions — on the operator's word, since a confirm changes how the rule arrives.
Each item is `{"rule_id": N, "field": "enforcement"|"salience"|"trigger",
"value": "hold" (or the trigger object), "verdict": "confirm"|"reject",
"note": "why"}`. Confirm sets the field on the rule (a trigger is added
beside the rule's others); reject records that the value is wrong for this
rule, so it is never proposed again. Put the operator's reason in `note`.
"""
return await weights_svc.judge(current_user_id(), judgments)
async def rule_adherence(days: int = 30, rule_id: int = 0) -> dict:
"""Whether the rules in force at each moment were followed there — per rule and per moment.
A rule is in force at a moment of a session when it was delivered there.
For each rule at each place (a moment such as `work.deliver`, or an arm
such as `pre_tool_rule`) over the last `days`: `in_force` (sessions it
was delivered there in), `opened` (sessions that opened it), and one
count per verdict — `followed`, `departed` (read and deliberately not
followed, with a reason), `broken` (the work went against it),
`not_applicable` (it did not bear on the work there) — and `unjudged`.
Verdicts come from an `enforce` refusal (the act did not happen), from
the session's own `rule_outcome` and `rule_misfired` calls, and from a
review of the transcript (`adherence_to_judge` / `judge_adherence`).
Returns `by_rule` (each with its places), `by_moment` (each with its
rules) and `totals`. `rule_id` narrows to one rule.
"""
return await adherence_svc.summary(current_user_id(), days=days, rule_id=rule_id or None)
async def adherence_to_judge(session_id: str = "", sessions: int = 3, per_session: int = 40) -> dict:
"""The rules that were in force at a moment of a session and have no verdict yet — for a transcript review.
Grouped by session, most recent first. Each item is one rule at one place
in that session: the rule's `statement` and `when_to_apply`, where it
arrived (`at`), how often and when (`delivered`, `first_at`, `last_at`),
and whether the session `opened` it. `how` says where the session's
transcript is kept.
To review a session: read its transcript around each item's times, see
what the work was at that moment, and decide whether it kept the rule.
Record the verdicts with `judge_adherence`, quoting or describing what in
the transcript shows each one. An item that did not bear on the work
there is `not_applicable`; that is a finding about where the rule is
delivered, and is as useful as the rest. `unjudged` is the total waiting.
`session_id` narrows to one session.
"""
return await adherence_svc.to_judge(
current_user_id(), session_id, sessions=sessions, per_session=per_session,
)
async def judge_adherence(verdicts: list[dict]) -> dict:
"""Record a transcript review's verdicts on rules in force at a moment of a session.
Each item is `{"session_id": "…", "rule_id": N, "at": "work.deliver",
"verdict": "followed"|"broken"|"departed"|"not_applicable",
"evidence": "…"}`, the `session_id`, `rule_id` and `at` as
`adherence_to_judge` listed them. `evidence` is required: what the
transcript shows — the act, the reply, or the passage — so a later reader
can check the verdict. `departed` is for a session that said why it did
not follow the rule; `broken` for work that went against it without one.
A review replaces the session's own account (a later, closer reading
wins), except where an `enforce` rule refused the act, which stands.
Returns `judged` and `refused`, each refused item with why.
"""
return await adherence_svc.judge(current_user_id(), verdicts)
def register(mcp) -> None: def register(mcp) -> None:
mcp.tool(name="list_moments")(list_moments) mcp.tool(name="list_moments")(list_moments)
mcp.tool(name="list_reply_shapes")(list_reply_shapes) mcp.tool(name="list_reply_shapes")(list_reply_shapes)
@@ -242,3 +388,10 @@ def register(mcp) -> None:
mcp.tool(name="rule_moment_proposals")(rule_moment_proposals) mcp.tool(name="rule_moment_proposals")(rule_moment_proposals)
mcp.tool(name="judge_rule_moments")(judge_rule_moments) mcp.tool(name="judge_rule_moments")(judge_rule_moments)
mcp.tool(name="rule_misfired")(rule_misfired) mcp.tool(name="rule_misfired")(rule_misfired)
mcp.tool(name="rules_to_weigh")(rules_to_weigh)
mcp.tool(name="propose_rule_weights")(propose_rule_weights)
mcp.tool(name="rule_weight_proposals")(rule_weight_proposals)
mcp.tool(name="judge_rule_weights")(judge_rule_weights)
mcp.tool(name="rule_adherence")(rule_adherence)
mcp.tool(name="adherence_to_judge")(adherence_to_judge)
mcp.tool(name="judge_adherence")(judge_adherence)
+4 -1
View File
@@ -144,7 +144,10 @@ async def create_note(
Args: Args:
title: Note title (required). title: Note title (required).
body: Markdown content. Supports [[wikilinks]] to other notes by title. body: Markdown content. Cite another record as `#N` (note, task,
lesson, snippet), `milestone N` or `rule N`; the web UI links each
one, titled on hover, and lists it in the target's backlinks.
`[[Title]]` links a note by its title.
tags: List of plain-string tags without # prefix, e.g. ["python", "ideas"]. tags: List of plain-string tags without # prefix, e.g. ["python", "ideas"].
project_id: Associate with a project (use 0 for no project / orphan note). project_id: Associate with a project (use 0 for no project / orphan note).
system_ids: Ids of the project's Systems to associate this note with system_ids: Ids of the project's Systems to associate this note with
+132 -6
View File
@@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone
from grimoire.mcp._context import current_user_id from grimoire.mcp._context import current_user_id
from grimoire.services import dedup as dedup_svc from grimoire.services import dedup as dedup_svc
from grimoire.services import moments as moments_svc from grimoire.services import moments as moments_svc
from grimoire.services import rule_triggers as rule_triggers_svc
from grimoire.services import rulebooks as rulebooks_svc from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services import trash as trash_svc from grimoire.services import trash as trash_svc
from grimoire.services.lesson_rules import confirmed_lesson_counts from grimoire.services.lesson_rules import confirmed_lesson_counts
@@ -342,6 +343,8 @@ async def create_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "", arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None, system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False, moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Create a new rule in a rulebook (a SHARED rule — keep it general). """Create a new rule in a rulebook (a SHARED rule — keep it general).
@@ -530,6 +533,30 @@ async def create_rule(
constraint expires when the ground under it moves, not on a constraint expires when the ground under it moves, not on a
schedule. Pairs with verify_with; both empty is the normal case. schedule. Pairs with verify_with; both empty is the normal case.
order_index: Display order within the topic (default 0). order_index: Display order within the topic (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. Declare
hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule force: Bypass the near-duplicate gate. By default, a title-identical rule
already in this topic BLOCKS creation and returns its id so you update already in this topic BLOCKS creation and returns its id so you update
it instead. Set true only for a genuinely distinct rule. A rule or it instead. Set true only for a genuinely distinct rule. A rule or
@@ -539,6 +566,7 @@ async def create_rule(
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not force: if not force:
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id) dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
if dup is not None: if dup is not None:
@@ -553,8 +581,9 @@ async def create_rule(
arose_from_id=arose_from_id, arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index, why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when, verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
) )
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "rule")) data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data) return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
@@ -565,6 +594,8 @@ async def create_project_rule(
arose_from_id: int = 0, verify_with: str = "", expires_when: str = "", arose_from_id: int = 0, verify_with: str = "", expires_when: str = "",
system_ids: list[int] | None = None, system_ids: list[int] | None = None,
moments: list[str] | None = None, force: bool = False, moments: list[str] | None = None, force: bool = False,
enforcement: str = "inform", salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Create a rule scoped to a single project (no rulebook needed). """Create a rule scoped to a single project (no rulebook needed).
@@ -640,6 +671,30 @@ async def create_project_rule(
expires_when: The state under which the rule stops being true — see expires_when: The state under which the rule stops being true — see
create_rule. A state, not a date. create_rule. A state, not a date.
order_index: Display order within the project's rule list (default 0). order_index: Display order within the project's rule list (default 0).
enforcement: What this rule does when it arrives. `inform` (the
default) puts a line beside the work. `hold` makes the reply or
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. Declare
hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. By default, a title-identical rule force: Bypass the near-duplicate gate. By default, a title-identical rule
already on this project BLOCKS creation and returns its id so you already on this project BLOCKS creation and returns its id so you
update it instead. Set true only for a genuinely distinct rule. An update it instead. Set true only for a genuinely distinct rule. An
@@ -648,6 +703,7 @@ async def create_project_rule(
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
derived_title = title.strip() or statement.strip().split(".")[0][:50] derived_title = title.strip() or statement.strip().split(".")[0][:50]
if not force: if not force:
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id) dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
@@ -662,8 +718,9 @@ async def create_project_rule(
arose_from_id=arose_from_id, arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index, why=why, how_to_apply=how_to_apply, order_index=order_index,
verify_with=verify_with, expires_when=expires_when, verify_with=verify_with, expires_when=expires_when,
enforcement=enforcement, salience=salience,
) )
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "rule")) data.update(dedup_svc.overlap_response(overlaps, "rule"))
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data) return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
@@ -675,6 +732,8 @@ async def update_rule(
moments: list[str] | None = None, arose_from_id: int = 0, moments: list[str] | None = None, arose_from_id: int = 0,
verify_with: str = "", expires_when: str = "", kind: str = "", verify_with: str = "", expires_when: str = "", kind: str = "",
clear_fields: list[str] | None = None, clear_fields: list[str] | None = None,
enforcement: str = "", salience: str = "",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged. """Update a rule. Empty strings / order_index=-1 leave fields unchanged.
@@ -735,9 +794,35 @@ async def update_rule(
expires_when: The state under which the rule stops being true. A expires_when: The state under which the rule stops being true. A
state, not a date. See create_rule. state, not a date. See create_rule.
clear_fields: Names of fields to empty, as above. clear_fields: Names of fields to empty, as above.
enforcement: What this rule does when it arrives. `inform` (the
default for a new rule) puts a line beside the work. `hold` makes the reply or
act it governs wait until the session has read the rule once
(file edits are never held) — for a rule whose miss costs a
rewrite. `enforce` refuses the act it governs, in the rule's own
words, every time — for a boundary only the operator moves; it
needs a trigger, or a mount on a moment an act reaches, to have
an act to refuse. A rule with triggers holds or refuses only the
acts they match; reached by its mount alone it is a line. Declare
hold or enforce on purpose; most rules inform.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit either to leave it unchanged.
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
fields: dict = {} fields: dict = {}
if title: if title:
fields["title"] = title fields["title"] = title
@@ -759,12 +844,16 @@ async def update_rule(
fields["expires_when"] = expires_when fields["expires_when"] = expires_when
if order_index >= 0: if order_index >= 0:
fields["order_index"] = order_index fields["order_index"] = order_index
if enforcement:
fields["enforcement"] = enforcement
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule( rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields, rule_id, uid, clear=clear_fields or (), **fields,
) )
if rule is None: if rule is None:
raise ValueError(f"rule {rule_id} not found") raise ValueError(f"rule {rule_id} not found")
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
# ── Preferences ───────────────────────────────────────────────────────── # ── Preferences ─────────────────────────────────────────────────────────
@@ -786,7 +875,8 @@ async def create_preference(
arose_from_id: int, why: str = "", how_to_apply: str = "", arose_from_id: int, why: str = "", how_to_apply: str = "",
order_index: int = 0, system_ids: list[int] | None = None, order_index: int = 0, system_ids: list[int] | None = None,
moments: list[str] | None = None, moments: list[str] | None = None,
force: bool = False, force: bool = False, salience: str = "normal",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Record how the operator wants work done. No approval loop — write it. """Record how the operator wants work done. No approval loop — write it.
@@ -860,6 +950,20 @@ async def create_preference(
done rather than what it is about: a rule on when work counts as done rather than what it is about: a rule on when work counts as
finished belongs at work.finish and reply.report, where nothing finished belongs at work.finish and reply.report, where nothing
said resembles it. Replaces the set; [] clears it. said resembles it. Replaces the set; [] clears it.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
force: Bypass the near-duplicate gate. For a genuinely distinct force: Bypass the near-duplicate gate. For a genuinely distinct
preference, not for one that is "mostly" different — a mostly preference, not for one that is "mostly" different — a mostly
different preference is an update. A RULE that already answers different preference is an update. A RULE that already answers
@@ -869,6 +973,7 @@ async def create_preference(
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not when_to_apply.strip(): if not when_to_apply.strip():
raise ValueError( raise ValueError(
"when_to_apply is required: a preference with no trigger never " "when_to_apply is required: a preference with no trigger never "
@@ -893,8 +998,9 @@ async def create_preference(
title=title, statement=statement, when_to_apply=when_to_apply, title=title, statement=statement, when_to_apply=when_to_apply,
kind="preference", arose_from_id=arose_from_id, kind="preference", arose_from_id=arose_from_id,
why=why, how_to_apply=how_to_apply, order_index=order_index, why=why, how_to_apply=how_to_apply, order_index=order_index,
salience=salience,
) )
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
data.update(dedup_svc.overlap_response(overlaps, "preference")) data.update(dedup_svc.overlap_response(overlaps, "preference"))
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data) return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
@@ -905,6 +1011,8 @@ async def update_preference(
how_to_apply: str = "", order_index: int = -1, how_to_apply: str = "", order_index: int = -1,
system_ids: list[int] | None = None, system_ids: list[int] | None = None,
moments: list[str] | None = None, clear_fields: list[str] | None = None, moments: list[str] | None = None, clear_fields: list[str] | None = None,
salience: str = "",
triggers: list[dict] | None = None,
) -> dict: ) -> dict:
"""Bring a preference up to date. Doing this mid-work is expected. """Bring a preference up to date. Doing this mid-work is expected.
@@ -959,9 +1067,25 @@ async def update_preference(
moments: Replaces the moments this preference arrives at (see moments: Replaces the moments this preference arrives at (see
create_preference); omit to leave them alone. create_preference); omit to leave them alone.
when_to_apply: The moment it applies, in session vocabulary. See above. when_to_apply: The moment it applies, in session vocabulary. See above.
triggers: What ACT this record applies to, checked exactly rather
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
over the file an act touches: "alembic/versions/*.py",
"frontend/**/*.vue"), `command` (a command head: "git push",
"docker compose"), `keyword` (a word or phrase in the command, the
content written or the reply). With no moment, the record arrives
on any act that matches. With a moment, its mount there becomes
conditional: it arrives at that moment only when the act matches,
so a rule about migrations can sit on work.change without arriving
at every edit. Replaces the set; [] clears it.
salience: `high`, `normal` (the default) or `low` — how this record
ranks against others of the same enforcement when a moment has
more to say than fits.
Omit to leave it unchanged.
""" """
uid = current_user_id() uid = current_user_id()
moments = moments_svc.require_moments(moments) moments = moments_svc.require_moments(moments)
triggers = rule_triggers_svc.require_triggers(triggers)
if not arose_from_id: if not arose_from_id:
raise ValueError( raise ValueError(
"arose_from_id is required: this edit is the record of how the " "arose_from_id is required: this edit is the record of how the "
@@ -981,12 +1105,14 @@ async def update_preference(
fields["how_to_apply"] = how_to_apply fields["how_to_apply"] = how_to_apply
if order_index >= 0: if order_index >= 0:
fields["order_index"] = order_index fields["order_index"] = order_index
if salience:
fields["salience"] = salience
rule = await rulebooks_svc.update_rule( rule = await rulebooks_svc.update_rule(
rule_id, uid, clear=clear_fields or (), **fields, rule_id, uid, clear=clear_fields or (), **fields,
) )
if rule is None: if rule is None:
raise ValueError(f"rule {rule_id} not found") raise ValueError(f"rule {rule_id} not found")
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments) return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
async def rule_history(rule_id: int, version_id: int = 0) -> dict: async def rule_history(rule_id: int, version_id: int = 0) -> dict:
+6 -1
View File
@@ -271,7 +271,9 @@ async def create_task(
Args: Args:
title: Task title (required). title: Task title (required).
body: Markdown description / notes for the task. body: Markdown description / notes for the task. Cite another record
as `#N` (note, task, lesson, snippet), `milestone N` or `rule N`;
the web UI links each one and lists it in the target's backlinks.
status: Initial status — one of: todo (default), in_progress, done, cancelled. status: Initial status — one of: todo (default), in_progress, done, cancelled.
priority: One of: low, medium, high, or 'none'. Omit (empty string) to leave unset. priority: One of: low, medium, high, or 'none'. Omit (empty string) to leave unset.
project_id: Associate with a project (0 = no project). project_id: Associate with a project (0 = no project).
@@ -482,6 +484,9 @@ async def add_task_log(task_id: int, content: str) -> dict:
cannot get from the body or the diff is what you tried, what you ruled cannot get from the body or the diff is what you tried, what you ruled
out, and where it actually stands. out, and where it actually stands.
Records named as `#N`, `milestone N` or `rule N` are links in the web UI,
and a `#N` here lists this task in that record's backlinks.
A log on an open task also marks it as being worked by this session — its A log on an open task also marks it as being worked by this session — its
`claim`. That is what brings the task and its newest `claim`. That is what brings the task and its newest
entries back to you after a compaction; it lapses by itself once the entries back to you after a compaction; it lapses by itself once the
+4
View File
@@ -60,6 +60,8 @@ from grimoire.models.retrieval_log import RetrievalLog # noqa: E402, F401
from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401 from grimoire.models.retrieval_tuning import RetrievalTuningEvent # noqa: E402, F401
from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401 from grimoire.models.note_usage import NoteUsageEvent # noqa: E402, F401
from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401 from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401 from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401 from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401 from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
@@ -83,6 +85,7 @@ from grimoire.models.rulebook import ( # noqa: E402, F401
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401 from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink # noqa: E402, F401
# After rules: it foreign-keys them. # After rules: it foreign-keys them.
from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401 from grimoire.models.rule_moment_judgment import RuleMomentJudgment # noqa: E402, F401
from grimoire.models.rule_field_judgment import RuleFieldJudgment # noqa: E402, F401
from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401 from grimoire.models.repo_binding import RepoBinding # noqa: E402, F401
from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401 from grimoire.models.forge_connection import ForgeConnection # noqa: E402, F401
from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401 from grimoire.models.code_shape import CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse # noqa: E402, F401
@@ -94,3 +97,4 @@ from grimoire.models.family import ( # noqa: E402, F401
FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform, FamilyAdoption, FamilyDecision, FamilyIdea, FamilyIdeaPlatform,
FamilyIdeaReference, Platform, ProjectPlatform, FamilyIdeaReference, Platform, ProjectPlatform,
) )
from grimoire.models.instance import InstanceIdentity # noqa: E402, F401
+26
View File
@@ -0,0 +1,26 @@
from datetime import datetime
from sqlalchemy import CheckConstraint, DateTime, Integer, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
class InstanceIdentity(Base):
"""The one row naming this database's id lineage.
Two stores with the same instance id number their rows the same way: one
is the other, or a restore of it made with the original ids kept. That is
what lets a backup roll a live instance back by id, and what refuses a
backup whose ids would land on unrelated rows. Made by the migration, so
an instance has it before anyone registers.
"""
__tablename__ = "instance_identity"
__table_args__ = (CheckConstraint("id = 1", name="ck_instance_identity_single_row"),)
id: Mapped[int] = mapped_column(Integer, primary_key=True, default=1)
instance_id: Mapped[str] = mapped_column(Text, nullable=False)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now()
)
+8
View File
@@ -74,6 +74,12 @@ class RetrievalLog(Base):
# [{"id": int, "score": float, "rank": int}, ...], highest-first. # [{"id": int, "score": float, "rank": int}, ...], highest-first.
result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list) result_ids: Mapped[list] = mapped_column(JSONB, nullable=False, default=list)
duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True) duration_ms: Mapped[float | None] = mapped_column(Float, nullable=True)
# THE CUE-SWAP GATE, on a surface that has one (`cue_gate`): the score a
# line had to reach on this call, and how many lines reached it. Both null
# on an ungated surface. A count beside a null bar is a gate that had too
# few earlier cues to judge by, so nothing found by resemblance spoke.
gate_bar: Mapped[float | None] = mapped_column(Float, nullable=True)
gate_kept: Mapped[int | None] = mapped_column(Integer, nullable=True)
__table_args__ = ( __table_args__ = (
Index("ix_retrieval_logs_created_at", "created_at"), Index("ix_retrieval_logs_created_at", "created_at"),
@@ -99,4 +105,6 @@ class RetrievalLog(Base):
"min_score": self.min_score, "min_score": self.min_score,
"result_ids": self.result_ids, "result_ids": self.result_ids,
"duration_ms": self.duration_ms, "duration_ms": self.duration_ms,
"gate_bar": self.gate_bar,
"gate_kept": self.gate_kept,
} }
+86
View File
@@ -0,0 +1,86 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
# What happened to a rule that was in force at a moment of a session.
FOLLOWED = "followed"
DEPARTED = "departed"
BROKEN = "broken"
NOT_APPLICABLE = "not_applicable"
VERDICTS = (FOLLOWED, DEPARTED, BROKEN, NOT_APPLICABLE)
# Where the verdict came from.
REFUSED = "refused" # the act was refused by an `enforce` rule: kept by construction
OUTCOME = "outcome" # the session declared it with `rule_outcome`
MISFIRE = "misfire" # the session reported it with `rule_misfired`
JUDGE = "judge" # a review of the session's transcript
SOURCES = (REFUSED, OUTCOME, MISFIRE, JUDGE)
class RuleAdherence(Base):
"""Whether a rule in force at a moment of a session was followed there.
The unit is a rule delivered at one place (`at`: a moment such as
`work.deliver`, or an arm such as `pre_tool_rule`) in one session — the
same unit `rule_deliveries` records, so every verdict sits on a delivery
and the readout can put "followed" beside "delivered" and "opened". A
rule delivered ten times at one moment of one session gets one verdict:
it was followed there or it was not.
`verdict` is one of:
- `followed` — the work kept the rule;
- `departed` — the session read it and deliberately did not follow it,
with its reason in `evidence`. A departure is an answer, not a fault;
- `broken` — the work went against it with no stated reason;
- `not_applicable` — the rule arrived but did not bear on what the
session was doing there (a misfire).
`source` says how it is known, strongest first: `refused` (an `enforce`
rule refused the act, so the act did not happen), `outcome` and
`misfire` (the session said so in a tool call, watched by the plugin),
`judge` (a later review read the transcript). A `refused` verdict is a
fact and is never replaced; any other is replaced by a later one, so a
review can correct a session's own account.
FK-free on `rule_id` and `user_id` like the other telemetry tables, and
pruned with the deliveries it describes.
"""
__tablename__ = "rule_adherence"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
rule_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
at: Mapped[str] = mapped_column(Text, nullable=False)
verdict: Mapped[str] = mapped_column(Text, nullable=False)
source: Mapped[str] = mapped_column(Text, nullable=False)
evidence: Mapped[str | None] = mapped_column(Text, nullable=True)
judged_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
__table_args__ = (
UniqueConstraint("user_id", "session_id", "rule_id", "at",
name="uq_rule_adherence_session_rule_at"),
Index("ix_rule_adherence_rule_at", "rule_id", "at"),
Index("ix_rule_adherence_judged_at", "judged_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"rule_id": self.rule_id,
"at": self.at,
"verdict": self.verdict,
"source": self.source,
"evidence": self.evidence,
"judged_at": iso(self.judged_at),
}
+83
View File
@@ -0,0 +1,83 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
FULL = "full"
REPEAT = "repeat"
FORMS = (FULL, REPEAT)
class RuleDelivery(Base):
"""One rule line put in front of one session, and whether it was opened after.
WHAT IT ANSWERS that `rule_usage_events` cannot. A surfaced event and a
pulled event are counted separately, so "was THIS delivery opened" has no
answer there: a rule opened once in a session reads as pulled whether it
was delivered once or twenty times. Here each delivery is a row, and the
open is stamped on the delivery it followed — so the open rate per rule,
per moment and per arm is a count of rows, and the ordering function reads
it as the rule's history at that moment. A delivery made to a session that
had already opened the rule is stamped as it is written, with its own
time: it reached a reader who had the rule.
`at` is where the rule was delivered: the moment it was mounted on
(`work.finish`) or the arm that found it (`pre_tool_rule`). `form` is
whether the line carried the rule's trigger (`full`) or only cited it
(`repeat`). Repeats are recorded too: they are deliveries a session can
open, and the case for retiring a rule rests on how rarely they are.
`plugin` is the version of the plugin that asked for the line, from the
request's `X-Grimoire-Plugin` header. Only a plugin that sends it reports
every open (`grimoire_record_opened.sh`), so a delivery without one was
made to a session whose opens never reach the server, and its unstamped
`opened_at` says nothing about whether it was read. The open-rate readers
count only deliveries that carry it. The server and the plugin ship on
different channels (the server from `dev`, the plugin from `main`, and a
running session keeps the plugin it started with), so rows from an older
plugin keep arriving for as long as such a session lives.
FK-free on `rule_id` and `user_id`, like the other telemetry tables: the
evidence that a rule was delivered forty times and opened never outlives
the rule, because it is the case for having deleted it.
"""
__tablename__ = "rule_deliveries"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
rule_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
source: Mapped[str] = mapped_column(Text, nullable=False)
at: Mapped[str] = mapped_column(Text, nullable=False)
form: Mapped[str] = mapped_column(Text, nullable=False)
delivered_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
opened_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
# Stamping an open: this session's latest delivery of this rule.
Index("ix_rule_deliveries_session_rule", "user_id", "session_id", "rule_id", "delivered_at"),
# History: a batch of rules at one moment.
Index("ix_rule_deliveries_rule_at", "rule_id", "at"),
Index("ix_rule_deliveries_delivered_at", "delivered_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"rule_id": self.rule_id,
"source": self.source,
"at": self.at,
"form": self.form,
"delivered_at": iso(self.delivered_at),
"opened_at": iso(self.opened_at),
"plugin": self.plugin,
}
@@ -0,0 +1,73 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, ForeignKey, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import CreatedAtMixin, iso
from grimoire.models.lesson_rule_link import CONFIRMED, LINK_STATES, REJECTED, SUGGESTED
__all__ = [
"CONFIRMED", "ENFORCEMENT", "FIELDS", "REJECTED", "SALIENCE", "SUGGESTED",
"TRIGGER", "RuleFieldJudgment",
]
# The fields of a rule that decide how it arrives once it is reached: what it
# does (`enforcement`), how it ranks beside rules of the same force
# (`salience`), and the typed predicates that reach it (`trigger`).
ENFORCEMENT, SALIENCE, TRIGGER = "enforcement", "salience", "trigger"
FIELDS = (ENFORCEMENT, SALIENCE, TRIGGER)
class RuleFieldJudgment(Base, CreatedAtMixin):
"""A proposed or judged value for one of a rule's delivery fields.
The rule row holds the current value; this holds the reasoning behind it
and the values that were turned down. One row per (rule, field, value):
- ``suggested`` — a pass read the rule and its delivery history and
proposed this value. Changes nothing until a person confirms it.
- ``confirmed`` — the value was judged right. For a proposal equal to
what the rule already carries, the pass's agreement is recorded this way,
so a rule that was looked at and left alone does not read as one nobody
looked at.
- ``rejected`` — judged wrong, kept with its reason so it is never
proposed again.
`value` is the enforcement or salience name, or for a trigger
`kind<TAB>pattern<TAB>moment` — one string, so the pair is unique.
`evidence` is the delivery history the proposer read, as it stood then.
"""
__tablename__ = "rule_field_judgments"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
rule_id: Mapped[int] = mapped_column(
BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), index=True,
)
field: Mapped[str] = mapped_column(Text)
value: Mapped[str] = mapped_column(Text)
state: Mapped[str] = mapped_column(Text, default=SUGGESTED, server_default=SUGGESTED)
# `pass` — an agent proposed it; `edit` — a person set the field directly.
source: Mapped[str] = mapped_column(Text, default="pass", server_default="pass")
note: Mapped[str | None] = mapped_column(Text, nullable=True)
evidence: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
judged_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
__table_args__ = (
UniqueConstraint("rule_id", "field", "value", name="uq_rule_field_judgments_value"),
)
def to_dict(self) -> dict:
return {
"rule_id": self.rule_id,
"field": self.field,
"value": self.value,
"state": self.state,
"source": self.source,
"note": self.note or "",
"evidence": self.evidence or {},
"judged_at": iso(self.judged_at),
"created_at": iso(self.created_at),
}
+27
View File
@@ -116,6 +116,15 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
# Defaults to `rule` so nothing changes force on upgrade. # Defaults to `rule` so nothing changes force on upgrade.
# CHECK ck_rules_kind (migration 0098). # CHECK ck_rules_kind (migration 0098).
kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule") kind: Mapped[str] = mapped_column(Text, default="rule", server_default="rule")
# WHAT THE RULE DOES WHEN IT ARRIVES, declared by its author rather than
# guessed from a score. `enforce`: the act it governs is checked. `hold`:
# the reply or act waits for one read of it. `inform`: a line beside the
# work, and never a stop. A preference is always `inform` (CHECK
# ck_rules_preference_informs). CHECK ck_rules_enforcement (migration 0128).
enforcement: Mapped[str] = mapped_column(Text, default="inform", server_default="inform")
# How this rule ranks among rules of the same enforcement when a moment has more
# to say than fits: `high`, `normal`, `low`. CHECK ck_rules_salience.
salience: Mapped[str] = mapped_column(Text, default="normal", server_default="normal")
why: Mapped[str | None] = mapped_column(Text, nullable=True) why: Mapped[str | None] = mapped_column(Text, nullable=True)
how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True) how_to_apply: Mapped[str | None] = mapped_column(Text, nullable=True)
# The three fields that tell a CONSTRAINT apart from a NORM (milestone # The three fields that tell a CONSTRAINT apart from a NORM (milestone
@@ -161,6 +170,8 @@ class Rule(Base, TimestampMixin, SoftDeleteMixin):
# codebase keeps re-encountering. Twenty bytes buys an answer that # codebase keeps re-encountering. Twenty bytes buys an answer that
# cannot be misread. # cannot be misread.
"kind": self.kind or "rule", "kind": self.kind or "rule",
"enforcement": self.enforcement or "inform",
"salience": self.salience or "normal",
"why": self.why or "", "why": self.why or "",
"how_to_apply": self.how_to_apply or "", "how_to_apply": self.how_to_apply or "",
"verify_with": self.verify_with or "", "verify_with": self.verify_with or "",
@@ -200,6 +211,22 @@ rule_moments = Table(
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)), Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
) )
# What a rule is TRIGGERED by: a typed predicate on the act itself — the tool
# called, a path it touches, the head of a command it runs, or a word in what
# it writes — checked in code with no embedding (`services/rule_triggers.py`).
# `moment` empty means the trigger fires on any act that matches it; a moment
# name makes the rule's mount on that moment conditional on the act matching.
rule_triggers = Table(
"rule_triggers",
Base.metadata,
Column("rule_id", BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
Column("kind", Text, primary_key=True),
Column("pattern", Text, primary_key=True),
Column("moment", Text, primary_key=True, default="", server_default=""),
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
)
class RuleRelation(Base, CreatedAtMixin): class RuleRelation(Base, CreatedAtMixin):
"""A typed edge between two rules. Each kind exists because without it a """A typed edge between two rules. Each kind exists because without it a
rulebook needs a workaround. rulebook needs a workaround.

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