@the-vibe-company/armada 0.2.27 → 0.2.28

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