From f55e263d7e968e0c5fe42146e5d7c0914ecd9498 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 23:15:24 -0500 Subject: [PATCH] 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