diff --git a/loopx/authority.py b/loopx/authority.py index bacadf244d..a1f0246f67 100644 --- a/loopx/authority.py +++ b/loopx/authority.py @@ -253,7 +253,7 @@ def _render_authority_markdown( def render_authority_source_markdown(payload: PayloadView) -> str: return _render_authority_markdown( - "LoopX Authority Source Registration", + "LoopX Authority Source Metadata Update" if payload.get("operation") == "update" else "LoopX Authority Source Registration", payload, entry_fields=(*_COMMON_MARKDOWN_ENTRY_FIELDS, "owner_status", "gate_status"), include_registry=True, diff --git a/loopx/cli_commands/registry_authority.py b/loopx/cli_commands/registry_authority.py index d254eb3b32..e7fb9c57e6 100644 --- a/loopx/cli_commands/registry_authority.py +++ b/loopx/cli_commands/registry_authority.py @@ -11,6 +11,7 @@ render_doc_registry_authority_import_markdown, render_authority_source_markdown, ) +from .registry_authority_metadata import update_authority_source from ..global_registry import sync_project_registry_to_global @@ -22,6 +23,7 @@ REGISTRY_AUTHORITY_COMMANDS = { "authority-sources", "register-authority-source", + "update-authority-source", "import-doc-registry-authority", } @@ -35,6 +37,15 @@ def register_registry_authority_commands(subparsers: argparse._SubParsersAction) sources.add_argument("--topic", help="Exact registered topic key.") sources.add_argument("--offset", type=int, default=0, help="Skip this many matches in stable source-id order.") sources.add_argument("--limit", type=int, default=20, help="Maximum matches to return (1–100).") + update = subparsers.add_parser( + "update-authority-source", help="Update existing material metadata while preserving source provenance and topics.", + ) + update.add_argument("--goal-id", required=True) + update.add_argument("--source-id", required=True) + for field in ("freshness", "owner-status", "gate-status", "revision", "conflict-rule"): + update.add_argument(f"--{field}", help="Recorded metadata only; omitted fields are preserved.") + update.add_argument("--dry-run", action="store_true", help="Preview without writing or syncing.") + update.add_argument("--no-global-sync", action="store_true", help="Skip shared registry summary refresh.") authority_parser = subparsers.add_parser( "register-authority-source", help="Register a redacted local authority/material source for a goal.", @@ -147,34 +158,50 @@ def handle_registry_authority_command( print_payload(payload, args.format, render_authority_sources_markdown) return 0 if payload["ok"] else 1 - if args.command == "register-authority-source": + if args.command in {"register-authority-source", "update-authority-source"}: + local_written = False try: - payload = register_authority_source( - registry_path=registry_path, - goal_id=args.goal_id, - source_id=args.source_id, - source_ref=args.source_ref, - source_kind=args.source_kind, - role=args.role, - freshness=args.freshness, - owner_status=args.owner_status, - gate_status=args.gate_status, - boundary=args.boundary, - revision=args.revision, - conflict_rule=args.conflict_rule, - topic=args.topic, - dry_run=bool(args.dry_run), - ) + if args.command == "update-authority-source": + payload = update_authority_source( + registry_path=registry_path, goal_id=args.goal_id, source_id=args.source_id, + freshness=args.freshness, owner_status=args.owner_status, gate_status=args.gate_status, + revision=args.revision, conflict_rule=args.conflict_rule, dry_run=bool(args.dry_run), + ) + else: + payload = register_authority_source( + registry_path=registry_path, + goal_id=args.goal_id, + source_id=args.source_id, + source_ref=args.source_ref, + source_kind=args.source_kind, + role=args.role, + freshness=args.freshness, + owner_status=args.owner_status, + gate_status=args.gate_status, + boundary=args.boundary, + revision=args.revision, + conflict_rule=args.conflict_rule, + topic=args.topic, + dry_run=bool(args.dry_run), + ) + local_written = bool(payload.get("written")) if not bool(args.no_global_sync): if args.dry_run: payload["global_sync"] = {"enabled": True, "dry_run": True, "wrote": False} else: - payload["global_sync"] = sync_project_registry_to_global( + sync_result = sync_project_registry_to_global( registry_path=registry_path, runtime_root_override=args.runtime_root, goal_id=args.goal_id, dry_run=False, ) + payload["global_sync"] = sync_result + if args.command == "update-authority-source" and sync_result.get("ok") is False: + payload["ok"] = False + payload["error"] = ( + "Project metadata was written, but shared registry synchronization failed: " + + str(sync_result.get("error") or "shared registry rejected the update") + ) else: payload["global_sync"] = {"enabled": False} except Exception as exc: @@ -184,7 +211,8 @@ def handle_registry_authority_command( "runtime_root": args.runtime_root, "goal_id": args.goal_id, "source_id": getattr(args, "source_id", None), - "written": False, + "written": local_written, + "operation": "update" if args.command == "update-authority-source" else "register", "dry_run": bool(getattr(args, "dry_run", False)), "error": str(exc), } diff --git a/loopx/cli_commands/registry_authority_metadata.py b/loopx/cli_commands/registry_authority_metadata.py new file mode 100644 index 0000000000..a8b599a9b1 --- /dev/null +++ b/loopx/cli_commands/registry_authority_metadata.py @@ -0,0 +1,71 @@ +"""Explicit metadata patches over the existing project material registration owner.""" +from __future__ import annotations + +import copy +from pathlib import Path +from typing import cast + +from ..authority import ( + Payload, _apply_authority_entry, _dict_view, find_goal_index, + normalize_project_materials, now_local, public_safe_optional, validate_authority_source_id, +) +from ..control_plane.projects.registry_codec import ( + load_project_registry, mutate_project_registry, require_runtime_compatible_project_registry, +) + + +def update_authority_source( + *, registry_path: Path, goal_id: str, source_id: str, + freshness: str | None = None, owner_status: str | None = None, + gate_status: str | None = None, revision: str | None = None, + conflict_rule: str | None = None, dry_run: bool = False, +) -> Payload: + """Patch recorded metadata under the registry lock; never reopen the source.""" + registry_path = registry_path.expanduser() + source_id = validate_authority_source_id(source_id) + changes: Payload = {} + for name, value in (("freshness", freshness), ("owner_status", owner_status), + ("gate_status", gate_status), ("revision", revision), + ("conflict_rule", conflict_rule)): + if value is not None: + cleaned = public_safe_optional(name, value) + if not cleaned: + raise ValueError(f"{name} must not be empty") + changes[name] = cleaned + if not changes: + raise ValueError("specify at least one metadata field to update") + + def reduce(registry: Payload) -> tuple[Payload, Payload]: + require_runtime_compatible_project_registry(registry, operation="authority metadata update") + index = find_goal_index(registry, goal_id) + goal = cast(list[Payload], registry["goals"])[index] + authority = _dict_view(goal.get("authority_registry")) + materials = normalize_project_materials(authority.get("project_materials")) + if source_id not in materials: + raise ValueError("source_id is not registered in this authoritative project registry; " + "select the project registry or register the source first") + entry = dict(materials[source_id]) + entry.update(changes) + entry["id"] = source_id + summary, _previous = _apply_authority_entry( + registry, goal_id=goal_id, entry=entry, registered_at=now_local(), + ) + return entry, summary + + if dry_run: + registry = load_project_registry(registry_path) + entry, summary = reduce(copy.deepcopy(registry)) + else: + entry, summary = mutate_project_registry( + registry_path, operation="update_authority_source", reducer=reduce, + ) + return { + "ok": True, "operation": "update", "dry_run": dry_run, "written": not dry_run, + "registry": str(registry_path), "goal_id": goal_id, "source_id": source_id, + "entry": entry, "updated_fields": sorted(changes), + "authority_registry_path": "authority_registry.project_materials", + "authority_registry_summary": summary, "raw_source_ref_stored": False, + "write_effect": "updated recorded metadata only; omitted fields, reference provenance and topics preserved; " + "no source access or permission change" if not dry_run else + "would update recorded metadata only; no registry writes or source access", + } diff --git a/loopx/help_surface.py b/loopx/help_surface.py index 137ef22409..26d7a0bc0e 100644 --- a/loopx/help_surface.py +++ b/loopx/help_surface.py @@ -407,6 +407,7 @@ def register_command_reference(subparsers: argparse._SubParsersAction[argparse.A "refresh-state", "reliability-diagnostics", "register-authority-source", + "update-authority-source", "registry-boundary", "reward", "reward-memory", diff --git a/skills/loopx-doc-registry/SKILL.md b/skills/loopx-doc-registry/SKILL.md index d2e650b6a8..b9c5fdab24 100644 --- a/skills/loopx-doc-registry/SKILL.md +++ b/skills/loopx-doc-registry/SKILL.md @@ -86,9 +86,46 @@ reference interpretation for displayed topics, exact filters and text search. Registration retains only a source-reference kind and digest, not its original URL/path. Use the original DOC_REGISTRY or authorized connector to locate and check the document, then reuse its listed source ID with -`register-authority-source` to update the recorded metadata. An inventory match +`update-authority-source` to update the recorded metadata. An inventory match is not evidence that the document was read or is still accessible. +## Maintain Existing Material Metadata + +After checking a material, preview a change to its recorded lifecycle metadata: + +```bash +loopx --registry .loopx/registry.json update-authority-source \ + --goal-id example-goal --source-id design-note \ + --freshness stale --gate-status needs_access --dry-run +``` + +Remove `--dry-run` to apply and refresh the shared registry summary; use +`--no-global-sync` to update only the project registry. Read back with +`authority-sources --goal-id example-goal --topic design` (using the registered +topic), or search for the source ID. Optional update fields are `--freshness`, +`--owner-status`, `--gate-status`, `--revision` and `--conflict-rule`. At least one +nonempty field is required. Omitted fields, original registration time, reference +kind/digest, imported summary metadata and topic mappings remain unchanged. +The source must already exist in the selected project registry. A shared summary +is insufficient; select the authoritative project registry explicitly. + +This records observations, not proof of reading, current access or permission to +access a source. No source is opened. Registration keeps its existing full-entry +replacement semantics; use it for deliberate replacement, supplying the complete +contract. Project writes use the existing registry transaction; shared-summary +sync follows separately. If sync fails after the project update, the failure +reports `ok: false` and `written: true`. Inspect the project readback; after +restoring shared registry access, sync the current project snapshot with the same +Goal and runtime root instead of replaying the metadata patch: + +```bash +loopx --registry .loopx/registry.json --runtime-root /path/to/runtime \ + sync-global --goal-id example-goal +``` + +Use the original resolved runtime root. Sync-only recovery preserves newer +metadata observations recorded since the failure. + ## Stop Conditions Stop and write a project-local todo or blocker instead of registering when: diff --git a/tests/architecture/test_source_session_registry_denial.py b/tests/architecture/test_source_session_registry_denial.py index 8ad66b7e8f..fb9163403b 100644 --- a/tests/architecture/test_source_session_registry_denial.py +++ b/tests/architecture/test_source_session_registry_denial.py @@ -28,6 +28,7 @@ "loopx/cli_runtime.py", "loopx/cli_commands/coordination_shadow.py", "loopx/cli_commands/manager_inbox.py", + "loopx/cli_commands/registry_authority_metadata.py", "loopx/cli_commands/registry_authority_read.py", "loopx/configure_goal.py", "loopx/control_plane/collaboration/goal_instance_scope.py", diff --git a/tests/test_authority_source_update_cli.py b/tests/test_authority_source_update_cli.py new file mode 100644 index 0000000000..7b81df1baa --- /dev/null +++ b/tests/test_authority_source_update_cli.py @@ -0,0 +1,234 @@ +"""Metadata maintenance preserves a registered material's identity and provenance.""" +from __future__ import annotations + +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from loopx.cli_commands.registry_authority_metadata import update_authority_source + + +def cli(path: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run([sys.executable, '-m', 'loopx.cli', '--registry', str(path), + '--format', 'json', *args], capture_output=True, text=True, timeout=45, + env={**os.environ, 'LOOPX_USAGE_PING': '0'}) + + +@pytest.fixture +def material(tmp_path: Path) -> Path: + path = tmp_path / 'project.json' + path.write_text(json.dumps({'schema_version': '0.1', 'goals': [ + {'id': 'demo', 'repo': str(tmp_path), 'authority_registry': {}}]})) + result = cli(path, 'register-authority-source', '--goal-id', 'demo', '--source-id', 'guide', + '--source-kind', 'doc', '--role', 'guide', '--freshness', 'current', + '--source-ref', str(tmp_path / 'never-created.md'), '--revision', 'edition-2', + '--topic', 'setup', '--conflict-rule', 'owner decides', '--no-global-sync') + assert result.returncode == 0, result.stdout + result.stderr + return path + + +def update(path: Path, *args: str) -> subprocess.CompletedProcess[str]: + return cli(path, 'update-authority-source', '--goal-id', 'demo', '--source-id', 'guide', *args) + + +@pytest.mark.parametrize('preview', [False, True]) +def test_source_session_update_rejected_without_writes(material: Path, preview: bool): + from loopx.control_plane.projects.registry_codec import SOURCE_SESSION_PROFILE_ID + + registry = json.loads(material.read_text()) + registry['profile_id'] = SOURCE_SESSION_PROFILE_ID + material.write_text(json.dumps(registry)) + before = material.read_bytes() + runtime = material.parent / 'denied-runtime' + result = cli(material, '--runtime-root', str(runtime), 'update-authority-source', + '--goal-id', 'demo', '--source-id', 'guide', '--freshness', 'stale', + *(['--dry-run'] if preview else [])) + assert result.returncode == 1, result.stdout + result.stderr + payload = json.loads(result.stdout) + assert payload['ok'] is False and payload['written'] is False + assert SOURCE_SESSION_PROFILE_ID in payload['error'] + assert material.read_bytes() == before + assert not runtime.exists() + + +def test_preview_apply_readback_preserves_reference_topics_and_omitted_fields(material: Path): + before = material.read_bytes() + original = json.loads(before)['goals'][0]['authority_registry']['project_materials']['guide'] + preview = update(material, '--freshness', 'stale', '--gate-status', 'needs_access', '--dry-run') + assert preview.returncode == 0, preview.stdout + preview.stderr + predicted = json.loads(preview.stdout) + assert predicted['written'] is False + assert predicted['global_sync']['wrote'] is False + assert material.read_bytes() == before + applied = cli(material, '--runtime-root', str(material.parent / 'runtime'), + 'update-authority-source', '--goal-id', 'demo', '--source-id', 'guide', + '--freshness', 'stale', '--gate-status', 'needs_access') + assert applied.returncode == 0, applied.stdout + applied.stderr + entry = json.loads(applied.stdout)['entry'] + assert entry == {**original, 'freshness': 'stale', 'gate_status': 'needs_access'} + assert entry == predicted['entry'] + read = cli(material, 'authority-sources', '--goal-id', 'demo', '--topic', 'setup', + '--query', 'stale needs_access edition-2') + assert read.returncode == 0, read.stdout + assert json.loads(read.stdout)['sources'][0]['source_ref_sha256'] == original['source_ref_sha256'] + goal = json.loads(material.read_text())['goals'][0] + assert goal['authority_sources'][0] == entry + shared = json.loads((material.parent / 'runtime' / 'registry.global.json').read_text())['goals'][0] + assert shared['authority_registry']['project_material_count'] == 1 + assert shared['authority_registry'] == json.loads(applied.stdout)['authority_registry_summary'] + # Metadata recording neither dereferences the unavailable source nor grants access. + assert not (material.parent / 'never-created.md').exists() + + +@pytest.mark.parametrize('args', [(), ('--freshness', ''), + ('--source-id', 'absent', '--freshness', 'stale'), + ('--source-id', '../bad', '--freshness', 'stale'), + ('--goal-id', 'absent', '--freshness', 'stale')]) +@pytest.mark.parametrize('preview', [False, True]) +def test_invalid_updates_never_create_or_replace(material: Path, args: tuple[str, ...], preview: bool): + before = material.read_bytes() + result = update(material, *args, '--no-global-sync', *(['--dry-run'] if preview else [])) + assert result.returncode != 0 + assert json.loads(result.stdout)['written'] is False + assert material.read_bytes() == before + + +def test_list_materials_and_import_metadata_preserved(material: Path): + registry = json.loads(material.read_text()) + authority = registry['goals'][0]['authority_registry'] + original = authority['project_materials']['guide'] + original.update(schema_version='doc_registry_authority_import_v0', default_entry_count=3) + authority['project_materials'] = [original] + authority['topic_authority'] = {'setup': [{'source_id': 'guide'}]} + material.write_text(json.dumps(registry)) + result = update(material, '--owner-status', 'reviewed', '--revision', 'edition-3', '--no-global-sync') + assert result.returncode == 0, result.stdout + entry = json.loads(result.stdout)['entry'] + assert entry == {**original, 'owner_status': 'reviewed', 'revision': 'edition-3'} + assert json.loads(material.read_text())['goals'][0]['authority_registry']['topic_authority'] == authority['topic_authority'] + + +def test_transaction_failure_keeps_original_bytes(material: Path, monkeypatch: pytest.MonkeyPatch): + from loopx.cli_commands import registry_authority_metadata as authority + before = material.read_bytes() + apply = authority._apply_authority_entry + + def fail_after_reduction(*args, **kwargs): + apply(*args, **kwargs) + raise ValueError('injected reduction failure') + + monkeypatch.setattr(authority, '_apply_authority_entry', fail_after_reduction) + with pytest.raises(ValueError, match='injected reduction failure'): + update_authority_source(registry_path=material, goal_id='demo', source_id='guide', freshness='stale') + assert material.read_bytes() == before + + +def test_markdown_preview_and_summary_recovery(material: Path): + before = material.read_bytes() + result = cli(material, '--format', 'markdown', 'update-authority-source', '--goal-id', 'demo', + '--source-id', 'guide', '--freshness', 'stale', '--dry-run') + assert result.returncode == 0, result.stdout + result.stderr + assert 'Metadata Update' in result.stdout + assert 'would update recorded metadata' in result.stdout + assert material.read_bytes() == before + applied = cli(material, '--format', 'markdown', 'update-authority-source', '--goal-id', 'demo', + '--source-id', 'guide', '--freshness', 'stale', '--no-global-sync') + assert applied.returncode == 0, applied.stdout + assert 'Metadata Update' in applied.stdout + assert 'updated recorded metadata' in applied.stdout + readback = cli(material, '--format', 'markdown', 'authority-sources', '--goal-id', 'demo', '--topic', 'setup') + assert readback.returncode == 0, readback.stdout + assert all(value in readback.stdout for value in ('stale', 'edition-2', 'setup')) + runtime = material.parent / 'runtime' + result = cli(material, '--runtime-root', str(runtime), 'update-authority-source', '--goal-id', 'demo', + '--source-id', 'guide', '--freshness', 'stale') + assert result.returncode == 0, result.stdout + shared = runtime / 'registry.global.json' + snapshot = shared.read_bytes() + material.rename(material.with_suffix('.saved')) + result = update(shared, '--freshness', 'current', '--no-global-sync') + assert result.returncode != 0 + assert 'project registry' in result.stdout + assert shared.read_bytes() == snapshot + assert not material.exists() + + +def test_sync_failure_reports_local_write_and_retry_recovers(material: Path): + runtime = material.parent / 'blocked-runtime' + runtime.write_text('not a directory') + args = ('--runtime-root', str(runtime), 'update-authority-source', '--goal-id', 'demo', + '--source-id', 'guide', '--freshness', 'stale') + result = cli(material, *args) + assert result.returncode != 0 + assert json.loads(result.stdout)['written'] is True + assert json.loads(material.read_text())['goals'][0]['authority_registry']['project_materials']['guide']['freshness'] == 'stale' + runtime.unlink() + result = cli(material, '--runtime-root', str(runtime), 'sync-global', '--goal-id', 'demo') + assert result.returncode == 0, result.stdout + assert (runtime / 'registry.global.json').exists() + + +def test_concurrent_disjoint_metadata_updates_preserve_each_other(material: Path): + from concurrent.futures import ThreadPoolExecutor + def apply(changes: dict): + return update_authority_source(registry_path=material, goal_id='demo', source_id='guide', **changes) + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(apply, [{'freshness': 'stale'}, {'owner_status': 'reviewed'}])) + assert all(result['written'] for result in results) + entry = json.loads(material.read_text())['goals'][0]['authority_registry']['project_materials']['guide'] + assert entry['freshness'] == 'stale' + assert entry['owner_status'] == 'reviewed' + assert entry['revision'] == 'edition-2' + assert entry['source_ref_sha256'] + + +@pytest.mark.skipif(os.name != 'posix' or getattr(os, 'geteuid', lambda: 0)() == 0, + reason='requires POSIX directory permissions enforced for a non-root user') +@pytest.mark.parametrize('output_format', ['json', 'markdown']) +def test_structured_sync_rejection_and_sync_only_recovery(material: Path, output_format: str): + runtime = material.parent / 'readonly-runtime' + route = ('--runtime-root', str(runtime)) + initial = cli(material, *route, 'sync-global', '--goal-id', 'demo') + assert initial.returncode == 0, initial.stdout + shared = runtime / 'registry.global.json' + before = shared.read_bytes() + original = json.loads(material.read_text())['goals'][0]['authority_registry']['project_materials']['guide'] + runtime.chmod(0o500) + try: + result = cli(material, *route, '--format', output_format, 'update-authority-source', + '--goal-id', 'demo', '--source-id', 'guide', '--freshness', 'stale') + assert result.returncode == 1, result.stdout + if output_format == 'json': + payload = json.loads(result.stdout) + assert payload['ok'] is False and payload['written'] is True + assert payload['global_sync']['ok'] is False + assert payload['global_sync']['write_denied'] is True + assert payload['global_sync']['error'] in payload['error'] + else: + assert '- written: `True`' in result.stdout + assert 'Permission denied' in result.stdout + assert shared.read_bytes() == before + committed = json.loads(material.read_text())['goals'][0]['authority_registry']['project_materials']['guide'] + assert committed == {**original, 'freshness': 'stale'} + # Another observation arrives before recovery. Recovery must not replay stale metadata. + later = cli(material, *route, 'update-authority-source', '--goal-id', 'demo', + '--source-id', 'guide', '--freshness', 'owner_review_pending', '--no-global-sync') + assert later.returncode == 0, later.stdout + newest = material.read_bytes() + finally: + runtime.chmod(0o700) + recovered = cli(material, *route, 'sync-global', '--goal-id', 'demo') + assert recovered.returncode == 0, recovered.stdout + assert material.read_bytes() == newest + entry = json.loads(newest)['goals'][0]['authority_registry']['project_materials']['guide'] + assert entry == {**original, 'freshness': 'owner_review_pending'} + before_summary = json.loads(before)['goals'][0]['authority_registry'] + summary = json.loads(shared.read_text())['goals'][0]['authority_registry'] + assert before_summary['project_material_owner_review_required_count'] == 0 + assert summary['project_material_owner_review_required_count'] == 1 + assert summary['project_material_stale_count'] == 0 + assert summary['project_material_count'] == 1