@the-vibe-company/armada 0.2.4 → 0.2.5

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 +10 -2
  2. package/dist/armada.js +569 -145
  3. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -1804,6 +1804,7 @@ var HAS_WELLFORMED = !!"".isWellFormed;
1804
1804
  var CONFIG_FILE = "armada.toml";
1805
1805
  var PLAN_POLICIES = ["approve", "pre-approved"];
1806
1806
  var routingLabelKey = (name) => name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]/gu, "");
1807
+ var PROFILE_RUNTIMES = ["conductor", "claude-code"];
1807
1808
  var CONFIG_DEFAULTS = {
1808
1809
  language: "en",
1809
1810
  readyLabel: "ready-for-agent",
@@ -1932,10 +1933,16 @@ function parseConfig(text, source = CONFIG_FILE) {
1932
1933
  problems.push(`"${path}" is not a usable profile name`);
1933
1934
  continue;
1934
1935
  }
1935
- known.push([path, p, ["agent", "model", "effort", "fast_mode"]]);
1936
+ known.push([path, p, ["runtime", "agent", "model", "effort", "fast_mode"]]);
1936
1937
  if (p.fast_mode !== undefined && typeof p.fast_mode !== "boolean")
1937
1938
  problems.push(`"${path}.fast_mode" must be true or false`);
1939
+ const runtime = p.runtime ?? "conductor";
1940
+ if (!PROFILE_RUNTIMES.includes(runtime))
1941
+ problems.push(`"${path}.runtime" must be one of ${PROFILE_RUNTIMES.map((r) => `"${r}"`).join(", ")}`);
1942
+ if (runtime === "claude-code" && p.agent !== undefined && p.agent !== "claude")
1943
+ problems.push(`"${path}.agent" must be "claude" with runtime = "claude-code"`);
1938
1944
  profiles[name] = {
1945
+ runtime: PROFILE_RUNTIMES.includes(runtime) ? runtime : "conductor",
1939
1946
  agent: str(p, path, "agent"),
1940
1947
  model: str(p, path, "model"),
1941
1948
  effort: str(p, path, "effort"),
@@ -2125,6 +2132,15 @@ agent = "codex"
2125
2132
  model = "gpt-6.1-sol"
2126
2133
  effort = "xhigh"
2127
2134
 
2135
+ # A worker run as a subagent of a coordinator's Claude Code session, in its own
2136
+ # worktree (the armada-runtime-claude-code skill). It dies with that session, so
2137
+ # long runs belong on Conductor. \`model\` is what the Agent tool takes; it applies no effort.
2138
+ # [conductor.profiles.local]
2139
+ # runtime = "claude-code"
2140
+ # agent = "claude"
2141
+ # model = "opus"
2142
+ # effort = "high"
2143
+
2128
2144
  # Which profile a ticket gets from its Linear labels: the first rule with a label
2129
2145
  # the ticket carries wins, in file order. \`armada brief --profile\` overrides it.
2130
2146
  [[conductor.routing]]
@@ -2197,26 +2213,34 @@ function handBackProblems({ pr, repository, sha, requiredChecks }) {
2197
2213
  problems.push(...checkProblems(pr.checks ?? [], requiredChecks));
2198
2214
  return problems;
2199
2215
  }
2200
- function checkProblems(checks, requiredChecks) {
2201
- const problems = [];
2216
+ function checkIssues(checks, requiredChecks) {
2217
+ const issues = [];
2218
+ const of = (name, state, required) => ({
2219
+ text: `${required ? "required " : ""}check "${name}" is ${state}`,
2220
+ pending: state !== "failure"
2221
+ });
2202
2222
  if (requiredChecks.length) {
2203
2223
  for (const name of requiredChecks) {
2204
2224
  const runs = checks.filter((c) => c.name === name);
2205
- const bad = runs.find((c) => c.state !== "success");
2225
+ const bad = runs.find((c) => c.state === "failure") ?? runs.find((c) => c.state !== "success");
2206
2226
  if (!runs.length)
2207
- problems.push(`required check "${name}" has not reported on the head yet`);
2227
+ issues.push({ text: `required check "${name}" has not reported on the head yet`, pending: true });
2208
2228
  else if (bad)
2209
- problems.push(`required check "${name}" is ${bad.state}`);
2229
+ issues.push(of(name, bad.state, true));
2210
2230
  }
2211
2231
  } else if (!checks.length) {
2212
- problems.push("no CI check has reported on the head yet (or set [gates] required_checks in armada.toml)");
2232
+ issues.push({
2233
+ text: "no CI check has reported on the head yet (or set [gates] required_checks in armada.toml)",
2234
+ pending: true
2235
+ });
2213
2236
  } else {
2214
2237
  for (const c of checks)
2215
2238
  if (c.state !== "success")
2216
- problems.push(`check "${c.name}" is ${c.state}`);
2239
+ issues.push(of(c.name, c.state, false));
2217
2240
  }
2218
- return problems;
2241
+ return issues;
2219
2242
  }
2243
+ var checkProblems = (checks, requiredChecks) => checkIssues(checks, requiredChecks).map((i) => i.text);
2220
2244
 
2221
2245
  // ../core/src/routing.ts
2222
2246
  class ProfileError extends Error {
@@ -2386,6 +2410,10 @@ var firstState = (states, ...types) => {
2386
2410
  }
2387
2411
  return null;
2388
2412
  };
2413
+ function liveProfile({ name, profile, routed, reason, why }) {
2414
+ const { runtime: _, ...settings } = profile;
2415
+ return { name, ...settings, routed, reason, why };
2416
+ }
2389
2417
  function claimLine(o) {
2390
2418
  const line = `Agent claim — runtime: ${o.runtime} · session: ${o.handle} · branch: ${o.branch ?? "unknown"} · started: ${o.started}`;
2391
2419
  const p = o.profile;
@@ -2472,7 +2500,7 @@ ${claimLine({ runtime: runtime.name, handle: input.handle, branch, started, prof
2472
2500
  branch,
2473
2501
  phase: phaseLabel ? "planning" : ticket.agentPhase,
2474
2502
  resuming,
2475
- profile: profile ? { name: profile.name, ...profile.profile, routed: profile.routed, reason: profile.reason, why: profile.why } : null
2503
+ profile: profile ? liveProfile(profile) : null
2476
2504
  }));
2477
2505
  if (launched?.length) {
2478
2506
  const who = [...new Set(launched.map((r) => r.author ?? "the owner"))].join(", ");
@@ -2610,6 +2638,7 @@ async function releaseTicket(ctx, input) {
2610
2638
  var ARMADA_PACKAGE = "@the-vibe-company/armada";
2611
2639
  var WORKER_SKILL_PATH = ".agents/skills/armada-worker/SKILL.md";
2612
2640
  var CONDUCTOR_HANDLE = '"$CONDUCTOR_WORKSPACE_ID/$CONDUCTOR_SESSION_ID"';
2641
+ var subagentName = (ticket) => ticket.toLowerCase();
2613
2642
  var MAX_NOTES = 10;
2614
2643
  var NOTE = "id createdAt body user { name }";
2615
2644
  var NOTES = `pageInfo { hasNextPage endCursor } nodes { ${NOTE} }`;
@@ -2732,8 +2761,10 @@ function buildBrief(input) {
2732
2761
  }));
2733
2762
  const pkg = `${ARMADA_PACKAGE}@${input.version}`;
2734
2763
  const branch = ticket.branchName;
2764
+ const runtime = choice?.profile.runtime ?? "conductor";
2765
+ const handle = runtime === "claude-code" ? subagentName(ticket.id) : CONDUCTOR_HANDLE;
2735
2766
  const claimCommand = [
2736
- `armada claim ${ticket.id} --runtime conductor --handle ${CONDUCTOR_HANDLE}`,
2767
+ `armada claim ${ticket.id} --runtime ${runtime} --handle ${handle}`,
2737
2768
  branch ? ` --branch ${branch}` : "",
2738
2769
  choice ? ` --profile ${shellWord(choice.name)}` : "",
2739
2770
  choice?.reason ? ` --reason ${shellWord(choice.reason)}` : ""
@@ -2748,14 +2779,16 @@ function buildBrief(input) {
2748
2779
  inShell: has(v.name),
2749
2780
  inStore: !has(v.name) && !!input.stored?.includes(v.name)
2750
2781
  })),
2751
- {
2752
- name: "ARMADA_TICKET",
2753
- required: true,
2754
- value: ticket.id,
2755
- inShell: false,
2756
- inStore: false,
2757
- purpose: "the ticket this worker owns"
2758
- }
2782
+ ...runtime === "claude-code" ? [] : [
2783
+ {
2784
+ name: "ARMADA_TICKET",
2785
+ required: true,
2786
+ value: ticket.id,
2787
+ inShell: false,
2788
+ inStore: false,
2789
+ purpose: "the ticket this worker owns"
2790
+ }
2791
+ ]
2759
2792
  ];
2760
2793
  const extra = input.conventions ?? null;
2761
2794
  if (extra && extra.text === null)
@@ -2772,7 +2805,7 @@ function buildBrief(input) {
2772
2805
  description: ticket.description
2773
2806
  },
2774
2807
  parent: ticket.parent,
2775
- runtime: "conductor",
2808
+ runtime,
2776
2809
  profile: choice ? { name: choice.name, ...choice.profile } : null,
2777
2810
  routing: choice ? { source: choice.source, rule: choice.rule, routed: choice.routed, reason: choice.reason, why: choice.why } : null,
2778
2811
  repository: { name: config.github.repository, url: `https://github.com/${config.github.repository}` },
@@ -2803,12 +2836,19 @@ var quote = (body) => body.trim().split(`
2803
2836
  var byLine = (n) => `${n.author ?? "unknown"}, ${n.createdAt.slice(0, 16).replace("T", " ")}Z — ${n.url}`;
2804
2837
  function renderPrompt(b) {
2805
2838
  const t = b.ticket;
2839
+ const subagent = b.runtime === "claude-code";
2806
2840
  const out = [
2807
2841
  `# ${t.id} — ${t.title}`,
2808
2842
  "",
2809
2843
  `You are an Armada worker. You own exactly one ticket, ${t.id} (${t.url}), and turn it into one green pull request on ${b.repository.name}. Follow the \`armada-worker\` skill (\`${WORKER_SKILL_PATH}\`) and the repository's \`AGENTS.md\`. Never merge.`,
2810
2844
  "",
2811
- "## First: install Armada and claim the ticket",
2845
+ ...subagent ? [
2846
+ "## Before anything: your own worktree",
2847
+ "",
2848
+ `You run as a Claude Code subagent of the coordinator's session, in your own git worktree. Before you run anything else or touch a file, check that \`git rev-parse --show-toplevel\` is a folder under \`.claude/worktrees/\`. If it is not, you are in the coordinator's checkout: call the \`EnterWorktree\` tool with the name \`${subagentName(t.id)}\` and work only there. If it is refused, change nothing: reply that you were launched without a worktree and end your turn; the coordinator relaunches you in one. Never edit, commit or switch branches in the coordinator's checkout.`,
2849
+ ""
2850
+ ] : [],
2851
+ subagent ? "## Then: install Armada and claim the ticket" : "## First: install Armada and claim the ticket",
2812
2852
  "",
2813
2853
  "```sh",
2814
2854
  b.install,
@@ -2826,8 +2866,12 @@ function renderPrompt(b) {
2826
2866
  "",
2827
2867
  "## Branch",
2828
2868
  "",
2829
- t.branch ? `Work on \`${t.branch}\`. Your workspace starts on a branch Conductor named; rename it before your first commit: \`git branch -m ${t.branch}\`.` : "Linear suggests no branch name for this ticket; name yours after the ticket id.",
2830
- ""
2869
+ t.branch ? `Work on \`${t.branch}\`. Your ${subagent ? "worktree starts on a branch Claude Code" : "workspace starts on a branch Conductor"} named; rename it before your first commit: \`git branch -m ${t.branch}\`.` : "Linear suggests no branch name for this ticket; name yours after the ticket id.",
2870
+ "",
2871
+ ...subagent ? [
2872
+ `You share the coordinator's machine and environment: its \`ARMADA_TICKET\`, if it has one, is not yours. Pass \`--ticket ${t.id}\` to every \`armada report\`, \`ask\` and \`release\`. You end when the coordinator's session ends: report at every step, so the ticket always says where you are.`,
2873
+ ""
2874
+ ] : []
2831
2875
  ];
2832
2876
  if (t.description)
2833
2877
  out.push("## Ticket", "", quote(t.description), "");
@@ -2855,7 +2899,7 @@ ${quote(x.handBack.body)}` : "No hand-back note.", "");
2855
2899
  out.push(`- ${w.id} — ${w.title} (${w.phase})${w.branch ? `, branch \`${w.branch}\`` : ""}${w.pr ? `, ${w.pr}` : ""}`);
2856
2900
  } else
2857
2901
  out.push("None.");
2858
- out.push("", "## Environment", "", b.launch ? `No key is needed in this workspace: once signed in, Armada hands each command the keys it needs, for ${t.id} only. If a command says this worker was cut off from Armada, stop and say so in your reply. Never print, commit or log a token or a key.` : `The coordinator set ${b.environment.map((v) => `\`${v.name}\``).join(", ")} in this workspace. Never print, commit or log their values.`);
2902
+ out.push("", "## Environment", "", b.launch ? `No key is needed in this workspace: once signed in, Armada hands each command the keys it needs, for ${t.id} only. If a command says this worker was cut off from Armada, stop and say so in your reply. Never print, commit or log a token or a key.` : subagent ? "You run with the coordinator's environment and keys. Never print, commit or log their values." : `The coordinator set ${b.environment.map((v) => `\`${v.name}\``).join(", ")} in this workspace. Never print, commit or log their values.`);
2859
2903
  if (b.conventions)
2860
2904
  out.push("", "## Project conventions", "", b.conventions.text.trim());
2861
2905
  return `${out.join(`
@@ -3401,6 +3445,20 @@ async function fetchPullDiff(opts) {
3401
3445
  throw new GithubError(`GitHub API HTTP ${res.status} reading the diff of #${opts.number}`);
3402
3446
  return res.text();
3403
3447
  }
3448
+ var COMMIT_QUERY = `
3449
+ query Commit($owner: String!, $name: String!, $oid: GitObjectID!) {
3450
+ repository(owner: $owner, name: $name) {
3451
+ object(oid: $oid) { ... on Commit { oid tree { oid } parents(first: 3) { nodes { oid } } } }
3452
+ }
3453
+ }`;
3454
+ async function fetchCommit(opts) {
3455
+ const [owner, name] = opts.repository.split("/");
3456
+ const json = await githubQuery(opts, COMMIT_QUERY, { owner, name, oid: opts.sha });
3457
+ const c = json.data?.repository?.object;
3458
+ if (!c?.oid || !c.tree || !c.parents)
3459
+ return null;
3460
+ return { sha: c.oid, tree: c.tree.oid, parents: c.parents.nodes.map((p) => p.oid) };
3461
+ }
3404
3462
  // ../core/src/inbox.ts
3405
3463
  function questionBody(question, options = []) {
3406
3464
  const listed = options.map((o) => o.trim()).filter(Boolean);
@@ -4112,6 +4170,11 @@ var LEASE_POLL_MS = 5000;
4112
4170
  var MERGE_BACKOFF_MS = [2000, 4000, 8000];
4113
4171
  var CONFIRM_BACKOFF_MS = [1000, 2000, 4000, 8000];
4114
4172
  var UNKNOWN_BACKOFF_MS = [2000, 4000];
4173
+ var MERGE_WAIT_DEFAULT_MS = 30 * 60000;
4174
+ var MERGE_WAIT_POLL_MS = 30000;
4175
+ var UPDATE_STALL_MS = 3 * 60000;
4176
+ var NO_CHECKS_GRACE_MS = 60000;
4177
+ var MAX_UPDATES = 20;
4115
4178
  var COMMITIZEN_TITLE = /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([\w./,-]+\))?!?: \S/;
4116
4179
  function findHandBack(ticket) {
4117
4180
  const c = ticket.comments.find((x) => x.status?.phase === "ready-to-merge");
@@ -4121,48 +4184,83 @@ function findHandBack(ticket) {
4121
4184
  const sha = c.status.summary.match(/\bhead ([0-9a-f]+)\b/i)?.[1];
4122
4185
  return { pr: pr ? Number(pr) : null, sha: sha?.toLowerCase() ?? null, at: c.createdAt };
4123
4186
  }
4187
+ var MERGEABLE_STATES = new Set(["CLEAN", "HAS_HOOKS"]);
4124
4188
  var STATE_HELP = {
4125
- BEHIND: "the base branch requires it to be up to date; ask the worker to rebase",
4189
+ BEHIND: "the base branch requires it to be up to date; ask the worker to rebase, or armada merge --wait updates it",
4126
4190
  BLOCKED: "a branch protection rule blocks it (a required review or check)",
4127
4191
  DIRTY: "it conflicts with its base; ask the worker to rebase",
4128
4192
  DRAFT: "it is a draft",
4129
- HAS_HOOKS: "GitHub reports pre-receive hooks; merge it by hand",
4130
4193
  UNKNOWN: "GitHub is still computing mergeability; try again in a minute",
4131
4194
  UNSTABLE: "a check that is not required is failing"
4132
4195
  };
4133
- function mergeProblems({ pull, ticket, handBack, requiredChecks }) {
4196
+ var stateLine = (pull) => `GitHub reports #${pull.number} as ${pull.mergeStateStatus}, not CLEAN${STATE_HELP[pull.mergeStateStatus] ? `: ${STATE_HELP[pull.mergeStateStatus]}` : ""}`;
4197
+ function assess({ pull, ticket, handBack, requiredChecks, lineage, now }) {
4134
4198
  const n = `#${pull.number}`;
4135
4199
  const problems = [];
4136
- if (ticket.agentPhase !== "ready-to-merge")
4137
- problems.push(`${ticket.id} has not been handed back: its agent phase is ${ticket.agentPhase ?? "not set"}, not ready-to-merge`);
4138
- if (!handBack)
4139
- problems.push(`${ticket.id} has no "Agent status: ready-to-merge" comment carrying the head SHA`);
4140
- else {
4141
- if (handBack.pr !== null && handBack.pr !== pull.number)
4142
- problems.push(`the hand-back on ${ticket.id} names PR #${handBack.pr}, not ${n}`);
4143
- if (!handBack.sha)
4144
- problems.push(`the hand-back on ${ticket.id} carries no head SHA`);
4145
- else if (!FULL_SHA.test(handBack.sha))
4146
- problems.push(`the handed-back SHA ${handBack.sha} is not a full 40-character SHA; ask the worker to report ready-to-merge again`);
4147
- else if (handBack.sha !== pull.headSha)
4148
- problems.push(`the head of ${n} is ${pull.headSha}, not the handed-back ${handBack.sha}: it moved after the hand-back; ask the worker to report again`);
4149
- }
4200
+ const waits = [];
4201
+ const notes = [];
4202
+ if (ticket) {
4203
+ if (ticket.agentPhase !== "ready-to-merge")
4204
+ problems.push(`${ticket.id} has not been handed back: its agent phase is ${ticket.agentPhase ?? "not set"}, not ready-to-merge`);
4205
+ if (!handBack)
4206
+ problems.push(`${ticket.id} has no "Agent status: ready-to-merge" comment carrying the head SHA`);
4207
+ else {
4208
+ if (handBack.pr !== null && handBack.pr !== pull.number)
4209
+ problems.push(`the hand-back on ${ticket.id} names PR #${handBack.pr}, not ${n}`);
4210
+ if (!handBack.sha)
4211
+ problems.push(`the hand-back on ${ticket.id} carries no head SHA`);
4212
+ else if (!FULL_SHA.test(handBack.sha))
4213
+ problems.push(`the handed-back SHA ${handBack.sha} is not a full 40-character SHA; ask the worker to report ready-to-merge again`);
4214
+ else if (handBack.sha !== pull.headSha && (lineage?.from !== handBack.sha || lineage.why !== null))
4215
+ problems.push(`the head of ${n} is ${pull.headSha}, not the handed-back ${handBack.sha}: it moved after the hand-back${lineage?.why ? ` and ${lineage.why}` : ""}; ask the worker to report again`);
4216
+ }
4217
+ } else if (lineage?.why)
4218
+ problems.push(`the head of ${n} moved from ${lineage.from} to ${pull.headSha} during this merge and ${lineage.why}`);
4150
4219
  if (pull.state !== "open")
4151
4220
  problems.push(`${n} is ${pull.state}, not open`);
4152
4221
  if (pull.draft)
4153
4222
  problems.push(`${n} is a draft`);
4154
4223
  if (!COMMITIZEN_TITLE.test(pull.title))
4155
4224
  problems.push(`the title "${pull.title}" is not in Commitizen format, e.g. "feat(cli): add a command"`);
4156
- if (pull.mergeStateStatus !== "CLEAN")
4157
- problems.push(`GitHub reports ${n} as ${pull.mergeStateStatus}, not CLEAN${STATE_HELP[pull.mergeStateStatus] ? `: ${STATE_HELP[pull.mergeStateStatus]}` : ""}`);
4158
- for (const p of checkProblems(pull.checks, requiredChecks))
4159
- problems.push(`on head ${pull.headSha.slice(0, 7)}: ${p}`);
4225
+ const checks = checkStates(pull, requiredChecks, !ticket && !lineage?.updates, now);
4226
+ problems.push(...checks.failed);
4227
+ waits.push(...checks.pending);
4228
+ notes.push(...checks.notes);
4229
+ const state = pull.mergeStateStatus;
4230
+ const running = checks.pending.length > 0 || pull.checks.some((c) => c.state === "pending");
4231
+ if (state === "UNKNOWN" || (state === "BLOCKED" || state === "UNSTABLE") && running)
4232
+ waits.push(stateLine(pull));
4233
+ else if (state === "UNSTABLE" && checks.skipped)
4234
+ notes.push(`GitHub reports #${pull.number} as UNSTABLE with no check failing.`);
4235
+ else if (!MERGEABLE_STATES.has(state) && state !== "BEHIND")
4236
+ problems.push(stateLine(pull));
4160
4237
  const { total, read, unresolved } = pull.reviewThreads;
4161
4238
  if (unresolved)
4162
4239
  problems.push(`${n} has ${unresolved} unresolved review thread${unresolved > 1 ? "s" : ""}`);
4163
4240
  else if (total > read)
4164
4241
  problems.push(`${n} has more than ${read} review threads; check they are resolved by hand`);
4165
- return problems;
4242
+ return { problems, waits, notes, behind: state === "BEHIND" };
4243
+ }
4244
+ function checkStates(pull, required, skippable, now) {
4245
+ const on = `on head ${short(pull.headSha)}: `;
4246
+ const failed = [];
4247
+ const pending = [];
4248
+ const notes = [];
4249
+ const ran = required.length ? pull.checks.some((c) => required.includes(c.name)) : pull.checks.length > 0;
4250
+ const quiet = pull.checks.every((c) => c.state === "success");
4251
+ if (skippable && !ran && quiet) {
4252
+ const pushed = pull.updatedAt ? Date.parse(pull.updatedAt) : Number.NaN;
4253
+ if (!now || Number.isNaN(pushed) || now.getTime() - pushed >= NO_CHECKS_GRACE_MS) {
4254
+ const which = required.length ? `none of ${required.map((r) => `"${r}"`).join(", ")}` : "no CI check";
4255
+ notes.push(`${which} ran on head ${short(pull.headSha)}; with --no-ticket it passes on GitHub's own state${pull.checks.length ? " and the checks that ran" : ""}, as for a release pull request opened with the workflow's token.`);
4256
+ return { failed, pending, notes, skipped: true };
4257
+ }
4258
+ pending.push(`${on}no check has reported yet, and it was updated less than ${NO_CHECKS_GRACE_MS / 60000} min ago`);
4259
+ return { failed, pending, notes, skipped: false };
4260
+ }
4261
+ for (const issue of checkIssues(pull.checks, required))
4262
+ (issue.pending ? pending : failed).push(`${on}${issue.text}`);
4263
+ return { failed, pending, notes, skipped: false };
4166
4264
  }
4167
4265
  function baseProblem(pull, cmp, localCommands) {
4168
4266
  if (!cmp)
@@ -4170,7 +4268,7 @@ function baseProblem(pull, cmp, localCommands) {
4170
4268
  if (cmp.behindBy === 0)
4171
4269
  return null;
4172
4270
  if (!localCommands.length)
4173
- return `the head lacks ${cmp.behindBy} commit${cmp.behindBy > 1 ? "s" : ""} of ${pull.baseRef}; ask the worker to rebase, or declare [gates] local_commands in armada.toml so armada merge can test the merge`;
4271
+ return `the head lacks ${cmp.behindBy} commit${cmp.behindBy > 1 ? "s" : ""} of ${pull.baseRef}; ask the worker to rebase, or declare [gates] local_commands in armada.toml so armada merge can test the merge (armada merge --wait updates the branch instead)`;
4174
4272
  return null;
4175
4273
  }
4176
4274
  var CODE_FILE = /\.(?:[cm]?[jt]sx?|py|go|rs)$/;
@@ -4271,6 +4369,12 @@ async function withLease(fleet, o, body) {
4271
4369
  }
4272
4370
  }
4273
4371
  var say = (ctx, line) => ctx.progress?.(line);
4372
+ var short = (sha) => sha.slice(0, 7);
4373
+ var plural = (k, word) => `${k} ${word}${k === 1 ? "" : "s"}`;
4374
+
4375
+ class NotYet extends Error {
4376
+ name = "NotYet";
4377
+ }
4274
4378
  async function readSettled(ctx, number) {
4275
4379
  let pull = await ctx.forge.readPull(number);
4276
4380
  for (const ms of UNKNOWN_BACKOFF_MS) {
@@ -4283,24 +4387,113 @@ async function readSettled(ctx, number) {
4283
4387
  throw new Refusal(`pull request #${number} was not found in ${ctx.config.github.repository}`, "armada status, which lists the pull requests waiting");
4284
4388
  return pull;
4285
4389
  }
4286
- async function readTicketFor(ctx, pull, explicit) {
4287
- const id = explicit?.trim().toUpperCase() || (pull.headRef ? ticketFromBranch(pull.headRef, ctx.config.tracker.programRoot) : null);
4390
+ async function readTicketFor(ctx, pull, input) {
4391
+ const named = pull.headRef ? ticketFromBranch(pull.headRef, ctx.config.tracker.programRoot) : null;
4392
+ if (input.noTicket) {
4393
+ if (input.ticket)
4394
+ throw new Refusal("--no-ticket and --ticket cannot go together", `armada merge ${pull.number}`);
4395
+ const team = ctx.config.tracker.programRoot.split("-")[0]?.toUpperCase();
4396
+ if (named && named.split("-")[0] === team)
4397
+ throw new Refusal(`the branch of #${pull.number} (${pull.headRef}) names ${named}: merge it on its worker's hand-back, not with --no-ticket`, `armada merge ${pull.number}`);
4398
+ return null;
4399
+ }
4400
+ const id = input.ticket?.trim().toUpperCase() || named;
4288
4401
  if (!id)
4289
- throw new Refusal(`the branch of #${pull.number} (${pull.headRef ?? "unknown"}) names no ticket`, `armada merge ${pull.number} --ticket <id>`);
4402
+ throw new Refusal(`the branch of #${pull.number} (${pull.headRef ?? "unknown"}) names no ticket`, `armada merge ${pull.number} --ticket <id>, or --no-ticket for a pull request no ticket owns (armada init, a release)`);
4290
4403
  const ticket = await ctx.linear.readTicket(id);
4291
4404
  if (!ticket)
4292
- throw new Refusal(`ticket ${id} not found in Linear`, `armada merge ${pull.number} --ticket <id>, with its ticket`);
4405
+ throw new Refusal(`ticket ${id} not found in Linear`, `armada merge ${pull.number} --ticket <id>, with its ticket, or --no-ticket for a pull request no ticket owns`);
4293
4406
  return ticket;
4294
4407
  }
4295
- async function checklist(ctx, input) {
4296
- const { config } = ctx;
4408
+ async function lineageOf(ctx, pull, from, run) {
4409
+ const known = run.lineages.get(pull.headSha);
4410
+ if (known?.from === from)
4411
+ return known;
4412
+ const base = pull.baseRef;
4413
+ const fail = (why) => ({ from, updates: null, why });
4414
+ try {
4415
+ const lineage = await (async () => {
4416
+ let sha = pull.headSha;
4417
+ for (let updates = 0;; updates++) {
4418
+ if (sha === from)
4419
+ return { from, updates, why: null };
4420
+ if (updates >= MAX_UPDATES)
4421
+ return fail(`more than ${MAX_UPDATES} merge commits stand on it`);
4422
+ const commit = await ctx.forge.commit(sha);
4423
+ const [first, second] = commit?.parents ?? [];
4424
+ if (commit?.parents.length !== 2 || !first || !second)
4425
+ return fail(`${short(sha)} is not a merge commit of ${base}`);
4426
+ const cmp = await ctx.forge.compare(base, second);
4427
+ if (cmp?.status !== "BEHIND" && cmp?.status !== "IDENTICAL")
4428
+ return fail(`the merge commit ${short(sha)} brings in ${short(second)}, which is not on ${base}`);
4429
+ if (!ctx.repo)
4430
+ return fail(`git is not available to check what the merge commit ${short(sha)} changes`);
4431
+ const tree = await ctx.repo.mergeTree({ branch: base, number: pull.number, ours: first, theirs: second });
4432
+ if (tree !== commit.tree)
4433
+ return fail(`the merge commit ${short(sha)} changes more than a clean merge of ${base}`);
4434
+ sha = first;
4435
+ }
4436
+ })();
4437
+ run.lineages.set(pull.headSha, lineage);
4438
+ return lineage;
4439
+ } catch (err) {
4440
+ return fail(`what it changes could not be checked (${err instanceof Error ? err.message : String(err)})`);
4441
+ }
4442
+ }
4443
+ async function look(ctx, input, run) {
4297
4444
  const pull = await readSettled(ctx, input.pr);
4298
- const ticket = await readTicketFor(ctx, pull, input.ticket);
4299
- const handBack = findHandBack(ticket);
4300
- const warnings = [...ticket.warnings];
4301
- const lines = [];
4302
- const problems = mergeProblems({ pull, ticket, handBack, requiredChecks: config.gates.requiredChecks });
4445
+ const ticket = await readTicketFor(ctx, pull, input);
4446
+ if (!ticket)
4447
+ run.pin ??= pull.headSha;
4448
+ const handBack = ticket ? findHandBack(ticket) : null;
4449
+ const from = ticket ? handBack?.sha && FULL_SHA.test(handBack.sha) ? handBack.sha : null : run.pin;
4450
+ let lineage = null;
4451
+ if (from === pull.headSha)
4452
+ lineage = { from, updates: 0, why: null };
4453
+ else if (from && pull.state === "open")
4454
+ lineage = await lineageOf(ctx, pull, from, run);
4303
4455
  const cmp = await ctx.forge.compare(pull.baseRef, pull.headSha);
4456
+ const a = assess({
4457
+ pull,
4458
+ ticket,
4459
+ handBack,
4460
+ requiredChecks: ctx.config.gates.requiredChecks,
4461
+ lineage,
4462
+ now: ctx.now()
4463
+ });
4464
+ const behind = a.behind || (cmp?.behindBy ?? 0) > 0;
4465
+ const testable = MERGEABLE_STATES.has(pull.mergeStateStatus) && ctx.config.gates.localCommands.length > 0 && ctx.repo !== null;
4466
+ return { ...a, behind, mustUpdate: behind && !testable, pull, ticket, cmp, lineage };
4467
+ }
4468
+ var label = (pull, ticket) => `#${pull.number}${ticket ? ` (${ticket.id})` : ""}`;
4469
+ function updatedNote(run, pull) {
4470
+ if (!run.updated.size)
4471
+ return "";
4472
+ return `
4473
+ This run updated the branch of #${pull.number} with ${pull.baseRef} (head now ${pull.headSha}): whoever pushes to it next pulls first.`;
4474
+ }
4475
+ function refuse(ctx, run, l, problems, hints = []) {
4476
+ const { pull, ticket } = l;
4477
+ const n = pull.number;
4478
+ return new Refusal(`${label(pull, ticket)} cannot be merged:
4479
+ ${problems.map((p) => ` - ${p}`).join(`
4480
+ `)}${hints.length ? `
4481
+ Hints (not blocking):
4482
+ ${hints.map((h) => ` - ${h}`).join(`
4483
+ `)}` : ""}${updatedNote(run, pull)}`, pull.state !== "open" ? `gh pr view ${n} --repo ${ctx.config.github.repository}` : !ticket ? `gh pr checks ${n} --repo ${ctx.config.github.repository}; armada merge ${n} --no-ticket once it is fixed` : ticket.agentPhase !== "ready-to-merge" ? ctx.lockRequired ? `armada inbox --wait, until ${ticket.id} is handed back` : `armada status, until ${ticket.id} shows ready-to-merge` : `armada answer --note ${ticket.id} "<what to fix>", once you told its worker; merge again after its next hand-back`);
4484
+ }
4485
+ async function checklist(ctx, input, run) {
4486
+ const { config } = ctx;
4487
+ const l = await look(ctx, input, run);
4488
+ const { pull, ticket, cmp } = l;
4489
+ const warnings = [...ticket?.warnings ?? []];
4490
+ const lines = [];
4491
+ const problems = [...l.problems];
4492
+ if (input.wait && !input.dryRun) {
4493
+ if (!problems.length && (l.waits.length || l.mustUpdate))
4494
+ throw new NotYet(l.mustUpdate ? `${pull.baseRef} moved` : l.waits[0] ?? "not ready");
4495
+ } else
4496
+ problems.push(...l.waits, ...l.pull.mergeStateStatus === "BEHIND" ? [stateLine(pull)] : []);
4304
4497
  const behind = baseProblem(pull, cmp, config.gates.localCommands);
4305
4498
  if (behind)
4306
4499
  problems.push(behind);
@@ -4325,14 +4518,12 @@ ${indent(test.output)}`);
4325
4518
  }
4326
4519
  const hints = await hintsFor(ctx, pull, cmp, warnings);
4327
4520
  if (problems.length)
4328
- throw new Refusal(`#${pull.number} (${ticket.id}) cannot be merged:
4329
- ${problems.map((p) => ` - ${p}`).join(`
4330
- `)}${hints.length ? `
4331
- Hints (not blocking):
4332
- ${hints.map((h) => ` - ${h}`).join(`
4333
- `)}` : ""}`, pull.state !== "open" ? `gh pr view ${pull.number} --repo ${config.github.repository}` : ticket.agentPhase !== "ready-to-merge" ? ctx.lockRequired ? `armada inbox --wait, until ${ticket.id} is handed back` : `armada status, until ${ticket.id} shows ready-to-merge` : `armada answer --note ${ticket.id} "<what to fix>", once you told its worker; merge again after its next hand-back`);
4334
- lines.unshift(`Checklist passed for #${pull.number} (${ticket.id}): handed back at ${pull.headSha}, CLEAN, checks green, no open review thread.`);
4335
- return { pull, ticket, sha: pull.headSha, baseSha: cmp?.baseSha ?? null, lines, hints, warnings };
4521
+ throw refuse(ctx, run, l, problems, hints);
4522
+ const updates = l.lineage?.updates ?? 0;
4523
+ const updatedFrom = updates && l.lineage ? l.lineage.from : null;
4524
+ const head = ticket ? updatedFrom ? `handed back at ${updatedFrom}, now ${pull.headSha} with only ${pull.baseRef} merged in (${plural(updates, "merge commit")})` : `handed back at ${pull.headSha}` : updatedFrom ? `head ${pull.headSha}, which is ${updatedFrom} with only ${pull.baseRef} merged in` : `head ${pull.headSha}`;
4525
+ lines.unshift(`Checklist passed for ${label(pull, ticket)}: ${head}, ${pull.mergeStateStatus}, checks green, no open review thread.`, ...l.notes);
4526
+ return { pull, ticket, sha: pull.headSha, updatedFrom, baseSha: cmp?.baseSha ?? null, lines, hints, warnings };
4336
4527
  }
4337
4528
  var indent = (text) => text.trimEnd().split(`
4338
4529
  `).map((l) => ` ${l}`).join(`
@@ -4357,27 +4548,25 @@ async function hintsFor(ctx, pull, cmp, warnings) {
4357
4548
  return [];
4358
4549
  }
4359
4550
  }
4360
- async function recheck(ctx, c) {
4361
- const pull = await readSettled(ctx, c.pull.number);
4362
- const ticket = await ctx.linear.readTicket(c.ticket.id) ?? c.ticket;
4363
- const problems = mergeProblems({
4364
- pull,
4365
- ticket,
4366
- handBack: findHandBack(ticket),
4367
- requiredChecks: ctx.config.gates.requiredChecks
4368
- });
4369
- if (pull.headSha === c.sha) {
4370
- const cmp = await ctx.forge.compare(pull.baseRef, pull.headSha);
4371
- if (cmp?.baseSha !== c.baseSha)
4372
- problems.push(`${pull.baseRef} moved to ${cmp?.baseSha ?? "an unknown commit"} while #${pull.number} was checked`);
4373
- }
4551
+ async function recheck(ctx, input, run, c) {
4552
+ const l = await look(ctx, input, run);
4553
+ const { pull } = l;
4554
+ const moved = [];
4555
+ if (pull.headSha !== c.sha)
4556
+ moved.push(`the head of #${pull.number} moved to ${pull.headSha} while it was checked`);
4557
+ else if (l.cmp?.baseSha !== c.baseSha)
4558
+ moved.push(`${pull.baseRef} moved to ${l.cmp?.baseSha ?? "an unknown commit"} while #${pull.number} was checked`);
4559
+ if (input.wait && !l.problems.length && (moved.length || l.waits.length))
4560
+ throw new NotYet(moved[0] ?? l.waits[0] ?? "not ready");
4561
+ const problems = [...l.problems, ...l.waits, ...moved];
4374
4562
  if (problems.length)
4375
4563
  throw new Refusal(`#${pull.number} changed while it was checked; nothing was merged:
4376
4564
  ${problems.map((p) => ` - ${p}`).join(`
4377
- `)}`, `armada merge ${pull.number} again`);
4565
+ `)}${updatedNote(run, pull)}`, `armada merge ${pull.number} again`);
4378
4566
  }
4379
4567
  async function mergePinned(ctx, pull, sha, ticket) {
4380
4568
  const n = `#${pull.number}`;
4569
+ const closeByHand = ticket ? `; if it merged, close ${ticket} by hand` : "";
4381
4570
  let readError = "";
4382
4571
  const read = () => {
4383
4572
  readError = "";
@@ -4395,7 +4584,7 @@ async function mergePinned(ctx, pull, sha, ticket) {
4395
4584
  break;
4396
4585
  const view = `gh pr view ${pull.number} --repo ${ctx.config.github.repository}`;
4397
4586
  if (!fresh)
4398
- throw new Refusal(`GitHub failed (${res.message}) and ${n} could not be read back (${readError || "not found"}); if it merged, close ${ticket} by hand`, view);
4587
+ throw new Refusal(`GitHub failed (${res.message}) and ${n} could not be read back (${readError || "not found"})${closeByHand}`, view);
4399
4588
  if (!res.transient)
4400
4589
  throw new Refusal(`GitHub refused to merge ${n}: ${res.message}`, `armada merge ${pull.number} --dry-run`);
4401
4590
  if (fresh.state !== "open")
@@ -4405,7 +4594,7 @@ async function mergePinned(ctx, pull, sha, ticket) {
4405
4594
  const wait = MERGE_BACKOFF_MS[attempt];
4406
4595
  if (wait === undefined)
4407
4596
  throw new Refusal(`GitHub kept failing (${res.message}) after ${attempt + 1} attempts; ${n} is still open and nothing was merged`, `armada merge ${pull.number} again once GitHub answers`);
4408
- say(ctx, `GitHub answered ${res.message}; ${n} is still open at ${sha.slice(0, 7)}, retrying in ${wait / 1000} s…`);
4597
+ say(ctx, `GitHub answered ${res.message}; ${n} is still open at ${short(sha)}, retrying in ${wait / 1000} s…`);
4409
4598
  await ctx.sleep(wait);
4410
4599
  }
4411
4600
  let seen = null;
@@ -4415,15 +4604,15 @@ async function mergePinned(ctx, pull, sha, ticket) {
4415
4604
  break;
4416
4605
  const wait = CONFIRM_BACKOFF_MS[i];
4417
4606
  if (wait === undefined)
4418
- throw new Refusal(seen ? `the merge of ${n} was accepted but GitHub shows it as ${seen.state}, not merged (auto-merge or a merge queue?); the ticket was left as is` : `the merge of ${n} was accepted but GitHub could not be read back (${readError || "not found"}); if it merged, close ${ticket} by hand`, `gh pr view ${pull.number} --repo ${ctx.config.github.repository}`);
4607
+ throw new Refusal(seen ? `the merge of ${n} was accepted but GitHub shows it as ${seen.state}, not merged (auto-merge or a merge queue?)${ticket ? "; the ticket was left as is" : ""}` : `the merge of ${n} was accepted but GitHub could not be read back (${readError || "not found"})${closeByHand}`, `gh pr view ${pull.number} --repo ${ctx.config.github.repository}`);
4419
4608
  await ctx.sleep(wait);
4420
4609
  }
4421
4610
  if (seen.headSha !== sha)
4422
- throw new Refusal(`${n} was merged at ${seen.headSha}, not at the handed-back ${sha}; check ${pull.baseRef} now`, `gh pr view ${pull.number} --repo ${ctx.config.github.repository}`);
4611
+ throw new Refusal(`${n} was merged at ${seen.headSha}, not at the ${ticket ? "handed-back" : "checked"} ${sha}; check ${pull.baseRef} now`, `gh pr view ${pull.number} --repo ${ctx.config.github.repository}`);
4423
4612
  return seen;
4424
4613
  }
4425
4614
  var runtimeGuide = (runtime) => runtime ? `armada-runtime-${runtime.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")}` : null;
4426
- async function closeTicket(ctx, ticket, merged, unlocked) {
4615
+ async function closeTicket(ctx, ticket, merged, c, unlocked) {
4427
4616
  const groups = ctx.config.tracker.labels;
4428
4617
  const done = ticket.statusType === "completed" ? null : firstState(ticket.states, "completed");
4429
4618
  await ctx.linear.updateTicket(ticket.uuid, {
@@ -4436,48 +4625,121 @@ async function closeTicket(ctx, ticket, merged, unlocked) {
4436
4625
  });
4437
4626
  if (!ticket.prs.some((p) => p.url === merged.url))
4438
4627
  await ctx.linear.linkUrl(ticket.uuid, merged.url, merged.title || `Pull request #${merged.number}`);
4439
- await ctx.linear.comment(ticket.uuid, `Agent status: merged — PR #${merged.number} squash-merged into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"}, head ${merged.headSha}${unlocked ? ", merged without lock (--no-lock)" : ""}`);
4628
+ await ctx.linear.comment(ticket.uuid, `Agent status: merged — PR #${merged.number} squash-merged into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"}, head ${merged.headSha}${c.updatedFrom ? `, the handed-back ${c.updatedFrom} updated with ${merged.baseRef}` : ""}${unlocked ? ", merged without lock (--no-lock)" : ""}`);
4440
4629
  return [
4441
4630
  `${ticket.id}: ${done ? `moved to ${done.name}` : "state unchanged"}, agent and ready labels removed, merged status posted.`
4442
4631
  ];
4443
4632
  }
4633
+ async function waitUntilReady(ctx, input, run, deadline) {
4634
+ const minutes = Math.round((input.wait?.timeoutMs ?? 0) / 60000);
4635
+ let shown = "";
4636
+ for (;; ) {
4637
+ const l = await look(ctx, input, run);
4638
+ const { pull } = l;
4639
+ const n = `#${pull.number}`;
4640
+ if (l.problems.length)
4641
+ throw refuse(ctx, run, l, l.problems);
4642
+ let reason;
4643
+ const asked = run.updated.get(pull.headSha);
4644
+ if (l.mustUpdate) {
4645
+ if (pull.mergeable === "CONFLICTING")
4646
+ throw refuse(ctx, run, l, [`${n} conflicts with ${pull.baseRef}; ask the worker to merge it in or rebase`]);
4647
+ if (pull.mergeable !== "MERGEABLE")
4648
+ reason = `GitHub is still computing whether ${n} merges cleanly with ${pull.baseRef}`;
4649
+ else if (asked !== undefined) {
4650
+ if (ctx.now().getTime() - asked >= UPDATE_STALL_MS)
4651
+ throw refuse(ctx, run, l, [
4652
+ `GitHub accepted to update the branch of ${n} with ${pull.baseRef}, but its head is still ${pull.headSha} after ${UPDATE_STALL_MS / 60000} min; update it on GitHub, or ask the worker to merge ${pull.baseRef} in`
4653
+ ]);
4654
+ reason = `GitHub is updating the branch of ${n} with ${pull.baseRef}`;
4655
+ } else {
4656
+ const res = await ctx.forge.updateBranch(pull.number, pull.headSha);
4657
+ const fresh = res.ok ? null : await ctx.forge.readPull(pull.number).catch(() => null);
4658
+ if (res.ok) {
4659
+ run.updated.set(pull.headSha, ctx.now().getTime());
4660
+ say(ctx, `Updated the branch of ${n} with ${pull.baseRef} (a merge commit on ${short(pull.headSha)}).`);
4661
+ reason = `the checks on the updated head of ${n}`;
4662
+ } else if (res.transient || fresh && fresh.headSha !== pull.headSha)
4663
+ reason = `GitHub could not update the branch of ${n} yet (${res.message})`;
4664
+ else
4665
+ throw refuse(ctx, run, l, [
4666
+ `GitHub refused to update the branch of ${n} with ${pull.baseRef}: ${res.message}. A branch protection rule or ruleset can forbid it (signed commits, restricted pushes); ask the worker to merge ${pull.baseRef} in or rebase`
4667
+ ]);
4668
+ }
4669
+ } else if (l.waits.length)
4670
+ reason = l.waits.join("; ");
4671
+ else
4672
+ return;
4673
+ if (reason !== shown)
4674
+ say(ctx, `Waiting: ${reason}…`);
4675
+ shown = reason;
4676
+ if (ctx.now().getTime() >= deadline)
4677
+ throw new Refusal(`${label(pull, l.ticket)} is still not ready after ${minutes} min: ${reason}; nothing was merged${updatedNote(run, pull)}`, `armada merge ${pull.number} --wait again${input.noTicket ? " --no-ticket" : ""}, or armada merge ${pull.number} --dry-run to see the checklist`);
4678
+ await ctx.sleep(MERGE_WAIT_POLL_MS);
4679
+ }
4680
+ }
4444
4681
  async function mergePullRequest(ctx, input) {
4682
+ const run = { pin: null, updated: new Map, lineages: new Map };
4445
4683
  if (input.dryRun) {
4446
- const c = await checklist(ctx, input);
4684
+ const c = await checklist(ctx, input, run);
4447
4685
  return outcome(c, false, null, c.lines.concat("Dry run: nothing was merged."), [], null);
4448
4686
  }
4687
+ if (!input.wait)
4688
+ return locked(ctx, input, run);
4689
+ if (!input.noLock && ctx.lockRequired) {
4690
+ const { fleet, warning } = await ctx.fleet();
4691
+ if (!fleet)
4692
+ throw lockUnavailable(ctx, input, warning);
4693
+ }
4694
+ const deadline = ctx.now().getTime() + input.wait.timeoutMs;
4695
+ for (;; ) {
4696
+ await waitUntilReady(ctx, input, run, deadline);
4697
+ try {
4698
+ return await locked(ctx, input, run);
4699
+ } catch (err) {
4700
+ if (!(err instanceof NotYet))
4701
+ throw err;
4702
+ say(ctx, `Not ready under the merge lock (${err.message}); lock given back, waiting again…`);
4703
+ }
4704
+ }
4705
+ }
4706
+ var lockUnavailable = (ctx, input, warning) => new Refusal(`the merge lock needs Armada, which is unavailable (${warning ?? "no answer"}); nothing was merged`, `armada merge ${input.pr} again once Armada answers, or armada merge ${input.pr} --no-lock if you are sure no other coordinator merges in ${ctx.config.project.slug} now`);
4707
+ async function locked(ctx, input, run) {
4449
4708
  const { config } = ctx;
4450
4709
  const slug = config.project.slug;
4451
4710
  const early = [];
4452
- const run = async (renew) => {
4453
- const c = await checklist(ctx, input);
4711
+ const body = async (renew) => {
4712
+ const c = await checklist(ctx, input, run);
4454
4713
  c.warnings.unshift(...early);
4455
- await recheck(ctx, c);
4714
+ await recheck(ctx, input, run, c);
4456
4715
  if (!await renew())
4457
4716
  throw new Refusal("the merge lock could not be renewed (it expired and another coordinator took it, or Armada did not answer); nothing was merged", `armada merge ${input.pr} again`);
4458
4717
  say(ctx, `Merging #${c.pull.number} at ${c.sha}…`);
4459
- const merged = await mergePinned(ctx, c.pull, c.sha, c.ticket.id);
4718
+ const merged = await mergePinned(ctx, c.pull, c.sha, c.ticket?.id ?? null);
4460
4719
  const lines = [
4461
4720
  ...c.lines,
4462
4721
  `Merged #${merged.number} into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"} (head ${merged.headSha}).`
4463
4722
  ];
4464
- try {
4465
- lines.push(...await closeTicket(ctx, c.ticket, merged, !!input.noLock));
4466
- } catch (err) {
4467
- throw new Error(`#${merged.number} is merged, but Linear could not be updated (${err instanceof Error ? err.message : String(err)}); close ${c.ticket.id} by hand: Done, agent and ready labels removed, pull request linked`);
4468
- }
4723
+ if (c.ticket)
4724
+ try {
4725
+ lines.push(...await closeTicket(ctx, c.ticket, merged, c, !!input.noLock));
4726
+ } catch (err) {
4727
+ throw new Error(`#${merged.number} is merged, but Linear could not be updated (${err instanceof Error ? err.message : String(err)}); close ${c.ticket.id} by hand: Done, agent and ready labels removed, pull request linked`);
4728
+ }
4729
+ else
4730
+ lines.push("No ticket: nothing was written to Linear.");
4469
4731
  return after(ctx, c, merged, lines);
4470
4732
  };
4471
4733
  if (input.noLock) {
4472
4734
  early.push(`merged without the merge lock (--no-lock): make sure no other coordinator merges in ${slug} now`);
4473
- return run(async () => true);
4735
+ return body(async () => true);
4474
4736
  }
4475
4737
  const { fleet, warning } = await ctx.fleet();
4476
4738
  if (!fleet && ctx.lockRequired)
4477
- throw new Refusal(`the merge lock needs Armada, which is unavailable (${warning ?? "no answer"}); nothing was merged`, `armada merge ${input.pr} again once Armada answers, or armada merge ${input.pr} --no-lock if you are sure no other coordinator merges in ${slug} now`);
4739
+ throw lockUnavailable(ctx, input, warning);
4478
4740
  if (!fleet) {
4479
4741
  early.push(`${warning ?? "not signed in to Armada"}; the merge lock was not taken, so make sure no other coordinator merges in ${slug} now`);
4480
- return run(async () => true);
4742
+ return body(async () => true);
4481
4743
  }
4482
4744
  return withLease(fleet, {
4483
4745
  project: slug,
@@ -4486,23 +4748,24 @@ async function mergePullRequest(ctx, input) {
4486
4748
  ttlMs: MERGE_LEASE_TTL_MS,
4487
4749
  sleep: ctx.sleep,
4488
4750
  onWait: (held) => say(ctx, `Waiting for the merge lock held by ${held?.holder ?? "another coordinator"} (until ${held?.expiresAt ?? "?"})…`)
4489
- }, run);
4751
+ }, body);
4490
4752
  }
4491
4753
  async function after(ctx, c, merged, lines) {
4492
- const live$ = await live(ctx, c.warnings, "record the merge", (fleet) => fleet.merge({
4493
- ticket: c.ticket.id,
4754
+ const ticket = c.ticket;
4755
+ const live$ = ticket ? await live(ctx, c.warnings, "record the merge", (fleet) => fleet.merge({
4756
+ ticket: ticket.id,
4494
4757
  number: merged.number,
4495
4758
  url: merged.url,
4496
4759
  mergeCommit: merged.mergeCommit,
4497
4760
  headSha: merged.headSha
4498
- }));
4761
+ })) : null;
4499
4762
  if (live$?.resolved)
4500
4763
  lines.push(`Hand-back resolved in the coordinator's inbox.`);
4501
4764
  let workers = [];
4502
4765
  let listed = false;
4503
4766
  try {
4504
4767
  const handles = new Map((live$?.open ?? []).map((h) => [h.ticket, h]));
4505
- workers = (await ctx.inFlight()).filter((t) => t.id !== c.ticket.id).map((t) => ({
4768
+ workers = (await ctx.inFlight()).filter((t) => t.id !== ticket?.id).map((t) => ({
4506
4769
  ticket: t.id,
4507
4770
  title: t.title,
4508
4771
  phase: t.phase,
@@ -4513,8 +4776,10 @@ async function after(ctx, c, merged, lines) {
4513
4776
  } catch (err) {
4514
4777
  c.warnings.push(`could not list the workers in flight (${err instanceof Error ? err.message : String(err)}); run armada status`);
4515
4778
  }
4516
- const claim = activeClaimComments(c.ticket.comments)[0]?.claim;
4517
- const runtime = live$?.handle?.runtime ?? c.ticket.agentRuntime ?? claim?.runtime ?? null;
4779
+ if (!ticket)
4780
+ return { ...outcome(c, true, merged, lines, workers, null), workersListed: listed };
4781
+ const claim = activeClaimComments(ticket.comments)[0]?.claim;
4782
+ const runtime = live$?.handle?.runtime ?? ticket.agentRuntime ?? claim?.runtime ?? null;
4518
4783
  const expected = runtimeGuide(runtime);
4519
4784
  let guide = null;
4520
4785
  try {
@@ -4537,7 +4802,7 @@ function outcome(c, merged, pr, lines, workers, archive) {
4537
4802
  headSha: p.headSha,
4538
4803
  mergeCommit: pr?.mergeCommit ?? null
4539
4804
  },
4540
- ticket: { id: c.ticket.id, url: c.ticket.url },
4805
+ ticket: c.ticket ? { id: c.ticket.id, url: c.ticket.url } : null,
4541
4806
  lines,
4542
4807
  hints: c.hints,
4543
4808
  workers,
@@ -4573,7 +4838,7 @@ async function readProjectConfig(p, opts) {
4573
4838
  import { createHash } from "node:crypto";
4574
4839
 
4575
4840
  // ../../skills/armada-coordinator/MERGE.md
4576
- var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Armada is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n\n## The release pull request\n\nSome repositories publish through release-please: every merge to the default branch opens or updates one release pull request, and merging it tags the version and publishes it. When the repository's rules (`AGENTS.md`) say to merge it after each merge, do it right after the ticket's merge, without a hand-back: no worker owns it, so `armada merge` does not apply.\n\n- **What it looks like.** Title `chore(main): release <version>`, opened by `github-actions`, label `autorelease: pending`, and a diff that only touches the changelog, the manifest and version fields. It is opened with the workflow's own token, so **no CI check runs on it** (only checks from apps such as Vercel, if any) and `mergeStateStatus` is `UNSTABLE`. Both are expected: the publish job runs the repository's checks again before publishing. Anything else in the diff, or a `DIRTY` state, is not expected: stop and tell the owner.\n- **Find it and its head:**\n\n```sh\ngh pr list --state open --label \"autorelease: pending\" --json number,title,headRefOid,mergeStateStatus\n```\n\n- **Merge it** pinned to that head, like any merge, and without `--delete-branch`:\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- **Check the publish.** After a minute or two the new version is on the registry, for example `npm view <package> version` for an npm package (the package is named in `AGENTS.md` or the release workflow). If it is not, open the Release run (`gh run list --workflow release.yml --limit 3`), fix the cause and re-run its failed jobs: a later push does not publish a version already tagged.\n- Release-please updates the same pull request on each merge to the default branch; one release pull request can carry several merges.\n";
4841
+ var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only, `--wait` when main keeps moving, `--no-ticket` for a pull request no ticket owns). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Main kept moving: `--wait`\n\nWith several workers in flight, main often moves between a green hand-back and its merge. Instead of asking the worker to rebase, run `armada merge <pr> --wait [--timeout <min>]` (30 minutes by default), in the background where your runtime allows it (Claude Code: `run_in_background`):\n\n- A head behind main that GitHub says merges cleanly is updated with GitHub's \"update branch\": a merge commit on the branch, no force-push. Squash merges make that merge commit harmless. When main does not require heads to be up to date and `[gates] local_commands` is set, it is test-merged instead, as without `--wait`, so a busy main does not restart CI each time.\n- It waits for every required check on the new head, then merges pinned to that head.\n- It holds the project's merge lock only while merging, not while waiting, so two waits never block each other. Signed in with Armada down, it refuses before touching the branch.\n- It stops at once, naming the cause, on a red check, a conflict, any other refused rule, or when GitHub refuses the update (a branch protection rule or ruleset can forbid it) or accepts it without the head moving within 3 minutes: ask the worker to fix it. A refusal after an update says so: the worker pulls the updated branch before pushing again.\n- The updated head still counts as the worker's hand-back, because the only change is main coming in: `armada merge` accepts a head that is the handed-back SHA followed only by merge commits, each bringing in a commit of main, with the tree of a clean merge (checked with git). That holds without `--wait` too, for example after \"Update branch\" on GitHub. The ticket's merged comment names both heads: `head <new>, the handed-back <old> updated with main`.\n\n## No ticket: `--no-ticket`\n\n`armada merge <pr> --no-ticket` merges a pull request no ticket owns: the `armada init` pull request (its output names the command) or the release pull request below. There is no hand-back and nothing is written to Linear; every other check is unchanged, and the merge is pinned to the head it checked. It refuses a branch that names a ticket of the program: that one is merged on its worker's hand-back.\n\nWhen none of the required checks ran on the head (a release pull request opened with the workflow's own token gets no CI run), it passes with a note, on GitHub's own state (`UNSTABLE` included, when nothing failed) and the checks that did run, once the head is a minute old; a younger head, or a head this run updated (its update starts CI), is waited for (`--wait`) or refused.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA (or that SHA with only main merged in), `CLEAN` (or `HAS_HOOKS`), not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, update it (`--wait`) or ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Armada is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n\n## The release pull request\n\nSome repositories publish through release-please: every merge to the default branch opens or updates one release pull request, and merging it tags the version and publishes it. When the repository's rules (`AGENTS.md`) say to merge it after each merge, do it right after the ticket's merge, without a hand-back: no worker owns it.\n\n- **What it looks like.** Title `chore(main): release <version>`, opened by `github-actions`, label `autorelease: pending`, and a diff that only touches the changelog, the manifest and version fields. It is opened with the workflow's own token, so **no CI check runs on it** (only checks from apps such as Vercel, if any) and `mergeStateStatus` is often `UNSTABLE` (`armada merge --no-ticket` accepts it when none of the required checks ran and nothing failed). Both are expected: the publish job runs the repository's checks again before publishing. Anything else in the diff, or a `DIRTY` state, is not expected: stop and tell the owner.\n- **Find it and its head:**\n\n```sh\ngh pr list --state open --label \"autorelease: pending\" --json number,title,headRefOid,mergeStateStatus\n```\n\n- **Merge it** with `armada merge <n> --no-ticket`: no ticket owns it, and no required check runs on it (see \"No ticket\" above). By hand, pin it to that head, like any merge, and without `--delete-branch`:\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- **Check the publish.** After a minute or two the new version is on the registry, for example `npm view <package> version` for an npm package (the package is named in `AGENTS.md` or the release workflow). If it is not, open the Release run (`gh run list --workflow release.yml --limit 3`), fix the cause and re-run its failed jobs: a later push does not publish a version already tagged.\n- Release-please updates the same pull request on each merge to the default branch; one release pull request can carry several merges.\n";
4577
4842
 
4578
4843
  // ../../skills/armada-coordinator/SKILL.md
4579
4844
  var SKILL_default = `---
@@ -4585,7 +4850,7 @@ The coordinator turns the owner's intent into merged pull requests. Each worker
4585
4850
 
4586
4851
  **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.
4587
4852
 
4588
- **Armada never drives a runtime.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime (for example \`armada-runtime-conductor\`). Armada records what happened.
4853
+ **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.
4589
4854
 
4590
4855
  ## Take over a run
4591
4856
 
@@ -4613,7 +4878,7 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
4613
4878
  - write the prompt with \`armada brief <ticket> --prompt > <file>\` and add what only you know: which parallel workers touch neighbouring code and where the boundary is, and decisions not yet on the ticket. The brief already says whether the plan needs approval (\`[policy] plans\`, or the ticket's label) and ends with the project's conventions (\`[brief] extra\`): put a note every worker needs in that file, not in each prompt;
4614
4879
  - launch it with the runtime guide's *launch* section, passing the profile's values. When the brief's \`Launch:\` line says the prompt carries a one-time token, pass no key: the worker signs in with it. When it says there is none, fix the reason (usually your sign-in) and brief again, rather than pass keys; the token works once, within the hour, so brief right before the launch;
4615
4880
  - check the claim: \`armada status\` shows the ticket in flight, phase \`planning\`, with the handle the runtime returned. Done when every launched ticket is In Progress with a claim.
4616
- 6. **Merge handed-back pull requests** one at a time with \`armada merge <pr>\`, following [MERGE.md](MERGE.md). Done when the pull request is merged, the ticket is Done with its agent labels removed, and every in-flight worker affected by what landed has been told. When the repository's rules (\`AGENTS.md\`) ask you to ship each merge through its release pull request (release-please's \`chore(main): release …\`), merge that one next, as "The release pull request" in [MERGE.md](MERGE.md) describes.
4881
+ 6. **Merge handed-back pull requests** one at a time with \`armada merge <pr>\` (\`--wait\` when main moved since the hand-back, \`--no-ticket\` for a pull request no ticket owns), following [MERGE.md](MERGE.md). Done when the pull request is merged, the ticket is Done with its agent labels removed, and every in-flight worker affected by what landed has been told. When the repository's rules (\`AGENTS.md\`) ask you to ship each merge through its release pull request (release-please's \`chore(main): release …\`), merge that one next, as "The release pull request" in [MERGE.md](MERGE.md) describes.
4617
4882
  7. **Turn findings into tickets.** A gap a worker reports or a bug you see becomes a ticket under the right spec, with blocked-by relations, and is launched when ready. No finding lives only in a transcript.
4618
4883
  8. **Report to the owner** in their language (\`tracker.language\` in \`armada.toml\`, or the owner's personal setting): what merged, what runs, what you decided for them, and the one thing they must do, with its exact place (a URL, a setting). Outcomes and numbers, no process narration.
4619
4884
 
@@ -4638,11 +4903,120 @@ You only learn of something new when a command you run ends. So while a worker i
4638
4903
  - When a command named here is missing from your Armada version (\`armada --help\`), do the step by hand with the same protocol and say so in your report.
4639
4904
  `;
4640
4905
 
4906
+ // ../../skills/armada-runtime-claude-code/SKILL.md
4907
+ var SKILL_default2 = `---
4908
+ name: armada-runtime-claude-code
4909
+ 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.
4910
+ ---
4911
+
4912
+ 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.
4913
+
4914
+ - **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).
4915
+ - **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.
4916
+ - A worker is one background subagent. Its Armada handle is its name: the ticket id in lowercase (\`abc-12\` for ABC-12), which the brief's claim line already uses. The worker's claim comment carries it, so \`armada status\` and the ticket lead back to the subagent.
4917
+ - **It shares your machine and environment**: your \`gh\` sign-in for its pushes, your installed \`armada\`, and every environment variable of your session. A worker needs no key: the prompt of \`armada brief\` carries a one-time launch token, and its first command exchanges it for a session limited to its ticket, kept in the machine's credentials file next to your own sign-in. Because it inherits your environment, an \`ARMADA_TICKET\` of yours is not its ticket: the brief tells it to pass \`--ticket\` to every command.
4918
+ - Run \`armada watch\` in the background while a worker is in flight, as the coordinator skill says: a worker's question, plan or hand-back reaches your inbox, not your conversation. The task notification Claude Code sends when a subagent stops is a hint to look, not the record.
4919
+
4920
+ ## Launch
4921
+
4922
+ 1. Pick a ready ticket from \`armada status\` that does not collide with work in flight.
4923
+ 2. Run \`armada brief ABC-12\` (with \`--profile <name> --reason "<why>"\` when you override the routed profile), right before the launch. Its \`Runtime:\` line must say \`claude-code\`: the profile has \`runtime = "claude-code"\` in \`armada.toml\`. Read the profile (model), the \`Launch:\` line and the warnings, and resolve every warning first. The profile's effort is not applied by the Agent tool; a worker that needs a set effort goes to Conductor.
4924
+ - \`Launch: one-time token in the prompt\` is the normal case. \`Launch: no launch token (…)\` says why: usually \`armada login\`, then brief again.
4925
+ 3. Read the prompt: \`armada brief ABC-12 --prompt\`. The token in it works once, within the hour: brief again when that hour has passed before the launch. Add what only you know (the boundary with a parallel worker, a decision not yet on the ticket) at the end.
4926
+ 4. Launch with the Agent tool, every value set:
4927
+
4928
+ \`\`\`json
4929
+ {
4930
+ "description": "ABC-12 <short title>",
4931
+ "name": "abc-12",
4932
+ "prompt": "<the whole armada brief --prompt text, then your notes>",
4933
+ "subagent_type": "general-purpose",
4934
+ "model": "<the profile's model, e.g. opus>",
4935
+ "isolation": "worktree",
4936
+ "run_in_background": true
4937
+ }
4938
+ \`\`\`
4939
+
4940
+ - \`isolation: "worktree"\` gives the worker a git worktree of its own under \`.claude/worktrees/\` (for example \`.claude/worktrees/agent-<id>\`), on a new branch (\`worktree-agent-<id>\`) from the default branch; the brief tells the worker to rename it to the ticket's branch. Never leave it out.
4941
+ - \`run_in_background: true\` returns at once, so you keep coordinating. Without it your turn waits for the whole ticket.
4942
+ - \`name\` is the handle in the brief's claim line. When your Agent tool has no \`name\` parameter, the result's \`agentId\` is the only way to reach the worker: record it at once with \`armada answer --note ABC-12 "subagent <agentId>"\`, so the ticket leads back to it after your context is compacted or a new coordinator takes over.
4943
+ - The result gives the \`agentId\` and an \`output_file\`: the worker's transcript (JSONL). Keep both. Never read that file whole: it is the entire conversation (Status section).
4944
+ - \`.claude/worktrees/\` appears as untracked in your own checkout: never commit it (add it to \`.gitignore\`).
4945
+
4946
+ 5. **Check the claim.** Within a few minutes, \`armada status\` lists the ticket in flight, phase \`planning\`, runtime \`Claude Code\`, and the claim comment reads \`session: abc-12\` and \`profile: <name>\`. No claim: read the transcript (Status section). A worker whose launch token was refused needs a new one: brief again and message it only the \`armada login --launch-token …\` line of the new prompt. A worker cut off from Armada was revoked on the dashboard or left idle for three days: ask the owner before you give it a new token.
4947
+
4948
+ ## Message
4949
+
4950
+ \`\`\`json
4951
+ { "to": "abc-12", "summary": "ABC-12 plan approved", "message": "Plan approved. Go on." }
4952
+ \`\`\`
4953
+
4954
+ SendMessage reaches the worker by its name, or by its \`agentId\` when it has none. A worker that is running gets the message at its next tool call; a worker that finished its turn (it handed back, asks a question, or stopped) is resumed from its transcript, in its worktree, and answers in a new turn. Success means the message was delivered, not that the worker acted on it: check its status, then read its reply. Make the first line a sentence that says what the message is. 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.
4955
+
4956
+ ## Status
4957
+
4958
+ Is the worker alive, and what did it do last? Three readings, cheapest first:
4959
+
4960
+ - **ListAgents** lists your subagents that are running: \`abc-12 · general-purpose · running · started 4m ago\`. A worker not in the list has finished its turn: it handed back, waits for an answer, or stopped. If \`armada status\` does not show it \`ready-to-merge\`, \`awaiting-approval\` or \`blocked\`, it has stopped without finishing: read its last reply, then message it to go on, or stop it and release the ticket.
4961
+ - **The task notification** Claude Code sends you when a subagent stops: \`status\` is \`completed\` (its turn ended) or \`killed\` (stopped), and \`result\` is its final reply. A worker that stops on an error says so there: read the transcript and message it to resume.
4962
+ - **Its last activity**: the time its transcript was last written, and the last event in it. A \`running\` worker whose transcript has not moved for twice \`policy.silence_minutes\` is stuck: message it, then stop it if it does not answer.
4963
+
4964
+ \`\`\`sh
4965
+ f=<output_file>
4966
+ date -u -r "$f" +%FT%TZ
4967
+ tail -n 1 "$f" | jq -r '[.timestamp, .type, (.message.content[0].type // "")] | join(" ")'
4968
+ \`\`\`
4969
+
4970
+ Its final reply and the commands it ran, without reading the whole file:
4971
+
4972
+ \`\`\`sh
4973
+ tail -n 200 "$f" | jq -r 'select(.type == "assistant") | .message.content[] | select(.type == "text") | .text' | tail -n 40
4974
+ tail -n 200 "$f" | jq -r 'select(.type == "assistant") | .message.content[] | select(.type == "tool_use") | .input.command // .name'
4975
+ \`\`\`
4976
+
4977
+ A filter that prints nothing: count the event types of the last lines, look at one event of the type you need, and adapt.
4978
+
4979
+ \`\`\`sh
4980
+ tail -n 200 "$f" | jq -r '.type' | sort | uniq -c
4981
+ \`\`\`
4982
+
4983
+ ## Stop and archive
4984
+
4985
+ A subagent has no workspace to archive: archiving it means stopping it and removing its worktree.
4986
+
4987
+ 1. Stop a worker that runs the wrong thing, or one you release: TaskStop with its name (or \`agentId\`).
4988
+
4989
+ \`\`\`json
4990
+ { "task_id": "abc-12" }
4991
+ \`\`\`
4992
+
4993
+ The notification that follows says \`killed\` and names the worktree it leaves: \`worktreePath\` and \`worktreeBranch\`. A stopped worker keeps its worktree and its changes; a message would resume it there.
4994
+
4995
+ 2. Record why when it does not hand back: \`armada release --ticket ABC-12 --reason "<why>"\`.
4996
+ 3. Remove its worktree once its pull request is merged, or once you released the ticket and nothing in the worktree is worth keeping. Wait until the worker is no longer running (ListAgents), then, from your own checkout:
4997
+
4998
+ \`\`\`sh
4999
+ git worktree list # find the worker's path and branch
5000
+ git -C .claude/worktrees/<dir> status --short # what would be lost
5001
+ git worktree remove --force .claude/worktrees/<dir>
5002
+ git branch -D <the worker's local branch> # the ticket's branch; the pull request and the remote branch stay on GitHub
5003
+ \`\`\`
5004
+
5005
+ A worktree in which the worker changed nothing is removed by Claude Code when the subagent ends; \`git worktree list\` no longer shows it.
5006
+
5007
+ ## A worker without a worktree
5008
+
5009
+ A subagent launched without \`isolation: "worktree"\` runs in your checkout. The brief's first section makes the worker check \`git rev-parse --show-toplevel\` before anything else and, when it is not under \`.claude/worktrees/\`, call the \`EnterWorktree\` tool with its name to move into a worktree of its own before it touches a file. Claude Code may refuse that from a subagent (it would change the working folder of your whole session); the worker then changes nothing, says so in its reply and ends its turn. Then:
5010
+
5011
+ 1. Check your own checkout: \`git status --short\` and \`git branch --show-current\`. Anything the worker changed there is not yours: move it to a worktree before you go on (\`git stash push -- <its files>\`, then \`git stash pop\` inside the new worker's worktree once it runs), and switch back to your branch if it moved.
5012
+ 2. Stop it (TaskStop), and launch it again under the same name with \`isolation: "worktree"\`. A worker that had already claimed claims again from the same handle, which keeps its claim.
5013
+ `;
5014
+
4641
5015
  // ../../skills/armada-runtime-conductor/SKILL.md
4642
- var SKILL_default2 = "---\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- 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\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12` (with `--profile <name> --reason \"<why>\"` when you override the routed profile), right before the launch. Read the profile (agent, model, effort, fast mode), the `Launch:` line and the warnings. Resolve every warning first: an open blocker, a ticket already in flight.\n - `Launch: one-time token in the prompt` is the normal case: the worker signs in to Armada with it and fetches its own keys. Its workspace receives no key at all.\n - `Launch: no launch token (…)` says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then brief again; `armada doctor` checks the sign-in. Launch with keys (step 4, second block) only on an Armada that keeps no keys yet (no accounts or no vault: a self-hosted one, CI, or before the owner's switch to the Keys page).\n3. Write the prompt to a file only you can read, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token in it works once, within the hour: brief again when that hour has passed before the launch.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt > /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\nWithout a launch token (an Armada that keeps no keys), pass the keys the 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 ten minutes: 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` again, and message it only the `armada login --launch-token …` line of the new prompt (Message section). A worker cut off from Armada was revoked on the dashboard (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";
5016
+ var SKILL_default3 = "---\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- 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\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12` (with `--profile <name> --reason \"<why>\"` when you override the routed profile), right before the launch. Read the profile (agent, model, effort, fast mode), the `Launch:` line and the warnings. Resolve every warning first: an open blocker, a ticket already in flight.\n - `Launch: one-time token in the prompt` is the normal case: the worker signs in to Armada with it and fetches its own keys. Its workspace receives no key at all.\n - `Launch: no launch token (…)` says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then brief again; `armada doctor` checks the sign-in. Launch with keys (step 4, second block) only on an Armada that keeps no keys yet (no accounts or no vault: a self-hosted one, CI, or before the owner's switch to the Keys page).\n3. Write the prompt to a file only you can read, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token in it works once, within the hour: brief again when that hour has passed before the launch.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt > /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\nWithout a launch token (an Armada that keeps no keys), pass the keys the 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 ten minutes: 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` again, and message it only the `armada login --launch-token …` line of the new prompt (Message section). A worker cut off from Armada was revoked on the dashboard (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";
4643
5017
 
4644
5018
  // ../../skills/armada-worker/SKILL.md
4645
- var SKILL_default3 = `---
5019
+ var SKILL_default4 = `---
4646
5020
  name: armada-worker
4647
5021
  description: Working one ticket as an Armada worker agent. Use when you were launched on a ticket by an Armada coordinator, or asked to claim, plan, implement and ship one ticket of a project that has an armada.toml. Covers the claim, the phase reports every 15 minutes, questions to the coordinator, the green pull request and the hand-back. A worker never merges.
4648
5022
  ---
@@ -4685,8 +5059,9 @@ var BUNDLED_SKILLS = [
4685
5059
  { path: "SKILL.md", content: SKILL_default }
4686
5060
  ]
4687
5061
  },
4688
- { name: "armada-runtime-conductor", files: [{ path: "SKILL.md", content: SKILL_default2 }] },
4689
- { name: "armada-worker", files: [{ path: "SKILL.md", content: SKILL_default3 }] }
5062
+ { name: "armada-runtime-claude-code", files: [{ path: "SKILL.md", content: SKILL_default2 }] },
5063
+ { name: "armada-runtime-conductor", files: [{ path: "SKILL.md", content: SKILL_default3 }] },
5064
+ { name: "armada-worker", files: [{ path: "SKILL.md", content: SKILL_default4 }] }
4690
5065
  ];
4691
5066
  function skillFolderHash(files) {
4692
5067
  const hash = createHash("sha256");
@@ -5115,7 +5490,7 @@ async function loadStatus(config, opts) {
5115
5490
  });
5116
5491
  }
5117
5492
  // package.json
5118
- var version = "0.2.4";
5493
+ var version = "0.2.5";
5119
5494
 
5120
5495
  // src/io.ts
5121
5496
  class UsageError extends Error {
@@ -5990,8 +6365,8 @@ function renderBrief(b) {
5990
6365
  `Brief for ${b.ticket.id} — ${b.ticket.title} (${b.ticket.status})`,
5991
6366
  b.ticket.url,
5992
6367
  "",
5993
- `Runtime: conductor (follow the armada-runtime-conductor skill to launch)`,
5994
- `Profile: ${p ? `${p.name}: agent ${p.agent}, model ${p.model}, effort ${p.effort}${p.fastMode ? ", fast mode" : ""}` : "none declared in armada.toml"}`,
6368
+ `Runtime: ${b.runtime} (follow the armada-runtime-${b.runtime} skill to launch)`,
6369
+ `Profile: ${p ? `${p.name}: agent ${p.agent}, model ${p.model}, effort ${p.effort}${b.runtime === "claude-code" ? " (not applied by the Agent tool)" : ""}${p.fastMode ? ", fast mode" : ""}` : "none declared in armada.toml"}`,
5995
6370
  ...b.routing ? [`Chosen by: ${b.routing.why}`] : [],
5996
6371
  `Plans: ${b.plans.rule === "pre-approved" ? "pre-approved" : "wait for approval"} (${b.plans.why})`,
5997
6372
  ...b.conventions ? [`Conventions: ${b.conventions.path} (under "Project conventions" in the prompt)`] : [],
@@ -6307,7 +6682,7 @@ async function buildDoctor(io, armadaVersion) {
6307
6682
  warnings: checks.filter((c) => c.level === "warning").length
6308
6683
  };
6309
6684
  }
6310
- var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
6685
+ var plural2 = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
6311
6686
  function renderDoctor(r) {
6312
6687
  const lines = [`Armada ${r.armadaVersion} doctor · ${r.root}`, ""];
6313
6688
  for (const c of r.checks) {
@@ -6323,7 +6698,7 @@ function renderDoctor(r) {
6323
6698
  if (!r.errors && !r.warnings)
6324
6699
  lines.push("Everything Armada needs is in place.");
6325
6700
  else
6326
- lines.push(`${plural(r.errors, "error")}, ${plural(r.warnings, "warning")}.${r.errors ? " Workers cannot be launched until the errors are fixed." : ""}`);
6701
+ lines.push(`${plural2(r.errors, "error")}, ${plural2(r.warnings, "warning")}.${r.errors ? " Workers cannot be launched until the errors are fixed." : ""}`);
6327
6702
  const errors = r.checks.filter((c) => c.level === "error");
6328
6703
  if (errors.length)
6329
6704
  lines.push(errors.some((c) => c.fix?.includes("armada init")) ? "Next: armada init, which opens one pull request with the fixes it can make" : `Next: ${errors[0]?.fix}`);
@@ -6425,6 +6800,7 @@ function prText(plan, version) {
6425
6800
  return { title, body: lines.join(`
6426
6801
  `) };
6427
6802
  }
6803
+ var mergeHint = (n) => `No ticket owns it: merge it with armada merge ${n} --no-ticket --wait, which waits for its checks`;
6428
6804
  async function init(io, opts) {
6429
6805
  const exec = requireExec(io);
6430
6806
  const first = (await loadCredentials(io)).credentials;
@@ -6504,6 +6880,7 @@ async function init(io, opts) {
6504
6880
  body
6505
6881
  ]);
6506
6882
  log(`Updated pull request ${existing.url}`);
6883
+ log(mergeHint(existing.number));
6507
6884
  } else {
6508
6885
  const url = await sh(exec, root, "gh", [
6509
6886
  "pr",
@@ -6519,8 +6896,12 @@ async function init(io, opts) {
6519
6896
  "--body",
6520
6897
  body
6521
6898
  ]);
6522
- log(`Opened pull request ${url.split(`
6523
- `).pop()}`);
6899
+ const opened = url.split(`
6900
+ `).pop() ?? "";
6901
+ log(`Opened pull request ${opened}`);
6902
+ const number = opened.match(/\/pull\/(\d+)/)?.[1];
6903
+ if (number)
6904
+ log(mergeHint(Number(number)));
6524
6905
  }
6525
6906
  if (plan.installed.length)
6526
6907
  log(`Installs: ${plan.installed.join(", ")}`);
@@ -6550,22 +6931,28 @@ var TRANSIENT = /\bHTTP 5\d\d\b|\b5\d\d (?:Bad Gateway|Service Unavailable|Gatew
6550
6931
  var tail = (text, lines = 30) => text.trimEnd().split(`
6551
6932
  `).slice(-lines).join(`
6552
6933
  `);
6553
- function ghMerge(exec, cwd, repository) {
6554
- return async (number, sha) => {
6555
- const args = ["pr", "merge", String(number), "--repo", repository, "--squash", "--match-head-commit", sha];
6556
- try {
6557
- const r = await exec("gh", args, { cwd });
6558
- const message = tail(`${r.stderr}
6934
+ async function ghAttempt(exec, cwd, args) {
6935
+ try {
6936
+ const r = await exec("gh", args, { cwd });
6937
+ const message = tail(`${r.stderr}
6559
6938
  ${r.stdout}`.trim(), 5) || `gh exited with ${r.code}`;
6560
- return { ok: r.code === 0, message, transient: r.code !== 0 && TRANSIENT.test(message) };
6561
- } catch (err) {
6562
- return {
6563
- ok: false,
6564
- message: `cannot run gh: ${err instanceof Error ? err.message : String(err)}`,
6565
- transient: false
6566
- };
6567
- }
6568
- };
6939
+ return { ok: r.code === 0, message, transient: r.code !== 0 && TRANSIENT.test(message) };
6940
+ } catch (err) {
6941
+ return {
6942
+ ok: false,
6943
+ message: `cannot run gh: ${err instanceof Error ? err.message : String(err)}`,
6944
+ transient: false
6945
+ };
6946
+ }
6947
+ }
6948
+ function ghMerge(exec, cwd, repository) {
6949
+ return (number, sha) => ghAttempt(exec, cwd, ["pr", "merge", String(number), "--repo", repository, "--squash", "--match-head-commit", sha]);
6950
+ }
6951
+ function ghUpdateBranch(exec, cwd, repository) {
6952
+ return (number, sha) => ghAttempt(exec, cwd, [
6953
+ ...["api", "--method", "PUT", `repos/${repository}/pulls/${number}/update-branch`],
6954
+ ...["-f", `expected_head_sha=${sha}`]
6955
+ ]);
6569
6956
  }
6570
6957
  var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6571
6958
  function gitRepo(exec, cwd) {
@@ -6603,6 +6990,18 @@ function gitRepo(exec, cwd) {
6603
6990
  }
6604
6991
  return uses;
6605
6992
  },
6993
+ async mergeTree({ branch, number, ours, theirs }) {
6994
+ const present = async (sha) => (await git(["cat-file", "-e", `${sha}^{commit}`])).code === 0;
6995
+ if (!await present(ours) || !await present(theirs))
6996
+ await must(["fetch", "--quiet", "origin", branch, `refs/pull/${number}/head`]);
6997
+ const r = await git(["merge-tree", "--write-tree", "--no-messages", ours, theirs]);
6998
+ if (r.code === 1)
6999
+ return null;
7000
+ if (r.code !== 0)
7001
+ throw new Error(`git merge-tree failed: ${tail(r.stderr || r.stdout, 5)}`);
7002
+ return r.stdout.split(`
7003
+ `)[0]?.trim() || null;
7004
+ },
6606
7005
  async testMerge({ branch, base, head, number, commands }) {
6607
7006
  await must(["fetch", "--quiet", "origin", branch, `refs/pull/${number}/head`]);
6608
7007
  const dir = join5(tmpdir2(), `armada-merge-${number}-${randomUUID().slice(0, 8)}`);
@@ -6654,8 +7053,14 @@ function prNumber(arg, repository) {
6654
7053
  throw new UsageError(`${pr.url} is not in the project repository ${repository}`);
6655
7054
  return pr.number;
6656
7055
  }
7056
+ function waitMinutes(raw) {
7057
+ const n = Number(raw);
7058
+ if (!Number.isFinite(n) || n <= 0)
7059
+ throw new UsageError(`--timeout must be a number of minutes, got "${raw}"`);
7060
+ return n;
7061
+ }
6657
7062
  function render(o) {
6658
- const out = [...o.lines, o.pr.url, o.ticket.url];
7063
+ const out = [...o.lines, o.pr.url, ...o.ticket ? [o.ticket.url] : []];
6659
7064
  if (o.hints.length)
6660
7065
  out.push("Hints for you to judge (not blocking):", ...o.hints.map((h) => ` - ${h}`));
6661
7066
  if (!o.merged)
@@ -6670,7 +7075,7 @@ function render(o) {
6670
7075
  out.push(` ${w.ticket} ${w.phase} ${[w.runtime, w.handle].filter(Boolean).join(" · ") || "runtime unknown"} ${w.title}`);
6671
7076
  }
6672
7077
  const a = o.archive;
6673
- if (a) {
7078
+ if (a && o.ticket) {
6674
7079
  const who = `${o.ticket.id} (${[a.runtime, a.handle].filter(Boolean).join(" · ") || "session unknown"})`;
6675
7080
  out.push(a.guide ? `Archive the worker's workspace of ${who} with the "Stop and archive" section of the ${a.guide} skill.` : `No runtime guide is installed for ${a.runtime ?? "the worker's runtime"}, so Armada has nothing to archive for ${who}: a local session or subagent ends with its task; stop it yourself if it still runs.`);
6676
7081
  }
@@ -6683,6 +7088,15 @@ async function merge2(io, config, credentials, a, configPath) {
6683
7088
  if (extra.length)
6684
7089
  throw new UsageError(`unexpected argument ${extra[0]}`);
6685
7090
  const number = prNumber(arg, config.github.repository);
7091
+ const noTicket = !!a.options["no-ticket"];
7092
+ if (noTicket && a.options.ticket)
7093
+ throw new UsageError("--no-ticket and --ticket cannot go together");
7094
+ const wait = !!a.options.wait;
7095
+ if (wait && a.options["dry-run"])
7096
+ throw new UsageError("--wait and --dry-run cannot go together");
7097
+ if (!wait && a.options.timeout !== undefined)
7098
+ throw new UsageError("--timeout applies to --wait");
7099
+ const timeoutMs = a.options.timeout === undefined ? MERGE_WAIT_DEFAULT_MS : waitMinutes(a.options.timeout) * 60000;
6686
7100
  if (!credentials.linearApiKey)
6687
7101
  throw missingKey(LINEAR_KEY);
6688
7102
  const token = credentials.githubToken;
@@ -6705,7 +7119,9 @@ async function merge2(io, config, credentials, a, configPath) {
6705
7119
  readPull: (n) => fetchMergePull({ ...gh, number: n }),
6706
7120
  compare: (base, head) => fetchComparison({ ...gh, base, head }),
6707
7121
  diff: (n) => fetchPullDiff({ ...gh, number: n }),
6708
- merge: ghMerge(exec, repoDir, config.github.repository)
7122
+ merge: ghMerge(exec, repoDir, config.github.repository),
7123
+ commit: (sha) => fetchCommit({ ...gh, sha }),
7124
+ updateBranch: ghUpdateBranch(exec, repoDir, config.github.repository)
6709
7125
  },
6710
7126
  repo: gitRepo(exec, repoDir),
6711
7127
  lockRequired: !!credentials.armadaSignIn,
@@ -6731,13 +7147,15 @@ async function merge2(io, config, credentials, a, configPath) {
6731
7147
  const o = await mergePullRequest(ctx, {
6732
7148
  pr: number,
6733
7149
  ticket: a.options.ticket ?? null,
7150
+ noTicket,
7151
+ wait: wait ? { timeoutMs } : null,
6734
7152
  dryRun: !!a.options["dry-run"],
6735
7153
  noLock: !!a.options["no-lock"]
6736
7154
  });
6737
7155
  const project = config.project.slug;
6738
7156
  const coordinator = coordinatorHandle(io);
6739
7157
  const known = (await watchOf(io, project)).state?.inFlight ?? null;
6740
- const inFlight = o.workersListed ? o.workers.filter((w) => !coordinator || w.handle !== coordinator).map((w) => w.ticket).sort((x, y) => x.localeCompare(y, "en", { numeric: true })) : o.merged && known ? known.filter((t) => t !== o.ticket.id) : known;
7158
+ const inFlight = o.workersListed ? o.workers.filter((w) => !coordinator || w.handle !== coordinator).map((w) => w.ticket).sort((x, y) => x.localeCompare(y, "en", { numeric: true })) : o.merged && known ? known.filter((t) => t !== o.ticket?.id) : known;
6741
7159
  if (o.merged)
6742
7160
  await remember(io, project, { inFlight, readAt: (io.now ?? (() => new Date))().toISOString() });
6743
7161
  const next = await rearmFor(io, project, { inFlight, open: null });
@@ -6747,7 +7165,7 @@ async function merge2(io, config, credentials, a, configPath) {
6747
7165
  for (const w of o.warnings)
6748
7166
  io.stderr(`armada: warning: ${w}
6749
7167
  `);
6750
- if (o.merged)
7168
+ if (o.merged && o.ticket)
6751
7169
  await endWorkerSessions(io, config, credentials, o.ticket.id, "merged", a.json);
6752
7170
  return 0;
6753
7171
  }
@@ -6960,13 +7378,19 @@ var COMMAND_HELP = {
6960
7378
  answer --note <ticket|plan item> "<message>"
6961
7379
  Coordinator: record a delivered note; an open plan is resolved
6962
7380
  `,
6963
- merge: ` merge <pr> [--ticket <id>] [--dry-run] [--no-lock]
7381
+ merge: ` merge <pr> [--ticket <id> | --no-ticket] [--dry-run] [--no-lock] [--wait [--timeout <min>]]
6964
7382
  Coordinator: check a handed-back pull request (hand-back SHA = head,
6965
7383
  CLEAN, required checks green, no open review thread, base contained
6966
7384
  or test-merged), squash-merge it pinned to that SHA under the merge
6967
7385
  lock, close the ticket and list the workers to tell. Never deletes
6968
7386
  the branch. --dry-run only runs the checklist. Signed in to Armada,
6969
7387
  refused while Armada is down; --no-lock then merges without the lock.
7388
+ --wait (--timeout in minutes, default 30): a head behind its base is
7389
+ updated on GitHub (a merge commit, no force-push) and its checks waited
7390
+ for, without the lock; a red check or a conflict stops it. A head that
7391
+ is the hand-back with only the base merged in counts as the hand-back.
7392
+ --no-ticket: a pull request no ticket owns (armada init, a release);
7393
+ nothing is written to Linear.
6970
7394
  `,
6971
7395
  brief: ` brief <ticket> [--profile <name> [--reason <why>]] [--prompt]
6972
7396
  A new worker's launch prompt, the Conductor profile (agent, model,
@@ -7083,7 +7507,7 @@ var VALUE_OPTIONS = [
7083
7507
  "launch-token",
7084
7508
  "api-url"
7085
7509
  ];
7086
- var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key", "no-stop-hook"];
7510
+ var FLAG_OPTIONS = ["dry-run", "no-lock", "no-ticket", "prompt", "wait", "note", "api-key", "no-stop-hook"];
7087
7511
  var COMMAND_OPTIONS = {
7088
7512
  claim: ["runtime", "handle", "branch", "profile", "reason"],
7089
7513
  report: ["ticket", "message", "message-file", "plan", "plan-file", "pr", "sha"],
@@ -7092,7 +7516,7 @@ var COMMAND_OPTIONS = {
7092
7516
  inbox: ["wait", "timeout"],
7093
7517
  answer: ["note", "message", "message-file"],
7094
7518
  init: ["program-root", "name", "slug", "no-stop-hook"],
7095
- merge: ["ticket", "dry-run", "no-lock"],
7519
+ merge: ["ticket", "no-ticket", "dry-run", "no-lock", "wait", "timeout"],
7096
7520
  brief: ["profile", "reason", "prompt"],
7097
7521
  login: ["api-key", "launch-token", "api-url"]
7098
7522
  };