@the-vibe-company/armada 0.2.1 → 0.2.3

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 +27 -4
  2. package/dist/armada.js +1045 -546
  3. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -7,7 +7,7 @@ import { readFile as readFile3 } from "node:fs/promises";
7
7
  import { isatty } from "node:tty";
8
8
 
9
9
  // src/cli.ts
10
- import { dirname as dirname3, join as join5, resolve } from "node:path";
10
+ import { dirname as dirname5, join as join5, resolve } from "node:path";
11
11
 
12
12
  // ../core/src/types.ts
13
13
  var LABEL_PHASES = [
@@ -220,6 +220,19 @@ function networkReason(err, timeoutMs) {
220
220
  }
221
221
  var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
222
222
  var CLOSED = new Set(["completed", "canceled"]);
223
+ var isCandidate = (i, rootId) => i.id !== rootId && !CLOSED.has(i.statusType) && (i.agentPhase !== null || i.statusType === "started");
224
+ async function readComments(opts, issues, warnings) {
225
+ const comments = [];
226
+ for (const batch of chunks(issues.map((i) => i.uuid), COMMENT_BATCH)) {
227
+ const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
228
+ for (const n of data.issues.nodes) {
229
+ await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
230
+ for (const c of n.comments.nodes)
231
+ comments.push(normalizeComment(c, n.identifier));
232
+ }
233
+ }
234
+ return comments;
235
+ }
223
236
  async function fetchProgram(opts) {
224
237
  try {
225
238
  return await fetchTree(opts, true);
@@ -260,16 +273,7 @@ async function fetchTree(opts, delegate) {
260
273
  for (const field of ["inverseRelations", "labels", "attachments"])
261
274
  await readRest(opts, r.identifier, MORE[field], r[field], warnings);
262
275
  const issues = all.map((r) => normalizeIssue(r, opts.labels));
263
- const candidates = issues.filter((i) => i.id !== root.identifier && !CLOSED.has(i.statusType) && (i.agentPhase || i.statusType === "started"));
264
- const comments = [];
265
- for (const batch of chunks(candidates.map((i) => i.uuid), COMMENT_BATCH)) {
266
- const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
267
- for (const n of data.issues.nodes) {
268
- await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
269
- for (const c of n.comments.nodes)
270
- comments.push(normalizeComment(c, n.identifier));
271
- }
272
- }
276
+ const comments = await readComments(opts, issues.filter((i) => isCandidate(i, root.identifier)), warnings);
273
277
  return {
274
278
  rootId: root.identifier,
275
279
  fetchedAt: (opts.now?.() ?? new Date).toISOString(),
@@ -303,6 +307,13 @@ async function readRest(opts, identifier, more, conn, warnings) {
303
307
  }
304
308
  }
305
309
  }
310
+ var CHANGED_COMMENTS_QUERY = `
311
+ query ChangedComments($filter: CommentFilter, $after: String) {
312
+ comments(first: ${MORE_PAGE}, after: $after, filter: $filter) {
313
+ pageInfo { hasNextPage endCursor }
314
+ nodes { ${MORE.comments.nodes} issue { identifier } }
315
+ }
316
+ }`;
306
317
 
307
318
  // ../core/src/armada-api.ts
308
319
  var displayCode = (code) => code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
@@ -1794,7 +1805,8 @@ var CONFIG_DEFAULTS = {
1794
1805
  phaseGroup: "Agent phase",
1795
1806
  runtimeGroup: "Agent runtime",
1796
1807
  runtimes: ["Claude Code", "Codex", "Conductor"],
1797
- silentAfterMinutes: 15
1808
+ silentAfterMinutes: 15,
1809
+ coordinatorMinutes: 10
1798
1810
  };
1799
1811
 
1800
1812
  class ConfigError extends Error {
@@ -1882,7 +1894,7 @@ function parseConfig(text, source = CONFIG_FILE) {
1882
1894
  ["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
1883
1895
  ["github", github, ["repository"]],
1884
1896
  ["gates", gatesT, ["required_checks", "local_commands"]],
1885
- ["policy", policyT, ["silence_minutes", "silent_after_minutes"]],
1897
+ ["policy", policyT, ["silence_minutes", "silent_after_minutes", "coordinator_minutes"]],
1886
1898
  ["conductor", conductorT, ["default_profile", "profiles", "routing"]]
1887
1899
  ];
1888
1900
  const profiles = {};
@@ -1959,6 +1971,14 @@ function parseConfig(text, source = CONFIG_FILE) {
1959
1971
  else
1960
1972
  problems.push(`"policy.${silenceKey}" must be a positive number`);
1961
1973
  }
1974
+ let coordinatorMinutes = CONFIG_DEFAULTS.coordinatorMinutes;
1975
+ if (policyT.coordinator_minutes !== undefined) {
1976
+ const v = policyT.coordinator_minutes;
1977
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
1978
+ coordinatorMinutes = v;
1979
+ else
1980
+ problems.push(`"policy.coordinator_minutes" must be a positive number`);
1981
+ }
1962
1982
  let requiredChecks = [];
1963
1983
  if (gatesT.required_checks !== undefined) {
1964
1984
  const v = gatesT.required_checks;
@@ -1997,7 +2017,7 @@ function parseConfig(text, source = CONFIG_FILE) {
1997
2017
  repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
1998
2018
  },
1999
2019
  gates: { requiredChecks, localCommands },
2000
- policy: { silentAfterMinutes },
2020
+ policy: { silentAfterMinutes, coordinatorMinutes },
2001
2021
  conductor: { defaultProfile, profiles, routing }
2002
2022
  };
2003
2023
  if (problems.length)
@@ -2032,6 +2052,7 @@ repository = ${q(p.repository)}
2032
2052
 
2033
2053
  [policy]
2034
2054
  silence_minutes = 15 # a worker with no report for longer than this shows as silent
2055
+ coordinator_minutes = 10 # an inbox item open longer than this shows "waiting for the coordinator"
2035
2056
 
2036
2057
  # How \`armada brief\` launches workers on Conductor. Every value is passed explicitly;
2037
2058
  # \`conductor model\` lists each agent's model ids and effort levels.
@@ -3324,11 +3345,13 @@ async function checkInbox(fleet, o) {
3324
3345
  throw new Error("Armada answered the first inbox read with nothing");
3325
3346
  const warnings = [...first.warnings];
3326
3347
  let items = first.items;
3348
+ let inFlight = first.inFlight ?? null;
3327
3349
  let etag = first.etag;
3328
3350
  const report = (timedOut) => ({
3329
3351
  project: o.project,
3330
3352
  generatedAt: o.now().toISOString(),
3331
3353
  items,
3354
+ inFlight,
3332
3355
  wait: o.wait && timedOut !== null ? { timeoutSeconds: Math.round(o.wait.timeoutMs / 1000), timedOut } : null,
3333
3356
  warnings: [...new Set(warnings)]
3334
3357
  });
@@ -3345,6 +3368,7 @@ async function checkInbox(fleet, o) {
3345
3368
  continue;
3346
3369
  const known = new Set(items.map(entryKey));
3347
3370
  items = read.items.map((e) => ({ ...e, new: !known.has(entryKey(e)) }));
3371
+ inFlight = read.inFlight ?? null;
3348
3372
  etag = read.etag;
3349
3373
  warnings.push(...read.warnings);
3350
3374
  if (items.some((e) => e.new))
@@ -3666,8 +3690,110 @@ function createLinearWriter(opts) {
3666
3690
  }
3667
3691
  // ../core/src/machine.ts
3668
3692
  import { randomBytes } from "node:crypto";
3669
- import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
3670
- import { isAbsolute, join } from "node:path";
3693
+ import { chmod, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3694
+ import { dirname, isAbsolute, join } from "node:path";
3695
+
3696
+ // ../core/src/watch.ts
3697
+ var WATCH_POLL_MS = 15000;
3698
+ var WATCH_IDLE_POLL_MS = 60000;
3699
+ var WATCH_BACKOFF_MS = [15000, 30000, 60000];
3700
+ var STOP_HOOK_VARIABLE = "ARMADA_STOP_HOOK";
3701
+ var EMPTY_WATCH_STATE = { root: null, seen: [], inFlight: null, readAt: null, stopped: null };
3702
+ function transientFailure(err) {
3703
+ if (!(err instanceof ArmadaApiError))
3704
+ return false;
3705
+ const s = err.status;
3706
+ if (s !== null)
3707
+ return s >= 500 || s === 408 || s === 429;
3708
+ return /\bunreachable\b|\bHTTP (?:5\d\d|408|429) without JSON\b/.test(err.message);
3709
+ }
3710
+ async function watchInbox(fleet, o) {
3711
+ const query = { coordinator: o.coordinator, silentAfterMinutes: o.silentAfterMinutes };
3712
+ const pollMs = o.pollMs ?? WATCH_POLL_MS;
3713
+ const idlePollMs = o.idlePollMs ?? WATCH_IDLE_POLL_MS;
3714
+ let known = new Set(o.seen);
3715
+ let etag = null;
3716
+ let items = [];
3717
+ let inFlight = null;
3718
+ let failures = 0;
3719
+ const warnings = new Set;
3720
+ const report = (outcome) => ({
3721
+ project: o.project,
3722
+ generatedAt: o.now().toISOString(),
3723
+ outcome,
3724
+ items,
3725
+ inFlight,
3726
+ warnings: [...warnings]
3727
+ });
3728
+ for (;; ) {
3729
+ let read;
3730
+ try {
3731
+ read = await fleet.inbox({ ...query, etag });
3732
+ } catch (err) {
3733
+ if (!transientFailure(err))
3734
+ throw err;
3735
+ const wait = WATCH_BACKOFF_MS[Math.min(failures, WATCH_BACKOFF_MS.length - 1)] ?? pollMs;
3736
+ failures++;
3737
+ o.onRetry?.(`${err.message}; still watching, next try in ${wait / 1000} s`);
3738
+ await o.sleep(wait);
3739
+ continue;
3740
+ }
3741
+ failures = 0;
3742
+ if (read) {
3743
+ items = read.items.map((e) => ({ ...e, new: !known.has(entryKey(e)) }));
3744
+ inFlight = read.inFlight ?? null;
3745
+ etag = read.etag;
3746
+ known = new Set(items.map(entryKey));
3747
+ for (const w of read.warnings)
3748
+ warnings.add(w);
3749
+ await o.onRead?.({ items, inFlight });
3750
+ if (items.some((e) => e.new))
3751
+ return report("items");
3752
+ if (inFlight !== null && !inFlight.length && !items.length)
3753
+ return report("nothing");
3754
+ }
3755
+ await o.sleep(inFlight !== null && !inFlight.length ? idlePollMs : pollMs);
3756
+ }
3757
+ }
3758
+ var workers = (n) => `${n} worker${n === 1 ? "" : "s"} in flight`;
3759
+ function rearm(o) {
3760
+ const then = o.act ? "act on the items above, then " : "";
3761
+ const watch = o.running !== null ? `armada watch is already running (pid ${o.running})` : null;
3762
+ let line;
3763
+ if (o.inFlight === null)
3764
+ line = watch ? `Workers may be in flight — ${then}${watch}.` : `While a worker is in flight, ${then}keep watching: armada watch`;
3765
+ else if (o.inFlight.length)
3766
+ line = `${workers(o.inFlight.length)} (${o.inFlight.join(", ")}) — ${watch ? `${then}${watch}.` : `${then}keep watching: armada watch`}`;
3767
+ else if (o.open)
3768
+ line = `No worker in flight, ${o.open} item${o.open === 1 ? "" : "s"} open — ${watch ? `${then}${watch}.` : `${then}keep watching: armada watch`}`;
3769
+ else if (o.open === null)
3770
+ line = "No worker in flight — nothing to watch.";
3771
+ else
3772
+ line = "No worker in flight and nothing open — nothing to watch.";
3773
+ return { inFlight: o.inFlight, open: o.open, running: o.running, line };
3774
+ }
3775
+ function stopHookDecision(o) {
3776
+ const off = o.env[STOP_HOOK_VARIABLE]?.trim().toLowerCase();
3777
+ if (off === "off" || off === "0" || off === "false")
3778
+ return { block: false, why: `${STOP_HOOK_VARIABLE}=${off}` };
3779
+ const s = o.state;
3780
+ if (!s?.root)
3781
+ return { block: false, why: `armada watch never ran for ${o.project} on this machine` };
3782
+ if (s.root !== o.root)
3783
+ return { block: false, why: `the coordinator's checkout is ${s.root}, not this one` };
3784
+ if (o.watching !== null)
3785
+ return { block: false, why: `armada watch is running (pid ${o.watching})` };
3786
+ if (s.stopped)
3787
+ return { block: false, why: `the last watch was refused: ${s.stopped}` };
3788
+ if (!s.inFlight?.length)
3789
+ return { block: false, why: "no worker in flight at the last read" };
3790
+ return {
3791
+ block: true,
3792
+ reason: `${workers(s.inFlight.length)} on ${o.project} (${s.inFlight.join(", ")}) and no armada watch is running, so a hand-back or a question would go unnoticed. Start \`armada watch\` in the background now (in Claude Code, Bash with run_in_background), then end your turn: you are woken when it returns. (${STOP_HOOK_VARIABLE}=off turns this hook off.)`
3793
+ };
3794
+ }
3795
+
3796
+ // ../core/src/machine.ts
3671
3797
  function machinePaths(env) {
3672
3798
  const xdg = env.XDG_CONFIG_HOME?.trim();
3673
3799
  const home = env.HOME?.trim();
@@ -3697,6 +3823,8 @@ var storeIsExposed = (store) => store.mode !== null && (store.mode & 63) !== 0;
3697
3823
  async function writePrivate(paths, path, text, mode) {
3698
3824
  await mkdir(paths.dir, { recursive: true, mode: 448 });
3699
3825
  await chmod(paths.dir, 448);
3826
+ if (dirname(path) !== paths.dir)
3827
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
3700
3828
  const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
3701
3829
  const handle = await open(tmp, "wx", mode);
3702
3830
  try {
@@ -3807,6 +3935,88 @@ async function ensurePersonalConfig(paths) {
3807
3935
  await writePrivate(paths, paths.config, PERSONAL_CONFIG_TEMPLATE, 420);
3808
3936
  return true;
3809
3937
  }
3938
+ function watchFiles(paths, project) {
3939
+ const dir = join(paths.dir, "watch");
3940
+ return { state: join(dir, `${project}.json`), lock: join(dir, `${project}.pid`) };
3941
+ }
3942
+ var strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null;
3943
+ var stringOr = (v) => typeof v === "string" && v ? v : null;
3944
+ async function readWatchState(paths, project) {
3945
+ let raw;
3946
+ try {
3947
+ raw = JSON.parse(await readFile(watchFiles(paths, project).state, "utf8"));
3948
+ } catch {
3949
+ return null;
3950
+ }
3951
+ if (typeof raw !== "object" || raw === null)
3952
+ return null;
3953
+ const r = raw;
3954
+ return {
3955
+ root: stringOr(r.root),
3956
+ seen: strings(r.seen) ?? [],
3957
+ inFlight: strings(r.inFlight),
3958
+ readAt: stringOr(r.readAt),
3959
+ stopped: stringOr(r.stopped)
3960
+ };
3961
+ }
3962
+ async function updateWatchState(paths, project, patch) {
3963
+ const state = { ...EMPTY_WATCH_STATE, ...await readWatchState(paths, project), ...patch };
3964
+ await writePrivate(paths, watchFiles(paths, project).state, `${JSON.stringify(state, null, 2)}
3965
+ `, 384);
3966
+ return state;
3967
+ }
3968
+ async function readWatchLock(paths, project) {
3969
+ try {
3970
+ const pid = Number((await readFile(watchFiles(paths, project).lock, "utf8")).trim());
3971
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
3972
+ } catch (err) {
3973
+ if (missing(err))
3974
+ return null;
3975
+ throw err;
3976
+ }
3977
+ }
3978
+ function processAlive(pid) {
3979
+ try {
3980
+ process.kill(pid, 0);
3981
+ return true;
3982
+ } catch (err) {
3983
+ return err.code === "EPERM";
3984
+ }
3985
+ }
3986
+ async function takeWatchLock(paths, project, pid, alive = processAlive) {
3987
+ const { lock } = watchFiles(paths, project);
3988
+ await mkdir(dirname(lock), { recursive: true, mode: 448 });
3989
+ const tmp = `${lock}.${randomBytes(6).toString("hex")}.tmp`;
3990
+ await writeFile(tmp, `${pid}
3991
+ `, { mode: 384 });
3992
+ try {
3993
+ for (let attempt = 0;attempt < 3; attempt++) {
3994
+ try {
3995
+ await link(tmp, lock);
3996
+ return { taken: true };
3997
+ } catch (err) {
3998
+ if (err.code !== "EEXIST")
3999
+ throw err;
4000
+ }
4001
+ const held = await readWatchLock(paths, project);
4002
+ if (held !== null && held !== pid && alive(held))
4003
+ return { taken: false, pid: held };
4004
+ if (await readWatchLock(paths, project) === held)
4005
+ await rm(lock, { force: true });
4006
+ }
4007
+ throw new Error(`cannot take the watch lock ${lock}`);
4008
+ } finally {
4009
+ await rm(tmp, { force: true });
4010
+ }
4011
+ }
4012
+ async function releaseWatchLock(paths, project, pid) {
4013
+ if (await readWatchLock(paths, project).catch(() => null) === pid)
4014
+ await rm(watchFiles(paths, project).lock, { force: true });
4015
+ }
4016
+ async function runningWatch(paths, project, alive = processAlive) {
4017
+ const pid = await readWatchLock(paths, project).catch(() => null);
4018
+ return pid !== null && alive(pid) ? pid : null;
4019
+ }
3810
4020
  // ../core/src/merge.ts
3811
4021
  var MERGE_LEASE = "merge";
3812
4022
  var MERGE_LEASE_TTL_MS = 20 * 60000;
@@ -4201,6 +4411,7 @@ async function after(ctx, c, merged, lines) {
4201
4411
  if (live$?.resolved)
4202
4412
  lines.push(`Hand-back resolved in the coordinator's inbox.`);
4203
4413
  let workers = [];
4414
+ let listed = false;
4204
4415
  try {
4205
4416
  const handles = new Map((live$?.open ?? []).map((h) => [h.ticket, h]));
4206
4417
  workers = (await ctx.inFlight()).filter((t) => t.id !== c.ticket.id).map((t) => ({
@@ -4210,6 +4421,7 @@ async function after(ctx, c, merged, lines) {
4210
4421
  runtime: t.runtime ?? handles.get(t.id)?.runtime ?? null,
4211
4422
  handle: handles.get(t.id)?.handle ?? null
4212
4423
  }));
4424
+ listed = true;
4213
4425
  } catch (err) {
4214
4426
  c.warnings.push(`could not list the workers in flight (${err instanceof Error ? err.message : String(err)}); run armada status`);
4215
4427
  }
@@ -4223,7 +4435,7 @@ async function after(ctx, c, merged, lines) {
4223
4435
  c.warnings.push(`could not look for the ${expected} skill (${err instanceof Error ? err.message : String(err)})`);
4224
4436
  }
4225
4437
  const archive = { runtime, handle: live$?.handle?.handle ?? claim?.session ?? null, guide };
4226
- return outcome(c, true, merged, lines, workers, archive);
4438
+ return { ...outcome(c, true, merged, lines, workers, archive), workersListed: listed };
4227
4439
  }
4228
4440
  function outcome(c, merged, pr, lines, workers, archive) {
4229
4441
  const p = pr ?? c.pull;
@@ -4241,6 +4453,7 @@ function outcome(c, merged, pr, lines, workers, archive) {
4241
4453
  lines,
4242
4454
  hints: c.hints,
4243
4455
  workers,
4456
+ workersListed: false,
4244
4457
  archive,
4245
4458
  warnings: c.warnings
4246
4459
  };
@@ -4293,7 +4506,7 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
4293
4506
  1. **Sign in to Armada.** \`armada doctor\` (or \`armada whoami\`) says whether this terminal is signed in and to which organization. If not: a person runs \`armada login\` and approves the code in the browser; a headless coordinator (a cloud workspace, CI) sets \`ARMADA_API_KEY\` to an organization API key an owner created on the Organization page. Signed in, Armada gives your commands the organization's keys, and every brief carries a one-time launch token, so no worker needs a key in its environment. Keys set in the environment still win over Armada's: they are the override for CI and a self-hosted Armada without accounts.
4294
4507
  2. **Find your coordination ticket.** When the owner gives the coordinator a ticket of its own (a run to carry out, for example "run this ticket end to end"), that ticket holds the run's history. Read its comments, newest first. A last comment \`Agent status: released — <text>\` is a hand-over: the previous coordinator stopped on purpose, \`<text>\` is the state it left (who runs, what was asked and answered, what remains), and the ticket is back without agent labels, waiting for you.
4295
4508
  3. **Claim it with your own handle**, never the previous coordinator's: \`armada claim <ticket> --runtime <your runtime> --handle <your handle> --branch <default branch>\`. In a Conductor workspace the runtime is \`conductor\` and the handle \`"$CONDUCTOR_WORKSPACE_ID/$CONDUCTOR_SESSION_ID"\`; on a laptop, the runtime you run in (a value of the runtime label group, for example \`claude-code\`) and a handle that names your session. The claim is refused while the previous coordinator still holds the ticket: ask the owner whether it stopped before releasing it for them. Without a coordination ticket, skip this step.
4296
- 4. **Read the fleet** (step 1 of the loop): \`armada status\` and \`armada inbox\` give each worker's handle, phase, question and hand-back. Trust them over the hand-over comment where they disagree: the comment is older.
4509
+ 4. **Read the fleet** (step 1 of the loop): \`armada status\` and \`armada inbox\` give each worker's handle, phase, question and hand-back. Trust them over the hand-over comment where they disagree: the comment is older. If a worker is in flight, start \`armada watch\` in the background now (see [Keep watching](#keep-watching)).
4297
4510
  5. **Report on your ticket** as a worker would, \`armada report implementing --ticket <ticket> --message "<what you found and do next>"\`, at least every \`policy.silence_minutes\`, and post the run's evidence there when it ends.
4298
4511
  6. **Hand over** when you stop before the run ends: \`armada release --ticket <ticket> --reason "<state so far and what remains>"\`. It posts the \`released\` comment the next coordinator reads. Write it for a reader with none of your context.
4299
4512
 
@@ -4316,7 +4529,18 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
4316
4529
  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.
4317
4530
  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.
4318
4531
 
4319
- Repeat from step 1. Between rounds, \`armada inbox --wait\` blocks until a new item arrives or its timeout (default 300 s, \`--timeout <seconds>\`; keep it under your command time limit). Each \`armada inbox\` call also tells the dashboard you are at work.
4532
+ Repeat from step 1.
4533
+
4534
+ ## Keep watching
4535
+
4536
+ You only learn of something new when a command you run ends. So while a worker is in flight, always have exactly one \`armada watch\` running, in the background (in Claude Code, a Bash command with \`run_in_background\`; in another runtime, its own way of running a command in the background). It waits until something needs you (a question, a plan, a request, a hand-back or a silent worker you have not been shown yet), prints it and exits, and you are woken. Armada being down or a command time limit does not end it, and it tells the dashboard you are at work.
4537
+
4538
+ - Start it as soon as a worker is in flight, and start it again right after acting on what it returned. Never end your turn with a worker in flight and no watch running: that is how a hand-back sits unmerged.
4539
+ - The last line of \`armada inbox\`, \`armada watch\`, \`armada merge\` and \`armada brief\` says whether to: \`2 workers in flight (ABC-1, ABC-2) — keep watching: armada watch\`, \`armada watch is already running (pid …)\`, or \`nothing to watch\`. Follow it. A second \`armada watch\` on the same project only says the first one is running.
4540
+ - \`armada watch\` exits with "nothing to watch" when no worker is in flight and nothing is open: the round is over.
4541
+ - Your own coordination ticket is not a worker: the watch and the re-arm line leave out the claim whose handle is yours, taken from \`ARMADA_COORDINATOR_HANDLE\`, else from Conductor's workspace and session. Outside Conductor, set \`ARMADA_COORDINATOR_HANDLE\` to the handle you claimed with.
4542
+ - In Claude Code, the stop hook \`armada init\` installs refuses to end your turn while workers are in flight and no watch runs, and tells you to start one. It holds only the checkout where \`armada watch\` ran, never a worker. If it misbehaves, \`ARMADA_STOP_HOOK=off\` in the environment turns it off; say so in your report. Other runtimes have no hook: follow the same rule yourself.
4543
+ - A runtime that cannot run a command in the background uses \`armada inbox --wait\` instead, again and again: it returns when a new item arrives or at its timeout (default 300 s, \`--timeout <seconds>\`; keep it under your command time limit).
4320
4544
 
4321
4545
  ## Rules of thumb
4322
4546
 
@@ -4390,6 +4614,8 @@ var AGENTS_SKILLS_DIR = ".agents/skills";
4390
4614
  var CLAUDE_SKILLS_DIR = ".claude/skills";
4391
4615
  var SKILLS_LOCK_FILE = "skills-lock.json";
4392
4616
  var CONDUCTOR_SETTINGS = ".conductor/settings.toml";
4617
+ var CLAUDE_SETTINGS = ".claude/settings.json";
4618
+ var STOP_HOOK_COMMAND = "armada hook stop 2>/dev/null || true";
4393
4619
  var GITIGNORE = ".gitignore";
4394
4620
  var SHIP_ARTIFACTS = "plans/ship-pr-dev/";
4395
4621
  var ok = (id, message) => ({ id, level: "ok", message, fix: null });
@@ -4505,9 +4731,56 @@ async function checkRepository(view, armadaVersion) {
4505
4731
  throw err;
4506
4732
  checks.push(bad("conductor", "error", err.message, `fix ${CONDUCTOR_SETTINGS}`));
4507
4733
  }
4734
+ checks.push(await stopHookCheck(view));
4508
4735
  checks.push(ignoresShipArtifacts(await view.readFile(GITIGNORE)) ? ok("gitignore", `${GITIGNORE} ignores ${SHIP_ARTIFACTS}`) : bad("gitignore", "warning", `${GITIGNORE} does not ignore ${SHIP_ARTIFACTS}, so the ship-pr-dev skill refuses to start`, "run `armada init`"));
4509
4736
  return checks;
4510
4737
  }
4738
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4739
+ function claudeSettings(text) {
4740
+ if (text === null)
4741
+ return null;
4742
+ let raw;
4743
+ try {
4744
+ raw = JSON.parse(text);
4745
+ } catch {
4746
+ throw new SetupError(`${CLAUDE_SETTINGS} is not valid JSON`);
4747
+ }
4748
+ if (!isObject(raw))
4749
+ throw new SetupError(`${CLAUDE_SETTINGS} is not a JSON object`);
4750
+ return raw;
4751
+ }
4752
+ function hasStopHook(settings) {
4753
+ const stop = isObject(settings?.hooks) ? settings.hooks.Stop : undefined;
4754
+ if (!Array.isArray(stop))
4755
+ return false;
4756
+ return stop.some((group) => isObject(group) && Array.isArray(group.hooks) && group.hooks.some((h) => isObject(h) && typeof h.command === "string" && h.command.includes("armada hook stop")));
4757
+ }
4758
+ function withStopHook(text) {
4759
+ const settings = claudeSettings(text) ?? {};
4760
+ if (hasStopHook(settings))
4761
+ return text ?? "";
4762
+ const hooks = settings.hooks ?? {};
4763
+ if (!isObject(hooks))
4764
+ throw new SetupError(`${CLAUDE_SETTINGS} has a "hooks" value that is not an object`);
4765
+ const stop = hooks.Stop ?? [];
4766
+ if (!Array.isArray(stop))
4767
+ throw new SetupError(`${CLAUDE_SETTINGS} has a "hooks.Stop" value that is not a list`);
4768
+ const entry = { hooks: [{ type: "command", command: STOP_HOOK_COMMAND, timeout: 10 }] };
4769
+ return `${JSON.stringify({ ...settings, hooks: { ...hooks, Stop: [...stop, entry] } }, null, 2)}
4770
+ `;
4771
+ }
4772
+ async function stopHookCheck(view) {
4773
+ const id = "stop-hook";
4774
+ let settings;
4775
+ try {
4776
+ settings = claudeSettings(await view.readFile(CLAUDE_SETTINGS));
4777
+ } catch (err) {
4778
+ if (!(err instanceof SetupError))
4779
+ throw err;
4780
+ return bad(id, "warning", `Claude Code stop hook not checked: ${err.message}`, `fix ${CLAUDE_SETTINGS}`);
4781
+ }
4782
+ return hasStopHook(settings) ? ok(id, `${CLAUDE_SETTINGS} has Armada's stop hook: a Claude Code coordinator cannot end its turn while workers are in flight and no armada watch runs (ARMADA_STOP_HOOK=off turns it off)`) : bad(id, "warning", `${CLAUDE_SETTINGS} has no Armada stop hook, so a Claude Code coordinator can stop watching its fleet without noticing`, "run `armada init` and accept the stop hook (this repository's settings only, never your user settings)");
4783
+ }
4511
4784
  async function guessSetupCommand(view) {
4512
4785
  const has = async (p) => await view.readFile(p) !== null;
4513
4786
  if (await has("bun.lock") || await has("bun.lockb"))
@@ -4570,7 +4843,7 @@ function lockText(lock, armadaVersion) {
4570
4843
  `;
4571
4844
  }
4572
4845
  async function planSetup(view, opts) {
4573
- const plan = { writes: [], removes: [], links: [], installed: [], updated: [] };
4846
+ const plan = { writes: [], removes: [], links: [], installed: [], updated: [], stopHook: false };
4574
4847
  if (opts.configText !== null && await view.readFile(CONFIG_FILE) === null)
4575
4848
  plan.writes.push({ path: CONFIG_FILE, content: opts.configText });
4576
4849
  const wholeDir = await linksWholeDir(view);
@@ -4598,6 +4871,21 @@ async function planSetup(view, opts) {
4598
4871
  plan.writes.push({ path: CONDUCTOR_SETTINGS, content: conductorSettings(await guessSetupCommand(view)) });
4599
4872
  else if (!conductorSetup(settings))
4600
4873
  plan.writes.push({ path: CONDUCTOR_SETTINGS, content: withSetup(settings, await guessSetupCommand(view)) });
4874
+ if (opts.stopHook ?? true) {
4875
+ const before = await view.readFile(CLAUDE_SETTINGS);
4876
+ let after;
4877
+ try {
4878
+ after = withStopHook(before);
4879
+ } catch (err) {
4880
+ if (!(err instanceof SetupError))
4881
+ throw err;
4882
+ throw new SetupError(`${err.message}: fix it, or leave the stop hook out with \`armada init --no-stop-hook\``);
4883
+ }
4884
+ if (after !== (before ?? "")) {
4885
+ plan.writes.push({ path: CLAUDE_SETTINGS, content: after });
4886
+ plan.stopHook = true;
4887
+ }
4888
+ }
4601
4889
  const gitignore = await view.readFile(GITIGNORE);
4602
4890
  if (!ignoresShipArtifacts(gitignore)) {
4603
4891
  const base = gitignore === null || gitignore === "" ? "" : `${gitignore.replace(/\n*$/, `
@@ -4656,6 +4944,7 @@ function buildStatus({
4656
4944
  github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
4657
4945
  },
4658
4946
  silentAfterMinutes: config.policy.silentAfterMinutes,
4947
+ coordinatorMinutes: config.policy.coordinatorMinutes,
4659
4948
  inFlight: lanes.map((l) => ({
4660
4949
  id: l.issue.id,
4661
4950
  title: l.issue.title,
@@ -4705,14 +4994,18 @@ async function readStatusSources(config, opts) {
4705
4994
  ...opts.fetch ? { fetch: opts.fetch } : {},
4706
4995
  now
4707
4996
  });
4708
- const forgeP = opts.githubToken ? fetchForge({
4997
+ const [program, forge] = await Promise.all([programP, readForge(config, opts, now)]);
4998
+ return { program, ...forge };
4999
+ }
5000
+ function readForge(config, opts, now) {
5001
+ if (!opts.githubToken)
5002
+ return Promise.resolve({ forge: null, forgeError: "no GitHub token (set GITHUB_TOKEN or run gh auth login)" });
5003
+ return fetchForge({
4709
5004
  token: opts.githubToken,
4710
5005
  repository: config.github.repository,
4711
5006
  ...opts.fetch ? { fetch: opts.fetch } : {},
4712
5007
  now
4713
- }).then((forge) => ({ forge, forgeError: null }), (err) => ({ forge: null, forgeError: err instanceof Error ? err.message : String(err) })) : Promise.resolve({ forge: null, forgeError: "no GitHub token (set GITHUB_TOKEN or run gh auth login)" });
4714
- const [program, forge] = await Promise.all([programP, forgeP]);
4715
- return { program, ...forge };
5008
+ }).then((forge) => ({ forge, forgeError: null }), (err) => ({ forge: null, forgeError: err instanceof Error ? err.message : String(err) }));
4716
5009
  }
4717
5010
  async function loadStatus(config, opts) {
4718
5011
  const now = opts.now ?? (() => new Date);
@@ -4731,7 +5024,7 @@ async function loadStatus(config, opts) {
4731
5024
  });
4732
5025
  }
4733
5026
  // package.json
4734
- var version = "0.2.1";
5027
+ var version = "0.2.3";
4735
5028
 
4736
5029
  // src/io.ts
4737
5030
  class UsageError extends Error {
@@ -4977,110 +5270,8 @@ async function authLogout(io) {
4977
5270
  return 0;
4978
5271
  }
4979
5272
 
4980
- // src/brief.ts
4981
- function renderBrief(b) {
4982
- const p = b.profile;
4983
- const width = Math.max(...b.environment.map((v) => v.name.length + (v.value ? v.value.length + 1 : 0)));
4984
- const out = [
4985
- `Brief for ${b.ticket.id} — ${b.ticket.title} (${b.ticket.status})`,
4986
- b.ticket.url,
4987
- "",
4988
- `Runtime: conductor (follow the armada-runtime-conductor skill to launch)`,
4989
- `Profile: ${p ? `${p.name}: agent ${p.agent}, model ${p.model}, effort ${p.effort}${p.fastMode ? ", fast mode" : ""}` : "none declared in armada.toml"}`,
4990
- ...b.routing ? [`Chosen by: ${b.routing.why}`] : [],
4991
- `Repository: ${b.repository.url}`,
4992
- `Branch: ${b.ticket.branch ?? "none suggested by Linear"} (the worker renames its workspace branch to it)`,
4993
- `Launch: ${b.launch ? `one-time token in the prompt, valid until ${b.launch.expiresAt.slice(0, 16).replace("T", " ")} UTC: the worker needs no key` : `no launch token${b.noLaunch ? ` (${b.noLaunch})` : ""}: pass the keys below in the worker's environment`}`,
4994
- "",
4995
- "Environment to pass (values are never printed):",
4996
- ...b.environment.map((v) => {
4997
- const label = v.value ? `${v.name}=${v.value}` : v.name;
4998
- const state = v.value ? "value above" : v.inShell ? "set in this shell" : v.inStore ? "in credentials file" : "NOT set in this shell";
4999
- return ` ${label.padEnd(width)} ${v.required ? "required" : "optional"} ${state.padEnd(21)} ${v.purpose}`;
5000
- })
5001
- ];
5002
- if (b.warnings.length)
5003
- out.push("", "Warnings:", ...b.warnings.map((w) => ` - ${w}`));
5004
- out.push("", `----- prompt (\`armada brief ${b.ticket.id} --prompt\` prints only this) -----`, "", b.prompt);
5005
- return out.join(`
5006
- `);
5007
- }
5008
- function launcher(io, config, credentials) {
5009
- return async (ticket) => {
5010
- const signIn = credentials.armadaSignIn;
5011
- if (!signIn)
5012
- return {
5013
- reason: "launch tokens need this terminal signed in to an Armada with accounts: armada login",
5014
- warn: false
5015
- };
5016
- const url = credentials.armadaApi.url;
5017
- try {
5018
- const t = await armadaApi({ url, ...io.fetch ? { fetch: io.fetch } : {} }).launchToken(signIn, {
5019
- project: config.project.slug,
5020
- ticket
5021
- });
5022
- const builtIn = armadaAddress(url) === armadaAddress(DEFAULT_ARMADA_API_URL);
5023
- return { token: t.token, expiresAt: t.expiresAt, apiUrl: builtIn ? null : armadaAddress(url) };
5024
- } catch (err) {
5025
- if (!(err instanceof ArmadaApiError))
5026
- throw err;
5027
- return { reason: err.message, warn: true };
5028
- }
5029
- };
5030
- }
5031
- async function brief2(io, config, credentials, a, version) {
5032
- const [ticket, ...extra] = a.rest;
5033
- if (!ticket)
5034
- throw new UsageError('brief needs a ticket: armada brief <ticket> [--profile <name> [--reason "<why>"]]');
5035
- if (extra.length)
5036
- throw new UsageError(`unexpected argument ${extra[0]}`);
5037
- const promptOnly = a.options.prompt === "true";
5038
- if (a.json && promptOnly)
5039
- throw new UsageError("pass --json or --prompt, not both");
5040
- const profile = a.options.profile?.trim() || null;
5041
- const reason = a.options.reason?.trim() || null;
5042
- if (reason && !profile)
5043
- throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
5044
- try {
5045
- checkRequestedProfile(config, profile);
5046
- } catch (err) {
5047
- if (err instanceof ProfileError)
5048
- throw new UsageError(err.message);
5049
- throw err;
5050
- }
5051
- if (!credentials.linearApiKey)
5052
- throw missingKey(LINEAR_KEY);
5053
- let b;
5054
- try {
5055
- b = await loadBrief(config, {
5056
- linearApiKey: credentials.linearApiKey,
5057
- ticket: ticket.toUpperCase(),
5058
- profile,
5059
- reason,
5060
- version,
5061
- env: io.env,
5062
- stored: STORED_KEYS.filter((k) => credentials.sources[k.name]?.kind === "store").map((k) => k.variable),
5063
- launch: launcher(io, config, credentials),
5064
- ...io.fetch ? { fetch: io.fetch } : {},
5065
- ...io.now ? { now: io.now } : {}
5066
- });
5067
- } catch (err) {
5068
- if (err instanceof BriefError)
5069
- throw new UsageError(err.message);
5070
- throw err;
5071
- }
5072
- if (a.json)
5073
- io.stdout(`${JSON.stringify(b, null, 2)}
5074
- `);
5075
- else if (promptOnly) {
5076
- io.stdout(b.prompt);
5077
- for (const w of b.warnings)
5078
- io.stderr(`armada: warning: ${w}
5079
- `);
5080
- } else
5081
- io.stdout(renderBrief(b));
5082
- return 0;
5083
- }
5273
+ // src/watch.ts
5274
+ import { dirname as dirname2 } from "node:path";
5084
5275
 
5085
5276
  // src/login.ts
5086
5277
  var hostOf = (url) => {
@@ -5275,42 +5466,575 @@ async function logout(io) {
5275
5466
  return 0;
5276
5467
  }
5277
5468
 
5278
- // src/repo.ts
5279
- import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, readlink, rm as rm2, symlink, writeFile } from "node:fs/promises";
5280
- import { dirname, join as join2, relative, sep } from "node:path";
5281
- var absent = (err) => {
5282
- const code = err.code;
5283
- return code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR";
5284
- };
5285
- async function collect(base, dir, out) {
5286
- for (const entry of await readdir(dir, { withFileTypes: true })) {
5287
- const full = join2(dir, entry.name);
5288
- if (entry.isDirectory()) {
5289
- if (entry.name !== ".git" && entry.name !== "node_modules")
5290
- await collect(base, full, out);
5291
- } else if (entry.isFile())
5292
- out.push({ path: relative(base, full).split(sep).join("/"), content: await readFile2(full) });
5469
+ // src/worker.ts
5470
+ function liveFleet(io, config, credentials) {
5471
+ const signIn = credentials.armadaSignIn;
5472
+ if (!signIn)
5473
+ return {
5474
+ fleet: null,
5475
+ warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
5476
+ };
5477
+ try {
5478
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
5479
+ return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
5480
+ } catch (err) {
5481
+ return {
5482
+ fleet: null,
5483
+ warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
5484
+ };
5293
5485
  }
5294
5486
  }
5295
- function fsRepoView(root) {
5296
- return {
5297
- readFile: (path) => readFile2(join2(root, path), "utf8").catch((err) => {
5298
- if (absent(err))
5299
- return null;
5300
- throw err;
5301
- }),
5302
- readLink: (path) => readlink(join2(root, path)).catch((err) => {
5303
- if (absent(err) || err.code === "EINVAL")
5304
- return null;
5305
- throw err;
5306
- }),
5307
- readFolder: async (path) => {
5308
- const out = [];
5309
- try {
5310
- await collect(join2(root, path), join2(root, path), out);
5311
- } catch (err) {
5312
- if (absent(err))
5313
- return null;
5487
+ function statusEvents(io, config, credentials) {
5488
+ const { fleet } = liveFleet(io, config, credentials);
5489
+ return fleet ? () => fleet.lastEventTimes() : undefined;
5490
+ }
5491
+ function currentTicket(io, config, explicit, workers = []) {
5492
+ const fromEnv = io.env.ARMADA_TICKET?.trim();
5493
+ const id = explicit?.trim() || fromEnv || (() => {
5494
+ const branch = io.gitBranch?.();
5495
+ return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
5496
+ })() || (workers.length === 1 ? workers[0] : null);
5497
+ if (!id)
5498
+ throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
5499
+ return id.toUpperCase();
5500
+ }
5501
+ function context(io, config, credentials) {
5502
+ if (!credentials.linearApiKey)
5503
+ throw missingKey(LINEAR_KEY);
5504
+ const linearOpts = {
5505
+ apiKey: credentials.linearApiKey,
5506
+ labels: config.tracker.labels,
5507
+ ...io.fetch ? { fetch: io.fetch } : {}
5508
+ };
5509
+ const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
5510
+ const live = liveFleet(io, config, credentials);
5511
+ const token = credentials.githubToken;
5512
+ return {
5513
+ config,
5514
+ linear,
5515
+ fleet: async () => live,
5516
+ readPull: token ? (number) => fetchPullRequest({
5517
+ token,
5518
+ repository: config.github.repository,
5519
+ number,
5520
+ ...io.fetch ? { fetch: io.fetch } : {}
5521
+ }) : null,
5522
+ now: io.now ?? (() => new Date)
5523
+ };
5524
+ }
5525
+ function print(io, outcome, json) {
5526
+ if (json) {
5527
+ io.stdout(`${JSON.stringify(outcome, null, 2)}
5528
+ `);
5529
+ return;
5530
+ }
5531
+ const out = [...outcome.lines];
5532
+ const s = outcome.state;
5533
+ if (s)
5534
+ out.push(`Now: ${s.status} · phase ${s.phase ?? "none"} · runtime ${s.runtime ?? "none"} · profile ${s.profile ?? "none"}`);
5535
+ out.push(outcome.url);
5536
+ if (outcome.inbox) {
5537
+ if (!outcome.inbox.length)
5538
+ out.push("Inbox: nothing waiting for you.");
5539
+ else {
5540
+ out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
5541
+ for (const item of outcome.inbox)
5542
+ out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
5543
+ `).map((l) => ` ${l}`));
5544
+ }
5545
+ }
5546
+ io.stdout(`${out.join(`
5547
+ `)}
5548
+ `);
5549
+ for (const w of outcome.warnings)
5550
+ io.stderr(`armada: warning: ${w}
5551
+ `);
5552
+ }
5553
+ async function readMessage(io, options) {
5554
+ if (options.message !== undefined && options["message-file"] !== undefined)
5555
+ throw new UsageError("pass --message or --message-file, not both");
5556
+ const file = options["message-file"];
5557
+ if (file === undefined)
5558
+ return options.message ?? null;
5559
+ const text = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
5560
+ if (text === null)
5561
+ throw new UsageError(`cannot read the message from ${file}`);
5562
+ if (!text.trim())
5563
+ throw new UsageError(`${file === "-" ? "standard input" : `message file ${file}`} is empty or whitespace-only`, 'pass --message "<text>" or pipe a non-empty message into --message-file -');
5564
+ return text;
5565
+ }
5566
+ async function withContext(io, config, credentials, json, act) {
5567
+ print(io, await act(context(io, config, credentials)), json);
5568
+ return 0;
5569
+ }
5570
+ async function claim(io, config, credentials, a) {
5571
+ const [ticket, ...extra] = a.rest;
5572
+ if (!ticket)
5573
+ throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
5574
+ if (extra.length)
5575
+ throw new UsageError(`unexpected argument ${extra[0]}`);
5576
+ const runtime = a.options.runtime?.trim();
5577
+ const handle = a.options.handle?.trim();
5578
+ if (!runtime)
5579
+ throw new UsageError("--runtime is required, e.g. --runtime conductor");
5580
+ const profile = a.options.profile?.trim() || null;
5581
+ const reason = a.options.reason?.trim() || null;
5582
+ if (reason && !profile)
5583
+ throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
5584
+ try {
5585
+ checkRequestedProfile(config, profile);
5586
+ } catch (err) {
5587
+ if (err instanceof ProfileError)
5588
+ throw new UsageError(err.message);
5589
+ throw err;
5590
+ }
5591
+ if (!handle)
5592
+ throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
5593
+ return withContext(io, config, credentials, a.json, (ctx) => claimTicket(ctx, {
5594
+ ticket: ticket.toUpperCase(),
5595
+ runtime,
5596
+ handle,
5597
+ ...a.options.branch ? { branch: a.options.branch } : {},
5598
+ profile,
5599
+ reason
5600
+ }));
5601
+ }
5602
+ async function report(io, config, credentials, a) {
5603
+ const [phase, ...extra] = a.rest;
5604
+ if (!phase || !isLabelPhase(phase))
5605
+ throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
5606
+ if (extra.length)
5607
+ throw new UsageError(`unexpected argument ${extra[0]}`);
5608
+ const message = await readMessage(io, a.options);
5609
+ if (!message?.trim() && phase !== "ready-to-merge")
5610
+ throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
5611
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5612
+ return withContext(io, config, credentials, a.json, (ctx) => reportPhase(ctx, {
5613
+ ticket,
5614
+ phase,
5615
+ message,
5616
+ pr: a.options.pr ?? null,
5617
+ sha: a.options.sha ?? null
5618
+ }));
5619
+ }
5620
+ async function release(io, config, credentials, a) {
5621
+ if (a.rest.length)
5622
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
5623
+ const reason = a.options.reason?.trim();
5624
+ if (!reason)
5625
+ throw new UsageError("--reason is required: why the ticket is given back");
5626
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5627
+ const code = await withContext(io, config, credentials, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
5628
+ await endWorkerSessions(io, config, credentials, ticket, "released", a.json);
5629
+ return code;
5630
+ }
5631
+ async function endWorkerSessions(io, config, credentials, ticket, reason, quiet) {
5632
+ const signIn = credentials.armadaSignIn;
5633
+ if (!signIn)
5634
+ return;
5635
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
5636
+ try {
5637
+ if (signIn.kind === "worker") {
5638
+ const paths = machinePaths(io.env);
5639
+ if (paths)
5640
+ await updateCredentialStore(paths, { [workerSessionVariable(signIn.ticket)]: null });
5641
+ await api.signOut(signIn);
5642
+ if (!quiet)
5643
+ io.stdout(`Signed out of Armada: the worker session of ${signIn.ticket} has ended.
5644
+ `);
5645
+ return;
5646
+ }
5647
+ const ended = await api.endWorkers(signIn, { project: config.project.slug, ticket, reason });
5648
+ if (ended && !quiet)
5649
+ io.stdout(`Ended ${ended === 1 ? "the worker session" : `${ended} worker sessions`} of ${ticket} on Armada.
5650
+ `);
5651
+ } catch (err) {
5652
+ io.stderr(`armada: warning: the worker session of ${ticket} was not ended on Armada (${err instanceof Error ? err.message : String(err)}); it ends on its own after 72 hours without a command, and the Workers page revokes it
5653
+ `);
5654
+ }
5655
+ }
5656
+
5657
+ // src/inbox.ts
5658
+ var DEFAULT_WAIT_SECONDS = 300;
5659
+ async function ask(io, config, credentials, a) {
5660
+ const [positional, ...extra] = a.rest;
5661
+ if (extra.length)
5662
+ throw new UsageError(`unexpected argument ${extra[0]}; quote the question`);
5663
+ const fromOption = await readMessage(io, a.options);
5664
+ if (positional !== undefined && fromOption !== null)
5665
+ throw new UsageError("give the question once: as an argument, --message or --message-file");
5666
+ const question = positional ?? fromOption;
5667
+ if (!question?.trim())
5668
+ throw new UsageError('ask needs a question: armada ask "<question, the options, your recommendation>"');
5669
+ const options = (a.options.options ?? "").split("|").map((o) => o.trim()).filter(Boolean);
5670
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5671
+ return withContext(io, config, credentials, a.json, (ctx) => askCoordinator(ctx, { ticket, question, options }));
5672
+ }
5673
+ async function answer(io, config, credentials, a) {
5674
+ const note = a.options.note === "true";
5675
+ const [target, positional, ...extra] = a.rest;
5676
+ const usage = note ? 'armada answer --note <ticket> "<message>"' : 'armada answer <item or ticket> "<answer>"';
5677
+ if (!target)
5678
+ throw new UsageError(`answer needs a target: ${usage}`);
5679
+ if (extra.length)
5680
+ throw new UsageError(`unexpected argument ${extra[0]}; quote the ${note ? "message" : "answer"}`);
5681
+ const fromOption = await readMessage(io, a.options);
5682
+ if (positional !== undefined && fromOption !== null)
5683
+ throw new UsageError("give the text once: as an argument, --message or --message-file");
5684
+ const text = positional ?? fromOption;
5685
+ if (!text?.trim())
5686
+ throw new UsageError(`answer needs the text: ${usage}`);
5687
+ return withContext(io, config, credentials, a.json, (ctx) => answerItem(ctx, { target, text, note }));
5688
+ }
5689
+ function waitSeconds(raw) {
5690
+ if (raw === undefined)
5691
+ return DEFAULT_WAIT_SECONDS;
5692
+ const n = Number(raw);
5693
+ if (!Number.isFinite(n) || n <= 0)
5694
+ throw new UsageError(`--timeout must be a number of seconds, got "${raw}"`);
5695
+ return n;
5696
+ }
5697
+ function renderEntries(project, items) {
5698
+ if (!items.length)
5699
+ return [`Inbox of ${project}: nothing waits for you.`];
5700
+ const out = [`Inbox of ${project} (${items.length}), oldest first:`];
5701
+ for (const e of items) {
5702
+ const head = [
5703
+ e.id === null ? e.kind : `#${e.id} ${e.kind}`,
5704
+ e.ticket,
5705
+ e.author && `from ${e.author}`,
5706
+ e.request?.question && `answers #${e.request.question}`,
5707
+ e.request?.profile && `profile ${e.request.profile}`,
5708
+ e.createdAt
5709
+ ].filter(Boolean).join(" · ");
5710
+ out.push(`${e.new ? "* " : " "}${head}`, ...e.body.split(`
5711
+ `).map((l) => l ? ` ${l}` : ""));
5712
+ }
5713
+ if (items.some((e) => e.kind === "question" || e.kind === "plan"))
5714
+ out.push(`Deliver each answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
5715
+ if (items.some((e) => e.kind === "answer-request" || e.kind === "launch-request"))
5716
+ out.push('Dashboard requests: deliver an answer-request, then armada answer <id> "<answer>"; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>".');
5717
+ return out;
5718
+ }
5719
+ function renderInbox(r, next) {
5720
+ const out = renderEntries(r.project, r.items);
5721
+ if (r.wait?.timedOut)
5722
+ out.push(`No new item within ${r.wait.timeoutSeconds} s.`);
5723
+ else if (r.wait)
5724
+ out.push("New items are marked *.");
5725
+ out.push(next.line);
5726
+ return `${out.join(`
5727
+ `)}
5728
+ `;
5729
+ }
5730
+ async function inbox2(io, config, credentials, a) {
5731
+ if (a.rest.length)
5732
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
5733
+ const wait = a.options.wait === "true";
5734
+ if (!wait && a.options.timeout !== undefined)
5735
+ throw new UsageError("--timeout applies to --wait");
5736
+ const timeoutMs = waitSeconds(a.options.timeout) * 1000;
5737
+ requireSignIn(credentials);
5738
+ const { fleet, warning } = liveFleet(io, config, credentials);
5739
+ if (!fleet)
5740
+ throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
5741
+ const report = await checkInbox(fleet, {
5742
+ project: config.project.slug,
5743
+ coordinator: coordinatorHandle(io),
5744
+ silentAfterMinutes: config.policy.silentAfterMinutes,
5745
+ now: io.now ?? (() => new Date),
5746
+ ...wait ? { wait: { timeoutMs, sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))) } } : {}
5747
+ });
5748
+ await remember(io, report.project, shown(io, report.items, report.inFlight));
5749
+ const next = await rearmFor(io, report.project, {
5750
+ inFlight: report.inFlight,
5751
+ open: report.items.length,
5752
+ act: report.items.length > 0
5753
+ });
5754
+ io.stdout(a.json ? `${JSON.stringify({ ...report, watch: next }, null, 2)}
5755
+ ` : renderInbox(report, next));
5756
+ for (const w of report.warnings)
5757
+ io.stderr(`armada: warning: ${w}
5758
+ `);
5759
+ return 0;
5760
+ }
5761
+
5762
+ // src/watch.ts
5763
+ function coordinatorHandle(io) {
5764
+ const workspace = io.env.CONDUCTOR_WORKSPACE_ID?.trim();
5765
+ const session = io.env.CONDUCTOR_SESSION_ID?.trim();
5766
+ return io.env.ARMADA_COORDINATOR_HANDLE?.trim() || (workspace && session ? `${workspace}/${session}` : null);
5767
+ }
5768
+ var alive = (io) => io.processAlive ?? processAlive;
5769
+ async function remember(io, project, patch) {
5770
+ const paths = machinePaths(io.env);
5771
+ if (!paths)
5772
+ return;
5773
+ try {
5774
+ await updateWatchState(paths, project, patch);
5775
+ } catch (err) {
5776
+ io.stderr(`armada: warning: could not keep the watch state (${err instanceof Error ? err.message : String(err)})
5777
+ `);
5778
+ }
5779
+ }
5780
+ async function watchOf(io, project) {
5781
+ const paths = machinePaths(io.env);
5782
+ if (!paths)
5783
+ return { state: null, running: null };
5784
+ const [state, running] = await Promise.all([
5785
+ readWatchState(paths, project),
5786
+ runningWatch(paths, project, alive(io)).catch(() => null)
5787
+ ]);
5788
+ return { state, running };
5789
+ }
5790
+ async function rearmFor(io, project, o) {
5791
+ const { running } = await watchOf(io, project);
5792
+ return rearm({ ...o, running });
5793
+ }
5794
+ var now = (io) => (io.now ?? (() => new Date))();
5795
+ var shown = (io, items, inFlight) => ({
5796
+ seen: items.map(entryKey),
5797
+ ...inFlight ? { inFlight, readAt: now(io).toISOString() } : {},
5798
+ stopped: null
5799
+ });
5800
+ async function watch2(io, config, credentials, a, configPath) {
5801
+ if (a.rest.length)
5802
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
5803
+ const project = config.project.slug;
5804
+ try {
5805
+ return await watchUntil(io, config, credentials, a.json, configPath);
5806
+ } catch (err) {
5807
+ await remember(io, project, { stopped: err instanceof Error ? err.message : String(err) });
5808
+ throw err;
5809
+ }
5810
+ }
5811
+ async function watchUntil(io, config, credentials, json, configPath) {
5812
+ requireSignIn(credentials);
5813
+ const { fleet, warning } = liveFleet(io, config, credentials);
5814
+ if (!fleet)
5815
+ throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
5816
+ const project = config.project.slug;
5817
+ const paths = machinePaths(io.env);
5818
+ const pid = io.pid ?? process.pid;
5819
+ if (paths) {
5820
+ const lock = await takeWatchLock(paths, project, pid, alive(io));
5821
+ if (!lock.taken) {
5822
+ const line = `armada watch is already running for ${project} (pid ${lock.pid}): its output arrives when it ends.`;
5823
+ io.stdout(json ? `${JSON.stringify({ project, running: lock.pid, line }, null, 2)}
5824
+ ` : `${line}
5825
+ `);
5826
+ return 0;
5827
+ }
5828
+ }
5829
+ try {
5830
+ const before = paths ? await readWatchState(paths, project) : null;
5831
+ await remember(io, project, { root: dirname2(configPath), stopped: null });
5832
+ const report = await watchInbox(fleet, {
5833
+ project,
5834
+ coordinator: coordinatorHandle(io),
5835
+ silentAfterMinutes: config.policy.silentAfterMinutes,
5836
+ seen: before?.seen ?? [],
5837
+ now: io.now ?? (() => new Date),
5838
+ sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))),
5839
+ onRead: async ({ inFlight }) => {
5840
+ if (inFlight)
5841
+ await remember(io, project, { inFlight, readAt: now(io).toISOString() });
5842
+ },
5843
+ onRetry: (message) => io.stderr(`armada: warning: ${message}
5844
+ `)
5845
+ });
5846
+ await remember(io, project, shown(io, report.items, report.inFlight));
5847
+ const next = rearm({ inFlight: report.inFlight, open: report.items.length, running: null, act: true });
5848
+ if (json)
5849
+ io.stdout(`${JSON.stringify({ ...report, watch: next }, null, 2)}
5850
+ `);
5851
+ else {
5852
+ const out = report.outcome === "nothing" ? [`Nothing to watch on ${project}: no worker in flight and nothing open.`] : [...renderEntries(project, report.items), "New items are marked *.", next.line];
5853
+ io.stdout(`${out.join(`
5854
+ `)}
5855
+ `);
5856
+ }
5857
+ for (const w of report.warnings)
5858
+ io.stderr(`armada: warning: ${w}
5859
+ `);
5860
+ return 0;
5861
+ } finally {
5862
+ if (paths)
5863
+ await releaseWatchLock(paths, project, pid).catch(() => {});
5864
+ }
5865
+ }
5866
+ async function hookStop(io, rest, findConfig) {
5867
+ if (rest[0] !== "stop" || rest.length > 1)
5868
+ throw new UsageError(rest[0] ? `unknown hook "${rest.join(" ")}"` : "hook needs a name: armada hook stop");
5869
+ try {
5870
+ let input = {};
5871
+ try {
5872
+ input = JSON.parse(await io.readStdin?.() || "{}");
5873
+ } catch {}
5874
+ const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : io.cwd;
5875
+ const { path, text } = await findConfig({ ...io, cwd });
5876
+ const project = parseConfig(text, path).project.slug;
5877
+ const { state, running } = await watchOf(io, project);
5878
+ const d = stopHookDecision({ project, root: dirname2(path), state, watching: running, env: io.env });
5879
+ if (d.block)
5880
+ io.stdout(`${JSON.stringify({ decision: "block", reason: d.reason })}
5881
+ `);
5882
+ } catch {}
5883
+ return 0;
5884
+ }
5885
+
5886
+ // src/brief.ts
5887
+ function renderBrief(b) {
5888
+ const p = b.profile;
5889
+ const width = Math.max(...b.environment.map((v) => v.name.length + (v.value ? v.value.length + 1 : 0)));
5890
+ const out = [
5891
+ `Brief for ${b.ticket.id} — ${b.ticket.title} (${b.ticket.status})`,
5892
+ b.ticket.url,
5893
+ "",
5894
+ `Runtime: conductor (follow the armada-runtime-conductor skill to launch)`,
5895
+ `Profile: ${p ? `${p.name}: agent ${p.agent}, model ${p.model}, effort ${p.effort}${p.fastMode ? ", fast mode" : ""}` : "none declared in armada.toml"}`,
5896
+ ...b.routing ? [`Chosen by: ${b.routing.why}`] : [],
5897
+ `Repository: ${b.repository.url}`,
5898
+ `Branch: ${b.ticket.branch ?? "none suggested by Linear"} (the worker renames its workspace branch to it)`,
5899
+ `Launch: ${b.launch ? `one-time token in the prompt, valid until ${b.launch.expiresAt.slice(0, 16).replace("T", " ")} UTC: the worker needs no key` : `no launch token${b.noLaunch ? ` (${b.noLaunch})` : ""}: pass the keys below in the worker's environment`}`,
5900
+ "",
5901
+ "Environment to pass (values are never printed):",
5902
+ ...b.environment.map((v) => {
5903
+ const label = v.value ? `${v.name}=${v.value}` : v.name;
5904
+ const state = v.value ? "value above" : v.inShell ? "set in this shell" : v.inStore ? "in credentials file" : "NOT set in this shell";
5905
+ return ` ${label.padEnd(width)} ${v.required ? "required" : "optional"} ${state.padEnd(21)} ${v.purpose}`;
5906
+ })
5907
+ ];
5908
+ if (b.warnings.length)
5909
+ out.push("", "Warnings:", ...b.warnings.map((w) => ` - ${w}`));
5910
+ out.push("", `----- prompt (\`armada brief ${b.ticket.id} --prompt\` prints only this) -----`, "", b.prompt);
5911
+ return out.join(`
5912
+ `);
5913
+ }
5914
+ function launcher(io, config, credentials) {
5915
+ return async (ticket) => {
5916
+ const signIn = credentials.armadaSignIn;
5917
+ if (!signIn)
5918
+ return {
5919
+ reason: "launch tokens need this terminal signed in to an Armada with accounts: armada login",
5920
+ warn: false
5921
+ };
5922
+ const url = credentials.armadaApi.url;
5923
+ try {
5924
+ const t = await armadaApi({ url, ...io.fetch ? { fetch: io.fetch } : {} }).launchToken(signIn, {
5925
+ project: config.project.slug,
5926
+ ticket
5927
+ });
5928
+ const builtIn = armadaAddress(url) === armadaAddress(DEFAULT_ARMADA_API_URL);
5929
+ return { token: t.token, expiresAt: t.expiresAt, apiUrl: builtIn ? null : armadaAddress(url) };
5930
+ } catch (err) {
5931
+ if (!(err instanceof ArmadaApiError))
5932
+ throw err;
5933
+ return { reason: err.message, warn: true };
5934
+ }
5935
+ };
5936
+ }
5937
+ async function brief2(io, config, credentials, a, version) {
5938
+ const [ticket, ...extra] = a.rest;
5939
+ if (!ticket)
5940
+ throw new UsageError('brief needs a ticket: armada brief <ticket> [--profile <name> [--reason "<why>"]]');
5941
+ if (extra.length)
5942
+ throw new UsageError(`unexpected argument ${extra[0]}`);
5943
+ const promptOnly = a.options.prompt === "true";
5944
+ if (a.json && promptOnly)
5945
+ throw new UsageError("pass --json or --prompt, not both");
5946
+ const profile = a.options.profile?.trim() || null;
5947
+ const reason = a.options.reason?.trim() || null;
5948
+ if (reason && !profile)
5949
+ throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
5950
+ try {
5951
+ checkRequestedProfile(config, profile);
5952
+ } catch (err) {
5953
+ if (err instanceof ProfileError)
5954
+ throw new UsageError(err.message);
5955
+ throw err;
5956
+ }
5957
+ if (!credentials.linearApiKey)
5958
+ throw missingKey(LINEAR_KEY);
5959
+ let b;
5960
+ try {
5961
+ b = await loadBrief(config, {
5962
+ linearApiKey: credentials.linearApiKey,
5963
+ ticket: ticket.toUpperCase(),
5964
+ profile,
5965
+ reason,
5966
+ version,
5967
+ env: io.env,
5968
+ stored: STORED_KEYS.filter((k) => credentials.sources[k.name]?.kind === "store").map((k) => k.variable),
5969
+ launch: launcher(io, config, credentials),
5970
+ ...io.fetch ? { fetch: io.fetch } : {},
5971
+ ...io.now ? { now: io.now } : {}
5972
+ });
5973
+ } catch (err) {
5974
+ if (err instanceof BriefError)
5975
+ throw new UsageError(err.message);
5976
+ throw err;
5977
+ }
5978
+ const project = config.project.slug;
5979
+ const known = (await watchOf(io, project)).state?.inFlight ?? [];
5980
+ const inFlight = [...new Set([...known, b.ticket.id])].sort((x, y) => x.localeCompare(y, "en", { numeric: true }));
5981
+ await remember(io, project, { inFlight, readAt: (io.now ?? (() => new Date))().toISOString() });
5982
+ if (promptOnly) {
5983
+ io.stdout(b.prompt);
5984
+ for (const w of b.warnings)
5985
+ io.stderr(`armada: warning: ${w}
5986
+ `);
5987
+ return 0;
5988
+ }
5989
+ const next = await rearmFor(io, project, { inFlight, open: null });
5990
+ if (a.json)
5991
+ io.stdout(`${JSON.stringify({ ...b, watch: next }, null, 2)}
5992
+ `);
5993
+ else
5994
+ io.stdout(`${renderBrief(b)}
5995
+
5996
+ ----- once launched -----
5997
+ ${next.line}
5998
+ `);
5999
+ return 0;
6000
+ }
6001
+
6002
+ // src/repo.ts
6003
+ import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, readlink, rm as rm2, symlink, writeFile as writeFile2 } from "node:fs/promises";
6004
+ import { dirname as dirname3, join as join2, relative, sep } from "node:path";
6005
+ var absent = (err) => {
6006
+ const code = err.code;
6007
+ return code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR";
6008
+ };
6009
+ async function collect(base, dir, out) {
6010
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
6011
+ const full = join2(dir, entry.name);
6012
+ if (entry.isDirectory()) {
6013
+ if (entry.name !== ".git" && entry.name !== "node_modules")
6014
+ await collect(base, full, out);
6015
+ } else if (entry.isFile())
6016
+ out.push({ path: relative(base, full).split(sep).join("/"), content: await readFile2(full) });
6017
+ }
6018
+ }
6019
+ function fsRepoView(root) {
6020
+ return {
6021
+ readFile: (path) => readFile2(join2(root, path), "utf8").catch((err) => {
6022
+ if (absent(err))
6023
+ return null;
6024
+ throw err;
6025
+ }),
6026
+ readLink: (path) => readlink(join2(root, path)).catch((err) => {
6027
+ if (absent(err) || err.code === "EINVAL")
6028
+ return null;
6029
+ throw err;
6030
+ }),
6031
+ readFolder: async (path) => {
6032
+ const out = [];
6033
+ try {
6034
+ await collect(join2(root, path), join2(root, path), out);
6035
+ } catch (err) {
6036
+ if (absent(err))
6037
+ return null;
5314
6038
  throw err;
5315
6039
  }
5316
6040
  return out;
@@ -5332,12 +6056,12 @@ async function applyPlan(root, plan) {
5332
6056
  await rm2(join2(root, path), { force: true });
5333
6057
  for (const w of plan.writes) {
5334
6058
  const full = join2(root, w.path);
5335
- await mkdir2(dirname(full), { recursive: true });
5336
- await writeFile(full, w.content);
6059
+ await mkdir2(dirname3(full), { recursive: true });
6060
+ await writeFile2(full, w.content);
5337
6061
  }
5338
6062
  for (const l of plan.links) {
5339
6063
  const full = join2(root, l.path);
5340
- await mkdir2(dirname(full), { recursive: true });
6064
+ await mkdir2(dirname3(full), { recursive: true });
5341
6065
  if (await lstat(full).catch(() => null))
5342
6066
  await rm2(full, { recursive: true, force: true });
5343
6067
  await symlink(l.target, full);
@@ -5418,390 +6142,111 @@ function keyFileChecks(machine, credentials) {
5418
6142
  return [
5419
6143
  ...checks,
5420
6144
  {
5421
- id: "local-keys",
5422
- level: "warning",
5423
- message: `${store.path} still holds ${unneeded.join(", ")}, which Armada now gives this terminal: ${unneeded.length === 1 ? "it is" : "they are"} no longer needed`,
5424
- fix: `\`armada auth logout\` removes ${unneeded.length === 1 ? "it" : "them"} from this machine; the sign-in to Armada stays`
5425
- }
5426
- ];
5427
- }
5428
- async function labelChecks(io, root, credentials) {
5429
- const text = await fsRepoView(root).readFile(CONFIG_FILE);
5430
- if (text === null)
5431
- return [];
5432
- let config;
5433
- try {
5434
- config = parseConfig(text, CONFIG_FILE);
5435
- } catch (err) {
5436
- if (err instanceof ConfigError)
5437
- return [];
5438
- throw err;
5439
- }
5440
- const { linearApiKey } = credentials;
5441
- if (!linearApiKey)
5442
- return [
5443
- {
5444
- id: "labels",
5445
- level: "warning",
5446
- message: `Linear labels not checked: no Linear key (${LINEAR_KEY.variable})`,
5447
- fix: `\`armada login\` to an Armada that keeps your organization's keys, or set ${LINEAR_KEY.variable}, then run doctor again`
5448
- }
5449
- ];
5450
- try {
5451
- const state = await readLabels(config, { apiKey: linearApiKey, ...io.fetch ? { fetch: io.fetch } : {} });
5452
- return checkLabels(state);
5453
- } catch (err) {
5454
- return [
5455
- {
5456
- id: "labels",
5457
- level: "warning",
5458
- message: `Linear labels not checked: ${err instanceof Error ? err.message : String(err)}`,
5459
- fix: "run doctor again once Linear answers"
5460
- }
5461
- ];
5462
- }
5463
- }
5464
- async function buildDoctor(io, armadaVersion) {
5465
- const root = (io.exec ? await gitRoot(io.exec, io.cwd) : null) ?? io.cwd;
5466
- const { machine, credentials } = await loadCredentials(io);
5467
- const checks = [
5468
- ...await checkRepository(fsRepoView(root), armadaVersion),
5469
- ...await signInChecks(io, credentials),
5470
- ...keyFileChecks(machine, credentials),
5471
- ...await labelChecks(io, root, credentials)
5472
- ];
5473
- return {
5474
- schemaVersion: 1,
5475
- root,
5476
- armadaVersion,
5477
- checks,
5478
- errors: checks.filter((c) => c.level === "error").length,
5479
- warnings: checks.filter((c) => c.level === "warning").length
5480
- };
5481
- }
5482
- var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
5483
- function renderDoctor(r) {
5484
- const lines = [`Armada ${r.armadaVersion} doctor · ${r.root}`, ""];
5485
- for (const c of r.checks) {
5486
- const [first, ...more] = c.message.split(`
5487
- `);
5488
- lines.push(` ${c.level.padEnd(8)} ${first}`);
5489
- for (const m of more)
5490
- lines.push(` ${m}`);
5491
- if (c.fix)
5492
- lines.push(` fix: ${c.fix}`);
5493
- }
5494
- lines.push("");
5495
- if (!r.errors && !r.warnings)
5496
- lines.push("Everything Armada needs is in place.");
5497
- else
5498
- lines.push(`${plural(r.errors, "error")}, ${plural(r.warnings, "warning")}.${r.errors ? " Workers cannot be launched until the errors are fixed." : ""}`);
5499
- const errors = r.checks.filter((c) => c.level === "error");
5500
- if (errors.length)
5501
- 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}`);
5502
- return `${lines.join(`
5503
- `)}
5504
- `;
5505
- }
5506
- async function doctor(io, json, armadaVersion) {
5507
- const report = await buildDoctor(io, armadaVersion);
5508
- io.stdout(json ? `${JSON.stringify(report, null, 2)}
5509
- ` : renderDoctor(report));
5510
- return report.errors ? 1 : 0;
5511
- }
5512
-
5513
- // src/worker.ts
5514
- function liveFleet(io, config, credentials) {
5515
- const signIn = credentials.armadaSignIn;
5516
- if (!signIn)
5517
- return {
5518
- fleet: null,
5519
- warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
5520
- };
5521
- try {
5522
- const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
5523
- return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
5524
- } catch (err) {
5525
- return {
5526
- fleet: null,
5527
- warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
5528
- };
5529
- }
5530
- }
5531
- function statusEvents(io, config, credentials) {
5532
- const { fleet } = liveFleet(io, config, credentials);
5533
- return fleet ? () => fleet.lastEventTimes() : undefined;
5534
- }
5535
- function currentTicket(io, config, explicit, workers = []) {
5536
- const fromEnv = io.env.ARMADA_TICKET?.trim();
5537
- const id = explicit?.trim() || fromEnv || (() => {
5538
- const branch = io.gitBranch?.();
5539
- return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
5540
- })() || (workers.length === 1 ? workers[0] : null);
5541
- if (!id)
5542
- throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
5543
- return id.toUpperCase();
5544
- }
5545
- function context(io, config, credentials) {
5546
- if (!credentials.linearApiKey)
5547
- throw missingKey(LINEAR_KEY);
5548
- const linearOpts = {
5549
- apiKey: credentials.linearApiKey,
5550
- labels: config.tracker.labels,
5551
- ...io.fetch ? { fetch: io.fetch } : {}
5552
- };
5553
- const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
5554
- const live = liveFleet(io, config, credentials);
5555
- const token = credentials.githubToken;
5556
- return {
5557
- config,
5558
- linear,
5559
- fleet: async () => live,
5560
- readPull: token ? (number) => fetchPullRequest({
5561
- token,
5562
- repository: config.github.repository,
5563
- number,
5564
- ...io.fetch ? { fetch: io.fetch } : {}
5565
- }) : null,
5566
- now: io.now ?? (() => new Date)
5567
- };
5568
- }
5569
- function print(io, outcome, json) {
5570
- if (json) {
5571
- io.stdout(`${JSON.stringify(outcome, null, 2)}
5572
- `);
5573
- return;
5574
- }
5575
- const out = [...outcome.lines];
5576
- const s = outcome.state;
5577
- if (s)
5578
- out.push(`Now: ${s.status} · phase ${s.phase ?? "none"} · runtime ${s.runtime ?? "none"} · profile ${s.profile ?? "none"}`);
5579
- out.push(outcome.url);
5580
- if (outcome.inbox) {
5581
- if (!outcome.inbox.length)
5582
- out.push("Inbox: nothing waiting for you.");
5583
- else {
5584
- out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
5585
- for (const item of outcome.inbox)
5586
- out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
5587
- `).map((l) => ` ${l}`));
5588
- }
5589
- }
5590
- io.stdout(`${out.join(`
5591
- `)}
5592
- `);
5593
- for (const w of outcome.warnings)
5594
- io.stderr(`armada: warning: ${w}
5595
- `);
6145
+ id: "local-keys",
6146
+ level: "warning",
6147
+ message: `${store.path} still holds ${unneeded.join(", ")}, which Armada now gives this terminal: ${unneeded.length === 1 ? "it is" : "they are"} no longer needed`,
6148
+ fix: `\`armada auth logout\` removes ${unneeded.length === 1 ? "it" : "them"} from this machine; the sign-in to Armada stays`
6149
+ }
6150
+ ];
5596
6151
  }
5597
- async function readMessage(io, options) {
5598
- if (options.message !== undefined && options["message-file"] !== undefined)
5599
- throw new UsageError("pass --message or --message-file, not both");
5600
- const file = options["message-file"];
5601
- if (file === undefined)
5602
- return options.message ?? null;
5603
- const text = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
6152
+ async function labelChecks(io, root, credentials) {
6153
+ const text = await fsRepoView(root).readFile(CONFIG_FILE);
5604
6154
  if (text === null)
5605
- throw new UsageError(`cannot read the message from ${file}`);
5606
- if (!text.trim())
5607
- throw new UsageError(`${file === "-" ? "standard input" : `message file ${file}`} is empty or whitespace-only`, 'pass --message "<text>" or pipe a non-empty message into --message-file -');
5608
- return text;
5609
- }
5610
- async function withContext(io, config, credentials, json, act) {
5611
- print(io, await act(context(io, config, credentials)), json);
5612
- return 0;
5613
- }
5614
- async function claim(io, config, credentials, a) {
5615
- const [ticket, ...extra] = a.rest;
5616
- if (!ticket)
5617
- throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
5618
- if (extra.length)
5619
- throw new UsageError(`unexpected argument ${extra[0]}`);
5620
- const runtime = a.options.runtime?.trim();
5621
- const handle = a.options.handle?.trim();
5622
- if (!runtime)
5623
- throw new UsageError("--runtime is required, e.g. --runtime conductor");
5624
- const profile = a.options.profile?.trim() || null;
5625
- const reason = a.options.reason?.trim() || null;
5626
- if (reason && !profile)
5627
- throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
6155
+ return [];
6156
+ let config;
5628
6157
  try {
5629
- checkRequestedProfile(config, profile);
6158
+ config = parseConfig(text, CONFIG_FILE);
5630
6159
  } catch (err) {
5631
- if (err instanceof ProfileError)
5632
- throw new UsageError(err.message);
6160
+ if (err instanceof ConfigError)
6161
+ return [];
5633
6162
  throw err;
5634
6163
  }
5635
- if (!handle)
5636
- throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
5637
- return withContext(io, config, credentials, a.json, (ctx) => claimTicket(ctx, {
5638
- ticket: ticket.toUpperCase(),
5639
- runtime,
5640
- handle,
5641
- ...a.options.branch ? { branch: a.options.branch } : {},
5642
- profile,
5643
- reason
5644
- }));
5645
- }
5646
- async function report(io, config, credentials, a) {
5647
- const [phase, ...extra] = a.rest;
5648
- if (!phase || !isLabelPhase(phase))
5649
- throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
5650
- if (extra.length)
5651
- throw new UsageError(`unexpected argument ${extra[0]}`);
5652
- const message = await readMessage(io, a.options);
5653
- if (!message?.trim() && phase !== "ready-to-merge")
5654
- throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
5655
- const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5656
- return withContext(io, config, credentials, a.json, (ctx) => reportPhase(ctx, {
5657
- ticket,
5658
- phase,
5659
- message,
5660
- pr: a.options.pr ?? null,
5661
- sha: a.options.sha ?? null
5662
- }));
5663
- }
5664
- async function release(io, config, credentials, a) {
5665
- if (a.rest.length)
5666
- throw new UsageError(`unexpected argument ${a.rest[0]}`);
5667
- const reason = a.options.reason?.trim();
5668
- if (!reason)
5669
- throw new UsageError("--reason is required: why the ticket is given back");
5670
- const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5671
- const code = await withContext(io, config, credentials, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
5672
- await endWorkerSessions(io, config, credentials, ticket, "released", a.json);
5673
- return code;
5674
- }
5675
- async function endWorkerSessions(io, config, credentials, ticket, reason, quiet) {
5676
- const signIn = credentials.armadaSignIn;
5677
- if (!signIn)
5678
- return;
5679
- const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
6164
+ const { linearApiKey } = credentials;
6165
+ if (!linearApiKey)
6166
+ return [
6167
+ {
6168
+ id: "labels",
6169
+ level: "warning",
6170
+ message: `Linear labels not checked: no Linear key (${LINEAR_KEY.variable})`,
6171
+ fix: `\`armada login\` to an Armada that keeps your organization's keys, or set ${LINEAR_KEY.variable}, then run doctor again`
6172
+ }
6173
+ ];
5680
6174
  try {
5681
- if (signIn.kind === "worker") {
5682
- const paths = machinePaths(io.env);
5683
- if (paths)
5684
- await updateCredentialStore(paths, { [workerSessionVariable(signIn.ticket)]: null });
5685
- await api.signOut(signIn);
5686
- if (!quiet)
5687
- io.stdout(`Signed out of Armada: the worker session of ${signIn.ticket} has ended.
5688
- `);
5689
- return;
5690
- }
5691
- const ended = await api.endWorkers(signIn, { project: config.project.slug, ticket, reason });
5692
- if (ended && !quiet)
5693
- io.stdout(`Ended ${ended === 1 ? "the worker session" : `${ended} worker sessions`} of ${ticket} on Armada.
5694
- `);
6175
+ const state = await readLabels(config, { apiKey: linearApiKey, ...io.fetch ? { fetch: io.fetch } : {} });
6176
+ return checkLabels(state);
5695
6177
  } catch (err) {
5696
- io.stderr(`armada: warning: the worker session of ${ticket} was not ended on Armada (${err instanceof Error ? err.message : String(err)}); it ends on its own after 72 hours without a command, and the Workers page revokes it
5697
- `);
6178
+ return [
6179
+ {
6180
+ id: "labels",
6181
+ level: "warning",
6182
+ message: `Linear labels not checked: ${err instanceof Error ? err.message : String(err)}`,
6183
+ fix: "run doctor again once Linear answers"
6184
+ }
6185
+ ];
5698
6186
  }
5699
6187
  }
5700
-
5701
- // src/inbox.ts
5702
- var DEFAULT_WAIT_SECONDS = 300;
5703
- async function ask(io, config, credentials, a) {
5704
- const [positional, ...extra] = a.rest;
5705
- if (extra.length)
5706
- throw new UsageError(`unexpected argument ${extra[0]}; quote the question`);
5707
- const fromOption = await readMessage(io, a.options);
5708
- if (positional !== undefined && fromOption !== null)
5709
- throw new UsageError("give the question once: as an argument, --message or --message-file");
5710
- const question = positional ?? fromOption;
5711
- if (!question?.trim())
5712
- throw new UsageError('ask needs a question: armada ask "<question, the options, your recommendation>"');
5713
- const options = (a.options.options ?? "").split("|").map((o) => o.trim()).filter(Boolean);
5714
- const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5715
- return withContext(io, config, credentials, a.json, (ctx) => askCoordinator(ctx, { ticket, question, options }));
5716
- }
5717
- async function answer(io, config, credentials, a) {
5718
- const note = a.options.note === "true";
5719
- const [target, positional, ...extra] = a.rest;
5720
- const usage = note ? 'armada answer --note <ticket> "<message>"' : 'armada answer <item or ticket> "<answer>"';
5721
- if (!target)
5722
- throw new UsageError(`answer needs a target: ${usage}`);
5723
- if (extra.length)
5724
- throw new UsageError(`unexpected argument ${extra[0]}; quote the ${note ? "message" : "answer"}`);
5725
- const fromOption = await readMessage(io, a.options);
5726
- if (positional !== undefined && fromOption !== null)
5727
- throw new UsageError("give the text once: as an argument, --message or --message-file");
5728
- const text = positional ?? fromOption;
5729
- if (!text?.trim())
5730
- throw new UsageError(`answer needs the text: ${usage}`);
5731
- return withContext(io, config, credentials, a.json, (ctx) => answerItem(ctx, { target, text, note }));
5732
- }
5733
- function waitSeconds(raw) {
5734
- if (raw === undefined)
5735
- return DEFAULT_WAIT_SECONDS;
5736
- const n = Number(raw);
5737
- if (!Number.isFinite(n) || n <= 0)
5738
- throw new UsageError(`--timeout must be a number of seconds, got "${raw}"`);
5739
- return n;
6188
+ async function buildDoctor(io, armadaVersion) {
6189
+ const root = (io.exec ? await gitRoot(io.exec, io.cwd) : null) ?? io.cwd;
6190
+ const { machine, credentials } = await loadCredentials(io);
6191
+ const checks = [
6192
+ ...await checkRepository(fsRepoView(root), armadaVersion),
6193
+ ...await signInChecks(io, credentials),
6194
+ ...keyFileChecks(machine, credentials),
6195
+ ...await labelChecks(io, root, credentials)
6196
+ ];
6197
+ return {
6198
+ schemaVersion: 1,
6199
+ root,
6200
+ armadaVersion,
6201
+ checks,
6202
+ errors: checks.filter((c) => c.level === "error").length,
6203
+ warnings: checks.filter((c) => c.level === "warning").length
6204
+ };
5740
6205
  }
5741
- function renderInbox(r) {
5742
- const out = [];
5743
- if (!r.items.length)
5744
- out.push(`Inbox of ${r.project}: nothing waits for you.`);
5745
- else {
5746
- out.push(`Inbox of ${r.project} (${r.items.length}), oldest first:`);
5747
- for (const e of r.items) {
5748
- const head = [
5749
- e.id === null ? e.kind : `#${e.id} ${e.kind}`,
5750
- e.ticket,
5751
- e.author && `from ${e.author}`,
5752
- e.request?.question && `answers #${e.request.question}`,
5753
- e.request?.profile && `profile ${e.request.profile}`,
5754
- e.createdAt
5755
- ].filter(Boolean).join(" · ");
5756
- out.push(`${e.new ? "* " : " "}${head}`, ...e.body.split(`
5757
- `).map((l) => l ? ` ${l}` : ""));
5758
- }
5759
- if (r.items.some((e) => e.kind === "question" || e.kind === "plan"))
5760
- out.push(`Deliver each answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
5761
- if (r.items.some((e) => e.kind === "answer-request" || e.kind === "launch-request"))
5762
- out.push('Dashboard requests: deliver an answer-request, then armada answer <id> "<answer>"; launch a launch-request (its claim resolves it), or decline it with armada answer <id> "<why>".');
6206
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
6207
+ function renderDoctor(r) {
6208
+ const lines = [`Armada ${r.armadaVersion} doctor · ${r.root}`, ""];
6209
+ for (const c of r.checks) {
6210
+ const [first, ...more] = c.message.split(`
6211
+ `);
6212
+ lines.push(` ${c.level.padEnd(8)} ${first}`);
6213
+ for (const m of more)
6214
+ lines.push(` ${m}`);
6215
+ if (c.fix)
6216
+ lines.push(` fix: ${c.fix}`);
5763
6217
  }
5764
- if (r.wait?.timedOut)
5765
- out.push(`No new item within ${r.wait.timeoutSeconds} s.`);
5766
- else if (r.wait)
5767
- out.push("New items are marked *.");
5768
- return `${out.join(`
6218
+ lines.push("");
6219
+ if (!r.errors && !r.warnings)
6220
+ lines.push("Everything Armada needs is in place.");
6221
+ else
6222
+ lines.push(`${plural(r.errors, "error")}, ${plural(r.warnings, "warning")}.${r.errors ? " Workers cannot be launched until the errors are fixed." : ""}`);
6223
+ const errors = r.checks.filter((c) => c.level === "error");
6224
+ if (errors.length)
6225
+ 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}`);
6226
+ return `${lines.join(`
5769
6227
  `)}
5770
6228
  `;
5771
6229
  }
5772
- async function inbox2(io, config, credentials, a) {
5773
- if (a.rest.length)
5774
- throw new UsageError(`unexpected argument ${a.rest[0]}`);
5775
- const wait = a.options.wait === "true";
5776
- if (!wait && a.options.timeout !== undefined)
5777
- throw new UsageError("--timeout applies to --wait");
5778
- const timeoutMs = waitSeconds(a.options.timeout) * 1000;
5779
- requireSignIn(credentials);
5780
- const { fleet, warning } = liveFleet(io, config, credentials);
5781
- if (!fleet)
5782
- throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
5783
- const workspace = io.env.CONDUCTOR_WORKSPACE_ID?.trim();
5784
- const session = io.env.CONDUCTOR_SESSION_ID?.trim();
5785
- const coordinator = io.env.ARMADA_COORDINATOR_HANDLE?.trim() || (workspace && session ? `${workspace}/${session}` : null);
5786
- const report = await checkInbox(fleet, {
5787
- project: config.project.slug,
5788
- coordinator,
5789
- silentAfterMinutes: config.policy.silentAfterMinutes,
5790
- now: io.now ?? (() => new Date),
5791
- ...wait ? { wait: { timeoutMs, sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))) } } : {}
5792
- });
5793
- io.stdout(a.json ? `${JSON.stringify(report, null, 2)}
5794
- ` : renderInbox(report));
5795
- for (const w of report.warnings)
5796
- io.stderr(`armada: warning: ${w}
5797
- `);
5798
- return 0;
6230
+ async function doctor(io, json, armadaVersion) {
6231
+ const report = await buildDoctor(io, armadaVersion);
6232
+ io.stdout(json ? `${JSON.stringify(report, null, 2)}
6233
+ ` : renderDoctor(report));
6234
+ return report.errors ? 1 : 0;
5799
6235
  }
5800
6236
 
5801
6237
  // src/init.ts
5802
6238
  import { mkdtemp, realpath, rm as rm3 } from "node:fs/promises";
5803
6239
  import { tmpdir } from "node:os";
5804
6240
  import { join as join3 } from "node:path";
6241
+ var STOP_HOOK_QUESTION = "Add the Claude Code stop hook to this repository's .claude/settings.json? A coordinator then cannot end its turn while workers are in flight and no armada watch runs; your user settings are not touched. [Y/n] ";
6242
+ async function wantsStopHook(io, opts) {
6243
+ if (opts.stopHook !== null)
6244
+ return opts.stopHook;
6245
+ if (!io.interactive || !io.prompt)
6246
+ return true;
6247
+ const answer = (await io.prompt(STOP_HOOK_QUESTION, { hidden: false }))?.trim().toLowerCase();
6248
+ return answer === undefined ? false : answer === "" || answer.startsWith("y");
6249
+ }
5805
6250
  var initBranch = (version) => `armada/init-${version}`;
5806
6251
  async function defaultBranch(exec, root) {
5807
6252
  const out = await sh(exec, root, "git", ["ls-remote", "--symref", "origin", "HEAD"]);
@@ -5864,6 +6309,10 @@ function prText(plan, version) {
5864
6309
  ...plan.writes.map((w) => `- write \`${w.path}\``),
5865
6310
  ...plan.links.map((l) => `- link \`${l.path}\` → \`${l.target}\``),
5866
6311
  ...plan.removes.map((p) => `- remove \`${p}\``),
6312
+ ...plan.stopHook ? [
6313
+ "",
6314
+ `The Claude Code stop hook in \`${CLAUDE_SETTINGS}\` keeps a coordinator from ending its turn while workers are in flight and no \`armada watch\` runs. It blocks only in the checkout where \`armada watch\` ran, never a worker's session, and \`ARMADA_STOP_HOOK=off\` turns it off.`
6315
+ ] : [],
5867
6316
  "",
5868
6317
  "Once merged, `armada doctor` passes on the default branch.",
5869
6318
  "",
@@ -5896,7 +6345,13 @@ async function init(io, opts) {
5896
6345
  await sh(exec, root, "git", ["worktree", "add", "--quiet", "--detach", checkout, baseSha]);
5897
6346
  const { config, text, source } = await resolveConfig(exec, root, checkout, opts);
5898
6347
  const view = fsRepoView(checkout);
5899
- const plan = await planSetup(view, { armadaVersion: opts.armadaVersion, configText: text });
6348
+ let plan = await planSetup(view, {
6349
+ armadaVersion: opts.armadaVersion,
6350
+ configText: text,
6351
+ stopHook: opts.stopHook !== false
6352
+ });
6353
+ if (plan.stopHook && !await wantsStopHook(io, opts))
6354
+ plan = await planSetup(view, { armadaVersion: opts.armadaVersion, configText: text, stopHook: false });
5900
6355
  const log = (line) => io.stdout(`${line}
5901
6356
  `);
5902
6357
  log(`Armada ${opts.armadaVersion} · ${config.github.repository} · ${config.tracker.programRoot}`);
@@ -5967,6 +6422,8 @@ async function init(io, opts) {
5967
6422
  log(`Installs: ${plan.installed.join(", ")}`);
5968
6423
  if (plan.updated.length)
5969
6424
  log(`Updates: ${plan.updated.join(", ")}`);
6425
+ if (plan.stopHook)
6426
+ log(`Adds the Claude Code stop hook to ${CLAUDE_SETTINGS}: this repository's settings, not your user settings.`);
5970
6427
  }
5971
6428
  const { fleet, warning } = liveFleet(io, config, credentials);
5972
6429
  if (!fleet)
@@ -5984,7 +6441,7 @@ async function init(io, opts) {
5984
6441
  import { randomUUID } from "node:crypto";
5985
6442
  import { rm as rm4 } from "node:fs/promises";
5986
6443
  import { hostname, tmpdir as tmpdir2 } from "node:os";
5987
- import { dirname as dirname2, join as join4 } from "node:path";
6444
+ import { dirname as dirname4, join as join4 } from "node:path";
5988
6445
  var TRANSIENT = /\bHTTP 5\d\d\b|\b5\d\d (?:Bad Gateway|Service Unavailable|Gateway Time-?out|Internal Server Error)\b|Bad Gateway|Service Unavailable|Gateway Time-?out|ECONNRESET|ETIMEDOUT|connection reset|i\/o timeout|TLS handshake timeout/i;
5989
6446
  var tail = (text, lines = 30) => text.trimEnd().split(`
5990
6447
  `).slice(-lines).join(`
@@ -6131,7 +6588,7 @@ async function merge2(io, config, credentials, a, configPath) {
6131
6588
  if (!exec)
6132
6589
  throw new UsageError("armada merge needs to run git and gh");
6133
6590
  const linearApiKey = credentials.linearApiKey;
6134
- const repoDir = dirname2(configPath);
6591
+ const repoDir = dirname4(configPath);
6135
6592
  const fetchOpt = io.fetch ? { fetch: io.fetch } : {};
6136
6593
  const gh = { token, repository: config.github.repository, ...fetchOpt };
6137
6594
  const linearOpts = { apiKey: linearApiKey, labels: config.tracker.labels, ...fetchOpt };
@@ -6173,8 +6630,16 @@ async function merge2(io, config, credentials, a, configPath) {
6173
6630
  dryRun: !!a.options["dry-run"],
6174
6631
  noLock: !!a.options["no-lock"]
6175
6632
  });
6176
- io.stdout(a.json ? `${JSON.stringify(o, null, 2)}
6177
- ` : render(o));
6633
+ const project = config.project.slug;
6634
+ const coordinator = coordinatorHandle(io);
6635
+ const known = (await watchOf(io, project)).state?.inFlight ?? null;
6636
+ 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;
6637
+ if (o.merged)
6638
+ await remember(io, project, { inFlight, readAt: (io.now ?? (() => new Date))().toISOString() });
6639
+ const next = await rearmFor(io, project, { inFlight, open: null });
6640
+ io.stdout(a.json ? `${JSON.stringify({ ...o, watch: next }, null, 2)}
6641
+ ` : `${render(o)}${next.line}
6642
+ `);
6178
6643
  for (const w of o.warnings)
6179
6644
  io.stderr(`armada: warning: ${w}
6180
6645
  `);
@@ -6337,10 +6802,12 @@ var COMMAND_HELP = {
6337
6802
  doctor: ` doctor What this repository lacks to be run by Armada, with the fix for each,
6338
6803
  and whether this terminal is signed in to Armada
6339
6804
  `,
6340
- init: ` init [--program-root <ISSUE-ID>] [--name <name>] [--slug <slug>]
6805
+ init: ` init [--program-root <ISSUE-ID>] [--name <name>] [--slug <slug>] [--no-stop-hook]
6341
6806
  Open one pull request that installs or updates it all, create the
6342
6807
  missing Linear labels and register the project. The options are for
6343
- a repository without armada.toml (Linear issue at the program root)
6808
+ a repository without armada.toml (Linear issue at the program root).
6809
+ It asks before adding the Claude Code stop hook to the repository's
6810
+ .claude/settings.json (yes without a terminal); --no-stop-hook skips it
6344
6811
  `,
6345
6812
  claim: ` claim <ticket> --runtime <name> --handle <id> [--branch <name>]
6346
6813
  [--profile <name> [--reason <why>]]
@@ -6366,8 +6833,15 @@ var COMMAND_HELP = {
6366
6833
  inbox: ` inbox [--wait [--timeout <seconds>]]
6367
6834
  Coordinator: open questions, plans, requests, hand-backs and silent workers,
6368
6835
  oldest first; records that the coordinator is at work. --wait returns
6369
- when a new item arrives or after --timeout (default 300 s). Needs a
6370
- sign-in to Armada
6836
+ when a new item arrives or after --timeout (default 300 s); \`armada watch\`
6837
+ is the way to keep listening. Needs a sign-in to Armada
6838
+ `,
6839
+ watch: ` watch Coordinator: run in the background while workers are in flight. Waits
6840
+ until something needs you (a question, plan, request, hand-back or silent
6841
+ worker you have not seen), prints it and exits; exits "nothing to watch"
6842
+ when no worker is in flight and nothing is open. Armada being down or a
6843
+ command time limit does not end it: it keeps asking. One per project on
6844
+ this machine. Needs a sign-in to Armada
6371
6845
  `,
6372
6846
  answer: ` answer <item|ticket> "<answer>"
6373
6847
  Coordinator: record an answer already delivered in the worker's
@@ -6391,6 +6865,11 @@ var COMMAND_HELP = {
6391
6865
  default_profile; --profile overrides it, with --reason when it differs.
6392
6866
  Signed in to Armada, the prompt starts with a one-time launch token, so
6393
6867
  the worker needs no key. --prompt prints only the prompt, for \`--message-file -\`
6868
+ `,
6869
+ hook: ` hook stop Claude Code's Stop hook, installed by \`armada init\`: a coordinator
6870
+ cannot end its turn while workers are in flight and no \`armada watch\`
6871
+ runs for the project in this checkout. Reads only local files;
6872
+ ARMADA_STOP_HOOK=off turns it off
6394
6873
  `,
6395
6874
  login: ` login Sign this terminal in to Armada: confirm the code it shows in the browser
6396
6875
  login --api-key Sign a headless coordinator in with an organization API key, read from a
@@ -6409,7 +6888,18 @@ var COMMAND_HELP = {
6409
6888
  `
6410
6889
  };
6411
6890
  var TICKET_OPTION = new Set(["report", "release", "ask", "merge"]);
6412
- var CONFIG_OPTION = new Set(["status", "claim", "report", "release", "ask", "inbox", "answer", "merge", "brief"]);
6891
+ var CONFIG_OPTION = new Set([
6892
+ "status",
6893
+ "claim",
6894
+ "report",
6895
+ "release",
6896
+ "ask",
6897
+ "inbox",
6898
+ "watch",
6899
+ "answer",
6900
+ "merge",
6901
+ "brief"
6902
+ ]);
6413
6903
  var JSON_OPTION = new Set([...CONFIG_OPTION, "doctor", "auth", "whoami"]);
6414
6904
  var TICKET_HELP = ` --ticket <id> Ticket for report, release and ask (default ARMADA_TICKET, then the git
6415
6905
  branch) and for merge (default: the ticket the PR branch names)
@@ -6434,14 +6924,15 @@ Keys (the environment first, then Armada when signed in, then the file):
6434
6924
 
6435
6925
  The fleet's live data (claims, reports, the inbox, the merge lock, the project
6436
6926
  registry) is reached through Armada with the sign-in: no database key is needed.
6437
- init, inbox and status --all need a sign-in; elsewhere, signed out, live activity
6438
- is not recorded and Linear stays the record.
6927
+ init, inbox, watch and status --all need a sign-in; elsewhere, signed out, live
6928
+ activity is not recorded and Linear stays the record.
6439
6929
 
6440
6930
  Files:
6441
6931
  $XDG_CONFIG_HOME/armada (default ~/.config/armada)
6442
6932
  credentials KEY=value lines, mode 0600, written by \`armada auth login\` and
6443
6933
  \`armada login\` (the sign-in: ARMADA_SESSION_TOKEN or ARMADA_API_KEY)
6444
6934
  config.toml personal defaults: language, [dashboard] url, [api] url
6935
+ watch/<project>.* the project's watch: its lock, what you were shown, who is in flight
6445
6936
  `;
6446
6937
  function commandHelp(command) {
6447
6938
  const block = Object.hasOwn(COMMAND_HELP, command) ? COMMAND_HELP[command] : undefined;
@@ -6480,7 +6971,7 @@ var VALUE_OPTIONS = [
6480
6971
  "launch-token",
6481
6972
  "api-url"
6482
6973
  ];
6483
- var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key"];
6974
+ var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key", "no-stop-hook"];
6484
6975
  var COMMAND_OPTIONS = {
6485
6976
  claim: ["runtime", "handle", "branch", "profile", "reason"],
6486
6977
  report: ["ticket", "message", "message-file", "pr", "sha"],
@@ -6488,7 +6979,7 @@ var COMMAND_OPTIONS = {
6488
6979
  ask: ["ticket", "options", "message", "message-file"],
6489
6980
  inbox: ["wait", "timeout"],
6490
6981
  answer: ["note", "message", "message-file"],
6491
- init: ["program-root", "name", "slug"],
6982
+ init: ["program-root", "name", "slug", "no-stop-hook"],
6492
6983
  merge: ["ticket", "dry-run", "no-lock"],
6493
6984
  brief: ["profile", "reason", "prompt"],
6494
6985
  login: ["api-key", "launch-token", "api-url"]
@@ -6544,12 +7035,12 @@ async function findConfig(io, explicit, command = "status") {
6544
7035
  throw new UsageError(`${path} does not exist`, `armada ${command} --config <file>, with the path of an ${CONFIG_FILE}`);
6545
7036
  return { path, text };
6546
7037
  }
6547
- for (let dir = resolve(io.cwd);; dir = dirname3(dir)) {
7038
+ for (let dir = resolve(io.cwd);; dir = dirname5(dir)) {
6548
7039
  const path = join5(dir, CONFIG_FILE);
6549
7040
  const text = await io.readFile(path);
6550
7041
  if (text !== null)
6551
7042
  return { path, text };
6552
- if (dirname3(dir) === dir)
7043
+ if (dirname5(dir) === dir)
6553
7044
  break;
6554
7045
  }
6555
7046
  throw new UsageError(`no ${CONFIG_FILE} found in ${io.cwd} or any parent directory, so this is not a repository Armada runs`, `armada init to set this repository up, armada ${command} --config <file> to use another ${CONFIG_FILE}, or armada status --all to see the registered projects`);
@@ -6640,6 +7131,13 @@ async function run(argv, io) {
6640
7131
  const { credentials } = await loadCredentials(io, scope ? { worker: scope } : {});
6641
7132
  return await worker(io, config, credentials, args);
6642
7133
  }
7134
+ if (args.command === "watch") {
7135
+ const { path, text } = await findConfig(io, args.config, "watch");
7136
+ const { credentials } = await loadCredentials(io);
7137
+ return await watch2(io, parseConfig(text, path), credentials, args, path);
7138
+ }
7139
+ if (args.command === "hook")
7140
+ return await hookStop(io, args.rest, (at) => findConfig(at, null, "hook"));
6643
7141
  if (args.command === "merge") {
6644
7142
  const { path, text } = await findConfig(io, args.config, "merge");
6645
7143
  const { credentials } = await loadCredentials(io);
@@ -6664,7 +7162,8 @@ async function run(argv, io) {
6664
7162
  armadaVersion: version,
6665
7163
  programRoot: args.options["program-root"] ?? null,
6666
7164
  name: args.options.name ?? null,
6667
- slug: args.options.slug ?? null
7165
+ slug: args.options.slug ?? null,
7166
+ stopHook: args.options["no-stop-hook"] === "true" ? false : null
6668
7167
  });
6669
7168
  }
6670
7169
  if (args.command === "login" || args.command === "logout" || args.command === "whoami") {