@the-vibe-company/armada 0.2.50 → 0.2.52

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 +609 -458
  2. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -10,319 +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 isShippingStage = (value) => value === "review" || value === "ci";
15
- var LABEL_PHASES = [
16
- "planning",
17
- "awaiting-approval",
18
- "implementing",
19
- "shipping",
20
- "blocked",
21
- "ready-to-merge",
22
- "awaiting-validation"
23
- ];
24
-
25
- // ../core/src/linear.ts
26
- var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
27
- var MAX_DEPTH = 8;
28
- var COMMENT_BATCH = 25;
29
- var MAX_COMMENTS = 100;
30
- var MORE_PAGE = 100;
31
- var REQUEST_TIMEOUT_MS = 30000;
32
-
33
- class LinearError extends Error {
34
- transport;
35
- name = "LinearError";
36
- constructor(message, transport = false) {
37
- super(message);
38
- this.transport = transport;
39
- }
40
- }
41
- var PHASES = [...LABEL_PHASES, "released", "merged"];
42
- var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
43
- var firstLine = (body) => (body.split(`
44
- `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
45
- var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
46
- var PLAN_BLOCK = /^## Plan[ \t]*$/m;
47
- function parseStatusLine(body) {
48
- const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
49
- if (!m?.[1])
50
- return null;
51
- const raw = m[1].toLowerCase();
52
- const phase = LEGACY[raw] ?? raw;
53
- const summary = (m[2] ?? "").trim();
54
- if (COORDINATOR_RECORD.test(summary))
55
- return null;
56
- if (!PHASES.includes(phase))
57
- return null;
58
- return PLAN_BLOCK.test(body) ? { phase, summary, plan: true } : { phase, summary };
59
- }
60
- var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
61
- var trimMarks = (v) => {
62
- const t = v.trim();
63
- return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
64
- };
65
- function parseClaim(body, at, author) {
66
- const line = body.split(`
67
- `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
68
- if (!line)
69
- return null;
70
- const field = (k) => {
71
- const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
72
- return v && trimMarks(v) || null;
73
- };
74
- const profileReason = body.split(`
75
- `).map(unescapeMarkdown).find((entry) => entry.startsWith("Profile reason: "))?.slice("Profile reason: ".length).trim();
76
- return {
77
- runtime: field("runtime"),
78
- session: field("session"),
79
- branch: field("branch|branche"),
80
- startedAt: field("started|démarré|demarre"),
81
- profile: field("profile"),
82
- ...profileReason ? { profileReason } : {},
83
- at,
84
- author
85
- };
86
- }
87
- function excerpt(markdown, max = 240) {
88
- const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
89
- return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
90
- }
91
- function parsePullRequestUrl(url, title = "") {
92
- const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
93
- return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
94
- }
95
- function agentLabels(labels, groups) {
96
- let agentPhase = null;
97
- for (const l of labels)
98
- if (l.group === groups.phaseGroup)
99
- agentPhase ??= phaseNamed(l.name);
100
- const runtime = labels.find((l) => l.group === groups.runtimeGroup);
101
- return { agentPhase, agentRuntime: runtime?.name ?? null };
102
- }
103
- var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
104
- var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
105
- function normalizeIssue(raw, groups) {
106
- const blockers = new Map;
107
- for (const r of raw.inverseRelations.nodes)
108
- if (r.type === "blocks")
109
- blockers.set(r.issue.identifier, { id: r.issue.identifier, statusType: r.issue.state.type });
110
- const prs = new Map;
111
- for (const a of raw.attachments.nodes) {
112
- const pr = parsePullRequestUrl(a.url, a.title);
113
- if (pr)
114
- prs.set(pr.url, pr);
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;
115
20
  }
116
- for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
117
- const pr = parsePullRequestUrl(m[0]);
118
- if (pr && !prs.has(pr.url))
119
- prs.set(pr.url, pr);
120
- }
121
- const labels = raw.labels.nodes.map((l) => ({ name: l.name, group: l.parent?.name ?? null }));
122
- return {
123
- id: raw.identifier,
124
- uuid: raw.id,
125
- title: raw.title,
126
- url: raw.url,
127
- status: raw.state.name,
128
- statusType: raw.state.type,
129
- assignee: raw.assignee?.name ?? null,
130
- delegate: raw.delegate?.name ?? null,
131
- labels: labels.map((l) => l.name),
132
- ...agentLabels(labels, groups),
133
- parentId: raw.parent?.identifier ?? null,
134
- createdAt: raw.createdAt,
135
- updatedAt: raw.updatedAt,
136
- startedAt: raw.startedAt,
137
- completedAt: raw.completedAt,
138
- canceledAt: raw.canceledAt,
139
- blockedBy: [...blockers.values()].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
140
- prs: [...prs.values()].sort((a, b) => a.number - b.number)
141
- };
142
- }
143
- function normalizeComment(raw, issueId) {
144
- const author = raw.user?.name ?? null;
145
- return {
146
- id: raw.id,
147
- issueId,
148
- author,
149
- createdAt: raw.createdAt,
150
- excerpt: excerpt(raw.body, 600),
151
- status: parseStatusLine(raw.body),
152
- claim: parseClaim(raw.body, raw.createdAt, author)
153
- };
154
- }
155
- var MORE = {
156
- inverseRelations: {
157
- field: "inverseRelations",
158
- nodes: "type issue { identifier state { type } }",
159
- operation: "MoreRelations",
160
- what: "relations"
161
- },
162
- labels: { field: "labels", nodes: "name parent { name }", operation: "MoreLabels", what: "labels" },
163
- attachments: { field: "attachments", nodes: "title url", operation: "MoreAttachments", what: "attachments" },
164
- comments: {
165
- field: "comments",
166
- nodes: "id createdAt body user { name }",
167
- operation: "MoreComments",
168
- what: "comments"
169
- }
170
- };
171
- var MORE_QUERY = (m) => `
172
- query ${m.operation}($id: String!, $after: String) {
173
- issue(id: $id) {
174
- ${m.field}(first: ${m.first ?? MORE_PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${m.nodes} } }
175
- }
176
- }`;
177
- var FIELDS = (delegate) => `
178
- fragment F on Issue {
179
- id identifier title url description createdAt updatedAt startedAt completedAt canceledAt
180
- state { name type }
181
- assignee { name }
182
- ${delegate ? "delegate { name }" : ""}
183
- parent { identifier }
184
- labels(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.labels.nodes} } }
185
- attachments(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.attachments.nodes} } }
186
- inverseRelations(first: 50) { pageInfo { hasNextPage endCursor } nodes { ${MORE.inverseRelations.nodes} } }
187
- }
188
- `;
189
- var ROOT_QUERY = (d) => `${FIELDS(d)} query Root($id: String!) { issue(id: $id) { ...F } }`;
190
- var CHILDREN_QUERY = (d) => `${FIELDS(d)}
191
- query Children($parents: [ID!], $after: String) {
192
- issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
193
- pageInfo { hasNextPage endCursor }
194
- nodes { ...F }
195
- }
196
- }`;
197
- var COMMENTS_QUERY = `
198
- query Comments($ids: [ID!]) {
199
- issues(first: 50, filter: { id: { in: $ids } }) {
200
- nodes { identifier comments(first: ${MAX_COMMENTS}) { pageInfo { hasNextPage endCursor } nodes { ${MORE.comments.nodes} } } }
201
- }
202
- }`;
203
- async function gql(opts, query, variables) {
204
- const doFetch = opts.fetch ?? fetch;
205
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
206
- const res = await doFetch(LINEAR_ENDPOINT, {
207
- method: "POST",
208
- headers: { "Content-Type": "application/json", Authorization: opts.apiKey },
209
- body: JSON.stringify({ query, variables }),
210
- signal: AbortSignal.timeout(timeoutMs)
211
- }).catch((err) => {
212
- throw new LinearError(`Linear API unreachable: ${networkReason(err, timeoutMs)}`, true);
213
- });
214
- if (res.status === 401)
215
- throw new LinearError("Linear rejected the API key (HTTP 401); check LINEAR_API_KEY", true);
216
- const json = await res.json().catch(() => ({}));
217
- if (json.errors?.length)
218
- throw new LinearError(`Linear API: ${json.errors.map((e) => e.message).join("; ")}`);
219
- if (!res.ok)
220
- throw new LinearError(`Linear API HTTP ${res.status}`, true);
221
- if (!json.data)
222
- throw new LinearError("Linear API: empty response");
223
- return json.data;
224
21
  }
225
22
  function networkReason(err, timeoutMs) {
226
23
  if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
227
24
  return `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`;
228
- return err instanceof Error ? err.message : String(err);
25
+ const code = codeOf(err);
26
+ const message = err instanceof Error ? err.message : String(err);
27
+ return code && !message.includes(code) ? `${message} (${code})` : message;
229
28
  }
230
- var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
231
- var CLOSED = new Set(["completed", "canceled"]);
232
- var isCandidate = (i, rootId) => i.id !== rootId && !CLOSED.has(i.statusType) && (i.agentPhase !== null || i.statusType === "started");
233
- async function readComments(opts, issues, warnings) {
234
- const comments = [];
235
- for (const batch of chunks(issues.map((i) => i.uuid), COMMENT_BATCH)) {
236
- const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
237
- for (const n of data.issues.nodes) {
238
- await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
239
- for (const c of n.comments.nodes)
240
- comments.push(normalizeComment(c, n.identifier));
241
- }
242
- }
243
- return comments;
244
- }
245
- async function fetchProgram(opts) {
246
- try {
247
- return await fetchTree(opts, true);
248
- } catch (err) {
249
- if (err instanceof LinearError && /delegate/i.test(err.message))
250
- return fetchTree(opts, false);
251
- throw err;
252
- }
253
- }
254
- async function fetchTree(opts, delegate) {
255
- const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
256
- if (!root)
257
- throw new LinearError(`Linear: program root ${opts.rootId} not found`);
258
- const all = [root];
259
- const warnings = [];
260
- let parents = [root.id];
261
- for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
262
- const next = [];
263
- let after = null;
264
- for (;; ) {
265
- const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
266
- all.push(...data.issues.nodes);
267
- next.push(...data.issues.nodes.map((n) => n.id));
268
- const { hasNextPage, endCursor } = data.issues.pageInfo;
269
- if (!hasNextPage)
270
- break;
271
- if (!endCursor || endCursor === after) {
272
- warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
273
- break;
274
- }
275
- after = endCursor;
276
- }
277
- parents = next;
278
- }
279
- if (parents.length)
280
- warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
281
- for (const r of all)
282
- for (const field of ["inverseRelations", "labels", "attachments"])
283
- await readRest(opts, r.identifier, MORE[field], r[field], warnings);
284
- const issues = all.map((r) => normalizeIssue(r, opts.labels));
285
- const comments = await readComments(opts, issues.filter((i) => isCandidate(i, root.identifier)), warnings);
286
- return {
287
- rootId: root.identifier,
288
- fetchedAt: (opts.now?.() ?? new Date).toISOString(),
289
- issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
290
- comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
291
- warnings
292
- };
293
- }
294
- async function readRest(opts, identifier, more, conn, warnings) {
295
- while (conn.pageInfo?.hasNextPage) {
296
- const after = conn.pageInfo.endCursor;
297
- try {
298
- if (!after)
299
- throw new LinearError("Linear gave no cursor for the next page");
300
- const data = await gql(opts, MORE_QUERY(more), {
301
- id: identifier,
302
- after
303
- });
304
- const page = data.issue?.[more.field];
305
- if (!page)
306
- throw new LinearError(`Linear: issue ${identifier} not found`);
307
- conn.nodes.push(...page.nodes);
308
- conn.pageInfo = page.pageInfo;
309
- if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
310
- throw new LinearError("Linear did not advance to a next page");
311
- } catch (err) {
312
- if (!(err instanceof LinearError) || err.transport)
313
- throw err;
314
- warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
315
- return;
316
- }
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;
317
35
  }
36
+ return null;
318
37
  }
319
- var CHANGED_COMMENTS_QUERY = `
320
- query ChangedComments($filter: CommentFilter, $after: String) {
321
- comments(first: ${MORE_PAGE}, after: $after, filter: $filter) {
322
- pageInfo { hasNextPage endCursor }
323
- 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(() => {});
324
98
  }
325
- }`;
99
+ }
100
+ throw new Error("unreachable request attempt");
101
+ }
326
102
 
327
103
  // ../core/src/armada-api.ts
328
104
  var MASKED_LAUNCH_TOKEN = "armada_launch_••••";
@@ -387,7 +163,6 @@ function apiBaseUrl(value) {
387
163
  }
388
164
  function armadaApi(opts) {
389
165
  const base = apiBaseUrl(opts.url);
390
- const doFetch = opts.fetch ?? fetch;
391
166
  const timeoutMs = opts.timeoutMs ?? TIMEOUT_MS;
392
167
  const host = base.host;
393
168
  let serverCli = null;
@@ -402,31 +177,37 @@ function armadaApi(opts) {
402
177
  headers["x-api-key"] = init.signIn.key;
403
178
  if (opts.version)
404
179
  headers[CLI_VERSION_HEADER] = opts.version;
405
- const res = await doFetch(new URL(`api/cli/${path}`, base).toString(), {
180
+ return httpRequest(new URL(`api/cli/${path}`, base).toString(), {
406
181
  method,
407
182
  headers,
408
- ...init.body ? { body: JSON.stringify(init.body) } : {},
409
- 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 };
410
206
  }).catch((err) => {
411
- 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;
412
210
  });
413
- const minimum = res.headers.get(CLI_MINIMUM_HEADER);
414
- const latest = res.headers.get(CLI_LATEST_HEADER) || null;
415
- if (minimum) {
416
- serverCli = { minimum, latest };
417
- opts.onServerCli?.(serverCli);
418
- }
419
- if (opts.version && minimum && compareVersions(opts.version, minimum) < 0) {
420
- await res.body?.cancel().catch(() => {});
421
- const install = versionToInstall(minimum, latest);
422
- throw new ArmadaApiError(upgradeLine(opts.version, install), null, false, res.status, install);
423
- }
424
- if (res.status === 304)
425
- return { status: 304, body: {} };
426
- const body = await res.json().catch(() => null);
427
- if (typeof body !== "object" || body === null || Array.isArray(body))
428
- 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");
429
- return { status: res.status, body };
430
211
  }
431
212
  const refusal = (status, body, what) => {
432
213
  const error = typeof body.error === "string" ? body.error : `HTTP ${status}`;
@@ -476,7 +257,11 @@ function armadaApi(opts) {
476
257
  return body;
477
258
  },
478
259
  async credentials(signIn, purpose = null) {
479
- 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
+ });
480
265
  if (status !== 200)
481
266
  throw refusal(status, body, status === 401 ? null : "Armada gave no keys");
482
267
  const str = (v) => typeof v === "string" && v.length > 0;
@@ -514,7 +299,18 @@ function armadaApi(opts) {
514
299
  const { status, body: answer } = await call("POST", `fleet/${op}`, {
515
300
  signIn,
516
301
  body,
517
- ...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)
518
314
  });
519
315
  if (status === 304)
520
316
  return null;
@@ -525,7 +321,7 @@ function armadaApi(opts) {
525
321
  return answer.result;
526
322
  },
527
323
  async listSecrets(signIn, project) {
528
- 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 });
529
325
  if (status !== 200)
530
326
  throw refusal(status, body, status === 401 ? null : "Armada did not list the secrets");
531
327
  if (!Array.isArray(body.secrets))
@@ -697,10 +493,10 @@ function checkAttachment(input) {
697
493
  }
698
494
 
699
495
  // ../core/src/model.ts
700
- var CLOSED2 = ["completed", "canceled"];
496
+ var CLOSED = ["completed", "canceled"];
701
497
  var NOT_STARTED = ["triage", "backlog", "unstarted"];
702
498
  var isDone = (i) => i.statusType === "completed";
703
- var isClosed = (i) => CLOSED2.includes(i.statusType);
499
+ var isClosed = (i) => CLOSED.includes(i.statusType);
704
500
  var isStarted = (i) => i.statusType === "started";
705
501
  var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
706
502
  var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
@@ -823,6 +619,18 @@ function criticalIds(m) {
823
619
  return out;
824
620
  }
825
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
+
826
634
  // ../core/src/fleet.ts
827
635
  var MIN = 60000;
828
636
  var NEEDS_HUMAN = ["awaiting-approval", "awaiting-validation", "blocked", "ready-to-merge"];
@@ -2874,100 +2682,400 @@ function setHerdrPermissions(text, names, choice) {
2874
2682
  `) ? `\r
2875
2683
  ` : `
2876
2684
  `;
2877
- let insertAt = keyLine(profileLines, "effort");
2878
- insertAt = insertAt < 0 ? keyLine(profileLines, "model") : insertAt;
2879
- insertAt = insertAt < 0 ? 1 : insertAt + 1;
2880
- if (insertAt > 0 && insertAt <= profileLines.length) {
2881
- const previous = insertAt - 1;
2882
- profileLines[previous] = addLineBreak(profileLines[previous] ?? "", newline);
2883
- }
2884
- const sourceLine = profileLines.find((line) => keyAssignment(line, "harness")) ?? "";
2885
- const indent = sourceLine.match(/^\s*/)?.[0] ?? "";
2886
- 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 }
2887
2948
  }
2888
- let profileSource = profileLines.join("");
2889
- const existingArgs = profile.extra_args;
2890
- if (choice === "ask" && existingArgs !== undefined) {
2891
- if (!Array.isArray(existingArgs) || !existingArgs.every((arg) => typeof arg === "string"))
2892
- throw new Error(`could not safely edit extra_args for profile "${name}"`);
2893
- const assignment = arrayAssignment(profileSource, "extra_args");
2894
- if (!assignment)
2895
- throw new Error(`could not safely edit extra_args for profile "${name}"`);
2896
- const scanned = assignment.scan.items.map((item) => item.value);
2897
- if (canonicalToml(scanned) !== canonicalToml(existingArgs))
2898
- throw new Error(`could not safely edit extra_args for profile "${name}"`);
2899
- profileSource = removeArrayItems(profileSource, assignment, (arg) => arg.trim() === HERDR_FULL_PERMISSION_ARGS[harness]);
2900
- const expectedProfile = expectedProfiles[name];
2901
- 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));
2902
2994
  }
2903
- const updatedProfile = expectedProfiles[name];
2904
- updatedProfile.permissions = choice;
2905
- replacements.push({ start: section.start, end: section.end, source: profileSource });
2906
2995
  }
2907
- const nextLines = [...lines];
2908
- for (const replacement of replacements.sort((a, b) => b.start - a.start))
2909
- nextLines.splice(replacement.start, replacement.end - replacement.start, ...linesOf(replacement.source));
2910
- const next = nextLines.join("");
2911
- if (canonicalToml(parse(next)) !== canonicalToml(expected))
2912
- throw new Error("could not safely edit profile permissions");
2913
- return next;
2996
+ return comments;
2914
2997
  }
2915
- function setHerdrModel(text, name, model) {
2916
- const raw = parse(text);
2917
- const profiles = raw.herdr?.profiles;
2918
- if (!profiles?.[name])
2919
- throw new Error("profile is no longer present");
2920
- const lines = text.split(/(?<=\n)/);
2921
- let section = -1;
2922
- let end = lines.length;
2923
- for (let i = 0;i < lines.length; i++) {
2924
- const header = lines[i]?.match(/^\s*\[herdr\s*\.\s*profiles\s*\.\s*(.+?)\]\s*(?:#.*)?(?:\r?\n)?$/);
2925
- if (header) {
2926
- const key = header[1]?.trim();
2927
- if (key && Object.hasOwn(parse(`[${key}]
2928
- `), name)) {
2929
- 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`);
2930
3026
  break;
2931
3027
  }
3028
+ after = endCursor;
2932
3029
  }
3030
+ parents = next;
2933
3031
  }
2934
- if (section < 0)
2935
- throw new Error("use an explicit [herdr.profiles.<name>] section to save the model");
2936
- for (let i = section + 1;i < lines.length; i++) {
2937
- if (/^\s*\[/.test(lines[i] ?? "")) {
2938
- end = i;
2939
- break;
2940
- }
2941
- }
2942
- let replaced = false;
2943
- for (let i = section + 1;i < end; i++) {
2944
- const match = lines[i]?.match(/^(\s*(?:model|"model"|'model')\s*=\s*)("(?:[^"\\]|\\.)*"|'[^']*')(.*?)(\r?\n)?$/);
2945
- if (match) {
2946
- const value = match[2]?.startsWith("'") && !model.includes("'") ? `'${model}'` : JSON.stringify(model);
2947
- lines[i] = `${match[1]}${value}${match[3]}${match[4] ?? ""}`;
2948
- replaced = true;
2949
- 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;
2950
3069
  }
2951
3070
  }
2952
- if (!replaced) {
2953
- const newline = text.includes(`\r
2954
- `) ? `\r
2955
- ` : `
2956
- `;
2957
- if (!(lines[section] ?? "").endsWith(`
2958
- `))
2959
- lines[section] += newline;
2960
- lines.splice(section + 1, 0, `model = ${JSON.stringify(model)}${newline}`);
2961
- }
2962
- const next = lines.join("");
2963
- profiles[name].model = model;
2964
- if (JSON.stringify(parse(next)) !== JSON.stringify(raw)) {
2965
- 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);
2966
- if (canonical(parse(next)) !== canonical(raw))
2967
- throw new Error("could not safely edit the profile model");
2968
- }
2969
- return next;
2970
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
+ }`;
2971
3079
 
2972
3080
  // ../core/src/npm.ts
2973
3081
  var ARMADA_PACKAGE = CLI_PACKAGE;
@@ -4310,22 +4418,22 @@ var PULLS_QUERY = `${PULL_FIELDS}
4310
4418
  }
4311
4419
  }`;
4312
4420
  async function githubQuery(opts, query, variables) {
4313
- const doFetch = opts.fetch ?? fetch;
4314
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
4315
- const res = await doFetch(GITHUB_GRAPHQL, {
4421
+ return httpRequest(GITHUB_GRAPHQL, {
4316
4422
  method: "POST",
4317
4423
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
4318
- body: JSON.stringify({ query, variables }),
4319
- 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;
4320
4432
  }).catch((err) => {
4321
- 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;
4322
4436
  });
4323
- if (!res.ok)
4324
- throw new GithubError(`GitHub API HTTP ${res.status}`);
4325
- const json = await res.json();
4326
- if (json.errors?.length)
4327
- throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
4328
- return json;
4329
4437
  }
4330
4438
  var PULL_QUERY = `${PULL_FIELDS}
4331
4439
  query Pull($owner: String!, $name: String!, $number: Int!) {
@@ -4388,24 +4496,24 @@ var FILE_QUERY = `
4388
4496
  }`;
4389
4497
  async function fetchDefaultBranchFile(opts) {
4390
4498
  const [owner, name] = opts.repository.split("/");
4391
- const doFetch = opts.fetch ?? fetch;
4392
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
4393
- const res = await doFetch(GITHUB_GRAPHQL, {
4499
+ return httpRequest(GITHUB_GRAPHQL, {
4394
4500
  method: "POST",
4395
4501
  headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
4396
- body: JSON.stringify({ query: FILE_QUERY, variables: { owner, name, expression: `HEAD:${opts.path}` } }),
4397
- 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;
4398
4512
  }).catch((err) => {
4399
- 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;
4400
4516
  });
4401
- if (!res.ok)
4402
- throw new GithubError(`GitHub API HTTP ${res.status}`);
4403
- const json = await res.json();
4404
- if (json.errors?.length)
4405
- throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
4406
- if (!json.data?.repository)
4407
- throw new GithubError(`GitHub: repository ${opts.repository} not found`);
4408
- return json.data.repository.object?.text ?? null;
4409
4517
  }
4410
4518
  var MERGE_PULL_QUERY = `${PULL_FIELDS}
4411
4519
  query MergePull($owner: String!, $name: String!, $number: Int!) {
@@ -4459,18 +4567,18 @@ async function fetchComparison(opts) {
4459
4567
  return { baseSha: ref.target.oid, ...ref.compare };
4460
4568
  }
4461
4569
  async function fetchPullDiff(opts) {
4462
- const doFetch = opts.fetch ?? fetch;
4463
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
4464
- 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}`, {
4465
4571
  method: "GET",
4466
- headers: { Accept: "application/vnd.github.diff", Authorization: `Bearer ${opts.token}` },
4467
- 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();
4468
4577
  }).catch((err) => {
4469
- 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;
4470
4581
  });
4471
- if (!res.ok)
4472
- throw new GithubError(`GitHub API HTTP ${res.status} reading the diff of #${opts.number}`);
4473
- return res.text();
4474
4582
  }
4475
4583
  var COMMIT_QUERY = `
4476
4584
  query Commit($owner: String!, $name: String!, $oid: GitObjectID!) {
@@ -5017,10 +5125,10 @@ function ensure(ok, what) {
5017
5125
  function createLinearWriter(opts) {
5018
5126
  return {
5019
5127
  async viewer() {
5020
- return (await gql(opts, VIEWER_QUERY, {})).viewer;
5128
+ return (await gql({ ...opts, retry: true }, VIEWER_QUERY, {})).viewer;
5021
5129
  },
5022
5130
  async readTicket(id) {
5023
- const data = await gql(opts, TICKET_QUERY, { id }).catch((err) => {
5131
+ const data = await gql({ ...opts, retry: true }, TICKET_QUERY, { id }).catch((err) => {
5024
5132
  if (err instanceof LinearError && /not found/i.test(err.message))
5025
5133
  return { issue: null };
5026
5134
  throw err;
@@ -5035,7 +5143,7 @@ function createLinearWriter(opts) {
5035
5143
  return normalizeTicket(raw, opts.labels, warnings);
5036
5144
  },
5037
5145
  async groupLabels(group, teamId) {
5038
- const data = await gql(opts, GROUP_LABELS_QUERY, { group });
5146
+ const data = await gql({ ...opts, retry: true }, GROUP_LABELS_QUERY, { group });
5039
5147
  const usable = data.issueLabels.nodes.filter((l) => !l.team || l.team.id === teamId);
5040
5148
  const byName = new Map;
5041
5149
  for (const l of [...usable].sort((a, b) => Number(!!b.team) - Number(!!a.team)))
@@ -5055,20 +5163,23 @@ function createLinearWriter(opts) {
5055
5163
  input.removedLabelIds = change.removeLabelIds;
5056
5164
  if (!Object.keys(input).length)
5057
5165
  return;
5058
- 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
+ });
5059
5170
  ensure(data.issueUpdate?.success, "update the ticket");
5060
5171
  },
5061
5172
  async comment(uuid, body) {
5062
- 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 } });
5063
5174
  ensure(data.commentCreate?.success && !!data.commentCreate.comment, "post the comment");
5064
5175
  return { id: data.commentCreate.comment?.id ?? "" };
5065
5176
  },
5066
5177
  async deleteComment(id) {
5067
- const data = await gql(opts, DELETE_COMMENT_MUTATION, { id });
5178
+ const data = await gql({ ...opts, retry: false }, DELETE_COMMENT_MUTATION, { id });
5068
5179
  ensure(data.commentDelete?.success, "delete the comment");
5069
5180
  },
5070
5181
  async linkUrl(uuid, url, title) {
5071
- const data = await gql(opts, LINK_MUTATION, {
5182
+ const data = await gql({ ...opts, retry: false }, LINK_MUTATION, {
5072
5183
  issueId: uuid,
5073
5184
  url,
5074
5185
  title
@@ -10233,6 +10344,7 @@ var planIsEmpty = (p) => !p.writes.length && !p.removes.length && !p.links.lengt
10233
10344
 
10234
10345
  // ../core/src/status.ts
10235
10346
  var STATUS_SCHEMA_VERSION = 1;
10347
+ var MERGED_SHOWN = 10;
10236
10348
  function routeOf(config, labels) {
10237
10349
  const route = routeProfile(config, labels);
10238
10350
  return route ? { profile: route.name, why: describeRoute(route, config) } : null;
@@ -10351,9 +10463,37 @@ function buildStatus({
10351
10463
  shippingStage: stageOf.get(ticket.id) ?? null
10352
10464
  } : null
10353
10465
  })) : null,
10466
+ merged: mergedTickets(m, phaseOf, live),
10354
10467
  warnings: [...program.warnings, ...forge?.warnings ?? [], ...extraWarnings]
10355
10468
  };
10356
10469
  }
10470
+ function mergedTickets(m, inFlight, live) {
10471
+ const out = [];
10472
+ for (const issue of m.program) {
10473
+ if (!m.isLeaf(issue) || inFlight.has(issue.id))
10474
+ continue;
10475
+ const event = freshEvent(issue.id, { live });
10476
+ const fresh = event?.kind === "merge" ? event : null;
10477
+ const merged = issue.prs.filter((p) => p.state === "merged").sort(byMergeTime).at(-1);
10478
+ const pr = merged ?? (fresh ? issue.prs.at(-1) : undefined);
10479
+ if (!pr || !(isDone(issue) || fresh))
10480
+ continue;
10481
+ const mergedAt = fresh?.at ?? merged?.mergedAt ?? issue.completedAt;
10482
+ if (!mergedAt)
10483
+ continue;
10484
+ const spec = m.specOf(issue.id);
10485
+ out.push({
10486
+ id: issue.id,
10487
+ title: issue.title,
10488
+ url: issue.url,
10489
+ spec: spec ? `Spec ${spec.ordinal}` : null,
10490
+ mergedAt,
10491
+ pr: { number: pr.number, url: pr.url }
10492
+ });
10493
+ }
10494
+ return out.sort((a, b) => b.mergedAt.localeCompare(a.mergedAt) || b.id.localeCompare(a.id, "en", { numeric: true })).slice(0, MERGED_SHOWN);
10495
+ }
10496
+ var byMergeTime = (a, b) => (a.mergedAt ?? "").localeCompare(b.mergedAt ?? "") || a.number - b.number;
10357
10497
  async function readStatusSources(config, opts) {
10358
10498
  const now = opts.now ?? (() => new Date);
10359
10499
  const programP = fetchProgram({
@@ -10542,7 +10682,7 @@ ${attachments.join(`
10542
10682
  };
10543
10683
  }
10544
10684
  // package.json
10545
- var version = "0.2.50";
10685
+ var version = "0.2.52";
10546
10686
 
10547
10687
  // src/attach.ts
10548
10688
  import { resolve } from "node:path";
@@ -10665,6 +10805,8 @@ async function fromArmada(io, credentials, purpose) {
10665
10805
  throw err;
10666
10806
  if (err.status === 503)
10667
10807
  return null;
10808
+ if (!credentials.linearApiKey)
10809
+ throw err;
10668
10810
  io.stderr(`! Armada gave no keys (${err.message}); using this machine's${err.next ? `. Next: ${err.next}` : ""}
10669
10811
  `);
10670
10812
  return null;
@@ -15667,6 +15809,15 @@ function readCodexModels(cwd, io = system) {
15667
15809
  });
15668
15810
  }
15669
15811
 
15812
+ // src/http.ts
15813
+ function cliFetch(doFetch = fetch) {
15814
+ return (url, init) => {
15815
+ const headers = new Headers(init.headers);
15816
+ headers.set("Connection", "close");
15817
+ return doFetch(url, { ...init, headers });
15818
+ };
15819
+ }
15820
+
15670
15821
  // src/line.ts
15671
15822
  var emptyLine = () => ({ answer: "", sequence: "none" });
15672
15823
  function feedLine(line, chunk) {
@@ -15952,7 +16103,7 @@ var code = await run(process.argv.slice(2), {
15952
16103
  },
15953
16104
  stderr: (t) => process.stderr.write(t),
15954
16105
  ghToken,
15955
- fetch: (url, init) => fetch(url, init),
16106
+ fetch: cliFetch(),
15956
16107
  inspectProcess: (pid) => inspectProcess(exec, pid),
15957
16108
  signalProcess: (pid, signal) => {
15958
16109
  process.kill(pid, signal);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@the-vibe-company/armada",
3
- "version": "0.2.50",
3
+ "version": "0.2.52",
4
4
  "type": "module",
5
5
  "description": "Run a fleet of coding agents on one project: the armada command line.",
6
6
  "license": "MIT",