fix registrar writebacks and own the State Hub access map

Ignore generated WORK-RECORDS.md/.custodian-brief.md in the registrar git
precondition, commit identifier writebacks even when registration is
incomplete, and name the remaining records in the error. Add
config/state-hub-access.yaml as the single source for the AGENTS.md port
map, rendered by rmgr scaffold and refreshed with --refresh-hub-access.

Assistant: grok
Assistant-Session: 01a04996-76e8-7f53-b971-1885cfbed436
This commit is contained in:
tegwick 2026-08-28 20:48:21 +02:00
parent 77caca1ab8
commit 7ea7690dfc
10 changed files with 480 additions and 44 deletions

View file

@ -26,6 +26,7 @@ from repo_manager.record_identity import scan_record_identities
LOCK_PATH = Path("/tmp/repo-manager-identifier-registrar.lock")
STATEHUB_TIMEOUT_SECONDS = 900
GENERATED_INDEX_PATHS = frozenset({".custodian-brief.md", "WORK-RECORDS.md"})
@dataclass
@ -175,12 +176,52 @@ def _requested_identity_findings(
)
def _porcelain_paths(stdout: str) -> list[str]:
paths: list[str] = []
for line in stdout.splitlines():
if not line.strip():
continue
if " -> " in line:
paths.append(line.split(" -> ", 1)[1].strip())
continue
paths.append(line[3:] if len(line) > 3 else line.strip())
return paths
def _remaining_record_ids(missing: dict[str, list[str]]) -> list[str]:
remaining: list[str] = []
for key in ("workplans", "tasks", "intakes", "decisions"):
remaining.extend(missing.get(key) or [])
return remaining
def _registration_incomplete_message(after: dict[str, list[str]], stdout: str) -> str:
remaining = _remaining_record_ids(after)
named = ", ".join(remaining) if remaining else "see missing_after"
message = (
"State Hub reconciliation did not assign every requested identifier: "
f"{named}"
)
for line in stdout.splitlines():
stripped = line.strip()
if "not created:" in stripped or "Internal Server Error" in stripped:
return f"{message}. Child: {stripped}"
return message
def _check_git(repo: Path) -> tuple[dict[str, Any], str | None]:
status = _git(repo, "status", "--porcelain")
if status.returncode != 0:
return {}, status.stderr.strip() or "not a Git repository"
if status.stdout.strip():
return {}, "worktree must be clean before registrar reconciliation"
dirty = _porcelain_paths(status.stdout)
generated = [path for path in dirty if path in GENERATED_INDEX_PATHS]
blocking = [path for path in dirty if path not in GENERATED_INDEX_PATHS]
if blocking:
return (
{"dirty": dirty, "ignored_generated": generated},
"worktree must be clean before registrar reconciliation; "
f"blocking: {', '.join(blocking)}",
)
upstream = _git(repo, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")
if upstream.returncode != 0:
@ -210,6 +251,7 @@ def _check_git(repo: Path) -> tuple[dict[str, Any], str | None]:
"behind": behind,
"ahead": ahead,
"origin": remote_url,
"ignored_generated": generated,
}, None
@ -511,19 +553,34 @@ def _run_statehub(command: list[str], *, env: dict[str, str]) -> subprocess.Comp
def _restore_generated_brief(repo: Path, paths: list[str]) -> tuple[list[str], str | None]:
"""Restore the generated brief after a projection-only repair child."""
"""Restore generated indexes after a projection-only repair child."""
if not paths:
return [], None
if paths != [".custodian-brief.md"]:
return [], "projection repair changed files other than the generated Custodian brief"
original = _git(repo, "show", "HEAD:.custodian-brief.md")
if original.returncode != 0:
return [], original.stderr.strip() or "could not read the committed Custodian brief"
(repo / ".custodian-brief.md").write_text(original.stdout, encoding="utf-8")
generated = [path for path in paths if path in GENERATED_INDEX_PATHS]
other = [path for path in paths if path not in GENERATED_INDEX_PATHS]
if other:
return [], (
"projection repair changed files other than generated indexes: "
+ ", ".join(other)
)
restored: list[str] = []
for path in generated:
original = _git(repo, "show", f"HEAD:{path}")
target = repo / path
if original.returncode != 0:
target.unlink(missing_ok=True)
else:
target.write_text(original.stdout, encoding="utf-8")
restored.append(path)
remaining = _git(repo, "status", "--porcelain")
if remaining.returncode != 0 or remaining.stdout.strip():
return [], remaining.stderr.strip() or "generated brief restoration left a dirty worktree"
return paths, None
leftover = [
path
for path in _porcelain_paths(remaining.stdout)
if path not in GENERATED_INDEX_PATHS
]
if remaining.returncode != 0 or leftover:
return restored, remaining.stderr.strip() or "generated index restoration left a dirty worktree"
return restored, None
def registrar_reconcile(
@ -682,12 +739,14 @@ def registrar_reconcile(
"decisions": len(bootstrap_records["decision"]),
}
if source_error:
return RegistrarResult(
"rejected",
evidence,
{"code": "bootstrap_source_invalid", "message": source_error},
cid,
)
error: dict[str, Any] = {
"code": "bootstrap_source_invalid",
"message": source_error,
}
token = source_error.split()[0]
if token not in {"repository", "a", "an", "the"}:
error["record"] = token
return RegistrarResult("rejected", evidence, error, cid)
LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)
with LOCK_PATH.open("a+", encoding="utf-8") as lock:
@ -792,23 +851,14 @@ def registrar_reconcile(
mode_verification_failed = bool(repair_projection_id and not repair_verified) or (
bootstrap_empty_projection and not bootstrap_verified
)
if (
incomplete = (
completed.returncode not in accepted_exit_codes
or any(after.values())
or mode_verification_failed
):
return RegistrarResult(
"failed",
evidence,
{
"code": "registration_incomplete",
"message": "State Hub reconciliation did not assign every requested identifier",
},
cid,
)
)
changed = _git(repo, "status", "--porcelain")
paths = [line[3:] for line in changed.stdout.splitlines() if len(line) > 3]
paths = _porcelain_paths(changed.stdout)
if (repair_verified or bootstrap_verified) and paths:
restored, restore_error = _restore_generated_brief(repo, paths)
evidence["restored_generated_paths"] = restored
@ -827,6 +877,7 @@ def registrar_reconcile(
paths,
"chore(registrar): assign State Hub identifiers",
)
evidence["committed_paths"] = paths
except GitError as exc:
return RegistrarResult(
"failed",
@ -838,7 +889,7 @@ def registrar_reconcile(
if push:
pushed, message = push_ff(repo)
evidence["push"] = {"ok": pushed, "message": message}
if not pushed:
if not pushed and not incomplete:
return RegistrarResult(
"failed",
evidence,
@ -848,4 +899,19 @@ def registrar_reconcile(
evidence["workplan_bindings"] = _sync_workplan_bindings(repo, api_base, repo.name)
if incomplete:
remaining = _remaining_record_ids(after)
return RegistrarResult(
"failed",
evidence,
{
"code": "registration_incomplete",
"message": _registration_incomplete_message(
after, completed.stdout or ""
),
"records": remaining,
},
cid,
)
return RegistrarResult("applied", evidence, None, cid)

View file

@ -8,6 +8,7 @@ from pathlib import Path
from typing import Any
from repo_manager.gitops import GitError, commit_paths, is_git_repo
from repo_manager.hub_access import apply_hub_access_block, render_hub_access_block
from repo_manager.standards import FLAVOR_MARKER_PREFIX, expected_workplan_prefix
from repo_manager.time import utc_today
@ -121,7 +122,9 @@ def scaffold_repository(
"AGENTS.md",
f"# Agent instructions — {slug}\n\n"
f"Orient: {'GOAL.md' if prj else 'INTENT.md'} → SCOPE.md → workplans/.\n"
f"Workplan prefix: `{prefix}-`.\n",
f"Workplan prefix: `{prefix}-`.\n\n"
"## State Hub Integration\n\n"
f"{render_hub_access_block()}\n",
)
if prj:
today = utc_today().isoformat()
@ -190,3 +193,36 @@ def scaffold_repository(
if not written:
evidence["noop"] = True
return CommandResult("applied", evidence, None, cid)
def refresh_hub_access(path: Path, *, commit: bool = True) -> CommandResult:
"""Replace the State Hub access table in AGENTS.md from the canonical map."""
cid = str(uuid.uuid4())
dest = path.expanduser().resolve()
agents = dest / "AGENTS.md"
evidence: dict[str, Any] = {"path": str(dest), "file": "AGENTS.md"}
if not agents.is_file():
return CommandResult(
"rejected",
evidence,
{"message": "AGENTS.md is missing; scaffold the repository first"},
cid,
)
original = agents.read_text(encoding="utf-8")
updated, action = apply_hub_access_block(original)
evidence["action"] = action
if action == "noop":
evidence["noop"] = True
return CommandResult("applied", evidence, None, cid)
agents.write_text(updated, encoding="utf-8")
evidence["written"] = ["AGENTS.md"]
if commit and is_git_repo(dest):
try:
evidence["git_sha"] = commit_paths(
dest,
["AGENTS.md"],
"docs(agents): refresh State Hub access map from repo-manager",
)
except GitError as exc:
return CommandResult("failed", evidence, {"message": str(exc)}, cid)
return CommandResult("applied", evidence, None, cid)