diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e4b9311..5ac884d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -25,6 +25,6 @@ jobs: - name: Install development dependencies run: python -m pip install --upgrade pip && python -m pip install -e '.[dev]' - name: Compile Python sources - run: python -m py_compile bridge_core/*.py scripts/*.py + run: python -m py_compile bridge/*.py - name: Run tests run: python -m pytest -q diff --git a/.gitignore b/.gitignore index 8986ac3..0650f86 100644 --- a/.gitignore +++ b/.gitignore @@ -1,27 +1,14 @@ -# Python +# Python and local build output __pycache__/ *.py[cod] -*.pyo .pytest_cache/ -.mypy_cache/ -.ruff_cache/ - -# Virtual environments +*.egg-info/ +build/ +dist/ .venv/ venv/ - -# Local Bridge runtime state -bridge/ - -# Private local shared notes, not part of OSS Bridge core -core/ - -# Local config and secrets -config/bridge_api.env -config/*.bak-* +# Keep runtime data outside the source package. +.bridge-data/ .env - -# OS/editor noise .DS_Store *.swp -*.swo diff --git a/README.md b/README.md index 944ccf8..aecdc5a 100644 --- a/README.md +++ b/README.md @@ -1,311 +1,144 @@ # Bridge -Bridge is an event-driven handoff bus for autonomous agents. - -It gives you a bounded place to create, receive, track, and close agent-to-agent work without turning every agent vault into a shared memory swamp. - -## What it does - -- creates explicit handoff records between agents -- stores an authoritative canonical record plus recoverable sender and recipient queue views -- enforces route policy and status transitions -- exposes a local HTTP API for wrappers and automation -- supports durable at-least-once lifecycle events plus immediate compatibility notifications -- supports read-only event consumers for surfacing lifecycle events into chat/UI adapters -- includes patrol tooling for reminders and unresolved-handoff detection - -## Configuration model - -Bridge ships with **no built-in agent IDs** and **no default route graph**. - -You choose your own agent names. Examples in this README use placeholders like `agent-a` and `agent-b`, but those are only sample values. - -Route policy is optional: - -- if `BRIDGE_ALLOWED_ROUTES` is unset, Bridge allows any sender -> recipient pair -- if `BRIDGE_ALLOWED_ROUTES` is set, Bridge only allows the configured pairs -- API auth tokens are discovered from `BRIDGE_TOKEN_` entries, so your deployed agent IDs come from config, not from the codebase - -You do **not** need to edit `bridge_core/models.py` or `bridge_core/policy.py` to adopt your own ecosystem. - -For deeper docs, start with `docs/README.md` and `docs/bridge-v2-reliability.md`. - -## Repository layout - -- `bridge_core/` - core models, policy, auth, repository, and service logic -- `scripts/` - CLI, wrappers, API server, patrol tooling, intake watcher, and token rotation -- `tests/` - pytest coverage for core flows, API, wrappers, patrol, and intake watchers -- `config/bridge_api.example.env` - example config for API tokens and notify hooks -- `deploy/systemd/` - generic systemd templates for self-hosted deployment -- `docs/` - architecture, deployment, and runtime documentation -- `examples/handoffs/` - example markdown payloads for common handoff patterns - -## Quick start - -### 1) Clone the repo - -```bash -git clone https://github.com/camaragon/bridge.git -cd bridge -``` - -### 2) Confirm Python - -Bridge uses the Python standard library at runtime. - -```bash -python3 --version -``` - -Expected: Python 3.10+ - -### 3) Run tests - -```bash -python3 -m pytest -q -``` - -### 4) Create a handoff with the direct CLI - -This is the fastest way to see Bridge working. - -```bash -python3 scripts/bridge_cli.py create \ - --sender agent-a \ - --recipient agent-b \ - --issue-type task \ - --subject "Demo handoff" \ - --requested-action "Inspect the repo and report back" \ - --minimal-context "Started from the README quickstart" \ - --idempotency-key "demo-create-1" -``` - -You should get JSON like: - -```json -{ - "handoff_id": "HND-20260426-000000-abcd", - "outbox": ".../bridge/outgoing/agent-a/HND-...md", - "inbox": ".../bridge/incoming/agent-b/HND-...md" -} -``` - -List open handoffs for the recipient: - -```bash -python3 scripts/bridge_cli.py list-open --agent agent-b -``` - -Mark it closed: - -```bash -python3 scripts/bridge_cli.py set-status --actor agent-b HND-... closed --outcome "Completed and reported back" -``` - -Archive it: - -```bash -python3 scripts/bridge_cli.py archive --actor agent-b HND-... -``` - -## HTTP API quick start - -The wrappers prefer the local API. - -### 1) Create a local config file - -```bash -mkdir -p config -cp config/bridge_api.example.env config/bridge_api.env -mkdir -p bridge/incoming bridge/outgoing bridge/archive bridge/audit -``` - -Edit `config/bridge_api.env` and replace: - -- `BRIDGE_TOKEN_AGENT_A` -- `BRIDGE_TOKEN_AGENT_B` -- `BRIDGE_TOKEN_AGENT_C` - -with real secret values. - -You usually do **not** need to change `BRIDGE_ROOT` or `BRIDGE_API_CONFIG` if you are running from this repo checkout. - -### 2) Start the API server - -```bash -python3 scripts/bridge_api_server.py -``` - -By default it listens on `127.0.0.1:8427`. - -### 3) Check health - -```bash -curl http://127.0.0.1:8427/v1/health -``` - -Expected: - -```json -{"ok": true, "service": "bridge-api"} -``` - -### 4) Use a wrapper - -```bash -python3 scripts/bridge_agent.py --agent agent-a create \ - --recipient agent-b \ - --issue-type task \ - --subject "Wrapper demo" \ - --requested-action "Verify API-backed handoff creation" \ - --minimal-context "Started from the README API quickstart" -``` - -List open handoffs: - -```bash -python3 scripts/bridge_agent.py --agent agent-b list-open -``` - -Acknowledge receipt: - -```bash -python3 scripts/bridge_agent.py --agent agent-b ack HND-... -``` - -Close with a resolution summary: - -```bash -python3 scripts/bridge_agent.py --agent agent-b close HND-... --outcome "Verified and complete" -``` - -## API endpoints - -- `GET /v1/health` -- `POST /v1/handoffs` -- `GET /v1/handoffs` -- `GET /v1/handoffs/{handoff_id}` -- `POST /v1/handoffs/{handoff_id}/ack` -- `POST /v1/handoffs/{handoff_id}/block` -- `POST /v1/handoffs/{handoff_id}/close` -- `POST /v1/handoffs/{handoff_id}/cancel` -- `POST /v1/handoffs/{handoff_id}/status` -- `POST /v1/handoffs/{handoff_id}/archive` - -Create accepts `Idempotency-Key` or `idempotency_key`. Lifecycle writes accept `expected_revision` or an `If-Match` header and return HTTP 409 for stale revisions. - -Durable outbox and reconciliation commands: - -```bash -python3 scripts/bridge_cli.py outbox-list --state pending -python3 scripts/bridge_cli.py outbox-deliver --limit 100 -python3 scripts/bridge_cli.py outbox-replay EVT-... -python3 scripts/bridge_cli.py outbox-recover -python3 scripts/bridge_cli.py outbox-resolve-transaction EVT-... --action enqueue --reason "verified missing delivery" -python3 scripts/bridge_cli.py reconcile --check-only -``` - -## Lifecycle notifications - -Bridge supports two layers of notification behavior: - -1. **recipient notify URLs** - - configured with `BRIDGE_NOTIFY_URL_` - - Bridge POSTs lifecycle events to recipient listeners - -2. **read-only lifecycle event consumers** - - configured with `BRIDGE_NOTIFY_EVENT_COMMAND_` - - `bridge_intake_watch.py` can execute a command for `handoff_closed` and `handoff_blocked` - - the command receives raw JSON on stdin - - this keeps Bridge core separate from Telegram, BlueBubbles, Slack, or other UI-specific adapters - -3. **read-only intake event consumers** - - configured with `BRIDGE_INTAKE_EVENT_COMMAND_` or generic `BRIDGE_INTAKE_EVENT_COMMAND` - - agent-scoped commands take precedence over the generic command; CLI `--intake-event-command` overrides both - - `bridge_intake_watch.py` can execute a command after auto-acknowledging a newly received handoff - - the command receives a generic `handoff_acknowledged` JSON event on stdin - - use this for local work-queue mirroring, indexing, or alerting without baking those systems into Bridge - -Run a recipient listener: - -```bash -python3 scripts/bridge_intake_watch.py --agent agent-b --listen --port 8522 -``` - -Run a one-shot inbox check: - -```bash -python3 scripts/bridge_intake_watch.py --agent agent-b --once -``` - -## Patrol and unresolved handoff detection - -Bridge includes patrol tooling for follow-up pressure without mutating the API surface. - -See `docs/runtime-layout.md` for runtime directory expectations. - -Run patrol manually: - -```bash -python3 scripts/bridge_patrol.py --stuck-hours 24 -``` - -Patrol can: - -- detect unacknowledged open handoffs -- re-hit notify endpoints after a delay -- emit active unresolved alerts for placeholder summaries like `pending` -- deduplicate reminders through `bridge/audit/patrol-reminders.json` - -## Configuration - -Main runtime variables: - -- `BRIDGE_PROJECT_ROOT` -- `BRIDGE_ROOT` -- `BRIDGE_API_CONFIG` -- `BRIDGE_API_HOST` -- `BRIDGE_API_PORT` -- `BRIDGE_TOKEN_AGENT_A` -- `BRIDGE_TOKEN_AGENT_B` -- `BRIDGE_TOKEN_AGENT_C` -- `BRIDGE_NOTIFY_URL_` -- `BRIDGE_NOTIFY_EVENT_COMMAND_` -- `BRIDGE_ALLOWED_ROUTES` - -## Safety boundary - -Bridge is intentionally split like this: - -- **Bridge core** owns handoff state, auditability, and lifecycle events -- **adapters/listeners** decide how to surface those events to humans or agent runtimes - -That keeps the core OSS-friendly and prevents messaging-platform logic from being baked into the handoff engine. - -## Deployment - -Generic systemd templates live in: - -- `deploy/systemd/bridge-api.service` -- `deploy/systemd/bridge-intake-watch@.service` -- `deploy/systemd/example-agent.env` - -These are templates for self-hosted deployments, not host-specific copies. - -## Development - -Run the full test suite: - -```bash -pytest -q -``` - -Compile-check scripts and tests: - -```bash -python3 -m py_compile bridge_core/*.py scripts/*.py tests/*.py -``` - -## License - -Apache-2.0 +Bridge is a small shared-file CLI for requests between agents. Each request has +an author, a recipient, an event history, a status, and someone who owes the next +move. Every kind of agent uses the same commands, including chat-gateway agents +and remote agents connecting over SSH. + +There is no server, token store, reminder patrol, or timer. Python 3.10+ on a +POSIX system is enough; runtime code uses only the standard library. + +## Run it + +Use `bin/bridge` from this checkout, or install the console command in your Python +environment with `python3 -m pip install .`. Development checks use +`python3 -m pip install -e '.[dev]'` and `python3 -m pytest -q`. + +An administrator prepares a shared directory such as `/srv/bridge`, grants the +participating accounts access, and writes `agents.conf` there. See +[the permission model](docs/design.md#permissions) before deploying. This CLI +does not install services, change ACLs, create accounts, or migrate old inboxes. +Keep the data root separate from this repository's `bridge/` Python package. + +```text +# agent Unix-account optional command with arguments +alice svc-a +bob svc-b /srv/bridge-tools/notify-example.sh bob +ops svc-a /srv/bridge-tools/notify-example.sh ops +``` + +Commands are split using shell-style quoting, but run directly without a shell. +Accounts must already exist. Agent ids use lowercase letters, digits, `_` and +`-`, starting with a letter or digit. The configuration and notify executables +are administrator-managed trusted files. + +Set `BRIDGE_ROOT=/srv/bridge`, or pass `--root /srv/bridge`. Options such as +`--root` and `--as` work before or after the subcommand. Each `--as` verifies +that the caller's real uid matches the configured Unix account, including on +read commands. Running as root does not bypass that check. + +## Make and answer a request + +Run the sender's command under `svc-a` and the recipient's commands under +`svc-b` in this example: + +```sh +export BRIDGE_ROOT=/srv/bridge +bridge new --as alice --to bob --subject 'Review artifact' --due 2030-01-15 < request.md +# Prints an id such as 20300110-120000-alice-review-artifact +bridge show 20300110-120000-alice-review-artifact +bridge reply --as bob 20300110-120000-alice-review-artifact --status working < progress.md +bridge reply --as bob 20300110-120000-alice-review-artifact --status blocked < question.md +bridge reply --as alice 20300110-120000-alice-review-artifact < answer.md +bridge close --as bob 20300110-120000-alice-review-artifact < outcome.md +``` + +The recipient alone sets `working` or `blocked` and closes with a nonempty +outcome on stdin. The sender alone cancels: + +```sh +bridge cancel --as alice 20300110-120000-alice-review-artifact < reason.md +``` + +Either participant may reply. A reply without `--status` preserves the status; +answering a blocked request does not automatically resume it. Active requests +can become `working`, `blocked`, `done`, or `cancelled`. Once working or blocked, +they cannot return to `open`. Terminal requests cannot receive further events. + +| Status | Who owes the next move | +| --- | --- | +| `open`, `working` | Recipient | +| `blocked` | Sender, until the sender answers; then recipient | +| `done`, `cancelled` | Nobody | + +The full UTF-8 event, including frontmatter, is limited to 64 KiB. Use LF line +endings; control characters other than LF and tab are refused. For larger +artifacts, put a readable file path in the Markdown body. A path is a reference, +not an attachment upload or an access grant. + +## Find requests and unread events + +```sh +bridge list # All active requests +bridge list --as bob --mine # Active requests involving bob +bridge list --as bob --owed # Active requests bob owes +bridge list --done # All done and cancelled requests +bridge show 20300110-120000-alice-review-artifact --json +bridge unseen --as bob --json +bridge unseen --as bob --mark --json +``` + +`list` includes age and due date. `list`, `show`, and `unseen` support `--json`. +JSON warnings flag events whose file owner does not match the declared author's +account; text output displays those warnings too. Readers with filesystem access +can see all requests, including completed ones. + +`unseen` lists individual events on requests the agent participates in, excluding +its own events. Without `--mark` it changes nothing. `--mark` returns and marks +the same snapshot. Seen keys are `request-id/event-file`, so a move from `open/` +to `done/` never makes a read event unread again. State defaults to +`$XDG_STATE_HOME/bridge/.seen`, or `~/.local/state/bridge/.seen`; +`--state-dir` overrides the directory. Keep that state local to the consumer. +Mark only after your consumer has handled the events; repeated delivery can be +deduplicated using each event's JSON `key`. With concurrent arrivals, process the +snapshot returned by `--mark` as well, rather than discarding its output. + +## Storage and waking agents + +```text +/srv/bridge/ + agents.conf + open/.bell + open/20300110-120000-alice-review-artifact/ + 00-alice.md + 01-bob.md + done//... +``` + +Events are write-once Markdown files. Status and who owes a reply come from the +latest event, or the first terminal event if one exists. Closing or cancelling +writes a terminal event and moves the folder to `done/`. If the process stops +between those actions, `list --done` still finds it by its event status. Sequence allocation uses hidden write-once reservations +inside each request; see [the design](docs/design.md). + +Every write rewrites `open/.bell` in place. The example +[systemd path unit](examples/bridge-wake.path) watches that one file, including +replies in nested request folders. Its paired [service](examples/bridge-wake.service) +checks `unseen` before waking an agent. No timer is needed. + +After each event, the other participant's optional notify command runs as the +writing Unix account. It receives **one line on stdin** containing the request +id, author, subject, and `bridge show ` pointer. `BRIDGE_ROOT` is set in its +environment. The command can wake any runtime through a site-provided adapter; +Bridge does not depend on a chat transport or a particular agent framework. +It runs for at most ten seconds. Failure produces a warning but the saved event +remains available through `list`, `show`, and `unseen`. + +[notify-example.sh](examples/notify-example.sh) shows both direct notifications +and an unseen-based path-unit wake. Customize the adapter and service account +before using the examples. The consumer reads and answers through Bridge; the +notification is only a doorbell. There are no automated reminders. + +See [request](examples/handoffs/request.md) and +[closure](examples/handoffs/closure.md) for the event format. The previous API, +tokens, watchers, patrol, and transaction/outbox design remain in Git history. diff --git a/bin/bridge b/bin/bridge new file mode 100755 index 0000000..fd35eae --- /dev/null +++ b/bin/bridge @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +"""Run from a checkout without installing the package.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from bridge.cli import main + +raise SystemExit(main()) diff --git a/bridge/__init__.py b/bridge/__init__.py new file mode 100644 index 0000000..6764799 --- /dev/null +++ b/bridge/__init__.py @@ -0,0 +1 @@ +"""Small, shared-file requests between agents.""" diff --git a/bridge/cli.py b/bridge/cli.py new file mode 100644 index 0000000..9ff7682 --- /dev/null +++ b/bridge/cli.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +import argparse +import json +import os +from pathlib import Path +import subprocess +import sys + +from .config import load_agents, require_identity +from .frontmatter import dump_document +from .policy import TERMINAL +from .store import create_file, mkdir, Store + + +def parser() -> argparse.ArgumentParser: + common = argparse.ArgumentParser(add_help=False) + for flag, options in ( + ("--root", {"help": "shared root (or BRIDGE_ROOT)"}), + ("--as", {"dest": "actor", "help": "configured agent identity"}), + ("--state-dir", {"help": "seen-list directory (default: XDG_STATE_HOME/bridge)"}), + ("--json", {"action": "store_true", "help": "JSON output for read commands"}), + ): + common.add_argument(flag, default=argparse.SUPPRESS, **options) + result = argparse.ArgumentParser(description="Shared-file requests between agents", parents=[common]) + commands = result.add_subparsers(dest="command", required=True) + for name in ("new", "reply", "close", "cancel", "list", "show", "unseen"): + command = commands.add_parser(name, parents=[common]) + if name == "new": + command.add_argument("--to", required=True) + command.add_argument("--subject", required=True) + command.add_argument("--due", metavar="YYYY-MM-DD") + if name in {"reply", "close", "cancel", "show"}: + command.add_argument("id") + if name == "reply": + command.add_argument("--status", choices=["working", "blocked"]) + if name == "list": + filters = command.add_mutually_exclusive_group() + for flag in ("--mine", "--owed", "--done"): + filters.add_argument(flag, action="store_true") + if name == "unseen": + command.add_argument("--mark", action="store_true", help="mark the returned events seen") + return result + + +def unseen(store: Store, actor: str, state: Path, mark: bool) -> list[dict]: + seen_file = state / f"{actor}.seen" + seen = set(seen_file.read_text(encoding="utf-8").splitlines()) if seen_file.exists() else set() + found = [] + for request in store.requests(): + if actor not in {request["from"], request["to"]}: + continue + for event in request["events"]: + if event["from"] != actor and event["key"] not in seen: + found.append({**event, "subject": request["subject"], "request_status": request["status"]}) + if mark and found: + missing = [] + parent = state + while not parent.exists(): + missing.append(parent) + parent = parent.parent + for directory in reversed(missing): + mkdir(directory) + # Append-only marking avoids losing another invocation's marks. + try: + create_file(seen_file, "") + except FileExistsError: + pass + with seen_file.open("a", encoding="utf-8") as stream: + stream.write("".join(event["key"] + "\n" for event in found)) + return found + + +def notify(store: Store, ident: str, actor: str) -> None: + request = store.load(ident) + target = request["to"] if actor == request["from"] else request["from"] + command = store.agents[target].notify + if not command: + return + pointer = f"bridge {ident} from {actor}: {request['subject']} - run bridge show {ident}\n" + try: + subprocess.run(command, input=pointer, text=True, check=True, timeout=10, + env={**os.environ, "BRIDGE_ROOT": str(store.root)}, + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + except (OSError, subprocess.SubprocessError) as exc: + print(f"warning: event saved; notify {target} failed: {exc}", file=sys.stderr) + + +def summary(request: dict) -> dict: + return {key: value for key, value in request.items() if key != "events"} + + +def main(argv: list[str] | None = None) -> int: + arguments = parser() + args = arguments.parse_args(argv) + root = getattr(args, "root", None) or os.environ.get("BRIDGE_ROOT") + if not root: + arguments.error("set --root or BRIDGE_ROOT") + actor = getattr(args, "actor", None) + try: + store = Store(Path(root).expanduser().resolve(), load_agents(Path(root).expanduser())) + if actor: + require_identity(store.agents, actor) + command = args.command + if command in {"new", "reply", "close", "cancel", "unseen"} and not actor: + raise ValueError(f"{command} requires --as") + if command in {"new", "reply", "close", "cancel"}: + if getattr(args, "json", False): + raise ValueError("--json is available on read commands") + # Decode bytes ourselves to reject CRLF instead of stdin's newline conversion. + body = sys.stdin.buffer.read(64 * 1024 + 1).decode("utf-8") + if command == "new": + ident = store.new(actor, args.to, args.subject, body, args.due) + else: + ident = args.id + status = {"close": "done", "cancel": "cancelled"}.get(command, getattr(args, "status", None)) + store.append(ident, actor, body, status) + notify(store, ident, actor) + print(ident) + return 0 + if command == "show": + result = store.load(args.id) + if getattr(args, "json", False): + print(json.dumps(result)) + else: + print(f"{result['id']} {result['status']} owes={result['owes'] or '-'}") + for event in result["events"]: + print(f"\n# {event['file']}") + for warning in event["warnings"]: + print(f"WARNING: {warning}") + meta = {key: value for key, value in event.items() + if key in {"id", "from", "to", "subject", "status", "due", "at"}} + print(dump_document(meta, event["body"])) + return 0 + if command == "unseen": + default = Path(os.environ.get("XDG_STATE_HOME", str(Path.home() / ".local/state"))) / "bridge" + result = unseen(store, actor, Path(getattr(args, "state_dir", default)).expanduser(), args.mark) + else: + if (args.mine or args.owed) and not actor: + raise ValueError("--mine and --owed require --as") + result = [summary(r) for r in store.requests() + if (r["status"] in TERMINAL) == args.done + and (not args.mine or actor in {r["from"], r["to"]}) + and (not args.owed or r["owes"] == actor)] + if getattr(args, "json", False): + print(json.dumps(result)) + else: + for item in result: + if command == "unseen": + print(f"{item['key']} from={item['from']} {item['subject']}") + else: + print(f"{item['id']} {item['status']} owes={item['owes'] or '-'} " + f"age={item['age_seconds'] // 3600}h due={item['due'] or '-'} {item['subject']}") + for warning in item["warnings"]: + print(f" WARNING: {warning}") + return 0 + except (OSError, ValueError) as exc: + print(f"bridge: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/bridge/config.py b/bridge/config.py new file mode 100644 index 0000000..0a60dfe --- /dev/null +++ b/bridge/config.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from dataclasses import dataclass +import os +from pathlib import Path +import pwd +import re +import shlex + +AGENT_ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9_-]*$") + + +def agent_id(value: str) -> str: + if not AGENT_ID_PATTERN.fullmatch(value): + raise ValueError(f"invalid agent id: {value!r}") + return value + + +@dataclass(frozen=True) +class Agent: + account: str + uid: int + notify: tuple[str, ...] = () + + +def load_agents(root: Path) -> dict[str, Agent]: + agents = {} + for number, line in enumerate((root / "agents.conf").read_text(encoding="utf-8").splitlines(), 1): + fields = shlex.split(line, comments=True) + if not fields: + continue + if len(fields) < 2: + raise ValueError(f"agents.conf:{number}: expected agent account [command ...]") + name, account, *command = fields + agent_id(name) + if name in agents: + raise ValueError(f"agents.conf:{number}: duplicate agent {name}") + try: + uid = pwd.getpwnam(account).pw_uid + except KeyError: + raise ValueError(f"agents.conf:{number}: unknown Unix account {account!r}") from None + agents[name] = Agent(account, uid, tuple(command)) + return agents + + +def require_identity(agents: dict[str, Agent], actor: str) -> None: + if actor not in agents: + raise ValueError(f"unknown agent: {actor}") + if os.getuid() != agents[actor].uid: + raise ValueError(f"--as {actor} requires Unix account {agents[actor].account}") diff --git a/bridge/frontmatter.py b/bridge/frontmatter.py new file mode 100644 index 0000000..4a32fce --- /dev/null +++ b/bridge/frontmatter.py @@ -0,0 +1,38 @@ +"""A small flat frontmatter format, not a YAML implementation.""" +from __future__ import annotations + +from collections.abc import Mapping + +MAX_BYTES = 64 * 1024 + + +def validate_text(text: str) -> str: + if len(text.encode("utf-8")) > MAX_BYTES: + raise ValueError("event exceeds 64 KiB; pass a readable file path instead") + if any((ord(char) < 32 and char not in "\n\t") or 127 <= ord(char) < 160 for char in text): + raise ValueError("text must use LF line endings and contain no control characters") + return text + + +def parse_frontmatter(text: str) -> tuple[dict[str, str], str]: + validate_text(text) + if not text.startswith("---\n") or "\n---\n" not in text[4:]: + raise ValueError("invalid frontmatter block") + header, body = text[4:].split("\n---\n", 1) + data = {} + for line in header.splitlines(): + if ": " not in line: + raise ValueError("expected key: value in frontmatter") + key, value = line.split(": ", 1) + if not key or key in data: + raise ValueError("empty or duplicate frontmatter key") + data[key] = value + return data, body.lstrip("\n") + + +def dump_document(data: Mapping[str, str], body: str) -> str: + for key, value in data.items(): + if any(char in key + value for char in "\r\n"): + raise ValueError("frontmatter values must be single lines") + header = "\n".join(f"{key}: {value}" for key, value in data.items()) + return validate_text(f"---\n{header}\n---\n\n{body}") diff --git a/bridge/policy.py b/bridge/policy.py new file mode 100644 index 0000000..5fae19c --- /dev/null +++ b/bridge/policy.py @@ -0,0 +1,34 @@ +"""Lifecycle rules; a reply without a status preserves the current status.""" + +STATUSES = {"open", "working", "blocked", "done", "cancelled"} +TERMINAL = {"done", "cancelled"} +STATUS_TRANSITIONS = { + "open": {"open", "working", "blocked", "done", "cancelled"}, + "working": {"working", "blocked", "done", "cancelled"}, + "blocked": {"blocked", "working", "done", "cancelled"}, + "done": set(), + "cancelled": set(), +} + + +def require_change(current: str, status: str, actor: str, sender: str, + recipient: str, body: str, *, explicit: bool = True) -> None: + if actor not in {sender, recipient}: + raise ValueError("only sender or recipient may reply") + if status not in STATUS_TRANSITIONS.get(current, set()): + raise ValueError(f"invalid transition: {current} -> {status}") + if status == "cancelled" and actor != sender: + raise ValueError("only the sender may cancel") + if status == "done": + if actor != recipient: + raise ValueError("only the recipient may close") + if not body.strip(): + raise ValueError("closing requires an outcome on stdin") + if explicit and status in {"working", "blocked"} and actor != recipient: + raise ValueError("only the recipient may set working or blocked") + + +def owes(status: str, sender: str, recipient: str, author: str) -> str | None: + if status in TERMINAL: + return None + return sender if status == "blocked" and author != sender else recipient diff --git a/bridge/store.py b/bridge/store.py new file mode 100644 index 0000000..47810d4 --- /dev/null +++ b/bridge/store.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +from datetime import datetime, timezone +import os +from pathlib import Path +import re +import sys + +from .config import Agent, agent_id, require_identity +from .frontmatter import dump_document, parse_frontmatter +from .policy import owes, require_change, STATUSES, TERMINAL + +EVENT_NAME = re.compile(r"^(\d+)-([a-z0-9][a-z0-9_-]*)\.md$") +REQUEST_ID = re.compile(r"^\d{8}-\d{6}-[a-z0-9][a-z0-9_-]*$") + + +class Missing(ValueError): + pass + + +def now() -> str: + return datetime.now(timezone.utc).isoformat(timespec="seconds") + + +def mkdir(path: Path) -> None: + try: + path.mkdir(mode=0o770) + except FileExistsError: + if not path.is_dir(): + raise + else: + path.chmod(0o770) + + +def create_file(path: Path, text: str, mode: int = 0o640) -> None: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode) + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream: + os.fchmod(stream.fileno(), mode) + stream.write(text) + stream.flush() + os.fsync(stream.fileno()) + + +class Store: + def __init__(self, root: Path, agents: dict[str, Agent]): + self.root, self.agents = root, agents + + def locate(self, ident: str) -> Path: + if not REQUEST_ID.fullmatch(ident): + raise ValueError("invalid request id") + for area in ("open", "done"): + path = self.root / area / ident + if path.is_dir(): + return path + raise Missing(f"request not found: {ident}") + + def load(self, ident: str) -> dict: + try: + names = list(self.locate(ident).iterdir()) + except FileNotFoundError: + names = list(self.locate(ident).iterdir()) + paths = sorted((p for p in names if EVENT_NAME.fullmatch(p.name)), + key=lambda p: (int(p.name.split("-", 1)[0]), p.name)) + if not paths: + raise Missing(f"request has no events: {ident}") + events = [] + for path in paths: + # A close can move the whole directory during this read. + try: + text = path.read_bytes().decode("utf-8") + uid = path.stat().st_uid + except FileNotFoundError: + path = self.locate(ident) / path.name + text = path.read_bytes().decode("utf-8") + uid = path.stat().st_uid + meta, body = parse_frontmatter(text) + if meta.get("id") != ident or meta.get("status") not in STATUSES: + raise ValueError(f"invalid event: {ident}/{path.name}") + author = meta.get("from", "") + warnings = [] + if author not in self.agents or uid != self.agents[author].uid: + warnings.append("file owner does not match declared author's account") + if EVENT_NAME.fullmatch(path.name).group(2) != author: + warnings.append("filename author does not match frontmatter") + events.append({**meta, "body": body, "file": path.name, + "key": f"{ident}/{path.name}", "owner_uid": uid, "warnings": warnings}) + first = events[0] + last = next((e for e in events if e["status"] in TERMINAL), events[-1]) + for event in events[events.index(last) + 1:]: + event["warnings"].append("published after the request ended; ignored for status") + if any(not first.get(key) for key in ("from", "to", "subject", "at")): + raise ValueError(f"incomplete request header: {ident}") + created = datetime.fromisoformat(first["at"]) + age = max(0, int((datetime.now(timezone.utc) - created).total_seconds())) + return {"id": ident, "from": first["from"], "to": first["to"], + "subject": first["subject"], "due": first.get("due"), "at": first["at"], + "age_seconds": age, "status": last["status"], + "owes": owes(last["status"], first["from"], first["to"], last["from"]), + "events": events, "warnings": [f"{e['file']}: {w}" for e in events for w in e["warnings"]]} + + def requests(self) -> list[dict]: + ids = set() + for area in ("open", "done"): + parent = self.root / area + if parent.exists(): + ids.update(p.name for p in parent.iterdir() if p.is_dir() and REQUEST_ID.fullmatch(p.name)) + loaded = [] + for ident in sorted(ids): + try: + loaded.append(self.load(ident)) + except Missing: + pass + return loaded + + def ring(self, ident: str) -> None: + path = self.root / "open" / ".bell" + try: + try: + create_file(path, ident + "\n", 0o660) + except FileExistsError: + # Never replace the inode: a path watcher and shared ACL depend on it. + with path.open("w", encoding="utf-8") as stream: + stream.write(ident + "\n") + except OSError as exc: + print(f"warning: event saved; .bell failed: {exc}", file=sys.stderr) + + def publish(self, folder: Path, meta: dict[str, str], body: str) -> str: + text = dump_document(meta, body) + sequence = max((int(p.name.split("-", 1)[0]) for p in folder.iterdir() + if EVENT_NAME.fullmatch(p.name)), default=-1) + 1 + # A common sequence name coordinates different authors too. Reservations + # are permanent write-once event inodes, not locks needing stale recovery. + while True: + claim = folder / f".{sequence:02d}" + try: + create_file(claim, text) + break + except FileExistsError: + sequence += 1 + # Publish only complete text; readers never see partially written headers. + name = f"{sequence:02d}-{meta['from']}.md" + os.link(claim, folder / name) + self.ring(meta["id"]) + return name + + def new(self, actor: str, recipient: str, subject: str, body: str, + due: str | None = None) -> str: + require_identity(self.agents, actor) + agent_id(recipient) + if recipient not in self.agents or recipient == actor: + raise ValueError("recipient must be a different configured agent") + if not subject.strip(): + raise ValueError("subject is required") + if due: + datetime.strptime(due, "%Y-%m-%d") + slug = re.sub(r"[^a-z0-9]+", "-", subject.lower()).strip("-")[:48] or "request" + base = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + f"-{actor}-{slug}" + # Validate before creating any request directory. + meta = {"id": base, "from": actor, "to": recipient, "subject": subject, + "status": "open", "at": now()} + if due: + meta["due"] = due + dump_document(meta, body) + for area in ("open", "done"): + mkdir(self.root / area) + suffix = 0 + while True: + ident = base + (f"-{suffix}" if suffix else "") + folder = self.root / "open" / ident + if (self.root / "done" / ident).exists(): + suffix += 1 + continue + try: + folder.mkdir(mode=0o770) + folder.chmod(0o770) + break + except FileExistsError: + suffix += 1 + meta["id"] = ident + self.publish(folder, meta, body) + return ident + + def append(self, ident: str, actor: str, body: str, status: str | None = None) -> None: + require_identity(self.agents, actor) + request = self.load(ident) + new_status = status or request["status"] + require_change(request["status"], new_status, actor, request["from"], + request["to"], body, explicit=status is not None) + folder = self.locate(ident) + name = self.publish(folder, {"id": ident, "from": actor, "status": new_status, "at": now()}, body) + events = self.load(ident)["events"] + files = [e["file"] for e in events] + ended = next((e["file"] for e in events if e["status"] in TERMINAL), name) + if files.index(ended) < files.index(name): + print(f"warning: event saved; request already ended by {ended}, so it was ignored for status", + file=sys.stderr) + return + if new_status in TERMINAL and folder.parent.name == "open": + try: + folder.rename(self.root / "done" / ident) + except OSError as exc: + # The terminal event is authoritative even if archiving is interrupted. + print(f"warning: event saved; move to done failed: {exc}", file=sys.stderr) diff --git a/bridge_core/__init__.py b/bridge_core/__init__.py deleted file mode 100644 index a59aa98..0000000 --- a/bridge_core/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -from .auth import AuthenticationError, load_agent_tokens, require_agent_token, resolve_agent_from_token -from .file_repository import FileBridgeRepository -from .models import CreateHandoffInput, HandoffRecord -from .service import BridgeService - -__all__ = [ - "AuthenticationError", - "BridgeService", - "CreateHandoffInput", - "FileBridgeRepository", - "HandoffRecord", - "load_agent_tokens", - "require_agent_token", - "resolve_agent_from_token", -] diff --git a/bridge_core/auth.py b/bridge_core/auth.py deleted file mode 100644 index 35835f1..0000000 --- a/bridge_core/auth.py +++ /dev/null @@ -1,69 +0,0 @@ -from __future__ import annotations - -from pathlib import Path -import hmac -import os - -from .runtime import normalize_agent_env_suffix, normalize_agent_id - -ENV_PREFIX = "BRIDGE_TOKEN_" - - -class AuthenticationError(ValueError): - pass - - -def _read_config_tokens(config_path: Path | str | None) -> dict[str, str]: - if config_path is None: - return {} - path = Path(config_path) - if not path.exists(): - return {} - tokens: dict[str, str] = {} - for raw_line in path.read_text(encoding="utf-8").splitlines(): - line = raw_line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, value = line.split("=", 1) - key = key.strip() - value = value.strip() - if key.startswith(ENV_PREFIX): - agent = normalize_agent_env_suffix(key[len(ENV_PREFIX) :]) - if value: - tokens[agent] = value - return tokens - - -def load_agent_tokens(config_path: Path | str | None = None) -> dict[str, str]: - tokens = _read_config_tokens(config_path) - for env_key, env_value in os.environ.items(): - if not env_key.startswith(ENV_PREFIX) or not env_value: - continue - agent = normalize_agent_env_suffix(env_key[len(ENV_PREFIX) :]) - tokens[agent] = env_value - return tokens - - -def resolve_agent_from_token(presented_token: str, config_path: Path | str | None = None) -> str: - if not presented_token: - raise AuthenticationError("missing bridge token") - matches = [ - agent - for agent, expected in load_agent_tokens(config_path).items() - if expected and hmac.compare_digest(expected, presented_token) - ] - if not matches: - raise AuthenticationError("invalid bridge token") - if len(matches) > 1: - raise AuthenticationError("bridge token matches multiple agents") - return matches[0] - - -def require_agent_token(agent: str, presented_token: str, config_path: Path | str | None = None) -> None: - normalized_agent = normalize_agent_id(agent) - tokens = load_agent_tokens(config_path) - expected = tokens.get(normalized_agent) - if not expected: - raise AuthenticationError(f"no configured token for agent: {agent}") - if not hmac.compare_digest(expected, presented_token): - raise AuthenticationError(f"invalid token for agent: {agent}") diff --git a/bridge_core/events.py b/bridge_core/events.py deleted file mode 100644 index 0a375bb..0000000 --- a/bridge_core/events.py +++ /dev/null @@ -1,75 +0,0 @@ -from __future__ import annotations - -from dataclasses import asdict, dataclass, field -from datetime import datetime, timezone -from typing import Any -from uuid import uuid4 - -from .models import CURRENT_SCHEMA_VERSION, HandoffRecord, now_iso - -DELIVERY_STATES = {"pending", "retrying", "delivered", "dead_letter"} - - -@dataclass(slots=True) -class LifecycleEvent: - event_id: str - handoff_id: str - event_type: str - revision: int - occurred_at: str - target_agent: str - sender: str - recipient: str - actor: str - status: str - subject: str - resolution_summary: str - correlation_id: str | None = None - causation_id: str | None = None - schema_version: int = CURRENT_SCHEMA_VERSION - attempts: int = 0 - next_attempt_at: str = field(default_factory=now_iso) - last_error: str = "" - delivery_state: str = "pending" - external_correlation: dict[str, str] = field(default_factory=dict) - - @classmethod - def from_handoff( - cls, - handoff: HandoffRecord, - *, - event_type: str, - actor: str, - target_agent: str, - event_id: str | None = None, - ) -> "LifecycleEvent": - return cls( - event_id=event_id or f"EVT-{uuid4().hex}", - handoff_id=handoff.handoff_id, - event_type=event_type, - revision=handoff.revision, - occurred_at=now_iso(), - target_agent=target_agent, - sender=handoff.sender, - recipient=handoff.recipient, - actor=actor, - status=handoff.status, - subject=handoff.subject, - resolution_summary=handoff.resolution_summary, - correlation_id=handoff.correlation_id, - causation_id=handoff.causation_id, - ) - - @classmethod - def from_mapping(cls, mapping: dict[str, Any]) -> "LifecycleEvent": - allowed = {field_name for field_name in cls.__dataclass_fields__} - values = {key: value for key, value in mapping.items() if key in allowed} - return cls(**values) - - def to_dict(self) -> dict[str, Any]: - return asdict(self) - - def due(self, now: datetime | None = None) -> bool: - current = now or datetime.now(timezone.utc) - due_at = datetime.fromisoformat(self.next_attempt_at.replace("Z", "+00:00")) - return self.delivery_state in {"pending", "retrying"} and due_at <= current \ No newline at end of file diff --git a/bridge_core/file_repository.py b/bridge_core/file_repository.py deleted file mode 100644 index 7192837..0000000 --- a/bridge_core/file_repository.py +++ /dev/null @@ -1,575 +0,0 @@ -from __future__ import annotations - -from contextlib import contextmanager -from pathlib import Path -from typing import Callable, Iterator -import fcntl -import hashlib -import json -import os -import re -import tempfile -import threading - -from .events import LifecycleEvent -from .frontmatter import dump_document, parse_frontmatter -from .models import CURRENT_SCHEMA_VERSION, HandoffRecord, StoredHandoff, now_iso -from .repository import ( - BridgeRepository, - HandoffNotFoundError, - IdempotencyConflictError, - RepositoryConflictError, -) - - -class FileBridgeRepository(BridgeRepository): - """Crash-safe canonical records with backward-compatible queue views.""" - - def __init__( - self, - bridge_root: Path | str, - *, - fault_injector: Callable[[str], None] | None = None, - initialize: bool = True, - ): - self.bridge_root = Path(bridge_root) - self.audit_file = self.bridge_root / "audit" / "handoff-log.md" - self.records_root = self.bridge_root / "records" - self.locks_root = self.bridge_root / ".locks" - self.idempotency_root = self.bridge_root / "idempotency" - self.events_root = self.bridge_root / "outbox" / "events" - self.transactions_root = self.bridge_root / "transactions" - self.resolved_transactions_root = self.bridge_root / "audit" / "resolved-transactions" - self.conflicts_root = self.bridge_root / "audit" / "conflicts" - self._fault_injector = fault_injector - self._thread_locks: dict[str, threading.RLock] = {} - self._thread_locks_guard = threading.Lock() - self._local = threading.local() - if initialize: - self._ensure_layout() - - def _ensure_layout(self) -> None: - for kind in ("incoming", "outgoing"): - (self.bridge_root / kind).mkdir(parents=True, exist_ok=True) - for path in ( - self.bridge_root / "archive", - self.audit_file.parent, - self.records_root, - self.locks_root, - self.idempotency_root, - self.events_root, - self.transactions_root, - self.resolved_transactions_root, - self.conflicts_root, - ): - path.mkdir(parents=True, exist_ok=True) - path.chmod(0o700) - if not self.audit_file.exists(): - self._atomic_write_bytes(self.audit_file, b"") - - def _queue_path(self, kind: str, agent: str, handoff_id: str) -> Path: - return self.bridge_root / kind / agent / f"{handoff_id}.md" - - def _canonical_path(self, handoff_id: str) -> Path: - return self.records_root / f"{handoff_id}.md" - - def _record_bytes(self, handoff: HandoffRecord) -> bytes: - return dump_document(handoff.to_frontmatter(), handoff.body).encode("utf-8") - - def _fsync_dir(self, path: Path) -> None: - descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)) - try: - os.fsync(descriptor) - finally: - os.close(descriptor) - - def _atomic_write_bytes(self, path: Path, content: bytes, *, mode: int = 0o600) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.parent.chmod(0o700) - descriptor, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) - temp_path = Path(temp_name) - try: - os.fchmod(descriptor, mode) - with os.fdopen(descriptor, "wb") as handle: - handle.write(content) - handle.flush() - os.fsync(handle.fileno()) - os.replace(temp_path, path) - path.chmod(mode) - self._fsync_dir(path.parent) - except BaseException: - try: - os.close(descriptor) - except OSError: - pass - temp_path.unlink(missing_ok=True) - raise - - def _atomic_write_json(self, path: Path, payload: dict[str, object]) -> None: - self._atomic_write_bytes(path, (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8")) - - def _write_record(self, path: Path, handoff: HandoffRecord) -> None: - self._atomic_write_bytes(path, self._record_bytes(handoff)) - - def _fault(self, stage: str) -> None: - if self._fault_injector is not None: - self._fault_injector(stage) - - def _lock_for(self, key: str) -> threading.RLock: - with self._thread_locks_guard: - return self._thread_locks.setdefault(key, threading.RLock()) - - @contextmanager - def _file_lock(self, key: str) -> Iterator[None]: - safe_key = hashlib.sha256(key.encode("utf-8")).hexdigest() - thread_lock = self._lock_for(safe_key) - with thread_lock: - depths = getattr(self._local, "depths", {}) - depth = depths.get(safe_key, 0) - depths[safe_key] = depth + 1 - self._local.depths = depths - lock_handle = None - try: - if depth == 0: - if self.locks_root.exists(): - lock_path = self.locks_root / f"{safe_key}.lock" - lock_handle = lock_path.open("a+b") - lock_path.chmod(0o600) - fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX) - yield - finally: - depths[safe_key] -= 1 - if depths[safe_key] == 0: - depths.pop(safe_key, None) - if lock_handle is not None: - fcntl.flock(lock_handle.fileno(), fcntl.LOCK_UN) - lock_handle.close() - - def handoff_lock(self, handoff_id: str): - return self._file_lock(f"handoff:{handoff_id}") - - def _idempotency_index_path(self, sender: str, key_hash: str) -> Path: - return self.idempotency_root / sender / f"{key_hash}.json" - - def _write_idempotency_index(self, handoff: HandoffRecord, key_hash: str) -> None: - self._atomic_write_json( - self._idempotency_index_path(handoff.sender, key_hash), - { - "schema_version": CURRENT_SCHEMA_VERSION, - "sender": handoff.sender, - "idempotency_key_hash": key_hash, - "request_hash": handoff.canonical_request_hash, - "handoff_id": handoff.handoff_id, - "created_at": handoff.created_at, - }, - ) - - def _recover_idempotency_index( - self, - *, - sender: str, - key_hash: str, - request_hash: str, - ) -> HandoffRecord | None: - matches: list[HandoffRecord] = [] - for path in sorted(self.records_root.glob("*.md")): - if key_hash not in path.read_text(encoding="utf-8", errors="replace"): - continue - record = self._load_path(path).record - if record.sender == sender and record.idempotency_key_hash == key_hash: - matches.append(record) - if len(matches) > 1: - raise RepositoryConflictError( - f"multiple canonical handoffs claim idempotency key for {sender}: {key_hash}" - ) - if not matches: - return None - recovered = matches[0] - if recovered.canonical_request_hash != request_hash: - raise IdempotencyConflictError( - f"idempotency key already used by {sender} with a different request payload" - ) - self._write_idempotency_index(recovered, key_hash) - self.reconcile_handoff(recovered.handoff_id, repair=True) - return self.load_records(recovered.handoff_id)[0].record - - def create(self, handoff: HandoffRecord, *, idempotency_key: str | None = None) -> HandoffRecord: - key_hash = hashlib.sha256(idempotency_key.encode("utf-8")).hexdigest() if idempotency_key else "" - create_lock = f"idempotency:{handoff.sender}:{key_hash}" if key_hash else f"create:{handoff.handoff_id}" - with self._file_lock(create_lock): - if key_hash: - index_path = self._idempotency_index_path(handoff.sender, key_hash) - if index_path.exists(): - index = json.loads(index_path.read_text(encoding="utf-8")) - if index.get("request_hash") != handoff.canonical_request_hash: - raise IdempotencyConflictError( - f"idempotency key already used by {handoff.sender} with a different request payload" - ) - original_id = str(index["handoff_id"]) - self.reconcile_handoff(original_id) - return self.load_records(original_id)[0].record - recovered = self._recover_idempotency_index( - sender=handoff.sender, - key_hash=key_hash, - request_hash=handoff.canonical_request_hash, - ) - if recovered is not None: - return recovered - handoff.idempotency_key_hash = key_hash - - with self.handoff_lock(handoff.handoff_id): - canonical = self._canonical_path(handoff.handoff_id) - if canonical.exists(): - raise RepositoryConflictError(f"handoff already exists: {handoff.handoff_id}") - self._write_record(canonical, handoff) - if key_hash: - self._write_idempotency_index(handoff, key_hash) - outgoing = self._queue_path("outgoing", handoff.sender, handoff.handoff_id) - incoming = self._queue_path("incoming", handoff.recipient, handoff.handoff_id) - self._write_record(outgoing, handoff) - self._fault("after_outgoing_write") - self._write_record(incoming, handoff) - self._fault("after_incoming_write") - self.append_audit(handoff, handoff.status) - return handoff - - def _load_path(self, path: Path) -> StoredHandoff: - data, body = parse_frontmatter(path.read_text(encoding="utf-8", errors="replace")) - return StoredHandoff(path=path, record=HandoffRecord.from_mapping(data, body)) - - def load_records(self, handoff_id: str) -> list[StoredHandoff]: - canonical = self._canonical_path(handoff_id) - matches: list[Path] = [] - if canonical.exists(): - matches.append(canonical) - queue_matches = sorted(self.bridge_root.glob(f"incoming/*/{handoff_id}.md")) - queue_matches += sorted(self.bridge_root.glob(f"outgoing/*/{handoff_id}.md")) - archive_matches = sorted((self.bridge_root / "archive" / handoff_id).glob("*.md")) - matches.extend(queue_matches) - matches.extend(archive_matches) - if not matches: - raise HandoffNotFoundError("handoff not found") - return [self._load_path(path) for path in matches] - - def list_incoming(self, agent: str) -> list[HandoffRecord]: - return [self._load_path(path).record for path in sorted((self.bridge_root / "incoming" / agent).glob("*.md"))] - - def save_records(self, records: list[StoredHandoff]) -> None: - if not records: - return - handoff_id = records[0].record.handoff_id - with self.handoff_lock(handoff_id): - canonical_record = next( - (item.record for item in records if item.path == self._canonical_path(handoff_id)), - records[0].record, - ) - canonical_record.schema_version = CURRENT_SCHEMA_VERSION - self._write_record(self._canonical_path(handoff_id), canonical_record) - for stored in records: - if stored.path == self._canonical_path(handoff_id) or "archive" in stored.path.parts: - continue - stored.record.schema_version = CURRENT_SCHEMA_VERSION - self._write_record(stored.path, stored.record) - - def archive_records(self, records: list[StoredHandoff]) -> Path: - handoff_id = records[0].record.handoff_id - with self.handoff_lock(handoff_id): - archive_dir = self.bridge_root / "archive" / handoff_id - archive_dir.mkdir(parents=True, exist_ok=True) - archive_dir.chmod(0o700) - canonical_record = next( - (item.record for item in records if item.path == self._canonical_path(handoff_id)), - records[0].record, - ) - canonical_path = archive_dir / f"{handoff_id}.md" - canonical_bytes = self._record_bytes(canonical_record) - self._atomic_write_bytes(canonical_path, canonical_bytes) - for stored in records: - path = stored.path - if path == self._canonical_path(handoff_id) or "archive" in path.parts: - continue - record_bytes = self._record_bytes(stored.record) - if record_bytes != canonical_bytes: - queue_label = path.parent.parent.name - suffix = stored.record.sender if queue_label == "outgoing" else stored.record.recipient - alternate = archive_dir / f"{handoff_id}.{queue_label}.{suffix}.md" - self._atomic_write_bytes(alternate, record_bytes) - path.unlink(missing_ok=True) - self._fsync_dir(path.parent) - self._canonical_path(handoff_id).unlink(missing_ok=True) - self._fsync_dir(self.records_root) - return archive_dir - - def append_audit(self, handoff: HandoffRecord, status: str) -> None: - metadata = "" - if status == "acknowledged" and handoff.acknowledged_at != "none": - metadata = f" | ack_source={handoff.acknowledgment_source} acknowledged_at={handoff.acknowledged_at}" - metadata += f" | schema={handoff.schema_version} revision={handoff.revision}" - line = ( - f"- {now_iso()} | {handoff.handoff_id} | {handoff.sender} -> {handoff.recipient} | " - f"{status} | {handoff.subject}{metadata}\n" - ).encode("utf-8") - with self._file_lock("audit"): - descriptor = os.open(self.audit_file, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) - try: - os.write(descriptor, line) - os.fsync(descriptor) - finally: - os.close(descriptor) - - def append_diagnostic_audit(self, handoff_id: str, event: str, detail: str) -> None: - line = f"- {now_iso()} | {handoff_id} | system | {event} | {detail}\n".encode("utf-8") - with self._file_lock("audit"): - descriptor = os.open(self.audit_file, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) - try: - os.write(descriptor, line) - os.fsync(descriptor) - finally: - os.close(descriptor) - - @staticmethod - def _safe_event_id(event_id: str) -> str: - if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,199}", event_id) is None: - raise ValueError("invalid event_id") - return event_id - - def _event_path(self, event_id: str) -> Path: - return self.events_root / f"{self._safe_event_id(event_id)}.json" - - def _transaction_path(self, event_id: str) -> Path: - return self.transactions_root / f"{self._safe_event_id(event_id)}.json" - - def _resolved_transaction_path(self, event_id: str) -> Path: - return self.resolved_transactions_root / f"{self._safe_event_id(event_id)}.json" - - def prepare_event(self, event: LifecycleEvent) -> None: - payload = {"phase": "prepared", "event": event.to_dict(), "prepared_at": now_iso()} - self._atomic_write_json(self._transaction_path(event.event_id), payload) - - def complete_event(self, event_id: str) -> None: - path = self._transaction_path(event_id) - path.unlink(missing_ok=True) - self._fsync_dir(self.transactions_root) - - def enqueue_event(self, event: LifecycleEvent) -> LifecycleEvent: - with self._file_lock(f"event:{event.event_id}"): - path = self._event_path(event.event_id) - if path.exists(): - return LifecycleEvent.from_mapping(json.loads(path.read_text(encoding="utf-8"))) - self._atomic_write_json(path, event.to_dict()) - return event - - def list_events(self, *, states: set[str] | None = None) -> list[LifecycleEvent]: - events = [] - for path in sorted(self.events_root.glob("*.json")): - event = LifecycleEvent.from_mapping(json.loads(path.read_text(encoding="utf-8"))) - if states is None or event.delivery_state in states: - events.append(event) - return events - - def update_event(self, event: LifecycleEvent) -> LifecycleEvent: - with self._file_lock(f"event:{event.event_id}"): - path = self._event_path(event.event_id) - if path.exists(): - current = LifecycleEvent.from_mapping(json.loads(path.read_text(encoding="utf-8"))) - if current.delivery_state == "delivered" and event.delivery_state != "delivered": - return current - if current.delivery_state == "dead_letter" and event.delivery_state in {"pending", "retrying"}: - return current - self._atomic_write_json(path, event.to_dict()) - return event - - def replay_event(self, event_id: str) -> LifecycleEvent: - with self._file_lock(f"event:{event_id}"): - path = self._event_path(event_id) - if not path.exists(): - raise HandoffNotFoundError(f"event not found: {event_id}") - event = LifecycleEvent.from_mapping(json.loads(path.read_text(encoding="utf-8"))) - event.delivery_state = "pending" - event.attempts = 0 - event.next_attempt_at = now_iso() - event.last_error = "" - self._atomic_write_json(path, event.to_dict()) - return event - - def recover_transactions(self) -> list[str]: - recovered: list[str] = [] - for path in sorted(self.transactions_root.glob("*.json")): - payload = json.loads(path.read_text(encoding="utf-8")) - event = LifecycleEvent.from_mapping(dict(payload["event"])) - if event.event_id != path.stem: - raise RepositoryConflictError( - f"prepared transaction event_id mismatch: path={path.stem} payload={event.event_id}" - ) - try: - record = self.load_records(event.handoff_id)[0].record - except HandoffNotFoundError: - continue - if record.revision != event.revision or record.status != event.status: - continue - self.enqueue_event(event) - self.complete_event(event.event_id) - recovered.append(event.event_id) - return recovered - - def resolve_transaction( - self, - event_id: str, - *, - action: str, - reason: str, - force_recoverable_discard: bool = False, - ) -> LifecycleEvent: - normalized_action = action.strip().lower() - if normalized_action not in {"enqueue", "discard"}: - raise ValueError("transaction action must be enqueue or discard") - if force_recoverable_discard and normalized_action != "discard": - raise ValueError("force_recoverable_discard is valid only for discard") - normalized_reason = reason.strip() - if not normalized_reason: - raise ValueError("transaction resolution requires a reason") - with self._file_lock(f"event:{event_id}"): - path = self._transaction_path(event_id) - if not path.exists(): - raise HandoffNotFoundError(f"prepared transaction not found: {event_id}") - payload = json.loads(path.read_text(encoding="utf-8")) - event = LifecycleEvent.from_mapping(dict(payload["event"])) - if event.event_id != event_id: - raise RepositoryConflictError( - f"prepared transaction event_id mismatch: path={event_id} payload={event.event_id}" - ) - canonical_revision: int | None = None - canonical_status: str | None = None - try: - canonical = self.load_records(event.handoff_id)[0].record - canonical_revision = canonical.revision - canonical_status = canonical.status - except HandoffNotFoundError: - pass - canonical_match = canonical_revision == event.revision and canonical_status == event.status - if normalized_action == "discard" and canonical_match and not force_recoverable_discard: - raise ValueError( - "prepared transaction is still recoverable; enqueue it or explicitly force recoverable discard" - ) - if normalized_action == "enqueue": - self.enqueue_event(event) - self._atomic_write_json( - self._resolved_transaction_path(event_id), - { - "schema_version": CURRENT_SCHEMA_VERSION, - "event": event.to_dict(), - "action": normalized_action, - "reason": normalized_reason[:1000], - "resolved_at": now_iso(), - "canonical_revision": canonical_revision, - "canonical_status": canonical_status, - "canonical_match": canonical_match, - "force_recoverable_discard": bool(force_recoverable_discard), - }, - ) - self.complete_event(event_id) - audit_reason = normalized_reason[:500].replace("\r", " ").replace("\n", " ") - self.append_diagnostic_audit( - event.handoff_id, - "transaction_resolved", - f"event_id={event_id} action={normalized_action} reason={audit_reason}", - ) - return event - - def _preserve_conflict(self, path: Path, *, reason: str) -> Path: - digest = hashlib.sha256(path.read_bytes()).hexdigest()[:12] - destination = self.conflicts_root / f"{path.stem}.{digest}.{path.parent.parent.name}.md" - if not destination.exists(): - self._atomic_write_bytes(destination, path.read_bytes()) - self.append_diagnostic_audit(path.stem, "mirror_conflict", f"{reason}; evidence={destination}") - return destination - - def reconcile_handoff(self, handoff_id: str, *, repair: bool = True) -> list[str]: - issues: list[str] = [] - with self.handoff_lock(handoff_id): - records = self.load_records(handoff_id) - canonical_path = self._canonical_path(handoff_id) - canonical = next((item for item in records if item.path == canonical_path), None) - queue_records = [item for item in records if "incoming" in item.path.parts or "outgoing" in item.path.parts] - legacy_without_canonical = canonical is None - if canonical is None: - if not queue_records: - return [f"{handoff_id}: missing canonical record"] - byte_variants = {item.path.read_bytes() for item in queue_records} - if len(byte_variants) > 1: - if repair: - for item in queue_records: - self._preserve_conflict(item.path, reason="no canonical record and divergent queue copies") - return [f"{handoff_id}: ambiguous divergent v1 queue copies"] - canonical = queue_records[0] - if repair: - issues.append(f"{handoff_id}: missing canonical record") - canonical.record.schema_version = CURRENT_SCHEMA_VERSION - self._write_record(canonical_path, canonical.record) - - expected = self._record_bytes(canonical.record) - expected_paths = [ - self._queue_path("outgoing", canonical.record.sender, handoff_id), - self._queue_path("incoming", canonical.record.recipient, handoff_id), - ] - for path in expected_paths: - if not path.exists(): - issues.append(f"{handoff_id}: missing mirror {path.relative_to(self.bridge_root)}") - if repair: - self._atomic_write_bytes(path, expected) - continue - if legacy_without_canonical: - if repair: - self._atomic_write_bytes(path, expected) - continue - item = self._load_path(path) - if item.record.revision != canonical.record.revision: - issues.append( - f"{handoff_id}: stale revision {path.relative_to(self.bridge_root)}=" - f"{item.record.revision} canonical={canonical.record.revision}" - ) - if repair: - self._preserve_conflict(path, reason="stale mirror revision") - self._atomic_write_bytes(path, expected) - elif path.read_bytes() != expected: - issues.append(f"{handoff_id}: divergent mirror {path.relative_to(self.bridge_root)}") - if repair: - self._preserve_conflict(path, reason="divergent mirror content") - self._atomic_write_bytes(path, expected) - if issues and repair: - self.append_diagnostic_audit(handoff_id, "reconciled", "; ".join(issues)) - return issues - - def diagnose(self, *, pending_age_seconds: float = 300.0) -> list[str]: - issues: list[str] = [] - ids = {path.stem for path in self.records_root.glob("*.md")} - ids.update(path.stem for path in self.bridge_root.glob("incoming/*/*.md")) - ids.update(path.stem for path in self.bridge_root.glob("outgoing/*/*.md")) - for handoff_id in sorted(ids): - issues.extend(self.reconcile_handoff(handoff_id, repair=False)) - now = __import__("time").time() - for event in self.list_events(): - path = self._event_path(event.event_id) - if event.delivery_state in {"pending", "retrying"} and now - path.stat().st_mtime > pending_age_seconds: - issues.append(f"{event.event_id}: pending outbox event beyond threshold") - if event.delivery_state == "dead_letter": - issues.append(f"{event.event_id}: dead-letter event") - for path in sorted(self.idempotency_root.glob("*/*.json")): - try: - index = json.loads(path.read_text(encoding="utf-8")) - record = self.load_records(str(index["handoff_id"]))[0].record - if record.sender != index.get("sender") or record.canonical_request_hash != index.get("request_hash"): - issues.append(f"{path.relative_to(self.bridge_root)}: idempotency index inconsistency") - except (OSError, ValueError, KeyError, HandoffNotFoundError, json.JSONDecodeError): - issues.append(f"{path.relative_to(self.bridge_root)}: idempotency index inconsistency") - for path in sorted(self.transactions_root.glob("*.json")): - try: - payload = json.loads(path.read_text(encoding="utf-8")) - event = LifecycleEvent.from_mapping(dict(payload["event"])) - if event.event_id != path.stem: - issues.append(f"{path.stem}: prepared transaction event_id mismatch") - else: - issues.append(f"{path.stem}: incomplete event transaction") - except (OSError, ValueError, KeyError, TypeError, json.JSONDecodeError): - issues.append(f"{path.stem}: malformed event transaction") - return issues \ No newline at end of file diff --git a/bridge_core/frontmatter.py b/bridge_core/frontmatter.py deleted file mode 100644 index f0c5afd..0000000 --- a/bridge_core/frontmatter.py +++ /dev/null @@ -1,62 +0,0 @@ -from __future__ import annotations - -from collections.abc import Mapping - - -class FrontmatterError(ValueError): - pass - - -def _sanitize_scalar(value: object) -> str: - return str(value).replace("\r", " ").replace("\n", " ") - - -def parse_frontmatter(text: str) -> tuple[dict[str, object], str]: - normalized = text.replace("\r\n", "\n") - if not normalized.startswith("---\n"): - return {}, normalized - parts = normalized.split("\n---\n", 1) - if len(parts) != 2: - raise FrontmatterError("invalid frontmatter block") - raw, body = parts - lines = raw.splitlines()[1:] - data: dict[str, object] = {} - index = 0 - while index < len(lines): - line = lines[index] - if not line.strip(): - index += 1 - continue - if line.endswith(":") and ": " not in line: - key = line[:-1] - values: list[str] = [] - index += 1 - while index < len(lines) and lines[index].startswith(" - "): - values.append(lines[index][4:]) - index += 1 - data[key] = values - continue - if ": " not in line: - index += 1 - continue - key, value = line.split(": ", 1) - data[key] = value - index += 1 - return data, body - - -def render_frontmatter(data: Mapping[str, object]) -> str: - lines = ["---"] - for key, value in data.items(): - if isinstance(value, list): - lines.append(f"{key}:") - for item in value: - lines.append(f" - {_sanitize_scalar(item)}") - else: - lines.append(f"{key}: {_sanitize_scalar(value)}") - lines.append("---") - return "\n".join(lines) - - -def dump_document(data: Mapping[str, object], body: str) -> str: - return render_frontmatter(data) + "\n\n" + body.lstrip("\n") diff --git a/bridge_core/models.py b/bridge_core/models.py deleted file mode 100644 index 09a89d7..0000000 --- a/bridge_core/models.py +++ /dev/null @@ -1,234 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field -from datetime import datetime, timezone -from pathlib import Path -from typing import Sequence -import hashlib -import json -import random - -CURRENT_SCHEMA_VERSION = 2 -ACTIVE_STATUSES = {"open", "acknowledged", "in_progress", "blocked"} -ALL_STATUSES = ACTIVE_STATUSES | {"closed", "cancelled", "archived"} -HANDOFF_KINDS = {"incident", "request", "question", "result"} -PRIORITIES = {"low", "medium", "high", "urgent"} -RISK_LEVELS = {"low", "medium", "high"} -DEFAULT_RESPONSE_FORMAT = "concise status + action + blocker if any" - - -def now_iso() -> str: - return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") - - -def generate_handoff_id() -> str: - ts = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") - suffix = "".join(random.choice("0123456789abcdef") for _ in range(4)) - return f"HND-{ts}-{suffix}" - - -@dataclass(slots=True) -class CreateHandoffInput: - sender: str - recipient: str - issue_type: str - subject: str - requested_action: str - minimal_context: str - handoff_kind: str = "request" - priority: str = "medium" - risk_level: str = "low" - due_at: str = "none" - approval_needed: bool = False - approval_context: str = "none" - response_format: str = DEFAULT_RESPONSE_FORMAT - related_paths: Sequence[str] = field(default_factory=list) - constraints: str = "- none" - idempotency_key: str | None = None - correlation_id: str | None = None - causation_id: str | None = None - - def validate(self) -> None: - if self.handoff_kind not in HANDOFF_KINDS: - raise ValueError(f"invalid handoff_kind: {self.handoff_kind}") - if self.priority not in PRIORITIES: - raise ValueError(f"invalid priority: {self.priority}") - if self.risk_level not in RISK_LEVELS: - raise ValueError(f"invalid risk_level: {self.risk_level}") - if self.idempotency_key is not None and not self.idempotency_key.strip(): - raise ValueError("idempotency_key must not be empty") - - def canonical_request_hash(self) -> str: - payload = { - "sender": self.sender, - "recipient": self.recipient, - "issue_type": self.issue_type, - "subject": self.subject, - "requested_action": self.requested_action, - "minimal_context": self.minimal_context, - "handoff_kind": self.handoff_kind, - "priority": self.priority, - "risk_level": self.risk_level, - "due_at": self.due_at or "none", - "approval_needed": bool(self.approval_needed), - "approval_context": self.approval_context or "none", - "response_format": self.response_format, - "related_paths": list(self.related_paths), - "constraints": self.constraints or "- none", - "correlation_id": self.correlation_id, - "causation_id": self.causation_id, - } - encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8") - return hashlib.sha256(encoded).hexdigest() - - -@dataclass(slots=True) -class HandoffRecord: - handoff_id: str - status: str - created_at: str - updated_at: str - acknowledged_at: str - acknowledgment_source: str - sender: str - recipient: str - issue_type: str - handoff_kind: str = "request" - priority: str = "medium" - risk_level: str = "low" - due_at: str = "none" - approval_needed: str = "no" - approval_context: str = "none" - resolution_summary: str = "pending" - subject: str = "" - response_format: str = DEFAULT_RESPONSE_FORMAT - related_paths: list[str] = field(default_factory=list) - body: str = "" - schema_version: int = CURRENT_SCHEMA_VERSION - revision: int = 0 - correlation_id: str | None = None - causation_id: str | None = None - canonical_request_hash: str = "" - idempotency_key_hash: str = "" - - @classmethod - def from_create(cls, data: CreateHandoffInput) -> "HandoffRecord": - data.validate() - ts = now_iso() - return cls( - handoff_id=generate_handoff_id(), - status="open", - created_at=ts, - updated_at=ts, - acknowledged_at="none", - acknowledgment_source="none", - sender=data.sender, - recipient=data.recipient, - issue_type=data.issue_type, - handoff_kind=data.handoff_kind, - priority=data.priority, - risk_level=data.risk_level, - due_at=data.due_at or "none", - approval_needed="yes" if data.approval_needed else "no", - approval_context=data.approval_context or "none", - resolution_summary="pending", - subject=data.subject, - response_format=data.response_format, - related_paths=list(data.related_paths), - body=render_body(data.requested_action, data.minimal_context, data.constraints), - schema_version=CURRENT_SCHEMA_VERSION, - revision=0, - correlation_id=data.correlation_id, - causation_id=data.causation_id, - canonical_request_hash=data.canonical_request_hash(), - ) - - @classmethod - def from_mapping(cls, mapping: dict[str, object], body: str) -> "HandoffRecord": - return cls( - handoff_id=str(mapping["handoff_id"]), - status=str(mapping.get("status", "open")), - created_at=str(mapping.get("created_at", "")), - updated_at=str(mapping.get("updated_at", "")), - acknowledged_at=str(mapping.get("acknowledged_at", "none") or "none"), - acknowledgment_source=str(mapping.get("acknowledgment_source", "none") or "none"), - sender=str(mapping.get("sender", "")), - recipient=str(mapping.get("recipient", "")), - issue_type=str(mapping.get("issue_type", "")), - handoff_kind=str(mapping.get("handoff_kind", "request") or "request"), - priority=str(mapping.get("priority", "medium") or "medium"), - risk_level=str(mapping.get("risk_level", "low") or "low"), - due_at=str(mapping.get("due_at", "none") or "none"), - approval_needed=str(mapping.get("approval_needed", "no") or "no"), - approval_context=str(mapping.get("approval_context", "none") or "none"), - resolution_summary=str(mapping.get("resolution_summary", "pending") or "pending"), - subject=str(mapping.get("subject", "")), - response_format=str(mapping.get("response_format", DEFAULT_RESPONSE_FORMAT) or DEFAULT_RESPONSE_FORMAT), - related_paths=[str(item) for item in mapping.get("related_paths", [])], - body=body, - schema_version=int(str(mapping.get("schema_version", 1) or 1)), - revision=int(str(mapping.get("revision", 0) or 0)), - correlation_id=_optional_string(mapping.get("correlation_id")), - causation_id=_optional_string(mapping.get("causation_id")), - canonical_request_hash=str(mapping.get("canonical_request_hash", "") or ""), - idempotency_key_hash=str(mapping.get("idempotency_key_hash", "") or ""), - ) - - def to_frontmatter(self) -> dict[str, object]: - return { - "schema_version": self.schema_version, - "revision": self.revision, - "handoff_id": self.handoff_id, - "status": self.status, - "created_at": self.created_at, - "updated_at": self.updated_at, - "acknowledged_at": self.acknowledged_at, - "acknowledgment_source": self.acknowledgment_source, - "sender": self.sender, - "recipient": self.recipient, - "issue_type": self.issue_type, - "handoff_kind": self.handoff_kind, - "priority": self.priority, - "risk_level": self.risk_level, - "due_at": self.due_at, - "approval_needed": self.approval_needed, - "approval_context": self.approval_context, - "resolution_summary": self.resolution_summary, - "subject": self.subject, - "response_format": self.response_format, - "related_paths": list(self.related_paths), - "correlation_id": self.correlation_id or "none", - "causation_id": self.causation_id or "none", - "canonical_request_hash": self.canonical_request_hash, - "idempotency_key_hash": self.idempotency_key_hash, - } - - -@dataclass(slots=True) -class StoredHandoff: - path: Path - record: HandoffRecord - - -def _optional_string(value: object) -> str | None: - normalized = str(value or "").strip() - return None if normalized in {"", "none"} else normalized - - -def render_body(requested_action: str, minimal_context: str, constraints: str) -> str: - return "\n".join( - [ - "## Requested Action", - requested_action.strip(), - "", - "## Minimal Context", - minimal_context.strip(), - "", - "## Constraints", - constraints.strip() if constraints.strip() else "- none", - "", - "## Outcome", - "- pending", - "", - ] - ) diff --git a/bridge_core/policy.py b/bridge_core/policy.py deleted file mode 100644 index 92e8141..0000000 --- a/bridge_core/policy.py +++ /dev/null @@ -1,109 +0,0 @@ -from __future__ import annotations - -from .models import ACTIVE_STATUSES, ALL_STATUSES -from .runtime import configured_routes, normalize_agent_id - -STATUS_ALIASES = {"acked": "acknowledged"} -STATUS_TRANSITIONS = { - "open": {"open", "acknowledged", "in_progress", "blocked", "closed", "cancelled"}, - "acknowledged": {"acknowledged", "in_progress", "blocked", "closed", "cancelled"}, - "in_progress": {"in_progress", "blocked", "closed", "acknowledged", "cancelled"}, - "blocked": {"blocked", "in_progress", "closed", "acknowledged", "cancelled"}, - "closed": {"closed", "archived"}, - "cancelled": {"cancelled", "archived"}, - "archived": {"archived"}, -} - - -class BridgePolicyError(ValueError): - pass - - -class RoutePolicyError(BridgePolicyError): - pass - - -class AccessPolicyError(BridgePolicyError): - pass - - -class StatusPolicyError(BridgePolicyError): - pass - - -def normalize_status(status: str) -> str: - normalized = STATUS_ALIASES.get(status, status) - if normalized not in ALL_STATUSES: - raise StatusPolicyError(f"invalid status: {status}") - return normalized - - -def require_agent(agent: str) -> str: - try: - return normalize_agent_id(agent) - except ValueError as exc: - raise AccessPolicyError(str(exc)) from exc - - -def allowed_routes() -> set[tuple[str, str]]: - return configured_routes() - - -def require_route(sender: str, recipient: str) -> None: - normalized_sender = require_agent(sender) - normalized_recipient = require_agent(recipient) - if normalized_sender == normalized_recipient: - raise RoutePolicyError("sender and recipient must differ") - routes = allowed_routes() - if routes and (normalized_sender, normalized_recipient) not in routes: - raise RoutePolicyError(f"route not allowed by policy: {normalized_sender} -> {normalized_recipient}") - - -def require_actor_access(actor: str, sender: str, recipient: str) -> None: - normalized_actor = require_agent(actor) - normalized_sender = require_agent(sender) - normalized_recipient = require_agent(recipient) - if normalized_actor not in {normalized_sender, normalized_recipient}: - raise AccessPolicyError(f"actor {actor} is not sender or recipient for this handoff") - - -def require_status_transition(current: str, new: str, *, has_resolution_summary: bool) -> str: - current_normalized = normalize_status(current) - new_normalized = normalize_status(new) - allowed = STATUS_TRANSITIONS[current_normalized] - if new_normalized not in allowed: - raise StatusPolicyError(f"invalid status transition: {current_normalized} -> {new_normalized}") - if new_normalized == "closed" and not has_resolution_summary: - raise StatusPolicyError("closing a handoff requires resolution summary") - return new_normalized - - -def require_lifecycle_role(*, actor: str, sender: str, recipient: str, new_status: str, maintenance: bool = False) -> None: - if maintenance: - return - require_actor_access(actor, sender, recipient) - normalized = normalize_status(new_status) - if actor == recipient and normalized in {"acknowledged", "in_progress", "blocked", "closed", "archived"}: - return - if actor == sender and normalized == "cancelled": - return - if normalized in {"open"} and actor == sender: - return - raise AccessPolicyError(f"actor {actor} is not authorized to set {normalized} for this handoff") - - -def is_active_status(status: str) -> bool: - return normalize_status(status) in ACTIVE_STATUSES - - -def visible_queues_for_actor(*, actor: str, sender: str, recipient: str, handoff_id: str) -> set[str]: - normalized_actor = require_agent(actor) - normalized_sender = require_agent(sender) - normalized_recipient = require_agent(recipient) - if normalized_actor not in {normalized_sender, normalized_recipient}: - raise AccessPolicyError(f"actor {actor} is not sender or recipient for this handoff") - return { - f"incoming/{normalized_recipient}/{handoff_id}.md", - f"outgoing/{normalized_sender}/{handoff_id}.md", - f"archive/{handoff_id}/{handoff_id}.md", - } diff --git a/bridge_core/repository.py b/bridge_core/repository.py deleted file mode 100644 index 6e25f46..0000000 --- a/bridge_core/repository.py +++ /dev/null @@ -1,89 +0,0 @@ -from __future__ import annotations - -from abc import ABC, abstractmethod -from pathlib import Path -from typing import ContextManager - -from .events import LifecycleEvent -from .models import HandoffRecord, StoredHandoff - - -class HandoffNotFoundError(FileNotFoundError): - pass - - -class IdempotencyConflictError(ValueError): - pass - - -class RevisionConflictError(ValueError): - pass - - -class RepositoryConflictError(RuntimeError): - pass - - -class BridgeRepository(ABC): - @abstractmethod - def create(self, handoff: HandoffRecord, *, idempotency_key: str | None = None) -> HandoffRecord: - raise NotImplementedError - - @abstractmethod - def handoff_lock(self, handoff_id: str) -> ContextManager[None]: - raise NotImplementedError - - @abstractmethod - def load_records(self, handoff_id: str) -> list[StoredHandoff]: - raise NotImplementedError - - @abstractmethod - def list_incoming(self, agent: str) -> list[HandoffRecord]: - raise NotImplementedError - - @abstractmethod - def save_records(self, records: list[StoredHandoff]) -> None: - raise NotImplementedError - - @abstractmethod - def archive_records(self, records: list[StoredHandoff]) -> Path: - raise NotImplementedError - - @abstractmethod - def append_audit(self, handoff: HandoffRecord, status: str) -> None: - raise NotImplementedError - - @abstractmethod - def enqueue_event(self, event: LifecycleEvent) -> LifecycleEvent: - raise NotImplementedError - - @abstractmethod - def prepare_event(self, event: LifecycleEvent) -> None: - raise NotImplementedError - - @abstractmethod - def complete_event(self, event_id: str) -> None: - raise NotImplementedError - - @abstractmethod - def list_events(self, *, states: set[str] | None = None) -> list[LifecycleEvent]: - raise NotImplementedError - - @abstractmethod - def update_event(self, event: LifecycleEvent) -> LifecycleEvent: - raise NotImplementedError - - @abstractmethod - def replay_event(self, event_id: str) -> LifecycleEvent: - raise NotImplementedError - - @abstractmethod - def resolve_transaction( - self, - event_id: str, - *, - action: str, - reason: str, - force_recoverable_discard: bool = False, - ) -> LifecycleEvent: - raise NotImplementedError diff --git a/bridge_core/runtime.py b/bridge_core/runtime.py deleted file mode 100644 index 37c4934..0000000 --- a/bridge_core/runtime.py +++ /dev/null @@ -1,127 +0,0 @@ -from __future__ import annotations - -from collections.abc import Iterable, Mapping -from pathlib import Path -import os -import re - -AGENT_ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9_-]*$") -ROUTE_ENV_VAR = "BRIDGE_ALLOWED_ROUTES" -AGENTS_ENV_VAR = "BRIDGE_AGENTS" -TOKEN_ENV_PREFIX = "BRIDGE_TOKEN_" -NOTIFY_URL_ENV_PREFIX = "BRIDGE_NOTIFY_URL_" -NOTIFY_EVENT_ENV_PREFIX = "BRIDGE_NOTIFY_EVENT_COMMAND_" -CONFIG_ENV_VAR = "BRIDGE_API_CONFIG" - - -def normalize_agent_id(agent: str, *, field_name: str = "agent") -> str: - normalized = str(agent or "").strip().lower() - if not normalized: - raise ValueError(f"missing {field_name}") - if not AGENT_ID_PATTERN.fullmatch(normalized): - raise ValueError( - f"invalid {field_name}: {agent!r}; expected lowercase letters, digits, hyphen, or underscore" - ) - return normalized - - -def normalize_agent_env_suffix(value: str) -> str: - return normalize_agent_id(str(value or "").strip().lower().replace("_", "-")) - - -def env_key_for_agent(prefix: str, agent: str) -> str: - normalized = normalize_agent_id(agent) - suffix = normalized.replace("-", "_").upper() - return f"{prefix}{suffix}" - - -def _split_csv_like(value: str) -> list[str]: - return [item.strip() for item in re.split(r"[\s,]+", value) if item.strip()] - - -def parse_agent_list(value: str | None) -> tuple[str, ...]: - if not value: - return () - seen: list[str] = [] - for item in _split_csv_like(value): - agent = normalize_agent_id(item) - if agent not in seen: - seen.append(agent) - return tuple(seen) - - -def parse_allowed_routes(value: str | None) -> set[tuple[str, str]]: - routes: set[tuple[str, str]] = set() - if not value: - return routes - for raw_route in _split_csv_like(value): - if ":" not in raw_route: - raise ValueError(f"invalid route entry: {raw_route!r}; expected sender:recipient") - sender, recipient = raw_route.split(":", 1) - routes.add((normalize_agent_id(sender, field_name="sender"), normalize_agent_id(recipient, field_name="recipient"))) - return routes - - -def _read_env_file(path: Path) -> dict[str, str]: - values: dict[str, str] = {} - for raw_line in path.read_text(encoding="utf-8").splitlines(): - line = raw_line.strip() - if not line or line.startswith("#") or "=" not in line: - continue - key, value = line.split("=", 1) - values[key.strip()] = value.strip() - return values - - -def configured_values() -> dict[str, str]: - values: dict[str, str] = {} - config_path = os.environ.get(CONFIG_ENV_VAR, "").strip() - if config_path: - path = Path(config_path) - if path.exists(): - values.update(_read_env_file(path)) - for key, value in os.environ.items(): - if key.startswith("BRIDGE_"): - values[key] = value - return values - - -def configured_routes() -> set[tuple[str, str]]: - return parse_allowed_routes(configured_values().get(ROUTE_ENV_VAR, "")) - - -def _agents_from_keyed_values(source: Iterable[str], prefix: str) -> set[str]: - agents: set[str] = set() - for key in source: - if not key.startswith(prefix): - continue - suffix = key[len(prefix) :].strip() - if suffix: - agents.add(normalize_agent_env_suffix(suffix)) - return agents - - -def discover_agents(*, bridge_root: Path | str | None = None, config_values: Mapping[str, str] | None = None) -> tuple[str, ...]: - values = dict(configured_values()) - if config_values: - values.update(config_values) - - agents: set[str] = set(parse_agent_list(values.get(AGENTS_ENV_VAR, ""))) - agents.update(_agents_from_keyed_values(values.keys(), TOKEN_ENV_PREFIX)) - agents.update(_agents_from_keyed_values(values.keys(), NOTIFY_URL_ENV_PREFIX)) - agents.update(_agents_from_keyed_values(values.keys(), NOTIFY_EVENT_ENV_PREFIX)) - for sender, recipient in parse_allowed_routes(values.get(ROUTE_ENV_VAR, "")): - agents.add(sender) - agents.add(recipient) - - if bridge_root is not None: - root = Path(bridge_root) - for kind in ("incoming", "outgoing"): - queue_root = root / kind - if not queue_root.exists(): - continue - for child in queue_root.iterdir(): - if child.is_dir(): - agents.add(normalize_agent_id(child.name)) - - return tuple(sorted(agents)) diff --git a/bridge_core/service.py b/bridge_core/service.py deleted file mode 100644 index f9b8fc7..0000000 --- a/bridge_core/service.py +++ /dev/null @@ -1,355 +0,0 @@ -from __future__ import annotations - -from datetime import datetime, timedelta, timezone -from pathlib import Path -from typing import Callable -import random -import re - -from .events import LifecycleEvent -from .models import CURRENT_SCHEMA_VERSION, CreateHandoffInput, HandoffRecord, StoredHandoff, now_iso -from .policy import ( - AccessPolicyError, - StatusPolicyError, - is_active_status, - normalize_status, - require_actor_access, - require_lifecycle_role, - require_route, - require_status_transition, -) -from .repository import BridgeRepository, IdempotencyConflictError, RepositoryConflictError, RevisionConflictError - - -class BridgeService: - def __init__(self, repository: BridgeRepository): - self.repository = repository - - def create_handoff(self, request: CreateHandoffInput) -> HandoffRecord: - require_route(request.sender, request.recipient) - request.validate() - proposed = HandoffRecord.from_create(request) - event = LifecycleEvent.from_handoff( - proposed, - event_type="handoff_created", - actor=request.sender, - target_agent=request.recipient, - ) - self.repository.prepare_event(event) - try: - created = self.repository.create(proposed, idempotency_key=request.idempotency_key) - except IdempotencyConflictError: - self.repository.complete_event(event.event_id) - raise - except RepositoryConflictError: - # Repository conflicts occur before this proposed handoff becomes - # canonical, so its prepared create event is not recoverable. - self.repository.complete_event(event.event_id) - raise - except BaseException: - # A prepared transaction is intentionally retained if canonical state was - # committed before a crash; recovery can decide whether to enqueue it. - raise - if created.handoff_id != proposed.handoff_id: - self.repository.complete_event(event.event_id) - return created - self.repository.enqueue_event(event) - self.repository.complete_event(event.event_id) - return created - - def get_handoff(self, handoff_id: str, *, actor: str | None = None) -> HandoffRecord: - records = self.repository.load_records(handoff_id) - primary = records[0].record - if actor is not None: - require_actor_access(actor, primary.sender, primary.recipient) - return primary - - def list_handoffs(self, agent: str, *, active_only: bool = True) -> list[HandoffRecord]: - records = self.repository.list_incoming(agent) - if active_only: - return [record for record in records if is_active_status(record.status)] - return records - - def list_open_handoffs(self, agent: str) -> list[HandoffRecord]: - return self.list_handoffs(agent, active_only=True) - - def set_status( - self, - handoff_id: str, - *, - actor: str, - status: str, - outcome: str = "", - acknowledgment_source: str | None = None, - expected_revision: int | None = None, - maintenance: bool = False, - ) -> HandoffRecord: - with self.repository.handoff_lock(handoff_id): - records = self.repository.load_records(handoff_id) - primary = records[0].record - normalized_requested = normalize_status(status) - require_lifecycle_role( - actor=actor, - sender=primary.sender, - recipient=primary.recipient, - new_status=normalized_requested, - maintenance=maintenance, - ) - outcome_text = outcome.strip() - if expected_revision is not None and expected_revision != primary.revision: - if self._is_safe_same_state_retry(primary, normalized_requested, outcome_text): - return primary - raise RevisionConflictError( - f"stale revision for {handoff_id}: expected {expected_revision}, current {primary.revision}" - ) - if self._is_safe_same_state_retry(primary, normalized_requested, outcome_text): - return primary - has_resolution_summary = bool(outcome_text or primary.resolution_summary != "pending") - normalized_status = require_status_transition( - primary.status, - normalized_requested, - has_resolution_summary=has_resolution_summary, - ) - ack_source = _normalize_acknowledgment_source(acknowledgment_source, status=normalized_status) - next_revision = primary.revision + 1 - updated = self._mutate_records( - records, - normalized_status, - outcome_text, - acknowledgment_source=ack_source, - revision=next_revision, - ) - target_agent = updated.recipient if normalized_status == "cancelled" else updated.sender - event = LifecycleEvent.from_handoff( - updated, - event_type=f"handoff_{normalized_status}", - actor=actor, - target_agent=target_agent, - ) - self.repository.prepare_event(event) - self.repository.save_records(records) - self.repository.append_audit(updated, updated.status) - self.repository.enqueue_event(event) - self.repository.complete_event(event.event_id) - return updated - - def cancel_handoff( - self, - handoff_id: str, - *, - actor: str, - reason: str, - expected_revision: int | None = None, - ) -> HandoffRecord: - if not reason.strip(): - raise StatusPolicyError("cancelling a handoff requires a reason") - return self.set_status( - handoff_id, - actor=actor, - status="cancelled", - outcome=reason, - expected_revision=expected_revision, - ) - - def archive_handoff( - self, - handoff_id: str, - *, - actor: str, - expected_revision: int | None = None, - maintenance: bool = False, - ) -> Path: - with self.repository.handoff_lock(handoff_id): - records = self.repository.load_records(handoff_id) - primary = records[0].record - require_lifecycle_role( - actor=actor, - sender=primary.sender, - recipient=primary.recipient, - new_status="archived", - maintenance=maintenance, - ) - if expected_revision is not None and expected_revision != primary.revision: - raise RevisionConflictError( - f"stale revision for {handoff_id}: expected {expected_revision}, current {primary.revision}" - ) - statuses = {normalize_status(item.record.status) for item in records} - if not statuses <= {"closed", "cancelled"}: - raise StatusPolicyError("only closed or cancelled handoffs can be archived") - archived = self._mutate_records( - records, - "archived", - "", - acknowledgment_source=None, - revision=primary.revision + 1, - ) - event = LifecycleEvent.from_handoff( - archived, - event_type="handoff_archived", - actor=actor, - target_agent=archived.sender, - ) - self.repository.prepare_event(event) - archive_dir = self.repository.archive_records(records) - self.repository.append_audit(archived, archived.status) - self.repository.enqueue_event(event) - self.repository.complete_event(event.event_id) - return archive_dir - - def list_outbox(self, *, states: set[str] | None = None) -> list[LifecycleEvent]: - return self.repository.list_events(states=states) - - def replay_event(self, event_id: str) -> LifecycleEvent: - return self.repository.replay_event(event_id) - - def resolve_transaction( - self, - event_id: str, - *, - action: str, - reason: str, - force_recoverable_discard: bool = False, - ) -> LifecycleEvent: - return self.repository.resolve_transaction( - event_id, - action=action, - reason=reason, - force_recoverable_discard=force_recoverable_discard, - ) - - def process_outbox( - self, - deliver: Callable[[LifecycleEvent], tuple[bool, str]], - *, - limit: int = 100, - max_attempts: int = 8, - base_delay_seconds: float = 1.0, - max_delay_seconds: float = 300.0, - ) -> list[LifecycleEvent]: - processed: list[LifecycleEvent] = [] - due = [event for event in self.list_outbox(states={"pending", "retrying"}) if event.due()] - for event in due[: max(0, limit)]: - ok, detail = deliver(event) - if ok: - processed.append(self._mark_event_delivered(event)) - else: - processed.append( - self._mark_event_failed( - event, - detail, - max_attempts=max_attempts, - base_delay_seconds=base_delay_seconds, - max_delay_seconds=max_delay_seconds, - ) - ) - return processed - - def mark_event_delivered(self, event_id: str) -> LifecycleEvent: - event = self._event(event_id) - return self._mark_event_delivered(event) - - def _mark_event_delivered(self, event: LifecycleEvent) -> LifecycleEvent: - event.delivery_state = "delivered" - event.last_error = "" - return self.repository.update_event(event) - - def mark_event_failed( - self, - event_id: str, - error: str, - *, - max_attempts: int = 8, - base_delay_seconds: float = 1.0, - max_delay_seconds: float = 300.0, - jitter_ratio: float = 0.2, - ) -> LifecycleEvent: - event = self._event(event_id) - return self._mark_event_failed( - event, - error, - max_attempts=max_attempts, - base_delay_seconds=base_delay_seconds, - max_delay_seconds=max_delay_seconds, - jitter_ratio=jitter_ratio, - ) - - def _mark_event_failed( - self, - event: LifecycleEvent, - error: str, - *, - max_attempts: int = 8, - base_delay_seconds: float = 1.0, - max_delay_seconds: float = 300.0, - jitter_ratio: float = 0.2, - ) -> LifecycleEvent: - event.attempts += 1 - event.last_error = error.strip()[:1000] - if event.attempts >= max(1, max_attempts): - event.delivery_state = "dead_letter" - event.next_attempt_at = now_iso() - else: - event.delivery_state = "retrying" - base = min(max_delay_seconds, base_delay_seconds * (2 ** (event.attempts - 1))) - jitter = random.uniform(0.0, max(0.0, base * jitter_ratio)) - next_attempt = datetime.now(timezone.utc) + timedelta(seconds=base + jitter) - event.next_attempt_at = next_attempt.isoformat().replace("+00:00", "Z") - return self.repository.update_event(event) - - def _event(self, event_id: str) -> LifecycleEvent: - for event in self.repository.list_events(): - if event.event_id == event_id: - return event - raise FileNotFoundError(f"event not found: {event_id}") - - @staticmethod - def _is_safe_same_state_retry(primary: HandoffRecord, status: str, outcome: str) -> bool: - if normalize_status(primary.status) != status: - return False - if not outcome: - return True - return primary.resolution_summary == outcome - - def _mutate_records( - self, - records: list[StoredHandoff], - status: str, - outcome: str, - *, - acknowledgment_source: str | None, - revision: int, - ) -> HandoffRecord: - updated: HandoffRecord | None = None - transition_time = now_iso() - for stored in records: - stored.record.status = status - stored.record.schema_version = CURRENT_SCHEMA_VERSION - stored.record.revision = revision - stored.record.updated_at = transition_time - if status == "acknowledged" and stored.record.acknowledged_at == "none": - stored.record.acknowledged_at = transition_time - stored.record.acknowledgment_source = acknowledgment_source or "manual" - if outcome: - stored.record.resolution_summary = outcome - stored.record.body = self._replace_outcome(stored.record.body, outcome) - if updated is None: - updated = stored.record - assert updated is not None - return updated - - @staticmethod - def _replace_outcome(body: str, outcome: str) -> str: - replacement = f"## Outcome\n{outcome}\n" - pattern = r"(?ms)^## Outcome\n.*?(?=^## |\Z)" - if re.search(pattern, body): - return re.sub(pattern, replacement, body, count=1) - return body.rstrip() + f"\n\n{replacement}" - - -def _normalize_acknowledgment_source(value: str | None, *, status: str) -> str | None: - if status != "acknowledged": - return None - normalized = str(value or "manual").strip().lower() - if normalized not in {"manual", "auto"}: - raise StatusPolicyError("acknowledgment_source must be auto or manual") - return normalized \ No newline at end of file diff --git a/bridge_core/tooling.py b/bridge_core/tooling.py deleted file mode 100644 index 7768b8f..0000000 --- a/bridge_core/tooling.py +++ /dev/null @@ -1,35 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass, field -from pathlib import Path - -from .frontmatter import parse_frontmatter -from .models import HandoffRecord - - -@dataclass(slots=True) -class LoadedHandoff: - path: Path - record: HandoffRecord - body: str - archive_file_count: int = 1 - archive_extra_files: list[str] = field(default_factory=list) - - -def load_handoff_path(path: Path) -> LoadedHandoff: - data, body = parse_frontmatter(path.read_text(encoding="utf-8", errors="replace")) - return LoadedHandoff(path=path, record=HandoffRecord.from_mapping(data, body), body=body) - - -def summarize_handoffs(paths) -> list[LoadedHandoff]: - return [load_handoff_path(path) for path in sorted(paths)] - - -def load_archive_entry(directory: Path) -> LoadedHandoff | None: - files = sorted(directory.glob("*.md")) - if not files: - return None - item = load_handoff_path(files[0]) - item.archive_file_count = len(files) - item.archive_extra_files = [str(path) for path in files[1:]] - return item diff --git a/config/bridge_api.example.env b/config/bridge_api.example.env deleted file mode 100644 index 832919b..0000000 --- a/config/bridge_api.example.env +++ /dev/null @@ -1,48 +0,0 @@ -# Bridge API token mapping. Keep real tokens out of version control. -BRIDGE_TOKEN_AGENT_A=*** -BRIDGE_TOKEN_AGENT_B=*** -# BRIDGE_TOKEN_AGENT_C=*** - -# Optional immediate notify hooks. Point each agent at its local bridge_intake_watch.py --listen endpoint. -# The API will POST to these URLs for handoff lifecycle events (create, close, block) and fall back to polling if delivery fails. -BRIDGE_NOTIFY_URL_AGENT_A=http://127.0.0.1:8521/notify -BRIDGE_NOTIFY_URL_AGENT_B=http://127.0.0.1:8522/notify -# BRIDGE_NOTIFY_URL_AGENT_C=http://127.0.0.1:8523/notify - -# Optional lifecycle event consumer commands. -# bridge_intake_watch.py will execute these read-only hooks for sender-side lifecycle events -# like handoff_closed and handoff_blocked. Each command receives the raw JSON event on stdin. -# BRIDGE_NOTIFY_EVENT_COMMAND_AGENT_A= -# BRIDGE_NOTIFY_EVENT_COMMAND_AGENT_B= -# BRIDGE_NOTIFY_EVENT_COMMAND_AGENT_C= - -# Optional intake event commands. -# bridge_intake_watch.py runs these after it auto-acknowledges a new recipient handoff. -# The command receives a generic handoff_acknowledged JSON event on stdin. Use this for -# local work-queue mirroring, alerting, or indexing without baking those systems into Bridge. -# Generic command applies to all agents unless an agent-scoped command is set. -# CLI --intake-event-command overrides both env forms. -# BRIDGE_INTAKE_EVENT_COMMAND= -# BRIDGE_INTAKE_EVENT_COMMAND_AGENT_A= -# BRIDGE_INTAKE_EVENT_COMMAND_AGENT_B= -# BRIDGE_INTAKE_EVENT_COMMAND_AGENT_C= - -# Optional launch settings for scripts/bridge_api_server.py. -# If you run Bridge directly from a repo checkout, the scripts already default to repo-relative paths. -# Set these explicitly only when you want a different runtime location. -BRIDGE_API_HOST=127.0.0.1 -BRIDGE_API_PORT=8427 -# Optional explicit route allowlist. If unset, all sender -> recipient pairs are allowed. -# BRIDGE_ALLOWED_ROUTES=agent-a:agent-b,agent-b:agent-a -# BRIDGE_PROJECT_ROOT=/absolute/path/to/bridge -# BRIDGE_ROOT=/absolute/path/to/bridge/bridge -# BRIDGE_API_CONFIG=/absolute/path/to/bridge/config/bridge_api.env - -# Optional patrol tuning (can also be passed as CLI flags to bridge_patrol.py) -# Built-in active unresolved alert: warn after this many hours if a handoff is still active -# and only has placeholder/admin summary text (for example `pending` or `actively investigating`). -# BRIDGE_PATROL_ACTIVE_ALERT_HOURS=0.5 -# BRIDGE_PATROL_REMINDER_AFTER_HOURS=0.5 -# BRIDGE_PATROL_REMINDER_REPEAT_HOURS=2 -# BRIDGE_PATROL_ESCALATE_AFTER_HOURS=6 -# BRIDGE_PATROL_ESCALATE_REPEAT_HOURS=24 diff --git a/deploy/systemd/README.md b/deploy/systemd/README.md deleted file mode 100644 index 214682b..0000000 --- a/deploy/systemd/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Example deployment units - -These units are templates, not drop-in copies of one specific live host deployment. - -## Files -- `bridge-api.service` — local Bridge API server -- `bridge-intake-watch@.service` — recipient notify listener template (`%i` = agent name) -- `example-agent.env` — per-agent listener settings consumed by `bridge-intake-watch@.service` - -## Expected layout -This example assumes the repo is deployed at `/opt/bridge` and runtime config lives at `/etc/bridge/bridge.env`. -Adjust paths for your host. - -## Lifecycle event consumers -`bridge-intake-watch.py` supports per-agent read-only event commands via env vars: -- `BRIDGE_NOTIFY_EVENT_COMMAND_` - -Each command receives the raw lifecycle JSON event on stdin. - -Bridge core should emit/store lifecycle state. -UI/chat-specific notification adapters should live outside Bridge core. diff --git a/deploy/systemd/bridge-api.service b/deploy/systemd/bridge-api.service deleted file mode 100644 index 41c16a6..0000000 --- a/deploy/systemd/bridge-api.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -Description=Bridge local API service -After=network.target - -[Service] -Type=simple -EnvironmentFile=/etc/bridge/bridge.env -WorkingDirectory=/opt/bridge -ExecStart=/usr/bin/python3 /opt/bridge/scripts/bridge_api_server.py --host ${BRIDGE_API_HOST} --port ${BRIDGE_API_PORT} --bridge-root ${BRIDGE_ROOT} --config ${BRIDGE_API_CONFIG} -Restart=on-failure -RestartSec=2 - -[Install] -WantedBy=default.target diff --git a/deploy/systemd/bridge-intake-watch@.service b/deploy/systemd/bridge-intake-watch@.service deleted file mode 100644 index b02b0a7..0000000 --- a/deploy/systemd/bridge-intake-watch@.service +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=Bridge intake notify listener for %i -After=bridge-api.service - -[Service] -Type=simple -EnvironmentFile=/etc/bridge/bridge.env -EnvironmentFile=-/etc/bridge/%i.env -WorkingDirectory=/opt/bridge -ExecStart=/usr/bin/python3 /opt/bridge/scripts/bridge_intake_watch.py --agent %i --listen --host 127.0.0.1 --port ${BRIDGE_NOTIFY_PORT} --event-command="${BRIDGE_NOTIFY_EVENT_COMMAND}" -Restart=on-failure -RestartSec=2 - -[Install] -WantedBy=default.target diff --git a/deploy/systemd/example-agent.env b/deploy/systemd/example-agent.env deleted file mode 100644 index f9ac614..0000000 --- a/deploy/systemd/example-agent.env +++ /dev/null @@ -1,5 +0,0 @@ -# Example per-agent notify listener settings for bridge-intake-watch@.service -BRIDGE_NOTIFY_PORT=8521 -# Example: a read-only lifecycle event consumer command. -# Leave empty if you only want recipient intake/auto-ack behavior. -BRIDGE_NOTIFY_EVENT_COMMAND= diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 7d48c0e..0000000 --- a/docs/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Bridge Docs - -## Start here -- [`../README.md`](../README.md) — project overview and quick start -- [`architecture.md`](architecture.md) — component boundaries and data flow -- [`bridge-v2-reliability.md`](bridge-v2-reliability.md) — reliability contracts, recovery, migration, deployment, and rollback -- [`deployment.md`](deployment.md) — deployment model and systemd template usage -- [`runtime-layout.md`](runtime-layout.md) — runtime directories under `BRIDGE_ROOT` - -## Examples -- [`../examples/handoffs/`](../examples/handoffs/) — example markdown handoff payloads diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index 5bf623d..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,43 +0,0 @@ -# Architecture - -## Design goal -Bridge provides explicit, auditable handoffs between autonomous agents without shared long-term memory. - -## Main components -- `bridge_core/` — Python package with models, policy, auth, repository, runtime helpers, and service logic -- `scripts/bridge_api_server.py` — local HTTP API for wrappers and automation -- `scripts/bridge_cli.py` — direct filesystem/API CLI for manual operations and testing -- `scripts/bridge_agent.py` — generic per-agent wrapper interface -- `scripts/bridge_intake_watch.py` — recipient listener and read-only lifecycle consumer entrypoint -- `scripts/bridge_patrol.py` — unresolved handoff detection and reminder tooling - -## Data flow -1. sender creates handoff through CLI or API-backed wrapper -2. Bridge validates auth, route policy, and status rules -3. Bridge v2 atomically writes a canonical record, then recoverable sender/recipient queue views -4. Bridge durably enqueues a versioned lifecycle event with at-least-once delivery semantics -5. optional recipient notify URL receives an immediate compatibility fast path -6. recipient acknowledges, progresses, blocks, closes, or archives; sender may explicitly cancel/withdraw -7. outbox delivery retries consumer outages with stable event IDs and dead-letter evidence - -## Boundaries -- Bridge ships with no built-in agent IDs -- route policy comes from config, not code constants -- lifecycle consumers are adapters outside core logic -- runtime state stays under `BRIDGE_ROOT`, outside tracked source -- agent-private memory stays outside Bridge entirely -- durable work state and worker dispatch stay in external work queues, not Bridge - -## Reliability v2 - -See [`bridge-v2-reliability.md`](bridge-v2-reliability.md) for the canonical-record transaction model, optimistic revisions, lifecycle authorization matrix, durable outbox, v1 compatibility, adapter contract, migration, deployment, and rollback procedures. - -## Why package name stays `bridge_core/` -`bridge_core/` is importable Python package name used across scripts and tests. Renaming it to bare `src/` would not be a like-for-like cleanup; `src/` is usually container directory for package layout, not package name itself. - -If a future packaging cleanup is desired, correct shape would be one of: -- keep current flat layout: `bridge_core/` -- adopt src-layout: `src/bridge_core/` -- rename package semantically: `src/bridge/` - -Plain `src/` alone would make imports and packaging less clear, not more. diff --git a/docs/bridge-v2-reliability.md b/docs/bridge-v2-reliability.md deleted file mode 100644 index c5d6526..0000000 --- a/docs/bridge-v2-reliability.md +++ /dev/null @@ -1,201 +0,0 @@ -# Bridge v2 reliability foundation - -## Scope and non-goals - -Bridge v2 is a backward-compatible reliability layer for explicit, scoped, redacted agent handoffs. It is an at-least-once event bus with idempotent producers and consumers. It does **not** provide exactly-once delivery, worker dispatch, shared memory, or durable work-state ownership. External work queues remain independent systems. - -Bridge core stays generic: `bridge_core/` imports no Hermes, Kanban, profile, vault, or messaging-platform code. - -## Transaction and recovery model - -### Canonical state and queue views - -A v2 handoff has one canonical Markdown record at: - -```text -records/.md -``` - -The existing files remain as backward-compatible queue views: - -```text -outgoing//.md -incoming//.md -``` - -The canonical record is authoritative. Record writes use a same-directory temporary file, flush, file `fsync`, mode `0600`, atomic rename, and parent-directory `fsync`. Creation and lifecycle mutation use an exclusive per-handoff `flock` plus an in-process reentrant lock. - -A create writes canonical state before queue views. If the process stops after one view, `reconcile` rebuilds the missing view from canonical evidence. A conflicting view is copied to `audit/conflicts/`, an audit event is appended, and only then may the view be replaced. Ambiguous v1 conflicts without canonical evidence are never auto-selected. - -Two byte-identical v1 queue copies without a canonical record are unambiguous legacy state, not divergence. Check-only reconciliation leaves them quiet. Repair mode materializes the v2 canonical record and rewrites both queue views to the canonical v2 representation without creating false conflict evidence. Non-identical v1 copies remain an operator decision. - -### Idempotent create - -Clients may send `Idempotency-Key` or `idempotency_key`. The key is scoped to the authenticated sender. Bridge stores only its SHA-256 digest in `idempotency//`; it stores a canonical request SHA-256 over material request fields. The raw key is not written. - -- same sender + key + canonical payload: return the original handoff; -- same sender + key + materially different payload: conflict (`HTTP 409`); -- concurrent identical requests: serialized by the sender/key lock and produce one handoff. - -Canonical state is written before its idempotency index. If a process stops in that interval, a retry under the same sender/key lock scans canonical records for the stored key digest, validates the canonical request hash, rebuilds the missing index, repairs queue views, and returns the original handoff. Multiple canonical claims for one sender/key digest fail closed as a repository conflict. - -### Lifecycle transactions and outbox - -Before a lifecycle state commit, Bridge writes a prepared transaction journal containing the immutable event envelope. It then: - -1. atomically commits canonical handoff state and queue views; -2. fsync-appends audit evidence; -3. atomically writes the outbox event; -4. removes the prepared transaction. - -If a process stops after state commit but before outbox enqueue, `outbox-recover` compares the prepared event with canonical revision/status and enqueues the same `event_id`. Consumer failure never rolls back handoff state. - -Automatic recovery deliberately leaves a prepared event untouched when canonical state has advanced or disappeared. An operator must inspect the transaction, canonical audit history, and downstream consumer state, then explicitly resolve it with `outbox-resolve-transaction`: `enqueue` preserves at-least-once historical delivery with the original `event_id`; `discard` is only for proven duplicate/invalid transactions. Bridge refuses to discard an event that still exactly matches canonical state unless the operator also supplies `--force-recoverable-discard`. Both actions require a reason and preserve canonical match evidence under `audit/resolved-transactions/` before removing the journal. - -Events live at `outbox/events/.json`. State transitions are `pending` → `retrying` → `delivered` or `dead_letter`. Backoff is bounded exponential delay plus jitter. Manual replay resets attempts and scheduling but retains `event_id`. - -Immediate notify remains a compatibility fast path. Its body preserves the v1 create/block/close shape and carries `X-Bridge-Event-ID`. Durable `outbox-deliver` sends the full v2 event body and the same header. - -## Record contract - -New records use: - -- `schema_version: 2` -- `revision: 0` at create, incremented once per lifecycle mutation -- optional `correlation_id` -- optional `causation_id` -- `canonical_request_hash` -- `idempotency_key_hash` when create idempotency is used - -Missing v2 fields mean a v1 record. A v1 record loads as `schema_version=1`, `revision=0` without an eager migration. Its first successful lifecycle mutation writes v2 canonical state and v2 queue views at revision 1. - -## Lifecycle event contract - -Every durable lifecycle event has: - -- `schema_version` -- unique stable `event_id` -- `handoff_id` -- `event_type` -- `revision` -- `occurred_at` -- `target_agent`, `sender`, `recipient`, `actor` -- `status`, `subject`, `resolution_summary` -- optional `correlation_id`, `causation_id` -- optional generic `external_correlation` mapping -- `attempts`, `next_attempt_at`, `last_error`, `delivery_state` - -Lifecycle event types are: - -- `handoff_created` -- `handoff_acknowledged` -- `handoff_in_progress` -- `handoff_blocked` -- `handoff_closed` -- `handoff_cancelled` -- `handoff_archived` - -`retrying` and `dead_letter` are durable delivery states for the same immutable event. Diagnostics/adapters may surface these as `handoff_retrying` and `handoff_dead_lettered` operational notifications without creating a second recursively delivered outbox item. - -## Optimistic concurrency - -API callers may send `expected_revision` or `If-Match: ""`. CLI/wrapper callers use `--expected-revision`. A stale update returns `HTTP 409 revision_conflict`. - -A repeated same-state request is a no-op when its outcome is empty or exactly matches the stored outcome. It does not increment revision or create another event. Authorization is checked before this no-op rule. - -## Lifecycle authorization matrix - -| Action | Sender | Recipient | Host maintenance | -|---|---:|---:|---:| -| create | yes | no | explicit tooling only | -| acknowledge | no | yes | recovery override | -| in progress | no | yes | recovery override | -| block | no | yes | recovery override | -| close with verified outcome | no | yes | recovery override | -| cancel/withdraw with reason | yes | no | recovery override | -| archive closed or sender-cancelled handoff | no | yes | recovery override | - -The API exposes no maintenance override. The service-layer `maintenance=True` path is deliberately explicit for offline host recovery tooling and must not be granted through participant tokens. - -## Generic work-queue adapter contract - -An external adapter consumes full v2 outbox events. It must persist processed `event_id` values and maintain a mapping keyed by `handoff_id`. Duplicate `event_id` is a no-op. - -Recommended reconciliation: - -- `handoff_acknowledged`: create or find the durable work item; persist its external ID in adapter-owned state. -- `handoff_in_progress`: update progress evidence, without making Bridge a dispatcher. -- `handoff_blocked`: update the existing work item with blocker evidence. -- `handoff_closed`: close/update the existing work item only after the event contains a verified outcome acceptable to local policy. -- `handoff_cancelled`: mark the work item withdrawn/cancelled under local policy. -- delivery failure: leave the event retrying; exhausted attempts provide dead-letter evidence. -- duplicate event: no-op and return success. - -An adapter may store a Kanban card ID in its own mapping or in generic `external_correlation` metadata. Bridge core neither imports nor calls Kanban. - -## Commands - -```bash -python3 scripts/bridge_cli.py outbox-list --state pending -python3 scripts/bridge_cli.py outbox-list --state dead_letter -python3 scripts/bridge_cli.py outbox-recover -python3 scripts/bridge_cli.py outbox-deliver --limit 100 -python3 scripts/bridge_cli.py outbox-replay EVT-... -python3 scripts/bridge_cli.py outbox-resolve-transaction EVT-... --action enqueue --reason "verified missing delivery" -python3 scripts/bridge_cli.py outbox-resolve-transaction EVT-... --action discard --reason "verified duplicate event" -python3 scripts/bridge_cli.py outbox-resolve-transaction EVT-... --action discard --force-recoverable-discard --reason "verified downstream duplicate; suppress recoverable replay" -python3 scripts/bridge_cli.py reconcile --check-only -python3 scripts/bridge_cli.py reconcile HND-... -``` - -`reconcile --check-only` is read-only. Repair mode restores only from unambiguous canonical evidence; conflict evidence is preserved before replacement. - -## Backward-compatible migration plan - -1. Deploy code without changing live data. -2. Run compile/tests and `reconcile --check-only` against a copied Bridge root. Identical v1 mirror pairs should not be reported as divergent. -3. Back up the live Bridge root with metadata and verify the backup can be listed/read. -4. Stop API/intake writers during the separately approved maintenance window. -5. Run `outbox-recover`, then `reconcile --check-only` on live data. -6. Resolve ambiguous divergent v1 copies manually; do not select by timestamp alone. -7. Run `reconcile` to lazily materialize canonical records and missing views. Verify identical v1 pairs migrate without conflict evidence. -8. Start the API, then run one bounded `outbox-deliver` pass. -9. Verify health, patrol, route/token authorization, open handoff counts, outbox/dead-letter counts, and one isolated synthetic route approved for the maintenance window. -10. Add one separately approved periodic invocation of `outbox-recover` + `outbox-deliver`; do not treat the API fast path as the retry scheduler. Enforce a single active deliverer with the service manager or an external lock. - -No bulk rewrite is required. Untouched v1 handoffs continue to load. - -## Live deployment plan (separate approval required) - -Deployment mutates production code/data and requires a doctor rundown plus explicit Cameron approval. The approved window should include: immutable backup path, exact release artifact, writer quiescence, pre/post patrol captures, service-specific restart scope, and rollback trigger. - -Do not modify token values or `config/bridge_api.env`. Existing route/token configuration remains valid. Optional retry settings are additive environment values: - -- `BRIDGE_OUTBOX_MAX_ATTEMPTS` -- `BRIDGE_OUTBOX_BASE_DELAY_SECONDS` -- `BRIDGE_OUTBOX_MAX_DELAY_SECONDS` -- `BRIDGE_PATROL_OUTBOX_PENDING_SECONDS` - -Adding those values or a periodic scheduler is a separate config/service approval. - -## Rollback - -1. Stop only Bridge API/intake/outbox writers in the approved window. -2. Preserve the current v2 Bridge root as forensic evidence; do not delete it. -3. Restore the pre-deployment Bridge-root backup atomically, including modes/ownership. -4. Restore the prior code release/symlink or package artifact. -5. Restore the prior service definitions only if they changed. -6. Start only the previously running Bridge units. -7. Verify local API health, route/token authorization, open handoff counts, and patrol. -8. Keep v2 outbox/transaction artifacts from the failed attempt for manual reconciliation; do not replay them into v1 automatically. - -Rollback trigger: canonical/queue divergence that cannot be reconciled unambiguously, authorization regression, sustained API errors, or outbox retries causing consumer harm. - -## Remaining operational risks - -- Filesystem atomic rename and `flock` assume a local POSIX filesystem with correct `fsync` behavior; network filesystems need separate validation. -- The API fast path is not a scheduler. Reliable retries require the separately deployed periodic `outbox-deliver` invocation. -- Legacy notify bodies are retained for compatibility; new adapters should consume full v2 outbox events. -- Manual edits to queue views become conflicts against canonical state and are preserved as evidence, not merged automatically. -- Event deduplication is an adapter responsibility keyed by `event_id`; Bridge guarantees at-least-once, not exactly-once. -- Outbox event files are not claimed or leased. A delivered/dead-letter state cannot be regressed by a stale failure update, but multiple deliverers can still duplicate consumer delivery; deploy exactly one deliverer until a claim/lease protocol is added. diff --git a/docs/deployment.md b/docs/deployment.md deleted file mode 100644 index 5b5b1a6..0000000 --- a/docs/deployment.md +++ /dev/null @@ -1,37 +0,0 @@ -# Deployment - -## Expected deployment pieces -- repo checkout, for example `/opt/bridge` -- env file, for example `/etc/bridge/bridge.env` -- runtime directory referenced by `BRIDGE_ROOT` -- optional systemd user or system services - -## Runtime prep -```bash -cp config/bridge_api.example.env config/bridge_api.env -mkdir -p bridge/incoming bridge/outgoing bridge/archive bridge/audit -``` - -## Start local API -```bash -python3 scripts/bridge_api_server.py -``` - -## Start recipient listener -```bash -python3 scripts/bridge_intake_watch.py --agent agent-b --listen --port 8522 -``` - -## Systemd templates -Generic examples live in [`../deploy/systemd/`](../deploy/systemd/): -- `bridge-api.service` -- `bridge-intake-watch@.service` -- `example-agent.env` - -Template-specific notes remain in [`../deploy/systemd/README.md`](../deploy/systemd/README.md). - -## Event adapters -Use `BRIDGE_NOTIFY_URL_` for immediate recipient notifications. -Use `BRIDGE_NOTIFY_EVENT_COMMAND_` for read-only lifecycle consumers. - -Adapters should stay outside `bridge_core/`. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..582cf0e --- /dev/null +++ b/docs/design.md @@ -0,0 +1,97 @@ +# Design + +Bridge keeps requests in a shared filesystem and private seen lists with each +consumer. The CLI has no running service. All participating agents, including +chat-gateway agents, file, receive, and answer requests through Bridge. + +## Events and lifecycle + +A request id is `YYYYMMDD-HHMMSS--` in UTC. If a name is +already used, creation adds a numeric suffix. `open//00-.md` contains +`id`, `from`, `to`, `subject`, `status`, optional `due`, and `at` frontmatter, then +Markdown. Subsequent events contain `id`, `from`, `status`, and `at`. +The frontmatter is a flat `key: value` format, not general YAML. + +Events use `O_CREAT|O_EXCL` and explicit mode `0640`. Different authors must +compete for the same sequence number, so a writer exclusively creates a hidden +`.NN` reservation, retrying the next number on collision. It writes and flushes +the complete event there, then hard-links it as `NN-.md`. Both names refer +to the same write-once inode. Reservations stay in place; there is no lock, +lease, journal, or lock-recovery process. An interrupted unpublished reservation +leaves a harmless gap. Readers use only the published `.md` names and sort +sequence numbers numerically. The filesystem must support hard links and atomic +same-filesystem directory rename; keep `open/` and `done/` on the same filesystem. + +The latest event determines status. `open` and `working` owe the recipient; +`blocked` owes the sender until the sender answers, then the recipient; `done` +and `cancelled` owe nobody. Only the recipient sets working/blocked or closes, +and closing needs a nonempty outcome. Only the sender cancels. Either may reply +without changing status. Terminal requests cannot reopen. A close or cancel +publishes its event before renaming the folder to `done/`. Readers search both +locations and classify by status, so a crash between publication and rename +still shows a terminal request under `list --done`. The first terminal event is +final: an event a concurrent writer publishes after it is kept but flagged with +a warning, does not change status, and its writer gets a stderr warning. +Listings skip a request folder that has no published event yet or vanishes while +being read. + +## Permissions + +Use access and default ACLs to share the root with existing Unix accounts such +as `svc-a` and `svc-b`. No new group or session restart is required. An +administrator provisions the root, `agents.conf`, and ACLs before use; Bridge +never changes host permissions or installs that policy itself. + +For the root, `open/`, `done/`, and descendants, grant every participating account +`rwx` access and default directory ACLs, with no access for other users. Do not +set the sticky bit: either participant must be able to move a request directory. +New CLI directories are explicitly `0770` and new event files `0640`, even under +a restrictive umask. A default ACL entry for a peer is limited by the `0640` +file's read-only group-class mask; on a `0770` directory it retains `rwx`. +This allows reading each other's events and adding events without editing files +owned by another account. An optional setgid bit on provisioned directories can +preserve an existing group; a new group is unnecessary. + +Provision `open/.bell` once as `0660` with write access for every participating +account. If absent, the first CLI write creates it as `0660`. Subsequent writes +open/write/close the existing inode, preserving its ownership and ACL. Never +replace it atomically, because a path watcher must keep observing it. +Provision `agents.conf` as administrator-controlled and readable by writers. +Seen lists are per-agent consumer state and are never stored in the shared data +root. Their CLI-created directories and files also use `0770` and `0640`. + +These modes express cooperation, not tamper-proof isolation: shared directory +write access permits unlinking or replacing a peer's files. Write-once behavior +is a CLI convention, not a filesystem immutability guarantee. Keep backups if +you need protection from deletion. + +## Identity and trust + +`agents.conf` maps an agent id to a Unix account and optional executable/arguments. +`--as` compares the caller's real uid to that account; there is no root override. +Readers compare every event's file uid with its declared author's configured +account and flag mismatches, including unknown authors. That is account-level +provenance, not signatures. Multiple agents under one account can declare each +other's names; the `from` field is self-declared within that account. + +Do not sync request files between machines in a way that rewrites file ownership. +Remote agents can run the CLI over SSH as their configured account instead. +Treat received Markdown as request data subject to the recipient's own authority +rules. An event does not grant permission to execute its contents. + +## Wake model + +Every event write updates `open/.bell`, including replies and terminal events. +A systemd `.path`/`.service` pair can wake a consumer when this file changes. A +watch on `open/` alone misses nested reply writes. Path notifications can coalesce; +consumers query `unseen`, which excludes their own events and uses location-free +keys. Seen marks survive movement to `done/`. Consumers should process returned +snapshots and tolerate repeated delivery. + +The other participant's configured notify command is an additional doorbell. +It executes without a shell as the writer, receives a one-line pointer on stdin, +and inherits `BRIDGE_ROOT`. A site adapter can forward that pointer to any local, +remote, or chat-gateway agent runtime. It must have the needed authority already; +Bridge never switches users or provisions credentials. Failure or timeout warns +without rolling back the event. The examples leave the actual runtime adapter +to the deployment. There is no server, chat dependency, timer, or reminder patrol. diff --git a/docs/runtime-layout.md b/docs/runtime-layout.md deleted file mode 100644 index 17906c9..0000000 --- a/docs/runtime-layout.md +++ /dev/null @@ -1,43 +0,0 @@ -# Runtime Layout - -Bridge runtime state is deployment-local and created at runtime. It is **not** part of the OSS source tree. - -## Runtime directories - -Bridge uses these directories under `BRIDGE_ROOT`: - -- `incoming//` -- `outgoing//` -- `archive/` -- `audit/` - -Per-agent directories are created on demand. Bridge ships with no built-in agent IDs. - -## What lives there - -- sender outbox copies -- recipient inbox copies -- archived closed handoffs -- audit logs and patrol reminder state - -Typical examples: - -- `bridge/audit/handoff-log.md` -- `bridge/audit/patrol-reminders.json` -- `bridge/archive/HND-.../` - -## Important boundary - -Keep runtime state out of git. - -Bridge source code lives in: - -- `bridge_core/` — core Python package -- `scripts/` — CLI, API server, patrol, intake watcher, wrappers, and helpers -- `tests/` — regression and integration coverage -- `config/` — example configuration only -- `deploy/` — deployment templates -- `docs/` — architecture and deployment documentation -- `examples/` — sample handoff payloads - -Runtime state should be created by the deployment, not tracked in the repository. diff --git a/examples/agents.conf.example b/examples/agents.conf.example new file mode 100644 index 0000000..45d88ad --- /dev/null +++ b/examples/agents.conf.example @@ -0,0 +1,4 @@ +# agent Unix-account optional executable and quoted arguments (no shell) +alice svc-a +bob svc-b /srv/bridge-tools/notify-example.sh bob +ops svc-a /srv/bridge-tools/notify-example.sh ops diff --git a/examples/bridge-wake.path b/examples/bridge-wake.path new file mode 100644 index 0000000..73e517b --- /dev/null +++ b/examples/bridge-wake.path @@ -0,0 +1,9 @@ +[Unit] +Description=Watch the shared Bridge doorbell + +[Path] +PathChanged=/srv/bridge/open/.bell +Unit=bridge-wake.service + +[Install] +WantedBy=default.target diff --git a/examples/bridge-wake.service b/examples/bridge-wake.service new file mode 100644 index 0000000..32708bc --- /dev/null +++ b/examples/bridge-wake.service @@ -0,0 +1,8 @@ +[Unit] +Description=Wake a Bridge consumer with unseen events + +[Service] +Type=oneshot +# User unit: run under the Unix account configured for ops. +Environment=BRIDGE_ROOT=/srv/bridge +ExecStart=/srv/bridge-tools/notify-example.sh --unseen ops diff --git a/examples/handoffs/action-request.md b/examples/handoffs/action-request.md deleted file mode 100644 index f35bc8a..0000000 --- a/examples/handoffs/action-request.md +++ /dev/null @@ -1,33 +0,0 @@ -# Action Request Example - -```md ---- -handoff_id: HND-YYYYMMDD-HHMMSS-xxx -status: open -created_at: YYYY-MM-DDTHH:MM:SSZ -updated_at: YYYY-MM-DDTHH:MM:SSZ -sender: agent-a -recipient: agent-b -issue_type: action_request -handoff_kind: request -priority: medium -risk_level: low -due_at: none -approval_needed: no -approval_context: none -resolution_summary: pending -subject: Short request title -response_format: concise feasibility + next step -related_paths: - - /path/if/relevant ---- - -## Requested Action - -## Minimal Context - -## Constraints - -## Outcome -- pending -``` diff --git a/examples/handoffs/approval-needed-escalation.md b/examples/handoffs/approval-needed-escalation.md deleted file mode 100644 index 686d3c8..0000000 --- a/examples/handoffs/approval-needed-escalation.md +++ /dev/null @@ -1,48 +0,0 @@ -# Approval Needed Example - -```md ---- -handoff_id: HND-YYYYMMDD-HHMMSS-xxx -status: blocked -created_at: YYYY-MM-DDTHH:MM:SSZ -updated_at: YYYY-MM-DDTHH:MM:SSZ -sender: agent-a -recipient: agent-b -issue_type: approval_needed -handoff_kind: request -priority: high -risk_level: high -due_at: none -approval_needed: yes -approval_context: Human approval required before action. -resolution_summary: pending -subject: Short approval request -response_format: explicit approve/deny + optional constraints -related_paths: - - /path/if/relevant ---- - -## Decision Needed - -## Requested Action -- decide whether to approve one of options below - -## Why Approval Is Required - -## Minimal Context - -## Constraints -- do not proceed until approval arrives - -## Approval Needed - -## Options -- option A -- option B - -## Recommended Option -- one line - -## Outcome -- pending -``` diff --git a/examples/handoffs/bridge-incident.md b/examples/handoffs/bridge-incident.md deleted file mode 100644 index 33487ab..0000000 --- a/examples/handoffs/bridge-incident.md +++ /dev/null @@ -1,35 +0,0 @@ -# Bridge Incident Example - -```md ---- -handoff_id: HND-YYYYMMDD-HHMMSS-xxx -status: open -created_at: YYYY-MM-DDTHH:MM:SSZ -updated_at: YYYY-MM-DDTHH:MM:SSZ -sender: agent-a -recipient: agent-b -issue_type: bridge_incident -handoff_kind: incident -risk_level: medium -priority: medium -due_at: none -approval_needed: no -approval_context: none -resolution_summary: pending -subject: Short bridge issue summary -response_format: concise status + action + blocker if any -related_paths: - - /path/if/relevant ---- - -## Requested Action -- investigate issue and contain if safe - -## Minimal Context - -## Constraints -- none - -## Outcome -- pending -``` diff --git a/examples/handoffs/closure.md b/examples/handoffs/closure.md new file mode 100644 index 0000000..a0ee0fa --- /dev/null +++ b/examples/handoffs/closure.md @@ -0,0 +1,10 @@ +--- +id: 20300110-120000-alice-review-artifact +from: bob +status: done +at: 2030-01-10T13:00:00+00:00 +--- + +Reviewed the draft against the schema. Findings: `/srv/artifacts/review.md`. +All required fields are present. Two optional descriptions need clarification; +the review lists their locations. No publishing was performed. diff --git a/examples/handoffs/issue-handoff.md b/examples/handoffs/issue-handoff.md deleted file mode 100644 index 0d1171e..0000000 --- a/examples/handoffs/issue-handoff.md +++ /dev/null @@ -1,36 +0,0 @@ -# Issue Handoff Example - -```md ---- -handoff_id: HND-YYYYMMDD-HHMMSS-xxx -status: open -created_at: YYYY-MM-DDTHH:MM:SSZ -updated_at: YYYY-MM-DDTHH:MM:SSZ -sender: agent-a -recipient: agent-b -issue_type: incident -handoff_kind: incident -priority: high -risk_level: medium -due_at: none -approval_needed: no -approval_context: none -resolution_summary: pending -subject: Short issue title -response_format: concise status + action + blocker if any -related_paths: - - /path/if/relevant ---- - -## Requested Action -Describe exactly what help is needed. - -## Minimal Context -Only context recipient needs to act. - -## Constraints -- any policy or technical constraints - -## Outcome -- pending -``` diff --git a/examples/handoffs/request.md b/examples/handoffs/request.md new file mode 100644 index 0000000..796632d --- /dev/null +++ b/examples/handoffs/request.md @@ -0,0 +1,14 @@ +--- +id: 20300110-120000-alice-review-artifact +from: alice +to: bob +subject: Review artifact +status: open +due: 2030-01-15 +at: 2030-01-10T12:00:00+00:00 +--- + +Please review `/srv/artifacts/draft.md` for consistency with the supplied schema. +Write findings to `/srv/artifacts/review.md` and close with the result path. +Ask for missing inputs with a blocked reply. This request authorizes reading +these artifacts and writing the review; publishing requires separate approval. diff --git a/examples/handoffs/result-closure.md b/examples/handoffs/result-closure.md deleted file mode 100644 index ce75e2e..0000000 --- a/examples/handoffs/result-closure.md +++ /dev/null @@ -1,35 +0,0 @@ -# Result Closure Example - -```md ---- -handoff_id: HND-YYYYMMDD-HHMMSS-xxx -status: closed -created_at: YYYY-MM-DDTHH:MM:SSZ -updated_at: YYYY-MM-DDTHH:MM:SSZ -sender: agent-a -recipient: agent-b -issue_type: result -handoff_kind: result -priority: medium -risk_level: low -due_at: none -approval_needed: no -approval_context: none -resolution_summary: closed and communicated -subject: Short result title -response_format: n/a -related_paths: - - /path/if/relevant ---- - -## Requested Action -- communicate completed result and any residual risk - -## Minimal Context - -## Constraints -- none - -## Outcome -- closed and communicated -``` diff --git a/examples/notify-example.sh b/examples/notify-example.sh new file mode 100755 index 0000000..9afc3aa --- /dev/null +++ b/examples/notify-example.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Customize /usr/local/bin/agent-wake to your runtime's supported wake adapter. +# That site-provided executable accepts --agent ID and a single pointer argument. +# It must be callable by the writer; Bridge does not change Unix accounts. +set -eu +if [ "${1:-}" = --unseen ]; then + agent=${2:?expected agent id} + pending=$(bridge unseen --as "$agent") + [ -n "$pending" ] || exit 0 + pointer="Bridge has unseen events; run bridge unseen --as $agent, handle them, and mark the returned snapshot." +else + agent=${1:?expected agent id} + IFS= read -r pointer +fi +# Do not mark here: the receiving agent must read the events through Bridge. +exec /usr/local/bin/agent-wake --agent "$agent" "$pointer" diff --git a/pyproject.toml b/pyproject.toml index 2c36d24..26a9aa6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,33 +4,21 @@ build-backend = "setuptools.build_meta" [project] name = "agent-bridge" -version = "0.1.0" -description = "A bounded filesystem + local API bridge for explicit multi-agent handoffs." +version = "0.2.0" +description = "Shared-file requests between agents." readme = "README.md" requires-python = ">=3.10" license = { text = "Apache-2.0" } -authors = [ - { name = "Bridge contributors" } -] -keywords = ["agents", "bridge", "handoff", "local-api", "orchestration"] -classifiers = [ - "Development Status :: 3 - Alpha", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Operating System :: POSIX :: Linux", -] + +[project.scripts] +bridge = "bridge.cli:main" [project.optional-dependencies] -dev = [ - "pytest>=8,<10", -] +dev = ["pytest>=8,<10"] [tool.pytest.ini_options] testpaths = ["tests"] pythonpath = ["."] [tool.setuptools] -packages = ["bridge_core"] +packages = ["bridge"] diff --git a/scripts/bridge_agent.py b/scripts/bridge_agent.py deleted file mode 100755 index 096b2d0..0000000 --- a/scripts/bridge_agent.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import sys -from pathlib import Path - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.runtime import normalize_agent_id -from bridge_wrapper_common import api_request, archive_result, create_result, invoke, list_result, set_status_result, status_result - - -def main() -> None: - parser = argparse.ArgumentParser(description='Generic Bridge wrapper for any configured agent') - parser.add_argument('--agent', required=True, help='agent identity used for API auth and CLI fallback') - parser.add_argument('--allow-cli-fallback', action='store_true', help='allow direct bridge_cli fallback when the local API is unavailable') - sub = parser.add_subparsers(dest='cmd', required=True) - - create_parser = sub.add_parser('create') - create_parser.add_argument('--recipient', required=True) - create_parser.add_argument('--issue-type', required=True) - create_parser.add_argument('--handoff-kind', default='request', choices=['incident', 'request', 'question', 'result']) - create_parser.add_argument('--priority', default='medium', choices=['low', 'medium', 'high', 'urgent']) - create_parser.add_argument('--risk-level', default='low', choices=['low', 'medium', 'high']) - create_parser.add_argument('--due-at', default='') - create_parser.add_argument('--subject', required=True) - create_parser.add_argument('--requested-action', required=True) - create_parser.add_argument('--minimal-context', required=True) - create_parser.add_argument('--constraints', default='') - create_parser.add_argument('--response-format', default='concise status + action + blocker if any') - create_parser.add_argument('--related-path', action='append') - create_parser.add_argument('--approval-needed', action='store_true') - create_parser.add_argument('--approval-context', default='') - create_parser.add_argument('--idempotency-key') - create_parser.add_argument('--correlation-id') - create_parser.add_argument('--causation-id') - - sub.add_parser('list-open') - - status_parser = sub.add_parser('status') - status_parser.add_argument('handoff_id') - - update_parser = sub.add_parser('set-status') - update_parser.add_argument('handoff_id') - update_parser.add_argument('status', choices=['open', 'acknowledged', 'in_progress', 'blocked', 'closed', 'cancelled']) - update_parser.add_argument('--outcome', default='') - update_parser.add_argument('--expected-revision', type=int) - - ack_parser = sub.add_parser('ack') - ack_parser.add_argument('handoff_id') - ack_parser.add_argument('--expected-revision', type=int) - - block_parser = sub.add_parser('block') - block_parser.add_argument('handoff_id') - block_parser.add_argument('--outcome', required=True) - block_parser.add_argument('--expected-revision', type=int) - - close_parser = sub.add_parser('close') - close_parser.add_argument('handoff_id') - close_parser.add_argument('--outcome', required=True) - close_parser.add_argument('--expected-revision', type=int) - - cancel_parser = sub.add_parser('cancel') - cancel_parser.add_argument('handoff_id') - cancel_parser.add_argument('--reason', required=True) - cancel_parser.add_argument('--expected-revision', type=int) - - archive_parser = sub.add_parser('archive') - archive_parser.add_argument('handoff_id') - archive_parser.add_argument('--expected-revision', type=int) - - args = parser.parse_args() - agent = normalize_agent_id(args.agent) - - if args.cmd == 'create': - payload = { - 'recipient': normalize_agent_id(args.recipient, field_name='recipient'), - 'issue_type': args.issue_type, - 'handoff_kind': args.handoff_kind, - 'priority': args.priority, - 'risk_level': args.risk_level, - 'due_at': args.due_at, - 'subject': args.subject, - 'requested_action': args.requested_action, - 'minimal_context': args.minimal_context, - 'constraints': args.constraints, - 'response_format': args.response_format, - 'related_paths': args.related_path or [], - 'approval_needed': args.approval_needed, - 'approval_context': args.approval_context, - 'idempotency_key': args.idempotency_key, - 'correlation_id': args.correlation_id, - 'causation_id': args.causation_id, - } - cli_args = [ - 'create', '--sender', agent, '--recipient', payload['recipient'], '--issue-type', args.issue_type, - '--handoff-kind', args.handoff_kind, '--priority', args.priority, '--risk-level', args.risk_level, - '--subject', args.subject, '--requested-action', args.requested_action, - '--minimal-context', args.minimal_context, '--response-format', args.response_format, - ] - if args.constraints: - cli_args += ['--constraints', args.constraints] - if args.due_at: - cli_args += ['--due-at', args.due_at] - if args.approval_needed: - cli_args.append('--approval-needed') - if args.approval_context: - cli_args += ['--approval-context', args.approval_context] - for path in args.related_path or []: - cli_args += ['--related-path', path] - for option, value in ( - ('--idempotency-key', args.idempotency_key), - ('--correlation-id', args.correlation_id), - ('--causation-id', args.causation_id), - ): - if value: - cli_args += [option, value] - invoke(agent, args, api_call=lambda: create_result(api_request(agent, 'POST', '/v1/handoffs', payload=payload)), cli_args=cli_args) - elif args.cmd == 'list-open': - invoke(agent, args, api_call=lambda: list_result(agent, api_request(agent, 'GET', '/v1/handoffs?active_only=true')), cli_args=['list-open', '--agent', agent]) - elif args.cmd == 'status': - invoke(agent, args, api_call=lambda: status_result(agent, args.handoff_id, api_request(agent, 'GET', f'/v1/handoffs/{args.handoff_id}')), cli_args=['status', '--actor', agent, args.handoff_id]) - elif args.cmd == 'set-status': - payload = {'status': args.status, 'outcome': args.outcome, 'expected_revision': args.expected_revision} - cli_args = ['set-status', '--actor', agent, args.handoff_id, args.status] - if args.outcome: - cli_args += ['--outcome', args.outcome] - if args.expected_revision is not None: - cli_args += ['--expected-revision', str(args.expected_revision)] - invoke(agent, args, api_call=lambda: set_status_result(agent, api_request(agent, 'POST', f'/v1/handoffs/{args.handoff_id}/status', payload=payload)), cli_args=cli_args) - elif args.cmd == 'ack': - payload = {'expected_revision': args.expected_revision} - cli_args = ['set-status', '--actor', agent, args.handoff_id, 'acknowledged'] - if args.expected_revision is not None: - cli_args += ['--expected-revision', str(args.expected_revision)] - invoke(agent, args, api_call=lambda: set_status_result(agent, api_request(agent, 'POST', f'/v1/handoffs/{args.handoff_id}/ack', payload=payload)), cli_args=cli_args) - elif args.cmd == 'block': - payload = {'outcome': args.outcome, 'expected_revision': args.expected_revision} - cli_args = ['set-status', '--actor', agent, args.handoff_id, 'blocked', '--outcome', args.outcome] - if args.expected_revision is not None: - cli_args += ['--expected-revision', str(args.expected_revision)] - invoke(agent, args, api_call=lambda: set_status_result(agent, api_request(agent, 'POST', f'/v1/handoffs/{args.handoff_id}/block', payload=payload)), cli_args=cli_args) - elif args.cmd == 'close': - payload = {'outcome': args.outcome, 'expected_revision': args.expected_revision} - cli_args = ['set-status', '--actor', agent, args.handoff_id, 'closed', '--outcome', args.outcome] - if args.expected_revision is not None: - cli_args += ['--expected-revision', str(args.expected_revision)] - invoke(agent, args, api_call=lambda: set_status_result(agent, api_request(agent, 'POST', f'/v1/handoffs/{args.handoff_id}/close', payload=payload)), cli_args=cli_args) - elif args.cmd == 'cancel': - payload = {'outcome': args.reason, 'expected_revision': args.expected_revision} - cli_args = ['set-status', '--actor', agent, args.handoff_id, 'cancelled', '--outcome', args.reason] - if args.expected_revision is not None: - cli_args += ['--expected-revision', str(args.expected_revision)] - invoke(agent, args, api_call=lambda: set_status_result(agent, api_request(agent, 'POST', f'/v1/handoffs/{args.handoff_id}/cancel', payload=payload)), cli_args=cli_args) - elif args.cmd == 'archive': - payload = {'expected_revision': args.expected_revision} - cli_args = ['archive', '--actor', agent, args.handoff_id] - if args.expected_revision is not None: - cli_args += ['--expected-revision', str(args.expected_revision)] - invoke(agent, args, api_call=lambda: archive_result(agent, api_request(agent, 'POST', f'/v1/handoffs/{args.handoff_id}/archive', payload=payload)), cli_args=cli_args) - - -if __name__ == '__main__': - main() diff --git a/scripts/bridge_api_server.py b/scripts/bridge_api_server.py deleted file mode 100755 index 389969a..0000000 --- a/scripts/bridge_api_server.py +++ /dev/null @@ -1,473 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import json -import os -import sys -from dataclasses import asdict, dataclass -from http import HTTPStatus -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from typing import Any -from urllib.parse import parse_qs, urlparse -from urllib.request import Request, urlopen - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.auth import AuthenticationError, load_agent_tokens, resolve_agent_from_token -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.frontmatter import parse_frontmatter -from bridge_core.models import CreateHandoffInput, DEFAULT_RESPONSE_FORMAT, HandoffRecord -from bridge_core.policy import AccessPolicyError, BridgePolicyError, RoutePolicyError, StatusPolicyError, is_active_status, require_actor_access -from bridge_core.repository import HandoffNotFoundError, IdempotencyConflictError, RevisionConflictError -from bridge_core.runtime import env_key_for_agent -from bridge_core.service import BridgeService - -DEFAULT_ROOT = Path(os.environ.get("BRIDGE_PROJECT_ROOT", str(SCRIPT_ROOT))) -DEFAULT_BRIDGE_ROOT = DEFAULT_ROOT / "bridge" -DEFAULT_CONFIG_PATH = DEFAULT_ROOT / "config" / "bridge_api.env" -DEFAULT_HOST = "127.0.0.1" -DEFAULT_PORT = 8427 -DEFAULT_NOTIFY_TIMEOUT_SECONDS = 1.0 - - -@dataclass(slots=True) -class ApiContext: - bridge_root: Path - config_path: Path | None - service: BridgeService - - -class BridgeApiServer(ThreadingHTTPServer): - daemon_threads = True - allow_reuse_address = True - - def __init__(self, server_address: tuple[str, int], context: ApiContext): - super().__init__(server_address, BridgeApiHandler) - self.context = context - - -class BridgeApiHandler(BaseHTTPRequestHandler): - server: BridgeApiServer - protocol_version = "HTTP/1.1" - - def do_GET(self) -> None: - self._dispatch("GET") - - def do_POST(self) -> None: - self._dispatch("POST") - - def log_message(self, format: str, *args: object) -> None: - return - - def _dispatch(self, method: str) -> None: - try: - parsed = urlparse(self.path) - path = parsed.path.rstrip("/") or "/" - if method == "GET" and path == "/v1/health": - self._send_json(HTTPStatus.OK, {"ok": True, "service": "bridge-api"}) - return - - actor = self._authenticate() - if method == "POST" and path == "/v1/handoffs": - body = self._read_json_body() - self._handle_create(actor, body) - return - if method == "GET" and path == "/v1/handoffs": - query = parse_qs(parsed.query) - active_only = _parse_active_only(query) - self._handle_list(actor, active_only=active_only) - return - - route = _match_handoff_route(path) - if route is None: - raise ApiError(HTTPStatus.NOT_FOUND, "not_found", "unknown endpoint") - - handoff_id, action = route - if method == "GET" and action is None: - self._handle_get(actor, handoff_id) - return - if method == "POST" and action in {"ack", "block", "close", "cancel", "archive", "status"}: - body = self._read_json_body(required=False) - self._handle_action(actor, handoff_id, action, body) - return - raise ApiError(HTTPStatus.NOT_FOUND, "not_found", "unknown endpoint") - except ApiError as exc: - self._send_json(exc.status, {"error": exc.error, "detail": exc.detail}) - except Exception as exc: # pragma: no cover - defensive guard - self._send_json(HTTPStatus.INTERNAL_SERVER_ERROR, {"error": "internal_error", "detail": str(exc)}) - - def _authenticate(self) -> str: - token = self.headers.get("Authorization", "") - if token.startswith("Bearer "): - token = token[len("Bearer ") :].strip() - elif token: - raise ApiError(HTTPStatus.UNAUTHORIZED, "unauthorized", "unsupported authorization scheme") - else: - token = self.headers.get("X-Bridge-Token", "").strip() - try: - return resolve_agent_from_token(token, self.server.context.config_path) - except AuthenticationError as exc: - raise ApiError(HTTPStatus.UNAUTHORIZED, "unauthorized", str(exc)) from exc - - def _read_json_body(self, *, required: bool = True) -> dict[str, Any]: - length_header = self.headers.get("Content-Length") - if not length_header: - if required: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", "request body is required") - return {} - try: - length = int(length_header) - except ValueError as exc: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", "invalid content length") from exc - raw = self.rfile.read(length) - if not raw: - if required: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", "request body is required") - return {} - try: - payload = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", "invalid json body") from exc - if not isinstance(payload, dict): - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", "json body must be an object") - return payload - - def _handle_create(self, actor: str, body: dict[str, Any]) -> None: - sender = str(body.get("sender", actor) or actor) - if sender != actor: - body = dict(body) - body["sender"] = actor - try: - request = CreateHandoffInput( - sender=actor, - recipient=str(_require_field(body, "recipient")), - issue_type=str(_require_field(body, "issue_type")), - subject=str(_require_field(body, "subject")), - requested_action=str(_require_field(body, "requested_action")), - minimal_context=str(_require_field(body, "minimal_context")), - handoff_kind=str(body.get("handoff_kind", "request") or "request"), - priority=str(body.get("priority", "medium") or "medium"), - risk_level=str(body.get("risk_level", "low") or "low"), - due_at=str(body.get("due_at", "none") or "none"), - approval_needed=bool(body.get("approval_needed", False)), - approval_context=str(body.get("approval_context", "none") or "none"), - response_format=str(body.get("response_format") or DEFAULT_RESPONSE_FORMAT), - related_paths=_coerce_string_list(body.get("related_paths", []), field_name="related_paths"), - constraints=str(body.get("constraints", "- none") or "- none"), - idempotency_key=str(body.get("idempotency_key") or self.headers.get("Idempotency-Key") or "") or None, - correlation_id=str(body.get("correlation_id") or "") or None, - causation_id=str(body.get("causation_id") or "") or None, - ) - record = self.server.context.service.create_handoff(request) - except RoutePolicyError as exc: - raise ApiError(HTTPStatus.FORBIDDEN, "forbidden", str(exc)) from exc - except IdempotencyConflictError as exc: - raise ApiError(HTTPStatus.CONFLICT, "idempotency_conflict", str(exc)) from exc - except (BridgePolicyError, ValueError, TypeError) as exc: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", str(exc)) from exc - _deliver_pending_for_handoff(self.server.context, record.handoff_id, record.revision) - self._send_json(HTTPStatus.CREATED, _record_to_dict(record)) - - def _handle_list(self, actor: str, *, active_only: bool) -> None: - items = [_record_to_dict(record) for record in _list_visible_handoffs(self.server.context, actor=actor, active_only=active_only)] - self._send_json(HTTPStatus.OK, {"actor": actor, "items": items}) - - def _handle_get(self, actor: str, handoff_id: str) -> None: - try: - record = self.server.context.service.get_handoff(handoff_id, actor=actor) - except HandoffNotFoundError as exc: - raise ApiError(HTTPStatus.NOT_FOUND, "not_found", str(exc)) from exc - except AccessPolicyError as exc: - raise ApiError(HTTPStatus.FORBIDDEN, "forbidden", str(exc)) from exc - self._send_json(HTTPStatus.OK, _record_to_dict(record)) - - def _handle_action(self, actor: str, handoff_id: str, action: str, body: dict[str, Any]) -> None: - try: - if action == "archive": - archive_dir = self.server.context.service.archive_handoff( - handoff_id, - actor=actor, - expected_revision=self._expected_revision(body), - ) - record = self.server.context.service.get_handoff(handoff_id, actor=actor) - payload = _record_to_dict(record) - payload["archive_path"] = str(archive_dir) - _deliver_pending_for_handoff(self.server.context, record.handoff_id, record.revision) - self._send_json(HTTPStatus.OK, payload) - return - if action == "status": - status_name = str(_require_field(body, "status")) - else: - status_name = { - "ack": "acknowledged", - "block": "blocked", - "close": "closed", - "cancel": "cancelled", - }[action] - outcome = str(body.get("outcome", "") or "") - acknowledgment_source = None - if status_name == "acknowledged": - acknowledgment_source = str(body.get("ack_source") or body.get("acknowledgment_source") or "manual") - record = self.server.context.service.set_status( - handoff_id, - actor=actor, - status=status_name, - outcome=outcome, - acknowledgment_source=acknowledgment_source, - expected_revision=self._expected_revision(body), - ) - except HandoffNotFoundError as exc: - raise ApiError(HTTPStatus.NOT_FOUND, "not_found", str(exc)) from exc - except AccessPolicyError as exc: - raise ApiError(HTTPStatus.FORBIDDEN, "forbidden", str(exc)) from exc - except RevisionConflictError as exc: - raise ApiError(HTTPStatus.CONFLICT, "revision_conflict", str(exc)) from exc - except StatusPolicyError as exc: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", str(exc)) from exc - _deliver_pending_for_handoff(self.server.context, record.handoff_id, record.revision) - self._send_json(HTTPStatus.OK, _record_to_dict(record)) - - def _expected_revision(self, body: dict[str, Any]) -> int | None: - value: object | None = body.get("expected_revision") - if value is None: - raw = self.headers.get("If-Match", "").strip() - if raw: - value = raw.removeprefix("W/").strip().strip('"') - if value in (None, ""): - return None - try: - return int(str(value)) - except ValueError as exc: - raise ApiError(HTTPStatus.BAD_REQUEST, "bad_request", "expected_revision/If-Match must be an integer") from exc - - def _send_json(self, status: HTTPStatus, payload: dict[str, Any]) -> None: - data = json.dumps(payload, sort_keys=True).encode("utf-8") - try: - self.send_response(int(status)) - self.send_header("Content-Type", "application/json; charset=utf-8") - self.send_header("Content-Length", str(len(data))) - self.send_header("Cache-Control", "no-store") - self.end_headers() - self.wfile.write(data) - except (BrokenPipeError, ConnectionResetError): - return - - -class ApiError(Exception): - def __init__(self, status: HTTPStatus, error: str, detail: str): - super().__init__(detail) - self.status = status - self.error = error - self.detail = detail - - -def _match_handoff_route(path: str) -> tuple[str, str | None] | None: - parts = [part for part in path.split("/") if part] - if len(parts) == 3 and parts[:2] == ["v1", "handoffs"]: - return parts[2], None - if len(parts) == 4 and parts[:2] == ["v1", "handoffs"]: - return parts[2], parts[3] - return None - - -def _parse_active_only(query: dict[str, list[str]]) -> bool: - raw = (query.get("active_only") or ["true"])[0].strip().lower() - return raw not in {"0", "false", "no", "off"} - - -def _require_field(body: dict[str, Any], field_name: str) -> Any: - value = body.get(field_name) - if value is None: - raise ValueError(f"missing required field: {field_name}") - if isinstance(value, str) and not value.strip(): - raise ValueError(f"missing required field: {field_name}") - return value - - -def _coerce_string_list(value: Any, *, field_name: str) -> list[str]: - if value in (None, ""): - return [] - if not isinstance(value, list): - raise ValueError(f"{field_name} must be a list") - return [str(item) for item in value] - - -def _record_to_dict(record: HandoffRecord) -> dict[str, Any]: - payload = asdict(record) - payload["related_paths"] = list(record.related_paths) - return payload - - -def _list_visible_handoffs(context: ApiContext, *, actor: str, active_only: bool) -> list[HandoffRecord]: - candidates: dict[str, HandoffRecord] = {} - visible_roots = [ - context.bridge_root / "incoming" / actor, - context.bridge_root / "outgoing" / actor, - ] - for root in visible_roots: - if not root.exists(): - continue - for path in sorted(root.glob("*.md")): - record = _record_from_path(path) - if active_only and not is_active_status(record.status): - continue - candidates.setdefault(record.handoff_id, record) - if not active_only: - archive_root = context.bridge_root / "archive" - if archive_root.exists(): - for path in sorted(archive_root.glob("*/*.md")): - record = _record_from_path(path) - try: - require_actor_access(actor, record.sender, record.recipient) - except AccessPolicyError: - continue - candidates.setdefault(record.handoff_id, record) - return sorted(candidates.values(), key=lambda record: (record.updated_at, record.handoff_id), reverse=True) - - -def _record_from_path(path: Path) -> HandoffRecord: - data, body = parse_frontmatter(path.read_text(encoding="utf-8", errors="replace")) - return HandoffRecord.from_mapping(data, body) - - -def _notify_agent( - context: ApiContext, - *, - target_agent: str, - payload: dict[str, Any], - event_id: str = "", -) -> tuple[bool, str]: - notify_url = os.environ.get(env_key_for_agent("BRIDGE_NOTIFY_URL_", target_agent), "").strip() - if not notify_url: - return False, f"no notify endpoint configured for {target_agent}" - token = load_agent_tokens(context.config_path).get(target_agent, "") - if not token: - return False, f"no token configured for {target_agent}" - request = Request( - notify_url, - method="POST", - data=json.dumps(payload).encode("utf-8"), - headers={ - "Accept": "application/json", - "Authorization": f"Bearer {token}", - "Content-Type": "application/json", - **({"X-Bridge-Event-ID": event_id} if event_id else {}), - }, - ) - try: - with urlopen(request, timeout=DEFAULT_NOTIFY_TIMEOUT_SECONDS): - return True, "delivered" - except Exception as exc: - return False, str(exc) - - -def _deliver_pending_for_handoff(context: ApiContext, handoff_id: str, revision: int) -> None: - candidates = [ - event - for event in context.service.list_outbox(states={"pending", "retrying"}) - if event.handoff_id == handoff_id and event.revision == revision and event.due() - ] - for event in candidates: - ok, detail = _notify_agent( - context, - target_agent=event.target_agent, - payload=_legacy_notify_payload(event), - event_id=event.event_id, - ) - if ok: - context.service._mark_event_delivered(event) - else: - context.service._mark_event_failed( - event, - detail, - max_attempts=int(os.environ.get("BRIDGE_OUTBOX_MAX_ATTEMPTS", "8")), - base_delay_seconds=float(os.environ.get("BRIDGE_OUTBOX_BASE_DELAY_SECONDS", "1")), - max_delay_seconds=float(os.environ.get("BRIDGE_OUTBOX_MAX_DELAY_SECONDS", "300")), - ) - - -def _legacy_notify_payload(event) -> dict[str, Any]: - if event.event_type == "handoff_created": - return { - "handoff_id": event.handoff_id, - "recipient": event.recipient, - "sender": event.sender, - "subject": event.subject, - "trigger": event.event_type, - } - if event.event_type in {"handoff_closed", "handoff_blocked"}: - return { - "trigger": event.event_type, - "handoff_id": event.handoff_id, - "sender": event.sender, - "recipient": event.recipient, - "actor": event.actor, - "status": event.status, - "subject": event.subject, - "resolution_summary": event.resolution_summary, - } - payload = event.to_dict() - payload["trigger"] = event.event_type - return payload - - -def build_server( - *, - host: str = DEFAULT_HOST, - port: int = DEFAULT_PORT, - bridge_root: Path | str = DEFAULT_BRIDGE_ROOT, - config_path: Path | str | None = DEFAULT_CONFIG_PATH, -) -> BridgeApiServer: - repository = FileBridgeRepository(bridge_root=Path(bridge_root)) - repository.recover_transactions() - context = ApiContext( - bridge_root=repository.bridge_root, - config_path=Path(config_path) if config_path is not None else None, - service=BridgeService(repository), - ) - return BridgeApiServer((host, port), context) - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description="Bridge Phase 3 local stdlib API server") - parser.add_argument("--host", default=os.environ.get("BRIDGE_API_HOST", DEFAULT_HOST)) - parser.add_argument("--port", type=int, default=int(os.environ.get("BRIDGE_API_PORT", str(DEFAULT_PORT)))) - parser.add_argument( - "--bridge-root", - default=os.environ.get("BRIDGE_ROOT", str(DEFAULT_BRIDGE_ROOT)), - ) - parser.add_argument( - "--config", - default=os.environ.get("BRIDGE_API_CONFIG", str(DEFAULT_CONFIG_PATH)), - ) - return parser.parse_args() - - -def main() -> None: - args = parse_args() - server = build_server( - host=args.host, - port=args.port, - bridge_root=args.bridge_root, - config_path=args.config, - ) - print(json.dumps({ - "host": args.host, - "port": server.server_port, - "bridge_root": str(server.context.bridge_root), - "config": str(server.context.config_path) if server.context.config_path is not None else None, - })) - try: - server.serve_forever() - except KeyboardInterrupt: - pass - finally: - server.server_close() - - -if __name__ == "__main__": - main() diff --git a/scripts/bridge_audit_view.py b/scripts/bridge_audit_view.py deleted file mode 100755 index 651dde1..0000000 --- a/scripts/bridge_audit_view.py +++ /dev/null @@ -1,284 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -from datetime import datetime, timezone -import os -from pathlib import Path -import sys - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.models import ACTIVE_STATUSES, now_iso -from bridge_core.policy import allowed_routes -from bridge_core.runtime import discover_agents -from bridge_core.tooling import LoadedHandoff, load_archive_entry, summarize_handoffs - -ROOT = Path(os.environ.get('BRIDGE_PROJECT_ROOT', str(SCRIPT_ROOT))) -BRIDGE = Path(os.environ.get('BRIDGE_ROOT', str(ROOT / 'bridge'))) -OUTPUT = Path(os.environ.get('BRIDGE_AUDIT_OUTPUT', str(BRIDGE / 'audit' / 'Bridge Audit View.md'))) -ARCHIVE_OUTPUT = Path(os.environ.get('BRIDGE_ARCHIVE_OUTPUT', str(BRIDGE / 'audit' / 'Bridge Archive Index.md'))) -ACTIVE = set(ACTIVE_STATUSES) -ARCHIVE_LIMIT = 25 - - -def parse_iso_datetime(value: str): - try: - return datetime.fromisoformat((value or '').replace('Z', '+00:00')) - except Exception: - return None - - -def age_hours(updated_at: str) -> str: - try: - dt = parse_iso_datetime(updated_at) - if dt is None: - raise ValueError('missing datetime') - delta = datetime.now(timezone.utc) - dt - return f'{delta.total_seconds()/3600.0:.1f}h' - except Exception: - return 'unknown' - - -def route_label(item: LoadedHandoff) -> str: - return f'{item.record.sender or "?"} → {item.record.recipient or "?"}' - - -def resolution_summary_for(item: LoadedHandoff) -> str: - summary = (item.record.resolution_summary or '').strip() - if summary: - return summary - marker = '## Outcome\n' - if marker in item.body: - outcome = item.body.split(marker, 1)[1].strip() - if outcome: - first_line = outcome.splitlines()[0].strip() - if first_line: - return first_line.lstrip('- ').strip() - return 'pending' - - -def archived_sort_key(item: LoadedHandoff): - updated = parse_iso_datetime(item.record.updated_at) - if updated is not None: - return updated - return datetime.min.replace(tzinfo=timezone.utc) - - -def active_sort_key(item: LoadedHandoff): - updated = parse_iso_datetime(item.record.updated_at) - if updated is not None: - return updated - return datetime.max.replace(tzinfo=timezone.utc) - - -def priority_risk_label(item: LoadedHandoff) -> str: - parts = [] - if item.record.priority and item.record.priority.lower() != 'none': - parts.append(item.record.priority) - if item.record.risk_level and item.record.risk_level.lower() != 'none': - parts.append(f'{item.record.risk_level}-risk') - return ' / '.join(parts) - - -def bullet_core(item: LoadedHandoff, include_updated: bool = True) -> str: - hid = item.record.handoff_id or item.path.stem - details = [f'`{hid}`', f'**{item.record.status or "?"}**'] - pr = priority_risk_label(item) - if pr: - details.append(pr) - details.extend([route_label(item), item.record.subject or '(no subject)']) - if include_updated: - updated = item.record.updated_at or '?' - details.append(f'updated `{updated}` ({age_hours(updated) if updated != "?" else "unknown"})') - return '- ' + ' — '.join(details) - - -def bullet_for(item: LoadedHandoff): - return bullet_core(item, include_updated=True) - - -def archive_bullet_for(item: LoadedHandoff): - hid = item.record.handoff_id or item.path.stem - details = [f'`{hid}`', '**archived**'] - pr = priority_risk_label(item) - if pr: - details.append(pr) - details.extend([ - route_label(item), - item.record.subject or '(no subject)', - f'archived `{item.record.updated_at or "?"}`', - resolution_summary_for(item), - ]) - if item.archive_file_count > 1: - details.append(f'preserved copies: {item.archive_file_count}') - return '- ' + ' — '.join(details) - - -def build_archive_index(archived): - recent = archived[:ARCHIVE_LIMIT] - by_route = {} - for item in recent: - by_route.setdefault(route_label(item), []).append(item) - - lines = [ - '# Bridge Archive Index', - '', - f'> Auto-generated from `{ROOT}` for human audit. Edit source scripts, not this note.', - '', - f'- Last refreshed: `{now_iso()}`', - f'- Archived handoffs included: **{len(recent)}**', - '', - '## Recent Closures', - ] - if not recent: - lines.append('- none') - else: - lines.extend(archive_bullet_for(item) for item in recent) - - lines += ['', '## By Route'] - if not by_route: - lines.append('- none') - else: - for route in sorted(by_route): - lines += ['', f'### {route}'] - lines.extend(archive_bullet_for(item) for item in by_route[route]) - return '\n'.join(lines) + '\n' - - -def main(): - agents = list(discover_agents(bridge_root=BRIDGE)) - incoming = {agent: summarize_handoffs((BRIDGE / 'incoming' / agent).glob('*.md')) for agent in agents} - archived = [] - for directory in sorted((BRIDGE / 'archive').glob('HND-*'), reverse=True): - item = load_archive_entry(directory) - if item: - archived.append(item) - archived.sort(key=archived_sort_key, reverse=True) - archived = archived[:ARCHIVE_LIMIT] - - now = datetime.now(timezone.utc) - active_items = [item for bucket in incoming.values() for item in bucket if item.record.status in ACTIVE] - oldest_active = min(active_items, key=active_sort_key) if active_items else None - blocked_items = [item for item in active_items if item.record.status == 'blocked'] - urgent_high_items = [item for item in active_items if (item.record.priority or '').strip().lower() in {'urgent', 'high'}] - recent_closures = [] - for item in archived: - updated_dt = parse_iso_datetime(item.record.updated_at) - if updated_dt is not None and (now - updated_dt).total_seconds() <= 24 * 3600: - recent_closures.append(item) - - route_violations = [] - stale = [] - routes = allowed_routes() - for bucket in incoming.values(): - for item in bucket: - if routes and (item.record.sender, item.record.recipient) not in routes: - route_violations.append(item) - if item.record.status in ACTIVE: - dt = parse_iso_datetime(item.record.updated_at) - if dt is not None: - hours = (now - dt).total_seconds() / 3600.0 - if hours > 24: - stale.append((hours, item)) - stale.sort(reverse=True, key=lambda entry: entry[0]) - - open_counts = {agent: sum(1 for item in bucket if item.record.status in ACTIVE) for agent, bucket in incoming.items()} - total_open = sum(open_counts.values()) - needs_attention = [] - seen_attention = set() - for item in blocked_items + urgent_high_items + [entry[1] for entry in stale] + route_violations: - hid = item.record.handoff_id or item.path.stem - if hid not in seen_attention: - seen_attention.add(hid) - needs_attention.append(item) - oldest_summary = ( - f'`{oldest_active.record.handoff_id or oldest_active.path.stem}` ({age_hours(oldest_active.record.updated_at)})' - if oldest_active else 'none' - ) - agent_summary_lines = [f'- `{agent}` inbox active: **{open_counts.get(agent, 0)}**' for agent in agents] or ['- No agents discovered yet'] - - lines = [ - '# Bridge Audit View', - '', - f'> Auto-generated from `{ROOT}` for human audit. Edit source scripts, not this note.', - '', - f'- Last refreshed: `{now_iso()}`', - f'- Total active handoffs: **{total_open}**', - *agent_summary_lines, - f'- Oldest active handoff: {oldest_summary}', - f'- Blocked handoffs: **{len(blocked_items)}**', - f'- Urgent/high priority active: **{len(urgent_high_items)}**', - f'- Closures in last 24h: **{len(recent_closures)}**', - '', - '## Current Health', - f'- Route violations: **{len(route_violations)}**' if route_violations else '- Route violations: none', - f'- Stale active handoffs (>24h): **{len(stale)}**' if stale else '- Stale active handoffs (>24h): none', - '', - '## Needs Attention', - ] - if not needs_attention: - lines.append('- none') - else: - lines.extend(bullet_for(item) for item in needs_attention) - - lines += ['', '## Blocked Handoffs'] - if not blocked_items: - lines.append('- none') - else: - lines.extend(bullet_for(item) for item in blocked_items) - - lines += ['', '## Oldest Active Handoff'] - lines.append('- none' if oldest_active is None else bullet_for(oldest_active)) - - lines += ['', '## Recent Closures (24h)'] - if not recent_closures: - lines.append('- none') - else: - lines.extend(archive_bullet_for(item) for item in recent_closures) - - for agent in agents: - lines += ['', f'## {agent} Inbox'] - bucket = [item for item in incoming.get(agent, []) if item.record.status in ACTIVE] - if not bucket: - lines.append('- none') - else: - lines.extend(bullet_for(item) for item in bucket) - - lines += ['', '## Route Violations'] - if not route_violations: - lines.append('- none') - else: - lines.extend(bullet_for(item) for item in route_violations) - - lines += ['', '## Stale Active Handoffs (>24h)'] - if not stale: - lines.append('- none') - else: - lines.extend(bullet_for(item) for _hours, item in stale) - - lines += ['', '## Recent Archived Handoffs'] - if not archived: - lines.append('- none') - else: - lines.extend(archive_bullet_for(item) for item in archived[:10]) - - lines += [ - '', - '## Quick Commands', - '- `python3 ./scripts/bridge_agent.py --agent list-open`', - '- `python3 ./scripts/bridge_agent.py --agent create --recipient ...`', - '- `python3 ./scripts/bridge_patrol.py --stuck-hours 24` # built-in 0.5h active unresolved alert + reminder/escalation checks', - ] - - OUTPUT.write_text('\n'.join(lines) + '\n', encoding='utf-8') - OUTPUT.chmod(0o600) - ARCHIVE_OUTPUT.write_text(build_archive_index(archived), encoding='utf-8') - ARCHIVE_OUTPUT.chmod(0o600) - print(f'wrote {OUTPUT}') - print(f'wrote {ARCHIVE_OUTPUT}') - - -if __name__ == '__main__': - main() diff --git a/scripts/bridge_cli.py b/scripts/bridge_cli.py deleted file mode 100755 index 19cb9f3..0000000 --- a/scripts/bridge_cli.py +++ /dev/null @@ -1,359 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import json -import os -import sys -from pathlib import Path -from urllib.request import Request, urlopen - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.frontmatter import FrontmatterError, parse_frontmatter as core_parse_frontmatter -from bridge_core.models import ALL_STATUSES, ACTIVE_STATUSES, CreateHandoffInput, HandoffRecord -from bridge_core.policy import RoutePolicyError, require_actor_access, require_route, visible_queues_for_actor -from bridge_core.repository import HandoffNotFoundError -from bridge_core.auth import load_agent_tokens -from bridge_core.runtime import configured_values, env_key_for_agent -from bridge_core.service import BridgeService - -ROOT = Path(os.environ.get('BRIDGE_PROJECT_ROOT', str(SCRIPT_ROOT))) -BRIDGE = Path(os.environ.get('BRIDGE_ROOT', str(ROOT / 'bridge'))) -AUDIT = BRIDGE / 'audit' / 'handoff-log.md' - - -def repository() -> FileBridgeRepository: - return FileBridgeRepository(bridge_root=BRIDGE) - - -def service() -> BridgeService: - return BridgeService(repository()) - - -def validate_route(sender, recipient): - try: - require_route(sender, recipient) - except RoutePolicyError as exc: - raise SystemExit(str(exc)) from exc - - -def parse_frontmatter(text): - normalized = text.replace('\r\n', '\n') - if not normalized.startswith('---\n'): - raise SystemExit('missing frontmatter') - try: - return core_parse_frontmatter(normalized) - except FrontmatterError as exc: - raise SystemExit(str(exc)) from exc - - -def _outbox_path(handoff_id: str, sender: str) -> Path: - return BRIDGE / 'outgoing' / sender / f'{handoff_id}.md' - - -def _inbox_path(handoff_id: str, recipient: str) -> Path: - return BRIDGE / 'incoming' / recipient / f'{handoff_id}.md' - - -def _load_records(handoff_id: str): - try: - return repository().load_records(handoff_id) - except HandoffNotFoundError as exc: - raise SystemExit(str(exc)) from exc - - -def _primary_record(handoff_id: str) -> HandoffRecord: - try: - return service().get_handoff(handoff_id) - except HandoffNotFoundError as exc: - raise SystemExit(str(exc)) from exc - - -def create(args): - validate_route(args.sender, args.recipient) - request = CreateHandoffInput( - sender=args.sender, - recipient=args.recipient, - issue_type=args.issue_type, - subject=args.subject, - requested_action=args.requested_action, - minimal_context=args.minimal_context, - handoff_kind=args.handoff_kind, - priority=args.priority, - risk_level=args.risk_level, - due_at=args.due_at or 'none', - approval_needed=bool(args.approval_needed), - approval_context=args.approval_context or 'none', - response_format=args.response_format, - related_paths=args.related_path or [], - constraints=args.constraints or '- none', - idempotency_key=getattr(args, 'idempotency_key', None), - correlation_id=getattr(args, 'correlation_id', None), - causation_id=getattr(args, 'causation_id', None), - ) - try: - record = service().create_handoff(request) - except (ValueError, TypeError) as exc: - raise SystemExit(str(exc)) from exc - print(json.dumps({ - 'handoff_id': record.handoff_id, - 'outbox': str(_outbox_path(record.handoff_id, record.sender)), - 'inbox': str(_inbox_path(record.handoff_id, record.recipient)), - 'revision': record.revision, - }, indent=2)) - - -def status(args): - records = _load_records(args.handoff_id) - primary = records[0].record - try: - require_actor_access(args.actor, primary.sender, primary.recipient) - except ValueError as exc: - raise SystemExit(str(exc)) from exc - - visible_targets = visible_queues_for_actor( - actor=args.actor, - sender=primary.sender, - recipient=primary.recipient, - handoff_id=args.handoff_id, - ) - visible_paths = [] - for stored in records: - relative_path = stored.path.relative_to(BRIDGE).as_posix() - if relative_path in visible_targets or relative_path.startswith(f'archive/{args.handoff_id}/'): - visible_paths.append(str(stored.path)) - print(json.dumps({ - 'handoff_id': args.handoff_id, - 'actor': args.actor, - 'paths': visible_paths, - 'statuses': sorted({stored.record.status for stored in records}), - 'revisions': sorted({stored.record.revision for stored in records}), - }, indent=2)) - - -def list_open(args): - try: - items = service().list_open_handoffs(args.agent) - except ValueError as exc: - raise SystemExit(str(exc)) from exc - payload = [ - { - 'path': str(_inbox_path(item.handoff_id, args.agent)), - 'status': item.status, - 'subject': item.subject, - 'sender': item.sender, - 'recipient': item.recipient, - } - for item in items - if item.status in ACTIVE_STATUSES - ] - print(json.dumps(payload, indent=2)) - - -def set_status(args): - try: - record = service().set_status( - args.handoff_id, - actor=args.actor, - status=args.status, - outcome=args.outcome, - expected_revision=getattr(args, 'expected_revision', None), - ) - except (HandoffNotFoundError, ValueError) as exc: - raise SystemExit(str(exc)) from exc - print(json.dumps({'handoff_id': record.handoff_id, 'actor': args.actor, 'status': record.status, 'revision': record.revision}, indent=2)) - - -def archive(args): - try: - archive_dir = service().archive_handoff( - args.handoff_id, - actor=args.actor, - expected_revision=getattr(args, 'expected_revision', None), - ) - except (HandoffNotFoundError, ValueError) as exc: - raise SystemExit(str(exc)) from exc - print(json.dumps({'handoff_id': args.handoff_id, 'actor': args.actor, 'archive_dir': str(archive_dir)}, indent=2)) - - -def outbox_list(args): - states = set(args.state) if args.state else None - print(json.dumps([event.to_dict() for event in service().list_outbox(states=states)], indent=2, sort_keys=True)) - - -def outbox_replay(args: argparse.Namespace) -> None: - event = service().replay_event(args.event_id) - print(json.dumps(event.to_dict(), indent=2, sort_keys=True)) - - -def outbox_resolve_transaction(args: argparse.Namespace) -> None: - event = service().resolve_transaction( - args.event_id, - action=args.action, - reason=args.reason, - force_recoverable_discard=args.force_recoverable_discard, - ) - print( - json.dumps( - {"event": event.to_dict(), "action": args.action, "reason": args.reason}, - indent=2, - sort_keys=True, - ) - ) - - -def reconcile(args): - repo = repository() - if args.handoff_id: - result = {args.handoff_id: repo.reconcile_handoff(args.handoff_id, repair=not args.check_only)} - else: - ids = {path.stem for path in repo.records_root.glob('*.md')} - ids.update(path.stem for path in BRIDGE.glob('incoming/*/*.md')) - ids.update(path.stem for path in BRIDGE.glob('outgoing/*/*.md')) - result = {handoff_id: repo.reconcile_handoff(handoff_id, repair=not args.check_only) for handoff_id in sorted(ids)} - print(json.dumps(result, indent=2, sort_keys=True)) - - -def recover_outbox(_args): - recovered = repository().recover_transactions() - print(json.dumps({'recovered_event_ids': recovered}, indent=2, sort_keys=True)) - - -def deliver_outbox(args): - repo = repository() - bridge_service = BridgeService(repo) - config_path = Path(os.environ['BRIDGE_API_CONFIG']) if os.environ.get('BRIDGE_API_CONFIG') else ROOT / 'config' / 'bridge_api.env' - os.environ.setdefault('BRIDGE_API_CONFIG', str(config_path)) - values = configured_values() - tokens = load_agent_tokens(config_path) - - def deliver(event): - url = values.get(env_key_for_agent('BRIDGE_NOTIFY_URL_', event.target_agent), '').strip() - token = tokens.get(event.target_agent, '') - if not url: - return False, f'no notify endpoint configured for {event.target_agent}' - if not token: - return False, f'no token configured for {event.target_agent}' - request = Request( - url, - method='POST', - data=json.dumps(event.to_dict(), sort_keys=True).encode('utf-8'), - headers={ - 'Accept': 'application/json', - 'Authorization': f'Bearer {token}', - 'Content-Type': 'application/json', - 'X-Bridge-Event-ID': event.event_id, - }, - ) - try: - with urlopen(request, timeout=args.timeout): - return True, 'delivered' - except Exception as exc: - return False, str(exc) - - processed = bridge_service.process_outbox( - deliver, - limit=args.limit, - max_attempts=args.max_attempts, - base_delay_seconds=args.base_delay_seconds, - max_delay_seconds=args.max_delay_seconds, - ) - print(json.dumps([event.to_dict() for event in processed], indent=2, sort_keys=True)) - - -def main(): - p = argparse.ArgumentParser(description='Agent bridge helper') - sub = p.add_subparsers(dest='cmd', required=True) - - c = sub.add_parser('create') - c.add_argument('--sender', required=True) - c.add_argument('--recipient', required=True) - c.add_argument('--issue-type', required=True) - c.add_argument('--handoff-kind', default='request', choices=['incident', 'request', 'question', 'result']) - c.add_argument('--priority', default='medium', choices=['low', 'medium', 'high', 'urgent']) - c.add_argument('--risk-level', default='low', choices=['low', 'medium', 'high']) - c.add_argument('--due-at', default='') - c.add_argument('--subject', required=True) - c.add_argument('--requested-action', required=True) - c.add_argument('--minimal-context', required=True) - c.add_argument('--constraints', default='') - c.add_argument('--response-format', default='concise status + action + blocker if any') - c.add_argument('--related-path', action='append') - c.add_argument('--approval-needed', action='store_true') - c.add_argument('--approval-context', default='') - c.add_argument('--idempotency-key') - c.add_argument('--correlation-id') - c.add_argument('--causation-id') - c.set_defaults(func=create) - - s = sub.add_parser('status') - s.add_argument('--actor', required=True) - s.add_argument('handoff_id') - s.set_defaults(func=status) - - l = sub.add_parser('list-open') - l.add_argument('--agent', required=True) - l.set_defaults(func=list_open) - - u = sub.add_parser('set-status') - u.add_argument('--actor', required=True) - u.add_argument('handoff_id') - u.add_argument('status', choices=sorted(ALL_STATUSES)) - u.add_argument('--outcome', default='') - u.add_argument('--expected-revision', type=int) - u.set_defaults(func=set_status) - - a = sub.add_parser('archive') - a.add_argument('--actor', required=True) - a.add_argument('handoff_id') - a.add_argument('--expected-revision', type=int) - a.set_defaults(func=archive) - - ol = sub.add_parser('outbox-list') - ol.add_argument('--state', action='append', choices=['pending', 'retrying', 'delivered', 'dead_letter']) - ol.set_defaults(func=outbox_list) - - replay_parser = sub.add_parser("outbox-replay", help="Replay an event without changing its event ID") - replay_parser.add_argument("event_id") - replay_parser.set_defaults(func=outbox_replay) - - resolve_parser = sub.add_parser( - "outbox-resolve-transaction", - help="Explicitly enqueue or discard a prepared transaction with audit evidence", - ) - resolve_parser.add_argument("event_id") - resolve_parser.add_argument("--action", choices=("enqueue", "discard"), required=True) - resolve_parser.add_argument("--reason", required=True) - resolve_parser.add_argument( - "--force-recoverable-discard", - action="store_true", - help="Permit discard even when canonical state still matches and automatic recovery is safe", - ) - resolve_parser.set_defaults(func=outbox_resolve_transaction) - - rec = sub.add_parser('reconcile') - rec.add_argument('handoff_id', nargs='?') - rec.add_argument('--check-only', action='store_true') - rec.set_defaults(func=reconcile) - - recover = sub.add_parser('outbox-recover') - recover.set_defaults(func=recover_outbox) - - deliver = sub.add_parser('outbox-deliver') - deliver.add_argument('--limit', type=int, default=100) - deliver.add_argument('--timeout', type=float, default=2.0) - deliver.add_argument('--max-attempts', type=int, default=int(os.environ.get('BRIDGE_OUTBOX_MAX_ATTEMPTS', '8'))) - deliver.add_argument('--base-delay-seconds', type=float, default=float(os.environ.get('BRIDGE_OUTBOX_BASE_DELAY_SECONDS', '1'))) - deliver.add_argument('--max-delay-seconds', type=float, default=float(os.environ.get('BRIDGE_OUTBOX_MAX_DELAY_SECONDS', '300'))) - deliver.set_defaults(func=deliver_outbox) - - args = p.parse_args() - args.func(args) - - -if __name__ == '__main__': - main() diff --git a/scripts/bridge_intake_watch.py b/scripts/bridge_intake_watch.py deleted file mode 100755 index bc43ab4..0000000 --- a/scripts/bridge_intake_watch.py +++ /dev/null @@ -1,454 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import json -import os -import shlex -import subprocess -import sys -import time -from http import HTTPStatus -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from typing import Any - -from pathlib import Path - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.auth import AuthenticationError, require_agent_token -from bridge_core.runtime import env_key_for_agent, normalize_agent_id -from bridge_wrapper_common import api_request, token_config_path - - -DEFAULT_POLL_INTERVAL = 60.0 -DEFAULT_NOTIFY_HOST = '127.0.0.1' -DEFAULT_NOTIFY_PORT = 0 -DEFAULT_NOTIFY_PATH = '/notify' -LIFECYCLE_NOTIFY_TRIGGERS = {'handoff_closed', 'handoff_blocked'} -EVENT_COMMAND_TIMEOUT_SECONDS = 30.0 - - -def _event_command_env_var(agent: str) -> str: - return env_key_for_agent('BRIDGE_NOTIFY_EVENT_COMMAND_', agent) - - -def _intake_event_command_env_var(agent: str) -> str: - return env_key_for_agent('BRIDGE_INTAKE_EVENT_COMMAND_', agent) - - -class IntakeNotifyServer(ThreadingHTTPServer): - daemon_threads = True - allow_reuse_address = True - - def __init__( - self, - server_address: tuple[str, int], - *, - agent: str, - dry_run: bool, - event_command: str | None = None, - intake_event_command: str | None = None, - ): - super().__init__(server_address, IntakeNotifyHandler) - self.agent = agent - self.dry_run = dry_run - self.event_command = event_command or None - self.intake_event_command = intake_event_command or None - - -class IntakeNotifyHandler(BaseHTTPRequestHandler): - server: IntakeNotifyServer - protocol_version = 'HTTP/1.1' - - def do_GET(self) -> None: - if self.path.rstrip('/') == '/health': - self._send_json(HTTPStatus.OK, {'ok': True, 'service': 'bridge-intake-watch', 'agent': self.server.agent}) - return - self._send_json(HTTPStatus.NOT_FOUND, {'error': 'not_found', 'detail': 'unknown endpoint'}) - - def do_POST(self) -> None: - if self.path.rstrip('/') != DEFAULT_NOTIFY_PATH: - self._send_json(HTTPStatus.NOT_FOUND, {'error': 'not_found', 'detail': 'unknown endpoint'}) - return - try: - self._authenticate() - event = self._read_json_body() - actions = handle_notify_event( - self.server.agent, - event, - dry_run=self.server.dry_run, - event_command=self.server.event_command, - intake_event_command=self.server.intake_event_command, - ) - except AuthenticationError as exc: - self._send_json(HTTPStatus.UNAUTHORIZED, {'error': 'unauthorized', 'detail': str(exc)}) - return - except ValueError as exc: - self._send_json(HTTPStatus.BAD_REQUEST, {'error': 'bad_request', 'detail': str(exc)}) - return - except SystemExit as exc: - self._send_json(HTTPStatus.BAD_GATEWAY, {'error': 'intake_failed', 'detail': str(exc)}) - return - payload = {'agent': self.server.agent, 'actions': actions, 'trigger': 'notify', 'event': event} - _emit(payload) - self._send_json(HTTPStatus.OK, payload) - - def log_message(self, format: str, *args: object) -> None: - return - - def _authenticate(self) -> None: - token = self.headers.get('Authorization', '') - if token.startswith('Bearer '): - token = token[len('Bearer ') :].strip() - elif token: - raise AuthenticationError('unsupported authorization scheme') - else: - token = self.headers.get('X-Bridge-Token', '').strip() - require_agent_token(self.server.agent, token, token_config_path()) - - def _read_json_body(self) -> dict[str, Any]: - length_header = self.headers.get('Content-Length', '').strip() - if not length_header: - return {} - try: - length = int(length_header) - except ValueError as exc: - raise ValueError('invalid content length') from exc - raw = self.rfile.read(length) - if not raw: - return {} - try: - payload = json.loads(raw.decode('utf-8')) - except (UnicodeDecodeError, json.JSONDecodeError) as exc: - raise ValueError('invalid json body') from exc - if not isinstance(payload, dict): - raise ValueError('json body must be an object') - return payload - - def _send_json(self, status: HTTPStatus, payload: dict[str, Any]) -> None: - data = json.dumps(payload, sort_keys=True).encode('utf-8') - try: - self.send_response(int(status)) - self.send_header('Content-Type', 'application/json; charset=utf-8') - self.send_header('Content-Length', str(len(data))) - self.send_header('Cache-Control', 'no-store') - self.end_headers() - self.wfile.write(data) - except (BrokenPipeError, ConnectionResetError): - # The Bridge API posts notify events with a short timeout and does not - # need the response body after the event command has completed. Avoid - # noisy tracebacks when the client closes first. - return - - -def build_notify_server( - *, - agent: str, - host: str = DEFAULT_NOTIFY_HOST, - port: int = DEFAULT_NOTIFY_PORT, - dry_run: bool = False, - event_command: str | None = None, - intake_event_command: str | None = None, -) -> IntakeNotifyServer: - return IntakeNotifyServer( - (host, port), - agent=agent, - dry_run=dry_run, - event_command=event_command, - intake_event_command=intake_event_command, - ) - - -def list_active_handoffs(agent: str) -> list[dict[str, Any]]: - payload = api_request(agent, 'GET', '/v1/handoffs?active_only=true') - items = payload.get('items', []) - if not isinstance(items, list): - raise SystemExit('bridge API returned invalid handoff list payload') - normalized: list[dict[str, Any]] = [] - for item in items: - if isinstance(item, dict): - normalized.append(item) - return normalized - - -def acknowledge_open_handoff(agent: str, handoff_id: str) -> dict[str, Any]: - payload = api_request(agent, 'POST', f'/v1/handoffs/{handoff_id}/ack', payload={'ack_source': 'auto'}) - if not isinstance(payload, dict): - raise SystemExit(f'bridge API returned invalid ack payload for {handoff_id}') - return payload - - -def _resolve_event_command(agent: str, event_command: str | None = None) -> str | None: - if event_command: - command = event_command.strip() - return command or None - scoped = os.getenv(_event_command_env_var(agent), '').strip() - if scoped: - return scoped - generic = os.getenv('BRIDGE_NOTIFY_EVENT_COMMAND', '').strip() - return generic or None - - -def _resolve_intake_event_command(agent: str, intake_event_command: str | None = None) -> str | None: - if intake_event_command: - command = intake_event_command.strip() - return command or None - scoped = os.getenv(_intake_event_command_env_var(agent), '').strip() - if scoped: - return scoped - generic = os.getenv('BRIDGE_INTAKE_EVENT_COMMAND', '').strip() - return generic or None - - -def _run_event_command( - agent: str, - event: dict[str, Any], - *, - event_command: str, - env_prefix: str = 'BRIDGE_NOTIFY', - action: str = 'event_command', - raise_on_failure: bool = True, -) -> dict[str, Any]: - handoff_id = str(event.get('handoff_id', '') or '') - trigger = str(event.get('trigger', '') or '') - argv = shlex.split(event_command) - if not argv: - raise SystemExit('event command resolved to empty argv') - env = os.environ.copy() - env.update({ - f'{env_prefix}_AGENT': agent, - f'{env_prefix}_TRIGGER': trigger, - f'{env_prefix}_HANDOFF_ID': handoff_id, - f'{env_prefix}_EVENT_JSON': json.dumps(event, sort_keys=True), - }) - try: - completed = subprocess.run( - argv, - input=json.dumps(event, sort_keys=True), - text=True, - capture_output=True, - timeout=EVENT_COMMAND_TIMEOUT_SECONDS, - env=env, - check=False, - ) - except subprocess.TimeoutExpired as exc: - detail = f'timed out after {EVENT_COMMAND_TIMEOUT_SECONDS:g}s' - if raise_on_failure: - raise SystemExit(f'event command failed for {trigger or "unknown"}: {detail}') from exc - return { - 'agent': agent, - 'handoff_id': handoff_id, - 'trigger': trigger, - 'action': action, - 'exit_code': None, - 'error': detail, - } - if completed.returncode != 0: - stderr = (completed.stderr or '').strip() - stdout = (completed.stdout or '').strip() - detail = stderr or stdout or f'exit {completed.returncode}' - if raise_on_failure: - raise SystemExit(f'event command failed for {trigger or "unknown"}: {detail}') - return { - 'agent': agent, - 'handoff_id': handoff_id, - 'trigger': trigger, - 'action': action, - 'exit_code': completed.returncode, - 'error': detail, - } - return { - 'agent': agent, - 'handoff_id': handoff_id, - 'trigger': trigger, - 'action': action, - 'exit_code': completed.returncode, - } - - -def _build_acknowledged_event(agent: str, source: dict[str, Any], acked: dict[str, Any]) -> dict[str, Any]: - return { - 'trigger': 'handoff_acknowledged', - 'handoff_id': str(acked.get('handoff_id', '') or source.get('handoff_id', '') or ''), - 'sender': str(acked.get('sender', '') or source.get('sender', '') or ''), - 'recipient': str(acked.get('recipient', '') or source.get('recipient', '') or agent), - 'actor': agent, - 'status': str(acked.get('status', '') or 'acknowledged'), - 'subject': str(acked.get('subject', '') or source.get('subject', '') or ''), - 'acknowledgment_source': str(acked.get('acknowledgment_source', '') or 'auto'), - } - - -def _run_intake_event_command(agent: str, source: dict[str, Any], acked: dict[str, Any], *, intake_event_command: str) -> dict[str, Any]: - event = _build_acknowledged_event(agent, source, acked) - return _run_event_command( - agent, - event, - event_command=intake_event_command, - env_prefix='BRIDGE_INTAKE', - action='intake_event_command', - raise_on_failure=False, - ) - - - -def handle_notify_event( - agent: str, - event: dict[str, Any], - *, - dry_run: bool = False, - event_command: str | None = None, - intake_event_command: str | None = None, -) -> list[dict[str, Any]]: - trigger = str(event.get('trigger', '') or '') - if trigger in LIFECYCLE_NOTIFY_TRIGGERS: - resolved_command = _resolve_event_command(agent, event_command) - if not resolved_command: - return [] - if dry_run: - return [{ - 'agent': agent, - 'handoff_id': str(event.get('handoff_id', '') or ''), - 'trigger': trigger, - 'action': 'would_run_event_command', - }] - return [_run_event_command(agent, event, event_command=resolved_command)] - return intake_once( - agent, - dry_run=dry_run, - intake_event_command=intake_event_command, - ) - - -def intake_once(agent: str, *, dry_run: bool = False, intake_event_command: str | None = None) -> list[dict[str, Any]]: - actions: list[dict[str, Any]] = [] - resolved_intake_command = _resolve_intake_event_command(agent, intake_event_command) - for item in list_active_handoffs(agent): - handoff_id = str(item.get('handoff_id', '') or '') - if not handoff_id: - continue - if str(item.get('recipient', '') or '') != agent: - continue - if str(item.get('status', '') or '') != 'open': - continue - subject = str(item.get('subject', '') or '') - if dry_run: - actions.append({ - 'agent': agent, - 'handoff_id': handoff_id, - 'status': 'open', - 'subject': subject, - 'action': 'would_acknowledge', - }) - if resolved_intake_command: - actions.append({ - 'agent': agent, - 'handoff_id': handoff_id, - 'trigger': 'handoff_acknowledged', - 'action': 'would_run_intake_event_command', - }) - continue - acked = acknowledge_open_handoff(agent, handoff_id) - actions.append({ - 'agent': agent, - 'handoff_id': handoff_id, - 'status': str(acked.get('status', '')), - 'ack_source': str(acked.get('acknowledgment_source', '')), - 'subject': subject, - 'action': 'acknowledged', - }) - if resolved_intake_command: - actions.append(_run_intake_event_command(agent, item, acked, intake_event_command=resolved_intake_command)) - return actions - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser(description='Poll the Bridge API and promptly acknowledge new handoffs for one agent.') - parser.add_argument('--agent', required=True) - parser.add_argument('--poll-interval', type=float, default=DEFAULT_POLL_INTERVAL) - parser.add_argument('--once', action='store_true', help='run one intake pass and exit') - parser.add_argument('--dry-run', action='store_true', help='report open handoffs without acknowledging them') - parser.add_argument('--listen', action='store_true', help='serve an immediate notify endpoint in addition to the polling loop') - parser.add_argument('--host', default=DEFAULT_NOTIFY_HOST, help='host to bind the notify endpoint to') - parser.add_argument('--port', type=int, default=DEFAULT_NOTIFY_PORT, help='port to bind the notify endpoint to') - parser.add_argument( - '--event-command', - default='', - help='optional command to run for handoff_closed/handoff_blocked lifecycle events; receives event JSON on stdin', - ) - parser.add_argument( - '--intake-event-command', - default='', - help='optional command to run after auto-acknowledging a new handoff; receives handoff_acknowledged JSON on stdin', - ) - return parser.parse_args() - - -def _emit(payload: dict[str, Any]) -> None: - print(json.dumps(payload, sort_keys=True), flush=True) - - -def _run_poll_loop( - agent: str, - *, - dry_run: bool, - once: bool, - poll_interval: float, - intake_event_command: str | None = None, -) -> None: - while True: - actions = intake_once(agent, dry_run=dry_run, intake_event_command=intake_event_command) - _emit({ - 'agent': agent, - 'checked_at': int(time.time()), - 'actions': actions, - }) - if once: - return - time.sleep(poll_interval) - - -def main() -> None: - args = parse_args() - args.agent = normalize_agent_id(args.agent) - poll_interval = max(args.poll_interval, 1.0) - event_command = _resolve_event_command(args.agent, args.event_command) - intake_event_command = _resolve_intake_event_command(args.agent, args.intake_event_command) - if args.listen: - server = build_notify_server( - agent=args.agent, - host=args.host, - port=args.port, - dry_run=args.dry_run, - event_command=event_command, - intake_event_command=intake_event_command, - ) - _emit({ - 'agent': args.agent, - 'notify_url': f'http://{args.host}:{server.server_port}{DEFAULT_NOTIFY_PATH}', - 'health_url': f'http://{args.host}:{server.server_port}/health', - 'mode': 'notify', - 'event_command_configured': bool(event_command), - 'intake_event_command_configured': bool(intake_event_command), - }) - try: - server.serve_forever() - except KeyboardInterrupt: - return - finally: - server.server_close() - return - _run_poll_loop( - args.agent, - dry_run=args.dry_run, - once=args.once, - poll_interval=poll_interval, - intake_event_command=intake_event_command, - ) - - -if __name__ == '__main__': - main() - diff --git a/scripts/bridge_patrol.py b/scripts/bridge_patrol.py deleted file mode 100755 index 03e2364..0000000 --- a/scripts/bridge_patrol.py +++ /dev/null @@ -1,463 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import json -import os -import subprocess -from datetime import datetime, timezone -from pathlib import Path -import sys -from urllib.error import HTTPError, URLError -from urllib.request import Request, urlopen - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.models import ACTIVE_STATUSES -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.policy import allowed_routes -from bridge_core.runtime import discover_agents, env_key_for_agent -from bridge_core.tooling import summarize_handoffs - -ROOT = Path(os.environ.get('BRIDGE_PROJECT_ROOT', str(SCRIPT_ROOT))) -BRIDGE = Path(os.environ.get('BRIDGE_ROOT', str(ROOT / 'bridge'))) -CONFIG = Path(os.environ.get('BRIDGE_API_CONFIG', str(ROOT / 'config' / 'bridge_api.env'))) -EXPECTED_DIR_MODE = '700' -EXPECTED_FILE_MODE = '600' -EXPECTED_SCRIPT_MODE = '700' -DEFAULT_API_URL = 'http://127.0.0.1:8427/v1/health' -DEFAULT_SYSTEMD_UNIT = 'bridge-api.service' -DEFAULT_REMINDER_AFTER_HOURS = 0.5 -DEFAULT_REMINDER_REPEAT_HOURS = 2.0 -DEFAULT_ESCALATE_AFTER_HOURS = 6.0 -DEFAULT_ESCALATE_REPEAT_HOURS = 24.0 -DEFAULT_ACTIVE_ALERT_HOURS = 0.5 -DEFAULT_NOTIFY_TIMEOUT_SECONDS = 1.0 -PATROL_STATE_PATH = Path(os.environ.get('BRIDGE_PATROL_STATE_PATH', str(BRIDGE / 'audit' / 'patrol-reminders.json'))) -ACTIVE = set(ACTIVE_STATUSES) -FOLLOW_UP_STATUSES = {'open', 'acknowledged', 'in_progress', 'blocked'} -SUMMARY_PLACEHOLDERS = {'', 'pending', 'none', 'n/a', 'na'} - - -def unresolved_follow_up_reason(record) -> str | None: - if record.status == 'open': - if record.acknowledged_at == 'none': - return 'unacknowledged_open_handoff' - return None - if record.status in FOLLOW_UP_STATUSES: - return f'unresolved_{record.status}_handoff' - return None - - -def resolution_summary_state(record) -> str: - summary = (record.resolution_summary or '').strip() - lowered = summary.lower() - if lowered in SUMMARY_PLACEHOLDERS: - return 'pending' - if 'actively investigating' in lowered or lowered.startswith('investigating'): - return 'investigating' - return 'actionable' - - -def needs_active_alert(record) -> tuple[bool, str]: - summary_state = resolution_summary_state(record) - reason = unresolved_follow_up_reason(record) - if reason is None: - return False, summary_state - return summary_state != 'actionable', summary_state - - -def iso_to_dt(value: str): - return datetime.fromisoformat(value.replace('Z', '+00:00')) - - -def mode_str(path: Path): - return oct(path.stat().st_mode & 0o777)[2:] - - -def bridge_api_health_url() -> str: - base = os.environ.get('BRIDGE_PATROL_API_URL') - if base: - return base - if CONFIG.exists(): - values = _read_env_file(CONFIG) - host = values.get('BRIDGE_API_HOST', '127.0.0.1') - port = values.get('BRIDGE_API_PORT', '8427') - return f'http://{host}:{port}/v1/health' - return DEFAULT_API_URL - - -def bridge_systemd_unit() -> str: - return os.environ.get('BRIDGE_PATROL_SYSTEMD_UNIT', DEFAULT_SYSTEMD_UNIT) - - -def patrol_state_path() -> Path: - override = os.environ.get('BRIDGE_PATROL_STATE_PATH', '').strip() - if override: - return Path(override) - return PATROL_STATE_PATH - - -def _read_env_file(path: Path) -> dict[str, str]: - values: dict[str, str] = {} - for raw in path.read_text(encoding='utf-8').splitlines(): - line = raw.strip() - if not line or line.startswith('#') or '=' not in line: - continue - key, value = line.split('=', 1) - values[key.strip()] = value.strip() - return values - - -def _load_runtime_config() -> dict[str, str]: - values: dict[str, str] = {} - if CONFIG.exists(): - values.update(_read_env_file(CONFIG)) - for key, value in os.environ.items(): - if key.startswith('BRIDGE_'): - values[key] = value - return values - - -def _float_setting(key: str, default: float) -> float: - runtime = _load_runtime_config() - raw = str(runtime.get(key, default)).strip() - try: - return float(raw) - except ValueError: - return default - - -def load_patrol_state(path: Path) -> dict[str, dict[str, object]]: - if not path.exists(): - return {} - try: - payload = json.loads(path.read_text(encoding='utf-8')) - except (OSError, json.JSONDecodeError): - return {} - if not isinstance(payload, dict): - return {} - normalized: dict[str, dict[str, object]] = {} - for handoff_id, item in payload.items(): - if isinstance(handoff_id, str) and isinstance(item, dict): - normalized[handoff_id] = dict(item) - return normalized - - -def save_patrol_state(path: Path, state: dict[str, dict[str, object]]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(json.dumps(state, indent=2, sort_keys=True) + '\n', encoding='utf-8') - path.chmod(0o600) - - -def notify_recipient(url: str, *, token: str, payload: dict[str, object]) -> tuple[bool, str]: - request = Request( - url, - method='POST', - data=json.dumps(payload, sort_keys=True).encode('utf-8'), - headers={ - 'Accept': 'application/json', - 'Authorization': f'Bearer {token}', - 'Content-Type': 'application/json', - }, - ) - try: - with urlopen(request, timeout=DEFAULT_NOTIFY_TIMEOUT_SECONDS) as response: - status = int(getattr(response, 'status', 200)) - return 200 <= status < 300, f'notify status={status}' - except HTTPError as exc: - return False, f'notify failed status={exc.code}' - except (URLError, TimeoutError, OSError) as exc: - return False, f'notify failed ({exc})' - - -def maybe_trigger_ack_reminder( - record, - *, - now: datetime, - runtime_config: dict[str, str], - state: dict[str, dict[str, object]], - reminder_after_hours: float, - reminder_repeat_hours: float, -) -> tuple[bool, str | None]: - reason = unresolved_follow_up_reason(record) - if reason is None or not record.updated_at: - return False, None - age_hours = (now - iso_to_dt(record.updated_at)).total_seconds() / 3600.0 - if age_hours < reminder_after_hours: - return False, None - reminder_state = state.setdefault(record.handoff_id, {}) - last_reminded_at = str(reminder_state.get('last_reminded_at', '') or '') - if last_reminded_at: - elapsed = (now - iso_to_dt(last_reminded_at)).total_seconds() / 3600.0 - if elapsed < reminder_repeat_hours: - return False, None - notify_url = runtime_config.get(env_key_for_agent('BRIDGE_NOTIFY_URL_', record.recipient), '').strip() - token = runtime_config.get(env_key_for_agent('BRIDGE_TOKEN_', record.recipient), '').strip() - if not notify_url: - return False, f'reminder skipped for {record.handoff_id}: no notify endpoint configured for {record.recipient}' - if not token: - return False, f'reminder skipped for {record.handoff_id}: no token configured for {record.recipient}' - reminded_at = now.replace(microsecond=0).isoformat().replace('+00:00', 'Z') - ok, detail = notify_recipient( - notify_url, - token=token, - payload={ - 'trigger': 'handoff_reminder', - 'reason': reason, - 'handoff_id': record.handoff_id, - 'recipient': record.recipient, - 'sender': record.sender, - 'subject': record.subject, - 'status': record.status, - 'age_hours': round(age_hours, 2), - 'reminder_after_hours': reminder_after_hours, - }, - ) - if not ok: - return False, f'reminder notify failed for {record.handoff_id}: {detail}' - reminder_state['last_reminded_at'] = reminded_at - reminder_state['reminder_count'] = int(reminder_state.get('reminder_count', 0) or 0) + 1 - reminder_state['last_reminder_detail'] = detail - return True, ( - f'reminder sent for {record.handoff_id} to {record.recipient} ' - f'status={record.status} age={age_hours:.1f}h count={reminder_state["reminder_count"]}' - ) - - -def maybe_mark_escalation( - record, - *, - now: datetime, - state: dict[str, dict[str, object]], - escalate_after_hours: float, - escalate_repeat_hours: float, -) -> str | None: - reason = unresolved_follow_up_reason(record) - if reason is None or not record.updated_at: - return None - age_hours = (now - iso_to_dt(record.updated_at)).total_seconds() / 3600.0 - if age_hours < escalate_after_hours: - return None - reminder_state = state.setdefault(record.handoff_id, {}) - escalated_at = str(reminder_state.get('escalated_at', '') or '') - if escalated_at: - elapsed = (now - iso_to_dt(escalated_at)).total_seconds() / 3600.0 - if elapsed < escalate_repeat_hours: - return None - mark = now.replace(microsecond=0).isoformat().replace('+00:00', 'Z') - reminder_state['escalated_at'] = mark - reminder_state['escalation_count'] = int(reminder_state.get('escalation_count', 0) or 0) + 1 - return ( - f'escalation: unresolved {record.status} handoff for {record.recipient}: {record.handoff_id} ' - f'age={age_hours:.1f}h subject={record.subject or "(no subject)"}' - ) - - -def check_systemd_service(unit: str) -> tuple[str, str]: - try: - proc = subprocess.run( - ['systemctl', '--user', 'is-active', unit], - capture_output=True, - text=True, - timeout=10, - check=False, - ) - except FileNotFoundError: - return 'warning', 'systemctl not available for bridge API check' - except subprocess.TimeoutExpired: - return 'warning', f'systemd check timed out for {unit}' - state = (proc.stdout or proc.stderr or '').strip() or 'unknown' - if proc.returncode == 0 and state == 'active': - return 'ok', f'{unit} active' - return 'warning', f'{unit} not active ({state})' - - -def check_api_health(url: str) -> tuple[str, str]: - try: - with urlopen(url, timeout=5) as response: - payload = json.loads(response.read().decode('utf-8')) - if payload.get('ok') is True: - return 'ok', f'bridge API health ok at {url}' - return 'warning', f'bridge API unhealthy payload at {url}' - except (URLError, TimeoutError, OSError, json.JSONDecodeError) as exc: - return 'warning', f'bridge API health failed at {url} ({exc})' - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument('--stuck-hours', type=float, default=24.0) - ap.add_argument('--active-alert-hours', type=float, default=_float_setting('BRIDGE_PATROL_ACTIVE_ALERT_HOURS', DEFAULT_ACTIVE_ALERT_HOURS)) - ap.add_argument('--reminder-after-hours', type=float, default=_float_setting('BRIDGE_PATROL_REMINDER_AFTER_HOURS', DEFAULT_REMINDER_AFTER_HOURS)) - ap.add_argument('--reminder-repeat-hours', type=float, default=_float_setting('BRIDGE_PATROL_REMINDER_REPEAT_HOURS', DEFAULT_REMINDER_REPEAT_HOURS)) - ap.add_argument('--escalate-after-hours', type=float, default=_float_setting('BRIDGE_PATROL_ESCALATE_AFTER_HOURS', DEFAULT_ESCALATE_AFTER_HOURS)) - ap.add_argument('--escalate-repeat-hours', type=float, default=_float_setting('BRIDGE_PATROL_ESCALATE_REPEAT_HOURS', DEFAULT_ESCALATE_REPEAT_HOURS)) - ap.add_argument('--outbox-pending-seconds', type=float, default=_float_setting('BRIDGE_PATROL_OUTBOX_PENDING_SECONDS', 300.0)) - args = ap.parse_args() - - now = datetime.now(timezone.utc) - warnings = [] - checks = [] - evidence = [] - runtime_config = _load_runtime_config() - state_path = patrol_state_path() - reminder_state = load_patrol_state(state_path) - state_changed = False - - critical_dirs = [ - ROOT, - ROOT / 'bridge', - ROOT / 'bridge' / 'incoming', - ROOT / 'bridge' / 'outgoing', - ROOT / 'bridge' / 'archive', - ROOT / 'bridge' / 'audit', - ROOT / 'scripts', - ROOT / 'docs', - ROOT / 'examples', - ] - agents = list(discover_agents(bridge_root=BRIDGE, config_values=runtime_config)) - for agent in agents: - critical_dirs.append(ROOT / 'bridge' / 'incoming' / agent) - critical_dirs.append(ROOT / 'bridge' / 'outgoing' / agent) - for directory in critical_dirs: - checks.append(f'checked dir {directory}') - if not directory.exists(): - warnings.append(f'missing dir: {directory}') - elif mode_str(directory) != EXPECTED_DIR_MODE: - warnings.append(f'bad mode {mode_str(directory)} on {directory}') - - if not CONFIG.exists(): - warnings.append(f'missing config file: {CONFIG}') - elif mode_str(CONFIG) != EXPECTED_FILE_MODE: - warnings.append(f'bad mode {mode_str(CONFIG)} on {CONFIG}') - else: - checks.append(f'checked config {CONFIG}') - - md_files = [path for path in ROOT.glob('**/*.md') if '.pytest_cache' not in path.parts] - for file_path in md_files: - if mode_str(file_path) != EXPECTED_FILE_MODE: - warnings.append(f'bad mode {mode_str(file_path)} on {file_path}') - - py_files = list((ROOT / 'scripts').glob('*.py')) - for file_path in py_files: - if mode_str(file_path) != EXPECTED_SCRIPT_MODE: - warnings.append(f'bad mode {mode_str(file_path)} on {file_path}') - - unit = bridge_systemd_unit() - service_state, service_message = check_systemd_service(unit) - checks.append(f'checked systemd user unit {unit}') - evidence.append(service_message) - if service_state != 'ok': - warnings.append(service_message) - - health_url = bridge_api_health_url() - api_state, api_message = check_api_health(health_url) - checks.append(f'checked API health {health_url}') - evidence.append(api_message) - if api_state != 'ok': - warnings.append(api_message) - - summarized = list(summarize_handoffs(BRIDGE.glob('incoming/*/*.md'))) - open_counts = {agent: 0 for agent in agents} - routes = allowed_routes() - for item in summarized: - record = item.record - if routes and (record.sender, record.recipient) not in routes: - warnings.append(f'disallowed route in {item.path}: {record.sender}->{record.recipient}') - if record.recipient in open_counts and record.status in ACTIVE: - open_counts[record.recipient] += 1 - if record.updated_at: - age_hours = (now - iso_to_dt(record.updated_at)).total_seconds() / 3600.0 - should_alert, summary_state = needs_active_alert(record) - if should_alert and age_hours > max(args.active_alert_hours, 0.0): - warnings.append( - f'active unresolved handoff for {record.recipient}: {record.handoff_id} ' - f'age={age_hours:.1f}h status={record.status} summary={summary_state} ' - f'subject={record.subject or "(no subject)"}' - ) - if age_hours > args.stuck_hours: - warnings.append( - f'stale {record.status} handoff for {record.recipient}: {item.path.name} age={age_hours:.1f}h subject={record.subject or "(no subject)"}' - ) - reminded, reminder_message = maybe_trigger_ack_reminder( - record, - now=now, - runtime_config=runtime_config, - state=reminder_state, - reminder_after_hours=max(args.reminder_after_hours, 0.0), - reminder_repeat_hours=max(args.reminder_repeat_hours, 0.0), - ) - if reminder_message: - evidence.append(reminder_message) - if reminded: - state_changed = True - escalation_warning = maybe_mark_escalation( - record, - now=now, - state=reminder_state, - escalate_after_hours=max(args.escalate_after_hours, 0.0), - escalate_repeat_hours=max(args.escalate_repeat_hours, 0.0), - ) - if escalation_warning: - warnings.append(escalation_warning) - state_changed = True - - repository_diagnostics = FileBridgeRepository(BRIDGE, initialize=False).diagnose( - pending_age_seconds=max(args.outbox_pending_seconds, 0.0) - ) - warnings.extend(repository_diagnostics) - evidence.append(f'bridge v2 diagnostics issues={len(repository_diagnostics)}') - - active_ids = {item.record.handoff_id for item in summarized if item.record.status in ACTIVE} - stale_state_keys = [handoff_id for handoff_id in reminder_state if handoff_id not in active_ids] - for handoff_id in stale_state_keys: - reminder_state.pop(handoff_id, None) - state_changed = True - - if state_changed: - save_patrol_state(state_path, reminder_state) - - open_count_summary = ' '.join(f'{agent}={open_counts[agent]}' for agent in agents) if agents else 'none' - evidence.append(f'open counts {open_count_summary}') - evidence.append(f'markdown files checked={len(md_files)}') - evidence.append(f'script files checked={len(py_files)}') - evidence.append( - 'ack reminder policy ' - f"after={max(args.reminder_after_hours, 0.0):.2f}h " - f"repeat={max(args.reminder_repeat_hours, 0.0):.2f}h " - f"escalate={max(args.escalate_after_hours, 0.0):.2f}h " - f"repeat={max(args.escalate_repeat_hours, 0.0):.2f}h" - ) - evidence.append(f'active handoff alert threshold={max(args.active_alert_hours, 0.0):.2f}h') - - status = 'ok' if not warnings else 'warning' - escalation = '- none' if not warnings else '- review warnings; tighten or triage as needed' - next_step = '- none' if not warnings else '- inspect stale handoffs, service health, or permission drift' - - print(f'status: {status}') - print('scope: bridge patrol') - print('checks:') - for item in checks[:12]: - print(f'- {item}') - if len(checks) > 12: - print(f'- ... ({len(checks) - 12} more checks)') - print('actions_taken:') - print('- scanned bridge directories, markdown files, and incoming handoffs') - print('- checked route policy, Bridge API health, service state, file permission posture, mirrors/revisions, outbox, idempotency indexes, active handoff aging, and unresolved-handoff reminders') - print('evidence:') - for item in evidence: - print(f'- {item}') - for item in warnings[:8]: - print(f'- {item}') - if len(warnings) > 8: - print(f'- ... ({len(warnings) - 8} more warnings)') - print('escalation:') - print(escalation) - print('next_suggested_step:') - print(next_step) - - -if __name__ == '__main__': - main() diff --git a/scripts/bridge_rotate_tokens.py b/scripts/bridge_rotate_tokens.py deleted file mode 100755 index a7d4339..0000000 --- a/scripts/bridge_rotate_tokens.py +++ /dev/null @@ -1,128 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import argparse -import os -import secrets -import shutil -import subprocess -import sys -from datetime import datetime, timezone -from pathlib import Path - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) - -from bridge_core.runtime import TOKEN_ENV_PREFIX, normalize_agent_env_suffix - -DEFAULT_ROOT = Path(__file__).resolve().parents[1] -DEFAULT_CONFIG = Path(os.environ.get('BRIDGE_API_CONFIG', str(DEFAULT_ROOT / 'config' / 'bridge_api.env'))) -DEFAULT_SERVICE = 'bridge-api.service' - - -def now_stamp() -> str: - return datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S') - - -def read_env_file(path: Path) -> list[str]: - if not path.exists(): - raise SystemExit(f'config not found: {path}') - return path.read_text(encoding='utf-8').splitlines() - - -def token_key(agent: str) -> str: - normalized = normalize_agent_env_suffix(agent) - return f"{TOKEN_ENV_PREFIX}{normalized.replace('-', '_').upper()}" - - -def discover_agents(lines: list[str]) -> tuple[str, ...]: - agents: list[str] = [] - for line in lines: - stripped = line.strip() - if not stripped.startswith(TOKEN_ENV_PREFIX) or '=' not in stripped: - continue - key = stripped.split('=', 1)[0] - agent = normalize_agent_env_suffix(key[len(TOKEN_ENV_PREFIX):]) - if agent not in agents: - agents.append(agent) - return tuple(agents) - - -def rotate_lines(lines: list[str], agents: set[str]) -> list[str]: - rotated = set() - output: list[str] = [] - normalized_agents = {normalize_agent_env_suffix(agent) for agent in agents} - for line in lines: - replaced = False - for agent in normalized_agents: - key = token_key(agent) - if line.startswith(f'{key}='): - output.append(f'{key}={secrets.token_urlsafe(32)}') - rotated.add(agent) - replaced = True - break - if not replaced: - output.append(line) - missing = [agent for agent in sorted(normalized_agents) if agent not in rotated] - if missing: - if output and output[-1] != '': - output.append('') - for agent in missing: - output.append(f'{token_key(agent)}={secrets.token_urlsafe(32)}') - if output and output[-1] != '': - output.append('') - return output - - -def backup_path(config: Path) -> Path: - return config.with_name(f'{config.name}.bak-{now_stamp()}') - - -def restart_service(unit: str) -> None: - subprocess.run(['systemctl', '--user', 'restart', unit], check=True, timeout=30) - subprocess.run(['systemctl', '--user', 'is-active', unit], check=True, timeout=30, capture_output=True, text=True) - - -def main() -> None: - parser = argparse.ArgumentParser(description='Rotate Bridge API tokens safely without echoing secret values') - parser.add_argument('--config', default=str(DEFAULT_CONFIG)) - parser.add_argument('--service', default=DEFAULT_SERVICE) - parser.add_argument('--agents', nargs='+', default=['all'], help='agent ids to rotate, or all') - parser.add_argument('--no-restart', action='store_true') - parser.add_argument('--dry-run', action='store_true') - args = parser.parse_args() - - config = Path(args.config) - lines = read_env_file(config) - available_agents = discover_agents(lines) - selected = set(available_agents if 'all' in args.agents else [normalize_agent_env_suffix(agent) for agent in args.agents]) - new_lines = rotate_lines(lines, selected) - backup = backup_path(config) - - if args.dry_run: - print('dry_run: yes') - print(f'config: {config}') - print(f'backup_would_be: {backup}') - print(f'agents: {", ".join(sorted(selected))}') - print(f'restart_service: {"no" if args.no_restart else args.service}') - return - - shutil.copy2(config, backup) - backup.chmod(0o600) - config.write_text('\n'.join(new_lines), encoding='utf-8') - config.chmod(0o600) - - restarted = False - if not args.no_restart: - restart_service(args.service) - restarted = True - - print(f'rotated_agents: {", ".join(sorted(selected))}') - print(f'config: {config}') - print(f'backup: {backup}') - print(f'service_restarted: {"yes" if restarted else "no"}') - - -if __name__ == '__main__': - main() diff --git a/scripts/bridge_wrapper_common.py b/scripts/bridge_wrapper_common.py deleted file mode 100755 index 8f7f6e5..0000000 --- a/scripts/bridge_wrapper_common.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python3 -from __future__ import annotations - -import json -import os -import subprocess -import sys -from argparse import Namespace -from pathlib import Path - -SCRIPT_ROOT = Path(__file__).resolve().parents[1] -if str(SCRIPT_ROOT) not in sys.path: - sys.path.insert(0, str(SCRIPT_ROOT)) -from typing import Any -from urllib.error import HTTPError, URLError -from urllib.request import Request, urlopen - -from bridge_core.auth import load_agent_tokens -from bridge_core.runtime import env_key_for_agent - -DEFAULT_ROOT = Path(os.environ.get('BRIDGE_PROJECT_ROOT', str(SCRIPT_ROOT))) -DEFAULT_API_URL = 'http://127.0.0.1:8427' -DEFAULT_CONFIG_PATH = DEFAULT_ROOT / 'config' / 'bridge_api.env' -CLI_PATH = DEFAULT_ROOT / 'scripts' / 'bridge_cli.py' - - -def _is_truthy(value: str | None) -> bool: - return str(value or '').strip().lower() in {'1', 'true', 'yes', 'on'} - - -def api_url() -> str: - return os.environ.get('BRIDGE_WRAPPER_API_URL') or os.environ.get('BRIDGE_API_URL') or DEFAULT_API_URL - - -def token_config_path() -> Path | None: - raw = os.environ.get('BRIDGE_WRAPPER_TOKEN_FILE') or os.environ.get('BRIDGE_API_CONFIG') - if raw: - return Path(raw) - return DEFAULT_CONFIG_PATH - - -def bridge_root() -> Path: - return Path(os.environ.get('BRIDGE_ROOT', str(DEFAULT_ROOT / 'bridge'))) - - -def allow_cli_fallback(args: Namespace) -> bool: - return bool(getattr(args, 'allow_cli_fallback', False) or _is_truthy(os.environ.get('BRIDGE_WRAPPER_ALLOW_CLI_FALLBACK'))) - - -def load_token(agent: str) -> str: - env_key = env_key_for_agent('BRIDGE_TOKEN_', agent) - if os.environ.get(env_key): - return os.environ[env_key] - tokens = load_agent_tokens(token_config_path()) - token = tokens.get(agent) - if token: - return token - raise SystemExit(f'missing bridge token for {agent}; set {env_key} or configure {token_config_path()}') - - -def api_request(agent: str, method: str, path: str, *, payload: dict[str, Any] | None = None) -> dict[str, Any]: - data = None - headers = { - 'Accept': 'application/json', - 'Authorization': f'Bearer {load_token(agent)}', - } - if payload is not None: - data = json.dumps(payload).encode('utf-8') - headers['Content-Type'] = 'application/json' - request = Request(f"{api_url().rstrip('/')}{path}", data=data, method=method, headers=headers) - try: - with urlopen(request, timeout=5) as response: - return json.loads(response.read().decode('utf-8')) - except HTTPError as exc: - detail = exc.read().decode('utf-8', errors='replace') - try: - payload = json.loads(detail) - raise SystemExit(payload.get('detail', detail) or detail) - except json.JSONDecodeError: - raise SystemExit(detail or str(exc)) from exc - except (URLError, OSError, TimeoutError) as exc: - raise ConnectionError(str(exc)) from exc - - -def cli_fallback(agent: str, cli_args: list[str]) -> None: - proc = subprocess.run(['python3', str(CLI_PATH)] + cli_args) - raise SystemExit(proc.returncode) - - -def invoke(agent: str, args: Namespace, *, api_call, cli_args: list[str]) -> None: - try: - payload = api_call() - except ConnectionError as exc: - if not allow_cli_fallback(args): - raise SystemExit( - f'bridge API unavailable at {api_url()}; set --allow-cli-fallback or BRIDGE_WRAPPER_ALLOW_CLI_FALLBACK=1 to use direct CLI fallback ({exc})' - ) from exc - cli_fallback(agent, cli_args) - return - print(json.dumps(payload, indent=2)) - - -def create_result(payload: dict[str, Any]) -> dict[str, Any]: - handoff_id = str(payload['handoff_id']) - sender = str(payload['sender']) - recipient = str(payload['recipient']) - root = bridge_root() - return { - 'handoff_id': handoff_id, - 'outbox': str(root / 'outgoing' / sender / f'{handoff_id}.md'), - 'inbox': str(root / 'incoming' / recipient / f'{handoff_id}.md'), - 'revision': int(payload.get('revision', 0)), - } - - -def list_result(agent: str, payload: dict[str, Any]) -> list[dict[str, Any]]: - root = bridge_root() - items = [] - for item in payload.get('items', []): - handoff_id = str(item['handoff_id']) - items.append({ - 'path': str(root / 'incoming' / agent / f'{handoff_id}.md'), - 'status': item.get('status', ''), - 'subject': item.get('subject', ''), - 'sender': item.get('sender', ''), - 'recipient': item.get('recipient', ''), - }) - return items - - -def status_result(agent: str, handoff_id: str, payload: dict[str, Any]) -> dict[str, Any]: - root = bridge_root() - sender = str(payload.get('sender', '')) - recipient = str(payload.get('recipient', '')) - paths = [] - if agent == sender: - paths.append(str(root / 'outgoing' / sender / f'{handoff_id}.md')) - if agent == recipient: - paths.append(str(root / 'incoming' / recipient / f'{handoff_id}.md')) - archive_path = root / 'archive' / handoff_id / f'{handoff_id}.md' - if archive_path.exists(): - paths.append(str(archive_path)) - return { - 'handoff_id': handoff_id, - 'actor': agent, - 'paths': paths, - 'statuses': sorted({str(payload.get('status', ''))}), - 'revisions': [int(payload.get('revision', 0))], - } - - -def set_status_result(agent: str, payload: dict[str, Any]) -> dict[str, Any]: - return { - 'handoff_id': str(payload['handoff_id']), - 'actor': agent, - 'status': str(payload['status']), - 'revision': int(payload.get('revision', 0)), - } - - -def archive_result(agent: str, payload: dict[str, Any]) -> dict[str, Any]: - return { - 'handoff_id': str(payload['handoff_id']), - 'actor': agent, - 'archive_dir': str(payload.get('archive_path') or (bridge_root() / 'archive' / payload['handoff_id'])), - } diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index cd10a58..0000000 --- a/tests/conftest.py +++ /dev/null @@ -1,52 +0,0 @@ -from __future__ import annotations - -import sys -from pathlib import Path - -import pytest - -ROOT_DIR = Path(__file__).resolve().parents[1] -SCRIPTS_DIR = ROOT_DIR / 'scripts' -for path in (ROOT_DIR, SCRIPTS_DIR): - if str(path) not in sys.path: - sys.path.insert(0, str(path)) - -TEST_AGENTS = ('agent-a', 'agent-b', 'agent-c') - - -@pytest.fixture(autouse=True) -def bridge_sandbox(tmp_path, monkeypatch): - import bridge_cli - import bridge_audit_view - - root = tmp_path / 'bridge' - bridge = root / 'bridge' - for kind in ('incoming', 'outgoing'): - for agent in TEST_AGENTS: - (bridge / kind / agent).mkdir(parents=True, exist_ok=True) - (bridge / 'archive').mkdir(parents=True, exist_ok=True) - (bridge / 'audit').mkdir(parents=True, exist_ok=True) - audit_file = bridge / 'audit' / 'handoff-log.md' - audit_file.write_text('', encoding='utf-8') - - system_dir = tmp_path / 'agent-a' / 'System' - system_dir.mkdir(parents=True, exist_ok=True) - output = system_dir / 'Bridge Audit View.md' - archive_output = system_dir / 'Bridge Archive Index.md' - - monkeypatch.setattr(bridge_cli, 'ROOT', root) - monkeypatch.setattr(bridge_cli, 'BRIDGE', bridge) - monkeypatch.setattr(bridge_cli, 'AUDIT', audit_file) - - monkeypatch.setattr(bridge_audit_view, 'ROOT', root) - monkeypatch.setattr(bridge_audit_view, 'BRIDGE', bridge) - monkeypatch.setattr(bridge_audit_view, 'OUTPUT', output) - monkeypatch.setattr(bridge_audit_view, 'ARCHIVE_OUTPUT', archive_output) - - return { - 'root': root, - 'bridge': bridge, - 'audit_file': audit_file, - 'output': output, - 'archive_output': archive_output, - } diff --git a/tests/test_bridge.py b/tests/test_bridge.py new file mode 100644 index 0000000..a1079d7 --- /dev/null +++ b/tests/test_bridge.py @@ -0,0 +1,306 @@ +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +import json +import os +from pathlib import Path +import pwd +import subprocess +import sys +import threading + +import pytest + +from bridge.cli import notify, unseen +from bridge.config import load_agents, require_identity +from bridge.frontmatter import dump_document, parse_frontmatter +from bridge.policy import require_change, TERMINAL +from bridge.store import Store + +REPO = Path(__file__).resolve().parents[1] + + +@pytest.fixture +def store(tmp_path): + account = pwd.getpwuid(os.getuid()).pw_name + (tmp_path / 'agents.conf').write_text(''.join(f'{agent} {account}\n' for agent in ('alice', 'bob', 'ops'))) + return Store(tmp_path, load_agents(tmp_path)) + + +def run(store, *args, body='', extra_env=None): + return subprocess.run([sys.executable, str(REPO / 'bin/bridge'), '--root', str(store.root), *args], + input=body.encode(), capture_output=True, + env={**os.environ, **(extra_env or {})}) + + +def test_lifecycle_and_owes(store): + ident = store.new('alice', 'bob', 'Review artifact', 'Inputs: /srv/artifacts/input.md\n', '2030-01-01') + first = store.load(ident) + assert first['status'] == 'open' and first['owes'] == 'bob' + original = (store.root / 'open' / ident / '00-alice.md').read_bytes() + store.append(ident, 'bob', 'Checking.', 'working') + store.append(ident, 'bob', 'Which revision?', 'blocked') + assert store.load(ident)['owes'] == 'alice' + store.append(ident, 'alice', 'Revision 2.') + answered = store.load(ident) + assert answered['status'] == 'blocked' and answered['owes'] == 'bob' + store.append(ident, 'bob', 'Resuming.', 'working') + store.append(ident, 'bob', 'Reviewed; result: /srv/artifacts/result.md', 'done') + request = store.load(ident) + assert request['status'] == 'done' and request['owes'] is None + assert request['due'] == '2030-01-01' + assert len(request['events']) == 6 + assert (store.root / 'done' / ident / '00-alice.md').read_bytes() == original + assert not (store.root / 'open' / ident).exists() + cancelled = store.new('alice', 'bob', 'Withdraw request', '') + store.append(cancelled, 'alice', 'No longer needed.', 'cancelled') + assert store.load(cancelled)['status'] == 'cancelled' + + +@pytest.mark.parametrize('actor,status,body', [ + ('alice', 'done', 'Result'), ('bob', 'cancelled', 'No'), + ('ops', None, 'Hello'), ('alice', 'working', 'Start'), + ('alice', 'blocked', 'Question'), ('bob', 'done', ' \n'), + ('bob', 'unknown', 'Bad status'), +]) +def test_role_refusals(store, actor, status, body): + ident = store.new('alice', 'bob', 'Task', 'Input') + with pytest.raises(ValueError): + store.append(ident, actor, body, status) + assert len(store.load(ident)['events']) == 1 + + +@pytest.mark.parametrize('current', ['open', 'working', 'blocked', 'done', 'cancelled']) +@pytest.mark.parametrize('target', ['open', 'working', 'blocked', 'done', 'cancelled']) +def test_transition_table(current, target): + allowed = current not in TERMINAL and (target != 'open' or current == 'open') + actor = 'alice' if target in {'open', 'cancelled'} else 'bob' + if allowed: + require_change(current, target, actor, 'alice', 'bob', 'Outcome') + else: + with pytest.raises(ValueError): + require_change(current, target, actor, 'alice', 'bob', 'Outcome') + + +def test_no_replies_after_terminal(store): + ident = store.new('alice', 'bob', 'Task', '') + store.append(ident, 'bob', 'Complete.', 'done') + with pytest.raises(ValueError, match='transition'): + store.append(ident, 'alice', 'Reopen?') + + +def test_concurrent_writers_different_authors(store, monkeypatch): + ident = store.new('alice', 'bob', 'Concurrent', 'Input') + # Force every writer to observe the same starting sequence before publication. + barrier = threading.Barrier(12) + original_load = store.load + def synchronized_load(value): + request = original_load(value) + barrier.wait(timeout=10) + return request + monkeypatch.setattr(store, 'load', synchronized_load) + with ThreadPoolExecutor(max_workers=12) as pool: + futures = [pool.submit(store.append, ident, 'alice' if index % 2 else 'bob', f'Reply {index}') + for index in range(12)] + for future in futures: + future.result() + events = original_load(ident)['events'] + assert len(events) == 13 + assert [int(event['file'].split('-')[0]) for event in events] == list(range(13)) + assert len({event['body'] for event in events}) == 13 + + +def test_modes_and_bell_inode(store): + old_umask = os.umask(0o077) + try: + ident = store.new('alice', 'bob', 'Modes', 'Input') + bell = store.root / 'open/.bell' + inode = bell.stat().st_ino + store.append(ident, 'bob', 'Working.', 'working') + assert bell.stat().st_ino == inode + assert bell.stat().st_mode & 0o777 == 0o660 + for area in ('open', 'done', f'open/{ident}'): + assert (store.root / area).stat().st_mode & 0o777 == 0o770 + for event in (store.root / 'open' / ident).iterdir(): + assert event.stat().st_mode & 0o777 == 0o640 + finally: + os.umask(old_umask) + + +def test_identity_refusal_and_owner_warning(store): + ident = store.new('alice', 'bob', 'Provenance', '') + store.agents['alice'] = replace(store.agents['alice'], uid=os.getuid() + 1) + with pytest.raises(ValueError, match='requires Unix account'): + store.new('alice', 'bob', 'Impersonation', '') + assert 'file owner' in store.load(ident)['events'][0]['warnings'][0] + with pytest.raises(ValueError, match='unknown agent'): + require_identity(store.agents, 'stranger') + + +def test_seen_excludes_self_and_survives_move(store, tmp_path): + state = tmp_path / 'state' + ident = store.new('alice', 'bob', 'Task', 'Input') + assert unseen(store, 'alice', state, False) == [] + first = unseen(store, 'bob', state, True) + assert len(first) == 1 + assert not unseen(store, 'bob', state, False) + store.append(ident, 'bob', 'Question?', 'blocked') + before = unseen(store, 'alice', state, True) + assert len(before) == 1 + store.append(ident, 'bob', 'Result.', 'done') + after = unseen(store, 'alice', state, False) + assert len(after) == 1 and after[0]['status'] == 'done' + assert not unseen(store, 'bob', state, False) + assert first[0]['key'] == store.load(ident)['events'][0]['key'] + assert (state / 'alice.seen').stat().st_mode & 0o777 == 0o640 + + +def test_notify_is_generic_and_failure_keeps_event(store, tmp_path, capsys): + output = tmp_path / 'notification' + code = 'import pathlib,sys; pathlib.Path(sys.argv[1]).write_text(sys.stdin.read()); sys.exit(3)' + store.agents['bob'] = replace(store.agents['bob'], notify=(sys.executable, '-c', code, str(output))) + ident = store.new('alice', 'bob', 'Wake recipient', 'Input') + notify(store, ident, 'alice') + assert ident in output.read_text() and 'from alice' in output.read_text() + assert output.read_text().count('\n') == 1 + assert 'event saved; notify bob failed' in capsys.readouterr().err + assert store.load(ident)['status'] == 'open' + store.agents['alice'] = replace(store.agents['alice'], notify=(sys.executable, '-c', code, str(output))) + store.append(ident, 'bob', 'Result.', 'done') + notify(store, ident, 'bob') + assert 'from bob' in output.read_text() + + +def test_interrupted_close_is_listed_as_done(store, monkeypatch): + ident = store.new('alice', 'bob', 'Crash before move', 'Input') + def crash(*args): + raise OSError('simulated interrupted rename') + monkeypatch.setattr(Path, 'rename', crash) + store.append(ident, 'bob', 'Finished.', 'done') + assert (store.root / 'open' / ident).exists() + assert store.requests()[0]['status'] == 'done' + closed = run(store, 'list', '--done', '--json') + assert closed.returncode == 0 and json.loads(closed.stdout)[0]['id'] == ident + assert json.loads(run(store, 'list', '--json').stdout) == [] + + +@pytest.mark.parametrize('body', ['Bad\r\ntext', 'Bad\x00text', 'Bad\x1btext', 'x' * 65536, 'é' * 33000]) +def test_invalid_input_leaves_no_request(store, body): + with pytest.raises(ValueError): + store.new('alice', 'bob', 'Task', body) + assert not (store.root / 'open').exists() + + +def test_frontmatter_and_path_rejections(store): + text = dump_document({'id': 'example', 'subject': 'Task: review'}, 'Body\n') + assert parse_frontmatter(text) == ({'id': 'example', 'subject': 'Task: review'}, 'Body\n') + with pytest.raises(ValueError): + store.new('alice', 'bob', 'Injected\nstatus: done', 'Body') + with pytest.raises(ValueError): + store.new('alice', 'alice', 'Self', '') + with pytest.raises(ValueError): + store.load('../../agents.conf') + + +def test_cli_commands_json_and_filters(store, tmp_path): + created = run(store, 'new', '--as', 'alice', '--to', 'bob', '--subject', 'CLI task', body='Input\n') + assert created.returncode == 0, created.stderr + ident = created.stdout.decode().strip() + listed = json.loads(run(store, '--as', 'bob', 'list', '--owed', '--json').stdout) + assert listed[0]['id'] == ident and listed[0]['owes'] == 'bob' + assert json.loads(run(store, 'list', '--mine', '--as', 'ops', '--json').stdout) == [] + assert run(store, 'reply', ident, '--as', 'bob', '--status', 'working', body='Started').returncode == 0 + shown = json.loads(run(store, 'show', ident, '--json').stdout) + assert shown['status'] == 'working' and len(shown['events']) == 2 + assert 'Started' in run(store, 'show', ident).stdout.decode() + state = str(tmp_path / 'seen') + marked = run(store, 'unseen', '--as', 'bob', '--state-dir', state, '--mark', '--json') + assert len(json.loads(marked.stdout)) == 1 + assert json.loads(run(store, 'unseen', '--as', 'bob', '--state-dir', state, '--json').stdout) == [] + assert run(store, 'close', ident, '--as', 'bob', body='Outcome: complete').returncode == 0 + assert json.loads(run(store, 'list', '--json').stdout) == [] + assert json.loads(run(store, 'list', '--done', '--json').stdout)[0]['status'] == 'done' + cancelled = run(store, 'new', '--as', 'alice', '--to', 'bob', '--subject', 'Cancel me').stdout.decode().strip() + assert run(store, 'cancel', cancelled, '--as', 'alice', body='Withdrawn').returncode == 0 + assert run(store, 'list', '--mine').returncode == 1 + assert run(store, 'unseen').returncode == 1 + assert run(store, 'new', '--as', 'alice', '--to', 'bob', '--subject', 'CRLF', body='Bad\r\n').returncode == 1 + + +def test_config_rejections_and_quoted_command(store): + path = store.root / 'agents.conf' + account = pwd.getpwuid(os.getuid()).pw_name + path.write_text(f'alice {account} /usr/bin/printf "quoted argument" # comment\n') + assert load_agents(store.root)['alice'].notify == ('/usr/bin/printf', 'quoted argument') + for text in (f'alice {account}\nalice {account}\n', 'bad/id account\n', 'alice\n', 'alice no-such-bridge-account\n'): + path.write_text(text) + with pytest.raises(ValueError): + load_agents(store.root) + + +def test_notify_command_from_configuration_and_root_environment(store, tmp_path): + account = pwd.getpwuid(os.getuid()).pw_name + output = tmp_path / 'pointer' + code = 'import os,pathlib,sys; pathlib.Path(sys.argv[1]).write_text(os.environ["BRIDGE_ROOT"] + "\\n" + sys.stdin.read())' + import shlex + command = shlex.join([sys.executable, '-c', code, str(output)]) + (store.root / 'agents.conf').write_text(f'alice {account}\nbob {account} {command}\n') + result = subprocess.run([str(REPO / 'bin/bridge'), 'new', '--as', 'alice', '--to', 'bob', '--subject', 'Notify'], + input=b'Body', capture_output=True, + env={**os.environ, 'BRIDGE_ROOT': str(store.root)}) + assert result.returncode == 0, result.stderr + assert output.read_text().startswith(str(store.root) + '\nbridge ') + assert result.stdout.decode().strip() in output.read_text() + + +def test_unpublished_claim_is_skipped(store): + ident = store.new('alice', 'bob', 'Interrupted writer', '') + (store.root / 'open' / ident / '.01').write_text('unfinished') + store.append(ident, 'bob', 'This event survives.') + files = [event['file'] for event in store.load(ident)['events']] + assert files == ['00-alice.md', '02-bob.md'] + + +def test_reply_racing_close_cannot_reopen(store): + ident = store.new('alice', 'bob', 'Race', 'Input') + stale = store.load(ident) + store.append(ident, 'bob', 'Finished.', 'done') + folder = store.root / 'done' / ident + store.publish(folder, {'id': ident, 'from': 'alice', 'status': stale['status'], 'at': '2030-01-01T00:00:00+00:00'}, 'Late.') + request = store.load(ident) + assert request['status'] == 'done' and request['owes'] is None + assert any(w.startswith('02-alice.md: published after') for w in request['warnings']) + with pytest.raises(ValueError, match='transition'): + store.append(ident, 'alice', 'Again?') + assert json.loads(run(store, 'list', '--json').stdout) == [] + + +def test_listing_skips_unpublished_and_moved_folders(store, tmp_path, monkeypatch): + ident = store.new('alice', 'bob', 'Published', 'Input') + (store.root / 'open' / '20300101-000000-alice-empty').mkdir() + assert [r['id'] for r in store.requests()] == [ident] + assert len(unseen(store, 'bob', tmp_path / 'state', False)) == 1 + assert json.loads(run(store, 'list', '--json').stdout)[0]['id'] == ident + moving = store.new('alice', 'bob', 'Moving', 'Input') + original_iterdir = Path.iterdir + def iterdir_then_move(path): + if path.name == moving and path.parent.name == 'open': + path.rename(store.root / 'done' / moving) + return original_iterdir(path) + monkeypatch.setattr(Path, 'iterdir', iterdir_then_move) + assert moving in [r['id'] for r in store.requests()] + + +def test_writer_losing_terminal_race_is_warned(store, monkeypatch, capsys): + ident = store.new('alice', 'bob', 'Race', 'Input') + original_load = store.load + def load_then_cancel(value): + request = original_load(value) + monkeypatch.setattr(store, 'load', original_load) + store.append(ident, 'alice', 'No longer needed.', 'cancelled') + return request + monkeypatch.setattr(store, 'load', load_then_cancel) + store.append(ident, 'bob', 'Need input.', 'blocked') + assert 'ignored for status' in capsys.readouterr().err + request = store.load(ident) + assert request['status'] == 'cancelled' and (store.root / 'done' / ident).is_dir() + assert [e['file'] for e in request['events']] == ['00-alice.md', '01-alice.md', '02-bob.md'] diff --git a/tests/test_bridge_api.py b/tests/test_bridge_api.py deleted file mode 100644 index 8b18708..0000000 --- a/tests/test_bridge_api.py +++ /dev/null @@ -1,619 +0,0 @@ -from __future__ import annotations - -import json -import threading -from pathlib import Path -from urllib.error import HTTPError -from urllib.parse import urlencode -from urllib.request import Request, urlopen - -import pytest - -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.frontmatter import parse_frontmatter -from bridge_core.models import CreateHandoffInput -from bridge_core.service import BridgeService -import bridge_api_server -import bridge_intake_watch - -@pytest.fixture -def api_server(tmp_path: Path): - root = tmp_path / "agent-shared" - bridge_root = root / "bridge" - config_path = root / "config" / "bridge_api.env" - config_path.parent.mkdir(parents=True, exist_ok=True) - config_path.write_text( - "\n".join( - [ - "BRIDGE_TOKEN_AGENT_A=token-agent-a", - "BRIDGE_TOKEN_AGENT_B=token-agent-b", - "BRIDGE_TOKEN_AGENT_C=token-agent-c", - "", - ] - ), - encoding="utf-8", - ) - - server = bridge_api_server.build_server( - host="127.0.0.1", - port=0, - bridge_root=bridge_root, - config_path=config_path, - ) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - yield { - "base_url": f"http://127.0.0.1:{server.server_port}", - "bridge_root": bridge_root, - } - finally: - server.shutdown() - thread.join(timeout=5) - server.server_close() - - -def _request( - base_url: str, - method: str, - path: str, - *, - token: str | None = None, - body: dict[str, object] | None = None, - query: dict[str, str] | None = None, - extra_headers: dict[str, str] | None = None, -) -> tuple[int, dict[str, object]]: - url = f"{base_url}{path}" - if query: - url += f"?{urlencode(query)}" - data = None - headers = {"Accept": "application/json"} - if body is not None: - data = json.dumps(body).encode("utf-8") - headers["Content-Type"] = "application/json" - if token is not None: - headers["Authorization"] = f"Bearer {token}" - if extra_headers: - headers.update(extra_headers) - request = Request(url, method=method, headers=headers, data=data) - try: - with urlopen(request, timeout=5) as response: - payload = response.read().decode("utf-8") - return response.status, json.loads(payload) - except HTTPError as exc: - payload = exc.read().decode("utf-8") - return exc.code, json.loads(payload) - - -def test_health_endpoint_reports_ok(api_server) -> None: - status, payload = _request(api_server["base_url"], "GET", "/v1/health") - - assert status == 200 - assert payload["ok"] is True - assert payload["service"] == "bridge-api" - - -def test_create_list_get_and_lifecycle_flow(api_server) -> None: - status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "sender": "agent-c", - "recipient": "agent-c", - "issue_type": "task", - "subject": "API flow", - "requested_action": "Handle the request.", - "minimal_context": "Server integration test.", - "related_paths": ["/tmp/demo.md"], - }, - ) - - assert status == 201 - assert created["sender"] == "agent-a" - assert created["recipient"] == "agent-c" - handoff_id = str(created["handoff_id"]) - - status, agent_a_list = _request(api_server["base_url"], "GET", "/v1/handoffs", token="token-agent-a") - assert status == 200 - assert [item["handoff_id"] for item in agent_a_list["items"]] == [handoff_id] - - status, agent_c_list = _request(api_server["base_url"], "GET", "/v1/handoffs", token="token-agent-c") - assert status == 200 - assert [item["handoff_id"] for item in agent_c_list["items"]] == [handoff_id] - - status, agent_b_list = _request(api_server["base_url"], "GET", "/v1/handoffs", token="token-agent-b") - assert status == 200 - assert agent_b_list["items"] == [] - - status, agent_a_get = _request(api_server["base_url"], "GET", f"/v1/handoffs/{handoff_id}", token="token-agent-a") - assert status == 200 - assert agent_a_get["handoff_id"] == handoff_id - - status, forbidden = _request(api_server["base_url"], "GET", f"/v1/handoffs/{handoff_id}", token="token-agent-b") - assert status == 403 - assert forbidden["error"] == "forbidden" - - status, acked = _request(api_server["base_url"], "POST", f"/v1/handoffs/{handoff_id}/ack", token="token-agent-c") - assert status == 200 - assert acked["status"] == "acknowledged" - assert acked["acknowledgment_source"] == "manual" - assert acked["acknowledged_at"] != "none" - - status, blocked = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/block", - token="token-agent-c", - body={"outcome": "Waiting on a dependency."}, - ) - assert status == 200 - assert blocked["status"] == "blocked" - assert blocked["resolution_summary"] == "Waiting on a dependency." - - status, in_progress = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/status", - token="token-agent-c", - body={"status": "in_progress"}, - ) - assert status == 200 - assert in_progress["status"] == "in_progress" - - status, closed = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/close", - token="token-agent-c", - body={"outcome": "Completed safely."}, - ) - assert status == 200 - assert closed["status"] == "closed" - assert closed["resolution_summary"] == "Completed safely." - - status, active_items = _request(api_server["base_url"], "GET", "/v1/handoffs", token="token-agent-c") - assert status == 200 - assert active_items["items"] == [] - - status, all_items = _request( - api_server["base_url"], - "GET", - "/v1/handoffs", - token="token-agent-c", - query={"active_only": "false"}, - ) - assert status == 200 - assert [item["status"] for item in all_items["items"]] == ["closed"] - - status, archived = _request(api_server["base_url"], "POST", f"/v1/handoffs/{handoff_id}/archive", token="token-agent-c") - assert status == 200 - assert archived["status"] == "archived" - assert archived["archive_path"].endswith(f"/archive/{handoff_id}") - - archived_file = api_server["bridge_root"] / "archive" / handoff_id / f"{handoff_id}.md" - archived_data, archived_body = parse_frontmatter(archived_file.read_text(encoding="utf-8")) - assert archived_data["status"] == "archived" - assert archived_data["resolution_summary"] == "Completed safely." - assert "## Outcome\nCompleted safely." in archived_body - - -def test_create_rejects_disallowed_route(api_server, monkeypatch) -> None: - monkeypatch.setenv("BRIDGE_ALLOWED_ROUTES", "agent-a:agent-c,agent-c:agent-a") - status, payload = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-b", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Denied route", - "requested_action": "Nope", - "minimal_context": "Blocked by policy.", - }, - ) - - assert status == 403 - assert payload["error"] == "forbidden" - assert "route not allowed" in str(payload["detail"]) - - -def test_bad_auth_is_rejected(api_server) -> None: - status, payload = _request(api_server["base_url"], "GET", "/v1/handoffs", token="wrong-token") - assert status == 401 - assert payload["error"] == "unauthorized" - - status, payload = _request( - api_server["base_url"], - "GET", - "/v1/handoffs", - extra_headers={"X-Bridge-Token": "token-agent-c"}, - ) - assert status == 200 - assert payload["actor"] == "agent-c" - - -def test_create_triggers_immediate_notify_when_recipient_endpoint_is_configured(api_server, monkeypatch) -> None: - monkeypatch.setenv("BRIDGE_WRAPPER_API_URL", api_server["base_url"]) - monkeypatch.setenv("BRIDGE_API_CONFIG", str(api_server["bridge_root"].parent / "config" / "bridge_api.env")) - notify_server = bridge_intake_watch.build_notify_server(agent="agent-c", host="127.0.0.1", port=0) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - monkeypatch.setenv("BRIDGE_NOTIFY_URL_AGENT_C", f"http://127.0.0.1:{notify_server.server_port}/notify") - try: - status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Push me now", - "requested_action": "Ack immediately.", - "minimal_context": "Configured notify endpoint should fire on create.", - }, - ) - assert status == 201 - handoff_id = str(created["handoff_id"]) - - status, handoff = _request(api_server["base_url"], "GET", f"/v1/handoffs/{handoff_id}", token="token-agent-c") - assert status == 200 - assert handoff["status"] == "acknowledged" - assert handoff["acknowledgment_source"] == "auto" - assert handoff["acknowledged_at"] != "none" - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() - - -def test_create_keeps_open_handoff_when_immediate_notify_fails(api_server, monkeypatch) -> None: - monkeypatch.setenv("BRIDGE_NOTIFY_URL_AGENT_C", "http://127.0.0.1:1/notify") - - status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Fallback remains", - "requested_action": "Polling backup should still work.", - "minimal_context": "Push delivery can fail without breaking create.", - }, - ) - - assert status == 201 - handoff_id = str(created["handoff_id"]) - - status, handoff = _request(api_server["base_url"], "GET", f"/v1/handoffs/{handoff_id}", token="token-agent-c") - assert status == 200 - assert handoff["status"] == "open" - - -def test_immediate_delivery_updates_loaded_event_without_rescanning(tmp_path: Path, monkeypatch) -> None: - repository = FileBridgeRepository(tmp_path / "bridge") - service = BridgeService(repository) - created = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Single outbox scan", - requested_action="Deliver once.", - minimal_context="Regression coverage for API-triggered delivery.", - ) - ) - context = bridge_api_server.ApiContext( - bridge_root=repository.bridge_root, - config_path=None, - service=service, - ) - original_list_events = repository.list_events - scans = 0 - - def counted_list_events(*, states=None): - nonlocal scans - scans += 1 - return original_list_events(states=states) - - monkeypatch.setattr(repository, "list_events", counted_list_events) - monkeypatch.setattr(bridge_api_server, "_notify_agent", lambda *args, **kwargs: (True, "delivered")) - - bridge_api_server._deliver_pending_for_handoff(context, created.handoff_id, created.revision) - - assert scans == 1 - assert original_list_events()[0].delivery_state == "delivered" - - -def test_close_notifies_sender_with_lifecycle_payload(api_server, monkeypatch) -> None: - captured_requests: list[dict[str, object]] = [] - - class _FakeResponse: - def __enter__(self): - return self - - def __exit__(self, exc_type, exc, tb): - return False - - def _fake_urlopen(request, timeout=0): - captured_requests.append( - { - "url": request.full_url, - "authorization": request.headers.get("Authorization"), - "body": json.loads(request.data.decode("utf-8")), - "timeout": timeout, - } - ) - return _FakeResponse() - - monkeypatch.setattr(bridge_api_server, "urlopen", _fake_urlopen) - monkeypatch.setenv("BRIDGE_NOTIFY_URL_AGENT_A", "http://notify.example/agent-a") - - status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Close push", - "requested_action": "Notify sender on close.", - "minimal_context": "Exercise close lifecycle push.", - }, - ) - assert status == 201 - handoff_id = str(created["handoff_id"]) - captured_requests.clear() - - status, closed = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/close", - token="token-agent-c", - body={"outcome": "Completed safely."}, - ) - - assert status == 200 - assert closed["status"] == "closed" - assert len(captured_requests) == 1 - request = captured_requests[0] - assert request["url"] == "http://notify.example/agent-a" - assert request["authorization"] == "Bearer token-agent-a" - assert request["timeout"] == bridge_api_server.DEFAULT_NOTIFY_TIMEOUT_SECONDS - assert request["body"] == { - "trigger": "handoff_closed", - "handoff_id": handoff_id, - "sender": "agent-a", - "recipient": "agent-c", - "actor": "agent-c", - "status": "closed", - "subject": "Close push", - "resolution_summary": "Completed safely.", - } - - -def test_block_notifies_sender_with_lifecycle_payload(api_server, monkeypatch) -> None: - captured_requests: list[dict[str, object]] = [] - - class _FakeResponse: - def __enter__(self): - return self - - def __exit__(self, exc_type, exc, tb): - return False - - def _fake_urlopen(request, timeout=0): - captured_requests.append( - { - "url": request.full_url, - "authorization": request.headers.get("Authorization"), - "body": json.loads(request.data.decode("utf-8")), - "timeout": timeout, - } - ) - return _FakeResponse() - - monkeypatch.setattr(bridge_api_server, "urlopen", _fake_urlopen) - monkeypatch.setenv("BRIDGE_NOTIFY_URL_AGENT_A", "http://notify.example/agent-a") - - status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Block push", - "requested_action": "Notify sender on block.", - "minimal_context": "Exercise block lifecycle push.", - }, - ) - assert status == 201 - handoff_id = str(created["handoff_id"]) - captured_requests.clear() - - status, blocked = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/block", - token="token-agent-c", - body={"outcome": "Waiting on dependency."}, - ) - - assert status == 200 - assert blocked["status"] == "blocked" - assert len(captured_requests) == 1 - request = captured_requests[0] - assert request["url"] == "http://notify.example/agent-a" - assert request["authorization"] == "Bearer token-agent-a" - assert request["timeout"] == bridge_api_server.DEFAULT_NOTIFY_TIMEOUT_SECONDS - assert request["body"] == { - "trigger": "handoff_blocked", - "handoff_id": handoff_id, - "sender": "agent-a", - "recipient": "agent-c", - "actor": "agent-c", - "status": "blocked", - "subject": "Block push", - "resolution_summary": "Waiting on dependency.", - } - - -def test_close_keeps_status_update_when_sender_notify_fails(api_server, monkeypatch) -> None: - def _failing_urlopen(request, timeout=0): - raise OSError("notify down") - - monkeypatch.setattr(bridge_api_server, "urlopen", _failing_urlopen) - monkeypatch.setenv("BRIDGE_NOTIFY_URL_AGENT_A", "http://notify.example/agent-a") - - status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Close fallback", - "requested_action": "Do not fail close when notify fails.", - "minimal_context": "Lifecycle notify should be best-effort.", - }, - ) - assert status == 201 - handoff_id = str(created["handoff_id"]) - - status, closed = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/close", - token="token-agent-c", - body={"outcome": "Completed despite notify failure."}, - ) - - assert status == 200 - assert closed["status"] == "closed" - assert closed["resolution_summary"] == "Completed despite notify failure." - - status, fetched = _request(api_server["base_url"], "GET", f"/v1/handoffs/{handoff_id}", token="token-agent-a") - assert status == 200 - assert fetched["status"] == "closed" - assert fetched["resolution_summary"] == "Completed despite notify failure." - - -def test_api_idempotency_conflict_returns_409(api_server) -> None: - body: dict[str, object] = { - "recipient": "agent-c", - "issue_type": "task", - "subject": "Idempotent API create", - "requested_action": "Create once.", - "minimal_context": "Concurrent-safe create.", - } - first_status, first = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body=body, - extra_headers={"Idempotency-Key": "api-create-1"}, - ) - duplicate_status, duplicate = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body=body, - extra_headers={"Idempotency-Key": "api-create-1"}, - ) - conflict_status, conflict = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={**body, "subject": "Different payload"}, - extra_headers={"Idempotency-Key": "api-create-1"}, - ) - - assert first_status == duplicate_status == 201 - assert duplicate["handoff_id"] == first["handoff_id"] - assert conflict_status == 409 - assert conflict["error"] == "idempotency_conflict" - - -def test_api_if_match_stale_revision_returns_409(api_server) -> None: - _status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Revision API", - "requested_action": "Exercise optimistic concurrency.", - "minimal_context": "If-Match test.", - }, - ) - handoff_id = str(created["handoff_id"]) - ack_status, acked = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/ack", - token="token-agent-c", - extra_headers={"If-Match": '"0"'}, - ) - stale_status, stale = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/block", - token="token-agent-c", - body={"outcome": "Stale update."}, - extra_headers={"If-Match": '"0"'}, - ) - - assert ack_status == 200 - assert acked["revision"] == 1 - assert stale_status == 409 - assert stale["error"] == "revision_conflict" - - -def test_api_role_authorization_rejects_sender_close_and_allows_cancel(api_server) -> None: - _status, created = _request( - api_server["base_url"], - "POST", - "/v1/handoffs", - token="token-agent-a", - body={ - "recipient": "agent-c", - "issue_type": "task", - "subject": "Role matrix API", - "requested_action": "Prove role-specific lifecycle rules.", - "minimal_context": "Sender may cancel, not close.", - }, - ) - handoff_id = str(created["handoff_id"]) - close_status, close_error = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/close", - token="token-agent-a", - body={"outcome": "Unauthorized close."}, - ) - cancel_status, cancelled = _request( - api_server["base_url"], - "POST", - f"/v1/handoffs/{handoff_id}/cancel", - token="token-agent-a", - body={"outcome": "Withdrawn safely."}, - ) - - assert close_status == 403 - assert close_error["error"] == "forbidden" - assert cancel_status == 200 - assert cancelled["status"] == "cancelled" diff --git a/tests/test_bridge_audit_view.py b/tests/test_bridge_audit_view.py deleted file mode 100644 index fbd1d28..0000000 --- a/tests/test_bridge_audit_view.py +++ /dev/null @@ -1,155 +0,0 @@ -from __future__ import annotations - -from datetime import datetime, timedelta, timezone -from pathlib import Path - -import bridge_audit_view - - -def _iso(dt: datetime) -> str: - return dt.replace(microsecond=0).isoformat().replace('+00:00', 'Z') - - -def _write_handoff(path: Path, **frontmatter): - lines = ['---'] - for key, value in frontmatter.items(): - lines.append(f'{key}: {value}') - lines += ['---', '', '## Outcome', frontmatter.get('resolution_summary', 'pending'), ''] - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text('\n'.join(lines), encoding='utf-8') - - -def test_audit_view_reports_core_signals_and_writes_archive_index(bridge_sandbox, monkeypatch): - monkeypatch.setenv('BRIDGE_ALLOWED_ROUTES', 'agent-c:agent-a,agent-a:agent-c,agent-b:agent-a,agent-a:agent-b') - bridge = bridge_sandbox['bridge'] - now = datetime.now(timezone.utc) - stale_time = _iso(now - timedelta(hours=30)) - fresh_time = _iso(now - timedelta(hours=2)) - archived_time = _iso(now - timedelta(hours=6)) - - _write_handoff( - bridge / 'incoming' / 'agent-a' / 'HND-ACTIVE-001.md', - handoff_id='HND-ACTIVE-001', - status='open', - created_at=stale_time, - updated_at=stale_time, - sender='agent-c', - recipient='agent-a', - issue_type='task', - handoff_kind='request', - priority='medium', - risk_level='low', - due_at='none', - approval_needed='no', - approval_context='none', - resolution_summary='pending', - subject='Stale inbox item', - response_format='bullet list', - ) - _write_handoff( - bridge / 'incoming' / 'agent-a' / 'HND-BLOCKED-001.md', - handoff_id='HND-BLOCKED-001', - status='blocked', - created_at=fresh_time, - updated_at=fresh_time, - sender='agent-b', - recipient='agent-a', - issue_type='incident', - handoff_kind='incident', - priority='high', - risk_level='medium', - due_at='none', - approval_needed='no', - approval_context='none', - resolution_summary='Waiting on approval', - subject='Blocked inbox item', - response_format='bullet list', - ) - _write_handoff( - bridge / 'incoming' / 'agent-c' / 'HND-VIOLATION-001.md', - handoff_id='HND-VIOLATION-001', - status='open', - created_at=fresh_time, - updated_at=fresh_time, - sender='agent-b', - recipient='agent-c', - issue_type='question', - handoff_kind='question', - priority='low', - risk_level='low', - due_at='none', - approval_needed='no', - approval_context='none', - resolution_summary='pending', - subject='Route violation item', - response_format='bullet list', - ) - archive_dir = bridge / 'archive' / 'HND-ARCH-001' - _write_handoff( - archive_dir / 'HND-ARCH-001.md', - handoff_id='HND-ARCH-001', - status='archived', - created_at=stale_time, - updated_at=archived_time, - sender='agent-a', - recipient='agent-c', - issue_type='result', - handoff_kind='result', - priority='urgent', - risk_level='high', - due_at='none', - approval_needed='no', - approval_context='none', - resolution_summary='Resolved and archived', - subject='Archived handoff', - response_format='bullet list', - ) - _write_handoff( - archive_dir / 'HND-ARCH-001.outgoing.agent-a.md', - handoff_id='HND-ARCH-001', - status='archived', - created_at=stale_time, - updated_at=archived_time, - sender='agent-a', - recipient='agent-c', - issue_type='result', - handoff_kind='result', - priority='urgent', - risk_level='high', - due_at='none', - approval_needed='no', - approval_context='none', - resolution_summary='Resolved and archived (preserved copy)', - subject='Archived handoff', - response_format='bullet list', - ) - - bridge_audit_view.main() - - audit_text = bridge_sandbox['output'].read_text(encoding='utf-8') - archive_text = bridge_sandbox['archive_output'].read_text(encoding='utf-8') - - assert '- Total active handoffs: **3**' in audit_text - assert '- `agent-a` inbox active: **2**' in audit_text - assert '- `agent-c` inbox active: **1**' in audit_text - assert '- Blocked handoffs: **1**' in audit_text - assert '- Stale active handoffs (>24h): **1**' in audit_text - assert '- Route violations: **1**' in audit_text - - assert '## Needs Attention' in audit_text - assert 'HND-BLOCKED-001' in audit_text - assert 'HND-ACTIVE-001' in audit_text - assert 'HND-VIOLATION-001' in audit_text - assert '## Route Violations' in audit_text - assert 'agent-b → agent-c' in audit_text - assert '## Stale Active Handoffs (>24h)' in audit_text - assert 'Stale inbox item' in audit_text - - assert '# Bridge Archive Index' in archive_text - assert '## Recent Closures' in archive_text - assert '## By Route' in archive_text - assert 'HND-ARCH-001' in archive_text - assert 'Resolved and archived' in archive_text - assert 'agent-a → agent-c' in archive_text - assert 'preserved copies: 2' in archive_text - assert 'preserved copies: 2' in audit_text diff --git a/tests/test_bridge_auth.py b/tests/test_bridge_auth.py deleted file mode 100644 index db27d87..0000000 --- a/tests/test_bridge_auth.py +++ /dev/null @@ -1,31 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -import pytest - -from bridge_core.auth import AuthenticationError, load_agent_tokens, require_agent_token - - -def test_load_agent_tokens_prefers_environment(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: - config_path = tmp_path / "tokens.env" - config_path.write_text("BRIDGE_TOKEN_AGENT_B=config-agent-b\n", encoding="utf-8") - monkeypatch.setenv("BRIDGE_TOKEN_AGENT_A", "env-agent-a") - - tokens = load_agent_tokens(config_path) - - assert tokens["agent-a"] == "env-agent-a" - assert tokens["agent-b"] == "config-agent-b" - assert "agent-c" not in tokens - - -def test_require_agent_token_uses_constant_time_compare(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv("BRIDGE_TOKEN_REVIEWER", "secret-value") - - require_agent_token("reviewer", "secret-value") - - with pytest.raises(AuthenticationError, match="invalid token"): - require_agent_token("reviewer", "wrong") - - with pytest.raises(AuthenticationError, match="no configured token"): - require_agent_token("observer", "anything") diff --git a/tests/test_bridge_cli.py b/tests/test_bridge_cli.py deleted file mode 100644 index 2200301..0000000 --- a/tests/test_bridge_cli.py +++ /dev/null @@ -1,170 +0,0 @@ -from __future__ import annotations - -import json -import subprocess -import sys -from argparse import Namespace -from pathlib import Path - -import pytest - -import bridge_cli - - -def _create_handoff(capsys): - bridge_cli.create( - Namespace( - sender='agent-a', - recipient='agent-c', - issue_type='task', - handoff_kind='request', - priority='high', - risk_level='medium', - due_at='2026-04-24T18:00:00Z', - approval_needed=False, - approval_context='', - subject='Lifecycle coverage', - response_format='bullet list', - related_path=['/tmp/example.md'], - requested_action='Handle the request.', - minimal_context='Only for tests.', - constraints='- keep sandboxed', - ) - ) - result = json.loads(capsys.readouterr().out) - return result['handoff_id'] - - -def test_validate_route_allows_agent_a_to_agent_c(): - bridge_cli.validate_route('agent-a', 'agent-c') - - -def test_validate_route_rejects_agent_b_to_agent_c(monkeypatch): - monkeypatch.setenv('BRIDGE_ALLOWED_ROUTES', 'agent-a:agent-c,agent-c:agent-a') - with pytest.raises(SystemExit, match='route not allowed'): - bridge_cli.validate_route('agent-b', 'agent-c') - - -def test_handoff_lifecycle_persists_resolution_summary(bridge_sandbox, capsys): - handoff_id = _create_handoff(capsys) - bridge = bridge_sandbox['bridge'] - - outgoing = bridge / 'outgoing' / 'agent-a' / f'{handoff_id}.md' - incoming = bridge / 'incoming' / 'agent-c' / f'{handoff_id}.md' - assert outgoing.exists() - assert incoming.exists() - - outbox_data, _ = bridge_cli.parse_frontmatter(outgoing.read_text(encoding='utf-8')) - inbox_data, _ = bridge_cli.parse_frontmatter(incoming.read_text(encoding='utf-8')) - assert outbox_data['status'] == 'open' - assert inbox_data['resolution_summary'] == 'pending' - - bridge_cli.set_status(Namespace(actor='agent-c', handoff_id=handoff_id, status='acknowledged', outcome='')) - capsys.readouterr() - - for path in (outgoing, incoming): - data, _ = bridge_cli.parse_frontmatter(path.read_text(encoding='utf-8')) - assert data['acknowledgment_source'] == 'manual' - assert data['acknowledged_at'] != 'none' - - bridge_cli.set_status( - Namespace( - actor='agent-c', - handoff_id=handoff_id, - status='closed', - outcome='Handled safely and fully documented.', - ) - ) - capsys.readouterr() - - for path in (outgoing, incoming): - data, body = bridge_cli.parse_frontmatter(path.read_text(encoding='utf-8')) - assert data['status'] == 'closed' - assert data['resolution_summary'] == 'Handled safely and fully documented.' - assert '## Outcome\nHandled safely and fully documented.' in body - - bridge_cli.archive(Namespace(actor='agent-c', handoff_id=handoff_id)) - archive_result = json.loads(capsys.readouterr().out) - archive_dir = bridge / 'archive' / handoff_id - - assert archive_result['archive_dir'] == str(archive_dir) - assert archive_dir.exists() - assert not outgoing.exists() - assert not incoming.exists() - - archived_file = archive_dir / f'{handoff_id}.md' - assert archived_file.exists() - archived_data, archived_body = bridge_cli.parse_frontmatter(archived_file.read_text(encoding='utf-8')) - assert archived_data['status'] == 'archived' - assert archived_data['resolution_summary'] == 'Handled safely and fully documented.' - assert '## Outcome\nHandled safely and fully documented.' in archived_body - - audit_lines = bridge_sandbox['audit_file'].read_text(encoding='utf-8').strip().splitlines() - assert len(audit_lines) == 4 - assert ' | open | Lifecycle coverage' in audit_lines[0] - assert f' | {handoff_id} | ' in audit_lines[-1] - assert ' | archived | Lifecycle coverage' in audit_lines[-1] - - -def test_archive_requires_closed_status(bridge_sandbox, capsys): - handoff_id = _create_handoff(capsys) - - outgoing = bridge_sandbox['bridge'] / 'outgoing' / 'agent-a' / f'{handoff_id}.md' - incoming = bridge_sandbox['bridge'] / 'incoming' / 'agent-c' / f'{handoff_id}.md' - assert outgoing.exists() - assert incoming.exists() - - with pytest.raises(SystemExit, match='only closed or cancelled handoffs can be archived'): - bridge_cli.archive(Namespace(actor='agent-c', handoff_id=handoff_id)) - - -def test_recipient_can_archive_sender_cancelled_handoff(bridge_sandbox, capsys): - handoff_id = _create_handoff(capsys) - bridge_cli.set_status( - Namespace( - actor='agent-a', - handoff_id=handoff_id, - status='cancelled', - outcome='Request withdrawn by sender.', - ) - ) - capsys.readouterr() - - bridge_cli.archive(Namespace(actor='agent-c', handoff_id=handoff_id)) - archive_result = json.loads(capsys.readouterr().out) - - assert Path(archive_result['archive_dir']).exists() - - -def test_relocated_bridge_cli_uses_repo_relative_root(tmp_path): - source_root = Path(__file__).resolve().parents[1] - relocated_root = tmp_path / 'bridge-copy' - relocated_root.mkdir(parents=True, exist_ok=True) - subprocess.run(['cp', '-R', str(source_root / 'bridge_core'), str(relocated_root / 'bridge_core')], check=True) - subprocess.run(['cp', '-R', str(source_root / 'scripts'), str(relocated_root / 'scripts')], check=True) - - proc = subprocess.run( - [ - sys.executable, - str(relocated_root / 'scripts' / 'bridge_cli.py'), - 'create', - '--sender', 'agent-a', - '--recipient', 'agent-c', - '--issue-type', 'task', - '--subject', 'Relocated root test', - '--requested-action', 'Verify repo-relative defaults', - '--minimal-context', 'Copied repo should use its own bridge directory', - ], - check=True, - capture_output=True, - text=True, - ) - payload = json.loads(proc.stdout) - - expected_outbox = relocated_root / 'bridge' / 'outgoing' / 'agent-a' / f"{payload['handoff_id']}.md" - expected_inbox = relocated_root / 'bridge' / 'incoming' / 'agent-c' / f"{payload['handoff_id']}.md" - - assert Path(payload['outbox']) == expected_outbox - assert Path(payload['inbox']) == expected_inbox - assert expected_outbox.exists() - assert expected_inbox.exists() diff --git a/tests/test_bridge_frontmatter.py b/tests/test_bridge_frontmatter.py deleted file mode 100644 index 57a3840..0000000 --- a/tests/test_bridge_frontmatter.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import annotations - -from bridge_core.frontmatter import parse_frontmatter, render_frontmatter - - -def test_parse_frontmatter_returns_plain_body_when_no_frontmatter() -> None: - data, body = parse_frontmatter("hello\nworld\n") - assert data == {} - assert body == "hello\nworld\n" - - -def test_parse_frontmatter_normalizes_crlf_input() -> None: - text = "---\r\nhandoff_id: HND-1\r\nstatus: open\r\n---\r\n\r\nBody\r\n" - data, body = parse_frontmatter(text) - assert data["handoff_id"] == "HND-1" - assert data["status"] == "open" - assert body == "\nBody\n" - - -def test_parse_frontmatter_ignores_invalid_non_mapping_lines() -> None: - text = "---\nstatus: open\nthis is junk\nrecipient: agent-c\n---\n\nBody\n" - data, body = parse_frontmatter(text) - assert data["status"] == "open" - assert data["recipient"] == "agent-c" - assert body == "\nBody\n" - - -def test_render_frontmatter_sanitizes_newlines_in_scalar_and_list_values() -> None: - rendered = render_frontmatter( - { - "status": "open\narchived", - "related_paths": ["/tmp/a\nstatus: archived"], - } - ) - assert "status: open archived" in rendered - assert "status: archived" not in rendered.splitlines()[1:] - assert " - /tmp/a status: archived" in rendered diff --git a/tests/test_bridge_intake_watch.py b/tests/test_bridge_intake_watch.py deleted file mode 100644 index ee97bbd..0000000 --- a/tests/test_bridge_intake_watch.py +++ /dev/null @@ -1,546 +0,0 @@ -from __future__ import annotations - -import json -from http import HTTPStatus -from pathlib import Path -import sys -import threading -from urllib.error import HTTPError -from urllib.request import Request, urlopen - -import pytest - -import bridge_api_server -import bridge_intake_watch - - -@pytest.fixture -def api_server(tmp_path: Path): - root = tmp_path / 'agent-shared' - bridge_root = root / 'bridge' - config_path = root / 'config' / 'bridge_api.env' - config_path.parent.mkdir(parents=True, exist_ok=True) - config_path.write_text( - '\n'.join([ - 'BRIDGE_TOKEN_AGENT_A=token-agent-a', - 'BRIDGE_TOKEN_AGENT_B=token-agent-b', - 'BRIDGE_TOKEN_AGENT_C=token-agent-c', - '', - ]), - encoding='utf-8', - ) - - server = bridge_api_server.build_server( - host='127.0.0.1', - port=0, - bridge_root=bridge_root, - config_path=config_path, - ) - thread = threading.Thread(target=server.serve_forever, daemon=True) - thread.start() - try: - yield { - 'base_url': f'http://127.0.0.1:{server.server_port}', - 'bridge_root': bridge_root, - } - finally: - server.shutdown() - thread.join(timeout=5) - server.server_close() - - -def _request( - base_url: str, - method: str, - path: str, - *, - token: str, - body: dict[str, object] | None = None, -) -> tuple[int, dict[str, object]]: - data = None - headers = { - 'Accept': 'application/json', - 'Authorization': f'Bearer {token}', - } - if body is not None: - data = json.dumps(body).encode('utf-8') - headers['Content-Type'] = 'application/json' - request = Request(f'{base_url}{path}', method=method, headers=headers, data=data) - try: - with urlopen(request, timeout=5) as response: - return response.status, json.loads(response.read().decode('utf-8')) - except HTTPError as exc: - return exc.code, json.loads(exc.read().decode('utf-8')) - - -def _configure_watch_env(monkeypatch, bridge_root: Path, base_url: str) -> None: - monkeypatch.setenv('BRIDGE_WRAPPER_API_URL', base_url) - monkeypatch.setenv('BRIDGE_API_CONFIG', str(bridge_root.parent / 'config' / 'bridge_api.env')) - - -def _notify_request( - notify_url: str, - *, - token: str, - body: dict[str, object] | None = None, -) -> tuple[int, dict[str, object]]: - request = Request( - notify_url, - method='POST', - headers={ - 'Accept': 'application/json', - 'Authorization': f'Bearer {token}', - 'Content-Type': 'application/json', - }, - data=json.dumps(body or {}).encode('utf-8'), - ) - try: - with urlopen(request, timeout=5) as response: - return response.status, json.loads(response.read().decode('utf-8')) - except HTTPError as exc: - return exc.code, json.loads(exc.read().decode('utf-8')) - - -def test_intake_once_acknowledges_open_handoff(api_server, monkeypatch) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Needs prompt ack', - 'requested_action': 'Acknowledge receipt.', - 'minimal_context': 'Watcher should catch this quickly.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - actions = bridge_intake_watch.intake_once('agent-c') - - assert actions == [ - { - 'agent': 'agent-c', - 'handoff_id': handoff_id, - 'status': 'acknowledged', - 'ack_source': 'auto', - 'subject': 'Needs prompt ack', - 'action': 'acknowledged', - } - ] - - status, payload = _request(api_server['base_url'], 'GET', f'/v1/handoffs/{handoff_id}', token='token-agent-c') - assert status == 200 - assert payload['status'] == 'acknowledged' - assert payload['acknowledgment_source'] == 'auto' - assert payload['acknowledged_at'] != 'none' - - -def test_intake_once_runs_intake_event_command(api_server, monkeypatch, tmp_path: Path) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - capture_path = tmp_path / 'captured-intake-event.json' - script_path = tmp_path / 'capture_intake_event.py' - script_path.write_text( - """import json, os, pathlib, sys\npayload = {\n 'stdin': json.loads(sys.stdin.read()),\n 'env': {key: os.environ.get(key) for key in [\n 'BRIDGE_INTAKE_AGENT',\n 'BRIDGE_INTAKE_TRIGGER',\n 'BRIDGE_INTAKE_HANDOFF_ID',\n 'BRIDGE_INTAKE_EVENT_JSON',\n 'BRIDGE_NOTIFY_AGENT',\n ]},\n}\npathlib.Path(sys.argv[1]).write_text(json.dumps(payload), encoding='utf-8')\n""", - encoding='utf-8', - ) - - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Mirror me', - 'requested_action': 'Acknowledge and emit intake event.', - 'minimal_context': 'Local deployments may mirror this to a work queue.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - actions = bridge_intake_watch.intake_once( - 'agent-c', - intake_event_command=f'{sys.executable} {script_path} {capture_path}', - ) - - assert actions == [ - { - 'agent': 'agent-c', - 'handoff_id': handoff_id, - 'status': 'acknowledged', - 'ack_source': 'auto', - 'subject': 'Mirror me', - 'action': 'acknowledged', - }, - { - 'agent': 'agent-c', - 'handoff_id': handoff_id, - 'trigger': 'handoff_acknowledged', - 'action': 'intake_event_command', - 'exit_code': 0, - }, - ] - captured = json.loads(capture_path.read_text(encoding='utf-8')) - expected_event = { - 'trigger': 'handoff_acknowledged', - 'handoff_id': handoff_id, - 'sender': 'agent-a', - 'recipient': 'agent-c', - 'actor': 'agent-c', - 'status': 'acknowledged', - 'subject': 'Mirror me', - 'acknowledgment_source': 'auto', - } - assert captured['stdin'] == expected_event - assert captured['env'] == { - 'BRIDGE_INTAKE_AGENT': 'agent-c', - 'BRIDGE_INTAKE_TRIGGER': 'handoff_acknowledged', - 'BRIDGE_INTAKE_HANDOFF_ID': handoff_id, - 'BRIDGE_INTAKE_EVENT_JSON': json.dumps(expected_event, sort_keys=True), - 'BRIDGE_NOTIFY_AGENT': None, - } - - -def test_resolve_intake_event_command_precedence_and_whitespace(monkeypatch) -> None: - monkeypatch.delenv('BRIDGE_INTAKE_EVENT_COMMAND_AGENT_C', raising=False) - monkeypatch.delenv('BRIDGE_INTAKE_EVENT_COMMAND', raising=False) - assert bridge_intake_watch._resolve_intake_event_command('agent-c') is None - assert bridge_intake_watch._resolve_intake_event_command('agent-c', ' ') is None - assert bridge_intake_watch._resolve_intake_event_command('agent-c', 'cli-hook') == 'cli-hook' - - monkeypatch.setenv('BRIDGE_INTAKE_EVENT_COMMAND', 'generic-hook') - assert bridge_intake_watch._resolve_intake_event_command('agent-c') == 'generic-hook' - - monkeypatch.setenv('BRIDGE_INTAKE_EVENT_COMMAND_AGENT_C', 'scoped-hook') - assert bridge_intake_watch._resolve_intake_event_command('agent-c') == 'scoped-hook' - assert bridge_intake_watch._resolve_intake_event_command('agent-c', 'cli-hook') == 'cli-hook' - - -def test_intake_event_command_failure_is_best_effort(api_server, monkeypatch, tmp_path: Path) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - script_path = tmp_path / 'fail_intake_event.py' - script_path.write_text("""import sys\nprint('bad hook', file=sys.stderr)\nsys.exit(7)\n""", encoding='utf-8') - - for subject in ('First', 'Second'): - status, _created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': subject, - 'requested_action': 'Acknowledge even if hook fails.', - 'minimal_context': 'Hook should be best-effort.', - }, - ) - assert status == 201 - - actions = bridge_intake_watch.intake_once( - 'agent-c', - intake_event_command=f'{sys.executable} {script_path}', - ) - - assert [action['action'] for action in actions] == [ - 'acknowledged', - 'intake_event_command', - 'acknowledged', - 'intake_event_command', - ] - failures = [action for action in actions if action['action'] == 'intake_event_command'] - assert all(action['exit_code'] == 7 for action in failures) - assert all(action['error'] == 'bad hook' for action in failures) - - -def test_intake_once_ignores_non_open_handoffs(api_server, monkeypatch) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Already acked', - 'requested_action': 'Nothing to do.', - 'minimal_context': 'Should not be acked twice by intake pass.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - status, acked = _request(api_server['base_url'], 'POST', f'/v1/handoffs/{handoff_id}/ack', token='token-agent-c', body={}) - assert status == 200 - assert acked['status'] == 'acknowledged' - - actions = bridge_intake_watch.intake_once('agent-c') - - assert actions == [] - - -def test_intake_once_dry_run_reports_without_mutating(api_server, monkeypatch) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Dry run only', - 'requested_action': 'Do not mutate.', - 'minimal_context': 'Visibility check only.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - actions = bridge_intake_watch.intake_once('agent-c', dry_run=True) - - assert actions == [ - { - 'agent': 'agent-c', - 'handoff_id': handoff_id, - 'status': 'open', - 'subject': 'Dry run only', - 'action': 'would_acknowledge', - } - ] - - status, payload = _request(api_server['base_url'], 'GET', f'/v1/handoffs/{handoff_id}', token='token-agent-c') - assert status == 200 - assert payload['status'] == 'open' - - -def test_notify_send_json_ignores_client_disconnect() -> None: - calls: list[tuple[object, ...]] = [] - - class BrokenPipeWriter: - def write(self, _data: bytes) -> None: - raise BrokenPipeError('client closed') - - handler = object.__new__(bridge_intake_watch.IntakeNotifyHandler) - handler.wfile = BrokenPipeWriter() - handler.send_response = lambda status: calls.append(('response', status)) - handler.send_header = lambda name, value: calls.append(('header', name, value)) - handler.end_headers = lambda: calls.append(('end_headers', None)) - - handler._send_json(HTTPStatus.OK, {'ok': True}) - - assert calls[0] == ('response', 200) - assert calls[-1] == ('end_headers', None) - - -def test_notify_server_acknowledges_open_handoff(api_server, monkeypatch) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - notify_server = bridge_intake_watch.build_notify_server(agent='agent-c', host='127.0.0.1', port=0) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - try: - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Notify now', - 'requested_action': 'Immediate acknowledge.', - 'minimal_context': 'Push endpoint should handle this.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - notify_url = f'http://127.0.0.1:{notify_server.server_port}/notify' - status, payload = _notify_request(notify_url, token='token-agent-c') - - assert status == 200 - assert payload['agent'] == 'agent-c' - assert payload['trigger'] == 'notify' - assert payload['actions'] == [ - { - 'agent': 'agent-c', - 'handoff_id': handoff_id, - 'status': 'acknowledged', - 'ack_source': 'auto', - 'subject': 'Notify now', - 'action': 'acknowledged', - } - ] - - status, handoff = _request(api_server['base_url'], 'GET', f'/v1/handoffs/{handoff_id}', token='token-agent-c') - assert status == 200 - assert handoff['status'] == 'acknowledged' - assert handoff['acknowledgment_source'] == 'auto' - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() - - -def test_notify_server_rejects_wrong_token(api_server, monkeypatch) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - notify_server = bridge_intake_watch.build_notify_server(agent='agent-c', host='127.0.0.1', port=0) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - try: - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Bad token', - 'requested_action': 'Should stay open.', - 'minimal_context': 'Unauthorized notify must not mutate.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - notify_url = f'http://127.0.0.1:{notify_server.server_port}/notify' - status, payload = _notify_request(notify_url, token='wrong-token') - - assert status == 401 - assert payload['error'] == 'unauthorized' - - status, handoff = _request(api_server['base_url'], 'GET', f'/v1/handoffs/{handoff_id}', token='token-agent-c') - assert status == 200 - assert handoff['status'] == 'open' - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() - - -def test_notify_server_exposes_lifecycle_events_without_mutating_handoff(api_server, monkeypatch) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - notify_server = bridge_intake_watch.build_notify_server(agent='agent-a', host='127.0.0.1', port=0) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - try: - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Lifecycle echo', - 'requested_action': 'Return lifecycle event immediately.', - 'minimal_context': 'Notify listener should expose pushed lifecycle payload.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - notify_url = f'http://127.0.0.1:{notify_server.server_port}/notify' - event = { - 'trigger': 'handoff_closed', - 'handoff_id': handoff_id, - 'sender': 'agent-a', - 'recipient': 'agent-c', - 'actor': 'agent-c', - 'status': 'closed', - 'subject': 'Lifecycle echo', - 'resolution_summary': 'Done now.', - } - status, payload = _notify_request(notify_url, token='token-agent-a', body=event) - - assert status == 200 - assert payload['agent'] == 'agent-a' - assert payload['trigger'] == 'notify' - assert payload['event'] == event - assert payload['actions'] == [] - - status, handoff = _request(api_server['base_url'], 'GET', f'/v1/handoffs/{handoff_id}', token='token-agent-a') - assert status == 200 - assert handoff['status'] == 'open' - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() - - -def test_notify_server_runs_lifecycle_event_command(api_server, monkeypatch, tmp_path: Path) -> None: - _configure_watch_env(monkeypatch, api_server['bridge_root'], api_server['base_url']) - capture_path = tmp_path / 'captured-event.json' - script_path = tmp_path / 'capture_event.py' - script_path.write_text( - """import json, pathlib, sys\npathlib.Path(sys.argv[1]).write_text(sys.stdin.read(), encoding='utf-8')\n""", - encoding='utf-8', - ) - notify_server = bridge_intake_watch.build_notify_server( - agent='agent-a', - host='127.0.0.1', - port=0, - event_command=f'{sys.executable} {script_path} {capture_path}', - ) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - try: - status, created = _request( - api_server['base_url'], - 'POST', - '/v1/handoffs', - token='token-agent-a', - body={ - 'recipient': 'agent-c', - 'issue_type': 'task', - 'subject': 'Lifecycle forward', - 'requested_action': 'Forward lifecycle payload to command.', - 'minimal_context': 'Listener should run command on close/block events.', - }, - ) - assert status == 201 - handoff_id = str(created['handoff_id']) - - notify_url = f'http://127.0.0.1:{notify_server.server_port}/notify' - event = { - 'trigger': 'handoff_closed', - 'handoff_id': handoff_id, - 'sender': 'agent-c', - 'recipient': 'agent-a', - 'actor': 'agent-c', - 'status': 'closed', - 'subject': 'Lifecycle forward', - 'resolution_summary': 'Done now.', - } - status, payload = _notify_request(notify_url, token='token-agent-a', body=event) - - assert status == 200 - assert payload['actions'] == [ - { - 'agent': 'agent-a', - 'handoff_id': handoff_id, - 'trigger': 'handoff_closed', - 'action': 'event_command', - 'exit_code': 0, - } - ] - assert json.loads(capture_path.read_text(encoding='utf-8')) == event - - status, handoff = _request(api_server['base_url'], 'GET', f'/v1/handoffs/{handoff_id}', token='token-agent-a') - assert status == 200 - assert handoff['status'] == 'open' - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() diff --git a/tests/test_bridge_patrol.py b/tests/test_bridge_patrol.py deleted file mode 100644 index 4b3cdc1..0000000 --- a/tests/test_bridge_patrol.py +++ /dev/null @@ -1,365 +0,0 @@ -from __future__ import annotations - -import json -from datetime import datetime, timedelta, timezone -from http import HTTPStatus -from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -import threading - -import bridge_patrol -from bridge_core.frontmatter import dump_document -from bridge_core.models import CreateHandoffInput, HandoffRecord -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.service import BridgeService - - -class _NotifyCaptureServer(ThreadingHTTPServer): - daemon_threads = True - allow_reuse_address = True - - def __init__(self, server_address: tuple[str, int]): - super().__init__(server_address, _NotifyCaptureHandler) - self.requests: list[dict[str, object]] = [] - - -class _NotifyCaptureHandler(BaseHTTPRequestHandler): - server: _NotifyCaptureServer - - def do_POST(self) -> None: - length = int(self.headers.get('Content-Length', '0')) - raw = self.rfile.read(length) - payload = json.loads(raw.decode('utf-8') or '{}') - self.server.requests.append(payload) - data = json.dumps({'ok': True}).encode('utf-8') - self.send_response(HTTPStatus.OK) - self.send_header('Content-Type', 'application/json; charset=utf-8') - self.send_header('Content-Length', str(len(data))) - self.end_headers() - self.wfile.write(data) - - def log_message(self, format: str, *args: object) -> None: - return - - -def _setup_patrol_root(tmp_path: Path, monkeypatch): - root = tmp_path / 'agent-shared' - bridge = root / 'bridge' - for kind in ('incoming', 'outgoing'): - for agent in ('agent-a', 'agent-b', 'agent-c'): - (bridge / kind / agent).mkdir(parents=True, exist_ok=True) - (bridge / 'archive').mkdir(parents=True, exist_ok=True) - (bridge / 'audit').mkdir(parents=True, exist_ok=True) - (root / 'scripts').mkdir(parents=True, exist_ok=True) - (root / 'docs').mkdir(parents=True, exist_ok=True) - (root / 'examples').mkdir(parents=True, exist_ok=True) - audit_file = bridge / 'audit' / 'handoff-log.md' - audit_file.write_text('', encoding='utf-8') - audit_file.chmod(0o600) - - config = root / 'config' / 'bridge_api.env' - config.parent.mkdir(parents=True, exist_ok=True) - config.write_text( - '\n'.join([ - 'BRIDGE_API_HOST=127.0.0.1', - 'BRIDGE_API_PORT=8427', - 'BRIDGE_TOKEN_AGENT_C=token-agent-c', - '', - ]), - encoding='utf-8', - ) - - for path in [ - root, - bridge, - bridge / 'incoming', - bridge / 'outgoing', - bridge / 'archive', - bridge / 'audit', - root / 'scripts', - root / 'docs', - root / 'examples', - bridge / 'incoming' / 'agent-a', - bridge / 'incoming' / 'agent-b', - bridge / 'incoming' / 'agent-c', - bridge / 'outgoing' / 'agent-a', - bridge / 'outgoing' / 'agent-b', - bridge / 'outgoing' / 'agent-c', - config.parent, - ]: - path.chmod(0o700) - config.chmod(0o600) - - monkeypatch.setattr(bridge_patrol, 'ROOT', root) - monkeypatch.setattr(bridge_patrol, 'BRIDGE', bridge) - monkeypatch.setattr(bridge_patrol, 'CONFIG', config) - monkeypatch.setattr(bridge_patrol, 'PATROL_STATE_PATH', bridge / 'audit' / 'patrol-reminders.json') - monkeypatch.setattr(bridge_patrol, 'bridge_systemd_unit', lambda: 'bridge-api.service') - return root, bridge, config - - -def _write_handoff( - bridge: Path, - *, - handoff_id: str, - recipient: str = 'agent-c', - updated_at: str, - status: str = 'open', - acknowledged_at: str = 'none', - resolution_summary: str = 'pending', -) -> Path: - record = HandoffRecord( - handoff_id=handoff_id, - status=status, - created_at=updated_at, - updated_at=updated_at, - acknowledged_at=acknowledged_at, - acknowledgment_source='none' if acknowledged_at == 'none' else 'auto', - sender='agent-a', - recipient=recipient, - issue_type='task', - handoff_kind='request', - priority='medium', - risk_level='low', - due_at='none', - approval_needed='no', - approval_context='none', - resolution_summary=resolution_summary, - subject='Patrol reminder target', - response_format='concise status + action + blocker if any', - related_paths=[], - body='## Requested Action\nAck it\n\n## Minimal Context\nTest\n\n## Constraints\n- none\n\n## Outcome\n- pending\n', - ) - path = bridge / 'incoming' / recipient / f'{handoff_id}.md' - document = dump_document(record.to_frontmatter(), record.body) - path.write_text(document, encoding='utf-8') - path.chmod(0o600) - outgoing = bridge / 'outgoing' / record.sender / f'{handoff_id}.md' - outgoing.write_text(document, encoding='utf-8') - outgoing.chmod(0o600) - return path - - -def test_patrol_warns_when_service_or_health_check_fail(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('warning', f'{unit} not active (inactive)')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('warning', f'bridge API health failed at {url} (connection refused)')) - monkeypatch.setattr('sys.argv', ['bridge_patrol.py']) - - bridge_patrol.main() - out = capsys.readouterr().out - assert 'status: warning' in out - assert 'bridge-api.service not active (inactive)' in out - assert 'bridge API health failed at http://127.0.0.1:8427/v1/health' in out - - -def test_patrol_ok_when_service_and_health_are_ok(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - monkeypatch.setattr('sys.argv', ['bridge_patrol.py']) - - bridge_patrol.main() - out = capsys.readouterr().out - assert 'status: ok' in out - assert 'bridge-api.service active' in out - assert 'bridge API health ok at http://127.0.0.1:8427/v1/health' in out - - -def test_patrol_sends_unacknowledged_reminder_once_and_persists_state(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - old_ts = (datetime.now(timezone.utc) - timedelta(hours=1)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - _write_handoff(bridge, handoff_id='HND-TEST-0001', updated_at=old_ts) - - notify_server = _NotifyCaptureServer(('127.0.0.1', 0)) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - monkeypatch.setenv('BRIDGE_NOTIFY_URL_AGENT_C', f'http://127.0.0.1:{notify_server.server_port}/notify') - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - try: - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '0.25', '--reminder-repeat-hours', '2', '--escalate-after-hours', '12']) - bridge_patrol.main() - out = capsys.readouterr().out - assert 'reminder sent for HND-TEST-0001 to agent-c' in out - assert len(notify_server.requests) == 1 - assert notify_server.requests[0]['trigger'] == 'handoff_reminder' - state_path = bridge / 'audit' / 'patrol-reminders.json' - state = json.loads(state_path.read_text(encoding='utf-8')) - assert state['HND-TEST-0001']['reminder_count'] == 1 - - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '0.25', '--reminder-repeat-hours', '2', '--escalate-after-hours', '12']) - bridge_patrol.main() - capsys.readouterr() - assert len(notify_server.requests) == 1 - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() - - -def test_patrol_escalates_old_unacknowledged_handoff_without_repeat(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - old_ts = (datetime.now(timezone.utc) - timedelta(hours=8)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - _write_handoff(bridge, handoff_id='HND-TEST-0002', updated_at=old_ts) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '99', '--escalate-after-hours', '6', '--escalate-repeat-hours', '24']) - bridge_patrol.main() - out = capsys.readouterr().out - assert 'status: warning' in out - assert 'escalation: unresolved open handoff for agent-c: HND-TEST-0002 age=8.0h' in out - - state_path = bridge / 'audit' / 'patrol-reminders.json' - state = json.loads(state_path.read_text(encoding='utf-8')) - assert state['HND-TEST-0002']['escalation_count'] == 1 - - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '99', '--escalate-after-hours', '6', '--escalate-repeat-hours', '24']) - bridge_patrol.main() - out = capsys.readouterr().out - assert out.count('escalation: unresolved open handoff for agent-c: HND-TEST-0002') == 0 - - -def test_patrol_escalates_old_acknowledged_handoff_without_resolution(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - old_ts = (datetime.now(timezone.utc) - timedelta(hours=7)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - _write_handoff( - bridge, - handoff_id='HND-TEST-0003', - updated_at=old_ts, - status='acknowledged', - acknowledged_at=old_ts, - ) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '99', '--escalate-after-hours', '6', '--escalate-repeat-hours', '24']) - - bridge_patrol.main() - out = capsys.readouterr().out - - assert 'status: warning' in out - assert 'escalation: unresolved acknowledged handoff for agent-c: HND-TEST-0003 age=7.0h' in out - - -def test_patrol_reminds_on_in_progress_handoff(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - updated_at = (datetime.now(timezone.utc) - timedelta(hours=1)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - acknowledged_at = (datetime.now(timezone.utc) - timedelta(hours=2)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - _write_handoff( - bridge, - handoff_id='HND-TEST-0004', - updated_at=updated_at, - status='in_progress', - acknowledged_at=acknowledged_at, - resolution_summary='Investigating; no stable fix yet.', - ) - - notify_server = _NotifyCaptureServer(('127.0.0.1', 0)) - thread = threading.Thread(target=notify_server.serve_forever, daemon=True) - thread.start() - monkeypatch.setenv('BRIDGE_NOTIFY_URL_AGENT_C', f'http://127.0.0.1:{notify_server.server_port}/notify') - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - try: - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '0.25', '--reminder-repeat-hours', '2', '--escalate-after-hours', '12']) - bridge_patrol.main() - out = capsys.readouterr().out - - assert 'reminder sent for HND-TEST-0004 to agent-c status=in_progress age=1.0h count=1' in out - assert len(notify_server.requests) == 1 - assert notify_server.requests[0]['reason'] == 'unresolved_in_progress_handoff' - assert notify_server.requests[0]['status'] == 'in_progress' - finally: - notify_server.shutdown() - thread.join(timeout=5) - notify_server.server_close() - - -def test_patrol_warns_on_active_handoff_older_than_alert_threshold_without_actionable_summary(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - updated_at = (datetime.now(timezone.utc) - timedelta(minutes=45)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - acknowledged_at = (datetime.now(timezone.utc) - timedelta(hours=1)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - _write_handoff( - bridge, - handoff_id='HND-TEST-0005', - updated_at=updated_at, - status='acknowledged', - acknowledged_at=acknowledged_at, - resolution_summary='pending', - ) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--active-alert-hours', '0.5', '--reminder-after-hours', '99', '--escalate-after-hours', '99']) - - bridge_patrol.main() - out = capsys.readouterr().out - - assert 'status: warning' in out - assert 'active unresolved handoff for agent-c: HND-TEST-0005 age=0.8h status=acknowledged summary=pending' in out - - - -def test_patrol_skips_active_alert_when_summary_is_actionable(tmp_path: Path, monkeypatch, capsys) -> None: - root, bridge, config = _setup_patrol_root(tmp_path, monkeypatch) - updated_at = (datetime.now(timezone.utc) - timedelta(minutes=45)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - acknowledged_at = (datetime.now(timezone.utc) - timedelta(hours=1)).replace(microsecond=0).isoformat().replace('+00:00', 'Z') - _write_handoff( - bridge, - handoff_id='HND-TEST-0006', - updated_at=updated_at, - status='acknowledged', - acknowledged_at=acknowledged_at, - resolution_summary='Root cause verified. Stable target is bluebubbles:+17209719704. Safe retry only after fresh approval.', - ) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--active-alert-hours', '0.5', '--reminder-after-hours', '99', '--escalate-after-hours', '99']) - - bridge_patrol.main() - out = capsys.readouterr().out - - assert 'active unresolved handoff for agent-c: HND-TEST-0006' not in out - assert 'status: ok' in out - - -def test_patrol_detects_v2_mirror_outbox_and_idempotency_drift(tmp_path: Path, monkeypatch, capsys) -> None: - _root, bridge, _config = _setup_patrol_root(tmp_path, monkeypatch) - repository = FileBridgeRepository(bridge) - service = BridgeService(repository) - record = service.create_handoff( - CreateHandoffInput( - sender='agent-a', - recipient='agent-c', - issue_type='task', - subject='V2 patrol drift', - requested_action='Detect all drift.', - minimal_context='Patrol regression.', - idempotency_key='patrol-v2-1', - ) - ) - (bridge / 'incoming' / 'agent-c' / f'{record.handoff_id}.md').unlink() - event = service.list_outbox()[0] - service.mark_event_failed(event.event_id, 'consumer down', max_attempts=1) - index_path = next(repository.idempotency_root.glob('*/*.json')) - index = json.loads(index_path.read_text(encoding='utf-8')) - index['request_hash'] = 'inconsistent' - index_path.write_text(json.dumps(index), encoding='utf-8') - index_path.chmod(0o600) - - monkeypatch.setattr(bridge_patrol, 'check_systemd_service', lambda unit: ('ok', f'{unit} active')) - monkeypatch.setattr(bridge_patrol, 'check_api_health', lambda url: ('ok', f'bridge API health ok at {url}')) - monkeypatch.setattr('sys.argv', ['bridge_patrol.py', '--reminder-after-hours', '99', '--escalate-after-hours', '99']) - bridge_patrol.main() - out = capsys.readouterr().out - - assert 'status: warning' in out - assert 'missing mirror incoming/agent-c/' in out - assert 'dead-letter event' in out - assert 'idempotency index inconsistency' in out diff --git a/tests/test_bridge_policy.py b/tests/test_bridge_policy.py deleted file mode 100644 index 7a53c65..0000000 --- a/tests/test_bridge_policy.py +++ /dev/null @@ -1,47 +0,0 @@ -from __future__ import annotations - -import pytest - -from bridge_core.policy import ( - RoutePolicyError, - StatusPolicyError, - normalize_status, - require_route, - require_status_transition, - visible_queues_for_actor, -) - - -def test_require_route_allows_arbitrary_agents_when_no_policy_is_configured() -> None: - require_route("agent-a", "agent-b") - - -def test_require_route_rejects_pairs_outside_configured_policy(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv("BRIDGE_ALLOWED_ROUTES", "agent-a:agent-b,agent-b:agent-a") - - with pytest.raises(RoutePolicyError, match="route not allowed"): - require_route("agent-a", "agent-c") - - -def test_normalize_status_supports_acked_alias() -> None: - assert normalize_status("acked") == "acknowledged" - - -def test_require_status_transition_rejects_invalid_close_without_outcome() -> None: - with pytest.raises(StatusPolicyError, match="requires resolution summary"): - require_status_transition("acknowledged", "closed", has_resolution_summary=False) - - -def test_visible_queues_for_actor_limits_to_sender_recipient_and_archive() -> None: - paths = visible_queues_for_actor( - actor="agent-b", - sender="agent-a", - recipient="agent-b", - handoff_id="HND-1", - ) - - assert paths == { - "incoming/agent-b/HND-1.md", - "outgoing/agent-a/HND-1.md", - "archive/HND-1/HND-1.md", - } diff --git a/tests/test_bridge_rotate_tokens.py b/tests/test_bridge_rotate_tokens.py deleted file mode 100644 index a64c3a5..0000000 --- a/tests/test_bridge_rotate_tokens.py +++ /dev/null @@ -1,38 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -import bridge_rotate_tokens - - -def test_rotate_lines_updates_only_selected_agents() -> None: - lines = [ - 'BRIDGE_TOKEN_AGENT_A=old-agent-a', - 'BRIDGE_TOKEN_AGENT_B=old-agent-b', - 'BRIDGE_TOKEN_AGENT_C=old-agent-c', - 'BRIDGE_API_PORT=8427', - '', - ] - rotated = bridge_rotate_tokens.rotate_lines(lines, {'agent-a', 'agent-c'}) - values = {line.split('=', 1)[0]: line.split('=', 1)[1] for line in rotated if line.startswith('BRIDGE_TOKEN_')} - assert values['BRIDGE_TOKEN_AGENT_B'] == 'old-agent-b' - assert values['BRIDGE_TOKEN_AGENT_A'] != 'old-agent-a' - assert values['BRIDGE_TOKEN_AGENT_C'] != 'old-agent-c' - - -def test_rotate_tokens_dry_run_does_not_modify_file(tmp_path: Path, monkeypatch, capsys) -> None: - config = tmp_path / 'bridge_api.env' - original = '\n'.join([ - 'BRIDGE_TOKEN_AGENT_A=old-agent-a', - 'BRIDGE_TOKEN_AGENT_B=old-agent-b', - 'BRIDGE_TOKEN_AGENT_C=old-agent-c', - '', - ]) - config.write_text(original, encoding='utf-8') - - monkeypatch.setattr('sys.argv', ['bridge_rotate_tokens.py', '--config', str(config), '--agents', 'agent-a', '--dry-run']) - bridge_rotate_tokens.main() - out = capsys.readouterr().out - - assert 'dry_run: yes' in out - assert config.read_text(encoding='utf-8') == original diff --git a/tests/test_bridge_service.py b/tests/test_bridge_service.py deleted file mode 100644 index 2729947..0000000 --- a/tests/test_bridge_service.py +++ /dev/null @@ -1,252 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -import pytest - -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.frontmatter import parse_frontmatter -from bridge_core.models import CreateHandoffInput -from bridge_core.policy import StatusPolicyError -from bridge_core.service import BridgeService - - -def _build_service(tmp_path: Path) -> tuple[BridgeService, Path]: - root = tmp_path / "agent-shared" - bridge = root / "bridge" - repo = FileBridgeRepository(bridge_root=bridge) - return BridgeService(repository=repo), bridge - - -def test_create_handoff_writes_dual_queue_files_and_defaults(tmp_path: Path) -> None: - service, bridge = _build_service(tmp_path) - - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Need follow-up", - requested_action="Handle it", - minimal_context="Only what is needed", - related_paths=["/tmp/example.md"], - ) - ) - - outgoing = bridge / "outgoing" / "agent-a" / f"{handoff.handoff_id}.md" - incoming = bridge / "incoming" / "agent-c" / f"{handoff.handoff_id}.md" - assert outgoing.exists() - assert incoming.exists() - - outgoing_data, outgoing_body = parse_frontmatter(outgoing.read_text(encoding="utf-8")) - incoming_data, incoming_body = parse_frontmatter(incoming.read_text(encoding="utf-8")) - assert outgoing_data == incoming_data - assert outgoing_body == incoming_body - assert handoff.status == "open" - assert handoff.handoff_kind == "request" - assert handoff.risk_level == "low" - assert handoff.due_at == "none" - assert handoff.approval_context == "none" - assert handoff.resolution_summary == "pending" - - -def test_create_handoff_rejects_invalid_domain_values(tmp_path: Path) -> None: - service, _bridge = _build_service(tmp_path) - - with pytest.raises(ValueError, match="invalid handoff_kind"): - service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Need follow-up", - requested_action="Handle it", - minimal_context="Only what is needed", - handoff_kind="weird", - ) - ) - - with pytest.raises(ValueError, match="invalid priority"): - service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Need follow-up", - requested_action="Handle it", - minimal_context="Only what is needed", - priority="p0", - ) - ) - - with pytest.raises(ValueError, match="invalid risk_level"): - service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Need follow-up", - requested_action="Handle it", - minimal_context="Only what is needed", - risk_level="severe", - ) - ) - - -def test_create_handoff_sanitizes_frontmatter_injected_values(tmp_path: Path) -> None: - service, bridge = _build_service(tmp_path) - - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="hello\nstatus: archived", - requested_action="Handle it", - minimal_context="Only what is needed", - related_paths=["/tmp/example.md\nstatus: archived"], - ) - ) - - outgoing = bridge / "outgoing" / "agent-a" / f"{handoff.handoff_id}.md" - data, _body = parse_frontmatter(outgoing.read_text(encoding="utf-8")) - assert data["status"] == "open" - assert data["subject"] == "hello status: archived" - assert data["related_paths"] == ["/tmp/example.md status: archived"] - - -def test_list_handoffs_returns_all_or_only_active(tmp_path: Path) -> None: - service, _bridge = _build_service(tmp_path) - - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Need follow-up", - requested_action="Handle it", - minimal_context="Only what is needed", - ) - ) - service.set_status(handoff.handoff_id, actor="agent-c", status="closed", outcome="Done.") - - assert service.list_handoffs("agent-c") == [] - all_items = service.list_handoffs("agent-c", active_only=False) - assert len(all_items) == 1 - assert all_items[0].handoff_id == handoff.handoff_id - assert all_items[0].status == "closed" - - -def test_set_status_updates_both_copies_and_archives_preserving_divergent_copy(tmp_path: Path) -> None: - service, bridge = _build_service(tmp_path) - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Lifecycle", - requested_action="Handle it", - minimal_context="Only what is needed", - ) - ) - - service.set_status(handoff.handoff_id, actor="agent-c", status="acked", acknowledgment_source="auto") - closed = service.set_status( - handoff.handoff_id, - actor="agent-c", - status="closed", - outcome="Finished safely.", - ) - assert closed.status == "closed" - assert closed.resolution_summary == "Finished safely." - - outgoing = bridge / "outgoing" / "agent-a" / f"{handoff.handoff_id}.md" - incoming = bridge / "incoming" / "agent-c" / f"{handoff.handoff_id}.md" - incoming.write_text(incoming.read_text(encoding="utf-8") + "\n\n", encoding="utf-8") - - archive_dir = service.archive_handoff(handoff.handoff_id, actor="agent-c") - canonical = archive_dir / f"{handoff.handoff_id}.md" - alternate = archive_dir / f"{handoff.handoff_id}.incoming.agent-c.md" - - assert archive_dir.exists() - assert canonical.exists() - assert alternate.exists() - assert not outgoing.exists() - assert not incoming.exists() - - archived_data, archived_body = parse_frontmatter(canonical.read_text(encoding="utf-8")) - assert archived_data["status"] == "archived" - assert archived_data["acknowledgment_source"] == "auto" - assert archived_data["acknowledged_at"] != "none" - assert archived_data["resolution_summary"] == "Finished safely." - assert "## Outcome\nFinished safely." in archived_body - - audit_lines = (bridge / "audit" / "handoff-log.md").read_text(encoding="utf-8").strip().splitlines() - assert len(audit_lines) == 4 - assert " | open | Lifecycle" in audit_lines[0] - assert " | acknowledged | Lifecycle | ack_source=auto acknowledged_at=" in audit_lines[1] - assert " | closed | Lifecycle" in audit_lines[2] - assert " | archived | Lifecycle" in audit_lines[3] - - -def test_set_status_rejects_unknown_acknowledgment_source(tmp_path: Path) -> None: - service, _bridge = _build_service(tmp_path) - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Bad ack source", - requested_action="Handle it", - minimal_context="Only what is needed", - ) - ) - - with pytest.raises(StatusPolicyError, match="acknowledgment_source must be auto or manual"): - service.set_status(handoff.handoff_id, actor="agent-c", status="acknowledged", acknowledgment_source="bot") - - -def test_set_status_uses_one_timestamp_and_preserves_sections_after_outcome(tmp_path: Path) -> None: - service, bridge = _build_service(tmp_path) - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-c", - issue_type="task", - subject="Outcome preservation", - requested_action="Handle it", - minimal_context="Only what is needed", - ) - ) - - incoming = bridge / "incoming" / "agent-c" / f"{handoff.handoff_id}.md" - data, body = parse_frontmatter(incoming.read_text(encoding="utf-8")) - body = body.rstrip() + "\n## Notes\nKeep this section.\n" - incoming.write_text("---\n" + "\n".join(f"{k}: {v}" if not isinstance(v, list) else f"{k}:\n" + "\n".join(f" - {item}" for item in v) for k, v in data.items()) + "\n---\n\n" + body.lstrip("\n"), encoding="utf-8") - - service.set_status(handoff.handoff_id, actor="agent-c", status="closed", outcome="Finished safely.") - - outgoing = bridge / "outgoing" / "agent-a" / f"{handoff.handoff_id}.md" - outgoing_data, outgoing_body = parse_frontmatter(outgoing.read_text(encoding="utf-8")) - incoming_data, incoming_body = parse_frontmatter(incoming.read_text(encoding="utf-8")) - assert outgoing_data["updated_at"] == incoming_data["updated_at"] - assert "## Notes\nKeep this section." in incoming_body - assert "## Outcome\nFinished safely.\n## Notes\nKeep this section." in incoming_body - assert outgoing_body.count("## Outcome") == 1 - - -def test_archive_requires_closed_status(tmp_path: Path) -> None: - service, _bridge = _build_service(tmp_path) - handoff = service.create_handoff( - CreateHandoffInput( - sender="agent-a", - recipient="agent-b", - issue_type="task", - subject="Still open", - requested_action="Handle it", - minimal_context="Only what is needed", - ) - ) - - with pytest.raises(StatusPolicyError, match="only closed or cancelled handoffs can be archived"): - service.archive_handoff(handoff.handoff_id, actor="agent-b") diff --git a/tests/test_bridge_v2_reliability.py b/tests/test_bridge_v2_reliability.py deleted file mode 100644 index 11dc8a4..0000000 --- a/tests/test_bridge_v2_reliability.py +++ /dev/null @@ -1,491 +0,0 @@ -from __future__ import annotations - -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path -import json - -import pytest - -from bridge_core.file_repository import FileBridgeRepository -from bridge_core.frontmatter import dump_document, parse_frontmatter -from bridge_core.models import CreateHandoffInput, HandoffRecord -from bridge_core.policy import AccessPolicyError -from bridge_core.repository import IdempotencyConflictError, RepositoryConflictError, RevisionConflictError -from bridge_core.service import BridgeService - - -def _request(*, key: str = "create-1", subject: str = "Bridge v2") -> CreateHandoffInput: - return CreateHandoffInput( - sender="agent-a", - recipient="agent-b", - issue_type="task", - subject=subject, - requested_action="Perform the bounded work.", - minimal_context="Reliability regression test.", - idempotency_key=key, - correlation_id="CORR-1", - causation_id="CAUSE-1", - ) - - -def _service(tmp_path: Path, **repo_kwargs) -> tuple[BridgeService, FileBridgeRepository]: - repository = FileBridgeRepository(tmp_path / "bridge", **repo_kwargs) - return BridgeService(repository), repository - - -def _write_v1_handoff(root: Path, *, handoff_id: str = "HND-V1-0001") -> HandoffRecord: - record = HandoffRecord( - handoff_id=handoff_id, - status="open", - created_at="2026-01-01T00:00:00Z", - updated_at="2026-01-01T00:00:00Z", - acknowledged_at="none", - acknowledgment_source="none", - sender="agent-a", - recipient="agent-b", - issue_type="task", - subject="Legacy handoff", - body="## Outcome\n- pending\n", - ) - frontmatter = record.to_frontmatter() - for key in ( - "schema_version", - "revision", - "correlation_id", - "causation_id", - "canonical_request_hash", - "idempotency_key_hash", - ): - frontmatter.pop(key) - document = dump_document(frontmatter, record.body) - for path in ( - root / "outgoing" / "agent-a" / f"{handoff_id}.md", - root / "incoming" / "agent-b" / f"{handoff_id}.md", - ): - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(document, encoding="utf-8") - return record - - -def test_concurrent_identical_create_requests_produce_one_handoff(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - - with ThreadPoolExecutor(max_workers=8) as executor: - records = list(executor.map(lambda _index: service.create_handoff(_request()), range(16))) - - assert len({record.handoff_id for record in records}) == 1 - assert len(list(repository.records_root.glob("*.md"))) == 1 - assert len(repository.list_events()) == 1 - - -def test_same_idempotency_key_with_different_payload_conflicts(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - service.create_handoff(_request()) - - with pytest.raises(IdempotencyConflictError, match="different request payload"): - service.create_handoff(_request(subject="Materially different")) - assert list(repository.transactions_root.glob("*.json")) == [] - - -def test_create_conflict_removes_unrecoverable_prepared_transaction(tmp_path: Path, monkeypatch) -> None: - service, repository = _service(tmp_path) - request = _request() - request.idempotency_key = None - existing = HandoffRecord.from_create(request) - repository.create(existing) - monkeypatch.setattr(HandoffRecord, "from_create", lambda _request: existing) - - with pytest.raises(RepositoryConflictError, match="handoff already exists"): - service.create_handoff(request) - - assert list(repository.transactions_root.glob("*.json")) == [] - - -def test_crash_after_first_mirror_write_is_recoverable(tmp_path: Path) -> None: - def fail_after_outgoing(stage: str) -> None: - if stage == "after_outgoing_write": - raise RuntimeError("simulated crash") - - root = tmp_path / "bridge" - crashing_service = BridgeService(FileBridgeRepository(root, fault_injector=fail_after_outgoing)) - with pytest.raises(RuntimeError, match="simulated crash"): - crashing_service.create_handoff(_request()) - - repository = FileBridgeRepository(root) - recovered = BridgeService(repository).create_handoff(_request()) - outgoing = root / "outgoing" / "agent-a" / f"{recovered.handoff_id}.md" - incoming = root / "incoming" / "agent-b" / f"{recovered.handoff_id}.md" - assert outgoing.exists() and incoming.exists() - recovered_event_ids = repository.recover_transactions() - assert len(recovered_event_ids) == 1 - assert repository.list_events()[0].event_id == recovered_event_ids[0] - - -def test_retry_rebuilds_missing_idempotency_index_after_crash(tmp_path: Path, monkeypatch) -> None: - service, repository = _service(tmp_path) - original_atomic_write_json = repository._atomic_write_json - failed = False - - def fail_first_index_write(path, payload): - nonlocal failed - if repository.idempotency_root in path.parents and not failed: - failed = True - raise RuntimeError("simulated index-write crash") - return original_atomic_write_json(path, payload) - - monkeypatch.setattr(repository, "_atomic_write_json", fail_first_index_write) - with pytest.raises(RuntimeError, match="simulated index-write crash"): - service.create_handoff(_request()) - - orphan_id = next(repository.records_root.glob("*.md")).stem - assert list(repository.idempotency_root.glob("*/*.json")) == [] - monkeypatch.setattr(repository, "_atomic_write_json", original_atomic_write_json) - - recovered = service.create_handoff(_request()) - - assert recovered.handoff_id == orphan_id - assert len(list(repository.records_root.glob("*.md"))) == 1 - assert len(list(repository.idempotency_root.glob("*/*.json"))) == 1 - assert len(list(repository.transactions_root.glob("*.json"))) == 1 - recovered_event_ids = repository.recover_transactions() - assert len(recovered_event_ids) == 1 - assert repository.list_events()[0].handoff_id == orphan_id - - -def test_recovery_does_not_enqueue_stale_prepared_event(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - created = service.create_handoff(_request()) - created_event = service.list_outbox()[0] - repository.complete_event(created_event.event_id) - event_path = repository._event_path(created_event.event_id) - event_path.unlink() - repository.prepare_event(created_event) - - service.set_status(created.handoff_id, actor="agent-b", status="acknowledged", expected_revision=0) - - assert repository.recover_transactions() == [] - assert not event_path.exists() - assert (repository.transactions_root / f"{created_event.event_id}.json").exists() - - -def test_stale_transaction_can_be_explicitly_enqueued_with_resolution_evidence(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - created = service.create_handoff(_request()) - created_event = service.list_outbox()[0] - repository.complete_event(created_event.event_id) - event_path = repository._event_path(created_event.event_id) - event_path.unlink() - repository.prepare_event(created_event) - service.set_status(created.handoff_id, actor="agent-b", status="acknowledged", expected_revision=0) - - resolved = service.resolve_transaction( - created_event.event_id, - action="enqueue", - reason="Verified missing historical create delivery after canonical state advanced.", - ) - - assert resolved.event_id == created_event.event_id - assert event_path.exists() - assert not (repository.transactions_root / f"{created_event.event_id}.json").exists() - evidence = repository.resolved_transactions_root / f"{created_event.event_id}.json" - payload = json.loads(evidence.read_text(encoding="utf-8")) - assert payload["action"] == "enqueue" - assert payload["reason"].startswith("Verified missing historical") - - -def test_transaction_resolution_rejects_path_traversal_event_id(tmp_path: Path) -> None: - _service_instance, repository = _service(tmp_path) - - with pytest.raises(ValueError, match="invalid event_id"): - repository.resolve_transaction("../outside", action="discard", reason="invalid input") - with pytest.raises(ValueError, match="invalid event_id"): - repository.resolve_transaction("EVT-valid\nforged", action="discard", reason="invalid input") - - -def test_transaction_resolution_rejects_payload_event_id_mismatch(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - service.create_handoff(_request()) - event = service.list_outbox()[0] - repository._event_path(event.event_id).unlink() - repository.prepare_event(event) - transaction_path = repository._transaction_path(event.event_id) - payload = json.loads(transaction_path.read_text(encoding="utf-8")) - payload["event"]["event_id"] = "EVT-substituted" - transaction_path.write_text(json.dumps(payload), encoding="utf-8") - - with pytest.raises(RepositoryConflictError, match="event_id mismatch"): - service.resolve_transaction(event.event_id, action="enqueue", reason="must fail closed") - with pytest.raises(RepositoryConflictError, match="event_id mismatch"): - repository.recover_transactions() - - assert transaction_path.exists() - assert not repository._event_path("EVT-substituted").exists() - assert any("event_id mismatch" in issue for issue in repository.diagnose()) - - -def test_prepared_transaction_can_be_discarded_with_resolution_evidence(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - service.create_handoff(_request()) - event = service.list_outbox()[0] - repository._event_path(event.event_id).unlink() - repository.prepare_event(event) - - with pytest.raises(ValueError, match="still recoverable"): - service.resolve_transaction( - event.event_id, - action="discard", - reason="Must not discard a recoverable event by default.", - ) - assert repository._transaction_path(event.event_id).exists() - - resolved = service.resolve_transaction( - event.event_id, - action="discard", - reason="Verified duplicate consumer delivery; no replay required.\n- not a second audit entry", - force_recoverable_discard=True, - ) - - assert resolved.event_id == event.event_id - assert not repository._event_path(event.event_id).exists() - evidence = json.loads(repository._resolved_transaction_path(event.event_id).read_text(encoding="utf-8")) - assert evidence["action"] == "discard" - assert evidence["canonical_match"] is True - assert evidence["force_recoverable_discard"] is True - assert len(repository.audit_file.read_text(encoding="utf-8").splitlines()) == 2 - - -def test_stale_delivery_failure_cannot_regress_delivered_event(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - service.create_handoff(_request()) - event = service.list_outbox()[0] - stale_copy = type(event).from_mapping(event.to_dict()) - - delivered = service.mark_event_delivered(event.event_id) - stale_result = service._mark_event_failed( - stale_copy, - "late failure from concurrent deliverer", - max_attempts=3, - base_delay_seconds=0, - ) - - assert delivered.delivery_state == "delivered" - assert stale_result.delivery_state == "delivered" - assert repository.list_events()[0].delivery_state == "delivered" - - -def test_process_outbox_does_not_rescan_events_for_each_delivery(tmp_path: Path, monkeypatch) -> None: - service, repository = _service(tmp_path) - for index in range(4): - service.create_handoff(_request(key=f"batch-{index}", subject=f"Batch {index}")) - - original_list_events = repository.list_events - calls = 0 - - def counted_list_events(*, states=None): - nonlocal calls - calls += 1 - return original_list_events(states=states) - - monkeypatch.setattr(repository, "list_events", counted_list_events) - processed = service.process_outbox(lambda _event: (True, "ok")) - - assert len(processed) == 4 - assert calls == 1 - - -def test_status_update_leaves_queue_views_at_same_revision(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - created = service.create_handoff(_request()) - updated = service.set_status( - created.handoff_id, - actor="agent-b", - status="acknowledged", - expected_revision=0, - ) - - records = repository.load_records(created.handoff_id) - assert updated.revision == 1 - assert {stored.record.revision for stored in records} == {1} - assert {stored.record.status for stored in records} == {"acknowledged"} - - -def test_concurrent_lifecycle_updates_have_one_revision_conflict(tmp_path: Path) -> None: - service, _repository = _service(tmp_path) - created = service.create_handoff(_request()) - - def update(status: str): - return service.set_status( - created.handoff_id, - actor="agent-b", - status=status, - outcome="Waiting." if status == "blocked" else "", - expected_revision=0, - ) - - outcomes: list[object] = [] - with ThreadPoolExecutor(max_workers=2) as executor: - futures = [executor.submit(update, status) for status in ("acknowledged", "blocked")] - for future in futures: - try: - outcomes.append(future.result()) - except Exception as exc: # asserted below - outcomes.append(exc) - - assert sum(isinstance(item, HandoffRecord) for item in outcomes) == 1 - assert sum(isinstance(item, RevisionConflictError) for item in outcomes) == 1 - - -def test_consumer_outage_keeps_event_and_recovery_reuses_event_id(tmp_path: Path) -> None: - service, _repository = _service(tmp_path) - created = service.create_handoff(_request()) - event = service.list_outbox(states={"pending"})[0] - - failed = service.process_outbox( - lambda _event: (False, "consumer unavailable"), - max_attempts=3, - base_delay_seconds=0, - max_delay_seconds=0, - )[0] - assert failed.event_id == event.event_id - assert failed.delivery_state == "retrying" - - delivered_ids: list[str] = [] - processed = service.process_outbox( - lambda retry: (delivered_ids.append(retry.event_id) or True, "ok"), - ) - assert processed[0].delivery_state == "delivered" - assert delivered_ids == [event.event_id] - assert created.handoff_id == processed[0].handoff_id - - -def test_replay_preserves_event_id_and_supports_consumer_deduplication(tmp_path: Path) -> None: - service, _repository = _service(tmp_path) - service.create_handoff(_request()) - event = service.list_outbox()[0] - service.mark_event_delivered(event.event_id) - - replayed = service.replay_event(event.event_id) - assert replayed.event_id == event.event_id - seen: set[str] = {event.event_id} - duplicate_effects: list[str] = [] - - def deduplicating_consumer(item): - if item.event_id not in seen: - duplicate_effects.append(item.event_id) - seen.add(item.event_id) - return True, "deduplicated" - - service.process_outbox(deduplicating_consumer) - assert duplicate_effects == [] - - -def test_exhausted_retries_dead_letter_and_manual_replay(tmp_path: Path) -> None: - service, _repository = _service(tmp_path) - service.create_handoff(_request()) - event = service.list_outbox()[0] - - first = service.mark_event_failed(event.event_id, "down", max_attempts=2, base_delay_seconds=0, jitter_ratio=0) - assert first.delivery_state == "retrying" - second = service.mark_event_failed(event.event_id, "still down", max_attempts=2, base_delay_seconds=0, jitter_ratio=0) - assert second.delivery_state == "dead_letter" - replayed = service.replay_event(event.event_id) - assert replayed.delivery_state == "pending" - assert replayed.attempts == 0 - assert replayed.event_id == event.event_id - - -def test_role_specific_lifecycle_actions_fail_closed(tmp_path: Path) -> None: - service, _repository = _service(tmp_path) - created = service.create_handoff(_request()) - - with pytest.raises(AccessPolicyError, match="not authorized"): - service.set_status(created.handoff_id, actor="agent-a", status="closed", outcome="Not sender-owned.") - with pytest.raises(AccessPolicyError, match="not authorized"): - service.set_status(created.handoff_id, actor="agent-b", status="cancelled", outcome="Not recipient-owned.") - - cancelled = service.cancel_handoff(created.handoff_id, actor="agent-a", reason="Request withdrawn.") - assert cancelled.status == "cancelled" - - -def test_existing_v1_handoff_loads_and_transitions_to_v2(tmp_path: Path) -> None: - root = tmp_path / "bridge" - repository = FileBridgeRepository(root) - _write_v1_handoff(root) - - loaded = BridgeService(repository).get_handoff("HND-V1-0001") - assert loaded.schema_version == 1 - assert loaded.revision == 0 - transitioned = BridgeService(repository).set_status( - "HND-V1-0001", - actor="agent-b", - status="acknowledged", - expected_revision=0, - ) - assert transitioned.schema_version == 2 - assert transitioned.revision == 1 - assert repository._canonical_path("HND-V1-0001").exists() - - -def test_identical_v1_mirrors_are_not_divergence_and_migrate_without_conflicts(tmp_path: Path) -> None: - root = tmp_path / "bridge" - repository = FileBridgeRepository(root) - _write_v1_handoff(root) - - assert repository.reconcile_handoff("HND-V1-0001", repair=False) == [] - - issues = repository.reconcile_handoff("HND-V1-0001", repair=True) - canonical = repository._canonical_path("HND-V1-0001") - outgoing = root / "outgoing" / "agent-a" / "HND-V1-0001.md" - incoming = root / "incoming" / "agent-b" / "HND-V1-0001.md" - - assert issues == ["HND-V1-0001: missing canonical record"] - assert canonical.exists() - assert outgoing.read_bytes() == canonical.read_bytes() - assert incoming.read_bytes() == canonical.read_bytes() - assert list(repository.conflicts_root.glob("HND-V1-0001.*")) == [] - - -def test_repository_diagnostics_detect_new_failure_states(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - created = service.create_handoff(_request()) - incoming = repository.bridge_root / "incoming" / "agent-b" / f"{created.handoff_id}.md" - incoming.unlink() - - event = service.list_outbox()[0] - service.mark_event_failed(event.event_id, "down", max_attempts=1) - - index_path = next(repository.idempotency_root.glob("*/*.json")) - index = json.loads(index_path.read_text(encoding="utf-8")) - index["request_hash"] = "bad-hash" - index_path.write_text(json.dumps(index), encoding="utf-8") - - stale = service.create_handoff(_request(key="create-stale", subject="Stale mirror")) - stale_outgoing = repository.bridge_root / "outgoing" / "agent-a" / f"{stale.handoff_id}.md" - stale_data, stale_body = parse_frontmatter(stale_outgoing.read_text(encoding="utf-8")) - stale_data["revision"] = "99" - stale_outgoing.write_text(dump_document(stale_data, stale_body), encoding="utf-8") - - divergent = service.create_handoff(_request(key="create-divergent", subject="Divergent mirror")) - divergent_outgoing = repository.bridge_root / "outgoing" / "agent-a" / f"{divergent.handoff_id}.md" - divergent_outgoing.write_text(divergent_outgoing.read_text(encoding="utf-8") + "\nlocal divergence\n", encoding="utf-8") - - issues = repository.diagnose(pending_age_seconds=0) - assert any("missing mirror" in issue for issue in issues) - assert any("stale revision" in issue for issue in issues) - assert any("divergent mirror" in issue for issue in issues) - assert any("pending outbox event beyond threshold" in issue for issue in issues) - assert any("dead-letter event" in issue for issue in issues) - assert any("idempotency index inconsistency" in issue for issue in issues) - - -def test_reconcile_preserves_divergent_evidence_before_repair(tmp_path: Path) -> None: - service, repository = _service(tmp_path) - created = service.create_handoff(_request()) - incoming = repository.bridge_root / "incoming" / "agent-b" / f"{created.handoff_id}.md" - incoming.write_text(incoming.read_text(encoding="utf-8") + "\nlocal note\n", encoding="utf-8") - - issues = repository.reconcile_handoff(created.handoff_id, repair=True) - assert any("divergent mirror" in issue for issue in issues) - assert list(repository.conflicts_root.glob(f"{created.handoff_id}.*.incoming.md")) - canonical = repository._canonical_path(created.handoff_id) - assert incoming.read_bytes() == canonical.read_bytes() diff --git a/tests/test_bridge_wrappers.py b/tests/test_bridge_wrappers.py deleted file mode 100644 index 117fee0..0000000 --- a/tests/test_bridge_wrappers.py +++ /dev/null @@ -1,98 +0,0 @@ -from __future__ import annotations - -import json -import subprocess -import sys -from pathlib import Path - -import pytest - -import bridge_agent - - -def test_generic_wrapper_create_uses_explicit_agent_identity(monkeypatch, capsys): - captured = {} - - def fake_api_request(agent, method, path, *, payload=None): - captured['agent'] = agent - captured['method'] = method - captured['path'] = path - captured['payload'] = payload - return { - 'handoff_id': 'HND-TEST-001', - 'sender': 'agent-a', - 'recipient': 'agent-b', - } - - def fake_invoke(agent, args, *, api_call, cli_args): - captured['invoke_agent'] = agent - captured['cli_args'] = cli_args - print(json.dumps(api_call())) - - monkeypatch.setattr(bridge_agent, 'api_request', fake_api_request) - monkeypatch.setattr(bridge_agent, 'invoke', fake_invoke) - monkeypatch.setattr( - sys, - 'argv', - [ - 'bridge_agent.py', - '--agent', 'agent-a', - 'create', - '--recipient', 'agent-b', - '--issue-type', 'task', - '--subject', 'API wrapper test', - '--requested-action', 'Do the thing', - '--minimal-context', 'Minimal context', - '--idempotency-key', 'wrapper-create-1', - ], - ) - - bridge_agent.main() - payload = json.loads(capsys.readouterr().out) - - assert captured['agent'] == 'agent-a' - assert captured['invoke_agent'] == 'agent-a' - assert captured['method'] == 'POST' - assert captured['path'] == '/v1/handoffs' - assert 'sender' not in captured['payload'] - assert captured['payload']['recipient'] == 'agent-b' - assert captured['payload']['idempotency_key'] == 'wrapper-create-1' - assert '--sender' in captured['cli_args'] - assert captured['cli_args'][captured['cli_args'].index('--sender') + 1] == 'agent-a' - assert captured['cli_args'][captured['cli_args'].index('--idempotency-key') + 1] == 'wrapper-create-1' - assert payload['handoff_id'] == 'HND-TEST-001' - assert payload['outbox'].endswith('/outgoing/agent-a/HND-TEST-001.md') - assert payload['inbox'].endswith('/incoming/agent-b/HND-TEST-001.md') - - -def test_generic_wrapper_refuses_cli_fallback_unless_enabled(monkeypatch): - monkeypatch.setattr(bridge_agent, 'api_request', lambda *args, **kwargs: (_ for _ in ()).throw(ConnectionError('down'))) - monkeypatch.setattr( - sys, - 'argv', - [ - 'bridge_agent.py', - '--agent', 'agent-a', - 'list-open', - ], - ) - - with pytest.raises(SystemExit, match='bridge API unavailable'): - bridge_agent.main() - - -def test_bridge_agent_script_runs_directly_from_repo_root(): - repo_root = Path(__file__).resolve().parents[1] - result = subprocess.run( - [ - sys.executable, - str(repo_root / 'scripts' / 'bridge_agent.py'), - '--help', - ], - cwd=repo_root, - capture_output=True, - text=True, - ) - - assert result.returncode == 0, result.stderr or result.stdout - assert 'Generic Bridge wrapper for any configured agent' in result.stdout