Skip to content

Commit 399fb59

Browse files
authored
Supervise Sasu runs through hcoord (#8)
* Start the hcoord daemon after a manual stop by converging its LaunchAgent launchd refuses to bootstrap a label it already has loaded with '5: Input/output error', and a stopped hcoord daemon keeps its label loaded, so 'hcoord daemon start' after 'hcoord daemon stop' failed with start_failed. The supervisor's LaunchAgent convergence already reads the loaded state first; it moves to cli/src/support/launchd.ts and the hcoord start converges on its plist and then kickstarts. The fake launchctl now answers a second bootstrap of a loaded label the way launchd does. * Check hcoord registration before dispatch creates a pane An hcoord-supervised dispatch now refuses before any pane or agent exists when the coordinator cannot take the run: a stopped daemon, an Observer pane without a Herdr agent name (dispatch used to invent the name 'observer', which hcoord refused after the implementor had started), or an Observer the coordinator cannot deliver to. 'hcoord sasu preflight' runs those checks without saving anything. The implementor's exact identity is recorded before registration, so a refusal that can only happen after start leaves a started record that --resume-handoff registers and hands off. Resume also stopped demanding a legacy supervisor enrollment, which refused every hcoord resume. Registration now carries the patrol interval as the watch interval, the recovery owner, slug, state path, and the replaced dispatch, and the run binding is readable with 'hcoord sasu show/list'. The Observer registers without a project so one Observer can supervise runs in several trees. Dispatch appends the hcoord notice forewarning to the handoff, status shows the coordinator registration, notify-only requests arrive as HCOORD_NOTICE, and a Sasu watch check names the run's digest command. * Send plan, block, and report to the Observer through hcoord On an hcoord-supervised run 'sasu implement plan' records its event and then sends the Observer an HCOORD_NOTICE naming the plan file. The new 'sasu implement block' carries the OBSERVER_BLOCK fields as a waiting hcoord question; the Observer answers it, or escalates and records a person's words as the human answer with itself as recorder and relays them, and the implementor acknowledges the delivery. The new 'sasu implement report' tells the Observer the current verification verdict right before the final report and declares nothing complete. Each notice's intent is fixed by the run, the event kind and the body, and the same content reuses its Sasu event, so a rerun sends nothing twice. A stopped daemon keeps the letter for later; a refusal fails the command with its reason and retry while the Sasu record stays. Legacy runs keep OBSERVER_BLOCK and their tick wake. Test children no longer inherit the developer's SASU_RUN_INSTANCE_ID. * Move, end, and show hcoord supervision through the run lifecycle 'sasu supervisor handover' on an hcoord run first asks the coordinator to move the watch to the new Observer's exact execution, together with the questions the implementor still waits on; until then the old Observer's place receives nothing. A replacement dispatch names the dispatch it replaces so the coordinator stops watching the gone implementor in the same save. 'sasu implement retire' and a completed ship delivery end the run's watch and cancel what it left open; a refusal names its retry. 'status --digest' adds the supervision owner and the coordinator's own record of the watch: participants, interval, open cycle, and last closed cycle. 'sasu supervisor status' lists hcoord-owned runs by slug from the coordinator, and flags a stopped daemon while any is active. * Document hcoord supervision for the Observer and the Implementor The Observer reference gains an hcoord Supervision section: how dispatch pins the owner and checks the coordinator before any pane, which notices arrive and what each asks, how a block is answered by the Observer or by a person recorded verbatim and relayed, and how recovery, handover, retire, and delivery work on an hcoord run. The legacy supervisor tick is labeled as applying to legacy runs only. The skill entrypoint names block and report, and docs/hcoord.md lists the Sasu subcommands. * Keep a person's unrelayed answer and a stopped cycle consistent across Sasu handover and end Review of 1027cf8 found two ledger gaps. A handover moved only open questions, so an answer a person had recorded through the old Observer but not yet relayed stayed owed to a session that had left; the new Observer now becomes its intermediary and receives the answer to relay. Ending a run whose watch a person had already stopped mid-cycle canceled the cycle's request but left the watch pointing at it; the watch's cycle is now cleared whenever the run ends. * Deliver to an idle or done execution when Herdr reports no readiness flag Herdr 0.9.1 reports interactive_ready only for agents it started, so a hand-started Observer never received hcoord deliveries. One readiness rule now covers delivery and preflight: a missing flag with idle or done state delivers, an explicit false holds, and busy states hold. Spawn paths keep waiting for an explicit true. The Sasu e2e fixture defaults to a hand-started Observer so the common live shape is the tested one. * Wait for launchd to release a booted-out label before bootstrapping it again launchctl bootout returns while the job is still exiting, and a bootstrap sent right after it fails with 5: Input/output error. The live hcoord daemon start that reloaded a changed plist stopped the daemon that way. Every bootout now waits, up to 30 s, for the label to read unloaded; a label that does not settle is reported instead of bootstrapped into a failure. * Identify hcoord participants by machine, pane, and session A Herdr restart gave every pane a new terminal id and cleared agent names while panes and sessions stayed, and matching the terminal made 7 of 12 live participants undeliverable. One predicate now decides whether two bindings are the same execution: machine, host scope, pane, and session, with the terminal compared only for an agent Herdr reports without a session. Delivery, preflight, registration, Sasu registration, handover, discovery, and spawn completion all use it. Registering the same pane and session again returns the same participant and records its current terminal and name; another session in the pane, or the same session in another pane, is still held. * Register an unnamed Observer under a name derived from its session Hand-started Observers carry no Herdr agent name, and since hcoord stopped matching names, refusing them only added a rename step to the normal setup. Dispatch and handover now record such an Observer as observer-<session prefix>, which stays the same across the runs it dispatches and across Herdr restarts; the pane is never renamed. * Run the daemon start tests only on macOS and guard the bootout settle on every platform hcoord daemon start refuses off macOS by design, so its two end-to-end tests failed on the Linux CI runner. They now skip there, and a unit test drives the shared LaunchAgent convergence through an injected launchctl whose bootout settles late, so CI still catches the bootstrap race. * Give hcoord generic end, check, brief, quiet patrol, and short messages - agent register --check answers what registration would decide (execution in its pane, no conflict, official delivery) and saves nothing. - agent end stops the participant's watch, drops its open cycle, and cancels its open questions; a second end changes nothing. - watch assign to another observer moves the target's open questions and unrelayed answers with the watch. - watch start/assign --brief carries the watcher's note on every watch check. - Quiet patrol: when a watched target is not working, its observer gets one check for that change; later cycles, reminders and escalation are skipped until the target works again. - Every HCOORD_* message is an identifier line, the command that closes it, and the carried content; handling steps leave the message. The Sasu e2e fixtures now keep the daemon socket path under the macOS 104-byte limit, which failed every coordinator call as a transport error. * Record a run's hcoord participants in state.json and call only generic hcoord commands - sasu supervisor use hcoord|legacy selects who supervises new dispatches, stored under ~/.sasu/supervisor/; retire-legacy writes its marker there. - Dispatch checks the Observer with agent register --check before any pane, then registers the Observer, the implementor as its child, and the implementor's watch with the patrol interval and a brief naming the digest, the retire step, and the recovery owner; the participant IDs go to state.json supervision.hcoord. A replacement ends the gone implementor. - plan, block and report send by those IDs; handover registers the new Observer and runs watch assign; retire and ship delivery or merge run agent end for the implementor. - The supervisor index lists hcoord runs apart from the tick's entries, so supervisor status shows them and the tick never wakes them. - status and the digest read the watch through agent show by the recorded IDs, and show when patrol is quiet. - sasu supervisor migrate-hcoord records IDs for older hcoord runs from hcoord agent list by pane and session, and reports runs it cannot match. * Remove every Sasu concept from hcoord hcoord now knows participants and the relations between them (parent, watch, request) and nothing about Sasu. The Sasu-specific subcommands and their daemon operations, the ledger's table of Sasu runs, the enable and legacy-retired markers under ~/.hcoord, the run line in delivered messages, and the run decoration on watch list are gone. The ledger loader keeps only the fields it knows, so an older ledger's run table is dropped on the next save. A client-specific hcoord subcommand is a usage error. The dispatch message tells the Observer that patrol stops after one check once the implementor stops working. * Document hcoord notice handling in the implement skill and the hcoord guide Messages now carry only an identifier, the closing command, and content, so the Observer reference explains each notice: the watch check and its brief (retire once verify passes and the PR is merged, otherwise close the cycle), quiet patrol, plan, block, answer, relay and delivery problems. It also covers sasu supervisor use, participant IDs in state.json, migrate-hcoord, handover through watch assign, and agent end on retire and delivery. The hcoord guide describes the generic register --check, agent end, watch brief and assign, quiet patrol, and message format. * Migrate a run whose Observer has duplicate records or a watch moved outside Sasu migrate-hcoord matched participants by bare pane and session, so the live ledger's two records of one Observer execution left this run unmatched, and a watch assigned to a new Observer outside Sasu went unnoticed. It now uses hcoord's own identity rule, keeps the record the implementor's watch points at (else the latest), and when the watch moved to another Observer records the run and names the handover to run from that pane.
1 parent ebbc3f1 commit 399fb59

35 files changed

Lines changed: 2073 additions & 384 deletions

‎cli/src/cli.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,18 @@ Usage:
5050
(archives and re-seals the edited PRD, refreshes metadata, and invalidates the current verification report.)
5151
sasu implement dispatch --name <unique-agent-name> --prd <path> [--kind <agent>] [--model <model>] [--effort <level>] [--env KEY=VALUE ...] [--patrol <minutes>] [--recovery-owner <supervisor|task-factory>] [--json]
5252
(starts exactly one marked implementor in its own pane with the handoff packet on stdin, records this pane as the run's Observer,
53-
and enrolls the run with the supervisor tick; recursive dispatch is refused. Use --resume-handoff for every durable partial phase,
53+
and enrolls the run with the supervisor tick, or after sasu supervisor use hcoord registers it with hcoord, whose watch interval is --patrol;
54+
recursive dispatch is refused. Use --resume-handoff for every durable partial phase,
5455
with --recover-absent-child only for a positively absent recorded started child; that recovery sends no input.)
5556
sasu implement escalate --reason "<what the implementor is stuck on>" [--target <finding-or-issue-ref>] [--agent <herdr-agent>] [--json]
5657
(bounded read-only diagnosis and context recovery; unavailable while a verify execution lease is live.)
5758
sasu implement artifact (--kind <screenshot|image|browser|api|db|log|file> --path <path> --description "<observation>" | --manifest <json-file>) [--source "<collector and method>"] [--collected-at <ISO-time>] [--target "<observed target>"] [--environment "<environment>"] [--refs "<B1,B2,...>"] [--json]
5859
sasu implement plan --path <plan-file> [--json]
59-
(records the execution plan written before the first source change; under Herdr the supervisor tick wakes the Observer once per plan event.)
60+
(records the execution plan written before the first source change; the Observer is woken once per plan: by the supervisor tick, or at once by an hcoord notice.)
61+
sasu implement block --kind <implementation|product|authority|runtime> --question "<text>" --recommendation "<text>" --reversible <yes|no> --scope-impact "<text>" [--external-effect "<text>"] [--json]
62+
(hcoord runs: records the block and asks the Observer through hcoord; end the turn, the answer arrives as HCOORD_ANSWER or HCOORD_RELAY.)
63+
sasu implement report [--summary "<text>"] [--json]
64+
(hcoord runs: right before the final report, sends the Observer the current verification verdict; it declares nothing complete.)
6065
sasu implement status [--slug <topic> | --state <path>] [--digest] [--json]
6166
(--digest prints deterministic facts since dispatch for the run's recorded Observer session; other sessions are refused.)
6267
sasu implement verify [--slug <topic> | --state <path>] [--json]
@@ -78,11 +83,13 @@ Usage:
7883
sasu interview coherence --slug <topic> [--min-decisions <n>] [--json]
7984
sasu interview status --slug <topic> [--json]
8085
sasu supervisor tick [--json] (one level-triggered pass over every indexed run; launchd runs it every 30 s)
81-
sasu supervisor status [--json] (LaunchAgent, last tick, per-run last wake and failure, guarded prompt support)
86+
sasu supervisor status [--json] (LaunchAgent, last tick, per-run last wake and failure, guarded prompt support, and hcoord runs)
8287
sasu supervisor install [--json] (write and load the user LaunchAgent for this build; converges on repeat)
8388
sasu supervisor uninstall [--json] (unload and remove the LaunchAgent and the Sasu Stop hook entries only)
8489
sasu supervisor retire-legacy [--json] (after the final legacy run, retire its LaunchAgent and Stop hook)
8590
sasu supervisor handover --slug <topic> --approval "<verbatim user approval>" [--json] (record this pane's session as the run's Observer)
91+
sasu supervisor use <hcoord|legacy> [--json] (who supervises new dispatches on this machine; dispatched runs keep their owner)
92+
sasu supervisor migrate-hcoord [--state <path> ...] [--json] (one time: record the hcoord participant IDs of older hcoord runs in their state.json from hcoord agent list)
8693
sasu doctor [--json]
8794
8895
Interview commands own the qa-log's mechanical bookkeeping (transcript source

‎cli/src/hcoord/cli.ts‎

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env node
22
import fs from "node:fs";
33
import os from "node:os";
4-
import { officialPromptSupport } from "./herdr";
54
import { HcoordError, LETTER_OPERATIONS, LETTER_SCHEMA, MAX_OUTBOX_LETTERS, REMOTE_PROTOCOL } from "./model";
65
import { outboxCount, readOutboxRaw, removeLetters, writeLetter } from "./outbox";
76
import { readHq, writeHq } from "./remote";
@@ -10,7 +9,7 @@ import { platformSupport, REMOTE_SETUP, startDaemon } from "./platform";
109
import { callDaemon, lastDaemonContact, runDaemon, staleRead, type WireResult } from "./transport";
1110
import { readAlert, reconcileAlert, warningLine } from "./health";
1211
import { notifyText } from "./platform";
13-
import { dataDir, legacyRetiredPath, loadLedger, sasuEnabledPath, stopMarkerPath } from "./store";
12+
import { dataDir, loadLedger, stopMarkerPath } from "./store";
1413

1514
interface Parsed { words: string[]; flags: Map<string, string | true>; tail: string[] }
1615
function parse(argv: string[]): Parsed {
@@ -39,12 +38,13 @@ function route(args: Parsed): { operation: string; data: Record<string, unknown>
3938
if (topic === "status") return { operation: "status", data: {} };
4039
if (topic === "config" && action === "show") return { operation: "status", data: {} };
4140
if (topic === "config" && action === "set") return { operation: "config.set", data: { key: needed(args, "key"), value: duration(needed(args, "value")) } };
42-
if (topic === "agent" && action === "register") return { operation: "agent.register", data: { machine: needed(args, "machine"), hostScope: flag(args, "host-scope") ?? process.env["HERDR_SOCKET_PATH"] ?? "default", session: needed(args, "session"), instance: needed(args, "instance"), name: needed(args, "name"), project: flag(args, "project"), parent: flag(args, "parent"), pane: flag(args, "pane") } };
41+
if (topic === "agent" && action === "register") return { operation: args.flags.has("check") ? "agent.check" : "agent.register", data: { machine: needed(args, "machine"), hostScope: flag(args, "host-scope") ?? process.env["HERDR_SOCKET_PATH"] ?? "default", session: needed(args, "session"), instance: needed(args, "instance"), name: needed(args, "name"), project: flag(args, "project"), parent: flag(args, "parent"), pane: flag(args, "pane") } };
4342
if (topic === "agent" && action === "spawn") return { operation: "agent.spawn", data: { parent: needed(args, "parent"), machine: flag(args, "machine"), repo: flag(args, "repo"), branch: flag(args, "branch"), path: flag(args, "path"), session: needed(args, "session"), name: needed(args, "name"), kind: flag(args, "kind") ?? "codex", intent: needed(args, "intent"), noWatch: args.flags.has("no-watch"), reconcilePane: flag(args, "reconcile-pane"), resumeStart: args.flags.has("resume-start"), nativeArgs: args.tail } };
4443
if (topic === "agent" && action === "list") return { operation: "agent.list", data: { project: flag(args, "project") } };
4544
if (topic === "agent" && action === "show") return { operation: "agent.show", data: { id: target } };
46-
if (topic === "watch" && action === "start") return { operation: "watch.start", data: { target, observer: needed(args, "observer"), actor: flag(args, "actor") ?? needed(args, "observer"), intervalMs: flag(args, "interval") ? duration(needed(args, "interval")) : undefined } };
47-
if (topic === "watch" && action === "assign") return { operation: "watch.assign", data: { target, observer: needed(args, "observer"), actor: needed(args, "actor"), expectedGeneration: flag(args, "expected-generation") } };
45+
if (topic === "agent" && action === "end") return { operation: "agent.end", data: { id: target, actor: needed(args, "actor") } };
46+
if (topic === "watch" && action === "start") return { operation: "watch.start", data: { target, observer: needed(args, "observer"), actor: flag(args, "actor") ?? needed(args, "observer"), intervalMs: flag(args, "interval") ? duration(needed(args, "interval")) : undefined, brief: flag(args, "brief") } };
47+
if (topic === "watch" && action === "assign") return { operation: "watch.assign", data: { target, observer: needed(args, "observer"), actor: needed(args, "actor"), expectedGeneration: flag(args, "expected-generation"), brief: flag(args, "brief") } };
4848
if (topic === "watch" && action === "stop") return { operation: "watch.stop", data: { target, actor: needed(args, "actor") } };
4949
if (topic === "watch" && action === "check") return { operation: "watch.check", data: { target, cycle: needed(args, "cycle"), actor: needed(args, "actor") } };
5050
if (topic === "watch" && action === "list") return { operation: "watch.list", data: {} };
@@ -58,8 +58,7 @@ function route(args: Parsed): { operation: string; data: Record<string, unknown>
5858
if (topic === "inbox") return { operation: "inbox", data: {} };
5959
if (topic === "graph") return { operation: "graph", data: {} };
6060
if (topic === "events") return { operation: "events", data: { cursor: flag(args, "cursor") ?? "0" } };
61-
if (topic === "sasu" && action === "register") return { operation: "sasu.register", data: { run: needed(args, "run"), project: needed(args, "project"), observerName: needed(args, "observer-name"), observerPane: needed(args, "observer-pane"), observerSession: needed(args, "observer-session"), observerInstance: needed(args, "observer-instance"), observerHostScope: flag(args, "observer-host-scope") ?? "default", implementorName: needed(args, "implementor-name"), implementorPane: needed(args, "implementor-pane"), implementorSession: needed(args, "implementor-session"), implementorInstance: needed(args, "implementor-instance"), implementorHostScope: flag(args, "implementor-host-scope") ?? "default" } };
62-
throw new HcoordError("invalid_argument", "usage: hcoord status | agent register/list/show | watch start/check/assign/stop/list | request send/show/reply/relay/ack/cancel/escalate | inbox | graph | events | daemon start/stop/status");
61+
throw new HcoordError("invalid_argument", "usage: hcoord status | agent register [--check]/list/show/end | watch start/check/assign/stop/list | request send/show/reply/relay/ack/cancel/escalate | inbox | graph | events | daemon start/stop/status");
6362
}
6463

6564
/**
@@ -177,27 +176,12 @@ export async function main(argv: string[]): Promise<number> {
177176
if (args.words[0] === "config" && args.words[1] === "set" && args.words[2] === "hq") { const result = await setHq(args.words[3]); print(result, json); return 0; }
178177
const hq = readHq();
179178
if (hq !== "local") {
180-
const { operation, data } = args.words[0] === "daemon" || args.words[0] === "sasu" ? { operation: `${args.words[0]}.${args.words[1]}`, data: {} } : route(args);
179+
const { operation, data } = args.words[0] === "daemon" ? { operation: `${args.words[0]}.${args.words[1]}`, data: {} } : route(args);
181180
if (!LETTER_OPERATIONS.has(operation)) throw new HcoordError("hq_only", `${operation} runs only at the coordinator HQ (${hq}); this machine keeps no conversation record`, { hq });
182181
const letter = writeLetter(operation, data);
183182
print({ ok: true, delivery: "pending", value: { letter: letter.id, operation, reason: `the coordinator at ${hq} applies it when it next collects this machine's letters; nothing else to do`, hq }, observedAt: new Date().toISOString() }, json);
184183
return 0;
185184
}
186-
if (args.words[0] === "sasu" && args.words[1] === "enable") {
187-
const status = await callDaemon("status");
188-
if (!status.ok) { print(status, json); return 1; }
189-
const capability = officialPromptSupport();
190-
if (!capability.ready) throw new HcoordError("unsupported_runtime", `Herdr agent delivery is unsupported or unconfirmed: ${capability.reason}; Sasu transition remains disabled`);
191-
fs.mkdirSync(dataDir(), { recursive: true, mode: 0o700 });
192-
fs.writeFileSync(sasuEnabledPath(), `${new Date().toISOString()}\n`, { mode: 0o600 });
193-
print({ ok: true, value: { enabled: true, newRunsOnly: true, existingRuns: "legacy supervisor retains ownership" }, observedAt: new Date().toISOString() }, json);
194-
return 0;
195-
}
196-
if (args.words[0] === "sasu" && args.words[1] === "status") {
197-
const enabled = fs.existsSync(sasuEnabledPath());
198-
print({ ok: true, value: { enabled, transition: "new runs only", legacySupervisorRetired: fs.existsSync(legacyRetiredPath()), existingRuns: "legacy supervisor until explicitly retired after its final run" }, observedAt: new Date().toISOString() }, json);
199-
return 0;
200-
}
201185
if (args.words[0] === "daemon") {
202186
const action = args.words[1];
203187
if (action === "run") {

0 commit comments

Comments
 (0)