Fork of agent-orchestrator for the agent-messenger integration (Habitat identities, launch/messaging adapters); upstream stays read-only
README.md

agent-orchestrator #

A generic, reusable harness for running and supervising a fleet of AI-agent sessions in tmux. One driver script + one declarative config (agents.toml) describe every agent — a Builder / Adversary loop pair, a persistent supervisor, a one-shot task — and a watchdog keeps them alive, healed, paced, and coordinated. The watchdog reloads project configuration every tick; its polling intervals are captured when it starts.

The driver takes project paths, kickoff prompts, handoff conventions and completion hooks from the project's config. This repository also includes examples and operational tools. The intended deployment uses one shared checkout and one fleet config per server; projects keep their own prompts and coordination records. Legacy configs remain supported.

agents.py            the driver + watchdog (pure Python stdlib; needs python >= 3.11 for tomllib)
agent-log.py         render claude JSONL transcripts into clean, greppable logs
scripts/agent-message.py  attributed, allowlisted, delivery-verified inter-agent transport
scripts/agent-tail.py     read durable Claude/Codex transcripts and report ended-turn state
agents.example.toml  a self-contained 2-agent example project
prompts/             generic role + kickoff templates (builder / adversary / kickoff)
examples/            runnable example projects — the Builder/Adversary variant family, snakepit, …
smoke.sh             bring the example up + tear it down in an isolated sandbox, then clean up
tests/               the test suite — unit tests + isolated live backend smokes + a runner
flake.nix/.lock      a Nix devShell with the runtime deps (python311, tmux, git)

Concepts #

CONCEPTS.md lists every concept in the harness with the constraint that makes it work — agents and lifecycle, backends, prompts and phases, supervision, state and secrets, inter-agent communication, external surfaces, testing. This README is the reference; that is the checklist. Read it to verify that how you start agents and how they talk to each other matches what was intended.

Quick start #

nix develop                                   # python311 + tmux + git on PATH (see "Nix" below)

python3 agents.py selftest                    # regression-test the activity detector (no config)
python3 agents.py status --config agents.example.toml   # one table: every agent + the phase
./smoke.sh                                    # prove up/down works end-to-end, isolated + clean

python3 agents.py init myproject              # scaffold a starter agents.toml + prompts/

up is use-or-create: an already-running session is left alone, never double-started.

python3 agents.py --config agents.toml up           # start all enabled agents + services + watchdog
python3 agents.py --config agents.toml up builder    # start just one agent (by name)
python3 agents.py --config agents.toml down          # stop everything
python3 agents.py --config agents.toml logs builder  # tail one session's log
python3 agents.py --config agents.toml phase show    # where the loop phase machine is
python3 scripts/agent-message.py --config agents.toml --list
python3 scripts/agent-message.py --config agents.toml adversary 'Review exact tip abc123'
python3 scripts/agent-tail.py --config agents.toml --status

--config defaults to ./agents.toml, falling back to one next to agents.py.

Messaging an existing Codex session without tmux #

agent-message.py can queue directly through a shared Codex app-server. Register the existing session in agents.toml; do not launch or resume a second copy:

[[agent]]
name = "supervisor"
backend = "codex"
enabled = false               # externally started; omit from bare `up`
watch = "none"
delivery = "codex"            # default remains "tmux"
thread_id = "01a06fbc-1b1d-71f1-ad1e-59fe24ff0bac" # replace with actual CODEX_THREAD_ID
remote_addr = "unix://"       # defaults to backend.remote_addr, then unix://
may_message = ["adversary"]

The [backend.codex] bin must be a Codex executable supporting queue --remote --thread --message. The recipient must be hosted by that app-server; starting a separate stdio server cannot reach another runtime's live session. This adds message delivery, not headless agent launching or supervision. Never explicitly run agents.py up supervisor for this externally managed entry.

Both sides use the usual agent-message.py <name> '<message>' command and need reciprocal may_message entries. Register each Codex sender's CODEX_THREAD_ID (also supported on tmux-delivered agents). With a thread registry present, an unregistered Codex thread fails closed instead of borrowing the shared daemon's environment or working directory. Proven tmux process ancestry still takes precedence over inherited thread environment, preserving attribution for pane-owned tools on other backends. Duplicate names, session identities and thread IDs are rejected. Update the registry when an agent starts a new thread; resume keeps the existing ID.

Messages retain the agent-origin header and private outcome log. Thread-derived labels carry (by thread); like environment/cwd attribution, this is cooperative attribution, not authentication against a hostile process. Queue acceptance is not a read receipt. Sends have a 30-second timeout and are never retried automatically: after a failure/timeout, check the recipient before resending.


Examples #

examples/ holds runnable example projects — copy one, point agents.py at its agents.toml, and go. The headline set is a family of Builder/Adversary variants that build the same task but each differ in one dimension — useful both as templates and as a study of the pattern:

  • builder-adversary — the canonical loop pair: a Builder that builds and an Adversary that cold-verifies every claim, coordinating only through git (claim(/review( commits + the watchdog handoff). Start here.
  • builder-adversary-min — the same pattern with the prompts compressed to minimal tokens.
  • builder-adversary-stateless — builder-adversary + context hygiene (compact at each checkpoint, read diffs not trees, lean loads) to minimise carried/reloaded context.
  • builder-adversary-lean — context hygiene + per-gate review (one claim/verdict per gate).
  • builder-adversary-deferred — the Adversary verifies once, after the whole build, in a final comprehensive review phase (vs per-phase / per-gate).
  • builder-solo — a single Builder that self-certifies, with no Adversary (the control).
  • snakepit — a different topology entirely: a pool of identical worker "snakes" pulling tasks from a shared filesystem queue, plus cleanup specialists. (examples/IDEAS.md sketches more.)

Each example has its own README.md. Run one by hand:

cd examples/builder-adversary
python3 ../../agents.py status --config agents.toml      # read-only
python3 ../../agents.py up     --config agents.toml       # needs `claude` on PATH

Benchmark. The separate agent-orchestrator-benchmark repo runs these Builder/Adversary variants head-to-head (N=5, real agents.py up runs) to measure what drives token cost. Short version: an independent adversary costs ~4.7× a solo builder, but the review cadence (per-gate / per-phase / deferred) is nearly token-neutral, and context hygiene is the one clean ~−22% win. See that repo's FINDINGS.md.


The config: agents.toml #

Configuration sections are [watchdog], [backend.<name>], [defaults], [project.<name>], [[agent]], [[service]], [loop], and optional [pipeline]. See agents.example.toml for a runnable example.

[watchdog] — global supervisor cadence #

[watchdog]
# systemd_unit         = "my-agent-watchdog.service" # optional: external lifecycle owner
signal_interval      = 30    # seconds between light checks (handoff / stall / limit)
heavy_interval       = 300   # seconds between heal + phase-advance checks
limit_probe_fallback = 300   # re-probe cadence for a usage-limited agent when reset time is unparsable
limit_reset_slack    = 45    # seconds to wait past a parsed reset before probing
stall_grace          = 180   # seconds of slack past a WAITING-UNTIL marker before a stall reboot
log_tokens           = false # opt-in: record per-phase token + time usage (see below)

Per-phase token + time logging (log_tokens). Set log_tokens = true (under [watchdog] or [loop]) and the watchdog records, for each phase, how many tokens each agent used and how long the phase took — appended as one JSON object per phase to <log_dir>/token-log.jsonl. Tokens are summed from each agent's Claude Code session transcript and attributed by working dir, so give each agent its own dir (the Builder/Adversary loop pair already uses separate clones) for accurate per-agent numbers. The watchdog snapshots a baseline when a phase starts and writes the delta (per agent, and the total) when the phase advances or the sequence completes — robust across watchdog restarts. Pretty-print it with agents.py tokens:

phase        dur(s)   builder adversary         TOTAL
-----------------------------------------------------
lex           372.0 3,910,118 3,221,447     7,131,565
parse         410.5 ...

[defaults] — inherited by every agent #

[defaults]
session_prefix = "myproj-"   # REQUIRED: fleet watchdog/service namespace; agent fallback.
log_dir        = ".ao-state" # Required unless agents_root supplies its .ao-state default.
backend        = "claude"
model          = "claude-sonnet-4-6"
dir            = "."         # explicit default cwd wins over agents_root; omit for per-agent dirs
watch          = "heal"      # none | heal | heal+stall
project_dir    = "."         # OPTIONAL: project root for resolving prompts/paths (default: config's dir)

session_prefix is required. log_dir is required in legacy configs; with agents_root, it defaults to <agents_root>/.ao-state. The harness has no project-specific fallbacks. Every relative path (log_dir, an agent's dir, handoff.repo, prompt/template files) resolves against project_dir, which defaults to the directory holding the config file. When the config lives in a sandbox but the prompts live elsewhere (as smoke.sh does), set project_dir explicitly.

Shared server workspaces #

[defaults]
agents_root = "/srv/agents"
engine_root = "/srv/agent-orchestrator" # optional; this is the shared-mode default
session_prefix = "fleet-"
# Omit dir and log_dir to use <agents_root>/<name> and <agents_root>/.ao-state.

[project.example]
session_prefix = "example-"

[[project.example.repo]]
name = "app"
url = "git@tangled.org:your-handle/app"
policy = "retrospective-review"

[[agent]]
name = "example-builder"
project = "example"
backend = "claude" # declare backend.claude as in the example config

An agent's explicit dir wins, then defaults.dir, then the root/name fallback. Without agents_root, the legacy . fallback remains. Launch, messaging and transcript lookup use ao_layout.agent_dir. Host aliases in configured parents (such as /srv) resolve consistently. Agent names remain globally unique; explicit session wins over the project prefix, then the defaults prefix. Duplicate names, resolved sessions (including services/watchdog), and registered thread IDs are refused. Existing message allowlists still apply.

python3 /srv/agent-orchestrator/agents.py --config /srv/agents/agents.toml provision example-builder
python3 /srv/agent-orchestrator/agents.py --config /srv/agents/agents.toml link-engine /srv/example

provision requires shared mode and an assigned project. It checks all existing destinations before adding missing clones; a matching clean clone is unchanged, including its branch and revision. It refuses dirty repos, unexpected workspace contents, wrong origins, non-repositories and redirected destination paths. Repository names must be single path components; URLs must match their stored origin. Use absolute paths for local repository URLs. Git failure leaves the workspace for inspection: fix or archive it explicitly, then retry. No reset, pull, overwrite or directory deletion is performed.

The agent-orchestrator repo name is reserved for a worktree of engine_root. Its URL must exactly match the live engine's origin; other repo entries with that same URL also use worktrees. New worktrees start detached at live main; create a branch before editing. Provisioning never fetches or changes live working files. link-engine requires an existing project and live engine, adds references/agent-orchestrator, and leaves an identical link alone. It refuses an occupied destination or redirected references directory.

Shared-mode up and watchdog healing use provisioning before launch, but permit ongoing edits and workspace artifacts. A legacy repository used as the cwd is left in its existing layout until explicitly migrated. A partial/invalid clone prevents launch on retries too; a forced restart preflights before killing the current session. Already-running sessions remain untouched. Neither explicit provision nor link-engine starts a session or watchdog.

[backend.<name>] — backends declared as data #

A backend is fully described by config — no code change to add one. The one field that selects behavior is prompt_delivery:

prompt_delivery how the kickoff reaches the agent example
"arg" passed as a CLI argument (claude-style) claude … "$(cat kickoff)"
"ping" typed in after a TUI connects (opencode-style) attach, wait, send-keys
"exec" a plain command; the prompt is written to a file generic / demo
[backend.claude]
bin             = "claude"
flags           = "--dangerously-skip-permissions"
remote_control  = true          # add a --remote-control <session> flag
supports_resume = true          # honor an agent's resume=true
prompt_delivery = "arg"
process_name    = "claude"      # the pane process a healthy session runs (backend-mismatch healing)
submit_key      = "Enter"       # key to submit a typed message
stall_idle      = 300           # seconds idle before a heal+stall agent is rebooted
active_re = "esc to interrupt|Running tool|· \\d+"   # pane shows the agent is WORKING
limit_re  = "usage limit|limit reached|reached your .*limit"   # usage/rate-limit banner
limit_ignore_re = "limit resets? available"   # a line matching both is NOT a limit (default shown; the Codex idle hint)
fatal_re  = "redacted_thinking|cannot be modified"  # unrecoverable session state → kill + restart

[backend.opencode]              # a TUI backend
bin             = "opencode"
attach          = "{bin} attach {server} --dir {dir}"
server          = "http://127.0.0.1:4096"
prompt_delivery = "ping"
process_name    = "opencode"
footer_ui       = true          # a static footer lingers after a turn → only the bottom = activity
log_grace       = 180           # within this many seconds of a log write, treat as active
connect_delay   = 12            # seconds to wait for the TUI before typing
submit_key      = "C-m"
model_env       = true          # pass the model via OPENCODE_CONFIG_CONTENT
preamble        = "set -a; . ./.env; set +a"   # shell run before launch (e.g. load creds)
active_re = "esc interrupt|thinking|running tool|preparing patch"
limit_re  = "usage limit|limit reached"

[backend.codex]                 # Codex TUI, exposed through Codex Remote Control
bin             = "codex"
preamble        = "{bin} remote-control start --json >/dev/null"
remote_addr     = "unix://"    # connect the TUI to that daemon (one shared thread writer)
flags           = "--dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust --no-alt-screen"
supports_resume = false         # thread-ID persistence is not implemented by this harness
prompt_delivery = "arg"
process_name    = "codex"
footer_ui       = true
log_grace       = 180
submit_key      = "Enter"
startup_prompt_re       = "Trusting the directory|Do you trust"
startup_prompt_response = "1" # explicitly trust the agent's configured working directory
startup_prompt_delay    = 2
stall_idle      = 300
active_re = "esc to interrupt|working|thinking|running|searching|exploring|implementing"
limit_re  = "usage limit|limit reached|reached your .*limit|out of (credits|tokens)"
fatal_re  = "connection is errored|not logged in|authentication required"

[backend.demo]                  # a dependency-free backend for testing the harness mechanics
bin             = "echo '[demo] {session} up'; exec sleep 1000000"
prompt_delivery = "exec"        # {kickoff}=prompt file, {session}=session name, {model}=model

For an "arg" backend the flag templates are configurable (so you can point at a non-claude CLI): resume_flag (default --resume '{id}'), model_flag (default --model '{model}'), remote_control_flag (default --remote-control '{session}'), remote_addr_flag (default --remote '{addr}'), and remote_cwd_flag (default -C {dir} whenever remote_addr is set). A backend that sets process_name participates in backend-mismatch healing; one that doesn't (e.g. demo) never does. An optional preamble runs first and must succeed before the TUI starts; it supports {bin}, {session}, {model}, and {dir} templates. The Codex backend uses it to idempotently start the shared Remote Control daemon, then uses remote_addr = "unix://" to connect each tmux-hosted Codex TUI to that daemon. The accompanying -C is required because the daemon's process directory is independent of the agent's. This keeps the app-server as the sole thread-store writer while local and Remote clients share the session in the configured project directory. For an unattended TUI with a deterministic first-run gate, startup_prompt_re opts into one screen check after startup_prompt_delay seconds; on a match, the harness types the explicitly configured startup_prompt_response and submit_key. Codex uses this to trust the agent's configured project directory so its argv kickoff can proceed.

[[agent]] — one block per agent #

[[agent]]
name    = "builder"            # tmux session defaults to <session_prefix><name>; override with session=
kind    = "loop"              # loop | persistent | task
backend = "claude"            # overrides defaults.backend
model   = "claude-opus-4-8"   # overrides defaults.model
dir     = "."                 # working dir (relative → project dir)
role    = "builder"           # loop agents only: role prompt = <roles_dir>/<role>.md
resume  = true                # (arg backends with supports_resume) --resume <state/<name>.id>
watch   = "heal+stall"        # none | heal | heal+stall
enabled = true                # false = excluded from bare `up`; pipeline stages are an exception
may_message = ["adversary"]   # absent = nobody; "*" is explicit permit-all
wake    = { interval = 3600, prompt_file = "prompts/supervise.md" }   # periodic nudge
prompt  = """inline startup text"""          # persistent/task agents; OR prompt_file = "path.md"
log_signature = "PROJECT PHASE"              # optional: disambiguate agents that share a dir (agent-log.py)
kind prompt source typical watch
loop auto-built: kickoff template + prompts/<role>.md heal+stall
persistent prompt / prompt_file (+ optional resume, wake) heal
task prompt (runs once, then idles) none, enabled=false

watch policy:

value behavior
none ignored by the watchdog entirely
heal restart if the session is dead, FATAL-wedged, or running the wrong backend; pause all healing while inside a usage-limit window; never reboot just for being idle
heal+stall everything in heal, plus reboot if idle past stall_idle — respecting any WAITING-UNTIL: <ISO-8601> self-wake marker the agent prints as its last line

[[service]] — non-AI helper processes #

[[service]]
name    = "cleanlogs"
command = "python3 agent-log.py follow-all"

Started by a bare up and killed by down. Services run in tmux; the watchdog does not automatically heal a crashed service. A later bare up recreates missing service sessions.

[project.<name>] — connected repos, their merge policy, and what every agent inherits #

A project names the repositories an agent may change and how a change lands in each. Every agent belongs to one project — project = "…" on the agent, else [defaults].project, else the sole declared project — and its kickoff is prefixed with the project's brief: the repos with their policy, the project's rules, and the contents of its guideline files. The rules travel with the agent instead of being retyped in every prompt; agents.py project <name> prints the brief exactly as agents receive it, and status shows each agent's project.

[project.lichen]
description = "the lichen.page CMS and its CI"
rules       = ["Product and test changes are separate, linked PRs.",
               "Never push to a test-*/full-test-* ref; the orchestrator triggers CI runs."]
guidelines  = ["machine-docs/PROJECT-GUIDELINES.md"]   # inlined into every agent's kickoff

[[project.lichen.repo]]
name   = "lichen.page.review"
url    = "git@tangled.org:notplants-bot.bsky.social/lichen.page.review"
policy = "review-stack"            # stacked linked PRs, each targeting the branch beneath; a human merges

[[project.lichen.repo]]
name   = "lichen-orchestrator"
policy = "retrospective-review"    # open a PR, get it reviewed, merge it yourself; reviewed after the fact

[[agent]]
name    = "builder"
project = "lichen"                 # optional when exactly one project is declared

Policies: review-stack (a stack of linked PRs, product and tests separate, a human merges — never merge it yourself) and retrospective-review (PR, independent review, self-merge; the operator reviews afterwards). Unknown policies and unknown project names fail config loading. An agent can opt out of the brief with project_brief = false; loop agents get it through the {project_brief} slot of their kickoff template. tangled_pr_merge.py --config agents.toml --merge (or $AGENTS_CONFIG) refuses to merge a review-stack repo unless --human-merge is passed.

[loop] — the phase state machine (governs kind="loop" agents) #

[loop]
state_file       = "phase-idx"          # under <log_dir>/state/
resume_phase     = true                 # keep the phase index across restarts (don't reset to 0)
auto_advance     = true                 # advance when the current phase's status file says done_marker
done_marker      = "## DONE"
kickoff_template = "prompts/kickoff.md" # project preamble; slots {phase_id}/{plan}/{status}/{role}
roles_dir        = "prompts"            # role prompt = <roles_dir>/<role>.md
handoff = { repo = ".", claim_pings = "adversary", review_pings = "builder", inboxes = ["ADVERSARY-INBOX.md", "BUILDER-INBOX.md"], claim_pattern = "^claim", review_pattern = "^review", state_subdir = "machine-docs" }
on_complete = { trigger_file = ".run-on-complete", run = "reporter" }   # run task agent on completion
phases = [
  { id = "p1", plan = "plans/p1.md", status = "STATUS-p1.md" },
  { id = "p2", plan = "plans/p2.md", status = "STATUS-p2.md", models = { builder = "claude-opus-4-8" } },
]
  • Kickoff template. A loop agent's prompt is kickoff_template (with {phase_id}, {plan}, {status}, {role} substituted from the current phase) followed by <roles_dir>/<role>.md. Both are project files; this repo ships generic starters in prompts/. There is no built-in preamble text.
  • Per-phase model override. A phase's models = { builder = "...", adversary = "..." } overrides those agents' model for just that phase (matched on the agent's role).
  • Auto-advance. Each signal tick, if the current phase's status file (looked up in handoff.repo's state_subdir/ then its root) contains a real done_marker — not a "Not yet…" placeholder — the watchdog stops the loops, bumps the phase index, and restarts them on the next phase. After the last phase it writes a SEQUENCE-COMPLETE marker under log_dir and stops the loops (idempotent — no churn). Appending a phase later clears the stale marker and resumes. On completion, an optional on_complete.run task agent fires if its trigger_file exists under log_dir.
  • Handoff signalling. The watchdog watches handoff.repo's origin/main for commits whose subject matches claim_pattern / review_pattern, and watches the two inboxes files. When a claim lands it pings the claim_pings agent; a review pings review_pings; an inbox change pings the relevant side. This is how the Builder and Adversary coordinate purely through git. claim_pings / review_pings may be a single agent name or a list — e.g. claim_pings = ["correctness-adversary", "readability-adversary"] pings every reviewer on a claim (each in its own session), for multi-reviewer setups.

[pipeline] — sequential standalone agents #

A pipeline runs distinct agents in order, advancing when each stage's completion file exists. Define its agents with enabled = false so the pipeline owns their lifecycle. The active stage participates in watchdog health checks even when its watch setting is none; heal+stall enables stall handling. Pipeline reconciliation also recreates a missing active stage.

[pipeline]
enabled = true
stages = [
  { agent = "build", done = "work/.ao-state/BUILD-COMPLETE" },
  { agent = "verify", done = "work/.ao-state/VERIFY-COMPLETE" },
]

Marker paths resolve against project_dir. The watchdog starts the first incomplete stage and retires other pipeline sessions. PIPELINE-COMPLETE under log_dir reflects whether all current markers exist; appending an incomplete stage clears it and resumes work. Removing a completion marker permits that stage to run again, so markers are part of the workflow's durable state.

Push side effect: when retiring a completed stage that is still running, the current implementation attempts git push origin HEAD:main in its agent's Git working directory before stopping it. The push is best effort and failure does not prevent retirement. Configure pipeline work only where that push is intended and authorized; do not assume the pipeline merely stops processes or that a completion marker proves a successful push.


Config vs state #

  • Config = agents.toml — declarative, version-controlled, the only source of truth.
  • State = <log_dir>/state/ — machine-written runtime only: phase-idx (current phase), <name>.id (resume id), limited-<session>.json (active usage-limit window), kickoff-<session>.txt (the exact prompt last sent). Git-ignore your log_dir.
  • Env = AGENT_MODEL_<name> / AGENT_BACKEND_<name> override those fields whenever load_config runs. They are not written back to TOML. An existing watchdog has its own process environment; a watchdog launched with these variables retains the overrides on every reload. Keep durable choices in TOML and check the watchdog's launch environment when an override appears to persist.

The driver: verbs #

The recommended (not required) verb set — an AI project-orchestrator can rely on these being present, but a harness is free to add more:

agents.py up [name…]               start enabled agents (+ services + watchdog); use-or-create
agents.py down [name…]             stop agents/services/watchdog (all, or named)
agents.py status                   table of every agent: kind, backend, model, watch, state, phase
agents.py watchdog                 the supervisor loop (what the <prefix>watchdog session runs)
agents.py logs <name>              tail that session's log
agents.py phase [show|next|set N]  inspect / move the loop phase index
agents.py tokens                   per-phase token + time report (when [watchdog].log_tokens = true)
agents.py selftest                 regression-test the backend activity detector (needs no config)
agents.py init [dir]               scaffold a starter agents.toml + prompts/ in a project dir
  --config PATH                    use a specific config (default: ./agents.toml)

The watchdog tick #

By default, agents.py watchdog runs as the <prefix>watchdog tmux session. When systemd_unit is configured, up and status instead defer to that unit and never create a tmux fallback; the unit should run agents.py watchdog directly. This keeps the real watchdog in its own cgroup while preserving accurate harness status. In either mode the watchdog re-reads the config every tick. Each loop:

  • signal tick (signal_interval): handoff pings, pipeline reconciliation, usage-limit and stall checks, due wakes, and loop phase advancement.
  • heavy tick (heavy_interval): heal watched agents unless a phase just advanced. Completed loop sequences stay stopped; persistent agents remain supervised.

Changes to agent configuration are read on subsequent ticks. Changes to signal_interval or heavy_interval require restarting the watchdog, because those intervals are read once at startup.

Usage-limit handling: when an agent prints a limit banner, the watchdog parses the reset time, arms a quiet window (never rebooting a limited agent), and at the end sends one probe to resume it — re-arming if the banner re-prints.


Intended layout #

Use one live engine at /srv/agent-orchestrator, one server config at /srv/agents/agents.toml, and an independent cwd at /srv/agents/<agent> for every agent, including orchestrators. Project repos may expose the engine through references/agent-orchestrator -> /srv/agent-orchestrator; engine edits belong in Git worktrees and reviewed PRs.

docs/LAYOUT.md defines the target and staged migration gates. The shared-workspace commands above provide engine support; deploying the server configuration and moving agents are separate, gated operations. Per-project engine submodules are the legacy layout, not the intended way to start new server deployments.


Skills #

Reusable, project-agnostic procedures for the agents that drive this harness, under skills/:

Skill For
stacked-prs adding a layer to a review-stack repo's PR chain: paired branches, explicit refspecs, rounds, never merge
secret-scan installing and using secret-scan.py; what to do when a commit is refused
tangled-repo creating a bot-owned Tangled repo; backing a repo up into one
gateway-domain giving a tailnet box a public HTTPS domain on the testing gateway
lichen-incus-terraform disposable NixOS test VMs on an Incus host via Terraform (lives in the incus-nix-tools submodule)
vm-workflow the VM workflow interface consumers build on
codeberg-pages publishing to Codeberg Pages

A project links or copies the ones it uses into its own skills directory and adds its specifics on top.

Tangled (the atproto forge) — the PR tools #

These tools use the Tangled appview through authenticated HTTP requests. They read tangled.cookie from the sops store by default. Some also support --cookie-file; the table below lists that support explicitly. Read-only commands use GET, while mutations submit appview forms. Run each tool with --help for its current flags.

Tool Action --cookie-file
tangled_pr.py Open a pull; --target is the destination branch Yes
tangled_pr_edit.py Edit title/body, or --show without editing Yes
tangled_pr_resubmit.py Advance a pull's round after a fixup; --check reads the current round Yes
tangled_pr_merge.py Check mergeability, merge or close No
tangled_pr_close.py Close, optionally comment first, then verify the resulting state No
tangled_comments.py Read discussion comments No
tangled_comment_post.py Post a discussion comment No
tangled_repo.py Create a repository Yes

The trap tangled_pr_resubmit.py exists for: pushing the branch does NOT update the pull. The appview keeps serving the patch it fetched when the pull was opened or last resubmitted, so reviewers read the pre-fixup code and no interdiff exists — with no warning, because the push itself succeeded. For a branch-based fixup, push the branch explicitly, run tangled_pr_resubmit.py, then use its interdiff URL when replying under the project's review workflow. There is no machine-docs/PR-WORKFLOW.md in this checkout.

Tangled authentication and pushing #

Cookie authentication and Git SSH authentication are separate. The tools do not obtain or refresh browser sessions. Renew an expired session through the approved Tangled login flow and update tangled.cookie using sops; this checkout does not contain scripts/get-tangled-cookie.py.

In agent-sandbox, an existing cookie file may instead be mounted at /secrets/tangled/cookie.env. For tools that support it, explicitly pass --cookie-file /secrets/tangled/cookie.env. The format is an unquoted line TANGLED_COOKIE=<complete Cookie header value>. Tools without that option still require the sops store; they do not automatically load /secrets/.env.

For hosted Tangled repositories, the verified SSH route is git@tangled.org. An HTTPS clone URL may redirect to a knot URL that does not provide the same SSH route. With the already configured key, push an explicit branch:

git push git@tangled.org:<owner>/<repo> HEAD:refs/heads/<branch>

If the key is not in your SSH configuration, select the actual mounted private key with GIT_SSH_COMMAND. In the September sandbox this was ssh -4 -i /secrets/tangled/id_ed25519 -o IdentitiesOnly=yes -o BatchMode=yes. Keep keys and cookie values out of remote URLs and tracked files.

Branch-protection behavior depends on the forge and deployment. The source reviews recorded here on 2026-08-23 and 2026-09-02 found no server-side branch protection in that Tangled version. Treat those as historical findings, not a claim about every future version. The opt-in client guards below provide a local boundary for projects whose policy reserves particular branches.

The incident this is written from (2026-09-02). A builder with push.default=upstream ran a refspec-less git push from a worktree whose upstream was review/main. Git resolved that to main, and the agent's work landed on the protected branch. It then force-pushed main back to the previous sha (lease-pinned, disclosed immediately, tree byte-for-byte restored) — which is the second rule broken to repair the first. The operator ruled the no-force-push rule stands as written, no lease exception: on an accidental push to a protected branch, stop, leave it, record it, wait for the operator. These conventions make that cheap and the accident nearly impossible.

Two client-side layers, both global for the agent user so they cover every worktree:

  1. A pre-push hook that refuses pushes to protected branches on protected remotes. Shipped as tools/git-hooks/pre-push; config-driven, inert until configured.

    mkdir -p ~/.config/git/hooks && cp tools/git-hooks/pre-push ~/.config/git/hooks/ && chmod +x ~/.config/git/hooks/pre-push
    git config --global core.hooksPath ~/.config/git/hooks
    git config --global --add agentOrchestrator.protectedRemote  lichen.page.review   # URL substring
    git config --global --add agentOrchestrator.protectedBranch  main                 # default: main stack
    

    Override for the one legitimate case: ALLOW_PROTECTED_PUSH=1 git push … — printed when used.

  2. git config --global push.default nothing. A refspec-less git push now fails outright ("You didn't specify any refspecs to push, and push.default is "nothing""). This closes the exact vector of the incident. Check your automation for bare git push first; there should be none — every push names its ref: git push <remote> HEAD:refs/heads/<branch>.

Example rules for projects that reserve merges to an operator — use the project's actual authorization policy when writing agent prompts:

  • Only the operator merges to main. Approval is not merge.
  • Never force-push or rewrite published history — including to undo your own mistake. If something lands where it should not: stop, record it, wait.
  • Always push by name. git push <remote> HEAD:refs/heads/<branch>, never bare git push.
  • Never bypass the guards. --no-verify skips the hook; -c push.default=… skips layer 2. Both are deliberate, not accidents, and the no-force-push rule covers them.

Positive-control the install: a dry-run push to main must be refused; a dry-run push explicitly targeting an unprotected test branch must pass; a refspec-less dry-run must fail with the push.default message; and git ls-remote must show no probe ref was created. A guard that was never seen to fire is not known to exist.

The testing gateway — public domains for tailnet boxes #

A box on the tailnet with no public IP can still have a real HTTPS domain: the shared testing gateway holds a wildcard record for *.gtest.commoninternet.net and forwards by SNI.

python3 engine/tools/gateway-domain.py add myapp     # -> myapp.gtest.commoninternet.net -> this box
python3 engine/tools/gateway-domain.py list
python3 engine/tools/gateway-domain.py remove myapp

The admin password is gateway.admin_password in the secret store below; the tool reads it itself. The gateway does not terminate TLS — it proxies the encrypted stream, so your box serves the certificate for that name. Full detail, including how to get a cert and why hostname backends are refused, is in the gateway-domain skill (skills/gateway-domain/SKILL.md).

Secrets — select the configured storage layout #

The core driver does not require a sops store. The bundled Tangled and gateway tools use secrets.py, which expects /secrets/store.yaml by default and an age key at ~/.config/sops/age/keys.txt. Override those paths with AO_SECRETS_STORE and SOPS_AGE_KEY_FILE. A missing or undecryptable store fails explicitly.

On managed orchestrator hosts, the established layout is:

Content Location
Values read through secrets.py sops+age encrypted /secrets/store.yaml
Project-specific credential files /secrets/<project>/
Shared credential files /secrets/files/
Default age private key ~/.config/sops/age/keys.txt

Keep private keys and credential files restricted to their intended users. A fixed-path consumer can use a symlink to its authoritative file. Applications that atomically rewrite OAuth credential files can replace such symlinks; keep those files at the application's managed location.

Agent-sandbox can instead receive files and .env data through the agent_secrets Docker volume. Its host-side build.sh overlays secrets/ after a successful build. This does not create a sops store, and secrets.py does not read those files automatically. Discover the mounted layout and use the consumer's supported interface; the VM workflow skill records the tested Incus layout. Do not relocate credentials merely because a different host's convention appears in these docs.

Store helper #

Supported CLI commands are list, get, exec-env, and with-file:

python3 engine/secrets.py list                         # names only
python3 engine/secrets.py exec-env <group> -- some-command
python3 engine/secrets.py with-file <group.key> -- command -i '{}'
sops /secrets/store.yaml                              # edit encrypted store

get <group.key> writes the value to stdout; avoid it in shared logs. with-file creates a 0600 file in a private temporary directory, substitutes its path for {}, and removes it when the command exits. There is no materialize command.

For Python integration, load this repository's secrets.py explicitly or ensure it is the module being imported: Python's standard library also has a module named secrets. The provided functions are get(dotted_key, default=None) and get_group(group_name).

tools/secrets.sh is a separate helper for per-host encrypted payloads. It uses SECRETS_HOST (default b1) and expects /secrets/<host>/<host>.yaml, .sops.yaml, and admin-age.key there. It is not an alias for secrets.py.

Keep credentials outside tracked files and remote URLs. Public handles, URLs and model names belong in ordinary configuration; the exact-value secret scanner regards values placed under its configured secrets root as secret material. Changing a credential's location requires updating its consumers too.

secret-scan.py scan examines staged additions; scan --audit examines tracked files, and scan --dir PATH also covers untracked and ignored files. Its current loader excludes candidate values shorter than eight characters and requires at least 40 loaded values. A smaller sandbox store can therefore fail the load check; none of these modes proves that every possible secret is covered. The pre-commit hook only runs in repositories where it has been installed.


Nix #

A flake.nix provides a reproducible devShell with the runtime deps (python311 for stdlib tomllib, plus tmux and git):

nix develop                                   # enter the shell
nix develop -c python3 agents.py selftest      # or run one command in it
nix flake check                                # evaluate + build the devShell

The agent CLIs themselves (claude, codex, opencode) are external, non-Nix tools — install them per their own docs and make sure they are on PATH before launching live agents. The devShell documents this in its banner.


VM integration tests #

When a project needs Docker or a real Linux VM that the current sandbox cannot provide, use the vm-workflow skill. It explains how to locate or clone the separate incus-nix-tools repository, discover mounted credentials, connect through Tailscale, run tests in a disposable Incus VM, and clean up. A prepopulated /tools/agent-orchestrator checkout does not also install incus-nix-tools.

Testing #

The tests/ directory holds the harness's own test suite. One runner drives everything:

  • tests/test_unit.py — the harness: config load, kickoff, the phase machine, limit parsing, waiting-until, the build-process detector.
  • tests/test_tools.py — standalone tools and Git hook behavior, with external calls mocked.
  • tests/test_agent_message.py — sender attribution, allowlists, paste/submit and delivery proof.
  • tests/test_agent_tail.py — durable transcript lookup, formatting and turn status.
  • tests/test_secret_scan.py — tracked-file accounting, symlink handling and failure reporting using isolated fixtures.

Mock the seam you own, not the tool you depend on. The build-detector tests used to fake pgrep and ps subprocess calls, so they passed on a host where neither was reachable and the real defect — empty output read as "no build running" — was invisible to every test. They now patch _proc_descendants and _comms, the functions this repo owns. A test that mocks a dependency proves the mock works.

nix develop -c ./tests/run.sh      # unit tests always; live backend smokes when available
# or just:  ./tests/run.sh         # (python3 + tmux must be on PATH)

What it runs:

  • Unit tests (tests/test_unit.py) — pure logic, no agents spawned, no live tmux sessions. Cover config load + defaults merge, kickoff-template assembly, the phase machine (advance on the done marker, idempotent sequence-complete, append-a-phase resumes), usage-limit reset-banner parsing, WAITING-UNTIL / stall parsing, and the per-backend activity detectors (claude + opencode footers). Always run; a failure fails the suite. Run them alone with python3 -m unittest discover -s tests (or python3 tests/test_unit.py).
  • Live backend smokes (tests/smoke_claude.sh, tests/smoke_codex.sh, tests/smoke_opencode.sh) — each brings a throwaway scratch project up through agents.py on a real backend, in a fully isolated sandbox (its own unique session_prefix, a temp log_dir, and — for opencode — a dedicated server on a non-default port AOTEST_OC_PORT, default 4097), confirms the session attaches and status reports it RUNNING, then downs it and cleans up (no leftover sessions, port freed). Skip conditions differ: Claude checks for tmux and its binary; Codex also checks login and Remote Control connectivity; OpenCode checks its binary and credentials. A runnable smoke can fail, and invoking these scripts can start real model sessions. Useful env: CLAUDE_BIN / CODEX_BIN / OPENCODE_BIN, AOTEST_MODEL, AOTEST_OC_PORT, AOTEST_OC_CREDS.
  • Isolation sanity — after the live runs, the runner asserts no aotest-* tmux sessions leaked and reports whether three known cc-ci-* sessions are present. That presence check is not a before/after comparison of arbitrary live sessions.

The smokes are safe by construction: a unique per-run session prefix (never cc-ci- or any real project's), a dedicated opencode port (never 4096), and a cleanup trap that fires on success, failure, and Ctrl+C.


Adding things #

  • Add an agent — add an [[agent]] block; agents.py up <name>. No code change.
  • Add a backend — add a [backend.<name>] block (bin, prompt_delivery, the regexes); point an agent at it with backend = "<name>".
  • Add / append a phase — add an entry to [loop].phases; the watchdog advances into it automatically (clearing a stale SEQUENCE-COMPLETE if the sequence had finished).
  • Change a model or backend — edit the field (or a phase's models = {}), then agents.py down <name> && agents.py up <name>. The watchdog re-reads the file; it won't fight you.

Raw watchdog usage capture #

Each watchdog tick appends one snapshot per identifiable Claude or Codex agent with a transcript to <log_dir>/usage-log.jsonl. Discovery uses agent-tail's ownership rules and the same resolved cwd as launch; ambiguous shared transcripts are not attributed twice. Capture is deterministic Python, with no model calls. Usage reports and quota analysis are a later, separate reader of this log.

Snapshots contain ts, agent, backend, model, transcript, last_activity, and cumulative (turns, input_tokens, output_tokens, cache_read, cache_create). Codex session totals are copied; Claude per-message usage blocks are accumulated once, coalescing repeated revisions of a message. Input counters retain backend semantics: Codex input includes cached input, Claude reports cache separately. model is the latest observed model, not a claim that all cumulative usage belongs to it. Turns count user requests, excluding Claude tool results and Codex's duplicate user-message notification within an identified task.

Extra rows record changed phase/marker values already known to the watchdog, Codex rate_limits observations, and reset events for rotation, truncation, rewritten cursor boundaries or decreasing cumulative counters. Snapshot epoch identifies reset boundaries. caught_up and skipped disclose bounded backlog and malformed/oversized records: at most 4 MiB per agent per tick, 1 MiB per line. Initial capture catches up from the start; later ticks read from a persisted cursor. A 4 KiB cursor checkpoint detects truncate-and-regrow rewrites at that boundary; it is not a whole-transcript integrity audit. No conversation bodies are stored.

Keep usage-state.json with the append-only log. An exclusive lock and durable pending batch let restart complete a partial append without duplicate rows or counter increments. Replaying the same tick timestamp is idempotent. Missing state with an existing log, or conflicting pending bytes, fails without replacing the log; supervision continues and reports a capture failure. Do not rotate or edit either file independently. The collector never alters source transcripts.

Codex transcript lookup first uses the validated resume UUID in <log_dir>/state/<agent>.id to match a rollout filename, then falls back to cwd and the existing shared-cwd ownership checks. A resumed rollout can retain its original cwd after a workspace move. Both agent-tail.py (display/status) and watchdog raw usage capture use this rule. Missing, invalid or unmatched IDs retain the cwd fallback; lookup never creates state or changes a transcript.