ah-engine¶
ah-engine is anti-hall's core component: a small resident program that answers the hooks instead of a new Node process for every
tool call. As of release 0.301.1 the engine is the only runtime: the Node hooks are gone. This page explains what it is, why it exists, what works today and what is not built yet. Anything not built
is marked planned with the number of its decision, for example planned (D33) for the scheduler; each number is an entry
in ah-engine/DECISIONS.md.
The exact list of commands, settings, metrics and error codes is generated from the engine itself and lives in
ah-engine/REFERENCE.md.
Status: shipped in release 0.301.1 (engine only, no Node hooks); see the roadmap. The plugin fetches the sha256-pinned engine itself on first use. The plugin's hooks are one thin trigger
per event: hooks.json runs the Rust thin client ~/.anti-hall/ah-engine/bin/ah-hook <Event>, which asks the engine. The
thin client is the only entry point, for hooks of both hosts and for every command (ah-hook <verb> runs ah-engine <verb>).
No Node and no shell script runs on an entry path; when the engine is absent or unreachable, the call passes through with one
notice per session (a daemon that answers with an error or no verdict is resolved by dispatch.failure_mode, see the Client bullet) (the manual ah-engine fallback node switch can hand calls to the Node backup in plugins/anti-hall-node/). The binaries are installed by the plugin's one shell file, hooks/install.sh, and checked against a sha256
pinned in the plugin (Install, go-live and rollback).
Supported platforms: macOS on Apple silicon. Linux (including WSL), Apple Intel and native Windows are coming soon (not supported or tested yet).
Why it exists¶
Each Bash tool call used to start nine Node hooks before the tool and six after. Measured on the plugin at the time, the
nine pre-tool hooks peak at about 409 MB combined and use 187 ms of CPU, and Node's own start-up is 65 to 100 percent
of each hook's cost (D1). The problem is bloat, not start-up time. The engine answers the same questions from one
long-lived process of about 5 MB, called by a client of about 2 MB that starts in about 2 ms (D2). Every figure is
labelled with how it was measured in the README of ah-engine/.
How it works¶
host (Claude Code / Codex)
| hook JSON on stdin
v
ah-hook <Event> (thin client, ~2 MB, ~2 ms)
| one framed request over a unix socket, hard 2 s budget
v
ah-engine serve (daemon, one per user, ~5 MB)
|-- rules (JSON file) regex rules: deny / warn / context
|-- checks (Rust + plugin JS) real logic a regex cannot express: the git and command checks
|-- telemetry metrics (snapshots + rollups), the impact ledger, and the lock-free telemetry recorder, stored
|-- project state per-project mailbox and key-value pairs, in hot.db
|-- memory layer active key-value items (budgeted, TTL) + pub/sub channels
`-- storage hot.db + archive.db (SQLite, bundled), one writer thread
- Client. Reads the hook payload, asks the daemon, prints the answer. If the engine is unreachable (no daemon, open
breaker, crash loop) the call exits 0 without a block, prints an environment advisory when one was recorded, and one notice
per session says the engine did not answer. If the daemon answered with a non-OK reply (busy, error, damaged) or no
verdict, a guarded event is resolved by
dispatch.failure_mode.infra(closedby default, so it blocks with exit 2); other events exit 0. Stdin the client cannot safely forward (invalid UTF-8, over the read cap) on a guarded or unknown event is refused with exit 2; a stdin read error fails open. No Node hook ships in the plugin, but the manual switchah-engine fallback nodehands calls to the Node backup kept inplugins/anti-hall-node/(see "The Node backup: shadow and fallback switch"; D11 describes the earlier automatic fallback design). - Daemon. One per user, started by the first client that finds none (D5, D6). It stays up after the last session
closes (D7): idle exit exists as the setting
daemon.idle_exit_s, default 0 meaning disabled. A newer client gets its answer, then the old daemon drains and exits so the next call starts the new build (D8). - Rules.
rules.json, evaluated in file order; every match contributes and anydenywins. A rule may name a built-in check instead of a pattern. - Historical note (migration era). The bullets below and the status table further down record how each check was ported from its Node original and speak of Node deferrals and byte parity. Those Node hooks no longer ship (release 0.301.1); read them as design history, not as current behavior.
- Small guard ports.
merge-side-pick,ship-it-guard,scan-throttle,coordinator-work-guardandcompact-declaration-guardare the five small guards ported from Node. They sharechecks/guardkit: the switch and skip-file lookup, the message layout, JavaScript-exact regex translation and the per-session state files the Node guards keep under~/.anti-hall/(written in the same bytes, so a Node hook that answers for the same session in turn reads the same record; an in-memory store remains for tests; the database-backed store is planned, D22). Their PostToolUse companions run as checks too (merge-side-pickrecords,coordinator-work-guardkeeps the work window,git-auditreads the recent commits,failure-root-cause-nudgeanswers PostToolUseFailure). Where the Node verdict cannot be reproduced exactly (a block whose stdout and stderr the reply cannot carry yet, a regex construct, a classifier that lives in another port) the check defers, so Node decides. - Prompt-emission ports.
verify-first,idle-agent-sweepandemit-dedupe-resetare the UserPromptSubmit and SessionStart context hooks of the dedupe family. They sharechecks/emit_dedupe, which reads and writes the very same per-session state file the Node hooks still use (~/.anti-hall/emit-dedupe/dedupe-<session>.json: key order, entry layout, the 24 hour key expiry, atomic write, suppression counter and the throttled sweep of idle session files). A state file, transcript line or timestamp that JavaScript might read differently defers the whole hook to Node before anything is written; so does a possible DevSwarm Primary session forverify-first, whose extra sentence depends on the repo'sCLAUDE.mdchain. - Context-budget gates.
limit-conserve-inject,auto-handover(both UserPromptSubmit),auto-handover-pause-nagandcompact-advice-guard(both Stop) answer the case in which the Node hook injects nothing, blocks nothing and writes no file: the feature off or skipped, a subagent, context below the threshold, no usage bucket over its limit, a turn whose final text holds no compact-recommendation wording. Every other case (a fire, a nag, a re-arm, an active conservation, a possible recommendation) defers, so the files those hooks write (the per-session latch, the account-switch file, the emit-dedupe state, the once-per-declaration hash) are only ever written by the Node implementation (checks/ctxbudget,defaults/ctxbudget.toml). - Injection gate (token cuts). After the Node hooks have run, the dispatcher passes on
limit-conserve-inject,task-tracker, the DevSwarm comms-override line andswarm-guard's shared-tree advisory only when the model does not already hold them (new, changed, or due again as a keepalive), per session and agent. State lives in the daemon, bounded (inject_gate.max_sessions,inject_gate.max_slots) and shown instatusand theinject_gate_*gauges;ah-engine ctl gateprints per-session injected and kept-out bytes. Each cut is a setting (context.injectGate*); off, the Node output passes unchanged (dispatch/inject.rs,gate.rs,defaults/inject_gate.toml). - Per-hook inline caps (context size). At the events in
context_size.events(SessionStart) a hook'sadditionalContextover its cap (context.inlineHookChars, per hook incontext_size.hook_caps) or, once the event total passescontext.inlineEventChars, the largest shrinkable ones, become a one-line summary plus the path of one file with the full text (nothing is truncated; hooks incontext_size.neverare exempt). The verify-first protocol is sent whole at a fresh start, as a short digest after a compaction or resume and as one line on a repeated start (context.protocolOnce,verify_first.*texts), andcontext.orchFullOn = autosends the compact orchestration text with the full rules on the first spawn (orch_state.auto_mode). Switch:context.shrinkInline(dispatch/shrink.rs,context_size.toml). - Per-event context budget (
ctx_keep.toml, plan v3 L12 / C2). The prompt digest, the SessionStart shrink and the over-cap join spill each move model-facingadditionalContextinto a file the model has to Read. Withcontext.injectGateNoSpillon (default off, envANTIHALL_CTX_NO_SPILL), an event inctx_keep.eventsinstead keeps its contexts withinctx_keep.chars_by_event(SessionStart 9000, UserPromptSubmit 3000): while the joined contexts are over it, the one with the lowestdispatch.context_priorityis dropped (ties: the longest, then the latest) and the three file writers are skipped for that event. A context at or abovedispatch.context_pin_priorityis never dropped; when the pinned ones alone are over the budget they stay whole and the host's cap applies as before. Blocks and decisions are untouched and nothing is stored. Counters (inctx_keep.toml):ctx_keep_dropped(event, check),ctx_keep_dropped_chars(event),ctx_keep_pinned_over(event); the event log line isdispatch_ctx_dropped(ctx_keep.msg_dropped). Code:dispatch/ctxkeep.rs. The Codex port needs no change: the same dispatcher serves--host codex. - Notice turns. A UserPromptSubmit whose prompt (first
notice_turn.prompt_charscharacters) starts as a harness notice, matched bynotice_turn.kinds(task notification, mesh inbox tick, goal check-in, message from another session, teammate message), is counted by kind innotice_turn_matchedwhether or not the switch is on. Withcontext.injectGateNoticeTurnson (default off, envANTIHALL_NOTICE_TURNS) the planner drops the pure per-prompt reminders innotice_turn.skip_checksfrom that turn's plan before they run, counted innotice_turn_skipped. A human prompt that only mentions a notice never matches (the patterns are anchored at the start).notice_turn.eventslists the events tested (dispatch/notice.rs,dispatch/plan.rs,notice_turn.toml). - Session maintenance ports.
version-alert,devswarm-version,claude-cli-version,repo-self-drift,defect-nudgeandprogress-pruneare the six SessionStart hooks that keep a small cache or ledger under the home directory. They are not guards (D74: non-guard hooks fail open) and they sharechecks/session: an order-preserving JSON value that prints numbers the way JavaScript does (the Node and Rust writers share the state files), the drift-cache mechanics and the JavaScript date and version reading. Each reproduces its Node hook's output bytes and its state-file writes. The engine never starts a background process: a stale version cache (Node spawns a detached probe), a payload with no working directory (Node reads its own), a.gitfile or date or JSON text it cannot read exactly like JavaScript, or a gitignore probe slower thansession.gitignore_probe_msall answer a deferral BEFORE anything is written, so the Node hook then runs whole and sees the state it would have seen. - Response-correctness ports.
speculation-guard,speculation-judge,claim-ledger(Stop) andoutput-verify-guard(PostToolUse on Bash) sharechecks/replykit: JavaScript-faithful JSON (key order and number text kept), the transcript tail reader, the once-per-turn gate and the stale-state sweep. The Jev call path is NOT ported with them: every call where Node would consult Jev (the master switch on forspeculation-guard; a flagged turn or a test-runner output with the integration notoffforclaim-ledgerandoutput-verify-guard; every opted-in call ofspeculation-judge, which is a model call with its own backends) defers to Node, so Jev-off installs are answered by the engine and Jev-on installs keep Node's exact behavior, log rows included. The block ofspeculation-guardis therefore never weaker than Node's (D74). The one deliberate difference with Jev off: Node'sclaim-ledgerandoutput-verify-guardstill append amode: "off"row to the Jev decision log per consult; the engine's Jev layer never does (D35), and neither do these checks. - Handover and Codex ports.
handover-resume(SessionStart),precompact-snapshot(PreCompact),codex-availability(SessionStart),codex-quota-detect(PostToolUse on Agent) andcodex-nudge(Stop) are ported from Node. They sharechecks/jsport, which reproduces the JavaScript behavior the hooks depend on (number formatting,JSON.parsekey order,Dateformatting and the part ofDate.parsewhose result is certain, UTF-16 string handling, the repository-identity resolver) andchecks/codex/quota.rs, the quota record in~/.anti-hall/codex-availability.json. A case the port cannot reproduce exactly (a date string in an unfamiliar shape, a state file holding__proto__, a Codex result whose key order could change what matches, an enabled Jev consult for the nudge) defers, so Node decides; the deferral happens before any write the Node hook would repeat. - Rule digest. The
rule-digestcheck (SessionStart, also after compaction) puts the essential rules the engine enforces into the session context. The rules are the registryguard_rules.rulesinguard_rules.toml: each row has a tier (essential,skill,off) and a source text; an essential rule also has a shortdigestfield beside its message entry (one line: the rule and what to do, a table by host where hosts differ).ah-regengenerates one digest file per host (engine/rule-digest.txt,engine/rule-digest.codex.txt) and theengine-rulesskill from them, and a drift test fails when a block text has no row, an essential rule has no digest field, or a message or digest edit leaves the committed digest stale. Therule_digestcounter records session starts bystate(on,off);rule_digest_callscounts check calls by the session's digeststateandoutcome(blocks per 100 matching calls, digest on versus off), andrule_retry_compliantscores the next call of a check after it blocked in a session (compliantorrepeat, bycheck). The settingcontext.ruleDigestturns it off. Thesession-bannercheck (SessionStart) shows one user-visible line with the plugin version and the rules enforced (ui.banner), andsession-summary(SessionEnd) one line with the session's blocks and the rules that fired most (ui.sessionSummary); the statusline is not used for this. - Task checks.
task-lifecycle-log,dispatch-tier,task-guardandtasklist-guardsharechecks/taskkit(the JavaScript string and truthiness semantics over a JSON value, the ledger text sanitizer, the UTC clock text, the project root resolversrepoRootandsessionProjectRootofhandover-find.jsanswered from the file system alone, and the work-detection port oflib/work-detect.js) andchecks/taskstate(the task list rebuilt from a transcript tail, the backfill that recovers records before the tail, and the unknown-state note). A task check does the file effects of its Node hook itself and answers exactly what Node would; anything it cannot reproduce byte for byte defers. The two Stop gates never block: they answer the Stops on which Node stays quiet and hand every Stop that would block, and every Stop whose decision needs a running-agent scan, to the Node hook (D74).task-tracker(UserPromptSubmit) stays on Node: its output depends on the emit-dedupe state, the Jev decision-log row written on every prompt and the agent scan, which are other lanes' ports. - Task-list hygiene.
tasklist-hygiene(PostToolUse and PreToolUse onTaskCreate/TaskUpdate, Claude only: Codex has no task tools or task hook events) is an engine-only script. After a task is marked completed it tells the agent, in one line, to log the outcome to the history ledger and delete the task; a subject overhandover.taskSubjectMaxor open tasks overhandover.taskListBudgetget one advisory line with the numbers.handover.taskListEnforce(off,advisorydefault,block) escalates the same breaches to refusing the call;handover.taskDoneNoteswitches the done line. Texts:task_guards.toml. Native task-window projection runs after successful task calls and only displaces pending, unowned tasks with confirmed creation provenance for the current session. Owned, in-progress and other sessions' tasks stay visible. Blocked updates save their blocked state and keep the full native record visible.guards.taskWindowBlockedKeepis an advisory threshold, and updates above it still proceed. Full displaced records are archived with their project task store before leaving the native list and are recoverable by their creator. Restore requires a confirmed native ID and an active archived record, so refused creates and tasks deleted without an active archive stay absent. Legacy archives without an active marker remain preserved for explicit owner recovery. Empty-ID reservations expire undertask_window.reserve_ttl_ms. Shared lists merge each joining session's legacy rows while preserving source files and use one project store and lock. Their ranking disables session-local live-agent slot exemptions. Cross-project projection is refused even when no backlog index exists. If a lock or record check prevents projection, native records stay visible and a reconciliation notice is emitted.guards.taskWindowSizeis therefore a window target, and the native list may exceed it while tasks are protected or projection fails. Claude/OMC enforce this through task hooks. Codex/OMX follow the same ownership and preservation rules in the manual task plan and store. - DevSwarm role ports.
devswarm-child-role(SessionStart) anddevswarm-parent-gate(Stop) sharechecks/devswarm_role. The Stop gate is a guard, so it is never weaker than Node (D74): the engine allows only where the Node hook exits silently before reading any mailbox (switch off, user skip, supervisor inactive, a child workspace, the judge child) and defers every session that could be blocked. The child-role check reproduces a child workspace's directive byte for byte when the stable launchers it names already exist with the content Node would write, and defers a Primary (seat adoption needs the DevSwarm CLI and the mailbox store, D45), a missing or stale launcher, and anything it cannot prove identical. The engine never writes a launcher. - Checks. A check is Rust code behind the
Checktrait, registered by name inchecks::registry(). Today there are sixty-one:devswarm-child-role,devswarm-parent-gate,devswarm-child-gate,devswarm-parent-reply-trackeranddevswarm-child-drain(see DevSwarm role ports above and the table below),task-lifecycle-log,dispatch-tier,task-guardandtasklist-guard(see Task checks above),devswarm-parent-inboxanddevswarm-child-turn(see DevSwarm prompt gates above), the five handover and Codex ports above, the four response-correctness ports above,limit-conserve-inject,auto-handover,auto-handover-pause-nagandcompact-advice-guard(the context-budget gates above),git(a port of the git-guard hook with 100 percent agreement with the Node original on every corpus tried),command(a port of the command-guard hook that answers the commands Node allows in every context and defers the rest to the Node hook, also at 100 percent agreement),model-routing(the model-routing guard for Agent/Task spawns), and the five small guard ports above:merge-side-pick,ship-it-guard,scan-throttle,coordinator-work-guardandcompact-declaration-guard(see the README ofah-engine/), and two PostToolUse-side checks:git-audit(the--auditpass of git-guard) andfailure-root-cause-nudge(PostToolUseFailure), plus the three context checksverify-first-subagent(SubagentStart),verify-first-full(SessionStart) andfable-availability(SessionStart). The context checks are not guards: they inject text or record a fact, never block, and anything they cannot reproduce exactly defers to the Node hook (D74); the four spawn/path context ports below; and the two prompt-emission portsidle-agent-sweep(agents that finished but were never stopped) andemit-dedupe-reset(marks a context loss at SessionStart); the retired per-turnverify-firstrotating reminder has no dispatch row any more (#958: the protocol arrives at SessionStart and SubagentStart); the four context-budget gates; and the six session maintenance ports above:version-alert,devswarm-version,claude-cli-version,repo-self-drift,defect-nudgeandprogress-prune; and the three agent and transcript controlsask-guard,silent-agent-nudgeandstale-agent-stop-note, which share one streaming port of the transcript agent scan (see the README ofah-engine/); and the two edit and shell guardsmerge-gateandapi-guard, which answer only what Node answers with no output and no side effect and defer the rest, so a possible block, a Jev shadow ask or an interpreter probe is always the Node hook's; andedit-guard(lane L12), which decides every target on the main thread as Node does (a block, the coordinator allowlist, the symlink and hard-link honesty walk, a Codexapply_patch) and defers only a call that needs the hook process's own working directory or home, or the JavaScript string form of an object; and the batch 14 to 16 ports: the spawn and comms guardsswarm-guard(the spawn-rate and memory-pressure limiter, with a lock file shared with the Node hook) anddevswarm-comms-guard, and the session gatesjev-weekly-scorecard,jev-review-reminderandrepair-on-reload. - Node-only ports.
task-tracker(UserPromptSubmit, Claude and Codex entries) reproduces the directive/reminder cycle, the transcript-growth and window triggers, the keepalive and burst dedupe, the open-tasks line, the unknown-state note, the scoring of the previous turn's dispatch demand and the JevnewRequestlabel of each prompt (the same request through the engine's Jev lane). It hands to Node, before anything is written, a session that could be a DevSwarm Primary, a session with a task the per-turn DISPATCH NOW line would name (it counts running agents and asks Jev for a tier), a dispatch-tier outcome still to label, and any state file only JavaScript reads.session-end-mcp-reaper(SessionEnd) sweeps the MCP orphans a crashed session left behind with Node's exact selection rules (PID 1 must be init, parent PID 1, MCP command signature, not a test runner or user-excluded, old enough, not owned by the service manager, capped) and Node's audit log; it never signals more than Node would, never itself, its parent or a pid below 2, and hands to Node a user pattern it cannot translate exactly, a start time not in thepsform, an ambiguous local time and a request whoseTZdiffers from the daemon's. Compared with the real hooks intests/task_tracker_parity.rsandtests/mcp_reaper_parity.rs(the latter on fakepsandlaunchctlprograms). - Spawn/path context ports.
inbox-read-guard(PreToolUse on Read),phase-tracker(PreToolUse on Agent and Task),orch-on-spawn(PreToolUse on spawns),verify-first-orch(SessionStart, the Claude entry) andverify-first-orch-codex(the Codex entry: the same hook without the--host=claudeflag, so no session is ever Claude-confident and the host's config directory is never read; same coverage otherwise). They sharechecks/spawnctx: the home directory the state files live under (with the test-run refusal of the real home), the DevSwarm detector, session-id sanitizing and the orchestration marker with its prune sweep. Each was compared against the real Node hook on a corpus of 70 to 103 payloads, on exit code, stdout bytes, stderr bytes and the state files left behind, with an isolated home per side (tests/it/spawn_ctx_parity.rs). What stays with Node, by design: a Read inside the raw DevSwarm store (the block depends on a module probe), a pending orchestration marker (the claim race and the transcript scan), a session where DevSwarm is active forverify-first-orch(whether it is a Primary changes the text), a working directory that is not a string, and a relative path or config directory that Node resolves against its own working directory. A deferral touches no state. ten:git(a port of the git-guard hook with 100 percent agreement with the Node original on every corpus tried),compact-declaration-guard(see the README ofah-engine/). - DevSwarm prompt gates.
devswarm-parent-inboxanddevswarm-child-turn(the two DevSwarm UserPromptSubmit hooks) answer their silent cases in the engine: not a Primary / not a child workspace, DevSwarm inactive (kill switch,devswarm.supervisorModeoff, auto mode withoutDEVSWARM_REPO_ID), the hook's own switch off, or a Jev judge child. They also answer an active Primary or child whose working directory has no git checkout around it (a headless judge session, for one): then the hook has no project identity, so the Primary says only its communication-override reminder through the emit-dedupe store (and defers while a seat-conflict marker is owed a repeat), and the child writes its heartbeat, says its fixed reminder block and its step plan, and defers while it has unread mail. A session in a checkout defers to the Node hook, which owns the workspace roster, the mailbox, the descriptor and the store (they need the engine-owned mesh and mailbox, D45, first).
Nudge and wake scope (GH #430, agents.nudgeScope, default on; env ANTIHALL_AGENT_NUDGE_SCOPE). An answered nudge is never queued again by the wake fallback (a snooze used to move the send clock, so the fallback re-queued the reminder the parent had already seen, id <nudge>-<n>-q). An agentHealth verdict of done holds the nudge for agent_nudge.limits.health_done_hold_ms with no judge call. Any new output from the child releases that hold; off, a recorded done hold is ignored. A done hold an older version wrote into the busy-hold field (nudge_hold, no activity time) is moved into the done holds on the first tick with the setting on (an entry further ahead than health_recheck_ms can only be such a hold): its expiry is kept, its baseline is the earlier of the child's last output and the verdict time the expiry implies, so output after the verdict releases it and an idle child stays held; off, the old field is read exactly as before. A stale-heartbeat row goes only to the session that wrote the heartbeat and only when it names a step; a lock-stall row goes only to the session whose process started the holder (agent_tracker.wake_scope.walk_max parents up). The nudge text names the answer that silences it. Off restores the earlier routing. Counters (agent telemetry events): fired = nudge/sent, nudge/reminded, reminder/heartbeat_stale (outcome advise), lockwatch/stall; suppressed = nudge/suppressed with reason judge_done or answered, and wake_scope/dropped with reason foreign_agent, empty_step or foreign_pid (the subject is a field, never part of the event name). Metrics (ah-engine metrics, declared in agent_nudge.toml): agent_nudge_sent {trigger}; agent_nudge_suppressed {reason: judge_done, answered} (a done hold keeps suppressing after its first count without another one); agent_nudge_done_hold_released (held child wrote new output; expiry is not counted); agent_nudge_legacy_hold_adopted (old-field done hold moved to the done holds); agent_nudge_to_owner {where: session, file} (sent and to_owner count only a delivery that succeeded); agent_nudge_delivery_failed {where: queue, wake, owner_file} (a failed write to the reminder queue, the wake feed or the owner notices file); agent_wake_dropped {reason: foreign_agent, empty_step, foreign_pid}.
What works today¶
| Area | Status | Decision |
|---|---|---|
| Daemon and client, single instance, version handoff, resident by default | implemented | D5-D8 |
| Never wedged: hard client budget, watchdog, breaker, crash-loop stop, bounded queue, per-request CPU budget | implemented | D9-D15 |
| Node fallback on every failure, never a silent allow | implemented | D11 |
| Failure classification, once-per-session advisory, secret-scrubbed diagnostics | implemented | D14 |
| Socket 0600, private directory, peer uid check, no network in the daemon | implemented | D16 |
| Shipped defaults for every tunable, table, message, path, env-var name, limit and timeout | implemented | D17 |
Built-in git check with exact parity to git-guard |
implemented | D29-D31 |
Built-in merge-side-pick check (advisory on a push after a one-sided conflict resolution; its PostToolUse pass records into ~/.anti-hall/merge-side-pick-<session>.json, the Node file) with exact parity |
implemented | D29-D31, D75 |
Built-in compact-declaration-guard check: allows new work unless the turn may hold a declaration (the common case, read from the transcript tail); a possible declaration, and so every block, defers to Node |
implemented | D29-D31, D75 |
Built-in coordinator-work-guard check: PreToolUse answers every call the payload proves is not the main thread and defers the rest (the block needs the command classifier, planned, D75); PostToolUse keeps the work window in the Node files (nudge, metrics, trips log, stale-file fold) whenever the call's classification is already stored by the Node PreToolUse pass or provably not work, and defers otherwise |
implemented in part | D29-D31, D75 |
R-inline rule (command-guard, coordinator-work-guard, edit-guard; switch guards.inlineRule, off by default; plan v3 L04; GH #336 #341 #485) |
With the switch on, the Bash write-parity block of command-guard stands down while spawning is stopped (nobody to hand the edit to), as the edit-guard Edit/Write block already does: the call is allowed with the one-time stand-down note, and a write that is also a heavy command with unbounded output is still stopped by the heavy-command block; the coordinator-work-guard window block names the step count (the stopped step included) and the limit; the blocks of command-guard and coordinator-work-guard are counted. Values and texts: inline_rule.toml (inline_rule.sw, inline_rule.window_what). Counters: inline_rule_blocked (guard, kind), inline_rule_standdown (guard). The delivery.act rows command (the check behind the command-guard hook) and edit-guard are added with the switch off or on: they only measure whether a spawn follows a block. No new state file |
implemented |
Transcript protection (command-guard, edit-guard; switch guards.transcriptProtect, on by default; GH #802) |
No agent writes a session transcript: a Bash write to a protected path (a redirect, tee, cp, mv, dd of=, sed -i, perl -i, ln, truncate, rm, inline interpreter code (python -c, node -e, perl -e, a heredoc fed to one) whose write call's own target, or receiver, holds a protected path literal (a target read at run time, such as sys.argv[1], is not a literal and is not stopped; a heredoc written to a file is not code), a remove or move of a folder that holds transcripts (its walk has one per-command budget and fails open past it); the write targets come from the shared parser of the tasklist work count) and an Edit/Write/MultiEdit/NotebookEdit/apply_patch to one are stopped for every agent, in or out of the session project, even when the command is otherwise allowed. Reading (cat, grep, jq) and memory notes (.md) stay allowed. Values and texts: transcript_protect.toml (transcript_protect.globs, transcript_protect.msg_what); counter transcript_write_blocked (kind). |
implemented |
Built-in git-audit check: the PostToolUse --audit pass of git-guard (recent commits with a self-credit trailer after a commit-creating command) with exact parity |
implemented | D29-D31, D75 |
Built-in failure-root-cause-nudge check: the PostToolUseFailure advisory with its noise filter (expected exit-1 predicates, harness refusals, once per turn through the Node turn-gate file) with exact parity |
implemented | D29-D31, D75 |
Built-in advisor-guard check (GH #404; engine-only, only when the session has an advisor tool: payload tool list, the transcript's advisor_tool attachment, earlier advisor use, or a configured advisorModel when the transcript head was never read; else silent): blocks once a plan written with no advisor call this task, and a second edit of a file after a failed test or build that followed its first edit; a passing run clears it; state is per agent Phase 3 (non-flagship main only; the main model is the transcript's own message.model, flagship = advisor.flagship_model_re, Opus/Fable/Codex flagship): guards.advisorThinking on PreToolUse Agent/Task nudges the first fix/design/investigate/root-cause/plan/review dispatch of a task with no advisor call since the owner's last message, blocks the second once, then passes (block_capped); guards.advisorRetry also gates a second fix dispatch for one issue key with no advisor call since the first (once per key); guards.advisorSayDo blocks one Stop per turn whose text announces an advisor call that did not follow. Consults are found by transcript scan (server_tool_use named advisor, or an advisor_tool_result block); harness text, task notifications and peers are not the owner (advisor.owner_*, advisor.non_owner_text_re); a subagent is read from its own transcript (advisor.agent_transcript_tpl), never the main one; what was seen is folded into the per-agent state so the rules do not depend on the 4 MB tail window. Rank exemption (guards.advisorRank, default off, GH #500): the plan block and the retry re-edit block are skipped in the main session while the main model ranks equal or higher than the advisor model of the newest non-sidechain advisor_tool attachment; a subagent or an unknown model keeps them on; counted in the advisor_rank metric (label result: skipped, applied, applied_unknown, applied_subagent). A read that stops at advisor.max_lines leaves the rules silent for that call (silent_behind, GH #558). Every phrase list, pattern, model list and text: advisor.toml. Codex: silent (no advisor tool). |
implemented | D88; settings in advisor.toml |
Built-in scan-throttle check (advisory throttle prefix for user-configured heavy scans) with exact parity; patterns it cannot match exactly defer |
implemented | D29-D31, D75 |
Built-in ship-it-guard check (opt-in plan gate for Edit, Write and MultiEdit; Bash and apply_patch defer to Node) with exact parity |
implemented | D29-D31, D75 |
Built-in limit-conserve-inject, auto-handover, auto-handover-pause-nag and compact-advice-guard checks: the quiet case of each hook, exact (stdout bytes, exit code and no state written); every fire, nag, re-arm, active conservation and possible compact recommendation defers to Node |
implemented | D29-D31, D74, D75 |
Built-in output-verify-guard check (advisory when a test run shows both a passing and a failing signal, once per turn): exact parity, 118 payload steps against the Node hook; a call Jev would be asked about, and an object output whose key order could change the answer, defer |
implemented | D29-D31, D74, D75 |
Built-in claim-ledger check (Stop, ledger only): the ledger and last-message files byte for byte, 91 steps against Node; a flagged turn Jev would be asked about defers |
implemented | D29-D31, D74, D75 |
Built-in speculation-guard check (Stop block on an unverified hedge, once per text, three per session): exact parity, 138 steps against Node, state file included; Jev on, the Stop after a block and guards.inferenceCheck on defer |
implemented | D29-D31, D74, D75 |
Built-in speculation-judge check: the off path of the opt-in model judge (switch off, judge child, skip) is answered; every opted-in call defers to Node, which makes the model call |
implemented in part | D29-D31, D74, D75 |
Built-in ask-guard check (PreToolUse on AskUserQuestion: the off, advise and block modes, the DESTRUCTIVE and CREDENTIAL markers and their log, the in-flight agents note) with exact parity; a transcript only JavaScript can read defers |
implemented | D29-D31, D75 |
Built-in stale-agent-stop-note check (PreToolUse on TaskStop: the advisory for an agent sent a message or resumed after its last report) with exact parity |
implemented | D29-D31, D75 |
Built-in sibling-sweep check (Stop, SubagentStop; guards.siblingSweep): engine-only, no Node twin (the table's fallback command is hooks/sibling-sweep, a shell no-op, so with the engine down nothing runs). Reminds once per cause per turn, capped per scope, when a reply states a bug's cause in a fix context and the turn shows no search for other occurrences of the pattern; the reminder travels as the one-shot Stop continuation JSON. Every phrase, message, limit and the follow-through window is a sibling_sweep.* setting read from the config files at call time, so tuning is a file edit and not a rebuild. Counts reminders and follow-through in ~/.anti-hall/logs/sibling-sweep.ndjson. |
implemented | D17, D74, D87 |
Built-in handover-hygiene check (SessionStart; guards.handoverHygiene): engine-only, no Node twin (fallback hooks/handover-hygiene, a shell no-op). Registers the project for the scheduled handovers job and tells the session once per distinct problem set when handovers are unindexed, stale, missing a brief, lack a Next action or carry a broken reference; the same script is the engine of ah-engine handovers and of the handovers job (index --registered, every schedule.handovers_ms). Tree layout, rules and texts: handovers.*. |
implemented | D17, D88 |
Built-in engine-role-guard check (PreToolUse on Bash; context.roleGuard): engine-only, no Node twin (fallback hooks/engine-roles, a shell no-op). Refuses an ah-engine command the caller's role may not run, per the roles.matrix in roles.toml: a subagent is told from the payload, a workspace child from DEVSWARM_SOURCE_BRANCH; the command line enforces the same matrix for what the environment proves (exit 77). |
implemented | D17, D74, D87, D88 |
Built-in broad-kill-guard check (PreToolUse on Bash, every agent: main session, workspace child, subagent, Codex; guards.broadKill, a locked safety switch): engine-only, no Node twin (fallback hooks/broad-kill-guard, a shell no-op), issue #38. Blocks pkill, killall, killall5, fuser -k, kill -1 / kill 0 and a kill fed by a name or port lookup (kill $(pgrep ...), pgrep ... \| xargs kill); kill <pid> of an explicit PID and pkill -P <pid or $$> (the caller's own children; parent 1 is not a scope) stay allowed. command-guard is coordinator-only and cannot see a subagent's call, which is where the motivating incident came from. It reads simple commands (quotes, substitutions, heredocs a shell reads, sh -c / eval scripts); a script file, an interpreter's kill call or a remote ssh host pkill are out of its reach. The command lists, patterns and texts are plugin data (broad_kill.toml); its own failure allows. |
implemented | D17, D74, D87, D88 |
Built-in burn-breaker check (PreToolUse on every tool, subagents only; agents.burnBreaker; GH #270): engine-only, no Node twin. Blocks a subagent's calls while its hard burn flag is up, which the agent tracker sets after burn.hard_tokens_no_outcome tokens with no commit, finished step, passing check or new file, or when the waste sensor marks the agent hard; the allow-list keeps commit, push, status, read-only inspection (grep, rg, ls, cat, head, tail, wc, git log/diff/show) and the agent's report. GH #458: an allowed way out is never paused: any git commit message form (the heredoc -m "$(cat <<'EOF' ...)" form, quotes, ; or & inside the message, -q, --no-verify, -s, --amend --no-edit; burn.commit_re, burn.heredoc) and the restore class in exact single-target forms only (a restore/rollback/revert/undo/teardown/cleanup program or script with plain arguments, one make target, git restore/checkout --/stash pop |
apply/revert burn.restore_bash_res, burn.restore_deny_res). Both are per-call exemptions, never progress. An error while judging a call is doubt and allows it. Threat model: an accidental runaway (loops, polling, waiting), not deliberate spoofing. HARD outcomes reset the accounting: Edit/Write first edits, real commits and pushes, passing builds and tests (unchanged). SOFT outcomes never reset it: a file the shell created or appended, a passing check command, a completed live probe; a recent one only holds off the pause within a per-burn-episode budget (burn.soft_hold cap and episode_ms since the last hard outcome; a polling loop of any pace is paused), and a build call still in flight holds it off (burn.doubt); the hard flag and its nudge stay, with a reminder that says the pause is held off. Counters: burn_breaker_paused (by reason burn/waste), burn_breaker_bypass (by kind commit/restore/report/send/tool/inspect/doubt), burn_pause_withheld (by reason building/soft), agent_outcome_kind (soft outcomes by kind shell_file/check/probe), all in ah-engine telemetry. The main session and the Primary are never blocked. Thresholds, lists and texts are in burn.toml and agent_tracker.toml; off switch agents.burnBreaker. |
implemented |
Built-in uncommitted-guard check (PreToolUse on Edit, Write, MultiEdit, NotebookEdit and apply_patch, subagents only; guards.uncommittedWork; GH #270): engine-only, no Node twin. Warns, then blocks, a subagent whose worktree holds more uncommitted lines than git.soft_uncommitted_lines and the hard line; a commit lifts it. Settings and texts in uncommitted_guard.toml. |
implemented | GH #270 |
Built-in lane-test-guard check (PreToolUse on Bash, subagents only; guards.laneTestGuard, bypass guards.allowTestSuites; GH #270): engine-only, no Node twin. Blocks suite-scale test commands (cargo test or nextest without a narrowing filter, --workspace, node --test without a file, replay and soak runs) so a lane runs only its own module's tests; guards.testPolicy = none blocks every test runner for subagents (guards.testPolicyMainThread adds the main session). Nested Agent/Task spawns from a subagent or teammate are blocked inside swarm-guard unless guards.allowNestedSpawns is on. The shared command parser, lists and texts are in lane_waste.toml. guards.laneTestLockBoundOnly (default on, #621) limits the block to runners that queue behind a shared build lock (cargo test or nextest, make test, test.sh, replay and soak); a lock-free runner (node --test, npm/pnpm/yarn/bun test, pytest, flutter test) is allowed. |
implemented | GH #270 |
Built-in wide-search-guard check (PreToolUse on Bash, every agent incl. the main thread; bypass guards.allowWideSearch; GH #174): engine-only, no Node twin. Blocks a whole-disk search (find, bfs, fd, rg, ag, ack, grep -r, mdfind without -onlyin) rooted at /, ~, $HOME, /Users or /Volumes, named or implied by cd/the working directory, and suggests a repo-scoped path. Roots, commands, per-path allow list and texts: lane_waste.toml (wide_search.*). guards.wideSearchDepthBound (default on, #623) allows a search with a depth limit within wide_search.depth_allow_max (find or bfs -maxdepth, fd or rg --max-depth). |
||
Built-in claim-evidence-guard check (Stop, Claude only; switches guards.claimEvidence and guards.pushedNotDone; GH #313): engine-only, no Node twin. Holds a reply once when it asserts a result (tests pass, verified, deployed, is fixed) with no matching tool call this turn, or calls work done after a push or PR with no later gh run or gh pr checks look. Codex payloads are not judged. Phrases, patterns, mode (block or log) and texts: claim_evidence.toml. A suppressor (conditional, report, label) must not let a bare factual claim through (GH #427, switch guards.claimEvidenceStrict, default on): a filler opener after if/when (opener_filler_re: "If you ask", "If true"), a reporting word that is a noun after an article (noun_before_re: "According to the reports") or the start of a compound (compound_after_re: "doc-string", "report-card"), and an honest-label word that is negated or noun-like (ack_before_not_re, ack_after_not_re: "not unverified", "unchecked boxes", "unverified aside") cover nothing; an "according to X," phrase keeps its clause across the comma only (clause_join_re, clause_join_break_re); a semicolon, dash, period or newline ends it, so "according to the docs; CI is green" leaves the second claim bare. Each refusal is counted in claim_evidence_suppressor_rejected {reason: filler_opener, source_noun, source_compound, label_not_a_label} (and as an advisory counter in status, under guards.claimEvidenceTelemetry); off restores the earlier reading. |
||
Built-in afk-mode check (UserPromptSubmit, PreToolUse, PostToolUse and Stop on Claude; SessionStart, UserPromptSubmit, PostToolUse and Stop on Codex; settings afk.*; GH #425): engine-only, no Node twin. AFK mode: a machine-wide flag (ah-engine afk on|off|status, ah-engine back, a typed afk / back / progress prompt, or idle detection after afk.idleMinutes without an owner prompt), the AFK rule once per session plus capped reminders, an AFK marker in the session progress file whose checklist bullets are the digest (with the percentage of [x] bullets), a nudge then a capped Stop hold (afk.max_blocks) of an overlong AFK reply (Claude), and the output tokens of each turn from the transcript usage split AFK vs present. No blocking questions (afk.noQuestions): while AFK a PreToolUse entry (afk-mode:pre) denies AskUserQuestion EVERY time with the question ladder (decide from the plan; ask the advisor; only a destructive/irreversible or work-wrecking choice not implied by the plan is parked as a NEEDS OWNER bullet and the rest of the plan continues), with no per-session cap (only a hook error lets it through); a turn that ends on a plain-text question is held at Stop with the ladder (capped by afk.question_max_holds, never on stop_hook_active; Claude and Codex); back / progress list NEEDS OWNER bullets first. Subagents (payloads with agent_id) never get the AFK rule and never touch the parent's once-per-session state; their AskUserQuestion calls are denied too (they are part of the autonomous run). Every rewrite of the flag file takes its cross-process lock (afk.lock_file, shared with ah-engine afk / back) and re-reads the flag inside it, so a stale ON copy never overwrites a newer OFF; a hook has one lock budget per call (afk.lock_wait_ms) for all its tries and writes nothing without the lock. Every flag write (hooks and CLI) is a fenced commit (afk.fence_infix): the holder stages afk.json.stage-<its lock token>, re-checks that the lock is still its own, then renames, and every holder removes all stages right after taking the lock and before reading the flag, so a holder whose expired lock (afk.lock_stale_ms) was taken over can never publish a stale ON over the new holder's OFF (its check fails, or its stage was swept and the rename finds nothing; counted afk_lock_lost). An idle entry is also re-checked by the host after the ownership check, immediately before the rename: when the owner presence or the flag's ended watermark moved past the value its idle decision used, the stage is discarded (counted afk_idle_revoked); the owner's back / afk off (typed or CLI) always bumps ended under the lock, even when the published flag is already OFF, and the CLI records presence before it waits for the lock, so a pending idle ON loses to a newer back. Latency caveat (known, accepted): hook calls of the same daemon queue on an in-process mutex before the per-call lock budget starts, so a hook behind another one of the same daemon can wait longer than afk.lock_wait_ms. ah-engine afk / back retry the lock for afk.cli_lock_wait_ms, never take over a live holder, and when it stays busy write nothing, print afk.msg_lock_busy and exit 1 (a typed afk / back replies the same text). Owner presence never moves backwards, and idle detection counts from the later of the last owner prompt and the flag's ended time (the last back), so a stale presence write cannot re-enter AFK right after back. Codex has no hookable question tool, so there the ladder is carried by the AFK rule and the Stop hold. Metrics afk_entered, afk_turns, digest_entries, idle_trips, afk_overlong_turns, afk_output_tokens, afk_turns_measured, afk_question_denied, afk_question_parked, afk_lock_lost, afk_idle_revoked. Texts, limits and patterns: afk.toml. Owner presence (GH #509): an answered question-tool call is presence (afk.answerPresence), and an idle AFK flag whose recorded presence is newer than its start is ended instead of injecting, counted afk_stale_injection_suppressed (by event). A live owner (GH #849): an owner prompt typed in a session after AFK started suspends that session's question block for afk.presentMinutes (other sessions stay blocked; non-owner prompts and scheduled turns never count; AFK stays on), counted afk_question_present_allowed (by where: pre, stop). |
||
Built-in queued-wait-guard check (PreToolUse on Bash, subagents only; guards.queuedWaitGuard; GH #270): engine-only, no Node twin. Blocks queueing a heavy command in the background and sleep or poll loops, which burn tokens while waiting on a lock. Lists and texts in lane_waste.toml. |
implemented | GH #270 |
Built-in cache-ttl-wait-guard check (PreToolUse on Bash, Monitor and TaskOutput, every agent; guards.cacheWaitGuard; GH #884): engine-only, no Node twin. A single call that waits longer than the prompt-cache window (cache_wait.limit_s, default 270 s: a sleep, a poll loop or watch under a long timeout or Bash timeout, a Monitor or TaskOutput deadline) gets an ORDER to split it into waits of cache_wait.split_s (240 s) or less. Advisory only, never a block; repeats climb the nudge ladder (nudges.kinds.cache_wait, acts at a Stop, and only when nudges.enabled is on, which is off by default). Counter cache_wait_orders_total (by tool and kind). A Monitor call whose whole command is the engine's own wake watcher (cache_wait.watcher_argv, GH #965) is left alone and counted by cache_wait_watcher_exempt_total (by tool). Claude and Codex (Codex has no Monitor or TaskOutput). Lists and texts in lane_waste.toml. |
implemented | GH #884 |
Waste telemetry from transcripts (agents.wasteSense; GH #884): the agent tracker counts two spent-token categories on waste_events_total and waste_tokens_total (source transcript): cache_expiry (an assistant turn that rebuilt its prompt cache after an idle gap above agent_waste.cache_expiry.ttl_ms; tokens = its cache-creation tokens) and poke_turn (a turn woken by the host, agent_waste.poke.origins, that made no tool call; tokens = its weighted tokens). ah-engine status shows them in the waste block next to the avoided-advisory categories. Claude transcripts only: Codex rollouts carry no cache-creation field, so cache_expiry is not available there. |
implemented | GH #884 |
Wake coalescing (devswarm.wakeWatchCoalesce, devswarm.wakeWatchRewakeMs; GH #884): one wake per state change, not one per message. The wake-watch of a child workspace holds a new mesh-direct mail line while the workspace has read none of its mail since its previous wake (its summary row's directUnread against the count at that wake plus what arrived since); reading anything ends the hold, and held mail still unread after the re-wake window wakes it once more (counter wake_watch_coalesced, by role). The native wake keeps its idle gate and 5-minute cooldown. A tool-less woken turn is counted against its sender (poke_turns_by_sender, poke_tokens_by_sender; the sender words are agent_waste.poke.senders, never an id). Host-neutral (Claude and Codex); the sender split reads Claude transcripts only. Coalesce window (devswarm.wakeWatchWindowMs, default 4000, 0 = off; GH #845 phase 2): the first new-mail edge on a child's watcher opens it, nothing prints and no cursor or watermark moves until it closes, then one line covers the direct and broadcast mail due; mail read inside the window prints nothing; a held wake whose workspace read part of its mail wakes again at the next window close instead of after the re-wake window. |
implemented | GH #884, GH #845 |
Agent ancestry telemetry (GH #1165): the ancestry walk that attributes a process to an agent fails closed when it cannot finish, and counts each incomplete walk on agent_ancestry_unknown (counter, label reason: depth, unreadable, reused, vanished; exactly one reason per walk). |
||
Request environment telemetry: when an allowlisted variable (request_env.allow) holds a value that is not UTF-8 it cannot be forwarded, so the capture is flagged incomplete (the checks take their failure policy instead of reading it as unset) and request_env_non_utf8 counts the variables lost (counter, unit variables). |
||
Send-on-change for the post-handover gate and the workspace context ceiling (GH #894, GH #884): auto-handover's post-handover new-work gate is sent when its state changes (the handover point, or the context band of autoHandover.nagStepPct points) and again after guards.handoverGateOnChangeRepeatS, through the on-change store of tool_advisory.profiles (profile handover_gate, switch guards.handoverGateOnChange; suppressed repeats are counted as emit-dedupe suppressions and repeated_advisory waste). A DevSwarm workspace (child) session past autoHandover.workspaceMaxTokens (150K) gets the fire as an order to finish its PR and start the next one in a fresh session (firedVia workspace). A reply whose additionalContext is empty is silence: an allow in telemetry, not an advisory decided and delivered (it was ~12k "deliveries" a window for limit-conserve-inject and auto-handover). Claude and Codex. |
implemented | GH #894 |
Invisible-channel ratchet (test tests/it/invisible_channel.rs, no runtime behaviour; GH #530, plan v2 B3): replays every model-facing output path (the golden corpus answers of each check through the dispatcher's combiner, a few scenario runs of the real scripts, the rule engine's notes and the health advisory merge) on every event and fails when advisory text lands where the model cannot read it (systemMessage, stderr on exit 0, stdout on exit 0 outside dispatch.plain_context_events, additionalContext on an event that ignores it). Today's offenders are listed in channel_ratchet.toml (channel_ratchet.offenders) and the list may only shrink: the test also fails on a listed row that no longer offends and on a new offender. channel_ratchet.user_only holds text that is for the user by design (with the reason), channel_ratchet.unexercised the dispatch-table pairs the corpus has no speaking case for, and channel_ratchet.context_events / block_events say which events deliver which channel to the model. |
implemented | GH #530 |
Agent waste sensor (agents.wasteSense; GH #270): per tracker tick, scores each agent's tokens against its outcomes (commits, finished steps, passing checks, new files), asks the Jev judge (agentWaste) over the soft threshold, and raises the agent_waste signal; a hard mark on a subagent, teammate or workspace feeds the burn breaker. Weights, thresholds and texts in agent_waste.toml. |
implemented | GH #270 |
Built-in engine-role-note check (SessionStart, SubagentStart; context.roleNote): engine-only. Tells the session its role, the engine verbs that role may run and the main skill to read (/anti-hall:engine, $anti-hall-engine on Codex); capped at roles.note_max. |
implemented | D17, D74, D87, D88 |
Built-in silent-agent-nudge check (Stop): answers every Stop that does not nudge, including the rewrite of the nudge state file; a Stop that would nudge defers to Node, which words it and checks the running build |
implemented in part | D29-D31, D75 |
Built-in merge-gate check (opt-in false-done backstop): allows every Bash call Node allows with no output (gate off, not an auto-merge command, no hedge phrase in the recent assistant text); a hedge phrase defers to Node, which owns the block and the Jev shadow ask |
implemented | D29-D31, D74, D75 |
Built-in api-guard check: allows every call that reaches no interpreter probe (guard off, not Python or JavaScript, no verifiable module or global named, no code file named in a shell command or patch); everything else defers, so the probes stay with Node |
implemented | D29-D31, D62, D74, D75 |
Built-in edit-guard check: the launcher-directory block (every agent), every call that is not the main thread, and the verdict on every main-thread target (coordinator allowlist with the symlink and hard-link honesty walk, trusted per-project allowlist, harness plan file, session scratchpad, handover documents, plan mode, DevSwarm child workers and wording, Codex apply_patch), byte for byte; a call that needs the hook process's own working directory or home, or the DevSwarm Primary inline-work note past its threshold, defers (lane L12) |
implemented | D29-D31, D74, D75, D88 |
Built-in task-lifecycle-log check (TaskCreated and TaskCompleted: the per-session history ledger line and its index entry) with exact parity of exit code, output and the files written; a relative cwd, a field cut through a surrogate pair and a number JavaScript prints differently defer to Node |
implemented | D29-D31, D74, D75 |
Built-in dispatch-tier check (PostToolUse on TaskCreate and TaskUpdate): asks Jev (dispatchTier, detached, advisory) once per task text, with the shared answer cache and the request marker in dispatch-tier-state.json as Node keeps them (DECISIONS 1.93); does nothing while the integration is off, and defers only input it cannot read exactly |
implemented | D29-D31, D74, D75 |
Built-in task-guard check (Stop): the Stops where no task is open (loop state removed, pruning advisory and unknown-state note printed exactly); every Stop with an open task, and every transcript record it cannot read exactly, defers to Node |
implemented | D29-D31, D74, D75 |
Task snapshot (#390; task_guards.toml taskstate.snapshot_*) |
The task list is rebuilt from the last taskstate.tail_bytes of the transcript, so a list whose creates lie further back was read as no tasks and every task guard (task-guard, task-tracker, dispatch-tier) went quiet. ah.transcript.tasks (lib/60-guards.js (65-d)) now keeps one snapshot file per session transcript under <state dir>/ah-engine/task-snapshots/ (taskstate.snapshot_dir; the guard and state variants each keep their own section, rewritten in place and atomically) and lays the tail's result over it: the tail wins per task id, what a tail-only update does not state (subject, owner, blockers, priority, start time) comes from the snapshot, and the snapshot's other tasks are kept. A task the tail found not found (a TaskGet or TaskUpdate answered so) is dropped from the snapshot's list. A tail that restarted or emptied the list (No tasks found, a TodoWrite, renumbering inside the tail), another snapshot format, a transcript smaller than when the snapshot was written, another session id or another file under the same path (a fingerprint of the first taskstate.snapshot_fingerprint_bytes bytes and of the bytes just before the tail window, read back at that fixed offset, differs) discards the snapshot, which is replaced by the new list. Renumbering across the snapshot's edge: a task's identity is the tool-use id of the TaskCreate that made it, never its subject (ah.transcript.tasks returns createdBy, number to tool-use id; the snapshot keeps ids per section). A TaskCreate the tail shows under a number the snapshot holds begins a new list when the tail starts at or after the byte size the snapshot was written at (every create in it is new), and, where the tail overlaps bytes the snapshot already saw, only when its tool-use id differs from the one the snapshot recorded for that number (the same bytes name the same id; a rename or an equal subject changes nothing); then the snapshot is discarded (reason renumbered). Where either id is missing (a snapshot task no create was recorded for, as a TodoWrite makes) the snapshot is kept and snapshot_identity_unknown counts it. A snapshot file over taskstate.snapshot_max_bytes is read as damaged and replaced (snapshot_error kind big). The read-merge-write of the file runs under one lock, a kernel flock on a persistent <snapshot>.flock file (taskstate.snapshot_lock_kind = flock, taskstate.snapshot_flock_suffix, never deleted, never counted against the cap; #407: the lock-file protocol cost four directory creates and four removals per take, and the kernel drops a dead holder's lock, so there is no stale wait); taskstate.snapshot_lock_kind = file (owner's settings.json, read through ah.cfgLive) restores the lock file of taskstate.snapshot_lock_suffix, and a filesystem without flock falls back to it by itself; taskstate.snapshot_lock_group times the wait steps, taskstate.snapshot_lock_wait_ms the wait. No other writer shares this file, so no Node lock peer is involved; during an upgrade an older engine on .lock and a newer one on .flock do not exclude each other, which can lose one variant section once (the next rebuild writes it). Counter snapshot_lock (kind flock/file/fallback, result taken/busy/null). A rebuild that finds it held writes nothing this time (snapshot_error kind lock). A snapshot with a malformed task is ignored and overwritten (snapshot_error kind shape); a snapshot that cannot be written leaves the tail's answer; the guard and state variants re-read the file just before writing so neither drops the other's section. Bytes nobody has read: when the tail starts after the size the snapshot was written at (no rebuild ran across a burst longer than the tail), a TaskUpdate in those bytes would be missed and the snapshot would list a finished task as open, so the rebuild reads back to the snapshot's size instead (taskstate.snapshot_gap_max_bytes, counted snapshot_gap result caught_up); a gap over the cap, or one that cannot be read exactly, is not trusted: the snapshot is discarded (reason gap, snapshot_gap result too_big or unread) and the tail alone answers, so a Stop never blocks on a list that may be stale (fail-open; a task that only the unreadable gap could have shown is not seen). Kill switch taskstate.snapshot_enabled (default on; the owner's settings.json taskstate.snapshot_enabled or config.toml [taskstate] overrides it; the script reads that effective value through ah.cfgLive, while ah.cfg stays the shipped value for every other read). Fail-open: any read, parse or write failure leaves the tail's answer. Nothing is ever deleted: at taskstate.snapshot_max_files a session without a snapshot gets none, and old snapshot files are left for the owner to remove. Counters: snapshot_written, snapshot_overlaid (tasks recovered), snapshot_discarded (reason), snapshot_gap (result), snapshot_identity_unknown, snapshot_error (kind), snapshot_lock (kind, result). The Node twin hooks/lib/task-state.js keeps the tail-only cliff |
implemented |
task-guard R-idle rule (Stop; switch guards.idleRule, off by default; plan v2 section 4; GH #461 #516 #517 #262 #177) |
With the switch on, the open-task blocks leave out a task that has a live owner agent or DevSwarm workspace, that a running agent names (#<id> in its description or launch name), that waits on the owner, that has a blockedOn reason, that says parked/blocked/waiting and gives the reason (a bare BLOCKED does not count) or that waits on a clock; plan mode is quiet; the block names the exact task ids and the step that clears them. Values and texts: task_guards.toml (task_guard.idle_rule_setting, idle_rule.*). Counters: idle_rule_fired, idle_rule_listed, idle_rule_suppressed, idle_slot_minutes (a proxy, see its doc), idle_rule_age_unknown; acted-on and ignored come from the delivery funnel row task-guard of delivery.act. No new state file |
implemented |
Built-in reply-length-guard check (Stop, Claude and Codex; switch guards.styleRule, off by default; settings guards.replyMaxChars, guards.replyMaxLines; plan v3 L10 R-style; GH #488 #489): holds a final reply over the size limits (fenced code and markdown tables free up to an allowance) when the user's last message did not ask for detail, a plan, a design, a spec or a report. Stateless: no state file; the retry after a hold carries stop_hook_active and is allowed. Plan mode, subagents and a payload with no reply text allow. Form block (default) or note, patterns, allowances and texts: reply_length.toml. Every main-session Stop is counted in reply_style_observed {result: ok, over, exempt; reason}, whatever the switch; a hit in reply_style_fired {form, again}, a pass with the switch on in reply_style_suppressed {reason}. Not on the delivery funnel (a shorter reply is not a tool reaction): acted-on = 1 - reply_style_fired. Off: the answers are unchanged.} / {again=false |
||
R-pair rule (task-pair-guard: PreToolUse and PostToolUse on Agent and Task, Stop; Claude only; switch guards.pairRule, on by default; plan v3 L11; GH #589) |
Pairs every task with the named agent working on it. With the switch on, an Agent or Task spawn without a name is denied (the step: add name, then set it as the task owner, or put #<task id> of an open task in the description), unless the switch guards.pairRuleByTaskId (on by default, kill switch) is on and its description starts with the id of an open task of the session list that no other agent owns (#<id> as the leading token, read by a bounded linear scan of the first pair_rule.description_scan_max characters with pair_rule.ref_*; a later #400, task #400, (#400) or [#400] is prose; a leading no-break space, BOM or zero-width character is no reference): that unnamed agent is paired by the task id, because a named teammate's reports do not reach the coordinator. Allow only on positive proof: a task list that cannot be read, an unclear reference, a closed or unknown task, or a task owned by another agent denies; the list is the NAMED list when CLAUDE_CODE_TASK_LIST_ID (forwarded by request_env.allow, named by taskstate.list_id_env) holds a valid id whose store directory exists (Claude Code keeps the session's tasks only there and leaves session-<8> empty), else the session task-store directory, which is the list even when empty (a deleted last task never revives from a stale transcript), the transcript only when no store directory exists; two store files with one task id, or a task whose owner is not text, deny too, and the denial for a task another agent owns names the owner and both ways out (TaskUpdate owner="", or spawn with that name) (a name shorter than pair_rule.name_min_chars is no name for the advisory and the Stop block), a named agent that no open task names as owner gets an advisory after the spawn, and a Stop with a live named agent that owns no open task, or an in-progress task owned by the agent id or description instead of its launch name, is blocked (at most pair_rule.ids_max items). Pairing is by agent name as a multiset (case and white space ignored): each open task owned by a name pairs with one live agent of that name, so two agents named alike need two tasks owned by that name; a surplus of tasks is not a pairing fact, and a block's stated steps always clear it (an agent short of a task is given a new one with TaskCreate, because setting the owner of a task the name already owns adds none; a name is data, so __proto__ pairs like any other). Open tasks with no owner and owners that name no live agent stay with task-guard. Main session only; quiet in plan mode, for subagents, on Codex (no owner field), while an OMC loop runs, and whenever the agents or tasks cannot be read or an agent liveness is unknown. Off, the facts are only counted. Values and texts: pair_rule.toml (pair_rule.*). Counters: pair_rule_observed (an unnamed spawn counts as paired_by_task_id, unnamed_unverified, unnamed_ref_unclear, unnamed_other_owner, unnamed_duplicate_task, unnamed_owner_unverified, unnamed_closed_task or unnamed_no_task while guards.pairRuleByTaskId is on), pair_rule_fired, pair_rule_suppressed; acted-on and ignored come from the delivery funnel row task-pair-guard of delivery.act. No new state file |
implemented |
Built-in tasklist-guard check (Stop): the Stops on which Node does not block, with its file effects (progress directory, progress and history indexes, the resume-verification marker and nudge, the plan-mode advisory); every Stop that would block defers to Node |
implemented | D29-D31, D74, D75 |
Built-in devswarm-child-role check (SessionStart): the mesh-only messaging and mailbox-wake directive of a child workspace, and of a Primary with no seat to settle (no session id, or a working directory that is no git checkout), byte for byte, when the stable launchers are current; a Primary in a checkout (seat adoption writes the mesh store), a missing launcher and the rest defer to Node |
implemented in part | D29-D31, D45, D74 |
Built-in devswarm-parent-gate check (Stop): the silent exits of the Node gate that happen before it reads any mailbox; every session that could be blocked defers to Node, so the gate is never weaker |
implemented in part | D29-D31, D45, D74 |
Built-in command check: command-guard's always-allowed commands and every command of a payload-proven subagent, exact; every other command defers to Node |
implemented | D29-D31 |
command check blocks (needs the hook's environment and a stdout-carrying block verdict) |
planned (D57) | D57 |
Built-in verify-first-subagent and verify-first-full checks: the verify-first protocol text (compact or full, Claude or Codex) injected at SubagentStart and SessionStart, byte for byte; a plugin root that cannot be proven defers |
implemented | D29-D31, D74 |
Built-in fable-availability check: reads the host's model cache, writes ~/.anti-hall/fable-availability.json and prints the availability note when a Fable model is entitled; a config file the engine's JSON reader rejects defers |
implemented | D29-D31, D74 |
Built-in inbox-read-guard, phase-tracker, orch-on-spawn, verify-first-orch and verify-first-orch-codex checks (the spawn/path context ports) with exact parity on the paths they answer, a DevSwarm Primary included (rule W comes from the plugin's files); the cases that need Node's own probes defer (a working directory or repository layout the engine cannot classify; orch-on-spawn takes the spawn-time claim itself and defers only the retry slot after the claim's lease, which needs the transcript scan; phase-tracker hashes any working directory in its JavaScript string form) |
implemented | D29-D31, D74, D75, D88 |
Built-in handover-resume and precompact-snapshot checks (handover persistence) with exact parity on the corpus; unreproducible cases defer |
implemented | D29-D31, D74 |
Built-in codex-availability, codex-quota-detect and codex-nudge checks (Codex availability and quota) with exact parity on the corpus; unreproducible cases defer |
implemented | D29-D31, D74 |
Built-in model-routing check for Agent/Task spawns: blocks execution-shaped flagship or inherited generic spawns and advises on routing mismatches. model_routing.never_routine (install, migrate, driver, firmware) keeps such work off the haiku rows (#620); guards.exploreHintSkip (default on) withholds the Explore hint from a review seat or a test-running brief (#336). guards.commandResolveWrapperScripts (default on) makes command-guard judge sh|bash <script> by the script body (#547). |
implemented | D29-D31, D75 |
Built-in verify-first, idle-agent-sweep and emit-dedupe-reset checks (prompt emission, advisory only) over the shared emit-dedupe state file, with exact parity including the state files; a DevSwarm Primary session and anything JavaScript might read differently defer to Node |
implemented | D29-D31, D74, D75 |
Built-in version-alert, devswarm-version, claude-cli-version checks (SessionStart drift and update advisories from a cached probe): output and state file identical to Node on a fresh cache; a stale or absent cache defers because Node starts the detached refresh |
implemented | D29-D31, D74, D75 |
Built-in repo-self-drift check (KB hook and skill counts against disk, model-KB audit age): the scan, its cache and the once-per-finding advisories identical to Node |
implemented | D29-D31, D74, D75 |
Built-in defect-nudge check (once-a-day count of unfinished defect reports or of rulings on this project's reports; counts and ages only): identical to Node; a payload without a working directory or a date the time zone can change defers |
implemented | D29-D31, D74, D75 |
Built-in progress-prune check (archive stale per-session progress files into the history ledger before removing them; weekly gitignore reminder using the client's git): identical to Node; an unusual .git file or a slow git defers |
implemented | D29-D31, D59, D74, D75 |
Built-in swarm-guard check (Agent and Task spawns): memory-pressure and spawn-rate blocks with exact parity, the spawn log, trip log and lock file shared with the Node hook; a spawn that might get the shared-tree advisory defers before it is recorded |
implemented, shared-tree advisory decided natively | D29-D31, D75 |
Built-in devswarm-comms-guard check (SendMessage to a DevSwarm workspace peer) with exact parity; a relative session directory defers |
implemented | D29-D31, D75 |
Built-in jev-weekly-scorecard and repair-on-reload checks: silent when provably nothing would be printed or written, otherwise the Node hook runs (report, migrations and the detached repair stay in Node, D60); no state file is written by the engine |
implemented in part | D29-D31, D60, D75 |
Built-in jev-review-reminder check (SessionStart): every notice of the Node hook, with Jev off or on: the one-time legacy-key notice (its state file, with the legacy key variables forwarded as presence flags only), the recommend-Jev notice and its latch, and the review-due line (the shadow review state and its metrics row), byte for byte; a state file shape only JavaScript reads the same way defers |
implemented | D29-D31, D60, D75 |
Built-in devswarm-child-gate, devswarm-parent-reply-tracker and devswarm-child-drain checks: answer what the Node hook decides before it reads anything but the environment, the settings files and the payload (switch off, skip recorded, not a DevSwarm child, a Bash call that is not a devswarm send); a child workspace, and a plausible send, defer to Node, which owns the mailbox store reads, the stop budgets, the hivecontrol probe and the reply-state writes (needs the mailbox in the engine, D45) |
implemented in part | D29-D31, D45, D74 |
| Check trait and registry, typed errors, documented code | implemented | D30, D39 |
Agent CLI: --json on every command, read-only vs state-changing registry, generated reference |
implemented | D50 |
Metrics (counters, gauges, latency percentiles) and ah-engine metrics; snapshots in hot.db, rollups in archive.db |
implemented | D51 |
Impact ledger and ah-engine impact, savings only as labelled estimates |
implemented, stored in hot.db | D52 |
| Status headline summary | implemented | D50-D52 |
Telemetry recorder: every hook, check and rule run counted by kind, hook or check, event and outcome with latency buckets and injected bytes; lock-free hot path; flushed to hot.db; daily rollups in archive.db; ah-engine telemetry |
implemented | D78 |
Routing telemetry: route events joined to spawn results by spawn_key, NET savings in ah-engine impact |
implemented (the check that writes route events is not ported yet; pre-engine data comes from transcripts, B5) | D77 |
The telemetry rollup as a scheduled daily job (telemetry_rollup) |
implemented | D33, D78 |
Embedded SQLite storage: hot.db and archive.db, WAL, configured durability, versioned migrations, the Store trait over SQLite |
implemented | D19, D21, D73 |
| Tiered lifecycle: write-through to SQLite then memory, active items only, byte budget, key-value with TTL, pub/sub channels | implemented | D20, D22, D25 |
| Transcript index: one incremental read of a session transcript, facts instead of lines, rebuilt on truncation or rotation | implemented as a library, not yet used by any check (planned, D75) | D22, D75 |
| Per-repo git cache: HEAD, branch, upstream, remotes, aliases, config values and the dirty bit, proven fresh by a file signature | implemented as a library, not yet used by any check (planned, D75) | D61, D75 |
| Pushing channel notifications to sessions (Monitor) | planned (D45) | D45 |
Size control: retention, the hot-to-archive mover, WAL checkpoints and VACUUM, ah-engine maintain |
implemented | D26 |
| Compressed export of old chat | planned (D26, D45) | D26, D45 |
Config files layered over the shipped defaults, watched, validated and swapped in atomically; config and config validate |
implemented | D18 |
Config loaded into versioned storage, config versions, rollback, export, restart handoff for restart-only keys |
planned (D18) | D18 |
| Durable write spool when the engine is down or busy: retry with backoff, fsync'd spool, drained exactly once in order | implemented | D24 |
Scheduler and ticker: engine-side jobs (maintain, backups if enabled, metrics snapshot, spool drain), jitter, catch-up, timeouts, retry and cooldown, run history, ah-engine schedule |
implemented | D33 |
| Agent-targeted jobs delivered to a session's mailbox | planned (D45) | D45 |
| Adding and removing jobs from the command line, schedules in versioned config | planned (D33, D18) | D33, D18 |
| Mesh messaging, Monitor push, chat database | planned (D45) | D45 |
Read-only reader of the per-repo DevSwarm stores Node writes (ah-engine mesh, src/mesh.rs): roster, per-workspace counts, messages, gates, cursors, reader cursors; byte-equal to Node's reader on every live store copy (parity P1). Stage 2 (src/meshw/, switch mesh.engine_writes, default off): send, mesh read, mesh history, roster --ack and inbox ack-primary (the successful path: the caller's own-partition cursor moves of a read receipt) with Node's store writes, locking and output, the summary projection refresh those verbs make (summaries/<repoKey>.json), a shadow mode that replays each store-writing verb on a store copy and logs the comparison, and deferral to Node for anything not reproduced exactly (decided before any write; after its own write the engine never reruns the verb in Node, it exits 70 instead). Turn it off with {"mesh":{"engine_writes":"off"}} in ~/.anti-hall/settings.json. Still Node: ingest, a mesh group (sibling partitions) in inbox read-primary and inbox tick, plain roster for any project that has a row, and the sibling and NDJSON-inbox cursor moves of ack-primary |
implemented in part | D45 |
Jev lane: Vercel and TypeSafe transports with fallback and breaker, Noul and Choice calls, off/shadow/on modes, add-block and advisory trust, cache, async queue with budgets, the jev-assist.ndjson rows, ah-engine jev |
implemented, one-shot only | D34-D38 |
| Jev wired into the dispatcher and the daemon, spend budget watch, audit snippets, daily rollups, persisted breaker and cache | planned (D58, D38) | D38, D58 |
Operator helpers: ah-engine jev-setup (status, enable, disable, set-key, bind-generic-key, mode), capability-scan, harvest, briefing, byte-for-byte with the Node scripts |
implemented | D81 |
Operator commands ah-engine update (pull, cache sync, harness re-registration, changelog) and ah-engine install-codex (the Codex port installer), with the Node scripts' output and file effects; the post-pull stages are run by the engine (table update_post.toml): budget deferral, the DevSwarm gate and the one-time per-version markers are answered natively, the stages' real work on the stores and settings runs by the script's own stage function in a bounded Node subprocess |
implemented | D81 |
| Backups and restore: online snapshot of both databases, scrubbed; restore keeps the current state first | implemented | D27 |
Health check and repair: ah-engine doctor (platform and versions, hook scripts on disk, live self-tests of the built-in guards, statusline, Workflow templates, the repair pass) and ah-engine migrate (the persisted-state migrations and sweeps) |
implemented for the plain-file steps; the DevSwarm-store steps and the spawn-based checks stay with the Node doctor | D81 |
| The DevSwarm store migrations, the statusline render, context footprint, supervisor, OMC and Codex detection, ingest units and the opt-in doctor flags in the engine doctor | planned (D81) | D81 |
| Issue log and opt-in upload | planned (D28) | D28 |
| Update checks as a scheduled job | planned (D44) | D44 |
One dispatcher call per hook event: ah-engine hook --event, built-in checks in the engine, the other hooks as Node, combined in table order; the plugin's hooks.json is one thin trigger per event, generated from the table (ah-engine gen-hooks) |
implemented on the engine-proto branch (the installed plugin changes when it merges) |
D58, D75, D87 |
Per-event and per-entry hook configuration ([events.<Event>], [entries.<id>]: mode, max_rules, budget_ms, order) and the when predicate |
implemented | D87 |
Realtime watch facility (src/watch/, generic: directories and file names in, coalesced batches or one rescan signal out): OS file events (FSEvents, inotify) by default, stat polling for 9p, drvfs, NFS, SMB, FUSE and any directory the OS refuses; bounded queue; no consumer wired yet |
implemented | R1 (DECISIONS.md, "Realtime watch backend") |
| Porting the other guards | planned (D57) | D57 |
| Prebuilt binaries for every Unix target, release automation (prepare, publish, sha256 and attestation), the plugin-side bootstrap with a pinned lock | implemented (see Install, go-live and rollback) | D56, D64, D67, D68 |
Session-cache refresh (v1.0 lane L06)¶
ah-engine refresh [--force] [--home <dir>] handles the refresh requests the SessionStart checks write (the remote-latest release tag for version-alert, the Claude Code and DevSwarm CLI versions for the drift probes, and the reload repair for repair-on-reload), each as a bounded subprocess. Where the Node hooks started a detached refresh, the engine's checks write a request file, answer at once and let this job do the work; the scheduler runs it every refresh.every_ms (refresh.toml).
Background units, the MCP reaper and the wake-watch monitor (v1.0 lane L08b)¶
ah-engine units <status|install|heal|uninstall> [--dry-run] [--bin <path>] [--json]writes and loads the one engine unit (a launchd agent on macOS, a systemd user timer on Linux) and, onheal, moves aside (never deletes) the Node units whose duty the engine now runs. Every action is a ledger line, an engine log line and a telemetry item.updateruns the heal as a post-pull stage anddoctor --repairas a repair row (units-heal), idempotent and silent when nothing changed; the settingmaintenance.unitsHeal(default on) switches both off.- Supervised unit (
maintenance.unitsSupervise, default on; all numbers inunits.toml): the unit restarts a killed daemon. launchd:KeepAlive{SuccessfulExit=false}+ThrottleInterval; systemd:Restart=always+RestartPreventExitStatus=0+SuccessExitStatus=75+RestartSec+StartLimit*. Exit 0 (stop, handoff, idle, another daemon answers, crash-loop stop) is never restarted;StartInterval/ the timer stays as the fallback for those. A supervised daemon (start reasonlaunchd/systemd) that an outside SIGTERM (kill <pid>) drained exitsdaemon.sigterm_exit_code(75) and logsexit/sigterm, never a crash; a clean drain cut off by its timer exitsdaemon.drain_timeout_exit_code(0). A client with no daemon asks the manager to start the unit (launchctl kickstart/systemctl --user start) only when the unit on disk is exactly what this engine would write and the client has noAH_ENGINE_*override the unit lacks; the ask is the start command only (units.kickstart_timeout_ms, 300 ms; measured on macOS with a release build and a scratch label:launchctl kickstartreturns in 11-18 ms and the daemon answers 0.60-0.69 s after it), logged asunit_kickstart/asked. A guard event then keeps waiting for the supervised daemon withinclient.cold_guard_wait_ms(loggingokwhen it answers,misswhen not, and failing open on a miss) and never starts a second, unsupervised daemon while the manager's is coming up; only a failed command makes the client start the daemon itself. A call that never waits (a prompt, an advisory, an answer-now call) runs the start command withinunits.kickstart_unguarded_ms(100 ms). The spool writer starts the daemon the same way. A supervised start obeys the crash-loop rule (crashloop_until, the spawn-rate rule overhealth.spawn_kinds, logged assupervised_startonly after the lock is won); a supervised start that fails (exit 78) counts asstart_failtoward that rule and exits 0 once it trips, so launchd (no start limit) stops restarting it everyunits.throttle_interval_s; if the state directory itself cannot be written the failure cannot be counted, so a supervised start exits 0 at once (the unit'sStartInterval/ timer retries) instead of the manager re-running it everyunits.throttle_interval_s. Counters (telemetry):supervised_start(by start reason) andunit_kickstart(by outcome code: asked, ok, miss, failed). On launchd the unit's stdout/stderr go tounits.plist_login the state directory (not /dev/null), so what the daemon can only say on stderr (a failure record it could not write) is kept; the daemon empties the file at start once it is overunits.plist_log_max_bytes. An older interval-only unit is found bydoctorand rewritten bydoctor --repair/units heal, the old file kept once as<unit>.bakin the unitsretired/directory (never replaced, never left next to the new unit).doctoralso warns when the unit file is not loaded by the service manager and when a supervised unit differs from what this engine would write (a client then does not use the manager). Not included: socket activation (launchdSockets, a systemd.socketunit): the unit starts the daemon, a client asks for it with kickstart, and the interval or timer remains the fallback (tracked as a follow-up issue). Verified on macOS with a scratch launchd label and a release build (never the live job):kill -9of the supervised daemon is restarted by launchd and answering 0.65-0.68 s after the kill (3 runs;KeepAlive{SuccessfulExit=false}covers death by signal); not verified on systemd outside the CI unit test. Limit: after a crash-loop binary rollback to an engine without this gate, the unit restarts the daemon everyunits.throttle_interval_s/units.restart_secwith no breaker until the rolled-back binary is replaced. ah-engine mcp-reaper run [--dry-run]is the port of the standalone MCP orphan reaper (ah-hook mcp-reaper), run by the scheduled jobmcp_reaper(mcp_reaper.job_every_ms). The settingmaintenance.mcpReaperJobisautoby default: it runs once the Node reaper's opt-in was carried over byunits heal, and never while a Node reaper unit is still installed, so the reaper never runs twice.monitors/monitors.jsonstarts ONE Monitor,ah-engine agents wake-watch --auto: a single process that streams the agent tracker's wake rows (agents.wakeWatch) and, in a DevSwarm session, the mesh wake lines (devswarm.wakeWatch; off, no mesh line is printed). The agent half runs on a thread, the DevSwarm half on the main thread; each keeps its own lock.devswarm wake-watchand the former second monitor entry are aliases of it (the alias prints a deprecation note on stderr only), so a running session or a Codex port that still names the old verb keeps working. Countermerged_watch_rows(labelled bysource) counts the printed rows; countermerged_watch_failed(labelled byhalf) counts a half that panicked (agent half of the merged wake watcher panicked; labelled by half). Countermonitor_nag_suppressed(labelled byreason) counts ticks where the re-arm line was held back because the session has no live child or background task to watch (agent_tracker.limits.monitor_min_bg). The tracker judges a DevSwarm session's coverage again on every tick (#972): a descriptor that names the session binds it before the app's sessionless row for the same checkout, an archived twin no longer hides a descriptor that has a live lock or was written after the archive, and a row no live descriptor binds loses its workspace facts and is a main session again; counteragent_ws_coverage(labelled byhow: archive_ignored, unbound). No Node watcher runs: when no engine can run the command the thin client prints one line and exitslauncher.cli_no_engine_exit.
Install, go-live and rollback¶
Install. The plugin ships ah-engine.lock (schema, engine version, tag and the sha256 of every release asset) and one shell
file, hooks/install.sh. While ~/.anti-hall/ah-engine/bin/ah-hook is missing, hooks.json runs install.sh for each hook
event: it prints nothing on stdout, exits 0 and gives one notice line per session on stderr. It downloads nothing by itself unless
you opted in (the setting engine.bootstrap = true, or AH_ENGINE_BOOTSTRAP=1; off by default). The install is a deliberate
step: the setup skill (/anti-hall:activate) runs sh hooks/install.sh --download. From then on the thin client does the same job
as ah-hook install [--lock FILE] [--print-target] [--auto] [-v] (--auto is the session-start form that honours the opt-in).
Both (never fail a session):
- detect the target (macOS arm64 or x86_64, Linux x86_64 or arm64 on glibc or musl, WSL as Linux; anything else, such as native Windows, is reported as unsupported and skipped);
- download
ah-engine-vX.Y.Z-<triple>.tar.gzfrom the GitHub Release over HTTPS (TLS 1.2 or newer, 120 s download limit, 128 MB size cap;curl, orwgetwhen there is nocurl); - install
ah-engine(andah-hook, when the release archive holds it) into~/.anti-hall/ah-engine/bin/only if the archive's sha256 equals the lock's entry. There is no trust on first use: a mismatch is refused and nothing is installed. Only the expected members are extracted, and the new engine must answerversionwith the pinned version first (ah-hook install); - do it atomically and keep the previous binaries as
bin/ah-engine.prevandbin/ah-hook.prev, under the one install lock that the integrity check and the updater share.
It is idempotent (the same lock does nothing), rate limited (a failed automatic attempt for a lock is retried after 6 hours), and
it never overwrites a binary it did not install (a local build is left alone). Every outcome is written to
~/.anti-hall/ah-engine/bootstrap.log as event=<id> key=value records. A plugin tree without ah-engine.lock installs
nothing. Every URL, command line, name and limit is in [install.*] of engine/defaults/engine.toml (see also
RELEASING.md). This download is the only network request the engine's install makes; see
PRIVACY.md.
Updating the engine (ah-hook update). One updater, the thin client's update command (no shell, no Node; deliberately outside the
engine so a broken engine stays fixable; ah-engine engine-update hands off to it), moves the binaries between three sources. When the
release archive also holds ah-hook, the thin client is swapped too: atomically, the old one kept as bin/ah-hook.prev, and put back at
once if the new one fails its own self-test. Every URL, timeout, channel name and text is in [updater.*] / msg.updater_* of
engine/defaults.
| Command | What it does |
|---|---|
ah-hook update --from FILE [--sha256 X] |
Offline: FILE is a release .tar.gz or a bare binary. The expected sha256 is --sha256, else the SHA256SUMS next to FILE, else ah-engine.lock; with none of them the sha is printed and --yes is required. A mismatch refuses. |
ah-hook update --channel stable |
The latest ah-engine-v* release, checked against its SHA256SUMS, this plugin's lock when the versions match, and the GitHub build attestation when gh is installed and logged in (skipped with a note otherwise). |
ah-hook update --channel dev |
The latest ah-engine-dev-<sha8> pre-release (built and attested by CI on each engine-proto push that changes ah-engine/). With the live kit installed it also syncs the plugin files at the commit the pre-release records, so engine and plugin do not drift. |
ah-hook update --rollback |
Restores the previous binaries (bin/ah-engine.prev, bin/ah-hook.prev); run again to toggle. With the live kit, restores the previous bundle and re-applies it. |
Each update smoke-tests the new binary (version), swaps it in atomically (the old one is kept as .prev), then restarts the daemon with
the engine's own stop and serve; any failure keeps the old binary. --dry-run checks everything and installs nothing. With the live
kit the binary and plugin go in through the kit (bundle/ and a go-live.sh re-apply, --live-select picks the entries), so the kit's
own rollback keeps working. Setting engine.autoUpdate = stable or dev (default off) runs --auto from the engine scheduler, at most
once a day. The updater's only network requests are the GitHub release API and downloads, and git fetch of one commit for the dev plugin sync;
ah-engine engine-update <same arguments> runs the same script (the engine itself does no network access, and a broken engine is still
updated with the script by hand). The scheduler job engine_update (defaults file engine_update.toml) runs engine-update --auto
every 6 hours; the script does nothing unless engine.autoUpdate is set and limits itself to one check a day.
Engine currency (issue #541, defaults file engine_currency.toml). The scheduler job engine_currency (hourly) tells you when the running
engine lags the source checkout it came from. It only reports: it never fetches, rebuilds or deploys. It compares the commit in the engine's
build version with the tip of engine_currency.branch (refs/remotes/origin/<branch>, then refs/heads/<branch>) in the checkout named by
the setting diagnostics.engineCurrencyCheckout, and, when the commits are equal, the git blob ids of the compared files
(engine_currency.hash_paths) at that tip with those of the files the running engine reads. Only git objects are read, never the checkout's working tree.
The result is ok, behind, files_differ or unreadable; it is counted in the metric engine_currency_check (label result), written once per
engine_currency.log_interval_ms as an event-log line of kind currency that names both commits and the step that clears it, and shown as the
currency field of ah-engine status --json (live_sha, dev_head, files_live_hash, files_dev_hash). The switch diagnostics.engineCurrency
(env ANTIHALL_ENGINE_CURRENCY) is on by default; with no checkout set (the default, because the path is local) the job does nothing.
Memory diagnostics (issue #21, defaults file diagnostics.toml). With diagnostics.mem_log on (default) the daemon appends one NDJSON line
per served request to mem.ndjson in the state directory (rotated at diagnostics.mem_log_max_bytes): the request kind and event, the checks
that ran, the resident set, the allocator's allocated and resident bytes and the counted heap before and after, and the size of the
transcript file. When the resident-set cap trips (diagnostics.mem_snapshot) the daemon writes mem-snapshot.json before it drains:
allocator statistics, thread count, each worker's interpreter and regex cache, the transcript caches and the platform memory map.
ah-engine status --memory prints the live figures, the latest snapshot and a summary of the log (top events and checks by total
resident-set growth; a check's row counts every request it took part in, so rows overlap). Nothing here changes a decision.
Per-call memory (mem::measure, diagnostics.check_mem, diagnostics.check_mem_sample_every). The counting allocator keeps three
thread-local counters per thread (bytes allocated, bytes freed, high-water mark of the net), so one call can report the bytes it allocated,
the most it grew the heap and what it kept. They are hand-written rather than read from jemalloc because they must give one unit (the requested
Layout size, the unit of the counted heap) under jemalloc and under AH_ENGINE_ALLOCATOR=system: jemalloc's thread.peak is sampled every
64 KiB of activity and does not exist in system mode, and thread.allocatedp counts usable sizes (the tests use it only as an oracle). The
counters are const-initialised and have no destructor, so nothing allocates inside the allocator. Measured cost in a release build: about
0.3 ns per allocation and free, 0.005 % of a core at the live rate of 190,000 allocations a second. check_mem = false stops the counting;
check_mem_sample_every = N measures every Nth call. A diag build (dhat) reports nothing.
status --memory also carries a live ledger under memory.ledger: the process tier in MB (footprint, jemalloc resident, the C-library
zones' bytes in use, never the address space they reserve) and a heap tier in bytes (the counted Rust heap, allocated, against the named
holders of the memory registry; other is what no holder names, attributed_pct the named share). invariant.other_nonneg is false, with
the holders listed in overcount_by, when the holders sum past the heap by more than mem.ledger_skew_bytes. The sys_reserved_* fields of
mem.ndjson rows are the zones' reserved address space (formerly sys_allocated_*); sys_in_use_* is the usage figure.
Memory budgets (issues #21 and #158, defaults file mem.toml). Every long-lived in-memory holder (the shared regex cache, each worker's
QuickJS interpreter, the transcript-tail cache, the config values leaked on purpose) registers with one registry in src/mem and gets a
soft and a hard limit from mem.<holder>_soft_bytes / _hard_bytes (and _low_water_pct); mem.global_* bounds the process. At the soft
limit the holder is logged once and evicted (least recently used first) down to its low-water mark, with hysteresis, while requests keep
being served. An insert that would cross the hard limit is refused (a cache miss; a script call fails open) and the holder is recycled; if
the process total (or a holder that cannot shrink) then stays over its hard limit for mem.global_restart_after_s, the daemon drains and
restarts cleanly with the reason in the event log. ah-engine status --memory lists each holder's bytes against its limits, the trigger
counts and the global totals under memory.budgets. A guard test (tests/it/mem_guard.rs, allowlist tests/mem_allowlist.txt) fails the
build when a long-lived collection appears outside src/mem without a stated bound. Helper-process output is cut at
mem.proc_output_max_bytes.
see PRIVACY.md.
Go-live. An engine check is trusted only after it has agreed with the Node hook it replaces. Before release the whole
dispatcher was replayed against Node (see Measured results); per entry the engine can also run
beside Node on live traffic: mode = "shadow" on a guard entry that has a built-in check runs the check next to the Node hook,
which still decides, and logs dispatch_shadow with whether the two agree (Dispatcher, configuration of events and
entries). A check that cannot reproduce Node exactly defers (exit 75 from the engine, the wrapper then runs the Node hooks).
Rollback. In order of how much you want to undo:
| To undo | Do |
|---|---|
| one check | set mode = "off" on its [entries."<id>"] in the engine's config.toml: only the engine's check is skipped, its Node hook decides (hot reload, no restart) |
| the engine, for now | ah-engine stop, then remove ~/.anti-hall/ah-engine/bin/ah-engine; the wrapper finds no binary (it looks at its test-only binary override, ~/.anti-hall/ah-engine/bin/ah-engine, then ah-engine on PATH; remove a PATH copy too) and runs the Node hooks |
| the engine, for good | also set engine.bootstrap = false or the opt-out variable (see Install above), or the next SessionStart reinstalls the pinned binary |
| a bad engine build | copy bin/ah-engine.prev back over bin/ah-engine; the bootstrap then leaves it alone (its sha256 no longer matches the install marker), so the rollback sticks until you remove the binary or the lock changes |
| a bad plugin edit of the engine files | nothing to do: the layered failover below falls back by itself |
Whatever the engine cannot do, the Node hooks did; that was the migration-era design. Since release 0.301.1 no Node hook ships
in the plugin; the backup is kept outside it (plugins/anti-hall-node/) and runs only when you switch it on with
ah-engine fallback node (see "The Node backup: shadow and fallback switch").
What still runs on Node¶
Historical (migration era). This section and its table describe the deferrals of the staged migration, kept for the record. The
dispatcher now has a standing guarantee that no production deferral reaches a Node start (src/dispatch/mod.rs, test
no_shipped_entry_can_defer_to_a_node_hook_that_is_not_launched); read the rows below as what used to stay on Node, not as the current runtime.
The engine did not replace Node at first; it answered what it could prove identical and left the rest. The list of what stayed on Node then (each was a deferral, so Node's answer was the one the host saw):
| Stays on Node | Why |
|---|---|
| DevSwarm mesh writes (mailbox, roster, cursors, archive) and the DevSwarm daemons (ingest, liveness supervisor, reaper) | the engine only reads the per-repo store in place (ah-engine mesh, read-only); engine-owned mesh writes are planned (D45) |
Every call that would consult Jev (the Jev integrations: speculation, claim ledger, output verify, git self-credit, model routing, tasklist, codex nudge, merge-gate hedge, parent-gate question, and the rest of the jevIntegrations table) |
the engine has the Jev lane as a library and ah-engine jev, but the dispatcher does not call it yet (planned, D58, D38); with Jev off the engine answers, with Jev on Node keeps its exact behavior |
The semantic judge (speculation-judge's model call to Haiku, directly or through your claude CLI) |
a model call with its own backends; the engine answers only the judge-off path |
| The statusline | a separate Node process the host runs for the status bar; not a hook |
| The blocking branch of several guards | api-guard's interpreter probes, merge-gate's hedge, task-guard and tasklist-guard Stops that would block, silent-agent-nudge, devswarm-parent-gate, and the command check's non-trivial verbs: the engine answers the quiet cases and defers any case that could block |
| SessionStart context over the 10,000 character host cap, and cases with a stale cache or a date, JSON or regex construct the engine cannot read exactly like JavaScript | the whole hook defers before anything is written, so Node sees the state it would have seen |
task-tracker, the doctor's DevSwarm migrations, the statusline render, supervisor and OMC/Codex detection |
see "What works today" for the planned items (D81) |
Platforms: macOS on Apple silicon. Linux (including WSL), Apple Intel and native Windows are coming soon; the bootstrap and the engine are not supported or tested there yet.
Measured results (pre-release)¶
These are pre-release measurements from one replay, not a guarantee and not a field result. Setup: a frozen sample of 2113 real hook payloads, replayed once through the exact go-live bundle (engine binary plus plugin tree) and once through the Node hooks of the same plugin tree, each side in its own pristine sandbox and isolated home, concurrently, paced at 0.15 s per payload.
| Measure | Result |
|---|---|
| Blocks Node made that the engine did not (ENGINE-WEAKER) | 0 of 68 (the engine blocked all 68) |
| Output identical to Node | 2059 of 2113 payloads |
| Differences | 30 text-only, 7 advisory dropped by the injection gate on purpose, 2 stricter, 15 SessionStart deferrals (over the context cap, so Node runs in production) |
| Hook rows answered natively by the engine | 87.0 percent (8748 of 10051); 54.1 percent of calls needed no Node fallback at all |
| CPU per call, engine (client plus daemon) | about 35.5 ms (client 28.2 ms including the Node hooks it launched, daemon 7.4 ms) |
| CPU per call, the Node hooks alone | 158.2 ms |
Known gap found by the same replay and not yet fixed: when two hooks block and one of them was deferred to Node, the engine's
output can keep only one block reason (5 payloads), and task-guard's informational "deferring Stop block" notice is not printed
(6 payloads). The decision (block) is the same in every one of them. The figures depend on the sample, the machine and the load; the
full report and the per-event table are kept with the release notes of the engine.
Commands¶
Every command accepts --json and prints one JSON object. Read-only commands never change state. The full table, with
arguments, is in the generated reference.
| Command | Read-only | What it does |
|---|---|---|
ah-engine hook |
no | The hook client: payload on stdin, answer on stdout. With --event it is the per-event dispatcher (see Dispatcher). |
ah-engine serve |
no | Run the daemon in the foreground. |
ah-engine status |
yes | State, uptime, memory, counters, breaker, rules and a headline summary. |
ah-engine metrics |
yes | Metric series; --check <name> narrows to one check; --rollup minute\|hour [--since <s>] shows stored rollups. |
ah-engine impact |
yes | What the engine affected; --kind, --project filter, --window <7d> for the NET section. |
ah-engine telemetry |
no | summary, events, rollup, funnel: see Telemetry below. funnel [--by model,project] [--window 7d] is the per-rule delivery funnel. ah-engine telemetry summary [--window 7d] is the one to run first: per hook and check, invocations, outcomes, latency and injected bytes. summary and events only read; rollup writes, idempotently. |
ah-engine docs |
yes | The generated reference (--format md, or --json), and the generated engine skill family (--format skill-list, --format skill --name <skill> [--host claude\|codex]). |
ah-engine gen-hooks --host claude\|codex [--kind hooks\|registry\|list\|map] |
yes | Print a file generated from the dispatch table: the thin hooks.json (one trigger per event), the per-hook registry, the wrapper's fallback list or its fallback map (D87). |
ah-engine check <name> |
no | Run one check on a payload from stdin, as the hook path runs it (parity harness); a stateful check keeps its own state and counters. |
ah-engine version |
yes | The version this build reports. |
ah-engine ctl <verb> [args] |
no | ping, reload (also re-reads the config files), stop, status, config, and profile on [sample\|full] [--for <dur>] / profile off / profile status: per-check CPU and allocation spans to a bounded file (diagnostics.profile* keys), off by default (one atomic load per call), auto-expiring when switched on at run time. |
ah-engine diag <topic> |
yes | Read-only reports over state the engine already keeps, not feature-gated: cpu, mem, threads, hooks, mesh, jev (from the daemon), fs and locks (the state directory; they work with the daemon down) and trace (the always-on ring of the latest check, duty, stage and hand-back records; also written to diagnostics.trace_dump_file when a hard limit trips). The heap-replay diag heap stays behind --features diag. |
ah-engine stop |
no | Drain and exit. |
ah-engine reset |
no | Clear the breaker, crash-loop stop and failure record. |
ah-engine maintain |
no | Size control: move inactive rows to archive.db, prune derived bookkeeping, checkpoint and VACUUM; prints a report. |
ah-engine proj <cwd> <verb> |
no | Per-project state in hot.db: mailbox put, take, len; key-value set, setex (TTL in seconds), get. A write the engine cannot take is spooled. |
ah-engine jev <ask\|status\|scrub\|evidence> |
no | The optional Jev lane: evidence reads one evidence pack per stdin line and prints what the evidence gate did with it (see "The evidence gate" under the Jev lane); ask reads JSON requests (one per stdin line) and prints each decision, status prints the resolved settings and every integration's mode (never a key), scrub redacts secrets from JSON strings. |
ah-engine doctor [--check] [--repair\|--fix] [--dry-run] [--migrations-only] [--quiet] |
no | The health check and repair, in the Node doctor's layout and finding texts. Read-only unless --repair; --dry-run previews; --migrations-only with either prints only the migration report as one JSON line. Each built-in guard is run in-process on a crafted payload (a payload the engine defers is run through its Node hook, as the dispatcher would; with no Node it is reported as a deferral, never a pass). |
ah-engine migrate [--dry-run] [--home <dir>] [--cwd <dir>] [--plugin-root <dir>] |
no | The persisted-state migrations and sweeps of the Node doctor's repair pass, with Node's report: legacy progress/history copy, reply-state, gate-intent and auto-archive forward migrations, the settings.json migration, the Jev triage cache repair, the lock scratch sweep and the retention sweeps. Idempotent, fail-open, no repo file is moved or deleted. |
ah-engine jev-setup <status\|enable\|disable\|set-key\|bind-generic-key\|test\|mode\|review-due\|reviewed\|snooze> |
no | The port of ah-hook jev-setup (D81): status prints the resolved settings, key presence yes or no, every integration's mode, the calls of the last 24 hours and the Vercel credit balance; enable, disable, bind-generic-key and mode <integration> on\|shadow\|off write settings.json and jev.json the way the script does (read-modify-write, key order kept, a corrupt file moved aside); set-key reads the key from stdin only and writes the key file with mode 0600; test makes one real gateway call per configured transport, each on its own, and review-due [--json], reviewed <integration> and snooze <integration> --days N keep the durable shadow-review state (~/.anti-hall/jev-review-state.json). Every verb is answered natively (v1.0 lane L03). |
ah-engine jev_sweep |
no | The scheduled jev_sweep job (jev::sweep): one evidence sweep of the supervisor's Jev questions; it gathers the WaitKind, Loop and StepMap facts (plan, transcript, git, CI, mesh), runs them through the evidence gate (jev_evidence.toml) and records the telemetry; Node no longer asks those three questions. Takes no arguments; the home directory comes from the environment. |
ah-engine gh <status\|segment\|poll> |
no | GitHub realtime (#20, independent of DevSwarm): status prints the followed repos with their pull request, review, CI and mergeability, the rate budget, the hold in force and the measured rate-limit cost of 200 and 304 answers (state file only, no network); segment [--cwd <dir>] prints the statusline piece for the repo that holds the directory; poll [--force] runs one tick now. |
ah-engine gh_poll |
no | The scheduled gh_poll job (ghrt::poll): one tick of GitHub realtime; always exits 0. |
ah-engine agent_tick |
no | The scheduled agent_tick job: one agent-tracker tick (the same as agents tick); prints its counts with --json. |
ah-engine capability-scan [--root <plugin dir>] |
yes | The port of ah-hook capability-scan (D81): which opt-in capabilities of a plugin tree are shipped and active on this machine, and how to enable the ones that are not; prints the JSON report, then one line per capability. |
ah-engine update [--check] [--post-pull-only] |
no | The port of ah-hook update (D81): git pull --ff-only of the marketplace clone (a dirty tree or a diverged history is a hard STOP with exit 1; an offline failure fails open), a copy of the plugin into a new version-pinned cache directory (never over or beside an existing one), claude plugin update anti-hall@anti-hall when the harness registry is behind (20 s bound, never answers a confirmation, installed_plugins.json is only read), the changelog delta, then one JSON status line and the human summary. --check compares versions only. The post-pull stages (update_post.toml, in update.js's order, status keys in its key order) are run by the engine: the overall post-pull budget (ANTIHALL_UPDATE_POSTPULL_BUDGET_MS) defers a stage whole, a stage that is DevSwarm-only is answered with the closed-gate text outside a DevSwarm session, a one-time stage already stamped complete for the new version in update-sweep-state.json is answered with the script's "already completed" shape, and everything else runs by the script's own exported stage function in a bounded Node subprocess (so its answer, key order included, is the script's). Reconcile, the store folds and heals, the settings migration and the Codex hook cleanup stay in Node for their real work: their results come from serde_json maps (sorted keys) in the engine's ports, which cannot reproduce the script's key order. A plugin file a stage needs being missing is also left to the script. |
ah-engine install-codex [--global] [--dry-run] [--root <plugin dir>] |
no | The port of codex/install-codex.js (D81): merges the generated Codex hook registration into .codex/hooks.json (project, or the home directory with --global), replacing only anti-hall's own groups, and enables the hooks feature in config.toml. A file that changes is copied to <file>.bak-<time> first; --dry-run writes nothing; a second run changes nothing. |
ah-engine harvest [--dir <path>] [--stale-days <n>] |
yes | The port of ah-hook harvest (D81): the anti-hall: <ceiling>, <when> debt markers of a code tree, flagged when they have no payback trigger or sit in files git says are old. |
ah-engine briefing [--root <plugin dir>] |
yes | The port of ah-hook briefing (D81): a derived inventory of a plugin tree, the registered hooks by event with the purpose from each hook's header comment, the skills, the DevSwarm substrate and the docs map. |
ah-engine settings <show\|get\|set\|reset\|judge\|trust-command-allow\|trust-edit-allow> [args] [--json] |
no | The port of ah-hook settings (L9a), byte-for-byte; replaces node "${CLAUDE_PLUGIN_ROOT}/ah-hook settings" ... in skills/settings/SKILL.md at the cutover. A run is also replayed by the Node script in a scratch home in the background (ops.shadow_rate_settings), a mismatch is a shadow telemetry event. |
ah-engine defect <report\|list\|show\|rule\|archive\|backfill\|recurring\|similar> [flags] [--json] |
no | The port of ah-hook defect with the defect store and history (L9a), byte-for-byte; replaces ah-hook defect ... in skills/defects/SKILL.md at the cutover. Shadowed by Node like settings (ops.shadow_rate_defect). |
ah-engine auto-handover-config <get [--json]\|set <1-99>\|off\|on\|nag on\|off\|nag-step <n>\|nag-quiet <n>\|max-tokens <n>> |
no | The port of ah-hook auto-handover-config (v1.0 lane L03): get or change the auto-handover trigger's settings (section autoHandover). The command reads the values as the settings store answers them (environment, file, plugin option, default) and writes the changed ones one key at a time through the same store as settings set; what to print and what changed is the plugin script engine/logic/rules/operator-cli.js. ANTIHALL_AUTO_HANDOVER_PCT=0 still switches the trigger off outright. |
ah-engine capacity-hashes [<path>...] [--json] |
yes | #928: read-only; prints the current sha256 of each file on the capacity-hold trusted-scripts list (dispatch.capacity_hold script.trusted: repo-relative path glob + content hash; a script run by path that matches an entry on both is not matched under load) with its state (trusted, changed, missing), found from the repo root of the current directory, and the hash of any path given. The list is never refreshed by itself: paste the printed hashes into engine/defaults/dispatch.toml, then run ah-regen to regenerate the pristine bundle and SHA manifest. |
ah-engine dispatch-report [--json] |
yes | The port of ah-hook dispatch-report (L03): effectiveness metrics of the parallel-dispatch demand (shown, followed, ignored, compliance, idle-neglect blocks), the Jev dispatch tier (verdicts, follow rate, accuracy proxies) and the coordinator-work window (nudges, blocks, work share per plugin version), from dispatch-demand-metrics.json, coordinator-work-metrics.json and the live session files; summaries and text are in engine/logic/rules/operator-cli.js. |
ah-engine finding-dedup [--file <findings.json>] |
yes | The port of ah-hook finding-dedup (L03): the advisory duplicate-finding detector of the deadly-loop trio. It reads a JSON array of findings (stdin or --file), asks Jev (findingDedup, trust advisory, four pairs at a time, at most 200) whether candidate pairs describe the same root cause and prints {"groups":[...]} on stdout and one possible duplicates line per confirmed pair on stderr. It never collapses anything; with Jev off, unkeyed or the integration off it prints no groups. The pairing and grouping rules are engine/logic/rules/operator-cli.js. |
ah-engine coordinator-work-baseline <transcript.jsonl> [--from-line <n>] [--cwd <dir>] [--json] |
yes | The port of ah-hook coordinator-work-baseline (L03): replays a transcript's main-thread Bash calls through the coordinator-work classifier and window and prints calls, work, the share as recorded and with enforcement, and the would-nudge and would-block counts. The replay is the plugin script engine/logic/rules/coordinator-work-baseline.js (built on command.js and coordinator-work-guard.js through script.includes); a command whose class only the hook process could tell is counted as not work and said once on stderr. |
ah-engine jev-report [--json] [--days N] [--window 24h\|7d] [--by project\|session] [--project <name>] [--weekly] [--since <iso>] [--until <iso>] [--exclude-window <iso>..<iso>] [--exclude-project <name>], jev-report label <hash> [tp\|fp], jev-report prune-audit --days N |
no | The port of ah-hook jev-report (the Jev report of the /anti-hall:jev skill), byte-for-byte: the command reads the decision, triage, judge and supervision logs (every retained generation), the daily rollups, the human labels, jev.json, the budget settings and the cached Vercel credit balance, and the plugin script engine/logic/rules/jev-report.js aggregates and renders the text or --json report (KEEP / REVIEW / REMOVE verdicts included); an integration whose every call in the window ran with mode off reads OFF (Jev was never asked, so there is nothing to judge), one with no regex comparison, no outcome rows, no labels and no changed decision reads REVIEW (no outcome signal: ...) instead of needs labels, --window 24h|7d narrows the whole report (a --since of now minus that many days unless --since is given), and a failed calls by kind section lists each integration's failed calls by reason (timeout, no-key, circuit-open, http-<status>); label and prune-audit are the two forms that write the Jev logs, the report itself only refreshes the credit cache and the once-a-day low-credit latch. Every threshold, list and word is jev_report.toml; a run it cannot reproduce exits 75 and writes nothing, so the command prints why and changes nothing. |
ah-engine statusline |
no | The port of statusline/statusline.js and its renderers (L9a): reads the session JSON on stdin, prints the two lines; runs from the statusLine setting through the thin client (ah-hook statusline); no Node statusline runs (see install-statusline and the migrate-statusline-engine step). Sampled shadow against Node, off the hot path (ops.shadow_rate_statusline, per thousand). |
ah-engine phase <set\|advance\|step\|agents\|update\|clear> [args] |
no | The port of statusline/phase.js (L9a), byte-for-byte: writes the phase state (~/.anti-hall/phase-state.json) the status line's phase bar shows. Fails open like the script; a state that is not a JSON object, or update with a numeric key or __proto__, is left to Node (exit 75, nothing written). Replayed by Node in a scratch home (ops.shadow_rate_phase). |
ah-engine afk on\|off\|status |
status only |
AFK mode, machine-wide (GH #425): writes the flag file ~/.anti-hall/afk.json the afk-mode check reads (on = manual AFK until back/off), under the flag lock: when another hook holds it past afk.cli_lock_wait_ms nothing is written and the command exits 1. The afk_entered count is left in the flag for the next hook to add (this process is not the daemon). |
ah-engine back |
no | Ends AFK mode and prints each session's digest: the checklist bullets after the AFK marker in its progress file (sessions of this AFK period, afk.digest_max_files), with the percentage of [x] bullets; rendered by the plugin script (afkDigest in afk-mode.js), so it matches the typed back. |
ah-engine install-statusline |
no | Retired no-op kept for old invocations: prints that anti-hall no longer writes a command-backed statusLine and exits 0. |
ah-engine uninstall-statusline [--user\|--project] [--purge-base] |
no | The port of ah-hook uninstall-statusline (L9a): restores the saved original statusLine, else the settings backup, else removes the key; the shared base is kept unless --purge-base. Same safeties and shadow as the installer (ops.shadow_rate_uninstall). |
ah-engine shadow-compare <dir> |
no | Internal: the detached half of a Node shadow; runs the Node version on a scratch home and logs a mismatch. |
ah-engine backup [--to <dir>] |
no | A consistent, scrubbed snapshot of hot.db and archive.db; prints its manifest. |
ah-engine restore <snapshot-dir> |
no | Keep the current state as a pre-restore snapshot, stop the daemon, swap in the snapshot. |
ah-engine config [--json] |
yes | The effective config with the source of every value (default, config_toml, settings, env), the files read, the active version, any rejected edit and settings pending a restart. Asks the running daemon, else reads the files. |
ah-engine config explain <key \| rule:<id>> [--cwd <dir>] [--json] |
yes | Where an effective value comes from: for a setting, every layer (env, project, settings, config_toml, default) with its value and whether it is applied, shadowed by a higher layer or refused; for rule:<id>, the rule as it stands after the shipped, user and project layers and the refusals that name it. Reads the files; the project layer is the one of --cwd (default: the current directory). |
ah-engine config validate <file> |
yes | Check an engine TOML file against the schema: exit 0 when valid, 1 with the reason when not. |
ah-engine config heal |
no | Add the settings the edited engine files lack, taken from the pristine copy (existing text kept, the file backed up first, idempotent). The automatic heal skips a version-controlled checkout; this command does not. |
ah-engine config versions, config rollback, config export |
no | planned (D18, they need the config database); they say so and exit 64. |
ah-engine agents status\|tick [--json] |
no | The agent tracker: status lists every tracked agent (tokens, cache, tool calls, progress, last output, state, flags) with today's reminder and recovery totals and never changes anything; tick runs one tracker tick now. See The agent tracker. |
ah-engine schedule list\|run <job>\|history |
no | The scheduler's jobs with their next run and last result; run one now; the run history. |
ah-engine mesh <roster\|unread\|read\|dump> --db <devswarm.db> [--id <ws>] [--since <n>] [--last <n>] |
yes | Read a repo's DevSwarm store in place, read-only (D45 stage S0): the registered workspaces, the per-workspace counts, a workspace's messages (capped, with a resume position), and the full canonical dump the parity harness compares with Node's reader. Refuses a journal-backed store; never creates or writes one. |
ah-engine devswarm <status\|line\|supervisor\|recover\|advisory\|archive\|plan-prune\|prune\|help\|skip\|archive-ignore\|archive-unignore\|gate-intent\|notice\|plan\|scope\|gate\|workspaces\|logs\|wake-directive\|ready-check\|app-state\|app-sync\|done\|primary\|relay\|archive-request\|nudge\|supervision-report\|sync-ui\|retention\|unarchive\|migrate-owner-keys\|ensure\|register\|correct\|reap-orphans\|wake-watch\|register-primary\|diagnose\|healthcheck\|merge\|spawn\|respawn\|reconcile-registry\|reap-stale\|reconcile-active\|auto-archive> |
no | The DevSwarm realtime state and owner actions (lane dswire; supervisor prints who owns the supervisor duties and recover --id <ws> --request <id> kills and resumes one session on demand, lane l7: see the devswarm entry of the generated reference)), and the store-free ah-hook mesh verbs (lane l8: help [<verb>] and <verb> --help, skip <guard> [--ttl <min>], archive-ignore <id>, archive-unignore <id>, gate-intent --reason <text>, notice --list, plan set|show <id>, scope add <id>, gate <id> --set/--clear (every gate but merged), workspaces list, logs, wake-directive <id> (child workspaces); lane l8b: ready-check <sha> (bounded git probes), app-state [--json] and app-sync [--dry-run] (the engine's app sync; a write needs Node's dry run to name the same markers first, a marker retirement is Node's); lane l8c (src/meshw/actverbs.rs, reportverbs.rs, dssup/retention/cli.rs): done [<id>] [--summary] (gate row with the head, plan close and its supervision event, one report to the Primary), primary outside the Primary checkout, relay <seq> --to <id>, archive-request <id> (a target with no descriptor or a fresh heartbeat), nudge <id> (the refusal for an unregistered id), supervision-report [--days n] [--json], sync-ui --titles-json <file> (the dry run) and retention status|run (run --dry-run, and run on one store only after Node's read-only planner agrees on every row; restore and several stores are Node's) - lane l8h (src/meshw/lifeverbs.rs): unarchive <id> (the restore of the reconcile port's op list under the workspace lock; a registry row at another worktree or an unreadable descriptor is Node's), migrate-owner-keys (the ownerKey backfill over active and archived descriptors; the re-home of a descriptor stranded in the hash bucket is Node's), ensure <id> and register <id> --worktree --session (an idempotent ensure of a descriptor of this project, a new or updated registration in the cwd's project with the registry row and reader declare; every refusal, the re-home, an archived twin, a second registry row of the worktree and a store that does not exist yet are Node's), correct <id> [--dry-run] (the correction text from the plan and the stray state, the send through the native send, warned_* on the plan and the correction event) and reap-orphans (no project, every refusal of the apply path and a project with no orphaned partition; a partition with unread mail and no reader, and any retirement, are Node's); register-primary (the Primary's own registration with the child-builder and live-holder refusals), diagnose and healthcheck (the mesh-health projection with split classification; a project with an orphan partition is Node's) and, through ah-engine mesh archive <id>, archive (the local archive and the app leg with Node's retry; Node's witness is not run for it); lane dsB (src/meshw/dsbverbs.rs, the capability gate and bounded call of hivecontrol.rs): merge [<args>] (the hivecontrol workspace check-merge and merge-into-source <args> pass-through with Node's argument vector, working directory and error text, and the mesh broadcast of the outcome; it has no Node witness, which would merge a second time), reconcile-registry (one workspace list all read and the drift report), reap-stale [--yes] and reconcile-active --active <ids> [--yes] (the dry runs, and a confirmed run with nothing to archive; archiving is the archive verb's app leg, so a run that would archive is Node's), auto-archive (the plan when the app database is absent), spawn <branch> (the usage and create-option refusals; the create itself - source-freshness fetch, launch poll, title follow-up, wake coverage - is Node's) and respawn <id> (the usage refusal and the refusal of a caller outside the Primary checkout); migrate stays Node's - the central-log refusals listed under Mesh verbs (lane l8d) are answered and logged by the engine, every other case it cannot prove stays Node's before anything is written; same arguments, same stdout and files as Node, --json kept in place, role matrix devswarm_wire.role_matrix: help open to every role, the others main session only; mesh.engine_writes off sends them to Node, on makes the engine answer and defer the cases it cannot reproduce, notice --post and unreadable state included; the launcher routes the same verbs to ah-engine mesh, and a background Node witness logs a match or mismatch per answered call to mesh-verify.jsonl): status / line print the live workspace state and its statusline segment, advisory --session <id> the changes that session has not seen, archive --id <ws> --request <id>, plan-prune --older-than <days> and prune --confirm-ids <ids> --plan <nonce> run the hivecontrol actions at the owner's request with Node's preconditions, ledger and confirmations. Role matrix (devswarm_wire.role_matrix): reads are open to every role, the acting verbs are for the main session only (a subagent, a Codex session or a workspace child gets exit 64 before anything is read). create is NOT PORTED: it fails with a stderr line naming ah-hook mesh and exit 69 (devswarm_wire.not_ported_exit), nothing done; merge is ported (the hivecontrol pass-through above). wake-watch [--auto] is the idle-wake Monitor (monitors/monitors.json runs the engine directly): the port of devswarm-wake-watch with the same stdout lines, stderr diagnostics, lock, cursor file and exit codes (tests/it/wake_watch_parity.rs compares the two). It runs until the session ends, on the realtime watch layer plus Node's poll tick (devswarm.wakeWatchPollMs), roles main session and workspace child (devswarm_wire.role_matrix), and answers exit 75 before printing or writing anything when only Node can decide: a Primary with no live child (Node prints its one idle line), a checkout nested in another one, a settings file the engine cannot parse as JavaScript does, or an idle-skip that depends on the supervisor's active-list cache. All its text and numbers are in wake_watch.toml. |
ah-engine mesh <ah-hook mesh argv> |
no | D45 stage 2: the same argv as ah-hook mesh. mesh.engine_writes off (default): Node runs it. shadow: Node runs it, the engine replays it on a copy of the store and logs the comparison to mesh-shadow.jsonl in the state directory. on: the engine answers send, mesh read, mesh history, roster --ack, inbox ack-primary, the plain heartbeat, inbox tick <id> (line and JSON form), the single-partition inbox read-primary and plain roster for a project with no rows itself (store write, lock and summary refresh) where it reproduces Node exactly and hands the rest to Node before writing anything; a failure after its own write exits 70 without rerunning Node (exit-code contract and per-verb telemetry: see Mesh verbs below). Off again: {"mesh":{"engine_writes":"off"}} in ~/.anti-hall/settings.json. |
ah-engine handovers <index\|check\|search> [query] [--project <dir>] [--registered] [--force] [--limit <n>] |
no | The handover brief tree under .anti-hall/handovers: index rebuilds the root brief and the per-day briefs (BRIEF.md plus a typed BRIEF.json sidecar each: session, seq, title, situation, next action, decisions, owner preferences, files, commits, references, previous and next handover of the session, attached PreCompact snapshots) for the days whose files changed, writing only files whose bytes change; check lists unindexed or stale handovers, missing briefs, malformed handovers and broken references without writing (exit 3 when any); search ranks entries from the sidecars (words must all match; date:, from:, to:, session:, kind:, file:, commit:, decision:, pref: filters). Never edits a handover file and never deletes; the logic is the plugin script handover-hygiene.js, every rule and text a handovers.* setting. |
Replacing the Node operator scripts (cutover notes)¶
These are the notes for the cutover lane; no SKILL.md or script text has been changed yet.
| Node today | Engine command | Notes for the cutover |
|---|---|---|
ah-hook update [--check] |
ah-engine update [--check] |
Same JSON status line, human summary and exit codes (1 only for the two STOPs). Progress lines on stderr are printed for the stages the engine runs itself (the harness registration). The stages that do real work (the DevSwarm store sweeps, the migrations) still need update.js in the pulled plugin tree and node on the PATH; without them such a stage reports attempted: false and why, and the stages the engine answers itself (closed gate, already done, deferred) need neither. |
ah-hook doctor [--repair] |
ah-engine doctor [--repair] |
Ported earlier; see the doctor row above for the flags still on Node. |
nodeah-hook migrate`` |
ah-engine migrate |
Ported earlier. |
ah-hook capability-scan |
ah-engine capability-scan |
Ported earlier. |
(old Node install-codex) |
ah-engine install-codex [--global] [--dry-run] [--root <plugin dir>] |
Same output and files. The plugin directory comes from --root or the plugin-root variable (Node derives it from its own location). The test-only refusal to write outside a temp dir is not carried over (the engine does not run under node --test). |
Shadow: update --check and update no longer start the Node script, and install-codex is engine-only (v1.0 lane L16): the Node install-codex.js remains only as the witness of the parity test (tests/it/update_parity.rs) until the decommission gate.
Codex helper scripts as verbs (lane L16). ah-engine codex-limit-status prints isConserving() as JSON (the limit-conservation decision of limit-conserve-inject: the limitConserve.mode setting, else the OMC usage cache with the threshold, reset-aware and snapshot-age rules and the account-switch guard) and ah-engine codex-activate writes the advisory ~/.anti-hall/codex-activated.json marker; they replace the old Codex helper scripts. The logic is the plugin script engine/logic/rules/codex-scripts.js; the keys are in codex_scripts.toml (and the ctxbudget.* keys it shares with the hook). tests/it/codex_scripts_parity.rs runs the Node script and the verb on identical scratch homes and compares them.
Codex replay (lane L16). ah-engine/parity/codex-replay/codex_replay.py records a Codex payload corpus (real Codex shell commands, apply_patch inputs and spawn_agent calls from the local Codex rollouts, read only; the Claude replay sample and the recorded guard goldens mapped to the Codex shape: patch text in tool_input.command, turn_id, model) and replays it two ways: run node runs every row of ah-fallback.codex.list (in plugins/anti-hall-node/hooks) as the host does, run engine runs ah-engine hook --host codex with the Node fallback disabled (a fallback row only records its id). compare classifies each call (identical, text-only, stricter, advisory-dropped, WEAKER, deferred) and separates a WEAKER call explained by a recorded engine defer row from an unexplained one; unexplained must be 0. Each side gets its own scratch HOME and sandbox, the DevSwarm variables are removed unless --keep-devswarm, and the engine daemon of the run is stopped at the end. The corpus itself stays local (it holds the owner's commands). edit-guard now answers a Codex apply_patch itself (launcher-directory deny over every Add/Update/Delete/Move path, non-main-thread allow); a main-thread patch and a malformed one still defer to Node. tests/it/codex_apply_patch_e2e.rs compares both guards with the Node hooks on identical scratch homes.
Two documented differences from update.js: when an update moves the version, Node runs its post-pull stages twice (the old
copy, then the new copy) and prints the second pass, which reports the one-time migrations as already completed; the engine
runs them once and prints that run. And the text of an operating-system error inside a status line (for example a failed
cache copy) is Rust's, not Node's.
Metrics and the impact ledger¶
Metrics are counters, gauges and latency histograms kept in memory and bounded. Latency percentiles are reported as
the upper bound of the histogram bucket that holds that rank, so they are upper estimates. The registered names are:
requests, busy_replies, errors, budget_trips, budget_soft (requests past the soft CPU budget daemon.eval_soft_us: logged, still served), panics, rejected_peers, accept_errors (accepts that failed with EMFILE and the like, by OS error code), slow_replies (replies finished after their client's deadline: slow but healthy), deadline_soft (requests answered after the client's fail-fast wait but inside the hard deadline: warned about only), dswire_full_sweeps (full DevSwarm action sweeps: every workspace's facts read, plus the mistake scan and the nag pass), client_gone_skipped (checks not run because the client had already closed its connection), wake_watch_rebin (wake-watch restart lines sent to the engine log instead of the Monitor stream, by line), qos_threads (request threads that asked for the daemon.qos class, by outcome: set, off, refused), script_soft (script calls past their soft CPU limit script.time_limit_ms: warned about, not cut), script_limit_trips (by kind: soft unloaded the least recently called checks down to the low-water mark, hard recycled the interpreter; both stay at zero when the limit is sized to the working set), script_unloads (checks unloaded by that limit), script_reloads (checks rebuilt after an unload: the cost of a limit set under the working set), script_module_loads (shared includes compiled), jev_slow (Jev calls slower than jev.soft_ms: the answer was still used), hook_calls, hook_latency_us, dispatch_checks,
check_calls, check_decisions, check_latency_us, check_latency_by_size_us and check_bytes_read (both by check and by the size class of the transcript the request named, load.size_labels), dispatch_overhead_us (the part of a dispatched request no check accounts for), agent_scan_kept and agent_scan_kept_miss (kept-walk hit or miss and why), transcript_line_skipped_oversize (by reader: transcript lines longer than agent_scan.max_line_bytes, 4 MiB, that the agent scan read past without holding or parsing; a line over the bound is not parsed, so the scan is unknown rather than complete, and agent_scan.max_line_bytes = 0 turns the bound off), transcript_scan_peak_bytes (byte histogram by check: the most one call held for transcript reads, a block of transcript.read_block_bytes plus the one line being assembled, whatever the window; every transcript window is read in blocks by transcript::scan), transcript_scan_waits and transcript_scan_turn_bypassed (requests that waited for their turn at reading a window, and those that got none before their deadline and read anyway, without a turn: the turn bounds concurrency and never changes an answer; at most transcript.max_concurrent_scans windows are read at once), agent_scan_degraded (by reader: scans returned unknown because the window held such a line; callers take their unsure path and the silent-agent nudge does not block a Stop on it; any oversize line degrades the scan, noise or not, because the skipped line may have carried a completion), evidence_cache and evidence_cache_rebuild (transcript evidence read from the kept lines or afresh, and why), evidence_walk (evidence walks the memory registry refused to keep, so the check deferred), tasks_cache and tasks_cache_rebuild (the task lines of a transcript read from the kept ones or afresh, and why), taskstate_memo (a task reconstruction another Stop check had already built for this state of the file: hit, miss or off), check_cpu_us (CPU spent inside each check) and event_check_cpu_us (the same by hook event; status --json shows cpu_us_total and cpu_us_per_call per check under phases.checks and a cpu block with by_event calls and CPU plus the telemetry.top_checks costliest checks), check_mem_peak_bytes and check_mem_alloc_bytes (byte histograms: the most one call of a check grew the heap by, and the bytes it allocated; the worst call is the histogram max) burst_dumps_written and burst_dumps_suppressed (burst allocation-site dumps written to files.burst_dumps_dir, and bursts that got none because of diagnostics.burst_dump_max_per_hour; the profile is diagnostics.burst_profile, trigger diagnostics.burst_dump_mb within diagnostics.burst_window_ms; query checks rows carry peak_heap_max_bytes, peak_heap_p95_bytes and alloc_max_bytes per check), regex_scratch_trims, regex_scratch_trim_freed_bytes and regex_compiles_latched (the ah.re.* cache: patterns whose lazy-DFA scratch a memory shrink or recycle dropped instead of evicting them (mem.regex_trim_scratch), the weight they stopped reporting, and patterns compiled while the process was over its global hard limit, which mem.regex_latched_bytes keeps to one per pattern per excursion), and check_mem_retained_bytes (bytes the check's calls kept), all from diagnostics.check_mem and shown per check under phases.checks in status --json and as a check_mem array of [check, peak, alloc] on each memory-log line, rule_hits, rss_kb, queue_depth, uptime_s, and for the
memory layer tier_items, tier_bytes, tier_hits, tier_misses, tier_evictions, tier_expired, bus_published
and bus_dropped, for the writer db_commits and db_writes (fewer commits than writes means group commit is sharing syncs), and for
the spool spool_applied and spool_quarantined, for the scheduler schedule_runs and schedule_missed, and for
size control db_hot_bytes, db_hot_wal_bytes,
db_archive_bytes, db_archive_wal_bytes, maintain_runs and maintain_last_ms, for a settings number outside the f64 range (1e400; it invalidates only its own key, #569) settings_value_invalid, and for the Jev lane jev_calls, jev_verdicts, jev_cost_micro_usd, jev_timeouts, jev_cooldowns, jev_changed, jev_latency_us and, per integration, the Stop gate's jev_asked_sync, jev_skipped_unflagged and jev_gate_timeouts, and for the injection gate inject_emitted, inject_emitted_bytes, inject_keepalive, inject_suppressed, inject_suppressed_bytes (by cut) and the memory gauges inject_gate_sessions, inject_gate_slots, inject_gate_bytes and inject_gate_evictions, and for the ack protocol and fail-opens (see below) hook_phase_us, wire_events, launcher_counter and fail_open.
Transcript store metrics (the per-session fact store, transcript.* settings): counters transcript_store_cold_builds, transcript_store_cold_bytes, transcript_store_refresh_bytes and transcript_store_appended_bytes (parsed over appended is 1.0 when every byte is parsed once), transcript_store_partial (questions answered unsure), transcript_store_waits and transcript_store_wait_timeouts (single flight), transcript_store_oversize_lines, transcript_store_evictions, transcript_store_rebuilds, transcript_store_snapshot_loads, transcript_store_snapshot_misses, transcript_store_snapshot_writes and transcript_store_snapshot_skipped; gauges transcript_store_bytes, transcript_store_sessions and transcript_read_buf_max_bytes (the most memory any reader held at once). heap_burst_total counts rises of the live heap by more than mem_gate.burst_bytes within mem_gate.burst_window_ms. The memory gate (scripts/mem-gate.sh, tests/mem_gate.rs) bounds them with the mem_gate.* settings.
Impact events record what the engine did to a call: block, advisory, warning, context and fallback. They
are stored in hot.db with exact per-combination totals, so counts survive a restart; the project is only ever a short
hash, never a path.
Savings are estimates, never measurements. A model-routing saving is the actual tokens the routed agent used times the price difference between the model it asked for and the model selected, assuming the original model would have used the same tokens. The method text is printed next to every figure, prices come from a configured price table that carries its own date and source, and no figure is shown while no routing event has been recorded (planned, D52). A measured benchmark, when one exists, is shown next to the estimate with its task set, model and date. None is registered yet.
Metrics are counted in memory. Every telemetry.snapshot_ms (default a minute) and when the daemon exits, the counters
and histograms are snapshotted into hot.db, and the same snapshot is rolled up into archive.db per resolution
(telemetry.rollups: per minute kept 24 h, per hour kept 30 days; pruned by ah-engine maintain). A new daemon starts
from the last snapshot, so counts survive a restart; after a crash they lose at most what came after the last snapshot.
Gauges are live readings and are not kept. ah-engine metrics --rollup minute --since 3600 lists the stored rollups.
mesh_pull_ts_fallback counts pulled DevSwarm batches holding a message whose time is a form Date.parse accepts but the engine does not reproduce: the store row then carries the import time (the message and its hash are intact) and the batch closes in the same tick.
Recorder runs made after the reply (defaults file recorders.toml): recorder_async_count counts each such run, by event and check; recorder_async_dropped counts runs not made or whose output was dropped, by event and reason (inline_full, undelivered, said); recorder_async_us is the wall time of one such run by check (the time the hook no longer waits for); the gauge recorder_queue_depth is the runs waiting or running in the whole daemon when status or metrics is read.
Ack protocol and phase telemetry (GitHub #199, #201; defaults file wire.toml). A hook client that finds the daemon's announcement
(wire.caps_file) opts a request in by adding its body length to the head line's version suffix (V <ver>-w1.<n>; a daemon that predates
the protocol ignores everything after the first -, and a client that finds no announcement uses the original exchange, so both directions
stay compatible). The daemon answers AHK1 REQ the moment the request is read and parsed, then the reply frame; the client answers
AHK1 RES after the verdict is handed to the host, carrying its own timings (connect, request to ACK, ACK to response) and the launcher's
counters (launcher.stats_env). No ACK(req) within wire.ack_timeout_ms means the daemon has not started on the request: the client
closes the connection and resends once (a daemon that finds the client gone when it writes ACK(req) judges nothing, so the resend is the
only judging); an acked request is never resent. A reply with no ACK(res) within wire.res_wait_ms is an undelivered_verdict fail-open.
status --json shows phases (per event: connect, req_ack, ack_response, delivery, queue_wait, judge, launcher_startup, each
with count, p50, p95 and max; per-check time under checks), wire (acked, delivered, retries, abandoned, ack timeouts) and fail_open.
hook_phase_us holds the phase histograms, wire_events the protocol counts and launcher_counter the launcher's counters by name.
Engine fail-opens (GitHub #201; fail_open.* in wire.toml). Every time the engine answers without a check's verdict for a reason that is
its own (missing config key, deadline cut, script timeout, Jev breaker open, busy, internal error, undelivered verdict) it counts
fail_open{reason,check}, writes one health-log line and, to an ack-mode client, sends the reason and check in the reply. More than
fail_open.soft_per_window of them in fail_open.window_s seconds makes status report degraded and the doctor warn (past
fail_open.hard_per_window it fails); a one-line notice tells the session. The engine never blocks a session because of it.
Mesh verbs: the exit-code contract and per-verb telemetry (D45 stage 2)¶
Exit codes of ah-engine mesh <ah-hook mesh argv> (mesh_write.exit_unable, mesh_write.exit_committed_failure):
| Code | Meaning | Caller does |
|---|---|---|
| the verb's own | the engine answered (or Node did, after a deferral); the code is the verb's result | passes it through |
| 69 | UNABLE OR SWITCHED OFF, NOTHING WRITTEN: the engine cannot do this verb or case (or mesh.engine_writes is off); a stderr line names the site and the manual command |
reports it; the failure is visible, never a silent hand-off (this was exit 75 before) |
| 70 | the engine WROTE and then failed (a panic, or a late deferral that is a bug) | reports it; never runs Node: running the verb again would write twice |
An inability is always decided before the first store write. 69 is never returned after a write: that is 70, a different code on purpose, because running the verb again after a write would write twice. The decision is
one pure function (meshw::next_step) unit-tested for every combination; tests/mesh_ack_parity.rs proves, for every deferral case of
inbox ack-primary, that an engine that cannot run Node exits 75, prints nothing, and leaves the store and the home tree byte-identical.
Telemetry per verb. Each on-mode call appends one JSON line to mesh-shadow.jsonl in the state directory:
{"ts", "verb", "mode", "result", "reason", "ms"}, with verb one of Send, MeshRead (also roster --ack), MeshHistory, InboxAckPrimary, Heartbeat, InboxTick, InboxReadPrimary, Roster and result:
result |
counts as | reason |
|---|---|---|
native |
a call the engine answered | empty |
defer |
a deferral (Node ran it) | the deferral case, e.g. receipt-reader, cursor-import, not-owner, lock-busy |
panic |
an engine error before any write (Node ran it) | empty |
committed-failure |
an error after the first write (exit 70) | the late deferral, or empty for a panic |
ms is the engine's own time for the attempt (it excludes Node's run after a deferral). Per verb: calls = lines, defers = defer lines, errors =
panic plus committed-failure lines, latency = ms. For example
jq -s 'group_by(.verb)[] | {verb: .[0].verb, calls: length, defers: map(select(.result=="defer"))|length, errors: map(select(.result=="panic" or .result=="committed-failure"))|length, p50_ms: (map(.ms)|sort|.[length/2|floor])}' mesh-shadow.jsonl.
Group defer lines by reason to see which unported case to port next.
heartbeat (plain form) and the unread union. ah-engine mesh heartbeat <id> --session S [--progress N --phase T --wip T --blockers T]
writes heartbeats/<id>.json and refreshes liveness/<id>.json to alive with pending, notDraining and oldestUnreadAgeMs from the
NDJSON-inbox + store-partition union (src/meshw/union.rs: Node's unionUnread, deduplicated by _h, the legacy line hash and, last, by
body; read bases from the partition's reader_cursors floor rows). Besides the heartbeat and verdict files it writes what the call asks for (below). It defers (before
writing anything; nothing is lost) when the call has no --session (Node would log the caller process), is
a primary-<hash> label, is a child addressing another id (Node warns on stderr), is a Primary checkout whose anchor session Node would
refresh, meets a partition without #floor rows (cursor-import),
a journal or unmarked store (journal-backend, store-backend), a store file it cannot open, a cursor file whose line is not a scalar,
or an inbox line whose _h is not a string, number or boolean, or an app database value it cannot convert like JavaScript (see below), or one of the write-side cases below.
--step for a workspace WITHOUT a plan is answered natively ("plan":{"ok":false,"reason":"no-plan","hint":...}, exactly Node's text). Telemetry: Heartbeat lines; the reason of a defer line is one of those
names.
Heartbeat write side: --summary and a step plan (src/meshw/plan.rs, Node: devswarm-lib/heartbeat-plan.js, devswarm-plan,
devswarm-supervision-metrics.js). --summary TEXT appends a heartbeat broadcast row (is_heartbeat = 1, sender = the id, urgency mesh_write.hb_urgency_default)
to the project's shared store and refreshes the summary projection, in Node's order (heartbeat record, verdict, row, summary, plan), after the ownership check
(the caller is the id, or owns it by its registry row, or by the identity family: cross-linked rows, the row's session, a placeholder). --step N [--status S],
and a --summary for a workspace that has a plan, update the plan file read-modify-write under its lock (<key>.json.lock, 5 s wait, 30 s stale, dead holder taken over at once),
as an ordered JSON value so every key the supervisor keeps survives in place, and append the supervision events (step, correction-followed, respawn-progress) to
logs/devswarm-supervision.ndjson. A busy lock answers lock-busy and a bad step bad-step (exit 2), exactly as Node. Defers, before any write: a refused or first-claim
ownership (Node drops the summary and writes an attempt record), an archived workspace, no project, a bad --urgency (Node logs these through the verb-outcome log), a
plan whose steps are not objects or whose file is not UTF-8, a respawn that is an array, a non-ASCII summary for a workspace WITH a plan (JavaScript's UTF-16 slicing
and lowercase tables), a devswarm.stepStallMin set anywhere (env, settings, plugin option) when a correction is being matched, and a supervision log past 1 MB (rotation stays
Node's). A failure after the heartbeat record was written (a store another process holds past the busy timeout, a plan write error) exits 70 and Node is never run. The Node
check copies the store with SQLite's online backup (never a link) and compares stdout, the heartbeat, verdict and cache files, the plan, the log lines, the summary projection and the
appended row (without the process-ancestry nonce); mesh-verify.jsonl lines carry diff and a detail window of the first difference.
The DevSwarm app database reader (src/meshw/appdb.rs, Node: devswarm-app-db). A heartbeat for a workspace with a
descriptor asks whether the app reports the workspace archived (builders.isActive = 0 AND isHidden = 1; without an isHidden column, isActive = 0;
by id first, else by worktree: an active builder there means not archived, only archived twins mean archived). Archived: the verdict is NOT cleared to alive
and the answer carries "appArchived":true; the heartbeat record is still written. The reader opens the file read only and never waits for a lock
(mesh_write.app_busy_timeout_ms, Node's node:sqlite does not either), so a missing, empty, non-SQLite, truncated, exclusively locked or
schema-less database is "no opinion" exactly as in Node, and any read that fails in builder_terminals, pull_requests or repositories makes the whole
snapshot null, as in Node. It keeps Node's cross-invocation cache <devswarm root>/cache/app-archived.json (30 s, keyed by the database's mtime, size and -wal file's,
integer-like ids come first in the file, as OVal serialises them like JavaScript); the cache write happens after the heartbeat record. Defers (before any write): a relative worktreePath (resolved against the cwd by
Node), a text or blob value in id/isActive/isHidden/builderType/worktreePath (JavaScript converts them in ways the engine does not copy), an integer beyond 2^53, a cache
file whose states or an entry has the wrong shape. Keys: mesh_write.app_*.
Node stays as a background check. In on mode every answered heartbeat is verified: before the engine writes, the parts of the DevSwarm
root a heartbeat touches are copied into a scratch home (the store is linked, read only; the plan and app-cache directories are copied); after it answers, a detached copy of the engine
(ah-engine mesh --shadow-verify ...) runs the real ah-hook mesh there with the engine's clock (and the real app database, read only) and compares Node's stdout and the heartbeat,
verdict and app-cache files it wrote with the engine's. Node's write never runs twice on the real home. One line per call goes to mesh-verify.jsonl in
the state directory: {"ts","verb","result","ms"} with result match, mismatch (plus both outputs, capped, and sameHeartbeat/sameVerdict/sameCache) or error (Node could not run);
count mismatches per verb before trusting a port. Keys: mesh_write.verify_*.
inbox tick <id> [--quiet] [--json] (src/meshw/tick.rs; Node: cmdInboxTick, inboxTickQuietLine, the count it runs). A tick counts the unread mail of the
workspace (the same NDJSON + store union as the heartbeat, read at the caller's own reader_cursors rows when the caller is a declared
reader, else at the floor), refreshes three records and prints one line (--quiet), or count's JSON with action renamed, idMismatch and
watcherArmed (no flag, or --json). Writes, all best effort as in Node: wake-tick/<id>.json (ts,
unreadTotal, meshGapWithheld, known, the carried-over seq), the heartbeat refresh (ts, state_ts, version of the existing
heartbeats/<id>.json, or a minimal inbox-tick record) and, when it found unread mail and a wake-watch lock exists, a line of
cron-found-mail.jsonl (kept to mesh_write.cron_found_mail_cap). The engine answers the steady state only: a descriptor with an inbox and
cursor file, one store partition (a second registry row of the same worktree is a mesh group that Node folds: defers), floor rows in place, a
live wake-watch lock (fresh within mesh_write.wake_lock_stale_ms, its pid not provably gone) so watcherArmed is true, no delivery-log
batch pending, spilled or left in the temp directory, and no trace of the devswarm.tickRosterEvery setting. An UNKNOWN count (the inbox or
its cursor file does not read) is answered in the line form: the union is then the store alone, known is false in the marker and the
line, and the known:false warning goes to stderr as Node prints it; the JSON form of an unknown count defers (its cursor and total
fields come from a second read of the broken files). Everything else defers before the first write: --child (it first imports the
native queue), an unarmed watcher (the idle, archived and limit skips and the re-arm cue stay in Node), a Primary whose anchor session
Node would refresh, a child addressing another id, a JSON form with more unread store rows than one call returns. Telemetry: InboxTick
lines. The background Node check (mesh-verify.jsonl) re-runs the real tick on a scratch copy of the DevSwarm root (store linked) with the
engine's clock and reader nonce and compares its output (the scratch home swapped for the real one), its refreshed heartbeat, its wake-tick
marker and its cron-found-mail file with the engine's. One difference from Node: Node opens the
store read-write (and would apply a pending schema migration); the engine opens it read only, so the migration waits for the next Node writer.
Is a watcher live? (src/meshw/watcher.rs; Node: watcherLockLive / watcherLiveForWorkspace in devswarm-wake-watch.js). One check answers inbox tick's watcherArmed (plain and --child) and the agent tracker's wake-path signal: the lock under the workspace's own id is fresh (mesh_write.wake_lock_stale_ms) with a pid not provably gone, or another registered row whose checkout is the same directory (resolved and real path) holds such a lock. The second case is a Monitor armed under the DevSwarm app's own row id for the workspace's checkout; it is counted in mesh_watcher_matched_by_checkout. An unreadable lock is not live.
Inbox advisories speak on change (GH #709; devswarm-child-turn.js, devswarm-parent-inbox.js, helper dwUnreadDecide in devswarm-child-role.js). The devswarm-child-inbox advisory of a child workspace and the devswarm-own-inbox advisory of a Primary used to repeat on every prompt while the same mail sat unread. Now each speaks when a signature of the unread SET (a child: the unread inbox lines with their ids; a Primary: cursor..total of its own row and of every alias or folded row, plus the questions asked, not the minutes they have waited) differs from the last one spoken in the session, or when devswarm.inboxAdvisoryCooldownMin (default 10) has passed since it. A new unread message always changes the set, so it speaks at once. The records are ONE store ~/.anti-hall/devswarm/unread-seen.json ({sig, at} per session and kind), checked and recorded as one step under its lock, capped at devswarm_prompt.unread_seen_max entries and pruned after devswarm_prompt.unread_seen_ttl_hours; a suppressed turn counts devswarm_inbox_advisory_suppressed (label kind: child, own). Switch devswarm.inboxAdvisoryOnChange (default on); off restores the advisory on every prompt.
The parent gate counts with the same function (GH #384, #419). The DevSwarm parent gate (devswarm-parent-gate.js) used to re-check the Primary's own mailbox as max(countFor, messageCount - own cursor), which counts own-family sends and wake rows that mesh inbox peek-primary leaves out, so a Stop could block on "(2 unread)" while peek showed 0. With devswarm.parentGateSharedCount on (default), the host's own-reader view (src/script/host_mesh.rs own_view / shared_unread) returns the union::unread_for count peek reports, re-checked live even with no own reader row, and the descriptor count drops rows the partition's identity family sent (union_of returns the family). A count the old projection would have raised is counted in devswarm_parent_gate_count_mismatch; blocks in devswarm_parent_gate_fired {kind: block, escalation}; quiet passes and dropped own sends in devswarm_parent_gate_suppressed {reason: escalated_quiet, drain, guard_held, version_stale, own_send}; all also as devswarm_parent_gate advisory counters in status. The escalation and own-unread texts name the next step (run peek-primary; if it shows 0, report the disagreement with defect), and repeat.allowed_keys adds it to the repeated-block hint. The orphaned-mesh warning (devswarm-parent-inbox.js) is shown once per session per set of orphaned ids with devswarm.orphanWarningOnce on (default); a repeat is counted in devswarm_orphans_warning_suppressed, git_blocked, git_push_blocked, git_push_ack_downgraded, git_audit_blocked. With the switch off the host still returns the old unread/total fields and the gate computes max(countFor, messageCount - own) exactly as before (the shared count travels in a separate shared field only the on path reads). A shared count read from a store base past the partition's message count (an impossible floor) is unknown, not a confirmed zero: shared is null, the gate counts unable devswarm-parent-gate:shared_unknown and keeps the count it had (the old projection with an own row, the cached count without one), so it fails toward blocking. A wake row is told apart by provenance, not by its body prefix alone (union::is_wake_row, the MESH_MESSAGE_COUNT_FROM_OTHERS skip): DevSwarm's reactivate-child prompt reaches the store only through the native ingest, which writes no mtype, while every mesh send row carries one, so a child's message that merely starts with agent_tracker.wake_prefix is still counted as mail (PR #428). GH #429 extends the same rule: an inbox-file line is a wake prompt only when its resolved sender is a Primary id or none (union::is_wake_line; it follows devswarm.noiseProvenance too, off = the prefix alone: its readers have no settings handle, so union_unread re-reads the switch from the settings file and the process environment of the engine running the read), a [Primary poke] mirror only with no mtype (store rows, union::is_poke_row, filtered in union_of) or a Primary/none sender (inbox lines, pgNoise); devswarm.noiseProvenance (default on) off restores the text-prefix rule, and lookalikes that count as mail are counted in mesh_noise_lookalike_kept {kind}. A saved store read position past the partition's message count is unknown in count_for, union_of (state: unsure) and shared_unread, never 0 or an empty list, so the gate keeps its cached count; devswarm.unreadPositionGuard (default on) off restores the old read, and each unknown is counted in mesh_unread_position_unknown {site}.
Own sends are not unread (src/meshw/union.rs unread_for / unread_at; Node: reader-cursors.js countFor with excludeFamily). The unread count of tick, read-primary, the roster/summary directUnread and the statusline goes through one helper that leaves out the unread rows the recipient's own identity family sent (recipientFamilyIds: the id plus every row cross-linked by session id; a row has its sender in the store sender column, an NDJSON line in its sender field). The row lists stay whole, so an ack still walks them; only the count drops. Each count that left something out bumps mesh_own_sends_excluded. The roster/summary count each workspace from the least-advanced LIVE reader of its partition, computed at read time (union::live_base_of: the minimum over its non-retired reader rows per namespace; Node reader-cursors.js liveBaseOf), never the stored floor a dead reader can hold back, and fall back to the shared floor only for a partition with no live reader row (mesh_summary_owner_fallback); the statusline still reads the floor. Tick and read-primary read at the caller's reader_cursors rows, and the read-primary unread list leaves out the same own-family mail as its count (history views keep it; the ack still walks it).
Senders of native messages (src/dssup/ingest/import.rs branch_sender / fallback_sender; Node: devswarm-branch-sender.js). A native message names only its branch. Ingest stamps the sender as the one registered workspace checked out under that branch; when the branch names none, a message in a child's partition is the one registered Primary's (as pull already stamps the NDJSON line), and the Primary's own partition or a second Primary stays unattributed (never a guess). inbox read-primary prints from as the NDJSON line's own sender, else its branch, and for a stored row with no sender (written before this) as the DONE: branch's workspace, else the same Primary fallback, at read time only: the store is never rewritten. Each fallback is counted in mesh_sender_fallback (label where: ingest, read) and the ingest ones are logged once per batch (mesh_write.msg_sender_fallback).
One workspace reference, one resolver (src/meshw/actverbs.rs resolve_archive_id / resolve_target_id, src/meshw/send.rs resolve_send_target; Node: resolveArchiveId, resolveTargetId, resolveSendTarget). send --to and every verb that targets another workspace (archive, unarchive, nudge, gate, plan, scope, respawn, correct, archive-ignore/unignore, wake-directive) accept the same forms: an exact id, a mesh label (primary-<hash>), or the unique prefix of a workspace id (the short id the roster prints) over the registry rows and the live descriptors. An exact id outranks a longer id that merely starts with it; several matches refuse and list every candidate; a prefix that only a live descriptor id carries is answered by Node's descriptor-alias step (the engine hands it over). Each resolution is counted in mesh_ref_resolved (label outcome: exact, mesh, prefix, ambiguous, none).
The enabled install (src/install.rs; Node: enabled-install). installed_plugins.json may register several anti-hall@<marketplace> keys; the one enabledPlugins marks true is the install the harness runs, and anti-hall@anti-hall is only the fallback when none is. The update version check and the wake-watch staleness check read that one; the generated stable launchers choose it the same way and log each choice (ah-engine/launcher-choice.log: enabled or fallback).
inbox read-primary <id> [--format text] [--json] [--session S] (src/meshw/readprimary.rs; Node: inbox-cmd.js, inbox-read.js
cmdInboxMessagesInner, cursors.js writeReadReceipt). A read that is not read-only: it files a read receipt, named by a fresh random
id (r + the clock in base 36 + 12 random hex digits), in read-receipts/<id>/ and prints the unread rows with the ackCommand that applies it.
The engine reproduces the single-partition read: the unread store rows after the caller's read base (its own reader_cursors row, else the
floor), merged with the NDJSON inbox lines when the descriptor has one (sorted by ts, a row without one last), the forward marker, the instance
digest, from/text/kind/bodyLength, the --format text rendering, and the receipt record (ops own + nd, hashes, reader, createdAt) so that
inbox ack-primary --receipt (Node's, or the engine's for the own-partition op) accepts it. The parity test checks stdout, exit code, the store and the
whole home tree with the receipt id made equal, then has Node ack both receipts and compares the cursors again. Defers before the receipt is
written (Node then runs the verb): a flag the engine does not read (--ack-as-owner, --legacy-ack-now, --unread, --with-broadcasts,
another --format), a missing descriptor, an unclaimed: marker the engine cannot take off (no --session and no CLAUDE_CODE_SESSION_ID, so Node
derives the session from the process tree; a caller that cannot prove it owns the row; a descriptor whose store key differs from the caller's project;
a reconcile sweep's drain), a mesh group (sibling partitions are merged with gap withholding and caps), a caller that does not own the id,
a project mismatch, a store that does not exist yet, a partition without floor rows, a descriptor whose inbox or cursor file does not read, more unread
rows than mesh_write.inbox_read_limit (Node truncates per source), a legacy forward whose original hash Node derives, Jev triage that may be
enabled while there is mail to label (Node labels it and records outcome tracking), no stable launcher on disk (the ackCommand names the path
Node resolves), and an old receipt in the directory (Node prunes receipts past mesh_write.receipt_keep_ms as it writes). Once the receipt
exists nothing defers; if the receipt cannot be written the verb defers with only a directory created. Lane l8d additions. --since / --tail are Node's refusal (window-flags-unsupported-on-acking-verb, exit 2): the engine prints it and logs it to
the central log itself. An unclaimed row is promoted natively when the caller's own words prove it (--session or CLAUDE_CODE_SESSION_ID, and the id
is the caller's identity, cross-linked to its own row, or the sole unclaimed row of its worktree): every deferral of the read is settled first, then
the descriptor (<id>.json.tmp renamed over it) and the registry row (upsertRegistry with the path-change guard off, then the summary refresh) are
written, one unclaimed-session-promoted event goes to the central log, the read is worked out again over the promoted row and the result carries
promotion: {promoted: true}. --ack-after-print acks the receipt the read files, in the same call, and prints the ack as autoAck: the ack's
refusals and the moves the engine does not apply (a receipt op on an NDJSON inbox or a sibling partition, a partition whose legacy cursors still need
Node's import) are settled BEFORE the receipt is filed, so nothing is written for an ack the engine would have to hand to Node; once the receipt exists
a failed cursor write is reported in autoAck.cursorWriteFailures, as Node reports it, and the read is never rerun. Telemetry: InboxReadPrimary lines. The
background Node check runs the real verb on a scratch copy (a consistent copy of the store, the descriptors' NDJSON inbox and cursor files copied
under the scratch home so a later ack cannot race it) and compares its output and its receipt with both random ids and both homes made equal.
Plain roster (src/meshw/roster.rs, src/meshw/rosterrows.rs, src/meshw/hivecontrol.rs; Node: cmdRoster, rosterHints, rosterHumanText, hcRun; lane l8f).
The engine answers a project's roster with its rows, text table or --json, and writes nothing (Node's roster is a pure read: the summary projection, a read-only
app database, no cache write). A row is the store's workspace plus its hints: worktree-gone, idle Nd (the persisted liveness verdict), archived (anti-hall's own
marker or the app database's verdict) and live session in archived workspace, dormant / idle (alive) (the heartbeat, the transcript's modification time and
the descriptor's registration time against devswarm.dormantMs or ANTIHALL_DEVSWARM_IDLE_MS, and a running session process), phantom, instance-split
(two live nonces within devswarm_cli.rr_split_gap_ms), done/archive-pending, app-live. Archived descriptors of the project become rows; the app database
adds appArchived, the title, the app object (rank, pinned, focused, finish, brief, builder type) and orders the rows by sidebar rank; appStillLive reports
workspaces anti-hall archived that the app still shows; a primary-<hash> ghost row folds into its canonical row by alias, tombstone or the app's builder on
its worktree. The texts and numbers are devswarm_cli.rr_* in the plugin's defaults.
What stays Node's, decided before anything is printed (exit 75 to the wrapper, nothing written): a row whose session transcript exists (Node reads its tail to say
whether the child waits on a human), a row with a step plan, a native hivecontrol child that is not already a store row, a child whose repository id disagrees
with the trusted lookup (Node logs it), the split-brain fallback row, an archive marker a newer occupant of the id superseded (Node logs it), the supervisor's
active-list cache when a row could depend on it, a dormancy window set to zero or below, an id JavaScript would order as an array index, and every odd value the shared
readers defer on. hivecontrol workspace list children (and, for a child carrying a repository id, workspace list all without DEVSWARM_REPO_ID) is one bounded
call (mesh_write.hivecontrol_timeout_ms; the child gets a closed stdin; more than mesh_write.hivecontrol_max_stdout_bytes of output fails it; a
child that ignores the termination signal is killed after mesh_write.hivecontrol_kill_grace_ms, where Node would wait for it for ever); a missing
binary, a spawn error, a timeout, a signal, a non-zero exit, an empty or unparsable answer are all "no children", as in Node's fail-open
fetchNativeChildren. In front of the call sits Node's capability
gate: the binary is found as Node finds it (ANTIHALL_DEVSWARM_HIVECONTROL, PATH, hivecontrol-path.json, the DevSwarm app's copy on macOS), its probe is read
from capabilities.json (keyed by path, mtime and size), and a missing or stale probe, which makes Node spawn the binary and rewrite the cache with the
clock in it, defers; a build whose workspace --help lacks list and whose dormant line Node already recorded is refused without a spawn, as Node does.
Telemetry: Roster lines; the background Node check compares the output on a scratch copy.
The central log (lane l8d, src/meshw/clog.rs). The refusals and events Node writes to ~/.anti-hall/logs/devswarm.jsonl (or $ANTI_HALL_LOG_DIR)
are written by the engine with the same line format (JSON.stringify(entry), keys in Node's order), the same file, the same size bound with rotation to
devswarm.jsonl.1, and the same rotate lock (devswarm.jsonl.rotate.lock, taken over only when stale and not held by a live process; a writer that
cannot get it within the wait budget appends without it). Each entry carries the writer's pid: the engine's own, which is the true writer; the parity tests
and the Node witness blank the timestamp and the pid on both sides (devswarm_cli.log_masks). A call under NODE_TEST_CONTEXT without a log directory is
Node's (it refuses the real-home fallback). Answered natively because of it: the --since/--tail refusal of inbox read-primary, the argument and
identity refusals of send (no project, --from mismatch, target mode, --question/--answers on a broadcast, message source, empty body, urgency,
sending to oneself) and of done (no project, Primary checkout, another workspace's id, no identity).
Still in Node, on purpose: inbox read-primary and inbox tick for a mesh group (the sibling partitions are merged with gap withholding, caps
and a liveness gate on each sibling's ack), inbox read-primary when Jev triage may label what it prints, inbox tick --child, an unarmed watcher
(idle, archived and limit skips), and every plain roster of a project that has a row. In shadow mode a verb that can be replayed on a store copy logs
match/mismatch/concurrent/defer; inbox ack-primary, heartbeat, inbox tick, inbox read-primary and roster cannot (they consume or write
files outside the store, or spawn), so Node runs them and the line says skipped.
DevSwarm realtime state (lane B1)¶
The engine keeps the live state of every DevSwarm workspace in one atomically swapped snapshot (devswarm_rt): lifecycle (active, closed, archived, hidden, unknown), paused, activity (working, stuck, waiting_ci, done, unknown), unread mail, plan step, last heartbeat and the linked PR. Every field carries its source, the time it was observed and a source signature; an unreadable source gives unknown, never a guess, and nothing is ever written back to a source. It is inert (no thread, no read, no write) when DevSwarm is not detected (no app database file and no workspace descriptor) or devswarm_rt.mode is off.
- Paused. No signal is proven yet. A workspace whose open terminals are all
resumableis reported aspaused?with that evidence and is never claimed paused untildevswarm_rt.paused_signalis set topanel_resumableafter an owner-confirmed crash fixture. - Reconcile. The whole state is re-read at start (differences from the persisted state are flagged
while_downwith a notify hold ofrestart_grace_ms) and everyreconcile_ms. A change a periodic or overflow reconcile finds is one events missed and counts inrt_reconcile_repairs;rt_edgescounts every change emitted andrt_shadow_mismatchesevery difference from the Node witness. - Persistence. hot.db tables
rt_entity(latest record per workspace) andrt_edges(capped change log). - GitHub facts. PR and CI facts come through the
GithubStatetrait when the GitHub realtime feature supplies them; otherwise from the app database'spull_requests.checkStatus, whose freshness is itslastSyncedAt. - Shadow. The comparison reads the Node witness's scratch-home tree (liveness verdicts, app-state cache), never the live Node files, and appends differences to
rt-shadow.ndjson.
Statusline dashboard. After every reconcile the daemon writes a compact copy of the snapshot (devswarm-line.json in the state
directory: per open workspace its activity and when that was observed). The statusline's DevSwarm segment reads only that file, never
the DevSwarm database, and shows the counts by state (ws ▶2 ⚠1 ⏳1 ✓2 open: working, stuck, waiting on CI, done but still open). A copy older
than the stale limit, an unreadable app database, or one workspace's activity observed too long ago shows ? instead of a guess. The
segment is on by default and is advisory only. Settings (~/.anti-hall/settings.json, statusline.devswarm.*, or the env named in
devswarm_rt.toml): enabled, format ({parts}), max_chars, stale_ms; the part texts, order and colors are devswarm_rt.line_*.
DevSwarm wiring and the Node cutover (lane dswire)¶
The daemon starts the DevSwarm layer only where DevSwarm exists (the app database or a workspace descriptor) and devswarm_rt.mode is not off; otherwise no thread, watcher or file is created. One thread (ah-dswire) owns the file watcher over the DevSwarm state directories and each active workspace's transcript directory, git directory and mesh store directory (never the SQLite files in it), and holds one read-only connection per SQLite source (the app database and each active workspace's mesh store) that it asks PRAGMA data_version every devswarm_wire.store_poll_ms: the counter moves exactly when another process commits, and this process's own reads never move it. A change is only a hint: the state is always re-derived from the sources. The thread sleeps until the next thing is due (never longer than devswarm_wire.wait_ms). devswarm_rt.mode is read from the daemon's live configuration: off at start starts nothing, and turning it off later drops the watcher and stops every reconcile and Jev sweep (the thread only checks the mode, every wait_ms) until it is on again. A transcript event is gated by a stat (inode, size): it counts only when a file grew, and at most once per devswarm_wire.transcript_min_interval_ms per workspace (growth inside the interval is acted on once, when it ends). A watcher overflow is a full reconcile, and the scheduler job devswarm_reconcile (devswarm_rt.reconcile_ms) is the safety net; what it finds that events missed counts in rt_reconcile_repairs.
- Actions from state. After a reconcile that found a change of a kind in
devswarm_wire.act_edge_kinds(or on every periodic and start-up reconcile) the engine runs the three automatic actions under Node's own settings (devswarm.autoArchive.{mode,idleMin,maxPerSweep,ignorePings},devswarm.nudgeMaxAttempts,devswarm.nudgeCooldownSec): auto-archive of finished workspaces (executorengine), and poke / escalate of stale ones (only where their executor isengine; the defaultautofollowsdevswarm_sup.mode, see the cutover below). Sweeps are at leastact_min_gap_msapart; a change inside the gap is run when the gap has passed. Facts are re-read from the sources right before each action; the one deliberate narrowing is that the idle gate uses Node's pre-0.109 rule (newest heartbeat or transcript time), so the engine can archive later than Node but never earlier. A poke waits onenudgeCooldownSecbefore the next decision about that workspace. Owner actions go throughah-engine devswarmunder the role matrix. - Consumers. The
devswarm-rt-advisoryhook check (UserPromptSubmit, main thread only, engine-only; its Node fallback is a no-op; its decision is the plugin scriptengine/logic/devswarm-rt-advisory.js, the engine only reads the state and the session marker) tells each session once about the changes since the generation it last saw (advisory_max_edges,advisory_max_chars; a session's first look starts from now).ah-engine devswarm lineprints the statusline segment. A change of kindplan_step,activity,prorchecks, or a commit or transcript write in a workspace, queues a per-childjev::sweep::sweep_only(the slowjev_sweepjob stays as the safety net). The queue is held in memory and saved tort-jev-dirty.jsoneverydevswarm_wire.jev_dirty_flush_mswhen it changed and when the thread stops. - Telemetry.
dswire_actions(by kind and outcome),dswire_standdown(sweeps skipped because the executor is not the engine),dswire_advisory,dswire_jev_dirty,dswire_jev_threads(threads started for a Jev sweep),dswire_jev_coalesced(sweep requests folded into the queue),dswire_reconcile_cpu_us(calling-thread CPU by cause and phase),dswire_reconcile_runs(by cause and outcome),dswire_mode_change(the layer's mode changed while running, by the new mode),dswire_stall_actions(pokes and escalations of silent workspaces by kind and outcome), plusrt_edgesandrt_reconcile_repairs. - Activity-line hysteresis (GH #632).
devswarm_rt.activity_min_dwell_s(default 300; 0 turns it off): the advisory tells a session a workspace's activity change (working, stuck) once; a flip and its flip back inside one batch are silent, and a change within the dwell of the one the session was last told (kept per workspace in the session's marker underact) is held and told on the first prompt after the dwell. With the advisory off nothing is told or counted and the marker follows the state's generation, but the activity changes seen meanwhile are folded into the held ones (flips cancel: stuck, working, stuck is nothing; a net change survives), and once it is on again and the dwell has passed only the net change versus what the session was last told is told. Counted bydevswarm_rt_activity_line(result=emittedorsuppressed_flip). - Mesh read telemetry (GH #626, #615).
mesh_ack_command_renderedcounts theackCommandstrings a read-primary prints (the quotes wrap the engine binary path only; the verb follows them, sosh -cruns it).mesh_read_peek_mismatch(reason=read_empty_unreadorpeek_empty_unread) counts a read or peek that listed no message while reporting a non-zero unread count; each one also logs the id, both counts and the time (opread-peek-mismatch). - Event-driven auto-archive and the done-but-open nag (
src/dsact/events.rs,nag.rs; on by default, settingsdevswarm.autoArchive.eventTrigger/eventDebounceMs,devswarm.nag.{enabled,everyMs,hourlyCap}). Alifecycle,activityorpredge marks the workspace dirty; once quiet for the debounce the event path runs the same archive as the sweep (gates a-h, ledger keyauto-archive:<id>:<doneHead>, a re-check against the live app database right before acting, a per-workspace in-flight lock shared with the timer sweep, a bounded call, a check that the app shows it archived). The timer sweep stays as the safety net. The nag tells the Primary once when a workspace is done (devswarm_act.nag_done_requires, clean, no unread, past idleMin) and still open, then a digest everynag.everyMs, capped per hour; it is silent for archived / closed workspaces and for ids auto-archive owns, and acts on nothing. Telemetry: every attempt is anactevent (shared schema) and a line indsact.events(feature, action, target, every gate's value, outcome, reason, latency); mistake signals (unarchived,activity-after-archive,nag-ignored) aremistakeevents about the action's key, recorded once. Metrics:dsx_actions(feature, outcome),dsx_mistakes(feature, signal),dsx_latency_us, and the gaugesdsx_auto_archive_success_rate,dsx_auto_archive_mistake_rate,dsx_nag_success_rate,dsx_nag_mistake_rate(success = ok / (ok + failed); mistake rate = mistakes per ok). - Stuck and silent children on events (feature 5). A workspace's silence clock is the newest of its heartbeat, its transcript and its git directory (
devswarm_rt.stall_sources,stall_git_paths); withdevswarm_rt.stall_require_quiet_sourcesat its default 3, activity on any of them resets it. The watcher reads the state again the moment a transcript or git event hits a workspace the state calls stuck, and the moment a working workspace's clock reachesstall_ms(stall_check_min_gap_ms), instead of waiting for the periodic reconcile. The poke and escalate are unchanged (the descriptor's own commands,nudgeMaxAttempts/nudgeCooldownSec, keyspoke:<id>:<n>andescalate:<id>), and every condition is read again from its source right before: still active (not archived, hidden or closed), not paused (paused?counts), not waiting on CI, still silent on enough sources. Each action is written to the action log and followed up afterstall_followup_wait_ms: a poke that changed nothing is anudge_no_changemistake, an escalation after which the workspace worked again isescalation_then_active. - Action log and mistake report. Every acting feature (
stall,merge_ready) appends toactions.ndjsonin the state directory: feature, action, target, the value of each decision input, the outcome (ok,refused,failed), the reason and the latency, plus the mistake signals found later and the follow-up results; the sharedact/mistaketelemetry events carry the same facts.ah-engine telemetry actions [feature] [--window <ms>]reports per feature the action counts by outcome, the success rate (ok of the actions that ran), the mistakes by kind and the mistake rate (distinct mistaken actions of the ok ones);--mistake <feature> <action> <target> <kind>records one the engine cannot see, such as an escalation the owner dismissed. Settings:actions.toml.
DevSwarm supervisor cutover: what the kit's go-live must flip¶
The Node supervisor (the engine supervisor duty, a launchd / systemd / cron job every 60-120 s) does more than archive, poke and escalate. Lane l7 gave every other duty to the engine's scheduler (job devswarm_supervisor, src/dssup, settings in devswarm_sup.toml), so the Node job can be switched off as a whole; lane l7b then moved the duties that are not store- or model-heavy into Rust. The inventory of what it does and what each duty became is in the lane notes (SUPERVISOR-DUTIES.md); in short:
| Duty | Now | Why the rest stays Node |
|---|---|---|
| log rotation, housekeeping (aged reaped logs and child-gate state) | native (dssup::tick, dssup::housekeep), Node's gate, state file, settings and result rows; Node's function runs only as the non-acting witness on a scratch mirror |
- |
recover (kill and resume of one session) |
native (dssup::kill): Node's exactly-one-target confirm-gate, the identity re-check before SIGTERM and again before SIGKILL, the recovery log and the liveness verdict byte for byte; Node's read-only findTarget is the witness, and the engine stands down when it would signal a process Node does not confirm |
- |
| the ingest drain | native, see "The ingest drain" below | - |
| liveness sweep: every workspace's verdict file | native (dssup::liveness): computeLiveness + writeVerdict byte for byte (heartbeat, transcript, last commit, mailbox union, sticky escalation, nudge window, never-launched). A workspace that is stale, has a Jev blocker or a step plan, or whose shape the engine will not reproduce goes to Node's own sweepOnce restricted to it (the engine never writes a stale verdict, so it can never nominate a workspace Node would not). A read-only Node computation over the live data (its file wrapper serves the old verdict and drops every write) is the witness |
suppressors, poke / escalate, the forced parent notice for an urgent mesh unread, straying and the Jev blocker label, and the re-send of parked notices stay Node's (store writes through notifyParentEscalation, the Jev assist and the plan supervision) |
| deferred post-update stage | native tick (dssup::deferred): the rotation cursor, the marker peek and the nothing-pending answer (no Node process on a no-op tick); a stage that has work runs as Node's runDeferredStage |
the stage bodies are the store folds of update.js (fold-all-stores, heal-orphan-partitions, fold-archived-rows, heal-registry-rows), thousands of lines that move user data |
| retention | native (dssup::retention): the first-run dry-run report (retention-dry-run.json, then the flip to armed), plan, archive-first tombstoning, space reclaim, the legacy journal fold and the archive-cap eviction, with the state / log files Node writes, under the agreement protocol below |
the fold's eligibility (Node's store merge check) is asked of Node's own foldLegacyJournal in a dry run each time; the engine folds only the exact files it names |
| app sync | native (dssup::appsync): one read of the DevSwarm desktop app's database per tick (the snapshot, with its capability gate reduced to table / column / file presence), the archived markers, the names cache, the message-gap cross-check and app-state.json byte for byte; no Node process on a quiet tick |
the retirement of a stale marker (restored descriptor, revived registry row, hard links under the per-id lock) is executed by Node's own retireStaleArchivedMarkers, after the agreement below |
| reconcile sweep | the engine owns the schedule, gate (cool-down state file), sweep lock, bound and record and runs Node's own function in a node subprocess, so every shared file stays Node's byte for byte |
it orchestrates ah-hook mesh reconcile (per-worktree queue drain into the shared store), the mesh duplicate fold, the hivecontrol active-list probe with its repository scoping, the archived cache and start-up sampling: store folds and a subprocess probe, each of which wants its own corpus-and-witness lane; the cool-down (default 15 minutes) already keeps it off most ticks |
Retention's safety bar. A wrong write loses a user's message text, so the native sweep holds a stricter bar than "same as Node". Retention never deletes a row: it sets old, fully read message bodies to NULL after archiving them (positions, counts and dedupe depend on every row staying). The engine plans natively; Node's own planStore and a dry-run pruneStore plan the same store read only; the engine writes only when the two agree on the exact candidate rows, on every partition's statistics and on the counts chosen, and only when a second native plan taken after Node's is identical to the first (the store did not move under the comparison). A disagreement, a witness that cannot run (while devswarm_sup.retention.requireWitness is on, the default), or a changed store does NOTHING that run, is logged to the witness log (match: false) and is not tried again before witness_every_ms. The archive is written with the system gzip and each month's member is decompressed and compared with its input before the rows it holds are tombstoned; inside the tombstoning transaction every row is re-checked against the live database (same partition and hash, same position, not an open question, still older than the window when chosen by age, broadcast rows still under every cursor) so the rows tombstoned are always a subset of what Node's own transaction would tombstone. Anything the engine cannot read exactly like Node (a body that is not text, an unreadable table, a missing gzip) hands the whole sweep to Node's function, as before. The first-run dry-run report only writes retention-dry-run.json, the state's phase and one log line, but because the flip to armed is what later permits tombstoning, each store's summary is agreed with Node's planner first (a disagreement hands the sweep to Node). The legacy journal fold and the archive-cap eviction (the one retention step that removes archived text for good, and only when the user set devswarm.retention.archiveMaxMB) follow the same rule: the engine lists the files itself, asks Node's own function for the same list in a dry run, and writes or removes only on an exact match (a journal file that changed after it was read is kept; an archive file that changed after the plan was made is not removed). devswarm_sup.dryRun.retention plans and compares and logs without writing; devswarm_sup.dryRun.verdicts does the same for the liveness sweep. Naming verdicts, deferred or retention in devswarm_sup.node_duties hands that duty back to Node.
App sync's safety bar. The sync reads the app's database read only and writes four kinds of file. app-state.json and the names cache are derived caches. An archived marker (archived/<id>.json, the descriptor's own content plus archivedBy / archivedAt) is created only if it does not exist (written to a temporary file and linked into place, never overwritten, never torn) and never touches the descriptor it copies; it is written only when Node's markAppArchivedDescriptors, run as a dry run, names exactly the same workspaces in the same order. A stale marker (written from the app's state, older than ten minutes, whose workspace the app now shows open, never one anti-hall's own archive verb wrote) is retired only when Node's retireStaleArchivedMarkers dry run names exactly the same ids, and then by Node's own function. A disagreement, or a Node that cannot run, does nothing for that step, logs match: false (or null) to the witness log under app_sync-mark / app_sync-retire, and the rest of the sync still runs. Every witness_every_ms the engine's whole state document is also compared byte for byte with Node's own dry-run state (app_sync line). Anything the engine cannot read exactly like JavaScript (a blob or an integer past 2^53 in the app database, a relative path, a date string V8's parser might read differently, an object key JavaScript would order or treat specially, an id the locale collation might order differently from bytes, a descriptor whose id is not a string or number) hands the whole sync to Node's function, and every step is idempotent so a hand-over after a partial pass repeats nothing. ANTIHALL_INGEST_DRY_RUN=1 computes everything and writes nothing; devswarm.appSync switches the sync off; naming app_sync in devswarm_sup.node_duties hands it back to Node.
An engine poke / escalation writes Node's liveness verdict and recovery log line in Node's exact bytes and sends the same one-time parent notice. ah-engine devswarm recover --id <ws> --request <id> is the on-demand kill-and-resume (main session only, never scheduled): the engine refuses an automated caller, an unsafe id, a repeated request, a workspace without a descriptor and one already recovered maxRecoveries times, then runs its own confirm-and-kill. Naming a duty in devswarm_sup.node_duties (housekeeping, recover) hands it back to Node's function, the rollback for one duty. The witness (devswarm_sup.witness, on by default) re-runs Node's function for a native duty on a scratch mirror (names, sizes and modification times, never contents) at most every witness_every_ms and logs one line per comparison to ~/.anti-hall/logs/devswarm-sup-witness.ndjson (match: false is a mismatch).
The switch is one setting, devswarm_sup.mode (~/.anti-hall/settings.json, section devswarm_sup): witness (default) leaves every duty to the Node job and the engine runs none of them; engine makes the scheduler run them and turns the auto executor of poke and escalate (their new default) into engine. devswarm_rt."act.<action>.executor" is auto | engine | node | off; auto-archive stays engine by default, an unknown word reads as node, so a typo makes the engine stand down, never act twice. The engine never edits a settings file or a launchd / systemd unit.
The double-run guard. While the Node supervisor's log (~/.anti-hall/devswarm-supervisor.log or its .1) was written within devswarm_sup.guard_ms (default 6 minutes; Node writes one line per sweep), the engine's supervisor duties AND its poke / escalate stand down (dswire_standdown), whatever the mode or executor words say. So a go-live done in either order never has two actors; the engine simply waits until the Node job has been quiet.
Go-live steps (owner, in this order; each step is safe on its own):
ah-engine devswarm supervisor- notemode: witnessandnodeSupervisorRunning(the age of Node's last log write in ms).- Stop the old Node job:
ah-hook units heal(retires the LaunchAgentcom.anti-hall.devswarm-supervisor, or the systemd user timer, or the cron line). Do NOT setANTIHALL_DEVSWARM_SUPERVISOR=offfor this: that variable also switches the DevSwarm hook context off. Leave the ingest daemons (com.anti-hall.devswarm-ingest.*) running. - Set
{"devswarm_sup": {"mode": "engine"}}in~/.anti-hall/settings.json(the daemon re-reads it; no restart). With the modeenginetheautoexecutors of poke and escalate are the engine; setting{"devswarm_rt": {"act.poke.executor": "engine", "act.escalate.executor": "engine"}}as well is equivalent. - Verify after about
guard_ms:ah-engine devswarm supervisorshowsmode: engine,nodeSupervisorRunning: nulland the executorsengine;ah-engine schedule history devswarm_supervisorshows runs;~/.anti-hall/logs/devswarm-supervisor-engine.ndjsongains a line per tick with each duty's outcome;~/.anti-hall/devswarm/liveness/*.jsonkeep being rewritten. - Roll back:
{"devswarm_sup": {"mode": "witness"}}and reinstall the old unit by hand if you need it. Auto-archive is independent: its own durableauto-archived.json(gate h) stops either side from repeating an archive at one HEAD, andANTIHALL_DEVSWARM_AUTO_ARCHIVE_MODE=offin a still-running Node job's environment keeps Node from archiving while the engine does.
Go-live steps for the ingest drain (after the supervisor steps; each step is safe on its own):
ah-engine devswarm ingest- notemode: witnessand the projects (the working directories of the Node daemons' fresh heartbeats, plusdevswarm_ingest.projects). Check each project'slocknames the Node daemon.- Set
{"devswarm_ingest": {"mode": "engine"}}in~/.anti-hall/settings.json. Nothing changes yet: while a Node daemon holds a project's lock the engine's drain for that project waits (it never takes a live holder's lock), so two consumers never read one destructive queue. - Retire the Node daemons:
ah-hook units heal(retirescom.anti-hall.devswarm-ingest.<project key>or its systemd / cron equivalent; stops the process). The engine takes the lock withinlock_retry_ms(30 s) of the holder going away, replays any batch the Node daemon left open in the WAL (wal/monitor-<project key>.ndjson: same file, same format), and keeps the heartbeat (heartbeats/ingest-<key>.json) and the log (~/.anti-hall/devswarm-ingest.log) fresh in Node's shape, sodoctorand the freshness banner read it as before. - Verify:
ah-engine devswarm ingestshows the lock held by the engine's pid;heartbeats/ingest-<key>.jsonhaslastMonitorOkMsmoving; a message sent to a Primary appears insummaries/<key>.json.~/.anti-hall/logs/devswarm-ingest-witness.ndjsongains amatch: trueline everywitness_every_msonce a batch with messages was drained. - Roll back:
{"devswarm_ingest": {"mode": "witness"}}(the drain threads end at the next daemon start; the daemon waits at shutdown for a monitor call in flight, so nothing it already took off the queue is lost) and reinstall the old daemon by hand if you need it. Do not leave a Node daemon running while the engine owns a project: it exits at once on the engine's lock and its unit restarts it in a loop. - After the Node daemons are gone,
devswarm_ingest.legacy_probemay be set to 0 (nothing legacy remains to wait for).
The reconcile port (src/dssup/recon, settings in devswarm_recon.toml) moves the state reconcile and the sweep tail write from Node to the engine one slice at a time, with the engine always the actor and Node only a witness. A planner reads the live home and returns an op list; the gate mirrors the inputs twice into scratch homes (SQLite stores by the online backup API), runs Node's own function on one mirror with its clock pinned and the engine's op list on the other, compares the normalised post-states byte for byte, and only on equality applies the same list to the real home, unit by unit, under the unit's per-workspace lock after re-checking every precondition. Anything not provably identical (a mismatch, a drifted precondition, a busy lock, an unmodelled state, Node absent) is handed back to Node with nothing written for it. The op vocabulary cannot delete or update a message row (a static test enforces it). Ported so far: the side files (sweep state, resume marker written atomically, name cache, repo-unknown marker, active snapshot with its partial-list floor, start-up sampling) and healRegistry / rehomeMiskeyedRow / rehomeCore; a mis-keyed row (rehomeAcrossStores) is still Node's. Slice S5 adds healOrphanPartitions (additive only): an orphan partition with a live descriptor and no worktree family is adopted, an orphan with no descriptor or another repository's descriptor is reported unhealable; archived orphans, worktree families (the forward into a survivor) and anything the summary projection cannot reproduce hand the whole store back to Node. It runs from the deferred post-update stage only when devswarm_sup.sweep_tail_mode is engine (default node), store by store before Node's own stage function, which keeps the stage marker. Slice S8 (recon/stage.rs) runs the four deferred post-update stages natively when devswarm_sup.sweep_tail_mode is engine: it walks the stage's pending-store list (update-sweep-state.json, written like Node's recordSweepResult/recordRun, tmp + rename, once at the end of the walk), one stage per supervisor tick within devswarm_sup.set_sweep_budget_ms, each store through its witnessed port or, when the engine cannot prove it, Node's own function for that one store in a bounded subprocess.
The reconcile port (src/dssup/recon, settings in devswarm_recon.toml) moves the state reconcile and the sweep tail write from Node to the engine one slice at a time, with the engine always the actor and Node only a witness. A planner reads the live home and returns an op list; the gate mirrors the inputs twice into scratch homes (SQLite stores by the online backup API), runs Node's own function on one mirror with its clock pinned and the engine's op list on the other, compares the normalised post-states byte for byte, and only on equality applies the same list to the real home, unit by unit, under the unit's per-workspace lock after re-checking every precondition. Anything not provably identical (a mismatch, a drifted precondition, a busy lock, an unmodelled state, Node absent) is handed back to Node with nothing written for it. The op vocabulary cannot delete or update a message row (a static test enforces it). Ported so far: the side files (sweep state, resume marker written atomically, name cache, repo-unknown marker, active snapshot with its partial-list floor, start-up sampling) and healRegistry / rehomeMiskeyedRow / rehomeCore; a mis-keyed row (rehomeAcrossStores) is still Node's. The mesh fold (foldMeshDuplicates, foldGroupIntoSurvivor, rekeySubdirRegistryRows, retireWorktreeDuplicates, retireArchivedWorktreeGroup, ghostRegistryRows, forwardArchivedOrphanUnread) runs only when devswarm_sup.sweep_tail_mode is engine (default node): the forward only adds rows, the one removal is the conditional registry delete Node performs, and any group whose survivor, anchor or summary needs liveness or the legacy cursor import goes back to Node whole.
The reconcile port (src/dssup/recon, settings in devswarm_recon.toml) moves the state reconcile and the sweep tail write from Node to the engine one slice at a time, with the engine always the actor and Node only a witness. A planner reads the live home and returns an op list; the gate mirrors the inputs twice into scratch homes (SQLite stores by the online backup API), runs Node's own function on one mirror with its clock pinned and the engine's op list on the other, compares the normalised post-states byte for byte, and only on equality applies the same list to the real home, unit by unit, under the unit's per-workspace lock after re-checking every precondition. Anything not provably identical (a mismatch, a drifted precondition, a busy lock, an unmodelled state, Node absent) is handed back to Node with nothing written for it. The op vocabulary cannot delete or update a message row (a static test enforces it). Ported so far: the side files (sweep state, resume marker written atomically, name cache, repo-unknown marker, active snapshot with its partial-list floor, start-up sampling) and healRegistry / rehomeMiskeyedRow / rehomeCore; a mis-keyed row (rehomeAcrossStores) is still Node's. The drain of one workspace (recon::pull, slice S3) reuses the pull inbox tick --child runs (meshw::pull): under the workspace's pull lock the engine plans the pull (every state it does not reproduce goes to Node before anything is touched), asks the non-destructive count and, for a count above zero, does the ONE destructive read and appends and fsyncs its raw bytes to the delivery log; only then does the witness run (Node's own inbox pull on one mirror against a recording hivecontrol that answers 0, the engine's ensure and log replay on the other, post-states compared byte for byte), and only on equality the same replay is applied to the real home. A crash, a witness mismatch, a Node that cannot run, a shortfall, a date form the engine does not reproduce or a log write that failed leaves the captured batch PENDING in the log and Node's next pull replays it (idempotent by the content hash); the witness never reads the native queue. One deliberate difference from Node's own fresh pull: the closing record of a batch the engine captured itself is written by the replay code, so it also names the workspace it went into, and the records of the log are in capture order (new batch before the closing records of the older ones). reconcile and the sweep (recon::sweep, slice S4) port cmdReconcile (budget, resume rotation, git-root probe, archived and repository-unknown skips, Node's one retry after a native timeout, names, resume marker, result object), distinctRepoKeys and the duty. A project the engine cannot answer as a whole (a descriptor stranded in the legacy bucket, a registry row that must move to another store) and any workspace it does not drain is run by Node's own function; the mesh fold, the active-workspace probe and its cache and the start-up sampling stay Node's (reconcileSweepIfDue runs with the engine's results as the reconcile step's answer). The duty is switched by devswarm_sup.reconcile_mode (node, the default, runs Node's reconcileSweepIfDue unchanged; engine runs the port, witness-gated) and applies only while devswarm_sup.mode is engine.
The ingest drain (src/dssup/ingest, settings in devswarm_ingest.toml) is what the engine ingest duty does, one thread per project, started by the daemon only when devswarm_ingest.mode is engine:
- Single consumer. The project's lock
locks/ingest-project-<repo key>.lockis Node's file and protocol: a holder whose pid is known to be dead is taken over at once, an unknown holder when stale, a live holder never. The engine re-stamps it (and the heartbeat) at least every 30 s so a Node starter keeps respecting it, and stops when it finds the lock taken. While a legacy per-worktree consumer of the same repo (locks/ingest-<worktree hash>.lock, found withgit worktree list) is alive the drain does not start, and it removes no lock file. - Loss-free.
hivecontrol workspace monitor -i 3 -t 30runs as a bounded subprocess in the project's main worktree with everyDEVSWARM_*variable scrubbed (a daemon started from inside a workspace must not read that workspace's queue), killed by the engine only at its own hard limit (-tplushard_margin_ms) and keeping what it printed before the kill. Every non-empty output is appended to the delivery WAL and fsynced before it is parsed (Node's format: abatchrecord, thendoneorquarantine); one iteration issues a new destructive read only when nothing is pending in the WAL and the WAL and its spill directory are writable, so a batch the store refuses (partition lock held, partition no longer registered) is replayed first, and a WAL that cannot be written spills the bytes and blocks reads instead of dropping them. Import isINSERT OR IGNOREby thenative:content hash under the partition's lock after a "still registered here" recheck, then the summary is refreshed. A batch of no known shape is closed asquarantine(its bytes stay whole in the WAL) and a prefix goes toquarantine/, rate-limited, never pruned. - Node's breaker. A missing or non-executable hivecontrol is a configuration fault: the backoff climbs 2 s, 5 s, 30 s, 2 min, 5 min and a line is logged only when the step changes (plus a rollup); a transient failure backs off 2 s x 2^(n-1) up to 5 min. Both ladders are tested against Node's functions.
- The witness. The engine mirrors each drained batch's raw bytes and the rows it wrote under
~/.anti-hall/witness/. Everywitness_every_msNode's owningestPayloadruns over the mirror in a scratch HOME against an empty scratch store; per batch the message count, the lossy flag and every row's hash, time and body are compared, and every mirrored row is checked in the live store (a loss check). Node never reads the live queue or the live store. One line per comparison goes to~/.anti-hall/logs/devswarm-ingest-witness.ndjson. -
Not ported. The sweep of other projects' orphaned ingest lock files (the engine's lock takeover already reclaims a dead holder of its own project's lock) and the wedged-holder SIGKILL (the engine never signals a lock holder). A message time whose
Date.parseform the engine does not reproduce uses the import time and counts intsFallbacks. When the engine cannot derive the summary projection for an exotic store it logssummary refresh deferred; the next refresh by any writer updates it. -
Dropped paths. A path found as a project that is not drained is logged in the ingest log once per (path, reason) and counted in
ingest_drops(labelreason:identity-deferred,not-a-repository,main-worktree-missing,no-repo-key,primary-id-error,not-registered; texts indevswarm_ingest.drop_reason_*).
The Node witness runs non-acting (scratch HOME, recording stub, devswarm_rt.witness_home); rt-shadow.ndjson and dsact.shadow record agreement.
Telemetry (D78, D77)¶
Telemetry answers "what did the engine and the hooks do, how often, how long did it take and how much did it inject into
the model's context", without ever recording content. It is local only: nothing is uploaded, and it is disclosed in
PRIVACY.md. telemetry.enabled (default on) turns recording off; telemetry.flush_ms and telemetry.retention_days
tune it (all in telemetry.toml).
What is recorded. For every hook request the daemon serves, one row k=hook; for every built-in check it runs
(including the git check) one row k=check with the check as h; for every regex rule match one row with h=rule. Each
row is counted by h (hook or check), e (hook event) and o (outcome: allow, block, advise, defer, error,
skip), with a latency histogram (ms buckets, telemetry.latency_buckets_us) and ib, the bytes injected into model
context. The hook rows add up to the total injected; a check's own ib is attribution inside it. This is automatic: the
dispatcher records around every check, so a newly ported check needs no telemetry code. Rich events carry typed extras:
route (a model-routing decision: requested and parent model, task class, recommended tier, down / up / allow /
exempt, and the spawn_key), spawn (the result: the model that ran and its token usage, joined to the route event by
spawn_key), jev (integration, mode, verdict, cost) and spill. An event's text fields hold identifiers only: the type
refuses prose, and a line with an unknown field or text where an identifier belongs is rejected, so no prompt, transcript
or file text can be stored.
Cost on the hook path. Recording is a hash of the labels and a few relaxed atomic additions into a sharded table, plus
a bounded in-memory ring for rich events: no I/O and no shared lock. Measured by tests/it/telemetry.rs (release build): the
record() median is under 1 microsecond (the test asserts it, alone and with four threads hammering the same labels).
Persistence and the loss window. The recorder flushes to hot.db every telemetry.flush_ms (default 10 s) and at a
clean shutdown, through the Store's writer. A kill -9 (or power loss) loses exactly what was recorded after the last
flush: at most telemetry.flush_ms of data. Everything flushed survives (tests/it/telemetry.rs kills a daemon and reads the
database). Samples that could not be kept (a full table, an event overwritten in the ring before a flush) are counted in
tel_dropped, never silently lost. Counters also feed the metrics registry (tel_events, tel_injected_bytes), so
ah-engine metrics shows the same numbers.
Counts of a scheduled child. A scheduled subprocess job (ah-engine <action> --json) is a process of its own, and only the daemon
reads the counts bumped through metrics::bump. Before it starts the job the daemon makes a private file for that run
(files.telemetry_child_counts) and names it to the child in the variable schedule.child_counts_env (<daemon pid>:<path>; the child
accepts it only while its parent is that pid). At exit the child appends one counter line per series to that file, with no lock, no
directory and no log; once the child has ended, however it ended, the daemon adds the lines to its own table and empties the file.
tel_child_counts (label result) counts the series handed over (series) and the lines refused (bad). The hook dispatcher carries no marker
and is unchanged.
Daily rollups. hot.db keeps one counter row per UTC day and (k, h, e, o). ah-engine telemetry rollup copies every
complete day into archive.db (counts, sums and latency histograms), replacing the archive row, so it is idempotent, and
removes hot rows older than telemetry.retention_days only after they are archived (and old events by the same
retention). The scheduler runs it daily (job telemetry_rollup, schedule.telemetry_rollup_ms); the command runs it by hand.
Reading it. ah-engine telemetry summary [--window 7d] (per hook and check: invocations, outcomes, p50/p95/p99 latency
upper bounds, injected bytes), ah-engine telemetry events [--kind route] [--window 7d] [--limit n]. With a daemon they
include data not yet flushed; without, they read the database and say so.
NET savings. ah-engine impact --json [--window 7d] joins route events to spawn results (a re-spawn after a steer is
compared against what the agent first asked for) and reports, in both directions, what steering saved (the tokens the agent
used times the price of the model it asked for minus the price of the model that ran) and what steering up cost, minus the
spenders: injected context (injected bytes over telemetry.bytes_per_token, priced as input tokens of the most common
parent model) and recorded Jev cost. Every figure is labelled an estimate and states its method. Prices come from
impact.price_table; it has no verified prices yet, so spawns are counted as unpriced and no dollar figure is invented.
Action and mistake events (one schema for every acting feature)¶
Every feature that acts emits one act event per action and, when a later observation shows the action should not have been
taken, one mistake event that points back at it. Both are ordinary telemetry events (identifiers and numbers only; field
names live in telemetry.fields in telemetry.toml). Emit with telemetry::emit::act(&ActRec{..}) and
telemetry::emit::mistake(&ActRec{..}); any process may call them.
| Concept | Event field | Meaning |
|---|---|---|
| feature | h |
The feature, a stable lowercase name (auto-archive, poke, nag, ...). |
| action | e |
The verb the feature performed (archive, poke, ...). |
| outcome | o |
act: allow = ran and verified, block = refused, stale or unverifiable, skip = not applicable, error, timeout. mistake: always advise. |
| latency_ms | ms |
Wall time of the action in whole milliseconds (act only). |
| target | target |
What it acted on (a workspace id, a PR number); an identifier, never text. |
| inputs | inputs |
A short digest of the decision inputs (optional). |
| reason | reason |
act: why it was refused or failed (a stable word such as stale, refused, in-doubt). mistake: what showed it was wrong (reopened, reverted, ...). |
| action_id | action_id |
The idempotency key of the action (cut to telemetry.token_max_len). A mistake carries the action_id of the act it refers to. |
The DevSwarm action layer (dsact) emits an act event for every action it attempts, including refusals, with the ledger
outcome word as the reason. ah-engine devswarm ledger [--json] [--since 7d|<days>] (every role may run it; switch:
devswarm_act.audit_enabled, on) is the one report: per feature the runs, done, failed, refused, success rate
(done / finished), refusals by reason, mistaken actions and mistake rate (distinct mistaken actions / done), p50 and p95
latency; the action ledger (outcomes per kind, keys started and never finished); and the Node witness agreement from
dsact.shadow. A mistake whose action_id matches no act event is counted as orphanMistakes. doctor shows the same
data as an "Action audit" section when there is any, and warns above devswarm_act.audit_failure_warn_pct /
audit_mistake_warn_pct, for in-doubt keys and for witness disagreements. It only reads.
Storage¶
The daemon keeps what it records in two SQLite databases inside the state directory (D19, D21). SQLite is compiled into the binary, so there is nothing to install; it was chosen over redb by measurement (D73).
| File | Holds | Durability |
|---|---|---|
hot.db |
frequent small writes: impact events and their totals, per-project mailboxes and key-value pairs, applied write ids | WAL, synchronous=FULL: a write is on disk before it is acknowledged |
archive.db |
append-mostly history: consumed messages, expired key values and old impact events moved out of hot.db; opened on first use |
WAL, synchronous=NORMAL, batched commits (synced like hot.db while maintenance moves rows) |
- One writer, group commit (D23). A single writer thread owns the
hot.dbwrite connection. Requests hand it their writes over a bounded queue (storage.write_queue; when it is full the write is refused as busy). The writer takes a write, gathers more for up tostorage.group_commit_ms(default 0: only what is already queued, which still groups writes that arrive during a commit), commits them in one transaction and only then answers each one. Each write sits in its own savepoint, so a refused write never undoes its neighbours. Reads use a second connection. - Acknowledged means committed. A project write is answered only after its transaction is on disk; a write that does
not commit within
storage.ack_timeout_msis answered with an error, and its write id makes a retry harmless. The testtests/it/durability.rskills the daemon with SIGKILL in the middle of a burst of writes from four threads, fifty times in a row, and checks after each restart that every acknowledged write is present, nothing present was invented or torn, and every write id matches exactly one row. - Hooks never wait on storage. Impact events from the hook path are queued without waiting; a later read first waits
for everything queued before it, so it sees them. If storage cannot open, the daemon logs why, shows it as
storageinstatus, and keeps serving hooks with the impact ledger in memory. - Settings are keys. Journal mode, synchronous level,
storage.fullfsync(macOS power-loss safety, off by default: it cost about 99 percent of the commit rate when measured, D73), page cache, mmap, timeouts and the writer queue are all instorage.toml. - Tiered lifecycle (D20, D22, D25). A write commits to SQLite first; only then does the writer make it active in
memory, so memory follows the commit order and never holds anything SQLite does not. Memory holds only active items:
a key set with
setexstops being active when its TTL passes (it is dropped from memory and its row stays in SQLite), and past the byte budget (tier.budget_kb) the least recently used item is dropped, which loses nothing. A restart starts with an empty memory layer and promotes items again as they are read. A read that races a write never promotes the older value. - Pub/sub. Each committed mailbox
putor keysetis announced on the channelproject:<hashed project>. A subscriber has a bounded queue; publishing never blocks, and a slow subscriber loses notifications (counted asbus_dropped), never data. Delivering these to sessions is the Monitor push, planned (D45). - Idempotent writes. A project write may carry a write id (
W <id>in the request). The writer records the id with the result in the same transaction, so a repeat returns the first answer and changes nothing. - Nothing in memory alone. Without storage every project operation is refused, so the client can retry and spool it.
- The spool (D24).
ah-engine projgives every write an id and sends it; while the daemon is absent (the client starts it), busy or failing, it retries with exponential backoff and jitter (spool.retries,spool.backoff_ms). If there is still no answer, a write (put,set,setex) is appended tospool.login the state directory, framed, checksummed, under a file lock and fsync'd, and the command reportsspooled <id>. Atakeis never spooled, since it needs an answer. The daemon applies the spool on start, everyspool.drain_ms, and before each project write (so a spooled write lands before a newer direct one), in file order, which keeps each session's order (AH_ENGINE_SESSIONnames the session). Each record carries its write id, so applying it twice changes nothing. A record that is damaged, or that the store refuses for good (a full mailbox), goes tospool.quarantinewith its reason; nothing is dropped. The spool is capped (spool.max_bytes): past the cap the write is refused, so the caller knows it was not kept. Hooks do not write project state today; they will use the same path when they do. - Size control (D26).
ah-engine maintainmoves what has left its active life fromhot.dbtoarchive.db: consumed messages afterretention.mailbox_consumed_s, key values expired longer thanretention.kv_expired_s, impact events older thanretention.impact_hot_sor beyondretention.impact_hot_rows(their totals stay). Each batch is committed toarchive.dbbefore it leaveshot.db, and a repeated copy is a no-op, so a crash in between loses and duplicates nothing. It then forgets applied write ids older thanretention.applied_s(derived bookkeeping, D59), checkpoints both WALs and VACUUMs both databases, and records the run. Archived user data is never deleted unlessretention.archive_delete_after_sis set (default 0, D26). It runs in its own process against the files, beside a live daemon or without one; SQLite's locks keep the two apart, and a daemon write that meets the lock is retried and, if need be, spooled. The scheduler runs it as the dailymaintainjob (schedule.maintain_ms). - Backup and restore (D27).
ah-engine backupcopies both databases with SQLite's online backup API, so the snapshot is consistent while the daemon writes, intobackups/<ms>/in the state directory (or--to <dir>, never over an existing snapshot). The copy is scrubbed: message bodies, values and recorded results (backup.scrub_columns) lose anything that looks like a secret and the home path, the file is VACUUMed so no unscrubbed page remains, and each file is integrity-checked and listed inmanifest.json. Project keys stay as they are, because a restore needs them.ah-engine restore <dir>checks the snapshot first (integrity, schema version), then keeps the current state as an unscrubbedbackups/pre-restore-<ms>/snapshot that it never deletes, stops the daemon and holds its lock so none starts, and copies each database into place with the same API. The next hook call starts a daemon on the restored state. - Versioned schema. Each database records how many migrations it has run (
PRAGMA user_version); opening applies the missing ones, each in its own transaction, and re-running them changes nothing. A database written by a newer build is refused rather than rewritten.
Shared read paths: the transcript index and the git cache¶
Two facts sources the guards will share instead of each re-reading a transcript or spawning git themselves. Both are
libraries inside the engine (src/transcript/, src/gitcache/); no check calls them yet, the checks that do are ported
in wave 2 (planned, D75).
Transcript index (ah_engine::transcript). At least 20 hooks read the session transcript, each in its own process,
so a Stop with 11 hooks read the same tail up to 11 times. An Index follows one transcript file and keeps a byte
offset at a line boundary. A refresh reads only the appended bytes. The first refresh reads the last
transcript.initial_window_bytes (the same 1.5 MB window and dropped partial first line as transcript-tail).
What it keeps, all bounded by transcript.toml:
| Fact | Mirrors |
|---|---|
| record counts by kind, malformed lines, sidechain, meta and compact-summary rows, compaction boundaries | the filters in devswarm-idle.js, inference-check.js and compact-advice.js |
| the newest assistant text, in the deduplicated and in the legacy extraction | speculation-guard.js collectTextFromEntryDedup and collectTextFromEntryLegacy |
| the newest typed user prompt | inference-check.js lastUserPrompt |
| the newest tool uses of any tool | task-state.js collectTU |
| the task-tool uses and their string results, in order | what task-state.js reconstructTasks reads |
every <task-notification> block, from all three transcript shapes (a user entry, an attachment prompt, a queue-operation content), with the terminal-agent view of agent-scan.js and the final-key view of devswarm-idle.js |
notificationTexts, finishedTaskKeys, scanTranscript |
task_status attachments that a compaction writes for live agents |
agent-scan.js |
Safety: a file smaller than the offset (truncation), a different device or inode (rotation), or a changed start or
changed bytes just before the offset (a rewrite) throws the facts away and rebuilds them from the file, so the index can
always be recreated from the transcript alone. A last line without a newline is shown through a one-record overlay and
never counted twice. More than transcript.max_update_bytes appended between two refreshes skips ahead to the newest
bytes and counts a gap. An Indexes registry holds one index per path, at most transcript.max_indexes, and drops an
idle one after transcript.idle_ttl_ms (D22: memory holds only active items). Parity with the Node readers is checked by
tests/it/transcript_parity.rs and, over real transcripts, by parity/run-transcript.js.
Git cache (ah_engine::gitcache). Guards spawn git for the branch, the remotes, the aliases, the work tree root
and the dirty state. GitCache::repo(dir, env) finds the repository the way git does from a directory (a .git
directory, or a gitdir: file for a submodule or a linked worktree, with commondir followed) and returns a handle whose
methods answer from memory while a signature of the repository's files is unchanged, else run git once.
| Fact | Method | Fresh equivalent |
|---|---|---|
| work tree root, absolute git directory | toplevel, git_dir |
rev-parse --show-toplevel, --absolute-git-dir |
| commit and branch | head, branch |
rev-parse HEAD, symbolic-ref --short HEAD |
| upstream and remotes | upstream, remotes |
rev-parse --abbrev-ref --symbolic-full-name @{upstream}, remote |
| aliases | aliases |
config -z --get-regexp ^alias\., parsed like git-alias-scan.js |
| one config value | config_get, config_path |
config --get, config --path --get |
| dirty bit | dirty, dirty_exact |
status --porcelain=v1 |
The signature (D61) holds the content of HEAD and of the branch ref it names, and the stat (device, inode, size, mtime,
ctime) of the index, the repository and per-worktree config, packed-refs, the user's global and system config, and, for
the upstream fact, the remote-tracking directories. Git replaces these files by rename, so a commit, a checkout, a config
change or a fetch changes the signature even within one clock tick. A hard TTL (gitcache.ttl_ms) applies as well.
Limits that the signature cannot see are handled in the open: a working-tree edit changes none of those files, so the
dirty bit has its own short TTL (gitcache.dirty_ttl_ms) and dirty_exact always asks git (a destructive decision must
use it); include.path and GIT_* overrides are not signed, so a call whose environment sets one of
gitcache.bypass_env is refused (Bypassed) and the caller runs git itself. A run that times out or fails to start is an
error and is never remembered; an exit status other than 0 is remembered as "git said no". tests/it/gitcache_parity.rs
compares every fact with a fresh git invocation on a plain repository, a linked worktree and a submodule, before and
after commits, amends, resets, branch switches, detached HEAD, pack-refs, config changes, fetches and stashes.
Process watch (orphans, stuck agents, resource and disk warnings)¶
One scheduled job (procwatch, schedule.procwatch_ms, default 30 s) and one engine-only advisory check
(procwatch-advisory: SessionStart, UserPromptSubmit, PreToolUse) that look after the machine a Claude session runs on. All of
it is configuration (procwatch.toml, resource_watch.toml, disk_watch.toml, with settings keys in /anti-hall:settings
under Process watch, Resource watch and Disk watch). It is for every user: nothing in it names a project or a path outside the
plugin's own directories. It warns; the only thing that can stop a process is a per-class opt-in, and nothing is ever deleted.
| Part | Does | Default |
|---|---|---|
| Orphan sweep | lists (and, per class, stops) processes an ended Claude session left behind | every class report |
| Stuck agents | names background agents of this session with no output for procwatch.stuckMinutes (reuses the silent-agent-nudge detection); warn only |
20 min, cooldown 15 min |
| Resource watch | names a process under a live session using >= resourceWatch.cpuPercent for cpuWindowSeconds, or memoryMb; system swap and memory pressure |
90 % for 120 s, 4096 MB, 8192 MB swap |
| Disk watch | free space of the project, HOME and temp volumes against a warn and a critical floor (GB and percent); names the biggest build/cache directories as a suggestion; before heavy commands at critical | warn 20 GB / 10 %, critical 5 GB / 3 %, block off |
What is an orphan. Claude Code puts CLAUDECODE, CLAUDE_CODE_SESSION_ID and CLAUDE_PID (the session process) into the
environment of everything it starts. A process is a candidate only when it carries the marker, it is reparented (its parent is
init or gone), its owner CLAUDE_PID is not a live Claude session command that started before it (a recycled pid counts as
gone), no ancestor is a live session, it matches a class and the class's minimum age, and it is not protected (the live engine
under ~/.anti-hall/ah-engine*, the plugin's hooks and companions, any Claude plugin cache). A process whose environment the
system will not show is not marked and is never touched. Classes: dev_server, test_runner, build_daemon, mcp_server,
shell_task, other (first match wins); children = true classes also list the descendants of a root. The owner's own classes go in
procwatch-classes.toml in the engine state directory (example: plugins/anti-hall/engine/examples/procwatch-dev.toml).
A kill is polite signal, procwatch.grace_ms, a fresh re-read of that one pid (same start time and command), then the forced
signal; one pid at a time, never by pattern, at most procwatch.max_kills_per_run a sweep. The MCP class reports what the
SessionEnd MCP reaper (a separate switch) would select, plus more; a test keeps it a superset.
Telemetry. Impact kinds orphan_candidate, orphan_kill, resource_warning, stuck_agent_warning, disk_warning and the
counter procwatch_events (labels kind and class). The sweep writes procwatch-report.json in the state directory (cost_ms, process
count, candidates, kills, recent warnings) which the advisory reads; the sweep's own cost on this Mac is about 50 ms for 990
processes with an orphan scan (release), and the resource-only sweep between scans reads the process table once.
Crate. sysinfo 0.39.6 (exact pin, released 2026-07-09), feature system only: the process table with parent, start time,
CPU, memory and environment, plus swap. It adds sysinfo, objc2-core-foundation and objc2-io-kit to the macOS graph (60 to 63 crates)
and nothing on Linux beyond itself. Disk free space is libc::statvfs (no extra crate); the macOS footprint
(proc_pid_rusage) and pressure level (sysctlbyname) are libc calls. ps is not parsed anywhere.
Per-platform differences handled (one interface, cfg(target_os) behind it, fixtures for both):
| Concern | macOS (arm64 and x86_64) | Linux (x86_64 and aarch64) |
|---|---|---|
| CPU % | per-core percent (100 = one core busy, above 100 for threads). The first reading of a process is 0 and is ignored; a warning needs every sample of the window. Apple Silicon: the percent is of one core's time whatever the core kind (performance or efficiency), so the same percent is less work on an efficiency core; the thresholds are per-core percent, not work | same semantics |
| Memory | physical footprint (proc_pid_rusage, compressed pages included, matches Activity Monitor); the resident size is the fallback |
resident set |
| Swap and pressure | swap from sysinfo; kern.memorystatus_vm_pressure_level (1/2/4) |
swap from sysinfo; /proc/pressure/memory some avg10 (PSI), absent on kernels without it (then no pressure reading) |
| Environment of another process | KERN_PROCARGS2, own user only; system (SIP) binaries show none. No environment means not marked, so never touched. Lineage fallback (parent chain to a claude command) is used for the resource watch, where the process is still attached |
/proc/<pid>/environ, own user (or root), NUL separated |
| Start time and age | seconds since the epoch from the system, no ps time formats |
same |
| Reparenting | to launchd (pid 1) |
to init/systemd, or a subreaper; WSL2 init is pid 1 or a relay: "parent is pid 1 or gone" covers both |
| Rosetta | an x86_64 process under Rosetta is listed and sampled like any other | n/a |
| Disk | statvfs; several APFS volumes share one container's free space, so volumes are told apart by device id and each is reported with its own path |
statvfs; tmpfs reports its own limit |
| Signals and nice | kill, setpriority (its which argument is int on macOS, unsigned on glibc: the libc constant has the right type on each) |
same calls |
Scheduler¶
The engine runs its own jobs on an internal ticker; nothing outside it (cron, a hook, a session) has to trigger them
(D33). The jobs ship in schedules.toml; schedules.json in the state directory can change or disable one, or add one
that uses a known action ({"jobs": {"maintain": {"every_ms": 3600000}}}); it is read when the daemon starts, and job
definitions in the config database are planned (D18). A shipped job's interval is a setting (schedule.maintain_ms,
schedule.backup_ms, telemetry.snapshot_ms, spool.drain_ms) read through the layered config on every planning pass,
so setting it in config.toml, settings.json or the environment takes effect without a restart; 0 pauses the job.
| Job | Does | Default interval | Runs as |
|---|---|---|---|
maintain |
size control (D26) | daily (schedule.maintain_ms) |
a subprocess, killed with its process group at its timeout |
backup |
a scrubbed backup (D27) | off (schedule.backup_ms = 0) |
a subprocess |
metrics_snapshot |
metrics snapshot and rollups (D51) | a minute (telemetry.snapshot_ms) |
in the daemon |
spool_drain |
applies spooled writes (D24) | a second (spool.drain_ms), started only when the spool file is non-empty (schedule.idle_gate_actions: an empty spool starts no thread and leaves no record) |
in the daemon |
procwatch |
process watch: orphans, resource use, report (see Process watch) | 30 s (schedule.procwatch_ms) |
in the daemon |
agent_tick |
one agent-tracker tick (see The agent tracker) | a minute (schedule.agent_tick_ms) |
a subprocess |
Every finished run records the CPU time of the threads that ran it (cpu_us, cpu_ms in schedule list, and the schedule_cpu_us counter (label job); a subprocess job's own CPU is not in it), so each job's cost is measurable without a profiler.
- Timing. The ticker sleeps until the next job is due (at most
schedule.tick_ms). Each next run is one interval after the current one starts, plus up tojitter_ms, so jobs do not run in step. - No double runs. A job never overlaps itself. A persisted job's next time is committed to
hot.dbbefore its run starts, so a restart (or a crash) never runs it twice; runs a killed daemon left open are markedinterrupted. - Missed windows. After the machine slept or the engine was down, a job set to
catch_up = "once"runs once, then one interval later; a job set to"skip"waits for its next window. Never once per missed window. - Timeouts, retries, cooldown. A run past its
timeout_msis stopped (a subprocess job is killed with its process group; an in-process one is recorded as timed out and the job waits for it before running again). A failed run is retried with exponential backoff (retries,backoff_ms,backoff_max_ms), then the job cools down (cooldown_ms). - History. Every run of a persisted job, and every failed run of the others, is kept in
hot.db(ah-engine schedule history);maintainforgets runs older thanretention.schedule_runs_s. - Agent jobs. A job of kind
agentis meant for a session's mailbox; until that lands (planned, D45) each of its runs is recorded with the statusplanned(D45), never as a failure.
The agent tracker¶
The engine follows every agent it can find and measures it, so a hung, looping or token-wasting agent is noticed and a quiet one is
reminded. It never kills, stops or edits an agent: it warns and reminds. Everything below is in agent_tracker.toml; the three
switches are agents.tracker (the whole feature), agents.reminders (queue nothing, only record) and agents.ownerNotify (default
off: the owner channel).
Waking an idle coordinator (#256). A reminder reaches a session through hook output at its next turn, which never comes while it
sits idle. The route target wake (a row of agent_tracker.targets: to names whose session, via how it is delivered) also writes
the reminder to the session's wake feed, and the Monitor agents wake-watch --auto (armed from monitors.json at SessionStart; off
with agents.wakeWatch) prints it as one [agent-wake] line, which wakes the session. It reads one small file and costs no tokens
while quiet; its stamp is what monitor_unarmed reads, so a live main or workspace session whose watcher is down (the harness starts it once and a
Monitor lives at most 30 minutes) is told in one line, with the exact Monitor command and timeout_ms, to re-arm it (rate-limited by
cooldowns.monitor_unarmed, silent for limits.monitor_grace_ms after a session is first seen). With the switch off (agents.wakeWatch for a main session, devswarm.wakeWatch for a DevSwarm workspace) it is told
once instead (monitor_off). Counters: monitor_rearm_prompted (re-arm lines queued) and monitor_rearmed (sessions whose watcher came back after one). Codex has no Monitor tool and is never asked; it keeps its cron and hooks. Two signals exist for it: idle_open_task (a subagent or workspace finished its turn with a task open and was silent
limits.idle_open_ms) and watched_exit (a background shell command an agent started has ended). Both fire once per state change
(once in agent_tracker.cooldowns); hung, looping, token waste and a stale heartbeat go to the same channel. A new target or
route is config; only a new kind of delivery needs code. The Codex port has no Monitor tool, so it keeps the queue delivery.
What it follows. Main Claude Code sessions, their subagents and background tasks (the transcripts under ~/.claude/projects),
agents known only by a heartbeat file (~/.anti-hall/agents/<id>.json, the file the Node watchdog reads), and DevSwarm workspaces
(descriptor, plan and wake-watch lock under ~/.anti-hall/devswarm; inert when that directory does not exist). Where the Claude Code
CLI's claude agents --json works it adds the host's own busy / waiting / blocked state and whether the process is gone. That source
is a bounded subprocess, probed once per Claude Code version (the result is cached; the version it was verified on, 2.1.295, is in
the config and shown by agents status), and any failure falls back to the transcripts. Human-formatted CLI output is never parsed.
What it measures. Per agent, read incrementally from a byte offset: input, output, cache-read and cache-write tokens (a message
repeated on several transcript lines is counted once), tool calls, errors, file edits, commits, passing test runs, plan or task steps
done, the last activity, the declared step, background shell commands and the wake paths armed. Progress units weigh a commit,
a finished step, a passing test run and a file edited for the first time (agent_tracker.weights).
Signals (thresholds in agent_tracker.limits): hung (a running turn with no activity: 20 min, 45 min while a tool call is
unanswered), looping (the same call 5 times in the last 30, the same file edited 9 times, the same error 4 times), token_waste
(600k tokens in 30 minutes with no progress unit; cache reads count 10%), drift (under 8% of the declared step's words appear in
the recent edits and commands), heartbeat_stale (a running heartbeat older than 20 min), monitor_unarmed (no live wake-watch for the session;
the session needs a live child (a running subagent or background shell, limits.monitor_min_bg = 1, #614; otherwise monitor_nag_suppressed{reason=no_live_child} counts the held-back line); for a DevSwarm workspace the wake-watch lock is missing, older than 2 minutes or its
process gone, which is the same rule inbox tick applies to watcherArmed).
Reminders. A flag must hold two ticks before a reminder. Each signal has a cooldown and a daily cap per agent, a tick has a cap,
and an agent with 3 undelivered reminders gets no more; a held-back reminder is recorded once per cooldown with its reason.
agent_tracker.routes says where each goes: to the agent itself, to its coordinator (a subagent's parent session, a workspace's
parent over the mesh, the newest main session for a heartbeat), or to the owner notices file.
The honest limit. The engine cannot wake an idle session. A queued reminder reaches a session at its next UserPromptSubmit or
PostToolUse, through the engine-only scripted check agent-reminders (plugin JavaScript, engine/logic/agent-reminders.js, which
advances a line cursor beside the queue and records the delivery). A DevSwarm workspace is reached through
agent-tracker/mesh-outbox.ndjson, the seam the mesh action layer takes nudge rows from. What lets an idle session wake at all is an
armed Monitor, cron or scheduled wake, which is why a missing one is a signal and its reminder carries the exact command.
Telemetry. Kind agent (schema in telemetry.fields; identifiers and numbers only): series (a sample per agent every 5 minutes:
tokens, tool calls, progress, flagged), signal (raised, with the number it tripped on), reminder (queued per channel, or held
back with the reason), delivery (a hook put it in front of the agent), outcome (recovered with the seconds since the reminder,
false_positive for a flag that cleared on its own while the agent made progress, unrecovered after outcome_timeout_ms,
cleared). ah-engine telemetry summary carries detail.agent: signals by name, reminders by channel, held back, recoveries and
the mean recovery time, false positives, and the tokens flagged agents burned. agents status prints today's totals from the
tracker's state file. The series is also kept in agent-tracker/series.ndjson (cut by age and size). The Node heartbeat watchdog is
the non-acting witness: a unit test runs it on the same heartbeat fixtures and requires the same stale set.
Limits. A session closed mid-turn looks hung until the CLI listing reports its process gone. Drift is a word-overlap heuristic against the declared step (a TodoWrite or TaskUpdate item, or the DevSwarm plan step); it is off for an agent that declares no step. The Jev Loop / WaitKind / StepMap verdicts of the evidence sweep are not an input yet.
The Jev lane¶
Jev is TypeSafe's "System One" decision model, reached through the Vercel AI Gateway or TypeSafe's own API. It is optional and off by default: with it off, missing, over budget or failing, every caller gets its own deterministic baseline, which is exactly what it would get without the lane (D35). Anything a deterministic rule can decide never goes to Jev (D34); only judgement calls do.
- Questions. A Noul question is yes/no (the answer is true when the reported probability is at least a half, and the confidence is how far from a half it is); a Choice question picks one labelled option. The request body is written byte for byte as the Node client writes it, after the one outbound scrub that redacts secrets (tokens, keys, URLs with credentials, emails, long opaque runs).
- Vendors and keys. The primary vendor is
jev.transport; an optional backup (jev.fallbackTransport) is tried once, inside the same time budget, after a timeout, a network error, a 5xx, a 402, a 429, or a 400 or 403 that names an exhausted balance. A rejected key (401) is never masked by the backup. Each vendor has its own circuit breaker: after three consecutive eligible failures it is skipped for five minutes, then probed once. A key goes only to the vendor it was entered for, only in the Authorization header; a redirect is never followed and a proxy variable is never used. A test endpoint override is honoured only for a loopback host (127.0.0.1,[::1], orlocalhost, which is rewritten to the literal so it is never resolved), and the connection is made through a resolver that returns only loopback addresses. - Modes. Each integration (the table in
jev.toml, with the defaults from the Node settings schema) isoff,shadoworon.shadowconsults Jev and logs what it would have changed but never changes an outcome.onapplies the call's trust rule:add-blockmay turn a non-blocking baseline into a block;advisorymay supply a label or an advisory. Jev never removes a block or an advisory, and it is never the only safety gate (D36). The Noderelax-blockrule is observe-only here. - Cost of being off. A disabled Jev costs a call one settings snapshot and nothing else: no hash, cache lookup, network, thread or log write.
- Budget, queue, cache. A call has a time budget (default 1.5 s, at most 3 s) covering connect, request and body. A
caller either waits for it (
ask) or queues it and moves on (ask_async: a bounded queue, a worker thread started on first use, a full queue answered with the baseline). Answers are cached by content hash, bounded to 500 entries, in the same file the Node hooks use (~/.anti-hall/cache/jev-assist.json, Node's shape and its read-merge-rename protocol, DECISIONS 1.93), so a text asked by either side is asked once. An entry the engine writes also names the vendor chain (vendors, models, endpoints), so one session's answer is never served to a session that would have asked someone else, and an answer from a test endpoint override is never cached. - The log. One row per decision in
~/.anti-hall/logs/jev-assist.ndjson, in the row shapejev reportreads: hashes, verdicts, confidences, latencies, costs and the reason a call produced nothing; never prompt text, never a key. It rotates at 2 MB. The daily rollups and the spend budget watch the Node client also writes are planned (D38). - The evidence gate (owner rule J1). A model is asked, Jev or Haiku through the cascade, only when the concrete evidence a
confident answer needs is in the call. For the supervisor integrations
devswarmWaitKind,devswarmLoopanddevswarmStepMap(src/jev/evidence.rs, configured per integration injev_evidence.toml;ah-engine jev evidenceis the entry point a supervisor calls with a pack of facts and sections), a decision goes: mode (anoffintegration writes nothing), then deterministic rules (a done, archived or held child is never asked about; running CI, an unanswered question to the parent, a report newer than anything received or a usage-limit pause mean waiting; a commit or progress in the last 60 minutes means not looping; one step in progress with no sequencing word, or a summary that quotes a step's text, is the step), then sufficiency (requiredminimums per integration: wait-kind needs 5 tool calls, 1 assistant text and mesh coverage; loop needs 10 tool calls; step-map needs 2 steps, a 15-character summary and an earlier summary that reported a step), then, for loop, a candidate check (the same command and error three times with no commit, or a revert: the model only confirms it). Only then is the labelled pack (FACTS, then line-numbered sections such as[tool_calls.3], capped per section and in total) asked: wait-kind and loop go to Haiku directly (alias fromjev.judgeModel,daily_capper integration per UTC day, the answer must cite a line that exists or it is discarded), step-map goes through the shared Jev layer and its cascade (cascade.escalate_below0.8 for it; the cascade stays off until its own switch is turned on). Modes are untouched: nothing here enables an integration, and ashadowintegration's answers are logged but never actionable. Hook-blocking paths never wait on Haiku. - The evidence sweep (
jev_sweep). The engine gathers the facts the gate needs; Node no longer asks these three questions.src/jev/sweep.rsruns as the scheduled jobjev_sweep(everyschedule.jev_sweep_ms, 15 minutes; a subprocess, so a timeout kills any model call it started) or by hand asah-engine jev sweep. For each child with a plan file (~/.anti-hall/devswarm/plans) and each of the three integrations whose mode is notoffit reads the plan, the end of the child's own transcript (tool calls, texts, errors, usage-limit text),git logof its worktree, the CI runs of its branch (the GitHub CLI) and the mesh store (what the child sent and was sent), builds the facts and sections, and hands them to the gate, which writes the decision row. A question whose subject has not changed is not asked again withinsweep.limits.reask_ms. The sweep acts on an answer only when the integration isonand the gate called it actionable (src/jev/sweep/act.rs, as Node's supervisor did): WaitKind attaches its verdict (stuck, or waiting on CI/owner/peer) as ajevnote to the child's idle and stall warnings indevswarm/stray/<key>.json; Loop attaches to the burn warning, else the stall warning, and aloopinganswer with neither adds Jev's own advisoryloopwarning (counted againstdevswarm.strayWarnMax); StepMap writesinferred_stepinto the plan under the plan lock (the plan label shows~#Nwhile no step was reported). Loop needs 0.9 confidence. The supervisor rewrites the stray state each pass, so the sweep keeps the last acted-on note per subject and puts it back. Each effect appends the supervision log events Node wrote (jevonce per subject,warnfor the advisory warning). Loop counts the same error text repeating on the step as well as repeated commands and reverts. Hold, the stall window and the warning cap are read through the settings layer (devswarm.heldPartitions,stepStallMin,strayWarnMax: environment,settings.json, plugin option, default). The realtime layer's snapshot (archived, paused, the linked PR's CI) is used when the per-child sweep has it. Everything tunable is injev_sweep.toml. - GitHub realtime (
ghrt, feature #20). Independent of DevSwarm: the repos followed are the git repos of the working directories of the user's live sessions. The daemon records thecwdof every hook it answers (at most once pergithub_rt.note_every_msper directory, inghrt/cwds.jsonunder the engine state directory); the scheduled jobgh_poll(a subprocess,schedule.gh_poll_ms, 20 s) drops directories older thancwd_ttl_ms, resolves each to its repo root,originslug (hosts inremote.hosts; any other remote is listed asnot_githuband never asked about) and branch (a detached HEAD asks for no pull request, only its commit's checks), and polls what is due. Calls aregh api -iwithIf-None-Match; the answer is read from the status line, never the exit code (gh 2.102 exits 1 for a 304). Per repo: the pull requests of the branch, then (open) the pull request, its reviews and the branch rules that name the required checks, then the check runs and workflow runs of the head commit. Cadence by state:poll_running_mswhile checks run,poll_idle_msfor an open pull request,poll_nopr_mswith none,poll_done_msonce merged or closed. A push is noticed by stat: the repo's HEAD, branch ref, remote-tracking ref (refs/remotes/origin/<branch>) andpacked-refs(resolved throughrev-parse --absolute-git-dir --git-common-dir, so linked worktrees work); a moved remote ref polls at once and, forpush_watch_ms, a commit with no checks yet reads as running. A local commit alone does not poll. Rate limits: every response'sX-Ratelimit-*is kept; calls in the window are held tobudget_pctof the limit (the real limit once seen,assumed_limitbefore), and belowmin_remainingnothing is called until the reset. A 403/429/5xx waitsRetry-After(capped bybackoff_max_ms), orbackoff_msdoubling per repeat; a 403 withremaining: 0waits for the reset; any other 403/404 puts that repo aside forpoll_error_mswithout holding the others.ghmissing, not logged in or offline are states shown bygh status, retried afterauth_retry_ms/offline_retry_ms, with no output and no error from the job. Measured, not assumed: a 304 answered from an ETag does not moveX-Ratelimit-Used(10 consecutive 304s on 2026-10-08: used stayed 16; the 200 after them took it to 17), so 304s are not counted in the budget (github_rt.count_304 = 0); the poller records theuseddelta of every answer by kind (gh status, sectionmeasure) so this stays checked on every machine. Edges (CI red or green on a commit, pull request merged or closed, changes requested, approved, conflict) are compared against the status of the previous complete poll of the same branch (the first sight is a baseline and raises none), deduped by repo, kind and commit or pull request insideedge_cooldown_ms, and kept inghrt/edges.json(max_edges). The rules (how an answer reads as a summary, a repo's status, the edges between two statuses, an edge's text, the statusline pieces, the polling cadence) are the plugin scriptengine/logic/rules/gh-rt.js, called throughscript::call_fnwith the settings it needs; the poller keeps the plumbing. Consumers:ah-engine gh status|segment; the engine-only checkgh-rt-advisory(UserPromptSubmit, plugin scriptengine/logic/gh-rt-advisory.js, fallback no-ophooks/gh-rt-advisory) tells each session about the edges of its own repo once, only for the kinds inadvisory_kinds, newer thanadvisory_max_age_ms, at mostadvisory_max_per_promptper prompt, with a per-session cursor file; owner notifications are opt-in (notify_kindsandnotify_argv, both empty by default; substituted text has shell metacharacters removed). Everything tunable is ingithub_rt.toml;settings.jsonsectiongithub_rtoverrides it (e.g.{"github_rt": {"enabled": false, "budget_pct": 5}}). Merge readiness (feature 4). When the pull request of a followed branch becomes ready (open, not a draft, CI green on its head with every required check present, no changes requested, approved whenready_require_approval, no conflict, GitHub'smergeable_stateinready_ok_states, not behind its base whenready_require_up_to_date; the rule isghReadyingh-rt.js) areadyedge is recorded once per head commit (ledger keyready:<repo>#<number>:<sha>,ghrt/ledger.ndjson) and told to the sessions of the repo whenready_notifyis on. Withready_auto_merge(default OFF, owner rule: no auto-merge; turn it on with{"github_rt": {"ready_auto_merge": true}}insettings.jsonor the engine config file) the engine then re-checks every condition live and runsready_merge_argv(gh pr merge <n> --repo <slug> --merge --match-head-commit <sha>, never--admin, so branch protection and required reviews still decide; GitHub's refusal is logged asrefused), once per head commit (keymerge:<repo>#<number>:<sha>, claimed in the ledger before the command runs). Each notice and merge is in the action log (ah-engine telemetry actions merge_ready) with its inputs, outcome and latency, andready_followupchecks the merge afterwards: red checks on the merge commit, or a commit that reverts it, are mistake signals (base_ci_red_after_merge,merged_then_reverted). Without a GitHub remote orghit does nothing. - Evidence telemetry. One row per gate decision in
~/.anti-hall/logs/jev-evidence.ndjson(emptied past 1 MB):phase(rule,skippedorasked),source(rule,jev,haiku,none),reason(insufficient,rule-skip,no-candidate,daily-cap,bad-evidence-ref,low-confidence,shadow,no-answer), therule, thelabel,confidence,evidenceRef,present(the facts that had a value) andmissing(the required items below their minimum, asfact:min), thechildkey the caller gave, andms. Direct Haiku calls also leave the usualjudge-calls.ndjsonrow. Never prompt text. - Parity.
parity/run-jev.jschecks request bodies, headers, decisions, log rows, settings and the scrub against the Node client (ah-engine/parity/run-jev.js). The deliberate differences (relax-block, atrueadvisory baseline, no row for an off call) are asserted separately.
Reliability and safety¶
- Hard budget. The client enforces a total deadline (default 2 s) with a watchdog thread;
hooks.json's own timeout is the last safety net. - Fallback, never a silent allow. A truncated, empty, corrupt, late or busy reply, an open breaker or a crash loop all run the Node hook (D11). Replies are length-framed and checksummed.
- Breaker and crash loop. Five failures in a minute open the breaker for a minute; four daemon deaths in ten minutes
stop respawning for half an hour. Both are recorded and reported once per session. A binary that exits at once reports no
death, so the starts are counted too: six daemon starts in a minute (
client.spawn_n,client.spawn_window_s) trip the same stop. Events from before a trip or a reset never count toward the next one, and the stop ends early when the binary is replaced by a different one. - Damaged binary roll-back. The daemon records its binary's sha256 once it has stayed up
daemon.healthy_after_s; a binary that did so is copied tobin/ah-engine.good. The installers (ah-hook install,ah-hook update) record the sha256 they installed as the expected one. When the installed binary differs from the expected sha256, has never run healthy and is failing (a crash-loop trip, orrollback.fail_nhook-wrapper failures inrollback.fail_window_s), the thin client (ah-hook integrity) renames it tobin/ah-engine.rolledback-<UTC time>-<sha8>(never deleted) and restores the known-good copy. A binary that ran healthy, or that matches the expected sha256, is never touched.rollback.on_mismatch = 0turns it off.ah-hook integrity statusshows what is known. - Resource caps. Bounded worker pool and queue (overflow answers busy, which means fallback), a per-request CPU budget,
an RSS cap that restarts the daemon cleanly,
nice, and per-session and per-project rate limits. - Security. The socket is mode 0600 in a private 0700 directory the daemon owner-checks; the peer's uid is checked;
the daemon opens no network connection (only the opt-in
ah-engine jev askandjev-setup statuscommands do, and only when Jev is on); payload text is never executed; state is partitioned per project. - No deletion. The engine deletes nothing outside its own state directory.
Configuration and data files¶
Tune in the plugin files; the engine only runs them. Every setting, table, message text, dispatch row and rule ships with
the plugin in plugins/anti-hall/engine/ (defaults/*.toml, listed by defaults/index.toml, and rules.json), is updated
with the plugin, and is read by the engine AT RUN TIME. Nothing of it is compiled into the binary (a test scans the binary for
the shipped texts), so tuning a hook, a rule or a message is an edit of a plugin file and never a rebuild.
How it is loaded:
| When | What happens |
|---|---|
| start-up | the daemon finds the plugin root (below), reads and validates every file (a malformed, undocumented or duplicated entry, a bad hook row, or a setting this engine version reads that the plugin lacks, is rejected with a reason code), and writes one small validated snapshot cache (defaults.cache) into the state directory |
| a defaults file changes | the daemon polls the files (config.watch_ms, settled for config.debounce_ms), validates the whole set, and swaps in the new snapshot atomically: no restart, in-flight requests finish on the old one. An invalid edit keeps the last good snapshot and logs defaults_invalid with the reason code (parse, doc, missing_key, ...); status shows it as config.last_error |
| the plugin is updated | a new directory at the same path shows as a changed file set; a new path arrives with the next request (AH_ENGINE_PLUGIN_ROOT, set by the wrapper from its own location, or the host's plugin-root variable) and is adopted when its index is newer than the active one, so two plugin versions in use at once cannot flip the daemon |
| the thin hook client | reads the snapshot cache (one file, only the keys a call asks for) instead of parsing 28 files; it parses the plugin files itself only when the cache is missing or belongs to another plugin root |
| an edited file is invalid | that file (or that setting) falls back to the last-known-good copy, then to the pristine copy (Layered failover and self-heal) |
| nothing loadable | no plugin root, or the edited, last-known-good and pristine copies all fail: the engine answers "unavailable" (exit code 75, which the wrapper turns into the Node hooks), logs why (defaults.error in the state directory and stderr) and never falls back to values compiled into the binary, because there are none |
The plugin root is the first of: AH_ENGINE_PLUGIN_ROOT (an explicit choice: if it has no engine/defaults/index.toml the load
fails), CLAUDE_PLUGIN_ROOT, PLUGIN_ROOT, the root recorded in the snapshot cache, a development checkout found by walking up
from the executable. The rules file is the AH_ENGINE_RULES override, else rules.json in the state directory when the user put
one there, else the plugin's engine/rules.json. The few fixed names this needs are in src/bootstrap.rs.
Files:
| File | Holds |
|---|---|
index.toml |
not settings: the list of the defaults files, in order, and the sub-directory (hooks.d) of further files |
limits.toml |
limits, buffer sizes, phrases and short texts that were literals in the source (the late additions of the no-compiled-config sweep) |
engine.toml |
environment variable names, paths and file names, daemon and client limits, project store caps, health policy, hook adapter, socket protocol |
messages.toml |
every message the engine produces (failure hints, advisories, replies, errors, command-line text) |
git.toml |
every table, limit, setting name and block message of the git check |
task_guards.toml |
switches, limits, file layout and messages of the task checks and their shared helpers |
advisory.toml |
the advisory layer (GitHub #225): fixed text once per session, state tables once per content change, per-session soft and hard caps per advisory kind, the rule-fallback rate limit and the metric names counted under advisory in status --json |
inference.toml |
the unsupported-inference scan of the speculation guard (guards.inferenceCheck): the causal connectives, the word lists, the identifier and stem rules and the block text |
roles.toml |
the role matrix (which role may run which engine verb), role detection names, the engine skill areas and their size budgets, and the role note texts; the anti-hall:engine skills are generated from it and the registry (ah-engine/scripts/gen-engine-skills.sh) |
broad_kill.toml |
the broad-kill guard: blocked commands, the scoped pkill -P form, lookup patterns, wrappers and shells it looks through, and the block texts |
devswarm_parent.toml |
the DevSwarm Primary prompt hook (devswarm-parent-inbox, for a Primary inside a git checkout): the event-log kind of a deferral to the Node hook, the maintainer-notice feed name and the hook's texts |
devswarm_role.toml |
names, switches and message templates of the devswarm-child-role and devswarm-parent-gate checks |
small_guards.toml |
patterns, switches, limits and messages of the small Bash guard ports and their shared helpers |
verify_first.toml |
the verify-first protocol texts (copied byte for byte from verify-first-core), the switches and message of the verify-first and fable-availability checks |
mcp_reaper.toml |
the session-end MCP sweep: its patterns, init names, age floor, cap, grace period, commands and audit log texts |
guards_v1.toml |
the v1.0 guard defers answered in plugin JavaScript (lane L07): the bounded host-spawn limits and interpreter probes of api-guard, the hook process stand-ins (hook_proc.*), the host key order of the output-verify scan, the Codex apply_patch parser and the guards' texts |
hardening.toml |
the hardening bar's own limits and wording (tests/it/hardening_bar.rs): what the engine must survive and the budgets it is held to |
guards_l12.toml |
the v1.0 main-thread half of edit-guard and the pending-marker half of orch-on-spawn (lane L12): the delegation, edit-allowlist, handover and unparseable-patch texts, the handover path parts, the DevSwarm descriptor and worktree locations, the inline-work counter's names, and the claim lease, suffixes and token of the spawn-time delivery |
units.toml |
the background-service units (ah-engine units, lane L08b): the unit names, launchd and systemd file shapes, the service-manager command lines, the ledger and lock files, the report words and the switch maintenance.unitsHeal |
agent_tracker.toml |
the agent tracker: every threshold, window, weight, route, cooldown, pattern, word, path and text, the Claude Code CLI source and the agent-reminders check |
host_proc.toml |
the generic process primitives (ah.proc.*, ah.sleep): the listing, age and service-manager commands and their bounds, the start-time forms, the signal and sleep caps |
task_tracker.toml |
the task-tracker directive and reminder texts, the untracked-request evidence gate, the open-tasks line (off by default), the Jev label question and the demand-metrics file |
realtime.toml |
the realtime watch facility: backend, poll interval, debounce and ceiling, queue and directory caps, the filesystem types that are polled, SQLite side-file suffixes, the mount-table path, and the latency and CPU targets |
judge.toml |
the judge calls the engine makes itself: the local Claude CLI client, the speculation-judge prompts and evidence limits, the mesh-triage worker's prompts and budgets, and the Jev-first cascade (thresholds, prompts, telemetry words) |
spawn_context.toml |
paths, switches, limits, messages and the orchestration text of the spawn/path context ports |
nudges.toml |
the nudge escalation ladder (#516): the severity class table (nudges.kinds), thresholds, the master switch (nudges.enabled, ANTIHALL_NUDGES), state path, block texts and telemetry step words |
- Nudge signals (GH #515, #517, #518). The agent tracker raises four more signals; each reaches the ladder through agent-reminders and has its own kind. stalled: a running child agent with no call in flight and not hung, whose transcript offset, tool calls, commits, changes, edits and progress line did not change for nudges.stall_limits.quiet_ms, or whose progress line repeated with no outcome for repeat_ms; the reminder names the agent, its age and its last 2 distinct progress lines (kind stalled_agents). Work the transcript does not show is never a stall (R-stuck, #535): once an agent was quiet for nudges.stall_limits.cpu_probe_pct percent of quiet_ms, the CPU of the process tree below its session (its own pid, else its parent's; the session process itself excluded; the table is read at most once a tick) is compared with the last reading, and a rise or fall of cpu_step_ms restarts the quiet window; an agent with a background build in flight (burn.doubt, bounded by its max_ms) or waiting on CI (agent_tracker.patterns.ci_wait) is never reported, but only while the wait is current: a CI command in the call history is no wait, one counts only when it is the background task still outstanding or was issued within ci_wait_fresh_ms, and a CI wait older than ci_wait_max_ms stops exempting. When two or more running agents stand below one parent and one has no pid of its own, the parent's tree is shared: its CPU is credited to none of them (counted nudge_signal step cpu_shared), so a quiet one is still reported. Each case is counted by stall_exempt by reason (building, ci_wait, cpu, cpu_unread when ps gave nothing, and future_ts_ignored when a stamp the exemptions read was later than the clock: it is no evidence, its window restarts, declared in nudges.stall_exempt). Standing exemptions of other tracker signals are counted by agent_signal_exempt (labelled by signal and reason): drift is not judged against a step task a live child of the session owns, and is judged against the task's current subject; idle_open_task never fires on a DevSwarm Primary row (#972). A child once seen stopped (an answered TaskStop, a terminal notice) stays stopped after the stop leaves the launching transcript's tail window, until it writes again past agent_tracker.limits.stop_resume_ms; counter agent_stop_sticky (labelled by how: recorded, held, resumed). A snooze a parent gave a child (agents nudge <child> snooze) holds the tracker's nag reminders about that child (agent_tracker.snooze_holds); burn, ended-task and no-work rows still flow. A hold reminder the session answers with a task update that writes the task's blocker fields (blockedOn rewritten or saved again, owner or status; a subject fix is no answer) confirms that hold for nudges.hold.confirm_ms (#961 tracker side). A child's successful message to its lead (agent_tracker.tools.report, recipients and the shortest report in agent_tracker.report_to) is an outcome (weight report), and merge and deploy commands are matched per shell segment, credited only when the call's success proves the segment ran (agent_tracker.ran_delims); a report text a child already earned credit for earns nothing again (counter agent_report_repeat). The ladder's Stop block for the kind is a hard block (class escalate, after 2 fires, at most max_blocks = 3 per episode: a row key with the default nudges.max_blocks = 0, no bound; a due block past the bound is counted as the step capped, also when it was already pending in a state written before the bound held), and delivery.act carries a nudge-ladder row (SendMessage, TaskStop or an agent spawn within 8 tool calls). idle_no_agents: an idle main session with open, unblocked, unassigned tasks (the host task list, nudges.idle_wake) and no agent running for idle_ms, sent as a wake row to the session itself. false_claim: an idle child whose last line claims running work (nudges.idle_wake_claims) with no call in flight, no build or background shell and no output for claim_ms. underparallel: an idle main session under the agent cap with unassigned tasks while an agent runs, or gap lines of its last reply (nudges.parallel_gap_phrases) that no task covers: "dispatch them in parallel" (kind parallel_dispatch). Switches: settings nudges.stall (on by default since R-stuck; the kill switch is nudges.stall false or ANTIHALL_NUDGES_STALL=false), nudges.idleWake, nudges.parallel. Counter nudge_signal by step (sampled, stalled, claim_checked, claim_flagged, idle_wake, parallel); the tracker's signal events count each raise and its resolve (acted on). Kind hooks were checked against the hooks' real texts: a kind with count_blocks also counts its hooks' blocks (the cap and routing denies, task-guard's idle Stop block), and a Stop another hook blocks holds the ladder block to the next Stop. |
|
inject_gate.toml |
the injection gate: its settings (context.injectGate*), what it recognises in the hooks' output, its state bounds and wire words |
ctxbudget.toml |
settings tables, state paths, limits and messages of the context-budget gates (limit-conserve-inject, auto-handover, auto-handover-pause-nag, compact-advice-guard) |
response_guards.toml |
patterns, switches, limits and messages of the four response-correctness ports (speculation-guard, speculation-judge, claim-ledger, output-verify-guard) and their shared helpers |
sibling_sweep.toml |
phrases, hedge and tool lists, messages, limits and the follow-through window of the sibling-sweep check; all read at call time through the config layers, so editing a settings file changes the next call |
handovers.toml |
layout, patterns, caps, severities, messages and search weights of the handover brief tree, read by handover-hygiene.js; a changed rule rebuilds every day brief on the next index run |
script.toml |
scripted check logic (D88 spike): the on/off switch, where check scripts and the owner override live, and the per-call time, heap and stack limits of the embedded QuickJS-NG runtime |
script_shared.toml |
the shared includes of the scripted checks (a script compiled once per worker interpreter instead of once per check that builds on it), the message for an include with no evaluator, and the metrics of that path; kept apart so script.toml and telemetry.toml stay at their pinned bytes |
agent_controls.toml |
patterns, switches, limits and messages of ask-guard, silent-agent-nudge, stale-agent-stop-note and the transcript agent scan they share |
codex_handover.toml |
patterns, switches, limits, file names and messages of the handover and Codex hook ports and the JavaScript-behavior helpers they share |
devswarm_gates.toml |
switches, role and mode variables and the command pre-filter words of the DevSwarm child gate, reply tracker and drain checks |
mesh.toml |
the mesh store reader (D45 S0): store and marker file names, the SQLite busy timeout and page cache, the preview length, the read byte cap and the --last bounds; and mesh.engine_writes (off, shadow, on), the switch of the stage 2 mesh writers |
mesh_write.toml |
the mesh store writers (D45 stage 2, ah-engine mesh <ah-hook mesh argv>): Node's store names and statements' column list, the busy retry, the per-workspace lock budget and steal limits, the identity file and variable names, argv flag names, output texts, and the shadow log, scratch and snapshot settings |
devswarm_rt.toml |
DevSwarm realtime state (lane B1): the mode (on by default; the Node supervisor is a non-acting witness), stale / stall / reconcile / restart-grace times, the edge-log cap, the paused signal (none until an owner-confirmed crash fixture proves it), the app-database column names and the PR and CI status words, and the witness and shadow-log settings |
devswarm_act.toml |
the DevSwarm action layer (src/dsact, script engine/logic/act/devswarm-act.js): which kinds may start automatically (Node's auto-archive, poke, escalate) and which only on the owner's request (archive, create, merge, an approved delete), the allowed hivecontrol verbs with their minimum versions and argv templates, the bounded-call timeouts, the autoArchive / nudge settings (same keys, tiers and defaults as Node), the ledger, plan and log file names, the delete plan's expiry and caller rule, and the error texts |
devswarm_sup.toml |
the DevSwarm supervisor duties (lane l7, src/dssup): the switch mode (witness / engine), the tick and its budget, the double-run guard, the sweep lock, the duty table (native or a Node function run bounded), Node's cool-down settings, the verdict mirror, recover's refusals and texts |
devswarm_ingest.toml |
the native ingest drain (lane l7b, src/dssup/ingest): the switch mode (witness / engine), the projects, the monitor call and its breaker ladders, the lock and the legacy-consumer probe, the delivery WAL, quarantine and heartbeat files, the batch shape and hash, the Node witness and every log line |
devswarm_recon.toml |
the native port of DevSwarm reconcile and the sweep tail (lane recon, src/dssup/recon): the Node witness dispatcher and its limits, the normaliser, the side-file names and thresholds (sweep state, resume marker, name cache, repo-unknown marker, active snapshot floor, start-up sampling), the registry-heal texts, the archived-rows and twin-descriptor texts and file names (slice S7; the switch devswarm_sup.sweep_tail_mode, node by default) and every reason a unit is handed back to Node |
| devswarm_recon.toml | the native port of DevSwarm reconcile and the sweep tail (lane recon, src/dssup/recon): the Node witness dispatcher and its limits, the normaliser, the side-file names and thresholds (sweep state, resume marker, name cache, repo-unknown marker, active snapshot floor, start-up sampling), the registry-heal texts, the drain's witness stub and environment, the reconcile budget, retry and result texts, the Node snippets of the handed-back steps and every reason a unit is handed back to Node |
| devswarm_wire.toml | the DevSwarm wiring (src/dswire): the per-action cutover switches devswarm_rt.act.<action>.executor, the thread's wait and sweep gap, which changes trigger sweeps, the git time limit, the watched directories, the advisory / statusline / Jev-dirty settings and texts, the owner verbs and their role matrix, and the fact-reader file names |
| devswarm_cli.toml | the DevSwarm CLI verbs ported from ah-hook mesh that need no store (src/meshw/simple.rs): the verb list in dispatch order, the help table (synopsis and side-effect note of every verb), the texts, flag names, limits and paths of help, the unknown-command answer, skip, archive-ignore, archive-unignore, gate-intent, notice --list, plan, scope, gate, workspaces, logs, wake-directive, ready-check, app-state, app-sync, done, primary, relay, archive-request, nudge, supervision-report, sync-ui and retention, and the Node witness's scratch paths, links and program |
| command.toml | every table, pattern and limit of the command check (heavy verbs and patterns, light exceptions, wrapper grammar, cloud CLI grammars, write-scan markers, the defer triggers) |
| commands.toml | the command registry data |
| claim_evidence.toml | the claim-evidence guard: its two switches, claim and push patterns, the evidence commands, the hold texts and the block/log mode |
| reply_length.toml | the R-style reply-length guard: its switch and two limits, the allowances for code and tables, the detail patterns, the form (block or note), the texts and the reply_style_* metrics |
| pair_rule.toml | R-pair (task-pair-guard): the switches guards.pairRule and guards.pairRuleByTaskId, the limits, the counter label texts, the message texts and the three pair_rule_* counters |
| afk.toml | AFK mode: its settings (afk.enabled, afk.idleDetect, afk.idleMinutes, afk.promptCommands, afk.enforce, afk.measure, afk.conciseCodex), the flag and state file names, the typed command words, the marker and digest patterns and texts, the rule and reminder texts, the reply limits and hold cap, the afk and back commands and the seven AFK metrics |
| flags.toml | the description of every command-line flag (flag.<name>), and the flags of other programs the source mentions (docs.external_flags); a test fails when a flag has no entry |
| schedules.toml | the scheduled jobs (maintain, backup, metrics snapshot, spool drain) and the scheduler settings |
| telemetry.toml | the metric and impact-kind registries, the savings method and the telemetry settings (telemetry.enabled, telemetry.flush_ms, telemetry.retention_days, table sizes and window defaults) |
| storage.toml | database file names, SQLite durability settings, the writer queue and group-commit window, the in-memory layer, the spool, retention, backups |
| config.toml | config layering: file names, watch and debounce timing, boolean tokens, restart-only settings, config messages |
| layers.toml | rule and settings layers (shipped, user, project): directory and file names, size and count caps, the project-allowed rule fields and settings (with their stricter direction), the locked rules, the rule actions in order of strictness, and the layer messages |
| transcript.toml | the transcript index: window and update caps, kept-fact counts, status sets, registry size and idle time |
| gitcache.toml | the git cache: git invocations, timeouts, TTLs, signed file names, the bypass environment, messages |
| jev_sweep.toml | the evidence sweep: the jev_sweep job and interval, where plans/transcripts/mesh stores are read, windows and limits, the transcript, git and CI commands and patterns, the evidence line words |
| actions.toml | the action log and its report: file names, rotation, the window, the features and the names of their mistake signals |
| github_rt.toml | GitHub realtime: the gh_poll job and interval, cadences, rate budget and backoff, which repos, the git and gh commands, endpoints, header and pattern names, status words, edge and advisory kinds, notification and statusline settings, the words |
| jev_evidence.toml | the evidence gate for the supervisor integrations: per-integration backend, daily cap, pack caps, required evidence, rules and question, the pack headings, the Haiku system prompt, the evidence log and its words |
| jev.toml | the Jev lane: vendor endpoints and models, budgets, breaker and fallback timing, the integration table with its default modes, cache and log limits, key-file rules, messages |
| setup.toml | the operator helper commands (jev-setup, capability-scan, harvest, briefing): the shared limits, the marker grammar and table widths, the briefing's scan limits, the settings lock timing, and the message texts, which are the Node scripts' own |
| settings_cli.toml, operator.toml | the operator tools settings, defect and statusline: the generated settings registry (parity/gen-settings-cli.js), the caps, enums, texts and colors, and the shadow sampling rates |
| operator_cli.toml | the verbs auto-handover-config, dispatch-report, finding-dedup, coordinator-work-baseline, the jev-setup review verbs and test, and the native answers of defect for the cases that used to defer: every text, name, number and the findings question; the rules are engine/logic/rules/operator-cli.js and rules/coordinator-work-baseline.js |
| jev_report.toml | the jev-report command: the report's thresholds (call and label minimums, the KEEP and REMOVE rates), every text of the report (the Node script's own, word for word), the log and cache file names and the credit-balance reasons; the rules that use them are the plugin script engine/logic/rules/jev-report.js |
| wake_watch.toml | the idle-wake Monitor devswarm wake-watch: its settings entries, tick and error back-off, lock timing, file names, the closed vocabulary of refusals and every event and diagnostic line (the Node watcher's own, word for word) |
| slcfg.toml | the status line helper commands phase, install-statusline and uninstall-statusline: their message texts (the Node scripts' own), file names, test-guard markers and the installer shadow's copy lists |
| update_cli.toml | the update and install-codex commands: marketplace, cache and registry paths, git and harness arguments and timeouts, the offline-failure patterns, every status and summary text, the Codex file names and the merge patterns |
| update_post.toml | the post-pull stages of update: the stage table (order, status key, plugin files needed, DevSwarm gate, one-time markers, the answers for a closed gate, a stage already done for the version and a deferred stage), the Node stage subprocess snippets and the status key order |
| dispatch.toml | the dispatcher's settings and the hand-maintained per-event table of hook entries (the table of record: the plugin's hooks.json files are generated from it) |
| hooks.toml | the hook configuration: defaults of [events.<Event>] and [entries.<id>], the when predicate vocabulary, the plan outcomes and their messages |
| hooks.d/*.toml | optional: per-batch [events.<Event>] / [entries."<id>"] defaults (one file per batch of ported hooks, so parallel lanes do not edit a shared file) |
| prompt_emit.toml | switches, limits, patterns and messages of the prompt-emission checks (verify-first, idle-agent-sweep, emit-dedupe-reset) and the emit-dedupe store they share |
| session.toml | the session-maintenance checks: switches, cache and ledger file names, time limits, baselines, claim patterns and messages |
| spawn_guards.toml | switches, limits, paths, memory-tool grammar and messages of the swarm-guard and devswarm-comms-guard ports |
| migrate.toml | the layout of the state migrate and doctor --repair work on (paths, file-name patterns, retention windows, the migration registry, read limits) and the report texts, which are Node's byte for byte |
| migrate_settings.toml | the settings schema as the settings.json migration reads it, generated from settings-schema.js (parity/gen-migrate-schema.js; a test fails when the two differ) |
| doctor.toml | the doctor's finding texts, the table of live self-tests (check, payload, environment, expected outcome, finding texts) and the flags it does not handle yet |
| session_gates.toml | switches, latch files, windows and the default-migration key list of the jev-weekly-scorecard, jev-review-reminder and repair-on-reload gates |
Each setting is a table with value, doc and optionally env (an environment variable that overrides a numeric value for
one process), min, max and unit. Code reads them through one module; a test fails the build if a tunable, table or
message is written in Rust instead (no_hardcoded_tunables), and another if code and defaults disagree. User-level
overrides are layered on at start and on every change (below); persisting each version in storage is planned (D18).
Layered failover and self-heal¶
The engine files in plugins/anti-hall/engine/defaults/ are meant to be edited, so a bad edit must not take the guards down.
Every load, per file and per setting, tries these layers in order and each layer passes the same validation:
- edited: the plugin's
engine/defaults/(what you or an update changed); - last-known-good:
<state dir>/defaults.lkg/<stamp>/, a copy of every edited file that last validated in full, stamped with the engine version, plugin root and plugin version (older stamps beyonddefaults_load.lkg_keepare removed); - pristine: SHA-verified bytes from the plugin's read-only
engine/defaults.pristine/, generated bundles for non-pinned files and loose copies for the four pinned files; - Node: if all three fail the engine answers "unavailable" (exit 75) and the wrapper runs the Node hooks.
Each fallback is logged (defaults_fallback with a reason code) and marks the engine degraded; the state is shown by
ah-engine status and advised once per session.
ah-regen generates the pristine bundles from engine/defaults/ in sorted path order, packing entries greedily within the
configured doctor.pristine_bundle_bytes budget. Files are named BUNDLE-0000, BUNDLE-0001 and so on.
The AH-PRISTINE preamble declares the format version and an opening delimiter absent from every payload. Each entry has
its own opening delimiter, a tab-separated relative path, byte length and SHA-256, the exact payload bytes, and a closing
delimiter. Independent framing preserves the neighboring entries when a header, length or delimiter is damaged. Bootstrap constants define the format version and file naming.
flags.toml, roles.toml, script.toml, telemetry.toml and index.toml stay loose beside index.sha256. The manifest
pins those pristine bytes separately from the shipped defaults.
The loader accepts a SHA-verified loose twin for compatibility. For bundled fallbacks it selects the entry matching the
manifest's pinned or shipped SHA, including when an overlay update leaves an older numbered bundle behind. The process reuses
the bundle index while the plugin root and bundle metadata match. ah-regen --check checks the generated bundles and manifest
for staleness without writing. Doctor and other read-only verbs also leave the pristine tree and state untouched.
Self-heal. A setting the edited files lack (an older file after an engine update, or a deleted table) is taken from the pristine
copy for that run and reported. The automatic heal then appends the missing table to the edited file, keeping the existing text
byte for byte, after backing the file up once beside it; the new text must parse and read back as the pristine value or nothing
is written, and a second run finds nothing to add. The automatic heal never writes into a version-controlled checkout;
ah-engine config heal does it on request, including there.
Config layering and hot-swap (D18)¶
Highest layer first, as ah-hook settings get resolves it:
- Environment: the setting's own
envvariable (numeric settings). settings.json:~/.anti-hall/settings.json(orAH_ENGINE_SETTINGS), the file the Node settings code reads. The settingsection.keyissettings[section]thenkey, flat or dotted-nested, coerced like Node (trimmed, bad values fall through, numbers clamped, booleans accept1/on/true/yesand0/off/false/no).config.tomlin the state directory (orAH_ENGINE_CONFIG): the engine's own file, written as[daemon]thenqueue = 32. It is strict: an unknown key, a wrong type or an out-of-range number invalidates the file.- The shipped default.
The daemon watches both files (polling, config.watch_ms, debounced by config.debounce_ms) and on ctl reload/SIGHUP.
A change is parsed and validated first and swapped in only if valid; a request takes one snapshot when it starts and sees
that version throughout. An invalid or unreadable file keeps the last good config and logs config_invalid; a deleted
file falls back to the next layer. A corrupt settings.json counts as invalid here (Node reads it as empty), so a
half-written edit cannot swap the daemon to defaults. Settings in config.restart_only keep their running value until
the next start and are listed as pending_restart (the settings a daemon thread reads once when it starts belong there:
realtime.*, devswarm_wire.wait_ms, devswarm_wire.reconcile_min_gap_ms); an automatic handoff for them is planned (D18).
Every read of a setting answers the effective value (#195): defaults::num, text, list, raw and the helpers built on
them read the owner's file layers first. The daemon installs each config snapshot it swaps in as that overlay; any other
process (a command, the hook client, the status line) reads both files once at start and resolves only the keys they name.
The environment layer is read by defaults::num itself, as before. defaults::shipped and defaults::get/all are the
schema (the shipped value), which is what the layers resolve over. Settings in config.locked cannot be changed by the files:
the names of the environment variables (the contract between the wrapper, the client and the daemon), the settings that say
where the config files are, the two lists themselves, the dispatch table dispatch.hooks_* (hooks are configured through
[events.*]/[entries.*], whose guard rules stay in force) and the command registry cmd.*; config.toml naming one is
invalid (locked), settings.json naming one is ignored. A value derived from settings (defaults::Cache, a compiled pattern) is rebuilt after an overlay change.
Rule and settings layers: shipped, user, project¶
Rules and settings come from three layers, lowest first: the shipped plugin files, the user (host) files under the
base directory (~/.anti-hall), and the project files under the session's project root. The environment stays on top for
settings. Every layer MERGES into the one below it, key by key: tables deep-merge, a rule with a new id is added, a rule with a
known id has only the fields it names replaced. No layer replaces another's file. All of it is read from the files at run time
(layers.toml holds every name, limit and text) and re-read when a file changes.
| Layer | Rules | Settings and hook sections |
|---|---|---|
| shipped | engine/rules.json in the plugin |
engine/defaults/*.toml |
| user | rules.json in the state directory (merged by id; it used to replace the shipped file) and <base>/rules/*.toml |
settings.json, then config.toml (see above) |
| project | <root>/.anti-hall/rules/*.toml |
hooks.project_file (<root>/.anti-hall/engine.toml): [events.*], [entries.*] and the settings listed in layers.project_settings |
A rule file holds [[rules]] tables with the fields of rules.json (id, events, tools, field, pattern, action
message, paths, plus enabled = false to switch a lower layer's rule off). A new rule needs an id and an action.
The project root is the git top level of the payload's cwd, found by the same resolver the other checks use; a nested
repository or a submodule is its own project, and a repository at the home directory does not read the user layer as a project.
The layers of the projects are cached per root, so two projects on one daemon never see each other's rules, and a project value
never enters the daemon-wide defaults::* overlay.
The project layer is repository content, so it is untrusted: data only (check and options run engine code and are
refused), size and count capped, schema validated, and tighten-only:
- it may add rules, raise a rule's
action(context<warn<deny) and change itsmessage; lowering the action, switching a rule off or changing any other field of a lower layer's rule is refused; - it may set only the settings in
layers.project_settings, each only in its stricter direction (up,down,on,off,add) relative to the value below it; locked settings (config.locked) are refused whatever the direction; - it may loosen a rule or setting only when the USER layer lists it in
layers.project_may_loosen(a project file cannot grant itself this).
The user layer may loosen anything except the rules in layers.locked_rules and the locked settings. A refused entry is logged
once (layer_notice) and skipped; an invalid, oversized or non-regular file (a symlink, a pipe) is ignored whole with one notice.
A bad layer never fails a request: the shipped rules and settings always apply. ah-engine config explain shows which layer a
value came from and what was refused.
Not yet request-scoped: the daemon's internal reads of a setting (defaults::num and friends) answer the user-level value, so a
project's setting value is visible to config explain and to request-scoped consumers (cfgstore::resolve_for_project) but is
not yet applied inside every check.
State lives in ~/.anti-hall/ah-engine/ (override with AH_ENGINE_DIR): hot.db and archive.db, the write spool
spool.log and its spool.quarantine, the backups/ directory, the optional schedules.json, the event log,
failure.json, the breaker and crash-loop markers, the run marker, the start counter and the per-session advisory stamps. The user's rules file is
rules.json there (merged over the shipped rules by id), or the path in AH_ENGINE_RULES (then the whole rule set).
A daemon found gone without a clean exit is logged as crash (counts toward the crash-loop stop, marks the engine degraded, writes
last_crash) unless the operating system booted after its last sign of life (its newest breadcrumb, or its start): then it is a
system_restart (a reboot, an OS update, a power loss), reported under health.system_restarts in status --json and counted
nowhere else. health.system_restart_slack_ms is the margin.
Scripted check logic and the host API (D88)¶
A check whose decision logic is a rule, a pattern or a text does not live in the binary. It ships as an editable plugin script
(engine/logic/<check>.js, helpers in engine/logic/lib/*.js, owner override ~/.anti-hall/logic/, a file of the same name
wins) and runs in an embedded QuickJS-NG interpreter, one runtime per worker thread. The engine keeps only the generic,
bounded primitives a script calls through ah.* (the raw functions are ahHost, shaped by lib/00-core.js (00-ah)). Patterns, limits,
tables and texts are defaults/*.toml entries the script reads with ah.cfg(key); a file edit, a plugin update or an owner
override applies on the next call. A script that cannot answer (an exception, a stack overflow, the time or heap limit, a
missing file) follows one rule: a check with a Node twin defers to it, an engine-only check blocks on a guard event and allows
quietly elsewhere. Time a primitive spends blocked (a child process, a lock wait, a Jev consult) is not script time.
Checks that decide in a script today: api-guard, inbox-read-guard, orch-on-spawn, verify-first-subagent,
verify-first-full, fable-availability, edit-guard, git (the git guard), git-audit (its PostToolUse audit, built on git.js through script.includes; command.js and git.js are compiled once per worker interpreter, script.shared_includes), swarm-guard, sibling-sweep, handover-hygiene, task-lifecycle-log, the three session gates (jev-weekly-scorecard, jev-review-reminder, repair-on-reload), merge-side-pick, scan-throttle, merge-gate, dispatch-tier, model-routing, speculation-guard, speculation-judge (every path that needs no model; a reply that needs the model defers to the Node hook), silent-agent-nudge, task-guard, tasklist-guard, ask-guard, phase-tracker, failure-root-cause-nudge, output-verify-guard, the six session-maintenance checks (version-alert, devswarm-version, claude-cli-version, repo-self-drift, defect-nudge, progress-prune), emit-dedupe-reset, precompact-snapshot, handover-resume, limit-conserve-inject, auto-handover, command (command-guard: the heavy-command gate, its carve-outs, the Bash edit parity and the DevSwarm and stash guards; its script is also the shared command classifier classifyBashWork) and coordinator-work-guard (the main-thread work window, built on command.js through script.includes; it classifies natively and keeps the window, metrics and trips files in the bytes and with the lock protocol the Node hook uses). command.js runs the Node functions of command-guard as they are, over a small compatibility layer (fs, path, os, process, require) that answers their file-system, path and settings questions from the primitives below; what only the Node hook process can see (its own working directory, a home it has to ask the system for) marks the call unsure and defers. Each has a
verify-first-full, fable-availability, edit-guard, git (the git guard), git-audit (its PostToolUse audit, built on git.js through script.includes), swarm-guard, sibling-sweep, ask-guard, phase-tracker, failure-root-cause-nudge, output-verify-guard, the six session-maintenance checks (version-alert, devswarm-version, claude-cli-version, repo-self-drift, defect-nudge, progress-prune), emit-dedupe-reset, precompact-snapshot, handover-resume, limit-conserve-inject, auto-handover, dispatch-tier, model-routing, speculation-guard, speculation-judge (every path that needs no model; a reply that needs the model defers to the Node hook), silent-agent-nudge, task-guard, tasklist-guard, stale-agent-stop-note, claim-ledger, idle-agent-sweep, auto-handover-pause-nag, compact-advice-guard and session-end-mcp-reaper. Each has a
golden corpus (tests/golden/<check>.jsonl, frozen from its compiled port before the port was removed) that the script must
reproduce byte for byte, and parity/run-golden.js replays the same corpus against the Node hook. A case may place events relative to the moment it is replayed ({NOW-<ms>}, {ISO-<ms>}, {DATE} in any string) and set normTs so clock readings, instants and calendar days in the answers and the watched files compare as {TS}, {ISO} and {DATE}; "node": false marks a case the Node hook cannot be given (a plugin root it resolves itself).
The host API (every primitive is read-only except the scoped writes, bounded, and returns null instead of throwing for an
ordinary failure):
ah. call |
What it does | Bounds |
|---|---|---|
cfg(key), cfgNum(key), cfgLive(key) |
a shipped defaults entry; a numeric one with its clamps; the value through the owner's editable layers (settings.json, config.toml, shipped) |
cfgLive is cached per file stamp and defaults generation |
env.get(name), env.passwdHome() |
a variable of the hook's own environment (never the daemon's) | |
useHome(path) |
make an absolute directory the home of the rest of the call (settings, skips, scoped state), as a Node hook whose os.homedir() fell back to the passwd home sees it |
absolute paths only |
settings.bool/enum/num/numStrict/str(key), settings.skipped(guard) |
the effective value of a setting entry through the settings chain (numStrict drops a value below the entry's minimum, as the Node settings.get does; str is a free-text setting); an unexpired skip |
|
settings.bool/enum/str/num(key), settings.skipped(guard) |
the effective value of a setting entry through the settings chain (str: the first non-empty tier, trimmed); an unexpired skip |
|
fs.isFile/isDir/size/readText/realpath/realpathEx |
file tests and reads (realpathEx tells a missing path from one that could not be examined) |
reads capped by script.read_max_bytes |
fs.lstat(path), fs.kind(path), fs.mtimeMs(path) |
{kind: file / dir / link / other, size, mtimeMs, mode, nlink} of the path itself (links not followed), null when absent, {kind: "error", code} when it exists but cannot be examined; the kind alone; the modification time |
|
fs.sha256File(path), fs.readHeadHex(path, n), uid() |
SHA-256 (hex) of a regular file; its first bytes as hex; the numeric user id | script.read_max_bytes |
fs.rangeSha1Hex(path, from, n) |
SHA-1 (hex) of the lowercase hex text of exactly n bytes of a regular file from byte from (what sha1(readRangeHex(..)) gave, without moving the bytes into the script); null when unreadable or fewer than n bytes exist |
script.read_max_bytes |
fs.readdir(path), fs.listDir(path), fs.readlink(path), fs.readTail(path, window) |
sorted entry names (readdir is capped, listDir is not and sorts by bytes); a link's target text; the last window bytes as text with the partial first line dropped |
script.readdir_max entries, else null; script.read_max_bytes |
fs.tailLines(path, window, crlf, needles) |
the lines of that same window (split on \n, or on \r?\n when crlf), only those holding one of needles when any are given, so a script that skips every other line never pulls a 0.5-1.5 MB window into the interpreter |
null when unreadable |
path.*, re.test/find/findAll |
Node path functions; linear-time regular expressions (flags i, m, r) |
one process-wide cache shared by all workers, bounded by script.regex_cache_bytes (estimated) and script.regex_cache_max, least recently used dropped first |
exec(prog, args, {cwd, env, timeoutMs}) |
one allow-listed program (script.exec_programs, today git) in its own process group with the request's environment plus env on top, no stdin |
script.exec_timeout_max_ms, script.exec_max_calls per call, script.exec_output_max_bytes per stream; null on a timeout or a start failure |
state.writeAtomic/appendFile/op(root, op, rel, text) |
the scoped writes: rel is relative to the home directory (or an absolute root named by op) and must start with script.write_root; op is write, after_reply (atomic, landing only once the reply was delivered), append, mkdir, remove or rename (the new path is the text) |
no absolute path, no .., no link below the root, script.write_max_bytes, script.write_path_max |
state.readText(rel), state.remove(rel), state.sweep(dirRel, prefix, ageMs, max) |
the scoped read; delete one regular file (an absent file is the goal state; a link or directory is refused or left); delete the old regular files of a state sub-directory whose name starts with a non-empty prefix, oldest first | reads capped by script.read_max_bytes; script.sweep_max_remove deletions per call |
state.lock(rel, group, waitMs), state.unlock(handle) |
the cross-process lock file (Node's lock protocol) under the same root, timings from the defaults group <group>.lock_* (waitMs replaces the group's wait) |
script.lock_max_held locks at once, taken in the script's fixed order; any still held when the call ends is released by the engine, newest first |
state.prune(prefix, keep), sessionState.get/probe/update(ns, key, fn) |
the state-file retention sweep of one writer prefix; the per-session state files the Node guards share, with an atomic locked read-modify-write | only that prefix, older than the TTL, throttled |
transcript.tailLines/agents/turnText |
the last lines of a file with byte offsets; the agents a transcript shows as running (id, description, launch input, launch / resume / last-seen times, output file); the current turn's assistant text | script.tail_max_bytes; a line JavaScript might read differently answers unsure |
transcript.tasks(path, variant, window, wide) |
the task list of a transcript tail, rebuilt as the Node hooks rebuild it (guard: task-guard, state: task-state, scan: the task part of tasklist-guard's pass), completed from before the window by the bounded subject backfill |
the window you pass; where Node's wall clock would decide, or a record only JavaScript reads exactly, the answer is unsure. The lines that can matter (a task tool use, a result that answers one, a line neither JSON parser reads) and the lines of the widened search that decide it are kept between calls (transcript.tasks_cache_*, mem.tasks_cache_*), so a call reads only the appended bytes; the answer is the one a read of the whole window gives |
transcript.agentScan(path, tailBytes, ignoreStops) |
every agent a transcript tail shows launched, adopted or live as a teammate, in launch order, with the ids whose terminal evidence stands and the teammates sent a message they have not reported on since (pending: name, agent id, send time, last report, last sign of life, live); ignoreStops skips a TaskStop with no result yet |
unsure for a relative path or a line JavaScript might read differently; null when unreadable |
transcript.grep(path, bytes, needles, re, flags) |
the lines of the last bytes of a transcript (a cut first line dropped, lines split on \n alone) that contain every string of needles and, when re is given, match it: {lines}, null (unreadable) or {unsure} (a relative path, or more lines than script.grep_max_bytes). The script filters megabytes natively and reads only the few lines that matter |
|
transcript.countProof(path) |
the running agents with what the count rests on: {rows: [{id, description}] \| null, seen: [launched ids], windowBytes} (rows null: the count cannot be trusted, and seen and windowBytes say why), or {unsure} |
|
jev.cachePeek(hash) |
what the dispatch-tier annotation reads of the shared Jev cache entry under hash: null (none), {unsure} or {answer, confidence} (each null when the entry holds no string or finite number) |
|
transcript.evidence(path, windowBytes) |
the text evidence of the end of a transcript, record by record, in order: user prompts (p), tool results (r), hook attachments (a), tool-call inputs (i) and the non-blank assistant text with its message id (t), each as the plain string the Node hook builds |
transcript.evidence_max_bytes window, transcript.evidence_max_chars of text in all; unsure for a relative path or a line JavaScript might read differently; null when unreadable. The items of every complete line are kept between calls (transcript.evidence_cache_*, mem.evidence_cache_*), so a call reads only the appended bytes; the answer is the one a fresh read of the window gives |
transcript.evidenceWalk(path, windowBytes, payloadText), transcript.walkHas(which, needle), transcript.walkNumbers(which, src, flags, strip) |
the claim ledger's walk of the evidence done in the engine, so the window's items never enter the interpreter: evidenceWalk answers null (unreadable), {unsure} or {truncated, walked, lastText, toolsThisTurn, toolsAtEnd, evidenceChars, withLastChars} (lengths in UTF-16 units; a reply payloadText already holds is left out of the evidence); walkHas (is needle in the evidence or withLast text) and walkNumbers (the sorted numbers it spells, as re.numbers) answer about the walk that call made, and throw when it is gone so the check fails open |
same items and transcript.evidence_* limits as transcript.evidence; kept walks under transcript.evidence_walk_*, mem.evidence_walk_* |
re.numbers(src, flags, text, strip) |
the distinct finite numbers the matches of a regex spell in text (the characters of strip removed from each match first), sorted ascending, from one native pass |
the text the script passes |
transcript.teammates(path, tailBytes), transcript.codexAgents(path, tailBytes) |
the named in-process teammates (Claude) or multi_agent_v1 agents (Codex rollout) the tail shows finished but never stopped or closed, with the time each went idle |
script.tail_max_bytes; unsure as above |
proc.list() |
the process table {rows: [{pid, ppid, cmd}]} (the configured ps command); null when the listing failed, timed out, was cut or was too big, never an empty table for a listing that did not arrive |
hostproc.list_timeout_ms, hostproc.list_max_bytes |
proc.ages(pids), proc.managed(pids) |
{ages: {pid: seconds}} (elapsed seconds, else the start time read in local time; an unknown age is left out) and {platform, managed: [pids], unverifiable} (the pids the platform's service manager owns: the launchctl listing on macOS, the control-group file on Linux; unverifiable when the listing failed); both {unsure: true} for an output too big, a start time in a form the engine does not read, an ambiguous local time or a zone the engine and the hook might read differently |
hostproc.probe_timeout_ms, hostproc.probe_max_bytes |
proc.signal(pid, forced) |
send the polite or the forced signal to ONE pid the script names after its own checks; true when sent. Refused (false, nothing sent) for a pid below hostproc.min_signal_pid, not an integer that fits the system call, the engine's own process or its parent, a pid the script's own proc.list() in this call did not show, a forced signal for a pid not first signalled politely in this call |
hostproc.signal_max_per_call signals per call |
sleep(ms) |
wait; the wait is not script time | hostproc.sleep_max_ms at a time, hostproc.sleep_total_max_ms in a call |
jev.ask(spec), jev.mode(id), jev.deadlineLeftMs() |
one question to the Jev lane, detached or (with sync) answered, with its trust, cache key, judge label, compare verdict and project; with relax Node's consultRelax (asked here only while the integration is on, else detached and null); with full the whole decision {outcome, jev, baseline, confidence, confident, ms, backend, reason, hash, changed}; the mode of an integration; the time left of the request |
the budget is clamped to the time left (jev.relax_sync_cap_ms for relax); time spent waiting is not script time; the caller owns the policy (count, total time) |
jev.recordOutcome(id, hash, outcome, source, projectFrom), jev.cacheHas(hash) |
a decision-log row joining a later observed result to the decision with that hash; whether the shared answer cache holds an answer under a hash (null: a file only JavaScript reads) |
no row for an empty id, hash or outcome |
homeGuard(), project.root(cwd), jev.enabled() |
{status: ok / guarded / unknown, home}: the home directory state files may live under (guarded: a test run against the real home, so no state is read or written); the project root of an absolute working directory as the handover finder resolves it (null when it depends on Node's own directory, git or a core.worktree setting); whether the Jev master switch is on |
|
plugin.versions(root), sys.cores() |
{running, registered, unsure}: the version of the plugin manifest under root and the one the host's registry names; the CPU count as Node's availableParallelism() reads it (null when the engine cannot read it the same way) |
|
clock.now(), clock.local(ms), home(), pid() |
the engine's one clock (injectable for tests); the local calendar fields and zone offset of an instant; the request's home directory; the engine's process id | |
sys.memory(), platform(), repo.context(dir, ancestor), scrub(text), sha1(text), fnv(text), contentHash(parts), log(kind, text) |
machine memory figures; the operating system; the checkout around a directory (ancestor: the Node missingPath: 'ancestor' option, default on); the engine's outbound secret scrubber; hashes (SHA-1, 64-bit FNV, the Jev content hash); a line in the event log |
|
settings.get(key, dflt, root), text.maskQuoted(text), shell.heredocAt(cmd, i) |
the settings chain with the caller's fallback; the speculation guard's quoted-text masking; the heredoc opener parser |
A script that is not a check at all is a rule set: engine/logic/rules/<name>.js defines global functions that engine code calls with
script::call_fn("rules/<name>", "<function>", <json>) and reads back as JSON (today rules/gh-rt, the GitHub realtime rules). The same
bounds apply (time, heap, the ah.* API); a call that fails gives no answer, and the caller decides what that means.
A script answers null, 'allow', 'defer', {block: text}, {advisory: text}, {exact: {code, out, err}}, or, for a routing check,
{routed: {verdict, meta: [{requested_model, parent_model, task_class, recommended_tier, selected_model, outcome, spawn_key, delegate,
blocked}]}}: the same verdict plus the route telemetry rows the daemon records before it handles the verdict. A shape of the wrong
kind, or a route row missing a field, is a script failure.
A scripted check's latency is held to script.p95_budget_us (or its entry in script.p95_budget_by_check) at the 95th percentile
(cargo test --release --test script_latency -- --nocapture). A check whose call legitimately takes longer than script.time_limit_ms (command-guard resolves repositories and runs git) has its own limit in script.time_limit_by_check.
Dispatcher¶
ah-engine hook --event <Event> [--tool <Tool>] [--host claude|codex] [--fallback-map <file>] stands in for every hook
the plugin used to register for that event (D58). Its table, dispatch.toml (hand-maintained since D87: it is the table of
record), lists each host's entries per event in combine order with the exact command, timeout and matcher, which built-in
check (today: git and the other ported guards, on PreToolUse) answers an entry, and optionally a when predicate. The
plugin's hooks.json files are generated from it (ah-engine gen-hooks, or ah-gen-fallback-list --repo .. for all of
them) and tests/it/hooks_files.rs fails on a byte of difference.
One thin trigger per event (D87). hooks/hooks.json has exactly one entry per event and no matcher:
the installed thin client ~/.anti-hall/ah-engine/bin/ah-hook <Event> (Codex adds --host codex), with the longest timeout
of the event's entries. It covers every event of the table and every event in dispatch.thin_events: all 33 Claude Code
events of the official reference except WorktreeCreate and WorktreeRemove (a WorktreeCreate hook replaces the default
worktree creation and a non-zero exit on either fails the operation, so there is no neutral pass-through; decision D87
exception), and the ten Codex events. The engine matches, filters and orders from the table and the config; an event the
table has no entry for answers the host with the neutral no-op (exit 0, no output) and the wrapper's fallback list marks it
empty. The per-hook registry the old hooks.json was (hooks/hooks.registry.json, codex/hooks/hooks.registry.json) is
generated too: nothing in the host reads it, the plugin's Node readers (doctor, briefing, hook-latency, tests) and the
manual Codex installer use it to know which hook scripts exist. A new hook is a row in the table; nothing else lists hooks.
- The entries whose matcher selects the payload are chosen the way the host chooses them: on Claude a matcher of
plain names is an exact name or list and anything else an unanchored regex; on Codex every matcher is a regex and
Edit/Writealso matchapply_patch. When nothing matches, the dispatcher says nothing and starts nothing. - Every entry without a built-in check starts at once as its Node hook, under the shell, with the payload on stdin and its own timeout. A hook past its timeout is killed with its process group and counts as saying nothing.
- The built-in checks run in the daemon (
Drequest; or in the client whendispatch.in_processis 1). An entry whose check defers, and every check when the daemon cannot answer, runs as its Node hook too (D11).--fallback-map(a JSON object of event, then hook id, to command) replaces an entry's Node command. - The results are combined the way the host combines separate hooks. Both hosts run matching hooks in parallel and
read each one's output on its own (the Claude Code and Codex hook docs, quoted in
dispatch.toml): - the first entry that exited 2 is the answer, byte for byte; failing that, the first whose JSON blocks;
- when exactly one entry said anything, its output, stderr and exit code pass through unchanged;
- several JSON answers merge:
additionalContextandsystemMessagevalues are joined in order, the strongestpermissionDecisionwins with its reason, any other field must agree, and stderr is concatenated.
Configuration of events and entries (D87). Two kinds of section, in the engine's config.toml (state dir) or a project
file (.anti-hall/engine.toml under the payload's cwd, below the user file in precedence; hooks.project_file):
[events.PostToolUse] # any event of either host's table or thin triggers
mode = "on" # on | shadow (run and log, never change the outcome) | off (skip, answer neutral); enabled = false is off
max_rules = 3 # entries evaluated per occurrence (0 = all); the rest are counted as skipped (max_rules)
budget_ms = 400 # wall budget: after it no new entry starts, running ones finish within their own timeouts
order = ["output-verify-guard"] # these ids run and combine first; an id the event's table lacks is an error
[entries."git-guard:audit"] # a table entry by id, or "PostToolUse/git-guard:audit" for one event only
mode = "shadow"
when = { field = "/tool_input/command", regex = '^git ' } # replaces the row's own `when`
Every key has a documented default (hooks.event_*, hooks.entry_*) and the whole file is validated when it is read: a bad
key rejects the file, the daemon keeps the previous snapshot and reports the error through last_error, and a one-shot
client reads the layer as empty and logs config_invalid. Guard events never become a silent allow: on PreToolUse,
PermissionRequest, Stop and SubagentStop, mode off or shadow and enabled = false are errors, max_rules must stay 0, and a
when cannot be overridden on a guard entry; mode off or shadow on a guard ENTRY is allowed only when it has a built-in check,
because its Node hook then still runs as the real decider (off skips only the engine's check; shadow runs the check beside the Node
hook and logs dispatch_shadow with whether the two agree). A project file may not configure guard events or entries at all.
budget_ms is allowed on a guard event: a built-in check's Node hook that cannot start in time fails the event closed.
The when predicate (D87). A table row or an [entries.*] override may carry when, a declarative filter that decides
per occurrence whether the entry applies (no when = it applies whenever its matcher does). Leaves: tool (a name or a
list), field (a JSON pointer into the payload, so /tool_input/file_path reads a tool-input field), setting (a boolean
switch of the shipped switch tables, such as guards.shipitGate, resolved from the request environment, then the loaded
settings.json, then the default, or one of the engine's own settings), env (a variable of the request environment,
request_env.allow only), session (first, every = N or at_least = N counters kept in memory per session with a TTL)
and transcript (a fact of the transcript index: records, compact_boundaries, sidechain_rows, meta_rows,
has_last_prompt, has_last_assistant, last_tool, terminal_agents, unresolved_agents). Each leaf takes exactly one
test (equals, in, regex, glob, exists, at_least, at_most); all, any and not combine them. Evaluation is
three-valued and an unknown answer applies the entry, so a guard is never skipped because the engine could not tell: a
one-shot client keeps no session counters and has no transcript index, so those two kinds are unknown there (the daemon
side of that is wired when a real entry first uses them). Predicates are not attached to any shipped row yet.
The plan and its telemetry. For each occurrence the plan applies, in order: the event's mode, its order, each entry's
mode, its when, then max_rules. Every entry is counted under one outcome: ran, skipped_predicate, skipped_max_rules,
skipped_budget, shadowed or off. A dispatch that skipped, shadowed or turned anything off, or ran under a non-default
config, writes one dispatch_plan event (with the config hash); the counters are the dispatch_entries metric, by event,
entry and outcome, and config --json reports the hash of the user file's hook sections (hooks_hash).
The environment (D76). A hook runs in its host's environment, not the daemon's. The client forwards the variables on
request_env.allow (defaults/engine.toml) with each V and D request, and every check runs against that
environment, never the daemon's own; a request without one gets an empty environment. The reply frame magic carries the
protocol version (AHR2), so a client and a daemon of different protocols fall back to Node.
Exact output. A check can answer with exact exit code, stdout and stderr bytes (Verdict::Exact), for guards whose
output is not the plain exit-2 block, for example the JSON block io.blockDecision produces.
What one process cannot say. The host shows each hook's additionalContext as its own reminder, with its own size
cap (10,000 characters on Claude, about 2,500 tokens on Codex); the dispatcher joins them into one value, which the
host caps as a whole. A join of several hooks' contexts over the cap is therefore not delivered as separate values: the
dispatcher logs dispatch_context_over_cap. On an event that cannot block it then spills natively
(dispatch.spill_over_cap, on by default): the contexts that fit stay inline whole and in priority order (dispatch.context_priority; the hooks of an event that cannot block are combined highest priority first, dispatch.priority_order), the rest is written
to a private file under dispatch.spill_dir in the state directory, and a last pointer line (dispatch.msg_spill_pointer)
names it, so nothing is cut and no Node hook runs; the spill is logged (dispatch_context_spilled) and counted in telemetry
as a spill event (per event in status delivery.spills_by_event; delivery.pinned_spills counts spills that had to take a context at or above dispatch.context_pin_priority). It applies only when the join is exactly the hooks' contexts joined by dispatch.context_joiner and the
file can be written; otherwise (and with the spill off) the dispatcher prints a message on stderr and exits
dispatch.defer_exit (75), asking its wrapper to run the Node hooks one by one as the host does, or, with
dispatch.defer_to_node 0, delivers the join for the host to spill. A block or decision next to an over-cap context on an event that cannot block keeps its fields; only the context is trimmed. On a guard event it never exits 75: it delivers the merged answer, and
the host spills the over-cap context itself. Delivery ledger (#312). status delivery.per_check counts per check what it decided (a message or a block), what was delivered (the reply carrying it written in time), what the agent complied with (a delivery.react tool call within delivery.react_window_calls tool calls; null for a check with no row) or ignored, and what was shed or lost (diagnostics.shed_never lists the checks that are never shed; delivery.essential_shed must stay 0 and doctor warns otherwise). The counters behind it are the metrics delivery_stage (by check and stage), delivery_lost (by check and reason), context_spills (by event) and context_spill_pinned. Per-rule funnel (B1, plan v2). The same stages split by the session's model family and the project: the metrics delivery_funnel (check, model, project, stage: decided, delivered, acted_on, ignored, lost, shed, suppressed; a shadowed entry's answer is decided and suppressed, never delivered or in a channel; past the series cap only model and project fold into the other bucket, which the report lists and flags, so no count is lost) and delivery_channel (check, channel, model, project; channels block, soft_block, advisory, system_message, stderr, plain). acted_on is the funnel's name for complied; a check's acted-on condition is its delivery.act row (tools, polarity do or avoid, a window counted in occurrences of one event, so a tool call or a turn end) else its delivery.react row, and it is by tool class only, so it is an upper bound. ah-engine telemetry funnel [--by model,project] [--window 7d] prints it (it needs the running engine; a window is the live counters less the stored hour metrics snapshot at the window start, and the report says when no snapshot is that old), and status delivery.funnel has the totals. delivery.funnel_enabled 0 stops the split. It only counts: no answer changes. diagnostics.deadline_grace_ms lets named checks start a little past the hard request deadline, and delays the cut of a scripted call of them already running by the same grace. Deadline cuts answer by policy (#463). A check cut at its request deadline (or not started past it) answers right there by its own failure policy (script.failure_mode_by_check), never a deferral to a Node hook that no longer runs; diagnostics.deadline_policy_by_check marks a check finish (never cut at the request deadline, it runs to its own script limits). Each cut is counted in status advisory.deadline_cut.<check>.<outcome> (outcome allow, allow_notice or block, the diagnostics.deadline_cut_outcome_* words). Shed tiers (#464). Past the HARD CPU limit only checks of tier optional (diagnostics.shed_tier_by_check, default diagnostics.shed_tier_default = reminder) are shed, so the rule reminders the agent needs keep answering; status budget.shed_by_session reports per session which checks were shed (bounded by diagnostics.shed_sessions_max), and delivery.per_check.<check>.shed counts shed answers per check. No Node (dispatch.defer_to_node 0). The infrastructure, spent-budget and
Stop channel (#540, plan v2 C1; stop_channel.toml). A Stop note sent as systemMessage is shown to the user and the model does not act on it (lab: 0 of 10 followed, the same as silence); sent as Stop additionalContext it continues the turn and is followed (10 of 10). With context.stopAdditionalContext on (default off; per check stop_channel.check_on / check_off, user-only text in stop_channel.user_only), the dispatcher moves a check's model-facing Stop note there on the hosts in stop_channel.hosts (Claude; Codex is unconfirmed, #559, and stays on its current channel); for the checks in stop_channel.stderr_checks (only tasklist-guard's plan-mode note) it also sends the exit-0 stderr note as context, and the engine-health advisory merged into a Stop answer follows the same switch. It keeps no state: a note moves only when the answer is not a hard block (blocked_kept), the Stop payload's background_tasks array is present and empty (no_background_field, background_pending), the combined Stop context is within stop_channel.context_max_chars (over_length), and the transcript shows fewer than context.stopContinuationLimit (K, default 3) of this channel's own continuations (Stop hook_additional_context attachments) since the last human-typed prompt, or since the start of the transcript when it has none, so an unattended run of notification turns is bounded too (over_k), and fewer than context.stopTotalContinuationLimit (default 8) continuations of both shapes together, a hard block's Stop hook feedback: entry counting here only (over_total; both limits are whole numbers from 0 to 8, a string, float or negative is ignored and the default stands, a larger number is lowered to 8 and counted as limit_clamped); a half-written newest transcript line that names the attachment counts as one continuation; a transcript that is unreadable, of an unknown shape or whose last human prompt is beyond stop_channel.tail_max_bytes is transcript_unreadable). Every other outcome leaves the answer as it is without the channel. The host's stop_hook_active flag is not used. Counters: the metric stop_channel (outcome, check, model, project), telemetry summary detail.stop_channel. The host writes its transcript asynchronously, so a continuation not yet written (and not even started on the line) is not counted; the limits bound the chain in the transcript, not to the exact entry.
panic paths that otherwise exit 75 answer by themselves: an event that cannot block skips its hooks (logged as
dispatch_no_node_skipped, one stderr line), a guard event follows dispatch.failure_mode for the path (budget and
infra closed, panic open by default; dispatch_no_node_closed / dispatch_no_node_open). Each answer is counted in
telemetry as the hook dispatcher-<path>. When one entry blocks, the advisories of the others are not shown; when several block, the
one block answered carries every block reason in table order (dispatch.reason_joiner), as the host would show the model
each of them. An empty additionalContext (a quiet turn, or a context the injection gate cut) is left out, never printed
empty. Results that cannot be
combined exactly (plain text next to another answer, a non-zero exit other than 2 next to another answer, two different
values for one field) are delivered as one answer and logged as dispatch_conflict: the JSON objects among the stdouts of
the hooks that exited 0 are merged into one line (the host reads a whole stdout as one object or as text, so two JSON lines
would lose every decision), a field set differently keeps the first hook's value, plain text next to JSON moves to
stderr, and the stderr of all hooks is kept.
Stop never blocks forever (D74). Exit 2 on Stop or SubagentStop keeps the agent running, so a fail-closed block there
that can never clear would stop it finishing. On those events (dispatch.stop_events) a payload with stop_hook_active true
fails open (exit 0, a note on stderr, dispatch_stop_open in the log), and so does every fail-closed block after
dispatch.stop_block_cap (2) consecutive ones in a session (counter files under stop-blocks/ in the state dir, reset
when the guards run fine again). For an over-cap payload the engine does not decide from a capped prefix: Node's Stop
hooks receive the full bytes first, and the cap applies only if they cannot run or make no decision. A hook's own block is
never affected.
Nudges escalate (#516). Advisories that repeat with no change stop being advisory. nudges.toml holds a severity class
table: per kind the hook ids it watches, a class (advisory counted only, escalate blocks after after fires then every
every, block = P0, blocks at the first fire) and the one required next action. The dispatcher (dispatch/ladder.rs) reads
each call's hook results before the token cuts, counts at most one fire per kind per turn and session, and resets a kind when
its hooks run quiet quiet_reset times in a row (the condition cleared). A due kind adds one decision: block to the next
main-session Stop: two lines, one emoji, the required action and the consequence. A Stop with stop_hook_active never gets
a ladder block, and any internal failure (corrupt state, a write that fails, a panic) adds nothing and is counted
(nudge_ladder_state_error by op: read, parse, write, facts, subject). The ladder is a state machine over entries (idle, counting,
pending, shown), tested in every transition. A guard's pass is read from the guard's OWN record, not from the ladder's history of it: a kind
that declares a guard (nudges.kinds: its hook, its switch, its state-file prefixes; nudges.guard_state says how they are read) holds
every ladder block at a Stop that hook let pass when its state files count a block in this session (task-guard at its own cap, with the
guard's kind switched off, with the ladder enabled after the cap, or with the ladder's state lost); no count of passes lifts that, only the
guard's own next block, its fact ending (the tasks are done) or its switch being turned off. A guard record that cannot be read blocks nothing
and is counted (facts). A kind that declares a fact (live_flags: a tracker signal on an agent; live_tasks: an open task) has it read
fresh at every Stop; the open-task fact is read from the list task-guard reads (Claude Code's task store first, taskstate.store_*, else the
transcript tail as task-guard reconstructs it, taskstate.tail_bytes), so the ladder never calls a task open or done that the guard's cap decided otherwise. A live_flags kind is kept per agent (nudges.subjects): a reminder counts for the agent its queue row names (the lines
agent-reminders took), and that agent's own signal ending (or the agent being gone, finished or dead) clears its entry (acted) whatever any
other agent does; a fire that names no agent is not counted (subject). A fact that cannot be read blocks nothing and is counted. All ladder settings are off by default: nudges.enabled
(master switch; also gates the folding below, ANTIHALL_NUDGES) and nudges.kinds in settings.json (per-kind class override, off to stop watching one). Telemetry: one check
event per step, hook nudge-<kind>, event fired, repeated, escalated, blocked, acted or ignored: the compliance
metric. With nudges.enabled on, a Stop block also carries the advisories of the other hooks in its reason (dispatch.msg_stop_advisories,
cut at a word at dispatch.stop_advisory_chars, 0 = nothing folded), because the model reads only the reason there; off, the
reason is the blocks' own.
Guards fail closed (D74). The guard events (dispatch.guard_events: PreToolUse, PermissionRequest, Stop,
SubagentStop) never turn a failure into a silent allow. The call answers exit 2 with dispatch.msg_fail_closed on stderr
(the log has dispatch_defer) when a Node hook cannot run (no runnable command, an unreadable --fallback-map, a usage
error such as an unknown host, a panic), cannot be started, is killed by a signal, or finishes with incomplete output, and
when the payload cannot be read. A payload longer than client.max_stdin skips the engine's own checks and routes the full
bytes to the matching Node hooks from the raw stdin spool; the engine fails closed only if those hooks cannot run or make
no guard decision. A hook that exits 2 (or prints a JSON block) keeps its block even if a leftover process holds its pipes
open. A payload the dispatcher cannot parse, or that names no tool, selects every entry of the event instead of none. A
hook that runs past its timeout stays the host's own discard (no decision), and is logged (dispatch_hook_timeout).
tests/it/fail_closed_matrix.rs crosses every guard event with every injected failure and asserts one invariant: exit 2 with
a message, or the result Node's hooks would give, never exit 0 with nothing printed unless a hook that ran allowed. Any
other event runs the hooks it can and logs dispatch_defer for the ones it cannot. The plugin is wired to the dispatcher on the
engine-proto branch through the thin triggers above (D75, D87).
Raw stdin spool (D87). Payloads within client.max_stdin are delivered from memory and do not touch the spool. Only an
over-cap payload needs the raw stdin spool; if it cannot be created, a guard event fails closed with a clear stderr reason,
while a non-guard event exits 0 with a stderr note and a log/telemetry record when the state dir is usable. The over-cap
spool is anonymous on Unix: it is created in the private state dir and immediately unlinked, then each Node child receives
stdin from a feeder using positional reads so children do not share file offsets. A startup sweep removes stale named
dispatch-stdin-*.tmp regular files left by older builds or unlink failures after dispatch.spool_stale_s; it does not
follow symlinks or remove fresh/non-matching files.
Parity. parity/run-dispatch.js runs every matching Node hook of an event as its own process (as the host does),
combines them with an independent model of the host (parity/dispatch-lib.js), and compares exit code, stdout and
stderr byte for byte with one dispatcher call; parity/fuzz-dispatch.js drives the merge with fake hooks. The
results are in the README of ah-engine/.
How to extend it¶
- A new check. Implement
Checkin its own module undersrc/checks/, list it inchecks::registry(), put its tables and messages in a defaults file, and port its Node source with a parity corpus (parity/). The generated reference picks it up on its own. - A new setting, message, metric or impact kind. Add the table to the right defaults file with a
doc, use it from code, then regenerateREFERENCE.md(cargo run -q -- docs --format md > REFERENCE.md). The tests tell you if you forgot. - A new command. Add its data to
commands.toml, a handler insrc/cli.rs, and regenerate the reference. - A new host. Hosts share the hook payload field names today; a host with a different shape needs an adapter
(D30). The dispatcher (D58) already keeps a table and matcher rules per host in
dispatch.toml.
Building from source¶
The toolchain (the latest stable Rust, with rustfmt and clippy) is pinned by ah-engine/rust-toolchain.toml, and the crate is on edition 2024. Dependencies are kept at their latest versions by Dependabot and the ah-engine-deps workflow (manual-run only while Linux is paused, #708); cargo deny check (ah-engine/deny.toml) and cargo audit gate licences and advisories (D84). From ah-engine/:
An offline build from the vendored source tarball published with each release uses
cargo build --release --offline --frozen. Release steps are in ah-engine/RELEASING.md.
Using a locally built binary¶
Copy your build to ~/.anti-hall/ah-engine/bin/ah-engine. The wrapper uses the binary at that path, and the bootstrap never
overwrites a binary it did not install (it checks the marker bootstrap.installed and the recorded binary sha256), so a local
build stays until you delete it. Run ah-hook integrity accept after copying it: that records it as the
expected binary and vouches for it, so a crash-looping build you are developing is never swapped for the known-good one. A binary-path override exists for the test suite only and is ignored otherwise.
Verifying release artifacts¶
Each release publishes the archives, a .sha256 per archive and SHA256SUMS, with build provenance:
The Node backup: shadow and fallback switch¶
The original Node hooks are kept as a backup outside the published plugin, in stages (shadow, then off, then deletion only with the owner's OK). Every switch, rate, timeout, path and text is a setting in nodeback.toml (the plugin's engine/defaults/ directory; the nodeback.* keys), so tuning is editing that file or the user config.toml, never a rebuild.
Stage 1, the shadow. The engine decides every hook event, as always. For a bounded share of the decision events (nodeback.shadow_events: PreToolUse, PermissionRequest, Stop, SubagentStop) it also starts a detached ah-engine shadow-run, after the answer is written, that runs the same Node hooks on their own in a scratch home (nodeback.shadow_scratch_dir) with their own timeout (nodeback.shadow_node_timeout_ms). It never changes the engine's verdict and never delays the hook; it fails silently. Engine and Node each write one row per check to the shadow ledger (shadow.ndjson in the state directory, source engine or node, verdict allow, advise or block, latency, error) and ah-engine shadow-compare pairs them: per check and per day it reports agreement, engine-weaker, engine-stricter and the errors of each side, plus what the shadow skipped. --days N, --check ID, --event NAME, --daily and --json narrow or extend it; a daily job (shadow_report, schedule.shadow_report_ms) writes the JSON to shadow-report.json.
- Mode
nodeback.shadow_mode:off,sampled(nodeback.shadow_sample_pctof events, plus every blocked event whilenodeback.shadow_sample_blocksis 1) orall. - Cost bounds:
nodeback.shadow_max_concurrentruns at once,nodeback.shadow_max_payload_bytes, and an end date (nodeback.shadow_end_date) after which the shadow turns itself off with one stderr notice. - Heat guard: no shadow run starts while the one-minute load per core is at or above
nodeback.shadow_load_max_pct, or while the daemon's own CPU budget (diagnostics.budget_cpu_pct) is breached. Skips are counted understatusaccounting asshadow/skip_load,skip_cpu,skip_busy,skip_payload.
Where the Node backup lives. The original Node code is not part of the published plugin: it was moved (with its relative paths) to plugins/anti-hall-node/, a sibling of plugins/anti-hall, so the plugin directory limits hold (sh ah-engine/tests/plugin-dir-limits.sh, limits in ah-engine/tests/plugin-dir-limits.toml). nodeback.node_dir (default ../anti-hall-node, relative to the plugin root) names it; the dispatch commands and the generated ah-fallback.* lists point at ${CLAUDE_PLUGIN_ROOT}/../anti-hall-node/.... When the directory is missing the shadow is skipped and counted (shadow / skip_no_node) and the fallback switch is a logged no-op: the engine keeps deciding, nothing blocks.
Stage 2, the fallback switch. ah-engine fallback node writes the marker file fallback.node in the state directory; while it exists the thin client ah-hook hands the call to the Node backup, which runs the original Node hooks directly instead of the engine and writes their verdicts to the ledger with source node. ah-engine fallback off removes it and ah-engine fallback status shows it (nodeback.fallback is the shipped default; the marker overrides it). The switch never flips by itself. If the engine is unreachable and the switch is off, the call still passes through with one notice (an unreachable engine only; see the Client bullet for a daemon that answers badly).
Retiring the Node path¶
The Node hooks and companions are replaced piece by piece. The policy:
- Switch a Node piece off only once the Rust path covers it and a comparison shows the engine is never weaker (replay and live witness).
- Switch off reversibly: move or unload, never delete. Files are removed only in the release that removes Node.
- Record what was switched off, when, and the exact command to switch it back on.
ah-engine status --migration lists every behaviour that is still on Node.
Node shadow witness. The witness records Node's verdict beside the engine's so the two can be compared. Switch it off by moving its root directory aside (for example to root.off-<date>); the witness script exits 0 when root is missing. Switch it back on by moving the directory back to root.
Legacy DevSwarm ingest jobs. Each project may still have a per-project launchd job (com.anti-hall.devswarm-ingest.<project>) running the Node ingest companion. The engine drains the same projects and takes the project's ingest lock once the Node job stops. To retire one:
cp ~/Library/LaunchAgents/<label>.plist <backup-dir>/<label>.plist.copy
launchctl bootout gui/$(id -u)/<label>
mv ~/Library/LaunchAgents/<label>.plist <backup-dir>/
Then confirm that the pid in the project's lock file under ~/.anti-hall/devswarm/locks/ (ingest-project-<project>.lock) is the engine's pid (~/.anti-hall/ah-engine/daemon.run) within a minute or two. If the engine does not take the lock, switch the job back on:
mv <backup-dir>/<label>.plist ~/Library/LaunchAgents/
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/<label>.plist
Troubleshooting¶
| Symptom | What to do |
|---|---|
| Hooks are slow or the engine seems absent | ah-engine status --json: look at running, breaker and crashloop. |
| An advisory says the engine stopped after repeated failures | It is already running on the Node hooks. ah-engine reset clears the stop; file an issue with the diagnostic block it printed. |
| "state directory is not writable" | Fix ownership and mode 700 of ~/.anti-hall/ah-engine, or point AH_ENGINE_DIR at a directory you own. |
| "socket path is too long" | Set AH_ENGINE_DIR to a shorter path. |
| Stop it | ah-engine stop. It starts again on the next hook call while the binary is installed; to turn it off, see Rollback. |
| Undo a bad restore | Every restore keeps the state before it in backups/pre-restore-<ms>/; restore that directory. |
hot.db keeps growing |
Run ah-engine maintain (it reports what it moved and the sizes before and after); see the retention.* settings. |
proj printed spooled <id> |
The engine was down or busy; the write is safe in spool.log and is applied when the engine runs. |
spool.quarantine has entries |
Records that were damaged or refused for good (for example a full mailbox), each with its reason; nothing was dropped. |
| The engine says it is degraded | An engine file fell back to the last-known-good or pristine copy. ah-engine config --json shows last_error; fix the edit, or ah-engine config heal for a missing setting. |
| A check misbehaves | Run ah-engine check git with the payload on stdin to see its verdict without a daemon. |
| The daemon uses CPU while nothing happens | ah-engine status --threads names the busy thread and the work counters behind it; see CPU and memory profiling. |
CPU and memory profiling¶
Which thread is busy. ah-engine status --threads [--json] asks the live daemon for every thread's CPU time twice,
diagnostics.threads_window_ms apart (1 s by default, AH_ENGINE_THREADS_WINDOW_MS for one run), and prints the CPU % of
one core per thread name (by_name, the workers summed) and per thread (threads). Thread names: ah-dswire (the DevSwarm
wire), ah-kqueue / ah-watch (the file watcher), worker (hook requests), scheduler, ah-db-writer, ah-dswire-jev
(a per-child Jev sweep). macOS reads task_threads / thread_info; Linux reads /proc/self/task/*/stat. The daemon only
takes snapshots; the client waits out the window, so no worker is held.
What the busy thread is doing. The same report has work_per_s, the counters per second over the window, and work_total:
| Counter | Meaning |
|---|---|
dswire_wakes |
times the DevSwarm thread woke from its sleep (it sleeps until the next deadline, at most devswarm_wire.wait_ms) |
dswire_store_commits |
polls in which a held SQLite source showed a commit by another process |
dswire_transcript_skipped |
transcript events the gate did not act on (no growth, or inside the interval) |
dswire_batches, dswire_paths |
change batches the watcher delivered to the DevSwarm thread, and the paths in them |
dswire_reconciles |
full re-reads of the DevSwarm state (at most one per devswarm_wire.reconcile_min_gap_ms) |
dswire_reconciles_deferred |
reconcile requests folded into one already waiting for the gap |
probe_cache_hits |
file reads a reconcile answered from the read cache (an unchanged heartbeat, plan or descriptor costs one stat; files modified within devswarm_rt.probe_cache_racy_ms are always read) |
probe_files_read, probe_bytes_read |
files (and bytes) the DevSwarm probes read: heartbeats, descriptors, plans |
Healthy idle: a reconcile every few seconds at most, ah-dswire well under 1%. A reconcile rate stuck at one per gap with no
real changes means a source changes all the time; the watcher ignores names ending in realtime.ignore_suffixes (a SQLite
-shm index changes when any process only opens its database, so a watched store used to wake the reconcile that opened it).
Readable stacks. Release binaries ship stripped; their symbols are built separately (Cargo.toml: debug =
"line-tables-only", split-debuginfo = "packed"). A local build leaves target/<triple>/release/ah-engine.dSYM (macOS) or
ah-engine.debug (Linux: the unstripped build, kept by scripts/split-symbols.sh before build.sh strips the shipped binary; a packed .dwp
cannot name frames alone) beside the binary, and scripts/build.sh copies them to <state>/symbols/<build id>/ (files.symbols_dir;
skipped in CI, AH_KEEP_SYMBOLS=0 turns it off), so they outlive a cargo clean; a release run uploads them as the workflow artifact
symbols-v<version>-<triple> (scripts/package.sh writes dist/symbols/ah-engine-v<version>-<triple>.symbols.tar.gz). They match only the binary of the
same build (check with dwarfdump --uuid). On macOS: sample <pid> 3 -file s.txt, then name a frame with
atos -o ah-engine.dSYM/Contents/Resources/DWARF/<file> -arch arm64 -l <load address> <address> (the load address is
printed on each ??? line of the sample). On Linux: perf record -g -p <pid> and perf report with the .debug next to the
binary, or eu-stack -p <pid>.
Burst dumps. When the counted heap grows by more than diagnostics.burst_dump_mb inside one window
(diagnostics.burst_window_ms; a window older than diagnostics.burst_window_max_ms when a request begins is opened again, so slow
growth over an idle gap is no burst; the window also opens at the heap as it is when the profile switches on) the daemon writes one
burst-<n>.json to files.burst_dumps_dir naming the allocating stacks, the event and the checks. Every dump carries build: the
engine version, the Mach-O LC_UUID / ELF build-id (build_id), the image base and the binary's path. The shipped binary is
stripped, so frames hold ip / offset and function: null; name them with
ah-engine diag burst-dump # the dumps, this binary's id, and whether its symbols are found
ah-engine diag burst-dump --symbolize [<dump>] # the newest dump when none is named
which finds the symbol file whose own id equals the dump's build_id (beside the binary the dump names, in
<state>/symbols/<build id>/, or anywhere under <state>/symbols/ two levels down, so an unpacked release symbols archive works),
refuses a file of another build, and runs diagnostics.symbolize_cmd_macos / _linux. By hand, per frame (use ip - 1 and offset - 1):
atos -o ah-engine.dSYM/Contents/Resources/DWARF/ah-engine -arch arm64 -l <build.image_base> <ip> (macOS) or
addr2line -f -C -p -e <ah-engine.debug> <offset> (Linux).
Debug mode and resource budgets¶
One build, two runtime modes. The shipped binary is the debug build too; debug mode only switches on extra work. Turn it on
with the setting diagnostics.debug_mode (the running daemon follows a change of the config files without a restart), with
AH_ENGINE_DEBUG=1 in the environment, or with --debug on serve / hook (the last two are per process and hold it on
whatever the setting says). While on it writes debug.ndjson in the state directory (rotated at
diagnostics.debug_log_max_bytes): verbose lines per module (daemon/request, daemon/cpu, client/hook, ...; narrow them with
diagnostics.debug_modules, a name or a daemon/ prefix), runtime invariant checks (daemon/queue: the depth counter against
the queue length; daemon/watchdog: busy workers against workers; a violation is logged and counted, never fatal), a per-thread
CPU sample every diagnostics.debug_thread_sample_ms and a memory line every diagnostics.debug_mem_snapshot_ms. ah-engine
status --json shows debug (enabled, forced, lines written, invariant violations). While off, each call site costs one relaxed
atomic load and its arguments are not evaluated.
Budgets. diagnostics.budget_cpu_pct (soft, 10 % of one core; the hard limit diagnostics.budget_cpu_hard_pct, 20 %, sheds optional work; both over diagnostics.budget_cpu_windows consecutive
daemon.cpu_check_ms windows) and diagnostics.budget_mem_mb (150 MB, the figure daemon.mem_metric selects) are the daemon's
resource budgets; 0 turns one off. The daemon reports a breach when it begins and when it ends in the health log (kind
budget, code cpu or mem), in status --json (budget: the readings, the budgets, breached, breaches), and in every
daemon health event (cpu_permille, budget_breach: bit 0 CPU, bit 1 memory). Reporting only: a breach changes nothing else. diagnostics.mem_target_mb (100 MB) is the
memory target the footprint is read against: status --json shows it as budget.mem_target_mb with budget.over_target; nothing
is enforced at it. SQLite allocates through the engine's own allocator (storage.sqlite_use_global_allocator, read at daemon
start; status --memory shows sqlite_global_allocator), so a database burst's pages go back to the OS as they are freed instead
of staying in the C library's zones. The counter sqlite_alloc_routing (label result) counts the routing attempt at each daemon start (routed, or failed when SQLite had already started).
Memory. ah-engine status --memory gives the heap against RSS, the allocator's own figures, the memory budgets of every
long-lived cache, and components: the sizes of the in-memory structures per subsystem (guard state, session counters, rate
buckets, Jev lanes, the DevSwarm state's workspaces and edge log, the thread count). For allocation sites see
DEVELOPMENT.md (diagnostics.allocator, MallocStackLogging, heaptrack).
FAQ¶
Does it send anything off my machine? No. Telemetry is local only. The one network request the install makes is the one-time binary download from the GitHub Release (sha256-checked against the plugin's lock; the opt-out variable named in Install skips it). The daemon opens no connection; only the opt-in Jev commands do. Any upload of diagnostics would be opt-in and disclosed first (D28, planned).
What if the engine crashes or disagrees with the Node hook? A crash or a bad answer falls back to the Node hook. A disagreement is a bug in the engine: the parity harness compares exit code, stdout and stderr with the Node guard, and a mismatch is fixed in Rust, never by changing the guard (D31).
Why Rust? The client uses about 2 MB against 44 MB for a Node process and answers in about 2 ms against about 20 ms
(D2). Numbers and how they were measured are in the README of ah-engine/.
Is it on? It is used whenever its binary is installed at ~/.anti-hall/ah-engine/bin/ah-engine, which the plugin's bootstrap does
once a release pins one in ah-engine.lock. With no binary, or after opting out of the bootstrap and removing it, the Node hooks run as before
(Rollback). ah-engine status --json and ah-engine telemetry summary show what it is doing.
Descriptor reads are bounded (ident::read_bounded / read_or_skip). A file a descriptor or receipt names (inbox, cursor file, workspace descriptor, read receipt) is never read when it is no regular file (a FIFO, socket or device would block the verb for good) or is over mesh_write.file_read_max_bytes. The verbs that carry on without the file skip it, count mesh_descriptor_read_skipped (labels site, reason) and log the site and reason; a pull whose inbox is no regular file refuses the append instead of blocking on it.
Current command registry additions¶
ah-engine post-update-check [--dry-run] [--expect-sha <sha256>]: The step every update ends with: verify exactly one live engine runs the installed binary (sha, path, answers status and a ping inside its budget), stop stale and scratch daemons and duplicate watchers by verified pid (never pkill), let watchers on a replaced binary re-execute themselves, report servers on an old binary, and clean old binary copies, dead pid files, a dead socket and dead temp files. --dry-run reports and changes nothing. Exit 0 verified, 1 not.ah-engine proc <list|status|stop|restart> [<pid>] [--confirmed] [--json]: Dashboard process actions by pid, audited:listshows the engine family's records (the wake watchers and the web server),status <pid>reads one,stop <pid> --confirmedsends SIGTERM andrestart <pid> --confirmedstops it and starts it again from its recorded command. Only a pid with a record of an engine-family process is accepted, it must still have the recorded start stamp and executable, an agent session is refused, and nothing is found by name or killed with SIGKILL.ah-engine harness <status|ops|trust <name>>: The host-orchestrator seam (one mapping file per host inengine/defaults/harness/).status(read-only) lists each harness file with the layer it loaded from (edited, lkg, pristine) or why it is off, whether it is active, trusted and detected for this call, and its resolved CLI path (resolved without running it).ops(read-only) prints the engine-owned safety table (harness_ops.toml): each op's safety class, the automatic kinds that may reach it and whether it takes passthrough arguments.trust <name>records the loaded file's hash as the owner's consent, so the automatic-reachable ops of an edited or twin-less harness file are admitted (destructive_read and owner_destructive ops, and identity / role lookups); any later edit re-arms the hold.ah-engine web [open|status] [--no-open] [--json]: The Command Center web dashboard (GH #266):open(default) starts the local server when it is not running and prints its address, opening it in the browser unless --no-open;statussays whether it runs. The server (binary ah-web) binds to the loopback address on a random port behind a per-session token, serves the live agent tree and exits when idle (web.idle_exit_s). Reads the agent list throughagents status; changes nothing. Switch: web.enabled.ah-engine describe [--part <a,b,...>] [--coverage]: The engine's generated self-description for the dashboard and agents: the generated reference (commands, flags, env, metrics, impact kinds) plus the registry settings, config files and keys, checks (bindings, reads, switch, rebindable), event bindings, scripts, Jev integrations, switches, jobs, control verbs and query sources;--part a,blimits it,--coveragereports the features no screen selector (web.coverage) covers, the ones a screen shows but cannot edit, and the selectors that match nothing. Nothing in it is hand-kept.ah-engine query [<source>] [--limit <n>] [--offset <n>] [--where <field=value,...>] [--since <7d>] [--window <7d>] [--schema]: Read-only, paginated query over the existing stores:query <source> [--limit N] [--offset N] [--where field=value,...] [--since 7d] [--schema];query sourceslists the sources (per-check stats, outcomes, kinds, events, counters, agents, health, config history) with their filters, and--schemashows one source's row fields.ah-engine audit entry-paths [--json] [--root <dir>] [--home <dir>] [--no-live]: The entry-path audit:audit entry-pathsinventories every js/sh/wrong-entry leftover in four sections (files of the plugin tree, command strings of hooks.json / defaults / skills / docs, files the engine itself generates into launcher directories, and a read-only look at the running machine: processes, LaunchAgents, crontab, installed hooks.json) against the allowlist in entry_audit.toml. Exit 0 = clean, 1 = findings.--no-liveskips the machine section (the deploy gate),--rootnames the repository or plugin root,--homethe home directory.
Archived children stay quiet (GH #508, switch devswarm.skipArchivedChildren, default off). The unread, urgent ("CHILD NOT DRAINING") and archive-ready reminders of devswarm-parent-inbox skipped a child only when the DevSwarm app said it was archived; anti-hall's own archive marker (archived/<id>.json) was ignored, so a marker-archived child kept being named. With the switch on, piRow answers closed from the explicit archived state only (no worktree path is inspected anywhere): the app's flag closes a row; a marker closes it only with proof the id was not re-created (no descriptor, the same session id on both sides, or neither with a session id and the descriptor not written since the marker). A descriptor with a different or newly missing session id, or one written after a session-less marker, keeps the child named. Each check filters closed rows itself: the unread and urgent nudges (one list), the archive-ready recommendation and the stale-workspaces notice, whose text then names the clearing step (archive <id>, devswarm_parent.stale_registry_head_archived). Nothing is marked, deleted or acknowledged and the summary's unread counts stay raw. Counters: devswarm_archived_child_skipped {check, reason} and devswarm_archived_child_kept {reason}. Unsure or off: every nudge as before. Marking mail expired stays a separate change (GH #564).
The Primary's mailbox cron runs only while a child workspace is alive (#709, switch devswarm.wakeCronOnlyWithChild, default on). A cron tick is a full model turn that re-reads the whole context, so a tick with no child to hear is pure cost. With the switch on, the SessionStart directive of a Claude Primary arms the Monitor wake-watch alone (devswarm_role.msg_wake_claude_parent_nocron), and a session that starts with no cron is recorded as cron-less. devswarm-parent-inbox reads the live children once per turn: with none left it shows ONE order to CronDelete the inbox tick job (devswarm_parent.msg_cron_delete, counter devswarm_cron_ctl, label action = delete_ordered), which reaches a session that armed the cron before the update because the order rides the next prompt, a cron tick's own turn included. The record {deleted, at} lives in devswarm/cron-ctl/<session>.json; an inbox tick newer than at spends it, so the next empty moment orders again. At the next live child the wake line (NO MAILBOX TICK / NO MAILBOX WAKE PATH) treats a tick marker older than at as absent, so the cron is asked for at once instead of after devswarm.cronMissingWarnMin. The wake line and the Stop gate already named no wake path without a live child. The Rust mesh wake-directive verb still prints the always-armed text (it is only named while a child is live). Switch off restores the always-armed cron. Claude only: Codex has no scheduler tool.
Advisories repeat on a state change, not on every tick (#709). The emit-dedupe keepalive that re-shows an unchanged block no longer counts a turn the scheduler delivered (a cron tick): guards.keepaliveCountsScheduled (default off; on restores the old rule) counts only the user turns of the transcript that name a turn origin other than emit_dedupe.uncounted_origins, and guards.injectionRepeatMinS (default 7200 s, 0 = off) re-shows the block once that long after its last emit so a purely scheduled session still gets it now and then. A transcript that names no turn origin counts as before. The two keepalives of the Primary's unread-mail segments moved from the script to devswarm_parent.nudge_keepalive and devswarm_parent.urgent_keepalive. The low-disk warning (diskWatch.repeatOnChangeOnly, default on) fires again only on a level change, a fall of diskWatch.repeatDropGb (5) or after diskWatch.repeatSeconds (21600) per volume. The claim-evidence guard does not scan the header row of a markdown table (guards.claimEvidenceMaskTableHeader, default on); body cells are still scanned. gcloud config get-value is a read (command.gcloud_inspect_verbs). The statusline.max_keys list starts with context_window_size, the field Claude Code documents. The counter waste_events_total (labels category, source) counts the repeats the new rules saved while the daemon holds it.
Smarter child-gate cron check, tracker skip and waste warning (#709, PR-A2b). (1) The child Stop gate reads session_crons from the Stop / SubagentStop payload (Claude Code 2.1.145+; {id, schedule, recurring, prompt} per scheduled job): a job that is recurring, has a schedule and whose prompt BEGINS (after an optional Mailbox tick: lead-in, run, quotes or backticks) with the tick command, node <path> inbox tick <id> or <cli> mesh inbox tick <id> (devswarm_gates.cg_cron_prompt_re; a prompt that only mentions inbox tick does not count; the payload carries no expiry) ends the cron-missing warning even when the tick marker is old (counted as waste_events_total{category="forced_turn",source="cron_listed"}), a list without it gets the cg_cron_missing_payload order (CronCreate, no CronList turn), and a payload without the list, or with a list of no recognised shape (old shape, malformed entries), keeps the age-based text (devswarm.cronFromPayload, default on; env ANTIHALL_DEVSWARM_CRON_FROM_PAYLOAD). The payload's background_tasks is not used by the child gate (it checks no monitor); the Primary gate's watcher check still reads lock files. (2) The task tracker says nothing on a cron-delivered turn (the newest user turn of the transcript is scheduled and holds the submitted prompt) while the open-task list hash equals the one it last noted, and does not ask Jev to label that prompt (context.taskTrackerSkipScheduled, default on; env ANTIHALL_TASK_TRACKER_SKIP_SCHEDULED); a changed list (id, subject, status, owner, blockedOn and the order-normalised blockedBy are fingerprinted) or a prompt a person typed is never skipped, and a turn counts as scheduled only when the matching record is provably the current turn's (the newest user prompt record, with the scheduled origin and the submitted text, with no assistant record after it); anything else speaks. (3) waste_tokens_total (labels category, source) estimates the tokens of the text a smarter rule left out (bytes divided by waste.bytes_per_token); it is the advisory text only, not the model turn it would have joined (that needs the transcript usage the engine does not expose to scripts, Rust work after 0.3.0). Each session keeps a rolling record (waste.* in prompt_emit.toml); guards.wasteWarn (default on) sends ONE advisory when a category's tokens in the last guards.wasteWarnWindowMin (60) minutes reach a higher level (guards.wasteWarnTokens x waste.level_multipliers, 1000 x 1/4/16) than the last call, so a constant rate warns once and a rise warns again (a dip within waste.hysteresis_pct of the held level's threshold is not a fall, and a record the disk will not take means no advisory); counted as waste_warnings_total. Not built: the statusline segment, the daily digest line and the level relative to a baseline (they need the telemetry report, Rust).
Git guard credit gaps (GH #457). The credit lists in git.toml name the session trailer (credit_session_keys, also git.self_credit_trailer_keys in limits.toml for the trailer-key remap check) and the session link (credit_url_markers; gh_body_markers for gh bodies), so the commit check, the reused-message check, the gh body check and the post-commit audit all see them. An inline commit message that still holds a shell expansion is refused with "write the message literally" (guards.gitCommitExpansionCheck, default on; env ANTIHALL_GIT_COMMIT_EXPANSION_CHECK; patterns commit_expansion_patterns, exceptions commit_expansion_allow; each pattern is matched at the start of the expansion within the whole text, so a pattern with lookbehind, \b, \B or a ^ alternative is dropped (counted, and named once per session in an advisory) while the other patterns keep working). A push is blocked when an unpushed commit carries a credit (guards.gitPushCreditCheck, default on; env ANTIHALL_GIT_PUSH_CREDIT_CHECK; a push that cannot be narrowed to the commits it sends (GH #506, below) reads every local commit no remote has (push_argv_log: git log --all --not --remotes, stash and refs/original excluded), so no refspec, config, mirror or insteadOf form routes around it); the block names the hashes with their local branches (push_argv_branch_contains, push_hit_format) and the plain fix (amend if unpushed on a branch you own, else tell the owner; never a shared-branch rebase or a force push) and rewrites nothing. Checked-out submodules (push_argv_cdup, push_gitmodules_file, push_argv_submodules) share the scan and its cap; the newest local annotated tags are read too (push_argv_tags, msg_push_tag_credit). A repository path that expands at run time is refused (push_repo_opts, push_repo_env_names, push_dynamic_path_res, push_dynamic_repo_cmd_re, msg_push_dynamic_repo), and any failing git query gives the not-checked advisory, never a silent pass. More than push_max_commits commits read is refused (msg_push_over_cap), never allowed unread. A commit whose message layer 1 cannot read (push_same_call_*: a file, stdin not fed by a quoted heredoc, an expansion, a reused or edited message, a commit with no literal -m, am, cherry-pick) in the same Bash call as a push is refused before anything runs (msg_push_same_call: commit and push in separate calls). git unavailable or timed out fails open with push_unchecked_advisory. The authoritative commit layer is git-audit (PostToolUse, guards.gitCommitAudit, default on, env ANTIHALL_GIT_COMMIT_AUDIT): after every Bash call it reads HEAD's reflog (git_audit.argv_reflog) for commits written in the last git_audit.window_s seconds by a commit-writing step (git_audit.reflog_creating; a fast-forward or a rebase start/finish/abort, git_audit.reflog_skip, writes nothing and is skipped), keeps those HEAD reaches and no remote has (git_audit.argv_log), and blocks on a stored credit with amend/reword instructions, whatever shell form wrote the message. Every expansion of an inline message is read: an allowed form ($(:), a heredoc substitution) is skipped and the scan goes on, a heredoc substitution is followed past its closing parenthesis in the whole command, and an unquoted heredoc body that expands is refused. The session trailer and link are decided by the git script only (its switches apply); the locked rules.json rule keeps its original co-author and generated-with patterns. Counters (declared in git.toml): git_blocked {reason: the message key without msg_, e.g. commit_credit, commit_expansion, push_credit, force_push}, git_push_blocked, git_audit_blocked, git_expansion_pattern_dropped; they appear in ah-engine metrics and the telemetry report. A commit_expansion_patterns entry that is not a valid regex or looks before the match start (lookbehind, \b, \B, ^) never fails the guard: it is dropped, counted by git_expansion_pattern_dropped, and named once per session in an advisory (git.expansion_pattern_advisory); the remaining patterns and every other git check keep working.
Pre-push credit scope (GH #506). The pre-push credit check reads only the commits a push sends when its command line names them and the configuration cannot widen it: the refspec sources (or HEAD for a bare push or one naming only a remote) not on any remote (git.push_argv_log_scoped), so unpushed work on other branches or worktrees neither blocks the push nor fills git.push_max_commits. A push the command line cannot narrow (git.push_unscoped_opts, git.push_unscoped_globals, git.push_unscoped_env_prefixes, a refspec matching git.push_refspec_unscoped_re) or whose repository configuration can widen it (git itself is asked, so every spelling it accepts counts: git.push_argv_config_bool over git.push_scope_bool_patterns, git.push_argv_config_raw over git.push_scope_any_patterns and git.push_scope_default_pattern with git.push_default_narrow; a query that fails reads as widening), or whose scoped query fails, reads every unpushed commit as before. Switch guards.gitPushCreditScope (default off; env ANTIHALL_GIT_PUSH_CREDIT_SCOPE; git.setting_push_credit_scope); counter git_push_scoped counts the pushes judged on their own commits. The narrowing is valid only on proof that nothing else in the same Bash call can run before the push and change what it publishes (the configuration and HEAD are read before the call runs): the call has none of the characters in git.push_narrow_forbidden_re (a semicolon, ||, a pipe, a single &, a substitution, a subshell, braces, a here-document, eval, source, alias, a shell name), every && segment before the push matches git.push_narrow_before_res (only cd to a literal absolute, ./, ../, ~/ path, . or ..: a bare relative name, cd - and ~user are not proven), and the push segment matches git.push_narrow_push_re (the push, optionally after -C <plain literal path>, then plain words only: no quote, $, glob or redirect, no -c; plain NAME=value assignments before git are allowed unless the name matches git.push_narrow_env_deny_re: GIT_*, HOME, PATH, XDG_* and the like, read per name with git.push_narrow_env_name_re). A proven chain is judged in the directory its own cd segments name (pushNarrowDir), so the call-time pass and the backstop pass read the same repository. With the switch on, any cd, pushd or popd word anywhere in a call that pushes (git.push_cd_word_re: also behind command or builtin, in braces or a subshell) whose target is not a literal path (git.push_cd_literal_re: cd -, cd ~-, popd, cd "$X", a bare cd) is refused with msg_push_dynamic_repo. Any other call reads every unpushed commit of the repository, as before #506; counter git_push_narrow_unproven counts those pushes. A script file that runs git config and then pushes is invisible to the check, with or without #506. A harmless output tail on the push (2>&1, | tail -5, | head, | cat: git.push_narrow_tail_re, cut off before the rest is checked; git.push_scope_redirect_re keeps 2>&1 from being read as a ref) keeps a proven push narrowed; any other pipe, redirect, tee or shell does not. Submodules: a narrowed push that does not recurse (no --recurse-submodules value outside git.push_recurse_off_values, no push.recurseSubmodules or submodule.recurse: git.push_recurse_flag_prefix, git.push_recurse_config_pattern) publishes only the submodule commits its gitlinks name, so only the submodules whose gitlink the pushed commits change are read, from the new gitlink back (git.push_argv_gitlinks, git.push_gitlink_line_re, git.push_gitlink_mode); a listing that cannot be read reads every submodule. The over-cap refusal names the repository and the count.
Late-reply wait (#684). A hook call whose daemon has not answered by client.deadline_ms keeps waiting only while the daemon visibly makes progress: the daemon writes the silence of its longest-silent busy worker into the fifth line of the heartbeat file on every watchdog tick, and the client fails open at once when that figure plus the heartbeat's age reaches client.progress_stale_ms (or when there is no figure). The wait is bounded per event: client.slow_fallback_max_ms (3 s) and the request ceiling daemon.request_hard_ms (2 s) for every event, client.slow_fallback_event_ms and daemon.request_hard_event_ms (9 s and 8 s) for Stop and SubagentStop only, so a loaded host does not fail the end-of-turn guards open while a prompt or a tool call never blocks for seconds on a stuck daemon; the launcher carries the same table. One host call of a check (git, a spawned program) may use at most daemon.host_call_share_pct of its event's ceiling, so a slow call cannot starve the checks after it.
Registered metric identifiers: lane_test_block, lane_test_lockfree_allowed, wide_search_depth_bounded, command_wrapper_resolved, model_routing_never_routine, model_routing_explore_hint_skipped, dssup_appdb_date_unread, mesh_heartbeat_degraded, mesh_store_backend_skipped, mesh_summary_read_failed, mesh_summary_settings_unreadable, mesh_report_skipped, answers_dropped, guard_answer_dropped, verdicts_saved_by_cpu_budget, wouldblock_retries, jev_arrival, claim_evidence_fired, claim_evidence_suppressed, burn_breaker_paused, burn_breaker_bypass, burn_pause_withheld, agent_outcome_kind, devswarm_parent_gate_fired, devswarm_parent_gate_suppressed, devswarm_parent_gate_count_mismatch, devswarm_orphans_warning_suppressed, spawns_denied_over_cap, spawn_reservations, runtime_escalation_stop_unrecorded, protocol_delivery, context_shrunk, silent_agent_nudge_fired, silent_agent_nudge_acked, inline_rule_blocked, inline_rule_standdown, idle_rule_fired, idle_rule_listed, idle_rule_suppressed, idle_slot_minutes, idle_rule_age_unknown, reply_style_observed, reply_style_fired, reply_style_suppressed, pair_rule_observed, pair_rule_fired, pair_rule_suppressed, notice_turn_matched, notice_turn_skipped, role_note_emitted, task_tracker_emitted, named_tree_bare, snapshot_written, snapshot_overlaid, snapshot_discarded, snapshot_identity_unknown, snapshot_error, taskstate_rows_skipped, doctor_codex_node_entries, doctor_statusline_skipped, claim_evidence_log_read_ok, claim_evidence_tool_ok (claim_evidence.tool_evidence, GH #845), ask_guard_denied, git_push_unscoped, misfire_suppressed, guards.injectionRepeatEvery, advisor_exempt, advisor.thinking_exempt_re, idle_order, owner_approval_pass (owner_approval.toml, GH #800), transcript_write_blocked, devswarm_unread_read_seen (counter, label reason: an unread backlog relabelled "read, not acked" because the child ran inbox read since the oldest message arrived), overload (counter, labels what, class, event: the daemon's orderly-overload outcomes - evicted, rejected, limited, shed_mode, timed_out - by admission class and event; overload.toml, GH #969).
Mesh sender identities (mesh_identity.toml, GH #845). The owner writes to the mesh as admin (a human) and anti-hall's own messages go out as ah-engine (a proxy acting for the owner); neither is ever stamped as the Primary. admin is declared by an operator shell with --as admin or the sender_env variable; a caller whose environment marks it as an agent is refused, and ah-engine is never selectable from the CLI. Every row stores its sender_kind; kind and rank are read from that stored kind, never from the sender's name, and the rank drives wake privilege and precedence when instructions conflict. Every value lives in the file.
Further registered metrics (each described in full in its [metric.<name>] entry in plugins/anti-hall/engine/defaults/):
request_env_non_utf8(counter, labels none,telemetry.toml) counts allowlisted environment variables (request_env.allow) whose values cannot be forwarded as UTF-8. The capture is flagged incomplete and checks take their failure policy instead of reading the variable as unset.afk_nostop(counter; labelsaction;afk.toml): No-stop state events (GH #958), by action: set, cleared (owner stop phrase), done (no open work left), held (a Stop held), capped (let through after afk.nostop_max_holds), escalated (the hold after afk.nostop_burst_max in its window), quiet (let through during afk.nostop_quiet_ms).agent_nudge_snooze_refused(counter; labelswhy;agent_nudge.toml): Snoozes orotherholds refused (#862), by why: no_progress (no outcome and no commit since the nudge or the last snooze) or capped (the agent already used agent_nudge.budget.snooze_max snoozes).native_wake_skipped(counter; labelsreason;agent_tracker.toml): Native wakes not attempted because the target cannot be woken that way (#900), by reason (primary-seat: a send to a Primary seat).compliance(counter; labelssignal,outcome;agent_tracker.toml): Task-list compliance signals (GH #958) by signal and outcome: fired, suppressed:, acted_on, false. auto_handover_fired(counter; labelsvia;ctxbudget.toml): Auto-handover fires (the once-per-arm handover order), by via: pct (the percent line), tokens (autoHandover.maxTokens), workspace (a DevSwarm workspace past autoHandover.workspaceMaxTokens, GH #884: ordered to a fresh session), and the same words with the Stop-side prefix (ctxbudget.ah_via_stop_prefix) when the Stop check fired it.devswarm_roster_flags(counter; labelsaction;devswarm_parent.toml): Roster flags (#844 item 4), by action: ordered (children named in an order line), gate_counted (a parent Stop-gate block that named flagged children), gate_notice (a flagged set already blocked on this session, shown as a notice).mesh_chat_ack(counter; labels none;mesh_chat.toml): Sends stored as an explicit ack (chat_kind = ack).mesh_room_ops(counter; labelsop,outcome;mesh_room.toml):mesh roomcommands, by subcommand and outcome (changed, unchanged, refused).mesh_room_sends(counter; labelswake;mesh_room.toml): Room messages stored, by whether the body narrowed the wake to mentioned members (mentions) or woke every member (members).mesh_wake_lines(counter; labelschannel,role;mesh_wake.toml): Wake lines the wake-watch printed, by channel (mail or broadcast) and watcher role: each is a woken turn (GH #845 baseline).mesh_wake_suppressed(counter; labelsreason;mesh_wake.toml): Native wakes (DevSwarm reactivate) a send skipped, by reason (GH #845).mesh_extras_dropped(counter; labels none;mesh_wake.toml): Sends whose GH #845 columns (chat_kind, wake_audience) could not be set because the store lacks them (its ALTER at open failed): the row is kept and read as a legacy row.mesh_broadcast_read_failed(counter; labels none;mesh_wake.toml): Drain reads (inbox read, read-primary) whose broadcast read failed and listed none, while the direct mail was still read.edit_guard_handover_redirected(counter; labelstool;omc_coexist.toml): New handovers outside anti-hall's handover folder that edit-guard blocked with the session handover path (guards.handoverRedirect), by tool.auto_handover_hint(counter; labelshost;omc_coexist.toml): Prompts that asked for a handover in plain words and got the handover skill and path line (autoHandover.promptHint), by host.usage_snapshot_stale(counter; labelsreader;omc_coexist.toml): Usage readings ignored because the snapshot was older than ctxbudget.usage_max_stale_ms (GH #981), by reader.auto_handover_quiet_omc(counter; labels none;omc_coexist.toml): Context checks that stayed quiet about stopping points because an OMC autonomous loop was active (autoHandover.quietOnOmcLoop).compact_advice_deferred_omc(counter; labels none;omc_coexist.toml): Compact recommendations compact-advice-guard let through because OMC's context guard orders /compact (guards.compactAdviceDeferToOmc).prefilter(counter; labelscheck,outcome;prefilter.toml): PreToolUse prefilter outcomes (#969 R1, defaults/prefilter.toml), by check and outcome (skip, run, agree, disagree).archive_submodule_drift_passed(counter; labelsverb;prompt_emit.toml): Archives that passed because the only uncommitted entries were submodule checkout drift (clean submodule, HEAD on a remote branch; #943, devswarm.archiveIgnoreSubmoduleDrift), by verb.archive_refused_unsafe(counter; labelsverb;prompt_emit.toml): Archives refused because the workspace's worktree held uncommitted changes, unpushed commits or a state git could not read (#876, devswarm_cli.archive_work_guard), by verb.resource_watch_pressure_warned(counter; labelssignal;resource_watch.toml): System memory pressure warnings raised by the resource watch (#900), by signal (psi, mac-level).coordinator_work_mesh_read_pass(counter; labelsverb;small_guards.toml): Mesh mailbox reads, peeks and acks the coordinator-work guard let through as not work (#900), by verb.stopmemo(counter; labelsevent,outcome;stopmemo.toml): Stop memo outcomes (#857 R5/R6, defaults/stopmemo.toml), by event and outcome (hit, miss, stored).idle_rule_hold_lapsed(counter; labelsreason;task_guards.toml): Task holds whose exemption lapsed after nudges.hold.hold_max_ms (the normal rule applies again), by exemption kind (owner, blocked_on, parked, clock).task_window(counter; labelsaction;task_guards.toml): Task-window actions at TaskCreate/TaskUpdate, by action (block_format, block_dup, block_full, block_order, block_owner, block_blocked, blocked_kept, block_drift, block_import, block_backlog_dup, saved_backlog, reserved, adopted, slot_free, store_write_failed, store_unreadable, lock_busy).script_regex_invalid(counter; labels none;telemetry.toml): Patterns a script handed the engine (ah.re.*,ah.transcript.*regexes, patterns read from settings) that the engine's regex dialect cannot compile (for example a lookahead).request_env_non_utf8counts allowlisted environment variables whose values cannot be represented as UTF-8 (telemetry.toml, unitvariables, no labels). The capture is marked incomplete and checks apply their failure policy. Both Claude/OMC and Codex/OMX use this request capture.transcript_cache(counter; labelsresult;telemetry.toml): Lookups of the shared incremental transcript view (idle-teammate scan,ah.fs.tailLineswith needles,ah.transcript.grep): hit (nothing appended), append (only the appended bytes were read) or rebuild (the window was read afresh).transcript_cache_rebuild(counter; labelsreason;telemetry.toml): Why a transcript-view lookup read its window afresh: none (nothing kept: first call, daemon restart, eviction or idle expiry), file (another file or a shorter one), window (the window moved past the kept lines), digest (the file was rewritten in place) or gen (the settings changed).
Rules after compaction (GH #519). A SessionStart from a compaction or resume sends the whole verify-first protocol again, once per such start (context.protocolFullAfterCompact, default on; off = the short digest); counter protocol_delivery by hook and kind (full, digest, repeat). The orchestration rules keep their short form there. The per-hook inline caps (context_size.*) never shrink a pinned context (priority at or above dispatch.context_pin_priority, such as the rule digest) unless it has its own context_size.hook_caps row, and the event total shrinks the lowest-priority contexts first (context.inlinePinned, default on; off = largest first); counter context_shrunk by class (pinned, low). silent-agent-nudge counts every Stop nudge it says (silent_agent_nudge_fired) and every one an ack withheld (silent_agent_nudge_acked).
Bare fresh-clone statements (GH #487). guards.sharedTreeBareClone (env ANTIHALL_SHARED_TREE_BARE_CLONE, default off) makes the shared-tree note treat a brief such as "clone ~/x and build" or "use ~/x as the working copy" as naming its own tree, through swarm_guard.re_named_tree_bare (read after swarm_guard.re_named_tree; a source path in "git clone ~/src ~/dst" does not match). Each spawn exempted only by it is counted (named_tree_bare, plus the swarm_guard_fp advisory event); a brief that also says "in place" still notes. The exemption fails safe: any negation token (not, no, never, without, avoid, except, rather than, instead of, any n't contraction whatever its apostrophe) anywhere in the same clause, with any words between, keeps the note (swarm_guard.re_named_tree_bare_negation), so only an unambiguous affirmative clause exempts and named_tree_bare counts only the warnings actually avoided (an allowed, recorded spawn; a rate block counts none). Whatever is ambiguous widens the clause: it ends only at a stop, ! or ? before white space and a capital letter (swarm_guard.re_named_tree_bare_clause_break; a semicolon is never a sentence end), never inside brackets, quotes (single quotes and markdown emphasis open a span only by their place in the text, so an apostrophe in a word opens none: swarm_guard.bare_mark_groups, swarm_guard.bare_mark_before), code ticks, strikethrough or dashes (also hyphens between spaces: swarm_guard.re_named_tree_bare_dash; an unclosed one runs to the end), after an abbreviation or a lone letter or digit, or in an ellipsis, spaced or not (swarm_guard.re_named_tree_bare_mask, swarm_guard.bare_nest_open, swarm_guard.bare_nest_toggle); blank lines, lists and newlines are no break, so a negation in a neighbouring bullet or after a semicolon keeps the note. Invisible format characters are removed first (swarm_guard.re_named_tree_bare_invisible). Only words that start with ~/, $HOME/, /, ./ or ../ are read as paths and blanked, over path characters only (swarm_guard.re_named_tree_bare_pathtok), so not/never and ~/x(not stay negations. Every affirmative statement is blanked from the in-place check, whatever its case.
Concurrent-agent cap (GH #484). guards.maxConcurrentAgents (default 6, 0 = off) extends spawn-ceiling: a spawn is denied when that many agents run, an agent of unknown liveness counting as running until the session proves it ended (counter spawns_denied_over_cap). The count unites the transcript's running agents with the tracker's live children, so an agent whose launch fell out of the transcript window still counts. An allowed spawn reserves its slot under a lock (spawn_ceiling.reservation_file, keyed by the tool call id), so the overlapping checks of one parallel burst cannot all pass; a reservation is released when its launch shows in the transcript or after spawn_ceiling.reservation_ttl_ms (counter spawn_reservations by outcome). A child whose nudges repeat agent_nudge.runtime_escalation.after_reminders times without finishing or being stopped is counted (runtime_escalations) and published to runtime-escalations.json; the coordinator's next Stop is blocked once per session (silent_nudge.rt_stop_cap) naming the agent and its runtime. A child at the block-tier runtime step (GH #687, row marked block) blocks every Stop until it is stopped or extended, on its own count (silent_nudge.rt_block_cap, a safety valve) so the two cannot use each other up; both blocks use the house format with no "advisory" line. Runtime steps are counted by agent_runtime_step_fired (step), agent_runtime_step_acted (step, action: stop, extend, msg) and agent_runtime_step_reported_wrong (step). When that block count cannot be saved the Stop is not blocked (counter runtime_escalation_stop_unrecorded, one log line), so a failed write never repeats the block. Codex hosts: the engine skips the ceiling for Codex payloads (standdown.codex_host), so the cap is Claude-only for now.
The shared JS Stop repeat breaker (agent_controls.toml, stop_reblock.*) covers devswarm-child-gate, the idle-task branch of task-guard, auto-handover-pause-nag and silent-agent-nudge on Claude and Codex (OMC and OMX). guards.stopReblock enables it; guards.stopReblockMax permits two repeats after the first unchanged block by default. The guard, normalized reason and meaningful guard state identify a repeat; changed state gets a fresh budget. State is saved immediately, since a Stop may repeat before a reply is delivered. Exhaustion releases the Stop, prints one short line once and counts waste_events_total{category=reblock_loop} for each released block. The TOML participant list is restrictive and its exclusion list keeps safety, evidence and destructive-action guards outside the breaker. Missing or corrupt breaker state starts a fresh budget; an unwritable record preserves the guard's block.
guards.runtimeStopReconcile (default on) reconciles runtime Stop rows with current tracker completion and recorded owner answers. stop/acted retire the current incarnation; other holds for the configured default (30 minutes), snooze holds for the requested minutes within the configured cap, and msg counts as acted for the verification window. Verbs and windows come from agent_nudge.answers/agent_nudge.limits. Logic never writes the publisher snapshot: atomic per-session overlays under .anti-hall/ah-engine/ retain audit rows without deletion. Verdicts expire according to silent_nudge.rt_repair, current live evidence overrides old completion, corrupt overlays are ignored, and a failed overlay write preserves the publisher block. Both Claude/OMC and Codex/OMX share this plugin logic; the Rust publisher is unchanged.
Registered impact identifiers: price_table, savings_method, estimate_label, measured_label, routing_how_counted, net_how_counted, spenders_how_counted, avoided_waste, benchmarks_how_counted, unlinked_how_counted, routing_unknown_status, recorded_label.
Claude and Codex hooks share the daemon workspace lookup cache. harness.lookup_cache_ttl_ms in harness.toml controls how long a successful row can serve the same session and cwd (default 5000 ms, maximum 60000 ms, zero disables reuse between hooks). harness.lookup_cache_max_entries caps retained rows (default 256, range 1–4096). The daemon evicts the least recently used row first. The memory registry also applies mem.lookup_cache_soft_bytes, mem.lookup_cache_hard_bytes and mem.lookup_cache_low_water_pct.
Additional defaults files: agent_nudge.toml, harness.toml, entry_audit.toml, io.toml, jev_arrival.toml, mesh_report.toml, post_update.toml, routine.toml, session_switches.toml, web.toml, web_graph.toml, web_manage.toml, web_ops.toml, web_tel.toml, webapi.toml.
The memory_leak_notices counter records retained-memory leak notices, labelled by top.
The switch-notice check reports engine switches on tool events.
The tasklist_integration_skipped counter records Stops where git integration commands (merge, cherry-pick, checkout, switch) alone would have reached the tasklist-guard work threshold and were not counted (guards.tasklistIntegrationSkip). The tasklist_progress_carried counter records Stops where the session's progress file under an earlier date was used after midnight (guards.tasklistCarryProgress). The command_heavy_segment_named counter records heavy-command blocks of a chain that named the heavy segment (guards.commandNameSegment). All three appear under advisory in ah-engine status. The telemetry of the recent fixes (recent_tel.enabled) adds four counters: cfg_cache counts the ah.cfg / ah.settings reads of check scripts by result (hit answered from the per-call memo, miss went to the host), folded into the next call's single cfgGen host call; tail_newest_reads counts newest-first transcript tail reads by mode (capped or fallback_full); requests_served counts the requests the daemon ran checks for; sigint_drains counts the graceful drains started by SIGINT. The launcher's launcher.notice_counters adds notice_shown, notice_suppressed and notice_evicted to its stats. The tasklist_hygiene counter records task-list hygiene events (completed-task note shown, task deleted, prune suggestion shown) by event (nudge, deleted, prune_suggested); it appears under advisory in ah-engine status as tasklist_hygiene.<event>.
Daemon exits (R0). The watchdog_exits counter records the watchdog's stall and stuck exits by kind. The daemon_exits counter records every daemon exit as its drain begins, by kind (health.exit_kinds: idle, rss, memory, handoff, sigterm, stall and the rest). Exits taken under load do not count toward the crash-loop rule.
Load-aware guard deadlines (#969). On a loaded machine a guard check gets more wall time instead of a capacity hold: for an event in daemon.load_scale_events (PreToolUse, PermissionRequest, Stop) the request's hard ceiling (daemon.request_hard_ms or its per-event row) and the late-reply wait (client.slow_fallback_max_ms or its row, in the client and the ah-hook watchdog alike) are multiplied by the 1-minute load average per core, clamped to [1, daemon.load_scale_max_permille/1000] and rounded down to daemon.load_scale_step_permille. client.deadline_ms never moves, and one factor for both keeps the hard ceiling plus the deadline grace inside the late wait. The factor is sampled once, by the ah-hook launcher, and lowered until the call's whole plan (cold wait, late wait, kill graces, wall margin) fits min(the hook timeout, the wrapper cap); it reaches the hook client in daemon.load_scale_env and the daemon in the request (load_permille), so neither samples the load itself and the three can not disagree. With the shipped numbers PreToolUse and PermissionRequest grow to at most 2x and Stop, whose late wait already fills its 10 s wrapper cap, does not grow. The counter deadline_load_scaled (event) counts the requests served with a factor above one.
Advisor adherence metrics (GH #404 phase 3)¶
The advisor counters are advisory-layer counters (status --json under advisory.<kind>.<metric>, and the metrics verb). The
daemon writes the advisory counter kind to the shared counter journal like every other process
(diagnostics.durable_counter_kinds), so they survive a daemon restart. Names are config: kinds in advisor.kind_*, metric names
in advisory.metric_names, per-type and latency names from advisor.metric_*_tpl and advisor.latency_buckets_s.
| Metric (status path) | Counts |
|---|---|
advisor_thinking.dispatch, advisor_thinking.dispatch_<type> |
thinking dispatches (fix, design, investigate, root_cause, plan, review) by a non-flagship main in an advisor session |
advisor_thinking.consulted_before |
those with an advisor call since the owner's last message |
advisor_thinking.consult_rate |
derived: consulted_before / dispatch, three decimals (diagnostics.advisory_ratios) |
advisor_thinking.nudge, .blocked, .block_capped |
first-hit nudges, the one block per task, hits past that block (passed) |
advisor_thinking.false_nag |
a nudge followed by routine (non-thinking) dispatch before any consult (best effort) |
advisor_consult.consult, .nudged, .spontaneous |
advisor calls seen in the transcript; after a phase-3 nudge or block, or with none pending |
advisor_consult.latency_le_<n>s, .latency_gt_<n>s |
time from the owner's last message to the advisor call, bucketed |
advisor_say_do.miss, .blocked |
turns that announced an advisor call that did not follow; the Stop blocks for them |
advisor_second_attempt.gated |
second fix dispatches for one issue key blocked for want of a consult |
advisor_retry.*, advisor_review.*, advisor_plan.* |
phase 1 and 2 (unchanged) |
The same tallies are kept per agent in the retry state file (~/.anti-hall/advisor-retry-<session>[.<agent>].json, stats).
Static child reminders (#709 gap follow-up)¶
devswarm.childStateOnly (default true; ANTIHALL_DEVSWARM_CHILD_STATE_ONLY) applies on Claude/OMC and Codex/OMX. The child-turn hook saves its last static reminder fingerprint and emits again only when its content, transcript path or context-reset marker changes. A missing, corrupt or unwritable record fails open. Setting it false restores the previous delivery retries and turn/time keepalives. Mail, plans and Stop reporting duties keep their independent checks.
The dispatcher can remove the unchanged comms paragraph after the hook records its full four-segment fingerprint. The delivered three-segment remainder cannot satisfy that exact fingerprint, so the old prompt-delivery path retried after emit_dedupe.max_pending_ms; the scheduled-turn keepalive fix and tool-advisory state dedupe did not cover this mismatch. The opt-in state-only path does not depend on downstream text shaping. This changes plugin JS/defaults only; no Rust renderer or dispatcher changes are needed.
Parked roster and unknown token totals (#709, PR-B)¶
The shared Claude/OMC and Codex/OMX parent-inbox roster now labels a child parked when the app explicitly shows it closed, the done gate is true, its id is owner-held, or a live session is waiting on a human. devswarm.parkedDisplay (default true) hides stale/escalated status, NOT DRAINING and stall-derived warnings for those rows. Actual unread mail, including urgent mail, still surfaces. Unknown app/transcript state retains live behavior. App-closure parking also requires a valid zero unread count; corrupt or missing unread state cannot hide status or NOT DRAINING flags, including rows with no session id. A human wait expires after devswarm.parkedMaxWaitMin (default 60; ANTIHALL_DEVSWARM_PARKED_MAX_WAIT_MIN). Cumulative burn and other signals remain visible: this change cannot prove their current rate. No parent-stop state is inferred.
devswarm.tokenUnknown (default true) shows tok ? in a roster plan cell when the token source is missing, unreadable, changed since sampling, not fully consumed, or the sample exceeds devswarm.tokenFreshMs (default 1800000 ms). Small unsampled appends up to devswarm.tokenOffsetToleranceBytes (default 4096; ANTIHALL_DEVSWARM_TOKEN_OFFSET_TOLERANCE_BYTES) are tolerated; larger gaps show tok ?. A fully sampled recent source still shows its total; this is a display stopgap, not a resolver or token-saving measurement. Metric token_usage_unresolved counts unknown displays; waste category stale_flag_on_parked counts hidden stale flags without estimating token savings.
Deferred under the Rust freeze: the global quiet-tick one-line gate (the independent hook results are combined in Rust; the existing digest enforces at least two lines and has no scheduled-state gate), the actual statusline missing-context branch, transcript resolution, and windowed parked burn. The statusline already prefers context_window_size from PR-A2; adding missing-data handling requires changing its Rust renderer. No quiet-tick block mode is enabled. No live deploy or idle-token reduction is claimed by these display changes.
Quiet scheduled ticks (#709 PR-C)¶
idle_gate.toml configures guards.idleGate (on), guards.idleGateMode (one_line, with block opt-in),
guards.idleGateOwnerCronOptIn (off), maintenance patterns, fingerprint fields, wording and the normal-tick ceiling.
The idle-gate dispatch entry aliases the existing registered devswarm-parent-inbox check on both Claude/OMC and
Codex/OMX; its conditions are mutually exclusive with the original entry. Eligibility remains limited to that check's
supervisor/parent-inbox contexts. Codex is silent unless its transcript actually supplies the same scheduled-turn proof;
this adds no Codex scheduler. A typed prompt is never sufficient proof, even when its text matches a cron.
The included engine/logic/idle-gate.js uses the shared dedupe.scheduledTurn detector. The first tick of each session/job,
a changed selected workspace/project fact, a changed task list or recorded session-block count, pending/unknown unread mail,
a mesh gap, running agents, background work or unavailable required state runs normally.
idle_gate.reject_actionable_tasks defaults to true: an unchanged pending/in-progress task without an unresolved
blocker still runs normally. Every live agent already disqualifies gating, including an agent owning an open task.
The transcript must expose a last assistant text turn; newer completion notifications, queued attachments and
unrecognized tool results run normally. Assistant tool calls do not acknowledge these events. A result bound to the
mailbox command is eligible only when its complete output proves zero unread, known mail and no mesh gap; positive
or unknown command output takes precedence over cached zero counts. Malformed baselines and transcript records run normally. Unchanged eligible ticks receive
No change since last tick: reply "idle" and stop immediately, no tool calls. The ceiling forces periodic normal ticks.
The gate refreshes existing no-mail wake-tick and heartbeat records before returning that directive; failed writes speak
normally. The waste_events_total counter uses category idle_scheduled_turn and source idle_gate; no full-context
saving estimate is claimed.
Limits under the no-Rust scope: this gate does not silence other dispatcher checks or their blockers. Their output can
still reach the model. Any sibling workspace in the cached summary runs normally because the script has no per-sibling mailbox freshness proof.
Live-child ticks and --child ticks run normally because watcher rearming/native queue imports are
not exposed to scripts. It does not delete/recreate crons or ask Jev to classify unknown owner prompts; unmatched prompts
fail open. PR/CI/disk facts affect the fingerprint only when the summary supplies configured fields, rather than by new
external polling. ah.sessionBlocks counts recorded blocks and exposes no telemetry-read error; unrecorded blocks and a
telemetry SQL read failure cannot be distinguished through this primitive. A missing or unreadable SQLite header does fail open;
benign telemetry writes do not enter the fingerprint. block emits the existing UPS decision shape but
whether a host avoids its model call is not verified; the live spike was not performed and the mode stays off by default.
The pristine script.toml checksum fixture is untouched; a fallback without the helper preserves normal parent-inbox behavior.
Tool-hook advisory fingerprints (#709) live in tool_advisory.toml (mirrored in defaults.pristine). PreToolUse usage warnings normalize the fullest limit, percentage bucket and reset; PostToolUse pairing reads the authoritative named task list before the transcript. Unchanged advisory text stays silent until its configurable cooldown; recovery followed by relapse speaks again. Blocks bypass suppression. Orchestration rules on spawn are once per session; SubagentStart protocol is once per receiving child identity, and missing identity fails open. Each behavior has a guards switch and a reminder setting, listed in the generated reference. Suppressed text increments waste_events_total with category repeated_advisory and the source. The shared engine logic serves Claude/OMC and Codex/OMX where each host exposes the event; usage and task-owner checks retain their existing Claude-only applicability.
The Advisor-first dispatch notice already fires only at the first thinking dispatch of a user turn; its second dispatch block and later allowed calls retain the existing state machine. This change does not alter that guard.
Runtime Stop reconciliation on both Claude/OMC and Codex/OMX has a shared
silent_nudge.rt_reconcile_bytes input budget (256 KiB) for tracker state, answers
and the session overlay. Metadata is checked before reading, each read is capped,
and a size change discards the evidence. Oversized input increments
runtime_escalation_reconcile_skipped; only reconciliation is skipped, preserving
the original publisher rows, true-positive blocks and existing Stop caps. No
truncated state or answers are interpreted as completion.
Tracker retention is separate: agent_tracker.limits.active_window_ms prunes by
seen, which rediscovery refreshes even for finished rows; done_keep_ms controls
display retention. max_agents limits discovery, not all retained rows.
state_max_bytes rejects oversized loads but does not bound serialized saves.
agent_nudge.limits.log_max trims ordinary closed nudges, while dead-notice append
paths do not apply that trim. A future engine-side bound should trim closed history
on every save and expire completed rows using terminal/last-output age, preserving
live rows and open nudges; it requires Rust changes and is not implemented here.