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"