@the-vibe-company/armada 0.2.13 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/armada.js +2085 -2078
  2. package/package.json +1 -1
package/dist/armada.js CHANGED
@@ -10,930 +10,578 @@ import { isatty } from "node:tty";
10
10
  // src/cli.ts
11
11
  import { dirname as dirname7, join as join6, resolve as resolve2 } 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
- ];
22
-
23
- // ../core/src/linear.ts
24
- var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
25
- var MAX_DEPTH = 8;
26
- var COMMENT_BATCH = 25;
27
- var MAX_COMMENTS = 100;
28
- var MORE_PAGE = 100;
29
- var REQUEST_TIMEOUT_MS = 30000;
13
+ // ../core/src/live.ts
14
+ import { createHash } from "node:crypto";
30
15
 
31
- class LinearError extends Error {
32
- transport;
33
- name = "LinearError";
34
- constructor(message, transport = false) {
35
- super(message);
36
- this.transport = transport;
37
- }
38
- }
39
- var PHASES = [...LABEL_PHASES, "released", "merged"];
40
- var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
41
- var firstLine = (body) => (body.split(`
42
- `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
43
- var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
44
- var PLAN_BLOCK = /^## Plan[ \t]*$/m;
45
- function parseStatusLine(body) {
46
- const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
47
- if (!m?.[1])
48
- return null;
49
- const raw = m[1].toLowerCase();
50
- const phase = LEGACY[raw] ?? raw;
51
- const summary = (m[2] ?? "").trim();
52
- if (COORDINATOR_RECORD.test(summary))
53
- return null;
54
- if (!PHASES.includes(phase))
55
- return null;
56
- return PLAN_BLOCK.test(body) ? { phase, summary, plan: true } : { phase, summary };
57
- }
58
- var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
59
- var trimMarks = (v) => {
60
- const t = v.trim();
61
- return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
62
- };
63
- function parseClaim(body, at, author) {
64
- const line = body.split(`
65
- `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
66
- if (!line)
67
- return null;
68
- const field = (k) => {
69
- const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
70
- return v && trimMarks(v) || null;
71
- };
72
- return {
73
- runtime: field("runtime"),
74
- session: field("session"),
75
- branch: field("branch|branche"),
76
- startedAt: field("started|démarré|demarre"),
77
- profile: field("profile"),
78
- at,
79
- author
80
- };
81
- }
82
- function excerpt(markdown, max = 240) {
83
- const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
84
- return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
85
- }
86
- function parsePullRequestUrl(url, title = "") {
87
- const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
88
- return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
16
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
17
+ /*!
18
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
19
+ * SPDX-License-Identifier: BSD-3-Clause
20
+ *
21
+ * Redistribution and use in source and binary forms, with or without
22
+ * modification, are permitted provided that the following conditions are met:
23
+ *
24
+ * 1. Redistributions of source code must retain the above copyright notice, this
25
+ * list of conditions and the following disclaimer.
26
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
27
+ * this list of conditions and the following disclaimer in the
28
+ * documentation and/or other materials provided with the distribution.
29
+ * 3. Neither the name of the copyright holder nor the names of its contributors
30
+ * may be used to endorse or promote products derived from this software without
31
+ * specific prior written permission.
32
+ *
33
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
34
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
35
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
36
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
37
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
38
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
39
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
40
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
41
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
42
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43
+ */
44
+ function getLineColFromPtr(string, ptr) {
45
+ let lines = string.slice(0, ptr).split(/\r?\n/);
46
+ return [lines.length, lines.pop().length + 1];
89
47
  }
90
- function agentLabels(labels, groups) {
91
- let agentPhase = null;
92
- for (const l of labels)
93
- if (l.group === groups.phaseGroup)
94
- agentPhase ??= phaseNamed(l.name);
95
- const runtime = labels.find((l) => l.group === groups.runtimeGroup);
96
- return { agentPhase, agentRuntime: runtime?.name ?? null };
48
+ function makeCodeBlock(string, line, column) {
49
+ let lines = string.split(/\r?\n/);
50
+ let codeblock = "";
51
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
52
+ for (let i = line - 1;i <= line + 1; i++) {
53
+ let l = lines[i - 1];
54
+ if (!l)
55
+ continue;
56
+ codeblock += i.toString().padEnd(numberLen, " ");
57
+ codeblock += ": ";
58
+ codeblock += l;
59
+ codeblock += `
60
+ `;
61
+ if (i === line) {
62
+ codeblock += " ".repeat(numberLen + column + 2);
63
+ codeblock += `^
64
+ `;
65
+ }
66
+ }
67
+ return codeblock;
97
68
  }
98
- var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
99
- var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
100
- function normalizeIssue(raw, groups) {
101
- const blockers = new Map;
102
- for (const r of raw.inverseRelations.nodes)
103
- if (r.type === "blocks")
104
- blockers.set(r.issue.identifier, { id: r.issue.identifier, statusType: r.issue.state.type });
105
- const prs = new Map;
106
- for (const a of raw.attachments.nodes) {
107
- const pr = parsePullRequestUrl(a.url, a.title);
108
- if (pr)
109
- prs.set(pr.url, pr);
69
+
70
+ class TomlError extends Error {
71
+ line;
72
+ column;
73
+ codeblock;
74
+ constructor(message, options) {
75
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
76
+ const codeblock = makeCodeBlock(options.toml, line, column);
77
+ super(`Invalid TOML document: ${message}
78
+
79
+ ${codeblock}`, options);
80
+ this.line = line;
81
+ this.column = column;
82
+ this.codeblock = codeblock;
110
83
  }
111
- for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
112
- const pr = parsePullRequestUrl(m[0]);
113
- if (pr && !prs.has(pr.url))
114
- prs.set(pr.url, pr);
84
+ static x(message, ctx, ptr) {
85
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
115
86
  }
116
- const labels = raw.labels.nodes.map((l) => ({ name: l.name, group: l.parent?.name ?? null }));
117
- return {
118
- id: raw.identifier,
119
- uuid: raw.id,
120
- title: raw.title,
121
- url: raw.url,
122
- status: raw.state.name,
123
- statusType: raw.state.type,
124
- assignee: raw.assignee?.name ?? null,
125
- delegate: raw.delegate?.name ?? null,
126
- labels: labels.map((l) => l.name),
127
- ...agentLabels(labels, groups),
128
- parentId: raw.parent?.identifier ?? null,
129
- createdAt: raw.createdAt,
130
- updatedAt: raw.updatedAt,
131
- startedAt: raw.startedAt,
132
- completedAt: raw.completedAt,
133
- canceledAt: raw.canceledAt,
134
- blockedBy: [...blockers.values()].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
135
- prs: [...prs.values()].sort((a, b) => a.number - b.number)
136
- };
137
- }
138
- function normalizeComment(raw, issueId) {
139
- const author = raw.user?.name ?? null;
140
- return {
141
- id: raw.id,
142
- issueId,
143
- author,
144
- createdAt: raw.createdAt,
145
- excerpt: excerpt(raw.body, 600),
146
- status: parseStatusLine(raw.body),
147
- claim: parseClaim(raw.body, raw.createdAt, author)
148
- };
149
87
  }
150
- var MORE = {
151
- inverseRelations: {
152
- field: "inverseRelations",
153
- nodes: "type issue { identifier state { type } }",
154
- operation: "MoreRelations",
155
- what: "relations"
156
- },
157
- labels: { field: "labels", nodes: "name parent { name }", operation: "MoreLabels", what: "labels" },
158
- attachments: { field: "attachments", nodes: "title url", operation: "MoreAttachments", what: "attachments" },
159
- comments: {
160
- field: "comments",
161
- nodes: "id createdAt body user { name }",
162
- operation: "MoreComments",
163
- what: "comments"
88
+
89
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/primitive.js
90
+ /*!
91
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
92
+ * SPDX-License-Identifier: BSD-3-Clause
93
+ *
94
+ * Redistribution and use in source and binary forms, with or without
95
+ * modification, are permitted provided that the following conditions are met:
96
+ *
97
+ * 1. Redistributions of source code must retain the above copyright notice, this
98
+ * list of conditions and the following disclaimer.
99
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
100
+ * this list of conditions and the following disclaimer in the
101
+ * documentation and/or other materials provided with the distribution.
102
+ * 3. Neither the name of the copyright holder nor the names of its contributors
103
+ * may be used to endorse or promote products derived from this software without
104
+ * specific prior written permission.
105
+ *
106
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
107
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
108
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
109
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
110
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
111
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
112
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
113
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
114
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
115
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
116
+ */
117
+ function parseString(ctx) {
118
+ let startPtr = ctx.p;
119
+ let c = ctx.s.charCodeAt(ctx.p++);
120
+ let first = c;
121
+ let isLiteral = c === 39;
122
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
123
+ if (isMultiline) {
124
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
125
+ ctx.p++;
126
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
127
+ ctx.p += 2;
164
128
  }
165
- };
166
- var MORE_QUERY = (m) => `
167
- query ${m.operation}($id: String!, $after: String) {
168
- issue(id: $id) {
169
- ${m.field}(first: ${m.first ?? MORE_PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${m.nodes} } }
170
- }
171
- }`;
172
- var FIELDS = (delegate) => `
173
- fragment F on Issue {
174
- id identifier title url description createdAt updatedAt startedAt completedAt canceledAt
175
- state { name type }
176
- assignee { name }
177
- ${delegate ? "delegate { name }" : ""}
178
- parent { identifier }
179
- labels(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.labels.nodes} } }
180
- attachments(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.attachments.nodes} } }
181
- inverseRelations(first: 50) { pageInfo { hasNextPage endCursor } nodes { ${MORE.inverseRelations.nodes} } }
182
- }
183
- `;
184
- var ROOT_QUERY = (d) => `${FIELDS(d)} query Root($id: String!) { issue(id: $id) { ...F } }`;
185
- var CHILDREN_QUERY = (d) => `${FIELDS(d)}
186
- query Children($parents: [ID!], $after: String) {
187
- issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
188
- pageInfo { hasNextPage endCursor }
189
- nodes { ...F }
190
- }
191
- }`;
192
- var COMMENTS_QUERY = `
193
- query Comments($ids: [ID!]) {
194
- issues(first: 50, filter: { id: { in: $ids } }) {
195
- nodes { identifier comments(first: ${MAX_COMMENTS}) { pageInfo { hasNextPage endCursor } nodes { ${MORE.comments.nodes} } } }
196
- }
197
- }`;
198
- async function gql(opts, query, variables) {
199
- const doFetch = opts.fetch ?? fetch;
200
- const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
201
- const res = await doFetch(LINEAR_ENDPOINT, {
202
- method: "POST",
203
- headers: { "Content-Type": "application/json", Authorization: opts.apiKey },
204
- body: JSON.stringify({ query, variables }),
205
- signal: AbortSignal.timeout(timeoutMs)
206
- }).catch((err) => {
207
- throw new LinearError(`Linear API unreachable: ${networkReason(err, timeoutMs)}`, true);
208
- });
209
- if (res.status === 401)
210
- throw new LinearError("Linear rejected the API key (HTTP 401); check LINEAR_API_KEY", true);
211
- const json = await res.json().catch(() => ({}));
212
- if (json.errors?.length)
213
- throw new LinearError(`Linear API: ${json.errors.map((e) => e.message).join("; ")}`);
214
- if (!res.ok)
215
- throw new LinearError(`Linear API HTTP ${res.status}`, true);
216
- if (!json.data)
217
- throw new LinearError("Linear API: empty response");
218
- return json.data;
219
- }
220
- function networkReason(err, timeoutMs) {
221
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
222
- return `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`;
223
- return err instanceof Error ? err.message : String(err);
224
- }
225
- var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
226
- var CLOSED = new Set(["completed", "canceled"]);
227
- var isCandidate = (i, rootId) => i.id !== rootId && !CLOSED.has(i.statusType) && (i.agentPhase !== null || i.statusType === "started");
228
- async function readComments(opts, issues, warnings) {
229
- const comments = [];
230
- for (const batch of chunks(issues.map((i) => i.uuid), COMMENT_BATCH)) {
231
- const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
232
- for (const n of data.issues.nodes) {
233
- await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
234
- for (const c of n.comments.nodes)
235
- comments.push(normalizeComment(c, n.identifier));
236
- }
237
- }
238
- return comments;
239
- }
240
- async function fetchProgram(opts) {
241
- try {
242
- return await fetchTree(opts, true);
243
- } catch (err) {
244
- if (err instanceof LinearError && /delegate/i.test(err.message))
245
- return fetchTree(opts, false);
246
- throw err;
247
- }
248
- }
249
- async function fetchTree(opts, delegate) {
250
- const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
251
- if (!root)
252
- throw new LinearError(`Linear: program root ${opts.rootId} not found`);
253
- const all = [root];
254
- const warnings = [];
255
- let parents = [root.id];
256
- for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
257
- const next = [];
258
- let after = null;
259
- for (;; ) {
260
- const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
261
- all.push(...data.issues.nodes);
262
- next.push(...data.issues.nodes.map((n) => n.id));
263
- const { hasNextPage, endCursor } = data.issues.pageInfo;
264
- if (!hasNextPage)
265
- break;
266
- if (!endCursor || endCursor === after) {
267
- warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
268
- break;
269
- }
270
- after = endCursor;
271
- }
272
- parents = next;
273
- }
274
- if (parents.length)
275
- warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
276
- for (const r of all)
277
- for (const field of ["inverseRelations", "labels", "attachments"])
278
- await readRest(opts, r.identifier, MORE[field], r[field], warnings);
279
- const issues = all.map((r) => normalizeIssue(r, opts.labels));
280
- const comments = await readComments(opts, issues.filter((i) => isCandidate(i, root.identifier)), warnings);
281
- return {
282
- rootId: root.identifier,
283
- fetchedAt: (opts.now?.() ?? new Date).toISOString(),
284
- issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
285
- comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
286
- warnings
287
- };
288
- }
289
- async function readRest(opts, identifier, more, conn, warnings) {
290
- while (conn.pageInfo?.hasNextPage) {
291
- const after = conn.pageInfo.endCursor;
292
- try {
293
- if (!after)
294
- throw new LinearError("Linear gave no cursor for the next page");
295
- const data = await gql(opts, MORE_QUERY(more), {
296
- id: identifier,
297
- after
298
- });
299
- const page = data.issue?.[more.field];
300
- if (!page)
301
- throw new LinearError(`Linear: issue ${identifier} not found`);
302
- conn.nodes.push(...page.nodes);
303
- conn.pageInfo = page.pageInfo;
304
- if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
305
- throw new LinearError("Linear did not advance to a next page");
306
- } catch (err) {
307
- if (!(err instanceof LinearError) || err.transport)
308
- throw err;
309
- warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
310
- return;
311
- }
312
- }
313
- }
314
- var CHANGED_COMMENTS_QUERY = `
315
- query ChangedComments($filter: CommentFilter, $after: String) {
316
- comments(first: ${MORE_PAGE}, after: $after, filter: $filter) {
317
- pageInfo { hasNextPage endCursor }
318
- nodes { ${MORE.comments.nodes} issue { identifier } }
319
- }
320
- }`;
321
-
322
- // ../core/src/armada-api.ts
323
- var MASKED_LAUNCH_TOKEN = "armada_launch_••••";
324
- var isMaskedLaunchToken = (token) => token.includes("•");
325
- var MASKED_LAUNCH_TOKEN_REFUSAL = {
326
- error: "this is the masked token from `armada brief`'s human view, not a launch token",
327
- next: "ask the coordinator for the `armada brief <ticket> --prompt` text: only it carries the token"
328
- };
329
- var displayCode = (code) => code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
330
- var CLI_PACKAGE = "@the-vibe-company/armada";
331
- var CLI_VERSION_HEADER = "x-armada-cli-version";
332
- var CLI_MINIMUM_HEADER = "x-armada-cli-minimum";
333
- var CLI_LATEST_HEADER = "x-armada-cli-latest";
334
- function compareVersions(a, b) {
335
- const parts = (v) => v.split(/[-+]/)[0]?.split(".").map((n) => Number.parseInt(n, 10) || 0) ?? [];
336
- const [x, y] = [parts(a), parts(b)];
337
- for (let i = 0;i < Math.max(x.length, y.length); i++) {
338
- const d = (x[i] ?? 0) - (y[i] ?? 0);
339
- if (d)
340
- return Math.sign(d);
341
- }
342
- return 0;
343
- }
344
- var versionToInstall = (minimum, latest) => latest && compareVersions(latest, minimum) >= 0 ? latest : minimum;
345
- var installCommand = (version) => `npm install -g ${CLI_PACKAGE}@${version}`;
346
- var upgradeLine = (version, install) => `Armada ${version} is older than this server expects: ${installCommand(install)}`;
347
- var releaseNotesUrl = (version) => `https://github.com/The-Vibe-Company/armada/releases/tag/v${version}`;
348
- var newerRelease = (running, latest) => latest && running !== "0.0.0" && compareVersions(latest, running) > 0 ? latest : null;
349
- var releaseLine = (running, latest) => `Armada ${latest} is out (you run ${running}): ${installCommand(latest)} — then armada init to refresh this project's skills. Changes: ${releaseNotesUrl(latest)}`;
350
-
351
- class ArmadaApiError extends Error {
352
- next;
353
- signedOut;
354
- status;
355
- upgrade;
356
- constructor(message, next = null, signedOut = false, status = null, upgrade = null) {
357
- super(message);
358
- this.next = next;
359
- this.signedOut = signedOut;
360
- this.status = status;
361
- this.upgrade = upgrade;
362
- }
363
- }
364
- var LOGIN_NEXT = "armada login";
365
- var TIMEOUT_MS = 30000;
366
- function apiBaseUrl(value) {
367
- let url;
368
- try {
369
- url = new URL(value);
370
- } catch {
371
- throw new ArmadaApiError(`the Armada API address "${value}" is not a URL`, "ARMADA_API_URL or [api] url in config.toml");
372
- }
373
- if (url.protocol !== "https:" && url.protocol !== "http:")
374
- throw new ArmadaApiError(`the Armada API address must be http or https, not ${url.protocol}`);
375
- if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
376
- throw new ArmadaApiError(`the Armada API address must use https (http only reaches localhost): ${url.origin}`, "ARMADA_API_URL or [api] url in config.toml");
377
- url.search = "";
378
- url.hash = "";
379
- if (!url.pathname.endsWith("/"))
380
- url.pathname += "/";
381
- return url;
382
- }
383
- function armadaApi(opts) {
384
- const base = apiBaseUrl(opts.url);
385
- const doFetch = opts.fetch ?? fetch;
386
- const timeoutMs = opts.timeoutMs ?? TIMEOUT_MS;
387
- const host = base.host;
388
- let serverCli = null;
389
- async function call(method, path, init = {}) {
390
- const limit = init.timeoutMs ?? timeoutMs;
391
- const headers = { Accept: "application/json" };
392
- if (init.body)
393
- headers["Content-Type"] = "application/json";
394
- if (init.signIn?.kind === "session" || init.signIn?.kind === "worker")
395
- headers.Authorization = `Bearer ${init.signIn.token}`;
396
- if (init.signIn?.kind === "api-key")
397
- headers["x-api-key"] = init.signIn.key;
398
- if (opts.version)
399
- headers[CLI_VERSION_HEADER] = opts.version;
400
- const res = await doFetch(new URL(`api/cli/${path}`, base).toString(), {
401
- method,
402
- headers,
403
- ...init.body ? { body: JSON.stringify(init.body) } : {},
404
- signal: AbortSignal.timeout(limit)
405
- }).catch((err) => {
406
- throw new ArmadaApiError(`Armada (${host}) unreachable: ${networkReason(err, limit)}`, "the same command again once it answers, or check ARMADA_API_URL");
407
- });
408
- const minimum = res.headers.get(CLI_MINIMUM_HEADER);
409
- const latest = res.headers.get(CLI_LATEST_HEADER) || null;
410
- if (minimum) {
411
- serverCli = { minimum, latest };
412
- opts.onServerCli?.(serverCli);
413
- }
414
- if (opts.version && minimum && compareVersions(opts.version, minimum) < 0) {
415
- await res.body?.cancel().catch(() => {});
416
- const install = versionToInstall(minimum, latest);
417
- throw new ArmadaApiError(upgradeLine(opts.version, install), null, false, res.status, install);
418
- }
419
- if (res.status === 304)
420
- return { status: 304, body: {} };
421
- const body = await res.json().catch(() => null);
422
- if (typeof body !== "object" || body === null || Array.isArray(body))
423
- 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");
424
- return { status: res.status, body };
425
- }
426
- const refusal = (status, body, what) => {
427
- const error = typeof body.error === "string" ? body.error : `HTTP ${status}`;
428
- const next = typeof body.next === "string" ? body.next : status === 401 ? LOGIN_NEXT : null;
429
- return new ArmadaApiError(what ? `${what}: ${error}` : error, next, status === 401, status);
430
- };
431
- return {
432
- serverCli: () => serverCli,
433
- async startDeviceLogin() {
434
- const { status, body } = await call("POST", "device/code");
435
- if (status !== 200)
436
- throw refusal(status, body, "Armada refused to start the sign-in");
437
- const str = (k) => typeof body[k] === "string" ? body[k] : "";
438
- const num = (k, d) => typeof body[k] === "number" && body[k] > 0 ? body[k] : d;
439
- if (!str("device_code") || !str("user_code") || !str("verification_uri"))
440
- throw new ArmadaApiError(`Armada (${host}) answered the sign-in without a code`);
441
- return {
442
- deviceCode: str("device_code"),
443
- userCode: str("user_code"),
444
- verificationUri: str("verification_uri"),
445
- verificationUriComplete: str("verification_uri_complete") || str("verification_uri"),
446
- expiresInSeconds: num("expires_in", 900),
447
- intervalSeconds: num("interval", 5)
448
- };
449
- },
450
- async pollDeviceLogin(deviceCode) {
451
- const { status, body } = await call("POST", "device/token", { body: { device_code: deviceCode } });
452
- if (status === 200 && typeof body.access_token === "string" && body.access_token)
453
- return { state: "approved", token: body.access_token };
454
- switch (body.error) {
455
- case "authorization_pending":
456
- return { state: "pending" };
457
- case "slow_down":
458
- return { state: "slow-down" };
459
- case "access_denied":
460
- return { state: "denied" };
461
- case "expired_token":
462
- case "invalid_grant":
463
- return { state: "expired" };
129
+ let parsed = "";
130
+ let sliceStart = ctx.p;
131
+ let state = 0;
132
+ for (;ctx.p < ctx.s.length; ctx.p++) {
133
+ c = ctx.s.charCodeAt(ctx.p);
134
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
135
+ state = state && 3;
136
+ } else if (c < 32 && c !== 9 || c === 127) {
137
+ TomlError.x("control characters are not allowed in strings", ctx);
138
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
139
+ if (isMultiline) {
140
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
141
+ ctx.p++;
142
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
143
+ ctx.p++;
464
144
  }
465
- throw refusal(status, body, "Armada refused the sign-in");
466
- },
467
- async whoami(signIn) {
468
- const { status, body } = await call("GET", "session", { signIn });
469
- if (status !== 200)
470
- throw refusal(status, body, status === 401 ? null : "Armada could not say who is signed in");
471
- return body;
472
- },
473
- async credentials(signIn, purpose = null) {
474
- const { status, body } = await call("POST", "credentials", { signIn, body: purpose ? { purpose } : {} });
475
- if (status !== 200)
476
- throw refusal(status, body, status === 401 ? null : "Armada gave no keys");
477
- const str = (v) => typeof v === "string" && v.length > 0;
478
- const org = body.organization;
479
- const linear = body.linear;
480
- const shaped = body.schemaVersion === 1 && str(org?.id) && (linear === null || str(linear?.apiKey));
481
- if (!shaped)
482
- throw new ArmadaApiError(`Armada (${host}) answered the keys in a shape this CLI does not know`);
483
- const warnings = Array.isArray(body.warnings) ? body.warnings.filter((w) => typeof w === "string") : [];
484
- const scope = linear?.scope === "own" || linear?.scope === "project" ? linear.scope : "organization";
485
- return {
486
- schemaVersion: 1,
487
- organization: org,
488
- linear: linear ? { apiKey: linear.apiKey, scope } : null,
489
- warnings
490
- };
491
- },
492
- async projects(signIn) {
493
- const { status, body } = await call("GET", "projects", { signIn });
494
- if (status !== 200)
495
- throw refusal(status, body, status === 401 ? null : "Armada did not list the projects");
496
- if (!Array.isArray(body.projects))
497
- throw new ArmadaApiError(`Armada (${host}) answered the projects in a shape this CLI does not know`);
498
- return body.projects.flatMap((p) => typeof p.slug === "string" && typeof p.name === "string" && typeof p.repository === "string" && typeof p.programRoot === "string" ? [
499
- {
500
- slug: p.slug,
501
- name: p.name,
502
- repository: p.repository,
503
- programRoot: p.programRoot,
504
- ...p.ownLinearKey === true ? { ownLinearKey: true } : {}
145
+ if (!state) {
146
+ let s = ctx.s.slice(sliceStart, ctx.p);
147
+ parsed = parsed ? parsed + s : s;
148
+ }
149
+ ctx.p += isMultiline ? 3 : 1;
150
+ return parsed;
151
+ } else if (!state) {
152
+ if (!isLiteral && c === 92) {
153
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
154
+ state = 1;
155
+ }
156
+ } else if (state === 1) {
157
+ if (c === 120 || c === 117 || c === 85) {
158
+ let errPtr = ctx.p++ - 1;
159
+ let value = 0;
160
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
161
+ for (let j = 0;j < len; j++, ctx.p++) {
162
+ let hex = ctx.s.charCodeAt(ctx.p);
163
+ let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
164
+ if (digit < 0)
165
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
166
+ value = value << 4 | digit;
505
167
  }
506
- ] : []);
507
- },
508
- async fleet(signIn, op, body, timeoutMs) {
509
- const { status, body: answer } = await call("POST", `fleet/${op}`, {
510
- signIn,
511
- body,
512
- ...timeoutMs ? { timeoutMs } : {}
513
- });
514
- if (status === 304)
515
- return null;
516
- if (status !== 200)
517
- throw refusal(status, answer, status === 401 ? null : "Armada refused");
518
- if (!("result" in answer))
519
- throw new ArmadaApiError(`Armada (${host}) answered fleet/${op} in a shape this CLI does not know`);
520
- return answer.result;
521
- },
522
- async listSecrets(signIn, project) {
523
- const { status, body } = await call("POST", "secrets/list", { signIn, body: { project } });
524
- if (status !== 200)
525
- throw refusal(status, body, status === 401 ? null : "Armada did not list the secrets");
526
- if (!Array.isArray(body.secrets))
527
- throw new ArmadaApiError(`Armada (${host}) answered the secrets in a shape this CLI does not know`);
528
- return body.secrets.flatMap((s) => typeof s.name === "string" && typeof s.setBy === "string" && typeof s.setAt === "string" ? [
529
- {
530
- name: s.name,
531
- scope: s.scope === "organization" ? "organization" : "project",
532
- setBy: s.setBy,
533
- setAt: s.setAt,
534
- overridden: s.overridden === true
168
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
169
+ TomlError.x("invalid unicode escape", ctx, errPtr);
535
170
  }
536
- ] : []);
537
- },
538
- async releaseSecrets(signIn, project, names = null) {
539
- const { status, body } = await call("POST", "secrets/release", { signIn, body: { project, names } });
540
- if (status !== 200)
541
- throw refusal(status, body, status === 401 ? null : "Armada gave no secrets");
542
- const secrets = Array.isArray(body.secrets) ? body.secrets : null;
543
- if (!secrets?.every((s) => typeof s.name === "string" && typeof s.value === "string"))
544
- throw new ArmadaApiError(`Armada (${host}) answered the secrets in a shape this CLI does not know`);
545
- const strings = (v) => Array.isArray(v) ? v.filter((w) => typeof w === "string") : [];
546
- return {
547
- project: typeof body.project === "string" ? body.project : project.slug,
548
- secrets: secrets.map((s) => ({
549
- name: String(s.name),
550
- value: String(s.value),
551
- scope: s.scope === "organization" ? "organization" : "project"
552
- })),
553
- missing: strings(body.missing),
554
- warnings: strings(body.warnings)
555
- };
556
- },
557
- async setSecret(signIn, target) {
558
- const { status, body } = await call("POST", "secrets/set", { signIn, body: target });
559
- if (status !== 200)
560
- throw refusal(status, body, status === 401 ? null : `Armada did not set ${target.name}`);
561
- },
562
- async unsetSecret(signIn, target) {
563
- const { status, body } = await call("POST", "secrets/unset", { signIn, body: target });
564
- if (status !== 200)
565
- throw refusal(status, body, status === 401 ? null : `Armada did not unset ${target.name}`);
566
- return body.deleted === true;
567
- },
568
- async launchToken(signIn, target) {
569
- const { status, body } = await call("POST", "launch-tokens", { signIn, body: target });
570
- if (status !== 200)
571
- throw refusal(status, body, status === 401 ? null : "Armada made no launch token");
572
- const w = body.worker;
573
- if (typeof body.token !== "string" || typeof body.expiresAt !== "string" || !w?.ticket)
574
- throw new ArmadaApiError(`Armada (${host}) answered the launch token in a shape this CLI does not know`);
575
- return body;
576
- },
577
- async exchangeLaunchToken(token, handle = null) {
578
- const { status, body } = await call("POST", "launch-tokens/exchange", {
579
- body: handle ? { token, handle } : { token }
580
- });
581
- if (status !== 200)
582
- throw refusal(status, body, null);
583
- const w = body.worker;
584
- const org = body.organization;
585
- if (typeof body.token !== "string" || !w?.ticket || !w.project || !org?.id)
586
- throw new ArmadaApiError(`Armada (${host}) answered the launch token in a shape this CLI does not know`);
587
- return body;
588
- },
589
- async endWorkers(signIn, target) {
590
- const { status, body } = await call("POST", "workers/end", { signIn, body: target });
591
- if (status !== 200)
592
- throw refusal(status, body, "Armada did not end the ticket's workers");
593
- return typeof body.ended === "number" ? body.ended : 0;
594
- },
595
- async signOut(signIn) {
596
- const { status, body } = await call("DELETE", "session", { signIn });
597
- if (status !== 200)
598
- throw refusal(status, body, "Armada refused the sign-out");
599
- }
600
- };
601
- }
602
- async function waitForApproval({ api, code, sleep, now }) {
603
- const deadline = now().getTime() + code.expiresInSeconds * 1000;
604
- let interval = code.intervalSeconds * 1000;
605
- for (;; ) {
606
- await sleep(interval);
607
- if (now().getTime() > deadline)
608
- break;
609
- let poll;
610
- try {
611
- poll = await api.pollDeviceLogin(code.deviceCode);
612
- } catch (err) {
613
- if (!(err instanceof ArmadaApiError) || !/unreachable/.test(err.message))
614
- throw err;
615
- interval = Math.min(interval * 2, 60000);
616
- continue;
617
- }
618
- if (poll.state === "approved")
619
- return poll.token;
620
- if (poll.state === "denied")
621
- throw new ArmadaApiError("the sign-in was denied in the browser", LOGIN_NEXT);
622
- if (poll.state === "expired")
623
- break;
624
- if (poll.state === "slow-down")
625
- interval += 5000;
626
- }
627
- throw new ArmadaApiError("the code expired before it was approved", LOGIN_NEXT);
628
- }
629
- // ../core/src/model.ts
630
- var CLOSED2 = ["completed", "canceled"];
631
- var NOT_STARTED = ["triage", "backlog", "unstarted"];
632
- var isDone = (i) => i.statusType === "completed";
633
- var isClosed = (i) => CLOSED2.includes(i.statusType);
634
- var isStarted = (i) => i.statusType === "started";
635
- var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
636
- var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
637
- function buildModel(issues, rootId) {
638
- const byId = new Map(issues.map((i) => [i.id, i]));
639
- const root = byId.get(rootId);
640
- if (!root)
641
- throw new Error(`program root ${rootId} is not among the issues read`);
642
- const childrenOf = new Map;
643
- for (const i of issues) {
644
- if (!i.parentId || !byId.has(i.parentId))
645
- continue;
646
- childrenOf.set(i.parentId, [...childrenOf.get(i.parentId) ?? [], i]);
647
- }
648
- const program = [];
649
- const walk = (id, seen) => {
650
- for (const c of childrenOf.get(id) ?? []) {
651
- if (seen.has(c.id))
652
- continue;
653
- seen.add(c.id);
654
- program.push(c);
655
- walk(c.id, seen);
656
- }
657
- };
658
- walk(root.id, new Set([root.id]));
659
- const specs = (childrenOf.get(root.id) ?? []).flatMap((issue) => {
660
- const m = issue.title.trim().match(SPEC_TITLE);
661
- return m?.[1] && m[3] ? [{ issue, ordinal: Number(m[1]), name: m[3].trim() }] : [];
662
- }).sort((a, b) => a.ordinal - b.ordinal || a.issue.createdAt.localeCompare(b.issue.createdAt));
663
- const specById = new Map(specs.map((s) => [s.issue.id, s]));
664
- const specOf = (id) => {
665
- const seen = new Set;
666
- for (let cur = byId.get(id);cur && !seen.has(cur.id); cur = cur.parentId ? byId.get(cur.parentId) : undefined) {
667
- seen.add(cur.id);
668
- const s = specById.get(cur.id);
669
- if (s)
670
- return s;
171
+ parsed += String.fromCodePoint(value);
172
+ sliceStart = ctx.p--;
173
+ state = 0;
174
+ } else if (isMultiline && (c === 32 || c === 9)) {
175
+ state = 2;
176
+ } else {
177
+ if (c === 98)
178
+ parsed += "\b";
179
+ else if (c === 116)
180
+ parsed += "\t";
181
+ else if (c === 110)
182
+ parsed += `
183
+ `;
184
+ else if (c === 102)
185
+ parsed += "\f";
186
+ else if (c === 114)
187
+ parsed += "\r";
188
+ else if (c === 101)
189
+ parsed += "\x1B";
190
+ else if (c === 34)
191
+ parsed += '"';
192
+ else if (c === 92)
193
+ parsed += "\\";
194
+ else
195
+ TomlError.x("unrecognised escape sequence", ctx);
196
+ sliceStart = ctx.p + 1;
197
+ state = 0;
198
+ }
199
+ } else if (c !== 32 && c !== 9) {
200
+ if (state === 2)
201
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
202
+ state = !isLiteral && c === 92 ? 1 : 0;
203
+ sliceStart = ctx.p;
671
204
  }
672
- return null;
673
- };
674
- const isLeaf = (i) => !childrenOf.get(i.id)?.length && !specById.has(i.id);
675
- const openBlockersOf = (i) => i.blockedBy.filter((b) => !isClosed(byId.get(b.id) ?? b)).map((b) => b.id);
676
- const stateOf = (i) => {
677
- if (isDone(i))
678
- return "done";
679
- if (i.statusType === "canceled")
680
- return "canceled";
681
- if (isStarted(i))
682
- return "active";
683
- return openBlockersOf(i).length ? "blocked" : "frontier";
684
- };
685
- return { root, byId, childrenOf, program, specs, specOf, isLeaf, openBlockersOf, stateOf };
686
- }
687
- function longestPathLevels(nodes) {
688
- const byId = new Map(nodes.map((n) => [n.id, n]));
689
- const level = new Map;
690
- const visiting = new Set;
691
- const visit = (id) => {
692
- const known = level.get(id);
693
- if (known !== undefined)
694
- return known;
695
- if (visiting.has(id))
696
- return 0;
697
- visiting.add(id);
698
- const blockers = (byId.get(id)?.blockedBy ?? []).map((b) => b.id).filter((b) => byId.has(b));
699
- const l = blockers.length ? Math.max(...blockers.map(visit)) + 1 : 0;
700
- visiting.delete(id);
701
- level.set(id, l);
702
- return l;
703
- };
704
- for (const n of nodes)
705
- visit(n.id);
706
- return level;
205
+ }
206
+ TomlError.x("unfinished string", ctx, startPtr);
707
207
  }
708
- function criticalPath(m, parentId) {
709
- const nodes = m.childrenOf.get(parentId) ?? [];
710
- const level = longestPathLevels(nodes);
711
- const remaining = nodes.filter((n) => !isClosed(n));
712
- const remIds = new Set(remaining.map((n) => n.id));
713
- const len = new Map;
714
- const prev = new Map;
715
- const order = [...remaining].sort((a, b) => (level.get(a.id) ?? 0) - (level.get(b.id) ?? 0));
716
- for (const n of order) {
717
- let best = 0;
718
- let bestPrev = null;
719
- for (const { id } of n.blockedBy) {
720
- if (!remIds.has(id))
721
- continue;
722
- const l = len.get(id) ?? 0;
723
- if (l > best) {
724
- best = l;
725
- bestPrev = id;
208
+
209
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/date.js
210
+ /*!
211
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
212
+ * SPDX-License-Identifier: BSD-3-Clause
213
+ *
214
+ * Redistribution and use in source and binary forms, with or without
215
+ * modification, are permitted provided that the following conditions are met:
216
+ *
217
+ * 1. Redistributions of source code must retain the above copyright notice, this
218
+ * list of conditions and the following disclaimer.
219
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
220
+ * this list of conditions and the following disclaimer in the
221
+ * documentation and/or other materials provided with the distribution.
222
+ * 3. Neither the name of the copyright holder nor the names of its contributors
223
+ * may be used to endorse or promote products derived from this software without
224
+ * specific prior written permission.
225
+ *
226
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
227
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
228
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
229
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
230
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
231
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
232
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
233
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
234
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
235
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
236
+ */
237
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
238
+
239
+ class TomlDate extends Date {
240
+ #hasDate = false;
241
+ #hasTime = false;
242
+ #offset = null;
243
+ constructor(date, fasttype, unsafeDelim) {
244
+ let hasDate = true;
245
+ let hasTime = true;
246
+ let offset = "Z";
247
+ let c;
248
+ if (typeof date === "string") {
249
+ if (fasttype)
250
+ prep: {
251
+ if (fasttype < 3) {
252
+ if (+date.slice(11, 13) > 23) {
253
+ date = "";
254
+ break prep;
255
+ }
256
+ if (fasttype === 2) {
257
+ offset = null;
258
+ date += "Z";
259
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
260
+ offset = date.slice(date.length - 6);
261
+ }
262
+ if (unsafeDelim)
263
+ date = date.slice(0, 10) + "T" + date.slice(11);
264
+ } else if (fasttype === 4) {
265
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
266
+ }
267
+ hasDate = fasttype !== 4;
268
+ hasTime = fasttype !== 3;
269
+ }
270
+ else {
271
+ let match = date.match(DATE_TIME_RE);
272
+ if (match) {
273
+ if (!match[1]) {
274
+ hasDate = false;
275
+ date = `0000-01-01T${date}`;
276
+ }
277
+ hasTime = !!match[2];
278
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
279
+ if (match[2] && +match[2] > 23) {
280
+ date = "";
281
+ } else {
282
+ offset = match[3] || null;
283
+ if (!offset && hasTime)
284
+ date += "Z";
285
+ }
286
+ } else {
287
+ date = "";
288
+ }
726
289
  }
727
290
  }
728
- len.set(n.id, best + 1);
729
- prev.set(n.id, bestPrev);
730
- }
731
- let tail = null;
732
- let tailLen = 0;
733
- for (const [id, l] of len)
734
- if (l > tailLen || l === tailLen && tail && id > tail) {
735
- tail = id;
736
- tailLen = l;
291
+ super(date);
292
+ if (!isNaN(this.getTime())) {
293
+ this.#hasDate = hasDate;
294
+ this.#hasTime = hasTime;
295
+ this.#offset = offset;
737
296
  }
738
- if (tailLen < 2)
739
- return [];
740
- const path = [];
741
- for (let cur = tail;cur; cur = prev.get(cur) ?? null) {
742
- const issue = m.byId.get(cur);
743
- if (issue)
744
- path.unshift(issue);
745
297
  }
746
- return path;
747
- }
748
- function criticalIds(m) {
749
- const out = new Set;
750
- for (const parent of m.childrenOf.keys())
751
- for (const i of criticalPath(m, parent))
752
- out.add(i.id);
753
- return out;
298
+ isDateTime() {
299
+ return this.#hasDate && this.#hasTime;
300
+ }
301
+ isLocal() {
302
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
303
+ }
304
+ isDate() {
305
+ return this.#hasDate && !this.#hasTime;
306
+ }
307
+ isTime() {
308
+ return this.#hasTime && !this.#hasDate;
309
+ }
310
+ isValid() {
311
+ return this.#hasDate || this.#hasTime;
312
+ }
313
+ toISOString() {
314
+ let iso = super.toISOString();
315
+ if (this.isDate())
316
+ return iso.slice(0, 10);
317
+ if (this.isTime())
318
+ return iso.slice(11, 23);
319
+ if (this.#offset === null)
320
+ return iso.slice(0, -1);
321
+ if (this.#offset === "Z" || this.#offset === "z")
322
+ return iso;
323
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
324
+ offset = this.#offset[0] === "-" ? offset : -offset;
325
+ let offsetDate = new Date(this.getTime() - offset * 60000);
326
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
327
+ }
328
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
329
+ let date = new TomlDate(jsDate);
330
+ date.#offset = offset;
331
+ return date;
332
+ }
333
+ static wrapAsLocalDateTime(jsDate) {
334
+ let date = new TomlDate(jsDate);
335
+ date.#offset = null;
336
+ return date;
337
+ }
338
+ static wrapAsLocalDate(jsDate) {
339
+ let date = new TomlDate(jsDate);
340
+ date.#hasTime = false;
341
+ date.#offset = null;
342
+ return date;
343
+ }
344
+ static wrapAsLocalTime(jsDate) {
345
+ let date = new TomlDate(jsDate);
346
+ date.#hasDate = false;
347
+ date.#offset = null;
348
+ return date;
349
+ }
754
350
  }
755
351
 
756
- // ../core/src/fleet.ts
757
- var MIN = 60000;
758
- var NEEDS_HUMAN = ["awaiting-approval", "blocked", "ready-to-merge"];
759
- var PHASE_RANK = {
760
- merged: 0,
761
- "ready-to-merge": 1,
762
- shipping: 2,
763
- implementing: 3,
764
- "awaiting-approval": 4,
765
- planning: 5,
766
- blocked: 6,
767
- released: 7
768
- };
769
- var PLAN_HINT = /\b(plan|objective|assumptions|awaiting (?:plan )?approval)\b/i;
770
- function commentsFor(comments, id) {
771
- return comments.filter((c) => c.issueId === id).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
772
- }
773
- function commentUrl(issue, c) {
774
- return `${issue.url}#comment-${c.id.slice(0, 8)}`;
352
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/extract.js
353
+ /*!
354
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
355
+ * SPDX-License-Identifier: BSD-3-Clause
356
+ *
357
+ * Redistribution and use in source and binary forms, with or without
358
+ * modification, are permitted provided that the following conditions are met:
359
+ *
360
+ * 1. Redistributions of source code must retain the above copyright notice, this
361
+ * list of conditions and the following disclaimer.
362
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
363
+ * this list of conditions and the following disclaimer in the
364
+ * documentation and/or other materials provided with the distribution.
365
+ * 3. Neither the name of the copyright holder nor the names of its contributors
366
+ * may be used to endorse or promote products derived from this software without
367
+ * specific prior written permission.
368
+ *
369
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
370
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
371
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
372
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
373
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
374
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
375
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
376
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
377
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
378
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
379
+ */
380
+ function isDigit(char, base = 10) {
381
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
775
382
  }
776
- function primaryPr(issue) {
777
- const byNewest = [...issue.prs].sort((a, b) => b.number - a.number);
778
- return byNewest.find((p) => p.state === "open") ?? byNewest[0] ?? null;
383
+ function isEndOfValue(char, delim) {
384
+ return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
779
385
  }
780
- function activeClaims(comments) {
781
- const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
782
- let claims = [];
783
- for (const c of asc) {
784
- if (c.status?.phase === "released")
785
- claims = [];
786
- if (c.claim)
787
- claims.push(c.claim);
386
+ function extractValue(ctx, end) {
387
+ let errPtr = ctx.p;
388
+ let c = ctx.s.charCodeAt(ctx.p);
389
+ if (c === 91 || c === 123) {
390
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
391
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
392
+ ctx.d++;
393
+ return value;
788
394
  }
789
- return claims;
790
- }
791
- var latest = (...xs) => xs.filter((x) => !!x).reduce((a, b) => b > a ? b : a, "");
792
- function inferPhase(pr, comments) {
793
- if (pr?.state === "open")
794
- return pr.ci === "success" && pr.mergeable !== "CONFLICTING" ? "ready-to-merge" : "shipping";
795
- if (comments.some((c) => PLAN_HINT.test(c.excerpt.slice(0, 120))))
796
- return "awaiting-approval";
797
- return "planning";
798
- }
799
- var ENDS_WORK = ["release", "merge"];
800
- var livePhase = (e) => e.kind === "release" ? "released" : LABEL_PHASES.find((p) => p === e.phase) ?? null;
801
- function freshEvent(issueId, opts) {
802
- const e = opts.live?.events[issueId];
803
- return e && opts.live && e.at > opts.live.after ? e : null;
395
+ if (c === 34 || c === 39) {
396
+ return parseString(ctx);
397
+ }
398
+ if (c === 116) {
399
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
400
+ TomlError.x("invalid value", ctx, errPtr);
401
+ return ctx.p++, true;
402
+ }
403
+ if (c === 102) {
404
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
405
+ TomlError.x("invalid value", ctx, errPtr);
406
+ return ctx.p++, false;
407
+ }
408
+ if (c === 43 || c === 45) {
409
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
410
+ }
411
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
412
+ return parseDate(ctx, c, end);
413
+ }
414
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
415
+ return parseTime(ctx, c, end);
416
+ }
417
+ return parseNumber(ctx, ctx.p, c, 0, end);
804
418
  }
805
- function buildLane(m, allComments, issue, opts) {
806
- const comments = commentsFor(allComments, issue.id);
807
- const withStatus = comments.find((c) => c.status && c.status.phase !== "released");
808
- const pr = primaryPr(issue);
809
- const claims = activeClaims(comments);
810
- let phase;
811
- let phaseSource;
812
- if (issue.agentPhase) {
813
- phase = issue.agentPhase;
814
- phaseSource = "label";
815
- } else if (withStatus?.status) {
816
- phase = withStatus.status.phase;
817
- phaseSource = "status-line";
818
- } else {
819
- phase = inferPhase(pr, comments);
820
- phaseSource = "inferred";
419
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
420
+ let c = startChr;
421
+ let state = 0;
422
+ let hasUnderscores = false;
423
+ if (c === 105) {
424
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
425
+ TomlError.x("invalid value", ctx, startPtr);
426
+ return ctx.p++, (sign || 1) / 0;
821
427
  }
822
- const fresh = freshEvent(issue.id, opts);
823
- const freshPhase = fresh ? livePhase(fresh) : null;
824
- const trackerPhase = phase;
825
- if (freshPhase && freshPhase !== "released") {
826
- phase = freshPhase;
827
- phaseSource = "live";
428
+ if (c === 110) {
429
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
430
+ TomlError.x("invalid value", ctx, startPtr);
431
+ return ctx.p++, NaN;
828
432
  }
829
- const shippingPhase = phase === "shipping" || phase === "ready-to-merge";
830
- if (pr?.state === "merged" && !isDone(issue) && (shippingPhase || phaseSource === "status-line" || phaseSource === "inferred"))
831
- phase = "merged";
832
- let announcing;
833
- for (const c of comments) {
834
- if (!c.status || c.status.phase === "released")
835
- continue;
836
- if (c.status.phase !== phase)
837
- break;
838
- announcing = c;
433
+ if (c === 48) {
434
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
435
+ return ctx.bi === true ? 0n : 0;
436
+ if (!sign) {
437
+ if (c === 120)
438
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
439
+ else if (c === 98)
440
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
441
+ else if (c === 111)
442
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
443
+ }
444
+ if (c === 46)
445
+ state = 2;
446
+ else if (c === 101 || c === 69)
447
+ state = 4;
448
+ else
449
+ TomlError.x("illegal leading zero", ctx, startPtr);
450
+ } else if (!isDigit(c))
451
+ TomlError.x("invalid value", ctx, startPtr);
452
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
453
+ if (!state)
454
+ state = 1;
455
+ if (c === 95) {
456
+ if (!(state & 1))
457
+ TomlError.x("illegal underscore", ctx);
458
+ state += 11;
459
+ hasUnderscores = true;
460
+ } else if (state === 1 && c === 46)
461
+ state = 2;
462
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
463
+ state = 4;
464
+ else if (state === 4 && (c === 43 || c === 45)) {} else if (!isDigit(c))
465
+ TomlError.x(`illegal character in numeric literal`, ctx);
466
+ else if (state > 9)
467
+ state -= 11;
468
+ else if (!(state & 1))
469
+ state++;
839
470
  }
840
- const since = (fresh && phaseSource === "live" && phase !== trackerPhase ? fresh.at : undefined) ?? announcing?.createdAt ?? (fresh && phaseSource === "live" ? fresh.at : undefined) ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
841
- const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt, fresh?.at);
842
- const lastReport = latest(comments.find((c) => c.status || c.claim)?.createdAt, claims.at(-1)?.at, opts.lastEvents?.[issue.id], fresh?.at) || null;
843
- const openBlockers = m.openBlockersOf(issue);
844
- const agent = issue.delegate ?? issue.assignee;
845
- const flags = [];
846
- const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
847
- const alive = lastReport ?? lastUpdate;
848
- if (!waitingOnHuman && opts.now - Date.parse(alive) > opts.silentAfterMinutes * MIN)
849
- flags.push("silent");
850
- if (pr?.state === "open" && pr.ci === "failure")
851
- flags.push("ci-failing");
852
- if (pr?.state === "open" && pr.mergeable === "CONFLICTING")
853
- flags.push("conflict");
854
- const runtimes = new Set(claims.map((c) => c.runtime).filter(Boolean));
855
- const claimRuntime = claims[0]?.runtime;
856
- if (claims.length > 1 || runtimes.size > 1 || issue.agentRuntime && claimRuntime && claimRuntime !== issue.agentRuntime)
857
- flags.push("double-claim");
858
- if (openBlockers.length)
859
- flags.push("started-before-blockers");
860
- if (!agent && phaseSource !== "live")
861
- flags.push("no-assignee");
862
- if (!issue.agentPhase && phaseSource !== "live")
863
- flags.push("no-phase-label");
864
- const spec = m.specOf(issue.id);
865
- return {
866
- issue,
867
- spec: spec ? `Spec ${spec.ordinal}` : null,
868
- phase,
869
- phaseSource,
870
- runtime: issue.agentRuntime ?? claimRuntime ?? fresh?.runtime ?? opts.live?.handles?.[issue.id]?.runtime ?? null,
871
- handle: opts.live?.handles?.[issue.id]?.handle ?? claims[0]?.session ?? fresh?.handle ?? null,
872
- claim: claims[0] ?? null,
873
- agent,
874
- since,
875
- lastUpdate,
876
- lastReport,
877
- statusLine: fresh?.message && phaseSource === "live" ? { summary: fresh.message, at: fresh.at, author: null, url: issue.url, plan: false } : withStatus?.status ? {
878
- summary: withStatus.status.summary,
879
- at: withStatus.createdAt,
880
- author: withStatus.author,
881
- url: commentUrl(issue, withStatus),
882
- plan: !!withStatus.status.plan
883
- } : null,
884
- pr,
885
- openBlockers,
886
- flags
887
- };
471
+ if (!state) {
472
+ let val = (startChr - 48) * (sign || 1);
473
+ return ctx.bi === true ? BigInt(val) : val;
474
+ }
475
+ if (!(state & 1))
476
+ TomlError.x("unfinished numeric value", ctx, startPtr);
477
+ let str = ctx.s.slice(startPtr, ctx.p);
478
+ if (hasUnderscores)
479
+ str = str.replaceAll("_", "");
480
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
888
481
  }
889
- function inFlight(m, comments, opts) {
890
- const held = (i) => {
891
- const fresh = freshEvent(i.id, opts);
892
- return fresh ? !ENDS_WORK.includes(fresh.kind) : !!i.agentPhase || isStarted(i);
893
- };
894
- return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && held(i)).map((i) => buildLane(m, comments, i, opts)).sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
482
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
483
+ let c, underscore = 1;
484
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
485
+ if (c === 95) {
486
+ if (underscore & 1)
487
+ TomlError.x("illegal underscore", ctx);
488
+ underscore = 3;
489
+ } else if (!isDigit(c, base))
490
+ TomlError.x(`illegal character in numeric literal`, ctx);
491
+ else if (underscore & 1)
492
+ underscore--;
493
+ }
494
+ if (underscore & 1)
495
+ TomlError.x("unfinished numeric value", ctx);
496
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
497
+ if (underscore)
498
+ str = str.replaceAll("_", "");
499
+ return parseInteger(ctx, str, base, startPtr);
895
500
  }
896
- function frontier(m, readyLabel) {
897
- const dependents = new Map;
898
- for (const i of m.program)
899
- for (const b of i.blockedBy)
900
- dependents.set(b.id, [...dependents.get(b.id) ?? [], i]);
901
- const transitive = (id, seen = new Set) => {
902
- for (const d of dependents.get(id) ?? [])
903
- if (!seen.has(d.id) && !isClosed(d)) {
904
- seen.add(d.id);
905
- transitive(d.id, seen);
501
+ function parseInteger(ctx, str, base, startPtr) {
502
+ if (ctx.bi !== true)
503
+ int: {
504
+ let val = parseInt(str, base);
505
+ if (!Number.isSafeInteger(val)) {
506
+ if (ctx.bi)
507
+ break int;
508
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
906
509
  }
907
- return seen;
908
- };
909
- const critical = criticalIds(m);
910
- return m.program.filter((i) => m.isLeaf(i) && isNotStarted(i) && !i.agentPhase && m.openBlockersOf(i).length === 0 && !i.prs.some((p) => p.state === "open")).map((issue) => {
911
- const spec = m.specOf(issue.id);
912
- const unlocksAll = [...transitive(issue.id)];
913
- const unlocksNow = (dependents.get(issue.id) ?? []).filter((d) => !isClosed(d) && m.openBlockersOf(d).every((b) => b === issue.id)).map((d) => d.id);
914
- const readyForAgent = issue.labels.includes(readyLabel) && issue.statusType !== "triage";
915
- const onCriticalPath = critical.has(issue.id);
916
- const score = (readyForAgent ? 1000 : 0) + (onCriticalPath ? 300 : 0) + unlocksAll.length * 20 + unlocksNow.length * 10 - (spec?.ordinal ?? 99);
917
- return {
918
- issue,
919
- spec: spec ? `Spec ${spec.ordinal}` : null,
920
- readyForAgent,
921
- onCriticalPath,
922
- unlocksAll,
923
- unlocksNow,
924
- score
925
- };
926
- }).sort((a, b) => b.score - a.score || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
510
+ return val;
511
+ }
512
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
927
513
  }
928
- function waitingPullRequests(m, prs) {
929
- const ticketOf = new Map;
930
- for (const i of m.program)
931
- for (const p of i.prs)
932
- ticketOf.set(p.url, i);
933
- return prs.filter((p) => p.state === "open").map((pr) => ({ pr, ticket: ticketOf.get(pr.url) ?? null })).sort((a, b) => a.pr.number - b.pr.number);
514
+ function parseDate(ctx, c, endChr) {
515
+ let startPtr = ctx.p++, unsafeSeparator;
516
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
517
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
518
+ }
519
+ ctx.p += 5;
520
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
521
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
522
+ if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
523
+ let t = ctx.s.slice(startPtr, ctx.p);
524
+ return readDate(ctx, t, 3, false, startPtr);
525
+ }
526
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
527
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
528
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
529
+ ctx.p += 3;
530
+ if (ctx.s.charCodeAt(ctx.p) === 46)
531
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
532
+ ;
533
+ if (c = ctx.s.charCodeAt(ctx.p)) {
534
+ if (c === 90 || c === 122) {
535
+ let t = ctx.s.slice(startPtr, ++ctx.p);
536
+ return readDate(ctx, t, 1, unsafeSeparator, startPtr, "[+00:00]");
537
+ }
538
+ if (c === 43 || c === 45) {
539
+ let t = ctx.s.slice(startPtr, ctx.p += 6);
540
+ return readDate(ctx, t, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
541
+ }
542
+ }
543
+ let t = ctx.s.slice(startPtr, ctx.p);
544
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
545
+ }
546
+ function parseTime(ctx, c, endChr) {
547
+ let start = ctx.p;
548
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
549
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
550
+ }
551
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
552
+ ctx.p += 3;
553
+ if (ctx.s.charCodeAt(ctx.p) === 46)
554
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
555
+ ;
556
+ let t = ctx.s.slice(start, ctx.p);
557
+ return readDate(ctx, t, 4, false, start);
558
+ }
559
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
560
+ if (ctx.ld) {
561
+ let date = new TomlDate(str, type, unsafeDelim);
562
+ if (!date.isValid())
563
+ TomlError.x("invalid date", ctx, errPtr);
564
+ return date;
565
+ }
566
+ try {
567
+ if (temporalSuffix)
568
+ str += temporalSuffix;
569
+ switch (type) {
570
+ case 1:
571
+ return Temporal.ZonedDateTime.from(str);
572
+ case 2:
573
+ return Temporal.PlainDateTime.from(str);
574
+ case 3:
575
+ return Temporal.PlainDate.from(str);
576
+ case 4:
577
+ return Temporal.PlainTime.from(str);
578
+ }
579
+ } catch (e) {
580
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
581
+ }
934
582
  }
935
583
 
936
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
584
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/util.js
937
585
  /*!
938
586
  * Copyright (c) Squirrel Chat et al., All rights reserved.
939
587
  * SPDX-License-Identifier: BSD-3-Clause
@@ -961,52 +609,32 @@ function waitingPullRequests(m, prs) {
961
609
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
962
610
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
963
611
  */
964
- function getLineColFromPtr(string, ptr) {
965
- let lines = string.slice(0, ptr).split(/\r?\n/);
966
- return [lines.length, lines.pop().length + 1];
967
- }
968
- function makeCodeBlock(string, line, column) {
969
- let lines = string.split(/\r?\n/);
970
- let codeblock = "";
971
- let numberLen = (Math.log10(line + 1) | 0) + 1;
972
- for (let i = line - 1;i <= line + 1; i++) {
973
- let l = lines[i - 1];
974
- if (!l)
975
- continue;
976
- codeblock += i.toString().padEnd(numberLen, " ");
977
- codeblock += ": ";
978
- codeblock += l;
979
- codeblock += `
980
- `;
981
- if (i === line) {
982
- codeblock += " ".repeat(numberLen + column + 2);
983
- codeblock += `^
984
- `;
612
+ function skipComment(ctx) {
613
+ for (;ctx.p < ctx.s.length; ctx.p++) {
614
+ let c = ctx.s.charCodeAt(ctx.p);
615
+ if (c === 10)
616
+ break;
617
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
618
+ ctx.p++;
619
+ break;
620
+ }
621
+ if (c < 32 && c !== 9 || c === 127) {
622
+ TomlError.x("control characters are not allowed in comments", ctx);
985
623
  }
986
624
  }
987
- return codeblock;
988
625
  }
989
-
990
- class TomlError extends Error {
991
- line;
992
- column;
993
- codeblock;
994
- constructor(message, options) {
995
- const [line, column] = getLineColFromPtr(options.toml, options.ptr);
996
- const codeblock = makeCodeBlock(options.toml, line, column);
997
- super(`Invalid TOML document: ${message}
998
-
999
- ${codeblock}`, options);
1000
- this.line = line;
1001
- this.column = column;
1002
- this.codeblock = codeblock;
1003
- }
1004
- static x(message, ctx, ptr) {
1005
- throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
626
+ function skipVoid(ctx, banNewLines, banComments) {
627
+ let c;
628
+ while (ctx.p < ctx.s.length) {
629
+ while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
630
+ ctx.p++;
631
+ if (banComments || c !== 35)
632
+ break;
633
+ skipComment(ctx);
1006
634
  }
1007
635
  }
1008
636
 
1009
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/primitive.js
637
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/struct.js
1010
638
  /*!
1011
639
  * Copyright (c) Squirrel Chat et al., All rights reserved.
1012
640
  * SPDX-License-Identifier: BSD-3-Clause
@@ -1034,99 +662,115 @@ ${codeblock}`, options);
1034
662
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1035
663
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1036
664
  */
1037
- function parseString(ctx) {
1038
- let startPtr = ctx.p;
1039
- let c = ctx.s.charCodeAt(ctx.p++);
1040
- let first = c;
1041
- let isLiteral = c === 39;
1042
- let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
1043
- if (isMultiline) {
1044
- if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
1045
- ctx.p++;
1046
- else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
1047
- ctx.p += 2;
1048
- }
1049
- let parsed = "";
1050
- let sliceStart = ctx.p;
665
+ function parseKey(ctx, end = 61) {
666
+ let startPtr;
1051
667
  let state = 0;
1052
- for (;ctx.p < ctx.s.length; ctx.p++) {
1053
- c = ctx.s.charCodeAt(ctx.p);
1054
- if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
1055
- state = state && 3;
1056
- } else if (c < 32 && c !== 9 || c === 127) {
1057
- TomlError.x("control characters are not allowed in strings", ctx);
1058
- } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
1059
- if (isMultiline) {
1060
- if (ctx.s.charCodeAt(ctx.p + 3) === first)
1061
- ctx.p++;
1062
- if (ctx.s.charCodeAt(ctx.p + 3) === first)
1063
- ctx.p++;
1064
- }
1065
- if (!state) {
1066
- let s = ctx.s.slice(sliceStart, ctx.p);
1067
- parsed = parsed ? parsed + s : s;
1068
- }
1069
- ctx.p += isMultiline ? 3 : 1;
1070
- return parsed;
1071
- } else if (!state) {
1072
- if (!isLiteral && c === 92) {
1073
- parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
1074
- state = 1;
1075
- }
1076
- } else if (state === 1) {
1077
- if (c === 120 || c === 117 || c === 85) {
1078
- let errPtr = ctx.p++ - 1;
1079
- let value = 0;
1080
- let len = c === 120 ? 2 : c === 117 ? 4 : 8;
1081
- for (let j = 0;j < len; j++, ctx.p++) {
1082
- let hex = ctx.s.charCodeAt(ctx.p);
1083
- let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
1084
- if (digit < 0)
1085
- TomlError.x("invalid non-hex character in unicode escape", ctx);
1086
- value = value << 4 | digit;
1087
- }
1088
- if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
1089
- TomlError.x("invalid unicode escape", ctx, errPtr);
1090
- }
1091
- parsed += String.fromCodePoint(value);
1092
- sliceStart = ctx.p--;
1093
- state = 0;
1094
- } else if (isMultiline && (c === 32 || c === 9)) {
1095
- state = 2;
1096
- } else {
1097
- if (c === 98)
1098
- parsed += "\b";
1099
- else if (c === 116)
1100
- parsed += "\t";
1101
- else if (c === 110)
1102
- parsed += `
1103
- `;
1104
- else if (c === 102)
1105
- parsed += "\f";
1106
- else if (c === 114)
1107
- parsed += "\r";
1108
- else if (c === 101)
1109
- parsed += "\x1B";
1110
- else if (c === 34)
1111
- parsed += '"';
1112
- else if (c === 92)
1113
- parsed += "\\";
1114
- else
1115
- TomlError.x("unrecognised escape sequence", ctx);
1116
- sliceStart = ctx.p + 1;
1117
- state = 0;
668
+ let parsed = [];
669
+ let sliceStart;
670
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
671
+ do {
672
+ if (c === end) {
673
+ if (!state)
674
+ TomlError.x("unexpected end of key", ctx);
675
+ if (state === 1)
676
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
677
+ return ctx.p++, parsed;
678
+ } else if (c === 46) {
679
+ if (!state)
680
+ TomlError.x("illegal empty bare key", ctx);
681
+ if (state === 1)
682
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
683
+ state = 0;
684
+ } else if (!state && (c === 34 || c === 39)) {
685
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
686
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
687
+ parsed.push(parseString(ctx));
688
+ state = 2;
689
+ ctx.p--;
690
+ } else if (c === 32 || c === 9) {
691
+ if (state === 1) {
692
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
693
+ state = 2;
1118
694
  }
1119
- } else if (c !== 32 && c !== 9) {
1120
- if (state === 2)
1121
- TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
1122
- state = !isLiteral && c === 92 ? 1 : 0;
695
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
696
+ TomlError.x("illegal character in key", ctx);
697
+ } else if (!state) {
698
+ state = 1;
1123
699
  sliceStart = ctx.p;
1124
700
  }
701
+ } while (c = ctx.s.charCodeAt(++ctx.p));
702
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
703
+ }
704
+ function parseInlineTable(ctx) {
705
+ let startPtr = ctx.p++;
706
+ let res = Object.create(null);
707
+ let seen = new Set;
708
+ let c;
709
+ while (ctx.p < ctx.s.length) {
710
+ skipVoid(ctx);
711
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
712
+ ctx.p++;
713
+ return res;
714
+ }
715
+ let k;
716
+ let t = res;
717
+ let hasOwn = false;
718
+ let errPtr = ctx.p;
719
+ let key = parseKey(ctx);
720
+ for (let i = 0;i < key.length; i++) {
721
+ if (i)
722
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
723
+ k = key[i];
724
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
725
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
726
+ }
727
+ let unsafe = k === "__proto__";
728
+ if (ctx.uk && (unsafe || k === "constructor")) {
729
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
730
+ break;
731
+ }
732
+ if (!hasOwn && unsafe) {
733
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
734
+ }
735
+ }
736
+ if (hasOwn) {
737
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
738
+ }
739
+ skipVoid(ctx, true, true);
740
+ let value = extractValue(ctx, 125);
741
+ if (t && typeof (t[k] = value) === "object")
742
+ seen.add(value);
743
+ skipVoid(ctx);
744
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
745
+ return res;
746
+ }
747
+ if (c !== 44)
748
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
1125
749
  }
1126
- TomlError.x("unfinished string", ctx, startPtr);
750
+ TomlError.x("unfinished table", ctx, startPtr);
751
+ }
752
+ function parseArray(ctx) {
753
+ let startPtr = ctx.p++;
754
+ let res = [];
755
+ let c;
756
+ while (ctx.p < ctx.s.length) {
757
+ skipVoid(ctx);
758
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
759
+ ctx.p++;
760
+ return res;
761
+ }
762
+ res.push(extractValue(ctx, 93));
763
+ skipVoid(ctx);
764
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
765
+ return res;
766
+ }
767
+ if (c !== 44)
768
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
769
+ }
770
+ TomlError.x("unfinished array", ctx, startPtr);
1127
771
  }
1128
772
 
1129
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/date.js
773
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/parse.js
1130
774
  /*!
1131
775
  * Copyright (c) Squirrel Chat et al., All rights reserved.
1132
776
  * SPDX-License-Identifier: BSD-3-Clause
@@ -1154,122 +798,131 @@ function parseString(ctx) {
1154
798
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1155
799
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1156
800
  */
1157
- var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
1158
-
1159
- class TomlDate extends Date {
1160
- #hasDate = false;
1161
- #hasTime = false;
1162
- #offset = null;
1163
- constructor(date, fasttype, unsafeDelim) {
1164
- let hasDate = true;
1165
- let hasTime = true;
1166
- let offset = "Z";
1167
- let c;
1168
- if (typeof date === "string") {
1169
- if (fasttype)
1170
- prep: {
1171
- if (fasttype < 3) {
1172
- if (+date.slice(11, 13) > 23) {
1173
- date = "";
1174
- break prep;
1175
- }
1176
- if (fasttype === 2) {
1177
- offset = null;
1178
- date += "Z";
1179
- } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
1180
- offset = date.slice(date.length - 6);
1181
- }
1182
- if (unsafeDelim)
1183
- date = date.slice(0, 10) + "T" + date.slice(11);
1184
- } else if (fasttype === 4) {
1185
- date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
1186
- }
1187
- hasDate = fasttype !== 4;
1188
- hasTime = fasttype !== 3;
1189
- }
1190
- else {
1191
- let match = date.match(DATE_TIME_RE);
1192
- if (match) {
1193
- if (!match[1]) {
1194
- hasDate = false;
1195
- date = `0000-01-01T${date}`;
1196
- }
1197
- hasTime = !!match[2];
1198
- hasTime && date[10] === " " && (date = date.replace(" ", "T"));
1199
- if (match[2] && +match[2] > 23) {
1200
- date = "";
1201
- } else {
1202
- offset = match[3] || null;
1203
- if (!offset && hasTime)
1204
- date += "Z";
1205
- }
1206
- } else {
1207
- date = "";
1208
- }
801
+ function peekTable(ctx, key, table, meta, type) {
802
+ let t = table;
803
+ let m = meta;
804
+ let k;
805
+ let hasOwn = false;
806
+ let state;
807
+ for (let i = 0;i < key.length; i++) {
808
+ if (i) {
809
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
810
+ m = (state = m[k]).c;
811
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
812
+ return null;
813
+ }
814
+ if (state.t === 2) {
815
+ let l = t.length - 1;
816
+ t = t[l];
817
+ m = m[l].c;
1209
818
  }
1210
819
  }
1211
- super(date);
1212
- if (!isNaN(this.getTime())) {
1213
- this.#hasDate = hasDate;
1214
- this.#hasTime = hasTime;
1215
- this.#offset = offset;
820
+ k = key[i];
821
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
822
+ return null;
823
+ }
824
+ if (!hasOwn) {
825
+ let unsafe = k === "__proto__";
826
+ if (ctx.uk && (unsafe || k === "constructor"))
827
+ return false;
828
+ if (unsafe) {
829
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
830
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
831
+ }
832
+ m[k] = {
833
+ t: i < key.length - 1 && type === 2 ? 3 : type,
834
+ d: false,
835
+ i: 0,
836
+ c: Object.create(null)
837
+ };
1216
838
  }
1217
839
  }
1218
- isDateTime() {
1219
- return this.#hasDate && this.#hasTime;
1220
- }
1221
- isLocal() {
1222
- return !this.#hasDate || !this.#hasTime || !this.#offset;
1223
- }
1224
- isDate() {
1225
- return this.#hasDate && !this.#hasTime;
1226
- }
1227
- isTime() {
1228
- return this.#hasTime && !this.#hasDate;
1229
- }
1230
- isValid() {
1231
- return this.#hasDate || this.#hasTime;
1232
- }
1233
- toISOString() {
1234
- let iso = super.toISOString();
1235
- if (this.isDate())
1236
- return iso.slice(0, 10);
1237
- if (this.isTime())
1238
- return iso.slice(11, 23);
1239
- if (this.#offset === null)
1240
- return iso.slice(0, -1);
1241
- if (this.#offset === "Z" || this.#offset === "z")
1242
- return iso;
1243
- let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
1244
- offset = this.#offset[0] === "-" ? offset : -offset;
1245
- let offsetDate = new Date(this.getTime() - offset * 60000);
1246
- return offsetDate.toISOString().slice(0, -1) + this.#offset;
840
+ state = m[k];
841
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
842
+ return null;
1247
843
  }
1248
- static wrapAsOffsetDateTime(jsDate, offset = "Z") {
1249
- let date = new TomlDate(jsDate);
1250
- date.#offset = offset;
1251
- return date;
844
+ if (type === 2) {
845
+ if (!state.d) {
846
+ state.d = true;
847
+ t[k] = [];
848
+ }
849
+ t[k].push(t = Object.create(null));
850
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: Object.create(null) };
1252
851
  }
1253
- static wrapAsLocalDateTime(jsDate) {
1254
- let date = new TomlDate(jsDate);
1255
- date.#offset = null;
1256
- return date;
852
+ if (state.d) {
853
+ return null;
1257
854
  }
1258
- static wrapAsLocalDate(jsDate) {
1259
- let date = new TomlDate(jsDate);
1260
- date.#hasTime = false;
1261
- date.#offset = null;
1262
- return date;
855
+ state.d = true;
856
+ if (type === 1) {
857
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
858
+ } else if (type === 0 && hasOwn) {
859
+ return null;
1263
860
  }
1264
- static wrapAsLocalTime(jsDate) {
1265
- let date = new TomlDate(jsDate);
1266
- date.#hasDate = false;
1267
- date.#offset = null;
1268
- return date;
861
+ return [k, t, state.c];
862
+ }
863
+ function validateTablePeek(ctx, peek, ptr) {
864
+ if (peek === null || ctx.uk === 2)
865
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
866
+ }
867
+ function parse(toml, options = {}) {
868
+ let ctx = {
869
+ s: toml,
870
+ p: 0,
871
+ d: options.maxDepth ?? 1000,
872
+ bi: options.integersAsBigInt ?? false,
873
+ ld: options.useLegacyDate ?? true,
874
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
875
+ };
876
+ let res = Object.create(null);
877
+ let meta = Object.create(null);
878
+ let tmp;
879
+ let skipping = false;
880
+ let tbl = res;
881
+ let m = meta;
882
+ if (toml.charCodeAt(0) === 65279)
883
+ ctx.p++;
884
+ skipVoid(ctx);
885
+ while (ctx.p < toml.length) {
886
+ if (toml.charCodeAt(ctx.p) === 91) {
887
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
888
+ tmp = ctx.p += +isTableArray;
889
+ skipping = false;
890
+ let k = parseKey(ctx, 93);
891
+ if (isTableArray) {
892
+ if (toml.charCodeAt(ctx.p) !== 93) {
893
+ TomlError.x("expected end of table array declaration", ctx);
894
+ }
895
+ ctx.p++;
896
+ }
897
+ let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
898
+ if (!p) {
899
+ validateTablePeek(ctx, p, tmp);
900
+ skipping = true;
901
+ } else {
902
+ m = p[2];
903
+ tbl = p[1];
904
+ }
905
+ } else {
906
+ tmp = ctx.p;
907
+ let k = parseKey(ctx);
908
+ let p = peekTable(ctx, k, tbl, m, 0);
909
+ if (!p && !skipping)
910
+ validateTablePeek(ctx, p, tmp);
911
+ skipVoid(ctx, true, true);
912
+ let v = extractValue(ctx, undefined);
913
+ if (p && !skipping)
914
+ p[1][p[0]] = v;
915
+ }
916
+ skipVoid(ctx, true);
917
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
918
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
919
+ }
920
+ skipVoid(ctx);
1269
921
  }
922
+ return res;
1270
923
  }
1271
924
 
1272
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/extract.js
925
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/stringify.js
1273
926
  /*!
1274
927
  * Copyright (c) Squirrel Chat et al., All rights reserved.
1275
928
  * SPDX-License-Identifier: BSD-3-Clause
@@ -1297,1004 +950,1370 @@ class TomlDate extends Date {
1297
950
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1298
951
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1299
952
  */
1300
- function isDigit(char, base = 10) {
1301
- return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
953
+ var HAS_WELLFORMED = !!"".isWellFormed;
954
+
955
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js
956
+ /*!
957
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
958
+ * SPDX-License-Identifier: BSD-3-Clause
959
+ *
960
+ * Redistribution and use in source and binary forms, with or without
961
+ * modification, are permitted provided that the following conditions are met:
962
+ *
963
+ * 1. Redistributions of source code must retain the above copyright notice, this
964
+ * list of conditions and the following disclaimer.
965
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
966
+ * this list of conditions and the following disclaimer in the
967
+ * documentation and/or other materials provided with the distribution.
968
+ * 3. Neither the name of the copyright holder nor the names of its contributors
969
+ * may be used to endorse or promote products derived from this software without
970
+ * specific prior written permission.
971
+ *
972
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
973
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
974
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
975
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
976
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
977
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
978
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
979
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
980
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
981
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
982
+ */
983
+
984
+ // ../core/src/config.ts
985
+ var CONFIG_FILE = "armada.toml";
986
+ var PLAN_POLICIES = ["approve", "pre-approved"];
987
+ var routingLabelKey = (name) => name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]/gu, "");
988
+ var PROFILE_RUNTIMES = ["conductor", "claude-code"];
989
+ var CONFIG_DEFAULTS = {
990
+ language: "en",
991
+ readyLabel: "ready-for-agent",
992
+ phaseGroup: "Agent phase",
993
+ runtimeGroup: "Agent runtime",
994
+ runtimes: ["Claude Code", "Codex", "Conductor"],
995
+ silentAfterMinutes: 15,
996
+ coordinatorMinutes: 10,
997
+ notStartedMinutes: 10,
998
+ plans: "approve",
999
+ preApprovedLabel: "plan-approved",
1000
+ approvalLabel: "needs-plan-approval"
1001
+ };
1002
+
1003
+ class ConfigError extends Error {
1004
+ source;
1005
+ problems;
1006
+ constructor(source, problems) {
1007
+ super(`${source} is invalid:
1008
+ ${problems.map((p) => ` - ${p}`).join(`
1009
+ `)}`);
1010
+ this.source = source;
1011
+ this.problems = problems;
1012
+ this.name = "ConfigError";
1013
+ }
1302
1014
  }
1303
- function isEndOfValue(char, delim) {
1304
- return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
1015
+ var SLUG = /^[a-z0-9][a-z0-9-]*$/;
1016
+ var ISSUE_ID = /^[A-Za-z][A-Za-z0-9]*-\d+$/;
1017
+ var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
1018
+ var RESERVED_SECRET_NAMES = ["LINEAR_API_KEY", "GITHUB_TOKEN", "GH_TOKEN"];
1019
+ function secretNameRefusal(name) {
1020
+ if (!SECRET_NAME.test(name))
1021
+ return "a secret name is in upper snake case, e.g. OPENAI_API_KEY";
1022
+ if (RESERVED_SECRET_NAMES.includes(name) || name.startsWith("ARMADA_"))
1023
+ return `${name} is a key Armada itself uses: it is set on the Keys page as such, not as a secret for workers`;
1024
+ return null;
1305
1025
  }
1306
- function extractValue(ctx, end) {
1307
- let errPtr = ctx.p;
1308
- let c = ctx.s.charCodeAt(ctx.p);
1309
- if (c === 91 || c === 123) {
1310
- ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
1311
- let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
1312
- ctx.d++;
1313
- return value;
1314
- }
1315
- if (c === 34 || c === 39) {
1316
- return parseString(ctx);
1317
- }
1318
- if (c === 116) {
1319
- if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
1320
- TomlError.x("invalid value", ctx, errPtr);
1321
- return ctx.p++, true;
1322
- }
1323
- if (c === 102) {
1324
- if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
1325
- TomlError.x("invalid value", ctx, errPtr);
1326
- return ctx.p++, false;
1327
- }
1328
- if (c === 43 || c === 45) {
1329
- return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
1330
- }
1331
- if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
1332
- return parseDate(ctx, c, end);
1333
- }
1334
- if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
1335
- return parseTime(ctx, c, end);
1026
+ var REPOSITORY = /^[\w.-]+\/[\w.-]+$/;
1027
+ var isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1028
+ function parseConfig(text, source = CONFIG_FILE) {
1029
+ let raw;
1030
+ try {
1031
+ raw = parse(text);
1032
+ } catch (err) {
1033
+ const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
1034
+ throw new ConfigError(source, [`not valid TOML${where}`]);
1336
1035
  }
1337
- return parseNumber(ctx, ctx.p, c, 0, end);
1338
- }
1339
- function parseNumber(ctx, startPtr, startChr, sign, endChr) {
1340
- let c = startChr;
1341
- let state = 0;
1342
- let hasUnderscores = false;
1343
- if (c === 105) {
1344
- if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
1345
- TomlError.x("invalid value", ctx, startPtr);
1346
- return ctx.p++, (sign || 1) / 0;
1036
+ const problems = [];
1037
+ const table = (key) => {
1038
+ const v = raw[key];
1039
+ if (v === undefined) {
1040
+ problems.push(`missing required table [${key}]`);
1041
+ return {};
1042
+ }
1043
+ if (!isTable(v)) {
1044
+ problems.push(`"${key}" must be a table`);
1045
+ return {};
1046
+ }
1047
+ return v;
1048
+ };
1049
+ const str = (t, path, key, opts = {}) => {
1050
+ const v = t[key];
1051
+ const dotted = `${path}.${key}`;
1052
+ if (v === undefined) {
1053
+ if (opts.default !== undefined)
1054
+ return opts.default;
1055
+ problems.push(`missing required key "${dotted}"`);
1056
+ return "";
1057
+ }
1058
+ if (typeof v !== "string" || !v.trim()) {
1059
+ problems.push(`"${dotted}" must be a non-empty string`);
1060
+ return "";
1061
+ }
1062
+ if (opts.pattern && !opts.pattern.test(v)) {
1063
+ problems.push(`"${dotted}" is "${v}", expected ${opts.hint}`);
1064
+ return "";
1065
+ }
1066
+ return v.trim();
1067
+ };
1068
+ const project = table("project");
1069
+ const tracker = table("tracker");
1070
+ const github = table("github");
1071
+ const labels = tracker.labels === undefined ? {} : tracker.labels;
1072
+ if (!isTable(labels))
1073
+ problems.push(`"tracker.labels" must be a table`);
1074
+ const policy = raw.policy === undefined ? {} : raw.policy;
1075
+ if (!isTable(policy))
1076
+ problems.push(`"policy" must be a table`);
1077
+ const labelsT = isTable(labels) ? labels : {};
1078
+ const policyT = isTable(policy) ? policy : {};
1079
+ const gates = raw.gates === undefined ? {} : raw.gates;
1080
+ if (!isTable(gates))
1081
+ problems.push(`"gates" must be a table`);
1082
+ const gatesT = isTable(gates) ? gates : {};
1083
+ const brief = raw.brief === undefined ? {} : raw.brief;
1084
+ if (!isTable(brief))
1085
+ problems.push(`"brief" must be a table`);
1086
+ const briefT = isTable(brief) ? brief : {};
1087
+ const secrets = raw.secrets === undefined ? {} : raw.secrets;
1088
+ if (!isTable(secrets))
1089
+ problems.push(`"secrets" must be a table`);
1090
+ const secretsT = isTable(secrets) ? secrets : {};
1091
+ const conductor = raw.conductor === undefined ? {} : raw.conductor;
1092
+ if (!isTable(conductor))
1093
+ problems.push(`"conductor" must be a table`);
1094
+ const conductorT = isTable(conductor) ? conductor : {};
1095
+ const profilesRaw = conductorT.profiles === undefined ? {} : conductorT.profiles;
1096
+ if (!isTable(profilesRaw))
1097
+ problems.push(`"conductor.profiles" must be a table of profiles`);
1098
+ const profilesT = isTable(profilesRaw) ? profilesRaw : {};
1099
+ const known = [
1100
+ ["project", project, ["name", "slug"]],
1101
+ ["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
1102
+ ["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
1103
+ ["github", github, ["repository"]],
1104
+ ["gates", gatesT, ["required_checks", "local_commands"]],
1105
+ [
1106
+ "policy",
1107
+ policyT,
1108
+ [
1109
+ "silence_minutes",
1110
+ "silent_after_minutes",
1111
+ "coordinator_minutes",
1112
+ "not_started_minutes",
1113
+ "plans",
1114
+ "pre_approved_label",
1115
+ "approval_label"
1116
+ ]
1117
+ ],
1118
+ ["brief", briefT, ["extra"]],
1119
+ ["secrets", secretsT, ["names"]],
1120
+ ["conductor", conductorT, ["default_profile", "profiles", "routing"]]
1121
+ ];
1122
+ const profiles = {};
1123
+ for (const [name, p] of Object.entries(profilesT)) {
1124
+ const path = `conductor.profiles.${name}`;
1125
+ if (!isTable(p)) {
1126
+ problems.push(`"${path}" must be a table`);
1127
+ continue;
1128
+ }
1129
+ if (name === "__proto__") {
1130
+ problems.push(`"${path}" is not a usable profile name`);
1131
+ continue;
1132
+ }
1133
+ known.push([path, p, ["runtime", "agent", "model", "effort", "fast_mode"]]);
1134
+ if (p.fast_mode !== undefined && typeof p.fast_mode !== "boolean")
1135
+ problems.push(`"${path}.fast_mode" must be true or false`);
1136
+ const runtime = p.runtime ?? "conductor";
1137
+ if (!PROFILE_RUNTIMES.includes(runtime))
1138
+ problems.push(`"${path}.runtime" must be one of ${PROFILE_RUNTIMES.map((r) => `"${r}"`).join(", ")}`);
1139
+ if (runtime === "claude-code" && p.agent !== undefined && p.agent !== "claude")
1140
+ problems.push(`"${path}.agent" must be "claude" with runtime = "claude-code"`);
1141
+ profiles[name] = {
1142
+ runtime: PROFILE_RUNTIMES.includes(runtime) ? runtime : "conductor",
1143
+ agent: str(p, path, "agent"),
1144
+ model: str(p, path, "model"),
1145
+ effort: str(p, path, "effort"),
1146
+ fastMode: p.fast_mode === true
1147
+ };
1347
1148
  }
1348
- if (c === 110) {
1349
- if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
1350
- TomlError.x("invalid value", ctx, startPtr);
1351
- return ctx.p++, NaN;
1149
+ let defaultProfile = null;
1150
+ if (conductorT.default_profile !== undefined) {
1151
+ defaultProfile = str(conductorT, "conductor", "default_profile") || null;
1152
+ if (defaultProfile && !Object.hasOwn(profiles, defaultProfile))
1153
+ problems.push(`"conductor.default_profile" is "${defaultProfile}", but there is no [conductor.profiles.${defaultProfile}]`);
1352
1154
  }
1353
- if (c === 48) {
1354
- if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
1355
- return ctx.bi === true ? 0n : 0;
1356
- if (!sign) {
1357
- if (c === 120)
1358
- return parseIntegerBaseN(ctx, startPtr, 16, endChr);
1359
- else if (c === 98)
1360
- return parseIntegerBaseN(ctx, startPtr, 2, endChr);
1361
- else if (c === 111)
1362
- return parseIntegerBaseN(ctx, startPtr, 8, endChr);
1155
+ const routing = [];
1156
+ const routingRaw = conductorT.routing ?? [];
1157
+ if (!Array.isArray(routingRaw))
1158
+ problems.push(`"conductor.routing" must be a list of [[conductor.routing]] rules`);
1159
+ else
1160
+ for (const [i, r] of routingRaw.entries()) {
1161
+ const path = `conductor.routing[${i + 1}]`;
1162
+ if (!isTable(r)) {
1163
+ problems.push(`"${path}" must be a table`);
1164
+ continue;
1165
+ }
1166
+ known.push([path, r, ["labels", "profile"]]);
1167
+ const labels = r.labels;
1168
+ const ok = Array.isArray(labels) && labels.length && labels.every((l) => typeof l === "string" && routingLabelKey(l));
1169
+ if (!ok)
1170
+ problems.push(`"${path}.labels" must be a non-empty list of Linear label names, each with a letter or digit`);
1171
+ const profile = str(r, path, "profile");
1172
+ if (profile && !Object.hasOwn(profiles, profile))
1173
+ problems.push(`"${path}.profile" is "${profile}", but there is no [conductor.profiles.${profile}]`);
1174
+ if (ok && profile)
1175
+ routing.push({ labels: labels.map((l) => l.trim()), profile });
1363
1176
  }
1364
- if (c === 46)
1365
- state = 2;
1366
- else if (c === 101 || c === 69)
1367
- state = 4;
1177
+ if (Array.isArray(routingRaw) && routingRaw.length && conductorT.default_profile === undefined)
1178
+ problems.push(`"conductor.default_profile" is required with [[conductor.routing]], for tickets no rule matches`);
1179
+ for (const [path, t, keys] of known)
1180
+ for (const key of Object.keys(t))
1181
+ if (!keys.includes(key))
1182
+ problems.push(`unknown key "${path}.${key}"`);
1183
+ let runtimes = [...CONFIG_DEFAULTS.runtimes];
1184
+ if (labelsT.runtimes !== undefined) {
1185
+ const v = labelsT.runtimes;
1186
+ if (Array.isArray(v) && v.length && v.every((x) => typeof x === "string" && x.trim()))
1187
+ runtimes = [...new Set(v.map((x) => x.trim()))];
1368
1188
  else
1369
- TomlError.x("illegal leading zero", ctx, startPtr);
1370
- } else if (!isDigit(c))
1371
- TomlError.x("invalid value", ctx, startPtr);
1372
- while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
1373
- if (!state)
1374
- state = 1;
1375
- if (c === 95) {
1376
- if (!(state & 1))
1377
- TomlError.x("illegal underscore", ctx);
1378
- state += 11;
1379
- hasUnderscores = true;
1380
- } else if (state === 1 && c === 46)
1381
- state = 2;
1382
- else if ((state === 1 || state === 3) && (c === 101 || c === 69))
1383
- state = 4;
1384
- else if (state === 4 && (c === 43 || c === 45)) {} else if (!isDigit(c))
1385
- TomlError.x(`illegal character in numeric literal`, ctx);
1386
- else if (state > 9)
1387
- state -= 11;
1388
- else if (!(state & 1))
1389
- state++;
1189
+ problems.push(`"tracker.labels.runtimes" must be a non-empty list of names`);
1390
1190
  }
1391
- if (!state) {
1392
- let val = (startChr - 48) * (sign || 1);
1393
- return ctx.bi === true ? BigInt(val) : val;
1191
+ const silenceKey = policyT.silence_minutes !== undefined ? "silence_minutes" : "silent_after_minutes";
1192
+ if (policyT.silence_minutes !== undefined && policyT.silent_after_minutes !== undefined)
1193
+ problems.push(`"policy.silent_after_minutes" is the old name of "policy.silence_minutes"; keep only one`);
1194
+ let silentAfterMinutes = CONFIG_DEFAULTS.silentAfterMinutes;
1195
+ if (policyT[silenceKey] !== undefined) {
1196
+ const v = policyT[silenceKey];
1197
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
1198
+ silentAfterMinutes = v;
1199
+ else
1200
+ problems.push(`"policy.${silenceKey}" must be a positive number`);
1394
1201
  }
1395
- if (!(state & 1))
1396
- TomlError.x("unfinished numeric value", ctx, startPtr);
1397
- let str = ctx.s.slice(startPtr, ctx.p);
1398
- if (hasUnderscores)
1399
- str = str.replaceAll("_", "");
1400
- return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
1401
- }
1402
- function parseIntegerBaseN(ctx, startPtr, base, endChr) {
1403
- let c, underscore = 1;
1404
- while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
1405
- if (c === 95) {
1406
- if (underscore & 1)
1407
- TomlError.x("illegal underscore", ctx);
1408
- underscore = 3;
1409
- } else if (!isDigit(c, base))
1410
- TomlError.x(`illegal character in numeric literal`, ctx);
1411
- else if (underscore & 1)
1412
- underscore--;
1202
+ let coordinatorMinutes = CONFIG_DEFAULTS.coordinatorMinutes;
1203
+ if (policyT.coordinator_minutes !== undefined) {
1204
+ const v = policyT.coordinator_minutes;
1205
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
1206
+ coordinatorMinutes = v;
1207
+ else
1208
+ problems.push(`"policy.coordinator_minutes" must be a positive number`);
1413
1209
  }
1414
- if (underscore & 1)
1415
- TomlError.x("unfinished numeric value", ctx);
1416
- let str = ctx.s.slice(startPtr + 2, ctx.p);
1417
- if (underscore)
1418
- str = str.replaceAll("_", "");
1419
- return parseInteger(ctx, str, base, startPtr);
1420
- }
1421
- function parseInteger(ctx, str, base, startPtr) {
1422
- if (ctx.bi !== true)
1423
- int: {
1424
- let val = parseInt(str, base);
1425
- if (!Number.isSafeInteger(val)) {
1426
- if (ctx.bi)
1427
- break int;
1428
- TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
1429
- }
1430
- return val;
1431
- }
1432
- return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
1433
- }
1434
- function parseDate(ctx, c, endChr) {
1435
- let startPtr = ctx.p++, unsafeSeparator;
1436
- if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
1437
- return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
1210
+ let notStartedMinutes = CONFIG_DEFAULTS.notStartedMinutes;
1211
+ if (policyT.not_started_minutes !== undefined) {
1212
+ const v = policyT.not_started_minutes;
1213
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
1214
+ notStartedMinutes = v;
1215
+ else
1216
+ problems.push(`"policy.not_started_minutes" must be a positive number`);
1438
1217
  }
1439
- ctx.p += 5;
1440
- if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
1441
- TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
1442
- if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
1443
- let t = ctx.s.slice(startPtr, ctx.p);
1444
- return readDate(ctx, t, 3, false, startPtr);
1218
+ let plans = CONFIG_DEFAULTS.plans;
1219
+ if (policyT.plans !== undefined) {
1220
+ const v = policyT.plans;
1221
+ if (typeof v === "string" && PLAN_POLICIES.includes(v.trim()))
1222
+ plans = v.trim();
1223
+ else
1224
+ problems.push(`"policy.plans" must be ${PLAN_POLICIES.map((p) => `"${p}"`).join(" or ")}`);
1445
1225
  }
1446
- if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
1447
- TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
1448
- if (ctx.s.charCodeAt(ctx.p += 3) === 58)
1449
- ctx.p += 3;
1450
- if (ctx.s.charCodeAt(ctx.p) === 46)
1451
- while (isDigit(ctx.s.charCodeAt(++ctx.p)))
1452
- ;
1453
- if (c = ctx.s.charCodeAt(ctx.p)) {
1454
- if (c === 90 || c === 122) {
1455
- let t = ctx.s.slice(startPtr, ++ctx.p);
1456
- return readDate(ctx, t, 1, unsafeSeparator, startPtr, "[+00:00]");
1457
- }
1458
- if (c === 43 || c === 45) {
1459
- let t = ctx.s.slice(startPtr, ctx.p += 6);
1460
- return readDate(ctx, t, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
1461
- }
1226
+ const preApprovedLabel = str(policyT, "policy", "pre_approved_label", { default: CONFIG_DEFAULTS.preApprovedLabel });
1227
+ const approvalLabel = str(policyT, "policy", "approval_label", { default: CONFIG_DEFAULTS.approvalLabel });
1228
+ if (preApprovedLabel && approvalLabel && routingLabelKey(preApprovedLabel) === routingLabelKey(approvalLabel))
1229
+ problems.push(`"policy.pre_approved_label" and "policy.approval_label" must name different labels`);
1230
+ let extra = null;
1231
+ if (briefT.extra !== undefined) {
1232
+ const v = str(briefT, "brief", "extra");
1233
+ if (v && (v.startsWith("/") || v.split(/[\\/]/).includes("..")))
1234
+ problems.push(`"brief.extra" is "${v}", expected a path inside the repository, relative to ${CONFIG_FILE}`);
1235
+ else if (v)
1236
+ extra = v;
1462
1237
  }
1463
- let t = ctx.s.slice(startPtr, ctx.p);
1464
- return readDate(ctx, t, 2, unsafeSeparator, startPtr);
1465
- }
1466
- function parseTime(ctx, c, endChr) {
1467
- let start = ctx.p;
1468
- if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
1469
- return parseNumber(ctx, --ctx.p, c, 0, endChr);
1238
+ let secretNames = [];
1239
+ if (secretsT.names !== undefined) {
1240
+ const v = secretsT.names;
1241
+ if (Array.isArray(v) && v.every((n) => typeof n === "string" && !secretNameRefusal(n.trim())))
1242
+ secretNames = [...new Set(v.map((n) => n.trim()))];
1243
+ else
1244
+ problems.push(`"secrets.names" must be a list of secret names in upper snake case, e.g. ["OPENAI_API_KEY"], none of Armada's own keys`);
1470
1245
  }
1471
- if (ctx.s.charCodeAt(ctx.p += 4) === 58)
1472
- ctx.p += 3;
1473
- if (ctx.s.charCodeAt(ctx.p) === 46)
1474
- while (isDigit(ctx.s.charCodeAt(++ctx.p)))
1475
- ;
1476
- let t = ctx.s.slice(start, ctx.p);
1477
- return readDate(ctx, t, 4, false, start);
1478
- }
1479
- function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
1480
- if (ctx.ld) {
1481
- let date = new TomlDate(str, type, unsafeDelim);
1482
- if (!date.isValid())
1483
- TomlError.x("invalid date", ctx, errPtr);
1484
- return date;
1246
+ let requiredChecks = [];
1247
+ if (gatesT.required_checks !== undefined) {
1248
+ const v = gatesT.required_checks;
1249
+ if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
1250
+ requiredChecks = [...new Set(v.map((c) => c.trim()))];
1251
+ else
1252
+ problems.push(`"gates.required_checks" must be a list of check names`);
1485
1253
  }
1486
- try {
1487
- if (temporalSuffix)
1488
- str += temporalSuffix;
1489
- switch (type) {
1490
- case 1:
1491
- return Temporal.ZonedDateTime.from(str);
1492
- case 2:
1493
- return Temporal.PlainDateTime.from(str);
1494
- case 3:
1495
- return Temporal.PlainDate.from(str);
1496
- case 4:
1497
- return Temporal.PlainTime.from(str);
1498
- }
1499
- } catch (e) {
1500
- TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
1254
+ let localCommands = [];
1255
+ if (gatesT.local_commands !== undefined) {
1256
+ const v = gatesT.local_commands;
1257
+ if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
1258
+ localCommands = v.map((c) => c.trim());
1259
+ else
1260
+ problems.push(`"gates.local_commands" must be a list of shell commands`);
1501
1261
  }
1262
+ const config = {
1263
+ project: {
1264
+ name: str(project, "project", "name"),
1265
+ slug: str(project, "project", "slug", { pattern: SLUG, hint: "lowercase letters, digits and dashes" })
1266
+ },
1267
+ tracker: {
1268
+ programRoot: str(tracker, "tracker", "program_root", {
1269
+ pattern: ISSUE_ID,
1270
+ hint: "an issue identifier such as ABC-1"
1271
+ }),
1272
+ language: str(tracker, "tracker", "language", { default: CONFIG_DEFAULTS.language }),
1273
+ readyLabel: str(tracker, "tracker", "ready_label", { default: CONFIG_DEFAULTS.readyLabel }),
1274
+ labels: {
1275
+ phaseGroup: str(labelsT, "tracker.labels", "phase_group", { default: CONFIG_DEFAULTS.phaseGroup }),
1276
+ runtimeGroup: str(labelsT, "tracker.labels", "runtime_group", { default: CONFIG_DEFAULTS.runtimeGroup }),
1277
+ runtimes
1278
+ }
1279
+ },
1280
+ github: {
1281
+ repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
1282
+ },
1283
+ gates: { requiredChecks, localCommands },
1284
+ policy: { silentAfterMinutes, coordinatorMinutes, notStartedMinutes, plans, preApprovedLabel, approvalLabel },
1285
+ brief: { extra },
1286
+ secrets: { names: secretNames },
1287
+ conductor: { defaultProfile, profiles, routing }
1288
+ };
1289
+ if (problems.length)
1290
+ throw new ConfigError(source, problems);
1291
+ config.tracker.programRoot = config.tracker.programRoot.toUpperCase();
1292
+ return config;
1502
1293
  }
1294
+ function configTemplate(p) {
1295
+ const q = JSON.stringify;
1296
+ return `# Armada configuration: one project = one repository + one tracker program root.
1297
+ # No secrets here: keys come from the environment or \`armada auth login\`.
1503
1298
 
1504
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/util.js
1505
- /*!
1506
- * Copyright (c) Squirrel Chat et al., All rights reserved.
1507
- * SPDX-License-Identifier: BSD-3-Clause
1508
- *
1509
- * Redistribution and use in source and binary forms, with or without
1510
- * modification, are permitted provided that the following conditions are met:
1511
- *
1512
- * 1. Redistributions of source code must retain the above copyright notice, this
1513
- * list of conditions and the following disclaimer.
1514
- * 2. Redistributions in binary form must reproduce the above copyright notice,
1515
- * this list of conditions and the following disclaimer in the
1516
- * documentation and/or other materials provided with the distribution.
1517
- * 3. Neither the name of the copyright holder nor the names of its contributors
1518
- * may be used to endorse or promote products derived from this software without
1519
- * specific prior written permission.
1520
- *
1521
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1522
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1523
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1524
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1525
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1526
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1527
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1528
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1529
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1530
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1531
- */
1532
- function skipComment(ctx) {
1533
- for (;ctx.p < ctx.s.length; ctx.p++) {
1534
- let c = ctx.s.charCodeAt(ctx.p);
1535
- if (c === 10)
1536
- break;
1537
- if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
1538
- ctx.p++;
1539
- break;
1540
- }
1541
- if (c < 32 && c !== 9 || c === 127) {
1542
- TomlError.x("control characters are not allowed in comments", ctx);
1543
- }
1544
- }
1299
+ [project]
1300
+ name = ${q(p.name)}
1301
+ slug = ${q(p.slug)} # stable id: lowercase letters, digits and dashes
1302
+
1303
+ [tracker]
1304
+ program_root = ${q(p.programRoot)} # Linear issue at the root of the program
1305
+ language = "en" # language of owner-facing output
1306
+ ready_label = "ready-for-agent"
1307
+
1308
+ [tracker.labels]
1309
+ phase_group = "Agent phase"
1310
+ runtime_group = "Agent runtime"
1311
+ runtimes = ["Claude Code", "Codex", "Conductor"]
1312
+
1313
+ [github]
1314
+ repository = ${q(p.repository)}
1315
+
1316
+ [gates]
1317
+ # required_checks = ["test"] # CI checks that must be green before a hand-back (default: every check)
1318
+
1319
+ [policy]
1320
+ silence_minutes = 15 # a worker with no report for longer than this shows as silent
1321
+ coordinator_minutes = 10 # an inbox item open longer than this shows "waiting for the coordinator"
1322
+ # not_started_minutes = 10 # a launched worker that has not claimed after this long shows as not started
1323
+ # plans = "approve" # or "pre-approved": workers post their plan and go on without waiting
1324
+ # pre_approved_label = "plan-approved" # a ticket with this label skips the approval
1325
+ # approval_label = "needs-plan-approval" # a ticket with this label waits for it; wins over the other
1326
+
1327
+ [brief]
1328
+ # extra = "docs/worker-conventions.md" # a file every worker brief carries under "Project conventions"
1329
+
1330
+ # How \`armada brief\` launches workers on Conductor. Every value is passed explicitly;
1331
+ # \`conductor model\` lists each agent's model ids and effort levels.
1332
+ [conductor]
1333
+ default_profile = "opus" # for tickets no routing rule matches
1334
+
1335
+ [conductor.profiles.opus]
1336
+ agent = "claude"
1337
+ model = "opus-5-5-1m"
1338
+ effort = "high"
1339
+
1340
+ [conductor.profiles.codex]
1341
+ agent = "codex"
1342
+ model = "gpt-6.1-sol"
1343
+ effort = "high"
1344
+
1345
+ [conductor.profiles.debug]
1346
+ agent = "codex"
1347
+ model = "gpt-6.1-sol"
1348
+ effort = "xhigh"
1349
+
1350
+ # A worker run as a subagent of a coordinator's Claude Code session, in its own
1351
+ # worktree (the armada-runtime-claude-code skill). It dies with that session, so
1352
+ # long runs belong on Conductor. \`model\` is what the Agent tool takes; it applies no effort.
1353
+ # [conductor.profiles.local]
1354
+ # runtime = "claude-code"
1355
+ # agent = "claude"
1356
+ # model = "opus"
1357
+ # effort = "high"
1358
+
1359
+ # Which profile a ticket gets from its Linear labels: the first rule with a label
1360
+ # the ticket carries wins, in file order. \`armada brief --profile\` overrides it.
1361
+ [[conductor.routing]]
1362
+ labels = ["web"]
1363
+ profile = "opus"
1364
+
1365
+ [[conductor.routing]]
1366
+ labels = ["api"]
1367
+ profile = "codex"
1368
+
1369
+ [[conductor.routing]]
1370
+ labels = ["Bug"]
1371
+ profile = "debug"
1372
+ `;
1545
1373
  }
1546
- function skipVoid(ctx, banNewLines, banComments) {
1547
- let c;
1548
- while (ctx.p < ctx.s.length) {
1549
- while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
1550
- ctx.p++;
1551
- if (banComments || c !== 35)
1552
- break;
1553
- skipComment(ctx);
1554
- }
1374
+ function slugify(name) {
1375
+ return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "project";
1555
1376
  }
1556
1377
 
1557
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/struct.js
1558
- /*!
1559
- * Copyright (c) Squirrel Chat et al., All rights reserved.
1560
- * SPDX-License-Identifier: BSD-3-Clause
1561
- *
1562
- * Redistribution and use in source and binary forms, with or without
1563
- * modification, are permitted provided that the following conditions are met:
1564
- *
1565
- * 1. Redistributions of source code must retain the above copyright notice, this
1566
- * list of conditions and the following disclaimer.
1567
- * 2. Redistributions in binary form must reproduce the above copyright notice,
1568
- * this list of conditions and the following disclaimer in the
1569
- * documentation and/or other materials provided with the distribution.
1570
- * 3. Neither the name of the copyright holder nor the names of its contributors
1571
- * may be used to endorse or promote products derived from this software without
1572
- * specific prior written permission.
1573
- *
1574
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1575
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1576
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1577
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1578
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1579
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1580
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1581
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1582
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1583
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1584
- */
1585
- function parseKey(ctx, end = 61) {
1586
- let startPtr;
1587
- let state = 0;
1588
- let parsed = [];
1589
- let sliceStart;
1590
- let c = ctx.s.charCodeAt(startPtr = ctx.p);
1591
- do {
1592
- if (c === end) {
1593
- if (!state)
1594
- TomlError.x("unexpected end of key", ctx);
1595
- if (state === 1)
1596
- parsed.push(ctx.s.slice(sliceStart, ctx.p));
1597
- return ctx.p++, parsed;
1598
- } else if (c === 46) {
1599
- if (!state)
1600
- TomlError.x("illegal empty bare key", ctx);
1601
- if (state === 1)
1602
- parsed.push(ctx.s.slice(sliceStart, ctx.p));
1603
- state = 0;
1604
- } else if (!state && (c === 34 || c === 39)) {
1605
- if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
1606
- TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
1607
- parsed.push(parseString(ctx));
1608
- state = 2;
1609
- ctx.p--;
1610
- } else if (c === 32 || c === 9) {
1611
- if (state === 1) {
1612
- parsed.push(ctx.s.slice(sliceStart, ctx.p));
1613
- state = 2;
1614
- }
1615
- } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
1616
- TomlError.x("illegal character in key", ctx);
1617
- } else if (!state) {
1618
- state = 1;
1619
- sliceStart = ctx.p;
1378
+ // ../core/src/model.ts
1379
+ var CLOSED = ["completed", "canceled"];
1380
+ var NOT_STARTED = ["triage", "backlog", "unstarted"];
1381
+ var isDone = (i) => i.statusType === "completed";
1382
+ var isClosed = (i) => CLOSED.includes(i.statusType);
1383
+ var isStarted = (i) => i.statusType === "started";
1384
+ var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
1385
+ var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
1386
+ function buildModel(issues, rootId) {
1387
+ const byId = new Map(issues.map((i) => [i.id, i]));
1388
+ const root = byId.get(rootId);
1389
+ if (!root)
1390
+ throw new Error(`program root ${rootId} is not among the issues read`);
1391
+ const childrenOf = new Map;
1392
+ for (const i of issues) {
1393
+ if (!i.parentId || !byId.has(i.parentId))
1394
+ continue;
1395
+ childrenOf.set(i.parentId, [...childrenOf.get(i.parentId) ?? [], i]);
1396
+ }
1397
+ const program = [];
1398
+ const walk = (id, seen) => {
1399
+ for (const c of childrenOf.get(id) ?? []) {
1400
+ if (seen.has(c.id))
1401
+ continue;
1402
+ seen.add(c.id);
1403
+ program.push(c);
1404
+ walk(c.id, seen);
1620
1405
  }
1621
- } while (c = ctx.s.charCodeAt(++ctx.p));
1622
- TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
1623
- }
1624
- function parseInlineTable(ctx) {
1625
- let startPtr = ctx.p++;
1626
- let res = Object.create(null);
1627
- let seen = new Set;
1628
- let c;
1629
- while (ctx.p < ctx.s.length) {
1630
- skipVoid(ctx);
1631
- if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
1632
- ctx.p++;
1633
- return res;
1406
+ };
1407
+ walk(root.id, new Set([root.id]));
1408
+ const specs = (childrenOf.get(root.id) ?? []).flatMap((issue) => {
1409
+ const m = issue.title.trim().match(SPEC_TITLE);
1410
+ return m?.[1] && m[3] ? [{ issue, ordinal: Number(m[1]), name: m[3].trim() }] : [];
1411
+ }).sort((a, b) => a.ordinal - b.ordinal || a.issue.createdAt.localeCompare(b.issue.createdAt));
1412
+ const specById = new Map(specs.map((s) => [s.issue.id, s]));
1413
+ const specOf = (id) => {
1414
+ const seen = new Set;
1415
+ for (let cur = byId.get(id);cur && !seen.has(cur.id); cur = cur.parentId ? byId.get(cur.parentId) : undefined) {
1416
+ seen.add(cur.id);
1417
+ const s = specById.get(cur.id);
1418
+ if (s)
1419
+ return s;
1634
1420
  }
1635
- let k;
1636
- let t = res;
1637
- let hasOwn = false;
1638
- let errPtr = ctx.p;
1639
- let key = parseKey(ctx);
1640
- for (let i = 0;i < key.length; i++) {
1641
- if (i)
1642
- t = hasOwn ? t[k] : t[k] = Object.create(null);
1643
- k = key[i];
1644
- if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
1645
- TomlError.x("trying to redefine an already defined value", ctx, errPtr);
1646
- }
1647
- let unsafe = k === "__proto__";
1648
- if (ctx.uk && (unsafe || k === "constructor")) {
1649
- t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
1650
- break;
1651
- }
1652
- if (!hasOwn && unsafe) {
1653
- Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
1421
+ return null;
1422
+ };
1423
+ const isLeaf = (i) => !childrenOf.get(i.id)?.length && !specById.has(i.id);
1424
+ const openBlockersOf = (i) => i.blockedBy.filter((b) => !isClosed(byId.get(b.id) ?? b)).map((b) => b.id);
1425
+ const stateOf = (i) => {
1426
+ if (isDone(i))
1427
+ return "done";
1428
+ if (i.statusType === "canceled")
1429
+ return "canceled";
1430
+ if (isStarted(i))
1431
+ return "active";
1432
+ return openBlockersOf(i).length ? "blocked" : "frontier";
1433
+ };
1434
+ return { root, byId, childrenOf, program, specs, specOf, isLeaf, openBlockersOf, stateOf };
1435
+ }
1436
+ function longestPathLevels(nodes) {
1437
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1438
+ const level = new Map;
1439
+ const visiting = new Set;
1440
+ const visit = (id) => {
1441
+ const known = level.get(id);
1442
+ if (known !== undefined)
1443
+ return known;
1444
+ if (visiting.has(id))
1445
+ return 0;
1446
+ visiting.add(id);
1447
+ const blockers = (byId.get(id)?.blockedBy ?? []).map((b) => b.id).filter((b) => byId.has(b));
1448
+ const l = blockers.length ? Math.max(...blockers.map(visit)) + 1 : 0;
1449
+ visiting.delete(id);
1450
+ level.set(id, l);
1451
+ return l;
1452
+ };
1453
+ for (const n of nodes)
1454
+ visit(n.id);
1455
+ return level;
1456
+ }
1457
+ function criticalPath(m, parentId) {
1458
+ const nodes = m.childrenOf.get(parentId) ?? [];
1459
+ const level = longestPathLevels(nodes);
1460
+ const remaining = nodes.filter((n) => !isClosed(n));
1461
+ const remIds = new Set(remaining.map((n) => n.id));
1462
+ const len = new Map;
1463
+ const prev = new Map;
1464
+ const order = [...remaining].sort((a, b) => (level.get(a.id) ?? 0) - (level.get(b.id) ?? 0));
1465
+ for (const n of order) {
1466
+ let best = 0;
1467
+ let bestPrev = null;
1468
+ for (const { id } of n.blockedBy) {
1469
+ if (!remIds.has(id))
1470
+ continue;
1471
+ const l = len.get(id) ?? 0;
1472
+ if (l > best) {
1473
+ best = l;
1474
+ bestPrev = id;
1654
1475
  }
1655
1476
  }
1656
- if (hasOwn) {
1657
- TomlError.x("trying to redefine an already defined value", ctx, errPtr);
1658
- }
1659
- skipVoid(ctx, true, true);
1660
- let value = extractValue(ctx, 125);
1661
- if (t && typeof (t[k] = value) === "object")
1662
- seen.add(value);
1663
- skipVoid(ctx);
1664
- if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
1665
- return res;
1666
- }
1667
- if (c !== 44)
1668
- TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
1477
+ len.set(n.id, best + 1);
1478
+ prev.set(n.id, bestPrev);
1669
1479
  }
1670
- TomlError.x("unfinished table", ctx, startPtr);
1671
- }
1672
- function parseArray(ctx) {
1673
- let startPtr = ctx.p++;
1674
- let res = [];
1675
- let c;
1676
- while (ctx.p < ctx.s.length) {
1677
- skipVoid(ctx);
1678
- if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
1679
- ctx.p++;
1680
- return res;
1681
- }
1682
- res.push(extractValue(ctx, 93));
1683
- skipVoid(ctx);
1684
- if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
1685
- return res;
1480
+ let tail = null;
1481
+ let tailLen = 0;
1482
+ for (const [id, l] of len)
1483
+ if (l > tailLen || l === tailLen && tail && id > tail) {
1484
+ tail = id;
1485
+ tailLen = l;
1686
1486
  }
1687
- if (c !== 44)
1688
- TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
1487
+ if (tailLen < 2)
1488
+ return [];
1489
+ const path = [];
1490
+ for (let cur = tail;cur; cur = prev.get(cur) ?? null) {
1491
+ const issue = m.byId.get(cur);
1492
+ if (issue)
1493
+ path.unshift(issue);
1689
1494
  }
1690
- TomlError.x("unfinished array", ctx, startPtr);
1495
+ return path;
1496
+ }
1497
+ function criticalIds(m) {
1498
+ const out = new Set;
1499
+ for (const parent of m.childrenOf.keys())
1500
+ for (const i of criticalPath(m, parent))
1501
+ out.add(i.id);
1502
+ return out;
1691
1503
  }
1692
1504
 
1693
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/parse.js
1694
- /*!
1695
- * Copyright (c) Squirrel Chat et al., All rights reserved.
1696
- * SPDX-License-Identifier: BSD-3-Clause
1697
- *
1698
- * Redistribution and use in source and binary forms, with or without
1699
- * modification, are permitted provided that the following conditions are met:
1700
- *
1701
- * 1. Redistributions of source code must retain the above copyright notice, this
1702
- * list of conditions and the following disclaimer.
1703
- * 2. Redistributions in binary form must reproduce the above copyright notice,
1704
- * this list of conditions and the following disclaimer in the
1705
- * documentation and/or other materials provided with the distribution.
1706
- * 3. Neither the name of the copyright holder nor the names of its contributors
1707
- * may be used to endorse or promote products derived from this software without
1708
- * specific prior written permission.
1709
- *
1710
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1711
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1712
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1713
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1714
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1715
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1716
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1717
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1718
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1719
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1720
- */
1721
- function peekTable(ctx, key, table, meta, type) {
1722
- let t = table;
1723
- let m = meta;
1724
- let k;
1725
- let hasOwn = false;
1726
- let state;
1727
- for (let i = 0;i < key.length; i++) {
1728
- if (i) {
1729
- t = hasOwn ? t[k] : t[k] = Object.create(null);
1730
- m = (state = m[k]).c;
1731
- if (type === 0 && (state.t === 1 || state.t === 2)) {
1732
- return null;
1733
- }
1734
- if (state.t === 2) {
1735
- let l = t.length - 1;
1736
- t = t[l];
1737
- m = m[l].c;
1738
- }
1739
- }
1740
- k = key[i];
1741
- if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
1742
- return null;
1743
- }
1744
- if (!hasOwn) {
1745
- let unsafe = k === "__proto__";
1746
- if (ctx.uk && (unsafe || k === "constructor"))
1747
- return false;
1748
- if (unsafe) {
1749
- Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
1750
- Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
1751
- }
1752
- m[k] = {
1753
- t: i < key.length - 1 && type === 2 ? 3 : type,
1754
- d: false,
1755
- i: 0,
1756
- c: Object.create(null)
1757
- };
1758
- }
1759
- }
1760
- state = m[k];
1761
- if (state.t !== type && !(type === 1 && state.t === 3)) {
1762
- return null;
1505
+ // ../core/src/types.ts
1506
+ var LABEL_PHASES = [
1507
+ "planning",
1508
+ "awaiting-approval",
1509
+ "implementing",
1510
+ "shipping",
1511
+ "blocked",
1512
+ "ready-to-merge"
1513
+ ];
1514
+
1515
+ // ../core/src/fleet.ts
1516
+ var MIN = 60000;
1517
+ var NEEDS_HUMAN = ["awaiting-approval", "blocked", "ready-to-merge"];
1518
+ var PHASE_RANK = {
1519
+ merged: 0,
1520
+ "ready-to-merge": 1,
1521
+ shipping: 2,
1522
+ implementing: 3,
1523
+ "awaiting-approval": 4,
1524
+ planning: 5,
1525
+ blocked: 6,
1526
+ released: 7
1527
+ };
1528
+ var PLAN_HINT = /\b(plan|objective|assumptions|awaiting (?:plan )?approval)\b/i;
1529
+ function commentsFor(comments, id) {
1530
+ return comments.filter((c) => c.issueId === id).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
1531
+ }
1532
+ function commentUrl(issue, c) {
1533
+ return `${issue.url}#comment-${c.id.slice(0, 8)}`;
1534
+ }
1535
+ function primaryPr(issue) {
1536
+ const byNewest = [...issue.prs].sort((a, b) => b.number - a.number);
1537
+ return byNewest.find((p) => p.state === "open") ?? byNewest[0] ?? null;
1538
+ }
1539
+ function activeClaims(comments) {
1540
+ const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1541
+ let claims = [];
1542
+ for (const c of asc) {
1543
+ if (c.status?.phase === "released")
1544
+ claims = [];
1545
+ if (c.claim)
1546
+ claims.push(c.claim);
1763
1547
  }
1764
- if (type === 2) {
1765
- if (!state.d) {
1766
- state.d = true;
1767
- t[k] = [];
1768
- }
1769
- t[k].push(t = Object.create(null));
1770
- state.c[state.i++] = state = { t: 1, d: false, i: 0, c: Object.create(null) };
1548
+ return claims;
1549
+ }
1550
+ var latest = (...xs) => xs.filter((x) => !!x).reduce((a, b) => b > a ? b : a, "");
1551
+ function inferPhase(pr, comments) {
1552
+ if (pr?.state === "open")
1553
+ return pr.ci === "success" && pr.mergeable !== "CONFLICTING" ? "ready-to-merge" : "shipping";
1554
+ if (comments.some((c) => PLAN_HINT.test(c.excerpt.slice(0, 120))))
1555
+ return "awaiting-approval";
1556
+ return "planning";
1557
+ }
1558
+ var ENDS_WORK = ["release", "merge"];
1559
+ var livePhase = (e) => e.kind === "release" ? "released" : LABEL_PHASES.find((p) => p === e.phase) ?? null;
1560
+ function freshEvent(issueId, opts) {
1561
+ const e = opts.live?.events[issueId];
1562
+ return e && opts.live && e.at > opts.live.after ? e : null;
1563
+ }
1564
+ function buildLane(m, allComments, issue, opts) {
1565
+ const comments = commentsFor(allComments, issue.id);
1566
+ const withStatus = comments.find((c) => c.status && c.status.phase !== "released");
1567
+ const pr = primaryPr(issue);
1568
+ const claims = activeClaims(comments);
1569
+ let phase;
1570
+ let phaseSource;
1571
+ if (issue.agentPhase) {
1572
+ phase = issue.agentPhase;
1573
+ phaseSource = "label";
1574
+ } else if (withStatus?.status) {
1575
+ phase = withStatus.status.phase;
1576
+ phaseSource = "status-line";
1577
+ } else {
1578
+ phase = inferPhase(pr, comments);
1579
+ phaseSource = "inferred";
1771
1580
  }
1772
- if (state.d) {
1773
- return null;
1581
+ const fresh = freshEvent(issue.id, opts);
1582
+ const freshPhase = fresh ? livePhase(fresh) : null;
1583
+ const trackerPhase = phase;
1584
+ if (freshPhase && freshPhase !== "released") {
1585
+ phase = freshPhase;
1586
+ phaseSource = "live";
1774
1587
  }
1775
- state.d = true;
1776
- if (type === 1) {
1777
- t = hasOwn ? t[k] : t[k] = Object.create(null);
1778
- } else if (type === 0 && hasOwn) {
1779
- return null;
1588
+ const shippingPhase = phase === "shipping" || phase === "ready-to-merge";
1589
+ if (pr?.state === "merged" && !isDone(issue) && (shippingPhase || phaseSource === "status-line" || phaseSource === "inferred"))
1590
+ phase = "merged";
1591
+ let announcing;
1592
+ for (const c of comments) {
1593
+ if (!c.status || c.status.phase === "released")
1594
+ continue;
1595
+ if (c.status.phase !== phase)
1596
+ break;
1597
+ announcing = c;
1780
1598
  }
1781
- return [k, t, state.c];
1782
- }
1783
- function validateTablePeek(ctx, peek, ptr) {
1784
- if (peek === null || ctx.uk === 2)
1785
- TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
1599
+ const since = (fresh && phaseSource === "live" && phase !== trackerPhase ? fresh.at : undefined) ?? announcing?.createdAt ?? (fresh && phaseSource === "live" ? fresh.at : undefined) ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
1600
+ const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt, fresh?.at);
1601
+ const lastReport = latest(comments.find((c) => c.status || c.claim)?.createdAt, claims.at(-1)?.at, opts.lastEvents?.[issue.id], fresh?.at) || null;
1602
+ const openBlockers = m.openBlockersOf(issue);
1603
+ const agent = issue.delegate ?? issue.assignee;
1604
+ const flags = [];
1605
+ const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
1606
+ const alive = lastReport ?? lastUpdate;
1607
+ if (!waitingOnHuman && opts.now - Date.parse(alive) > opts.silentAfterMinutes * MIN)
1608
+ flags.push("silent");
1609
+ if (pr?.state === "open" && pr.ci === "failure")
1610
+ flags.push("ci-failing");
1611
+ if (pr?.state === "open" && pr.mergeable === "CONFLICTING")
1612
+ flags.push("conflict");
1613
+ const runtimes = new Set(claims.map((c) => c.runtime).filter(Boolean));
1614
+ const claimRuntime = claims[0]?.runtime;
1615
+ if (claims.length > 1 || runtimes.size > 1 || issue.agentRuntime && claimRuntime && claimRuntime !== issue.agentRuntime)
1616
+ flags.push("double-claim");
1617
+ if (openBlockers.length)
1618
+ flags.push("started-before-blockers");
1619
+ if (!agent && phaseSource !== "live")
1620
+ flags.push("no-assignee");
1621
+ if (!issue.agentPhase && phaseSource !== "live")
1622
+ flags.push("no-phase-label");
1623
+ const spec = m.specOf(issue.id);
1624
+ return {
1625
+ issue,
1626
+ spec: spec ? `Spec ${spec.ordinal}` : null,
1627
+ phase,
1628
+ phaseSource,
1629
+ runtime: issue.agentRuntime ?? claimRuntime ?? fresh?.runtime ?? opts.live?.handles?.[issue.id]?.runtime ?? null,
1630
+ handle: opts.live?.handles?.[issue.id]?.handle ?? claims[0]?.session ?? fresh?.handle ?? null,
1631
+ claim: claims[0] ?? null,
1632
+ agent,
1633
+ since,
1634
+ lastUpdate,
1635
+ lastReport,
1636
+ statusLine: fresh?.message && phaseSource === "live" ? { summary: fresh.message, at: fresh.at, author: null, url: issue.url, plan: false } : withStatus?.status ? {
1637
+ summary: withStatus.status.summary,
1638
+ at: withStatus.createdAt,
1639
+ author: withStatus.author,
1640
+ url: commentUrl(issue, withStatus),
1641
+ plan: !!withStatus.status.plan
1642
+ } : null,
1643
+ pr,
1644
+ openBlockers,
1645
+ flags
1646
+ };
1786
1647
  }
1787
- function parse(toml, options = {}) {
1788
- let ctx = {
1789
- s: toml,
1790
- p: 0,
1791
- d: options.maxDepth ?? 1000,
1792
- bi: options.integersAsBigInt ?? false,
1793
- ld: options.useLegacyDate ?? true,
1794
- uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
1648
+ function inFlight(m, comments, opts) {
1649
+ const held = (i) => {
1650
+ const fresh = freshEvent(i.id, opts);
1651
+ return fresh ? !ENDS_WORK.includes(fresh.kind) : !!i.agentPhase || isStarted(i);
1795
1652
  };
1796
- let res = Object.create(null);
1797
- let meta = Object.create(null);
1798
- let tmp;
1799
- let skipping = false;
1800
- let tbl = res;
1801
- let m = meta;
1802
- if (toml.charCodeAt(0) === 65279)
1803
- ctx.p++;
1804
- skipVoid(ctx);
1805
- while (ctx.p < toml.length) {
1806
- if (toml.charCodeAt(ctx.p) === 91) {
1807
- let isTableArray = toml.charCodeAt(++ctx.p) === 91;
1808
- tmp = ctx.p += +isTableArray;
1809
- skipping = false;
1810
- let k = parseKey(ctx, 93);
1811
- if (isTableArray) {
1812
- if (toml.charCodeAt(ctx.p) !== 93) {
1813
- TomlError.x("expected end of table array declaration", ctx);
1814
- }
1815
- ctx.p++;
1816
- }
1817
- let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
1818
- if (!p) {
1819
- validateTablePeek(ctx, p, tmp);
1820
- skipping = true;
1821
- } else {
1822
- m = p[2];
1823
- tbl = p[1];
1824
- }
1825
- } else {
1826
- tmp = ctx.p;
1827
- let k = parseKey(ctx);
1828
- let p = peekTable(ctx, k, tbl, m, 0);
1829
- if (!p && !skipping)
1830
- validateTablePeek(ctx, p, tmp);
1831
- skipVoid(ctx, true, true);
1832
- let v = extractValue(ctx, undefined);
1833
- if (p && !skipping)
1834
- p[1][p[0]] = v;
1835
- }
1836
- skipVoid(ctx, true);
1837
- if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
1838
- TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
1839
- }
1840
- skipVoid(ctx);
1841
- }
1842
- return res;
1653
+ return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && held(i)).map((i) => buildLane(m, comments, i, opts)).sort((a, b) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
1654
+ }
1655
+ function frontier(m, readyLabel) {
1656
+ const dependents = new Map;
1657
+ for (const i of m.program)
1658
+ for (const b of i.blockedBy)
1659
+ dependents.set(b.id, [...dependents.get(b.id) ?? [], i]);
1660
+ const transitive = (id, seen = new Set) => {
1661
+ for (const d of dependents.get(id) ?? [])
1662
+ if (!seen.has(d.id) && !isClosed(d)) {
1663
+ seen.add(d.id);
1664
+ transitive(d.id, seen);
1665
+ }
1666
+ return seen;
1667
+ };
1668
+ const critical = criticalIds(m);
1669
+ return m.program.filter((i) => m.isLeaf(i) && isNotStarted(i) && !i.agentPhase && m.openBlockersOf(i).length === 0 && !i.prs.some((p) => p.state === "open")).map((issue) => {
1670
+ const spec = m.specOf(issue.id);
1671
+ const unlocksAll = [...transitive(issue.id)];
1672
+ const unlocksNow = (dependents.get(issue.id) ?? []).filter((d) => !isClosed(d) && m.openBlockersOf(d).every((b) => b === issue.id)).map((d) => d.id);
1673
+ const readyForAgent = issue.labels.includes(readyLabel) && issue.statusType !== "triage";
1674
+ const onCriticalPath = critical.has(issue.id);
1675
+ const score = (readyForAgent ? 1000 : 0) + (onCriticalPath ? 300 : 0) + unlocksAll.length * 20 + unlocksNow.length * 10 - (spec?.ordinal ?? 99);
1676
+ return {
1677
+ issue,
1678
+ spec: spec ? `Spec ${spec.ordinal}` : null,
1679
+ readyForAgent,
1680
+ onCriticalPath,
1681
+ unlocksAll,
1682
+ unlocksNow,
1683
+ score
1684
+ };
1685
+ }).sort((a, b) => b.score - a.score || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
1686
+ }
1687
+ function waitingPullRequests(m, prs) {
1688
+ const ticketOf = new Map;
1689
+ for (const i of m.program)
1690
+ for (const p of i.prs)
1691
+ ticketOf.set(p.url, i);
1692
+ return prs.filter((p) => p.state === "open").map((pr) => ({ pr, ticket: ticketOf.get(pr.url) ?? null })).sort((a, b) => a.pr.number - b.pr.number);
1843
1693
  }
1844
1694
 
1845
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/stringify.js
1846
- /*!
1847
- * Copyright (c) Squirrel Chat et al., All rights reserved.
1848
- * SPDX-License-Identifier: BSD-3-Clause
1849
- *
1850
- * Redistribution and use in source and binary forms, with or without
1851
- * modification, are permitted provided that the following conditions are met:
1852
- *
1853
- * 1. Redistributions of source code must retain the above copyright notice, this
1854
- * list of conditions and the following disclaimer.
1855
- * 2. Redistributions in binary form must reproduce the above copyright notice,
1856
- * this list of conditions and the following disclaimer in the
1857
- * documentation and/or other materials provided with the distribution.
1858
- * 3. Neither the name of the copyright holder nor the names of its contributors
1859
- * may be used to endorse or promote products derived from this software without
1860
- * specific prior written permission.
1861
- *
1862
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1863
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1864
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1865
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1866
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1867
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1868
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1869
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1870
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1871
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1872
- */
1873
- var HAS_WELLFORMED = !!"".isWellFormed;
1874
-
1875
- // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js
1876
- /*!
1877
- * Copyright (c) Squirrel Chat et al., All rights reserved.
1878
- * SPDX-License-Identifier: BSD-3-Clause
1879
- *
1880
- * Redistribution and use in source and binary forms, with or without
1881
- * modification, are permitted provided that the following conditions are met:
1882
- *
1883
- * 1. Redistributions of source code must retain the above copyright notice, this
1884
- * list of conditions and the following disclaimer.
1885
- * 2. Redistributions in binary form must reproduce the above copyright notice,
1886
- * this list of conditions and the following disclaimer in the
1887
- * documentation and/or other materials provided with the distribution.
1888
- * 3. Neither the name of the copyright holder nor the names of its contributors
1889
- * may be used to endorse or promote products derived from this software without
1890
- * specific prior written permission.
1891
- *
1892
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1893
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1894
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1895
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1896
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1897
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1898
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1899
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1900
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1901
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1902
- */
1695
+ // ../core/src/live.ts
1696
+ var LAUNCH_WINDOW_MS = 24 * 60 * 60000;
1697
+ var MIN2 = 60000;
1698
+ var REWRITTEN = ["hand-back", "plan"];
1699
+ var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 12);
1700
+ var entryKey = (e) => e.id !== null ? REWRITTEN.includes(e.kind) ? `#${e.id}@${digest(e.body)}` : `#${e.id}` : e.version ? `version:${e.version}` : `${e.kind}:${e.ticket}`;
1701
+ var hhmm = (iso) => `${iso.slice(11, 16)} UTC`;
1702
+ function notStartedBody(l, now) {
1703
+ const minutes = Math.floor((now.getTime() - Date.parse(l.launchedAt)) / MIN2);
1704
+ const why = l.tokenUsedAt ? `the worker signed in with its launch token at ${hhmm(l.tokenUsedAt)}, then stopped before \`armada claim\`` : "its launch token was never used: the worker never reached its `armada login` line (an install that failed, a prompt cut short)";
1705
+ return `launched ${minutes} min ago and never claimed; ${why}${l.handle ? ` (session ${l.handle})` : ""}. Check its session with the runtime guide's status section; launch it again with armada brief, or revoke the launch on the dashboard's Workers page`;
1706
+ }
1707
+ var notStartedLaunches = (launches, now, minutes) => launches.filter((l) => now.getTime() - Date.parse(l.launchedAt) > minutes * MIN2);
1903
1708
 
1904
- // ../core/src/config.ts
1905
- var CONFIG_FILE = "armada.toml";
1906
- var PLAN_POLICIES = ["approve", "pre-approved"];
1907
- var routingLabelKey = (name) => name.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]/gu, "");
1908
- var PROFILE_RUNTIMES = ["conductor", "claude-code"];
1909
- var CONFIG_DEFAULTS = {
1910
- language: "en",
1911
- readyLabel: "ready-for-agent",
1912
- phaseGroup: "Agent phase",
1913
- runtimeGroup: "Agent runtime",
1914
- runtimes: ["Claude Code", "Codex", "Conductor"],
1915
- silentAfterMinutes: 15,
1916
- coordinatorMinutes: 10,
1917
- notStartedMinutes: 10,
1918
- plans: "approve",
1919
- preApprovedLabel: "plan-approved",
1920
- approvalLabel: "needs-plan-approval"
1921
- };
1709
+ // ../core/src/activity.ts
1710
+ var SAME_MS = 10 * 60000;
1711
+ // ../core/src/linear.ts
1712
+ var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
1713
+ var MAX_DEPTH = 8;
1714
+ var COMMENT_BATCH = 25;
1715
+ var MAX_COMMENTS = 100;
1716
+ var MORE_PAGE = 100;
1717
+ var REQUEST_TIMEOUT_MS = 30000;
1922
1718
 
1923
- class ConfigError extends Error {
1924
- source;
1925
- problems;
1926
- constructor(source, problems) {
1927
- super(`${source} is invalid:
1928
- ${problems.map((p) => ` - ${p}`).join(`
1929
- `)}`);
1930
- this.source = source;
1931
- this.problems = problems;
1932
- this.name = "ConfigError";
1719
+ class LinearError extends Error {
1720
+ transport;
1721
+ name = "LinearError";
1722
+ constructor(message, transport = false) {
1723
+ super(message);
1724
+ this.transport = transport;
1933
1725
  }
1934
1726
  }
1935
- var SLUG = /^[a-z0-9][a-z0-9-]*$/;
1936
- var ISSUE_ID = /^[A-Za-z][A-Za-z0-9]*-\d+$/;
1937
- var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
1938
- var RESERVED_SECRET_NAMES = ["LINEAR_API_KEY", "GITHUB_TOKEN", "GH_TOKEN"];
1939
- function secretNameRefusal(name) {
1940
- if (!SECRET_NAME.test(name))
1941
- return "a secret name is in upper snake case, e.g. OPENAI_API_KEY";
1942
- if (RESERVED_SECRET_NAMES.includes(name) || name.startsWith("ARMADA_"))
1943
- return `${name} is a key Armada itself uses: it is set on the Keys page as such, not as a secret for workers`;
1944
- return null;
1727
+ var PHASES = [...LABEL_PHASES, "released", "merged"];
1728
+ var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
1729
+ var firstLine = (body) => (body.split(`
1730
+ `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
1731
+ var COORDINATOR_RECORD = /^(?:answer|note)\s*:/i;
1732
+ var PLAN_BLOCK = /^## Plan[ \t]*$/m;
1733
+ function parseStatusLine(body) {
1734
+ const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
1735
+ if (!m?.[1])
1736
+ return null;
1737
+ const raw = m[1].toLowerCase();
1738
+ const phase = LEGACY[raw] ?? raw;
1739
+ const summary = (m[2] ?? "").trim();
1740
+ if (COORDINATOR_RECORD.test(summary))
1741
+ return null;
1742
+ if (!PHASES.includes(phase))
1743
+ return null;
1744
+ return PLAN_BLOCK.test(body) ? { phase, summary, plan: true } : { phase, summary };
1945
1745
  }
1946
- var REPOSITORY = /^[\w.-]+\/[\w.-]+$/;
1947
- var isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1948
- function parseConfig(text, source = CONFIG_FILE) {
1949
- let raw;
1950
- try {
1951
- raw = parse(text);
1952
- } catch (err) {
1953
- const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
1954
- throw new ConfigError(source, [`not valid TOML${where}`]);
1955
- }
1956
- const problems = [];
1957
- const table = (key) => {
1958
- const v = raw[key];
1959
- if (v === undefined) {
1960
- problems.push(`missing required table [${key}]`);
1961
- return {};
1962
- }
1963
- if (!isTable(v)) {
1964
- problems.push(`"${key}" must be a table`);
1965
- return {};
1966
- }
1967
- return v;
1968
- };
1969
- const str = (t, path, key, opts = {}) => {
1970
- const v = t[key];
1971
- const dotted = `${path}.${key}`;
1972
- if (v === undefined) {
1973
- if (opts.default !== undefined)
1974
- return opts.default;
1975
- problems.push(`missing required key "${dotted}"`);
1976
- return "";
1977
- }
1978
- if (typeof v !== "string" || !v.trim()) {
1979
- problems.push(`"${dotted}" must be a non-empty string`);
1980
- return "";
1981
- }
1982
- if (opts.pattern && !opts.pattern.test(v)) {
1983
- problems.push(`"${dotted}" is "${v}", expected ${opts.hint}`);
1984
- return "";
1985
- }
1986
- return v.trim();
1987
- };
1988
- const project = table("project");
1989
- const tracker = table("tracker");
1990
- const github = table("github");
1991
- const labels = tracker.labels === undefined ? {} : tracker.labels;
1992
- if (!isTable(labels))
1993
- problems.push(`"tracker.labels" must be a table`);
1994
- const policy = raw.policy === undefined ? {} : raw.policy;
1995
- if (!isTable(policy))
1996
- problems.push(`"policy" must be a table`);
1997
- const labelsT = isTable(labels) ? labels : {};
1998
- const policyT = isTable(policy) ? policy : {};
1999
- const gates = raw.gates === undefined ? {} : raw.gates;
2000
- if (!isTable(gates))
2001
- problems.push(`"gates" must be a table`);
2002
- const gatesT = isTable(gates) ? gates : {};
2003
- const brief = raw.brief === undefined ? {} : raw.brief;
2004
- if (!isTable(brief))
2005
- problems.push(`"brief" must be a table`);
2006
- const briefT = isTable(brief) ? brief : {};
2007
- const secrets = raw.secrets === undefined ? {} : raw.secrets;
2008
- if (!isTable(secrets))
2009
- problems.push(`"secrets" must be a table`);
2010
- const secretsT = isTable(secrets) ? secrets : {};
2011
- const conductor = raw.conductor === undefined ? {} : raw.conductor;
2012
- if (!isTable(conductor))
2013
- problems.push(`"conductor" must be a table`);
2014
- const conductorT = isTable(conductor) ? conductor : {};
2015
- const profilesRaw = conductorT.profiles === undefined ? {} : conductorT.profiles;
2016
- if (!isTable(profilesRaw))
2017
- problems.push(`"conductor.profiles" must be a table of profiles`);
2018
- const profilesT = isTable(profilesRaw) ? profilesRaw : {};
2019
- const known = [
2020
- ["project", project, ["name", "slug"]],
2021
- ["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
2022
- ["tracker.labels", labelsT, ["phase_group", "runtime_group", "runtimes"]],
2023
- ["github", github, ["repository"]],
2024
- ["gates", gatesT, ["required_checks", "local_commands"]],
2025
- [
2026
- "policy",
2027
- policyT,
2028
- [
2029
- "silence_minutes",
2030
- "silent_after_minutes",
2031
- "coordinator_minutes",
2032
- "not_started_minutes",
2033
- "plans",
2034
- "pre_approved_label",
2035
- "approval_label"
2036
- ]
2037
- ],
2038
- ["brief", briefT, ["extra"]],
2039
- ["secrets", secretsT, ["names"]],
2040
- ["conductor", conductorT, ["default_profile", "profiles", "routing"]]
2041
- ];
2042
- const profiles = {};
2043
- for (const [name, p] of Object.entries(profilesT)) {
2044
- const path = `conductor.profiles.${name}`;
2045
- if (!isTable(p)) {
2046
- problems.push(`"${path}" must be a table`);
2047
- continue;
2048
- }
2049
- if (name === "__proto__") {
2050
- problems.push(`"${path}" is not a usable profile name`);
2051
- continue;
2052
- }
2053
- known.push([path, p, ["runtime", "agent", "model", "effort", "fast_mode"]]);
2054
- if (p.fast_mode !== undefined && typeof p.fast_mode !== "boolean")
2055
- problems.push(`"${path}.fast_mode" must be true or false`);
2056
- const runtime = p.runtime ?? "conductor";
2057
- if (!PROFILE_RUNTIMES.includes(runtime))
2058
- problems.push(`"${path}.runtime" must be one of ${PROFILE_RUNTIMES.map((r) => `"${r}"`).join(", ")}`);
2059
- if (runtime === "claude-code" && p.agent !== undefined && p.agent !== "claude")
2060
- problems.push(`"${path}.agent" must be "claude" with runtime = "claude-code"`);
2061
- profiles[name] = {
2062
- runtime: PROFILE_RUNTIMES.includes(runtime) ? runtime : "conductor",
2063
- agent: str(p, path, "agent"),
2064
- model: str(p, path, "model"),
2065
- effort: str(p, path, "effort"),
2066
- fastMode: p.fast_mode === true
2067
- };
1746
+ var unescapeMarkdown = (line) => line.replace(/\\([!-/:-@[-`{-~])/g, "$1");
1747
+ var trimMarks = (v) => {
1748
+ const t = v.trim();
1749
+ return t.match(/^([*_`]+)(.+)\1$/)?.[2]?.trim() ?? t;
1750
+ };
1751
+ function parseClaim(body, at, author) {
1752
+ const line = body.split(`
1753
+ `).map(unescapeMarkdown).find((l) => /^[\s*_`>]*Agent claim\b/i.test(l));
1754
+ if (!line)
1755
+ return null;
1756
+ const field = (k) => {
1757
+ const v = line.match(new RegExp(`(?:${k})[*_\`]*\\s*:\\s*([^·|]+)`, "i"))?.[1];
1758
+ return v && trimMarks(v) || null;
1759
+ };
1760
+ return {
1761
+ runtime: field("runtime"),
1762
+ session: field("session"),
1763
+ branch: field("branch|branche"),
1764
+ startedAt: field("started|démarré|demarre"),
1765
+ profile: field("profile"),
1766
+ at,
1767
+ author
1768
+ };
1769
+ }
1770
+ function excerpt(markdown, max = 240) {
1771
+ const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
1772
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
1773
+ }
1774
+ function parsePullRequestUrl(url, title = "") {
1775
+ const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
1776
+ return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
1777
+ }
1778
+ function agentLabels(labels, groups) {
1779
+ let agentPhase = null;
1780
+ for (const l of labels)
1781
+ if (l.group === groups.phaseGroup)
1782
+ agentPhase ??= phaseNamed(l.name);
1783
+ const runtime = labels.find((l) => l.group === groups.runtimeGroup);
1784
+ return { agentPhase, agentRuntime: runtime?.name ?? null };
1785
+ }
1786
+ var sameName = (a, b) => a.toLowerCase().replace(/[^a-z0-9]/g, "") === b.toLowerCase().replace(/[^a-z0-9]/g, "");
1787
+ var phaseNamed = (name) => LABEL_PHASES.find((p) => sameName(p, name)) ?? null;
1788
+ function normalizeIssue(raw, groups) {
1789
+ const blockers = new Map;
1790
+ for (const r of raw.inverseRelations.nodes)
1791
+ if (r.type === "blocks")
1792
+ blockers.set(r.issue.identifier, { id: r.issue.identifier, statusType: r.issue.state.type });
1793
+ const prs = new Map;
1794
+ for (const a of raw.attachments.nodes) {
1795
+ const pr = parsePullRequestUrl(a.url, a.title);
1796
+ if (pr)
1797
+ prs.set(pr.url, pr);
2068
1798
  }
2069
- let defaultProfile = null;
2070
- if (conductorT.default_profile !== undefined) {
2071
- defaultProfile = str(conductorT, "conductor", "default_profile") || null;
2072
- if (defaultProfile && !Object.hasOwn(profiles, defaultProfile))
2073
- problems.push(`"conductor.default_profile" is "${defaultProfile}", but there is no [conductor.profiles.${defaultProfile}]`);
1799
+ for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
1800
+ const pr = parsePullRequestUrl(m[0]);
1801
+ if (pr && !prs.has(pr.url))
1802
+ prs.set(pr.url, pr);
2074
1803
  }
2075
- const routing = [];
2076
- const routingRaw = conductorT.routing ?? [];
2077
- if (!Array.isArray(routingRaw))
2078
- problems.push(`"conductor.routing" must be a list of [[conductor.routing]] rules`);
2079
- else
2080
- for (const [i, r] of routingRaw.entries()) {
2081
- const path = `conductor.routing[${i + 1}]`;
2082
- if (!isTable(r)) {
2083
- problems.push(`"${path}" must be a table`);
2084
- continue;
2085
- }
2086
- known.push([path, r, ["labels", "profile"]]);
2087
- const labels = r.labels;
2088
- const ok = Array.isArray(labels) && labels.length && labels.every((l) => typeof l === "string" && routingLabelKey(l));
2089
- if (!ok)
2090
- problems.push(`"${path}.labels" must be a non-empty list of Linear label names, each with a letter or digit`);
2091
- const profile = str(r, path, "profile");
2092
- if (profile && !Object.hasOwn(profiles, profile))
2093
- problems.push(`"${path}.profile" is "${profile}", but there is no [conductor.profiles.${profile}]`);
2094
- if (ok && profile)
2095
- routing.push({ labels: labels.map((l) => l.trim()), profile });
1804
+ const labels = raw.labels.nodes.map((l) => ({ name: l.name, group: l.parent?.name ?? null }));
1805
+ return {
1806
+ id: raw.identifier,
1807
+ uuid: raw.id,
1808
+ title: raw.title,
1809
+ url: raw.url,
1810
+ status: raw.state.name,
1811
+ statusType: raw.state.type,
1812
+ assignee: raw.assignee?.name ?? null,
1813
+ delegate: raw.delegate?.name ?? null,
1814
+ labels: labels.map((l) => l.name),
1815
+ ...agentLabels(labels, groups),
1816
+ parentId: raw.parent?.identifier ?? null,
1817
+ createdAt: raw.createdAt,
1818
+ updatedAt: raw.updatedAt,
1819
+ startedAt: raw.startedAt,
1820
+ completedAt: raw.completedAt,
1821
+ canceledAt: raw.canceledAt,
1822
+ blockedBy: [...blockers.values()].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
1823
+ prs: [...prs.values()].sort((a, b) => a.number - b.number)
1824
+ };
1825
+ }
1826
+ function normalizeComment(raw, issueId) {
1827
+ const author = raw.user?.name ?? null;
1828
+ return {
1829
+ id: raw.id,
1830
+ issueId,
1831
+ author,
1832
+ createdAt: raw.createdAt,
1833
+ excerpt: excerpt(raw.body, 600),
1834
+ status: parseStatusLine(raw.body),
1835
+ claim: parseClaim(raw.body, raw.createdAt, author)
1836
+ };
1837
+ }
1838
+ var MORE = {
1839
+ inverseRelations: {
1840
+ field: "inverseRelations",
1841
+ nodes: "type issue { identifier state { type } }",
1842
+ operation: "MoreRelations",
1843
+ what: "relations"
1844
+ },
1845
+ labels: { field: "labels", nodes: "name parent { name }", operation: "MoreLabels", what: "labels" },
1846
+ attachments: { field: "attachments", nodes: "title url", operation: "MoreAttachments", what: "attachments" },
1847
+ comments: {
1848
+ field: "comments",
1849
+ nodes: "id createdAt body user { name }",
1850
+ operation: "MoreComments",
1851
+ what: "comments"
1852
+ }
1853
+ };
1854
+ var MORE_QUERY = (m) => `
1855
+ query ${m.operation}($id: String!, $after: String) {
1856
+ issue(id: $id) {
1857
+ ${m.field}(first: ${m.first ?? MORE_PAGE}, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${m.nodes} } }
2096
1858
  }
2097
- if (Array.isArray(routingRaw) && routingRaw.length && conductorT.default_profile === undefined)
2098
- problems.push(`"conductor.default_profile" is required with [[conductor.routing]], for tickets no rule matches`);
2099
- for (const [path, t, keys] of known)
2100
- for (const key of Object.keys(t))
2101
- if (!keys.includes(key))
2102
- problems.push(`unknown key "${path}.${key}"`);
2103
- let runtimes = [...CONFIG_DEFAULTS.runtimes];
2104
- if (labelsT.runtimes !== undefined) {
2105
- const v = labelsT.runtimes;
2106
- if (Array.isArray(v) && v.length && v.every((x) => typeof x === "string" && x.trim()))
2107
- runtimes = [...new Set(v.map((x) => x.trim()))];
2108
- else
2109
- problems.push(`"tracker.labels.runtimes" must be a non-empty list of names`);
1859
+ }`;
1860
+ var FIELDS = (delegate) => `
1861
+ fragment F on Issue {
1862
+ id identifier title url description createdAt updatedAt startedAt completedAt canceledAt
1863
+ state { name type }
1864
+ assignee { name }
1865
+ ${delegate ? "delegate { name }" : ""}
1866
+ parent { identifier }
1867
+ labels(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.labels.nodes} } }
1868
+ attachments(first: 25) { pageInfo { hasNextPage endCursor } nodes { ${MORE.attachments.nodes} } }
1869
+ inverseRelations(first: 50) { pageInfo { hasNextPage endCursor } nodes { ${MORE.inverseRelations.nodes} } }
2110
1870
  }
2111
- const silenceKey = policyT.silence_minutes !== undefined ? "silence_minutes" : "silent_after_minutes";
2112
- if (policyT.silence_minutes !== undefined && policyT.silent_after_minutes !== undefined)
2113
- problems.push(`"policy.silent_after_minutes" is the old name of "policy.silence_minutes"; keep only one`);
2114
- let silentAfterMinutes = CONFIG_DEFAULTS.silentAfterMinutes;
2115
- if (policyT[silenceKey] !== undefined) {
2116
- const v = policyT[silenceKey];
2117
- if (typeof v === "number" && Number.isFinite(v) && v > 0)
2118
- silentAfterMinutes = v;
2119
- else
2120
- problems.push(`"policy.${silenceKey}" must be a positive number`);
1871
+ `;
1872
+ var ROOT_QUERY = (d) => `${FIELDS(d)} query Root($id: String!) { issue(id: $id) { ...F } }`;
1873
+ var CHILDREN_QUERY = (d) => `${FIELDS(d)}
1874
+ query Children($parents: [ID!], $after: String) {
1875
+ issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
1876
+ pageInfo { hasNextPage endCursor }
1877
+ nodes { ...F }
1878
+ }
1879
+ }`;
1880
+ var COMMENTS_QUERY = `
1881
+ query Comments($ids: [ID!]) {
1882
+ issues(first: 50, filter: { id: { in: $ids } }) {
1883
+ nodes { identifier comments(first: ${MAX_COMMENTS}) { pageInfo { hasNextPage endCursor } nodes { ${MORE.comments.nodes} } } }
1884
+ }
1885
+ }`;
1886
+ async function gql(opts, query, variables) {
1887
+ const doFetch = opts.fetch ?? fetch;
1888
+ const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
1889
+ const res = await doFetch(LINEAR_ENDPOINT, {
1890
+ method: "POST",
1891
+ headers: { "Content-Type": "application/json", Authorization: opts.apiKey },
1892
+ body: JSON.stringify({ query, variables }),
1893
+ signal: AbortSignal.timeout(timeoutMs)
1894
+ }).catch((err) => {
1895
+ throw new LinearError(`Linear API unreachable: ${networkReason(err, timeoutMs)}`, true);
1896
+ });
1897
+ if (res.status === 401)
1898
+ throw new LinearError("Linear rejected the API key (HTTP 401); check LINEAR_API_KEY", true);
1899
+ const json = await res.json().catch(() => ({}));
1900
+ if (json.errors?.length)
1901
+ throw new LinearError(`Linear API: ${json.errors.map((e) => e.message).join("; ")}`);
1902
+ if (!res.ok)
1903
+ throw new LinearError(`Linear API HTTP ${res.status}`, true);
1904
+ if (!json.data)
1905
+ throw new LinearError("Linear API: empty response");
1906
+ return json.data;
1907
+ }
1908
+ function networkReason(err, timeoutMs) {
1909
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
1910
+ return `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`;
1911
+ return err instanceof Error ? err.message : String(err);
1912
+ }
1913
+ var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
1914
+ var CLOSED2 = new Set(["completed", "canceled"]);
1915
+ var isCandidate = (i, rootId) => i.id !== rootId && !CLOSED2.has(i.statusType) && (i.agentPhase !== null || i.statusType === "started");
1916
+ async function readComments(opts, issues, warnings) {
1917
+ const comments = [];
1918
+ for (const batch of chunks(issues.map((i) => i.uuid), COMMENT_BATCH)) {
1919
+ const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
1920
+ for (const n of data.issues.nodes) {
1921
+ await readRest(opts, n.identifier, MORE.comments, n.comments, warnings);
1922
+ for (const c of n.comments.nodes)
1923
+ comments.push(normalizeComment(c, n.identifier));
1924
+ }
2121
1925
  }
2122
- let coordinatorMinutes = CONFIG_DEFAULTS.coordinatorMinutes;
2123
- if (policyT.coordinator_minutes !== undefined) {
2124
- const v = policyT.coordinator_minutes;
2125
- if (typeof v === "number" && Number.isFinite(v) && v > 0)
2126
- coordinatorMinutes = v;
2127
- else
2128
- problems.push(`"policy.coordinator_minutes" must be a positive number`);
1926
+ return comments;
1927
+ }
1928
+ async function fetchProgram(opts) {
1929
+ try {
1930
+ return await fetchTree(opts, true);
1931
+ } catch (err) {
1932
+ if (err instanceof LinearError && /delegate/i.test(err.message))
1933
+ return fetchTree(opts, false);
1934
+ throw err;
2129
1935
  }
2130
- let notStartedMinutes = CONFIG_DEFAULTS.notStartedMinutes;
2131
- if (policyT.not_started_minutes !== undefined) {
2132
- const v = policyT.not_started_minutes;
2133
- if (typeof v === "number" && Number.isFinite(v) && v > 0)
2134
- notStartedMinutes = v;
2135
- else
2136
- problems.push(`"policy.not_started_minutes" must be a positive number`);
1936
+ }
1937
+ async function fetchTree(opts, delegate) {
1938
+ const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
1939
+ if (!root)
1940
+ throw new LinearError(`Linear: program root ${opts.rootId} not found`);
1941
+ const all = [root];
1942
+ const warnings = [];
1943
+ let parents = [root.id];
1944
+ for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
1945
+ const next = [];
1946
+ let after = null;
1947
+ for (;; ) {
1948
+ const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
1949
+ all.push(...data.issues.nodes);
1950
+ next.push(...data.issues.nodes.map((n) => n.id));
1951
+ const { hasNextPage, endCursor } = data.issues.pageInfo;
1952
+ if (!hasNextPage)
1953
+ break;
1954
+ if (!endCursor || endCursor === after) {
1955
+ warnings.push(`issues at depth ${depth + 1}: Linear did not advance to the next page; the rest are ignored`);
1956
+ break;
1957
+ }
1958
+ after = endCursor;
1959
+ }
1960
+ parents = next;
2137
1961
  }
2138
- let plans = CONFIG_DEFAULTS.plans;
2139
- if (policyT.plans !== undefined) {
2140
- const v = policyT.plans;
2141
- if (typeof v === "string" && PLAN_POLICIES.includes(v.trim()))
2142
- plans = v.trim();
2143
- else
2144
- problems.push(`"policy.plans" must be ${PLAN_POLICIES.map((p) => `"${p}"`).join(" or ")}`);
1962
+ if (parents.length)
1963
+ warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
1964
+ for (const r of all)
1965
+ for (const field of ["inverseRelations", "labels", "attachments"])
1966
+ await readRest(opts, r.identifier, MORE[field], r[field], warnings);
1967
+ const issues = all.map((r) => normalizeIssue(r, opts.labels));
1968
+ const comments = await readComments(opts, issues.filter((i) => isCandidate(i, root.identifier)), warnings);
1969
+ return {
1970
+ rootId: root.identifier,
1971
+ fetchedAt: (opts.now?.() ?? new Date).toISOString(),
1972
+ issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
1973
+ comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
1974
+ warnings
1975
+ };
1976
+ }
1977
+ async function readRest(opts, identifier, more, conn, warnings) {
1978
+ while (conn.pageInfo?.hasNextPage) {
1979
+ const after = conn.pageInfo.endCursor;
1980
+ try {
1981
+ if (!after)
1982
+ throw new LinearError("Linear gave no cursor for the next page");
1983
+ const data = await gql(opts, MORE_QUERY(more), {
1984
+ id: identifier,
1985
+ after
1986
+ });
1987
+ const page = data.issue?.[more.field];
1988
+ if (!page)
1989
+ throw new LinearError(`Linear: issue ${identifier} not found`);
1990
+ conn.nodes.push(...page.nodes);
1991
+ conn.pageInfo = page.pageInfo;
1992
+ if (page.pageInfo?.hasNextPage && page.pageInfo.endCursor === after)
1993
+ throw new LinearError("Linear did not advance to a next page");
1994
+ } catch (err) {
1995
+ if (!(err instanceof LinearError) || err.transport)
1996
+ throw err;
1997
+ warnings.push(`${identifier}: could not read all its ${more.what} (${err.message}); some may be missing`);
1998
+ return;
1999
+ }
2145
2000
  }
2146
- const preApprovedLabel = str(policyT, "policy", "pre_approved_label", { default: CONFIG_DEFAULTS.preApprovedLabel });
2147
- const approvalLabel = str(policyT, "policy", "approval_label", { default: CONFIG_DEFAULTS.approvalLabel });
2148
- if (preApprovedLabel && approvalLabel && routingLabelKey(preApprovedLabel) === routingLabelKey(approvalLabel))
2149
- problems.push(`"policy.pre_approved_label" and "policy.approval_label" must name different labels`);
2150
- let extra = null;
2151
- if (briefT.extra !== undefined) {
2152
- const v = str(briefT, "brief", "extra");
2153
- if (v && (v.startsWith("/") || v.split(/[\\/]/).includes("..")))
2154
- problems.push(`"brief.extra" is "${v}", expected a path inside the repository, relative to ${CONFIG_FILE}`);
2155
- else if (v)
2156
- extra = v;
2001
+ }
2002
+ var CHANGED_COMMENTS_QUERY = `
2003
+ query ChangedComments($filter: CommentFilter, $after: String) {
2004
+ comments(first: ${MORE_PAGE}, after: $after, filter: $filter) {
2005
+ pageInfo { hasNextPage endCursor }
2006
+ nodes { ${MORE.comments.nodes} issue { identifier } }
2007
+ }
2008
+ }`;
2009
+
2010
+ // ../core/src/armada-api.ts
2011
+ var MASKED_LAUNCH_TOKEN = "armada_launch_••••";
2012
+ var isMaskedLaunchToken = (token) => token.includes("•");
2013
+ var MASKED_LAUNCH_TOKEN_REFUSAL = {
2014
+ error: "this is the masked token from `armada brief`'s human view, not a launch token",
2015
+ next: "ask the coordinator for the `armada brief <ticket> --prompt` text: only it carries the token"
2016
+ };
2017
+ var displayCode = (code) => code.length === 8 ? `${code.slice(0, 4)}-${code.slice(4)}` : code;
2018
+ var CLI_PACKAGE = "@the-vibe-company/armada";
2019
+ var CLI_VERSION_HEADER = "x-armada-cli-version";
2020
+ var CLI_MINIMUM_HEADER = "x-armada-cli-minimum";
2021
+ var CLI_LATEST_HEADER = "x-armada-cli-latest";
2022
+ function compareVersions(a, b) {
2023
+ const parts = (v) => v.split(/[-+]/)[0]?.split(".").map((n) => Number.parseInt(n, 10) || 0) ?? [];
2024
+ const [x, y] = [parts(a), parts(b)];
2025
+ for (let i = 0;i < Math.max(x.length, y.length); i++) {
2026
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
2027
+ if (d)
2028
+ return Math.sign(d);
2157
2029
  }
2158
- let secretNames = [];
2159
- if (secretsT.names !== undefined) {
2160
- const v = secretsT.names;
2161
- if (Array.isArray(v) && v.every((n) => typeof n === "string" && !secretNameRefusal(n.trim())))
2162
- secretNames = [...new Set(v.map((n) => n.trim()))];
2163
- else
2164
- problems.push(`"secrets.names" must be a list of secret names in upper snake case, e.g. ["OPENAI_API_KEY"], none of Armada's own keys`);
2030
+ return 0;
2031
+ }
2032
+ var versionToInstall = (minimum, latest) => latest && compareVersions(latest, minimum) >= 0 ? latest : minimum;
2033
+ var installCommand = (version) => `npm install -g ${CLI_PACKAGE}@${version}`;
2034
+ var upgradeLine = (version, install) => `Armada ${version} is older than this server expects: ${installCommand(install)}`;
2035
+ var releaseNotesUrl = (version) => `https://github.com/The-Vibe-Company/armada/releases/tag/v${version}`;
2036
+ var newerRelease = (running, latest) => latest && running !== "0.0.0" && compareVersions(latest, running) > 0 ? latest : null;
2037
+ var releaseLine = (running, latest) => `Armada ${latest} is out (you run ${running}): ${installCommand(latest)} — then armada init to refresh this project's skills. Changes: ${releaseNotesUrl(latest)}`;
2038
+
2039
+ class ArmadaApiError extends Error {
2040
+ next;
2041
+ signedOut;
2042
+ status;
2043
+ upgrade;
2044
+ constructor(message, next = null, signedOut = false, status = null, upgrade = null) {
2045
+ super(message);
2046
+ this.next = next;
2047
+ this.signedOut = signedOut;
2048
+ this.status = status;
2049
+ this.upgrade = upgrade;
2165
2050
  }
2166
- let requiredChecks = [];
2167
- if (gatesT.required_checks !== undefined) {
2168
- const v = gatesT.required_checks;
2169
- if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
2170
- requiredChecks = [...new Set(v.map((c) => c.trim()))];
2171
- else
2172
- problems.push(`"gates.required_checks" must be a list of check names`);
2051
+ }
2052
+ var LOGIN_NEXT = "armada login";
2053
+ var TIMEOUT_MS = 30000;
2054
+ function apiBaseUrl(value) {
2055
+ let url;
2056
+ try {
2057
+ url = new URL(value);
2058
+ } catch {
2059
+ throw new ArmadaApiError(`the Armada API address "${value}" is not a URL`, "ARMADA_API_URL or [api] url in config.toml");
2173
2060
  }
2174
- let localCommands = [];
2175
- if (gatesT.local_commands !== undefined) {
2176
- const v = gatesT.local_commands;
2177
- if (Array.isArray(v) && v.every((c) => typeof c === "string" && c.trim()))
2178
- localCommands = v.map((c) => c.trim());
2179
- else
2180
- problems.push(`"gates.local_commands" must be a list of shell commands`);
2061
+ if (url.protocol !== "https:" && url.protocol !== "http:")
2062
+ throw new ArmadaApiError(`the Armada API address must be http or https, not ${url.protocol}`);
2063
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
2064
+ throw new ArmadaApiError(`the Armada API address must use https (http only reaches localhost): ${url.origin}`, "ARMADA_API_URL or [api] url in config.toml");
2065
+ url.search = "";
2066
+ url.hash = "";
2067
+ if (!url.pathname.endsWith("/"))
2068
+ url.pathname += "/";
2069
+ return url;
2070
+ }
2071
+ function armadaApi(opts) {
2072
+ const base = apiBaseUrl(opts.url);
2073
+ const doFetch = opts.fetch ?? fetch;
2074
+ const timeoutMs = opts.timeoutMs ?? TIMEOUT_MS;
2075
+ const host = base.host;
2076
+ let serverCli = null;
2077
+ async function call(method, path, init = {}) {
2078
+ const limit = init.timeoutMs ?? timeoutMs;
2079
+ const headers = { Accept: "application/json" };
2080
+ if (init.body)
2081
+ headers["Content-Type"] = "application/json";
2082
+ if (init.signIn?.kind === "session" || init.signIn?.kind === "worker")
2083
+ headers.Authorization = `Bearer ${init.signIn.token}`;
2084
+ if (init.signIn?.kind === "api-key")
2085
+ headers["x-api-key"] = init.signIn.key;
2086
+ if (opts.version)
2087
+ headers[CLI_VERSION_HEADER] = opts.version;
2088
+ const res = await doFetch(new URL(`api/cli/${path}`, base).toString(), {
2089
+ method,
2090
+ headers,
2091
+ ...init.body ? { body: JSON.stringify(init.body) } : {},
2092
+ signal: AbortSignal.timeout(limit)
2093
+ }).catch((err) => {
2094
+ throw new ArmadaApiError(`Armada (${host}) unreachable: ${networkReason(err, limit)}`, "the same command again once it answers, or check ARMADA_API_URL");
2095
+ });
2096
+ const minimum = res.headers.get(CLI_MINIMUM_HEADER);
2097
+ const latest = res.headers.get(CLI_LATEST_HEADER) || null;
2098
+ if (minimum) {
2099
+ serverCli = { minimum, latest };
2100
+ opts.onServerCli?.(serverCli);
2101
+ }
2102
+ if (opts.version && minimum && compareVersions(opts.version, minimum) < 0) {
2103
+ await res.body?.cancel().catch(() => {});
2104
+ const install = versionToInstall(minimum, latest);
2105
+ throw new ArmadaApiError(upgradeLine(opts.version, install), null, false, res.status, install);
2106
+ }
2107
+ if (res.status === 304)
2108
+ return { status: 304, body: {} };
2109
+ const body = await res.json().catch(() => null);
2110
+ if (typeof body !== "object" || body === null || Array.isArray(body))
2111
+ 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");
2112
+ return { status: res.status, body };
2181
2113
  }
2182
- const config = {
2183
- project: {
2184
- name: str(project, "project", "name"),
2185
- slug: str(project, "project", "slug", { pattern: SLUG, hint: "lowercase letters, digits and dashes" })
2114
+ const refusal = (status, body, what) => {
2115
+ const error = typeof body.error === "string" ? body.error : `HTTP ${status}`;
2116
+ const next = typeof body.next === "string" ? body.next : status === 401 ? LOGIN_NEXT : null;
2117
+ return new ArmadaApiError(what ? `${what}: ${error}` : error, next, status === 401, status);
2118
+ };
2119
+ return {
2120
+ serverCli: () => serverCli,
2121
+ async startDeviceLogin() {
2122
+ const { status, body } = await call("POST", "device/code");
2123
+ if (status !== 200)
2124
+ throw refusal(status, body, "Armada refused to start the sign-in");
2125
+ const str = (k) => typeof body[k] === "string" ? body[k] : "";
2126
+ const num = (k, d) => typeof body[k] === "number" && body[k] > 0 ? body[k] : d;
2127
+ if (!str("device_code") || !str("user_code") || !str("verification_uri"))
2128
+ throw new ArmadaApiError(`Armada (${host}) answered the sign-in without a code`);
2129
+ return {
2130
+ deviceCode: str("device_code"),
2131
+ userCode: str("user_code"),
2132
+ verificationUri: str("verification_uri"),
2133
+ verificationUriComplete: str("verification_uri_complete") || str("verification_uri"),
2134
+ expiresInSeconds: num("expires_in", 900),
2135
+ intervalSeconds: num("interval", 5)
2136
+ };
2137
+ },
2138
+ async pollDeviceLogin(deviceCode) {
2139
+ const { status, body } = await call("POST", "device/token", { body: { device_code: deviceCode } });
2140
+ if (status === 200 && typeof body.access_token === "string" && body.access_token)
2141
+ return { state: "approved", token: body.access_token };
2142
+ switch (body.error) {
2143
+ case "authorization_pending":
2144
+ return { state: "pending" };
2145
+ case "slow_down":
2146
+ return { state: "slow-down" };
2147
+ case "access_denied":
2148
+ return { state: "denied" };
2149
+ case "expired_token":
2150
+ case "invalid_grant":
2151
+ return { state: "expired" };
2152
+ }
2153
+ throw refusal(status, body, "Armada refused the sign-in");
2154
+ },
2155
+ async whoami(signIn) {
2156
+ const { status, body } = await call("GET", "session", { signIn });
2157
+ if (status !== 200)
2158
+ throw refusal(status, body, status === 401 ? null : "Armada could not say who is signed in");
2159
+ return body;
2160
+ },
2161
+ async credentials(signIn, purpose = null) {
2162
+ const { status, body } = await call("POST", "credentials", { signIn, body: purpose ? { purpose } : {} });
2163
+ if (status !== 200)
2164
+ throw refusal(status, body, status === 401 ? null : "Armada gave no keys");
2165
+ const str = (v) => typeof v === "string" && v.length > 0;
2166
+ const org = body.organization;
2167
+ const linear = body.linear;
2168
+ const shaped = body.schemaVersion === 1 && str(org?.id) && (linear === null || str(linear?.apiKey));
2169
+ if (!shaped)
2170
+ throw new ArmadaApiError(`Armada (${host}) answered the keys in a shape this CLI does not know`);
2171
+ const warnings = Array.isArray(body.warnings) ? body.warnings.filter((w) => typeof w === "string") : [];
2172
+ const scope = linear?.scope === "own" || linear?.scope === "project" ? linear.scope : "organization";
2173
+ return {
2174
+ schemaVersion: 1,
2175
+ organization: org,
2176
+ linear: linear ? { apiKey: linear.apiKey, scope } : null,
2177
+ warnings
2178
+ };
2186
2179
  },
2187
- tracker: {
2188
- programRoot: str(tracker, "tracker", "program_root", {
2189
- pattern: ISSUE_ID,
2190
- hint: "an issue identifier such as ABC-1"
2191
- }),
2192
- language: str(tracker, "tracker", "language", { default: CONFIG_DEFAULTS.language }),
2193
- readyLabel: str(tracker, "tracker", "ready_label", { default: CONFIG_DEFAULTS.readyLabel }),
2194
- labels: {
2195
- phaseGroup: str(labelsT, "tracker.labels", "phase_group", { default: CONFIG_DEFAULTS.phaseGroup }),
2196
- runtimeGroup: str(labelsT, "tracker.labels", "runtime_group", { default: CONFIG_DEFAULTS.runtimeGroup }),
2197
- runtimes
2198
- }
2180
+ async projects(signIn) {
2181
+ const { status, body } = await call("GET", "projects", { signIn });
2182
+ if (status !== 200)
2183
+ throw refusal(status, body, status === 401 ? null : "Armada did not list the projects");
2184
+ if (!Array.isArray(body.projects))
2185
+ throw new ArmadaApiError(`Armada (${host}) answered the projects in a shape this CLI does not know`);
2186
+ return body.projects.flatMap((p) => typeof p.slug === "string" && typeof p.name === "string" && typeof p.repository === "string" && typeof p.programRoot === "string" ? [
2187
+ {
2188
+ slug: p.slug,
2189
+ name: p.name,
2190
+ repository: p.repository,
2191
+ programRoot: p.programRoot,
2192
+ ...p.ownLinearKey === true ? { ownLinearKey: true } : {}
2193
+ }
2194
+ ] : []);
2199
2195
  },
2200
- github: {
2201
- repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
2196
+ async fleet(signIn, op, body, timeoutMs) {
2197
+ const { status, body: answer } = await call("POST", `fleet/${op}`, {
2198
+ signIn,
2199
+ body,
2200
+ ...timeoutMs ? { timeoutMs } : {}
2201
+ });
2202
+ if (status === 304)
2203
+ return null;
2204
+ if (status !== 200)
2205
+ throw refusal(status, answer, status === 401 ? null : "Armada refused");
2206
+ if (!("result" in answer))
2207
+ throw new ArmadaApiError(`Armada (${host}) answered fleet/${op} in a shape this CLI does not know`);
2208
+ return answer.result;
2202
2209
  },
2203
- gates: { requiredChecks, localCommands },
2204
- policy: { silentAfterMinutes, coordinatorMinutes, notStartedMinutes, plans, preApprovedLabel, approvalLabel },
2205
- brief: { extra },
2206
- secrets: { names: secretNames },
2207
- conductor: { defaultProfile, profiles, routing }
2210
+ async listSecrets(signIn, project) {
2211
+ const { status, body } = await call("POST", "secrets/list", { signIn, body: { project } });
2212
+ if (status !== 200)
2213
+ throw refusal(status, body, status === 401 ? null : "Armada did not list the secrets");
2214
+ if (!Array.isArray(body.secrets))
2215
+ throw new ArmadaApiError(`Armada (${host}) answered the secrets in a shape this CLI does not know`);
2216
+ return body.secrets.flatMap((s) => typeof s.name === "string" && typeof s.setBy === "string" && typeof s.setAt === "string" ? [
2217
+ {
2218
+ name: s.name,
2219
+ scope: s.scope === "organization" ? "organization" : "project",
2220
+ setBy: s.setBy,
2221
+ setAt: s.setAt,
2222
+ overridden: s.overridden === true
2223
+ }
2224
+ ] : []);
2225
+ },
2226
+ async releaseSecrets(signIn, project, names = null) {
2227
+ const { status, body } = await call("POST", "secrets/release", { signIn, body: { project, names } });
2228
+ if (status !== 200)
2229
+ throw refusal(status, body, status === 401 ? null : "Armada gave no secrets");
2230
+ const secrets = Array.isArray(body.secrets) ? body.secrets : null;
2231
+ if (!secrets?.every((s) => typeof s.name === "string" && typeof s.value === "string"))
2232
+ throw new ArmadaApiError(`Armada (${host}) answered the secrets in a shape this CLI does not know`);
2233
+ const strings = (v) => Array.isArray(v) ? v.filter((w) => typeof w === "string") : [];
2234
+ return {
2235
+ project: typeof body.project === "string" ? body.project : project.slug,
2236
+ secrets: secrets.map((s) => ({
2237
+ name: String(s.name),
2238
+ value: String(s.value),
2239
+ scope: s.scope === "organization" ? "organization" : "project"
2240
+ })),
2241
+ missing: strings(body.missing),
2242
+ warnings: strings(body.warnings)
2243
+ };
2244
+ },
2245
+ async setSecret(signIn, target) {
2246
+ const { status, body } = await call("POST", "secrets/set", { signIn, body: target });
2247
+ if (status !== 200)
2248
+ throw refusal(status, body, status === 401 ? null : `Armada did not set ${target.name}`);
2249
+ },
2250
+ async unsetSecret(signIn, target) {
2251
+ const { status, body } = await call("POST", "secrets/unset", { signIn, body: target });
2252
+ if (status !== 200)
2253
+ throw refusal(status, body, status === 401 ? null : `Armada did not unset ${target.name}`);
2254
+ return body.deleted === true;
2255
+ },
2256
+ async launchToken(signIn, target) {
2257
+ const { status, body } = await call("POST", "launch-tokens", { signIn, body: target });
2258
+ if (status !== 200)
2259
+ throw refusal(status, body, status === 401 ? null : "Armada made no launch token");
2260
+ const w = body.worker;
2261
+ if (typeof body.token !== "string" || typeof body.expiresAt !== "string" || !w?.ticket)
2262
+ throw new ArmadaApiError(`Armada (${host}) answered the launch token in a shape this CLI does not know`);
2263
+ return body;
2264
+ },
2265
+ async exchangeLaunchToken(token, handle = null) {
2266
+ const { status, body } = await call("POST", "launch-tokens/exchange", {
2267
+ body: handle ? { token, handle } : { token }
2268
+ });
2269
+ if (status !== 200)
2270
+ throw refusal(status, body, null);
2271
+ const w = body.worker;
2272
+ const org = body.organization;
2273
+ if (typeof body.token !== "string" || !w?.ticket || !w.project || !org?.id)
2274
+ throw new ArmadaApiError(`Armada (${host}) answered the launch token in a shape this CLI does not know`);
2275
+ return body;
2276
+ },
2277
+ async endWorkers(signIn, target) {
2278
+ const { status, body } = await call("POST", "workers/end", { signIn, body: target });
2279
+ if (status !== 200)
2280
+ throw refusal(status, body, "Armada did not end the ticket's workers");
2281
+ return typeof body.ended === "number" ? body.ended : 0;
2282
+ },
2283
+ async signOut(signIn) {
2284
+ const { status, body } = await call("DELETE", "session", { signIn });
2285
+ if (status !== 200)
2286
+ throw refusal(status, body, "Armada refused the sign-out");
2287
+ }
2208
2288
  };
2209
- if (problems.length)
2210
- throw new ConfigError(source, problems);
2211
- config.tracker.programRoot = config.tracker.programRoot.toUpperCase();
2212
- return config;
2213
- }
2214
- function configTemplate(p) {
2215
- const q = JSON.stringify;
2216
- return `# Armada configuration: one project = one repository + one tracker program root.
2217
- # No secrets here: keys come from the environment or \`armada auth login\`.
2218
-
2219
- [project]
2220
- name = ${q(p.name)}
2221
- slug = ${q(p.slug)} # stable id: lowercase letters, digits and dashes
2222
-
2223
- [tracker]
2224
- program_root = ${q(p.programRoot)} # Linear issue at the root of the program
2225
- language = "en" # language of owner-facing output
2226
- ready_label = "ready-for-agent"
2227
-
2228
- [tracker.labels]
2229
- phase_group = "Agent phase"
2230
- runtime_group = "Agent runtime"
2231
- runtimes = ["Claude Code", "Codex", "Conductor"]
2232
-
2233
- [github]
2234
- repository = ${q(p.repository)}
2235
-
2236
- [gates]
2237
- # required_checks = ["test"] # CI checks that must be green before a hand-back (default: every check)
2238
-
2239
- [policy]
2240
- silence_minutes = 15 # a worker with no report for longer than this shows as silent
2241
- coordinator_minutes = 10 # an inbox item open longer than this shows "waiting for the coordinator"
2242
- # not_started_minutes = 10 # a launched worker that has not claimed after this long shows as not started
2243
- # plans = "approve" # or "pre-approved": workers post their plan and go on without waiting
2244
- # pre_approved_label = "plan-approved" # a ticket with this label skips the approval
2245
- # approval_label = "needs-plan-approval" # a ticket with this label waits for it; wins over the other
2246
-
2247
- [brief]
2248
- # extra = "docs/worker-conventions.md" # a file every worker brief carries under "Project conventions"
2249
-
2250
- # How \`armada brief\` launches workers on Conductor. Every value is passed explicitly;
2251
- # \`conductor model\` lists each agent's model ids and effort levels.
2252
- [conductor]
2253
- default_profile = "opus" # for tickets no routing rule matches
2254
-
2255
- [conductor.profiles.opus]
2256
- agent = "claude"
2257
- model = "opus-5-5-1m"
2258
- effort = "high"
2259
-
2260
- [conductor.profiles.codex]
2261
- agent = "codex"
2262
- model = "gpt-6.1-sol"
2263
- effort = "high"
2264
-
2265
- [conductor.profiles.debug]
2266
- agent = "codex"
2267
- model = "gpt-6.1-sol"
2268
- effort = "xhigh"
2269
-
2270
- # A worker run as a subagent of a coordinator's Claude Code session, in its own
2271
- # worktree (the armada-runtime-claude-code skill). It dies with that session, so
2272
- # long runs belong on Conductor. \`model\` is what the Agent tool takes; it applies no effort.
2273
- # [conductor.profiles.local]
2274
- # runtime = "claude-code"
2275
- # agent = "claude"
2276
- # model = "opus"
2277
- # effort = "high"
2278
-
2279
- # Which profile a ticket gets from its Linear labels: the first rule with a label
2280
- # the ticket carries wins, in file order. \`armada brief --profile\` overrides it.
2281
- [[conductor.routing]]
2282
- labels = ["web"]
2283
- profile = "opus"
2284
-
2285
- [[conductor.routing]]
2286
- labels = ["api"]
2287
- profile = "codex"
2288
-
2289
- [[conductor.routing]]
2290
- labels = ["Bug"]
2291
- profile = "debug"
2292
- `;
2293
2289
  }
2294
- function slugify(name) {
2295
- return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "project";
2290
+ async function waitForApproval({ api, code, sleep, now }) {
2291
+ const deadline = now().getTime() + code.expiresInSeconds * 1000;
2292
+ let interval = code.intervalSeconds * 1000;
2293
+ for (;; ) {
2294
+ await sleep(interval);
2295
+ if (now().getTime() > deadline)
2296
+ break;
2297
+ let poll;
2298
+ try {
2299
+ poll = await api.pollDeviceLogin(code.deviceCode);
2300
+ } catch (err) {
2301
+ if (!(err instanceof ArmadaApiError) || !/unreachable/.test(err.message))
2302
+ throw err;
2303
+ interval = Math.min(interval * 2, 60000);
2304
+ continue;
2305
+ }
2306
+ if (poll.state === "approved")
2307
+ return poll.token;
2308
+ if (poll.state === "denied")
2309
+ throw new ArmadaApiError("the sign-in was denied in the browser", LOGIN_NEXT);
2310
+ if (poll.state === "expired")
2311
+ break;
2312
+ if (poll.state === "slow-down")
2313
+ interval += 5000;
2314
+ }
2315
+ throw new ArmadaApiError("the code expired before it was approved", LOGIN_NEXT);
2296
2316
  }
2297
-
2298
2317
  // ../core/src/phases.ts
2299
2318
  var TRANSITIONS = {
2300
2319
  planning: ["awaiting-approval", "implementing"],
@@ -3343,21 +3362,6 @@ function updateDotenv(text, updates) {
3343
3362
  `)}
3344
3363
  ` : "";
3345
3364
  }
3346
- // ../core/src/live.ts
3347
- import { createHash } from "node:crypto";
3348
- var LAUNCH_WINDOW_MS = 24 * 60 * 60000;
3349
- var MIN2 = 60000;
3350
- var REWRITTEN = ["hand-back", "plan"];
3351
- var digest = (text) => createHash("sha256").update(text).digest("base64url").slice(0, 12);
3352
- var entryKey = (e) => e.id !== null ? REWRITTEN.includes(e.kind) ? `#${e.id}@${digest(e.body)}` : `#${e.id}` : e.version ? `version:${e.version}` : `${e.kind}:${e.ticket}`;
3353
- var hhmm = (iso) => `${iso.slice(11, 16)} UTC`;
3354
- function notStartedBody(l, now) {
3355
- const minutes = Math.floor((now.getTime() - Date.parse(l.launchedAt)) / MIN2);
3356
- const why = l.tokenUsedAt ? `the worker signed in with its launch token at ${hhmm(l.tokenUsedAt)}, then stopped before \`armada claim\`` : "its launch token was never used: the worker never reached its `armada login` line (an install that failed, a prompt cut short)";
3357
- return `launched ${minutes} min ago and never claimed; ${why}${l.handle ? ` (session ${l.handle})` : ""}. Check its session with the runtime guide's status section; launch it again with armada brief, or revoke the launch on the dashboard's Workers page`;
3358
- }
3359
- var notStartedLaunches = (launches, now, minutes) => launches.filter((l) => now.getTime() - Date.parse(l.launchedAt) > minutes * MIN2);
3360
-
3361
3365
  // ../core/src/fleet-api.ts
3362
3366
  var WORKER_FLEET_OPS = ["claim", "report", "ask", "release"];
3363
3367
  var FLEET_OPS = [
@@ -5085,6 +5089,8 @@ function outcome(c, merged, pr, lines, workers, archive) {
5085
5089
  warnings: c.warnings
5086
5090
  };
5087
5091
  }
5092
+ // ../core/src/timeline.ts
5093
+ var SAME_REPORT_MS = 2 * 60000;
5088
5094
  // ../core/src/projects.ts
5089
5095
  var message = (err) => err instanceof Error ? err.message : String(err);
5090
5096
  async function readProjectConfig(p, opts) {
@@ -5736,7 +5742,8 @@ function buildStatus({
5736
5742
  title: p.title,
5737
5743
  draft: p.draft ?? null,
5738
5744
  ci: p.ci ?? null,
5739
- mergeable: p.mergeable ?? null
5745
+ mergeable: p.mergeable ?? null,
5746
+ createdAt: p.createdAt ?? null
5740
5747
  });
5741
5748
  return {
5742
5749
  schemaVersion: STATUS_SCHEMA_VERSION,
@@ -5846,7 +5853,7 @@ async function loadStatus(config, opts) {
5846
5853
  });
5847
5854
  }
5848
5855
  // package.json
5849
- var version = "0.2.13";
5856
+ var version = "0.2.15";
5850
5857
 
5851
5858
  // src/api.ts
5852
5859
  var runs = new WeakMap;