From 55f53de92d9e9365ccdb20345cefe761dcc80077 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 09:41:09 -0500 Subject: [PATCH 1/9] fix(8139): a shape the agent walked past at the end-of-turn check is named again in its next notes The after phase answers `left`, the asked lines still unjudged; the Stop hook carries them as `earlier=` into the next checks, each up to two more asks, and the note names them apart from the last turn's writes. Co-Authored-By: Claude Opus 5.5 --- plugin/.claude-plugin/plugin.json | 2 +- plugin/hooks/grimoire_shape_check.sh | 98 ++++++++++++++++++++----- plugin/skills/shape-accounting/SKILL.md | 7 +- src/grimoire/routes/plugin.py | 28 +++++-- src/grimoire/services/shape_check.py | 73 ++++++++++++++---- tests/test_services_shape_check.py | 34 +++++++++ tests/test_shape_check_hook.py | 58 +++++++++++++++ 7 files changed, 260 insertions(+), 40 deletions(-) diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index dad95a90..708c1ccb 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "grimoire", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.11.25.1721", + "version": "2026.11.27.1440", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/hooks/grimoire_shape_check.sh b/plugin/hooks/grimoire_shape_check.sh index 75e651f4..3434f660 100644 --- a/plugin/hooks/grimoire_shape_check.sh +++ b/plugin/hooks/grimoire_shape_check.sh @@ -20,7 +20,16 @@ # removes it once the instance has answered); # .asked — the lines that note named. At the first stop after the note # was carried, they go back as `phase=after`, which records -# whether they were judged, and are then forgotten. +# whether they were judged; +# .asked_earlier — the same, for the carried lines the note named +# apart from this turn's; +# .earlier — what the after phase said is still unjudged, as +# `Npathkindname`, N the asks walked past. +# These ride the next check as `earlier=`, so a shape the +# agent moved on from is named again rather than surviving +# only as a count. A line walked past more than +# GRIMOIRE_EARLIER_MAX times is dropped: past that the +# repeat is noise, and the coverage line still counts it. # A note no prompt has carried yet (two stops in a row) is asked again with # that turn's writes added, so nothing is dropped and nothing is asked twice. # @@ -55,17 +64,23 @@ state_dir="${TMPDIR:-/tmp}/grimoire-shapecheck" mkdir -p "$state_dir" 2>/dev/null || true note_file="$state_dir/${safe_sid}.note" asked_file="$state_dir/${safe_sid}.asked" +asked_earlier_file="$state_dir/${safe_sid}.asked_earlier" +earlier_file="$state_dir/${safe_sid}.earlier" +# Each walked-past shape is asked this many more times, then dropped. +earlier_max="${GRIMOIRE_EARLIER_MAX:-2}" -# A note no prompt has carried: its lines join this turn's, asked afresh. +# A note no prompt has carried: its lines join this turn's, asked afresh. Its +# carried lines are still in .earlier, so they ride the next check too. if [ -f "$note_file" ]; then if [ -s "$asked_file" ]; then mkdir -p "$(dirname "$ledger")" 2>/dev/null || true cat "$asked_file" >> "$ledger" 2>/dev/null || true fi - rm -f "$note_file" "$asked_file" 2>/dev/null || true + rm -f "$note_file" "$asked_file" "$asked_earlier_file" 2>/dev/null || true fi -[ -s "$asked_file" ] || [ -s "$ledger" ] || exit 0 +[ -s "$asked_file" ] || [ -s "$asked_earlier_file" ] || [ -s "$ledger" ] \ + || [ -s "$earlier_file" ] || exit 0 grimoire_config || exit 0 dir="${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}" @@ -89,32 +104,81 @@ esac # 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 \ +# The note a prompt carried: were its lines judged since? What is still +# unjudged comes back as `left`, and becomes the carried set, each line's +# walked-past count one higher than it was. +if [ -s "$asked_file" ] || [ -s "$asked_earlier_file" ]; then + asked="" + [ -s "$asked_file" ] && asked=$(_unique "$asked_file") + asked_q="" + if [ -n "$asked" ]; then + asked_enc=$(printf '%s' "$asked" | grimoire_urlenc) || asked_enc="" + asked_q="&written=${asked_enc}" + fi + if [ -s "$asked_earlier_file" ]; then + prior_enc=$(_unique "$asked_earlier_file" | grimoire_urlenc) || prior_enc="" + [ -n "$prior_enc" ] && asked_q="${asked_q}&earlier=${prior_enc}" + fi + if after=$(curl -fsS --max-time 4 \ -H "Authorization: Bearer ${token}" \ -H "X-Grimoire-Plugin: ${plugin_version:-}" \ - "${url%/}/api/plugin/shape-check?phase=after&written=${asked_enc}${scope_q}" \ - >/dev/null 2>&1; then - rm -f "$asked_file" 2>/dev/null || true + "${url%/}/api/plugin/shape-check?phase=after${asked_q}${scope_q}" 2>/dev/null); then + rm -f "$asked_file" "$asked_earlier_file" 2>/dev/null || true + left_file="$state_dir/${safe_sid}.left" + grimoire_json_pick "$(printf '%s' "$after" | grimoire_json_flat)" '.left' \ + > "$left_file" 2>/dev/null || true + prev="$earlier_file" + [ -f "$prev" ] || prev=/dev/null + awk -F'\t' -v max="$earlier_max" ' + FILENAME == ARGV[1] { if (NF == 4) seen[$2 "\t" $3 "\t" $4] = $1; next } + NF == 3 { + n = (($0 in seen) ? seen[$0] : 0) + 1 + if (n <= max) print n "\t" $0 + }' "$prev" "$left_file" > "${earlier_file}.new" 2>/dev/null || true + mv -f "${earlier_file}.new" "$earlier_file" 2>/dev/null || true + [ -s "$earlier_file" ] || rm -f "$earlier_file" 2>/dev/null || true + rm -f "$left_file" 2>/dev/null || true fi fi -[ -s "$ledger" ] || exit 0 -written=$(_unique "$ledger") -written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0 +written="" +[ -s "$ledger" ] && written=$(_unique "$ledger") +# The carried lines, minus any this turn wrote again (those are this turn's). +earlier="" +if [ -s "$earlier_file" ]; then + mine_file="$state_dir/${safe_sid}.mine" + printf '%s\n' "$written" > "$mine_file" 2>/dev/null || true + earlier=$(awk -F'\t' ' + FILENAME == ARGV[1] { if (NF == 3) mine[$0] = 1; next } + NF == 4 { line = $2 "\t" $3 "\t" $4; if (!(line in mine) && !seen[line]++) print line } + ' "$mine_file" "$earlier_file" 2>/dev/null | head -n 40) + rm -f "$mine_file" 2>/dev/null || true +fi +[ -n "$written" ] || [ -n "$earlier" ] || exit 0 + +check_q="" +if [ -n "$written" ]; then + written_enc=$(printf '%s' "$written" | grimoire_urlenc) || exit 0 + check_q="&written=${written_enc}" +fi +if [ -n "$earlier" ]; then + earlier_enc=$(printf '%s' "$earlier" | grimoire_urlenc) || earlier_enc="" + [ -n "$earlier_enc" ] && check_q="${check_q}&earlier=${earlier_enc}" +fi answer=$(curl -fsS --max-time 4 \ -H "Authorization: Bearer ${token}" \ -H "X-Grimoire-Plugin: ${plugin_version:-}" \ - "${url%/}/api/plugin/shape-check?phase=check&written=${written_enc}${scope_q}" 2>/dev/null) \ + "${url%/}/api/plugin/shape-check?phase=check${check_q}${scope_q}" 2>/dev/null) \ || exit 0 # unreachable: keep the ledger note=$(grimoire_json_pick "$(printf '%s' "$answer" | grimoire_json_flat)" '.note') if [ -n "$note" ]; then printf '%s' "$note" > "$note_file" 2>/dev/null || true - printf '%s\n' "$written" > "$asked_file" 2>/dev/null || true + [ -n "$written" ] && printf '%s\n' "$written" > "$asked_file" 2>/dev/null + [ -n "$earlier" ] && printf '%s\n' "$earlier" > "$asked_earlier_file" 2>/dev/null +else + # Nothing unjudged, the carried lines included: they were answered. + rm -f "$earlier_file" 2>/dev/null || true fi rm -f "$ledger" 2>/dev/null || true exit 0 diff --git a/plugin/skills/shape-accounting/SKILL.md b/plugin/skills/shape-accounting/SKILL.md index fda51e34..640b5f4a 100644 --- a/plugin/skills/shape-accounting/SKILL.md +++ b/plugin/skills/shape-accounting/SKILL.md @@ -53,8 +53,11 @@ unjudged. The ledger is filled from your answers, given while you still know them. When a turn wrote definitions nobody has judged, the plugin's Stop hook lists them -once — with whatever the machinery holds as evidence — and you classify them -in one `classify_shapes(project_id, repo=…, …)` call (the `reusing-code` skill +— with whatever the machinery holds as evidence — and you classify them +in one `classify_shapes(project_id, repo=…, …)` call. What you move on from is +named again in your next few notes, marked as written earlier in the session, +because nothing else names a shape after that (the coverage line only counts +it) (the `reusing-code` skill says what each verdict means). `repo` lets a verdict land on a shape the sync has not read yet. So a project worked this way stays accounted as it grows, and an audit pass is a CHECK that the reflex held — the coverage line names diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index e31656ab..a9d62198 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -755,17 +755,28 @@ async def shape_check(): Query: written (str) — newline-separated `pathkindname` lines, repo-relative, kind css|sym|file. + earlier (opt) — the same lines for shapes this session wrote in an + earlier turn, was asked about and walked past. The + hook carries them for a bounded number of asks; + the note names them apart from this turn's. phase (str) — check | after. Anything else is a 400. repo (opt) — working repo remote, resolved like the other arms. project_id (opt) — explicit scope override. + + The after phase also answers `left`: the asked lines still unjudged, as + ledger lines, which the hook carries into its next ask. """ phase = (request.args.get("phase") or "check").strip() if phase not in shape_check_svc.PHASES: return jsonify({"error": f"phase must be one of {list(shape_check_svc.PHASES)}"}), 400 written = shape_check_svc.parse_written(request.args.get("written") or "") + earlier = [ + line for line in shape_check_svc.parse_written(request.args.get("earlier") or "") + if line not in written + ] project_id, repo, _unbound = await _project_scope() body: dict = {"status": "ok", "unjudged": []} - if not project_id or not written: + if not project_id or not (written or earlier): return jsonify(body) from grimoire.services import access from grimoire.services import coverage as coverage_svc @@ -774,7 +785,9 @@ async def shape_check(): if not await access.can_read_project(g.user.id, project_id): return jsonify(body) repo_key = repo_bindings_svc.normalize_repo_key(repo) if repo else "" - unjudged = await shape_ledger_svc.unjudged_shapes(project_id, written, repo_key=repo_key) + unjudged = await shape_ledger_svc.unjudged_shapes( + project_id, written + earlier, repo_key=repo_key, + ) # A snippet recorded AT a shape is the strongest verdict there is — the # next refresh stamps that row canonical. Until then the ledger cannot # know, so the recorded locations answer for it: an agent who just @@ -786,17 +799,22 @@ async def shape_check(): } unjudged = [u for u in unjudged if (u["path"], u["symbol"]) not in recorded and not (u["kind"] == "file" and (u["path"], "") in recorded)] + carried = set(earlier) + fresh = [u for u in unjudged if (u["path"], u["kind"], u["symbol"]) not in carried] + repeat = [u for u in unjudged if (u["path"], u["kind"], u["symbol"]) in carried] outcome = shape_check_svc.outcome_for(phase, unjudged) await shape_check_svc.record_shape_check( - g.user.id, outcome, written=len(written), unjudged=len(unjudged), - project_id=project_id, + g.user.id, outcome, written=len(written) + len(earlier), unjudged=len(unjudged), + project_id=project_id, earlier=len(repeat), ) body["outcome"] = outcome body["unjudged"] = unjudged if outcome == "noted": body["note"] = shape_check_svc.note_text( - unjudged, project_id=project_id, repo=repo_key or repo, + fresh, project_id=project_id, repo=repo_key or repo, earlier=repeat, ) + if phase == "after": + body["left"] = shape_check_svc.ledger_lines(unjudged) return jsonify(body) diff --git a/src/grimoire/services/shape_check.py b/src/grimoire/services/shape_check.py index 81593b7a..d68648c6 100644 --- a/src/grimoire/services/shape_check.py +++ b/src/grimoire/services/shape_check.py @@ -68,31 +68,62 @@ def _evidence_note(evidence: dict) -> str: return f" ({'; '.join(parts)})" if parts else "" -def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str: - """What the agent reads at the start of the turn after one that wrote - unjudged shapes. - - Phrased as a practice: what to decide and the one - call that records it, not a prohibition. The reusing-code skill owns the - longer version of what each verdict means. - """ +def _shape_lines(items: list[dict], *, project_id: int) -> list[str]: lines = [] - for item in unjudged[:_LISTED]: + for item in items[:_LISTED]: new = " — new" if item.get("status") == "new" else "" lines.append( f"- {item['path']} · {item['symbol']} ({item['kind']}){new}" f"{_evidence_note(item.get('evidence') or {})}" ) - more = len(unjudged) - _LISTED + more = len(items) - _LISTED if more > 0: lines.append(f"- … and {more} more (list_shapes(project_id={project_id}, path=…) shows them)") + return lines + + +def _count(n: int) -> str: + return f"{n} definition{'s' if n != 1 else ''}" + + +def note_text(unjudged: list[dict], *, project_id: int, repo: str, + earlier: list[dict] | None = None) -> str: + """What the agent reads at the start of the turn after one that wrote + unjudged shapes. + + ``earlier`` is what this session wrote in an earlier turn, was asked + about, and walked past. The per-turn ledger forgets a line once its note + has been answered, and nothing else names a shape by name — the coverage + line carries only a count — so the hook carries walked-past lines into + a bounded number of later asks. The note says plainly that they are a + repeat, and why. + + Phrased as a practice: what to decide and the one + call that records it, not a prohibition. The reusing-code skill owns the + longer version of what each verdict means. + """ + earlier = earlier or [] + parts = [] + if unjudged: + parts.append( + f"Your last turn wrote {_count(len(unjudged))} that nobody has judged yet. " + "You built them, so you know what each one is — record it alongside this " + "turn's work, while that is still true, so the next session starts from your " + "answer instead of rebuilding it:\n" + + "\n".join(_shape_lines(unjudged, project_id=project_id)) + ) + if earlier: + verb = "is" if len(earlier) == 1 else "are" + parts.append( + f"{'Also: ' if unjudged else ''}{_count(len(earlier))} you wrote earlier in this " + f"session {verb} still unjudged. You were asked and moved on; nothing else will " + "name them again, so they are asked once more while you still know what they " + "are:\n" + + "\n".join(_shape_lines(earlier, project_id=project_id)) + ) repo_arg = f', repo="{repo}"' if repo else "" return ( - f"Your last turn wrote {len(unjudged)} definition{'s' if len(unjudged) != 1 else ''} " - "that nobody has judged yet. You built them, so you know what each one is — " - "record it alongside this turn's work, while that is still true, so the next " - "session starts from your answer instead of rebuilding it:\n" - + "\n".join(lines) + "\n\n".join(parts) + "\n\nFor each: something another part of the code should reuse → record it " "with create_snippet (name, code, when to reach for it, location); built from a " "recorded snippet → `instance` of it; a deliberate departure from one → " @@ -105,6 +136,13 @@ def note_text(unjudged: list[dict], *, project_id: int, repo: str) -> str: ) +def ledger_lines(items: list[dict]) -> str: + """``items`` back as the hook's own `pathkindname` lines — what + the after phase hands the hook so it can carry the walked-past shapes + forward without parsing a JSON list in shell.""" + return "\n".join(f"{i['path']}\t{i['kind']}\t{i['symbol']}" for i in items) + + async def record_shape_check( user_id: int | None, outcome: str, @@ -112,12 +150,17 @@ async def record_shape_check( written: int, unjudged: int, project_id: int | None = None, + earlier: int = 0, ) -> None: if outcome not in OUTCOMES: raise ValueError(f"unknown shape-check outcome {outcome!r}") details: dict = {"outcome": outcome, "written": written, "unjudged": unjudged} if project_id: details["project_id"] = project_id + # How many of `unjudged` were carried from an earlier turn's walked-past + # ask — so a window can tell a fresh ask from a repeat. + if earlier: + details["earlier"] = earlier async with async_session() as session: session.add(AppLog( category="plugin", diff --git a/tests/test_services_shape_check.py b/tests/test_services_shape_check.py index 69b54bf6..8ed5c0ff 100644 --- a/tests/test_services_shape_check.py +++ b/tests/test_services_shape_check.py @@ -91,3 +91,37 @@ def test_the_window_counts_turns_asks_and_asks_walked_past(): # A window that spans the end-of-turn hold this check once was still sums. mixed = summarise(["blocked", "left_after_block", "noted", "judged_after_note"]) assert mixed == {"checked": 2, "asked": 2, "left": 1} + + +def test_the_note_names_walked_past_shapes_apart_from_this_turns(): + from grimoire.services.shape_check import note_text + + fresh = [{"path": "a.py", "kind": "sym", "symbol": "new_one", "status": "new", "evidence": {}}] + old = [{"path": "b.py", "kind": "sym", "symbol": "old_one", "status": "unclassified", + "evidence": {}}] + both = note_text(fresh, project_id=2, repo="", earlier=old) + assert "last turn wrote 1 definition " in both + assert "Also: 1 definition you wrote earlier in this session is still unjudged" in both + assert both.index("a.py · new_one") < both.index("b.py · old_one") + alone = note_text([], project_id=2, repo="", earlier=old + old) + assert "last turn" not in alone + assert alone.startswith("2 definitions you wrote earlier in this session are still unjudged") + assert "classify_shapes(project_id=2" in alone + + +def test_the_after_phase_hands_back_ledger_lines(): + from grimoire.services.shape_check import ledger_lines + + items = [{"path": "a.py", "kind": "sym", "symbol": "f"}, + {"path": "w/A.svelte", "kind": "file", "symbol": "A"}] + assert ledger_lines(items) == "a.py\tsym\tf\nw/A.svelte\tfile\tA" + assert ledger_lines([]) == "" + + +async def test_a_repeat_is_counted_apart_in_the_outcome_record(): + from grimoire.services.shape_check import record_shape_check + + session = make_mock_session() + with patch("grimoire.services.shape_check.async_session", return_value=session): + await record_shape_check(7, "noted", written=3, unjudged=2, project_id=2, earlier=1) + assert json.loads(session.add.call_args.args[0].details)["earlier"] == 1 diff --git a/tests/test_shape_check_hook.py b/tests/test_shape_check_hook.py index 093a2e9b..a4205fcb 100644 --- a/tests/test_shape_check_hook.py +++ b/tests/test_shape_check_hook.py @@ -237,3 +237,61 @@ def test_an_unreachable_instance_keeps_the_question_for_later(tmp_path): ledger = _write_ledger(tmp_path, ["a.py\tsym\thelper"]) assert _stop(env, _repo(tmp_path)) == "" assert ledger.exists() + + +# ── what the agent walked past is asked again, a bounded number of times ── + +def _earlier_file(tmp_path, session="s1"): + return tmp_path / "grimoire-shapecheck" / f"{session}.earlier" + + +def test_a_walked_past_shape_is_named_again_then_dropped(tmp_path): + """The after phase's `left` becomes the carried set: the next check sends + it as `earlier` even on a turn that wrote nothing, and a shape walked + past more than GRIMOIRE_EARLIER_MAX times stops being asked.""" + reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE, + "left": "a.py\tsym\tfirst"}).encode() + with http_sink(reply) as (port, seen): + env = _env(tmp_path, f"http://127.0.0.1:{port}") + repo = _repo(tmp_path) + _write_ledger(tmp_path, ["a.py\tsym\tfirst"]) + _stop(env, repo) + assert seen[-1]["phase"] == ["check"] and "earlier" not in seen[-1] + + for walked_past in (1, 2): + _prompt(env, repo) + _stop(env, repo) + after, check = seen[-2], seen[-1] + assert after["phase"] == ["after"] + assert check["phase"] == ["check"] + assert check["earlier"] == ["a.py\tsym\tfirst"] + assert "written" not in check, "this turn wrote nothing; the repeat is named apart" + assert _earlier_file(tmp_path).read_text() == f"{walked_past}\ta.py\tsym\tfirst\n" + + _prompt(env, repo) + _stop(env, repo) + assert seen[-1]["phase"] == ["after"], "walked past a third time: not asked again" + assert seen[-1]["earlier"] == ["a.py\tsym\tfirst"] + assert not _earlier_file(tmp_path).exists() + + +def test_a_carried_shape_this_turn_rewrote_is_this_turns(tmp_path): + reply = json.dumps({"status": "ok", "outcome": "noted", "note": NOTE}).encode() + with http_sink(reply) as (port, seen): + env = _env(tmp_path, f"http://127.0.0.1:{port}") + _earlier_file(tmp_path).parent.mkdir(parents=True, exist_ok=True) + _earlier_file(tmp_path).write_text("1\ta.py\tsym\tfirst\n1\tb.py\tsym\tother\n") + _write_ledger(tmp_path, ["a.py\tsym\tfirst"]) + _stop(env, _repo(tmp_path)) + assert seen[-1]["written"] == ["a.py\tsym\tfirst"] + assert seen[-1]["earlier"] == ["b.py\tsym\tother"] + + +def test_a_check_with_nothing_unjudged_forgets_the_carried_set(tmp_path): + with http_sink(b'{"status":"ok","outcome":"passed","unjudged":[]}') as (port, seen): + env = _env(tmp_path, f"http://127.0.0.1:{port}") + _earlier_file(tmp_path).parent.mkdir(parents=True, exist_ok=True) + _earlier_file(tmp_path).write_text("1\ta.py\tsym\tfirst\n") + _stop(env, _repo(tmp_path)) + assert seen[-1]["earlier"] == ["a.py\tsym\tfirst"] + assert not _earlier_file(tmp_path).exists(), "judged since: nothing left to carry" From de55b73075fa02dc897d9fc4808cce0cb459464f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 09:41:09 -0500 Subject: [PATCH 2/9] fix(8140): family triggers open only records that can carry an idea, and enter_project names a project's unevaluated candidates Tasks, non-knowledge kinds and records titled for their own project are never opened as candidates by the citation or repeat trigger; a lineage word inside a quoted title no longer reads as lineage. The family line counts and names this project's own candidates that only the system has decided on. Co-Authored-By: Claude Opus 5.5 --- plugin/skills/family-canon/SKILL.md | 4 + src/grimoire/mcp/tools/projects.py | 5 +- src/grimoire/services/family.py | 97 +++++++++++++++++++++- src/grimoire/services/family_adoption.py | 35 ++++++-- tests/test_family.py | 36 ++++++++ tests/test_family_delivery.py | 12 +++ tests/test_integration_family_promotion.py | 46 ++++++++++ 7 files changed, 224 insertions(+), 11 deletions(-) diff --git a/plugin/skills/family-canon/SKILL.md b/plugin/skills/family-canon/SKILL.md index c3e1d62e..890a1117 100644 --- a/plugin/skills/family-canon/SKILL.md +++ b/plugin/skills/family-canon/SKILL.md @@ -45,6 +45,10 @@ face, and if so write the note that carries the idea. enter_project's `family` key counts what this project owes the family: `unassessed`, `owed`, `needs_recheck`, each with the call that lists them. +It also names this project's own records that a trigger proposed and nobody +evaluated (`candidates`): you hold their context, so evaluate each as above, +or `retire_family_idea` one that is not an idea at all (a task, a note about +this project alone). Answer an idea **when your work reaches its area**, not as a chore list at session start — the count is there so it is never invisible, not so it preempts the operator's task. diff --git a/src/grimoire/mcp/tools/projects.py b/src/grimoire/mcp/tools/projects.py index 2ea28a5f..2156c458 100644 --- a/src/grimoire/mcp/tools/projects.py +++ b/src/grimoire/mcp/tools/projects.py @@ -140,7 +140,10 @@ async def enter_project(project_id: int) -> dict: version (`needs_recheck`) — each with the list_family_adoptions call that lists them. Answer an unassessed idea when your work reaches its area (get_family_adoption, then assess_family_adoption, or classify the code - against it); the family-canon skill has the order. + against it); the family-canon skill has the order. It also counts this + project's own records that a trigger proposed as family ideas and nobody + has evaluated (`candidates`), naming them: this project's session holds + their context, so it is the one asked to promote or retire each. `inception` appears ONLY when the project is yours and nobody has decided what it inherits: it carries the current defaults diff --git a/src/grimoire/services/family.py b/src/grimoire/services/family.py index f457aa98..69a2d1c4 100644 --- a/src/grimoire/services/family.py +++ b/src/grimoire/services/family.py @@ -115,6 +115,9 @@ _LINEAGE = re.compile( ) # How far before a `#N` the lineage word may sit: the same clause, roughly. _LINEAGE_WINDOW = 80 +# A quoted title, straight or curly quotes, on one line. Bounded so a stray +# quote mark cannot blank a whole paragraph. +_QUOTED = re.compile(r'"[^"\n]{1,200}"|\u201c[^\u201d\n]{1,200}\u201d') # Note kinds the repeat trigger compares: recorded knowledge and shapes, not # the to-do list — and each only against its own kind. A repeat is the same @@ -127,6 +130,38 @@ _LINEAGE_WINDOW = 80 # once the idea is canon. _REPEAT_KINDS = ("snippet", "note") + +def about_its_own_project(title: str | None, project_title: str | None) -> bool: + """Whether a record's title opens with its own project's name. + + "Storehouse: start here", "Torn Stars — Economy System": a record named + for its project describes that project — its overview, its founding + decisions, one system of one game — and cannot carry an idea every + project on a platform shares, however closely another project's + overview resembles it. The name must end at a word boundary, so a + project called "Sync" does not claim "Syncthing relay". + """ + t = (title or "").strip().casefold() + p = (project_title or "").strip().casefold() + if not p or not t.startswith(p): + return False + return len(t) == len(p) or not t[len(p)].isalnum() + + +def can_carry_idea(*, is_task: bool, note_type: str | None, title: str | None, + project_title: str | None) -> bool: + """Whether a record is the kind a trigger may open as a family candidate. + + A task is a unit of work in one project, so it is never the idea itself: + an idea it carries is written up as a note and proposed. Only recorded + knowledge and shapes (`_REPEAT_KINDS`) qualify, and not a record about + its own project (`about_its_own_project`). The triggers open candidates + without anyone reading them, so they hold to this; an agent who has read + a record may still propose it by hand.""" + if is_task or (note_type or "note") not in _REPEAT_KINDS: + return False + return not about_its_own_project(title, project_title) + MEMBER_STATES = ("declared", "detected") _IDEA_ACTIONS = ("propose", "promote", "revise", "retire") @@ -862,9 +897,15 @@ def lineage_citations(text: str | None) -> list[int]: from grimoire.services.record_refs import REF_RE found: list[int] = [] - for m in REF_RE.finditer(text or ""): + text = text or "" + # A quoted span is a record's TITLE, written beside its id by convention + # (#12 "Release parsing and matching"). Its words describe that record, + # not this one's lineage, so they are blanked before the window is read; + # blanked to the same length, so match positions stay valid. + bare = _QUOTED.sub(lambda q: " " * len(q.group(0)), text) + for m in REF_RE.finditer(text): start = max(0, m.start() - _LINEAGE_WINDOW) - window = text[start:m.start()] + window = bare[start:m.start()] window = re.split(r"[\n.;]", window)[-1] if _LINEAGE.search(window): n = int(m.group(1)) @@ -873,6 +914,41 @@ def lineage_citations(text: str | None) -> list[int]: return found +async def _project_titles(session, project_ids: set[int]) -> dict[int, str]: + return dict((await session.execute( + select(Project.id, Project.title).where(Project.id.in_(project_ids)) + )).all()) + + +async def unevaluated_candidates(user_id: int, project_id: int, *, limit: int = 5) -> dict: + """This project's own records that are family candidates nobody has + evaluated: every decision on them so far is the system's own proposal. + + The triggers open candidates; nothing else asks anyone to evaluate one, + so without a reader they only accumulate. The project a candidate lives + in is where its context is, so its own sessions are asked, on entering. + {count, ideas: [{id, title}]}, oldest first, up to ``limit`` named.""" + judged = select(FamilyDecision.idea_id).where( + FamilyDecision.idea_id == FamilyIdea.note_id, + FamilyDecision.decided_via != "system", + ).exists() + where = ( + FamilyIdea.status == "candidate", Note.project_id == project_id, + Note.deleted_at.is_(None), access.readable_notes_clause(user_id), ~judged, + ) + async with async_session() as session: + count = (await session.execute( + select(func.count()).select_from(FamilyIdea) + .join(Note, Note.id == FamilyIdea.note_id).where(*where) + )).scalar() or 0 + rows = (await session.execute( + select(Note.id, Note.title).select_from(FamilyIdea) + .join(Note, Note.id == FamilyIdea.note_id).where(*where) + .order_by(FamilyIdea.created_at.asc()).limit(limit) + )).all() if count else [] + return {"count": int(count), "ideas": [{"id": i, "title": t} for i, t in rows]} + + async def _member_platform_ids(session, project_id: int) -> set[int]: return set((await session.execute( select(ProjectPlatform.platform_id).where( @@ -902,14 +978,20 @@ async def citation_trigger(user_id: int, note) -> str | None: return None async with async_session() as session: rows = (await session.execute( - select(Note.id, Note.title, Note.project_id, Project.title) + select(Note.id, Note.title, Note.project_id, Project.title, + Note.status, Note.note_type) .join(Project, Project.id == Note.project_id) .where( Note.id.in_(cited), Note.deleted_at.is_(None), Note.project_id.is_not(None), Note.project_id != note.project_id, ) )).all() - for source_id, source_title, _pid, project_title in sorted(rows, key=lambda r: cited.index(r[0])): + for source_id, source_title, _pid, project_title, status, note_type in sorted( + rows, key=lambda r: cited.index(r[0]), + ): + if not can_carry_idea(is_task=status is not None, note_type=note_type, + title=source_title, project_title=project_title): + continue if not await access.can_write_note(user_id, source_id): continue idea, created = await propose( @@ -944,6 +1026,9 @@ async def repeat_trigger(user_id: int, note) -> str | None: if not getattr(note, "project_id", None) or note.is_task or kind not in _REPEAT_KINDS: return None async with async_session() as session: + titles = await _project_titles(session, {note.project_id}) + if about_its_own_project(note.title, titles.get(note.project_id)): + return None mine = await _member_platform_ids(session, note.project_id) if not mine: return None @@ -958,6 +1043,10 @@ async def repeat_trigger(user_id: int, note) -> str | None: if (other.note_type or "note") != kind: continue async with async_session() as session: + other_project = (await _project_titles(session, {other.project_id})).get(other.project_id) + if not can_carry_idea(is_task=other.is_task, note_type=other.note_type, + title=other.title, project_title=other_project): + continue shared = mine & await _member_platform_ids(session, other.project_id) if not shared or not await access.can_write_note(user_id, other.id): continue diff --git a/src/grimoire/services/family_adoption.py b/src/grimoire/services/family_adoption.py index e8ff5c79..75659a31 100644 --- a/src/grimoire/services/family_adoption.py +++ b/src/grimoire/services/family_adoption.py @@ -1222,10 +1222,13 @@ async def _shapes_follow(user_id: int, project_id: int, idea_id: int, outcome: s # ideas themselves by retrieval, and the owed answers filed while a task was # open, handed back when it closes. -def family_line(project_id: int, cells: list[dict]) -> dict | None: +def family_line(project_id: int, cells: list[dict], + candidates: dict | None = None) -> dict | None: """The `family` line enter_project carries: what this project has not - answered, owes, or answered against an older canon version. None when - all three are zero — the key is attached only when it asks something. + answered, owes, or answered against an older canon version — and which + of its own records are family candidates nobody has evaluated + (`family.unevaluated_candidates`). None when all are zero — the key is + attached only when it asks something. Shown on EVERY entry (the step settled this), not only when a session touches a platform: entering is when the agent chooses what to work on, @@ -1234,7 +1237,9 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None: unassessed = sum(1 for c in cells if c["in_scope"] and c["status"] == "unassessed") owed = sum(1 for c in cells if c["status"] == "owed") recheck = sum(1 for c in cells if c["needs_recheck"]) - if not (unassessed or owed or recheck): + candidates = candidates or {} + n_cand = int(candidates.get("count") or 0) + if not (unassessed or owed or recheck or n_cand): return None parts, calls = [], {} if unassessed: @@ -1246,9 +1251,23 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None: if recheck: parts.append(f"{recheck} to recheck") calls["needs_recheck"] = f"list_family_adoptions(project_id={project_id}, needs_recheck=true)" + if n_cand: + # Named by id: the list tool pages every project's ideas, and these + # are the few that this project's own session is placed to judge. + named = ", ".join(f"#{c['id']} \"{c['title']}\"" for c in candidates.get("ideas") or []) + more = n_cand - len(candidates.get("ideas") or []) + parts.append(f"{n_cand} of this project's own record{'s' if n_cand != 1 else ''} " + "proposed as family ideas, never evaluated") + calls["candidates"] = ( + f"get_family_idea(id) for each — {named}" + + (f", and {more} more (list_family_ideas(status=\"candidate\"))" if more > 0 else "") + + "; then promote_family_idea if all three criteria hold, or " + "retire_family_idea if it is not an idea at all" + ) return { "line": "family canon on this project's platforms: " + " · ".join(parts), "unassessed": unassessed, "owed": owed, "needs_recheck": recheck, + "candidates": n_cand, "calls": calls, "answer_with": ("get_family_adoption(project_id, idea_id) reads one with its " "precedents; assess_family_adoption answers it — or classify_shapes " @@ -1257,8 +1276,11 @@ def family_line(project_id: int, cells: list[dict]) -> dict | None: async def family_readout(user_id: int, project_id: int) -> dict | None: + from grimoire.services import family as family_svc + matrix = await adoption_matrix(user_id, project_id=project_id) - return family_line(project_id, matrix["cells"]) + candidates = await family_svc.unevaluated_candidates(user_id, project_id) + return family_line(project_id, matrix["cells"], candidates) # --- whether the line reached the project --------------------------------------- @@ -1285,7 +1307,8 @@ async def record_entry(user_id: int, project_id: int, line: dict | None, *, if failed: details["readout_failed"] = True if line: - details.update({k: int(line.get(k) or 0) for k in ("unassessed", "owed", "needs_recheck")}) + details.update({k: int(line.get(k) or 0) + for k in ("unassessed", "owed", "needs_recheck", "candidates")}) try: async with async_session() as session: session.add(AppLog( diff --git a/tests/test_family.py b/tests/test_family.py index f11ae610..5dc66c10 100644 --- a/tests/test_family.py +++ b/tests/test_family.py @@ -161,3 +161,39 @@ async def test_re_saving_a_closed_milestone_asks_nothing(): out = await update_milestone(project_id=3, milestone_id=5, status="done") assert "family_hint" not in out trigger.assert_not_awaited() + + +def test_a_lineage_word_inside_a_quoted_title_is_not_lineage(): + """Records are cited with their titles beside them; a title's words + describe THAT record, so they cannot claim the next citation's lineage.""" + text = ('- Tasks: #3510 "Release parsing and matching, verified", #7407 "Downloads", ' + '#20 “mirrors the old flow”, #30') + assert lineage_citations(text) == [] + # The convention itself still reads: a lineage word outside the quotes. + assert lineage_citations('Ported from #12 "Signed APK lane".') == [12] + + +@pytest.mark.parametrize(("title", "project", "about"), [ + ("Storehouse: start here", "Storehouse", True), + ("Torn Stars — Economy System", "Torn Stars", True), + ("storehouse", "Storehouse", True), + ("Syncthing relay", "Sync", False), + ("Signed APK lane", "Storehouse", False), + ("Storehouse: start here", "", False), +]) +def test_a_record_named_for_its_own_project_is_about_that_project(title, project, about): + from grimoire.services.family import about_its_own_project + + assert about_its_own_project(title, project) is about + + +def test_only_knowledge_and_shapes_not_about_one_project_can_carry_an_idea(): + from grimoire.services.family import can_carry_idea + + kw = dict(title="Signed APK lane", project_title="android one") + assert can_carry_idea(is_task=False, note_type="note", **kw) + assert can_carry_idea(is_task=False, note_type="snippet", **kw) + assert not can_carry_idea(is_task=True, note_type="note", **kw) + assert not can_carry_idea(is_task=False, note_type="lesson", **kw) + assert not can_carry_idea(is_task=False, note_type="note", + title="android one: start here", project_title="android one") diff --git a/tests/test_family_delivery.py b/tests/test_family_delivery.py index c207e465..1ad405b1 100644 --- a/tests/test_family_delivery.py +++ b/tests/test_family_delivery.py @@ -97,3 +97,15 @@ def test_every_surface_that_meets_family_canon_points_at_the_skill(): assert "`family`" in tool_doc("grimoire.mcp.tools.projects", "enter_project") assert "family_owed" in tool_doc("grimoire.mcp.tools.tasks", "update_task") assert "family_owed" in skill_text("reporting-back") + + +def test_the_line_names_this_projects_own_unevaluated_candidates(): + cand = {"count": 3, "ideas": [{"id": 7, "title": "Signed APK lane"}, + {"id": 9, "title": "Outbox"}]} + line = family_line(5, [], cand) + assert line["candidates"] == 3 + assert line["line"].endswith("3 of this project's own records proposed as family ideas, never evaluated") + call = line["calls"]["candidates"] + assert '#7 "Signed APK lane", #9 "Outbox"' in call and "and 1 more" in call + assert "promote_family_idea" in call and "retire_family_idea" in call + assert family_line(5, [], {"count": 0, "ideas": []}) is None diff --git a/tests/test_integration_family_promotion.py b/tests/test_integration_family_promotion.py index 618b1347..cac35e4b 100644 --- a/tests/test_integration_family_promotion.py +++ b/tests/test_integration_family_promotion.py @@ -396,3 +396,49 @@ async def test_someone_who_cannot_write_the_idea_cannot_link_it(family, topics): await _promote(family) with pytest.raises(ValueError, match="no write access"): await family_svc.set_topic(family["outsider"], family["note"], topics["spare"]) + + +async def test_a_citation_of_a_task_or_of_a_projects_own_overview_is_silent(family): + """A task is work in one project and an overview describes one project: + neither carries a shared idea, so citing either with a lineage word opens + nothing.""" + async with async_session() as s: + task = Note(user_id=family["owner"], project_id=family["a"], status="todo", + title="Ship the signed lane", body="do it") + overview = Note(user_id=family["owner"], project_id=family["a"], + title="android one: start here", body="what the project is") + s.add_all([task, overview]) + await s.commit() + ids = (task.id, overview.id) + for source in ids: + citing = await _note_in(family["b"], family["owner"], f"Matching #{source}.") + assert await family_svc.citation_trigger(family["owner"], citing) is None + assert await _idea(source) is None + + +async def test_a_repeat_of_a_projects_own_overview_is_silent(family): + async with async_session() as s: + overview = Note(user_id=family["owner"], project_id=family["a"], + title="android one: start here", body="One keystore, two channels.") + s.add(overview) + await s.commit() + await s.refresh(overview) + repeat = await _note_in(family["b"], family["owner"], "One keystore, two channels.") + with patch("grimoire.services.embeddings.semantic_search_notes", + AsyncMock(return_value=[(0.9, overview)])): + assert await family_svc.repeat_trigger(family["owner"], repeat) is None + assert await _idea(overview.id) is None + + +async def test_a_candidate_counts_as_unevaluated_until_someone_other_than_the_system_decides(family): + await family_svc.propose(family["owner"], family["note"], reason="opened by a trigger", + trigger="repeat", decided_via="system") + got = await family_svc.unevaluated_candidates(family["owner"], family["a"]) + assert got == {"count": 1, "ideas": [{"id": family["note"], "title": "Signed APK lane"}]} + assert (await family_svc.unevaluated_candidates(family["owner"], family["b"]))["count"] == 0 + # An agent's evaluation that holds it as a candidate is an evaluation. + await family_svc.promote(family["owner"], family["note"], applies_when="", + platforms=["android-app"], criteria={}, evidence=[], + reason="held: not stated for the platform") + assert (await _idea(family["note"])).status == "candidate" + assert (await family_svc.unevaluated_candidates(family["owner"], family["a"]))["count"] == 0 From 2903b090a19340da0f226e4d9195515c69f14bb3 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 09:51:00 -0500 Subject: [PATCH 3/9] fix(8139): the carried lines go to the after phase without a trailing newline Co-Authored-By: Claude Opus 5.5 --- plugin/.claude-plugin/plugin.json | 2 +- plugin/hooks/grimoire_shape_check.sh | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 708c1ccb..07a1c6f3 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "grimoire", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.11.27.1440", + "version": "2026.11.27.1451", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/hooks/grimoire_shape_check.sh b/plugin/hooks/grimoire_shape_check.sh index 3434f660..68014d13 100644 --- a/plugin/hooks/grimoire_shape_check.sh +++ b/plugin/hooks/grimoire_shape_check.sh @@ -116,7 +116,8 @@ if [ -s "$asked_file" ] || [ -s "$asked_earlier_file" ]; then asked_q="&written=${asked_enc}" fi if [ -s "$asked_earlier_file" ]; then - prior_enc=$(_unique "$asked_earlier_file" | grimoire_urlenc) || prior_enc="" + prior=$(_unique "$asked_earlier_file") + prior_enc=$(printf '%s' "$prior" | grimoire_urlenc) || prior_enc="" [ -n "$prior_enc" ] && asked_q="${asked_q}&earlier=${prior_enc}" fi if after=$(curl -fsS --max-time 4 \ From 706f49a12a5b1ce15466982d986b83183253737c Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 09:56:19 -0500 Subject: [PATCH 4/9] fix(fence): the cross-project permission prompt says what changes and where first, in plain words The first line names the act and the project it lands in against the one the session works in; the second says when to approve; the agent's issue-filing call moves to a last line in parentheses. Tool names are spelled out and project ids dropped from the operator's text. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/services/write_scope.py | 35 ++++++++++++++++++++-------- tests/test_write_scope.py | 13 ++++++----- 2 files changed, 32 insertions(+), 16 deletions(-) diff --git a/src/grimoire/services/write_scope.py b/src/grimoire/services/write_scope.py index c04d4de1..384fe096 100644 --- a/src/grimoire/services/write_scope.py +++ b/src/grimoire/services/write_scope.py @@ -303,8 +303,21 @@ async def _titles(ids: list[int]) -> dict[int, str]: def _named(project_id: int, titles: dict[int, str]) -> str: - title = titles.get(project_id) - return f"{title} (project {project_id})" if title else f"project {project_id}" + return titles.get(project_id) or f"project {project_id}" + + +def _doing(tool: str, act: str) -> str: + """The act in words a person reads at a glance: "Retire family idea", + "git push", "Editing a file". A tool name is spelled out, not quoted.""" + act = act.strip() + if act.endswith(" in"): + act = act[:-3] + if act: + return act[:1].upper() + act[1:] + if tool: + words = tool.replace("_", " ").strip() + return words[:1].upper() + words[1:] + return "This change" async def check_act( @@ -343,22 +356,24 @@ async def check_act( targets = [{"id": p, "title": titles.get(p, "")} for p in others] if tool and is_issue_filing(tool, args): return {"allowed": True, "targets": targets, "issue": True, "reason": ""} + # The reason is the permission prompt's text: the operator reads it + # first, so it leads with what changes and where, then when to approve. + # The session reads it after a "no", so the last line is for the agent. there = ", ".join(_named(p, titles) for p in others) + home = _named(session_project, titles) if tool in RULE_CURATION_TOOLS: rules = sorted({r for name in _RULE_ARGS for r in _positive_ints(args.get(name))}) which = ", ".join(f"rule {r}" for r in rules) or "a rule" reason = ( - f"This session belongs to {_named(session_project, titles)}. {tool} changes " - f"{which} of {there}, a different project. Rules are the operator's to " - f"curate from any session: approve if they asked for this change." + f"Changing {which} in {there}, but this session is working in {home}.\n" + "Rules are yours to curate from any session. Approve if you asked for this change." ) return {"allowed": False, "targets": targets, "issue": False, "reason": reason} - what = act.strip() or (f"{tool} changes" if tool else "This changes") first = others[0] reason = ( - f"This session belongs to {_named(session_project, titles)}. {what} {there}, " - f"a different project. From here, the one change to make there is filing an " - f"issue: create_task(project_id={first}, kind=\"issue\") with how it was found " - f"and the evidence. Approve only if this session should change {there} itself." + f"{_doing(tool, act)} in {there}, but this session is working in {home}.\n" + f"Approve only if you asked for this change to {there}.\n" + f"(If not: the agent can report it there instead, with " + f"create_task(project_id={first}, kind=\"issue\").)" ) return {"allowed": False, "targets": targets, "issue": False, "reason": reason} diff --git a/tests/test_write_scope.py b/tests/test_write_scope.py index 98677a62..87b544e5 100644 --- a/tests/test_write_scope.py +++ b/tests/test_write_scope.py @@ -147,9 +147,10 @@ async def test_a_write_in_another_project_asks_and_says_how_to_file_an_issue_ins out = await check_act(1, 2, tool="update_task", args={"task_id": 5}) assert out["allowed"] is False assert out["targets"] == [{"id": 9, "title": "Elsewhere"}] - assert "Home (project 2)" in out["reason"] - assert "Elsewhere (project 9)" in out["reason"] - assert 'create_task(project_id=9, kind="issue")' in out["reason"] + first, ask, agent = out["reason"].split("\n") + assert first == "Update task in Elsewhere, but this session is working in Home." + assert ask == "Approve only if you asked for this change to Elsewhere." + assert 'create_task(project_id=9, kind="issue")' in agent async def test_a_rule_edit_in_another_project_names_the_rule_and_suggests_no_issue(): @@ -157,12 +158,12 @@ async def test_a_rule_edit_in_another_project_names_the_rule_and_suggests_no_iss with a, b, c: out = await check_act(1, 2, tool="update_rule", args={"rule_id": 130, "salience": "low"}) assert out["allowed"] is False - assert "rule 130 of Elsewhere (project 9)" in out["reason"] + assert out["reason"].startswith("Changing rule 130 in Elsewhere, but this session is working in Home.") assert "create_task" not in out["reason"] with a, b, c: related = await check_act(1, 2, tool="relate_rules", args={"from_rule_id": 4, "to_rule_id": 130, "kind": "overrides"}) - assert "rule 4, rule 130 of" in related["reason"] + assert related["reason"].startswith("Changing rule 4, rule 130 in Elsewhere") async def test_filing_an_issue_in_another_project_goes_ahead(): @@ -192,7 +193,7 @@ async def test_a_directory_in_another_project_asks_in_the_words_of_the_act(): out = await check_act(1, 2, target_project=9, act="git push in") same = await check_act(1, 2, target_project=2, act="git push in") assert out["allowed"] is False - assert "git push in Elsewhere (project 9)" in out["reason"] + assert out["reason"].startswith("Git push in Elsewhere, but this session is working in Home.") assert same["allowed"] is True From 65f1be80b690d3b6a024f9dd70d168a8548a88b9 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 14:12:14 -0500 Subject: [PATCH 5/9] feat(8141): every gate that stops a tool call is recorded, with what followed A rule set to enforce or hold, the act checkpoint and the project fence stopped work and left no record. The hook that makes each stop now reports it to POST /api/plugin/gate-stop; the hook decides, not the server, because the per-rule and per-session caps are kept in the plugin. - gate_stops table (migration 0138): gate, outcome (stopped / let_through / asked), rule, where it was reached, tool, target project, call id. - An open of the rule stamps the stop as cleared (rule-opened). A fenced call that then runs stamps ran: grimoire_fence_ran.sh, a PostToolUse on the fenced tools, matches the call id the fence left pending. That is the operator's yes. - A hold or checkpoint the spent session budget lets through is reported as let_through; the per-rule once is not. - The readout: by gate and by rule, stops, cleared by a read, misfired (rule_misfired after it), let through by the cap, ran. In retrieval_telemetry as `gates`, at /api/retrieval/gate-stops, and on the Moments settings page ("When a rule stopped the work"). - act_decision carries `at`, the moment the deciding rule was reached at. Co-Authored-By: Claude Opus 5.5 --- alembic/versions/0138_gate_stops.py | 49 +++++ frontend/src/api/moments.ts | 42 ++++ frontend/src/components/GateStops.vue | 121 +++++++++++ frontend/src/components/MomentsSettings.vue | 23 +- plugin/PACKAGING.md | 7 +- plugin/hooks/grimoire_defs.sh | 46 ++++ plugin/hooks/grimoire_fence_ran.sh | 53 +++++ plugin/hooks/grimoire_moment.sh | 15 +- plugin/hooks/grimoire_project_fence.sh | 18 ++ plugin/hooks/grimoire_tool_rules.sh | 11 +- plugin/hooks/hooks.json | 9 + scripts/check_plugin.py | 7 + src/grimoire/mcp/tools/search.py | 21 ++ src/grimoire/models/__init__.py | 1 + src/grimoire/models/gate_stop.py | 88 ++++++++ src/grimoire/routes/plugin.py | 53 +++++ src/grimoire/routes/retrieval.py | 15 ++ src/grimoire/services/backup.py | 3 + src/grimoire/services/gate_stops.py | 217 +++++++++++++++++++ src/grimoire/services/retrieval_pipeline.py | 7 +- src/grimoire/services/retrieval_telemetry.py | 11 + src/grimoire/services/rule_deliveries.py | 6 +- tests/test_gate_stop_hooks.py | 196 +++++++++++++++++ tests/test_integration_gate_stops.py | 122 +++++++++++ 24 files changed, 1128 insertions(+), 13 deletions(-) create mode 100644 alembic/versions/0138_gate_stops.py create mode 100644 frontend/src/components/GateStops.vue create mode 100644 plugin/hooks/grimoire_fence_ran.sh create mode 100644 src/grimoire/models/gate_stop.py create mode 100644 src/grimoire/services/gate_stops.py create mode 100644 tests/test_gate_stop_hooks.py create mode 100644 tests/test_integration_gate_stops.py diff --git a/alembic/versions/0138_gate_stops.py b/alembic/versions/0138_gate_stops.py new file mode 100644 index 00000000..57540682 --- /dev/null +++ b/alembic/versions/0138_gate_stops.py @@ -0,0 +1,49 @@ +"""gate stops: each time a Grimoire gate stood in front of a tool call + +Revision ID: 0138 +Revises: 0137 +Create Date: 2026-11-27 + +A row per stop the plugin made: a moment rule set to enforce or hold, the +act checkpoint, or the project fence asking the operator. With whether the +session then opened the rule (`cleared_at`) and whether the stopped call ran +after all (`ran_at`), so how often each gate stops work, for which rule, and +whether it cleared the way it is meant to can be read. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0138" +down_revision = "0137" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "gate_stops", + sa.Column("id", sa.BigInteger(), primary_key=True), + sa.Column("user_id", sa.BigInteger(), nullable=False), + sa.Column("session_id", sa.Text(), nullable=False), + sa.Column("gate", sa.Text(), nullable=False), + sa.Column("outcome", sa.Text(), nullable=False), + sa.Column("rule_id", sa.BigInteger(), nullable=True), + sa.Column("tool", sa.Text(), nullable=False), + sa.Column("at", sa.Text(), nullable=True), + sa.Column("target", sa.Text(), nullable=True), + sa.Column("call_id", sa.Text(), nullable=True), + sa.Column("stopped_at", sa.DateTime(timezone=True), nullable=False, + server_default=sa.func.now()), + sa.Column("cleared_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("ran_at", sa.DateTime(timezone=True), nullable=True), + sa.Column("plugin", sa.Text(), nullable=True), + ) + op.create_index("ix_gate_stops_session_rule", "gate_stops", + ["user_id", "session_id", "rule_id", "stopped_at"]) + op.create_index("ix_gate_stops_stopped_at", "gate_stops", ["stopped_at"]) + + +def downgrade() -> None: + op.drop_index("ix_gate_stops_stopped_at", table_name="gate_stops") + op.drop_index("ix_gate_stops_session_rule", table_name="gate_stops") + op.drop_table("gate_stops") diff --git a/frontend/src/api/moments.ts b/frontend/src/api/moments.ts index 0815a37c..e02bb439 100644 --- a/frontend/src/api/moments.ts +++ b/frontend/src/api/moments.ts @@ -340,6 +340,48 @@ export function getRecordReach(days = 30): Promise { return apiGet(`/api/retrieval/record-reach?days=${days}`); } +/** The gates that can stop a tool call. */ +export type GateName = "enforce" | "hold" | "checkpoint" | "fence"; + +export interface GateCounts { + /** Calls denied, or for the fence, put to the operator. */ + stops: number; + /** Calls a hold would have stopped, let through because the session's + * stop budget was spent. */ + let_through: number; + /** Stops the session cleared by opening the rule. */ + cleared: number; + /** Stops whose rule the session then reported as a misfire. */ + misfired: number; + /** Stopped calls that ran after all; for the fence, the operator's yes. */ + ran: number; +} + +export interface GateRuleRow extends GateCounts { + rule_id: number; + gate: GateName; + /** The moment or arm the rule was reached at. */ + at: string | null; + title: string | null; + sessions: number; + last_stopped_at: string | null; +} + +export interface GateStopsPayload { + days: number; + by_gate: Record; + by_rule: GateRuleRow[]; + fence: { tool: string; target: string | null; asks: number; ran: number }[]; + /** The first stop ever recorded; null when none has been. */ + complete_from: string | null; + covers_window: boolean | null; +} + +/** How often each gate stood in front of a tool call, and what followed. */ +export function getGateStops(days = 30): Promise { + return apiGet(`/api/retrieval/gate-stops?days=${days}`); +} + /** Whether the rules in force at each moment were followed there. */ export function getAdherence(days = 30): Promise { return apiGet(`/api/retrieval/adherence?days=${days}`); diff --git a/frontend/src/components/GateStops.vue b/frontend/src/components/GateStops.vue new file mode 100644 index 00000000..98cf2717 --- /dev/null +++ b/frontend/src/components/GateStops.vue @@ -0,0 +1,121 @@ + + + + + + +