@the-vibe-company/armada 0.0.0

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +116 -0
  3. package/dist/armada.js +2600 -0
  4. package/package.json +40 -0
package/dist/armada.js ADDED
@@ -0,0 +1,2600 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/main.ts
4
+ import { spawnSync } from "node:child_process";
5
+ import { readFile as readFile2 } from "node:fs/promises";
6
+
7
+ // src/cli.ts
8
+ import { dirname, join as join2, resolve } from "node:path";
9
+
10
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js
11
+ /*!
12
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
13
+ * SPDX-License-Identifier: BSD-3-Clause
14
+ *
15
+ * Redistribution and use in source and binary forms, with or without
16
+ * modification, are permitted provided that the following conditions are met:
17
+ *
18
+ * 1. Redistributions of source code must retain the above copyright notice, this
19
+ * list of conditions and the following disclaimer.
20
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
21
+ * this list of conditions and the following disclaimer in the
22
+ * documentation and/or other materials provided with the distribution.
23
+ * 3. Neither the name of the copyright holder nor the names of its contributors
24
+ * may be used to endorse or promote products derived from this software without
25
+ * specific prior written permission.
26
+ *
27
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
28
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
29
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
30
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
31
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
33
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
35
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37
+ */
38
+ function getLineColFromPtr(string, ptr) {
39
+ let lines = string.slice(0, ptr).split(/\r?\n/);
40
+ return [lines.length, lines.pop().length + 1];
41
+ }
42
+ function makeCodeBlock(string, line, column) {
43
+ let lines = string.split(/\r?\n/);
44
+ let codeblock = "";
45
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
46
+ for (let i = line - 1;i <= line + 1; i++) {
47
+ let l = lines[i - 1];
48
+ if (!l)
49
+ continue;
50
+ codeblock += i.toString().padEnd(numberLen, " ");
51
+ codeblock += ": ";
52
+ codeblock += l;
53
+ codeblock += `
54
+ `;
55
+ if (i === line) {
56
+ codeblock += " ".repeat(numberLen + column + 2);
57
+ codeblock += `^
58
+ `;
59
+ }
60
+ }
61
+ return codeblock;
62
+ }
63
+
64
+ class TomlError extends Error {
65
+ line;
66
+ column;
67
+ codeblock;
68
+ constructor(message, options) {
69
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
70
+ const codeblock = makeCodeBlock(options.toml, line, column);
71
+ super(`Invalid TOML document: ${message}
72
+
73
+ ${codeblock}`, options);
74
+ this.line = line;
75
+ this.column = column;
76
+ this.codeblock = codeblock;
77
+ }
78
+ static x(message, ctx, ptr) {
79
+ throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });
80
+ }
81
+ }
82
+
83
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/primitive.js
84
+ /*!
85
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
86
+ * SPDX-License-Identifier: BSD-3-Clause
87
+ *
88
+ * Redistribution and use in source and binary forms, with or without
89
+ * modification, are permitted provided that the following conditions are met:
90
+ *
91
+ * 1. Redistributions of source code must retain the above copyright notice, this
92
+ * list of conditions and the following disclaimer.
93
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
94
+ * this list of conditions and the following disclaimer in the
95
+ * documentation and/or other materials provided with the distribution.
96
+ * 3. Neither the name of the copyright holder nor the names of its contributors
97
+ * may be used to endorse or promote products derived from this software without
98
+ * specific prior written permission.
99
+ *
100
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
101
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
102
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
103
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
104
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
105
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
106
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
107
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
108
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
109
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
110
+ */
111
+ function parseString(ctx) {
112
+ let startPtr = ctx.p;
113
+ let c = ctx.s.charCodeAt(ctx.p++);
114
+ let first = c;
115
+ let isLiteral = c === 39;
116
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
117
+ if (isMultiline) {
118
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
119
+ ctx.p++;
120
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
121
+ ctx.p += 2;
122
+ }
123
+ let parsed = "";
124
+ let sliceStart = ctx.p;
125
+ let state = 0;
126
+ for (;ctx.p < ctx.s.length; ctx.p++) {
127
+ c = ctx.s.charCodeAt(ctx.p);
128
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
129
+ state = state && 3;
130
+ } else if (c < 32 && c !== 9 || c === 127) {
131
+ TomlError.x("control characters are not allowed in strings", ctx);
132
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
133
+ if (isMultiline) {
134
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
135
+ ctx.p++;
136
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
137
+ ctx.p++;
138
+ }
139
+ if (!state) {
140
+ let s = ctx.s.slice(sliceStart, ctx.p);
141
+ parsed = parsed ? parsed + s : s;
142
+ }
143
+ ctx.p += isMultiline ? 3 : 1;
144
+ return parsed;
145
+ } else if (!state) {
146
+ if (!isLiteral && c === 92) {
147
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
148
+ state = 1;
149
+ }
150
+ } else if (state === 1) {
151
+ if (c === 120 || c === 117 || c === 85) {
152
+ let errPtr = ctx.p++ - 1;
153
+ let value = 0;
154
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
155
+ for (let j = 0;j < len; j++, ctx.p++) {
156
+ let hex = ctx.s.charCodeAt(ctx.p);
157
+ let digit = hex >= 48 && hex <= 57 ? hex - 48 : hex >= 65 && hex <= 70 ? hex - 65 + 10 : hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1;
158
+ if (digit < 0)
159
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
160
+ value = value << 4 | digit;
161
+ }
162
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
163
+ TomlError.x("invalid unicode escape", ctx, errPtr);
164
+ }
165
+ parsed += String.fromCodePoint(value);
166
+ sliceStart = ctx.p--;
167
+ state = 0;
168
+ } else if (isMultiline && (c === 32 || c === 9)) {
169
+ state = 2;
170
+ } else {
171
+ if (c === 98)
172
+ parsed += "\b";
173
+ else if (c === 116)
174
+ parsed += "\t";
175
+ else if (c === 110)
176
+ parsed += `
177
+ `;
178
+ else if (c === 102)
179
+ parsed += "\f";
180
+ else if (c === 114)
181
+ parsed += "\r";
182
+ else if (c === 101)
183
+ parsed += "\x1B";
184
+ else if (c === 34)
185
+ parsed += '"';
186
+ else if (c === 92)
187
+ parsed += "\\";
188
+ else
189
+ TomlError.x("unrecognised escape sequence", ctx);
190
+ sliceStart = ctx.p + 1;
191
+ state = 0;
192
+ }
193
+ } else if (c !== 32 && c !== 9) {
194
+ if (state === 2)
195
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
196
+ state = !isLiteral && c === 92 ? 1 : 0;
197
+ sliceStart = ctx.p;
198
+ }
199
+ }
200
+ TomlError.x("unfinished string", ctx, startPtr);
201
+ }
202
+
203
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/date.js
204
+ /*!
205
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
206
+ * SPDX-License-Identifier: BSD-3-Clause
207
+ *
208
+ * Redistribution and use in source and binary forms, with or without
209
+ * modification, are permitted provided that the following conditions are met:
210
+ *
211
+ * 1. Redistributions of source code must retain the above copyright notice, this
212
+ * list of conditions and the following disclaimer.
213
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
214
+ * this list of conditions and the following disclaimer in the
215
+ * documentation and/or other materials provided with the distribution.
216
+ * 3. Neither the name of the copyright holder nor the names of its contributors
217
+ * may be used to endorse or promote products derived from this software without
218
+ * specific prior written permission.
219
+ *
220
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
221
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
222
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
223
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
224
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
225
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
226
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
227
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
228
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
229
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
230
+ */
231
+ 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;
232
+
233
+ class TomlDate extends Date {
234
+ #hasDate = false;
235
+ #hasTime = false;
236
+ #offset = null;
237
+ constructor(date, fasttype, unsafeDelim) {
238
+ let hasDate = true;
239
+ let hasTime = true;
240
+ let offset = "Z";
241
+ let c;
242
+ if (typeof date === "string") {
243
+ if (fasttype)
244
+ prep: {
245
+ if (fasttype < 3) {
246
+ if (+date.slice(11, 13) > 23) {
247
+ date = "";
248
+ break prep;
249
+ }
250
+ if (fasttype === 2) {
251
+ offset = null;
252
+ date += "Z";
253
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
254
+ offset = date.slice(date.length - 6);
255
+ }
256
+ if (unsafeDelim)
257
+ date = date.slice(0, 10) + "T" + date.slice(11);
258
+ } else if (fasttype === 4) {
259
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
260
+ }
261
+ hasDate = fasttype !== 4;
262
+ hasTime = fasttype !== 3;
263
+ }
264
+ else {
265
+ let match = date.match(DATE_TIME_RE);
266
+ if (match) {
267
+ if (!match[1]) {
268
+ hasDate = false;
269
+ date = `0000-01-01T${date}`;
270
+ }
271
+ hasTime = !!match[2];
272
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
273
+ if (match[2] && +match[2] > 23) {
274
+ date = "";
275
+ } else {
276
+ offset = match[3] || null;
277
+ if (!offset && hasTime)
278
+ date += "Z";
279
+ }
280
+ } else {
281
+ date = "";
282
+ }
283
+ }
284
+ }
285
+ super(date);
286
+ if (!isNaN(this.getTime())) {
287
+ this.#hasDate = hasDate;
288
+ this.#hasTime = hasTime;
289
+ this.#offset = offset;
290
+ }
291
+ }
292
+ isDateTime() {
293
+ return this.#hasDate && this.#hasTime;
294
+ }
295
+ isLocal() {
296
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
297
+ }
298
+ isDate() {
299
+ return this.#hasDate && !this.#hasTime;
300
+ }
301
+ isTime() {
302
+ return this.#hasTime && !this.#hasDate;
303
+ }
304
+ isValid() {
305
+ return this.#hasDate || this.#hasTime;
306
+ }
307
+ toISOString() {
308
+ let iso = super.toISOString();
309
+ if (this.isDate())
310
+ return iso.slice(0, 10);
311
+ if (this.isTime())
312
+ return iso.slice(11, 23);
313
+ if (this.#offset === null)
314
+ return iso.slice(0, -1);
315
+ if (this.#offset === "Z" || this.#offset === "z")
316
+ return iso;
317
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
318
+ offset = this.#offset[0] === "-" ? offset : -offset;
319
+ let offsetDate = new Date(this.getTime() - offset * 60000);
320
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
321
+ }
322
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
323
+ let date = new TomlDate(jsDate);
324
+ date.#offset = offset;
325
+ return date;
326
+ }
327
+ static wrapAsLocalDateTime(jsDate) {
328
+ let date = new TomlDate(jsDate);
329
+ date.#offset = null;
330
+ return date;
331
+ }
332
+ static wrapAsLocalDate(jsDate) {
333
+ let date = new TomlDate(jsDate);
334
+ date.#hasTime = false;
335
+ date.#offset = null;
336
+ return date;
337
+ }
338
+ static wrapAsLocalTime(jsDate) {
339
+ let date = new TomlDate(jsDate);
340
+ date.#hasDate = false;
341
+ date.#offset = null;
342
+ return date;
343
+ }
344
+ }
345
+
346
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/extract.js
347
+ /*!
348
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
349
+ * SPDX-License-Identifier: BSD-3-Clause
350
+ *
351
+ * Redistribution and use in source and binary forms, with or without
352
+ * modification, are permitted provided that the following conditions are met:
353
+ *
354
+ * 1. Redistributions of source code must retain the above copyright notice, this
355
+ * list of conditions and the following disclaimer.
356
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
357
+ * this list of conditions and the following disclaimer in the
358
+ * documentation and/or other materials provided with the distribution.
359
+ * 3. Neither the name of the copyright holder nor the names of its contributors
360
+ * may be used to endorse or promote products derived from this software without
361
+ * specific prior written permission.
362
+ *
363
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
364
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
365
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
366
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
367
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
368
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
369
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
370
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
371
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
372
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
373
+ */
374
+ function isDigit(char, base = 10) {
375
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
376
+ }
377
+ function isEndOfValue(char, delim) {
378
+ return char === 32 || char === 9 || char === 10 || char === 13 || delim && (char === delim || char === 44) || char === 35;
379
+ }
380
+ function extractValue(ctx, end) {
381
+ let errPtr = ctx.p;
382
+ let c = ctx.s.charCodeAt(ctx.p);
383
+ if (c === 91 || c === 123) {
384
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
385
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
386
+ ctx.d++;
387
+ return value;
388
+ }
389
+ if (c === 34 || c === 39) {
390
+ return parseString(ctx);
391
+ }
392
+ if (c === 116) {
393
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
394
+ TomlError.x("invalid value", ctx, errPtr);
395
+ return ctx.p++, true;
396
+ }
397
+ if (c === 102) {
398
+ 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)
399
+ TomlError.x("invalid value", ctx, errPtr);
400
+ return ctx.p++, false;
401
+ }
402
+ if (c === 43 || c === 45) {
403
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
404
+ }
405
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
406
+ return parseDate(ctx, c, end);
407
+ }
408
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
409
+ return parseTime(ctx, c, end);
410
+ }
411
+ return parseNumber(ctx, ctx.p, c, 0, end);
412
+ }
413
+ function parseNumber(ctx, startPtr, startChr, sign, endChr) {
414
+ let c = startChr;
415
+ let state = 0;
416
+ let hasUnderscores = false;
417
+ if (c === 105) {
418
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
419
+ TomlError.x("invalid value", ctx, startPtr);
420
+ return ctx.p++, (sign || 1) / 0;
421
+ }
422
+ if (c === 110) {
423
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
424
+ TomlError.x("invalid value", ctx, startPtr);
425
+ return ctx.p++, NaN;
426
+ }
427
+ if (c === 48) {
428
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
429
+ return ctx.bi === true ? 0n : 0;
430
+ if (!sign) {
431
+ if (c === 120)
432
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
433
+ else if (c === 98)
434
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
435
+ else if (c === 111)
436
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
437
+ }
438
+ if (c === 46)
439
+ state = 2;
440
+ else if (c === 101 || c === 69)
441
+ state = 4;
442
+ else
443
+ TomlError.x("illegal leading zero", ctx, startPtr);
444
+ } else if (!isDigit(c))
445
+ TomlError.x("invalid value", ctx, startPtr);
446
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
447
+ if (!state)
448
+ state = 1;
449
+ if (c === 95) {
450
+ if (!(state & 1))
451
+ TomlError.x("illegal underscore", ctx);
452
+ state += 11;
453
+ hasUnderscores = true;
454
+ } else if (state === 1 && c === 46)
455
+ state = 2;
456
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
457
+ state = 4;
458
+ else if (state === 4 && (c === 43 || c === 45)) {} else if (!isDigit(c))
459
+ TomlError.x(`illegal character in numeric literal`, ctx);
460
+ else if (state > 9)
461
+ state -= 11;
462
+ else if (!(state & 1))
463
+ state++;
464
+ }
465
+ if (!state) {
466
+ let val = (startChr - 48) * (sign || 1);
467
+ return ctx.bi === true ? BigInt(val) : val;
468
+ }
469
+ if (!(state & 1))
470
+ TomlError.x("unfinished numeric value", ctx, startPtr);
471
+ let str = ctx.s.slice(startPtr, ctx.p);
472
+ if (hasUnderscores)
473
+ str = str.replaceAll("_", "");
474
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
475
+ }
476
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
477
+ let c, underscore = 1;
478
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
479
+ if (c === 95) {
480
+ if (underscore & 1)
481
+ TomlError.x("illegal underscore", ctx);
482
+ underscore = 3;
483
+ } else if (!isDigit(c, base))
484
+ TomlError.x(`illegal character in numeric literal`, ctx);
485
+ else if (underscore & 1)
486
+ underscore--;
487
+ }
488
+ if (underscore & 1)
489
+ TomlError.x("unfinished numeric value", ctx);
490
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
491
+ if (underscore)
492
+ str = str.replaceAll("_", "");
493
+ return parseInteger(ctx, str, base, startPtr);
494
+ }
495
+ function parseInteger(ctx, str, base, startPtr) {
496
+ if (ctx.bi !== true)
497
+ int: {
498
+ let val = parseInt(str, base);
499
+ if (!Number.isSafeInteger(val)) {
500
+ if (ctx.bi)
501
+ break int;
502
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
503
+ }
504
+ return val;
505
+ }
506
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
507
+ }
508
+ function parseDate(ctx, c, endChr) {
509
+ let startPtr = ctx.p++, unsafeSeparator;
510
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
511
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
512
+ }
513
+ ctx.p += 5;
514
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
515
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
516
+ 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) {
517
+ let t2 = ctx.s.slice(startPtr, ctx.p);
518
+ return readDate(ctx, t2, 3, false, startPtr);
519
+ }
520
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
521
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
522
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
523
+ ctx.p += 3;
524
+ if (ctx.s.charCodeAt(ctx.p) === 46)
525
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
526
+ ;
527
+ if (c = ctx.s.charCodeAt(ctx.p)) {
528
+ if (c === 90 || c === 122) {
529
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
530
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
531
+ }
532
+ if (c === 43 || c === 45) {
533
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
534
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
535
+ }
536
+ }
537
+ let t = ctx.s.slice(startPtr, ctx.p);
538
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
539
+ }
540
+ function parseTime(ctx, c, endChr) {
541
+ let start = ctx.p;
542
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
543
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
544
+ }
545
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
546
+ ctx.p += 3;
547
+ if (ctx.s.charCodeAt(ctx.p) === 46)
548
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
549
+ ;
550
+ let t = ctx.s.slice(start, ctx.p);
551
+ return readDate(ctx, t, 4, false, start);
552
+ }
553
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
554
+ if (ctx.ld) {
555
+ let date = new TomlDate(str, type, unsafeDelim);
556
+ if (!date.isValid())
557
+ TomlError.x("invalid date", ctx, errPtr);
558
+ return date;
559
+ }
560
+ try {
561
+ if (temporalSuffix)
562
+ str += temporalSuffix;
563
+ switch (type) {
564
+ case 1:
565
+ return Temporal.ZonedDateTime.from(str);
566
+ case 2:
567
+ return Temporal.PlainDateTime.from(str);
568
+ case 3:
569
+ return Temporal.PlainDate.from(str);
570
+ case 4:
571
+ return Temporal.PlainTime.from(str);
572
+ }
573
+ } catch (e) {
574
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
575
+ }
576
+ }
577
+
578
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/util.js
579
+ /*!
580
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
581
+ * SPDX-License-Identifier: BSD-3-Clause
582
+ *
583
+ * Redistribution and use in source and binary forms, with or without
584
+ * modification, are permitted provided that the following conditions are met:
585
+ *
586
+ * 1. Redistributions of source code must retain the above copyright notice, this
587
+ * list of conditions and the following disclaimer.
588
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
589
+ * this list of conditions and the following disclaimer in the
590
+ * documentation and/or other materials provided with the distribution.
591
+ * 3. Neither the name of the copyright holder nor the names of its contributors
592
+ * may be used to endorse or promote products derived from this software without
593
+ * specific prior written permission.
594
+ *
595
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
596
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
597
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
598
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
599
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
600
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
601
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
602
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
603
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
604
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
605
+ */
606
+ function skipComment(ctx) {
607
+ for (;ctx.p < ctx.s.length; ctx.p++) {
608
+ let c = ctx.s.charCodeAt(ctx.p);
609
+ if (c === 10)
610
+ break;
611
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
612
+ ctx.p++;
613
+ break;
614
+ }
615
+ if (c < 32 && c !== 9 || c === 127) {
616
+ TomlError.x("control characters are not allowed in comments", ctx);
617
+ }
618
+ }
619
+ }
620
+ function skipVoid(ctx, banNewLines, banComments) {
621
+ let c;
622
+ while (ctx.p < ctx.s.length) {
623
+ 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)))
624
+ ctx.p++;
625
+ if (banComments || c !== 35)
626
+ break;
627
+ skipComment(ctx);
628
+ }
629
+ }
630
+
631
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/struct.js
632
+ /*!
633
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
634
+ * SPDX-License-Identifier: BSD-3-Clause
635
+ *
636
+ * Redistribution and use in source and binary forms, with or without
637
+ * modification, are permitted provided that the following conditions are met:
638
+ *
639
+ * 1. Redistributions of source code must retain the above copyright notice, this
640
+ * list of conditions and the following disclaimer.
641
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
642
+ * this list of conditions and the following disclaimer in the
643
+ * documentation and/or other materials provided with the distribution.
644
+ * 3. Neither the name of the copyright holder nor the names of its contributors
645
+ * may be used to endorse or promote products derived from this software without
646
+ * specific prior written permission.
647
+ *
648
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
649
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
650
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
651
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
652
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
653
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
654
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
655
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
656
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
657
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
658
+ */
659
+ function parseKey(ctx, end = 61) {
660
+ let startPtr;
661
+ let state = 0;
662
+ let parsed = [];
663
+ let sliceStart;
664
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
665
+ do {
666
+ if (c === end) {
667
+ if (!state)
668
+ TomlError.x("unexpected end of key", ctx);
669
+ if (state === 1)
670
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
671
+ return ctx.p++, parsed;
672
+ } else if (c === 46) {
673
+ if (!state)
674
+ TomlError.x("illegal empty bare key", ctx);
675
+ if (state === 1)
676
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
677
+ state = 0;
678
+ } else if (!state && (c === 34 || c === 39)) {
679
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
680
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
681
+ parsed.push(parseString(ctx));
682
+ state = 2;
683
+ ctx.p--;
684
+ } else if (c === 32 || c === 9) {
685
+ if (state === 1) {
686
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
687
+ state = 2;
688
+ }
689
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
690
+ TomlError.x("illegal character in key", ctx);
691
+ } else if (!state) {
692
+ state = 1;
693
+ sliceStart = ctx.p;
694
+ }
695
+ } while (c = ctx.s.charCodeAt(++ctx.p));
696
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
697
+ }
698
+ function parseInlineTable(ctx) {
699
+ let startPtr = ctx.p++;
700
+ let res = Object.create(null);
701
+ let seen = new Set;
702
+ let c;
703
+ while (ctx.p < ctx.s.length) {
704
+ skipVoid(ctx);
705
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
706
+ ctx.p++;
707
+ return res;
708
+ }
709
+ let k;
710
+ let t = res;
711
+ let hasOwn = false;
712
+ let errPtr = ctx.p;
713
+ let key = parseKey(ctx);
714
+ for (let i = 0;i < key.length; i++) {
715
+ if (i)
716
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
717
+ k = key[i];
718
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
719
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
720
+ }
721
+ let unsafe = k === "__proto__";
722
+ if (ctx.uk && (unsafe || k === "constructor")) {
723
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
724
+ break;
725
+ }
726
+ if (!hasOwn && unsafe) {
727
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
728
+ }
729
+ }
730
+ if (hasOwn) {
731
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
732
+ }
733
+ skipVoid(ctx, true, true);
734
+ let value = extractValue(ctx, 125);
735
+ if (t && typeof (t[k] = value) === "object")
736
+ seen.add(value);
737
+ skipVoid(ctx);
738
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
739
+ return res;
740
+ }
741
+ if (c !== 44)
742
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
743
+ }
744
+ TomlError.x("unfinished table", ctx, startPtr);
745
+ }
746
+ function parseArray(ctx) {
747
+ let startPtr = ctx.p++;
748
+ let res = [];
749
+ let c;
750
+ while (ctx.p < ctx.s.length) {
751
+ skipVoid(ctx);
752
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
753
+ ctx.p++;
754
+ return res;
755
+ }
756
+ res.push(extractValue(ctx, 93));
757
+ skipVoid(ctx);
758
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
759
+ return res;
760
+ }
761
+ if (c !== 44)
762
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
763
+ }
764
+ TomlError.x("unfinished array", ctx, startPtr);
765
+ }
766
+
767
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/parse.js
768
+ /*!
769
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
770
+ * SPDX-License-Identifier: BSD-3-Clause
771
+ *
772
+ * Redistribution and use in source and binary forms, with or without
773
+ * modification, are permitted provided that the following conditions are met:
774
+ *
775
+ * 1. Redistributions of source code must retain the above copyright notice, this
776
+ * list of conditions and the following disclaimer.
777
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
778
+ * this list of conditions and the following disclaimer in the
779
+ * documentation and/or other materials provided with the distribution.
780
+ * 3. Neither the name of the copyright holder nor the names of its contributors
781
+ * may be used to endorse or promote products derived from this software without
782
+ * specific prior written permission.
783
+ *
784
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
785
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
786
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
787
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
788
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
789
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
790
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
791
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
792
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
793
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
794
+ */
795
+ function peekTable(ctx, key, table, meta, type) {
796
+ let t = table;
797
+ let m = meta;
798
+ let k;
799
+ let hasOwn = false;
800
+ let state;
801
+ for (let i = 0;i < key.length; i++) {
802
+ if (i) {
803
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
804
+ m = (state = m[k]).c;
805
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
806
+ return null;
807
+ }
808
+ if (state.t === 2) {
809
+ let l = t.length - 1;
810
+ t = t[l];
811
+ m = m[l].c;
812
+ }
813
+ }
814
+ k = key[i];
815
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
816
+ return null;
817
+ }
818
+ if (!hasOwn) {
819
+ let unsafe = k === "__proto__";
820
+ if (ctx.uk && (unsafe || k === "constructor"))
821
+ return false;
822
+ if (unsafe) {
823
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
824
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
825
+ }
826
+ m[k] = {
827
+ t: i < key.length - 1 && type === 2 ? 3 : type,
828
+ d: false,
829
+ i: 0,
830
+ c: Object.create(null)
831
+ };
832
+ }
833
+ }
834
+ state = m[k];
835
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
836
+ return null;
837
+ }
838
+ if (type === 2) {
839
+ if (!state.d) {
840
+ state.d = true;
841
+ t[k] = [];
842
+ }
843
+ t[k].push(t = Object.create(null));
844
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: Object.create(null) };
845
+ }
846
+ if (state.d) {
847
+ return null;
848
+ }
849
+ state.d = true;
850
+ if (type === 1) {
851
+ t = hasOwn ? t[k] : t[k] = Object.create(null);
852
+ } else if (type === 0 && hasOwn) {
853
+ return null;
854
+ }
855
+ return [k, t, state.c];
856
+ }
857
+ function validateTablePeek(ctx, peek, ptr) {
858
+ if (peek === null || ctx.uk === 2)
859
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
860
+ }
861
+ function parse(toml, options = {}) {
862
+ let ctx = {
863
+ s: toml,
864
+ p: 0,
865
+ d: options.maxDepth ?? 1000,
866
+ bi: options.integersAsBigInt ?? false,
867
+ ld: options.useLegacyDate ?? true,
868
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
869
+ };
870
+ let res = Object.create(null);
871
+ let meta = Object.create(null);
872
+ let tmp;
873
+ let skipping = false;
874
+ let tbl = res;
875
+ let m = meta;
876
+ if (toml.charCodeAt(0) === 65279)
877
+ ctx.p++;
878
+ skipVoid(ctx);
879
+ while (ctx.p < toml.length) {
880
+ if (toml.charCodeAt(ctx.p) === 91) {
881
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
882
+ tmp = ctx.p += +isTableArray;
883
+ skipping = false;
884
+ let k = parseKey(ctx, 93);
885
+ if (isTableArray) {
886
+ if (toml.charCodeAt(ctx.p) !== 93) {
887
+ TomlError.x("expected end of table array declaration", ctx);
888
+ }
889
+ ctx.p++;
890
+ }
891
+ let p = peekTable(ctx, k, res, meta, isTableArray ? 2 : 1);
892
+ if (!p) {
893
+ validateTablePeek(ctx, p, tmp);
894
+ skipping = true;
895
+ } else {
896
+ m = p[2];
897
+ tbl = p[1];
898
+ }
899
+ } else {
900
+ tmp = ctx.p;
901
+ let k = parseKey(ctx);
902
+ let p = peekTable(ctx, k, tbl, m, 0);
903
+ if (!p && !skipping)
904
+ validateTablePeek(ctx, p, tmp);
905
+ skipVoid(ctx, true, true);
906
+ let v = extractValue(ctx, undefined);
907
+ if (p && !skipping)
908
+ p[1][p[0]] = v;
909
+ }
910
+ skipVoid(ctx, true);
911
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
912
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
913
+ }
914
+ skipVoid(ctx);
915
+ }
916
+ return res;
917
+ }
918
+
919
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/stringify.js
920
+ /*!
921
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
922
+ * SPDX-License-Identifier: BSD-3-Clause
923
+ *
924
+ * Redistribution and use in source and binary forms, with or without
925
+ * modification, are permitted provided that the following conditions are met:
926
+ *
927
+ * 1. Redistributions of source code must retain the above copyright notice, this
928
+ * list of conditions and the following disclaimer.
929
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
930
+ * this list of conditions and the following disclaimer in the
931
+ * documentation and/or other materials provided with the distribution.
932
+ * 3. Neither the name of the copyright holder nor the names of its contributors
933
+ * may be used to endorse or promote products derived from this software without
934
+ * specific prior written permission.
935
+ *
936
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
937
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
938
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
939
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
940
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
941
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
942
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
943
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
944
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
945
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
946
+ */
947
+ var HAS_WELLFORMED = !!"".isWellFormed;
948
+
949
+ // ../../node_modules/.bun/smol-toml@1.9.0/node_modules/smol-toml/dist/index.js
950
+ /*!
951
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
952
+ * SPDX-License-Identifier: BSD-3-Clause
953
+ *
954
+ * Redistribution and use in source and binary forms, with or without
955
+ * modification, are permitted provided that the following conditions are met:
956
+ *
957
+ * 1. Redistributions of source code must retain the above copyright notice, this
958
+ * list of conditions and the following disclaimer.
959
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
960
+ * this list of conditions and the following disclaimer in the
961
+ * documentation and/or other materials provided with the distribution.
962
+ * 3. Neither the name of the copyright holder nor the names of its contributors
963
+ * may be used to endorse or promote products derived from this software without
964
+ * specific prior written permission.
965
+ *
966
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
967
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
968
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
969
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
970
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
971
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
972
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
973
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
974
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
975
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
976
+ */
977
+
978
+ // ../core/src/config.ts
979
+ var CONFIG_FILE = "armada.toml";
980
+ var CONFIG_DEFAULTS = {
981
+ language: "en",
982
+ readyLabel: "ready-for-agent",
983
+ phaseGroup: "Agent phase",
984
+ runtimeGroup: "Agent runtime",
985
+ silentAfterMinutes: 15
986
+ };
987
+
988
+ class ConfigError extends Error {
989
+ source;
990
+ problems;
991
+ constructor(source, problems) {
992
+ super(`${source} is invalid:
993
+ ${problems.map((p) => ` - ${p}`).join(`
994
+ `)}`);
995
+ this.source = source;
996
+ this.problems = problems;
997
+ this.name = "ConfigError";
998
+ }
999
+ }
1000
+ var SLUG = /^[a-z0-9][a-z0-9-]*$/;
1001
+ var ISSUE_ID = /^[A-Za-z][A-Za-z0-9]*-\d+$/;
1002
+ var REPOSITORY = /^[\w.-]+\/[\w.-]+$/;
1003
+ var isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1004
+ function parseConfig(text, source = CONFIG_FILE) {
1005
+ let raw;
1006
+ try {
1007
+ raw = parse(text);
1008
+ } catch (err) {
1009
+ const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
1010
+ throw new ConfigError(source, [`not valid TOML${where}`]);
1011
+ }
1012
+ const problems = [];
1013
+ const table = (key) => {
1014
+ const v = raw[key];
1015
+ if (v === undefined) {
1016
+ problems.push(`missing required table [${key}]`);
1017
+ return {};
1018
+ }
1019
+ if (!isTable(v)) {
1020
+ problems.push(`"${key}" must be a table`);
1021
+ return {};
1022
+ }
1023
+ return v;
1024
+ };
1025
+ const str = (t, path, key, opts = {}) => {
1026
+ const v = t[key];
1027
+ const dotted = `${path}.${key}`;
1028
+ if (v === undefined) {
1029
+ if (opts.default !== undefined)
1030
+ return opts.default;
1031
+ problems.push(`missing required key "${dotted}"`);
1032
+ return "";
1033
+ }
1034
+ if (typeof v !== "string" || !v.trim()) {
1035
+ problems.push(`"${dotted}" must be a non-empty string`);
1036
+ return "";
1037
+ }
1038
+ if (opts.pattern && !opts.pattern.test(v)) {
1039
+ problems.push(`"${dotted}" is "${v}", expected ${opts.hint}`);
1040
+ return "";
1041
+ }
1042
+ return v.trim();
1043
+ };
1044
+ const project = table("project");
1045
+ const tracker = table("tracker");
1046
+ const github = table("github");
1047
+ const labels = tracker.labels === undefined ? {} : tracker.labels;
1048
+ if (!isTable(labels))
1049
+ problems.push(`"tracker.labels" must be a table`);
1050
+ const policy = raw.policy === undefined ? {} : raw.policy;
1051
+ if (!isTable(policy))
1052
+ problems.push(`"policy" must be a table`);
1053
+ const labelsT = isTable(labels) ? labels : {};
1054
+ const policyT = isTable(policy) ? policy : {};
1055
+ const known = [
1056
+ ["project", project, ["name", "slug"]],
1057
+ ["tracker", tracker, ["program_root", "language", "ready_label", "labels"]],
1058
+ ["tracker.labels", labelsT, ["phase_group", "runtime_group"]],
1059
+ ["github", github, ["repository"]],
1060
+ ["policy", policyT, ["silent_after_minutes"]]
1061
+ ];
1062
+ for (const [path, t, keys] of known)
1063
+ for (const key of Object.keys(t))
1064
+ if (!keys.includes(key))
1065
+ problems.push(`unknown key "${path}.${key}"`);
1066
+ let silentAfterMinutes = CONFIG_DEFAULTS.silentAfterMinutes;
1067
+ if (policyT.silent_after_minutes !== undefined) {
1068
+ const v = policyT.silent_after_minutes;
1069
+ if (typeof v === "number" && Number.isFinite(v) && v > 0)
1070
+ silentAfterMinutes = v;
1071
+ else
1072
+ problems.push(`"policy.silent_after_minutes" must be a positive number`);
1073
+ }
1074
+ const config = {
1075
+ project: {
1076
+ name: str(project, "project", "name"),
1077
+ slug: str(project, "project", "slug", { pattern: SLUG, hint: "lowercase letters, digits and dashes" })
1078
+ },
1079
+ tracker: {
1080
+ programRoot: str(tracker, "tracker", "program_root", {
1081
+ pattern: ISSUE_ID,
1082
+ hint: "an issue identifier such as ABC-1"
1083
+ }),
1084
+ language: str(tracker, "tracker", "language", { default: CONFIG_DEFAULTS.language }),
1085
+ readyLabel: str(tracker, "tracker", "ready_label", { default: CONFIG_DEFAULTS.readyLabel }),
1086
+ labels: {
1087
+ phaseGroup: str(labelsT, "tracker.labels", "phase_group", { default: CONFIG_DEFAULTS.phaseGroup }),
1088
+ runtimeGroup: str(labelsT, "tracker.labels", "runtime_group", { default: CONFIG_DEFAULTS.runtimeGroup })
1089
+ }
1090
+ },
1091
+ github: {
1092
+ repository: str(github, "github", "repository", { pattern: REPOSITORY, hint: "owner/name" })
1093
+ },
1094
+ policy: { silentAfterMinutes }
1095
+ };
1096
+ if (problems.length)
1097
+ throw new ConfigError(source, problems);
1098
+ config.tracker.programRoot = config.tracker.programRoot.toUpperCase();
1099
+ return config;
1100
+ }
1101
+ // ../core/src/credentials.ts
1102
+ var LINEAR_KEY = {
1103
+ name: "linearApiKey",
1104
+ variable: "LINEAR_API_KEY",
1105
+ secret: true,
1106
+ label: "Linear API key",
1107
+ hint: "Linear > Settings > Security & access > Personal API keys"
1108
+ };
1109
+ var STORED_KEYS = [
1110
+ LINEAR_KEY,
1111
+ {
1112
+ name: "tursoUrl",
1113
+ variable: "ARMADA_TURSO_URL",
1114
+ secret: false,
1115
+ label: "Turso database URL",
1116
+ hint: "libsql://<database>-<organization>.turso.io, from `turso db show <database> --url`"
1117
+ },
1118
+ {
1119
+ name: "tursoToken",
1120
+ variable: "ARMADA_TURSO_TOKEN",
1121
+ secret: true,
1122
+ label: "Turso database token",
1123
+ hint: "`turso db tokens create <database>`"
1124
+ }
1125
+ ];
1126
+ var clean = (v) => v?.trim() || null;
1127
+ var fromEnv = (env, variable) => {
1128
+ const value = clean(env[variable]);
1129
+ return value ? { value, source: { kind: "env", variable } } : null;
1130
+ };
1131
+ function resolveCredentials({ env, store = {}, personal, ghToken }) {
1132
+ const fromStore = (variable) => {
1133
+ const value = clean(store[variable]);
1134
+ return value ? { value, source: { kind: "store" } } : null;
1135
+ };
1136
+ const stored = (variable) => fromEnv(env, variable) ?? fromStore(variable);
1137
+ const fromGh = () => {
1138
+ const value = clean(ghToken?.());
1139
+ return value ? { value, source: { kind: "gh" } } : null;
1140
+ };
1141
+ const tursoUrlConfig = clean(personal?.turso.url);
1142
+ const found = {
1143
+ linearApiKey: stored("LINEAR_API_KEY"),
1144
+ tursoUrl: stored("ARMADA_TURSO_URL") ?? (tursoUrlConfig ? { value: tursoUrlConfig, source: { kind: "config", key: "turso.url" } } : null),
1145
+ tursoToken: stored("ARMADA_TURSO_TOKEN"),
1146
+ githubToken: fromEnv(env, "GITHUB_TOKEN") ?? fromEnv(env, "GH_TOKEN") ?? fromGh()
1147
+ };
1148
+ return {
1149
+ linearApiKey: found.linearApiKey?.value ?? null,
1150
+ tursoUrl: found.tursoUrl?.value ?? null,
1151
+ tursoToken: found.tursoToken?.value ?? null,
1152
+ githubToken: found.githubToken?.value ?? null,
1153
+ sources: {
1154
+ linearApiKey: found.linearApiKey?.source ?? null,
1155
+ tursoUrl: found.tursoUrl?.source ?? null,
1156
+ tursoToken: found.tursoToken?.source ?? null,
1157
+ githubToken: found.githubToken?.source ?? null
1158
+ }
1159
+ };
1160
+ }
1161
+ var missingKeys = (credentials) => STORED_KEYS.filter((k) => credentials[k.name] === null);
1162
+ function missingKeyMessage(key) {
1163
+ return `${key.variable} is not set. Set it in the environment, or run \`armada auth login\` to store it on this machine (${key.hint}).`;
1164
+ }
1165
+ // ../core/src/dotenv.ts
1166
+ var ASSIGNMENT = /^\s*(export\s+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$/;
1167
+ function shellWord(raw) {
1168
+ let out = "";
1169
+ let k = 0;
1170
+ while (k < raw.length) {
1171
+ const c = raw.charAt(k);
1172
+ if (c === " " || c === "\t")
1173
+ break;
1174
+ if (c === "'") {
1175
+ const end = raw.indexOf("'", k + 1);
1176
+ if (end < 0)
1177
+ return null;
1178
+ out += raw.slice(k + 1, end);
1179
+ k = end + 1;
1180
+ } else if (c === '"') {
1181
+ k++;
1182
+ for (;; ) {
1183
+ if (k >= raw.length)
1184
+ return null;
1185
+ const d = raw.charAt(k);
1186
+ if (d === '"')
1187
+ break;
1188
+ const next = raw.charAt(k + 1);
1189
+ if (d === "\\" && (next === '"' || next === "\\" || next === "$" || next === "`")) {
1190
+ out += next;
1191
+ k += 2;
1192
+ } else {
1193
+ out += d;
1194
+ k++;
1195
+ }
1196
+ }
1197
+ k++;
1198
+ } else if (c === "\\") {
1199
+ if (k + 1 >= raw.length)
1200
+ return null;
1201
+ out += raw.charAt(k + 1);
1202
+ k += 2;
1203
+ } else {
1204
+ out += c;
1205
+ k++;
1206
+ }
1207
+ }
1208
+ const rest = raw.slice(k).trim();
1209
+ return rest === "" || rest.startsWith("#") ? { value: out, comment: rest } : null;
1210
+ }
1211
+ function parseLine(line) {
1212
+ const trimmed = line.trim();
1213
+ if (!trimmed || trimmed.startsWith("#"))
1214
+ return "blank";
1215
+ const m = ASSIGNMENT.exec(line);
1216
+ if (!m)
1217
+ return null;
1218
+ const word = shellWord(m[3] ?? "");
1219
+ return word === null ? null : { key: m[2] ?? "", value: word.value };
1220
+ }
1221
+ var splitLines = (text) => text.split(/\r?\n/);
1222
+ function parseDotenv(text) {
1223
+ const values = new Map;
1224
+ const invalidLines = [];
1225
+ const assigned = new Set;
1226
+ splitLines(text).forEach((line, index) => {
1227
+ const key = ASSIGNMENT.exec(line)?.[2];
1228
+ if (key !== undefined)
1229
+ assigned.add(key);
1230
+ const parsed = parseLine(line);
1231
+ if (parsed === null)
1232
+ invalidLines.push(index + 1);
1233
+ else if (parsed !== "blank")
1234
+ values.set(parsed.key, parsed.value);
1235
+ });
1236
+ return { values: Object.fromEntries(values), invalidLines, assigned: [...assigned] };
1237
+ }
1238
+ var SHELL_SAFE = /^[A-Za-z0-9_\-.:/@+=,%]+$/;
1239
+ function formatDotenvValue(key, value) {
1240
+ if (/[\r\n\0]/.test(value))
1241
+ throw new Error(`the value for ${key} contains a line break and cannot be stored`);
1242
+ if (value === "")
1243
+ return "''";
1244
+ return SHELL_SAFE.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
1245
+ }
1246
+ function updateDotenv(text, updates) {
1247
+ const lines = text === "" ? [] : splitLines(text);
1248
+ if (lines.length && lines[lines.length - 1] === "")
1249
+ lines.pop();
1250
+ const seen = new Set;
1251
+ const out = [];
1252
+ for (const line of lines) {
1253
+ const m = ASSIGNMENT.exec(line);
1254
+ const key = m?.[2];
1255
+ if (!m || key === undefined || !Object.hasOwn(updates, key)) {
1256
+ out.push(line);
1257
+ continue;
1258
+ }
1259
+ if (seen.has(key))
1260
+ continue;
1261
+ seen.add(key);
1262
+ const value = updates[key];
1263
+ if (value === null || value === undefined)
1264
+ continue;
1265
+ const comment = shellWord(m[3] ?? "")?.comment;
1266
+ out.push(`${m[1] ?? ""}${key}=${formatDotenvValue(key, value)}${comment ? ` ${comment}` : ""}`);
1267
+ }
1268
+ for (const [key, value] of Object.entries(updates)) {
1269
+ if (seen.has(key) || value === null)
1270
+ continue;
1271
+ out.push(`${key}=${formatDotenvValue(key, value)}`);
1272
+ }
1273
+ return out.length ? `${out.join(`
1274
+ `)}
1275
+ ` : "";
1276
+ }
1277
+ // ../core/src/model.ts
1278
+ var CLOSED = ["completed", "canceled"];
1279
+ var NOT_STARTED = ["triage", "backlog", "unstarted"];
1280
+ var isDone = (i) => i.statusType === "completed";
1281
+ var isClosed = (i) => CLOSED.includes(i.statusType);
1282
+ var isStarted = (i) => i.statusType === "started";
1283
+ var isNotStarted = (i) => NOT_STARTED.includes(i.statusType);
1284
+ var SPEC_TITLE = /^Spec\s+(\d+)\s*\/\s*(\d+)\s*[—–-]\s*(.+)$/;
1285
+ function buildModel(issues, rootId) {
1286
+ const byId = new Map(issues.map((i) => [i.id, i]));
1287
+ const root = byId.get(rootId);
1288
+ if (!root)
1289
+ throw new Error(`program root ${rootId} is not among the issues read`);
1290
+ const childrenOf = new Map;
1291
+ for (const i of issues) {
1292
+ if (!i.parentId || !byId.has(i.parentId))
1293
+ continue;
1294
+ childrenOf.set(i.parentId, [...childrenOf.get(i.parentId) ?? [], i]);
1295
+ }
1296
+ const program = [];
1297
+ const walk = (id, seen) => {
1298
+ for (const c of childrenOf.get(id) ?? []) {
1299
+ if (seen.has(c.id))
1300
+ continue;
1301
+ seen.add(c.id);
1302
+ program.push(c);
1303
+ walk(c.id, seen);
1304
+ }
1305
+ };
1306
+ walk(root.id, new Set([root.id]));
1307
+ const specs = (childrenOf.get(root.id) ?? []).flatMap((issue) => {
1308
+ const m = issue.title.trim().match(SPEC_TITLE);
1309
+ return m?.[1] && m[3] ? [{ issue, ordinal: Number(m[1]), name: m[3].trim() }] : [];
1310
+ }).sort((a, b) => a.ordinal - b.ordinal || a.issue.createdAt.localeCompare(b.issue.createdAt));
1311
+ const specById = new Map(specs.map((s) => [s.issue.id, s]));
1312
+ const specOf = (id) => {
1313
+ const seen = new Set;
1314
+ for (let cur = byId.get(id);cur && !seen.has(cur.id); cur = cur.parentId ? byId.get(cur.parentId) : undefined) {
1315
+ seen.add(cur.id);
1316
+ const s = specById.get(cur.id);
1317
+ if (s)
1318
+ return s;
1319
+ }
1320
+ return null;
1321
+ };
1322
+ const isLeaf = (i) => !childrenOf.get(i.id)?.length && !specById.has(i.id);
1323
+ const openBlockersOf = (i) => i.blockedBy.filter((b) => !isClosed(byId.get(b.id) ?? b)).map((b) => b.id);
1324
+ const stateOf = (i) => {
1325
+ if (isDone(i))
1326
+ return "done";
1327
+ if (i.statusType === "canceled")
1328
+ return "canceled";
1329
+ if (isStarted(i))
1330
+ return "active";
1331
+ return openBlockersOf(i).length ? "blocked" : "frontier";
1332
+ };
1333
+ return { root, byId, childrenOf, program, specs, specOf, isLeaf, openBlockersOf, stateOf };
1334
+ }
1335
+ function longestPathLevels(nodes) {
1336
+ const byId = new Map(nodes.map((n) => [n.id, n]));
1337
+ const level = new Map;
1338
+ const visiting = new Set;
1339
+ const visit = (id) => {
1340
+ const known = level.get(id);
1341
+ if (known !== undefined)
1342
+ return known;
1343
+ if (visiting.has(id))
1344
+ return 0;
1345
+ visiting.add(id);
1346
+ const blockers = (byId.get(id)?.blockedBy ?? []).map((b) => b.id).filter((b) => byId.has(b));
1347
+ const l = blockers.length ? Math.max(...blockers.map(visit)) + 1 : 0;
1348
+ visiting.delete(id);
1349
+ level.set(id, l);
1350
+ return l;
1351
+ };
1352
+ for (const n of nodes)
1353
+ visit(n.id);
1354
+ return level;
1355
+ }
1356
+ function criticalPath(m, parentId) {
1357
+ const nodes = m.childrenOf.get(parentId) ?? [];
1358
+ const level = longestPathLevels(nodes);
1359
+ const remaining = nodes.filter((n) => !isClosed(n));
1360
+ const remIds = new Set(remaining.map((n) => n.id));
1361
+ const len = new Map;
1362
+ const prev = new Map;
1363
+ const order = [...remaining].sort((a, b) => (level.get(a.id) ?? 0) - (level.get(b.id) ?? 0));
1364
+ for (const n of order) {
1365
+ let best = 0;
1366
+ let bestPrev = null;
1367
+ for (const { id } of n.blockedBy) {
1368
+ if (!remIds.has(id))
1369
+ continue;
1370
+ const l = len.get(id) ?? 0;
1371
+ if (l > best) {
1372
+ best = l;
1373
+ bestPrev = id;
1374
+ }
1375
+ }
1376
+ len.set(n.id, best + 1);
1377
+ prev.set(n.id, bestPrev);
1378
+ }
1379
+ let tail = null;
1380
+ let tailLen = 0;
1381
+ for (const [id, l] of len)
1382
+ if (l > tailLen || l === tailLen && tail && id > tail) {
1383
+ tail = id;
1384
+ tailLen = l;
1385
+ }
1386
+ if (tailLen < 2)
1387
+ return [];
1388
+ const path = [];
1389
+ for (let cur = tail;cur; cur = prev.get(cur) ?? null) {
1390
+ const issue = m.byId.get(cur);
1391
+ if (issue)
1392
+ path.unshift(issue);
1393
+ }
1394
+ return path;
1395
+ }
1396
+ function criticalIds(m) {
1397
+ const out = new Set;
1398
+ for (const parent of m.childrenOf.keys())
1399
+ for (const i of criticalPath(m, parent))
1400
+ out.add(i.id);
1401
+ return out;
1402
+ }
1403
+
1404
+ // ../core/src/fleet.ts
1405
+ var MIN = 60000;
1406
+ var NEEDS_HUMAN = ["awaiting-approval", "blocked", "ready-to-merge"];
1407
+ var PHASE_RANK = {
1408
+ merged: 0,
1409
+ "ready-to-merge": 1,
1410
+ shipping: 2,
1411
+ implementing: 3,
1412
+ "awaiting-approval": 4,
1413
+ planning: 5,
1414
+ blocked: 6,
1415
+ released: 7
1416
+ };
1417
+ var PLAN_HINT = /\b(plan|objective|assumptions|awaiting (?:plan )?approval)\b/i;
1418
+ function commentsFor(comments, id) {
1419
+ return comments.filter((c) => c.issueId === id).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
1420
+ }
1421
+ function commentUrl(issue, c) {
1422
+ return `${issue.url}#comment-${c.id.slice(0, 8)}`;
1423
+ }
1424
+ function primaryPr(issue) {
1425
+ const byNewest = [...issue.prs].sort((a, b) => b.number - a.number);
1426
+ return byNewest.find((p) => p.state === "open") ?? byNewest[0] ?? null;
1427
+ }
1428
+ function activeClaims(comments) {
1429
+ const asc = [...comments].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1430
+ let claims = [];
1431
+ for (const c of asc) {
1432
+ if (c.status?.phase === "released")
1433
+ claims = [];
1434
+ if (c.claim)
1435
+ claims.push(c.claim);
1436
+ }
1437
+ return claims;
1438
+ }
1439
+ var latest = (...xs) => xs.filter((x) => !!x).reduce((a, b) => b > a ? b : a, "");
1440
+ function inferPhase(pr, comments) {
1441
+ if (pr?.state === "open")
1442
+ return pr.ci === "success" && pr.mergeable !== "CONFLICTING" ? "ready-to-merge" : "shipping";
1443
+ if (comments.some((c) => PLAN_HINT.test(c.excerpt.slice(0, 120))))
1444
+ return "awaiting-approval";
1445
+ return "planning";
1446
+ }
1447
+ function buildLane(m, allComments, issue, opts) {
1448
+ const comments = commentsFor(allComments, issue.id);
1449
+ const withStatus = comments.find((c) => c.status && c.status.phase !== "released");
1450
+ const pr = primaryPr(issue);
1451
+ const claims = activeClaims(comments);
1452
+ let phase;
1453
+ let phaseSource;
1454
+ if (issue.agentPhase) {
1455
+ phase = issue.agentPhase;
1456
+ phaseSource = "label";
1457
+ } else if (withStatus?.status) {
1458
+ phase = withStatus.status.phase;
1459
+ phaseSource = "status-line";
1460
+ } else {
1461
+ phase = inferPhase(pr, comments);
1462
+ phaseSource = "inferred";
1463
+ }
1464
+ const shippingPhase = phase === "shipping" || phase === "ready-to-merge";
1465
+ if (pr?.state === "merged" && !isDone(issue) && (shippingPhase || phaseSource !== "label"))
1466
+ phase = "merged";
1467
+ const announcing = comments.find((c) => c.status?.phase === phase);
1468
+ const since = announcing?.createdAt ?? (phase === "shipping" || phase === "ready-to-merge" ? pr?.createdAt : undefined) ?? claims[0]?.at ?? issue.startedAt ?? issue.updatedAt;
1469
+ const lastUpdate = latest(issue.updatedAt, comments[0]?.createdAt, pr?.updatedAt, issue.startedAt);
1470
+ const openBlockers = m.openBlockersOf(issue);
1471
+ const agent = issue.delegate ?? issue.assignee;
1472
+ const flags = [];
1473
+ const waitingOnHuman = NEEDS_HUMAN.includes(phase) || phase === "merged";
1474
+ if (!waitingOnHuman && opts.now - Date.parse(lastUpdate) > opts.silentAfterMinutes * MIN)
1475
+ flags.push("silent");
1476
+ if (pr?.state === "open" && pr.ci === "failure")
1477
+ flags.push("ci-failing");
1478
+ if (pr?.state === "open" && pr.mergeable === "CONFLICTING")
1479
+ flags.push("conflict");
1480
+ const runtimes = new Set(claims.map((c) => c.runtime).filter(Boolean));
1481
+ const claimRuntime = claims[0]?.runtime;
1482
+ if (claims.length > 1 || runtimes.size > 1 || issue.agentRuntime && claimRuntime && claimRuntime !== issue.agentRuntime)
1483
+ flags.push("double-claim");
1484
+ if (openBlockers.length)
1485
+ flags.push("started-before-blockers");
1486
+ if (!agent)
1487
+ flags.push("no-assignee");
1488
+ if (!issue.agentPhase)
1489
+ flags.push("no-phase-label");
1490
+ const spec = m.specOf(issue.id);
1491
+ return {
1492
+ issue,
1493
+ spec: spec ? `Spec ${spec.ordinal}` : null,
1494
+ phase,
1495
+ phaseSource,
1496
+ runtime: issue.agentRuntime ?? claimRuntime ?? null,
1497
+ claim: claims[0] ?? null,
1498
+ agent,
1499
+ since,
1500
+ lastUpdate,
1501
+ statusLine: withStatus?.status ? {
1502
+ summary: withStatus.status.summary,
1503
+ at: withStatus.createdAt,
1504
+ author: withStatus.author,
1505
+ url: commentUrl(issue, withStatus)
1506
+ } : null,
1507
+ pr,
1508
+ openBlockers,
1509
+ flags
1510
+ };
1511
+ }
1512
+ function inFlight(m, comments, opts) {
1513
+ return m.program.filter((i) => m.isLeaf(i) && !isClosed(i) && (i.agentPhase || isStarted(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 }));
1514
+ }
1515
+ function frontier(m, readyLabel) {
1516
+ const dependents = new Map;
1517
+ for (const i of m.program)
1518
+ for (const b of i.blockedBy)
1519
+ dependents.set(b.id, [...dependents.get(b.id) ?? [], i]);
1520
+ const transitive = (id, seen = new Set) => {
1521
+ for (const d of dependents.get(id) ?? [])
1522
+ if (!seen.has(d.id) && !isClosed(d)) {
1523
+ seen.add(d.id);
1524
+ transitive(d.id, seen);
1525
+ }
1526
+ return seen;
1527
+ };
1528
+ const critical = criticalIds(m);
1529
+ 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) => {
1530
+ const spec = m.specOf(issue.id);
1531
+ const unlocksAll = [...transitive(issue.id)];
1532
+ const unlocksNow = (dependents.get(issue.id) ?? []).filter((d) => !isClosed(d) && m.openBlockersOf(d).every((b) => b === issue.id)).map((d) => d.id);
1533
+ const readyForAgent = issue.labels.includes(readyLabel) && issue.statusType !== "triage";
1534
+ const onCriticalPath = critical.has(issue.id);
1535
+ const score = (readyForAgent ? 1000 : 0) + (onCriticalPath ? 300 : 0) + unlocksAll.length * 20 + unlocksNow.length * 10 - (spec?.ordinal ?? 99);
1536
+ return {
1537
+ issue,
1538
+ spec: spec ? `Spec ${spec.ordinal}` : null,
1539
+ readyForAgent,
1540
+ onCriticalPath,
1541
+ unlocksAll,
1542
+ unlocksNow,
1543
+ score
1544
+ };
1545
+ }).sort((a, b) => b.score - a.score || a.issue.id.localeCompare(b.issue.id, "en", { numeric: true }));
1546
+ }
1547
+ function waitingPullRequests(m, prs) {
1548
+ const ticketOf = new Map;
1549
+ for (const i of m.program)
1550
+ for (const p of i.prs)
1551
+ ticketOf.set(p.url, i);
1552
+ 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);
1553
+ }
1554
+ // ../core/src/types.ts
1555
+ var LABEL_PHASES = [
1556
+ "planning",
1557
+ "awaiting-approval",
1558
+ "implementing",
1559
+ "shipping",
1560
+ "blocked",
1561
+ "ready-to-merge"
1562
+ ];
1563
+
1564
+ // ../core/src/linear.ts
1565
+ var LINEAR_ENDPOINT = "https://api.linear.app/graphql";
1566
+ var MAX_DEPTH = 8;
1567
+ var MAX_PAGES = 20;
1568
+ var COMMENT_BATCH = 25;
1569
+ var MAX_COMMENTS = 100;
1570
+ var REQUEST_TIMEOUT_MS = 30000;
1571
+
1572
+ class LinearError extends Error {
1573
+ name = "LinearError";
1574
+ }
1575
+ var PHASES = [...LABEL_PHASES, "released", "merged"];
1576
+ var LEGACY = { "handed-back": "ready-to-merge", "ci-fixing": "shipping" };
1577
+ var firstLine = (body) => (body.split(`
1578
+ `).find((l) => l.trim()) ?? "").replace(/[*_`]/g, "");
1579
+ function parseStatusLine(body) {
1580
+ const m = firstLine(body).match(/^\s*Agent status\s*:\s*([a-z-]+)\s*(?:[—–-]+\s*(.*))?$/i);
1581
+ if (!m?.[1])
1582
+ return null;
1583
+ const raw = m[1].toLowerCase();
1584
+ const phase = LEGACY[raw] ?? raw;
1585
+ return PHASES.includes(phase) ? { phase, summary: (m[2] ?? "").trim() } : null;
1586
+ }
1587
+ function parseClaim(body, at, author) {
1588
+ const line = firstLine(body);
1589
+ if (!/^\s*Agent claim\b/i.test(line))
1590
+ return null;
1591
+ const field = (k) => line.match(new RegExp(`(?:${k})\\s*:\\s*([^·|]+)`, "i"))?.[1]?.trim() || null;
1592
+ return {
1593
+ runtime: field("runtime"),
1594
+ session: field("session"),
1595
+ branch: field("branch|branche"),
1596
+ startedAt: field("started|démarré|demarre"),
1597
+ at,
1598
+ author
1599
+ };
1600
+ }
1601
+ function excerpt(markdown, max = 240) {
1602
+ const text = markdown.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*]\([^)]*\)/g, "").replace(/\[([^\]]+)]\(<?[^)]*>?\)/g, "$1").replace(/[#*_`>|]/g, "").replace(/\s+/g, " ").trim();
1603
+ return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
1604
+ }
1605
+ function parsePullRequestUrl(url, title = "") {
1606
+ const m = url.match(/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d+)/);
1607
+ return m?.[1] && m[2] ? { url: `https://github.com/${m[1]}/pull/${m[2]}`, repo: m[1], number: Number(m[2]), title } : null;
1608
+ }
1609
+ function agentLabels(labels, groups) {
1610
+ const phase = labels.find((l) => l.group === groups.phaseGroup && LABEL_PHASES.includes(l.name));
1611
+ const runtime = labels.find((l) => l.group === groups.runtimeGroup);
1612
+ return { agentPhase: phase?.name ?? null, agentRuntime: runtime?.name ?? null };
1613
+ }
1614
+ function truncationWarnings(raw) {
1615
+ const cut = (c, what) => c.pageInfo?.hasNextPage ? [`${raw.identifier}: more ${what} than Armada reads; some are ignored`] : [];
1616
+ return [
1617
+ ...cut(raw.inverseRelations, "relations"),
1618
+ ...cut(raw.labels, "labels"),
1619
+ ...cut(raw.attachments, "attachments")
1620
+ ];
1621
+ }
1622
+ function normalizeIssue(raw, groups) {
1623
+ const blockers = new Map;
1624
+ for (const r of raw.inverseRelations.nodes)
1625
+ if (r.type === "blocks")
1626
+ blockers.set(r.issue.identifier, { id: r.issue.identifier, statusType: r.issue.state.type });
1627
+ const prs = new Map;
1628
+ for (const a of raw.attachments.nodes) {
1629
+ const pr = parsePullRequestUrl(a.url, a.title);
1630
+ if (pr)
1631
+ prs.set(pr.url, pr);
1632
+ }
1633
+ for (const m of raw.description?.matchAll(/https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/g) ?? []) {
1634
+ const pr = parsePullRequestUrl(m[0]);
1635
+ if (pr && !prs.has(pr.url))
1636
+ prs.set(pr.url, pr);
1637
+ }
1638
+ const labels = raw.labels.nodes.map((l) => ({ name: l.name, group: l.parent?.name ?? null }));
1639
+ return {
1640
+ id: raw.identifier,
1641
+ uuid: raw.id,
1642
+ title: raw.title,
1643
+ url: raw.url,
1644
+ status: raw.state.name,
1645
+ statusType: raw.state.type,
1646
+ assignee: raw.assignee?.name ?? null,
1647
+ delegate: raw.delegate?.name ?? null,
1648
+ labels: labels.map((l) => l.name),
1649
+ ...agentLabels(labels, groups),
1650
+ parentId: raw.parent?.identifier ?? null,
1651
+ createdAt: raw.createdAt,
1652
+ updatedAt: raw.updatedAt,
1653
+ startedAt: raw.startedAt,
1654
+ completedAt: raw.completedAt,
1655
+ canceledAt: raw.canceledAt,
1656
+ blockedBy: [...blockers.values()].sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
1657
+ prs: [...prs.values()].sort((a, b) => a.number - b.number)
1658
+ };
1659
+ }
1660
+ function normalizeComment(raw, issueId) {
1661
+ const author = raw.user?.name ?? null;
1662
+ return {
1663
+ id: raw.id,
1664
+ issueId,
1665
+ author,
1666
+ createdAt: raw.createdAt,
1667
+ excerpt: excerpt(raw.body, 600),
1668
+ status: parseStatusLine(raw.body),
1669
+ claim: parseClaim(raw.body, raw.createdAt, author)
1670
+ };
1671
+ }
1672
+ var FIELDS = (delegate) => `
1673
+ fragment F on Issue {
1674
+ id identifier title url description createdAt updatedAt startedAt completedAt canceledAt
1675
+ state { name type }
1676
+ assignee { name }
1677
+ ${delegate ? "delegate { name }" : ""}
1678
+ parent { identifier }
1679
+ labels(first: 25) { pageInfo { hasNextPage } nodes { name parent { name } } }
1680
+ attachments(first: 25) { pageInfo { hasNextPage } nodes { title url } }
1681
+ inverseRelations(first: 50) { pageInfo { hasNextPage } nodes { type issue { identifier state { type } } } }
1682
+ }
1683
+ `;
1684
+ var ROOT_QUERY = (d) => `${FIELDS(d)} query Root($id: String!) { issue(id: $id) { ...F } }`;
1685
+ var CHILDREN_QUERY = (d) => `${FIELDS(d)}
1686
+ query Children($parents: [ID!], $after: String) {
1687
+ issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
1688
+ pageInfo { hasNextPage endCursor }
1689
+ nodes { ...F }
1690
+ }
1691
+ }`;
1692
+ var COMMENTS_QUERY = `
1693
+ query Comments($ids: [ID!]) {
1694
+ issues(first: 50, filter: { id: { in: $ids } }) {
1695
+ nodes { identifier comments(first: ${MAX_COMMENTS}) { pageInfo { hasNextPage } nodes { id createdAt body user { name } } } }
1696
+ }
1697
+ }`;
1698
+ async function gql(opts, query, variables) {
1699
+ const doFetch = opts.fetch ?? fetch;
1700
+ const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
1701
+ const res = await doFetch(LINEAR_ENDPOINT, {
1702
+ method: "POST",
1703
+ headers: { "Content-Type": "application/json", Authorization: opts.apiKey },
1704
+ body: JSON.stringify({ query, variables }),
1705
+ signal: AbortSignal.timeout(timeoutMs)
1706
+ }).catch((err) => {
1707
+ throw new LinearError(`Linear API unreachable: ${networkReason(err, timeoutMs)}`);
1708
+ });
1709
+ if (res.status === 401)
1710
+ throw new LinearError("Linear rejected the API key (HTTP 401); check LINEAR_API_KEY");
1711
+ const json = await res.json().catch(() => ({}));
1712
+ if (json.errors?.length)
1713
+ throw new LinearError(`Linear API: ${json.errors.map((e) => e.message).join("; ")}`);
1714
+ if (!res.ok)
1715
+ throw new LinearError(`Linear API HTTP ${res.status}`);
1716
+ if (!json.data)
1717
+ throw new LinearError("Linear API: empty response");
1718
+ return json.data;
1719
+ }
1720
+ function networkReason(err, timeoutMs) {
1721
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"))
1722
+ return `no answer within ${timeoutMs >= 1000 ? `${Math.round(timeoutMs / 1000)} s` : `${timeoutMs} ms`}`;
1723
+ return err instanceof Error ? err.message : String(err);
1724
+ }
1725
+ var chunks = (xs, n) => Array.from({ length: Math.ceil(xs.length / n) }, (_, k) => xs.slice(k * n, k * n + n));
1726
+ var CLOSED2 = new Set(["completed", "canceled"]);
1727
+ async function fetchProgram(opts) {
1728
+ try {
1729
+ return await fetchTree(opts, true);
1730
+ } catch (err) {
1731
+ if (err instanceof LinearError && /delegate/i.test(err.message))
1732
+ return fetchTree(opts, false);
1733
+ throw err;
1734
+ }
1735
+ }
1736
+ async function fetchTree(opts, delegate) {
1737
+ const root = (await gql(opts, ROOT_QUERY(delegate), { id: opts.rootId })).issue;
1738
+ if (!root)
1739
+ throw new LinearError(`Linear: program root ${opts.rootId} not found`);
1740
+ const all = [root];
1741
+ const warnings = [];
1742
+ let parents = [root.id];
1743
+ for (let depth = 0;depth < MAX_DEPTH && parents.length; depth++) {
1744
+ const next = [];
1745
+ let after = null;
1746
+ for (let page = 0;; page++) {
1747
+ if (page === MAX_PAGES) {
1748
+ warnings.push(`more than ${MAX_PAGES * 50} issues at depth ${depth + 1}; the rest are ignored`);
1749
+ break;
1750
+ }
1751
+ const data = await gql(opts, CHILDREN_QUERY(delegate), { parents, after });
1752
+ all.push(...data.issues.nodes);
1753
+ next.push(...data.issues.nodes.map((n) => n.id));
1754
+ if (!data.issues.pageInfo.hasNextPage)
1755
+ break;
1756
+ after = data.issues.pageInfo.endCursor;
1757
+ }
1758
+ parents = next;
1759
+ }
1760
+ if (parents.length)
1761
+ warnings.push(`the program is deeper than ${MAX_DEPTH} levels; deeper issues are ignored`);
1762
+ for (const r of all)
1763
+ warnings.push(...truncationWarnings(r));
1764
+ const issues = all.map((r) => normalizeIssue(r, opts.labels));
1765
+ const candidates = issues.filter((i) => i.id !== root.identifier && !CLOSED2.has(i.statusType) && (i.agentPhase || i.statusType === "started"));
1766
+ const comments = [];
1767
+ for (const batch of chunks(candidates.map((i) => i.uuid), COMMENT_BATCH)) {
1768
+ const data = await gql(opts, COMMENTS_QUERY, { ids: batch });
1769
+ for (const n of data.issues.nodes) {
1770
+ for (const c of n.comments.nodes)
1771
+ comments.push(normalizeComment(c, n.identifier));
1772
+ if (n.comments.pageInfo?.hasNextPage)
1773
+ warnings.push(`${n.identifier}: more than ${MAX_COMMENTS} comments; its phase and claim may be out of date`);
1774
+ }
1775
+ }
1776
+ return {
1777
+ rootId: root.identifier,
1778
+ fetchedAt: (opts.now?.() ?? new Date).toISOString(),
1779
+ issues: issues.sort((a, b) => a.id.localeCompare(b.id, "en", { numeric: true })),
1780
+ comments: comments.sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
1781
+ warnings
1782
+ };
1783
+ }
1784
+
1785
+ // ../core/src/github.ts
1786
+ var GITHUB_GRAPHQL = "https://api.github.com/graphql";
1787
+
1788
+ class GithubError extends Error {
1789
+ name = "GithubError";
1790
+ }
1791
+ function checkState(status, conclusion) {
1792
+ const s = (status ?? "").toUpperCase();
1793
+ const c = (conclusion ?? "").toUpperCase();
1794
+ if (s && s !== "COMPLETED")
1795
+ return "pending";
1796
+ if (["SUCCESS", "NEUTRAL", "SKIPPED"].includes(c))
1797
+ return "success";
1798
+ if (["FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE", "ERROR", "STALE"].includes(c))
1799
+ return "failure";
1800
+ return "pending";
1801
+ }
1802
+ function rollup(states) {
1803
+ if (!states.length)
1804
+ return "none";
1805
+ if (states.includes("failure"))
1806
+ return "failure";
1807
+ if (states.includes("pending"))
1808
+ return "pending";
1809
+ return "success";
1810
+ }
1811
+ function ticketIdFromBranch(branch, known) {
1812
+ for (const m of branch.matchAll(/(?:^|[/_-])([a-z][a-z0-9]*-\d+)(?=[-_/]|$)/gi)) {
1813
+ const id = m[1]?.toUpperCase();
1814
+ if (id && known.has(id))
1815
+ return id;
1816
+ }
1817
+ return null;
1818
+ }
1819
+ function normalizePull(raw, repo) {
1820
+ const status = raw.commits.nodes[0]?.commit.statusCheckRollup ?? null;
1821
+ const checks = status?.contexts.nodes.map((c) => c.__typename === "CheckRun" ? { name: c.name, state: checkState(c.status, c.conclusion) } : { name: c.context, state: checkState("", c.state) });
1822
+ return {
1823
+ url: raw.url,
1824
+ number: raw.number,
1825
+ repo,
1826
+ title: raw.title,
1827
+ state: raw.state === "OPEN" ? "open" : raw.state === "MERGED" ? "merged" : "closed",
1828
+ draft: raw.isDraft,
1829
+ ci: checks ? rollup(checks.map((c) => c.state)) : "none",
1830
+ checks: checks ?? [],
1831
+ mergeable: raw.mergeable,
1832
+ headRef: raw.headRefName,
1833
+ headSha: raw.headRefOid,
1834
+ createdAt: raw.createdAt,
1835
+ updatedAt: raw.updatedAt,
1836
+ mergedAt: raw.mergedAt
1837
+ };
1838
+ }
1839
+ var PULLS_QUERY = `
1840
+ fragment P on PullRequest {
1841
+ number title url state isDraft mergeable headRefName headRefOid createdAt updatedAt mergedAt
1842
+ commits(last: 1) { nodes { commit { statusCheckRollup { state contexts(first: 50) { nodes {
1843
+ __typename
1844
+ ... on CheckRun { name status conclusion }
1845
+ ... on StatusContext { context state }
1846
+ } } } } } }
1847
+ }
1848
+ query Pulls($owner: String!, $name: String!) {
1849
+ repository(owner: $owner, name: $name) {
1850
+ open: pullRequests(states: OPEN, first: 100, orderBy: { field: UPDATED_AT, direction: DESC }) {
1851
+ pageInfo { hasNextPage }
1852
+ nodes { ...P }
1853
+ }
1854
+ closed: pullRequests(states: [MERGED, CLOSED], first: 30, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { ...P } }
1855
+ }
1856
+ }`;
1857
+ async function fetchForge(opts) {
1858
+ const [owner, name] = opts.repository.split("/");
1859
+ const doFetch = opts.fetch ?? fetch;
1860
+ const timeoutMs = opts.timeoutMs ?? REQUEST_TIMEOUT_MS;
1861
+ const res = await doFetch(GITHUB_GRAPHQL, {
1862
+ method: "POST",
1863
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${opts.token}` },
1864
+ body: JSON.stringify({ query: PULLS_QUERY, variables: { owner, name } }),
1865
+ signal: AbortSignal.timeout(timeoutMs)
1866
+ }).catch((err) => {
1867
+ throw new GithubError(`GitHub API unreachable: ${networkReason(err, timeoutMs)}`);
1868
+ });
1869
+ if (!res.ok)
1870
+ throw new GithubError(`GitHub API HTTP ${res.status}`);
1871
+ const json = await res.json();
1872
+ if (json.errors?.length)
1873
+ throw new GithubError(`GitHub API: ${json.errors.map((e) => e.message).join("; ")}`);
1874
+ const repo = json.data?.repository;
1875
+ if (!repo)
1876
+ throw new GithubError(`GitHub: repository ${opts.repository} not found`);
1877
+ return {
1878
+ repo: opts.repository,
1879
+ fetchedAt: (opts.now?.() ?? new Date).toISOString(),
1880
+ prs: [...repo.open.nodes, ...repo.closed.nodes].map((p) => normalizePull(p, opts.repository)),
1881
+ warnings: repo.open.pageInfo?.hasNextPage ? ["more than 100 open pull requests; the least recently updated are ignored"] : []
1882
+ };
1883
+ }
1884
+ function attachPullRequests(program, forge) {
1885
+ if (!forge)
1886
+ return program.issues;
1887
+ const known = new Set(program.issues.map((i) => i.id));
1888
+ const byUrl = new Map(forge.prs.map((p) => [p.url, p]));
1889
+ const byTicket = new Map;
1890
+ for (const p of forge.prs) {
1891
+ const id = p.headRef ? ticketIdFromBranch(p.headRef, known) : null;
1892
+ if (id)
1893
+ byTicket.set(id, [...byTicket.get(id) ?? [], p]);
1894
+ }
1895
+ return program.issues.map((issue) => {
1896
+ const prs = issue.prs.map((p) => {
1897
+ const live = byUrl.get(p.url);
1898
+ return live ? { ...p, ...live, title: live.title || p.title } : p;
1899
+ });
1900
+ for (const p of byTicket.get(issue.id) ?? [])
1901
+ if (!prs.some((x) => x.url === p.url))
1902
+ prs.push(p);
1903
+ return { ...issue, prs: prs.sort((a, b) => a.number - b.number) };
1904
+ });
1905
+ }
1906
+ // ../core/src/machine.ts
1907
+ import { randomBytes } from "node:crypto";
1908
+ import { chmod, mkdir, open, readFile, rename, rm, stat } from "node:fs/promises";
1909
+ import { isAbsolute, join } from "node:path";
1910
+ function machinePaths(env) {
1911
+ const xdg = env.XDG_CONFIG_HOME?.trim();
1912
+ const home = env.HOME?.trim();
1913
+ const base = xdg && isAbsolute(xdg) ? xdg : home ? join(home, ".config") : null;
1914
+ if (!base)
1915
+ return null;
1916
+ const dir = join(base, "armada");
1917
+ return { dir, credentials: join(dir, "credentials"), config: join(dir, "config.toml") };
1918
+ }
1919
+ var missing = (err) => {
1920
+ const code = err.code;
1921
+ return code === "ENOENT" || code === "ENOTDIR";
1922
+ };
1923
+ async function readCredentialStore(path) {
1924
+ let text;
1925
+ let mode;
1926
+ try {
1927
+ [text, mode] = await Promise.all([readFile(path, "utf8"), stat(path).then((s) => s.mode & 511)]);
1928
+ } catch (err) {
1929
+ if (missing(err))
1930
+ return { path, exists: false, mode: null, values: {}, invalidLines: [], assigned: [] };
1931
+ throw new Error(`cannot read ${path}: ${err.code ?? "unknown error"}`);
1932
+ }
1933
+ return { path, exists: true, mode, ...parseDotenv(text) };
1934
+ }
1935
+ var storeIsExposed = (store) => store.mode !== null && (store.mode & 63) !== 0;
1936
+ async function writePrivate(paths, path, text, mode) {
1937
+ await mkdir(paths.dir, { recursive: true, mode: 448 });
1938
+ await chmod(paths.dir, 448);
1939
+ const tmp = `${path}.${randomBytes(6).toString("hex")}.tmp`;
1940
+ const handle = await open(tmp, "wx", mode);
1941
+ try {
1942
+ await handle.writeFile(text, "utf8");
1943
+ await handle.sync();
1944
+ await handle.close();
1945
+ await chmod(tmp, mode);
1946
+ await rename(tmp, path);
1947
+ } catch (err) {
1948
+ await handle.close().catch(() => {});
1949
+ await rm(tmp, { force: true });
1950
+ throw err;
1951
+ }
1952
+ }
1953
+ async function updateCredentialStore(paths, updates) {
1954
+ let text = "";
1955
+ try {
1956
+ text = await readFile(paths.credentials, "utf8");
1957
+ } catch (err) {
1958
+ if (!missing(err))
1959
+ throw err;
1960
+ }
1961
+ await writePrivate(paths, paths.credentials, updateDotenv(text, updates), 384);
1962
+ }
1963
+ var EMPTY_PERSONAL_CONFIG = { language: null, turso: { url: null }, dashboard: { url: null } };
1964
+ var isTable2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
1965
+ function parsePersonalConfig(text, source = "config.toml") {
1966
+ let raw;
1967
+ try {
1968
+ raw = parse(text);
1969
+ } catch (err) {
1970
+ const where = err instanceof TomlError ? ` (line ${err.line}, column ${err.column})` : "";
1971
+ throw new ConfigError(source, [`not valid TOML${where}`]);
1972
+ }
1973
+ const problems = [];
1974
+ const known = { turso: ["url"], dashboard: ["url"] };
1975
+ for (const [key, v] of Object.entries(raw)) {
1976
+ if (key === "language")
1977
+ continue;
1978
+ const keys = known[key];
1979
+ if (!keys) {
1980
+ if (!isTable2(v))
1981
+ problems.push(`unknown key "${key}"`);
1982
+ continue;
1983
+ }
1984
+ if (!isTable2(v)) {
1985
+ problems.push(`"${key}" must be a table`);
1986
+ continue;
1987
+ }
1988
+ for (const k of Object.keys(v))
1989
+ if (!keys.includes(k))
1990
+ problems.push(`unknown key "${key}.${k}"`);
1991
+ }
1992
+ const str = (v, dotted) => {
1993
+ if (v === undefined)
1994
+ return null;
1995
+ if (typeof v === "string" && v.trim())
1996
+ return v.trim();
1997
+ problems.push(`"${dotted}" must be a non-empty string`);
1998
+ return null;
1999
+ };
2000
+ const table = (key) => isTable2(raw[key]) ? raw[key] : {};
2001
+ const config = {
2002
+ language: str(raw.language, "language"),
2003
+ turso: { url: str(table("turso").url, "turso.url") },
2004
+ dashboard: { url: str(table("dashboard").url, "dashboard.url") }
2005
+ };
2006
+ if (problems.length)
2007
+ throw new ConfigError(source, problems);
2008
+ return config;
2009
+ }
2010
+ async function readPersonalConfig(path) {
2011
+ let text;
2012
+ try {
2013
+ text = await readFile(path, "utf8");
2014
+ } catch (err) {
2015
+ if (missing(err))
2016
+ return { exists: false, config: EMPTY_PERSONAL_CONFIG };
2017
+ throw err;
2018
+ }
2019
+ return { exists: true, config: parsePersonalConfig(text, path) };
2020
+ }
2021
+ var PERSONAL_CONFIG_TEMPLATE = `# Armada personal defaults for this machine. No secrets here:
2022
+ # keys live in the credentials file next to this one (armada auth login).
2023
+
2024
+ # Your language for Armada's messages (BCP 47 tag).
2025
+ # language = "en"
2026
+
2027
+ # [turso]
2028
+ # url = "libsql://<database>-<organization>.turso.io"
2029
+
2030
+ # [dashboard]
2031
+ # url = "https://<your-armada-dashboard>"
2032
+ `;
2033
+ async function ensurePersonalConfig(paths) {
2034
+ try {
2035
+ await stat(paths.config);
2036
+ return false;
2037
+ } catch (err) {
2038
+ if (!missing(err))
2039
+ throw err;
2040
+ }
2041
+ await writePrivate(paths, paths.config, PERSONAL_CONFIG_TEMPLATE, 420);
2042
+ return true;
2043
+ }
2044
+ // ../core/src/status.ts
2045
+ var STATUS_SCHEMA_VERSION = 1;
2046
+ function buildStatus({ config, program, forge, forgeError = null, now }) {
2047
+ const issues = attachPullRequests(program, forge);
2048
+ const m = buildModel(issues, program.rootId);
2049
+ const lanes = inFlight(m, program.comments, {
2050
+ now: now.getTime(),
2051
+ silentAfterMinutes: config.policy.silentAfterMinutes
2052
+ });
2053
+ const phaseOf = new Map(lanes.map((l) => [l.issue.id, l.phase]));
2054
+ const prRef = (p) => ({
2055
+ number: p.number,
2056
+ url: p.url,
2057
+ title: p.title,
2058
+ draft: p.draft ?? null,
2059
+ ci: p.ci ?? null,
2060
+ mergeable: p.mergeable ?? null
2061
+ });
2062
+ return {
2063
+ schemaVersion: STATUS_SCHEMA_VERSION,
2064
+ generatedAt: now.toISOString(),
2065
+ project: { name: config.project.name, slug: config.project.slug, repository: config.github.repository },
2066
+ programRoot: { id: m.root.id, title: m.root.title, url: m.root.url },
2067
+ sources: {
2068
+ linear: { fetchedAt: program.fetchedAt },
2069
+ github: { fetchedAt: forge?.fetchedAt ?? null, error: forge ? null : forgeError ?? "not read" }
2070
+ },
2071
+ silentAfterMinutes: config.policy.silentAfterMinutes,
2072
+ inFlight: lanes.map((l) => ({
2073
+ id: l.issue.id,
2074
+ title: l.issue.title,
2075
+ url: l.issue.url,
2076
+ spec: l.spec,
2077
+ phase: l.phase,
2078
+ phaseSource: l.phaseSource,
2079
+ runtime: l.runtime,
2080
+ agent: l.agent,
2081
+ since: l.since,
2082
+ lastUpdate: l.lastUpdate,
2083
+ silent: l.flags.includes("silent"),
2084
+ statusLine: l.statusLine ? { summary: l.statusLine.summary, at: l.statusLine.at, url: l.statusLine.url } : null,
2085
+ pr: l.pr ? prRef(l.pr) : null,
2086
+ openBlockers: l.openBlockers,
2087
+ flags: l.flags
2088
+ })),
2089
+ frontier: frontier(m, config.tracker.readyLabel).map((c) => ({
2090
+ id: c.issue.id,
2091
+ title: c.issue.title,
2092
+ url: c.issue.url,
2093
+ spec: c.spec,
2094
+ readyForAgent: c.readyForAgent,
2095
+ onCriticalPath: c.onCriticalPath,
2096
+ unlocks: c.unlocksAll
2097
+ })),
2098
+ pullRequests: forge ? waitingPullRequests(m, forge.prs).map(({ pr, ticket }) => ({
2099
+ ...prRef(pr),
2100
+ headSha: pr.headSha ?? null,
2101
+ updatedAt: pr.updatedAt ?? null,
2102
+ failingChecks: (pr.checks ?? []).filter((c) => c.state === "failure").map((c) => c.name),
2103
+ ticket: ticket ? { id: ticket.id, phase: phaseOf.get(ticket.id) ?? ticket.agentPhase } : null
2104
+ })) : null,
2105
+ warnings: [...program.warnings, ...forge?.warnings ?? []]
2106
+ };
2107
+ }
2108
+ async function loadStatus(config, opts) {
2109
+ const now = opts.now ?? (() => new Date);
2110
+ const programP = fetchProgram({
2111
+ apiKey: opts.linearApiKey,
2112
+ rootId: config.tracker.programRoot,
2113
+ labels: config.tracker.labels,
2114
+ ...opts.fetch ? { fetch: opts.fetch } : {},
2115
+ now
2116
+ });
2117
+ const forgeP = opts.githubToken ? fetchForge({
2118
+ token: opts.githubToken,
2119
+ repository: config.github.repository,
2120
+ ...opts.fetch ? { fetch: opts.fetch } : {},
2121
+ now
2122
+ }).then((forge2) => ({ forge: forge2, error: null }), (err) => ({ forge: null, error: err instanceof Error ? err.message : String(err) })) : Promise.resolve({ forge: null, error: "no GitHub token (set GITHUB_TOKEN or run gh auth login)" });
2123
+ const [program, { forge, error }] = await Promise.all([programP, forgeP]);
2124
+ return buildStatus({ config, program, forge, forgeError: error, now: now() });
2125
+ }
2126
+ // package.json
2127
+ var version = "0.0.0";
2128
+
2129
+ // src/io.ts
2130
+ class UsageError extends Error {
2131
+ }
2132
+
2133
+ // src/auth.ts
2134
+ async function loadMachine(io) {
2135
+ const paths = machinePaths(io.env);
2136
+ if (!paths)
2137
+ return { paths, store: null, personal: null };
2138
+ const [store, personal] = await Promise.all([
2139
+ readCredentialStore(paths.credentials),
2140
+ readPersonalConfig(paths.config)
2141
+ ]);
2142
+ return { paths, store, personal };
2143
+ }
2144
+ async function loadCredentials(io) {
2145
+ const machine2 = await loadMachine(io);
2146
+ const credentials2 = resolveCredentials({
2147
+ env: io.env,
2148
+ ghToken: io.ghToken,
2149
+ ...machine2.store ? { store: machine2.store.values } : {},
2150
+ ...machine2.personal ? { personal: machine2.personal.config } : {}
2151
+ });
2152
+ return { machine: machine2, credentials: credentials2 };
2153
+ }
2154
+ var describeSource = (s) => {
2155
+ switch (s.kind) {
2156
+ case "env":
2157
+ return `environment (${s.variable})`;
2158
+ case "store":
2159
+ return "credentials file";
2160
+ case "config":
2161
+ return `personal config (${s.key})`;
2162
+ case "gh":
2163
+ return "GitHub CLI login (gh auth token)";
2164
+ }
2165
+ };
2166
+ var octal = (mode) => `0${mode.toString(8).padStart(3, "0")}`;
2167
+ function requirePaths(paths) {
2168
+ if (paths)
2169
+ return paths;
2170
+ throw new UsageError(`neither HOME nor XDG_CONFIG_HOME is set, so there is no place to store keys on this machine. Set ${STORED_KEYS.map((k) => k.variable).join(", ")} in the environment instead.`);
2171
+ }
2172
+ function storeWarnings(machine2) {
2173
+ const store = machine2.store;
2174
+ if (!store?.exists)
2175
+ return [];
2176
+ const warnings = [];
2177
+ if (storeIsExposed(store) && store.mode !== null)
2178
+ warnings.push(`${store.path} can be read by other users (mode ${octal(store.mode)}); run: chmod 600 ${store.path}`);
2179
+ for (const line of store.invalidLines)
2180
+ warnings.push(`${store.path} line ${line} is not KEY=value; it is kept but ignored`);
2181
+ return warnings;
2182
+ }
2183
+ async function authLogin(io) {
2184
+ const { machine: machine2, credentials: credentials2 } = await loadCredentials(io);
2185
+ const missing2 = missingKeys(credentials2);
2186
+ if (!missing2.length) {
2187
+ io.stdout("Every Armada key is already set. Run `armada auth status` to see where each comes from.\n");
2188
+ return 0;
2189
+ }
2190
+ const paths = requirePaths(machine2.paths);
2191
+ if (!io.interactive || !io.prompt) {
2192
+ const width = Math.max(...missing2.map((k) => k.variable.length));
2193
+ io.stderr(`armada: auth login needs an interactive terminal. Set these environment variables instead:
2194
+ ${missing2.map((k) => ` ${k.variable.padEnd(width)} ${k.label}: ${k.hint}`).join(`
2195
+ `)}
2196
+ or add them as KEY=value lines to ${paths.credentials} (mode 0600).
2197
+ `);
2198
+ return 2;
2199
+ }
2200
+ io.stderr(`Armada keeps its keys in ${paths.credentials}, readable only by you.
2201
+ Leave an answer empty to skip it.
2202
+ `);
2203
+ const updates = {};
2204
+ for (const key of missing2) {
2205
+ io.stderr(`
2206
+ ${key.label}: ${key.hint}
2207
+ `);
2208
+ const answer = await io.prompt(`${key.variable}${key.secret ? " (hidden)" : ""}: `, { hidden: key.secret });
2209
+ if (answer === null) {
2210
+ io.stderr(`Cancelled. Nothing was saved.
2211
+ `);
2212
+ return 130;
2213
+ }
2214
+ const value = answer.trim();
2215
+ if (value)
2216
+ updates[key.variable] = value;
2217
+ }
2218
+ const saved = Object.keys(updates);
2219
+ if (saved.length) {
2220
+ await updateCredentialStore(paths, updates);
2221
+ io.stdout(`
2222
+ Saved ${saved.join(", ")} in ${paths.credentials}.
2223
+ `);
2224
+ if (await ensurePersonalConfig(paths))
2225
+ io.stdout(`Created ${paths.config} for your personal defaults.
2226
+ `);
2227
+ } else
2228
+ io.stdout(`
2229
+ Nothing saved.
2230
+ `);
2231
+ const skipped = missing2.filter((k) => !saved.includes(k.variable)).map((k) => k.variable);
2232
+ if (skipped.length)
2233
+ io.stdout(`Still missing: ${skipped.join(", ")}. Run \`armada auth login\` again to add them.
2234
+ `);
2235
+ return 0;
2236
+ }
2237
+ function buildAuthStatus(machine2, credentials2) {
2238
+ const keys = [
2239
+ ...STORED_KEYS.map((k) => ({ variable: k.variable, label: k.label, source: credentials2.sources[k.name] })),
2240
+ { variable: "GITHUB_TOKEN", label: "GitHub token", source: credentials2.sources.githubToken }
2241
+ ].map((k) => ({ ...k, present: k.source !== null }));
2242
+ return {
2243
+ schemaVersion: 1,
2244
+ keys,
2245
+ credentialsFile: machine2.store ? {
2246
+ path: machine2.store.path,
2247
+ exists: machine2.store.exists,
2248
+ mode: machine2.store.mode === null ? null : octal(machine2.store.mode)
2249
+ } : null,
2250
+ personalConfig: machine2.paths && machine2.personal ? { path: machine2.paths.config, exists: machine2.personal.exists } : null,
2251
+ warnings: storeWarnings(machine2)
2252
+ };
2253
+ }
2254
+ function renderAuthStatus(status2) {
2255
+ const width = Math.max(...status2.keys.map((k) => k.variable.length));
2256
+ const lines = ["Armada keys"];
2257
+ for (const k of status2.keys) {
2258
+ const where = k.source ? describeSource(k.source) : k.variable === "GITHUB_TOKEN" ? "set GITHUB_TOKEN or run `gh auth login`" : `set ${k.variable} or run \`armada auth login\``;
2259
+ lines.push(` ${k.variable.padEnd(width)} ${(k.present ? "set" : "missing").padEnd(7)} ${where}`);
2260
+ }
2261
+ lines.push("");
2262
+ const file = status2.credentialsFile;
2263
+ lines.push(file ? `Credentials file ${file.path}${file.exists ? ` (mode ${file.mode})` : " (not created yet)"}` : "Credentials file none: neither HOME nor XDG_CONFIG_HOME is set");
2264
+ if (status2.personalConfig)
2265
+ lines.push(`Personal config ${status2.personalConfig.path}${status2.personalConfig.exists ? "" : " (not created yet)"}`);
2266
+ for (const w of status2.warnings)
2267
+ lines.push(`! ${w}`);
2268
+ return `${lines.join(`
2269
+ `)}
2270
+ `;
2271
+ }
2272
+ async function authStatus(io, json) {
2273
+ const { machine: machine2, credentials: credentials2 } = await loadCredentials(io);
2274
+ const status2 = buildAuthStatus(machine2, credentials2);
2275
+ io.stdout(json ? `${JSON.stringify(status2, null, 2)}
2276
+ ` : renderAuthStatus(status2));
2277
+ return 0;
2278
+ }
2279
+ async function authLogout(io) {
2280
+ const paths = requirePaths(machinePaths(io.env));
2281
+ const store = await readCredentialStore(paths.credentials);
2282
+ const stored = STORED_KEYS.filter((k) => store.assigned.includes(k.variable));
2283
+ if (!stored.length) {
2284
+ io.stdout(`No Armada key is stored in ${paths.credentials}.
2285
+ `);
2286
+ } else {
2287
+ await updateCredentialStore(paths, Object.fromEntries(STORED_KEYS.map((k) => [k.variable, null])));
2288
+ io.stdout(`Removed ${stored.map((k) => k.variable).join(", ")} from ${paths.credentials}.
2289
+ `);
2290
+ }
2291
+ const fromEnv2 = STORED_KEYS.filter((k) => io.env[k.variable]?.trim()).map((k) => k.variable);
2292
+ if (fromEnv2.length)
2293
+ io.stdout(`Still set in the environment, and still used: ${fromEnv2.join(", ")}. Unset them to stop using them.
2294
+ `);
2295
+ return 0;
2296
+ }
2297
+
2298
+ // src/render.ts
2299
+ var MIN2 = 60000;
2300
+ function relative(iso, now) {
2301
+ const diff = now - Date.parse(iso);
2302
+ const m = Math.round(Math.abs(diff) / MIN2);
2303
+ const suffix = diff >= 0 ? "ago" : "from now";
2304
+ if (m < 1)
2305
+ return "just now";
2306
+ if (m < 60)
2307
+ return `${m} min ${suffix}`;
2308
+ const h = Math.round(m / 60);
2309
+ if (h < 48)
2310
+ return `${h} h ${suffix}`;
2311
+ return `${Math.round(h / 24)} d ${suffix}`;
2312
+ }
2313
+ var truncate = (s, n) => s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s;
2314
+ var pad = (s, n) => s.padEnd(n);
2315
+ var MERGEABLE = {
2316
+ MERGEABLE: "mergeable",
2317
+ CONFLICTING: "conflicts",
2318
+ UNKNOWN: "mergeability unknown"
2319
+ };
2320
+ function prState(pr) {
2321
+ return [
2322
+ pr.draft ? "draft" : null,
2323
+ pr.ci === "none" ? "no CI" : pr.ci ? `CI ${pr.ci}` : null,
2324
+ pr.mergeable ? MERGEABLE[pr.mergeable] ?? pr.mergeable.toLowerCase() : null
2325
+ ].filter(Boolean).join(" · ");
2326
+ }
2327
+ var phaseLabel = (t) => t.phaseSource === "label" ? t.phase : `${t.phase} (${t.phaseSource})`;
2328
+ function renderStatus(r) {
2329
+ const now = Date.parse(r.generatedAt);
2330
+ const out = [];
2331
+ const idWidth = Math.max(6, ...r.inFlight.map((t) => t.id.length), ...r.frontier.map((t) => t.id.length), ...(r.pullRequests ?? []).map((p) => `#${p.number}`.length));
2332
+ const indent = " ".repeat(idWidth + 4);
2333
+ const phaseWidth = Math.max(0, ...r.inFlight.map((t) => phaseLabel(t).length));
2334
+ out.push(`${r.project.name} · ${r.programRoot.id} ${r.programRoot.title}`);
2335
+ const gh = r.sources.github.error ? `GitHub not read: ${r.sources.github.error}` : `GitHub ${r.project.repository}`;
2336
+ out.push(`Read ${r.generatedAt.slice(0, 16).replace("T", " ")} UTC · Linear ${r.programRoot.id} · ${gh}`);
2337
+ out.push("", `In flight (${r.inFlight.length})`);
2338
+ if (!r.inFlight.length)
2339
+ out.push(" nobody is working");
2340
+ for (const t of r.inFlight) {
2341
+ const who = [t.runtime, t.agent].filter(Boolean).join(" · ") || "unassigned";
2342
+ out.push(` ${pad(t.id, idWidth)} ${pad(phaseLabel(t), phaseWidth)} ${who} · updated ${relative(t.lastUpdate, now)}`);
2343
+ out.push(`${indent}${truncate(t.title, 90)}${t.spec ? ` [${t.spec}]` : ""}`);
2344
+ if (t.statusLine?.summary)
2345
+ out.push(`${indent}“${truncate(t.statusLine.summary, 100)}”`);
2346
+ if (t.pr)
2347
+ out.push(`${indent}${[`PR #${t.pr.number}`, prState(t.pr)].filter(Boolean).join(" · ")}`);
2348
+ if (t.flags.length)
2349
+ out.push(`${indent}! ${t.flags.join(", ")}`);
2350
+ }
2351
+ const ready = r.frontier.filter((t) => t.readyForAgent);
2352
+ const untriaged = r.frontier.filter((t) => !t.readyForAgent);
2353
+ out.push("", `Ready to start (${ready.length})`);
2354
+ if (!ready.length)
2355
+ out.push(" no unblocked ticket is marked ready");
2356
+ for (const t of ready) {
2357
+ const meta = [
2358
+ t.spec,
2359
+ t.unlocks.length ? `unlocks ${t.unlocks.length}` : null,
2360
+ t.onCriticalPath ? "critical path" : null
2361
+ ].filter(Boolean).join(" · ");
2362
+ out.push(` ${pad(t.id, idWidth)} ${truncate(t.title, 80)}${meta ? ` (${meta})` : ""}`);
2363
+ }
2364
+ if (untriaged.length) {
2365
+ out.push("", `Unblocked but not marked ready (${untriaged.length})`);
2366
+ for (const t of untriaged)
2367
+ out.push(` ${pad(t.id, idWidth)} ${truncate(t.title, 80)}`);
2368
+ }
2369
+ out.push("", `Pull requests waiting (${r.pullRequests?.length ?? "?"})`);
2370
+ if (!r.pullRequests)
2371
+ out.push(" GitHub was not read");
2372
+ else if (!r.pullRequests.length)
2373
+ out.push(" none open");
2374
+ for (const p of r.pullRequests ?? []) {
2375
+ const ticket = p.ticket ? `${p.ticket.id}${p.ticket.phase ? ` ${p.ticket.phase}` : ""}` : "no ticket";
2376
+ out.push(` ${pad(`#${p.number}`, idWidth)} ${[ticket, prState(p)].filter(Boolean).join(" · ")}`);
2377
+ out.push(`${indent}${truncate(p.title, 90)}`);
2378
+ if (p.failingChecks.length)
2379
+ out.push(`${indent}! failing: ${p.failingChecks.join(", ")}`);
2380
+ }
2381
+ if (r.warnings.length) {
2382
+ out.push("", `Warnings (${r.warnings.length})`);
2383
+ for (const w of r.warnings)
2384
+ out.push(` ! ${w}`);
2385
+ }
2386
+ return `${out.join(`
2387
+ `)}
2388
+ `;
2389
+ }
2390
+
2391
+ // src/cli.ts
2392
+ var USAGE = `Usage: armada <command> [options]
2393
+
2394
+ Commands:
2395
+ status Tickets in flight, tickets ready to start and pull requests waiting
2396
+ auth login Ask for the missing keys (hidden input) and store them on this machine
2397
+ auth status Show which keys are set and where each comes from, never their values
2398
+ auth logout Remove Armada's keys from this machine
2399
+
2400
+ Options:
2401
+ --json Print the status as JSON
2402
+ --config <path> Use this armada.toml instead of searching from the current directory
2403
+ -h, --help Show this help
2404
+ -v, --version Print the version
2405
+
2406
+ Keys (the environment always wins over the file):
2407
+ LINEAR_API_KEY Linear API key (required by status)
2408
+ ARMADA_TURSO_URL Turso database URL
2409
+ ARMADA_TURSO_TOKEN Turso database token
2410
+ GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
2411
+
2412
+ Files:
2413
+ $XDG_CONFIG_HOME/armada (default ~/.config/armada)
2414
+ credentials KEY=value lines, mode 0600, written by \`armada auth login\`
2415
+ config.toml personal defaults: language, [turso] url, [dashboard] url
2416
+ `;
2417
+ function parseArgs(argv) {
2418
+ const args = { command: null, rest: [], json: false, config: null, help: false, version: false };
2419
+ for (let k = 0;k < argv.length; k++) {
2420
+ const a = argv[k];
2421
+ if (a === "--json")
2422
+ args.json = true;
2423
+ else if (a === "-h" || a === "--help")
2424
+ args.help = true;
2425
+ else if (a === "-v" || a === "--version")
2426
+ args.version = true;
2427
+ else if (a === "--config") {
2428
+ const v = argv[++k];
2429
+ if (!v)
2430
+ throw new UsageError("--config needs a path");
2431
+ args.config = v;
2432
+ } else if (a?.startsWith("--config="))
2433
+ args.config = a.slice("--config=".length);
2434
+ else if (a?.startsWith("-"))
2435
+ throw new UsageError(`unknown option ${a}`);
2436
+ else if (!args.command && a)
2437
+ args.command = a;
2438
+ else if (a)
2439
+ args.rest.push(a);
2440
+ }
2441
+ return args;
2442
+ }
2443
+ async function findConfig(io, explicit) {
2444
+ if (explicit) {
2445
+ const path = resolve(io.cwd, explicit);
2446
+ const text = await io.readFile(path);
2447
+ if (text === null)
2448
+ throw new UsageError(`${path} does not exist`);
2449
+ return { path, text };
2450
+ }
2451
+ for (let dir = resolve(io.cwd);; dir = dirname(dir)) {
2452
+ const path = join2(dir, CONFIG_FILE);
2453
+ const text = await io.readFile(path);
2454
+ if (text !== null)
2455
+ return { path, text };
2456
+ if (dirname(dir) === dir)
2457
+ break;
2458
+ }
2459
+ throw new UsageError(`no ${CONFIG_FILE} found in ${io.cwd} or any parent directory. Add one at the repository root (see README).`);
2460
+ }
2461
+ async function status2(io, args) {
2462
+ const { path, text } = await findConfig(io, args.config);
2463
+ const config2 = parseConfig(text, path);
2464
+ const { linearApiKey, githubToken } = (await loadCredentials(io)).credentials;
2465
+ if (!linearApiKey)
2466
+ throw new UsageError(missingKeyMessage(LINEAR_KEY));
2467
+ const report = await loadStatus(config2, {
2468
+ linearApiKey,
2469
+ githubToken,
2470
+ ...io.fetch ? { fetch: io.fetch } : {},
2471
+ ...io.now ? { now: io.now } : {}
2472
+ });
2473
+ io.stdout(args.json ? `${JSON.stringify(report, null, 2)}
2474
+ ` : renderStatus(report));
2475
+ return 0;
2476
+ }
2477
+ function noExtra(rest) {
2478
+ if (rest.length)
2479
+ throw new UsageError(`unexpected argument ${rest[0]}`);
2480
+ }
2481
+ async function run(argv, io) {
2482
+ try {
2483
+ const args = parseArgs(argv);
2484
+ if (args.version) {
2485
+ io.stdout(`${version}
2486
+ `);
2487
+ return 0;
2488
+ }
2489
+ if (args.help || !args.command) {
2490
+ (args.help ? io.stdout : io.stderr)(USAGE);
2491
+ return args.help ? 0 : 2;
2492
+ }
2493
+ if (args.command === "status") {
2494
+ noExtra(args.rest);
2495
+ return await status2(io, args);
2496
+ }
2497
+ if (args.command === "auth") {
2498
+ const [sub, ...extra] = args.rest;
2499
+ noExtra(extra);
2500
+ if (sub === "login")
2501
+ return await authLogin(io);
2502
+ if (sub === "status")
2503
+ return await authStatus(io, args.json);
2504
+ if (sub === "logout")
2505
+ return await authLogout(io);
2506
+ throw new UsageError(sub ? `unknown auth command "${sub}"` : "auth needs a command: login, status or logout");
2507
+ }
2508
+ throw new UsageError(`unknown command "${args.command}"`);
2509
+ } catch (err) {
2510
+ if (err instanceof UsageError || err instanceof ConfigError) {
2511
+ io.stderr(`armada: ${err.message}
2512
+ `);
2513
+ return 2;
2514
+ }
2515
+ io.stderr(`armada: ${err instanceof Error ? err.message : String(err)}
2516
+ `);
2517
+ return 1;
2518
+ }
2519
+ }
2520
+
2521
+ // src/line.ts
2522
+ var emptyLine = () => ({ answer: "", sequence: "none" });
2523
+ function feedLine(line, chunk) {
2524
+ let { answer, sequence } = line;
2525
+ for (const c of chunk) {
2526
+ if (sequence === "start")
2527
+ sequence = c === "[" ? "csi" : "none";
2528
+ else if (sequence === "csi") {
2529
+ if (c >= "@" && c <= "~")
2530
+ sequence = "none";
2531
+ } else if (c === "\x1B")
2532
+ sequence = "start";
2533
+ else if (c === "\r" || c === `
2534
+ `)
2535
+ return { answer, sequence, result: answer };
2536
+ else if (c === "\x03" || c === "\x04" && !answer)
2537
+ return { answer, sequence, result: null };
2538
+ else if (c === "" || c === "\b")
2539
+ answer = answer.slice(0, -1);
2540
+ else if (c >= " ")
2541
+ answer += c;
2542
+ }
2543
+ return { answer, sequence };
2544
+ }
2545
+ function echo(before, after) {
2546
+ let common = 0;
2547
+ while (common < before.length && common < after.length && before[common] === after[common])
2548
+ common++;
2549
+ return "\b \b".repeat(before.length - common) + after.slice(common);
2550
+ }
2551
+
2552
+ // src/main.ts
2553
+ function ghToken() {
2554
+ try {
2555
+ const r = spawnSync("gh", ["auth", "token"], { encoding: "utf8", timeout: 5000 });
2556
+ return r.status === 0 ? r.stdout.trim() || null : null;
2557
+ } catch {
2558
+ return null;
2559
+ }
2560
+ }
2561
+ function prompt(question, { hidden }) {
2562
+ const stdin = process.stdin;
2563
+ return new Promise((done) => {
2564
+ let line = emptyLine();
2565
+ const onData = (chunk) => {
2566
+ const before = line.answer;
2567
+ line = feedLine(line, chunk);
2568
+ if (!hidden && line.result !== null)
2569
+ process.stderr.write(echo(before, line.answer));
2570
+ if (line.result === undefined)
2571
+ return;
2572
+ stdin.off("data", onData);
2573
+ stdin.setRawMode(false);
2574
+ stdin.pause();
2575
+ process.stderr.write(`
2576
+ `);
2577
+ done(line.result);
2578
+ };
2579
+ stdin.setRawMode(true);
2580
+ process.stderr.write(question);
2581
+ stdin.setEncoding("utf8");
2582
+ stdin.on("data", onData);
2583
+ stdin.resume();
2584
+ });
2585
+ }
2586
+ var code = await run(process.argv.slice(2), {
2587
+ cwd: process.cwd(),
2588
+ env: process.env,
2589
+ readFile: (path) => readFile2(path, "utf8").catch((err) => {
2590
+ if (err.code === "ENOENT" || err.code === "ENOTDIR")
2591
+ return null;
2592
+ throw err;
2593
+ }),
2594
+ stdout: (t) => process.stdout.write(t),
2595
+ stderr: (t) => process.stderr.write(t),
2596
+ ghToken,
2597
+ interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
2598
+ prompt
2599
+ });
2600
+ process.stdout.write("", () => process.exit(code));