@the-vibe-company/armada 0.1.13 → 0.1.15

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 +24 -3
  2. package/dist/armada.js +843 -460
  3. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -9,133 +9,6 @@ import { isatty } from "node:tty";
9
9
  // src/cli.ts
10
10
  import { dirname as dirname3, join as join5, resolve } from "node:path";
11
11
 
12
- // ../core/src/model.ts
13
- var CLOSED = ["completed", "canceled"];
14
- var NOT_STARTED = ["triage", "backlog", "unstarted"];
15
- var isDone = (i) => i.statusType === "completed";
16
- var isClosed = (i) => CLOSED.includes(i.statusType);
17
- var isStarted = (i) => i.statusType === "started";
18
- var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
19
- var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
20
- function buildModel(issues, rootId) {
21
- const byId = new Map(issues.map((i) => [i.id, i]));
22
- const root = byId.get(rootId);
23
- if (!root)
24
- throw new Error(`program root ${rootId} is not among the issues read`);
25
- const childrenOf = new Map;
26
- for (const i of issues) {
27
- if (!i.parentId || !byId.has(i.parentId))
28
- continue;
29
- childrenOf.set(i.parentId, [...childrenOf.get(i.parentId) ?? [], i]);
30
- }
31
- const program = [];
32
- const walk = (id, seen) => {
33
- for (const c of childrenOf.get(id) ?? []) {
34
- if (seen.has(c.id))
35
- continue;
36
- seen.add(c.id);
37
- program.push(c);
38
- walk(c.id, seen);
39
- }
40
- };
41
- walk(root.id, new Set([root.id]));
42
- const specs = (childrenOf.get(root.id) ?? []).flatMap((issue) => {
43
- const m = issue.title.trim().match(SPEC_TITLE);
44
- return m?.[1] && m[3] ? [{ issue, ordinal: Number(m[1]), name: m[3].trim() }] : [];
45
- }).sort((a, b) => a.ordinal - b.ordinal || a.issue.createdAt.localeCompare(b.issue.createdAt));
46
- const specById = new Map(specs.map((s) => [s.issue.id, s]));
47
- const specOf = (id) => {
48
- const seen = new Set;
49
- for (let cur = byId.get(id);cur && !seen.has(cur.id); cur = cur.parentId ? byId.get(cur.parentId) : undefined) {
50
- seen.add(cur.id);
51
- const s = specById.get(cur.id);
52
- if (s)
53
- return s;
54
- }
55
- return null;
56
- };
57
- const isLeaf = (i) => !childrenOf.get(i.id)?.length && !specById.has(i.id);
58
- const openBlockersOf = (i) => i.blockedBy.filter((b) => !isClosed(byId.get(b.id) ?? b)).map((b) => b.id);
59
- const stateOf = (i) => {
60
- if (isDone(i))
61
- return "done";
62
- if (i.statusType === "canceled")
63
- return "canceled";
64
- if (isStarted(i))
65
- return "active";
66
- return openBlockersOf(i).length ? "blocked" : "frontier";
67
- };
68
- return { root, byId, childrenOf, program, specs, specOf, isLeaf, openBlockersOf, stateOf };
69
- }
70
- function longestPathLevels(nodes) {
71
- const byId = new Map(nodes.map((n) => [n.id, n]));
72
- const level = new Map;
73
- const visiting = new Set;
74
- const visit = (id) => {
75
- const known = level.get(id);
76
- if (known !== undefined)
77
- return known;
78
- if (visiting.has(id))
79
- return 0;
80
- visiting.add(id);
81
- const blockers = (byId.get(id)?.blockedBy ?? []).map((b) => b.id).filter((b) => byId.has(b));
82
- const l = blockers.length ? Math.max(...blockers.map(visit)) + 1 : 0;
83
- visiting.delete(id);
84
- level.set(id, l);
85
- return l;
86
- };
87
- for (const n of nodes)
88
- visit(n.id);
89
- return level;
90
- }
91
- function criticalPath(m, parentId) {
92
- const nodes = m.childrenOf.get(parentId) ?? [];
93
- const level = longestPathLevels(nodes);
94
- const remaining = nodes.filter((n) => !isClosed(n));
95
- const remIds = new Set(remaining.map((n) => n.id));
96
- const len = new Map;
97
- const prev = new Map;
98
- const order = [...remaining].sort((a, b) => (level.get(a.id) ?? 0) - (level.get(b.id) ?? 0));
99
- for (const n of order) {
100
- let best = 0;
101
- let bestPrev = null;
102
- for (const { id } of n.blockedBy) {
103
- if (!remIds.has(id))
104
- continue;
105
- const l = len.get(id) ?? 0;
106
- if (l > best) {
107
- best = l;
108
- bestPrev = id;
109
- }
110
- }
111
- len.set(n.id, best + 1);
112
- prev.set(n.id, bestPrev);
113
- }
114
- let tail = null;
115
- let tailLen = 0;
116
- for (const [id, l] of len)
117
- if (l > tailLen || l === tailLen && tail && id > tail) {
118
- tail = id;
119
- tailLen = l;
120
- }
121
- if (tailLen < 2)
122
- return [];
123
- const path = [];
124
- for (let cur = tail;cur; cur = prev.get(cur) ?? null) {
125
- const issue = m.byId.get(cur);
126
- if (issue)
127
- path.unshift(issue);
128
- }
129
- return path;
130
- }
131
- function criticalIds(m) {
132
- const out = new Set;
133
- for (const parent of m.childrenOf.keys())
134
- for (const i of criticalPath(m, parent))
135
- out.add(i.id);
136
- return out;
137
- }
138
-
139
12
  // ../core/src/types.ts
140
13
  var LABEL_PHASES = [
141
14
  "planning",
@@ -146,256 +19,77 @@ var LABEL_PHASES = [
146
19
  "ready-to-merge"
147
20
  ];
148
21
 
149
- // ../core/src/fleet.ts
150
- var MIN = 60000;
151
- var NEEDS_HUMAN = ["awaiting-approval", "blocked", "ready-to-merge"];
152
- var PHASE_RANK = {
153
- merged: 0,
154
- "ready-to-merge": 1,
155
- shipping: 2,
156
- implementing: 3,
157
- "awaiting-approval": 4,
158
- planning: 5,
159
- blocked: 6,
160
- released: 7
161
- };
162
- var PLAN_HINT = /\b(plan|objective|assumptions|awaiting (?:plan )?approval)\b/i;
163
- function commentsFor(comments, id) {
164
- return comments.filter((c) => c.issueId === id).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
22
+ // ../core/src/linear.ts
23
+ var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
24
+ var MAX_DEPTH = 8;
25
+ var COMMENT_BATCH = 25;
26
+ var MAX_COMMENTS = 100;
27
+ var MORE_PAGE = 100;
28
+ var REQUEST_TIMEOUT_MS = 30000;
29
+
30
+ class LinearError extends Error {
31
+ transport;
32
+ name = "LinearError";
33
+ constructor(message, transport = false) {
34
+ super(message);
35
+ this.transport = transport;
36
+ }
165
37
  }
166
- function commentUrl(issue, c) {
167
- return `${issue.url}#comment-${c.id.slice(0, 8)}`;
38
+ var PHASES = [...LABEL_PHASES, "released", "merged"];
39
+ var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
40
+ var firstLine = (body) => (body.split(`
41
+ `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
42
+ var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
43
+ function parseStatusLine(body) {
44
+ const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
45
+ if (!m?.[1])
46
+ return null;
47
+ const raw = m[1].toLowerCase();
48
+ const phase = LEGACY[raw] ?? raw;
49
+ const summary = (m[2] ?? "").trim();
50
+ if (COORDINATOR_RECORD.test(summary))
51
+ return null;
52
+ return PHASES.includes(phase) ? { phase, summary } : null;
168
53
  }
169
- function primaryPr(issue) {
170
- const byNewest = [...issue.prs].sort((a, b) => b.number - a.number);
171
- return byNewest.find((p) => p.state === "open") ?? byNewest[0] ?? null;
54
+ var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
55
+ var trimMarks = (v) => {
56
+ const t = v.trim();
57
+ return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
58
+ };
59
+ function parseClaim(body, at, author) {
60
+ const line = body.split(`
61
+ `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
62
+ if (!line)
63
+ return null;
64
+ const field = (k) => {
65
+ const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
66
+ return v && trimMarks(v) || null;
67
+ };
68
+ return {
69
+ runtime: field("runtime"),
70
+ session: field("session"),
71
+ branch: field("branch|branche"),
72
+ startedAt: field("started|démarré|demarre"),
73
+ profile: field("profile"),
74
+ at,
75
+ author
76
+ };
172
77
  }
173
- function activeClaims(comments) {
174
- const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
175
- let claims = [];
176
- for (const c of asc) {
177
- if (c.status?.phase === "released")
178
- claims = [];
179
- if (c.claim)
180
- claims.push(c.claim);
181
- }
182
- return claims;
78
+ function excerpt(markdown, max = 240) {
79
+ const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
80
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
183
81
  }
184
- var latest = (...xs) => xs.filter((x) => !!x).reduce((a, b) => b > a ? b : a, "");
185
- function inferPhase(pr, comments) {
186
- if (pr?.state === "open")
187
- return pr.ci === "success" && pr.mergeable !== "CONFLICTING" ? "ready-to-merge" : "shipping";
188
- if (comments.some((c) => PLAN_HINT.test(c.excerpt.slice(0, 120))))
189
- return "awaiting-approval";
190
- return "planning";
82
+ function parsePullRequestUrl(url, title = "") {
83
+ const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
84
+ return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
191
85
  }
192
- var ENDS_WORK = ["release", "merge"];
193
- var livePhase = (e) => e.kind === "release" ? "released" : LABEL_PHASES.find((p) => p === e.phase) ?? null;
194
- function freshEvent(issueId, opts) {
195
- const e = opts.live?.events[issueId];
196
- return e && opts.live && e.at > opts.live.after ? e : null;
197
- }
198
- function buildLane(m, allComments, issue, opts) {
199
- const comments = commentsFor(allComments, issue.id);
200
- const withStatus = comments.find((c) => c.status && c.status.phase !== "released");
201
- const pr = primaryPr(issue);
202
- const claims = activeClaims(comments);
203
- let phase;
204
- let phaseSource;
205
- if (issue.agentPhase) {
206
- phase = issue.agentPhase;
207
- phaseSource = "label";
208
- } else if (withStatus?.status) {
209
- phase = withStatus.status.phase;
210
- phaseSource = "status-line";
211
- } else {
212
- phase = inferPhase(pr, comments);
213
- phaseSource = "inferred";
214
- }
215
- const fresh = freshEvent(issue.id, opts);
216
- const freshPhase = fresh ? livePhase(fresh) : null;
217
- const trackerPhase = phase;
218
- if (freshPhase && freshPhase !== "released") {
219
- phase = freshPhase;
220
- phaseSource = "live";
221
- }
222
- const shippingPhase = phase === "shipping" || phase === "ready-to-merge";
223
- if (pr?.state === "merged" && !isDone(issue) && (shippingPhase || phaseSource === "status-line" || phaseSource === "inferred"))
224
- phase = "merged";
225
- let announcing;
226
- for (const c of comments) {
227
- if (!c.status || c.status.phase === "released")
228
- continue;
229
- if (c.status.phase !== phase)
230
- break;
231
- announcing = c;
232
- }
233
- const since = (fresh && phaseSource === "live" && phase !== trackerPhase ? fresh.at : undefined) ?? announcing?.createdAt ?? (fresh && phaseSource === "live" ? fresh.at : undefined) ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
234
- const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt, fresh?.at);
235
- const lastReport = latest(comments.find((c) => c.status || c.claim)?.createdAt, claims.at(-1)?.at, opts.lastEvents?.[issue.id], fresh?.at) || null;
236
- const openBlockers = m.openBlockersOf(issue);
237
- const agent = issue.delegate ?? issue.assignee;
238
- const flags = [];
239
- const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
240
- const alive = lastReport ?? lastUpdate;
241
- if (!waitingOnHuman && opts.now - Date.parse(alive) > opts.silentAfterMinutes * MIN)
242
- flags.push("silent");
243
- if (pr?.state === "open" && pr.ci === "failure")
244
- flags.push("ci-failing");
245
- if (pr?.state === "open" && pr.mergeable === "CONFLICTING")
246
- flags.push("conflict");
247
- const runtimes = new Set(claims.map((c) => c.runtime).filter(Boolean));
248
- const claimRuntime = claims[0]?.runtime;
249
- if (claims.length > 1 || runtimes.size > 1 || issue.agentRuntime && claimRuntime && claimRuntime !== issue.agentRuntime)
250
- flags.push("double-claim");
251
- if (openBlockers.length)
252
- flags.push("started-before-blockers");
253
- if (!agent && phaseSource !== "live")
254
- flags.push("no-assignee");
255
- if (!issue.agentPhase && phaseSource !== "live")
256
- flags.push("no-phase-label");
257
- const spec = m.specOf(issue.id);
258
- return {
259
- issue,
260
- spec: spec ? `Spec ${spec.ordinal}` : null,
261
- phase,
262
- phaseSource,
263
- runtime: issue.agentRuntime ?? claimRuntime ?? fresh?.runtime ?? opts.live?.handles?.[issue.id]?.runtime ?? null,
264
- handle: opts.live?.handles?.[issue.id]?.handle ?? claims[0]?.session ?? fresh?.handle ?? null,
265
- claim: claims[0] ?? null,
266
- agent,
267
- since,
268
- lastUpdate,
269
- lastReport,
270
- statusLine: fresh?.message && phaseSource === "live" ? { summary: fresh.message, at: fresh.at, author: null, url: issue.url } : withStatus?.status ? {
271
- summary: withStatus.status.summary,
272
- at: withStatus.createdAt,
273
- author: withStatus.author,
274
- url: commentUrl(issue, withStatus)
275
- } : null,
276
- pr,
277
- openBlockers,
278
- flags
279
- };
280
- }
281
- function inFlight(m, comments, opts) {
282
- const held = (i) => {
283
- const fresh = freshEvent(i.id, opts);
284
- return fresh ? !ENDS_WORK.includes(fresh.kind) : !!i.agentPhase || isStarted(i);
285
- };
286
- return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && held(i)).map((i) => buildLane(m, comments, i, opts)).sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
287
- }
288
- function frontier(m, readyLabel) {
289
- const dependents = new Map;
290
- for (const i of m.program)
291
- for (const b of i.blockedBy)
292
- dependents.set(b.id, [...dependents.get(b.id) ?? [], i]);
293
- const transitive = (id, seen = new Set) => {
294
- for (const d of dependents.get(id) ?? [])
295
- if (!seen.has(d.id) && !isClosed(d)) {
296
- seen.add(d.id);
297
- transitive(d.id, seen);
298
- }
299
- return seen;
300
- };
301
- const critical = criticalIds(m);
302
- return m.program.filter((i) => m.isLeaf(i) && isNotStarted(i) && !i.agentPhase && m.openBlockersOf(i).length === 0 && !i.prs.some((p) => p.state === "open")).map((issue) => {
303
- const spec = m.specOf(issue.id);
304
- const unlocksAll = [...transitive(issue.id)];
305
- const unlocksNow = (dependents.get(issue.id) ?? []).filter((d) => !isClosed(d) && m.openBlockersOf(d).every((b) => b === issue.id)).map((d) => d.id);
306
- const readyForAgent = issue.labels.includes(readyLabel) && issue.statusType !== "triage";
307
- const onCriticalPath = critical.has(issue.id);
308
- const score = (readyForAgent ? 1000 : 0) + (onCriticalPath ? 300 : 0) + unlocksAll.length * 20 + unlocksNow.length * 10 - (spec?.ordinal ?? 99);
309
- return {
310
- issue,
311
- spec: spec ? `Spec ${spec.ordinal}` : null,
312
- readyForAgent,
313
- onCriticalPath,
314
- unlocksAll,
315
- unlocksNow,
316
- score
317
- };
318
- }).sort((a, b) => b.score - a.score || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
319
- }
320
- function waitingPullRequests(m, prs) {
321
- const ticketOf = new Map;
322
- for (const i of m.program)
323
- for (const p of i.prs)
324
- ticketOf.set(p.url, i);
325
- return prs.filter((p) => p.state === "open").map((pr) => ({ pr, ticket: ticketOf.get(pr.url) ?? null })).sort((a, b) => a.pr.number - b.pr.number);
326
- }
327
-
328
- // ../core/src/linear.ts
329
- var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
330
- var MAX_DEPTH = 8;
331
- var COMMENT_BATCH = 25;
332
- var MAX_COMMENTS = 100;
333
- var MORE_PAGE = 100;
334
- var REQUEST_TIMEOUT_MS = 30000;
335
-
336
- class LinearError extends Error {
337
- transport;
338
- name = "LinearError";
339
- constructor(message, transport = false) {
340
- super(message);
341
- this.transport = transport;
342
- }
343
- }
344
- var PHASES = [...LABEL_PHASES, "released", "merged"];
345
- var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
346
- var firstLine = (body) => (body.split(`
347
- `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
348
- var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
349
- function parseStatusLine(body) {
350
- const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
351
- if (!m?.[1])
352
- return null;
353
- const raw = m[1].toLowerCase();
354
- const phase = LEGACY[raw] ?? raw;
355
- const summary = (m[2] ?? "").trim();
356
- if (COORDINATOR_RECORD.test(summary))
357
- return null;
358
- return PHASES.includes(phase) ? { phase, summary } : null;
359
- }
360
- var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
361
- var trimMarks = (v) => {
362
- const t = v.trim();
363
- return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
364
- };
365
- function parseClaim(body, at, author) {
366
- const line = body.split(`
367
- `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
368
- if (!line)
369
- return null;
370
- const field = (k) => {
371
- const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
372
- return v && trimMarks(v) || null;
373
- };
374
- return {
375
- runtime: field("runtime"),
376
- session: field("session"),
377
- branch: field("branch|branche"),
378
- startedAt: field("started|démarré|demarre"),
379
- profile: field("profile"),
380
- at,
381
- author
382
- };
383
- }
384
- function excerpt(markdown, max = 240) {
385
- const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
386
- return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
387
- }
388
- function parsePullRequestUrl(url, title = "") {
389
- const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
390
- return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
391
- }
392
- function agentLabels(labels, groups) {
393
- let agentPhase = null;
394
- for (const l of labels)
395
- if (l.group === groups.phaseGroup)
396
- agentPhase ??= phaseNamed(l.name);
397
- const runtime = labels.find((l) => l.group === groups.runtimeGroup);
398
- return { agentPhase, agentRuntime: runtime?.name ?? null };
86
+ function agentLabels(labels, groups) {
87
+ let agentPhase = null;
88
+ for (const l of labels)
89
+ if (l.group === groups.phaseGroup)
90
+ agentPhase ??= phaseNamed(l.name);
91
+ const runtime = labels.find((l) => l.group === groups.runtimeGroup);
92
+ return { agentPhase, agentRuntime: runtime?.name ?? null };
399
93
  }
400
94
  var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
401
95
  var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
@@ -525,7 +219,7 @@ function networkReason(err, timeoutMs) {
525
219
  return err instanceof Error ? err.message : String(err);
526
220
  }
527
221
  var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
528
- var CLOSED2 = new Set(["completed", "canceled"]);
222
+ var CLOSED = new Set(["completed", "canceled"]);
529
223
  async function fetchProgram(opts) {
530
224
  try {
531
225
  return await fetchTree(opts, true);
@@ -534,80 +228,523 @@ async function fetchProgram(opts) {
534
228
  return fetchTree(opts, false);
535
229
  throw err;
536
230
  }
537
- }
538
- async function fetchTree(opts, delegate) {
539
- const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
540
- if (!root)
541
- throw new LinearError(`Linear: program root ${opts.rootId} not found`);
542
- const all = [root];
543
- const warnings = [];
544
- let parents = [root.id];
545
- for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
546
- const next = [];
547
- let after = null;
548
- for (;; ) {
549
- const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
550
- all.push(...data.issues.nodes);
551
- next.push(...data.issues.nodes.map((n) => n.id));
552
- const { hasNextPage, endCursor } = data.issues.pageInfo;
553
- if (!hasNextPage)
554
- break;
555
- if (!endCursor || endCursor === after) {
556
- warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
557
- break;
558
- }
559
- after = endCursor;
560
- }
561
- parents = next;
231
+ }
232
+ async function fetchTree(opts, delegate) {
233
+ const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
234
+ if (!root)
235
+ throw new LinearError(`Linear: program root ${opts.rootId} not found`);
236
+ const all = [root];
237
+ const warnings = [];
238
+ let parents = [root.id];
239
+ for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
240
+ const next = [];
241
+ let after = null;
242
+ for (;; ) {
243
+ const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
244
+ all.push(...data.issues.nodes);
245
+ next.push(...data.issues.nodes.map((n) => n.id));
246
+ const { hasNextPage, endCursor } = data.issues.pageInfo;
247
+ if (!hasNextPage)
248
+ break;
249
+ if (!endCursor || endCursor === after) {
250
+ warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
251
+ break;
252
+ }
253
+ after = endCursor;
254
+ }
255
+ parents = next;
256
+ }
257
+ if (parents.length)
258
+ warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
259
+ for (const r of all)
260
+ for (const field of ["inverseRelations", "labels", "attachments"])
261
+ await readRest(opts, r.identifier, MORE[field], r[field], warnings);
262
+ const issues = all.map((r) => normalizeIssue(r, opts.labels));
263
+ const candidates = issues.filter((i) => i.id !== root.identifier && !CLOSED.has(i.statusType) && (i.agentPhase || i.statusType === "started"));
264
+ const comments = [];
265
+ for (const batch of chunks(candidates.map((i) => i.uuid), COMMENT_BATCH)) {
266
+ const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
267
+ for (const n of data.issues.nodes) {
268
+ await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
269
+ for (const c of n.comments.nodes)
270
+ comments.push(normalizeComment(c, n.identifier));
271
+ }
272
+ }
273
+ return {
274
+ rootId: root.identifier,
275
+ fetchedAt: (opts.now?.() ?? new Date).toISOString(),
276
+ issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
277
+ comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
278
+ warnings
279
+ };
280
+ }
281
+ async function readRest(opts, identifier, more, conn, warnings) {
282
+ while (conn.pageInfo?.hasNextPage) {
283
+ const after = conn.pageInfo.endCursor;
284
+ try {
285
+ if (!after)
286
+ throw new LinearError("Linear gave no cursor for the next page");
287
+ const data = await gql(opts, MORE_QUERY(more), {
288
+ id: identifier,
289
+ after
290
+ });
291
+ const page = data.issue?.[more.field];
292
+ if (!page)
293
+ throw new LinearError(`Linear: issue ${identifier} not found`);
294
+ conn.nodes.push(...page.nodes);
295
+ conn.pageInfo = page.pageInfo;
296
+ if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
297
+ throw new LinearError("Linear did not advance to a next page");
298
+ } catch (err) {
299
+ if (!(err instanceof LinearError) || err.transport)
300
+ throw err;
301
+ warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
302
+ return;
303
+ }
304
+ }
305
+ }
306
+
307
+ // ../core/src/armada-api.ts
308
+ var displayCode = (code) => code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
309
+
310
+ class ArmadaApiError extends Error {
311
+ next;
312
+ signedOut;
313
+ constructor(message, next = null, signedOut = false) {
314
+ super(message);
315
+ this.next = next;
316
+ this.signedOut = signedOut;
317
+ }
318
+ }
319
+ var LOGIN_NEXT = "armada login";
320
+ var TIMEOUT_MS = 30000;
321
+ function apiBaseUrl(value) {
322
+ let url;
323
+ try {
324
+ url = new URL(value);
325
+ } catch {
326
+ throw new ArmadaApiError(`the Armada API address "${value}" is not a URL`, "ARMADA_API_URL or [api] url in config.toml");
327
+ }
328
+ if (url.protocol !== "https:" && url.protocol !== "http:")
329
+ throw new ArmadaApiError(`the Armada API address must be http or https, not ${url.protocol}`);
330
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
331
+ throw new ArmadaApiError(`the Armada API address must use https (http only reaches localhost): ${url.origin}`, "ARMADA_API_URL or [api] url in config.toml");
332
+ url.search = "";
333
+ url.hash = "";
334
+ if (!url.pathname.endsWith("/"))
335
+ url.pathname += "/";
336
+ return url;
337
+ }
338
+ function armadaApi(opts) {
339
+ const base = apiBaseUrl(opts.url);
340
+ const doFetch = opts.fetch ?? fetch;
341
+ const timeoutMs = opts.timeoutMs ?? TIMEOUT_MS;
342
+ const host = base.host;
343
+ async function call(method, path, init = {}) {
344
+ const headers = { Accept: "application/json" };
345
+ if (init.body)
346
+ headers["Content-Type"] = "application/json";
347
+ if (init.signIn?.kind === "session")
348
+ headers.Authorization = `Bearer ${init.signIn.token}`;
349
+ if (init.signIn?.kind === "api-key")
350
+ headers["x-api-key"] = init.signIn.key;
351
+ const res = await doFetch(new URL(`api/cli/${path}`, base).toString(), {
352
+ method,
353
+ headers,
354
+ ...init.body ? { body: JSON.stringify(init.body) } : {},
355
+ signal: AbortSignal.timeout(timeoutMs)
356
+ }).catch((err) => {
357
+ throw new ArmadaApiError(`Armada (${host}) unreachable: ${networkReason(err, timeoutMs)}`, "the same command again once it answers, or check ARMADA_API_URL");
358
+ });
359
+ const body = await res.json().catch(() => null);
360
+ if (typeof body !== "object" || body === null || Array.isArray(body))
361
+ throw new ArmadaApiError(`Armada (${host}) answered HTTP ${res.status} without JSON: is ${base.origin} an Armada?`, "check ARMADA_API_URL or [api] url in config.toml");
362
+ return { status: res.status, body };
363
+ }
364
+ const refusal = (status, body, what) => {
365
+ const error = typeof body.error === "string" ? body.error : `HTTP ${status}`;
366
+ const next = typeof body.next === "string" ? body.next : status === 401 ? LOGIN_NEXT : null;
367
+ return new ArmadaApiError(what ? `${what}: ${error}` : error, next, status === 401);
368
+ };
369
+ return {
370
+ async startDeviceLogin() {
371
+ const { status, body } = await call("POST", "device/code");
372
+ if (status !== 200)
373
+ throw refusal(status, body, "Armada refused to start the sign-in");
374
+ const str = (k) => typeof body[k] === "string" ? body[k] : "";
375
+ const num = (k, d) => typeof body[k] === "number" && body[k] > 0 ? body[k] : d;
376
+ if (!str("device_code") || !str("user_code") || !str("verification_uri"))
377
+ throw new ArmadaApiError(`Armada (${host}) answered the sign-in without a code`);
378
+ return {
379
+ deviceCode: str("device_code"),
380
+ userCode: str("user_code"),
381
+ verificationUri: str("verification_uri"),
382
+ verificationUriComplete: str("verification_uri_complete") || str("verification_uri"),
383
+ expiresInSeconds: num("expires_in", 900),
384
+ intervalSeconds: num("interval", 5)
385
+ };
386
+ },
387
+ async pollDeviceLogin(deviceCode) {
388
+ const { status, body } = await call("POST", "device/token", { body: { device_code: deviceCode } });
389
+ if (status === 200 && typeof body.access_token === "string" && body.access_token)
390
+ return { state: "approved", token: body.access_token };
391
+ switch (body.error) {
392
+ case "authorization_pending":
393
+ return { state: "pending" };
394
+ case "slow_down":
395
+ return { state: "slow-down" };
396
+ case "access_denied":
397
+ return { state: "denied" };
398
+ case "expired_token":
399
+ case "invalid_grant":
400
+ return { state: "expired" };
401
+ }
402
+ throw refusal(status, body, "Armada refused the sign-in");
403
+ },
404
+ async whoami(signIn) {
405
+ const { status, body } = await call("GET", "session", { signIn });
406
+ if (status !== 200)
407
+ throw refusal(status, body, status === 401 ? null : "Armada could not say who is signed in");
408
+ return body;
409
+ },
410
+ async signOut(signIn) {
411
+ const { status, body } = await call("DELETE", "session", { signIn });
412
+ if (status !== 200)
413
+ throw refusal(status, body, "Armada refused the sign-out");
414
+ }
415
+ };
416
+ }
417
+ async function waitForApproval({ api, code, sleep, now }) {
418
+ const deadline = now().getTime() + code.expiresInSeconds * 1000;
419
+ let interval = code.intervalSeconds * 1000;
420
+ for (;; ) {
421
+ await sleep(interval);
422
+ if (now().getTime() > deadline)
423
+ break;
424
+ let poll;
425
+ try {
426
+ poll = await api.pollDeviceLogin(code.deviceCode);
427
+ } catch (err) {
428
+ if (!(err instanceof ArmadaApiError) || !/unreachable/.test(err.message))
429
+ throw err;
430
+ interval = Math.min(interval * 2, 60000);
431
+ continue;
432
+ }
433
+ if (poll.state === "approved")
434
+ return poll.token;
435
+ if (poll.state === "denied")
436
+ throw new ArmadaApiError("the sign-in was denied in the browser", LOGIN_NEXT);
437
+ if (poll.state === "expired")
438
+ break;
439
+ if (poll.state === "slow-down")
440
+ interval += 5000;
441
+ }
442
+ throw new ArmadaApiError("the code expired before it was approved", LOGIN_NEXT);
443
+ }
444
+ // ../core/src/model.ts
445
+ var CLOSED2 = ["completed", "canceled"];
446
+ var NOT_STARTED = ["triage", "backlog", "unstarted"];
447
+ var isDone = (i) => i.statusType === "completed";
448
+ var isClosed = (i) => CLOSED2.includes(i.statusType);
449
+ var isStarted = (i) => i.statusType === "started";
450
+ var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
451
+ var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
452
+ function buildModel(issues, rootId) {
453
+ const byId = new Map(issues.map((i) => [i.id, i]));
454
+ const root = byId.get(rootId);
455
+ if (!root)
456
+ throw new Error(`program root ${rootId} is not among the issues read`);
457
+ const childrenOf = new Map;
458
+ for (const i of issues) {
459
+ if (!i.parentId || !byId.has(i.parentId))
460
+ continue;
461
+ childrenOf.set(i.parentId, [...childrenOf.get(i.parentId) ?? [], i]);
462
+ }
463
+ const program = [];
464
+ const walk = (id, seen) => {
465
+ for (const c of childrenOf.get(id) ?? []) {
466
+ if (seen.has(c.id))
467
+ continue;
468
+ seen.add(c.id);
469
+ program.push(c);
470
+ walk(c.id, seen);
471
+ }
472
+ };
473
+ walk(root.id, new Set([root.id]));
474
+ const specs = (childrenOf.get(root.id) ?? []).flatMap((issue) => {
475
+ const m = issue.title.trim().match(SPEC_TITLE);
476
+ return m?.[1] && m[3] ? [{ issue, ordinal: Number(m[1]), name: m[3].trim() }] : [];
477
+ }).sort((a, b) => a.ordinal - b.ordinal || a.issue.createdAt.localeCompare(b.issue.createdAt));
478
+ const specById = new Map(specs.map((s) => [s.issue.id, s]));
479
+ const specOf = (id) => {
480
+ const seen = new Set;
481
+ for (let cur = byId.get(id);cur && !seen.has(cur.id); cur = cur.parentId ? byId.get(cur.parentId) : undefined) {
482
+ seen.add(cur.id);
483
+ const s = specById.get(cur.id);
484
+ if (s)
485
+ return s;
486
+ }
487
+ return null;
488
+ };
489
+ const isLeaf = (i) => !childrenOf.get(i.id)?.length && !specById.has(i.id);
490
+ const openBlockersOf = (i) => i.blockedBy.filter((b) => !isClosed(byId.get(b.id) ?? b)).map((b) => b.id);
491
+ const stateOf = (i) => {
492
+ if (isDone(i))
493
+ return "done";
494
+ if (i.statusType === "canceled")
495
+ return "canceled";
496
+ if (isStarted(i))
497
+ return "active";
498
+ return openBlockersOf(i).length ? "blocked" : "frontier";
499
+ };
500
+ return { root, byId, childrenOf, program, specs, specOf, isLeaf, openBlockersOf, stateOf };
501
+ }
502
+ function longestPathLevels(nodes) {
503
+ const byId = new Map(nodes.map((n) => [n.id, n]));
504
+ const level = new Map;
505
+ const visiting = new Set;
506
+ const visit = (id) => {
507
+ const known = level.get(id);
508
+ if (known !== undefined)
509
+ return known;
510
+ if (visiting.has(id))
511
+ return 0;
512
+ visiting.add(id);
513
+ const blockers = (byId.get(id)?.blockedBy ?? []).map((b) => b.id).filter((b) => byId.has(b));
514
+ const l = blockers.length ? Math.max(...blockers.map(visit)) + 1 : 0;
515
+ visiting.delete(id);
516
+ level.set(id, l);
517
+ return l;
518
+ };
519
+ for (const n of nodes)
520
+ visit(n.id);
521
+ return level;
522
+ }
523
+ function criticalPath(m, parentId) {
524
+ const nodes = m.childrenOf.get(parentId) ?? [];
525
+ const level = longestPathLevels(nodes);
526
+ const remaining = nodes.filter((n) => !isClosed(n));
527
+ const remIds = new Set(remaining.map((n) => n.id));
528
+ const len = new Map;
529
+ const prev = new Map;
530
+ const order = [...remaining].sort((a, b) => (level.get(a.id) ?? 0) - (level.get(b.id) ?? 0));
531
+ for (const n of order) {
532
+ let best = 0;
533
+ let bestPrev = null;
534
+ for (const { id } of n.blockedBy) {
535
+ if (!remIds.has(id))
536
+ continue;
537
+ const l = len.get(id) ?? 0;
538
+ if (l > best) {
539
+ best = l;
540
+ bestPrev = id;
541
+ }
542
+ }
543
+ len.set(n.id, best + 1);
544
+ prev.set(n.id, bestPrev);
545
+ }
546
+ let tail = null;
547
+ let tailLen = 0;
548
+ for (const [id, l] of len)
549
+ if (l > tailLen || l === tailLen && tail && id > tail) {
550
+ tail = id;
551
+ tailLen = l;
552
+ }
553
+ if (tailLen < 2)
554
+ return [];
555
+ const path = [];
556
+ for (let cur = tail;cur; cur = prev.get(cur) ?? null) {
557
+ const issue = m.byId.get(cur);
558
+ if (issue)
559
+ path.unshift(issue);
560
+ }
561
+ return path;
562
+ }
563
+ function criticalIds(m) {
564
+ const out = new Set;
565
+ for (const parent of m.childrenOf.keys())
566
+ for (const i of criticalPath(m, parent))
567
+ out.add(i.id);
568
+ return out;
569
+ }
570
+
571
+ // ../core/src/fleet.ts
572
+ var MIN = 60000;
573
+ var NEEDS_HUMAN = ["awaiting-approval", "blocked", "ready-to-merge"];
574
+ var PHASE_RANK = {
575
+ merged: 0,
576
+ "ready-to-merge": 1,
577
+ shipping: 2,
578
+ implementing: 3,
579
+ "awaiting-approval": 4,
580
+ planning: 5,
581
+ blocked: 6,
582
+ released: 7
583
+ };
584
+ var PLAN_HINT = /\b(plan|objective|assumptions|awaiting (?:plan )?approval)\b/i;
585
+ function commentsFor(comments, id) {
586
+ return comments.filter((c) => c.issueId === id).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
587
+ }
588
+ function commentUrl(issue, c) {
589
+ return `${issue.url}#comment-${c.id.slice(0, 8)}`;
590
+ }
591
+ function primaryPr(issue) {
592
+ const byNewest = [...issue.prs].sort((a, b) => b.number - a.number);
593
+ return byNewest.find((p) => p.state === "open") ?? byNewest[0] ?? null;
594
+ }
595
+ function activeClaims(comments) {
596
+ const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
597
+ let claims = [];
598
+ for (const c of asc) {
599
+ if (c.status?.phase === "released")
600
+ claims = [];
601
+ if (c.claim)
602
+ claims.push(c.claim);
603
+ }
604
+ return claims;
605
+ }
606
+ var latest = (...xs) => xs.filter((x) => !!x).reduce((a, b) => b > a ? b : a, "");
607
+ function inferPhase(pr, comments) {
608
+ if (pr?.state === "open")
609
+ return pr.ci === "success" && pr.mergeable !== "CONFLICTING" ? "ready-to-merge" : "shipping";
610
+ if (comments.some((c) => PLAN_HINT.test(c.excerpt.slice(0, 120))))
611
+ return "awaiting-approval";
612
+ return "planning";
613
+ }
614
+ var ENDS_WORK = ["release", "merge"];
615
+ var livePhase = (e) => e.kind === "release" ? "released" : LABEL_PHASES.find((p) => p === e.phase) ?? null;
616
+ function freshEvent(issueId, opts) {
617
+ const e = opts.live?.events[issueId];
618
+ return e && opts.live && e.at > opts.live.after ? e : null;
619
+ }
620
+ function buildLane(m, allComments, issue, opts) {
621
+ const comments = commentsFor(allComments, issue.id);
622
+ const withStatus = comments.find((c) => c.status && c.status.phase !== "released");
623
+ const pr = primaryPr(issue);
624
+ const claims = activeClaims(comments);
625
+ let phase;
626
+ let phaseSource;
627
+ if (issue.agentPhase) {
628
+ phase = issue.agentPhase;
629
+ phaseSource = "label";
630
+ } else if (withStatus?.status) {
631
+ phase = withStatus.status.phase;
632
+ phaseSource = "status-line";
633
+ } else {
634
+ phase = inferPhase(pr, comments);
635
+ phaseSource = "inferred";
636
+ }
637
+ const fresh = freshEvent(issue.id, opts);
638
+ const freshPhase = fresh ? livePhase(fresh) : null;
639
+ const trackerPhase = phase;
640
+ if (freshPhase && freshPhase !== "released") {
641
+ phase = freshPhase;
642
+ phaseSource = "live";
562
643
  }
563
- if (parents.length)
564
- warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
565
- for (const r of all)
566
- for (const field of ["inverseRelations", "labels", "attachments"])
567
- await readRest(opts, r.identifier, MORE[field], r[field], warnings);
568
- const issues = all.map((r) => normalizeIssue(r, opts.labels));
569
- const candidates = issues.filter((i) => i.id !== root.identifier && !CLOSED2.has(i.statusType) && (i.agentPhase || i.statusType === "started"));
570
- const comments = [];
571
- for (const batch of chunks(candidates.map((i) => i.uuid), COMMENT_BATCH)) {
572
- const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
573
- for (const n of data.issues.nodes) {
574
- await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
575
- for (const c of n.comments.nodes)
576
- comments.push(normalizeComment(c, n.identifier));
577
- }
644
+ const shippingPhase = phase === "shipping" || phase === "ready-to-merge";
645
+ if (pr?.state === "merged" && !isDone(issue) && (shippingPhase || phaseSource === "status-line" || phaseSource === "inferred"))
646
+ phase = "merged";
647
+ let announcing;
648
+ for (const c of comments) {
649
+ if (!c.status || c.status.phase === "released")
650
+ continue;
651
+ if (c.status.phase !== phase)
652
+ break;
653
+ announcing = c;
578
654
  }
655
+ const since = (fresh && phaseSource === "live" && phase !== trackerPhase ? fresh.at : undefined) ?? announcing?.createdAt ?? (fresh && phaseSource === "live" ? fresh.at : undefined) ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
656
+ const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt, fresh?.at);
657
+ const lastReport = latest(comments.find((c) => c.status || c.claim)?.createdAt, claims.at(-1)?.at, opts.lastEvents?.[issue.id], fresh?.at) || null;
658
+ const openBlockers = m.openBlockersOf(issue);
659
+ const agent = issue.delegate ?? issue.assignee;
660
+ const flags = [];
661
+ const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
662
+ const alive = lastReport ?? lastUpdate;
663
+ if (!waitingOnHuman && opts.now - Date.parse(alive) > opts.silentAfterMinutes * MIN)
664
+ flags.push("silent");
665
+ if (pr?.state === "open" && pr.ci === "failure")
666
+ flags.push("ci-failing");
667
+ if (pr?.state === "open" && pr.mergeable === "CONFLICTING")
668
+ flags.push("conflict");
669
+ const runtimes = new Set(claims.map((c) => c.runtime).filter(Boolean));
670
+ const claimRuntime = claims[0]?.runtime;
671
+ if (claims.length > 1 || runtimes.size > 1 || issue.agentRuntime && claimRuntime && claimRuntime !== issue.agentRuntime)
672
+ flags.push("double-claim");
673
+ if (openBlockers.length)
674
+ flags.push("started-before-blockers");
675
+ if (!agent && phaseSource !== "live")
676
+ flags.push("no-assignee");
677
+ if (!issue.agentPhase && phaseSource !== "live")
678
+ flags.push("no-phase-label");
679
+ const spec = m.specOf(issue.id);
579
680
  return {
580
- rootId: root.identifier,
581
- fetchedAt: (opts.now?.() ?? new Date).toISOString(),
582
- issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
583
- comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
584
- warnings
681
+ issue,
682
+ spec: spec ? `Spec ${spec.ordinal}` : null,
683
+ phase,
684
+ phaseSource,
685
+ runtime: issue.agentRuntime ?? claimRuntime ?? fresh?.runtime ?? opts.live?.handles?.[issue.id]?.runtime ?? null,
686
+ handle: opts.live?.handles?.[issue.id]?.handle ?? claims[0]?.session ?? fresh?.handle ?? null,
687
+ claim: claims[0] ?? null,
688
+ agent,
689
+ since,
690
+ lastUpdate,
691
+ lastReport,
692
+ statusLine: fresh?.message && phaseSource === "live" ? { summary: fresh.message, at: fresh.at, author: null, url: issue.url } : withStatus?.status ? {
693
+ summary: withStatus.status.summary,
694
+ at: withStatus.createdAt,
695
+ author: withStatus.author,
696
+ url: commentUrl(issue, withStatus)
697
+ } : null,
698
+ pr,
699
+ openBlockers,
700
+ flags
585
701
  };
586
702
  }
587
- async function readRest(opts, identifier, more, conn, warnings) {
588
- while (conn.pageInfo?.hasNextPage) {
589
- const after = conn.pageInfo.endCursor;
590
- try {
591
- if (!after)
592
- throw new LinearError("Linear gave no cursor for the next page");
593
- const data = await gql(opts, MORE_QUERY(more), {
594
- id: identifier,
595
- after
596
- });
597
- const page = data.issue?.[more.field];
598
- if (!page)
599
- throw new LinearError(`Linear: issue ${identifier} not found`);
600
- conn.nodes.push(...page.nodes);
601
- conn.pageInfo = page.pageInfo;
602
- if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
603
- throw new LinearError("Linear did not advance to a next page");
604
- } catch (err) {
605
- if (!(err instanceof LinearError) || err.transport)
606
- throw err;
607
- warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
608
- return;
609
- }
610
- }
703
+ function inFlight(m, comments, opts) {
704
+ const held = (i) => {
705
+ const fresh = freshEvent(i.id, opts);
706
+ return fresh ? !ENDS_WORK.includes(fresh.kind) : !!i.agentPhase || isStarted(i);
707
+ };
708
+ return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && held(i)).map((i) => buildLane(m, comments, i, opts)).sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
709
+ }
710
+ function frontier(m, readyLabel) {
711
+ const dependents = new Map;
712
+ for (const i of m.program)
713
+ for (const b of i.blockedBy)
714
+ dependents.set(b.id, [...dependents.get(b.id) ?? [], i]);
715
+ const transitive = (id, seen = new Set) => {
716
+ for (const d of dependents.get(id) ?? [])
717
+ if (!seen.has(d.id) && !isClosed(d)) {
718
+ seen.add(d.id);
719
+ transitive(d.id, seen);
720
+ }
721
+ return seen;
722
+ };
723
+ const critical = criticalIds(m);
724
+ return m.program.filter((i) => m.isLeaf(i) && isNotStarted(i) && !i.agentPhase && m.openBlockersOf(i).length === 0 && !i.prs.some((p) => p.state === "open")).map((issue) => {
725
+ const spec = m.specOf(issue.id);
726
+ const unlocksAll = [...transitive(issue.id)];
727
+ const unlocksNow = (dependents.get(issue.id) ?? []).filter((d) => !isClosed(d) && m.openBlockersOf(d).every((b) => b === issue.id)).map((d) => d.id);
728
+ const readyForAgent = issue.labels.includes(readyLabel) && issue.statusType !== "triage";
729
+ const onCriticalPath = critical.has(issue.id);
730
+ const score = (readyForAgent ? 1000 : 0) + (onCriticalPath ? 300 : 0) + unlocksAll.length * 20 + unlocksNow.length * 10 - (spec?.ordinal ?? 99);
731
+ return {
732
+ issue,
733
+ spec: spec ? `Spec ${spec.ordinal}` : null,
734
+ readyForAgent,
735
+ onCriticalPath,
736
+ unlocksAll,
737
+ unlocksNow,
738
+ score
739
+ };
740
+ }).sort((a, b) => b.score - a.score || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
741
+ }
742
+ function waitingPullRequests(m, prs) {
743
+ const ticketOf = new Map;
744
+ for (const i of m.program)
745
+ for (const p of i.prs)
746
+ ticketOf.set(p.url, i);
747
+ return prs.filter((p) => p.state === "open").map((pr) => ({ pr, ticket: ticketOf.get(pr.url) ?? null })).sort((a, b) => a.pr.number - b.pr.number);
611
748
  }
612
749
 
613
750
  // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
@@ -3101,6 +3238,19 @@ async function loadBrief(config, opts) {
3101
3238
  });
3102
3239
  }
3103
3240
  // ../core/src/credentials.ts
3241
+ var DEFAULT_ARMADA_API_URL = "https://armada.thevibecompany.co";
3242
+ var SESSION_TOKEN_VARIABLE = "ARMADA_SESSION_TOKEN";
3243
+ var API_KEY_VARIABLE = "ARMADA_API_KEY";
3244
+ var API_URL_VARIABLE = "ARMADA_API_URL";
3245
+ var SIGNED_IN_TO_VARIABLE = "ARMADA_SIGNED_IN_TO";
3246
+ function armadaAddress(url) {
3247
+ try {
3248
+ const u = new URL(url.trim());
3249
+ return `${u.origin}${u.pathname.replace(/\/+$/, "")}`;
3250
+ } catch {
3251
+ return url.trim();
3252
+ }
3253
+ }
3104
3254
  var LINEAR_KEY = {
3105
3255
  name: "linearApiKey",
3106
3256
  variable: "LINEAR_API_KEY",
@@ -3141,6 +3291,16 @@ function resolveCredentials({ env, store = {}, personal, ghToken }) {
3141
3291
  return value ? { value, source: { kind: "gh" } } : null;
3142
3292
  };
3143
3293
  const tursoUrlConfig = clean(personal?.turso.url);
3294
+ const apiUrlConfig = clean(personal?.api.url);
3295
+ const apiUrl = fromEnv(env, API_URL_VARIABLE);
3296
+ const armadaApi = apiUrl ? { url: apiUrl.value, source: apiUrl.source } : apiUrlConfig ? { url: apiUrlConfig, source: { kind: "config", key: "api.url" } } : { url: DEFAULT_ARMADA_API_URL, source: { kind: "default" } };
3297
+ const envKey = fromEnv(env, API_KEY_VARIABLE);
3298
+ const signedInTo = armadaAddress(clean(store[SIGNED_IN_TO_VARIABLE]) ?? DEFAULT_ARMADA_API_URL);
3299
+ const here = signedInTo === armadaAddress(armadaApi.url);
3300
+ const session = fromStore(SESSION_TOKEN_VARIABLE);
3301
+ const storedKey = fromStore(API_KEY_VARIABLE);
3302
+ const armadaSignInElsewhere = !here && (session || storedKey) ? signedInTo : null;
3303
+ const armadaSignIn = envKey ? { kind: "api-key", key: envKey.value, source: envKey.source } : session && here ? { kind: "session", token: session.value, source: session.source } : storedKey && here ? { kind: "api-key", key: storedKey.value, source: storedKey.source } : null;
3144
3304
  const found = {
3145
3305
  linearApiKey: stored("LINEAR_API_KEY"),
3146
3306
  tursoUrl: stored("ARMADA_TURSO_URL") ?? (tursoUrlConfig ? { value: tursoUrlConfig, source: { kind: "config", key: "turso.url" } } : null),
@@ -3157,7 +3317,10 @@ function resolveCredentials({ env, store = {}, personal, ghToken }) {
3157
3317
  tursoUrl: found.tursoUrl?.source ?? null,
3158
3318
  tursoToken: found.tursoToken?.source ?? null,
3159
3319
  githubToken: found.githubToken?.source ?? null
3160
- }
3320
+ },
3321
+ armadaApi,
3322
+ armadaSignIn,
3323
+ armadaSignInElsewhere: envKey ? null : armadaSignInElsewhere
3161
3324
  };
3162
3325
  }
3163
3326
  var missingKeys = (credentials) => STORED_KEYS.filter((k) => credentials[k.name] === null);
@@ -3563,6 +3726,8 @@ async function readInbox(db, o) {
3563
3726
  }));
3564
3727
  const asking = new Set(items.filter((i) => i.kind === "question").map((i) => i.ticket));
3565
3728
  for (const h of handles) {
3729
+ if (o.coordinator && h.handle === o.coordinator)
3730
+ continue;
3566
3731
  const e = events[h.ticket];
3567
3732
  if (e && (e.kind === "release" || e.kind === "merge"))
3568
3733
  continue;
@@ -4028,7 +4193,12 @@ async function updateCredentialStore(paths, updates) {
4028
4193
  }
4029
4194
  await writePrivate(paths, paths.credentials, updateDotenv(text, updates), 384);
4030
4195
  }
4031
- var EMPTY_PERSONAL_CONFIG = { language: null, turso: { url: null }, dashboard: { url: null } };
4196
+ var EMPTY_PERSONAL_CONFIG = {
4197
+ language: null,
4198
+ turso: { url: null },
4199
+ dashboard: { url: null },
4200
+ api: { url: null }
4201
+ };
4032
4202
  var isTable2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4033
4203
  function parsePersonalConfig(text, source = "config.toml") {
4034
4204
  let raw;
@@ -4039,7 +4209,7 @@ function parsePersonalConfig(text, source = "config.toml") {
4039
4209
  throw new ConfigError(source, [`not valid TOML${where}`]);
4040
4210
  }
4041
4211
  const problems = [];
4042
- const known = { turso: ["url"], dashboard: ["url"] };
4212
+ const known = { turso: ["url"], dashboard: ["url"], api: ["url"] };
4043
4213
  for (const [key, v] of Object.entries(raw)) {
4044
4214
  if (key === "language")
4045
4215
  continue;
@@ -4069,7 +4239,8 @@ function parsePersonalConfig(text, source = "config.toml") {
4069
4239
  const config = {
4070
4240
  language: str(raw.language, "language"),
4071
4241
  turso: { url: str(table("turso").url, "turso.url") },
4072
- dashboard: { url: str(table("dashboard").url, "dashboard.url") }
4242
+ dashboard: { url: str(table("dashboard").url, "dashboard.url") },
4243
+ api: { url: str(table("api").url, "api.url") }
4073
4244
  };
4074
4245
  if (problems.length)
4075
4246
  throw new ConfigError(source, problems);
@@ -4097,6 +4268,10 @@ var PERSONAL_CONFIG_TEMPLATE = `# Armada personal defaults for this machine. No
4097
4268
 
4098
4269
  # [dashboard]
4099
4270
  # url = "https://<your-armada-dashboard>"
4271
+
4272
+ # The Armada the CLI signs in to (armada login), for a self-hosted one.
4273
+ # [api]
4274
+ # url = "https://armada.example.com"
4100
4275
  `;
4101
4276
  async function ensurePersonalConfig(paths) {
4102
4277
  try {
@@ -4432,13 +4607,17 @@ async function closeTicket(ctx, ticket, merged, unlocked) {
4432
4607
  const done = ticket.statusType === "completed" ? null : firstState(ticket.states, "completed");
4433
4608
  await ctx.linear.updateTicket(ticket.uuid, {
4434
4609
  ...done ? { stateId: done.id } : {},
4435
- removeLabelIds: [...others(ticket, groups.phaseGroup, null), ...others(ticket, groups.runtimeGroup, null)]
4610
+ removeLabelIds: [
4611
+ ...others(ticket, groups.phaseGroup, null),
4612
+ ...others(ticket, groups.runtimeGroup, null),
4613
+ ...ticket.labels.filter((label) => label.name === ctx.config.tracker.readyLabel).map((label) => label.id)
4614
+ ]
4436
4615
  });
4437
4616
  if (!ticket.prs.some((p) => p.url === merged.url))
4438
4617
  await ctx.linear.linkUrl(ticket.uuid, merged.url, merged.title || `Pull request #${merged.number}`);
4439
4618
  await ctx.linear.comment(ticket.uuid, `Agent status: merged — PR #${merged.number} squash-merged into ${merged.baseRef} as ${merged.mergeCommit ?? "unknown"}, head ${merged.headSha}${unlocked ? ", merged without lock (--no-lock)" : ""}`);
4440
4619
  return [
4441
- `${ticket.id}: ${done ? `moved to ${done.name}` : "state unchanged"}, agent labels removed, merged status posted.`
4620
+ `${ticket.id}: ${done ? `moved to ${done.name}` : "state unchanged"}, agent and ready labels removed, merged status posted.`
4442
4621
  ];
4443
4622
  }
4444
4623
  async function mergePullRequest(ctx, input) {
@@ -4464,7 +4643,7 @@ async function mergePullRequest(ctx, input) {
4464
4643
  try {
4465
4644
  lines.push(...await closeTicket(ctx, c.ticket, merged, !!input.noLock));
4466
4645
  } catch (err) {
4467
- throw new Error(`#${merged.number} is merged, but Linear could not be updated (${err instanceof Error ? err.message : String(err)}); close ${c.ticket.id} by hand: Done, agent labels removed, pull request linked`);
4646
+ throw new Error(`#${merged.number} is merged, but Linear could not be updated (${err instanceof Error ? err.message : String(err)}); close ${c.ticket.id} by hand: Done, agent and ready labels removed, pull request linked`);
4468
4647
  }
4469
4648
  return after(ctx, c, merged, lines);
4470
4649
  };
@@ -4598,7 +4777,7 @@ async function readProjectConfig(p, opts) {
4598
4777
  import { createHash } from "node:crypto";
4599
4778
 
4600
4779
  // ../../skills/armada-coordinator/MERGE.md
4601
- var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Turso is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n";
4780
+ var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Turso is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n\n## The release pull request\n\nSome repositories publish through release-please: every merge to the default branch opens or updates one release pull request, and merging it tags the version and publishes it. When the repository's rules (`AGENTS.md`) say to merge it after each merge, do it right after the ticket's merge, without a hand-back: no worker owns it, so `armada merge` does not apply.\n\n- **What it looks like.** Title `chore(main): release <version>`, opened by `github-actions`, label `autorelease: pending`, and a diff that only touches the changelog, the manifest and version fields. It is opened with the workflow's own token, so **no CI check runs on it** (only checks from apps such as Vercel, if any) and `mergeStateStatus` is `UNSTABLE`. Both are expected: the publish job runs the repository's checks again before publishing. Anything else in the diff, or a `DIRTY` state, is not expected: stop and tell the owner.\n- **Find it and its head:**\n\n```sh\ngh pr list --state open --label \"autorelease: pending\" --json number,title,headRefOid,mergeStateStatus\n```\n\n- **Merge it** pinned to that head, like any merge, and without `--delete-branch`:\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- **Check the publish.** After a minute or two the new version is on the registry, for example `npm view <package> version` for an npm package (the package is named in `AGENTS.md` or the release workflow). If it is not, open the Release run (`gh run list --workflow release.yml --limit 3`), fix the cause and re-run its failed jobs: a later push does not publish a version already tagged.\n- Release-please updates the same pull request on each merge to the default branch; one release pull request can carry several merges.\n";
4602
4781
 
4603
4782
  // ../../skills/armada-coordinator/SKILL.md
4604
4783
  var SKILL_default = `---
@@ -4612,6 +4791,16 @@ The coordinator turns the owner's intent into merged pull requests. Each worker
4612
4791
 
4613
4792
  **Armada never drives a runtime.** Launching, messaging, checking and stopping a worker go through the runtime guide skill for the worker's runtime (for example \`armada-runtime-conductor\`). Armada records what happened.
4614
4793
 
4794
+ ## Take over a run
4795
+
4796
+ A coordinator may start cold, on a laptop or in a fresh cloud session, with nothing but the repository and its keys. Everything it needs is in the tracker, GitHub and Turso; the Armada [runbook](https://github.com/The-Vibe-Company/armada/blob/main/docs/runbook.md) says how to start one.
4797
+
4798
+ 1. **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.
4799
+ 2. **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.
4800
+ 3. **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.
4801
+ 4. **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.
4802
+ 5. **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.
4803
+
4615
4804
  ## Loop
4616
4805
 
4617
4806
  1. **Read the fleet** with \`armada status\` and \`armada inbox\`, never from memory. Done when you can name every ticket in flight and its phase, every ready ticket, every pull request waiting, every silent worker and every pending question or request.
@@ -4627,7 +4816,7 @@ The coordinator turns the owner's intent into merged pull requests. Each worker
4627
4816
  - write the prompt with \`armada brief <ticket> --prompt > <file>\` and add what only you know: which parallel workers touch neighbouring code and where the boundary is, and decisions not yet on the ticket;
4628
4817
  - launch it with the runtime guide's *launch* section, passing the profile's values and the environment variables the brief names;
4629
4818
  - check the claim: \`armada status\` shows the ticket in flight, phase \`planning\`, with the handle the runtime returned. Done when every launched ticket is In Progress with a claim.
4630
- 6. **Merge handed-back pull requests** one at a time with \`armada merge <pr>\`, following [MERGE.md](MERGE.md). Done when the pull request is merged, the ticket is Done with its agent labels removed, and every in-flight worker affected by what landed has been told.
4819
+ 6. **Merge handed-back pull requests** one at a time with \`armada merge <pr>\`, following [MERGE.md](MERGE.md). Done when the pull request is merged, the ticket is Done with its agent labels removed, and every in-flight worker affected by what landed has been told. When the repository's rules (\`AGENTS.md\`) ask you to ship each merge through its release pull request (release-please's \`chore(main): release …\`), merge that one next, as "The release pull request" in [MERGE.md](MERGE.md) describes.
4631
4820
  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.
4632
4821
  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.
4633
4822
 
@@ -4642,7 +4831,7 @@ Repeat from step 1. Between rounds, \`armada inbox --wait\` blocks until a new i
4642
4831
  `;
4643
4832
 
4644
4833
  // ../../skills/armada-runtime-conductor/SKILL.md
4645
- var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.2; if a flag is refused, compare with `conductor <command> --help`.\n\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication (`conductor auth status`), 4 server error.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12` (with `--profile <name> --reason \"<why>\"` when you override the routed profile). Read the profile (agent, model, effort, fast mode), the environment table and the warnings. Resolve every warning first: an open blocker, a ticket already in flight. Export each required variable the table marks `NOT set in this shell`. One marked `in credentials file` is in Armada's machine store: keep the `set -a` line of the launch command below, which loads that file without printing it.\n3. Write the prompt to a file, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket):\n\n```sh\narmada brief ABC-12 --prompt > /tmp/abc-12-brief.md\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode; drop an optional `--env` line whose variable you do not have. Run the whole block as one command: shell state does not carry over between separate calls, and the subshell keeps the keys out of the rest of your session. Drop the `set -a` line when every variable is set in your shell.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n --env ARMADA_TURSO_URL=\"$ARMADA_TURSO_URL\" \\\n --env ARMADA_TURSO_TOKEN=\"$ARMADA_TURSO_TOKEN\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace. The brief's first commands install your Armada version (`npm install -g`) and claim the ticket with them. `--env` values are not shown back by `workspace get`.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after ten minutes: read the transcript (Status section). If the worker cannot claim (for example a missing key), fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from; the third, each turn's final reply; the fourth, the commands and tools the worker ran. `.content.rawPayload` is the agent's own event format: these filters read the `claude` agent; for another agent, look at one event and adapt the filter.\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n";
4834
+ var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12` (with `--profile <name> --reason \"<why>\"` when you override the routed profile). Read the profile (agent, model, effort, fast mode), the environment table and the warnings. Resolve every warning first: an open blocker, a ticket already in flight. Export each required variable the table marks `NOT set in this shell`. One marked `in credentials file` is in Armada's machine store: keep the `set -a` line of the launch command below, which loads that file without printing it.\n3. Write the prompt to a file, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket):\n\n```sh\narmada brief ABC-12 --prompt > /tmp/abc-12-brief.md\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode; drop an optional `--env` line whose variable you do not have. Run the whole block as one command: shell state does not carry over between separate calls, and the subshell keeps the keys out of the rest of your session. Drop the `set -a` line when every variable is set in your shell.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n --env ARMADA_TURSO_URL=\"$ARMADA_TURSO_URL\" \\\n --env ARMADA_TURSO_TOKEN=\"$ARMADA_TURSO_TOKEN\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace. The brief's first commands install your Armada version (`npm install -g`) and claim the ticket with them. `--env` values are not shown back by `workspace get`.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after ten minutes: read the transcript (Status section). If the worker cannot claim (for example a missing key), fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n";
4646
4835
 
4647
4836
  // ../../skills/armada-worker/SKILL.md
4648
4837
  var SKILL_default3 = `---
@@ -5046,7 +5235,7 @@ async function loadStatus(config, opts) {
5046
5235
  });
5047
5236
  }
5048
5237
  // package.json
5049
- var version = "0.1.13";
5238
+ var version = "0.1.15";
5050
5239
 
5051
5240
  // src/io.ts
5052
5241
  class UsageError extends Error {
@@ -5176,6 +5365,11 @@ function buildAuthStatus(machine, credentials) {
5176
5365
  mode: machine.store.mode === null ? null : octal(machine.store.mode)
5177
5366
  } : null,
5178
5367
  personalConfig: machine.paths && machine.personal ? { path: machine.paths.config, exists: machine.personal.exists } : null,
5368
+ signIn: {
5369
+ api: credentials.armadaApi,
5370
+ method: credentials.armadaSignIn?.kind ?? null,
5371
+ source: credentials.armadaSignIn?.source ?? null
5372
+ },
5179
5373
  warnings: storeWarnings(machine)
5180
5374
  };
5181
5375
  }
@@ -5193,6 +5387,10 @@ function renderAuthStatus(status) {
5193
5387
  lines.push(`Personal config ${status.personalConfig.path}${status.personalConfig.exists ? "" : " (not created yet)"}`);
5194
5388
  for (const w of status.warnings)
5195
5389
  lines.push(`! ${w}`);
5390
+ const { signIn } = status;
5391
+ const api = signIn.api.source.kind === "default" ? "built in" : describeSource(signIn.api.source);
5392
+ lines.push("", "Armada sign-in", ` API ${signIn.api.url} (${api})`);
5393
+ lines.push(signIn.method && signIn.source ? ` Signed in with ${signIn.method === "session" ? "the session of `armada login`" : "an organization API key"}, from the ${describeSource(signIn.source)}; \`armada whoami\` shows who` : " Signed in no: run `armada login`, or set ARMADA_API_KEY on a headless coordinator");
5196
5394
  return `${lines.join(`
5197
5395
  `)}
5198
5396
  `;
@@ -5746,8 +5944,12 @@ async function inbox2(io, config, credentials, a) {
5746
5944
  if (!db)
5747
5945
  throw new Refusal(`the inbox lives in Turso, which is unavailable: ${warning ?? "no answer"}`, "armada inbox again once Turso answers (armada auth status shows the URL in use)");
5748
5946
  try {
5947
+ const workspace = io.env.CONDUCTOR_WORKSPACE_ID?.trim();
5948
+ const session = io.env.CONDUCTOR_SESSION_ID?.trim();
5949
+ const coordinator = io.env.ARMADA_COORDINATOR_HANDLE?.trim() || (workspace && session ? `${workspace}/${session}` : null);
5749
5950
  const report = await checkInbox(db, {
5750
5951
  project: config.project.slug,
5952
+ coordinator,
5751
5953
  silentAfterMinutes: config.policy.silentAfterMinutes,
5752
5954
  now: io.now ?? (() => new Date),
5753
5955
  ...wait ? { wait: { timeoutMs, sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))) } } : {}
@@ -5955,6 +6157,148 @@ async function init(io, opts) {
5955
6157
  }
5956
6158
  }
5957
6159
 
6160
+ // src/login.ts
6161
+ var hostOf = (url) => {
6162
+ try {
6163
+ return new URL(url).host;
6164
+ } catch {
6165
+ return url;
6166
+ }
6167
+ };
6168
+ var apiOf = (io, url) => armadaApi({ url, ...io.fetch ? { fetch: io.fetch } : {} });
6169
+ var storedAt = (machine) => armadaAddress(machine.store?.values[SIGNED_IN_TO_VARIABLE]?.trim() || DEFAULT_ARMADA_API_URL);
6170
+ var sleepOf = (io) => io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
6171
+ function requireSignIn(credentials) {
6172
+ if (credentials.armadaSignIn)
6173
+ return credentials.armadaSignIn;
6174
+ const elsewhere = credentials.armadaSignInElsewhere;
6175
+ if (elsewhere)
6176
+ throw new UsageError(`this terminal is signed in to ${hostOf(elsewhere)}, not to ${hostOf(credentials.armadaApi.url)} (named by ARMADA_API_URL or [api] url); its sign-in is never sent to another Armada`, `armada login to sign in to ${hostOf(credentials.armadaApi.url)}, or point ARMADA_API_URL back to ${elsewhere}`);
6177
+ throw new UsageError(`not signed in to Armada (${hostOf(credentials.armadaApi.url)}). A person signs in with \`armada login\`; a headless coordinator sets ${API_KEY_VARIABLE} to an organization API key`, LOGIN_NEXT);
6178
+ }
6179
+ function describeIdentity(identity) {
6180
+ const org = identity.organization ? `${identity.organization.name}${identity.organization.role ? ` (${identity.organization.role})` : ""}` : "no organization yet";
6181
+ if (identity.via === "api-key") {
6182
+ const key = identity.apiKey?.name ?? identity.apiKey?.start ?? "an API key";
6183
+ return `the API key "${key}" of ${org}`;
6184
+ }
6185
+ const who = identity.user ? identity.user.name ? `${identity.user.name} <${identity.user.email}>` : identity.user.email : "?";
6186
+ return `${who}, ${org}`;
6187
+ }
6188
+ function paths(io) {
6189
+ const p = machinePaths(io.env);
6190
+ if (p)
6191
+ return p;
6192
+ throw new UsageError(`neither HOME nor XDG_CONFIG_HOME is set, so this machine has no place to keep a sign-in. Set ${API_KEY_VARIABLE} in the environment instead.`);
6193
+ }
6194
+ async function readApiKey(io) {
6195
+ if (io.interactive && io.prompt)
6196
+ return io.prompt("Armada API key (hidden): ", { hidden: true });
6197
+ if (io.readStdin)
6198
+ return io.readStdin();
6199
+ return null;
6200
+ }
6201
+ async function loginWithApiKey(io, credentials) {
6202
+ const p = paths(io);
6203
+ const answer = await readApiKey(io);
6204
+ if (answer === null) {
6205
+ io.stderr(`Cancelled. Nothing was saved.
6206
+ `);
6207
+ return 130;
6208
+ }
6209
+ const key = answer.trim();
6210
+ if (!key)
6211
+ throw new UsageError('no API key given. Paste it at the prompt, or pipe it in: printf %s "$KEY" | armada login --api-key', "the Organization page of Armada, where an owner creates one");
6212
+ const url = credentials.armadaApi.url;
6213
+ const identity = await apiOf(io, url).whoami({ kind: "api-key", key });
6214
+ await updateCredentialStore(p, {
6215
+ [API_KEY_VARIABLE]: key,
6216
+ [SESSION_TOKEN_VARIABLE]: null,
6217
+ [SIGNED_IN_TO_VARIABLE]: armadaAddress(url)
6218
+ });
6219
+ io.stdout(`Signed in to ${hostOf(credentials.armadaApi.url)} as ${describeIdentity(identity)}.
6220
+ The key is stored in ${p.credentials}.
6221
+ `);
6222
+ return 0;
6223
+ }
6224
+ async function login(io, apiKey) {
6225
+ const { machine, credentials } = await loadCredentials(io);
6226
+ const host = hostOf(credentials.armadaApi.url);
6227
+ if (credentials.armadaSignIn?.source.kind === "env")
6228
+ io.stderr(`! ${API_KEY_VARIABLE} is set in the environment: it wins over what \`armada login\` stores.
6229
+ `);
6230
+ if (apiKey)
6231
+ return loginWithApiKey(io, credentials);
6232
+ const p = paths(io);
6233
+ const url = credentials.armadaApi.url;
6234
+ const api = apiOf(io, url);
6235
+ const code = await api.startDeviceLogin();
6236
+ io.stderr(`First copy your one-time code: ${displayCode(code.userCode)}
6237
+ Then confirm it at ${code.verificationUriComplete}
6238
+ `);
6239
+ if (io.interactive && io.openUrl?.(code.verificationUriComplete))
6240
+ io.stderr(`Opening it in your browser.
6241
+ `);
6242
+ io.stderr(`Waiting for the confirmation (the code expires in ${Math.round(code.expiresInSeconds / 60)} minutes)…
6243
+ `);
6244
+ const token = await waitForApproval({ api, code, sleep: sleepOf(io), now: io.now ?? (() => new Date) });
6245
+ const identity = await api.whoami({ kind: "session", token });
6246
+ const previous = machine.store?.values[SESSION_TOKEN_VARIABLE]?.trim();
6247
+ await updateCredentialStore(p, {
6248
+ [SESSION_TOKEN_VARIABLE]: token,
6249
+ [API_KEY_VARIABLE]: null,
6250
+ [SIGNED_IN_TO_VARIABLE]: armadaAddress(url)
6251
+ });
6252
+ if (previous && previous !== token)
6253
+ await apiOf(io, storedAt(machine)).signOut({ kind: "session", token: previous }).catch(() => {});
6254
+ io.stdout(`Signed in to ${host} as ${describeIdentity(identity)}.
6255
+ `);
6256
+ if (!identity.organization)
6257
+ io.stdout(`Next: accept an invitation, or create an organization, at ${new URL("welcome", apiBaseUrl(credentials.armadaApi.url))}
6258
+ `);
6259
+ return 0;
6260
+ }
6261
+ async function whoami(io, json) {
6262
+ const { credentials } = await loadCredentials(io);
6263
+ const signIn = requireSignIn(credentials);
6264
+ const identity = await apiOf(io, credentials.armadaApi.url).whoami(signIn);
6265
+ if (json) {
6266
+ const out = { ...identity, api: credentials.armadaApi.url, source: signIn.source };
6267
+ io.stdout(`${JSON.stringify(out, null, 2)}
6268
+ `);
6269
+ return 0;
6270
+ }
6271
+ io.stdout(`Signed in to ${hostOf(credentials.armadaApi.url)} as ${describeIdentity(identity)}.
6272
+ `);
6273
+ return 0;
6274
+ }
6275
+ async function logout(io) {
6276
+ const { machine } = await loadCredentials(io);
6277
+ const p = paths(io);
6278
+ const at = storedAt(machine);
6279
+ const stored = [SESSION_TOKEN_VARIABLE, API_KEY_VARIABLE].filter((k) => machine.store?.assigned.includes(k));
6280
+ const session = machine.store?.values[SESSION_TOKEN_VARIABLE]?.trim();
6281
+ if (session) {
6282
+ await apiOf(io, at).signOut({ kind: "session", token: session }).catch((err) => io.stderr(`! the session could not be revoked on Armada (${err instanceof Error ? err.message : String(err)}); it expires on its own
6283
+ `));
6284
+ }
6285
+ if (stored.length) {
6286
+ await updateCredentialStore(p, {
6287
+ [SESSION_TOKEN_VARIABLE]: null,
6288
+ [API_KEY_VARIABLE]: null,
6289
+ [SIGNED_IN_TO_VARIABLE]: null
6290
+ });
6291
+ io.stdout(`Signed out of ${hostOf(at)}: removed the sign-in from ${p.credentials}.
6292
+ `);
6293
+ } else
6294
+ io.stdout(`This terminal was not signed in to Armada (nothing in ${p.credentials}).
6295
+ `);
6296
+ if (io.env[API_KEY_VARIABLE]?.trim())
6297
+ io.stdout(`${API_KEY_VARIABLE} is still set in the environment, and still signs this terminal in. Unset it to stop.
6298
+ `);
6299
+ return 0;
6300
+ }
6301
+
5958
6302
  // src/merge.ts
5959
6303
  import { randomUUID } from "node:crypto";
5960
6304
  import { rm as rm4 } from "node:fs/promises";
@@ -6375,6 +6719,14 @@ var COMMAND_HELP = {
6375
6719
  The profile follows [[conductor.routing]] on the ticket's labels, then
6376
6720
  default_profile; --profile overrides it, with --reason when it differs.
6377
6721
  --prompt prints only the prompt, for \`--message-file -\`
6722
+ `,
6723
+ login: ` login Sign this terminal in to Armada: confirm the code it shows in the browser
6724
+ login --api-key Sign a headless coordinator in with an organization API key, read from a
6725
+ hidden prompt or standard input (ARMADA_API_KEY in the environment also works)
6726
+ `,
6727
+ whoami: ` whoami The person or API key this terminal is signed in as, and its organization
6728
+ `,
6729
+ logout: ` logout Sign this terminal out of Armada: revoke its session, remove it from the machine
6378
6730
  `,
6379
6731
  auth: ` auth login Ask for the missing keys (hidden input) and store them on this machine
6380
6732
  auth status Show which keys are set and where each comes from, never their values
@@ -6383,7 +6735,7 @@ var COMMAND_HELP = {
6383
6735
  };
6384
6736
  var TICKET_OPTION = new Set(["report", "release", "ask", "merge"]);
6385
6737
  var CONFIG_OPTION = new Set(["status", "claim", "report", "release", "ask", "inbox", "answer", "merge", "brief"]);
6386
- var JSON_OPTION = new Set([...CONFIG_OPTION, "doctor", "auth"]);
6738
+ var JSON_OPTION = new Set([...CONFIG_OPTION, "doctor", "auth", "whoami"]);
6387
6739
  var TICKET_HELP = ` --ticket <id> Ticket for report, release and ask (default ARMADA_TICKET, then the git
6388
6740
  branch) and for merge (default: the ticket the PR branch names)
6389
6741
  `;
@@ -6405,11 +6757,14 @@ Keys (the environment always wins over the file):
6405
6757
  ARMADA_TURSO_TOKEN Turso database token
6406
6758
  GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
6407
6759
  (merge also runs gh and git, with gh's own login)
6760
+ ARMADA_API_KEY Organization API key: signs a headless coordinator in to Armada
6761
+ ARMADA_API_URL The Armada to sign in to (default https://armada.thevibecompany.co)
6408
6762
 
6409
6763
  Files:
6410
6764
  $XDG_CONFIG_HOME/armada (default ~/.config/armada)
6411
- credentials KEY=value lines, mode 0600, written by \`armada auth login\`
6412
- config.toml personal defaults: language, [turso] url, [dashboard] url
6765
+ credentials KEY=value lines, mode 0600, written by \`armada auth login\` and
6766
+ \`armada login\` (the sign-in: ARMADA_SESSION_TOKEN or ARMADA_API_KEY)
6767
+ config.toml personal defaults: language, [turso] url, [dashboard] url, [api] url
6413
6768
  `;
6414
6769
  function commandHelp(command) {
6415
6770
  const block = Object.hasOwn(COMMAND_HELP, command) ? COMMAND_HELP[command] : undefined;
@@ -6446,7 +6801,7 @@ var VALUE_OPTIONS = [
6446
6801
  "options",
6447
6802
  "timeout"
6448
6803
  ];
6449
- var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note"];
6804
+ var FLAG_OPTIONS = ["dry-run", "no-lock", "prompt", "wait", "note", "api-key"];
6450
6805
  var COMMAND_OPTIONS = {
6451
6806
  claim: ["runtime", "handle", "branch", "profile", "reason"],
6452
6807
  report: ["ticket", "message", "message-file", "pr", "sha"],
@@ -6456,7 +6811,8 @@ var COMMAND_OPTIONS = {
6456
6811
  answer: ["note", "message", "message-file"],
6457
6812
  init: ["program-root", "name", "slug"],
6458
6813
  merge: ["ticket", "dry-run", "no-lock"],
6459
- brief: ["profile", "reason", "prompt"]
6814
+ brief: ["profile", "reason", "prompt"],
6815
+ login: ["api-key"]
6460
6816
  };
6461
6817
  function parseArgs(argv) {
6462
6818
  const args = {
@@ -6492,7 +6848,7 @@ function parseArgs(argv) {
6492
6848
  else
6493
6849
  args.options[name] = v;
6494
6850
  } else if (a?.startsWith("-"))
6495
- throw new UsageError(`unknown option ${a}`);
6851
+ throw new UsageError(`unknown option ${name ? `--${name}${named?.[2] !== undefined ? "=…" : ""}` : a}`);
6496
6852
  else if (!args.command && a)
6497
6853
  args.command = a;
6498
6854
  else if (a)
@@ -6555,6 +6911,8 @@ function commandOf(argv) {
6555
6911
  function nextStep(err, command) {
6556
6912
  if (err instanceof Refusal)
6557
6913
  return err.next;
6914
+ if (err instanceof ArmadaApiError)
6915
+ return err.next;
6558
6916
  if (err instanceof UsageError)
6559
6917
  return err.next ?? (command ? `armada ${command} --help` : "armada --help, which lists every command");
6560
6918
  if (err instanceof ConfigError)
@@ -6623,6 +6981,15 @@ async function run(argv, io) {
6623
6981
  slug: args.options.slug ?? null
6624
6982
  });
6625
6983
  }
6984
+ if (args.command === "login" || args.command === "logout" || args.command === "whoami") {
6985
+ if (args.rest.length)
6986
+ throw new UsageError(`${args.command} takes no argument${args.command === "login" ? ": an API key is read from a hidden prompt or standard input, never from the command line" : ""}`);
6987
+ if (args.command === "login")
6988
+ return await login(io, args.options["api-key"] === "true");
6989
+ if (args.command === "logout")
6990
+ return await logout(io);
6991
+ return await whoami(io, args.json);
6992
+ }
6626
6993
  if (args.command === "auth") {
6627
6994
  const [sub, ...extra] = args.rest;
6628
6995
  noExtra(extra);
@@ -6726,6 +7093,21 @@ function prompt(question, { hidden }) {
6726
7093
  stdin.resume();
6727
7094
  });
6728
7095
  }
7096
+ function openUrl(url) {
7097
+ if (!/^https?:\/\//.test(url))
7098
+ return false;
7099
+ if (process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
7100
+ return false;
7101
+ const [command, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
7102
+ try {
7103
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
7104
+ child.on("error", () => {});
7105
+ child.unref();
7106
+ return true;
7107
+ } catch {
7108
+ return false;
7109
+ }
7110
+ }
6729
7111
  var exec = (command, args, { cwd }) => new Promise((done, fail) => {
6730
7112
  const child = spawn(command, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
6731
7113
  let stdout = "";
@@ -6754,6 +7136,7 @@ var code = await run(process.argv.slice(2), {
6754
7136
  prompt,
6755
7137
  gitBranch,
6756
7138
  readStdin,
6757
- exec
7139
+ exec,
7140
+ openUrl
6758
7141
  });
6759
7142
  process.exitCode = code;