@the-vibe-company/armada 0.2.0 → 0.2.2

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 +8 -3
  2. package/dist/armada.js +1028 -544
  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 = [
@@ -1794,7 +1794,8 @@ var CONFIG_DEFAULTS = {
1794
1794
  phaseGroup: "Agent phase",
1795
1795
  runtimeGroup: "Agent runtime",
1796
1796
  runtimes: ["Claude Code", "Codex", "Conductor"],
1797
- silentAfterMinutes: 15
1797
+ silentAfterMinutes: 15,
1798
+ coordinatorMinutes: 10
1798
1799
  };
1799
1800
 
1800
1801
  class ConfigError extends Error {
@@ -1882,7 +1883,7 @@ function parseConfig(text, source = CONFIG_FILE) {
1882
1883
  ["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
1883
1884
  ["github", github, ["repository"]],
1884
1885
  ["gates", gatesT, ["required_checks", "local_commands"]],
1885
- ["policy", policyT, ["silence_minutes", "silent_after_minutes"]],
1886
+ ["policy", policyT, ["silence_minutes", "silent_after_minutes", "coordinator_minutes"]],
1886
1887
  ["conductor", conductorT, ["default_profile", "profiles", "routing"]]
1887
1888
  ];
1888
1889
  const profiles = {};
@@ -1959,6 +1960,14 @@ function parseConfig(text, source = CONFIG_FILE) {
1959
1960
  else
1960
1961
  problems.push(`"policy.${silenceKey}" must be a positive number`);
1961
1962
  }
1963
+ let coordinatorMinutes = CONFIG_DEFAULTS.coordinatorMinutes;
1964
+ if (policyT.coordinator_minutes !== undefined) {
1965
+ const v = policyT.coordinator_minutes;
1966
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
1967
+ coordinatorMinutes = v;
1968
+ else
1969
+ problems.push(`"policy.coordinator_minutes" must be a positive number`);
1970
+ }
1962
1971
  let requiredChecks = [];
1963
1972
  if (gatesT.required_checks !== undefined) {
1964
1973
  const v = gatesT.required_checks;
@@ -1997,7 +2006,7 @@ function parseConfig(text, source = CONFIG_FILE) {
1997
2006
  repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
1998
2007
  },
1999
2008
  gates: { requiredChecks, localCommands },
2000
- policy: { silentAfterMinutes },
2009
+ policy: { silentAfterMinutes, coordinatorMinutes },
2001
2010
  conductor: { defaultProfile, profiles, routing }
2002
2011
  };
2003
2012
  if (problems.length)
@@ -2032,6 +2041,7 @@ repository = ${q(p.repository)}
2032
2041
 
2033
2042
  [policy]
2034
2043
  silence_minutes = 15 # a worker with no report for longer than this shows as silent
2044
+ coordinator_minutes = 10 # an inbox item open longer than this shows "waiting for the coordinator"
2035
2045
 
2036
2046
  # How \`armada brief\` launches workers on Conductor. Every value is passed explicitly;
2037
2047
  # \`conductor model\` lists each agent's model ids and effort levels.
@@ -3324,11 +3334,13 @@ async function checkInbox(fleet, o) {
3324
3334
  throw new Error("Armada answered the first inbox read with nothing");
3325
3335
  const warnings = [...first.warnings];
3326
3336
  let items = first.items;
3337
+ let inFlight = first.inFlight ?? null;
3327
3338
  let etag = first.etag;
3328
3339
  const report = (timedOut) => ({
3329
3340
  project: o.project,
3330
3341
  generatedAt: o.now().toISOString(),
3331
3342
  items,
3343
+ inFlight,
3332
3344
  wait: o.wait && timedOut !== null ? { timeoutSeconds: Math.round(o.wait.timeoutMs / 1000), timedOut } : null,
3333
3345
  warnings: [...new Set(warnings)]
3334
3346
  });
@@ -3345,6 +3357,7 @@ async function checkInbox(fleet, o) {
3345
3357
  continue;
3346
3358
  const known = new Set(items.map(entryKey));
3347
3359
  items = read.items.map((e) => ({ ...e, new: !known.has(entryKey(e)) }));
3360
+ inFlight = read.inFlight ?? null;
3348
3361
  etag = read.etag;
3349
3362
  warnings.push(...read.warnings);
3350
3363
  if (items.some((e) => e.new))
@@ -3666,8 +3679,110 @@ function createLinearWriter(opts) {
3666
3679
  }
3667
3680
  // ../core/src/machine.ts
3668
3681
  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";
3682
+ import { chmod, link, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
3683
+ import { dirname, isAbsolute, join } from "node:path";
3684
+
3685
+ // ../core/src/watch.ts
3686
+ var WATCH_POLL_MS = 15000;
3687
+ var WATCH_IDLE_POLL_MS = 60000;
3688
+ var WATCH_BACKOFF_MS = [15000, 30000, 60000];
3689
+ var STOP_HOOK_VARIABLE = "ARMADA_STOP_HOOK";
3690
+ var EMPTY_WATCH_STATE = { root: null, seen: [], inFlight: null, readAt: null, stopped: null };
3691
+ function transientFailure(err) {
3692
+ if (!(err instanceof ArmadaApiError))
3693
+ return false;
3694
+ const s = err.status;
3695
+ if (s !== null)
3696
+ return s >= 500 || s === 408 || s === 429;
3697
+ return /\bunreachable\b|\bHTTP (?:5\d\d|408|429) without JSON\b/.test(err.message);
3698
+ }
3699
+ async function watchInbox(fleet, o) {
3700
+ const query = { coordinator: o.coordinator, silentAfterMinutes: o.silentAfterMinutes };
3701
+ const pollMs = o.pollMs ?? WATCH_POLL_MS;
3702
+ const idlePollMs = o.idlePollMs ?? WATCH_IDLE_POLL_MS;
3703
+ let known = new Set(o.seen);
3704
+ let etag = null;
3705
+ let items = [];
3706
+ let inFlight = null;
3707
+ let failures = 0;
3708
+ const warnings = new Set;
3709
+ const report = (outcome) => ({
3710
+ project: o.project,
3711
+ generatedAt: o.now().toISOString(),
3712
+ outcome,
3713
+ items,
3714
+ inFlight,
3715
+ warnings: [...warnings]
3716
+ });
3717
+ for (;; ) {
3718
+ let read;
3719
+ try {
3720
+ read = await fleet.inbox({ ...query, etag });
3721
+ } catch (err) {
3722
+ if (!transientFailure(err))
3723
+ throw err;
3724
+ const wait = WATCH_BACKOFF_MS[Math.min(failures, WATCH_BACKOFF_MS.length - 1)] ?? pollMs;
3725
+ failures++;
3726
+ o.onRetry?.(`${err.message}; still watching, next try in ${wait / 1000} s`);
3727
+ await o.sleep(wait);
3728
+ continue;
3729
+ }
3730
+ failures = 0;
3731
+ if (read) {
3732
+ items = read.items.map((e) => ({ ...e, new: !known.has(entryKey(e)) }));
3733
+ inFlight = read.inFlight ?? null;
3734
+ etag = read.etag;
3735
+ known = new Set(items.map(entryKey));
3736
+ for (const w of read.warnings)
3737
+ warnings.add(w);
3738
+ await o.onRead?.({ items, inFlight });
3739
+ if (items.some((e) => e.new))
3740
+ return report("items");
3741
+ if (inFlight !== null && !inFlight.length && !items.length)
3742
+ return report("nothing");
3743
+ }
3744
+ await o.sleep(inFlight !== null && !inFlight.length ? idlePollMs : pollMs);
3745
+ }
3746
+ }
3747
+ var workers = (n) => `${n} worker${n === 1 ? "" : "s"} in flight`;
3748
+ function rearm(o) {
3749
+ const then = o.act ? "act on the items above, then " : "";
3750
+ const watch = o.running !== null ? `armada watch is already running (pid ${o.running})` : null;
3751
+ let line;
3752
+ if (o.inFlight === null)
3753
+ line = watch ? `Workers may be in flight — ${then}${watch}.` : `While a worker is in flight, ${then}keep watching: armada watch`;
3754
+ else if (o.inFlight.length)
3755
+ line = `${workers(o.inFlight.length)} (${o.inFlight.join(", ")}) — ${watch ? `${then}${watch}.` : `${then}keep watching: armada watch`}`;
3756
+ else if (o.open)
3757
+ line = `No worker in flight, ${o.open} item${o.open === 1 ? "" : "s"} open — ${watch ? `${then}${watch}.` : `${then}keep watching: armada watch`}`;
3758
+ else if (o.open === null)
3759
+ line = "No worker in flight — nothing to watch.";
3760
+ else
3761
+ line = "No worker in flight and nothing open — nothing to watch.";
3762
+ return { inFlight: o.inFlight, open: o.open, running: o.running, line };
3763
+ }
3764
+ function stopHookDecision(o) {
3765
+ const off = o.env[STOP_HOOK_VARIABLE]?.trim().toLowerCase();
3766
+ if (off === "off" || off === "0" || off === "false")
3767
+ return { block: false, why: `${STOP_HOOK_VARIABLE}=${off}` };
3768
+ const s = o.state;
3769
+ if (!s?.root)
3770
+ return { block: false, why: `armada watch never ran for ${o.project} on this machine` };
3771
+ if (s.root !== o.root)
3772
+ return { block: false, why: `the coordinator's checkout is ${s.root}, not this one` };
3773
+ if (o.watching !== null)
3774
+ return { block: false, why: `armada watch is running (pid ${o.watching})` };
3775
+ if (s.stopped)
3776
+ return { block: false, why: `the last watch was refused: ${s.stopped}` };
3777
+ if (!s.inFlight?.length)
3778
+ return { block: false, why: "no worker in flight at the last read" };
3779
+ return {
3780
+ block: true,
3781
+ 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.)`
3782
+ };
3783
+ }
3784
+
3785
+ // ../core/src/machine.ts
3671
3786
  function machinePaths(env) {
3672
3787
  const xdg = env.XDG_CONFIG_HOME?.trim();
3673
3788
  const home = env.HOME?.trim();
@@ -3697,6 +3812,8 @@ var storeIsExposed = (store) => store.mode !== null && (store.mode & 63) !== 0;
3697
3812
  async function writePrivate(paths, path, text, mode) {
3698
3813
  await mkdir(paths.dir, { recursive: true, mode: 448 });
3699
3814
  await chmod(paths.dir, 448);
3815
+ if (dirname(path) !== paths.dir)
3816
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
3700
3817
  const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
3701
3818
  const handle = await open(tmp, "wx", mode);
3702
3819
  try {
@@ -3807,6 +3924,88 @@ async function ensurePersonalConfig(paths) {
3807
3924
  await writePrivate(paths, paths.config, PERSONAL_CONFIG_TEMPLATE, 420);
3808
3925
  return true;
3809
3926
  }
3927
+ function watchFiles(paths, project) {
3928
+ const dir = join(paths.dir, "watch");
3929
+ return { state: join(dir, `${project}.json`), lock: join(dir, `${project}.pid`) };
3930
+ }
3931
+ var strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null;
3932
+ var stringOr = (v) => typeof v === "string" && v ? v : null;
3933
+ async function readWatchState(paths, project) {
3934
+ let raw;
3935
+ try {
3936
+ raw = JSON.parse(await readFile(watchFiles(paths, project).state, "utf8"));
3937
+ } catch {
3938
+ return null;
3939
+ }
3940
+ if (typeof raw !== "object" || raw === null)
3941
+ return null;
3942
+ const r = raw;
3943
+ return {
3944
+ root: stringOr(r.root),
3945
+ seen: strings(r.seen) ?? [],
3946
+ inFlight: strings(r.inFlight),
3947
+ readAt: stringOr(r.readAt),
3948
+ stopped: stringOr(r.stopped)
3949
+ };
3950
+ }
3951
+ async function updateWatchState(paths, project, patch) {
3952
+ const state = { ...EMPTY_WATCH_STATE, ...await readWatchState(paths, project), ...patch };
3953
+ await writePrivate(paths, watchFiles(paths, project).state, `${JSON.stringify(state, null, 2)}
3954
+ `, 384);
3955
+ return state;
3956
+ }
3957
+ async function readWatchLock(paths, project) {
3958
+ try {
3959
+ const pid = Number((await readFile(watchFiles(paths, project).lock, "utf8")).trim());
3960
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : null;
3961
+ } catch (err) {
3962
+ if (missing(err))
3963
+ return null;
3964
+ throw err;
3965
+ }
3966
+ }
3967
+ function processAlive(pid) {
3968
+ try {
3969
+ process.kill(pid, 0);
3970
+ return true;
3971
+ } catch (err) {
3972
+ return err.code === "EPERM";
3973
+ }
3974
+ }
3975
+ async function takeWatchLock(paths, project, pid, alive = processAlive) {
3976
+ const { lock } = watchFiles(paths, project);
3977
+ await mkdir(dirname(lock), { recursive: true, mode: 448 });
3978
+ const tmp = `${lock}.${randomBytes(6).toString("hex")}.tmp`;
3979
+ await writeFile(tmp, `${pid}
3980
+ `, { mode: 384 });
3981
+ try {
3982
+ for (let attempt = 0;attempt < 3; attempt++) {
3983
+ try {
3984
+ await link(tmp, lock);
3985
+ return { taken: true };
3986
+ } catch (err) {
3987
+ if (err.code !== "EEXIST")
3988
+ throw err;
3989
+ }
3990
+ const held = await readWatchLock(paths, project);
3991
+ if (held !== null && held !== pid && alive(held))
3992
+ return { taken: false, pid: held };
3993
+ if (await readWatchLock(paths, project) === held)
3994
+ await rm(lock, { force: true });
3995
+ }
3996
+ throw new Error(`cannot take the watch lock ${lock}`);
3997
+ } finally {
3998
+ await rm(tmp, { force: true });
3999
+ }
4000
+ }
4001
+ async function releaseWatchLock(paths, project, pid) {
4002
+ if (await readWatchLock(paths, project).catch(() => null) === pid)
4003
+ await rm(watchFiles(paths, project).lock, { force: true });
4004
+ }
4005
+ async function runningWatch(paths, project, alive = processAlive) {
4006
+ const pid = await readWatchLock(paths, project).catch(() => null);
4007
+ return pid !== null && alive(pid) ? pid : null;
4008
+ }
3810
4009
  // ../core/src/merge.ts
3811
4010
  var MERGE_LEASE = "merge";
3812
4011
  var MERGE_LEASE_TTL_MS = 20 * 60000;
@@ -4201,6 +4400,7 @@ async function after(ctx, c, merged, lines) {
4201
4400
  if (live$?.resolved)
4202
4401
  lines.push(`Hand-back resolved in the coordinator's inbox.`);
4203
4402
  let workers = [];
4403
+ let listed = false;
4204
4404
  try {
4205
4405
  const handles = new Map((live$?.open ?? []).map((h) => [h.ticket, h]));
4206
4406
  workers = (await ctx.inFlight()).filter((t) => t.id !== c.ticket.id).map((t) => ({
@@ -4210,6 +4410,7 @@ async function after(ctx, c, merged, lines) {
4210
4410
  runtime: t.runtime ?? handles.get(t.id)?.runtime ?? null,
4211
4411
  handle: handles.get(t.id)?.handle ?? null
4212
4412
  }));
4413
+ listed = true;
4213
4414
  } catch (err) {
4214
4415
  c.warnings.push(`could not list the workers in flight (${err instanceof Error ? err.message : String(err)}); run armada status`);
4215
4416
  }
@@ -4223,7 +4424,7 @@ async function after(ctx, c, merged, lines) {
4223
4424
  c.warnings.push(`could not look for the ${expected} skill (${err instanceof Error ? err.message : String(err)})`);
4224
4425
  }
4225
4426
  const archive = { runtime, handle: live$?.handle?.handle ?? claim?.session ?? null, guide };
4226
- return outcome(c, true, merged, lines, workers, archive);
4427
+ return { ...outcome(c, true, merged, lines, workers, archive), workersListed: listed };
4227
4428
  }
4228
4429
  function outcome(c, merged, pr, lines, workers, archive) {
4229
4430
  const p = pr ?? c.pull;
@@ -4241,6 +4442,7 @@ function outcome(c, merged, pr, lines, workers, archive) {
4241
4442
  lines,
4242
4443
  hints: c.hints,
4243
4444
  workers,
4445
+ workersListed: false,
4244
4446
  archive,
4245
4447
  warnings: c.warnings
4246
4448
  };
@@ -4293,7 +4495,7 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
4293
4495
  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
4496
  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
4497
  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.
4498
+ 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
4499
  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
4500
  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
4501
 
@@ -4316,7 +4518,18 @@ A coordinator may start cold, on a laptop or in a fresh cloud session, with noth
4316
4518
  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
4519
  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
4520
 
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.
4521
+ Repeat from step 1.
4522
+
4523
+ ## Keep watching
4524
+
4525
+ 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.
4526
+
4527
+ - 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.
4528
+ - 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.
4529
+ - \`armada watch\` exits with "nothing to watch" when no worker is in flight and nothing is open: the round is over.
4530
+ - 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.
4531
+ - 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.
4532
+ - 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
4533
 
4321
4534
  ## Rules of thumb
4322
4535
 
@@ -4390,6 +4603,8 @@ var AGENTS_SKILLS_DIR = ".agents/skills";
4390
4603
  var CLAUDE_SKILLS_DIR = ".claude/skills";
4391
4604
  var SKILLS_LOCK_FILE = "skills-lock.json";
4392
4605
  var CONDUCTOR_SETTINGS = ".conductor/settings.toml";
4606
+ var CLAUDE_SETTINGS = ".claude/settings.json";
4607
+ var STOP_HOOK_COMMAND = "armada hook stop 2>/dev/null || true";
4393
4608
  var GITIGNORE = ".gitignore";
4394
4609
  var SHIP_ARTIFACTS = "plans/ship-pr-dev/";
4395
4610
  var ok = (id, message) => ({ id, level: "ok", message, fix: null });
@@ -4505,9 +4720,56 @@ async function checkRepository(view, armadaVersion) {
4505
4720
  throw err;
4506
4721
  checks.push(bad("conductor", "error", err.message, `fix ${CONDUCTOR_SETTINGS}`));
4507
4722
  }
4723
+ checks.push(await stopHookCheck(view));
4508
4724
  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
4725
  return checks;
4510
4726
  }
4727
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4728
+ function claudeSettings(text) {
4729
+ if (text === null)
4730
+ return null;
4731
+ let raw;
4732
+ try {
4733
+ raw = JSON.parse(text);
4734
+ } catch {
4735
+ throw new SetupError(`${CLAUDE_SETTINGS} is not valid JSON`);
4736
+ }
4737
+ if (!isObject(raw))
4738
+ throw new SetupError(`${CLAUDE_SETTINGS} is not a JSON object`);
4739
+ return raw;
4740
+ }
4741
+ function hasStopHook(settings) {
4742
+ const stop = isObject(settings?.hooks) ? settings.hooks.Stop : undefined;
4743
+ if (!Array.isArray(stop))
4744
+ return false;
4745
+ 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")));
4746
+ }
4747
+ function withStopHook(text) {
4748
+ const settings = claudeSettings(text) ?? {};
4749
+ if (hasStopHook(settings))
4750
+ return text ?? "";
4751
+ const hooks = settings.hooks ?? {};
4752
+ if (!isObject(hooks))
4753
+ throw new SetupError(`${CLAUDE_SETTINGS} has a "hooks" value that is not an object`);
4754
+ const stop = hooks.Stop ?? [];
4755
+ if (!Array.isArray(stop))
4756
+ throw new SetupError(`${CLAUDE_SETTINGS} has a "hooks.Stop" value that is not a list`);
4757
+ const entry = { hooks: [{ type: "command", command: STOP_HOOK_COMMAND, timeout: 10 }] };
4758
+ return `${JSON.stringify({ ...settings, hooks: { ...hooks, Stop: [...stop, entry] } }, null, 2)}
4759
+ `;
4760
+ }
4761
+ async function stopHookCheck(view) {
4762
+ const id = "stop-hook";
4763
+ let settings;
4764
+ try {
4765
+ settings = claudeSettings(await view.readFile(CLAUDE_SETTINGS));
4766
+ } catch (err) {
4767
+ if (!(err instanceof SetupError))
4768
+ throw err;
4769
+ return bad(id, "warning", `Claude Code stop hook not checked: ${err.message}`, `fix ${CLAUDE_SETTINGS}`);
4770
+ }
4771
+ 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)");
4772
+ }
4511
4773
  async function guessSetupCommand(view) {
4512
4774
  const has = async (p) => await view.readFile(p) !== null;
4513
4775
  if (await has("bun.lock") || await has("bun.lockb"))
@@ -4570,7 +4832,7 @@ function lockText(lock, armadaVersion) {
4570
4832
  `;
4571
4833
  }
4572
4834
  async function planSetup(view, opts) {
4573
- const plan = { writes: [], removes: [], links: [], installed: [], updated: [] };
4835
+ const plan = { writes: [], removes: [], links: [], installed: [], updated: [], stopHook: false };
4574
4836
  if (opts.configText !== null && await view.readFile(CONFIG_FILE) === null)
4575
4837
  plan.writes.push({ path: CONFIG_FILE, content: opts.configText });
4576
4838
  const wholeDir = await linksWholeDir(view);
@@ -4598,6 +4860,21 @@ async function planSetup(view, opts) {
4598
4860
  plan.writes.push({ path: CONDUCTOR_SETTINGS, content: conductorSettings(await guessSetupCommand(view)) });
4599
4861
  else if (!conductorSetup(settings))
4600
4862
  plan.writes.push({ path: CONDUCTOR_SETTINGS, content: withSetup(settings, await guessSetupCommand(view)) });
4863
+ if (opts.stopHook ?? true) {
4864
+ const before = await view.readFile(CLAUDE_SETTINGS);
4865
+ let after;
4866
+ try {
4867
+ after = withStopHook(before);
4868
+ } catch (err) {
4869
+ if (!(err instanceof SetupError))
4870
+ throw err;
4871
+ throw new SetupError(`${err.message}: fix it, or leave the stop hook out with \`armada init --no-stop-hook\``);
4872
+ }
4873
+ if (after !== (before ?? "")) {
4874
+ plan.writes.push({ path: CLAUDE_SETTINGS, content: after });
4875
+ plan.stopHook = true;
4876
+ }
4877
+ }
4601
4878
  const gitignore = await view.readFile(GITIGNORE);
4602
4879
  if (!ignoresShipArtifacts(gitignore)) {
4603
4880
  const base = gitignore === null || gitignore === "" ? "" : `${gitignore.replace(/\n*$/, `
@@ -4656,6 +4933,7 @@ function buildStatus({
4656
4933
  github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
4657
4934
  },
4658
4935
  silentAfterMinutes: config.policy.silentAfterMinutes,
4936
+ coordinatorMinutes: config.policy.coordinatorMinutes,
4659
4937
  inFlight: lanes.map((l) => ({
4660
4938
  id: l.issue.id,
4661
4939
  title: l.issue.title,
@@ -4731,7 +5009,7 @@ async function loadStatus(config, opts) {
4731
5009
  });
4732
5010
  }
4733
5011
  // package.json
4734
- var version = "0.2.0";
5012
+ var version = "0.2.2";
4735
5013
 
4736
5014
  // src/io.ts
4737
5015
  class UsageError extends Error {
@@ -4977,110 +5255,8 @@ async function authLogout(io) {
4977
5255
  return 0;
4978
5256
  }
4979
5257
 
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
- }
5258
+ // src/watch.ts
5259
+ import { dirname as dirname2 } from "node:path";
5084
5260
 
5085
5261
  // src/login.ts
5086
5262
  var hostOf = (url) => {
@@ -5275,55 +5451,588 @@ async function logout(io) {
5275
5451
  return 0;
5276
5452
  }
5277
5453
 
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) });
5454
+ // src/worker.ts
5455
+ function liveFleet(io, config, credentials) {
5456
+ const signIn = credentials.armadaSignIn;
5457
+ if (!signIn)
5458
+ return {
5459
+ fleet: null,
5460
+ warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
5461
+ };
5462
+ try {
5463
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
5464
+ return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
5465
+ } catch (err) {
5466
+ return {
5467
+ fleet: null,
5468
+ warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
5469
+ };
5293
5470
  }
5294
5471
  }
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;
5314
- throw err;
5315
- }
5316
- return out;
5317
- }
5318
- };
5472
+ function statusEvents(io, config, credentials) {
5473
+ const { fleet } = liveFleet(io, config, credentials);
5474
+ return fleet ? () => fleet.lastEventTimes() : undefined;
5319
5475
  }
5320
- async function assertNoLinkedParent(root, path) {
5321
- const parts = path.split("/").slice(0, -1);
5322
- for (let k = 1;k <= parts.length; k++) {
5323
- const parent = parts.slice(0, k).join("/");
5324
- if ((await lstat(join2(root, parent)).catch(() => null))?.isSymbolicLink())
5325
- throw new CommandError(`${parent} is a link; Armada does not write through it. Replace it with a folder first.`);
5326
- }
5476
+ function currentTicket(io, config, explicit, workers = []) {
5477
+ const fromEnv = io.env.ARMADA_TICKET?.trim();
5478
+ const id = explicit?.trim() || fromEnv || (() => {
5479
+ const branch = io.gitBranch?.();
5480
+ return branch ? ticketFromBranch(branch, config.tracker.programRoot) : null;
5481
+ })() || (workers.length === 1 ? workers[0] : null);
5482
+ if (!id)
5483
+ throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
5484
+ return id.toUpperCase();
5485
+ }
5486
+ function context(io, config, credentials) {
5487
+ if (!credentials.linearApiKey)
5488
+ throw missingKey(LINEAR_KEY);
5489
+ const linearOpts = {
5490
+ apiKey: credentials.linearApiKey,
5491
+ labels: config.tracker.labels,
5492
+ ...io.fetch ? { fetch: io.fetch } : {}
5493
+ };
5494
+ const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
5495
+ const live = liveFleet(io, config, credentials);
5496
+ const token = credentials.githubToken;
5497
+ return {
5498
+ config,
5499
+ linear,
5500
+ fleet: async () => live,
5501
+ readPull: token ? (number) => fetchPullRequest({
5502
+ token,
5503
+ repository: config.github.repository,
5504
+ number,
5505
+ ...io.fetch ? { fetch: io.fetch } : {}
5506
+ }) : null,
5507
+ now: io.now ?? (() => new Date)
5508
+ };
5509
+ }
5510
+ function print(io, outcome, json) {
5511
+ if (json) {
5512
+ io.stdout(`${JSON.stringify(outcome, null, 2)}
5513
+ `);
5514
+ return;
5515
+ }
5516
+ const out = [...outcome.lines];
5517
+ const s = outcome.state;
5518
+ if (s)
5519
+ out.push(`Now: ${s.status} · phase ${s.phase ?? "none"} · runtime ${s.runtime ?? "none"} · profile ${s.profile ?? "none"}`);
5520
+ out.push(outcome.url);
5521
+ if (outcome.inbox) {
5522
+ if (!outcome.inbox.length)
5523
+ out.push("Inbox: nothing waiting for you.");
5524
+ else {
5525
+ out.push(`Inbox (${outcome.inbox.length}) — read and act on these:`);
5526
+ for (const item of outcome.inbox)
5527
+ out.push(` #${item.id} ${item.kind}${item.author ? ` from ${item.author}` : ""} · ${item.createdAt}`, ...item.body.split(`
5528
+ `).map((l) => ` ${l}`));
5529
+ }
5530
+ }
5531
+ io.stdout(`${out.join(`
5532
+ `)}
5533
+ `);
5534
+ for (const w of outcome.warnings)
5535
+ io.stderr(`armada: warning: ${w}
5536
+ `);
5537
+ }
5538
+ async function readMessage(io, options) {
5539
+ if (options.message !== undefined && options["message-file"] !== undefined)
5540
+ throw new UsageError("pass --message or --message-file, not both");
5541
+ const file = options["message-file"];
5542
+ if (file === undefined)
5543
+ return options.message ?? null;
5544
+ const text = file === "-" ? await io.readStdin?.() ?? null : await io.readFile(file);
5545
+ if (text === null)
5546
+ throw new UsageError(`cannot read the message from ${file}`);
5547
+ if (!text.trim())
5548
+ 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 -');
5549
+ return text;
5550
+ }
5551
+ async function withContext(io, config, credentials, json, act) {
5552
+ print(io, await act(context(io, config, credentials)), json);
5553
+ return 0;
5554
+ }
5555
+ async function claim(io, config, credentials, a) {
5556
+ const [ticket, ...extra] = a.rest;
5557
+ if (!ticket)
5558
+ throw new UsageError("claim needs a ticket: armada claim <ticket> --runtime <name> --handle <id>");
5559
+ if (extra.length)
5560
+ throw new UsageError(`unexpected argument ${extra[0]}`);
5561
+ const runtime = a.options.runtime?.trim();
5562
+ const handle = a.options.handle?.trim();
5563
+ if (!runtime)
5564
+ throw new UsageError("--runtime is required, e.g. --runtime conductor");
5565
+ const profile = a.options.profile?.trim() || null;
5566
+ const reason = a.options.reason?.trim() || null;
5567
+ if (reason && !profile)
5568
+ throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
5569
+ try {
5570
+ checkRequestedProfile(config, profile);
5571
+ } catch (err) {
5572
+ if (err instanceof ProfileError)
5573
+ throw new UsageError(err.message);
5574
+ throw err;
5575
+ }
5576
+ if (!handle)
5577
+ throw new UsageError("--handle is required: the runtime's id for this session, e.g. <workspace>/<session>");
5578
+ return withContext(io, config, credentials, a.json, (ctx) => claimTicket(ctx, {
5579
+ ticket: ticket.toUpperCase(),
5580
+ runtime,
5581
+ handle,
5582
+ ...a.options.branch ? { branch: a.options.branch } : {},
5583
+ profile,
5584
+ reason
5585
+ }));
5586
+ }
5587
+ async function report(io, config, credentials, a) {
5588
+ const [phase, ...extra] = a.rest;
5589
+ if (!phase || !isLabelPhase(phase))
5590
+ throw new UsageError(`report needs a phase: ${LABEL_PHASES.join(", ")}${phase ? ` (got "${phase}")` : ""}`);
5591
+ if (extra.length)
5592
+ throw new UsageError(`unexpected argument ${extra[0]}`);
5593
+ const message = await readMessage(io, a.options);
5594
+ if (!message?.trim() && phase !== "ready-to-merge")
5595
+ throw new UsageError("--message is required: what you did or what you are doing (first line = summary)");
5596
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5597
+ return withContext(io, config, credentials, a.json, (ctx) => reportPhase(ctx, {
5598
+ ticket,
5599
+ phase,
5600
+ message,
5601
+ pr: a.options.pr ?? null,
5602
+ sha: a.options.sha ?? null
5603
+ }));
5604
+ }
5605
+ async function release(io, config, credentials, a) {
5606
+ if (a.rest.length)
5607
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
5608
+ const reason = a.options.reason?.trim();
5609
+ if (!reason)
5610
+ throw new UsageError("--reason is required: why the ticket is given back");
5611
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5612
+ const code = await withContext(io, config, credentials, a.json, (ctx) => releaseTicket(ctx, { ticket, reason }));
5613
+ await endWorkerSessions(io, config, credentials, ticket, "released", a.json);
5614
+ return code;
5615
+ }
5616
+ async function endWorkerSessions(io, config, credentials, ticket, reason, quiet) {
5617
+ const signIn = credentials.armadaSignIn;
5618
+ if (!signIn)
5619
+ return;
5620
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
5621
+ try {
5622
+ if (signIn.kind === "worker") {
5623
+ const paths = machinePaths(io.env);
5624
+ if (paths)
5625
+ await updateCredentialStore(paths, { [workerSessionVariable(signIn.ticket)]: null });
5626
+ await api.signOut(signIn);
5627
+ if (!quiet)
5628
+ io.stdout(`Signed out of Armada: the worker session of ${signIn.ticket} has ended.
5629
+ `);
5630
+ return;
5631
+ }
5632
+ const ended = await api.endWorkers(signIn, { project: config.project.slug, ticket, reason });
5633
+ if (ended && !quiet)
5634
+ io.stdout(`Ended ${ended === 1 ? "the worker session" : `${ended} worker sessions`} of ${ticket} on Armada.
5635
+ `);
5636
+ } catch (err) {
5637
+ 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
5638
+ `);
5639
+ }
5640
+ }
5641
+
5642
+ // src/inbox.ts
5643
+ var DEFAULT_WAIT_SECONDS = 300;
5644
+ async function ask(io, config, credentials, a) {
5645
+ const [positional, ...extra] = a.rest;
5646
+ if (extra.length)
5647
+ throw new UsageError(`unexpected argument ${extra[0]}; quote the question`);
5648
+ const fromOption = await readMessage(io, a.options);
5649
+ if (positional !== undefined && fromOption !== null)
5650
+ throw new UsageError("give the question once: as an argument, --message or --message-file");
5651
+ const question = positional ?? fromOption;
5652
+ if (!question?.trim())
5653
+ throw new UsageError('ask needs a question: armada ask "<question, the options, your recommendation>"');
5654
+ const options = (a.options.options ?? "").split("|").map((o) => o.trim()).filter(Boolean);
5655
+ const ticket = currentTicket(io, config, a.options.ticket, credentials.workerTickets);
5656
+ return withContext(io, config, credentials, a.json, (ctx) => askCoordinator(ctx, { ticket, question, options }));
5657
+ }
5658
+ async function answer(io, config, credentials, a) {
5659
+ const note = a.options.note === "true";
5660
+ const [target, positional, ...extra] = a.rest;
5661
+ const usage = note ? 'armada answer --note <ticket> "<message>"' : 'armada answer <item or ticket> "<answer>"';
5662
+ if (!target)
5663
+ throw new UsageError(`answer needs a target: ${usage}`);
5664
+ if (extra.length)
5665
+ throw new UsageError(`unexpected argument ${extra[0]}; quote the ${note ? "message" : "answer"}`);
5666
+ const fromOption = await readMessage(io, a.options);
5667
+ if (positional !== undefined && fromOption !== null)
5668
+ throw new UsageError("give the text once: as an argument, --message or --message-file");
5669
+ const text = positional ?? fromOption;
5670
+ if (!text?.trim())
5671
+ throw new UsageError(`answer needs the text: ${usage}`);
5672
+ return withContext(io, config, credentials, a.json, (ctx) => answerItem(ctx, { target, text, note }));
5673
+ }
5674
+ function waitSeconds(raw) {
5675
+ if (raw === undefined)
5676
+ return DEFAULT_WAIT_SECONDS;
5677
+ const n = Number(raw);
5678
+ if (!Number.isFinite(n) || n <= 0)
5679
+ throw new UsageError(`--timeout must be a number of seconds, got "${raw}"`);
5680
+ return n;
5681
+ }
5682
+ function renderEntries(project, items) {
5683
+ if (!items.length)
5684
+ return [`Inbox of ${project}: nothing waits for you.`];
5685
+ const out = [`Inbox of ${project} (${items.length}), oldest first:`];
5686
+ for (const e of items) {
5687
+ const head = [
5688
+ e.id === null ? e.kind : `#${e.id} ${e.kind}`,
5689
+ e.ticket,
5690
+ e.author && `from ${e.author}`,
5691
+ e.request?.question && `answers #${e.request.question}`,
5692
+ e.request?.profile && `profile ${e.request.profile}`,
5693
+ e.createdAt
5694
+ ].filter(Boolean).join(" · ");
5695
+ out.push(`${e.new ? "* " : " "}${head}`, ...e.body.split(`
5696
+ `).map((l) => l ? ` ${l}` : ""));
5697
+ }
5698
+ if (items.some((e) => e.kind === "question" || e.kind === "plan"))
5699
+ out.push(`Deliver each answer in the worker's session with the runtime guide, then record it: armada answer <id> "<answer>".`);
5700
+ if (items.some((e) => e.kind === "answer-request" || e.kind === "launch-request"))
5701
+ 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>".');
5702
+ return out;
5703
+ }
5704
+ function renderInbox(r, next) {
5705
+ const out = renderEntries(r.project, r.items);
5706
+ if (r.wait?.timedOut)
5707
+ out.push(`No new item within ${r.wait.timeoutSeconds} s.`);
5708
+ else if (r.wait)
5709
+ out.push("New items are marked *.");
5710
+ out.push(next.line);
5711
+ return `${out.join(`
5712
+ `)}
5713
+ `;
5714
+ }
5715
+ async function inbox2(io, config, credentials, a) {
5716
+ if (a.rest.length)
5717
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
5718
+ const wait = a.options.wait === "true";
5719
+ if (!wait && a.options.timeout !== undefined)
5720
+ throw new UsageError("--timeout applies to --wait");
5721
+ const timeoutMs = waitSeconds(a.options.timeout) * 1000;
5722
+ requireSignIn(credentials);
5723
+ const { fleet, warning } = liveFleet(io, config, credentials);
5724
+ if (!fleet)
5725
+ throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
5726
+ const report = await checkInbox(fleet, {
5727
+ project: config.project.slug,
5728
+ coordinator: coordinatorHandle(io),
5729
+ silentAfterMinutes: config.policy.silentAfterMinutes,
5730
+ now: io.now ?? (() => new Date),
5731
+ ...wait ? { wait: { timeoutMs, sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))) } } : {}
5732
+ });
5733
+ await remember(io, report.project, shown(io, report.items, report.inFlight));
5734
+ const next = await rearmFor(io, report.project, {
5735
+ inFlight: report.inFlight,
5736
+ open: report.items.length,
5737
+ act: report.items.length > 0
5738
+ });
5739
+ io.stdout(a.json ? `${JSON.stringify({ ...report, watch: next }, null, 2)}
5740
+ ` : renderInbox(report, next));
5741
+ for (const w of report.warnings)
5742
+ io.stderr(`armada: warning: ${w}
5743
+ `);
5744
+ return 0;
5745
+ }
5746
+
5747
+ // src/watch.ts
5748
+ function coordinatorHandle(io) {
5749
+ const workspace = io.env.CONDUCTOR_WORKSPACE_ID?.trim();
5750
+ const session = io.env.CONDUCTOR_SESSION_ID?.trim();
5751
+ return io.env.ARMADA_COORDINATOR_HANDLE?.trim() || (workspace && session ? `${workspace}/${session}` : null);
5752
+ }
5753
+ var alive = (io) => io.processAlive ?? processAlive;
5754
+ async function remember(io, project, patch) {
5755
+ const paths = machinePaths(io.env);
5756
+ if (!paths)
5757
+ return;
5758
+ try {
5759
+ await updateWatchState(paths, project, patch);
5760
+ } catch (err) {
5761
+ io.stderr(`armada: warning: could not keep the watch state (${err instanceof Error ? err.message : String(err)})
5762
+ `);
5763
+ }
5764
+ }
5765
+ async function watchOf(io, project) {
5766
+ const paths = machinePaths(io.env);
5767
+ if (!paths)
5768
+ return { state: null, running: null };
5769
+ const [state, running] = await Promise.all([
5770
+ readWatchState(paths, project),
5771
+ runningWatch(paths, project, alive(io)).catch(() => null)
5772
+ ]);
5773
+ return { state, running };
5774
+ }
5775
+ async function rearmFor(io, project, o) {
5776
+ const { running } = await watchOf(io, project);
5777
+ return rearm({ ...o, running });
5778
+ }
5779
+ var now = (io) => (io.now ?? (() => new Date))();
5780
+ var shown = (io, items, inFlight) => ({
5781
+ seen: items.map(entryKey),
5782
+ ...inFlight ? { inFlight, readAt: now(io).toISOString() } : {},
5783
+ stopped: null
5784
+ });
5785
+ async function watch2(io, config, credentials, a, configPath) {
5786
+ if (a.rest.length)
5787
+ throw new UsageError(`unexpected argument ${a.rest[0]}`);
5788
+ const project = config.project.slug;
5789
+ try {
5790
+ return await watchUntil(io, config, credentials, a.json, configPath);
5791
+ } catch (err) {
5792
+ await remember(io, project, { stopped: err instanceof Error ? err.message : String(err) });
5793
+ throw err;
5794
+ }
5795
+ }
5796
+ async function watchUntil(io, config, credentials, json, configPath) {
5797
+ requireSignIn(credentials);
5798
+ const { fleet, warning } = liveFleet(io, config, credentials);
5799
+ if (!fleet)
5800
+ throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
5801
+ const project = config.project.slug;
5802
+ const paths = machinePaths(io.env);
5803
+ const pid = io.pid ?? process.pid;
5804
+ if (paths) {
5805
+ const lock = await takeWatchLock(paths, project, pid, alive(io));
5806
+ if (!lock.taken) {
5807
+ const line = `armada watch is already running for ${project} (pid ${lock.pid}): its output arrives when it ends.`;
5808
+ io.stdout(json ? `${JSON.stringify({ project, running: lock.pid, line }, null, 2)}
5809
+ ` : `${line}
5810
+ `);
5811
+ return 0;
5812
+ }
5813
+ }
5814
+ try {
5815
+ const before = paths ? await readWatchState(paths, project) : null;
5816
+ await remember(io, project, { root: dirname2(configPath), stopped: null });
5817
+ const report = await watchInbox(fleet, {
5818
+ project,
5819
+ coordinator: coordinatorHandle(io),
5820
+ silentAfterMinutes: config.policy.silentAfterMinutes,
5821
+ seen: before?.seen ?? [],
5822
+ now: io.now ?? (() => new Date),
5823
+ sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))),
5824
+ onRead: async ({ inFlight }) => {
5825
+ if (inFlight)
5826
+ await remember(io, project, { inFlight, readAt: now(io).toISOString() });
5827
+ },
5828
+ onRetry: (message) => io.stderr(`armada: warning: ${message}
5829
+ `)
5830
+ });
5831
+ await remember(io, project, shown(io, report.items, report.inFlight));
5832
+ const next = rearm({ inFlight: report.inFlight, open: report.items.length, running: null, act: true });
5833
+ if (json)
5834
+ io.stdout(`${JSON.stringify({ ...report, watch: next }, null, 2)}
5835
+ `);
5836
+ else {
5837
+ 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];
5838
+ io.stdout(`${out.join(`
5839
+ `)}
5840
+ `);
5841
+ }
5842
+ for (const w of report.warnings)
5843
+ io.stderr(`armada: warning: ${w}
5844
+ `);
5845
+ return 0;
5846
+ } finally {
5847
+ if (paths)
5848
+ await releaseWatchLock(paths, project, pid).catch(() => {});
5849
+ }
5850
+ }
5851
+ async function hookStop(io, rest, findConfig) {
5852
+ if (rest[0] !== "stop" || rest.length > 1)
5853
+ throw new UsageError(rest[0] ? `unknown hook "${rest.join(" ")}"` : "hook needs a name: armada hook stop");
5854
+ try {
5855
+ let input = {};
5856
+ try {
5857
+ input = JSON.parse(await io.readStdin?.() || "{}");
5858
+ } catch {}
5859
+ const cwd = typeof input.cwd === "string" && input.cwd ? input.cwd : io.cwd;
5860
+ const { path, text } = await findConfig({ ...io, cwd });
5861
+ const project = parseConfig(text, path).project.slug;
5862
+ const { state, running } = await watchOf(io, project);
5863
+ const d = stopHookDecision({ project, root: dirname2(path), state, watching: running, env: io.env });
5864
+ if (d.block)
5865
+ io.stdout(`${JSON.stringify({ decision: "block", reason: d.reason })}
5866
+ `);
5867
+ } catch {}
5868
+ return 0;
5869
+ }
5870
+
5871
+ // src/brief.ts
5872
+ function renderBrief(b) {
5873
+ const p = b.profile;
5874
+ const width = Math.max(...b.environment.map((v) => v.name.length + (v.value ? v.value.length + 1 : 0)));
5875
+ const out = [
5876
+ `Brief for ${b.ticket.id} — ${b.ticket.title} (${b.ticket.status})`,
5877
+ b.ticket.url,
5878
+ "",
5879
+ `Runtime: conductor (follow the armada-runtime-conductor skill to launch)`,
5880
+ `Profile: ${p ? `${p.name}: agent ${p.agent}, model ${p.model}, effort ${p.effort}${p.fastMode ? ", fast mode" : ""}` : "none declared in armada.toml"}`,
5881
+ ...b.routing ? [`Chosen by: ${b.routing.why}`] : [],
5882
+ `Repository: ${b.repository.url}`,
5883
+ `Branch: ${b.ticket.branch ?? "none suggested by Linear"} (the worker renames its workspace branch to it)`,
5884
+ `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`}`,
5885
+ "",
5886
+ "Environment to pass (values are never printed):",
5887
+ ...b.environment.map((v) => {
5888
+ const label = v.value ? `${v.name}=${v.value}` : v.name;
5889
+ const state = v.value ? "value above" : v.inShell ? "set in this shell" : v.inStore ? "in credentials file" : "NOT set in this shell";
5890
+ return ` ${label.padEnd(width)} ${v.required ? "required" : "optional"} ${state.padEnd(21)} ${v.purpose}`;
5891
+ })
5892
+ ];
5893
+ if (b.warnings.length)
5894
+ out.push("", "Warnings:", ...b.warnings.map((w) => ` - ${w}`));
5895
+ out.push("", `----- prompt (\`armada brief ${b.ticket.id} --prompt\` prints only this) -----`, "", b.prompt);
5896
+ return out.join(`
5897
+ `);
5898
+ }
5899
+ function launcher(io, config, credentials) {
5900
+ return async (ticket) => {
5901
+ const signIn = credentials.armadaSignIn;
5902
+ if (!signIn)
5903
+ return {
5904
+ reason: "launch tokens need this terminal signed in to an Armada with accounts: armada login",
5905
+ warn: false
5906
+ };
5907
+ const url = credentials.armadaApi.url;
5908
+ try {
5909
+ const t = await armadaApi({ url, ...io.fetch ? { fetch: io.fetch } : {} }).launchToken(signIn, {
5910
+ project: config.project.slug,
5911
+ ticket
5912
+ });
5913
+ const builtIn = armadaAddress(url) === armadaAddress(DEFAULT_ARMADA_API_URL);
5914
+ return { token: t.token, expiresAt: t.expiresAt, apiUrl: builtIn ? null : armadaAddress(url) };
5915
+ } catch (err) {
5916
+ if (!(err instanceof ArmadaApiError))
5917
+ throw err;
5918
+ return { reason: err.message, warn: true };
5919
+ }
5920
+ };
5921
+ }
5922
+ async function brief2(io, config, credentials, a, version) {
5923
+ const [ticket, ...extra] = a.rest;
5924
+ if (!ticket)
5925
+ throw new UsageError('brief needs a ticket: armada brief <ticket> [--profile <name> [--reason "<why>"]]');
5926
+ if (extra.length)
5927
+ throw new UsageError(`unexpected argument ${extra[0]}`);
5928
+ const promptOnly = a.options.prompt === "true";
5929
+ if (a.json && promptOnly)
5930
+ throw new UsageError("pass --json or --prompt, not both");
5931
+ const profile = a.options.profile?.trim() || null;
5932
+ const reason = a.options.reason?.trim() || null;
5933
+ if (reason && !profile)
5934
+ throw new UsageError("--reason goes with --profile: it says why the routed profile is not used");
5935
+ try {
5936
+ checkRequestedProfile(config, profile);
5937
+ } catch (err) {
5938
+ if (err instanceof ProfileError)
5939
+ throw new UsageError(err.message);
5940
+ throw err;
5941
+ }
5942
+ if (!credentials.linearApiKey)
5943
+ throw missingKey(LINEAR_KEY);
5944
+ let b;
5945
+ try {
5946
+ b = await loadBrief(config, {
5947
+ linearApiKey: credentials.linearApiKey,
5948
+ ticket: ticket.toUpperCase(),
5949
+ profile,
5950
+ reason,
5951
+ version,
5952
+ env: io.env,
5953
+ stored: STORED_KEYS.filter((k) => credentials.sources[k.name]?.kind === "store").map((k) => k.variable),
5954
+ launch: launcher(io, config, credentials),
5955
+ ...io.fetch ? { fetch: io.fetch } : {},
5956
+ ...io.now ? { now: io.now } : {}
5957
+ });
5958
+ } catch (err) {
5959
+ if (err instanceof BriefError)
5960
+ throw new UsageError(err.message);
5961
+ throw err;
5962
+ }
5963
+ const project = config.project.slug;
5964
+ const known = (await watchOf(io, project)).state?.inFlight ?? [];
5965
+ const inFlight = [...new Set([...known, b.ticket.id])].sort((x, y) => x.localeCompare(y, "en", { numeric: true }));
5966
+ await remember(io, project, { inFlight, readAt: (io.now ?? (() => new Date))().toISOString() });
5967
+ if (promptOnly) {
5968
+ io.stdout(b.prompt);
5969
+ for (const w of b.warnings)
5970
+ io.stderr(`armada: warning: ${w}
5971
+ `);
5972
+ return 0;
5973
+ }
5974
+ const next = await rearmFor(io, project, { inFlight, open: null });
5975
+ if (a.json)
5976
+ io.stdout(`${JSON.stringify({ ...b, watch: next }, null, 2)}
5977
+ `);
5978
+ else
5979
+ io.stdout(`${renderBrief(b)}
5980
+
5981
+ ----- once launched -----
5982
+ ${next.line}
5983
+ `);
5984
+ return 0;
5985
+ }
5986
+
5987
+ // src/repo.ts
5988
+ import { lstat, mkdir as mkdir2, readdir, readFile as readFile2, readlink, rm as rm2, symlink, writeFile as writeFile2 } from "node:fs/promises";
5989
+ import { dirname as dirname3, join as join2, relative, sep } from "node:path";
5990
+ var absent = (err) => {
5991
+ const code = err.code;
5992
+ return code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR";
5993
+ };
5994
+ async function collect(base, dir, out) {
5995
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
5996
+ const full = join2(dir, entry.name);
5997
+ if (entry.isDirectory()) {
5998
+ if (entry.name !== ".git" && entry.name !== "node_modules")
5999
+ await collect(base, full, out);
6000
+ } else if (entry.isFile())
6001
+ out.push({ path: relative(base, full).split(sep).join("/"), content: await readFile2(full) });
6002
+ }
6003
+ }
6004
+ function fsRepoView(root) {
6005
+ return {
6006
+ readFile: (path) => readFile2(join2(root, path), "utf8").catch((err) => {
6007
+ if (absent(err))
6008
+ return null;
6009
+ throw err;
6010
+ }),
6011
+ readLink: (path) => readlink(join2(root, path)).catch((err) => {
6012
+ if (absent(err) || err.code === "EINVAL")
6013
+ return null;
6014
+ throw err;
6015
+ }),
6016
+ readFolder: async (path) => {
6017
+ const out = [];
6018
+ try {
6019
+ await collect(join2(root, path), join2(root, path), out);
6020
+ } catch (err) {
6021
+ if (absent(err))
6022
+ return null;
6023
+ throw err;
6024
+ }
6025
+ return out;
6026
+ }
6027
+ };
6028
+ }
6029
+ async function assertNoLinkedParent(root, path) {
6030
+ const parts = path.split("/").slice(0, -1);
6031
+ for (let k = 1;k <= parts.length; k++) {
6032
+ const parent = parts.slice(0, k).join("/");
6033
+ if ((await lstat(join2(root, parent)).catch(() => null))?.isSymbolicLink())
6034
+ throw new CommandError(`${parent} is a link; Armada does not write through it. Replace it with a folder first.`);
6035
+ }
5327
6036
  }
5328
6037
  async function applyPlan(root, plan) {
5329
6038
  for (const path of [...plan.removes, ...plan.writes.map((w) => w.path), ...plan.links.map((l) => l.path)])
@@ -5332,12 +6041,12 @@ async function applyPlan(root, plan) {
5332
6041
  await rm2(join2(root, path), { force: true });
5333
6042
  for (const w of plan.writes) {
5334
6043
  const full = join2(root, w.path);
5335
- await mkdir2(dirname(full), { recursive: true });
5336
- await writeFile(full, w.content);
6044
+ await mkdir2(dirname3(full), { recursive: true });
6045
+ await writeFile2(full, w.content);
5337
6046
  }
5338
6047
  for (const l of plan.links) {
5339
6048
  const full = join2(root, l.path);
5340
- await mkdir2(dirname(full), { recursive: true });
6049
+ await mkdir2(dirname3(full), { recursive: true });
5341
6050
  if (await lstat(full).catch(() => null))
5342
6051
  await rm2(full, { recursive: true, force: true });
5343
6052
  await symlink(l.target, full);
@@ -5418,390 +6127,111 @@ function keyFileChecks(machine, credentials) {
5418
6127
  return [
5419
6128
  ...checks,
5420
6129
  {
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
- `);
6130
+ id: "local-keys",
6131
+ level: "warning",
6132
+ message: `${store.path} still holds ${unneeded.join(", ")}, which Armada now gives this terminal: ${unneeded.length === 1 ? "it is" : "they are"} no longer needed`,
6133
+ fix: `\`armada auth logout\` removes ${unneeded.length === 1 ? "it" : "them"} from this machine; the sign-in to Armada stays`
6134
+ }
6135
+ ];
5596
6136
  }
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);
6137
+ async function labelChecks(io, root, credentials) {
6138
+ const text = await fsRepoView(root).readFile(CONFIG_FILE);
5604
6139
  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");
6140
+ return [];
6141
+ let config;
5628
6142
  try {
5629
- checkRequestedProfile(config, profile);
6143
+ config = parseConfig(text, CONFIG_FILE);
5630
6144
  } catch (err) {
5631
- if (err instanceof ProfileError)
5632
- throw new UsageError(err.message);
6145
+ if (err instanceof ConfigError)
6146
+ return [];
5633
6147
  throw err;
5634
6148
  }
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 } : {} });
6149
+ const { linearApiKey } = credentials;
6150
+ if (!linearApiKey)
6151
+ return [
6152
+ {
6153
+ id: "labels",
6154
+ level: "warning",
6155
+ message: `Linear labels not checked: no Linear key (${LINEAR_KEY.variable})`,
6156
+ fix: `\`armada login\` to an Armada that keeps your organization's keys, or set ${LINEAR_KEY.variable}, then run doctor again`
6157
+ }
6158
+ ];
5680
6159
  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
- `);
6160
+ const state = await readLabels(config, { apiKey: linearApiKey, ...io.fetch ? { fetch: io.fetch } : {} });
6161
+ return checkLabels(state);
5695
6162
  } 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
- `);
6163
+ return [
6164
+ {
6165
+ id: "labels",
6166
+ level: "warning",
6167
+ message: `Linear labels not checked: ${err instanceof Error ? err.message : String(err)}`,
6168
+ fix: "run doctor again once Linear answers"
6169
+ }
6170
+ ];
5698
6171
  }
5699
6172
  }
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;
6173
+ async function buildDoctor(io, armadaVersion) {
6174
+ const root = (io.exec ? await gitRoot(io.exec, io.cwd) : null) ?? io.cwd;
6175
+ const { machine, credentials } = await loadCredentials(io);
6176
+ const checks = [
6177
+ ...await checkRepository(fsRepoView(root), armadaVersion),
6178
+ ...await signInChecks(io, credentials),
6179
+ ...keyFileChecks(machine, credentials),
6180
+ ...await labelChecks(io, root, credentials)
6181
+ ];
6182
+ return {
6183
+ schemaVersion: 1,
6184
+ root,
6185
+ armadaVersion,
6186
+ checks,
6187
+ errors: checks.filter((c) => c.level === "error").length,
6188
+ warnings: checks.filter((c) => c.level === "warning").length
6189
+ };
5740
6190
  }
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>".');
6191
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
6192
+ function renderDoctor(r) {
6193
+ const lines = [`Armada ${r.armadaVersion} doctor · ${r.root}`, ""];
6194
+ for (const c of r.checks) {
6195
+ const [first, ...more] = c.message.split(`
6196
+ `);
6197
+ lines.push(` ${c.level.padEnd(8)} ${first}`);
6198
+ for (const m of more)
6199
+ lines.push(` ${m}`);
6200
+ if (c.fix)
6201
+ lines.push(` fix: ${c.fix}`);
5763
6202
  }
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(`
6203
+ lines.push("");
6204
+ if (!r.errors && !r.warnings)
6205
+ lines.push("Everything Armada needs is in place.");
6206
+ else
6207
+ lines.push(`${plural(r.errors, "error")}, ${plural(r.warnings, "warning")}.${r.errors ? " Workers cannot be launched until the errors are fixed." : ""}`);
6208
+ const errors = r.checks.filter((c) => c.level === "error");
6209
+ if (errors.length)
6210
+ 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}`);
6211
+ return `${lines.join(`
5769
6212
  `)}
5770
6213
  `;
5771
6214
  }
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;
6215
+ async function doctor(io, json, armadaVersion) {
6216
+ const report = await buildDoctor(io, armadaVersion);
6217
+ io.stdout(json ? `${JSON.stringify(report, null, 2)}
6218
+ ` : renderDoctor(report));
6219
+ return report.errors ? 1 : 0;
5799
6220
  }
5800
6221
 
5801
6222
  // src/init.ts
5802
6223
  import { mkdtemp, realpath, rm as rm3 } from "node:fs/promises";
5803
6224
  import { tmpdir } from "node:os";
5804
6225
  import { join as join3 } from "node:path";
6226
+ 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] ";
6227
+ async function wantsStopHook(io, opts) {
6228
+ if (opts.stopHook !== null)
6229
+ return opts.stopHook;
6230
+ if (!io.interactive || !io.prompt)
6231
+ return true;
6232
+ const answer = (await io.prompt(STOP_HOOK_QUESTION, { hidden: false }))?.trim().toLowerCase();
6233
+ return answer === undefined ? false : answer === "" || answer.startsWith("y");
6234
+ }
5805
6235
  var initBranch = (version) => `armada/init-${version}`;
5806
6236
  async function defaultBranch(exec, root) {
5807
6237
  const out = await sh(exec, root, "git", ["ls-remote", "--symref", "origin", "HEAD"]);
@@ -5864,6 +6294,10 @@ function prText(plan, version) {
5864
6294
  ...plan.writes.map((w) => `- write \`${w.path}\``),
5865
6295
  ...plan.links.map((l) => `- link \`${l.path}\` → \`${l.target}\``),
5866
6296
  ...plan.removes.map((p) => `- remove \`${p}\``),
6297
+ ...plan.stopHook ? [
6298
+ "",
6299
+ `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.`
6300
+ ] : [],
5867
6301
  "",
5868
6302
  "Once merged, `armada doctor` passes on the default branch.",
5869
6303
  "",
@@ -5896,7 +6330,13 @@ async function init(io, opts) {
5896
6330
  await sh(exec, root, "git", ["worktree", "add", "--quiet", "--detach", checkout, baseSha]);
5897
6331
  const { config, text, source } = await resolveConfig(exec, root, checkout, opts);
5898
6332
  const view = fsRepoView(checkout);
5899
- const plan = await planSetup(view, { armadaVersion: opts.armadaVersion, configText: text });
6333
+ let plan = await planSetup(view, {
6334
+ armadaVersion: opts.armadaVersion,
6335
+ configText: text,
6336
+ stopHook: opts.stopHook !== false
6337
+ });
6338
+ if (plan.stopHook && !await wantsStopHook(io, opts))
6339
+ plan = await planSetup(view, { armadaVersion: opts.armadaVersion, configText: text, stopHook: false });
5900
6340
  const log = (line) => io.stdout(`${line}
5901
6341
  `);
5902
6342
  log(`Armada ${opts.armadaVersion} · ${config.github.repository} · ${config.tracker.programRoot}`);
@@ -5967,6 +6407,8 @@ async function init(io, opts) {
5967
6407
  log(`Installs: ${plan.installed.join(", ")}`);
5968
6408
  if (plan.updated.length)
5969
6409
  log(`Updates: ${plan.updated.join(", ")}`);
6410
+ if (plan.stopHook)
6411
+ log(`Adds the Claude Code stop hook to ${CLAUDE_SETTINGS}: this repository's settings, not your user settings.`);
5970
6412
  }
5971
6413
  const { fleet, warning } = liveFleet(io, config, credentials);
5972
6414
  if (!fleet)
@@ -5984,7 +6426,7 @@ async function init(io, opts) {
5984
6426
  import { randomUUID } from "node:crypto";
5985
6427
  import { rm as rm4 } from "node:fs/promises";
5986
6428
  import { hostname, tmpdir as tmpdir2 } from "node:os";
5987
- import { dirname as dirname2, join as join4 } from "node:path";
6429
+ import { dirname as dirname4, join as join4 } from "node:path";
5988
6430
  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
6431
  var tail = (text, lines = 30) => text.trimEnd().split(`
5990
6432
  `).slice(-lines).join(`
@@ -6131,7 +6573,7 @@ async function merge2(io, config, credentials, a, configPath) {
6131
6573
  if (!exec)
6132
6574
  throw new UsageError("armada merge needs to run git and gh");
6133
6575
  const linearApiKey = credentials.linearApiKey;
6134
- const repoDir = dirname2(configPath);
6576
+ const repoDir = dirname4(configPath);
6135
6577
  const fetchOpt = io.fetch ? { fetch: io.fetch } : {};
6136
6578
  const gh = { token, repository: config.github.repository, ...fetchOpt };
6137
6579
  const linearOpts = { apiKey: linearApiKey, labels: config.tracker.labels, ...fetchOpt };
@@ -6173,8 +6615,16 @@ async function merge2(io, config, credentials, a, configPath) {
6173
6615
  dryRun: !!a.options["dry-run"],
6174
6616
  noLock: !!a.options["no-lock"]
6175
6617
  });
6176
- io.stdout(a.json ? `${JSON.stringify(o, null, 2)}
6177
- ` : render(o));
6618
+ const project = config.project.slug;
6619
+ const coordinator = coordinatorHandle(io);
6620
+ const known = (await watchOf(io, project)).state?.inFlight ?? null;
6621
+ 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;
6622
+ if (o.merged)
6623
+ await remember(io, project, { inFlight, readAt: (io.now ?? (() => new Date))().toISOString() });
6624
+ const next = await rearmFor(io, project, { inFlight, open: null });
6625
+ io.stdout(a.json ? `${JSON.stringify({ ...o, watch: next }, null, 2)}
6626
+ ` : `${render(o)}${next.line}
6627
+ `);
6178
6628
  for (const w of o.warnings)
6179
6629
  io.stderr(`armada: warning: ${w}
6180
6630
  `);
@@ -6337,10 +6787,12 @@ var COMMAND_HELP = {
6337
6787
  doctor: ` doctor What this repository lacks to be run by Armada, with the fix for each,
6338
6788
  and whether this terminal is signed in to Armada
6339
6789
  `,
6340
- init: ` init [--program-root <ISSUE-ID>] [--name <name>] [--slug <slug>]
6790
+ init: ` init [--program-root <ISSUE-ID>] [--name <name>] [--slug <slug>] [--no-stop-hook]
6341
6791
  Open one pull request that installs or updates it all, create the
6342
6792
  missing Linear labels and register the project. The options are for
6343
- a repository without armada.toml (Linear issue at the program root)
6793
+ a repository without armada.toml (Linear issue at the program root).
6794
+ It asks before adding the Claude Code stop hook to the repository's
6795
+ .claude/settings.json (yes without a terminal); --no-stop-hook skips it
6344
6796
  `,
6345
6797
  claim: ` claim <ticket> --runtime <name> --handle <id> [--branch <name>]
6346
6798
  [--profile <name> [--reason <why>]]
@@ -6366,8 +6818,15 @@ var COMMAND_HELP = {
6366
6818
  inbox: ` inbox [--wait [--timeout <seconds>]]
6367
6819
  Coordinator: open questions, plans, requests, hand-backs and silent workers,
6368
6820
  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
6821
+ when a new item arrives or after --timeout (default 300 s); \`armada watch\`
6822
+ is the way to keep listening. Needs a sign-in to Armada
6823
+ `,
6824
+ watch: ` watch Coordinator: run in the background while workers are in flight. Waits
6825
+ until something needs you (a question, plan, request, hand-back or silent
6826
+ worker you have not seen), prints it and exits; exits "nothing to watch"
6827
+ when no worker is in flight and nothing is open. Armada being down or a
6828
+ command time limit does not end it: it keeps asking. One per project on
6829
+ this machine. Needs a sign-in to Armada
6371
6830
  `,
6372
6831
  answer: ` answer <item|ticket> "<answer>"
6373
6832
  Coordinator: record an answer already delivered in the worker's
@@ -6391,6 +6850,11 @@ var COMMAND_HELP = {
6391
6850
  default_profile; --profile overrides it, with --reason when it differs.
6392
6851
  Signed in to Armada, the prompt starts with a one-time launch token, so
6393
6852
  the worker needs no key. --prompt prints only the prompt, for \`--message-file -\`
6853
+ `,
6854
+ hook: ` hook stop Claude Code's Stop hook, installed by \`armada init\`: a coordinator
6855
+ cannot end its turn while workers are in flight and no \`armada watch\`
6856
+ runs for the project in this checkout. Reads only local files;
6857
+ ARMADA_STOP_HOOK=off turns it off
6394
6858
  `,
6395
6859
  login: ` login Sign this terminal in to Armada: confirm the code it shows in the browser
6396
6860
  login --api-key Sign a headless coordinator in with an organization API key, read from a
@@ -6409,7 +6873,18 @@ var COMMAND_HELP = {
6409
6873
  `
6410
6874
  };
6411
6875
  var TICKET_OPTION = new Set(["report", "release", "ask", "merge"]);
6412
- var CONFIG_OPTION = new Set(["status", "claim", "report", "release", "ask", "inbox", "answer", "merge", "brief"]);
6876
+ var CONFIG_OPTION = new Set([
6877
+ "status",
6878
+ "claim",
6879
+ "report",
6880
+ "release",
6881
+ "ask",
6882
+ "inbox",
6883
+ "watch",
6884
+ "answer",
6885
+ "merge",
6886
+ "brief"
6887
+ ]);
6413
6888
  var JSON_OPTION = new Set([...CONFIG_OPTION, "doctor", "auth", "whoami"]);
6414
6889
  var TICKET_HELP = ` --ticket <id> Ticket for report, release and ask (default ARMADA_TICKET, then the git
6415
6890
  branch) and for merge (default: the ticket the PR branch names)
@@ -6434,14 +6909,15 @@ Keys (the environment first, then Armada when signed in, then the file):
6434
6909
 
6435
6910
  The fleet's live data (claims, reports, the inbox, the merge lock, the project
6436
6911
  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.
6912
+ init, inbox, watch and status --all need a sign-in; elsewhere, signed out, live
6913
+ activity is not recorded and Linear stays the record.
6439
6914
 
6440
6915
  Files:
6441
6916
  $XDG_CONFIG_HOME/armada (default ~/.config/armada)
6442
6917
  credentials KEY=value lines, mode 0600, written by \`armada auth login\` and
6443
6918
  \`armada login\` (the sign-in: ARMADA_SESSION_TOKEN or ARMADA_API_KEY)
6444
6919
  config.toml personal defaults: language, [dashboard] url, [api] url
6920
+ watch/<project>.* the project's watch: its lock, what you were shown, who is in flight
6445
6921
  `;
6446
6922
  function commandHelp(command) {
6447
6923
  const block = Object.hasOwn(COMMAND_HELP, command) ? COMMAND_HELP[command] : undefined;
@@ -6480,7 +6956,7 @@ var VALUE_OPTIONS = [
6480
6956
  "launch-token",
6481
6957
  "api-url"
6482
6958
  ];
6483
- var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key"];
6959
+ var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key", "no-stop-hook"];
6484
6960
  var COMMAND_OPTIONS = {
6485
6961
  claim: ["runtime", "handle", "branch", "profile", "reason"],
6486
6962
  report: ["ticket", "message", "message-file", "pr", "sha"],
@@ -6488,7 +6964,7 @@ var COMMAND_OPTIONS = {
6488
6964
  ask: ["ticket", "options", "message", "message-file"],
6489
6965
  inbox: ["wait", "timeout"],
6490
6966
  answer: ["note", "message", "message-file"],
6491
- init: ["program-root", "name", "slug"],
6967
+ init: ["program-root", "name", "slug", "no-stop-hook"],
6492
6968
  merge: ["ticket", "dry-run", "no-lock"],
6493
6969
  brief: ["profile", "reason", "prompt"],
6494
6970
  login: ["api-key", "launch-token", "api-url"]
@@ -6544,12 +7020,12 @@ async function findConfig(io, explicit, command = "status") {
6544
7020
  throw new UsageError(`${path} does not exist`, `armada ${command} --config <file>, with the path of an ${CONFIG_FILE}`);
6545
7021
  return { path, text };
6546
7022
  }
6547
- for (let dir = resolve(io.cwd);; dir = dirname3(dir)) {
7023
+ for (let dir = resolve(io.cwd);; dir = dirname5(dir)) {
6548
7024
  const path = join5(dir, CONFIG_FILE);
6549
7025
  const text = await io.readFile(path);
6550
7026
  if (text !== null)
6551
7027
  return { path, text };
6552
- if (dirname3(dir) === dir)
7028
+ if (dirname5(dir) === dir)
6553
7029
  break;
6554
7030
  }
6555
7031
  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 +7116,13 @@ async function run(argv, io) {
6640
7116
  const { credentials } = await loadCredentials(io, scope ? { worker: scope } : {});
6641
7117
  return await worker(io, config, credentials, args);
6642
7118
  }
7119
+ if (args.command === "watch") {
7120
+ const { path, text } = await findConfig(io, args.config, "watch");
7121
+ const { credentials } = await loadCredentials(io);
7122
+ return await watch2(io, parseConfig(text, path), credentials, args, path);
7123
+ }
7124
+ if (args.command === "hook")
7125
+ return await hookStop(io, args.rest, (at) => findConfig(at, null, "hook"));
6643
7126
  if (args.command === "merge") {
6644
7127
  const { path, text } = await findConfig(io, args.config, "merge");
6645
7128
  const { credentials } = await loadCredentials(io);
@@ -6664,7 +7147,8 @@ async function run(argv, io) {
6664
7147
  armadaVersion: version,
6665
7148
  programRoot: args.options["program-root"] ?? null,
6666
7149
  name: args.options.name ?? null,
6667
- slug: args.options.slug ?? null
7150
+ slug: args.options.slug ?? null,
7151
+ stopHook: args.options["no-stop-hook"] === "true" ? false : null
6668
7152
  });
6669
7153
  }
6670
7154
  if (args.command === "login" || args.command === "logout" || args.command === "whoami") {