@the-vibe-company/armada 0.2.49 → 0.2.51

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 (2) hide show
  1. package/dist/armada.js +625 -470
  2. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -10,318 +10,95 @@ import { isatty } from "node:tty";
10
10
  // src/cli.ts
11
11
  import { dirname as dirname9, join as join9, resolve as resolve3 } from "node:path";
12
12
 
13
- // ../core/src/types.ts
14
- var LABEL_PHASES = [
15
- "planning",
16
- "awaiting-approval",
17
- "implementing",
18
- "shipping",
19
- "blocked",
20
- "ready-to-merge",
21
- "awaiting-validation"
22
- ];
23
-
24
- // ../core/src/linear.ts
25
- var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
26
- var MAX_DEPTH = 8;
27
- var COMMENT_BATCH = 25;
28
- var MAX_COMMENTS = 100;
29
- var MORE_PAGE = 100;
30
- var REQUEST_TIMEOUT_MS = 30000;
31
-
32
- class LinearError extends Error {
33
- transport;
34
- name = "LinearError";
35
- constructor(message, transport = false) {
36
- super(message);
37
- this.transport = transport;
13
+ // ../core/src/http.ts
14
+ class HttpRequestError extends Error {
15
+ attempts;
16
+ name = "HttpRequestError";
17
+ constructor(error, timeoutMs, attempts) {
18
+ super(`${networkReason(error, timeoutMs)}${attempts > 1 ? "; failed after 2 attempts (one retry)" : ""}`);
19
+ this.attempts = attempts;
38
20
  }
39
21
  }
40
- var PHASES = [...LABEL_PHASES, "released", "merged"];
41
- var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
42
- var firstLine = (body) => (body.split(`
43
- `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
44
- var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
45
- var PLAN_BLOCK = /^## Plan[ \t]*$/m;
46
- function parseStatusLine(body) {
47
- const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
48
- if (!m?.[1])
49
- return null;
50
- const raw = m[1].toLowerCase();
51
- const phase = LEGACY[raw] ?? raw;
52
- const summary = (m[2] ?? "").trim();
53
- if (COORDINATOR_RECORD.test(summary))
54
- return null;
55
- if (!PHASES.includes(phase))
56
- return null;
57
- return PLAN_BLOCK.test(body) ? { phase, summary, plan: true } : { phase, summary };
58
- }
59
- var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
60
- var trimMarks = (v) => {
61
- const t = v.trim();
62
- return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
63
- };
64
- function parseClaim(body, at, author) {
65
- const line = body.split(`
66
- `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
67
- if (!line)
68
- return null;
69
- const field = (k) => {
70
- const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
71
- return v && trimMarks(v) || null;
72
- };
73
- const profileReason = body.split(`
74
- `).map(unescapeMarkdown).find((entry) => entry.startsWith("Profile reason: "))?.slice("Profile reason: ".length).trim();
75
- return {
76
- runtime: field("runtime"),
77
- session: field("session"),
78
- branch: field("branch|branche"),
79
- startedAt: field("started|démarré|demarre"),
80
- profile: field("profile"),
81
- ...profileReason ? { profileReason } : {},
82
- at,
83
- author
84
- };
85
- }
86
- function excerpt(markdown, max = 240) {
87
- const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
88
- return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
89
- }
90
- function parsePullRequestUrl(url, title = "") {
91
- const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
92
- return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
93
- }
94
- function agentLabels(labels, groups) {
95
- let agentPhase = null;
96
- for (const l of labels)
97
- if (l.group === groups.phaseGroup)
98
- agentPhase ??= phaseNamed(l.name);
99
- const runtime = labels.find((l) => l.group === groups.runtimeGroup);
100
- return { agentPhase, agentRuntime: runtime?.name ?? null };
101
- }
102
- var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
103
- var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
104
- function normalizeIssue(raw, groups) {
105
- const blockers = new Map;
106
- for (const r of raw.inverseRelations.nodes)
107
- if (r.type === "blocks")
108
- blockers.set(r.issue.identifier, { id: r.issue.identifier, statusType: r.issue.state.type });
109
- const prs = new Map;
110
- for (const a of raw.attachments.nodes) {
111
- const pr = parsePullRequestUrl(a.url, a.title);
112
- if (pr)
113
- prs.set(pr.url, pr);
114
- }
115
- for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
116
- const pr = parsePullRequestUrl(m[0]);
117
- if (pr && !prs.has(pr.url))
118
- prs.set(pr.url, pr);
119
- }
120
- const labels = raw.labels.nodes.map((l) => ({ name: l.name, group: l.parent?.name ?? null }));
121
- return {
122
- id: raw.identifier,
123
- uuid: raw.id,
124
- title: raw.title,
125
- url: raw.url,
126
- status: raw.state.name,
127
- statusType: raw.state.type,
128
- assignee: raw.assignee?.name ?? null,
129
- delegate: raw.delegate?.name ?? null,
130
- labels: labels.map((l) => l.name),
131
- ...agentLabels(labels, groups),
132
- parentId: raw.parent?.identifier ?? null,
133
- createdAt: raw.createdAt,
134
- updatedAt: raw.updatedAt,
135
- startedAt: raw.startedAt,
136
- completedAt: raw.completedAt,
137
- canceledAt: raw.canceledAt,
138
- blockedBy: [...blockers.values()].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
139
- prs: [...prs.values()].sort((a, b) => a.number - b.number)
140
- };
141
- }
142
- function normalizeComment(raw, issueId) {
143
- const author = raw.user?.name ?? null;
144
- return {
145
- id: raw.id,
146
- issueId,
147
- author,
148
- createdAt: raw.createdAt,
149
- excerpt: excerpt(raw.body, 600),
150
- status: parseStatusLine(raw.body),
151
- claim: parseClaim(raw.body, raw.createdAt, author)
152
- };
153
- }
154
- var MORE = {
155
- inverseRelations: {
156
- field: "inverseRelations",
157
- nodes: "type issue { identifier state { type } }",
158
- operation: "MoreRelations",
159
- what: "relations"
160
- },
161
- labels: { field: "labels", nodes: "name parent { name }", operation: "MoreLabels", what: "labels" },
162
- attachments: { field: "attachments", nodes: "title url", operation: "MoreAttachments", what: "attachments" },
163
- comments: {
164
- field: "comments",
165
- nodes: "id createdAt body user { name }",
166
- operation: "MoreComments",
167
- what: "comments"
168
- }
169
- };
170
- var MORE_QUERY = (m) => `
171
- query ${m.operation}($id: String!, $after: String) {
172
- issue(id: $id) {
173
- ${m.field}(first: ${m.first ?? MORE_PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${m.nodes} } }
174
- }
175
- }`;
176
- var FIELDS = (delegate) => `
177
- fragment F on Issue {
178
- id identifier title url description createdAt updatedAt startedAt completedAt canceledAt
179
- state { name type }
180
- assignee { name }
181
- ${delegate ? "delegate { name }" : ""}
182
- parent { identifier }
183
- labels(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.labels.nodes} } }
184
- attachments(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.attachments.nodes} } }
185
- inverseRelations(first: 50) { pageInfo { hasNextPage endCursor } nodes { ${MORE.inverseRelations.nodes} } }
186
- }
187
- `;
188
- var ROOT_QUERY = (d) => `${FIELDS(d)} query Root($id: String!) { issue(id: $id) { ...F } }`;
189
- var CHILDREN_QUERY = (d) => `${FIELDS(d)}
190
- query Children($parents: [ID!], $after: String) {
191
- issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
192
- pageInfo { hasNextPage endCursor }
193
- nodes { ...F }
194
- }
195
- }`;
196
- var COMMENTS_QUERY = `
197
- query Comments($ids: [ID!]) {
198
- issues(first: 50, filter: { id: { in: $ids } }) {
199
- nodes { identifier comments(first: ${MAX_COMMENTS}) { pageInfo { hasNextPage endCursor } nodes { ${MORE.comments.nodes} } } }
200
- }
201
- }`;
202
- async function gql(opts, query, variables) {
203
- const doFetch = opts.fetch ?? fetch;
204
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
205
- const res = await doFetch(LINEAR_ENDPOINT, {
206
- method: "POST",
207
- headers: { "Content-Type": "application/json", Authorization: opts.apiKey },
208
- body: JSON.stringify({ query, variables }),
209
- signal: AbortSignal.timeout(timeoutMs)
210
- }).catch((err) => {
211
- throw new LinearError(`Linear API unreachable: ${networkReason(err, timeoutMs)}`, true);
212
- });
213
- if (res.status === 401)
214
- throw new LinearError("Linear rejected the API key (HTTP 401); check LINEAR_API_KEY", true);
215
- const json = await res.json().catch(() => ({}));
216
- if (json.errors?.length)
217
- throw new LinearError(`Linear API: ${json.errors.map((e) => e.message).join("; ")}`);
218
- if (!res.ok)
219
- throw new LinearError(`Linear API HTTP ${res.status}`, true);
220
- if (!json.data)
221
- throw new LinearError("Linear API: empty response");
222
- return json.data;
223
- }
224
22
  function networkReason(err, timeoutMs) {
225
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
226
- return `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`;
227
- return err instanceof Error ? err.message : String(err);
228
- }
229
- var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
230
- var CLOSED = new Set(["completed", "canceled"]);
231
- var isCandidate = (i, rootId) => i.id !== rootId && !CLOSED.has(i.statusType) && (i.agentPhase !== null || i.statusType === "started");
232
- async function readComments(opts, issues, warnings) {
233
- const comments = [];
234
- for (const batch of chunks(issues.map((i) => i.uuid), COMMENT_BATCH)) {
235
- const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
236
- for (const n of data.issues.nodes) {
237
- await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
238
- for (const c of n.comments.nodes)
239
- comments.push(normalizeComment(c, n.identifier));
240
- }
241
- }
242
- return comments;
243
- }
244
- async function fetchProgram(opts) {
245
- try {
246
- return await fetchTree(opts, true);
247
- } catch (err) {
248
- if (err instanceof LinearError && /delegate/i.test(err.message))
249
- return fetchTree(opts, false);
250
- throw err;
251
- }
252
- }
253
- async function fetchTree(opts, delegate) {
254
- const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
255
- if (!root)
256
- throw new LinearError(`Linear: program root ${opts.rootId} not found`);
257
- const all = [root];
258
- const warnings = [];
259
- let parents = [root.id];
260
- for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
261
- const next = [];
262
- let after = null;
263
- for (;; ) {
264
- const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
265
- all.push(...data.issues.nodes);
266
- next.push(...data.issues.nodes.map((n) => n.id));
267
- const { hasNextPage, endCursor } = data.issues.pageInfo;
268
- if (!hasNextPage)
269
- break;
270
- if (!endCursor || endCursor === after) {
271
- warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
272
- break;
273
- }
274
- after = endCursor;
275
- }
276
- parents = next;
277
- }
278
- if (parents.length)
279
- warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
280
- for (const r of all)
281
- for (const field of ["inverseRelations", "labels", "attachments"])
282
- await readRest(opts, r.identifier, MORE[field], r[field], warnings);
283
- const issues = all.map((r) => normalizeIssue(r, opts.labels));
284
- const comments = await readComments(opts, issues.filter((i) => isCandidate(i, root.identifier)), warnings);
285
- return {
286
- rootId: root.identifier,
287
- fetchedAt: (opts.now?.() ?? new Date).toISOString(),
288
- issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
289
- comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
290
- warnings
291
- };
292
- }
293
- async function readRest(opts, identifier, more, conn, warnings) {
294
- while (conn.pageInfo?.hasNextPage) {
295
- const after = conn.pageInfo.endCursor;
296
- try {
297
- if (!after)
298
- throw new LinearError("Linear gave no cursor for the next page");
299
- const data = await gql(opts, MORE_QUERY(more), {
300
- id: identifier,
301
- after
302
- });
303
- const page = data.issue?.[more.field];
304
- if (!page)
305
- throw new LinearError(`Linear: issue ${identifier} not found`);
306
- conn.nodes.push(...page.nodes);
307
- conn.pageInfo = page.pageInfo;
308
- if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
309
- throw new LinearError("Linear did not advance to a next page");
310
- } catch (err) {
311
- if (!(err instanceof LinearError) || err.transport)
312
- throw err;
313
- warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
314
- return;
315
- }
23
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
24
+ return `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`;
25
+ const code = codeOf(err);
26
+ const message = err instanceof Error ? err.message : String(err);
27
+ return code && !message.includes(code) ? `${message} (${code})` : message;
28
+ }
29
+ function codeOf(error) {
30
+ for (let depth = 0;depth < 4 && error && typeof error === "object"; depth++) {
31
+ const e = error;
32
+ if (typeof e.code === "string" && /^(?:E[A-Z_]+|UND_ERR_[A-Z_]+|ConnectionClosed|ConnectionRefused)$/.test(e.code))
33
+ return e.code;
34
+ error = e.cause;
316
35
  }
36
+ return null;
317
37
  }
318
- var CHANGED_COMMENTS_QUERY = `
319
- query ChangedComments($filter: CommentFilter, $after: String) {
320
- comments(first: ${MORE_PAGE}, after: $after, filter: $filter) {
321
- pageInfo { hasNextPage endCursor }
322
- nodes { ${MORE.comments.nodes} issue { identifier } }
38
+ function transient(error) {
39
+ if (!(error instanceof Error))
40
+ return false;
41
+ if (error.name === "TimeoutError" || error.name === "AbortError")
42
+ return true;
43
+ const code = codeOf(error);
44
+ if (code)
45
+ return /^(?:ECONNRESET|ECONNREFUSED|EPIPE|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|UND_ERR_(?:CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT|SOCKET)|ConnectionClosed|ConnectionRefused)$/.test(code);
46
+ return error instanceof TypeError && error.message === "fetch failed";
47
+ }
48
+ async function httpRequest(url, init, opts, read) {
49
+ init.signal?.throwIfAborted();
50
+ const doFetch = opts.fetch ?? fetch;
51
+ const attempts = opts.retry ? 2 : 1;
52
+ for (let attempt = 1;attempt <= attempts; attempt++) {
53
+ const limit = opts.retry ? Math.min(opts.timeoutMs ?? 30000, attempt === 1 ? 5000 : 1e4) : opts.timeoutMs ?? 30000;
54
+ const deadline = (opts.timeoutSignal ?? AbortSignal.timeout)(limit);
55
+ const controller = new AbortController;
56
+ const signal = init.signal ? AbortSignal.any([controller.signal, init.signal]) : controller.signal;
57
+ let response;
58
+ let fetchFailed = false;
59
+ let onDeadline = () => {};
60
+ const expired = new Promise((_resolve, reject) => {
61
+ onDeadline = () => {
62
+ controller.abort(deadline.reason);
63
+ reject(deadline.reason);
64
+ };
65
+ deadline.addEventListener("abort", onDeadline, { once: true });
66
+ if (deadline.aborted)
67
+ onDeadline();
68
+ });
69
+ try {
70
+ return await Promise.race([
71
+ expired,
72
+ (async () => {
73
+ try {
74
+ response = await doFetch(url, { ...init, signal });
75
+ signal.throwIfAborted();
76
+ } catch (error) {
77
+ fetchFailed = true;
78
+ throw error;
79
+ }
80
+ return read(response);
81
+ })()
82
+ ]);
83
+ } catch (error) {
84
+ if (init.signal?.aborted || error instanceof Error && error.name === "AbortError" && !deadline.aborted)
85
+ throw error;
86
+ const cause = deadline.aborted ? deadline.reason : error;
87
+ const transport = fetchFailed || deadline.aborted || transient(cause);
88
+ if (!transport)
89
+ throw error;
90
+ if (attempt < attempts && (!response || response.ok) && transient(cause))
91
+ continue;
92
+ throw new HttpRequestError(cause, limit, attempt);
93
+ } finally {
94
+ deadline.removeEventListener("abort", onDeadline);
95
+ controller.abort();
96
+ if (response?.body && !response.bodyUsed)
97
+ response.body.cancel().catch(() => {});
323
98
  }
324
- }`;
99
+ }
100
+ throw new Error("unreachable request attempt");
101
+ }
325
102
 
326
103
  // ../core/src/armada-api.ts
327
104
  var MASKED_LAUNCH_TOKEN = "armada_launch_••••";
@@ -386,7 +163,6 @@ function apiBaseUrl(value) {
386
163
  }
387
164
  function armadaApi(opts) {
388
165
  const base = apiBaseUrl(opts.url);
389
- const doFetch = opts.fetch ?? fetch;
390
166
  const timeoutMs = opts.timeoutMs ?? TIMEOUT_MS;
391
167
  const host = base.host;
392
168
  let serverCli = null;
@@ -401,31 +177,37 @@ function armadaApi(opts) {
401
177
  headers["x-api-key"] = init.signIn.key;
402
178
  if (opts.version)
403
179
  headers[CLI_VERSION_HEADER] = opts.version;
404
- const res = await doFetch(new URL(`api/cli/${path}`, base).toString(), {
180
+ return httpRequest(new URL(`api/cli/${path}`, base).toString(), {
405
181
  method,
406
182
  headers,
407
- ...init.body ? { body: JSON.stringify(init.body) } : {},
408
- signal: AbortSignal.timeout(limit)
183
+ ...init.body ? { body: JSON.stringify(init.body) } : {}
184
+ }, { fetch: opts.fetch, timeoutMs: limit, retry: init.retry ?? method === "GET" }, async (res) => {
185
+ const minimum = res.headers.get(CLI_MINIMUM_HEADER);
186
+ const latest = res.headers.get(CLI_LATEST_HEADER) || null;
187
+ if (minimum) {
188
+ serverCli = { minimum, latest };
189
+ opts.onServerCli?.(serverCli);
190
+ }
191
+ if (opts.version && minimum && compareVersions(opts.version, minimum) < 0) {
192
+ await res.body?.cancel().catch(() => {});
193
+ const install = versionToInstall(minimum, latest);
194
+ throw new ArmadaApiError(upgradeLine(opts.version, install), null, false, res.status, install);
195
+ }
196
+ if (res.status === 304)
197
+ return { status: 304, body: {} };
198
+ const body = await res.json().catch((err) => {
199
+ if (err instanceof SyntaxError)
200
+ return null;
201
+ throw err;
202
+ });
203
+ if (typeof body !== "object" || body === null || Array.isArray(body))
204
+ 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");
205
+ return { status: res.status, body };
409
206
  }).catch((err) => {
410
- throw new ArmadaApiError(`Armada (${host}) unreachable: ${networkReason(err, limit)}`, "the same command again once it answers, or check ARMADA_API_URL");
207
+ if (err instanceof HttpRequestError)
208
+ throw new ArmadaApiError(`Armada (${host}) unreachable: ${err.message} (${method} ${path})`, "the same command again once it answers, or check ARMADA_API_URL");
209
+ throw err;
411
210
  });
412
- const minimum = res.headers.get(CLI_MINIMUM_HEADER);
413
- const latest = res.headers.get(CLI_LATEST_HEADER) || null;
414
- if (minimum) {
415
- serverCli = { minimum, latest };
416
- opts.onServerCli?.(serverCli);
417
- }
418
- if (opts.version && minimum && compareVersions(opts.version, minimum) < 0) {
419
- await res.body?.cancel().catch(() => {});
420
- const install = versionToInstall(minimum, latest);
421
- throw new ArmadaApiError(upgradeLine(opts.version, install), null, false, res.status, install);
422
- }
423
- if (res.status === 304)
424
- return { status: 304, body: {} };
425
- const body = await res.json().catch(() => null);
426
- if (typeof body !== "object" || body === null || Array.isArray(body))
427
- 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");
428
- return { status: res.status, body };
429
211
  }
430
212
  const refusal = (status, body, what) => {
431
213
  const error = typeof body.error === "string" ? body.error : `HTTP ${status}`;
@@ -475,7 +257,11 @@ function armadaApi(opts) {
475
257
  return body;
476
258
  },
477
259
  async credentials(signIn, purpose = null) {
478
- const { status, body } = await call("POST", "credentials", { signIn, body: purpose ? { purpose } : {} });
260
+ const { status, body } = await call("POST", "credentials", {
261
+ signIn,
262
+ body: purpose ? { purpose } : {},
263
+ retry: true
264
+ });
479
265
  if (status !== 200)
480
266
  throw refusal(status, body, status === 401 ? null : "Armada gave no keys");
481
267
  const str = (v) => typeof v === "string" && v.length > 0;
@@ -513,7 +299,18 @@ function armadaApi(opts) {
513
299
  const { status, body: answer } = await call("POST", `fleet/${op}`, {
514
300
  signIn,
515
301
  body,
516
- ...timeoutMs ? { timeoutMs } : {}
302
+ ...timeoutMs ? { timeoutMs } : {},
303
+ retry: [
304
+ "events/latest",
305
+ "events/state",
306
+ "heartbeats/latest",
307
+ "runtime/handles",
308
+ "runtime/handle",
309
+ "launches",
310
+ "inbox/item",
311
+ "inbox/ticket",
312
+ "validations"
313
+ ].includes(op)
517
314
  });
518
315
  if (status === 304)
519
316
  return null;
@@ -524,7 +321,7 @@ function armadaApi(opts) {
524
321
  return answer.result;
525
322
  },
526
323
  async listSecrets(signIn, project) {
527
- const { status, body } = await call("POST", "secrets/list", { signIn, body: { project } });
324
+ const { status, body } = await call("POST", "secrets/list", { signIn, body: { project }, retry: true });
528
325
  if (status !== 200)
529
326
  throw refusal(status, body, status === 401 ? null : "Armada did not list the secrets");
530
327
  if (!Array.isArray(body.secrets))
@@ -696,10 +493,10 @@ function checkAttachment(input) {
696
493
  }
697
494
 
698
495
  // ../core/src/model.ts
699
- var CLOSED2 = ["completed", "canceled"];
496
+ var CLOSED = ["completed", "canceled"];
700
497
  var NOT_STARTED = ["triage", "backlog", "unstarted"];
701
498
  var isDone = (i) => i.statusType === "completed";
702
- var isClosed = (i) => CLOSED2.includes(i.statusType);
499
+ var isClosed = (i) => CLOSED.includes(i.statusType);
703
500
  var isStarted = (i) => i.statusType === "started";
704
501
  var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
705
502
  var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
@@ -822,6 +619,18 @@ function criticalIds(m) {
822
619
  return out;
823
620
  }
824
621
 
622
+ // ../core/src/types.ts
623
+ var isShippingStage = (value) => value === "review" || value === "ci";
624
+ var LABEL_PHASES = [
625
+ "planning",
626
+ "awaiting-approval",
627
+ "implementing",
628
+ "shipping",
629
+ "blocked",
630
+ "ready-to-merge",
631
+ "awaiting-validation"
632
+ ];
633
+
825
634
  // ../core/src/fleet.ts
826
635
  var MIN = 60000;
827
636
  var NEEDS_HUMAN = ["awaiting-approval", "awaiting-validation", "blocked", "ready-to-merge"];
@@ -862,6 +671,11 @@ var latest = (...xs) => xs.filter((x) => !!x).reduce((a, b) => b > a ? b : a, ""
862
671
  function workerLivenessAt(worker) {
863
672
  return latest(worker.lastHeartbeat, worker.lastReport) || worker.lastUpdate;
864
673
  }
674
+ function deriveShippingStage(pr) {
675
+ if (pr?.state !== "open")
676
+ return null;
677
+ return pr.ci && pr.ci !== "none" || pr.checks?.some((c) => c.state !== "none") ? "ci" : "review";
678
+ }
865
679
  function inferPhase(pr, comments) {
866
680
  if (pr?.state === "open")
867
681
  return pr.ci === "success" && pr.mergeable !== "CONFLICTING" ? "ready-to-merge" : "shipping";
@@ -902,6 +716,11 @@ function buildLane(m, allComments, issue, opts) {
902
716
  const shippingPhase = phase === "shipping" || phase === "ready-to-merge";
903
717
  if (pr?.state === "merged" && !isDone(issue) && (shippingPhase || phaseSource === "status-line" || phaseSource === "inferred"))
904
718
  phase = "merged";
719
+ const event = opts.live?.events[issue.id];
720
+ const claimedAt = opts.live?.handles?.[issue.id]?.claimedAt ?? claims.at(-1)?.at;
721
+ const leftShipping = comments.find((c) => c.status && c.status.phase !== "shipping");
722
+ const explicitStage = (event?.kind === "report" || event?.kind === "claim") && event.phase === "shipping" && (!claimedAt || event.at >= claimedAt) && (!leftShipping || event.at >= leftShipping.createdAt) ? event.shippingStage : null;
723
+ const shippingStage = phase === "shipping" ? explicitStage ?? deriveShippingStage(pr) : null;
905
724
  let announcing;
906
725
  for (const c of comments) {
907
726
  if (!c.status || c.status.phase === "released")
@@ -941,6 +760,7 @@ function buildLane(m, allComments, issue, opts) {
941
760
  spec: spec ? `Spec ${spec.ordinal}` : null,
942
761
  phase,
943
762
  phaseSource,
763
+ shippingStage,
944
764
  runtime: issue.agentRuntime ?? claimRuntime ?? fresh?.runtime ?? opts.live?.handles?.[issue.id]?.runtime ?? null,
945
765
  handle: opts.live?.handles?.[issue.id]?.handle ?? claims[0]?.session ?? fresh?.handle ?? null,
946
766
  claim: claims[0] ?? null,
@@ -2862,100 +2682,400 @@ function setHerdrPermissions(text, names, choice) {
2862
2682
  `) ? `\r
2863
2683
  ` : `
2864
2684
  `;
2865
- let insertAt = keyLine(profileLines, "effort");
2866
- insertAt = insertAt < 0 ? keyLine(profileLines, "model") : insertAt;
2867
- insertAt = insertAt < 0 ? 1 : insertAt + 1;
2868
- if (insertAt > 0 && insertAt <= profileLines.length) {
2869
- const previous = insertAt - 1;
2870
- profileLines[previous] = addLineBreak(profileLines[previous] ?? "", newline);
2871
- }
2872
- const sourceLine = profileLines.find((line) => keyAssignment(line, "harness")) ?? "";
2873
- const indent = sourceLine.match(/^\s*/)?.[0] ?? "";
2874
- profileLines.splice(insertAt, 0, `${indent}permissions = ${JSON.stringify(choice)}${newline}`);
2685
+ let insertAt = keyLine(profileLines, "effort");
2686
+ insertAt = insertAt < 0 ? keyLine(profileLines, "model") : insertAt;
2687
+ insertAt = insertAt < 0 ? 1 : insertAt + 1;
2688
+ if (insertAt > 0 && insertAt <= profileLines.length) {
2689
+ const previous = insertAt - 1;
2690
+ profileLines[previous] = addLineBreak(profileLines[previous] ?? "", newline);
2691
+ }
2692
+ const sourceLine = profileLines.find((line) => keyAssignment(line, "harness")) ?? "";
2693
+ const indent = sourceLine.match(/^\s*/)?.[0] ?? "";
2694
+ profileLines.splice(insertAt, 0, `${indent}permissions = ${JSON.stringify(choice)}${newline}`);
2695
+ }
2696
+ let profileSource = profileLines.join("");
2697
+ const existingArgs = profile.extra_args;
2698
+ if (choice === "ask" && existingArgs !== undefined) {
2699
+ if (!Array.isArray(existingArgs) || !existingArgs.every((arg) => typeof arg === "string"))
2700
+ throw new Error(`could not safely edit extra_args for profile "${name}"`);
2701
+ const assignment = arrayAssignment(profileSource, "extra_args");
2702
+ if (!assignment)
2703
+ throw new Error(`could not safely edit extra_args for profile "${name}"`);
2704
+ const scanned = assignment.scan.items.map((item) => item.value);
2705
+ if (canonicalToml(scanned) !== canonicalToml(existingArgs))
2706
+ throw new Error(`could not safely edit extra_args for profile "${name}"`);
2707
+ profileSource = removeArrayItems(profileSource, assignment, (arg) => arg.trim() === HERDR_FULL_PERMISSION_ARGS[harness]);
2708
+ const expectedProfile = expectedProfiles[name];
2709
+ expectedProfile.extra_args = existingArgs.filter((arg) => arg.trim() !== HERDR_FULL_PERMISSION_ARGS[harness]);
2710
+ }
2711
+ const updatedProfile = expectedProfiles[name];
2712
+ updatedProfile.permissions = choice;
2713
+ replacements.push({ start: section.start, end: section.end, source: profileSource });
2714
+ }
2715
+ const nextLines = [...lines];
2716
+ for (const replacement of replacements.sort((a, b) => b.start - a.start))
2717
+ nextLines.splice(replacement.start, replacement.end - replacement.start, ...linesOf(replacement.source));
2718
+ const next = nextLines.join("");
2719
+ if (canonicalToml(parse(next)) !== canonicalToml(expected))
2720
+ throw new Error("could not safely edit profile permissions");
2721
+ return next;
2722
+ }
2723
+ function setHerdrModel(text, name, model) {
2724
+ const raw = parse(text);
2725
+ const profiles = raw.herdr?.profiles;
2726
+ if (!profiles?.[name])
2727
+ throw new Error("profile is no longer present");
2728
+ const lines = text.split(/(?<=\n)/);
2729
+ let section = -1;
2730
+ let end = lines.length;
2731
+ for (let i = 0;i < lines.length; i++) {
2732
+ const header = lines[i]?.match(/^\s*\[herdr\s*\.\s*profiles\s*\.\s*(.+?)\]\s*(?:#.*)?(?:\r?\n)?$/);
2733
+ if (header) {
2734
+ const key = header[1]?.trim();
2735
+ if (key && Object.hasOwn(parse(`[${key}]
2736
+ `), name)) {
2737
+ section = i;
2738
+ break;
2739
+ }
2740
+ }
2741
+ }
2742
+ if (section < 0)
2743
+ throw new Error("use an explicit [herdr.profiles.<name>] section to save the model");
2744
+ for (let i = section + 1;i < lines.length; i++) {
2745
+ if (/^\s*\[/.test(lines[i] ?? "")) {
2746
+ end = i;
2747
+ break;
2748
+ }
2749
+ }
2750
+ let replaced = false;
2751
+ for (let i = section + 1;i < end; i++) {
2752
+ const match = lines[i]?.match(/^(\s*(?:model|"model"|'model')\s*=\s*)("(?:[^"\\]|\\.)*"|'[^']*')(.*?)(\r?\n)?$/);
2753
+ if (match) {
2754
+ const value = match[2]?.startsWith("'") && !model.includes("'") ? `'${model}'` : JSON.stringify(model);
2755
+ lines[i] = `${match[1]}${value}${match[3]}${match[4] ?? ""}`;
2756
+ replaced = true;
2757
+ break;
2758
+ }
2759
+ }
2760
+ if (!replaced) {
2761
+ const newline = text.includes(`\r
2762
+ `) ? `\r
2763
+ ` : `
2764
+ `;
2765
+ if (!(lines[section] ?? "").endsWith(`
2766
+ `))
2767
+ lines[section] += newline;
2768
+ lines.splice(section + 1, 0, `model = ${JSON.stringify(model)}${newline}`);
2769
+ }
2770
+ const next = lines.join("");
2771
+ profiles[name].model = model;
2772
+ if (JSON.stringify(parse(next)) !== JSON.stringify(raw)) {
2773
+ const canonical = (value) => JSON.stringify(value, (_, v) => typeof v === "object" && v !== null && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((key) => [key, v[key]])) : v);
2774
+ if (canonical(parse(next)) !== canonical(raw))
2775
+ throw new Error("could not safely edit the profile model");
2776
+ }
2777
+ return next;
2778
+ }
2779
+
2780
+ // ../core/src/linear.ts
2781
+ var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
2782
+ var MAX_DEPTH = 8;
2783
+ var COMMENT_BATCH = 25;
2784
+ var MAX_COMMENTS = 100;
2785
+ var MORE_PAGE = 100;
2786
+ class LinearError extends Error {
2787
+ transport;
2788
+ name = "LinearError";
2789
+ constructor(message, transport = false) {
2790
+ super(message);
2791
+ this.transport = transport;
2792
+ }
2793
+ }
2794
+ var PHASES = [...LABEL_PHASES, "released", "merged"];
2795
+ var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
2796
+ var firstLine = (body) => (body.split(`
2797
+ `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
2798
+ var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
2799
+ var PLAN_BLOCK = /^## Plan[ \t]*$/m;
2800
+ function parseStatusLine(body) {
2801
+ const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
2802
+ if (!m?.[1])
2803
+ return null;
2804
+ const raw = m[1].toLowerCase();
2805
+ const phase = LEGACY[raw] ?? raw;
2806
+ const summary = (m[2] ?? "").trim();
2807
+ if (COORDINATOR_RECORD.test(summary))
2808
+ return null;
2809
+ if (!PHASES.includes(phase))
2810
+ return null;
2811
+ return PLAN_BLOCK.test(body) ? { phase, summary, plan: true } : { phase, summary };
2812
+ }
2813
+ var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
2814
+ var trimMarks = (v) => {
2815
+ const t = v.trim();
2816
+ return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
2817
+ };
2818
+ function parseClaim(body, at, author) {
2819
+ const line = body.split(`
2820
+ `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
2821
+ if (!line)
2822
+ return null;
2823
+ const field = (k) => {
2824
+ const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
2825
+ return v && trimMarks(v) || null;
2826
+ };
2827
+ const profileReason = body.split(`
2828
+ `).map(unescapeMarkdown).find((entry) => entry.startsWith("Profile reason: "))?.slice("Profile reason: ".length).trim();
2829
+ return {
2830
+ runtime: field("runtime"),
2831
+ session: field("session"),
2832
+ branch: field("branch|branche"),
2833
+ startedAt: field("started|démarré|demarre"),
2834
+ profile: field("profile"),
2835
+ ...profileReason ? { profileReason } : {},
2836
+ at,
2837
+ author
2838
+ };
2839
+ }
2840
+ function excerpt(markdown, max = 240) {
2841
+ const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
2842
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
2843
+ }
2844
+ function parsePullRequestUrl(url, title = "") {
2845
+ const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
2846
+ return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
2847
+ }
2848
+ function agentLabels(labels, groups) {
2849
+ let agentPhase = null;
2850
+ for (const l of labels)
2851
+ if (l.group === groups.phaseGroup)
2852
+ agentPhase ??= phaseNamed(l.name);
2853
+ const runtime = labels.find((l) => l.group === groups.runtimeGroup);
2854
+ return { agentPhase, agentRuntime: runtime?.name ?? null };
2855
+ }
2856
+ var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
2857
+ var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
2858
+ function normalizeIssue(raw, groups) {
2859
+ const blockers = new Map;
2860
+ for (const r of raw.inverseRelations.nodes)
2861
+ if (r.type === "blocks")
2862
+ blockers.set(r.issue.identifier, { id: r.issue.identifier, statusType: r.issue.state.type });
2863
+ const prs = new Map;
2864
+ for (const a of raw.attachments.nodes) {
2865
+ const pr = parsePullRequestUrl(a.url, a.title);
2866
+ if (pr)
2867
+ prs.set(pr.url, pr);
2868
+ }
2869
+ for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
2870
+ const pr = parsePullRequestUrl(m[0]);
2871
+ if (pr && !prs.has(pr.url))
2872
+ prs.set(pr.url, pr);
2873
+ }
2874
+ const labels = raw.labels.nodes.map((l) => ({ name: l.name, group: l.parent?.name ?? null }));
2875
+ return {
2876
+ id: raw.identifier,
2877
+ uuid: raw.id,
2878
+ title: raw.title,
2879
+ url: raw.url,
2880
+ status: raw.state.name,
2881
+ statusType: raw.state.type,
2882
+ assignee: raw.assignee?.name ?? null,
2883
+ delegate: raw.delegate?.name ?? null,
2884
+ labels: labels.map((l) => l.name),
2885
+ ...agentLabels(labels, groups),
2886
+ parentId: raw.parent?.identifier ?? null,
2887
+ createdAt: raw.createdAt,
2888
+ updatedAt: raw.updatedAt,
2889
+ startedAt: raw.startedAt,
2890
+ completedAt: raw.completedAt,
2891
+ canceledAt: raw.canceledAt,
2892
+ blockedBy: [...blockers.values()].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
2893
+ prs: [...prs.values()].sort((a, b) => a.number - b.number)
2894
+ };
2895
+ }
2896
+ function normalizeComment(raw, issueId) {
2897
+ const author = raw.user?.name ?? null;
2898
+ return {
2899
+ id: raw.id,
2900
+ issueId,
2901
+ author,
2902
+ createdAt: raw.createdAt,
2903
+ excerpt: excerpt(raw.body, 600),
2904
+ status: parseStatusLine(raw.body),
2905
+ claim: parseClaim(raw.body, raw.createdAt, author)
2906
+ };
2907
+ }
2908
+ var MORE = {
2909
+ inverseRelations: {
2910
+ field: "inverseRelations",
2911
+ nodes: "type issue { identifier state { type } }",
2912
+ operation: "MoreRelations",
2913
+ what: "relations"
2914
+ },
2915
+ labels: { field: "labels", nodes: "name parent { name }", operation: "MoreLabels", what: "labels" },
2916
+ attachments: { field: "attachments", nodes: "title url", operation: "MoreAttachments", what: "attachments" },
2917
+ comments: {
2918
+ field: "comments",
2919
+ nodes: "id createdAt body user { name }",
2920
+ operation: "MoreComments",
2921
+ what: "comments"
2922
+ }
2923
+ };
2924
+ var MORE_QUERY = (m) => `
2925
+ query ${m.operation}($id: String!, $after: String) {
2926
+ issue(id: $id) {
2927
+ ${m.field}(first: ${m.first ?? MORE_PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${m.nodes} } }
2928
+ }
2929
+ }`;
2930
+ var FIELDS = (delegate) => `
2931
+ fragment F on Issue {
2932
+ id identifier title url description createdAt updatedAt startedAt completedAt canceledAt
2933
+ state { name type }
2934
+ assignee { name }
2935
+ ${delegate ? "delegate { name }" : ""}
2936
+ parent { identifier }
2937
+ labels(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.labels.nodes} } }
2938
+ attachments(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.attachments.nodes} } }
2939
+ inverseRelations(first: 50) { pageInfo { hasNextPage endCursor } nodes { ${MORE.inverseRelations.nodes} } }
2940
+ }
2941
+ `;
2942
+ var ROOT_QUERY = (d) => `${FIELDS(d)} query Root($id: String!) { issue(id: $id) { ...F } }`;
2943
+ var CHILDREN_QUERY = (d) => `${FIELDS(d)}
2944
+ query Children($parents: [ID!], $after: String) {
2945
+ issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
2946
+ pageInfo { hasNextPage endCursor }
2947
+ nodes { ...F }
2875
2948
  }
2876
- let profileSource = profileLines.join("");
2877
- const existingArgs = profile.extra_args;
2878
- if (choice === "ask" && existingArgs !== undefined) {
2879
- if (!Array.isArray(existingArgs) || !existingArgs.every((arg) => typeof arg === "string"))
2880
- throw new Error(`could not safely edit extra_args for profile "${name}"`);
2881
- const assignment = arrayAssignment(profileSource, "extra_args");
2882
- if (!assignment)
2883
- throw new Error(`could not safely edit extra_args for profile "${name}"`);
2884
- const scanned = assignment.scan.items.map((item) => item.value);
2885
- if (canonicalToml(scanned) !== canonicalToml(existingArgs))
2886
- throw new Error(`could not safely edit extra_args for profile "${name}"`);
2887
- profileSource = removeArrayItems(profileSource, assignment, (arg) => arg.trim() === HERDR_FULL_PERMISSION_ARGS[harness]);
2888
- const expectedProfile = expectedProfiles[name];
2889
- expectedProfile.extra_args = existingArgs.filter((arg) => arg.trim() !== HERDR_FULL_PERMISSION_ARGS[harness]);
2949
+ }`;
2950
+ var COMMENTS_QUERY = `
2951
+ query Comments($ids: [ID!]) {
2952
+ issues(first: 50, filter: { id: { in: $ids } }) {
2953
+ nodes { identifier comments(first: ${MAX_COMMENTS}) { pageInfo { hasNextPage endCursor } nodes { ${MORE.comments.nodes} } } }
2954
+ }
2955
+ }`;
2956
+ async function gql(opts, query, variables) {
2957
+ return httpRequest(LINEAR_ENDPOINT, {
2958
+ method: "POST",
2959
+ headers: { "Content-Type": "application/json", Authorization: opts.apiKey },
2960
+ body: JSON.stringify({ query, variables })
2961
+ }, opts, async (res) => {
2962
+ if (res.status === 401)
2963
+ throw new LinearError("Linear rejected the API key (HTTP 401); check LINEAR_API_KEY", true);
2964
+ const json = await res.json().catch((err) => {
2965
+ if (err instanceof SyntaxError)
2966
+ return {};
2967
+ throw err;
2968
+ });
2969
+ if (json.errors?.length)
2970
+ throw new LinearError(`Linear API: ${json.errors.map((e) => e.message).join("; ")}`);
2971
+ if (!res.ok)
2972
+ throw new LinearError(`Linear API HTTP ${res.status}`, true);
2973
+ if (!json.data)
2974
+ throw new LinearError("Linear API: empty response");
2975
+ return json.data;
2976
+ }).catch((err) => {
2977
+ if (err instanceof HttpRequestError)
2978
+ throw new LinearError(`Linear API unreachable: ${err.message}`, true);
2979
+ throw err;
2980
+ });
2981
+ }
2982
+ var readGql = (opts, query, variables) => gql({ ...opts, retry: true }, query, variables);
2983
+ var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
2984
+ var CLOSED2 = new Set(["completed", "canceled"]);
2985
+ var isCandidate = (i, rootId) => i.id !== rootId && !CLOSED2.has(i.statusType) && (i.agentPhase !== null || i.statusType === "started");
2986
+ async function readComments(opts, issues, warnings) {
2987
+ const comments = [];
2988
+ for (const batch of chunks(issues.map((i) => i.uuid), COMMENT_BATCH)) {
2989
+ const data = await readGql(opts, COMMENTS_QUERY, { ids: batch });
2990
+ for (const n of data.issues.nodes) {
2991
+ await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
2992
+ for (const c of n.comments.nodes)
2993
+ comments.push(normalizeComment(c, n.identifier));
2890
2994
  }
2891
- const updatedProfile = expectedProfiles[name];
2892
- updatedProfile.permissions = choice;
2893
- replacements.push({ start: section.start, end: section.end, source: profileSource });
2894
2995
  }
2895
- const nextLines = [...lines];
2896
- for (const replacement of replacements.sort((a, b) => b.start - a.start))
2897
- nextLines.splice(replacement.start, replacement.end - replacement.start, ...linesOf(replacement.source));
2898
- const next = nextLines.join("");
2899
- if (canonicalToml(parse(next)) !== canonicalToml(expected))
2900
- throw new Error("could not safely edit profile permissions");
2901
- return next;
2996
+ return comments;
2902
2997
  }
2903
- function setHerdrModel(text, name, model) {
2904
- const raw = parse(text);
2905
- const profiles = raw.herdr?.profiles;
2906
- if (!profiles?.[name])
2907
- throw new Error("profile is no longer present");
2908
- const lines = text.split(/(?<=\n)/);
2909
- let section = -1;
2910
- let end = lines.length;
2911
- for (let i = 0;i < lines.length; i++) {
2912
- const header = lines[i]?.match(/^\s*\[herdr\s*\.\s*profiles\s*\.\s*(.+?)\]\s*(?:#.*)?(?:\r?\n)?$/);
2913
- if (header) {
2914
- const key = header[1]?.trim();
2915
- if (key && Object.hasOwn(parse(`[${key}]
2916
- `), name)) {
2917
- section = i;
2998
+ async function fetchProgram(opts) {
2999
+ try {
3000
+ return await fetchTree(opts, true);
3001
+ } catch (err) {
3002
+ if (err instanceof LinearError && /delegate/i.test(err.message))
3003
+ return fetchTree(opts, false);
3004
+ throw err;
3005
+ }
3006
+ }
3007
+ async function fetchTree(opts, delegate) {
3008
+ const root = (await readGql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
3009
+ if (!root)
3010
+ throw new LinearError(`Linear: program root ${opts.rootId} not found`);
3011
+ const all = [root];
3012
+ const warnings = [];
3013
+ let parents = [root.id];
3014
+ for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
3015
+ const next = [];
3016
+ let after = null;
3017
+ for (;; ) {
3018
+ const data = await readGql(opts, CHILDREN_QUERY(delegate), { parents, after });
3019
+ all.push(...data.issues.nodes);
3020
+ next.push(...data.issues.nodes.map((n) => n.id));
3021
+ const { hasNextPage, endCursor } = data.issues.pageInfo;
3022
+ if (!hasNextPage)
3023
+ break;
3024
+ if (!endCursor || endCursor === after) {
3025
+ warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
2918
3026
  break;
2919
3027
  }
3028
+ after = endCursor;
2920
3029
  }
3030
+ parents = next;
2921
3031
  }
2922
- if (section < 0)
2923
- throw new Error("use an explicit [herdr.profiles.<name>] section to save the model");
2924
- for (let i = section + 1;i < lines.length; i++) {
2925
- if (/^\s*\[/.test(lines[i] ?? "")) {
2926
- end = i;
2927
- break;
2928
- }
2929
- }
2930
- let replaced = false;
2931
- for (let i = section + 1;i < end; i++) {
2932
- const match = lines[i]?.match(/^(\s*(?:model|"model"|'model')\s*=\s*)("(?:[^"\\]|\\.)*"|'[^']*')(.*?)(\r?\n)?$/);
2933
- if (match) {
2934
- const value = match[2]?.startsWith("'") && !model.includes("'") ? `'${model}'` : JSON.stringify(model);
2935
- lines[i] = `${match[1]}${value}${match[3]}${match[4] ?? ""}`;
2936
- replaced = true;
2937
- break;
3032
+ if (parents.length)
3033
+ warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
3034
+ for (const r of all)
3035
+ for (const field of ["inverseRelations", "labels", "attachments"])
3036
+ await readRest(opts, r.identifier, MORE[field], r[field], warnings);
3037
+ const issues = all.map((r) => normalizeIssue(r, opts.labels));
3038
+ const comments = await readComments(opts, issues.filter((i) => isCandidate(i, root.identifier)), warnings);
3039
+ return {
3040
+ rootId: root.identifier,
3041
+ fetchedAt: (opts.now?.() ?? new Date).toISOString(),
3042
+ issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
3043
+ comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
3044
+ warnings
3045
+ };
3046
+ }
3047
+ async function readRest(opts, identifier, more, conn, warnings) {
3048
+ while (conn.pageInfo?.hasNextPage) {
3049
+ const after = conn.pageInfo.endCursor;
3050
+ try {
3051
+ if (!after)
3052
+ throw new LinearError("Linear gave no cursor for the next page");
3053
+ const data = await readGql(opts, MORE_QUERY(more), {
3054
+ id: identifier,
3055
+ after
3056
+ });
3057
+ const page = data.issue?.[more.field];
3058
+ if (!page)
3059
+ throw new LinearError(`Linear: issue ${identifier} not found`);
3060
+ conn.nodes.push(...page.nodes);
3061
+ conn.pageInfo = page.pageInfo;
3062
+ if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
3063
+ throw new LinearError("Linear did not advance to a next page");
3064
+ } catch (err) {
3065
+ if (!(err instanceof LinearError) || err.transport)
3066
+ throw err;
3067
+ warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
3068
+ return;
2938
3069
  }
2939
3070
  }
2940
- if (!replaced) {
2941
- const newline = text.includes(`\r
2942
- `) ? `\r
2943
- ` : `
2944
- `;
2945
- if (!(lines[section] ?? "").endsWith(`
2946
- `))
2947
- lines[section] += newline;
2948
- lines.splice(section + 1, 0, `model = ${JSON.stringify(model)}${newline}`);
2949
- }
2950
- const next = lines.join("");
2951
- profiles[name].model = model;
2952
- if (JSON.stringify(parse(next)) !== JSON.stringify(raw)) {
2953
- const canonical = (value) => JSON.stringify(value, (_, v) => typeof v === "object" && v !== null && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((key) => [key, v[key]])) : v);
2954
- if (canonical(parse(next)) !== canonical(raw))
2955
- throw new Error("could not safely edit the profile model");
2956
- }
2957
- return next;
2958
3071
  }
3072
+ var CHANGED_COMMENTS_QUERY = `
3073
+ query ChangedComments($filter: CommentFilter, $after: String) {
3074
+ comments(first: ${MORE_PAGE}, after: $after, filter: $filter) {
3075
+ pageInfo { hasNextPage endCursor }
3076
+ nodes { ${MORE.comments.nodes} issue { identifier } }
3077
+ }
3078
+ }`;
2959
3079
 
2960
3080
  // ../core/src/npm.ts
2961
3081
  var ARMADA_PACKAGE = CLI_PACKAGE;
@@ -3481,6 +3601,8 @@ function resolvePr(ticket, repository, pr) {
3481
3601
  async function reportPhase(ctx, input) {
3482
3602
  const { config, linear } = ctx;
3483
3603
  const groups = config.tracker.labels;
3604
+ if (input.stage != null && (input.phase !== "shipping" || !isShippingStage(input.stage)))
3605
+ throw new Refusal("--stage is for shipping: use review or ci", 'armada report shipping --stage review|ci --message "<progress>"');
3484
3606
  const ticket = await readOpenTicket(ctx, input.ticket);
3485
3607
  const problem = transitionProblem(ticket.agentPhase, input.phase);
3486
3608
  if (problem)
@@ -3553,6 +3675,7 @@ ${body}` : statusLine);
3553
3675
  const inbox = await live(ctx, warnings, "record the report", (fleet) => fleet.report({
3554
3676
  ticket: ticket.id,
3555
3677
  phase: input.phase,
3678
+ shippingStage: isShippingStage(input.stage) ? input.stage : null,
3556
3679
  previous: ticket.agentPhase,
3557
3680
  summary,
3558
3681
  message: plan ? [summary, body].join(`
@@ -4295,22 +4418,22 @@ var PULLS_QUERY = `${PULL_FIELDS}
4295
4418
  }
4296
4419
  }`;
4297
4420
  async function githubQuery(opts, query, variables) {
4298
- const doFetch = opts.fetch ?? fetch;
4299
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
4300
- const res = await doFetch(GITHUB_GRAPHQL, {
4421
+ return httpRequest(GITHUB_GRAPHQL, {
4301
4422
  method: "POST",
4302
4423
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
4303
- body: JSON.stringify({ query, variables }),
4304
- signal: AbortSignal.timeout(timeoutMs)
4424
+ body: JSON.stringify({ query, variables })
4425
+ }, { ...opts, retry: true }, async (res) => {
4426
+ if (!res.ok)
4427
+ throw new GithubError(`GitHub API HTTP ${res.status}`);
4428
+ const json = await res.json();
4429
+ if (json.errors?.length)
4430
+ throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
4431
+ return json;
4305
4432
  }).catch((err) => {
4306
- throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
4433
+ if (err instanceof HttpRequestError)
4434
+ throw new GithubError(`GitHub API unreachable: ${err.message}`);
4435
+ throw err;
4307
4436
  });
4308
- if (!res.ok)
4309
- throw new GithubError(`GitHub API HTTP ${res.status}`);
4310
- const json = await res.json();
4311
- if (json.errors?.length)
4312
- throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
4313
- return json;
4314
4437
  }
4315
4438
  var PULL_QUERY = `${PULL_FIELDS}
4316
4439
  query Pull($owner: String!, $name: String!, $number: Int!) {
@@ -4373,24 +4496,24 @@ var FILE_QUERY = `
4373
4496
  }`;
4374
4497
  async function fetchDefaultBranchFile(opts) {
4375
4498
  const [owner, name] = opts.repository.split("/");
4376
- const doFetch = opts.fetch ?? fetch;
4377
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
4378
- const res = await doFetch(GITHUB_GRAPHQL, {
4499
+ return httpRequest(GITHUB_GRAPHQL, {
4379
4500
  method: "POST",
4380
4501
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
4381
- body: JSON.stringify({ query: FILE_QUERY, variables: { owner, name, expression: `HEAD:${opts.path}` } }),
4382
- signal: AbortSignal.timeout(timeoutMs)
4502
+ body: JSON.stringify({ query: FILE_QUERY, variables: { owner, name, expression: `HEAD:${opts.path}` } })
4503
+ }, { ...opts, retry: true }, async (res) => {
4504
+ if (!res.ok)
4505
+ throw new GithubError(`GitHub API HTTP ${res.status}`);
4506
+ const json = await res.json();
4507
+ if (json.errors?.length)
4508
+ throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
4509
+ if (!json.data?.repository)
4510
+ throw new GithubError(`GitHub: repository ${opts.repository} not found`);
4511
+ return json.data.repository.object?.text ?? null;
4383
4512
  }).catch((err) => {
4384
- throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
4513
+ if (err instanceof HttpRequestError)
4514
+ throw new GithubError(`GitHub API unreachable: ${err.message}`);
4515
+ throw err;
4385
4516
  });
4386
- if (!res.ok)
4387
- throw new GithubError(`GitHub API HTTP ${res.status}`);
4388
- const json = await res.json();
4389
- if (json.errors?.length)
4390
- throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
4391
- if (!json.data?.repository)
4392
- throw new GithubError(`GitHub: repository ${opts.repository} not found`);
4393
- return json.data.repository.object?.text ?? null;
4394
4517
  }
4395
4518
  var MERGE_PULL_QUERY = `${PULL_FIELDS}
4396
4519
  query MergePull($owner: String!, $name: String!, $number: Int!) {
@@ -4444,18 +4567,18 @@ async function fetchComparison(opts) {
4444
4567
  return { baseSha: ref.target.oid, ...ref.compare };
4445
4568
  }
4446
4569
  async function fetchPullDiff(opts) {
4447
- const doFetch = opts.fetch ?? fetch;
4448
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
4449
- const res = await doFetch(`https://api.github.com/repos/${opts.repository}/pulls/${opts.number}`, {
4570
+ return httpRequest(`https://api.github.com/repos/${opts.repository}/pulls/${opts.number}`, {
4450
4571
  method: "GET",
4451
- headers: { Accept: "application/vnd.github.diff", Authorization: `Bearer ${opts.token}` },
4452
- signal: AbortSignal.timeout(timeoutMs)
4572
+ headers: { Accept: "application/vnd.github.diff", Authorization: `Bearer ${opts.token}` }
4573
+ }, { ...opts, retry: true }, async (res) => {
4574
+ if (!res.ok)
4575
+ throw new GithubError(`GitHub API HTTP ${res.status} reading the diff of #${opts.number}`);
4576
+ return res.text();
4453
4577
  }).catch((err) => {
4454
- throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
4578
+ if (err instanceof HttpRequestError)
4579
+ throw new GithubError(`GitHub API unreachable: ${err.message}`);
4580
+ throw err;
4455
4581
  });
4456
- if (!res.ok)
4457
- throw new GithubError(`GitHub API HTTP ${res.status} reading the diff of #${opts.number}`);
4458
- return res.text();
4459
4582
  }
4460
4583
  var COMMIT_QUERY = `
4461
4584
  query Commit($owner: String!, $name: String!, $oid: GitObjectID!) {
@@ -4538,6 +4661,7 @@ var FLEET_OPS = [
4538
4661
  "coordinator",
4539
4662
  "request",
4540
4663
  "events/latest",
4664
+ "events/state",
4541
4665
  "heartbeats/latest",
4542
4666
  "runtime/handles",
4543
4667
  "runtime/handle",
@@ -4569,6 +4693,7 @@ function fleetClient(o) {
4569
4693
  register: () => call("register", {}).then(() => {
4570
4694
  return;
4571
4695
  }),
4696
+ latestEvents: () => call("events/state", {}),
4572
4697
  lastEventTimes: () => call("events/latest", {}),
4573
4698
  heartbeatTimes: () => call("heartbeats/latest", {}),
4574
4699
  heartbeat: (input) => call("heartbeat", input),
@@ -5000,10 +5125,10 @@ function ensure(ok, what) {
5000
5125
  function createLinearWriter(opts) {
5001
5126
  return {
5002
5127
  async viewer() {
5003
- return (await gql(opts, VIEWER_QUERY, {})).viewer;
5128
+ return (await gql({ ...opts, retry: true }, VIEWER_QUERY, {})).viewer;
5004
5129
  },
5005
5130
  async readTicket(id) {
5006
- const data = await gql(opts, TICKET_QUERY, { id }).catch((err) => {
5131
+ const data = await gql({ ...opts, retry: true }, TICKET_QUERY, { id }).catch((err) => {
5007
5132
  if (err instanceof LinearError && /not found/i.test(err.message))
5008
5133
  return { issue: null };
5009
5134
  throw err;
@@ -5018,7 +5143,7 @@ function createLinearWriter(opts) {
5018
5143
  return normalizeTicket(raw, opts.labels, warnings);
5019
5144
  },
5020
5145
  async groupLabels(group, teamId) {
5021
- const data = await gql(opts, GROUP_LABELS_QUERY, { group });
5146
+ const data = await gql({ ...opts, retry: true }, GROUP_LABELS_QUERY, { group });
5022
5147
  const usable = data.issueLabels.nodes.filter((l) => !l.team || l.team.id === teamId);
5023
5148
  const byName = new Map;
5024
5149
  for (const l of [...usable].sort((a, b) => Number(!!b.team) - Number(!!a.team)))
@@ -5038,20 +5163,23 @@ function createLinearWriter(opts) {
5038
5163
  input.removedLabelIds = change.removeLabelIds;
5039
5164
  if (!Object.keys(input).length)
5040
5165
  return;
5041
- const data = await gql(opts, UPDATE_MUTATION, { id: uuid, input });
5166
+ const data = await gql({ ...opts, retry: false }, UPDATE_MUTATION, {
5167
+ id: uuid,
5168
+ input
5169
+ });
5042
5170
  ensure(data.issueUpdate?.success, "update the ticket");
5043
5171
  },
5044
5172
  async comment(uuid, body) {
5045
- const data = await gql(opts, COMMENT_MUTATION, { input: { issueId: uuid, body } });
5173
+ const data = await gql({ ...opts, retry: false }, COMMENT_MUTATION, { input: { issueId: uuid, body } });
5046
5174
  ensure(data.commentCreate?.success && !!data.commentCreate.comment, "post the comment");
5047
5175
  return { id: data.commentCreate.comment?.id ?? "" };
5048
5176
  },
5049
5177
  async deleteComment(id) {
5050
- const data = await gql(opts, DELETE_COMMENT_MUTATION, { id });
5178
+ const data = await gql({ ...opts, retry: false }, DELETE_COMMENT_MUTATION, { id });
5051
5179
  ensure(data.commentDelete?.success, "delete the comment");
5052
5180
  },
5053
5181
  async linkUrl(uuid, url, title) {
5054
- const data = await gql(opts, LINK_MUTATION, {
5182
+ const data = await gql({ ...opts, retry: false }, LINK_MUTATION, {
5055
5183
  issueId: uuid,
5056
5184
  url,
5057
5185
  title
@@ -6576,7 +6704,7 @@ You are a worker. You own exactly one ticket, named in your launch brief. You tu
6576
6704
  2. **Branch.** Use the branch named after the ticket (the tracker suggests one, for example \`feature/abc-12-short-title\`), created from the latest default branch.
6577
6705
  3. **Plan.** Write the plan: what changes, how it is tested, and the checks a person could observe when it is done. Your brief's "Plan" section says in one line whether it needs approval (from \`[policy] plans\` in \`armada.toml\`, or a label on the ticket); follow that line, do not guess. Pre-approved: post the plan with \`armada report implementing --plan-file -\` (or \`--plan-file <path>\`) and go on; do not enter \`awaiting-approval\`. Otherwise post it with \`armada report awaiting-approval --plan-file -\`: it creates a \`plan\` item in the coordinator's inbox. \`--plan-file\` posts the plan as its own block, under a one-line status (\`--message\` sets that line, else the plan's first line). Push your branch and wait for the coordinator's decision in your session. On approval, report \`implementing\`; on amendments, report \`planning\`, revise the plan and submit it for approval again.
6578
6706
  4. **Implement** test-first. A material change to the approved plan needs a new approval.
6579
- 5. **Ship.** \`armada report shipping --pr <number>\`. Use the bundled \`ship-pr-dev\` skill by default, including its independent \`review-code-dev\` gate and report-only \`capture-learning-tools\` pass. Within that workflow you own delivery (Git and the PR); its delegated helpers are its workers. The Armada coordinator still owns merging. If it cannot run (for example the OCR download or isolated reviewer is unavailable), record the exact limitation and use the fallback: run the repository's local checks, open the pull request with a Commitizen title (\`feat(scope): …\`), link it on the ticket, and fix CI until every required check is green.
6707
+ 5. **Ship.** \`armada report shipping --pr <number> --message "Preparing the pull request for independent review"\`. Use the bundled \`ship-pr-dev\` skill by default, including its independent \`review-code-dev\` gate and report-only \`capture-learning-tools\` pass. At the independent \`review-code-dev\` review gate, report \`armada report shipping --stage review --pr <number> --message "Independent code review started"\` (omit \`--pr\` if no PR is open yet). Once that review passes, report \`armada report shipping --stage ci --pr <number> --message "Independent review passed; checking CI"\`. Report \`review\` again when changes need another independent review, and \`ci\` after it passes. Keep \`--stage review|ci\` on repeated shipping reports so the current step stays explicit. These stages are Armada data, not Linear labels; other phases do not take \`--stage\`. Within that workflow you own delivery (Git and the PR); its delegated helpers are its workers. The Armada coordinator still owns merging. If it cannot run (for example the OCR download or isolated reviewer is unavailable), record the exact limitation and use the fallback: run the repository's local checks, open the pull request with a Commitizen title (\`feat(scope): …\`), link it on the ticket, and fix CI until every required check is green.
6580
6708
  6. **Bring the default branch in** right before hand-back (rebase, or merge it into your branch; squash merges make both fine), and get CI green on that final head. Never force-push a branch someone else pushed to.
6581
6709
  7. **Hand back.** \`armada report ready-to-merge --pr <number> --sha <full 40-character head SHA> --shipped-with "ship-pr-dev"\`. For the fallback, use \`--shipped-with "fallback: <exact reason ship-pr-dev could not run>"\`. The generated hand-back line names the shipping path in Linear and \`armada inbox\`. Armada refuses a short SHA, a SHA that is not the pull request head, or a red check. Then report to the coordinator: \`shipped with ship-pr-dev\` or \`shipped with the fallback: <reason>\`, pull request URL, full SHA, CI state, the decisions you made, and what the next tickets need to know.
6582
6710
 
@@ -10241,6 +10369,7 @@ function buildStatus({
10241
10369
  ...heartbeats ? { heartbeats } : {},
10242
10370
  ...live ? { live } : {}
10243
10371
  });
10372
+ const stageOf = new Map(lanes.map((l) => [l.issue.id, l.shippingStage ?? null]));
10244
10373
  const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
10245
10374
  const prRef = (p) => ({
10246
10375
  files: p.files ?? null,
@@ -10282,6 +10411,7 @@ function buildStatus({
10282
10411
  url: l.issue.url,
10283
10412
  spec: l.spec,
10284
10413
  phase: l.phase,
10414
+ shippingStage: l.shippingStage ?? null,
10285
10415
  phaseSource: l.phaseSource,
10286
10416
  runtime: l.runtime,
10287
10417
  handle: l.handle,
@@ -10326,7 +10456,11 @@ function buildStatus({
10326
10456
  updatedAt: pr.updatedAt ?? null,
10327
10457
  failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
10328
10458
  branch: pr.headRef ?? null,
10329
- ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
10459
+ ticket: ticket ? {
10460
+ id: ticket.id,
10461
+ phase: phaseOf.get(ticket.id) ?? ticket.agentPhase,
10462
+ shippingStage: stageOf.get(ticket.id) ?? null
10463
+ } : null
10330
10464
  })) : null,
10331
10465
  warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
10332
10466
  };
@@ -10361,7 +10495,7 @@ async function loadStatus(config, opts) {
10361
10495
  const launchesP = opts.launches ? opts.launches().then((launches) => ({ launches }), (err) => ({
10362
10496
  warning: `Armada's launches could not be read (${err instanceof Error ? err.message : String(err)}); workers launched that never started are not listed`
10363
10497
  })) : Promise.resolve({});
10364
- const [{ program, forge, forgeError }, events, launches, heartbeats, runtimeHandles] = await Promise.all([
10498
+ const [{ program, forge, forgeError }, events, launches, heartbeats, runtimeHandles, latestEvents] = await Promise.all([
10365
10499
  readStatusSources(config, opts),
10366
10500
  eventsP,
10367
10501
  launchesP,
@@ -10370,6 +10504,9 @@ async function loadStatus(config, opts) {
10370
10504
  }),
10371
10505
  opts.runtimeHandles?.().catch(() => {
10372
10506
  return;
10507
+ }),
10508
+ opts.latestEvents?.().catch(() => {
10509
+ return;
10373
10510
  })
10374
10511
  ]);
10375
10512
  return buildStatus({
@@ -10379,11 +10516,11 @@ async function loadStatus(config, opts) {
10379
10516
  forgeError,
10380
10517
  ...events.events ? { lastEvents: events.events } : {},
10381
10518
  ...heartbeats ? { heartbeats } : {},
10382
- ...runtimeHandles ? {
10519
+ ...runtimeHandles || latestEvents ? {
10383
10520
  live: {
10384
10521
  after: program.fetchedAt,
10385
- events: {},
10386
- handles: Object.fromEntries(runtimeHandles.map((h) => [h.ticket, h]))
10522
+ events: latestEvents ?? {},
10523
+ handles: Object.fromEntries((runtimeHandles ?? []).map((h) => [h.ticket, h]))
10387
10524
  }
10388
10525
  } : {},
10389
10526
  ...launches.launches ? { launches: launches.launches } : {},
@@ -10516,7 +10653,7 @@ ${attachments.join(`
10516
10653
  };
10517
10654
  }
10518
10655
  // package.json
10519
- var version = "0.2.49";
10656
+ var version = "0.2.51";
10520
10657
 
10521
10658
  // src/attach.ts
10522
10659
  import { resolve } from "node:path";
@@ -10639,6 +10776,8 @@ async function fromArmada(io, credentials, purpose) {
10639
10776
  throw err;
10640
10777
  if (err.status === 503)
10641
10778
  return null;
10779
+ if (!credentials.linearApiKey)
10780
+ throw err;
10642
10781
  io.stderr(`! Armada gave no keys (${err.message}); using this machine's${err.next ? `. Next: ${err.next}` : ""}
10643
10782
  `);
10644
10783
  return null;
@@ -11874,6 +12013,7 @@ function statusLive(io, config, credentials) {
11874
12013
  const { fleet } = liveFleet(io, config, credentials);
11875
12014
  return fleet ? {
11876
12015
  lastEvents: () => fleet.lastEventTimes(),
12016
+ latestEvents: () => fleet.latestEvents(),
11877
12017
  heartbeats: () => fleet.heartbeatTimes(),
11878
12018
  launches: () => fleet.pendingLaunches(),
11879
12019
  runtimeHandles: () => observeHerdr(io, fleet)
@@ -12028,6 +12168,7 @@ async function report(io, config, credentials, a) {
12028
12168
  return withContext(io, config, credentials, a.json, (ctx) => reportPhase(ctx, {
12029
12169
  ticket,
12030
12170
  phase,
12171
+ stage: a.options.stage ?? null,
12031
12172
  message,
12032
12173
  plan,
12033
12174
  pr: a.options.pr ?? null,
@@ -14416,7 +14557,10 @@ function prState(pr) {
14416
14557
  pr.mergeable ? MERGEABLE[pr.mergeable] ?? pr.mergeable.toLowerCase() : null
14417
14558
  ].filter(Boolean).join(" · ");
14418
14559
  }
14419
- var phaseLabel = (t) => t.phaseSource === "label" ? t.phase : `${t.phase} (${t.phaseSource})`;
14560
+ var phaseLabel = (t) => {
14561
+ const phase = `${t.phase}${t.shippingStage ? ` · ${t.shippingStage}` : ""}`;
14562
+ return t.phaseSource === "label" ? phase : `${phase} (${t.phaseSource})`;
14563
+ };
14420
14564
  function renderStatus(r) {
14421
14565
  const now = Date.parse(r.generatedAt);
14422
14566
  const out = [];
@@ -14480,7 +14624,7 @@ function renderStatus(r) {
14480
14624
  else if (!r.pullRequests.length)
14481
14625
  out.push(" none open");
14482
14626
  for (const p of r.pullRequests ?? []) {
14483
- const ticket = p.ticket ? `${p.ticket.id}${p.ticket.phase ? ` ${p.ticket.phase}` : ""}` : "no ticket";
14627
+ const ticket = p.ticket ? `${p.ticket.id}${p.ticket.phase ? ` ${p.ticket.phase}${p.ticket.shippingStage ? ` · ${p.ticket.shippingStage}` : ""}` : ""}` : "no ticket";
14484
14628
  out.push(` ${pad(`#${p.number}`, idWidth)} ${[ticket, prState(p)].filter(Boolean).join(" · ")}`);
14485
14629
  out.push(`${indent}${truncate(p.title, 90)}`);
14486
14630
  if (p.failingChecks.length)
@@ -14922,7 +15066,7 @@ var COMMAND_HELP = {
14922
15066
  rules the coordinator judged apply. Prints the ticket's state afterwards
14923
15067
  `,
14924
15068
  report: ` report <phase> [--message <text> | --message-file <path|->] [--pr <n|url>] [--sha <sha>]
14925
- [--plan <text> | --plan-file <path|->] [--shipped-with "ship-pr-dev"|"fallback: <reason>"]
15069
+ [--plan <text> | --plan-file <path|->] [--shipped-with "ship-pr-dev"|"fallback: <reason>"] [--stage review|ci]
14926
15070
  Report a phase (planning, awaiting-approval, implementing, shipping,
14927
15071
  blocked, ready-to-merge, awaiting-validation); the same phase again is a
14928
15072
  status update; armada validate is how a worker enters awaiting-validation.
@@ -14930,6 +15074,7 @@ var COMMAND_HELP = {
14930
15074
  message's first line, else the plan's); awaiting-approval sends it to
14931
15075
  the coordinator's inbox.
14932
15076
  ready-to-merge needs --sha (full 40 characters, the PR head) and green CI.
15077
+ --stage is shipping only: review at independent review, ci after it passes.
14933
15078
  --shipped-with names the shipping path in its hand-back and inbox.
14934
15079
  Prints the ticket's state and what waits in this worker's inbox.
14935
15080
  `,
@@ -15170,6 +15315,7 @@ var VALUE_OPTIONS = [
15170
15315
  "pr",
15171
15316
  "sha",
15172
15317
  "shipped-with",
15318
+ "stage",
15173
15319
  "reason",
15174
15320
  "program-root",
15175
15321
  "name",
@@ -15209,7 +15355,7 @@ var COMMAND_OPTIONS = {
15209
15355
  attach: ["caption", "for"],
15210
15356
  heartbeat: ["every", "parent", "background", "ticket", "handle"],
15211
15357
  claim: ["runtime", "handle", "branch", "profile", "reason", "validation", "validation-reason"],
15212
- report: ["ticket", "message", "message-file", "plan", "plan-file", "pr", "sha", "shipped-with"],
15358
+ report: ["ticket", "message", "message-file", "plan", "plan-file", "pr", "sha", "shipped-with", "stage"],
15213
15359
  release: ["ticket", "reason"],
15214
15360
  ask: ["ticket", "options", "message", "message-file"],
15215
15361
  inbox: ["wait", "timeout"],
@@ -15634,6 +15780,15 @@ function readCodexModels(cwd, io = system) {
15634
15780
  });
15635
15781
  }
15636
15782
 
15783
+ // src/http.ts
15784
+ function cliFetch(doFetch = fetch) {
15785
+ return (url, init) => {
15786
+ const headers = new Headers(init.headers);
15787
+ headers.set("Connection", "close");
15788
+ return doFetch(url, { ...init, headers });
15789
+ };
15790
+ }
15791
+
15637
15792
  // src/line.ts
15638
15793
  var emptyLine = () => ({ answer: "", sequence: "none" });
15639
15794
  function feedLine(line, chunk) {
@@ -15919,7 +16074,7 @@ var code = await run(process.argv.slice(2), {
15919
16074
  },
15920
16075
  stderr: (t) => process.stderr.write(t),
15921
16076
  ghToken,
15922
- fetch: (url, init) => fetch(url, init),
16077
+ fetch: cliFetch(),
15923
16078
  inspectProcess: (pid) => inspectProcess(exec, pid),
15924
16079
  signalProcess: (pid, signal) => {
15925
16080
  process.kill(pid, signal);