From f4d64862559e41adc17bd441de1e6d7e8c2d8892 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 13:22:50 -0500 Subject: [PATCH 1/7] fix(8321): a .grimoire marker that disagrees with the repo's binding is named at session start A marker copied along with a repo outlived the project it was written for: the Throne folder's marker still named project 38 after the split, so every hook held the session to Cartographer and writes to Throne stopped on the project fence, with nothing saying why. The SessionStart hook now sends the remote beside a marker's project_id. The marker still decides the project; /context also resolves the remote's binding, and when it names a different project the context says which project each names and how to fix the file. Co-Authored-By: Claude Opus 5.5 --- plugin/.claude-plugin/plugin.json | 2 +- plugin/hooks/grimoire_session_context.sh | 5 +++ src/grimoire/routes/plugin.py | 10 ++++- src/grimoire/services/plugin_context.py | 27 +++++++++++- tests/test_services_plugin_context.py | 53 ++++++++++++++++++++++++ tests/test_session_context_failure.py | 19 +++++++++ 6 files changed, 113 insertions(+), 3 deletions(-) diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index eb2846fe..afbee0bf 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, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.12.01.0748", + "version": "2026.12.02.1822", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/hooks/grimoire_session_context.sh b/plugin/hooks/grimoire_session_context.sh index 8b730d98..b36237a9 100755 --- a/plugin/hooks/grimoire_session_context.sh +++ b/plugin/hooks/grimoire_session_context.sh @@ -183,6 +183,11 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then q="source=$(printf '%s' "$source" | grimoire_urlenc)" [ -n "$sid_now" ] && q="${q}&session_id=$(printf '%s' "$sid_now" | grimoire_urlenc)" [ -n "$scope" ] && q="${q}&${scope}" + # A marker named the project: send the remote too. The marker still wins, + # and the server says so when the remote is bound to a different project. + case "$scope" in + project_id=*) [ -n "$repo" ] && q="${q}&repo=$(printf '%s' "$repo" | grimoire_urlenc)" ;; + esac q="?${q}" # ONE FETCH, NAMED WHEN IT FAILS. A timeout, an HTTP error and a refused key # need different fixes, so each gets its own sentence. curl's write-out still diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 0daaa564..b957510d 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -116,16 +116,24 @@ async def session_context(): send it when a `.grimoire` marker file names a project. Takes precedence over `repo`. Access-checked like any other read — an id this account cannot read loads no project rather than failing. + Sent with `repo`, the remote's binding is still looked up, and a + binding to a different project is reported in the context. source (optional str) — the host's SessionStart source (startup, resume, compact, clear, fork); decides what the claim section says. session_id (optional str) — the session's id, so a claim bound to it reads as this session's own. """ - project_id, _repo, unbound_repo = await _project_scope() + project_id, repo, unbound_repo = await _project_scope() + # A marker named the project and the hook sent the remote beside it: look + # the remote up too, so a disagreement between the two can be said. + repo_project_id = 0 + if project_id and repo: + repo_project_id = await repo_bindings_svc.resolve_project(g.user.id, repo) or 0 result = await plugin_ctx_svc.build_session_context( g.user.id, project_id, unbound_repo=unbound_repo, source=(request.args.get("source") or "").strip()[:20], session_id=(request.args.get("session_id") or "").strip()[:200], + repo_project_id=repo_project_id, ) return jsonify(result) diff --git a/src/grimoire/services/plugin_context.py b/src/grimoire/services/plugin_context.py index 94be4dce..474e3068 100644 --- a/src/grimoire/services/plugin_context.py +++ b/src/grimoire/services/plugin_context.py @@ -2339,9 +2339,26 @@ def _goal_line(goal: str, project_id: int) -> str: return f"Goal: {short} (full goal: `enter_project({project_id})`)" +async def _marker_conflict_lines(user_id: int, project, repo_project_id: int) -> list[str]: + """The section saying a `.grimoire` marker and the repo's binding name + different projects, and that the marker is the one in force.""" + bound = await projects_svc.get_project(user_id, repo_project_id) + bound_name = f"{bound.title} (id {bound.id})" if bound is not None else f"project {repo_project_id}" + return [ + "", + "## ⚠️ This folder's `.grimoire` marker overrides its repo binding", + f"The marker file names {project.title} (id {project.id}), but this " + f"repo's remote is bound to {bound_name}. The marker wins, so every " + f"hook this session (rules, recall, the project fence) works as " + f"{project.title}, and writes to {bound_name} stop on a permission " + "prompt. If this folder belongs to the bound project, correct the " + "marker's `project_id` or delete the file so the binding decides.", + ] + + async def build_session_context( user_id: int, project_id: int = 0, unbound_repo: str = "", - source: str = "", session_id: str = "", + source: str = "", session_id: str = "", repo_project_id: int = 0, ) -> dict: """Render the SessionStart context for a user, optionally project-scoped. @@ -2360,6 +2377,12 @@ async def build_session_context( claim section says (`task_claims.render_claims`): a compaction gets back the work it had claimed with its latest logs; a new session hears about other sessions' live and abandoned claims; a resume hears nothing. + repo_project_id: the project the working repo's remote is bound to, + when a `.grimoire` marker named `project_id` instead. The marker + wins, but when the two differ the session is told which project + each names: a marker copied along with a repo outlives the + project it was written for, and without this line a session is + held to the old project with nothing saying why. Returns {"context": str, "project": dict | None}. @@ -2389,6 +2412,8 @@ async def build_session_context( _goal_line(goal, project.id), f"Open todo tasks: {open_count}", ] + if repo_project_id and repo_project_id != project.id: + lines += await _marker_conflict_lines(user_id, project, repo_project_id) # A design system binds the same way a rule does, and without this # the standards would reach only an agent that already knew to look diff --git a/tests/test_services_plugin_context.py b/tests/test_services_plugin_context.py index 0d5bd4e6..3114c2f9 100644 --- a/tests/test_services_plugin_context.py +++ b/tests/test_services_plugin_context.py @@ -136,6 +136,59 @@ async def test_build_session_context_includes_project_when_scoped(): assert "Reflex:" not in out["context"] +@pytest.mark.parametrize("repo_project_id, says", [(43, True), (38, False), (0, False)]) +async def test_a_marker_that_disagrees_with_the_repo_binding_is_named(repo_project_id, says): + """A `.grimoire` marker names project 38 while the repo's remote is bound + to 43: the marker wins, and the session is told which project each names + and how to fix the file. Agreeing, or no binding to compare, says nothing.""" + projects = {38: MagicMock(id=38, title="Cartographer", goal="", design_system_id=None), + 43: MagicMock(id=43, title="Throne", goal="", design_system_id=None)} + + async def get_project(_uid, pid): + return projects.get(pid) + + with patch("grimoire.services.plugin_context.projects_svc.get_project", get_project), \ + patch("grimoire.services.plugin_context.notes_svc.list_notes", + AsyncMock(return_value=([], 0))): + from grimoire.services.plugin_context import build_session_context + out = await build_session_context(user_id=7, project_id=38, repo_project_id=repo_project_id) + + assert out["project"] == {"id": 38, "title": "Cartographer"} + ctx = out["context"] + assert ("overrides its repo binding" in ctx) is says + if says: + assert "names Cartographer (id 38)" in ctx and "bound to Throne (id 43)" in ctx + assert "delete the file" in ctx + + +@pytest.mark.parametrize("query, resolves, passed", [ + ({"project_id": "38", "repo": "https://git.example.com/o/r.git"}, 43, 43), + ({"project_id": "38"}, 43, 0), + ({"repo": "https://git.example.com/o/r.git"}, 43, 0), +]) +async def test_the_route_looks_up_the_remote_beside_a_marker(query, resolves, passed): + """With a marker's project_id AND the remote, the route resolves the + remote's binding too and hands it on; the project stays the marker's. + With only one key there is nothing to compare.""" + import inspect + from types import SimpleNamespace + + from quart import Quart, g + + from grimoire.routes import plugin as routes + + build = AsyncMock(return_value={"context": "", "project": None}) + app = Quart(__name__) + async with app.test_request_context("/api/plugin/context", query_string=query): + g.user = SimpleNamespace(id=7) + with patch.object(routes.repo_bindings_svc, "resolve_project", AsyncMock(return_value=resolves)), \ + patch.object(routes.plugin_ctx_svc, "build_session_context", build): + await inspect.unwrap(routes.session_context)() + args, kwargs = build.await_args + assert args[1] == (38 if "project_id" in query else resolves) + assert kwargs["repo_project_id"] == passed + + def test_a_short_goal_is_shown_whole(): from grimoire.services.plugin_context import _goal_line assert _goal_line("ship it", 2) == "Goal: ship it" diff --git a/tests/test_session_context_failure.py b/tests/test_session_context_failure.py index bf6ef10c..5acca812 100644 --- a/tests/test_session_context_failure.py +++ b/tests/test_session_context_failure.py @@ -52,3 +52,22 @@ def test_the_fallback_is_a_first_step_not_an_option(tmp_path): def test_a_marker_names_the_exact_call(tmp_path): out = run_hook(tmp_path, DEAD, marker_project=31) assert "Start by calling `enter_project(31)`" in out + + +def test_a_marker_sends_the_remote_beside_it_so_a_disagreement_can_be_said(tmp_path): + """The marker decides the project, but a marker copied along with a repo + can outlive the project it was written for. The remote goes too, so the + server can compare it with the repo's binding; a folder outside any repo + sends the marker alone.""" + from tests.helpers import http_sink + + need_tools("bash", "curl", "awk", "git") + subprocess.run(["git", "init", "-q", str(tmp_path)], check=True) + subprocess.run(["git", "-C", str(tmp_path), "remote", "add", "origin", + "https://git.example.com/owner/split-off.git"], check=True) + with http_sink(b'{"context":"","project":null}') as (port, seen): + url = f"http://127.0.0.1:{port}" + run_hook(tmp_path, url, marker_project=38) + ask = seen[0] + assert ask["project_id"] == ["38"] + assert ask["repo"] == ["https://git.example.com/owner/split-off.git"] -- 2.54.0 From ccee6aeffa45c92f03cebf1bd7bbf47e66e7d3a5 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 13:29:17 -0500 Subject: [PATCH 2/7] fix(8321): the remote is looked up beside a marker only when the marker sent the project, not again after it resolved the project itself Co-Authored-By: Claude Opus 5.5 --- src/grimoire/routes/plugin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index b957510d..32d198c5 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -127,7 +127,7 @@ async def session_context(): # A marker named the project and the hook sent the remote beside it: look # the remote up too, so a disagreement between the two can be said. repo_project_id = 0 - if project_id and repo: + if request.args.get("project_id") and repo: repo_project_id = await repo_bindings_svc.resolve_project(g.user.id, repo) or 0 result = await plugin_ctx_svc.build_session_context( g.user.id, project_id, unbound_repo=unbound_repo, -- 2.54.0 From d5a9e0f8c8c1d46a8ac0092ec284bc62f7000e9c Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 16:44:50 -0500 Subject: [PATCH 3/7] test(8249): the tool-rules hook and its route agree on every name, checked by running the hook The old test read the hook script, the shared helpers and the route source and compared parameter names as text. It now runs grimoire_tool_rules.sh against a local listener, in a repo with a remote and every session ledger holding something, and checks that every key the hook sent is one the route, its project-scope helper or the session binder reads. Co-Authored-By: Claude Opus 5.5 --- tests/test_rule_usage_wiring.py | 110 +++++++++++++++----------------- 1 file changed, 50 insertions(+), 60 deletions(-) diff --git a/tests/test_rule_usage_wiring.py b/tests/test_rule_usage_wiring.py index d3871ec5..626e087e 100644 --- a/tests/test_rule_usage_wiring.py +++ b/tests/test_rule_usage_wiring.py @@ -721,73 +721,63 @@ def test_the_tool_arm_is_registered_on_bash(): assert any("grimoire_prior_art.sh" in c for c in entries["Write|Edit"]) -def test_the_hook_and_the_route_agree_on_every_parameter_name(): +def test_the_route_reads_every_name_the_hook_sends(tmp_path): """Two layers that only this test connects agree on their contract. - The hook is shell and the route is Python; nothing but this test connects - them. A renamed query arg fails SILENTLY — the route reads an absent value, - the arm quietly searches nothing, and the surface looks like one that never + The hook is shell and the route is Python; nothing else connects them. A + renamed query key fails SILENTLY — the route reads an absent value, the + arm quietly searches nothing, and the surface looks like one that never finds anything rather than one that is broken. + + So the hook is run for real, in a repo with a remote and with every + session ledger it keeps holding something, and every key it sends must be + one the route reads: in the handler, in the project-scope helper it calls, + or in the session binder that runs before every plugin route. """ - import re + import json + import os + import subprocess - hook = Path("plugin/hooks/grimoire_tool_rules.sh").read_text() - defs = Path("plugin/hooks/grimoire_defs.sh").read_text() - route = Path("src/grimoire/routes/plugin.py").read_text() - handler = route.split("async def pre_tool_rules")[1].split("\n@plugin_bp")[0] + from grimoire.routes import plugin as routes + from tests.helpers import http_sink, need_tools, route_query_args - sent = set(re.findall(r"[?&]([a-z_]+)=", hook)) - # `root` and `cwd`: where the command runs, so the paths it - # names can be made repo-relative for the rulings arm. - # `session_id`: which session the lines go to, for the delivery record. - assert sent == {"tool", "command", "exclude_rule_ids", "root", "cwd", "session_id"}, sent + need_tools("bash", "curl", "awk", "git") + hook = Path(__file__).resolve().parents[1] / "plugin" / "hooks" / "grimoire_tool_rules.sh" + env = {"PATH": os.environ["PATH"], "GRIMOIRE_TOKEN": "t", + "TMPDIR": str(tmp_path), "HOME": str(tmp_path)} + repo = tmp_path / "repo" + repo.mkdir() + subprocess.run(["git", "init", "-q"], cwd=repo, check=True, env=env) + subprocess.run(["git", "remote", "add", "origin", "https://example.com/acme/app.git"], + cwd=repo, check=True, env=env) + # The opened ledger is written by the hook that watches get_rule, not this one. + state = tmp_path / "grimoire-priorart" + state.mkdir() + (state / "s-args.opened.ids").write_text("7\n") + # The first reply fills the named-rule and rulings ledgers, so the second + # run sends every key the hook has. + reply = b'{"context":"> rule 33","rule_ids":[33],"ruling_system_ids":[4]}' + event = {"session_id": "s-args", "cwd": str(repo), "tool_name": "Bash", + "tool_input": {"command": "git push origin dev"}} + with http_sink(by_path={"/api/plugin/tool-rules": reply}) as (port, seen): + env["GRIMOIRE_URL"] = f"http://127.0.0.1:{port}" + for _ in range(2): + out = subprocess.run(["bash", str(hook)], input=json.dumps(event), + capture_output=True, text=True, env=env, timeout=30) + assert out.returncode == 0, out.stderr + asks = [e for e in seen if e["_path"] == "/api/plugin/tool-rules"] + assert len(asks) == 2 + sent = {k for k in asks[-1] if not k.startswith("_")} + assert {"tool", "command", "repo", "root", "cwd", "exclude_rule_ids", "held_rule_ids", + "seen_ruling_systems", "session_id"} <= sent, sent - # The project-scope key is the shared helper's to choose: the hook - # splices in `grimoire_scope_query`'s output, which is `repo=` inside a git - # repo and `project_id=` where a `.grimoire` marker names the project. Both - # halves are one contract with the route, so both are pinned. - assert "grimoire_scope_query" in hook, "hook no longer asks for a project scope" - # `held_rule_ids` joins them for the same reason: the OPENED ledger - # is read by a shared helper so its ageing and format cannot drift from the - # naming ledger's, which means the key is spelled in defs rather than here. - assert "grimoire_held_query" in hook, "hook no longer sends the opened ledger" - assert set(re.findall(r"printf '([a-z_]+)=", defs)) == {"repo", "project_id"} - # Spelled with its own leading `&` because it is APPENDED to a query that - # already has a scope key, where the two above are alternatives that open - # one. Asserted separately for that reason: a scope key and a ledger key - # are different contracts that happen to share a file. - assert "printf '&held_rule_ids=" in defs, ( - "the opened ledger's query key is no longer spelled in the helper" - ) - # The rulings ledger, shared with the write-path hook — - # spelled once in its helper for the same reason. - assert "grimoire_rulings_query" in hook, "hook no longer sends the rulings ledger" - assert "printf '&seen_ruling_systems=" in defs, ( - "the rulings ledger's query key is no longer spelled in the helper" - ) - - # Both scope keys are read by the shared _project_scope() helper, not inline. - assert "_project_scope()" in handler - scope = route.split("async def _project_scope")[1].split("\n@plugin_bp")[0] - for arg in ("project_id", "repo"): - assert f'request.args.get("{arg}"' in scope, ( - f"the hooks can send {arg!r} and the route never reads it" - ) - # Read by the handler itself, not the scope helper — it is about what the - # reader holds, not about which project the work belongs to. - assert 'request.args.get("held_rule_ids")' in handler, ( - "the hook sends held_rule_ids and the route never reads it" - ) - for arg in ("tool", "command", "exclude_rule_ids", "root", "cwd", "seen_ruling_systems"): - assert f'request.args.get("{arg}")' in handler, ( - f"the hook sends {arg!r} and the route never reads it" - ) - # The session is bound for every plugin route at once, before the handler. - binder = route.split("async def _bind_delivery_session")[1].split("\n@plugin_bp")[0] - assert "@plugin_bp.before_request" in route.split("async def _bind_delivery_session")[0][-80:] - assert 'request.args.get("session_id")' in binder, ( - "the hook sends session_id and no route reads it" - ) + read = route_query_args(routes.pre_tool_rules, routes._project_scope, + routes._bind_delivery_session) + assert sent <= read, f"the route ignores {sorted(sent - read)}" + # The binder reads session_id only because it runs before this route. + assert routes._bind_delivery_session in routes.plugin_bp.before_request_funcs[None] + # A `.grimoire` marker sends project_id in place of repo, and the route reads that too. + assert "project_id" in read # ── The CALL log is unconditional; the SURFACING log is not ─────────── -- 2.54.0 From 451e12973119493521f4c8c66e0b5a40e7404370 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 16:44:50 -0500 Subject: [PATCH 4/7] test(8249): DELIBERATE BREAK, the tool-rules route reads seen_rulings instead of seen_ruling_systems Reverted in the next commit. CI must fail test_the_route_reads_every_name_the_hook_sends here. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/routes/plugin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 32d198c5..33de509c 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -351,7 +351,7 @@ async def pre_tool_rules(): project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids, root=(request.args.get("root") or "").strip(), cwd=(request.args.get("cwd") or "").strip(), - seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")), + seen_ruling_systems=_int_list(request.args.get("seen_rulings")), ) fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, { hook_payload_svc.RULE: "rule_ids", hook_payload_svc.RULING: "ruling_system_ids", @@ -772,7 +772,7 @@ async def write_path_prior_art(): repo_key=repo_bindings_svc.normalize_repo_key(repo) if repo else "", exclude_derive=exclude_derive, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids, - seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")), + seen_ruling_systems=_int_list(request.args.get("seen_rulings")), ) fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, { hook_payload_svc.NOTE: "note_ids", hook_payload_svc.SYNC: "sync_note_ids", -- 2.54.0 From 1a9057e8753b37eaeca8e1b60874167eb330a9b2 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 16:49:45 -0500 Subject: [PATCH 5/7] Revert "test(8249): DELIBERATE BREAK, the tool-rules route reads seen_rulings instead of seen_ruling_systems" This reverts commit 451e12973119493521f4c8c66e0b5a40e7404370. --- src/grimoire/routes/plugin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 33de509c..32d198c5 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -351,7 +351,7 @@ async def pre_tool_rules(): project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids, root=(request.args.get("root") or "").strip(), cwd=(request.args.get("cwd") or "").strip(), - seen_ruling_systems=_int_list(request.args.get("seen_rulings")), + seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")), ) fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, { hook_payload_svc.RULE: "rule_ids", hook_payload_svc.RULING: "ruling_system_ids", @@ -772,7 +772,7 @@ async def write_path_prior_art(): repo_key=repo_bindings_svc.normalize_repo_key(repo) if repo else "", exclude_derive=exclude_derive, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids, - seen_ruling_systems=_int_list(request.args.get("seen_rulings")), + seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")), ) fitted = await hook_payload_svc.fit(g.user.id, hook_payload_svc.parts_of(result, { hook_payload_svc.NOTE: "note_ids", hook_payload_svc.SYNC: "sync_note_ids", -- 2.54.0 From af5edd5c3ff92a4d1819b0be3c70c25b6c6eb39a Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 16:49:53 -0500 Subject: [PATCH 6/7] test(8249): the prior-art and moment contract tests count the session binder as a reader of session_id They subtracted session_id from what the hook sent, and their failure message still listed it. The binder that runs before every plugin route reads it, so it is passed to route_query_args beside the handler and the scope helper. Co-Authored-By: Claude Opus 5.5 --- tests/test_moment_delivery.py | 4 ++-- tests/test_write_path_trigger.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/test_moment_delivery.py b/tests/test_moment_delivery.py index fa5884e3..c80b000b 100644 --- a/tests/test_moment_delivery.py +++ b/tests/test_moment_delivery.py @@ -360,8 +360,8 @@ def test_the_route_reads_every_name_the_hook_sends(tmp_path): last = [e for e in seen if e["_path"] == "/api/plugin/moment"][-1] sent = {k for k in last if not k.startswith("_")} assert {"exclude_rule_ids", "held_rule_ids", "shapes_seen"} <= sent, sent - read = route_query_args(routes.moment, routes._project_scope) - assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}" + read = route_query_args(routes.moment, routes._project_scope, routes._bind_delivery_session) + assert sent <= read, f"the route ignores {sorted(sent - read)}" assert {"tool_name", "tool_input"} <= set(json.loads(last["_body"])) diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index b71be78c..2279d18a 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -972,8 +972,9 @@ def test_route_reads_every_arg_the_hook_sends(tmp_path): # Every ledger the hook keeps went out, so this run exercised the whole query. assert {"path", "code", "repo", "shapes", "exclude_ids", "exclude_sync_ids", "exclude_rule_ids", "exclude_derive", "held_rule_ids", "seen_ruling_systems"} <= sent, sent - read = route_query_args(routes.write_path_prior_art, routes._project_scope) - assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}" + read = route_query_args(routes.write_path_prior_art, routes._project_scope, + routes._bind_delivery_session) + assert sent <= read, f"the route ignores {sorted(sent - read)}" # project_id is the other scope key the hook can send (from a project marker). assert "project_id" in read -- 2.54.0 From f55e263d7e968e0c5fe42146e5d7c0914ecd9498 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 23:15:24 -0500 Subject: [PATCH 7/7] fix(8376): a repo that leaves a project takes its shape rows out of that project's accounting A coverage refresh walks only the repos bound to a project, but its readout counts every live row, so the rows of a repo unbound or re-bound to another project were never synced again and kept counting: in the total, the gap list, and every reader of live rows (proposer, divergence, stamp review). Re-binding a repo to another project and unbinding it now stamp its rows on the project it left as vanished, and each refresh sweeps any rows still left under a repo nobody binds to the project. A bound repo the forge did not serve this time stays live. Each stamped row gets an `unbound` event and keeps its judgment, so binding the repo back revives it like any vanished row. Plugin version bumped for the shape-accounting skill's event list. Co-Authored-By: Claude Opus 5.5 --- plugin/.claude-plugin/plugin.json | 2 +- plugin/skills/shape-accounting/SKILL.md | 4 +- src/grimoire/mcp/tools/shapes.py | 3 +- src/grimoire/models/code_shape.py | 6 +- src/grimoire/services/coverage.py | 3 + src/grimoire/services/repo_bindings.py | 25 ++++- src/grimoire/services/shape_ledger.py | 33 ++++++ tests/test_integration_shape_unbound.py | 141 ++++++++++++++++++++++++ tests/test_shape_ledger.py | 4 +- 9 files changed, 211 insertions(+), 10 deletions(-) create mode 100644 tests/test_integration_shape_unbound.py diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index afbee0bf..3e3302fb 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, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.12.02.1822", + "version": "2026.12.03.0415", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/skills/shape-accounting/SKILL.md b/plugin/skills/shape-accounting/SKILL.md index c6c0c23e..8185a7e7 100644 --- a/plugin/skills/shape-accounting/SKILL.md +++ b/plugin/skills/shape-accounting/SKILL.md @@ -172,8 +172,8 @@ Three questions the ledger answers mechanically: it), `variant` with the why if the departure is deliberate. The write-path hint asks the same question in-band the moment such a shape is written. - **History** — `shape_history(project_id, path, symbol?)`: the current rows - plus every `classified` / `vanished` / `reappeared` / `drifted` / `moved` - event with its commit — "instance of #N from , re-judged variant of #M because + plus every `classified` / `vanished` / `reappeared` / `drifted` / `moved` / + `unbound` (its repo left the project) event with its commit — "instance of #N from , re-judged variant of #M because R, vanished at C". Rows, not recollection. - **Recheck** — `list_shapes(project_id, flag="recheck")`: judged instances/variants whose body changed since judged. The judgment stands; diff --git a/src/grimoire/mcp/tools/shapes.py b/src/grimoire/mcp/tools/shapes.py index 8853d327..0c074ed9 100644 --- a/src/grimoire/mcp/tools/shapes.py +++ b/src/grimoire/mcp/tools/shapes.py @@ -274,7 +274,8 @@ async def shape_history( of #N and later a variant of #M shows both), `vanished`, `reappeared`, `drifted` (the body moved under a judgment; see list_shapes flag= "recheck"), `moved` (move_path carried the row; the event's `path` - is the one it left). Each event carries the commit the tree was read at. + is the one it left), `unbound` (its repo was unbound from the project or + bound to another one). Each event carries the commit the tree was read at. Read it as a timeline: "instance of #N from , re-judged variant of #M at because , vanished at ". diff --git a/src/grimoire/models/code_shape.py b/src/grimoire/models/code_shape.py index bce61cdf..89a29d1d 100644 --- a/src/grimoire/models/code_shape.py +++ b/src/grimoire/models/code_shape.py @@ -340,7 +340,9 @@ class CodeShapeConsumer(Base): # What a shape's history records. Not "appeared" — first_seen and # created_at already say that on the row; history is for what CHANGED. # A `moved` event carries the path the shape left; the row says where it went. -SHAPE_EVENTS = ("classified", "vanished", "reappeared", "drifted", "moved") +# `unbound` is a vanish whose cause is the repo leaving the project (unbound, +# or bound to another project), not the code leaving the tree. +SHAPE_EVENTS = ("classified", "vanished", "reappeared", "drifted", "moved", "unbound") class CodeShapeEvent(Base): @@ -349,7 +351,7 @@ class CodeShapeEvent(Base): "We used #N here from , #M replaced it at commit C, reason R" is a question the ledger row alone cannot answer once it has moved on; this table keeps each judgment (status, snippet, who, why, at which commit) - and each presence change (vanished / reappeared / drifted / moved) as it + and each presence change (vanished / reappeared / drifted / moved / unbound) as it happened. Denormalised path/symbol/kind so a directory's history reads without joining; `snippet_id` is deliberately FK-free — history outlives the snippet it names, which is the point. diff --git a/src/grimoire/services/coverage.py b/src/grimoire/services/coverage.py index 6b113142..507ff42a 100644 --- a/src/grimoire/services/coverage.py +++ b/src/grimoire/services/coverage.py @@ -896,6 +896,9 @@ async def compute_coverage( logger.warning("shape proposer failed for %s", key, exc_info=True) if not served: return None + # A repo unbound or re-bound elsewhere is outside every walk above, so + # its rows would otherwise stay live here for good. + await shape_ledger.vanish_unbound(project_id) # Platform detection rides the same walk: the paths are in # hand once. It only ever ADDS membership the project has no answer for, diff --git a/src/grimoire/services/repo_bindings.py b/src/grimoire/services/repo_bindings.py index 90bb10f8..fab6e7d2 100644 --- a/src/grimoire/services/repo_bindings.py +++ b/src/grimoire/services/repo_bindings.py @@ -78,6 +78,10 @@ async def set_binding( binding: a name sets it, ``""`` clears it back to the forge's default branch, ``None`` leaves whatever stands (a re-bind that only moves the project keeps the ref it had). + + A re-bind to another project stamps the repo's rows on the project it + left as vanished (`shape_ledger.vanish_unbound`): the old project's + refresh no longer walks the repo, so nothing else would. """ key = normalize_repo_key(raw_repo) if not key: @@ -89,16 +93,23 @@ async def set_binding( ) ) binding = existing.scalar_one_or_none() + left = None if binding is None: binding = RepoBinding(user_id=user_id, repo_key=key, project_id=project_id) session.add(binding) else: + if binding.project_id != project_id: + left = binding.project_id binding.project_id = project_id if ref is not None: binding.ref = ref.strip() or None await session.commit() await session.refresh(binding) - return binding + if left is not None: + from grimoire.services.shape_ledger import vanish_unbound + + await vanish_unbound(left) + return binding async def move_binding( @@ -229,7 +240,11 @@ async def bindings_for_key(raw_repo: str) -> list[RepoBinding]: async def delete_binding(user_id: int, raw_repo: str) -> bool: - """Remove a repo's binding. Returns True if a row was deleted.""" + """Remove a repo's binding. Returns True if a row was deleted. + + The repo's rows on the project it was bound to are stamped vanished in + the same call, unless another binding still ties the repo to it. + """ key = normalize_repo_key(raw_repo) if not key: return False @@ -242,6 +257,10 @@ async def delete_binding(user_id: int, raw_repo: str) -> bool: binding = row.scalar_one_or_none() if binding is None: return False + left = binding.project_id await session.delete(binding) await session.commit() - return True + from grimoire.services.shape_ledger import vanish_unbound + + await vanish_unbound(left) + return True diff --git a/src/grimoire/services/shape_ledger.py b/src/grimoire/services/shape_ledger.py index 6ca13ecd..d9eb9edd 100644 --- a/src/grimoire/services/shape_ledger.py +++ b/src/grimoire/services/shape_ledger.py @@ -34,6 +34,7 @@ from grimoire.models import async_session from grimoire.models.code_shape import ( REASON_CODES, CodeShape, CodeShapeConsumer, CodeShapeEvent, CodeShapeUse, ) +from grimoire.models.repo_binding import RepoBinding from grimoire.models.base import iso logger = logging.getLogger(__name__) @@ -171,6 +172,38 @@ async def sync_repo_shapes( await session.commit() +async def vanish_unbound(project_id: int) -> int: + """Stamp vanished every live row of a repo no longer bound to the project. + + A sync only reaches the repos a project is bound to, so the rows of a repo + that was unbound, or re-bound to another project, are never matched + against a tree again: no sync can vanish them, and they kept counting in + the accounting, the gap list and every reader of live rows. Bound by + anyone counts (a collaborator's binding is as much the project's as the + owner's), and a bound repo the forge cannot reach this time is still + bound, so its rows stand. Each row gets an `unbound` event, its + judgment is kept, and binding the repo again lets the next sync revive + it like any vanished row. Returns how many rows were stamped. + """ + now = datetime.now(timezone.utc) + async with async_session() as session: + bound = select(RepoBinding.repo_key).where(RepoBinding.project_id == project_id) + rows = ( + await session.execute( + select(CodeShape).where( + CodeShape.project_id == project_id, + CodeShape.vanished_at.is_(None), + CodeShape.repo_key.not_in(bound), + ) + ) + ).scalars().all() + for row in rows: + row.vanished_at = now + session.add(_event(row, "unbound", now, commit=row.last_seen_commit)) + await session.commit() + return len(rows) + + async def move_shapes( user_id: int, project_id: int, from_path: str, to_path: str, ) -> dict: diff --git a/tests/test_integration_shape_unbound.py b/tests/test_integration_shape_unbound.py new file mode 100644 index 00000000..a501bd24 --- /dev/null +++ b/tests/test_integration_shape_unbound.py @@ -0,0 +1,141 @@ +"""Real-Postgres integration tests for the ledger rows of a repo that leaves a +project. + +A coverage refresh walks only the repos bound to a project, so the rows of a +repo that was unbound, or re-bound to another project, would never be matched +against a tree again and would keep counting. Re-binding, unbinding and the +refresh's own sweep stamp them vanished, with an `unbound` event and their +judgment kept; a repo still bound stays live whether or not the forge served +it this time. +""" +import pytest +import pytest_asyncio +from sqlalchemy import select + +from grimoire.models import async_session +from grimoire.models.code_shape import CodeShape, CodeShapeEvent +from grimoire.models.project import Project +from grimoire.services import repo_bindings as svc +from grimoire.services.shape_ledger import ( + classify_shapes, live_rows, sync_repo_shapes, vanish_unbound, +) +from tests.helpers import ensure_user + +pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")] + +MOVING = "https://git.example.com/alice/engine.git" +STAYING = "https://git.example.com/alice/atlas.git" +MOVING_KEY = "git.example.com/alice/engine" +STAYING_KEY = "git.example.com/alice/atlas" + + +@pytest_asyncio.fixture +async def split(): + """One project bound to two repos, each with a synced ledger, one row + judged in the repo that is about to leave.""" + async with async_session() as s: + owner = await ensure_user(s, "shape_unbound_owner") + first = Project(user_id=owner.id, title="Before the split") + second = Project(user_id=owner.id, title="After the split") + s.add_all([first, second]) + await s.flush() + ids = {"owner": owner.id, "first": first.id, "second": second.id} + await s.commit() + + await svc.set_binding(ids["owner"], MOVING, ids["first"]) + await svc.set_binding(ids["owner"], STAYING, ids["first"]) + await sync_repo_shapes( + ids["first"], MOVING_KEY, + [("src/sim.py", "sym", "tick"), ("src/sim.py", "sym", "spawn")], + seen_marker="c1", + ) + await sync_repo_shapes( + ids["first"], STAYING_KEY, [("src/map.py", "sym", "render")], seen_marker="c1", + ) + await classify_shapes(ids["owner"], ids["first"], [ + {"path": "src/sim.py", "symbol": "tick", "status": "exempt", + "reason": "one caller"}, + ]) + yield ids + await svc.delete_binding(ids["owner"], MOVING) + await svc.delete_binding(ids["owner"], STAYING) + + +async def _live_keys(pid: int) -> set[str]: + return {r.repo_key for r in await live_rows(pid)} + + +async def _rows(pid: int, key: str) -> list[CodeShape]: + async with async_session() as s: + rows = await s.execute( + select(CodeShape).where(CodeShape.project_id == pid, CodeShape.repo_key == key) + ) + return list(rows.scalars()) + + +async def _events(shape_ids: list[int]) -> list[str]: + async with async_session() as s: + rows = await s.execute( + select(CodeShapeEvent.event).where(CodeShapeEvent.shape_id.in_(shape_ids)) + ) + return [e for (e,) in rows.all()] + + +@pytest.mark.integration +async def test_rebinding_a_repo_elsewhere_vanishes_its_rows_on_the_project_it_left(split): + await svc.set_binding(split["owner"], MOVING, split["second"]) + + assert await _live_keys(split["first"]) == {STAYING_KEY} + left = await _rows(split["first"], MOVING_KEY) + assert len(left) == 2 and all(r.vanished_at is not None for r in left) + assert {r.symbol: r.status for r in left} == {"tick": "exempt", "spawn": "unclassified"} + assert (await _events([r.id for r in left])).count("unbound") == 2 + staying = await _rows(split["first"], STAYING_KEY) + assert [r.vanished_at for r in staying] == [None] + + +@pytest.mark.integration +async def test_unbinding_a_repo_vanishes_its_rows(split): + assert await svc.delete_binding(split["owner"], MOVING) + + assert await _live_keys(split["first"]) == {STAYING_KEY} + + +@pytest.mark.integration +async def test_a_bound_repo_stays_live_though_no_sync_reached_it(split): + # The refresh's sweep keys on bindings, not on which repos the forge + # served: with every repo still bound, nothing is stamped. + assert await vanish_unbound(split["first"]) == 0 + assert await _live_keys(split["first"]) == {MOVING_KEY, STAYING_KEY} + + +@pytest.mark.integration +async def test_the_sweep_catches_rows_left_by_a_move_made_before_it_existed(split): + # A binding moved by a plain UPDATE, as every re-bind did before the + # sweep, leaves the rows live; the refresh's sweep is what clears them. + from grimoire.models.repo_binding import RepoBinding + + async with async_session() as s: + binding = (await s.execute( + select(RepoBinding).where(RepoBinding.repo_key == MOVING_KEY) + )).scalar_one() + binding.project_id = split["second"] + await s.commit() + assert await _live_keys(split["first"]) == {MOVING_KEY, STAYING_KEY} + + assert await vanish_unbound(split["first"]) == 2 + assert await _live_keys(split["first"]) == {STAYING_KEY} + + +@pytest.mark.integration +async def test_binding_the_repo_back_revives_its_rows_with_their_judgment(split): + await svc.set_binding(split["owner"], MOVING, split["second"]) + await svc.set_binding(split["owner"], MOVING, split["first"]) + await sync_repo_shapes( + split["first"], MOVING_KEY, + [("src/sim.py", "sym", "tick"), ("src/sim.py", "sym", "spawn")], + seen_marker="c2", + ) + + back = {r.symbol: (r.vanished_at, r.status) for r in await _rows(split["first"], MOVING_KEY)} + assert back == {"tick": (None, "exempt"), "spawn": (None, "unclassified")} diff --git a/tests/test_shape_ledger.py b/tests/test_shape_ledger.py index 2d544ea2..f34ad372 100644 --- a/tests/test_shape_ledger.py +++ b/tests/test_shape_ledger.py @@ -707,5 +707,7 @@ def test_history_and_divergence_columns_are_pinned(): fk = next(iter(ev.c.shape_id.foreign_keys)) assert fk.ondelete == "CASCADE" and fk.column.table.name == "code_shapes" assert not ev.c.snippet_id.foreign_keys # history outlives the snippet - assert SHAPE_EVENTS == ("classified", "vanished", "reappeared", "drifted", "moved") + assert SHAPE_EVENTS == ( + "classified", "vanished", "reappeared", "drifted", "moved", "unbound", + ) assert "code_shape_events" in Base.metadata.tables -- 2.54.0