From 35b5344452d1f0ed41a47adaba33ff60a78d1398 Mon Sep 17 00:00:00 2001 From: Matt Date: Tue, 4 Aug 2026 21:48:12 -0400 Subject: [PATCH] feat: add Hermes federation control plane Add root-installable read-only tools for bounded lane context and federation drift checks, plus a bundled operating skill and tests. --- README.md | 16 + __init__.py | 5 + hermes_plugin/README.md | 25 ++ hermes_plugin/__init__.py | 144 +++++++ hermes_plugin/federation.py | 269 ++++++++++++ .../skills/federated-vaults/SKILL.md | 36 ++ plugin.yaml | 7 + tests/test_federation_plugin.py | 406 ++++++++++++++++++ 8 files changed, 908 insertions(+) create mode 100644 __init__.py create mode 100644 hermes_plugin/README.md create mode 100644 hermes_plugin/__init__.py create mode 100644 hermes_plugin/federation.py create mode 100644 hermes_plugin/skills/federated-vaults/SKILL.md create mode 100644 plugin.yaml create mode 100644 tests/test_federation_plugin.py diff --git a/README.md b/README.md index 1acf588..dac63b2 100644 --- a/README.md +++ b/README.md @@ -277,6 +277,22 @@ It is a coordination protocol, workspace layout, and operating discipline. Add s 6. Put recurring integrations in n8n, cron, CI, or another deterministic scheduler. 7. Add backup/versioning and pass a restore drill before trusting the deployment. +## Hermes-native control plane + +This repository is also a standalone Hermes Agent plugin. Install it directly from GitHub: + +```bash +hermes plugins install LiquidMatty/federated-vaults --enable +hermes tools enable federation --platform cli +``` + +It adds two deliberately read-only tools: + +- `federation_context` loads bounded START context only for a registry lane owned by the active Hermes profile, plus an optional project. Reads fail closed above explicit size budgets (256 KiB project note; 1 MiB worklist/control file). +- `federation_doctor` checks registry paths, doorway protocol echoes, and worklist schema/status drift. + +It also adds `/federation` and the bundled `federated-vaults:federated-vaults` skill. See [`hermes_plugin/README.md`](hermes_plugin/README.md). + ## License MIT. Use freely, without warranty. Adapt the templates to your own inventory, permissions, integrations, and operational requirements. diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..974e8e7 --- /dev/null +++ b/__init__.py @@ -0,0 +1,5 @@ +"""Installable Hermes plugin entry point for Federated Vaults.""" + +from .hermes_plugin import _split_args, federation_context, federation_doctor, register + +__all__ = ["federation_context", "federation_doctor", "register"] diff --git a/hermes_plugin/README.md b/hermes_plugin/README.md new file mode 100644 index 0000000..7ff0819 --- /dev/null +++ b/hermes_plugin/README.md @@ -0,0 +1,25 @@ +# Federated Vaults Hermes Plugin + +This repository is directly installable as a Hermes plugin: + +```bash +hermes plugins install LiquidMatty/federated-vaults --enable +hermes tools enable federation --platform cli +``` + +The plugin adds: + +- `federation_context` — loads bounded START context only for a lane owned by the active Hermes profile: newest HUB/lane changelog lines, the named project note, and its full worklist within explicit read budgets. Cross-lane reads require an explicit operator-mediated handoff. Oversized project notes (>256 KiB) and worklists/control files (>1 MiB) fail closed rather than being truncated silently. +- `federation_doctor` — read-only checks for missing registered lanes, doorway protocol-version drift, invalid worklist JSON, and non-canonical task statuses. +- `/federation doctor [root]` and `/federation context [project] [root]`. +- `federated-vaults:federated-vaults` — the operational skill bundled with the plugin. + +The implementation is intentionally read-only. It surfaces drift but never rewrites HUB canon, doorways, changelogs, or worklists automatically. + +## Local development + +```bash +python3 -m unittest discover -s tests -p 'test_federation_plugin.py' -v +``` + +A federation is discovered by walking upward until a `HUB/` directory contains `PROTOCOL.md`, `PRINCIPLES.md`, and `CHANGELOG.md`. Lanes come from `HUB/REGISTRY.md`; no machine-specific root path is compiled into the plugin. diff --git a/hermes_plugin/__init__.py b/hermes_plugin/__init__.py new file mode 100644 index 0000000..500ffb1 --- /dev/null +++ b/hermes_plugin/__init__.py @@ -0,0 +1,144 @@ +"""Hermes registration surface for the Federated Vaults plugin.""" + +from __future__ import annotations + +import json +import os +import shlex +from pathlib import Path + +from .federation import load_context, run_doctor + + +def _json(value: object) -> str: + return json.dumps(value, default=lambda item: str(item), indent=2) + + +def _root(args: dict) -> str: + return args.get("root") or os.getcwd() + + +def _active_profile() -> str: + """Resolve the active Hermes profile, failing closed outside Hermes.""" + try: + from hermes_cli.profiles import get_active_profile_name + + return get_active_profile_name() + except Exception: + return "__unknown_profile__" + + +def federation_doctor(args: dict, **_: object) -> str: + """Hermes tool handler for read-only federation checks.""" + try: + return _json(run_doctor(_root(args))) + except Exception as exc: + return _json({"success": False, "error": str(exc), "type": exc.__class__.__name__}) + + +def federation_context(args: dict, **_: object) -> str: + """Hermes tool handler for bounded lane context.""" + try: + lane = args.get("lane") + if not lane: + return _json({"success": False, "error": "lane is required"}) + return _json( + load_context( + _root(args), + lane=lane, + project=args.get("project"), + log_lines=int(args.get("log_lines", 20)), + requesting_profile=_active_profile(), + ) + ) + except Exception as exc: + return _json({"success": False, "error": str(exc), "type": exc.__class__.__name__}) + + +def _split_args(raw_args: str, windows: bool = False) -> list[str]: + """Split slash-command arguments without consuming Windows path separators.""" + parts = shlex.split(raw_args, posix=not windows) + if not windows: + return parts + return [ + part[1:-1] if len(part) >= 2 and part[0] == part[-1] and part[0] in {'"', "'"} else part + for part in parts + ] + + +def _slash(raw_args: str = "", **_: object) -> str: + """Handle `/federation doctor` and `/federation context [project]`.""" + try: + parts = _split_args(raw_args, windows=os.name == "nt") + except ValueError as exc: + return f"Invalid arguments: {exc}" + if not parts or parts[0] in {"help", "-h", "--help"}: + return "Usage: /federation doctor [root] | /federation context [project] [root]" + if parts[0] in {"doctor", "status"}: + return federation_doctor({"root": parts[1] if len(parts) > 1 else os.getcwd()}) + if parts[0] == "context" and len(parts) >= 2: + return federation_context( + { + "lane": parts[1], + "project": parts[2] if len(parts) > 2 else None, + "root": parts[3] if len(parts) > 3 else os.getcwd(), + } + ) + return "Usage: /federation doctor [root] | /federation context [project] [root]" + + +_DOCTOR_SCHEMA = { + "name": "federation_doctor", + "description": "Run read-only drift and integrity checks on a Federated Vaults HUB and its registered active lanes.", + "parameters": { + "type": "object", + "properties": { + "root": {"type": "string", "description": "Federation root or any path inside it. Defaults to the current working directory."} + }, + }, +} + +_CONTEXT_SCHEMA = { + "name": "federation_context", + "description": "Load bounded START context for a lane owned by the active Hermes profile: top changelog lines, project note, and full worklist.", + "parameters": { + "type": "object", + "properties": { + "lane": {"type": "string", "description": "Registry vault name, profile name, or vault directory name."}, + "project": {"type": "string", "description": "Optional project note/worklist slug."}, + "root": {"type": "string", "description": "Federation root or any path inside it."}, + "log_lines": {"type": "integer", "minimum": 1, "maximum": 100, "default": 20}, + }, + "required": ["lane"], + }, +} + + +def register(ctx) -> None: + ctx.register_tool( + name="federation_doctor", + toolset="federation", + schema=_DOCTOR_SCHEMA, + handler=federation_doctor, + description=_DOCTOR_SCHEMA["description"], + emoji="🗂️", + ) + ctx.register_tool( + name="federation_context", + toolset="federation", + schema=_CONTEXT_SCHEMA, + handler=federation_context, + description=_CONTEXT_SCHEMA["description"], + emoji="🗂️", + ) + ctx.register_command( + "federation", + handler=_slash, + description="Inspect a Federated Vaults tree and load bounded lane context.", + args_hint="doctor [root] | context [project] [root]", + ) + ctx.register_skill( + "federated-vaults", + Path(__file__).parent / "skills" / "federated-vaults" / "SKILL.md", + "Operate safely inside a HUB-and-lanes Federated Vaults tree.", + ) diff --git a/hermes_plugin/federation.py b/hermes_plugin/federation.py new file mode 100644 index 0000000..a92d919 --- /dev/null +++ b/hermes_plugin/federation.py @@ -0,0 +1,269 @@ +"""Core filesystem operations for the Federated Vaults Hermes plugin.""" + +from __future__ import annotations + +from pathlib import Path +import json +import re + +_REQUIRED_HUB_FILES = ("PROTOCOL.md", "PRINCIPLES.md", "CHANGELOG.md") +_ALLOWED_STATUSES = {"incomplete", "in_progress", "blocked", "complete"} +_PROTOCOL_VERSION = re.compile(r"(?im)^Protocol-Version:\s*([^\s]+)") +_DOORWAY_VERSION = re.compile(r"(?im)^Protocol-Version echo:\s*([^\s]+)") +_KNOWN_REGISTRY_STATUS_PREFIXES = ("active", "retired", "inactive", "archived", "canonical", "template") +_MAX_CONTROL_FILE_BYTES = 1024 * 1024 +_MAX_PROJECT_NOTE_BYTES = 256 * 1024 +_MAX_WORKLIST_BYTES = 1024 * 1024 + + +class FileTooLargeError(ValueError): + """Raised when a context file exceeds its explicit read budget.""" + + +def _is_within(path: Path, boundary: Path) -> bool: + resolved = path.resolve() + resolved_boundary = boundary.resolve() + return resolved == resolved_boundary or resolved_boundary in resolved.parents + + +def _read_text(path: Path, boundary: Path, max_bytes: int = _MAX_CONTROL_FILE_BYTES) -> str: + if not _is_within(path, boundary): + raise PermissionError(f"Refusing to read path outside boundary: {path}") + size = path.stat().st_size + if size > max_bytes: + raise FileTooLargeError(f"File is too large to read safely ({size} > {max_bytes} bytes): {path}") + return path.read_text(encoding="utf-8", errors="replace") + + +def discover_federation(start: Path | str) -> Path: + """Return the nearest parent whose HUB contains the canonical files.""" + current = Path(start).expanduser().resolve() + if current.is_file(): + current = current.parent + for candidate in (current, *current.parents): + hub = candidate / "HUB" + if _is_within(hub, candidate) and all( + (hub / name).is_file() and _is_within(hub / name, hub) + for name in _REQUIRED_HUB_FILES + ): + return candidate + raise FileNotFoundError(f"No federation HUB found from {current}") + + +def parse_registry(registry_path: Path | str, root: Path | str) -> list[dict]: + """Parse the Markdown registry table into normalized lane records.""" + registry_path = Path(registry_path) + root = Path(root).resolve() + rows: list[dict] = [] + header_found = False + for line_number, line in enumerate(_read_text(registry_path, root / "HUB").splitlines(), start=1): + if "| Vault |" in line: + header_found = True + continue + if not line.startswith("|") or line.startswith("|---"): + continue + columns = [column.strip() for column in line.strip("|").split("|")] + if len(columns) < 5: + raise ValueError(f"Malformed registry row at line {line_number}: expected at least 5 columns") + name, raw_path, purpose, profile, status = columns[:5] + if not name or not raw_path or not status: + raise ValueError(f"Malformed registry row at line {line_number}: required field is empty") + path = root / "HUB" if raw_path == "this folder" else (root / "HUB" / raw_path).resolve() + inside_root = path == root or root in path.parents + normalized_status = status.casefold() + rows.append( + { + "name": name, + "path": path, + "purpose": purpose, + "profile": profile, + "status": status, + "status_known": normalized_status.startswith(_KNOWN_REGISTRY_STATUS_PREFIXES), + "active": normalized_status.startswith("active"), + "inside_root": inside_root, + "exists": inside_root and path.is_dir(), + } + ) + if not header_found: + raise ValueError("Registry table header is missing") + if not rows: + raise ValueError("Registry contains no vault rows") + return rows + + +def run_doctor(start: Path | str) -> dict: + """Run read-only structural checks across the registered federation.""" + root = discover_federation(start) + hub = root / "HUB" + protocol_text = _read_text(hub / "PROTOCOL.md", hub) + explicit = _PROTOCOL_VERSION.search(protocol_text) + heading = re.search(r"(?im)^#\s+.*?\b(v\d+(?:\.\d+)+)\b", protocol_text) + canonical_version = explicit.group(1) if explicit else (heading.group(1) if heading else None) + findings: list[dict] = [] + if canonical_version is None: + findings.append({"code": "missing_protocol_version", "path": str(hub / "PROTOCOL.md")}) + try: + rows = parse_registry(hub / "REGISTRY.md", root) + except FileNotFoundError as exc: + return { + "status": "findings", + "root": str(root), + "protocol_version": canonical_version, + "lanes": [], + "findings": [{"code": "missing_registry", "path": str(hub / "REGISTRY.md"), "error": str(exc)}], + } + except (OSError, ValueError) as exc: + return { + "status": "findings", + "root": str(root), + "protocol_version": canonical_version, + "lanes": [], + "findings": [{"code": "invalid_registry", "path": str(hub / "REGISTRY.md"), "error": str(exc)}], + } + + for row in rows: + if not row["inside_root"]: + findings.append({"code": "registry_path_outside_root", "lane": row["name"], "path": str(row["path"])}) + continue + if not row["status_known"]: + findings.append({"code": "invalid_registry_status", "lane": row["name"], "status": row["status"]}) + continue + if row["active"] and row["name"] != "HUB" and not row["profile"].strip(): + findings.append({"code": "missing_registry_owner", "lane": row["name"]}) + continue + if not row["active"] or row["name"] == "HUB": + continue + lane = row["path"] + if not lane.is_dir(): + findings.append({"code": "missing_lane", "lane": row["name"], "path": str(lane)}) + continue + doorway = lane / "AGENTS.md" + if not doorway.is_file(): + findings.append({"code": "missing_doorway", "lane": row["name"], "path": str(doorway)}) + elif not _is_within(doorway, lane): + findings.append({"code": "doorway_outside_lane", "lane": row["name"], "path": str(doorway)}) + elif canonical_version: + doorway_match = _DOORWAY_VERSION.search(_read_text(doorway, lane)) + doorway_version = doorway_match.group(1) if doorway_match else None + if doorway_version != canonical_version: + findings.append( + { + "code": "protocol_mismatch", + "lane": row["name"], + "expected": canonical_version, + "actual": doorway_version, + } + ) + + for worklist in lane.glob("OUTPUTS/**/worklist.json"): + if not _is_within(worklist, lane): + findings.append({"code": "worklist_outside_lane", "path": str(worklist)}) + continue + try: + payload = json.loads(_read_text(worklist, lane, _MAX_WORKLIST_BYTES)) + except FileTooLargeError as exc: + findings.append({"code": "worklist_too_large", "path": str(worklist), "error": str(exc)}) + continue + except (OSError, json.JSONDecodeError) as exc: + findings.append({"code": "invalid_worklist_json", "path": str(worklist), "error": str(exc)}) + continue + tasks = payload.get("tasks") if isinstance(payload, dict) else None + if not isinstance(payload, dict) or not isinstance(tasks, list): + findings.append({"code": "invalid_worklist_schema", "path": str(worklist)}) + continue + for task in tasks: + if not isinstance(task, dict): + findings.append({"code": "invalid_worklist_schema", "path": str(worklist)}) + continue + status = task.get("status") + if status not in _ALLOWED_STATUSES: + findings.append( + { + "code": "invalid_worklist_status", + "path": str(worklist), + } + ) + + return { + "status": "findings" if findings else "clean", + "root": str(root), + "protocol_version": canonical_version, + "lanes": rows, + "findings": findings, + } + + +def _resolve_lane(rows: list[dict], selector: str) -> dict: + wanted = selector.casefold() + for row in rows: + profiles = {item.strip().casefold() for item in row["profile"].split(",") if item.strip()} + candidates = {row["name"].casefold(), row["path"].name.casefold(), *profiles} + if wanted in candidates: + return row + raise ValueError(f"Lane not found: {selector}") + + +def load_context( + start: Path | str, + lane: str, + project: str | None = None, + log_lines: int = 20, + requesting_profile: str | None = None, +) -> dict: + """Load the bounded federation START context for one registered lane.""" + if not 1 <= log_lines <= 100: + raise ValueError("log_lines must be between 1 and 100") + root = discover_federation(start) + rows = parse_registry(root / "HUB" / "REGISTRY.md", root) + record = _resolve_lane(rows, lane) + if not record["active"]: + raise PermissionError(f"Lane is not active: {record['name']}") + if requesting_profile: + owners = {item.strip().casefold() for item in record["profile"].split(",") if item.strip()} + if requesting_profile.casefold() not in owners: + raise PermissionError( + f"Profile {requesting_profile!r} does not own lane {record['name']!r}; " + "cross-lane context requires explicit operator mediation" + ) + lane_path = record["path"] + if not record["inside_root"]: + raise PermissionError(f"Registry lane resolves outside federation root: {lane}") + if not lane_path.is_dir(): + raise FileNotFoundError(f"Lane directory is missing: {lane_path}") + + def bounded(path: Path, boundary: Path) -> list[str]: + return _read_text(path, boundary).splitlines()[:log_lines] if path.is_file() else [] + + result: dict = { + "root": str(root), + "lane": record["name"], + "profile": record["profile"], + "hub_changelog": bounded(root / "HUB" / "CHANGELOG.md", root / "HUB"), + "lane_changelog": bounded(lane_path / "VAULT" / "CHANGELOG.md", lane_path), + "project_note": None, + "project_note_path": None, + "worklist": None, + "worklist_path": None, + } + if not project: + return result + if project in {".", ".."} or re.search(r"[\\/:]", project): + raise ValueError("project must be a single project name or output slug") + + project_dir = lane_path / "VAULT" / "01 Projects" + notes = [path for path in project_dir.glob("*.md") if path.stem.casefold() == project.casefold()] + if notes: + if not _is_within(notes[0], lane_path): + raise PermissionError(f"Project note resolves outside lane: {notes[0]}") + result["project_note_path"] = str(notes[0]) + result["project_note"] = _read_text(notes[0], lane_path, _MAX_PROJECT_NOTE_BYTES) + worklist = lane_path / "OUTPUTS" / project / "worklist.json" + if not worklist.is_file(): + matches = [path for path in (lane_path / "OUTPUTS").glob("*/worklist.json") if path.parent.name.casefold() == project.casefold()] + worklist = matches[0] if matches else worklist + if worklist.is_file(): + if not _is_within(worklist, lane_path): + raise PermissionError(f"Worklist resolves outside lane: {worklist}") + result["worklist_path"] = str(worklist) + result["worklist"] = json.loads(_read_text(worklist, lane_path, _MAX_WORKLIST_BYTES)) + return result diff --git a/hermes_plugin/skills/federated-vaults/SKILL.md b/hermes_plugin/skills/federated-vaults/SKILL.md new file mode 100644 index 0000000..3b92a73 --- /dev/null +++ b/hermes_plugin/skills/federated-vaults/SKILL.md @@ -0,0 +1,36 @@ +--- +name: federated-vaults +description: "Use when working in a HUB-and-lanes federated vault tree." +version: 0.1.0 +platforms: [linux, macos, windows] +--- + +# Federated Vaults in Hermes + +Use this skill whenever the current work lives in a federation with `HUB/PROTOCOL.md`, `HUB/REGISTRY.md`, and isolated vault lanes. + +## Start + +1. Call `federation_context` with the active Hermes profile's owning lane and project slug. The tool denies non-owned lanes and returns only the bounded START context: newest HUB lines, newest lane lines, the project note, and the full worklist when present and within the explicit read budgets. Oversized files fail closed. +2. Treat the vault files as canonical. Conversation and memory are recall aids, never the task-state source of truth. +3. If the doorway protocol echo differs from the HUB, obey the HUB and report the drift. + +## Work + +- Stay in the owning lane unless the operator explicitly authorizes a named cross-boundary read or write. +- Use a worklist for multi-step, delegated, migration, integration, or system-build work. +- Keep completion criteria separate from test criteria; record evidence immediately. +- Version deliverables. Never delete, bulk-move, or bulk-rename without explicit approval. +- Keep credentials and private identifiers out of vault files. + +## Handoffs + +Non-trivial cross-lane work travels as a handoff package in the receiving lane: project note plus `OUTPUTS//worklist.json`, with a final report-back task. A HUB changelog line is awareness, not the task payload. + +## Verification + +Call `federation_doctor` for a read-only check of registry paths, doorway protocol echoes, and worklist JSON/status values. Findings are evidence to review, not permission to auto-edit canon. + +## End + +When files changed, update the owning lane changelog, project status/open items, and only add a sanitized HUB pointer if another lane is affected. If nothing changed, write nothing. diff --git a/plugin.yaml b/plugin.yaml new file mode 100644 index 0000000..30d4bb8 --- /dev/null +++ b/plugin.yaml @@ -0,0 +1,7 @@ +name: federated-vaults +version: 0.1.0 +description: "Hermes-native control plane for file-first federated vaults: bounded START context, registry awareness, and read-only drift checks." +author: LiquidMatty +provides_tools: + - federation_doctor + - federation_context diff --git a/tests/test_federation_plugin.py b/tests/test_federation_plugin.py new file mode 100644 index 0000000..3512864 --- /dev/null +++ b/tests/test_federation_plugin.py @@ -0,0 +1,406 @@ +import importlib.util +import json +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_DIR = Path(__file__).resolve().parents[1] +PLUGIN_DIR = REPO_DIR +sys.path.insert(0, str(REPO_DIR)) + +from hermes_plugin.federation import ( # noqa: E402 + discover_federation, + load_context, + parse_registry, + run_doctor, +) + + +class FederationDiscoveryTests(unittest.TestCase): + def test_discovers_parent_with_hub_and_parses_registry(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + (root / "HUB").mkdir() + (root / "HUB" / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (root / "HUB" / "PRINCIPLES.md").write_text("# Principles\n") + (root / "HUB" / "CHANGELOG.md").write_text("# Log\n") + (root / "Client Vault").mkdir() + (root / "HUB" / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| Client | ../Client Vault | Client lane | client_agent | active | thin |\n" + "| Old | ../Old Vault | retired | old_agent | retired | gone |\n" + ) + + found = discover_federation(root / "Client Vault") + rows = parse_registry(found / "HUB" / "REGISTRY.md", found) + + self.assertEqual(found, root.resolve()) + self.assertEqual(rows[0]["name"], "Client") + self.assertEqual(rows[0]["profile"], "client_agent") + self.assertTrue(rows[0]["active"]) + self.assertEqual(rows[0]["path"], (root / "Client Vault").resolve()) + self.assertFalse(rows[1]["active"]) + + (root / "HUB" / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| Escape | ../../outside | Work | rogue | active | |\n" + ) + escaped = parse_registry(root / "HUB" / "REGISTRY.md", root)[0] + self.assertFalse(escaped["inside_root"]) + + +class FederationDoctorTests(unittest.TestCase): + def test_reports_and_skips_active_lane_without_profile_owner(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + output = lane / "OUTPUTS" / "alpha" + hub.mkdir() + output.mkdir(parents=True) + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status |\n" + "|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | | active |\n" + ) + (lane / "AGENTS.md").write_text("Protocol-Version echo: 2\n") + (output / "worklist.json").write_text(json.dumps({"tasks": [{"status": "private-status"}]})) + + report = run_doctor(root) + codes = {finding["code"] for finding in report["findings"]} + self.assertIn("missing_registry_owner", codes) + self.assertNotIn("invalid_worklist_status", codes) + + def test_reports_out_of_root_paths_even_for_hub_and_inactive_rows(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) / "federation" + hub = root / "HUB" + hub.mkdir(parents=True) + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status |\n" + "|---|---|---|---|---|\n" + "| HUB | ../../outside-hub | Coordination | — | active |\n" + "| Retired | ../../outside-retired | Archive | retired_agent | retired |\n" + ) + + report = run_doctor(root) + outside = [finding for finding in report["findings"] if finding["code"] == "registry_path_outside_root"] + self.assertEqual({finding["lane"] for finding in outside}, {"HUB", "Retired"}) + + def test_reports_oversized_worklist_without_aborting(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + output = lane / "OUTPUTS" / "alpha" + hub.mkdir() + output.mkdir(parents=True) + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status |\n" + "|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | lane_agent | active |\n" + ) + (lane / "AGENTS.md").write_text("Protocol-Version echo: 2\n") + (output / "worklist.json").write_text(json.dumps({"tasks": [], "padding": "x" * (1024 * 1024)})) + + report = run_doctor(root) + self.assertIn("worklist_too_large", {finding["code"] for finding in report["findings"]}) + + def test_reports_missing_protocol_version(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + hub.mkdir() + (hub / "PROTOCOL.md").write_text("# HUB Protocol\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status |\n" + "|---|---|---|---|---|\n" + "| HUB | this folder | Coordination | — | canonical |\n" + ) + + report = run_doctor(root) + self.assertIn("missing_protocol_version", {finding["code"] for finding in report["findings"]}) + + def test_reports_unknown_registry_status_instead_of_skipping_lane(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + hub.mkdir() + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status |\n" + "|---|---|---|---|---|\n" + "| Lane | this folder | Work | lane_agent | mystery |\n" + ) + + report = run_doctor(root) + self.assertIn("invalid_registry_status", {finding["code"] for finding in report["findings"]}) + + def test_reports_malformed_registry_instead_of_clean(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + hub.mkdir() + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| broken | only-two-columns |\n" + ) + + report = run_doctor(root) + self.assertEqual(report["status"], "findings") + self.assertIn("invalid_registry", {finding["code"] for finding in report["findings"]}) + + def test_accepts_public_protocol_version_heading(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + hub.mkdir() + lane.mkdir() + (hub / "PROTOCOL.md").write_text("# HUB Protocol v0.6.0\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | lane_agent | active | |\n" + ) + (lane / "AGENTS.md").write_text("Protocol-Version echo: v0.5.0\n") + + report = run_doctor(root) + + self.assertEqual(report["protocol_version"], "v0.6.0") + self.assertEqual(report["findings"][0]["code"], "protocol_mismatch") + + def test_reports_protocol_mismatch_missing_lane_and_invalid_worklist(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + (lane / "OUTPUTS" / "build").mkdir(parents=True) + hub.mkdir() + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | lane_agent | active | |\n" + "| Missing | ../Missing | Work | missing_agent | active | |\n" + ) + (lane / "AGENTS.md").write_text("Protocol-Version echo: 1\n") + (lane / "OUTPUTS" / "build" / "worklist.json").write_text( + json.dumps({"project": "build", "tasks": [{"id": "T1", "status": "done"}]}) + ) + malformed = lane / "OUTPUTS" / "malformed" + malformed.mkdir() + (malformed / "worklist.json").write_text("[]") + missing_tasks = lane / "OUTPUTS" / "missing-tasks" + missing_tasks.mkdir() + (missing_tasks / "worklist.json").write_text("{}") + + report = run_doctor(root) + codes = {finding["code"] for finding in report["findings"]} + + self.assertEqual(report["status"], "findings") + self.assertIn("missing_lane", codes) + self.assertIn("protocol_mismatch", codes) + self.assertIn("invalid_worklist_status", codes) + self.assertIn("invalid_worklist_schema", codes) + self.assertEqual(sum(finding["code"] == "invalid_worklist_schema" for finding in report["findings"]), 2) + self.assertTrue( + all( + "task" not in finding and "status" not in finding + for finding in report["findings"] + if finding["code"] == "invalid_worklist_status" + ) + ) + + +class FederationContextTests(unittest.TestCase): + def test_rejects_oversized_project_note_and_worklist(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + projects = lane / "VAULT" / "01 Projects" + output = lane / "OUTPUTS" / "alpha" + hub.mkdir() + projects.mkdir(parents=True) + output.mkdir(parents=True) + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status |\n" + "|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | lane_agent | active |\n" + ) + note = projects / "alpha.md" + worklist = output / "worklist.json" + note.write_text("x" * (256 * 1024 + 1)) + worklist.write_text('{"tasks": []}') + + with self.assertRaisesRegex(ValueError, "too large"): + load_context(root, lane="lane_agent", project="alpha") + + note.write_text("# Alpha\n") + worklist.write_text(json.dumps({"tasks": [], "padding": "x" * (1024 * 1024)})) + with self.assertRaisesRegex(ValueError, "too large"): + load_context(root, lane="lane_agent", project="alpha") + + def test_loads_bounded_start_context_and_full_worklist(self): + with tempfile.TemporaryDirectory() as raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + project_dir = lane / "VAULT" / "01 Projects" + output_dir = lane / "OUTPUTS" / "alpha" + hub.mkdir() + project_dir.mkdir(parents=True) + output_dir.mkdir(parents=True) + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("\n".join(f"hub-{i}" for i in range(150))) + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | lane_agent, alternate | active | |\n" + "| Retired | ../Lane | Archive | retired_agent | retired | |\n" + ) + (lane / "VAULT" / "CHANGELOG.md").write_text("\n".join(f"lane-{i}" for i in range(150))) + (project_dir / "alpha.md").write_text("# Alpha\nCurrent status\n") + (output_dir / "worklist.json").write_text(json.dumps({"project": "alpha", "tasks": []})) + + context = load_context(root, lane="alternate", project="alpha", log_lines=20) + + self.assertEqual(len(context["hub_changelog"]), 20) + self.assertNotIn("hub-20", context["hub_changelog"]) + self.assertIn("Current status", context["project_note"]) + self.assertEqual(context["worklist"]["project"], "alpha") + + with self.assertRaises(ValueError): + load_context(root, lane="alternate", log_lines=999) + + with self.assertRaises(PermissionError): + load_context(root, lane="alternate", requesting_profile="other_agent") + owned = load_context(root, lane="alternate", requesting_profile="alternate") + self.assertEqual(owned["lane"], "Lane") + with self.assertRaises(PermissionError): + load_context(root, lane="retired_agent", requesting_profile="retired_agent") + + for unsafe_project in ("../outside", "C:outside"): + with self.subTest(project=unsafe_project), self.assertRaises(ValueError): + load_context(root, lane="alternate", project=unsafe_project) + + def test_refuses_symlinked_context_files_outside_lane(self): + with tempfile.TemporaryDirectory() as raw, tempfile.TemporaryDirectory() as outside_raw: + root = Path(raw) + hub = root / "HUB" + lane = root / "Lane" + projects = lane / "VAULT" / "01 Projects" + hub.mkdir() + projects.mkdir(parents=True) + (hub / "PROTOCOL.md").write_text("Protocol-Version: 2\n") + (hub / "PRINCIPLES.md").write_text("# Principles\n") + (hub / "CHANGELOG.md").write_text("# Log\n") + (hub / "REGISTRY.md").write_text( + "| Vault | Path | Purpose | Hermes profile | Status | Notes |\n" + "|---|---|---|---|---|---|\n" + "| Lane | ../Lane | Work | lane_agent | active | |\n" + ) + outside = Path(outside_raw) / "private.md" + outside.write_text("private") + try: + (projects / "alpha.md").symlink_to(outside) + except OSError as exc: + self.skipTest(f"symlinks unavailable: {exc}") + + with self.assertRaises(PermissionError): + load_context(root, lane="lane_agent", project="alpha") + + +class PluginRegistrationTests(unittest.TestCase): + def test_manifest_advertises_registered_tools(self): + manifest = (REPO_DIR / "plugin.yaml").read_text(encoding="utf-8") + self.assertIn("provides_tools:", manifest) + self.assertIn("federation_doctor", manifest) + self.assertIn("federation_context", manifest) + + def test_registers_two_tools_slash_command_and_skill(self): + spec = importlib.util.spec_from_file_location( + "fv_plugin", + PLUGIN_DIR / "__init__.py", + submodule_search_locations=[str(PLUGIN_DIR)], + ) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + previous = sys.modules.pop("federation", None) + plugin_path = str(PLUGIN_DIR) + sys.path.remove(plugin_path) + sys.modules["fv_plugin"] = module + try: + spec.loader.exec_module(module) + finally: + sys.path.insert(0, plugin_path) + if previous is not None: + sys.modules["federation"] = previous + + class Context: + def __init__(self): + self.tools = [] + self.commands = [] + self.skills = [] + + def register_tool(self, **kwargs): + self.tools.append(kwargs) + + def register_command(self, name, **kwargs): + self.commands.append((name, kwargs)) + + def register_skill(self, name, path, description=""): + self.skills.append((name, Path(path), description)) + + ctx = Context() + module.register(ctx) + + captured = {} + implementation = sys.modules["fv_plugin.hermes_plugin"] + setattr(implementation, "_active_profile", lambda: "owner_agent") + setattr(implementation, "load_context", lambda *args, **kwargs: captured.update(kwargs) or {}) + self.assertEqual(json.loads(module.federation_context({"lane": "Lane", "root": "."})), {}) + self.assertEqual(captured["requesting_profile"], "owner_agent") + + windows_parts = module._split_args(r'doctor "C:\vaults\fed"', windows=True) + self.assertEqual(windows_parts, ["doctor", r"C:\vaults\fed"]) + self.assertEqual({item["name"] for item in ctx.tools}, {"federation_context", "federation_doctor"}) + for item in ctx.tools: + self.assertNotIn("function", item["schema"]) + self.assertEqual(item["schema"]["name"], item["name"]) + self.assertIn("parameters", item["schema"]) + self.assertEqual(ctx.commands[0][0], "federation") + self.assertEqual(ctx.skills[0][0], "federated-vaults") + + +if __name__ == "__main__": + unittest.main()