diff --git a/docs/architecture/state-hub_v0.1.md b/docs/architecture/state-hub_v0.1.md index d79762f..d6d9991 100644 --- a/docs/architecture/state-hub_v0.1.md +++ b/docs/architecture/state-hub_v0.1.md @@ -33,7 +33,9 @@ toward `repo-manager` and `hub-core`. ### 1.1 Requirements Overview - Rebuild coordination state from registered repository files. -- One identifier registrar (ADR-007). This workstation is not it. +- Deterministic UUIDv5 work-record identifiers (ADR-007). Any instance may + reconcile the same repository; the canonical record id produces the same + database key and writeback bytes on every instance. - Preserve compatibility; do not take new permanent architectural ownership. diff --git a/scripts/consistency_check.py b/scripts/consistency_check.py index 77524f3..02b39b6 100644 --- a/scripts/consistency_check.py +++ b/scripts/consistency_check.py @@ -11,7 +11,7 @@ Checks: C-04 workstream-status-drift WARN Yes File status != DB status (file wins) C-05 workstream-title-drift WARN Yes File title != DB title (file wins) C-06 workstream-unlinked WARN Yes Workplan has no state_hub_workstream_id - Identifier minting (--fix create+writeback) is registrar-only (ADR-007) + --fix derives the UUID from the canonical record id and writes it back C-07 orphan-db-active FAIL No Active DB workstream, no backing file C-08 orphan-db-closed INFO No Finished/archived DB workstream, no file C-09 workstream-repo-mismatch FAIL Yes DB workstream repo_id != file location @@ -46,10 +46,10 @@ Usage: python scripts/consistency_check.py --all [--fix] [--no-writeback] [--json] [--api-base URL] python scripts/consistency_check.py --here [PATH] [--fix] [--no-writeback] [--json] [--api-base URL] -Registrar (ADR-007 interim / RMGR-WP-0005-T01): - C-06 / C-11 / C-32 mint hub IDs into files only when this instance is the - identifier registrar. Default: hostname starts with ``railiance``. - Override with STATEHUB_REGISTRAR=1 or =0. Read/project checks are unchanged. +Identifiers (ADR-007 / RMGR-WP-0005): + C-06 / C-11 / C-32 derive UUIDv5 identifiers from the fleet namespace and + canonical record id. Any instance may reconcile; independent instances + produce the same identifier and byte-identical writeback. Exit codes (single-repo / local CLI): 0 — clean (no FAILs or WARNs; INFOs are allowed) @@ -2834,38 +2834,6 @@ def _write_custodian_brief(api_base: str, repo_slug: str, repo_path: str) -> boo return True -# --------------------------------------------------------------------------- -# Identifier registrar (ADR-007 decision 2 / RMGR-WP-0005-T01) -# --------------------------------------------------------------------------- - -def _is_identifier_registrar() -> bool: - """True when this instance may mint hub IDs into repository files.""" - try: - from repo_manager.registrar import is_identifier_registrar - - return is_identifier_registrar() - except ImportError: - raw = os.environ.get("STATEHUB_REGISTRAR", "").strip().lower() - if raw in {"1", "true", "yes", "on"}: - return True - if raw in {"0", "false", "no", "off"}: - return False - return socket.gethostname().lower().startswith("railiance") - - -def _skip_non_registrar_mint(report: "ConsistencyReport", check_id: str, label: str) -> bool: - if _is_identifier_registrar(): - return False - report.fixes_applied.append( - f"{check_id} skipped: this instance is not the identifier registrar " - f"({label}; do not retry or set STATEHUB_REGISTRAR directly; after " - "committing and pushing file-backed work run once: " - "uv run --project ~/repo-manager rmgr sync --path . --push; " - "ADR-012 / STATE-WP-0086)" - ) - return True - - # --------------------------------------------------------------------------- # Fix engine # --------------------------------------------------------------------------- @@ -3019,8 +2987,6 @@ def fix_repo( ) elif issue.check_id == "C-06": - if _skip_non_registrar_mint(report, "C-06", "workplan UUID"): - continue wp_file = Path(ctx["wp_file"]) meta = ctx["meta"] domain = ctx["domain"] @@ -3179,8 +3145,6 @@ def fix_repo( ) elif issue.check_id == "C-32": - if _skip_non_registrar_mint(report, "C-32", "work-record UUID"): - continue md_path = ctx["md_path"] kind = ctx["kind"] rid = ctx["rid"] @@ -3316,8 +3280,6 @@ def fix_repo( ) elif issue.check_id == "C-11": - if _skip_non_registrar_mint(report, "C-11", "task UUID"): - continue ws_id = ctx["ws_id"] ws_status = ctx.get("ws_status", "") task = ctx["task"] diff --git a/tests/test_consistency_check.py b/tests/test_consistency_check.py index 363249e..2d74296 100644 --- a/tests/test_consistency_check.py +++ b/tests/test_consistency_check.py @@ -1587,12 +1587,12 @@ class TestC06WorkstreamCreation: assert f'state_hub_task_id: "{expected_task_id}"' in patched assert any("C-06 fixed" in fix for fix in report.fixes_applied) - def test_fix_repo_skips_c06_mint_when_not_registrar(self, tmp_path, monkeypatch): - repo = tmp_path / "repo" - workplans = repo / "workplans" - workplans.mkdir(parents=True) - wp = workplans / "STATE-WP-0001-demo.md" - wp.write_text( + def test_fix_repo_derives_identical_writeback_across_instances( + self, tmp_path, monkeypatch + ): + import socket + + source = ( "---\n" "id: STATE-WP-0001\n" "type: workplan\n" @@ -1607,30 +1607,75 @@ class TestC06WorkstreamCreation: "id: STATE-WP-0001-T01\n" "status: todo\n" "priority: high\n" - "```\n", - encoding="utf-8", + "```\n" ) + repos = {} + for instance in ("hub-a", "hub-b"): + repo = tmp_path / instance + workplans = repo / "workplans" + workplans.mkdir(parents=True) + (workplans / "STATE-WP-0001-demo.md").write_text(source, encoding="utf-8") + repos[instance] = repo - created = [] + stores = { + instance: {"workplans": {}, "tasks": {}} + for instance in repos + } + create_attempts = { + instance: {"workplans": 0, "tasks": 0} + for instance in repos + } - def fake_get(_api_base, path, params=None, **_kwargs): + def instance_name(api_base): + return api_base.rsplit("/", 1)[-1] + + def fake_get(api_base, path, params=None, **_kwargs): + instance = instance_name(api_base) + store = stores[instance] if path == "/repos/demo-repo": - import socket - return { - "id": "repo-1", + "id": f"repo-{instance}", "slug": "demo-repo", - "local_path": str(repo), - "host_paths": {socket.gethostname(): str(repo)}, + "local_path": str(repos[instance]), + "host_paths": {socket.gethostname(): str(repos[instance])}, "domain_slug": "financials", } if path == "/topics": - return [{"id": "topic-1", "domain_slug": "financials"}] + return [{"id": f"topic-{instance}", "domain_slug": "financials"}] + if path.startswith("/workplans/"): + return store["workplans"].get(path.rsplit("/", 1)[-1]) + if path.startswith("/tasks/"): + return store["tasks"].get(path.rsplit("/", 1)[-1]) + if path == "/workplans": + rows = list(store["workplans"].values()) + if params: + rows = [ + row for row in rows + if all(row.get(key) == value for key, value in params.items()) + ] + return rows + if path == "/tasks": + rows = list(store["tasks"].values()) + if params: + rows = [ + row for row in rows + if all(row.get(key) == value for key, value in params.items()) + ] + return rows return [] - def fake_post(_api_base, path, body): - created.append((path, body)) - return {"id": "should-not-mint", **body} + def fake_post(api_base, path, body): + instance = instance_name(api_base) + collection = path.strip("/") + if collection not in {"workplans", "tasks"}: + return {"ok": True} + create_attempts[instance][collection] += 1 + existing = stores[instance][collection].get(body["id"]) + if existing is not None: + return existing + stored = dict(body) + stores[instance][collection][body["id"]] = stored + return stored monkeypatch.setattr("consistency_check._api_get", fake_get) monkeypatch.setattr("consistency_check._api_post", fake_post) @@ -1639,18 +1684,43 @@ class TestC06WorkstreamCreation: monkeypatch.setattr("consistency_check._detect_ahead_of_remote", lambda _repo_path: 0) monkeypatch.setattr("consistency_check._write_custodian_brief", lambda *args, **kwargs: False) monkeypatch.setattr("consistency_check._git_push", lambda _repo_path: (True, "pushed")) + monkeypatch.setattr( + "consistency_check._git_commit_writeback", lambda *args, **kwargs: False + ) monkeypatch.setenv("STATEHUB_REGISTRAR", "0") - report = fix_repo("http://unused", "demo-repo") + reports = { + instance: fix_repo(f"http://{instance}", "demo-repo") + for instance in repos + } + written = [ + (repo / "workplans" / "STATE-WP-0001-demo.md").read_bytes() + for repo in repos.values() + ] + assert written[0] == written[1] + workplan_id = _derived_work_record_uuid("STATE-WP-0001") + task_id = _derived_work_record_uuid("STATE-WP-0001-T01") + text = written[0].decode("utf-8") + assert f'state_hub_workstream_id: "{workplan_id}"' in text + assert f'state_hub_task_id: "{task_id}"' in text + for instance in repos: + assert set(stores[instance]["workplans"]) == {workplan_id} + assert set(stores[instance]["tasks"]) == {task_id} + assert create_attempts[instance] == {"workplans": 1, "tasks": 1} + assert not any("identifier registrar" in fix for fix in reports[instance].fixes_applied) - assert created == [] - patched = wp.read_text(encoding="utf-8") - assert "state_hub_workstream_id" not in patched - assert "state_hub_task_id" not in patched - assert any("not the identifier registrar" in fix for fix in report.fixes_applied) - assert any("rmgr sync" in fix for fix in report.fixes_applied) - assert not any("set STATEHUB_REGISTRAR=1" in fix for fix in report.fixes_applied) - assert any(issue.check_id == "C-06" for issue in report.issues) + # A second reconcile is idempotent: neither independent hub creates a + # duplicate record and the repository bytes remain unchanged. + for instance in repos: + fix_repo(f"http://{instance}", "demo-repo") + assert create_attempts == { + "hub-a": {"workplans": 1, "tasks": 1}, + "hub-b": {"workplans": 1, "tasks": 1}, + } + assert [ + (repo / "workplans" / "STATE-WP-0001-demo.md").read_bytes() + for repo in repos.values() + ] == written # --------------------------------------------------------------------------- # _git_pull (T02 remote fix helper)