@the-vibe-company/armada 0.2.37 → 0.2.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +5 -3
  2. package/dist/armada.js +650 -330
  3. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -954,7 +954,14 @@ function buildLane(m, allComments, issue, opts) {
954
954
  function inFlight(m, comments, opts) {
955
955
  const held = (i) => {
956
956
  const fresh = freshEvent(i.id, opts);
957
- return fresh ? !ENDS_WORK.includes(fresh.kind) : !!i.agentPhase || isStarted(i);
957
+ const handle = opts.live?.handles?.[i.id];
958
+ const open = !!handle && !handle.releasedAt;
959
+ if (fresh) {
960
+ if (!ENDS_WORK.includes(fresh.kind))
961
+ return true;
962
+ return open && !!handle.claimedAt && handle.claimedAt > fresh.at;
963
+ }
964
+ return open || !!i.agentPhase || isStarted(i);
958
965
  };
959
966
  return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && held(i)).map((i) => buildLane(m, comments, i, opts)).sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
960
967
  }
@@ -3868,89 +3875,6 @@ function updateDotenv(text, updates) {
3868
3875
 
3869
3876
  // ../core/src/live.ts
3870
3877
  import { createHash } from "node:crypto";
3871
- var LAUNCH_WINDOW_MS = 24 * 60 * 60000;
3872
- var UNUSED_LAUNCH_GRACE_MS = 60 * 60000;
3873
- var unusedLaunchExpired = (launch, now) => !launch.tokenUsedAt && now.getTime() > (launch.tokenExpiresAt ? Date.parse(launch.tokenExpiresAt) : Date.parse(launch.launchedAt) + 60 * 60000) + UNUSED_LAUNCH_GRACE_MS;
3874
- var followedLaunches = (launches, now) => launches.filter((launch) => now.getTime() - Date.parse(launch.launchedAt) <= LAUNCH_WINDOW_MS && !unusedLaunchExpired(launch, now));
3875
- var MIN2 = 60000;
3876
- var REWRITTEN = ["hand-back", "plan"];
3877
- var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 12);
3878
- var entryKey = (e) => e.id !== null ? REWRITTEN.includes(e.kind) ? `#${e.id}@${digest(e.body)}` : `#${e.id}` : e.version ? `version:${e.version}` : e.kind === "not-started" && e.body.startsWith("not started (token expired)") ? `not-started:${e.ticket}:expired@${digest(e.body)}` : `${e.kind}:${e.ticket}`;
3879
- function handBackPr(body) {
3880
- const match = body.split(`
3881
- `, 1)[0]?.match(/\bPR #(\d+)\b/i);
3882
- const number = match ? Number(match[1]) : 0;
3883
- return Number.isSafeInteger(number) && number > 0 ? number : null;
3884
- }
3885
- var hhmm = (iso) => `${iso.slice(11, 16)} UTC`;
3886
- function notStartedBody(l, now) {
3887
- const minutes = Math.floor((now.getTime() - Date.parse(l.launchedAt)) / MIN2);
3888
- const why = l.tokenUsedAt ? `the worker signed in with its launch token at ${hhmm(l.tokenUsedAt)}, then stopped before \`armada claim\`` : "its launch token was never used: the worker never reached its `armada login` line (an install that failed, a prompt cut short)";
3889
- return `launched ${minutes} min ago and never claimed; ${why}${l.handle ? ` (session ${l.handle})` : ""}. Check its session with the runtime guide's status section; launch it again with armada brief ${l.ticket} --prompt, or revoke it with armada launch revoke ${l.ticket}`;
3890
- }
3891
- var notStartedLaunches = (launches, now, minutes) => followedLaunches(launches, now).filter((l) => now.getTime() - Date.parse(l.launchedAt) > minutes * MIN2);
3892
-
3893
- // ../core/src/fleet-api.ts
3894
- var WORKER_FLEET_OPS = ["claim", "report", "ask", "release", "heartbeat", "validate"];
3895
- var FLEET_OPS = [
3896
- ...WORKER_FLEET_OPS,
3897
- "register",
3898
- "coordinator",
3899
- "request",
3900
- "events/latest",
3901
- "heartbeats/latest",
3902
- "launches",
3903
- "inbox",
3904
- "inbox/item",
3905
- "inbox/ticket",
3906
- "inbox/resolve",
3907
- "answer",
3908
- "merge",
3909
- "validations",
3910
- "done",
3911
- "lease/acquire",
3912
- "lease/renew",
3913
- "lease/release"
3914
- ];
3915
- var LEASE_TTL_MAX_MS = 60 * 60000;
3916
- var NOT_MODIFIED = Symbol("not modified");
3917
- var CALL_TIMEOUT_MS = 15000;
3918
- function fleetClient(o) {
3919
- const call = async (op, input) => await o.api.fleet(o.signIn, op, { project: o.project, input }, CALL_TIMEOUT_MS);
3920
- return {
3921
- coordinator: (facts) => call("coordinator", facts).then(() => {
3922
- return;
3923
- }),
3924
- request: (input) => call("request", input),
3925
- register: () => call("register", {}).then(() => {
3926
- return;
3927
- }),
3928
- lastEventTimes: () => call("events/latest", {}),
3929
- heartbeatTimes: () => call("heartbeats/latest", {}),
3930
- heartbeat: (input) => call("heartbeat", input),
3931
- pendingLaunches: () => call("launches", {}),
3932
- claim: (c) => call("claim", c),
3933
- report: (r) => call("report", r),
3934
- ask: (q) => call("ask", q),
3935
- release: (r) => call("release", r).then(() => {
3936
- return;
3937
- }),
3938
- inbox: (q) => call("inbox", q),
3939
- inboxItem: (id) => call("inbox/item", { id }),
3940
- ticketItems: (ticket) => call("inbox/ticket", { ticket }),
3941
- answer: (a) => call("answer", a),
3942
- resolve: (r) => call("inbox/resolve", r),
3943
- merge: (m) => call("merge", m),
3944
- validate: (v) => call("validate", v),
3945
- validations: (q) => call("validations", q),
3946
- done: (d) => call("done", d),
3947
- acquireLease: (l) => call("lease/acquire", l),
3948
- renewLease: (l) => call("lease/renew", l),
3949
- releaseLease: (l) => call("lease/release", l).then(() => {
3950
- return;
3951
- })
3952
- };
3953
- }
3954
3878
 
3955
3879
  // ../core/src/github.ts
3956
3880
  var GITHUB_GRAPHQL = "https://api.github.com/graphql";
@@ -4239,6 +4163,105 @@ async function fetchPreview(opts) {
4239
4163
  return https(vercel?.targetUrl);
4240
4164
  }
4241
4165
 
4166
+ // ../core/src/live.ts
4167
+ var LAUNCH_WINDOW_MS = 24 * 60 * 60000;
4168
+ var UNUSED_LAUNCH_GRACE_MS = 60 * 60000;
4169
+ var unusedLaunchExpired = (launch, now) => !launch.tokenUsedAt && now.getTime() > (launch.tokenExpiresAt ? Date.parse(launch.tokenExpiresAt) : Date.parse(launch.launchedAt) + 60 * 60000) + UNUSED_LAUNCH_GRACE_MS;
4170
+ var followedLaunches = (launches, now) => launches.filter((launch) => now.getTime() - Date.parse(launch.launchedAt) <= LAUNCH_WINDOW_MS && !unusedLaunchExpired(launch, now));
4171
+ var MIN2 = 60000;
4172
+ var REWRITTEN = ["hand-back", "plan"];
4173
+ var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 12);
4174
+ var entryKey = (e) => e.id !== null ? REWRITTEN.includes(e.kind) ? `#${e.id}@${digest(e.body)}` : `#${e.id}` : e.version ? `version:${e.version}` : e.kind === "not-started" && e.body.startsWith("not started (token expired)") ? `not-started:${e.ticket}:expired@${digest(e.body)}` : `${e.kind}:${e.ticket}`;
4175
+ function handBackPr(body) {
4176
+ const match = body.split(`
4177
+ `, 1)[0]?.match(/\bPR #(\d+)\b/i);
4178
+ const number = match ? Number(match[1]) : 0;
4179
+ return Number.isSafeInteger(number) && number > 0 ? number : null;
4180
+ }
4181
+ var hhmm = (iso) => `${iso.slice(11, 16)} UTC`;
4182
+ function notStartedBody(l, now) {
4183
+ const minutes = Math.floor((now.getTime() - Date.parse(l.launchedAt)) / MIN2);
4184
+ const why = l.tokenUsedAt ? `the worker signed in with its launch token at ${hhmm(l.tokenUsedAt)}, then stopped before \`armada claim\`` : "its launch token was never used: the worker never reached its `armada login` line (an install that failed, a prompt cut short)";
4185
+ return `launched ${minutes} min ago and never claimed; ${why}${l.handle ? ` (session ${l.handle})` : ""}. Check its session with the runtime guide's status section; launch it again with armada brief ${l.ticket} --prompt, or revoke it with armada launch revoke ${l.ticket}`;
4186
+ }
4187
+ var notStartedLaunches = (launches, now, minutes) => followedLaunches(launches, now).filter((l) => now.getTime() - Date.parse(l.launchedAt) > minutes * MIN2);
4188
+ function freshRuntimeState(observation, now, minutes, claimedAt) {
4189
+ if (!observation || claimedAt && (observation.at < claimedAt || (observation.since ?? observation.at) < claimedAt))
4190
+ return null;
4191
+ const age = now.getTime() - Date.parse(observation.at);
4192
+ return observation.state !== "unknown" && Number.isFinite(age) && age >= 0 && age <= minutes * MIN2 ? observation.state : null;
4193
+ }
4194
+
4195
+ // ../core/src/fleet-api.ts
4196
+ var WORKER_FLEET_OPS = ["claim", "report", "ask", "release", "heartbeat", "validate"];
4197
+ var FLEET_OPS = [
4198
+ ...WORKER_FLEET_OPS,
4199
+ "register",
4200
+ "coordinator",
4201
+ "request",
4202
+ "events/latest",
4203
+ "heartbeats/latest",
4204
+ "runtime/handles",
4205
+ "runtime/handle",
4206
+ "runtime/observe",
4207
+ "runtime/stop",
4208
+ "launches",
4209
+ "inbox",
4210
+ "inbox/item",
4211
+ "inbox/ticket",
4212
+ "inbox/resolve",
4213
+ "answer",
4214
+ "merge",
4215
+ "validations",
4216
+ "done",
4217
+ "lease/acquire",
4218
+ "lease/renew",
4219
+ "lease/release"
4220
+ ];
4221
+ var LEASE_TTL_MAX_MS = 60 * 60000;
4222
+ var NOT_MODIFIED = Symbol("not modified");
4223
+ var CALL_TIMEOUT_MS = 15000;
4224
+ function fleetClient(o) {
4225
+ const call = async (op, input) => await o.api.fleet(o.signIn, op, { project: o.project, input }, CALL_TIMEOUT_MS);
4226
+ return {
4227
+ coordinator: (facts) => call("coordinator", facts).then(() => {
4228
+ return;
4229
+ }),
4230
+ request: (input) => call("request", input),
4231
+ register: () => call("register", {}).then(() => {
4232
+ return;
4233
+ }),
4234
+ lastEventTimes: () => call("events/latest", {}),
4235
+ heartbeatTimes: () => call("heartbeats/latest", {}),
4236
+ heartbeat: (input) => call("heartbeat", input),
4237
+ runtimeHandles: () => call("runtime/handles", {}),
4238
+ runtimeHandle: (ticket) => call("runtime/handle", { ticket }),
4239
+ observeRuntime: (input) => call("runtime/observe", input),
4240
+ stopRuntime: (input) => call("runtime/stop", input),
4241
+ pendingLaunches: () => call("launches", {}),
4242
+ claim: (c) => call("claim", c),
4243
+ report: (r) => call("report", r),
4244
+ ask: (q) => call("ask", q),
4245
+ release: (r) => call("release", r).then(() => {
4246
+ return;
4247
+ }),
4248
+ inbox: (q) => call("inbox", q),
4249
+ inboxItem: (id) => call("inbox/item", { id }),
4250
+ ticketItems: (ticket) => call("inbox/ticket", { ticket }),
4251
+ answer: (a) => call("answer", a),
4252
+ resolve: (r) => call("inbox/resolve", r),
4253
+ merge: (m) => call("merge", m),
4254
+ validate: (v) => call("validate", v),
4255
+ validations: (q) => call("validations", q),
4256
+ done: (d) => call("done", d),
4257
+ acquireLease: (l) => call("lease/acquire", l),
4258
+ renewLease: (l) => call("lease/renew", l),
4259
+ releaseLease: (l) => call("lease/release", l).then(() => {
4260
+ return;
4261
+ })
4262
+ };
4263
+ }
4264
+
4242
4265
  // ../core/src/heartbeat.ts
4243
4266
  async function heartbeatLoop(options) {
4244
4267
  let claimedAt = null;
@@ -4390,7 +4413,10 @@ async function answerItem(ctx, input) {
4390
4413
  ticketId = input.target.trim().toUpperCase();
4391
4414
  if (!input.note) {
4392
4415
  const open = await live(ctx, warnings, `read the open questions of ${ticketId}`, (fleet) => fleet.ticketItems(ticketId ?? ""));
4393
- if (open && !open.some((i) => i.kind === "question" || i.kind === "plan"))
4416
+ const handle = open && !open.some((i) => i.kind === "question" || i.kind === "plan") ? await live(ctx, warnings, `read the runtime of ${ticketId}`, (fleet) => fleet.runtimeHandle(ticketId ?? "")) : null;
4417
+ const observation = handle?.runtimeState;
4418
+ const runtimeBlocked = ctx.deliverAnswer && handle?.runtime.toLowerCase() === "herdr" && !handle.releasedAt && observation?.state === "blocked" && Date.parse(observation.at) <= ctx.now().getTime() && ctx.now().getTime() - Date.parse(observation.at) <= config.policy.silentAfterMinutes * 60000;
4419
+ if (open && !open.some((i) => i.kind === "question" || i.kind === "plan") && !runtimeBlocked)
4394
4420
  throw new Refusal(`${ticketId} has no open question or plan in the inbox`, `armada answer --note ${ticketId} "<message>", for an unsolicited message`);
4395
4421
  }
4396
4422
  }
@@ -4403,6 +4429,11 @@ async function answerItem(ctx, input) {
4403
4429
  const question = item?.kind === "answer-request" ? item.request?.question ?? null : null;
4404
4430
  const answered = question === null ? item : await live(ctx, warnings, `read the item answered by #${item?.id}`, (fleet) => fleet.inboxItem(question));
4405
4431
  const answerKind = answered?.kind === "plan" ? "plan" : "question";
4432
+ const claim = ticketId && ctx.deliverAnswer ? await live(ctx, warnings, `read the claim of ${ticketId}`, (fleet) => fleet.runtimeHandle(ticketId)) : null;
4433
+ if (claim?.runtime.toLowerCase() === "herdr" && claim.releasedAt)
4434
+ throw new Refusal("the herdr worker has ended; no answer was delivered", "armada inbox");
4435
+ if (claim?.runtime.toLowerCase() === "herdr" && answered && answered.createdAt < claim.claimedAt)
4436
+ throw new Refusal("the question belongs to an earlier worker claim; no answer was delivered", "armada inbox");
4406
4437
  let url = "";
4407
4438
  if (ticketId) {
4408
4439
  const ticket = await linear.readTicket(ticketId);
@@ -4410,14 +4441,20 @@ async function answerItem(ctx, input) {
4410
4441
  throw new Refusal(`ticket ${ticketId} not found in Linear`, "armada inbox");
4411
4442
  url = ticket.url;
4412
4443
  warnings.push(...ticket.warnings);
4413
- if (!ticket.agentPhase) {
4444
+ const herdrClaim = claim?.runtime.toLowerCase() === "herdr" && !claim.releasedAt;
4445
+ if (!ticket.agentPhase && !herdrClaim) {
4414
4446
  if (input.note)
4415
4447
  throw new Refusal(`${ticket.id} has no agent phase: no worker holds it, so there is no one to tell`, "armada status, to see which tickets are in flight");
4416
4448
  warnings.push(`${ticket.id} has no agent phase (no worker holds it); the answer was not posted on the ticket`);
4417
4449
  } else {
4418
4450
  const ref = item?.kind === "answer-request" ? `Answers ${question === null ? "the open question or plan" : `${answerKind} #${question}`}, as ${item.author ?? "the owner"} asked from the dashboard (request #${item.id}).` : itemId === null ? null : `Answers ${answerKind} #${itemId}.`;
4419
- await linear.comment(ticket.uuid, statusComment(ticket.agentPhase, input.note ? "note" : "answer", text, ref));
4420
- lines.push(`${input.note ? "Note" : "Answer"} posted on ${ticket.id} (${ticket.agentPhase}).`);
4451
+ if (ctx.deliverAnswer && await ctx.deliverAnswer(ticket.id, text, claim?.runtime ?? ticket.agentRuntime, claim))
4452
+ lines.push(`Delivered to ${ticket.id}'s herdr pane.`);
4453
+ if (ticket.agentPhase) {
4454
+ await linear.comment(ticket.uuid, statusComment(ticket.agentPhase, input.note ? "note" : "answer", text, ref));
4455
+ lines.push(`${input.note ? "Note" : "Answer"} posted on ${ticket.id} (${ticket.agentPhase}).`);
4456
+ } else
4457
+ warnings.push(`${ticket.id} has no tracker phase; the delivered answer is recorded in Armada`);
4421
4458
  }
4422
4459
  }
4423
4460
  const recorded = await live(ctx, warnings, `record the ${input.note ? "note" : "answer"}`, (fleet) => fleet.answer({ text, note: !!input.note, ticket: ticketId, item: itemId }));
@@ -5947,7 +5984,7 @@ The coordinator turns the owner's intent into merged pull requests. Each worker
5947
5984
 
5948
5985
  **Standing authority.** Unless the owner said otherwise, they delegate reversible technical decisions, plan approval and merging to you: act, then report. Escalate only product decisions, irreversible or outward-facing actions, and anything that spends money.
5949
5986
 
5950
- **Armada never drives a runtime.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime: \`armada-runtime-conductor\` for a Conductor workspace, \`armada-runtime-claude-code\` for a subagent of your own Claude Code session (the \`Runtime:\` line of \`armada brief\` names it). Armada records what happened.
5987
+ **Use the worker's runtime guide.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime: \`armada-runtime-conductor\` for a Conductor workspace, \`armada-runtime-claude-code\` for a subagent of your own Claude Code session (the \`Runtime:\` line of \`armada brief\` names it). For persistent local workers, \`armada-runtime-herdr\` uses Armada's integrated launch, state, answer and safe stop commands. Other runtimes are delivered separately and Armada records what happened.
5951
5988
 
5952
5989
  ## Take over a run
5953
5990
 
@@ -5964,7 +6001,7 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
5964
6001
  ## Loop
5965
6002
 
5966
6003
  1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question, plan or request.
5967
- 2. **Answer what waits for you first.** For each question in \`armada inbox\`: decide it, or escalate it to the owner when it is a product decision: \`armada ask-owner <ticket> "<question>" --choices "<a> | <b>"\` puts it on the owner's Validations page and prints the link to send them; their pick arrives as a \`decision\` item. For each \`plan\` item: read the full plan, approve it or give concrete amendments. Deliver the decision in the worker's session with the runtime guide's *message* section, then record it with \`armada answer <item> "approved"\` or \`armada answer <item> "<amendments and reason>"\`. The worker resumes with \`implementing\` on approval, or returns to \`planning\` and submits a revised plan. \`armada answer\` only records; it never reaches the worker. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both. A message the worker did not ask for (main moved, bring it in) takes the same path: deliver it with the runtime guide, then \`armada answer --note <ticket> "<message>"\`. Done when the inbox shows no open question or plan.
6004
+ 2. **Answer what waits for you first.** For each question in \`armada inbox\`: decide it, or escalate it to the owner when it is a product decision: \`armada ask-owner <ticket> "<question>" --choices "<a> | <b>"\` puts it on the owner's Validations page and prints the link to send them; their pick arrives as a \`decision\` item. For each \`plan\` item: read the full plan, approve it or give concrete amendments. Deliver the decision in the worker's session with the runtime guide's *message* section, then record it with \`armada answer <item> "approved"\` or \`armada answer <item> "<amendments and reason>"\`. The worker resumes with \`implementing\` on approval, or returns to \`planning\` and submits a revised plan. \`armada answer\` delivers herdr answers automatically; omit the separate delivery step for herdr. Decide reversible choices yourself and prefer the option that keeps behaviour observable. When two workers need the same shared resource (a migration slot, a generated file, a version number), set the rule once and tell both. A message the worker did not ask for (main moved, bring it in) takes the same path: deliver it with the runtime guide, then \`armada answer --note <ticket> "<message>"\`. A live herdr \`runtime-blocked\` entry has no item id: read the pane and answer by ticket. Done when the inbox shows no open question or plan.
5968
6005
  3. **Carry out the owner's dashboard requests.** They are the owner's word, signed with their name; they never reached a worker.
5969
6006
  - \`answer-request\` (it names the question or plan it answers, \`answers #<id>\`): deliver its text in the worker's session with the runtime guide's *message* section, as the owner's answer or plan approval, then \`armada answer <request id> "<the text you delivered>"\`. That resolves the request and its question or plan, and the ticket names who answered. If the item is gone (the worker was released or changed phase), \`armada answer <request id> "<why>"\` closes it.
5970
6007
  - \`launch-request\`: launch the ticket as in step 5. A request may name a label-routed profile or one the owner chose; otherwise choose from the profiles' \`when\` rules. Pass \`--profile\` and \`--reason\` when a choice or override is needed. The worker's \`armada claim\` resolves the request and posts who asked. If the ticket must not start (it collides with work in flight, or its plan changed), decline it: \`armada answer <request id> "<why>"\`, and tell the owner in your report.
@@ -6019,7 +6056,7 @@ name: armada-runtime-claude-code
6019
6056
  description: Runtime guide for running Armada workers as local subagents of a Claude Code coordinator. Use when an Armada coordinator running in Claude Code must launch a worker on a ticket with the Agent tool, send it a message, check whether a silent worker is still alive, or stop it and clean up its worktree. Four fixed sections, each with the exact tool call and how to read its result.
6020
6057
  ---
6021
6058
 
6022
- Armada never calls a runtime. This guide tells a coordinator running inside Claude Code how to launch, message, check and stop a worker as one of its own subagents (the Agent tool), and what to record in Armada afterwards. It was checked against Claude Code's Agent, SendMessage, TaskStop and EnterWorktree tools as of October 2026; if a parameter below is refused, read the tool's own description and adapt.
6059
+ Armada records Conductor and Claude Code runtime actions separately; persistent herdr workers use integrated commands. This guide tells a coordinator running inside Claude Code how to launch, message, check and stop a worker as one of its own subagents (the Agent tool), and what to record in Armada afterwards. It was checked against Claude Code's Agent, SendMessage, TaskStop and EnterWorktree tools as of October 2026; if a parameter below is refused, read the tool's own description and adapt.
6023
6060
 
6024
6061
  - **A subagent lives inside your session.** It dies when your session ends: closing the terminal, a crash or the end of a cloud machine stops every worker you launched this way, mid-turn. Use this runtime for short tickets you will see through in one sitting. Long runs, and anything that must survive you, go to Conductor (the \`armada-runtime-conductor\` skill).
6025
6062
  - **Always in its own worktree.** A subagent launched without \`isolation: "worktree"\` works in your own checkout: it edits your files and switches your branch under you, and two such workers overwrite each other. Never launch one without it.
@@ -6131,7 +6168,16 @@ A subagent launched without \`isolation: "worktree"\` runs in your checkout. The
6131
6168
  files: [
6132
6169
  {
6133
6170
  path: "SKILL.md",
6134
- content: "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- On a Mac, the app ships the CLI at `/Applications/Conductor.app/Contents/Resources/bin/conductor`, which is not on PATH. `armada doctor` looks for it and prints the fix: a link from a directory already on PATH (`ln -s \"/Applications/Conductor.app/Contents/Resources/bin/conductor\" ~/.local/bin/conductor`), or a PATH line for your shell profile.\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- A worker needs no key in its workspace: the prompt of `armada brief` carries a one-time launch token, and the worker's first command exchanges it for a session limited to its ticket, through which Armada gives each command its keys. The token works once, within the hour, so a copy left in a transcript is useless once used.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\nThe brief starts `armada heartbeat --every 5m --parent \"$PPID\" --background` immediately after claim. It creates a detached process group (like `nohup` + `setsid`) with closed terminal streams and a PID file under `~/.config/armada/watch/`. Plain `&` and `nohup` alone can be killed by command-tool cleanup on Cloud; detached startup survives between turns and while waiting for a message. `$PPID` in the agent's command shell must be the persistent agent process, never `$$` (the shell). The heartbeat stops with that parent or when Armada ends the current session (release, merge, revoke). If startup fails or the runtime cannot retain any background process, fall back to manual reports at least every 15 minutes and record that fallback on the ticket. Reports remain progress dots, not liveness.\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Read the ticket and parent, then choose its profile. A matching label rule wins; otherwise match the profiles' `when` rules by most files/work. Mixed front-end/back-end work: choose the larger part and say why with `--profile <name> --reason \"<why>\"`. An optional `armada brief ABC-12` or `--json` preview helps resolve the choice and warnings, but is read-only: neither creates a launch token nor marks a worker in flight. If the choice is still needed, `--prompt` refuses before minting anything.\n3. **Make one brief call for the launch:** `--prompt --profile-line` writes only the worker prompt to stdout and the selected profile (agent, model, effort, fast mode, runtime and reason) to stderr. Read that line to configure Conductor; no second brief is needed for the profile. Keep any `--profile` and `--reason` flags on this call. Resolve warnings before launching. Never cut a launch message from the human view or `--json`: they carry no token. Write the prompt to a file only you can read, then add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token works once, within the hour; if you cancel or the runtime launch fails, use `armada launch revoke ABC-12`. Generate a fresh prompt if its token has expired.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt --profile-line > /tmp/abc-12-brief.md)\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode. Run the whole block as one command: shell state does not carry over between separate calls.\n\n```sh\nconductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\nrm -f /tmp/abc-12-brief.md\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\nIf the prompt has no launch token, its stderr warning says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then generate a new prompt; `armada doctor` checks the sign-in. Only on an Armada that keeps no keys yet (no accounts or no vault), pass the keys the read-only brief's environment table marks `required`, from your shell or from Armada's credentials file (`in credentials file`: the `set -a` line loads it without printing it; drop it when every variable is set in your shell). The subshell keeps the keys out of the rest of your session. Without a launch token the worker is not signed in to Armada: its claims and reports reach Linear only, with a warning. When Conductor's organization environment still holds the keys, every workspace already has them: use the first block.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\nrm -f /tmp/abc-12-brief.md\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace, and signs `gh` in for the worker's pushes. The brief's first commands install your Armada version (`npm install -g`), sign in with the launch token (`armada login --launch-token`) and claim the ticket. `--env` values are not shown back by `workspace get`.\n- Keys in Conductor's organization environment reach every workspace, workers included: once Armada keeps the organization's keys, they belong on Armada's Keys page, not there.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after `[policy] not_started_minutes` (ten by default): `armada watch` and `armada inbox` show a `not-started` entry; status lists it under \"Pending launches\" with `armada launch revoke ABC-12`. It says whether the worker never used its launch token (it never reached its login line) or signed in and stopped before its claim. An unused token expired more than an hour ago produces one `not started (token expired)` inbox notice, then clears. Exchanged launches without a claim stop being followed after 24 hours and remain revocable. Read the transcript (Status section). A worker whose launch token was refused (already used, or more than an hour old) needs a new one: `armada brief ABC-12 --prompt --profile-line` again, and message it only the `armada login --launch-token …` line of the new `--prompt` output (Message section). A worker cut off from Armada was revoked (Organization > Workers says by whom) or left idle for three days: ask the owner before you give a revoked worker a new token. If the worker cannot claim for another reason, fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n"
6171
+ content: "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada records Conductor and Claude Code runtime actions separately; persistent herdr workers use integrated commands. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- On a Mac, the app ships the CLI at `/Applications/Conductor.app/Contents/Resources/bin/conductor`, which is not on PATH. `armada doctor` looks for it and prints the fix: a link from a directory already on PATH (`ln -s \"/Applications/Conductor.app/Contents/Resources/bin/conductor\" ~/.local/bin/conductor`), or a PATH line for your shell profile.\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- A worker needs no key in its workspace: the prompt of `armada brief` carries a one-time launch token, and the worker's first command exchanges it for a session limited to its ticket, through which Armada gives each command its keys. The token works once, within the hour, so a copy left in a transcript is useless once used.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\nThe brief starts `armada heartbeat --every 5m --parent \"$PPID\" --background` immediately after claim. It creates a detached process group (like `nohup` + `setsid`) with closed terminal streams and a PID file under `~/.config/armada/watch/`. Plain `&` and `nohup` alone can be killed by command-tool cleanup on Cloud; detached startup survives between turns and while waiting for a message. `$PPID` in the agent's command shell must be the persistent agent process, never `$$` (the shell). The heartbeat stops with that parent or when Armada ends the current session (release, merge, revoke). If startup fails or the runtime cannot retain any background process, fall back to manual reports at least every 15 minutes and record that fallback on the ticket. Reports remain progress dots, not liveness.\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Read the ticket and parent, then choose its profile. A matching label rule wins; otherwise match the profiles' `when` rules by most files/work. Mixed front-end/back-end work: choose the larger part and say why with `--profile <name> --reason \"<why>\"`. An optional `armada brief ABC-12` or `--json` preview helps resolve the choice and warnings, but is read-only: neither creates a launch token nor marks a worker in flight. If the choice is still needed, `--prompt` refuses before minting anything.\n3. **Make one brief call for the launch:** `--prompt --profile-line` writes only the worker prompt to stdout and the selected profile (agent, model, effort, fast mode, runtime and reason) to stderr. Read that line to configure Conductor; no second brief is needed for the profile. Keep any `--profile` and `--reason` flags on this call. Resolve warnings before launching. Never cut a launch message from the human view or `--json`: they carry no token. Write the prompt to a file only you can read, then add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token works once, within the hour; if you cancel or the runtime launch fails, use `armada launch revoke ABC-12`. Generate a fresh prompt if its token has expired.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt --profile-line > /tmp/abc-12-brief.md)\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode. Run the whole block as one command: shell state does not carry over between separate calls.\n\n```sh\nconductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\nrm -f /tmp/abc-12-brief.md\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\nIf the prompt has no launch token, its stderr warning says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then generate a new prompt; `armada doctor` checks the sign-in. Only on an Armada that keeps no keys yet (no accounts or no vault), pass the keys the read-only brief's environment table marks `required`, from your shell or from Armada's credentials file (`in credentials file`: the `set -a` line loads it without printing it; drop it when every variable is set in your shell). The subshell keeps the keys out of the rest of your session. Without a launch token the worker is not signed in to Armada: its claims and reports reach Linear only, with a warning. When Conductor's organization environment still holds the keys, every workspace already has them: use the first block.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\nrm -f /tmp/abc-12-brief.md\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace, and signs `gh` in for the worker's pushes. The brief's first commands install your Armada version (`npm install -g`), sign in with the launch token (`armada login --launch-token`) and claim the ticket. `--env` values are not shown back by `workspace get`.\n- Keys in Conductor's organization environment reach every workspace, workers included: once Armada keeps the organization's keys, they belong on Armada's Keys page, not there.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after `[policy] not_started_minutes` (ten by default): `armada watch` and `armada inbox` show a `not-started` entry; status lists it under \"Pending launches\" with `armada launch revoke ABC-12`. It says whether the worker never used its launch token (it never reached its login line) or signed in and stopped before its claim. An unused token expired more than an hour ago produces one `not started (token expired)` inbox notice, then clears. Exchanged launches without a claim stop being followed after 24 hours and remain revocable. Read the transcript (Status section). A worker whose launch token was refused (already used, or more than an hour old) needs a new one: `armada brief ABC-12 --prompt --profile-line` again, and message it only the `armada login --launch-token …` line of the new `--prompt` output (Message section). A worker cut off from Armada was revoked (Organization > Workers says by whom) or left idle for three days: ask the owner before you give a revoked worker a new token. If the worker cannot claim for another reason, fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n"
6172
+ }
6173
+ ]
6174
+ },
6175
+ {
6176
+ name: "armada-runtime-herdr",
6177
+ files: [
6178
+ {
6179
+ path: "SKILL.md",
6180
+ content: '---\nname: armada-runtime-herdr\ndescription: Runtime guide for persistent Armada workers on this machine through herdr. Four sections cover launch, message, status, and stop with safe worktree archival.\n---\n\nHerdr keeps each worker in its own worktree and terminal across coordinator restarts. Run these commands on the machine that launched the worker, against the same herdr server/session. The claim stores JSON `{workspace,pane,agent}`: recover it from `armada status --json` or the ticket\'s claim comment instead of relying on your old coordinator session. Requires herdr 0.9.1+, a supported harness already signed in, and an Armada coordinator sign-in. Never handle harness keys or sign-ins.\n\n## Launch\n\n```sh\narmada launch ABC-12 --runtime herdr --profile backend --reason "back end work" --json\n```\n\nThe profile in `[herdr.profiles]` selects the harness, model and effort. Label routing wins; use a reason for semantic selection or an override. An optional `--harness claude|codex|opencode|deepseek` checks the selected profile. DeepSeek profiles run OpenCode with the exact configured DeepSeek model; Armada reports their runtime agent as `opencode` while preserving the DeepSeek profile label. Launch checks tools first, creates a worktree, starts the harness, and sends the scoped worker brief. Its JSON gives the `handle` and worktree path, without the token. The worker signs in with its one-time launch token, claims the stored handle and starts its heartbeat. No claim after the configured timeout: read the pane, fix the cause, or revoke the unused launch with `armada launch revoke ABC-12`. Failed launch retains the worktree for inspection.\n\n## Message\n\n```sh\narmada answer <inbox-id> "Plan approved. Go on."\narmada answer ABC-12 "<answer to a live harness approval or question>"\narmada answer --note ABC-12 --message-file /tmp/abc-12-message.md\n```\n\nFor herdr, Armada verifies the saved pane, delivers literal text plus Enter and then records the answer on the ticket and in the inbox. Read an approval UI before deciding what input it expects; the answer may be a short choice such as `y`. Delivery errors leave the question open and write no successful answer. Inspect the pane before retrying after a timeout: the terminal may already have received the input. There is no separate delivery step. Successful delivery confirms submission, not that the worker has completed a turn. For other runtimes, follow their guide and deliver before recording with Armada.\n\n## Status\n\n```sh\narmada status --json\narmada inbox\nherdr agent get <pane>\nherdr agent read <pane> --source recent-unwrapped --lines 120\nherdr agent wait <pane> --until idle --until done --until blocked --timeout 30000\n```\n\n`status`, `inbox` and each `watch` poll discover workers from persisted claims and publish local observations to Armada. The dashboard shows that stored live state beside the last report; it never probes a local runtime. Observations expire after `policy.silence_minutes`.\n\nHerdr\'s `.result.agent` carries `workspace_id`, `pane_id`, `name` and `agent_status`. Verify all three IDs against the claim. `working` is a running turn, `blocked` is an approval or question UI, and `idle`/`done` are ready for input. A live `runtime-blocked` inbox entry can appear before a worker report; read its pane and answer by ticket. It clears after an answer until the next blocked transition. Herdr\'s state-change counter preserves approvals that arrive between polls, even when both readings are blocked. `unknown` falls back to Armada reports; it is not proof of completion. DeepSeek and other harnesses also report their phase to herdr via `pane report-agent --source armada` on report, ask and heartbeat. Reporting failures warn and do not fail the worker command.\n\nTerminal reads print text directly, not JSON. Do not paste credentials or complete transcripts into tickets. A coordinator restart changes no worker handle: read `armada status` and continue from those claims.\n\n## Stop and archive\n\n```sh\n# For unfinished work, release the ticket with its reason first.\narmada release --ticket ABC-12 --reason "<why the worker is being stopped>"\narmada stop ABC-12\n```\n\nAfter merge, run `armada stop ABC-12` directly; the released claim is still discoverable for cleanup. Stop verifies the linked worktree belongs to this repository and the claim\'s branch. It refuses uncommitted files (including untracked files), a missing remote upstream, an unreachable upstream, or commits not on that upstream, and explains what remains. Push or preserve that work before retrying; never force removal. It fetches the configured upstream, interrupts an active turn and waits up to five seconds for idle or done, then rechecks the checkout before `herdr worktree remove --workspace <workspace>` without `--force`. Herdr ends the workspace terminals and removes the checkout; the branch remains. The exact saved claim is marked ended. If the worker does not settle, the checkout stays intact; inspect the pane and retry. Failed removal leaves the claim and checkout for inspection; inspect `herdr worktree list` before retrying a timeout.\n'
6135
6181
  }
6136
6182
  ]
6137
6183
  },
@@ -9884,6 +9930,7 @@ function buildStatus({
9884
9930
  lastUpdate: l.lastUpdate,
9885
9931
  lastReport: l.lastReport,
9886
9932
  lastHeartbeat: l.lastHeartbeat,
9933
+ runtimeState: freshRuntimeState(live?.handles?.[l.issue.id]?.runtimeState, now, config.policy.silentAfterMinutes, live?.handles?.[l.issue.id]?.claimedAt),
9887
9934
  silent: l.flags.includes("silent"),
9888
9935
  statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url, plan: l.statusLine.plan } : null,
9889
9936
  pr: l.pr ? prRef(l.pr) : null,
@@ -9948,12 +9995,15 @@ async function loadStatus(config, opts) {
9948
9995
  const launchesP = opts.launches ? opts.launches().then((launches) => ({ launches }), (err) => ({
9949
9996
  warning: `Armada's launches could not be read (${err instanceof Error ? err.message : String(err)}); workers launched that never started are not listed`
9950
9997
  })) : Promise.resolve({});
9951
- const [{ program, forge, forgeError }, events, launches, heartbeats] = await Promise.all([
9998
+ const [{ program, forge, forgeError }, events, launches, heartbeats, runtimeHandles] = await Promise.all([
9952
9999
  readStatusSources(config, opts),
9953
10000
  eventsP,
9954
10001
  launchesP,
9955
10002
  opts.heartbeats?.().catch(() => {
9956
10003
  return;
10004
+ }),
10005
+ opts.runtimeHandles?.().catch(() => {
10006
+ return;
9957
10007
  })
9958
10008
  ]);
9959
10009
  return buildStatus({
@@ -9963,6 +10013,13 @@ async function loadStatus(config, opts) {
9963
10013
  forgeError,
9964
10014
  ...events.events ? { lastEvents: events.events } : {},
9965
10015
  ...heartbeats ? { heartbeats } : {},
10016
+ ...runtimeHandles ? {
10017
+ live: {
10018
+ after: program.fetchedAt,
10019
+ events: {},
10020
+ handles: Object.fromEntries(runtimeHandles.map((h) => [h.ticket, h]))
10021
+ }
10022
+ } : {},
9966
10023
  ...launches.launches ? { launches: launches.launches } : {},
9967
10024
  extraWarnings: [events.warning, launches.warning].filter((w) => !!w),
9968
10025
  now: now()
@@ -10093,7 +10150,7 @@ ${attachments.join(`
10093
10150
  };
10094
10151
  }
10095
10152
  // package.json
10096
- var version = "0.2.37";
10153
+ var version = "0.2.39";
10097
10154
 
10098
10155
  // src/attach.ts
10099
10156
  import { resolve } from "node:path";
@@ -10630,73 +10687,463 @@ async function logout(io) {
10630
10687
  return 0;
10631
10688
  }
10632
10689
 
10633
- // src/worker.ts
10634
- function liveFleet(io, config, credentials) {
10635
- const signIn = credentials.armadaSignIn;
10636
- if (!signIn)
10637
- return {
10638
- fleet: null,
10639
- warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
10640
- };
10641
- try {
10642
- const api = apiOf(io, credentials.armadaApi.url);
10643
- return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
10644
- } catch (err) {
10645
- return {
10646
- fleet: null,
10647
- warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
10648
- };
10690
+ // src/herdr.ts
10691
+ class HerdrError extends UsageError {
10692
+ code;
10693
+ constructor(message, code) {
10694
+ super(message);
10695
+ this.code = code;
10649
10696
  }
10650
10697
  }
10651
- function statusLive(io, config, credentials) {
10652
- const { fleet } = liveFleet(io, config, credentials);
10653
- return fleet ? {
10654
- lastEvents: () => fleet.lastEventTimes(),
10655
- heartbeats: () => fleet.heartbeatTimes(),
10656
- launches: () => fleet.pendingLaunches()
10657
- } : undefined;
10658
- }
10659
- function currentTicket(io, config, explicit, workers = []) {
10660
- const fromEnv = io.env.ARMADA_TICKET?.trim();
10661
- const id = explicit?.trim() || fromEnv || (() => {
10662
- const branch = io.gitBranch?.();
10663
- return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
10664
- })() || (workers.length === 1 ? workers[0] : null);
10665
- if (!id)
10666
- throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
10667
- return id.toUpperCase();
10668
- }
10669
- function context(io, config, credentials) {
10670
- if (!credentials.linearApiKey)
10671
- throw missingKey(LINEAR_KEY);
10672
- const linearOpts = {
10673
- apiKey: credentials.linearApiKey,
10674
- labels: config.tracker.labels,
10675
- ...io.fetch ? { fetch: io.fetch } : {}
10676
- };
10677
- const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
10678
- const live = liveFleet(io, config, credentials);
10679
- const token = credentials.githubToken;
10680
- return {
10681
- config,
10682
- linear,
10683
- fleet: async () => live,
10684
- readPull: token ? (number) => fetchPullRequest({
10685
- token,
10686
- repository: config.github.repository,
10687
- number,
10688
- ...io.fetch ? { fetch: io.fetch } : {}
10689
- }) : null,
10690
- now: io.now ?? (() => new Date)
10691
- };
10692
- }
10693
- function print(io, outcome, json) {
10694
- if (json) {
10695
- io.stdout(`${JSON.stringify(outcome, null, 2)}
10696
- `);
10698
+ var harnessArgs = (p) => [
10699
+ "--model",
10700
+ herdrHarnessKind(p.harness) === "opencode" ? `${p.model.split("#")[0]}#${p.effort}` : p.model,
10701
+ ...p.harness === "codex" ? ["-c", `model_reasoning_effort=${JSON.stringify(p.effort)}`] : p.harness === "claude" ? ["--effort", p.effort] : [],
10702
+ ...p.extraArgs
10703
+ ];
10704
+ var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
10705
+ var id = (v) => typeof v === "string" && /^[a-zA-Z0-9][a-zA-Z0-9:_-]{0,127}$/.test(v);
10706
+ function parseHerdrHandle(raw) {
10707
+ let h = null;
10708
+ try {
10709
+ h = object(JSON.parse(raw));
10710
+ } catch {}
10711
+ if (!h || !id(h.workspace) || !id(h.pane) || !id(h.agent) || !/^[a-z][a-z0-9_-]{0,31}$/.test(h.agent))
10712
+ throw new UsageError("invalid herdr claim handle; expected JSON with workspace, pane and agent");
10713
+ return { workspace: h.workspace, pane: h.pane, agent: h.agent };
10714
+ }
10715
+ function herdrPhase(phase) {
10716
+ if (phase === "blocked" || phase === "awaiting-approval" || phase === "awaiting-validation")
10717
+ return "blocked";
10718
+ if (phase === "ready-to-merge")
10719
+ return "idle";
10720
+ return phase && ["planning", "implementing", "shipping"].includes(phase) ? "working" : "unknown";
10721
+ }
10722
+ async function reportHerdr(io, phase, agent, heartbeat = false) {
10723
+ if (io.env.HERDR_ENV !== "1" || !io.env.HERDR_PANE_ID)
10697
10724
  return;
10725
+ try {
10726
+ if (!id(io.env.HERDR_PANE_ID))
10727
+ throw new Error("invalid pane");
10728
+ await new Herdr(io).report(io.env.HERDR_PANE_ID, agent, herdrPhase(phase), heartbeat);
10729
+ } catch {
10730
+ io.stderr(`armada: warning: could not report worker state to herdr; Armada reporting continues.
10731
+ `);
10698
10732
  }
10699
- const out = [...outcome.lines];
10733
+ }
10734
+ var runtimeEnvironment = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => /^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TMP|TEMP|LANG|TERM|LC_[A-Z_]+|XDG_(CONFIG_HOME|DATA_HOME|STATE_HOME|CACHE_HOME|RUNTIME_DIR)|HERDR_(SESSION|SOCKET_PATH|CONFIG_PATH))$/.test(name)));
10735
+ var credentialNames = (env, extra) => [
10736
+ ...new Set([
10737
+ "LINEAR_API_KEY",
10738
+ "GITHUB_TOKEN",
10739
+ "GH_TOKEN",
10740
+ "ARMADA_API_KEY",
10741
+ "ARMADA_SESSION_TOKEN",
10742
+ "ARMADA_SIGNED_IN_TO",
10743
+ "ARMADA_API_URL",
10744
+ "OPENAI_API_KEY",
10745
+ "ANTHROPIC_API_KEY",
10746
+ ...Object.keys(env).filter((name) => /^(ARMADA_|CONDUCTOR_)|(?:KEY|TOKEN|SECRET|PASSWORD)$/.test(name)),
10747
+ ...extra
10748
+ ])
10749
+ ].filter((name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)).sort();
10750
+
10751
+ class Herdr {
10752
+ io;
10753
+ constructor(io) {
10754
+ this.io = io;
10755
+ }
10756
+ async call(args, timeoutMs = 40000) {
10757
+ const operation = args.slice(0, 2).join(" ");
10758
+ let reply;
10759
+ let code;
10760
+ try {
10761
+ if (!this.io.exec)
10762
+ throw new Error("no exec");
10763
+ const out = await this.io.exec("herdr", args, { cwd: this.io.cwd, timeoutMs });
10764
+ code = out.code;
10765
+ if (code === 0 && !out.stdout.trim() && !out.stderr.trim() && ["pane run", "pane report-agent"].includes(operation))
10766
+ return {};
10767
+ reply = object(JSON.parse(out.stdout || out.stderr));
10768
+ } catch {
10769
+ throw new UsageError(`herdr ${operation} failed; inspect the runtime with herdr agent list`);
10770
+ }
10771
+ const error = object(reply?.error);
10772
+ if (code !== 0 || error) {
10773
+ const reason = typeof error?.code === "string" && /^[a-z_]{1,64}$/.test(error.code) ? ` (${error.code})` : "";
10774
+ throw new HerdrError(`herdr ${operation} failed${reason}; inspect the runtime with herdr agent list`, reason ? String(error?.code) : null);
10775
+ }
10776
+ if (!reply)
10777
+ throw new UsageError(`herdr ${operation} returned invalid JSON`);
10778
+ return reply;
10779
+ }
10780
+ async ensureServer() {
10781
+ const status = async (timeoutMs) => {
10782
+ const server = object((await this.call(["status", "--json"], timeoutMs)).server);
10783
+ if (!server || typeof server.running !== "boolean")
10784
+ throw new UsageError("invalid herdr server status response");
10785
+ if (server.running && (server.compatible === false || server.endpoint_compatible === false))
10786
+ throw new UsageError("the running herdr server is incompatible; update or restart it before launching");
10787
+ return server.running;
10788
+ };
10789
+ if (await status(5000))
10790
+ return;
10791
+ if (!this.io.detach || !await this.io.detach("herdr", ["server"], { cwd: this.io.cwd, env: runtimeEnvironment(this.io.env) }))
10792
+ throw new UsageError("could not start herdr server; start it headless with herdr server");
10793
+ const now = this.io.now ?? (() => new Date);
10794
+ const deadline = now().getTime() + 5000;
10795
+ for (let attempt = 0;attempt < 20; attempt++) {
10796
+ const remaining = deadline - now().getTime();
10797
+ if (remaining <= 0)
10798
+ break;
10799
+ if (await status(Math.min(1000, remaining)))
10800
+ return;
10801
+ const delay = Math.min(250, deadline - now().getTime());
10802
+ if (delay > 0)
10803
+ await (this.io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))))(delay);
10804
+ }
10805
+ throw new UsageError("herdr server did not become ready; inspect herdr status");
10806
+ }
10807
+ async create(input) {
10808
+ const agent = input.ticket.toLowerCase();
10809
+ if (!/^[a-z][a-z0-9_-]{0,31}$/.test(agent))
10810
+ throw new UsageError("ticket cannot be used as a herdr agent name");
10811
+ const r = object((await this.call([
10812
+ "worktree",
10813
+ "create",
10814
+ "--cwd",
10815
+ input.repo,
10816
+ "--branch",
10817
+ input.branch,
10818
+ "--base",
10819
+ input.base,
10820
+ "--no-focus"
10821
+ ])).result);
10822
+ const workspace = object(r?.workspace)?.workspace_id;
10823
+ const rootPane = object(r?.root_pane)?.pane_id;
10824
+ const path = object(r?.worktree)?.path;
10825
+ if (!id(workspace) || !id(rootPane) || typeof path !== "string" || !path.startsWith("/") || object(r?.root_pane)?.workspace_id !== workspace)
10826
+ throw new UsageError("invalid herdr worktree response; inspect herdr worktree list before retrying");
10827
+ const tab = object((await this.call([
10828
+ "tab",
10829
+ "create",
10830
+ "--workspace",
10831
+ workspace,
10832
+ "--cwd",
10833
+ path,
10834
+ "--no-focus",
10835
+ ...credentialNames(this.io.env, input.secrets ?? []).flatMap((name) => ["--env", `${name}=`]),
10836
+ "--env",
10837
+ `ARMADA_TICKET=${input.ticket}`
10838
+ ])).result);
10839
+ const pane = object(tab?.root_pane)?.pane_id;
10840
+ if (!id(pane) || pane === rootPane || object(tab?.root_pane)?.workspace_id !== workspace)
10841
+ throw new UsageError("invalid herdr worker pane response; inspect herdr pane list before retrying");
10842
+ await this.call(["pane", "close", rootPane]);
10843
+ return { workspace, pane, agent, path };
10844
+ }
10845
+ async start(handle, profile) {
10846
+ const r = await this.call([
10847
+ "agent",
10848
+ "start",
10849
+ handle.agent,
10850
+ "--kind",
10851
+ herdrHarnessKind(profile.harness),
10852
+ "--pane",
10853
+ handle.pane,
10854
+ "--timeout",
10855
+ "30000",
10856
+ "--",
10857
+ ...harnessArgs(profile)
10858
+ ]);
10859
+ this.checkAgent(r, handle);
10860
+ }
10861
+ async prompt(handle, prompt) {
10862
+ const r = await this.call([
10863
+ "agent",
10864
+ "prompt",
10865
+ handle.agent,
10866
+ prompt,
10867
+ "--wait",
10868
+ "--until",
10869
+ "working",
10870
+ "--timeout",
10871
+ "30000"
10872
+ ]);
10873
+ const agent = this.checkAgent(r, handle);
10874
+ if (agent.agent_status !== "working")
10875
+ throw new UsageError("herdr did not confirm the worker is working");
10876
+ }
10877
+ async state(handle) {
10878
+ return (await this.reading(handle)).state;
10879
+ }
10880
+ async reading(handle) {
10881
+ const agent = this.checkAgent(await this.call(["agent", "get", handle.pane], 5000), handle);
10882
+ const state = agent.agent_status;
10883
+ if (!["working", "blocked", "idle", "done", "unknown"].includes(String(state)))
10884
+ throw new UsageError("invalid herdr agent state");
10885
+ const sequence = agent.state_change_seq;
10886
+ if (sequence !== undefined && (!Number.isSafeInteger(sequence) || Number(sequence) < 0))
10887
+ throw new UsageError("invalid herdr state-change sequence");
10888
+ return { state, ...sequence === undefined ? {} : { sequence: Number(sequence) } };
10889
+ }
10890
+ async message(handle, text) {
10891
+ const state = await this.state(handle);
10892
+ if (state === "blocked")
10893
+ await this.call(["pane", "run", handle.pane, text]);
10894
+ else
10895
+ this.checkAgent(await this.call(["agent", "prompt", handle.pane, text]), handle);
10896
+ }
10897
+ async quiesce(handle) {
10898
+ const state = await this.state(handle);
10899
+ if (state === "idle" || state === "done")
10900
+ return;
10901
+ if (state === "unknown")
10902
+ throw new UsageError("cannot stop an unverified active turn; wait for herdr idle state");
10903
+ await this.call(["agent", "send-keys", handle.pane, "ctrl+c"], 5000);
10904
+ const agent = this.checkAgent(await this.call(["agent", "wait", handle.pane, "--until", "idle", "--until", "done", "--timeout", "5000"], 7000), handle);
10905
+ if (agent.agent_status !== "idle" && agent.agent_status !== "done")
10906
+ throw new UsageError("worker is still active; its worktree was retained");
10907
+ }
10908
+ async report(pane, agent, state, heartbeat = false) {
10909
+ if (agent === "armada" || heartbeat) {
10910
+ const current = object(object((await this.call(["pane", "get", pane], 5000)).result)?.pane);
10911
+ if (current?.pane_id !== pane)
10912
+ throw new UsageError("invalid herdr pane response");
10913
+ if (agent === "armada" && typeof current.agent === "string" && current.agent)
10914
+ agent = current.agent;
10915
+ if (heartbeat && state === "working" && current.agent_status === "blocked")
10916
+ state = "blocked";
10917
+ }
10918
+ if (agent === "deepseek" || agent === herdrHarnessLabel("deepseek"))
10919
+ agent = herdrHarnessKind("deepseek");
10920
+ await this.call(["pane", "report-agent", pane, "--source", "armada", "--agent", agent, "--state", state], 5000);
10921
+ }
10922
+ async worktree(handle) {
10923
+ const ws = object(object((await this.call(["workspace", "get", handle.workspace], 5000)).result)?.workspace);
10924
+ const tree = object(ws?.worktree);
10925
+ if (ws?.workspace_id !== handle.workspace || tree?.is_linked_worktree !== true || typeof tree.repo_root !== "string" || !tree.repo_root.startsWith("/") || typeof tree.checkout_path !== "string" || !tree.checkout_path.startsWith("/") || tree.repo_root === tree.checkout_path)
10926
+ throw new UsageError("herdr workspace is not a verified linked worktree; left it untouched");
10927
+ return { repo: tree.repo_root, path: tree.checkout_path };
10928
+ }
10929
+ async remove(handle, path) {
10930
+ const result = object((await this.call(["worktree", "remove", "--workspace", handle.workspace])).result);
10931
+ if (result?.workspace_id !== handle.workspace || result?.path !== path || result?.forced !== false)
10932
+ throw new UsageError("invalid herdr worktree removal response; inspect herdr worktree list before retrying");
10933
+ }
10934
+ checkAgent(reply, handle) {
10935
+ const agent = object(object(reply.result)?.agent);
10936
+ if (!agent || agent.name !== handle.agent || agent.pane_id !== handle.pane || agent.workspace_id !== handle.workspace)
10937
+ throw new UsageError("invalid herdr agent response; inspect herdr agent list before retrying");
10938
+ return agent;
10939
+ }
10940
+ }
10941
+
10942
+ // src/runtime.ts
10943
+ var isHerdr = (runtime) => runtime.toLowerCase() === "herdr";
10944
+ async function observeHerdr(io, fleet) {
10945
+ const handles = await fleet.runtimeHandles();
10946
+ const local = handles.filter((h) => isHerdr(h.runtime));
10947
+ if (!local.length)
10948
+ return handles;
10949
+ await Promise.all(local.map(async (h) => {
10950
+ try {
10951
+ await verifyProvenance(io, h);
10952
+ const reading = await new Herdr(io).reading(parseHerdrHandle(h.handle));
10953
+ await fleet.observeRuntime({ ticket: h.ticket, handle: h.handle, claimedAt: h.claimedAt, ...reading });
10954
+ } catch {}
10955
+ }));
10956
+ return fleet.runtimeHandles();
10957
+ }
10958
+ function observingFleet(io, fleet) {
10959
+ return {
10960
+ ...fleet,
10961
+ inbox: async (query) => {
10962
+ try {
10963
+ await observeHerdr(io, fleet);
10964
+ } catch {}
10965
+ return fleet.inbox(query);
10966
+ }
10967
+ };
10968
+ }
10969
+ async function deliverHerdr(io, fleet, ticket, text, expected) {
10970
+ const h = await fleet.runtimeHandle(ticket);
10971
+ if (!h || !isHerdr(h.runtime))
10972
+ return false;
10973
+ if (!expected || h.handle !== expected.handle || h.claimedAt !== expected.claimedAt)
10974
+ throw new Refusal(`${ticket}'s claim changed before delivery; no answer was delivered`, "armada inbox");
10975
+ if (h.releasedAt)
10976
+ throw new Refusal(`${ticket}'s herdr worker has ended; no answer was delivered`, "armada status");
10977
+ await verifyProvenance(io, h);
10978
+ const current = await fleet.runtimeHandle(ticket);
10979
+ if (!current || current.handle !== h.handle || current.claimedAt !== h.claimedAt || current.releasedAt)
10980
+ throw new Refusal(`${ticket}'s claim changed before delivery; no answer was delivered`, "armada inbox");
10981
+ await new Herdr(io).message(parseHerdrHandle(h.handle), text);
10982
+ return true;
10983
+ }
10984
+ async function verifyProvenance(io, h) {
10985
+ const tree = await new Herdr(io).worktree(parseHerdrHandle(h.handle));
10986
+ const git = async (cwd, args) => {
10987
+ const result = await io.exec?.("git", args, { cwd, timeoutMs: 5000 });
10988
+ if (result?.code !== 0)
10989
+ throw new Refusal("could not verify the herdr claim repository", "armada status");
10990
+ return result.stdout.trim();
10991
+ };
10992
+ const commonArgs = ["rev-parse", "--path-format=absolute", "--git-common-dir"];
10993
+ const local = await git(io.cwd, commonArgs);
10994
+ const worker = await git(tree.path, commonArgs);
10995
+ if (!local || local !== worker || !h.branch || await git(tree.path, ["branch", "--show-current"]) !== h.branch)
10996
+ throw new Refusal("herdr workspace does not match the claimed repository and branch", "armada status");
10997
+ }
10998
+ async function stop(io, config, credentials, args) {
10999
+ const [raw, ...extra] = args.rest;
11000
+ if (!raw || extra.length)
11001
+ throw new Refusal("stop needs one ticket: armada stop <ticket>", "armada stop --help");
11002
+ requireSignIn(credentials);
11003
+ const { fleet } = liveFleet(io, config, credentials);
11004
+ if (!fleet)
11005
+ throw new Refusal("stop needs Armada's stored claim", "armada whoami");
11006
+ const ticket = raw.toUpperCase();
11007
+ const h = await fleet.runtimeHandle(ticket);
11008
+ if (!h || !isHerdr(h.runtime))
11009
+ throw new Refusal(`${ticket} has no herdr claim to stop`, "armada status");
11010
+ const handle = parseHerdrHandle(h.handle);
11011
+ const runtime = new Herdr(io);
11012
+ let tree;
11013
+ try {
11014
+ tree = await runtime.worktree(handle);
11015
+ } catch (error) {
11016
+ if (!(error instanceof HerdrError) || error.code !== "workspace_not_found")
11017
+ throw error;
11018
+ if (!await fleet.stopRuntime({ ticket, handle: h.handle, claimedAt: h.claimedAt }))
11019
+ throw new Refusal("claim changed during archive recovery", "armada status");
11020
+ io.stdout(args.json ? `${JSON.stringify({ ticket, stopped: true, alreadyAbsent: true })}
11021
+ ` : `${ticket}'s herdr workspace is already absent; its claim is ended.
11022
+ `);
11023
+ return 0;
11024
+ }
11025
+ const git = async (cwd, argv) => {
11026
+ const r = await io.exec?.("git", argv, { cwd, timeoutMs: 30000 });
11027
+ if (r?.code !== 0)
11028
+ throw new Refusal("could not verify the worker's Git state; left its worktree untouched", `git -C ${tree.path} status`);
11029
+ return r.stdout.trim();
11030
+ };
11031
+ const localCommon = await git(io.cwd, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
11032
+ const treeCommon = await git(tree.path, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
11033
+ const branch = await git(tree.path, ["branch", "--show-current"]);
11034
+ if (localCommon !== treeCommon || !h.branch || branch !== h.branch)
11035
+ throw new Refusal("herdr worktree does not match this repository and claim branch; left it untouched", "herdr worktree list");
11036
+ const dirty = await git(tree.path, ["status", "--porcelain=v1", "--untracked-files=all"]);
11037
+ if (dirty)
11038
+ throw new Refusal(`cannot stop ${ticket}: uncommitted work remains:
11039
+ ${dirty}`, `git -C ${tree.path} status`);
11040
+ const upstream = await git(tree.path, [
11041
+ "for-each-ref",
11042
+ "--format=%(upstream:remotename)%00%(upstream:remoteref)",
11043
+ `refs/heads/${branch}`
11044
+ ]);
11045
+ const [remote, ref] = upstream.split("\x00");
11046
+ if (!remote || remote === "." || remote.startsWith("-") || !ref?.startsWith("refs/heads/"))
11047
+ throw new Refusal(`cannot stop ${ticket}: the branch has no verified remote upstream`, `git -C ${tree.path} push -u origin ${branch}`);
11048
+ const advertised = await git(tree.path, ["ls-remote", "--exit-code", "--heads", "--", remote, ref]);
11049
+ const [remoteHead, remoteRef] = advertised.split("\t");
11050
+ if (!/^[a-f0-9]{40,64}$/.test(remoteHead ?? "") || remoteRef !== ref)
11051
+ throw new Refusal(`cannot stop ${ticket}: could not verify the upstream head`, `git -C ${tree.path} fetch`);
11052
+ await git(tree.path, ["fetch", "--no-tags", "--no-write-fetch-head", "--", remote, ref]);
11053
+ const localHead = await git(tree.path, ["rev-parse", "HEAD"]);
11054
+ const left = await git(tree.path, ["log", "--format=%h %s", `${remoteHead}..${localHead}`]);
11055
+ if (left)
11056
+ throw new Refusal(`cannot stop ${ticket}: unpushed commits remain:
11057
+ ${left}`, `git -C ${tree.path} push`);
11058
+ await runtime.quiesce(handle);
11059
+ if (await git(tree.path, ["status", "--porcelain=v1", "--untracked-files=all"]))
11060
+ throw new Refusal(`cannot stop ${ticket}: the worktree changed during verification`, `git -C ${tree.path} status`);
11061
+ const current = await fleet.runtimeHandle(ticket);
11062
+ if (!current || current.handle !== h.handle || current.claimedAt !== h.claimedAt)
11063
+ throw new Refusal(`${ticket}'s claim changed; left the runtime untouched`, "armada status");
11064
+ const state = await runtime.state(handle);
11065
+ if (state !== "idle" && state !== "done")
11066
+ throw new Refusal("worker resumed during stop; left its worktree untouched", "armada status");
11067
+ if (await git(tree.path, ["rev-parse", "HEAD"]) !== localHead)
11068
+ throw new Refusal(`cannot stop ${ticket}: new commits appeared during verification`, `git -C ${tree.path} status`);
11069
+ await runtime.remove(handle, tree.path);
11070
+ if (!await fleet.stopRuntime({ ticket, handle: h.handle, claimedAt: h.claimedAt }))
11071
+ throw new Refusal("worktree removed, but claim changed during cleanup; inspect the new claim", "armada status");
11072
+ const result = { ticket, path: tree.path, stopped: true };
11073
+ io.stdout(args.json ? `${JSON.stringify(result, null, 2)}
11074
+ ` : `Stopped ${ticket} and removed ${tree.path}; its branch is retained.
11075
+ `);
11076
+ return 0;
11077
+ }
11078
+
11079
+ // src/worker.ts
11080
+ function liveFleet(io, config, credentials) {
11081
+ const signIn = credentials.armadaSignIn;
11082
+ if (!signIn)
11083
+ return {
11084
+ fleet: null,
11085
+ warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
11086
+ };
11087
+ try {
11088
+ const api = apiOf(io, credentials.armadaApi.url);
11089
+ return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
11090
+ } catch (err) {
11091
+ return {
11092
+ fleet: null,
11093
+ warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
11094
+ };
11095
+ }
11096
+ }
11097
+ function statusLive(io, config, credentials) {
11098
+ const { fleet } = liveFleet(io, config, credentials);
11099
+ return fleet ? {
11100
+ lastEvents: () => fleet.lastEventTimes(),
11101
+ heartbeats: () => fleet.heartbeatTimes(),
11102
+ launches: () => fleet.pendingLaunches(),
11103
+ runtimeHandles: () => observeHerdr(io, fleet)
11104
+ } : undefined;
11105
+ }
11106
+ function currentTicket(io, config, explicit, workers = []) {
11107
+ const fromEnv = io.env.ARMADA_TICKET?.trim();
11108
+ const id = explicit?.trim() || fromEnv || (() => {
11109
+ const branch = io.gitBranch?.();
11110
+ return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
11111
+ })() || (workers.length === 1 ? workers[0] : null);
11112
+ if (!id)
11113
+ throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
11114
+ return id.toUpperCase();
11115
+ }
11116
+ function context(io, config, credentials) {
11117
+ if (!credentials.linearApiKey)
11118
+ throw missingKey(LINEAR_KEY);
11119
+ const linearOpts = {
11120
+ apiKey: credentials.linearApiKey,
11121
+ labels: config.tracker.labels,
11122
+ ...io.fetch ? { fetch: io.fetch } : {}
11123
+ };
11124
+ const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
11125
+ const live = liveFleet(io, config, credentials);
11126
+ const token = credentials.githubToken;
11127
+ return {
11128
+ config,
11129
+ linear,
11130
+ fleet: async () => live,
11131
+ readPull: token ? (number) => fetchPullRequest({
11132
+ token,
11133
+ repository: config.github.repository,
11134
+ number,
11135
+ ...io.fetch ? { fetch: io.fetch } : {}
11136
+ }) : null,
11137
+ now: io.now ?? (() => new Date)
11138
+ };
11139
+ }
11140
+ function print(io, outcome, json) {
11141
+ if (json) {
11142
+ io.stdout(`${JSON.stringify(outcome, null, 2)}
11143
+ `);
11144
+ return;
11145
+ }
11146
+ const out = [...outcome.lines];
10700
11147
  const s = outcome.state;
10701
11148
  if (s)
10702
11149
  out.push(`Now: ${s.status} · phase ${s.phase ?? "none"} · runtime ${s.runtime ?? "none"} · profile ${s.profile ?? "none"}`);
@@ -10733,7 +11180,13 @@ async function readMessage(io, options, name = "message") {
10733
11180
  return text;
10734
11181
  }
10735
11182
  async function withContext(io, config, credentials, json, act) {
10736
- print(io, await act(context(io, config, credentials)), json);
11183
+ const outcome = await act(context(io, config, credentials));
11184
+ if (outcome.state?.phase) {
11185
+ const profile = outcome.state.profile;
11186
+ const agent = profile ? config.herdr.profiles[profile]?.harness : null;
11187
+ await reportHerdr(io, outcome.state.phase, agent ?? "armada");
11188
+ }
11189
+ print(io, outcome, json);
10737
11190
  return 0;
10738
11191
  }
10739
11192
  async function claim(io, config, credentials, a) {
@@ -10896,7 +11349,23 @@ async function answer(io, config, credentials, a) {
10896
11349
  const text = positional ?? fromOption;
10897
11350
  if (!text?.trim())
10898
11351
  throw new UsageError(`answer needs the text: ${usage}`);
10899
- return withContext(io, config, credentials, a.json, (ctx) => answerItem(ctx, { target, text, note }));
11352
+ return withContext(io, config, credentials, a.json, (ctx) => answerItem({
11353
+ ...ctx,
11354
+ deliverAnswer: async (ticket, message, runtime, claim) => {
11355
+ if (runtime && runtime.toLowerCase() !== "herdr")
11356
+ return false;
11357
+ const { fleet } = liveFleet(io, config, credentials);
11358
+ if (!fleet) {
11359
+ if (runtime?.toLowerCase() === "herdr")
11360
+ throw new Refusal("cannot read the herdr claim before delivery", "armada whoami");
11361
+ return false;
11362
+ }
11363
+ const delivered = await deliverHerdr(io, fleet, ticket, message, claim);
11364
+ if (!delivered && runtime?.toLowerCase() === "herdr")
11365
+ throw new Refusal("the herdr claim is missing or changed; no answer was delivered", "armada status");
11366
+ return delivered;
11367
+ }
11368
+ }, { target, text, note }));
10900
11369
  }
10901
11370
  function waitSeconds(raw) {
10902
11371
  if (raw === undefined)
@@ -10925,10 +11394,12 @@ function renderEntries(project, items) {
10925
11394
  if (e.kind === "hand-back" && !/shipped with (?:ship-pr-dev|the fallback:)|shipping path unreported/.test(e.body))
10926
11395
  out.push(" shipping path unreported");
10927
11396
  }
11397
+ if (items.some((e) => e.kind === "runtime-blocked"))
11398
+ out.push('Read the blocked herdr pane with its runtime guide, then answer: armada answer <ticket> "<answer>".');
10928
11399
  if (items.some((e) => e.kind === "question" || e.kind === "plan"))
10929
- out.push(`Deliver each answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
11400
+ out.push(`For herdr, armada answer delivers automatically. Deliver each other answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
10930
11401
  if (items.some((e) => ["answer-request", "launch-request", "merge-request", "release-request", "plan-changes"].includes(e.kind)))
10931
- out.push('Dashboard requests: deliver an answer-request, then armada answer <id> "<answer>"; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>". Handle or decline merge-request, release-request and plan-changes, then resolve them with armada answer <id> "<result>". Plan changes are not an approval.');
11402
+ out.push('Dashboard requests: armada answer <id> "<answer>" delivers herdr answer-requests automatically; deliver answers for other runtimes first; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>". Handle or decline merge-request, release-request and plan-changes, then resolve them with armada answer <id> "<result>". Plan changes are not an approval.');
10932
11403
  return out;
10933
11404
  }
10934
11405
  function renderInbox(r, next) {
@@ -10953,7 +11424,7 @@ async function inbox(io, config, credentials, a) {
10953
11424
  const { fleet, warning } = liveFleet(io, config, credentials);
10954
11425
  if (!fleet)
10955
11426
  throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
10956
- const report = await checkInbox(fleet, {
11427
+ const report = await checkInbox(observingFleet(io, fleet), {
10957
11428
  project: config.project.slug,
10958
11429
  coordinator: coordinatorHandle(io),
10959
11430
  facts: detectCoordinator(io),
@@ -11153,7 +11624,7 @@ async function watchUntil(io, config, credentials, json, configPath) {
11153
11624
  throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
11154
11625
  const before = paths ? await readWatchState(paths, project) : null;
11155
11626
  await remember(io, project, { root: dirname2(configPath), stopped: null });
11156
- const report = await watchInbox(fleet, {
11627
+ const report = await watchInbox(observingFleet(watchingIo, fleet), {
11157
11628
  project,
11158
11629
  signal: controller.signal,
11159
11630
  coordinator: coordinatorHandle(io),
@@ -12176,7 +12647,12 @@ async function heartbeat(io, config, credentials, args) {
12176
12647
  now: io.now ?? (() => new Date),
12177
12648
  sleep: io.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
12178
12649
  parentAlive: alive,
12179
- ping: (input) => fleet.heartbeat(input),
12650
+ ping: async (input) => {
12651
+ const result = await fleet.heartbeat(input);
12652
+ if (result.active)
12653
+ await reportHerdr(io, result.phase, result.agent ?? "armada", true);
12654
+ return result;
12655
+ },
12180
12656
  ready: async (session) => {
12181
12657
  const name = `${config.project.slug}-heartbeat-${ticket.toLowerCase()}-${createHash3("sha256").update(`${handle}/${session.claimedAt}`).digest("hex").slice(0, 12)}`;
12182
12658
  const acquired = await takeWatchLock(paths, name, pid, io.processAlive ?? processAlive);
@@ -12412,166 +12888,6 @@ async function init(io, opts) {
12412
12888
 
12413
12889
  // src/launch.ts
12414
12890
  import { dirname as dirname5, join as join6 } from "node:path";
12415
-
12416
- // src/herdr.ts
12417
- var harnessArgs = (p) => [
12418
- "--model",
12419
- herdrHarnessKind(p.harness) === "opencode" ? `${p.model.split("#")[0]}#${p.effort}` : p.model,
12420
- ...p.harness === "codex" ? ["-c", `model_reasoning_effort=${JSON.stringify(p.effort)}`] : p.harness === "claude" ? ["--effort", p.effort] : [],
12421
- ...p.extraArgs
12422
- ];
12423
- var object = (v) => typeof v === "object" && v !== null && !Array.isArray(v) ? v : null;
12424
- var id = (v) => typeof v === "string" && /^[a-zA-Z0-9:_-]{1,128}$/.test(v);
12425
- var runtimeEnvironment = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => /^(PATH|HOME|USER|LOGNAME|SHELL|TMPDIR|TMP|TEMP|LANG|TERM|LC_[A-Z_]+|XDG_(CONFIG_HOME|DATA_HOME|STATE_HOME|CACHE_HOME|RUNTIME_DIR)|HERDR_(SESSION|SOCKET_PATH|CONFIG_PATH))$/.test(name)));
12426
- var credentialNames = (env, extra) => [
12427
- ...new Set([
12428
- "LINEAR_API_KEY",
12429
- "GITHUB_TOKEN",
12430
- "GH_TOKEN",
12431
- "ARMADA_API_KEY",
12432
- "ARMADA_SESSION_TOKEN",
12433
- "ARMADA_SIGNED_IN_TO",
12434
- "ARMADA_API_URL",
12435
- "OPENAI_API_KEY",
12436
- "ANTHROPIC_API_KEY",
12437
- ...Object.keys(env).filter((name) => /^(ARMADA_|CONDUCTOR_)|(?:KEY|TOKEN|SECRET|PASSWORD)$/.test(name)),
12438
- ...extra
12439
- ])
12440
- ].filter((name) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(name)).sort();
12441
-
12442
- class Herdr {
12443
- io;
12444
- constructor(io) {
12445
- this.io = io;
12446
- }
12447
- async call(args, timeoutMs = 40000) {
12448
- const operation = args.slice(0, 2).join(" ");
12449
- let reply;
12450
- let code;
12451
- try {
12452
- if (!this.io.exec)
12453
- throw new Error("no exec");
12454
- const out = await this.io.exec("herdr", args, { cwd: this.io.cwd, timeoutMs });
12455
- code = out.code;
12456
- reply = object(JSON.parse(out.stdout || out.stderr));
12457
- } catch {
12458
- throw new UsageError(`herdr ${operation} failed; inspect the runtime with herdr agent list`);
12459
- }
12460
- const error = object(reply?.error);
12461
- if (code !== 0 || error) {
12462
- const reason = typeof error?.code === "string" && /^[a-z_]{1,64}$/.test(error.code) ? ` (${error.code})` : "";
12463
- throw new UsageError(`herdr ${operation} failed${reason}; inspect the runtime with herdr agent list`);
12464
- }
12465
- if (!reply)
12466
- throw new UsageError(`herdr ${operation} returned invalid JSON`);
12467
- return reply;
12468
- }
12469
- async ensureServer() {
12470
- const status = async (timeoutMs) => {
12471
- const server = object((await this.call(["status", "--json"], timeoutMs)).server);
12472
- if (!server || typeof server.running !== "boolean")
12473
- throw new UsageError("invalid herdr server status response");
12474
- if (server.running && (server.compatible === false || server.endpoint_compatible === false))
12475
- throw new UsageError("the running herdr server is incompatible; update or restart it before launching");
12476
- return server.running;
12477
- };
12478
- if (await status(5000))
12479
- return;
12480
- if (!this.io.detach || !await this.io.detach("herdr", ["server"], { cwd: this.io.cwd, env: runtimeEnvironment(this.io.env) }))
12481
- throw new UsageError("could not start herdr server; start it headless with herdr server");
12482
- const now = this.io.now ?? (() => new Date);
12483
- const deadline = now().getTime() + 5000;
12484
- for (let attempt = 0;attempt < 20; attempt++) {
12485
- const remaining = deadline - now().getTime();
12486
- if (remaining <= 0)
12487
- break;
12488
- if (await status(Math.min(1000, remaining)))
12489
- return;
12490
- const delay = Math.min(250, deadline - now().getTime());
12491
- if (delay > 0)
12492
- await (this.io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))))(delay);
12493
- }
12494
- throw new UsageError("herdr server did not become ready; inspect herdr status");
12495
- }
12496
- async create(input) {
12497
- const agent = input.ticket.toLowerCase();
12498
- if (!/^[a-z][a-z0-9_-]{0,31}$/.test(agent))
12499
- throw new UsageError("ticket cannot be used as a herdr agent name");
12500
- const r = object((await this.call([
12501
- "worktree",
12502
- "create",
12503
- "--cwd",
12504
- input.repo,
12505
- "--branch",
12506
- input.branch,
12507
- "--base",
12508
- input.base,
12509
- "--no-focus"
12510
- ])).result);
12511
- const workspace = object(r?.workspace)?.workspace_id;
12512
- const rootPane = object(r?.root_pane)?.pane_id;
12513
- const path = object(r?.worktree)?.path;
12514
- if (!id(workspace) || !id(rootPane) || typeof path !== "string" || !path.startsWith("/") || object(r?.root_pane)?.workspace_id !== workspace)
12515
- throw new UsageError("invalid herdr worktree response; inspect herdr worktree list before retrying");
12516
- const tab = object((await this.call([
12517
- "tab",
12518
- "create",
12519
- "--workspace",
12520
- workspace,
12521
- "--cwd",
12522
- path,
12523
- "--no-focus",
12524
- ...credentialNames(this.io.env, input.secrets ?? []).flatMap((name) => ["--env", `${name}=`]),
12525
- "--env",
12526
- `ARMADA_TICKET=${input.ticket}`
12527
- ])).result);
12528
- const pane = object(tab?.root_pane)?.pane_id;
12529
- if (!id(pane) || pane === rootPane || object(tab?.root_pane)?.workspace_id !== workspace)
12530
- throw new UsageError("invalid herdr worker pane response; inspect herdr pane list before retrying");
12531
- await this.call(["pane", "close", rootPane]);
12532
- return { workspace, pane, agent, path };
12533
- }
12534
- async start(handle, profile) {
12535
- const r = await this.call([
12536
- "agent",
12537
- "start",
12538
- handle.agent,
12539
- "--kind",
12540
- herdrHarnessKind(profile.harness),
12541
- "--pane",
12542
- handle.pane,
12543
- "--timeout",
12544
- "30000",
12545
- "--",
12546
- ...harnessArgs(profile)
12547
- ]);
12548
- this.checkAgent(r, handle);
12549
- }
12550
- async prompt(handle, prompt) {
12551
- const r = await this.call([
12552
- "agent",
12553
- "prompt",
12554
- handle.agent,
12555
- prompt,
12556
- "--wait",
12557
- "--until",
12558
- "working",
12559
- "--timeout",
12560
- "30000"
12561
- ]);
12562
- const agent = this.checkAgent(r, handle);
12563
- if (agent.agent_status !== "working")
12564
- throw new UsageError("herdr did not confirm the worker is working");
12565
- }
12566
- checkAgent(reply, handle) {
12567
- const agent = object(object(reply.result)?.agent);
12568
- if (!agent || agent.name !== handle.agent || agent.pane_id !== handle.pane || agent.workspace_id !== handle.workspace)
12569
- throw new UsageError("invalid herdr agent response; inspect herdr agent list before retrying");
12570
- return agent;
12571
- }
12572
- }
12573
-
12574
- // src/launch.ts
12575
12891
  async function launch(io, config, credentials, args, version, configPath) {
12576
12892
  if (args.rest[0] !== "revoke")
12577
12893
  return launchLocal(io, config, credentials, args, version, configPath);
@@ -13074,7 +13390,7 @@ function renderStatus(r) {
13074
13390
  if (!r.inFlight.length)
13075
13391
  out.push(" nobody is working");
13076
13392
  for (const t of r.inFlight) {
13077
- const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
13393
+ const who = [t.runtime, t.runtimeState && `live ${t.runtimeState}`, t.agent].filter(Boolean).join(" · ") || "unassigned";
13078
13394
  out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · ${t.lastReport ? `reported ${relative2(t.lastReport, now)}` : `updated ${relative2(t.lastUpdate, now)}`}`);
13079
13395
  out.push(`${indent}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
13080
13396
  if (t.profile)
@@ -13610,12 +13926,15 @@ var COMMAND_HELP = {
13610
13926
  this machine. Needs a sign-in to Armada
13611
13927
  watch --stop Stop only this project's verified watch and release its lock. Local,
13612
13928
  no sign-in needed. Never stop a watch just to read inbox or status
13929
+ `,
13930
+ stop: ` stop <ticket>
13931
+ Stop a herdr worker and archive its worktree only when clean and fully pushed
13613
13932
  `,
13614
13933
  answer: ` answer <item|ticket> "<answer>"
13615
- Coordinator: record an answer already delivered in the worker's
13616
- session (runtime guide): resolves the question or plan and posts it on
13617
- the ticket. A ticket id answers its open questions and plans. A hand-back id can
13618
- clear a merged/closed PR or a Done/Canceled ticket. Never calls a runtime
13934
+ Coordinator: deliver to a herdr worker and record the answer. For other
13935
+ runtimes, deliver with the runtime guide first. Resolves the question or
13936
+ plan and posts it on the ticket. A ticket id also answers a live herdr block.
13937
+ A hand-back id can clear a merged/closed PR or a Done/Canceled ticket
13619
13938
  answer --note <ticket|plan item> "<message>"
13620
13939
  Coordinator: record a delivered note; an open plan is resolved
13621
13940
  `,
@@ -13719,6 +14038,7 @@ var CONFIG_OPTION = new Set([
13719
14038
  "inbox",
13720
14039
  "watch",
13721
14040
  "answer",
14041
+ "stop",
13722
14042
  "merge",
13723
14043
  "brief",
13724
14044
  "launch"
@@ -14046,7 +14366,7 @@ async function dispatch(argv, io) {
14046
14366
  });
14047
14367
  return await heartbeat(io, config, credentials, args);
14048
14368
  }
14049
- const worker = { claim, report, release, ask, inbox, answer, validate, "ask-owner": askOwner, done }[args.command];
14369
+ const worker = { claim, report, release, ask, inbox, answer, stop, validate, "ask-owner": askOwner, done }[args.command];
14050
14370
  if (worker) {
14051
14371
  const { path, text } = await findConfig(io, args.config, args.command);
14052
14372
  const config = parseConfig(text, path);