@the-vibe-company/armada 0.1.21 → 0.2.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 (3) hide show
  1. package/README.md +62 -28
  2. package/dist/armada.js +283 -1041
  3. package/package.json +2 -5
package/dist/armada.js CHANGED
@@ -343,6 +343,7 @@ function armadaApi(opts) {
343
343
  const timeoutMs = opts.timeoutMs ?? TIMEOUT_MS;
344
344
  const host = base.host;
345
345
  async function call(method, path, init = {}) {
346
+ const limit = init.timeoutMs ?? timeoutMs;
346
347
  const headers = { Accept: "application/json" };
347
348
  if (init.body)
348
349
  headers["Content-Type"] = "application/json";
@@ -354,10 +355,12 @@ function armadaApi(opts) {
354
355
  method,
355
356
  headers,
356
357
  ...init.body ? { body: JSON.stringify(init.body) } : {},
357
- signal: AbortSignal.timeout(timeoutMs)
358
+ signal: AbortSignal.timeout(limit)
358
359
  }).catch((err) => {
359
- throw new ArmadaApiError(`Armada (${host}) unreachable: ${networkReason(err, timeoutMs)}`, "the same command again once it answers, or check ARMADA_API_URL");
360
+ throw new ArmadaApiError(`Armada (${host}) unreachable: ${networkReason(err, limit)}`, "the same command again once it answers, or check ARMADA_API_URL");
360
361
  });
362
+ if (res.status === 304)
363
+ return { status: 304, body: {} };
361
364
  const body = await res.json().catch(() => null);
362
365
  if (typeof body !== "object" || body === null || Array.isArray(body))
363
366
  throw new ArmadaApiError(`Armada (${host}) answered HTTP ${res.status} without JSON: is ${base.origin} an Armada?`, "check ARMADA_API_URL or [api] url in config.toml");
@@ -409,22 +412,45 @@ function armadaApi(opts) {
409
412
  throw refusal(status, body, status === 401 ? null : "Armada could not say who is signed in");
410
413
  return body;
411
414
  },
412
- async credentials(signIn, held, purpose = null) {
413
- const { status, body } = await call("POST", "credentials", {
414
- signIn,
415
- body: purpose ? { turso: held, purpose } : { turso: held }
416
- });
415
+ async credentials(signIn, purpose = null) {
416
+ const { status, body } = await call("POST", "credentials", { signIn, body: purpose ? { purpose } : {} });
417
417
  if (status !== 200)
418
418
  throw refusal(status, body, status === 401 ? null : "Armada gave no keys");
419
419
  const str = (v) => typeof v === "string" && v.length > 0;
420
420
  const org = body.organization;
421
421
  const linear = body.linear;
422
- const turso = body.turso;
423
- const shaped = body.schemaVersion === 1 && str(org?.id) && (linear === null || str(linear?.apiKey)) && (turso === null || turso?.kind === "kept" && str(turso.revision) && str(turso.expiresAt) || (turso?.kind === "minted" || turso?.kind === "stored") && str(turso.url) && str(turso.token));
422
+ const shaped = body.schemaVersion === 1 && str(org?.id) && (linear === null || str(linear?.apiKey));
424
423
  if (!shaped)
425
424
  throw new ArmadaApiError(`Armada (${host}) answered the keys in a shape this CLI does not know`);
426
425
  const warnings = Array.isArray(body.warnings) ? body.warnings.filter((w) => typeof w === "string") : [];
427
- return { ...body, warnings };
426
+ return {
427
+ schemaVersion: 1,
428
+ organization: org,
429
+ linear: linear ? { apiKey: linear.apiKey, scope: linear.scope === "own" ? "own" : "organization" } : null,
430
+ warnings
431
+ };
432
+ },
433
+ async projects(signIn) {
434
+ const { status, body } = await call("GET", "projects", { signIn });
435
+ if (status !== 200)
436
+ throw refusal(status, body, status === 401 ? null : "Armada did not list the projects");
437
+ if (!Array.isArray(body.projects))
438
+ throw new ArmadaApiError(`Armada (${host}) answered the projects in a shape this CLI does not know`);
439
+ return body.projects.flatMap((p) => typeof p.slug === "string" && typeof p.name === "string" && typeof p.repository === "string" && typeof p.programRoot === "string" ? [{ slug: p.slug, name: p.name, repository: p.repository, programRoot: p.programRoot }] : []);
440
+ },
441
+ async fleet(signIn, op, body, timeoutMs) {
442
+ const { status, body: answer } = await call("POST", `fleet/${op}`, {
443
+ signIn,
444
+ body,
445
+ ...timeoutMs ? { timeoutMs } : {}
446
+ });
447
+ if (status === 304)
448
+ return null;
449
+ if (status !== 200)
450
+ throw refusal(status, answer, status === 401 ? null : "Armada refused");
451
+ if (!("result" in answer))
452
+ throw new ArmadaApiError(`Armada (${host}) answered fleet/${op} in a shape this CLI does not know`);
453
+ return answer.result;
428
454
  },
429
455
  async launchToken(signIn, target) {
430
456
  const { status, body } = await call("POST", "launch-tokens", { signIn, body: target });
@@ -2180,499 +2206,6 @@ function checkProblems(checks, requiredChecks) {
2180
2206
  return problems;
2181
2207
  }
2182
2208
 
2183
- // ../core/src/turso.ts
2184
- var MIGRATIONS = [
2185
- {
2186
- version: 1,
2187
- statements: [
2188
- `CREATE TABLE IF NOT EXISTS projects (
2189
- slug TEXT PRIMARY KEY,
2190
- name TEXT NOT NULL,
2191
- repository TEXT NOT NULL,
2192
- program_root TEXT NOT NULL,
2193
- created_at TEXT NOT NULL,
2194
- updated_at TEXT NOT NULL
2195
- )`,
2196
- `CREATE TABLE IF NOT EXISTS events (
2197
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2198
- project TEXT NOT NULL,
2199
- ticket TEXT NOT NULL,
2200
- kind TEXT NOT NULL,
2201
- phase TEXT,
2202
- message TEXT,
2203
- runtime TEXT,
2204
- handle TEXT,
2205
- pr_url TEXT,
2206
- head_sha TEXT,
2207
- created_at TEXT NOT NULL
2208
- )`,
2209
- "CREATE INDEX IF NOT EXISTS events_by_ticket ON events (project, ticket, created_at)",
2210
- `CREATE TABLE IF NOT EXISTS runtime_handles (
2211
- project TEXT NOT NULL,
2212
- ticket TEXT NOT NULL,
2213
- runtime TEXT NOT NULL,
2214
- handle TEXT NOT NULL,
2215
- branch TEXT,
2216
- claimed_at TEXT NOT NULL,
2217
- released_at TEXT,
2218
- PRIMARY KEY (project, ticket)
2219
- )`,
2220
- `CREATE TABLE IF NOT EXISTS inbox_items (
2221
- id INTEGER PRIMARY KEY AUTOINCREMENT,
2222
- project TEXT NOT NULL,
2223
- ticket TEXT,
2224
- kind TEXT NOT NULL,
2225
- recipient TEXT NOT NULL,
2226
- author TEXT,
2227
- body TEXT NOT NULL,
2228
- created_at TEXT NOT NULL,
2229
- resolved_at TEXT,
2230
- resolution TEXT
2231
- )`,
2232
- "CREATE INDEX IF NOT EXISTS inbox_open ON inbox_items (project, recipient, resolved_at)",
2233
- `CREATE TABLE IF NOT EXISTS leases (
2234
- project TEXT NOT NULL,
2235
- name TEXT NOT NULL,
2236
- holder TEXT NOT NULL,
2237
- acquired_at TEXT NOT NULL,
2238
- expires_at TEXT NOT NULL,
2239
- PRIMARY KEY (project, name)
2240
- )`
2241
- ]
2242
- },
2243
- {
2244
- version: 2,
2245
- statements: [
2246
- "CREATE INDEX IF NOT EXISTS events_by_time ON events (project, created_at)",
2247
- "CREATE INDEX IF NOT EXISTS events_by_kind ON events (project, kind, created_at)"
2248
- ]
2249
- },
2250
- {
2251
- version: 3,
2252
- statements: [
2253
- `CREATE TABLE IF NOT EXISTS worker_profiles (
2254
- project TEXT NOT NULL,
2255
- ticket TEXT NOT NULL,
2256
- profile TEXT NOT NULL,
2257
- agent TEXT NOT NULL,
2258
- model TEXT NOT NULL,
2259
- effort TEXT NOT NULL,
2260
- fast_mode INTEGER NOT NULL,
2261
- routed TEXT,
2262
- reason TEXT,
2263
- why TEXT NOT NULL,
2264
- recorded_at TEXT NOT NULL,
2265
- PRIMARY KEY (project, ticket)
2266
- )`
2267
- ]
2268
- },
2269
- {
2270
- version: 4,
2271
- statements: [
2272
- `CREATE TABLE IF NOT EXISTS inbox_requests (
2273
- item INTEGER PRIMARY KEY,
2274
- project TEXT NOT NULL,
2275
- question INTEGER,
2276
- profile TEXT
2277
- )`,
2278
- "CREATE INDEX IF NOT EXISTS inbox_requests_by_question ON inbox_requests (project, question)"
2279
- ]
2280
- },
2281
- {
2282
- version: 5,
2283
- statements: [
2284
- `CREATE TABLE IF NOT EXISTS project_organizations (
2285
- project TEXT PRIMARY KEY,
2286
- organization TEXT NOT NULL,
2287
- assigned_at TEXT NOT NULL
2288
- )`
2289
- ]
2290
- }
2291
- ];
2292
- var SCHEMA_VERSION = MIGRATIONS.at(-1)?.version ?? 0;
2293
-
2294
- class TursoError extends Error {
2295
- name = "TursoError";
2296
- }
2297
- function redact(err, token) {
2298
- let message = err instanceof Error ? err.message : String(err);
2299
- if (token)
2300
- message = message.split(token).join("***");
2301
- return message.replace(/(authToken=)[^&\s"']+/gi, "$1***");
2302
- }
2303
- async function openTurso({ url, token }) {
2304
- let db;
2305
- try {
2306
- const { createClient } = await import("@libsql/client");
2307
- db = createClient(token ? { url, authToken: token } : { url });
2308
- } catch (err) {
2309
- throw new TursoError(`cannot open the Turso database: ${redact(err, token)}`);
2310
- }
2311
- try {
2312
- await migrate(db);
2313
- } catch (err) {
2314
- db.close();
2315
- throw new TursoError(`Turso database unavailable: ${redact(err, token)}`);
2316
- }
2317
- return db;
2318
- }
2319
- async function migrate(db) {
2320
- await db.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)");
2321
- const current = Number((await db.execute("SELECT max(version) AS v FROM schema_migrations")).rows[0]?.v ?? 0);
2322
- for (const m of MIGRATIONS) {
2323
- if (m.version <= current)
2324
- continue;
2325
- const stmts = [
2326
- ...m.statements,
2327
- {
2328
- sql: "INSERT OR IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)",
2329
- args: [m.version, new Date().toISOString()]
2330
- }
2331
- ];
2332
- await db.batch(stmts, "write");
2333
- }
2334
- return Math.max(current, SCHEMA_VERSION);
2335
- }
2336
- async function upsertProject(db, p, now = new Date) {
2337
- const at = now.toISOString();
2338
- await db.execute({
2339
- sql: `INSERT INTO projects (slug, name, repository, program_root, created_at, updated_at)
2340
- VALUES (?, ?, ?, ?, ?, ?)
2341
- ON CONFLICT (slug) DO UPDATE SET
2342
- name = excluded.name, repository = excluded.repository,
2343
- program_root = excluded.program_root, updated_at = excluded.updated_at
2344
- WHERE name IS NOT excluded.name OR repository IS NOT excluded.repository
2345
- OR program_root IS NOT excluded.program_root`,
2346
- args: [p.slug, p.name, p.repository, p.programRoot, at, at]
2347
- });
2348
- }
2349
- async function ensureProject(db, p, now = new Date) {
2350
- const at = now.toISOString();
2351
- await db.execute({
2352
- sql: `INSERT OR IGNORE INTO projects (slug, name, repository, program_root, created_at, updated_at)
2353
- VALUES (?, ?, ?, ?, ?, ?)`,
2354
- args: [p.slug, p.name, p.repository, p.programRoot, at, at]
2355
- });
2356
- }
2357
- async function listProjects(db) {
2358
- const rs = await db.execute(`SELECT p.slug, p.name, p.repository, p.program_root, o.organization, p.created_at, p.updated_at
2359
- FROM projects p LEFT JOIN project_organizations o ON o.project = p.slug ORDER BY p.slug`);
2360
- return rs.rows.map((r) => ({
2361
- slug: String(r.slug),
2362
- name: String(r.name),
2363
- repository: String(r.repository),
2364
- programRoot: String(r.program_root),
2365
- organization: r.organization === null ? null : String(r.organization),
2366
- createdAt: String(r.created_at),
2367
- updatedAt: String(r.updated_at)
2368
- }));
2369
- }
2370
- var NO_TICKET = "";
2371
- async function recordEvent(db, e) {
2372
- await db.execute({
2373
- sql: `INSERT INTO events (project, ticket, kind, phase, message, runtime, handle, pr_url, head_sha, created_at)
2374
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2375
- args: [
2376
- e.project,
2377
- e.ticket,
2378
- e.kind,
2379
- e.phase ?? null,
2380
- e.message ?? null,
2381
- e.runtime ?? null,
2382
- e.handle ?? null,
2383
- e.prUrl ?? null,
2384
- e.headSha ?? null,
2385
- e.at.toISOString()
2386
- ]
2387
- });
2388
- }
2389
- async function lastEventTimes(db, project) {
2390
- const rs = await db.execute({
2391
- sql: "SELECT ticket, max(created_at) AS at FROM events WHERE project = ? AND ticket <> '' GROUP BY ticket",
2392
- args: [project]
2393
- });
2394
- return Object.fromEntries(rs.rows.map((r) => [String(r.ticket), String(r.at)]));
2395
- }
2396
- async function latestEvents(db, project, opts = {}) {
2397
- const rs = await db.execute({
2398
- sql: `SELECT ticket, kind, phase, message, runtime, handle, pr_url, created_at FROM (
2399
- SELECT *, row_number() OVER (PARTITION BY ticket ORDER BY created_at DESC, id DESC) AS n
2400
- FROM events WHERE project = ? AND created_at >= ? AND ticket <> ''
2401
- ) WHERE n = 1`,
2402
- args: [project, opts.since?.toISOString() ?? ""]
2403
- });
2404
- const text = (v) => v === null || v === undefined ? null : String(v);
2405
- return Object.fromEntries(rs.rows.map((r) => [
2406
- String(r.ticket),
2407
- {
2408
- kind: String(r.kind),
2409
- phase: text(r.phase),
2410
- message: text(r.message),
2411
- runtime: text(r.runtime),
2412
- handle: text(r.handle),
2413
- prUrl: text(r.pr_url),
2414
- at: String(r.created_at)
2415
- }
2416
- ]));
2417
- }
2418
- async function recordCoordinatorSeen(db, seen) {
2419
- await recordEvent(db, {
2420
- project: seen.project,
2421
- ticket: NO_TICKET,
2422
- kind: "inbox",
2423
- handle: seen.handle ?? null,
2424
- at: seen.at
2425
- });
2426
- }
2427
- async function saveWorkerProfile(db, w) {
2428
- const p = w.profile;
2429
- if (!p) {
2430
- await db.execute({
2431
- sql: "DELETE FROM worker_profiles WHERE project = ? AND ticket = ?",
2432
- args: [w.project, w.ticket]
2433
- });
2434
- return;
2435
- }
2436
- await db.execute({
2437
- sql: `INSERT OR REPLACE INTO worker_profiles
2438
- (project, ticket, profile, agent, model, effort, fast_mode, routed, reason, why, recorded_at)
2439
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
2440
- args: [
2441
- w.project,
2442
- w.ticket,
2443
- p.name,
2444
- p.agent,
2445
- p.model,
2446
- p.effort,
2447
- p.fastMode ? 1 : 0,
2448
- p.routed,
2449
- p.reason,
2450
- p.why,
2451
- w.at.toISOString()
2452
- ]
2453
- });
2454
- }
2455
- async function saveRuntimeHandle(db, h) {
2456
- await db.execute({
2457
- sql: `INSERT INTO runtime_handles (project, ticket, runtime, handle, branch, claimed_at, released_at)
2458
- VALUES (?, ?, ?, ?, ?, ?, NULL)
2459
- ON CONFLICT (project, ticket) DO UPDATE SET
2460
- claimed_at = CASE WHEN handle = excluded.handle AND released_at IS NULL
2461
- THEN claimed_at ELSE excluded.claimed_at END,
2462
- runtime = excluded.runtime, handle = excluded.handle, branch = excluded.branch,
2463
- released_at = NULL`,
2464
- args: [h.project, h.ticket, h.runtime, h.handle, h.branch, h.at.toISOString()]
2465
- });
2466
- }
2467
- async function releaseRuntimeHandle(db, project, ticket, at) {
2468
- await db.batch([
2469
- {
2470
- sql: "UPDATE runtime_handles SET released_at = ? WHERE project = ? AND ticket = ? AND released_at IS NULL",
2471
- args: [at.toISOString(), project, ticket]
2472
- },
2473
- { sql: "DELETE FROM worker_profiles WHERE project = ? AND ticket = ?", args: [project, ticket] }
2474
- ], "write");
2475
- }
2476
- async function openRuntimeHandles(db, project) {
2477
- const rs = await db.execute({
2478
- sql: `SELECT h.project, h.ticket, h.runtime, h.handle, h.branch, h.claimed_at, h.released_at, p.profile
2479
- FROM runtime_handles h
2480
- LEFT JOIN worker_profiles p ON p.project = h.project AND p.ticket = h.ticket
2481
- WHERE h.project = ? AND h.released_at IS NULL ORDER BY h.ticket`,
2482
- args: [project]
2483
- });
2484
- return rs.rows.map((r) => ({
2485
- project: String(r.project),
2486
- ticket: String(r.ticket),
2487
- runtime: String(r.runtime),
2488
- handle: String(r.handle),
2489
- branch: r.branch === null ? null : String(r.branch),
2490
- claimedAt: String(r.claimed_at),
2491
- releasedAt: null,
2492
- profile: r.profile === null ? null : String(r.profile)
2493
- }));
2494
- }
2495
- async function getRuntimeHandle(db, project, ticket) {
2496
- const rs = await db.execute({
2497
- sql: `SELECT h.project, h.ticket, h.runtime, h.handle, h.branch, h.claimed_at, h.released_at, p.profile
2498
- FROM runtime_handles h
2499
- LEFT JOIN worker_profiles p ON p.project = h.project AND p.ticket = h.ticket
2500
- WHERE h.project = ? AND h.ticket = ?`,
2501
- args: [project, ticket]
2502
- });
2503
- const r = rs.rows[0];
2504
- return r ? {
2505
- project: String(r.project),
2506
- ticket: String(r.ticket),
2507
- runtime: String(r.runtime),
2508
- handle: String(r.handle),
2509
- branch: r.branch === null ? null : String(r.branch),
2510
- claimedAt: String(r.claimed_at),
2511
- releasedAt: r.released_at === null ? null : String(r.released_at),
2512
- profile: r.profile === null ? null : String(r.profile)
2513
- } : null;
2514
- }
2515
- async function addInboxItem(db, item) {
2516
- const rs = await db.execute({
2517
- sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
2518
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
2519
- args: [item.project, item.ticket, item.kind, item.recipient, item.author, item.body, item.at.toISOString()]
2520
- });
2521
- return Number(rs.lastInsertRowid);
2522
- }
2523
- async function putPlan(db, item) {
2524
- await db.execute({
2525
- sql: `INSERT INTO inbox_items (project, ticket, kind, recipient, author, body, created_at)
2526
- SELECT ?, ?, 'plan', 'coordinator', ?, ?, ?
2527
- WHERE NOT EXISTS (SELECT 1 FROM inbox_items
2528
- WHERE project = ? AND ticket = ? AND kind = 'plan' AND resolved_at IS NULL)`,
2529
- args: [item.project, item.ticket, item.author, item.body, item.at.toISOString(), item.project, item.ticket]
2530
- });
2531
- }
2532
- async function putHandBack(db, item) {
2533
- const updated = await db.execute({
2534
- sql: `UPDATE inbox_items SET body = ?, author = ?, created_at = ?
2535
- WHERE project = ? AND ticket = ? AND kind = 'hand-back' AND resolved_at IS NULL`,
2536
- args: [item.body, item.author, item.at.toISOString(), item.project, item.ticket]
2537
- });
2538
- if (!updated.rowsAffected)
2539
- await addInboxItem(db, { ...item, kind: "hand-back", recipient: "coordinator" });
2540
- }
2541
- var INBOX_COLUMNS = `i.id, i.project, i.ticket, i.kind, i.recipient, i.author, i.body, i.created_at,
2542
- i.resolved_at, i.resolution, q.item AS request_item, q.question AS request_question, q.profile AS request_profile`;
2543
- var INBOX_FROM = "inbox_items i LEFT JOIN inbox_requests q ON q.item = i.id";
2544
- var inboxItem = (r) => ({
2545
- id: Number(r.id),
2546
- project: String(r.project),
2547
- ticket: r.ticket === null ? null : String(r.ticket),
2548
- kind: String(r.kind),
2549
- recipient: String(r.recipient),
2550
- author: r.author === null ? null : String(r.author),
2551
- body: String(r.body),
2552
- createdAt: String(r.created_at),
2553
- ...r.request_item === null || r.request_item === undefined ? {} : {
2554
- request: {
2555
- question: r.request_question === null ? null : Number(r.request_question),
2556
- profile: r.request_profile === null ? null : String(r.request_profile)
2557
- }
2558
- }
2559
- });
2560
- async function openInboxItems(db, q) {
2561
- const rs = await db.execute({
2562
- sql: `SELECT ${INBOX_COLUMNS} FROM ${INBOX_FROM}
2563
- WHERE i.project = ? AND i.recipient = ? AND i.resolved_at IS NULL ${q.ticket ? "AND i.ticket = ?" : ""}
2564
- ORDER BY i.created_at, i.id`,
2565
- args: q.ticket ? [q.project, q.recipient, q.ticket] : [q.project, q.recipient]
2566
- });
2567
- return rs.rows.map(inboxItem);
2568
- }
2569
- var inboxRow = (r) => ({
2570
- ...inboxItem(r),
2571
- resolvedAt: r.resolved_at === null ? null : String(r.resolved_at),
2572
- resolution: r.resolution === null ? null : String(r.resolution)
2573
- });
2574
- async function getInboxItem(db, project, id) {
2575
- const rs = await db.execute({
2576
- sql: `SELECT ${INBOX_COLUMNS} FROM ${INBOX_FROM} WHERE i.project = ? AND i.id = ?`,
2577
- args: [project, id]
2578
- });
2579
- const r = rs.rows[0];
2580
- return r ? inboxRow(r) : null;
2581
- }
2582
- async function resolveInboxItem(db, q) {
2583
- const rs = await db.execute({
2584
- sql: "UPDATE inbox_items SET resolved_at = ?, resolution = ? WHERE project = ? AND id = ? AND resolved_at IS NULL",
2585
- args: [q.at.toISOString(), q.resolution, q.project, q.id]
2586
- });
2587
- return rs.rowsAffected > 0;
2588
- }
2589
- async function lastAnsweredAt(db, project) {
2590
- const rs = await db.execute({
2591
- sql: `SELECT ticket, max(resolved_at) AS at FROM inbox_items
2592
- WHERE project = ? AND kind IN ('question', 'plan') AND ticket IS NOT NULL AND resolved_at IS NOT NULL
2593
- GROUP BY ticket`,
2594
- args: [project]
2595
- });
2596
- return Object.fromEntries(rs.rows.map((r) => [String(r.ticket), String(r.at)]));
2597
- }
2598
- async function resolveInboxItems(db, q) {
2599
- const rs = await db.execute({
2600
- sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2601
- WHERE project = ? AND ticket = ? AND kind = ? AND resolved_at IS NULL`,
2602
- args: [q.at.toISOString(), q.resolution, q.project, q.ticket, q.kind]
2603
- });
2604
- return rs.rowsAffected;
2605
- }
2606
- async function resolveAnswerRequests(db, q) {
2607
- const rs = await db.execute({
2608
- sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2609
- WHERE project = ? AND kind = 'answer-request' AND resolved_at IS NULL
2610
- AND id IN (SELECT item FROM inbox_requests WHERE project = ? AND question = ?)`,
2611
- args: [q.at.toISOString(), q.resolution, q.project, q.project, q.question]
2612
- });
2613
- return rs.rowsAffected;
2614
- }
2615
- async function resolvePlans(db, input) {
2616
- const args = [input.at.toISOString(), input.resolution, input.project, input.ticket];
2617
- const [, resolved] = await db.batch([
2618
- {
2619
- sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2620
- WHERE project = ? AND kind = 'answer-request' AND resolved_at IS NULL
2621
- AND id IN (SELECT q.item FROM inbox_requests q JOIN inbox_items i ON i.id = q.question
2622
- WHERE i.project = ? AND i.ticket = ? AND i.kind = 'plan' AND i.resolved_at IS NULL)`,
2623
- args: [input.at.toISOString(), input.resolution, input.project, input.project, input.ticket]
2624
- },
2625
- {
2626
- sql: `UPDATE inbox_items SET resolved_at = ?, resolution = ?
2627
- WHERE project = ? AND ticket = ? AND kind = 'plan' AND resolved_at IS NULL`,
2628
- args
2629
- }
2630
- ], "write");
2631
- return resolved?.rowsAffected ?? 0;
2632
- }
2633
- async function acquireLease(db, l) {
2634
- const at = l.at.toISOString();
2635
- const expires = new Date(l.at.getTime() + l.ttlMs).toISOString();
2636
- const rs = await db.execute({
2637
- sql: `INSERT INTO leases (project, name, holder, acquired_at, expires_at) VALUES (?, ?, ?, ?, ?)
2638
- ON CONFLICT (project, name) DO UPDATE SET
2639
- acquired_at = CASE WHEN leases.holder = excluded.holder THEN leases.acquired_at ELSE excluded.acquired_at END,
2640
- holder = excluded.holder, expires_at = excluded.expires_at
2641
- WHERE leases.holder = excluded.holder OR leases.expires_at <= ?`,
2642
- args: [l.project, l.name, l.holder, at, expires, at]
2643
- });
2644
- if (rs.rowsAffected)
2645
- return { acquired: true };
2646
- return { acquired: false, held: await getLease(db, l.project, l.name) };
2647
- }
2648
- async function getLease(db, project, name) {
2649
- const rs = await db.execute({
2650
- sql: "SELECT project, name, holder, acquired_at, expires_at FROM leases WHERE project = ? AND name = ?",
2651
- args: [project, name]
2652
- });
2653
- const r = rs.rows[0];
2654
- return r ? {
2655
- project: String(r.project),
2656
- name: String(r.name),
2657
- holder: String(r.holder),
2658
- acquiredAt: String(r.acquired_at),
2659
- expiresAt: String(r.expires_at)
2660
- } : null;
2661
- }
2662
- async function renewLease(db, l) {
2663
- const rs = await db.execute({
2664
- sql: "UPDATE leases SET expires_at = ? WHERE project = ? AND name = ? AND holder = ?",
2665
- args: [new Date(l.at.getTime() + l.ttlMs).toISOString(), l.project, l.name, l.holder]
2666
- });
2667
- return rs.rowsAffected > 0;
2668
- }
2669
- async function releaseLease(db, l) {
2670
- await db.execute({
2671
- sql: "DELETE FROM leases WHERE project = ? AND name = ? AND holder = ?",
2672
- args: [l.project, l.name, l.holder]
2673
- });
2674
- }
2675
-
2676
2209
  // ../core/src/worker.ts
2677
2210
  class Refusal extends Error {
2678
2211
  next;
@@ -2682,24 +2215,24 @@ class Refusal extends Error {
2682
2215
  this.next = next;
2683
2216
  }
2684
2217
  }
2685
- var TURSO_TIMEOUT_MS = 1e4;
2218
+ var LIVE_TIMEOUT_MS = 20000;
2686
2219
  async function live(ctx, warnings, what, step) {
2687
- const { db, warning } = await ctx.turso();
2688
- if (!db) {
2689
- if (warning)
2220
+ const { fleet, warning } = await ctx.fleet();
2221
+ if (!fleet) {
2222
+ if (warning && !warnings.includes(warning))
2690
2223
  warnings.push(warning);
2691
2224
  return null;
2692
2225
  }
2693
2226
  let timer;
2694
2227
  try {
2695
2228
  return await Promise.race([
2696
- step(db),
2229
+ step(fleet),
2697
2230
  new Promise((_, reject) => {
2698
- timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_TIMEOUT_MS / 1000} s`)), TURSO_TIMEOUT_MS);
2231
+ timer = setTimeout(() => reject(new Error(`no answer within ${LIVE_TIMEOUT_MS / 1000} s`)), LIVE_TIMEOUT_MS);
2699
2232
  })
2700
2233
  ]);
2701
2234
  } catch (err) {
2702
- warnings.push(`Turso: could not ${what} (${redact(err)}); Linear is up to date`);
2235
+ warnings.push(`Armada: could not ${what} (${err instanceof Error ? err.message : String(err)}); Linear is up to date`);
2703
2236
  return null;
2704
2237
  } finally {
2705
2238
  clearTimeout(timer);
@@ -2851,45 +2384,15 @@ ${claimLine({ runtime: runtime.name, handle: input.handle, branch, started, prof
2851
2384
  ]
2852
2385
  });
2853
2386
  lines.push(`${inProgress ? `Moved to ${inProgress.name}` : "State unchanged"}, assigned to ${viewer.name}, labels ${phaseLabel?.name ?? ticket.agentPhase} and ${runtime.name}.`);
2854
- const at = ctx.now();
2855
- const launched = await live(ctx, warnings, "record the claim", async (db) => {
2856
- await ensureProject(db, projectOf(config), at);
2857
- await saveRuntimeHandle(db, {
2858
- project: config.project.slug,
2859
- ticket: ticket.id,
2860
- runtime: runtime.name,
2861
- handle: input.handle,
2862
- branch,
2863
- at
2864
- });
2865
- if (!resuming)
2866
- await saveWorkerProfile(db, {
2867
- project: config.project.slug,
2868
- ticket: ticket.id,
2869
- profile: profile ? { name: profile.name, ...profile.profile, routed: profile.routed, reason: profile.reason, why: profile.why } : null,
2870
- at
2871
- });
2872
- await recordEvent(db, {
2873
- project: config.project.slug,
2874
- ticket: ticket.id,
2875
- kind: "claim",
2876
- phase: phaseLabel ? "planning" : ticket.agentPhase,
2877
- runtime: runtime.name,
2878
- handle: input.handle,
2879
- at
2880
- });
2881
- if (resuming)
2882
- return [];
2883
- const asked = (await openInboxItems(db, { project: config.project.slug, recipient: "coordinator", ticket: ticket.id })).filter((i) => i.kind === "launch-request");
2884
- for (const r of asked)
2885
- await resolveInboxItem(db, {
2886
- project: config.project.slug,
2887
- id: r.id,
2888
- resolution: `claimed by ${runtime.name} (${input.handle})`,
2889
- at
2890
- });
2891
- return asked;
2892
- });
2387
+ const launched = await live(ctx, warnings, "record the claim", (fleet) => fleet.claim({
2388
+ ticket: ticket.id,
2389
+ runtime: runtime.name,
2390
+ handle: input.handle,
2391
+ branch,
2392
+ phase: phaseLabel ? "planning" : ticket.agentPhase,
2393
+ resuming,
2394
+ profile: profile ? { name: profile.name, ...profile.profile, routed: profile.routed, reason: profile.reason, why: profile.why } : null
2395
+ }));
2893
2396
  if (launched?.length) {
2894
2397
  const who = [...new Set(launched.map((r) => r.author ?? "the owner"))].join(", ");
2895
2398
  const ids = launched.map((r) => `#${r.id}`).join(", ");
@@ -2975,46 +2478,15 @@ ${body}` : statusLine);
2975
2478
  const lines = [
2976
2479
  ticket.agentPhase === input.phase ? `Status update posted on ${ticket.id} (${input.phase}).` : `${ticket.id}: ${ticket.agentPhase} → ${input.phase}.`
2977
2480
  ];
2978
- const at = ctx.now();
2979
- const inbox = await live(ctx, warnings, "record the report", async (db) => {
2980
- await ensureProject(db, projectOf(config), at);
2981
- await recordEvent(db, {
2982
- project: config.project.slug,
2983
- ticket: ticket.id,
2984
- kind: "report",
2985
- phase: input.phase,
2986
- message: summary,
2987
- prUrl: pr?.url ?? null,
2988
- headSha: sha,
2989
- at
2990
- });
2991
- if (input.phase === "awaiting-approval" && ticket.agentPhase !== input.phase) {
2992
- const handle = await getRuntimeHandle(db, config.project.slug, ticket.id);
2993
- await putPlan(db, {
2994
- project: config.project.slug,
2995
- ticket: ticket.id,
2996
- author: handle && !handle.releasedAt ? handle.handle : null,
2997
- body: message,
2998
- at
2999
- });
3000
- } else if (input.phase !== "awaiting-approval") {
3001
- await resolvePlans(db, {
3002
- project: config.project.slug,
3003
- ticket: ticket.id,
3004
- resolution: `worker reported ${input.phase}`,
3005
- at
3006
- });
3007
- }
3008
- if (input.phase === "ready-to-merge")
3009
- await putHandBack(db, {
3010
- project: config.project.slug,
3011
- ticket: ticket.id,
3012
- author: null,
3013
- body: statusLine,
3014
- at
3015
- });
3016
- return openInboxItems(db, { project: config.project.slug, recipient: "worker", ticket: ticket.id });
3017
- });
2481
+ const inbox = await live(ctx, warnings, "record the report", (fleet) => fleet.report({
2482
+ ticket: ticket.id,
2483
+ phase: input.phase,
2484
+ previous: ticket.agentPhase,
2485
+ summary,
2486
+ message,
2487
+ prUrl: pr?.url ?? null,
2488
+ headSha: sha
2489
+ }));
3018
2490
  const state = await readBack(ctx, ticket.id, warnings);
3019
2491
  return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox, state };
3020
2492
  }
@@ -3032,38 +2504,7 @@ async function releaseTicket(ctx, input) {
3032
2504
  });
3033
2505
  await linear.comment(ticket.uuid, `Agent status: released — ${input.reason.trim()}`);
3034
2506
  const lines = [`Released ${ticket.id}${back ? `, moved back to ${back.name}` : ""}.`];
3035
- const at = ctx.now();
3036
- await live(ctx, warnings, "record the release", async (db) => {
3037
- await ensureProject(db, projectOf(config), at);
3038
- await releaseRuntimeHandle(db, config.project.slug, ticket.id, at);
3039
- await resolvePlans(db, {
3040
- project: config.project.slug,
3041
- ticket: ticket.id,
3042
- resolution: `ticket released: ${input.reason.trim()}`,
3043
- at
3044
- });
3045
- await resolveInboxItems(db, {
3046
- project: config.project.slug,
3047
- ticket: ticket.id,
3048
- kind: "question",
3049
- resolution: `ticket released: ${input.reason.trim()}`,
3050
- at
3051
- });
3052
- await resolveInboxItems(db, {
3053
- project: config.project.slug,
3054
- ticket: ticket.id,
3055
- kind: "answer-request",
3056
- resolution: `ticket released: ${input.reason.trim()}`,
3057
- at
3058
- });
3059
- await recordEvent(db, {
3060
- project: config.project.slug,
3061
- ticket: ticket.id,
3062
- kind: "release",
3063
- message: input.reason.trim(),
3064
- at
3065
- });
3066
- });
2507
+ await live(ctx, warnings, "record the release", (fleet) => fleet.release({ ticket: ticket.id, reason: input.reason.trim() }));
3067
2508
  return { ticket: ticket.id, url: ticket.url, lines, warnings, inbox: null };
3068
2509
  }
3069
2510
 
@@ -3144,9 +2585,7 @@ function handBackNote(notes) {
3144
2585
  return withStatus.find((n) => parseStatusLine(n.body)?.phase === "ready-to-merge") ?? withStatus[0] ?? null;
3145
2586
  }
3146
2587
  var VARIABLES = [
3147
- { name: "LINEAR_API_KEY", required: true, purpose: "Linear key the worker claims and reports with" },
3148
- { name: "ARMADA_TURSO_URL", required: false, purpose: "Turso database for live activity" },
3149
- { name: "ARMADA_TURSO_TOKEN", required: false, purpose: "Turso database token" }
2588
+ { name: "LINEAR_API_KEY", required: true, purpose: "Linear key the worker claims and reports with" }
3150
2589
  ];
3151
2590
 
3152
2591
  class BriefError extends Error {
@@ -3357,7 +2796,7 @@ var SESSION_TOKEN_VARIABLE = "ARMADA_SESSION_TOKEN";
3357
2796
  var API_KEY_VARIABLE = "ARMADA_API_KEY";
3358
2797
  var API_URL_VARIABLE = "ARMADA_API_URL";
3359
2798
  var SIGNED_IN_TO_VARIABLE = "ARMADA_SIGNED_IN_TO";
3360
- var TURSO_LEASE_VARIABLE = "ARMADA_TURSO_LEASE";
2799
+ var RETIRED_VARIABLES = ["ARMADA_TURSO_URL", "ARMADA_TURSO_TOKEN", "ARMADA_TURSO_LEASE"];
3361
2800
  var WORKER_SESSION_PREFIX = "ARMADA_WORKER_SESSION_";
3362
2801
  var workerSessionVariable = (ticket) => `${WORKER_SESSION_PREFIX}${ticket.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
3363
2802
  var formatRecord = (record) => Buffer.from(JSON.stringify(record), "utf8").toString("base64url");
@@ -3373,11 +2812,6 @@ function parseRecord(value, keys) {
3373
2812
  return null;
3374
2813
  }
3375
2814
  }
3376
- var formatLease = (lease) => formatRecord(lease);
3377
- function parseLease(value) {
3378
- const l = parseRecord(value, ["api", "organization", "url", "token", "expiresAt", "revision"]);
3379
- return l && !Number.isNaN(Date.parse(l.expiresAt)) ? l : null;
3380
- }
3381
2815
  var formatWorkerSession = (worker) => formatRecord(worker);
3382
2816
  function parseWorkerSession(value) {
3383
2817
  return parseRecord(value, ["api", "token", "ticket", "project", "organization", "id"]);
@@ -3405,23 +2839,7 @@ var LINEAR_KEY = {
3405
2839
  label: "Linear API key",
3406
2840
  hint: "Linear > Settings > Security & access > Personal API keys"
3407
2841
  };
3408
- var STORED_KEYS = [
3409
- LINEAR_KEY,
3410
- {
3411
- name: "tursoUrl",
3412
- variable: "ARMADA_TURSO_URL",
3413
- secret: false,
3414
- label: "Turso database URL",
3415
- hint: "libsql://<database>-<organization>.turso.io, from `turso db show <database> --url`"
3416
- },
3417
- {
3418
- name: "tursoToken",
3419
- variable: "ARMADA_TURSO_TOKEN",
3420
- secret: true,
3421
- label: "Turso database token",
3422
- hint: "`turso db tokens create <database>`"
3423
- }
3424
- ];
2842
+ var STORED_KEYS = [LINEAR_KEY];
3425
2843
  var clean = (v) => v?.trim() || null;
3426
2844
  var fromEnv = (env, variable) => {
3427
2845
  const value = clean(env[variable]);
@@ -3439,12 +2857,10 @@ function resolveCredentials({
3439
2857
  const value = clean(store[variable]);
3440
2858
  return value ? { value, source: { kind: "store" } } : null;
3441
2859
  };
3442
- const stored = (variable) => fromEnv(env, variable) ?? fromStore(variable);
3443
2860
  const fromGh = () => {
3444
2861
  const value = clean(ghToken?.());
3445
2862
  return value ? { value, source: { kind: "gh" } } : null;
3446
2863
  };
3447
- const tursoUrlConfig = clean(personal?.turso.url);
3448
2864
  const apiUrlConfig = clean(personal?.api.url);
3449
2865
  const apiUrl = fromEnv(env, API_URL_VARIABLE);
3450
2866
  const workers = storedWorkers(store);
@@ -3465,22 +2881,15 @@ function resolveCredentials({
3465
2881
  source: { kind: "store" }
3466
2882
  } : envKey ? { kind: "api-key", key: envKey.value, source: envKey.source } : session && here ? { kind: "session", token: session.value, source: session.source } : storedKey && here ? { kind: "api-key", key: storedKey.value, source: storedKey.source } : null;
3467
2883
  const fromArmada = (value, detail) => value && detail ? { value, source: { kind: "armada", detail } } : null;
3468
- const tursoPair = armada?.turso && !fromEnv(env, "ARMADA_TURSO_URL") && !fromEnv(env, "ARMADA_TURSO_TOKEN") ? armada.turso : null;
3469
2884
  const found = {
3470
2885
  linearApiKey: fromEnv(env, "LINEAR_API_KEY") ?? fromArmada(armada?.linearApiKey?.value, armada?.linearApiKey?.detail) ?? fromStore("LINEAR_API_KEY"),
3471
- tursoUrl: fromArmada(tursoPair?.url, tursoPair?.detail) ?? stored("ARMADA_TURSO_URL") ?? (tursoUrlConfig ? { value: tursoUrlConfig, source: { kind: "config", key: "turso.url" } } : null),
3472
- tursoToken: fromArmada(tursoPair?.token, tursoPair?.detail) ?? stored("ARMADA_TURSO_TOKEN"),
3473
2886
  githubToken: fromEnv(env, "GITHUB_TOKEN") ?? fromEnv(env, "GH_TOKEN") ?? fromGh()
3474
2887
  };
3475
2888
  return {
3476
2889
  linearApiKey: found.linearApiKey?.value ?? null,
3477
- tursoUrl: found.tursoUrl?.value ?? null,
3478
- tursoToken: found.tursoToken?.value ?? null,
3479
2890
  githubToken: found.githubToken?.value ?? null,
3480
2891
  sources: {
3481
2892
  linearApiKey: found.linearApiKey?.source ?? null,
3482
- tursoUrl: found.tursoUrl?.source ?? null,
3483
- tursoToken: found.tursoToken?.source ?? null,
3484
2893
  githubToken: found.githubToken?.source ?? null
3485
2894
  },
3486
2895
  armadaApi,
@@ -3605,6 +3014,54 @@ function updateDotenv(text, updates) {
3605
3014
  `)}
3606
3015
  ` : "";
3607
3016
  }
3017
+ // ../core/src/live.ts
3018
+ var entryKey = (e) => e.id === null ? `silent:${e.ticket}` : `#${e.id}`;
3019
+
3020
+ // ../core/src/fleet-api.ts
3021
+ var WORKER_FLEET_OPS = ["claim", "report", "ask", "release"];
3022
+ var FLEET_OPS = [
3023
+ ...WORKER_FLEET_OPS,
3024
+ "register",
3025
+ "events/latest",
3026
+ "inbox",
3027
+ "inbox/item",
3028
+ "inbox/ticket",
3029
+ "inbox/resolve",
3030
+ "answer",
3031
+ "merge",
3032
+ "lease/acquire",
3033
+ "lease/renew",
3034
+ "lease/release"
3035
+ ];
3036
+ var LEASE_TTL_MAX_MS = 60 * 60000;
3037
+ var NOT_MODIFIED = Symbol("not modified");
3038
+ var CALL_TIMEOUT_MS = 15000;
3039
+ function fleetClient(o) {
3040
+ const call = async (op, input) => await o.api.fleet(o.signIn, op, { project: o.project, input }, CALL_TIMEOUT_MS);
3041
+ return {
3042
+ register: () => call("register", {}).then(() => {
3043
+ return;
3044
+ }),
3045
+ lastEventTimes: () => call("events/latest", {}),
3046
+ claim: (c) => call("claim", c),
3047
+ report: (r) => call("report", r),
3048
+ ask: (q) => call("ask", q),
3049
+ release: (r) => call("release", r).then(() => {
3050
+ return;
3051
+ }),
3052
+ inbox: (q) => call("inbox", q),
3053
+ inboxItem: (id) => call("inbox/item", { id }),
3054
+ ticketItems: (ticket) => call("inbox/ticket", { ticket }),
3055
+ answer: (a) => call("answer", a),
3056
+ resolve: (r) => call("inbox/resolve", r),
3057
+ merge: (m) => call("merge", m),
3058
+ acquireLease: (l) => call("lease/acquire", l),
3059
+ renewLease: (l) => call("lease/renew", l),
3060
+ releaseLease: (l) => call("lease/release", l).then(() => {
3061
+ return;
3062
+ })
3063
+ };
3064
+ }
3608
3065
  // ../core/src/github.ts
3609
3066
  var GITHUB_GRAPHQL = "https://api.github.com/graphql";
3610
3067
 
@@ -3836,7 +3293,6 @@ async function fetchPullDiff(opts) {
3836
3293
  return res.text();
3837
3294
  }
3838
3295
  // ../core/src/inbox.ts
3839
- var MIN2 = 60000;
3840
3296
  function questionBody(question, options = []) {
3841
3297
  const listed = options.map((o) => o.trim()).filter(Boolean);
3842
3298
  const text = question.trim();
@@ -3851,19 +3307,7 @@ async function askCoordinator(ctx, input) {
3851
3307
  throw new Refusal("the question is empty: say what you need decided", 'armada ask "<question, the options, your recommendation>"');
3852
3308
  const body = questionBody(input.question, input.options);
3853
3309
  const out = await reportPhase(ctx, { ticket: input.ticket, phase: "blocked", message: `question: ${body}` });
3854
- const project = ctx.config.project.slug;
3855
- const item = await live(ctx, out.warnings, "put the question in the coordinator's inbox", async (db) => {
3856
- const held = await getRuntimeHandle(db, project, out.ticket);
3857
- return addInboxItem(db, {
3858
- project,
3859
- ticket: out.ticket,
3860
- kind: "question",
3861
- recipient: "coordinator",
3862
- author: held && !held.releasedAt ? held.handle : null,
3863
- body,
3864
- at: ctx.now()
3865
- });
3866
- });
3310
+ const item = await live(ctx, out.warnings, "put the question in the coordinator's inbox", (fleet) => fleet.ask({ ticket: out.ticket, body }));
3867
3311
  const lines = [
3868
3312
  ...out.lines,
3869
3313
  item === null ? "The question is on the ticket only: the coordinator sees the blocked phase in `armada status`." : `Question #${item} is in the coordinator's inbox.`,
@@ -3871,93 +3315,40 @@ async function askCoordinator(ctx, input) {
3871
3315
  ];
3872
3316
  return { ...out, lines, warnings: [...new Set(out.warnings)], item };
3873
3317
  }
3874
- var entryKey = (e) => e.id === null ? `silent:${e.ticket}` : `#${e.id}`;
3875
- async function readInbox(db, o) {
3876
- const now = o.now().getTime();
3877
- const [items, handles, events, answered] = await Promise.all([
3878
- openInboxItems(db, { project: o.project, recipient: "coordinator" }),
3879
- openRuntimeHandles(db, o.project),
3880
- latestEvents(db, o.project),
3881
- lastAnsweredAt(db, o.project)
3882
- ]);
3883
- const entries = items.map((i) => ({
3884
- id: i.id,
3885
- kind: i.kind,
3886
- ticket: i.ticket,
3887
- author: i.author,
3888
- body: i.body,
3889
- createdAt: i.createdAt,
3890
- new: false,
3891
- ...i.request ? { request: i.request } : {}
3892
- }));
3893
- const asking = new Set(items.filter((i) => i.kind === "question").map((i) => i.ticket));
3894
- for (const h of handles) {
3895
- if (o.coordinator && h.handle === o.coordinator)
3896
- continue;
3897
- const e = events[h.ticket];
3898
- if (e && (e.kind === "release" || e.kind === "merge"))
3899
- continue;
3900
- if (asking.has(h.ticket))
3901
- continue;
3902
- const reported = e?.at ?? h.claimedAt;
3903
- const answer = answered[h.ticket];
3904
- const owesReport = !!answer && answer > reported;
3905
- if (!owesReport && NEEDS_HUMAN.includes(e?.phase))
3906
- continue;
3907
- const last = owesReport ? answer : reported;
3908
- const quiet = now - Date.parse(last);
3909
- if (quiet <= o.silentAfterMinutes * MIN2)
3910
- continue;
3911
- entries.push({
3912
- id: null,
3913
- kind: "silent",
3914
- ticket: h.ticket,
3915
- author: h.handle,
3916
- body: `no report for ${Math.floor(quiet / MIN2)} min${owesReport ? " since its question was answered" : ""} (phase ${e?.phase ?? "unknown"}, ${h.runtime} ${h.handle}); check it with the runtime guide's status section`,
3917
- createdAt: last,
3918
- new: false
3919
- });
3920
- }
3921
- return entries.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || (a.id ?? 0) - (b.id ?? 0));
3922
- }
3923
- var PRESENCE_EVERY_MS = MIN2;
3924
- var INBOX_POLL_MS = 5000;
3925
- async function checkInbox(db, o) {
3318
+ var INBOX_POLL_MS = 15000;
3319
+ async function checkInbox(fleet, o) {
3926
3320
  const started = o.now();
3927
- const warnings = [];
3928
- const seen = (at) => recordCoordinatorSeen(db, { project: o.project, handle: o.coordinator ?? null, at }).catch((err) => {
3929
- const w = `could not record the coordinator's presence (${redact(err)})`;
3930
- if (!warnings.includes(w))
3931
- warnings.push(w);
3932
- });
3933
- await seen(started);
3934
- let items = await readInbox(db, o);
3321
+ const query = { coordinator: o.coordinator ?? null, silentAfterMinutes: o.silentAfterMinutes };
3322
+ const first = await fleet.inbox({ ...query, etag: null });
3323
+ if (!first)
3324
+ throw new Error("Armada answered the first inbox read with nothing");
3325
+ const warnings = [...first.warnings];
3326
+ let items = first.items;
3327
+ let etag = first.etag;
3935
3328
  const report = (timedOut) => ({
3936
3329
  project: o.project,
3937
3330
  generatedAt: o.now().toISOString(),
3938
3331
  items,
3939
3332
  wait: o.wait && timedOut !== null ? { timeoutSeconds: Math.round(o.wait.timeoutMs / 1000), timedOut } : null,
3940
- warnings
3333
+ warnings: [...new Set(warnings)]
3941
3334
  });
3942
3335
  if (!o.wait)
3943
3336
  return report(null);
3944
3337
  const { sleep, timeoutMs, pollMs = INBOX_POLL_MS } = o.wait;
3945
- let known = new Set(items.map(entryKey));
3946
- let lastSeen = started.getTime();
3947
3338
  for (;; ) {
3948
3339
  const left = timeoutMs - (o.now().getTime() - started.getTime());
3949
3340
  if (left <= 0)
3950
3341
  return report(true);
3951
3342
  await sleep(Math.min(pollMs, left));
3952
- const at = o.now();
3953
- if (at.getTime() - lastSeen >= PRESENCE_EVERY_MS) {
3954
- await seen(at);
3955
- lastSeen = at.getTime();
3956
- }
3957
- items = (await readInbox(db, o)).map((e) => ({ ...e, new: !known.has(entryKey(e)) }));
3343
+ const read = await fleet.inbox({ ...query, etag });
3344
+ if (!read)
3345
+ continue;
3346
+ const known = new Set(items.map(entryKey));
3347
+ items = read.items.map((e) => ({ ...e, new: !known.has(entryKey(e)) }));
3348
+ etag = read.etag;
3349
+ warnings.push(...read.warnings);
3958
3350
  if (items.some((e) => e.new))
3959
3351
  return report(false);
3960
- known = new Set(items.map(entryKey));
3961
3352
  }
3962
3353
  }
3963
3354
  var ITEM_ID = /^#?(\d+)$/;
@@ -3988,7 +3379,7 @@ async function answerItem(ctx, input) {
3988
3379
  let ticketId = null;
3989
3380
  if (idMatch) {
3990
3381
  itemId = Number(idMatch[1]);
3991
- item = await live(ctx, warnings, `read inbox item #${itemId}`, (db) => getInboxItem(db, project, itemId ?? 0));
3382
+ item = await live(ctx, warnings, `read inbox item #${itemId}`, (fleet) => fleet.inboxItem(itemId ?? 0));
3992
3383
  if (input.note && item?.kind !== "plan")
3993
3384
  throw new Refusal("a note goes to a ticket or a plan, not to another inbox item", 'armada answer --note <ticket> "<message>"');
3994
3385
  if (!item)
@@ -4003,7 +3394,7 @@ async function answerItem(ctx, input) {
4003
3394
  } else {
4004
3395
  ticketId = input.target.trim().toUpperCase();
4005
3396
  if (!input.note) {
4006
- const open = await live(ctx, warnings, `read the open questions of ${ticketId}`, (db) => openInboxItems(db, { project, recipient: "coordinator", ticket: ticketId ?? "" }));
3397
+ const open = await live(ctx, warnings, `read the open questions of ${ticketId}`, (fleet) => fleet.ticketItems(ticketId ?? ""));
4007
3398
  if (open && !open.some((i) => i.kind === "question" || i.kind === "plan"))
4008
3399
  throw new Refusal(`${ticketId} has no open question or plan in the inbox`, `armada answer --note ${ticketId} "<message>", for an unsolicited message`);
4009
3400
  }
@@ -4011,7 +3402,7 @@ async function answerItem(ctx, input) {
4011
3402
  if (item?.kind === "launch-request")
4012
3403
  return declineLaunch(ctx, item, text, warnings);
4013
3404
  const question = item?.kind === "answer-request" ? item.request?.question ?? null : null;
4014
- const answered = question === null ? item : await live(ctx, warnings, `read the item answered by #${item?.id}`, (db) => getInboxItem(db, project, question));
3405
+ const answered = question === null ? item : await live(ctx, warnings, `read the item answered by #${item?.id}`, (fleet) => fleet.inboxItem(question));
4015
3406
  const answerKind = answered?.kind === "plan" ? "plan" : "question";
4016
3407
  let url = "";
4017
3408
  if (ticketId) {
@@ -4030,40 +3421,7 @@ async function answerItem(ctx, input) {
4030
3421
  lines.push(`${input.note ? "Note" : "Answer"} posted on ${ticket.id} (${ticket.agentPhase}).`);
4031
3422
  }
4032
3423
  }
4033
- const at = ctx.now();
4034
- const recorded = await live(ctx, warnings, `record the ${input.note ? "note" : "answer"}`, async (db) => {
4035
- await ensureProject(db, projectOf(config), at);
4036
- if (input.note) {
4037
- if (ticketId)
4038
- await resolvePlans(db, { project, ticket: ticketId, resolution: text, at });
4039
- const id = await addInboxItem(db, {
4040
- project,
4041
- ticket: ticketId,
4042
- kind: "note",
4043
- recipient: "worker",
4044
- author: "coordinator",
4045
- body: text,
4046
- at
4047
- });
4048
- await resolveInboxItem(db, { project, id, resolution: "delivered through the runtime", at });
4049
- return `Note #${id} recorded.`;
4050
- }
4051
- if (item?.kind === "answer-request") {
4052
- await resolveInboxItem(db, { project, id: item.id, resolution: text, at });
4053
- const closed = question !== null && await resolveInboxItem(db, { project, id: question, resolution: text, at });
4054
- return `Dashboard request #${item.id} delivered${closed ? `; ${answerKind} #${question} resolved` : ""}.`;
4055
- }
4056
- if (itemId !== null) {
4057
- const done = await resolveInboxItem(db, { project, id: itemId, resolution: text, at });
4058
- if (item?.kind === "question" || item?.kind === "plan")
4059
- await resolveAnswerRequests(db, { project, question: itemId, resolution: text, at });
4060
- return done ? `Inbox item #${itemId} resolved.` : `Inbox item #${itemId} was already resolved.`;
4061
- }
4062
- const n = await resolveInboxItems(db, { project, ticket: ticketId ?? "", kind: "question", resolution: text, at });
4063
- const plans = await resolvePlans(db, { project, ticket: ticketId ?? "", resolution: text, at });
4064
- await resolveInboxItems(db, { project, ticket: ticketId ?? "", kind: "answer-request", resolution: text, at });
4065
- return `${n} open question${n === 1 ? "" : "s"}${plans ? ` and ${plans} plan${plans === 1 ? "" : "s"}` : ""} of ${ticketId} resolved.`;
4066
- });
3424
+ const recorded = await live(ctx, warnings, `record the ${input.note ? "note" : "answer"}`, (fleet) => fleet.answer({ text, note: !!input.note, ticket: ticketId, item: itemId }));
4067
3425
  if (recorded)
4068
3426
  lines.push(recorded);
4069
3427
  if (!input.note)
@@ -4071,8 +3429,7 @@ async function answerItem(ctx, input) {
4071
3429
  return { ticket: ticketId ?? `#${itemId}`, url, lines, warnings: [...new Set(warnings)], inbox: null };
4072
3430
  }
4073
3431
  async function declineLaunch(ctx, item, reason, warnings) {
4074
- const project = ctx.config.project.slug;
4075
- const done = await live(ctx, warnings, `decline launch request #${item.id}`, (db) => resolveInboxItem(db, { project, id: item.id, resolution: `declined: ${reason}`, at: ctx.now() }));
3432
+ const done = await live(ctx, warnings, `decline launch request #${item.id}`, (fleet) => fleet.resolve({ id: item.id, resolution: `declined: ${reason}` }));
4076
3433
  const lines = done === null ? [] : [
4077
3434
  done ? `Launch request #${item.id} for ${item.ticket} declined; the dashboard shows it closed.` : `Launch request #${item.id} was already resolved.`
4078
3435
  ];
@@ -4366,7 +3723,6 @@ async function updateCredentialStore(paths, updates) {
4366
3723
  }
4367
3724
  var EMPTY_PERSONAL_CONFIG = {
4368
3725
  language: null,
4369
- turso: { url: null },
4370
3726
  dashboard: { url: null },
4371
3727
  api: { url: null }
4372
3728
  };
@@ -4380,7 +3736,7 @@ function parsePersonalConfig(text, source = "config.toml") {
4380
3736
  throw new ConfigError(source, [`not valid TOML${where}`]);
4381
3737
  }
4382
3738
  const problems = [];
4383
- const known = { turso: ["url"], dashboard: ["url"], api: ["url"] };
3739
+ const known = { dashboard: ["url"], api: ["url"] };
4384
3740
  for (const [key, v] of Object.entries(raw)) {
4385
3741
  if (key === "language")
4386
3742
  continue;
@@ -4409,7 +3765,6 @@ function parsePersonalConfig(text, source = "config.toml") {
4409
3765
  const table = (key) => isTable2(raw[key]) ? raw[key] : {};
4410
3766
  const config = {
4411
3767
  language: str(raw.language, "language"),
4412
- turso: { url: str(table("turso").url, "turso.url") },
4413
3768
  dashboard: { url: str(table("dashboard").url, "dashboard.url") },
4414
3769
  api: { url: str(table("api").url, "api.url") }
4415
3770
  };
@@ -4434,9 +3789,6 @@ var PERSONAL_CONFIG_TEMPLATE = `# Armada personal defaults for this machine. No
4434
3789
  # Your language for Armada's messages (BCP 47 tag).
4435
3790
  # language = "en"
4436
3791
 
4437
- # [turso]
4438
- # url = "libsql://<database>-<organization>.turso.io"
4439
-
4440
3792
  # [dashboard]
4441
3793
  # url = "https://<your-armada-dashboard>"
4442
3794
 
@@ -4577,31 +3929,31 @@ function semanticHints(symbols, uses, base) {
4577
3929
  }
4578
3930
  return hints;
4579
3931
  }
4580
- var LOCK_CALL_TIMEOUT_MS = 1e4;
3932
+ var LOCK_CALL_TIMEOUT_MS = 20000;
4581
3933
  async function timed(p, ms, what) {
4582
3934
  let timer;
4583
3935
  try {
4584
3936
  return await Promise.race([
4585
3937
  p,
4586
3938
  new Promise((_, reject) => {
4587
- timer = setTimeout(() => reject(new Refusal(`Turso did not answer within ${ms / 1000} s to ${what}; nothing was merged`, "the same armada merge again, or with --no-lock if you are sure no other coordinator merges now")), ms);
3939
+ timer = setTimeout(() => reject(new Refusal(`Armada did not answer within ${ms / 1000} s to ${what}; nothing was merged`, "the same armada merge again, or with --no-lock if you are sure no other coordinator merges now")), ms);
4588
3940
  })
4589
3941
  ]);
4590
3942
  } finally {
4591
3943
  clearTimeout(timer);
4592
3944
  }
4593
3945
  }
4594
- async function withLease(db, o, body) {
4595
- const key = { project: o.project, name: o.name, holder: o.holder, ttlMs: o.ttlMs };
3946
+ async function withLease(fleet, o, body) {
3947
+ const key = { name: o.name, holder: o.holder, ttlMs: o.ttlMs };
4596
3948
  const poll = o.pollMs ?? LEASE_POLL_MS;
4597
3949
  const maxWait = o.maxWaitMs ?? o.ttlMs;
4598
3950
  const lockTimeout = o.timeoutMs ?? LOCK_CALL_TIMEOUT_MS;
4599
3951
  let waited = 0;
4600
3952
  let lastHolder;
4601
3953
  for (;; ) {
4602
- const got = await timed(acquireLease(db, { ...key, at: o.now() }), lockTimeout, `take the ${o.name} lock`).catch(async (err) => {
4603
- await timed(releaseLease(db, key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
4604
- throw err;
3954
+ const got = await timed(fleet.acquireLease(key), lockTimeout, `take the ${o.name} lock`).catch(async (err) => {
3955
+ await timed(fleet.releaseLease(key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
3956
+ throw err instanceof Refusal ? err : new Refusal(`the ${o.name} lock could not be taken (${err instanceof Error ? err.message : String(err)}); nothing was merged`, "the same armada merge again, or with --no-lock if you are sure no other coordinator merges now");
4605
3957
  });
4606
3958
  if (got.acquired)
4607
3959
  break;
@@ -4615,9 +3967,9 @@ async function withLease(db, o, body) {
4615
3967
  waited += poll;
4616
3968
  }
4617
3969
  try {
4618
- return await body(() => timed(renewLease(db, { ...key, at: o.now() }), lockTimeout, `renew the ${o.name} lock`).catch(() => false));
3970
+ return await body(() => timed(fleet.renewLease(key), lockTimeout, `renew the ${o.name} lock`).catch(() => false));
4619
3971
  } finally {
4620
- await timed(releaseLease(db, key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
3972
+ await timed(fleet.releaseLease(key), lockTimeout, `release the ${o.name} lock`).catch(() => {});
4621
3973
  }
4622
3974
  }
4623
3975
  var say = (ctx, line) => ctx.progress?.(line);
@@ -4680,7 +4032,7 @@ ${problems.map((p) => ` - ${p}`).join(`
4680
4032
  `)}${hints.length ? `
4681
4033
  Hints (not blocking):
4682
4034
  ${hints.map((h) => ` - ${h}`).join(`
4683
- `)}` : ""}`, pull.state !== "open" ? `gh pr view ${pull.number} --repo ${config.github.repository}` : ticket.agentPhase !== "ready-to-merge" ? ctx.tursoConfigured ? `armada inbox --wait, until ${ticket.id} is handed back` : `armada status, until ${ticket.id} shows ready-to-merge` : `armada answer --note ${ticket.id} "<what to fix>", once you told its worker; merge again after its next hand-back`);
4035
+ `)}` : ""}`, pull.state !== "open" ? `gh pr view ${pull.number} --repo ${config.github.repository}` : ticket.agentPhase !== "ready-to-merge" ? ctx.lockRequired ? `armada inbox --wait, until ${ticket.id} is handed back` : `armada status, until ${ticket.id} shows ready-to-merge` : `armada answer --note ${ticket.id} "<what to fix>", once you told its worker; merge again after its next hand-back`);
4684
4036
  lines.unshift(`Checklist passed for #${pull.number} (${ticket.id}): handed back at ${pull.headSha}, CLEAN, checks green, no open review thread.`);
4685
4037
  return { pull, ticket, sha: pull.headSha, baseSha: cmp?.baseSha ?? null, lines, hints, warnings };
4686
4038
  }
@@ -4804,7 +4156,7 @@ async function mergePullRequest(ctx, input) {
4804
4156
  c.warnings.unshift(...early);
4805
4157
  await recheck(ctx, c);
4806
4158
  if (!await renew())
4807
- throw new Refusal("the merge lock could not be renewed (it expired and another coordinator took it, or Turso did not answer); nothing was merged", `armada merge ${input.pr} again`);
4159
+ throw new Refusal("the merge lock could not be renewed (it expired and another coordinator took it, or Armada did not answer); nothing was merged", `armada merge ${input.pr} again`);
4808
4160
  say(ctx, `Merging #${c.pull.number} at ${c.sha}…`);
4809
4161
  const merged = await mergePinned(ctx, c.pull, c.sha, c.ticket.id);
4810
4162
  const lines = [
@@ -4822,58 +4174,30 @@ async function mergePullRequest(ctx, input) {
4822
4174
  early.push(`merged without the merge lock (--no-lock): make sure no other coordinator merges in ${slug} now`);
4823
4175
  return run(async () => true);
4824
4176
  }
4825
- const { db, warning } = await ctx.turso();
4826
- if (!db && ctx.tursoConfigured)
4827
- throw new Refusal(`the merge lock needs Turso, which is unavailable (${warning ?? "no answer"}); nothing was merged`, `armada merge ${input.pr} again once Turso answers, or armada merge ${input.pr} --no-lock if you are sure no other coordinator merges in ${slug} now`);
4828
- if (!db) {
4829
- early.push(`${warning ?? "Turso is not configured"}; the merge lock was not taken, so make sure no other coordinator merges in ${slug} now`);
4177
+ const { fleet, warning } = await ctx.fleet();
4178
+ if (!fleet && ctx.lockRequired)
4179
+ throw new Refusal(`the merge lock needs Armada, which is unavailable (${warning ?? "no answer"}); nothing was merged`, `armada merge ${input.pr} again once Armada answers, or armada merge ${input.pr} --no-lock if you are sure no other coordinator merges in ${slug} now`);
4180
+ if (!fleet) {
4181
+ early.push(`${warning ?? "not signed in to Armada"}; the merge lock was not taken, so make sure no other coordinator merges in ${slug} now`);
4830
4182
  return run(async () => true);
4831
4183
  }
4832
- return withLease(db, {
4184
+ return withLease(fleet, {
4833
4185
  project: slug,
4834
4186
  name: MERGE_LEASE,
4835
4187
  holder: ctx.holder,
4836
4188
  ttlMs: MERGE_LEASE_TTL_MS,
4837
- now: ctx.now,
4838
4189
  sleep: ctx.sleep,
4839
4190
  onWait: (held) => say(ctx, `Waiting for the merge lock held by ${held?.holder ?? "another coordinator"} (until ${held?.expiresAt ?? "?"})…`)
4840
4191
  }, run);
4841
4192
  }
4842
4193
  async function after(ctx, c, merged, lines) {
4843
- const { config } = ctx;
4844
- const slug = config.project.slug;
4845
- const at = ctx.now();
4846
- const live$ = await live(ctx, c.warnings, "record the merge", async (db) => {
4847
- await ensureProject(db, projectOf(config), at);
4848
- const handle = await getRuntimeHandle(db, slug, c.ticket.id);
4849
- await recordEvent(db, {
4850
- project: slug,
4851
- ticket: c.ticket.id,
4852
- kind: "merge",
4853
- phase: "merged",
4854
- message: `PR #${merged.number} merged as ${merged.mergeCommit ?? "unknown"}`,
4855
- prUrl: merged.url,
4856
- headSha: merged.headSha,
4857
- at
4858
- });
4859
- const resolved = await resolveInboxItems(db, {
4860
- project: slug,
4861
- ticket: c.ticket.id,
4862
- kind: "hand-back",
4863
- resolution: `merged as ${merged.mergeCommit ?? "unknown"}`,
4864
- at
4865
- });
4866
- await resolveInboxItems(db, { project: slug, ticket: c.ticket.id, kind: "question", resolution: "merged", at });
4867
- await resolveInboxItems(db, {
4868
- project: slug,
4869
- ticket: c.ticket.id,
4870
- kind: "answer-request",
4871
- resolution: "merged",
4872
- at
4873
- });
4874
- await releaseRuntimeHandle(db, slug, c.ticket.id, at);
4875
- return { handle, resolved, open: await openRuntimeHandles(db, slug) };
4876
- });
4194
+ const live$ = await live(ctx, c.warnings, "record the merge", (fleet) => fleet.merge({
4195
+ ticket: c.ticket.id,
4196
+ number: merged.number,
4197
+ url: merged.url,
4198
+ mergeCommit: merged.mergeCommit,
4199
+ headSha: merged.headSha
4200
+ }));
4877
4201
  if (live$?.resolved)
4878
4202
  lines.push(`Hand-back resolved in the coordinator's inbox.`);
4879
4203
  let workers = [];
@@ -4948,7 +4272,7 @@ async function readProjectConfig(p, opts) {
4948
4272
  import { createHash } from "node:crypto";
4949
4273
 
4950
4274
  // ../../skills/armada-coordinator/MERGE.md
4951
- var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Turso is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n\n## The release pull request\n\nSome repositories publish through release-please: every merge to the default branch opens or updates one release pull request, and merging it tags the version and publishes it. When the repository's rules (`AGENTS.md`) say to merge it after each merge, do it right after the ticket's merge, without a hand-back: no worker owns it, so `armada merge` does not apply.\n\n- **What it looks like.** Title `chore(main): release <version>`, opened by `github-actions`, label `autorelease: pending`, and a diff that only touches the changelog, the manifest and version fields. It is opened with the workflow's own token, so **no CI check runs on it** (only checks from apps such as Vercel, if any) and `mergeStateStatus` is `UNSTABLE`. Both are expected: the publish job runs the repository's checks again before publishing. Anything else in the diff, or a `DIRTY` state, is not expected: stop and tell the owner.\n- **Find it and its head:**\n\n```sh\ngh pr list --state open --label \"autorelease: pending\" --json number,title,headRefOid,mergeStateStatus\n```\n\n- **Merge it** pinned to that head, like any merge, and without `--delete-branch`:\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- **Check the publish.** After a minute or two the new version is on the registry, for example `npm view <package> version` for an npm package (the package is named in `AGENTS.md` or the release workflow). If it is not, open the Release run (`gh run list --workflow release.yml --limit 3`), fix the cause and re-run its failed jobs: a later push does not publish a version already tagged.\n- Release-please updates the same pull request on each merge to the default branch; one release pull request can carry several merges.\n";
4275
+ var MERGE_default = "# Merging a pull request\n\nRun `armada merge <pr>` (add `--dry-run` to see the checklist only). It checks everything below, takes the project's merge lock, merges pinned to the handed-back SHA, confirms the merge on GitHub and closes the ticket. Its output lists the workers in flight to tell and the worker session to archive. When a refusal names a rule, fix the cause (usually: ask the worker to rebase and report again) rather than merging by hand. When you must merge by hand, follow the same steps.\n\n## Before\n\n1. The worker has handed back: `Agent phase` is `ready-to-merge` and you have the full 40-character head SHA it reported.\n2. `gh pr view <n> --json headRefOid,mergeStateStatus,isDraft,title` shows that SHA, `CLEAN`, not a draft, and a Commitizen title.\n3. `gh pr checks <n>` shows every required check passing.\n4. The head contains the current default branch: `git merge-base --is-ancestor origin/<default> <sha>`. If not, ask the worker to rebase.\n5. Semantic check: search the default branch for callers of anything the pull request deletes or renames.\n\n## Merge\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- One merge at a time: `armada merge` holds the project's merge lock. If it refuses because Armada is down, use `--no-lock` only when you are sure no other coordinator merges in the project.\n- Leave out `--delete-branch`: it deletes local worktrees that have the branch checked out, including other agents'. Delete the branch once its worktree is gone.\n- If GitHub answers with a 5xx, check `gh pr view <n> --json state` before retrying.\n\n## After\n\n1. The ticket is Done, its `Agent phase` and `Agent runtime` labels removed, the pull request linked.\n2. Tell every in-flight worker what the merge changes for them: a shared file, a migration, a new check, code they must now reuse or delete.\n3. Archive the merged worker's workspace with the \"Stop and archive\" section of its runtime guide.\n4. Launch the tickets this merge unblocked.\n\n## The release pull request\n\nSome repositories publish through release-please: every merge to the default branch opens or updates one release pull request, and merging it tags the version and publishes it. When the repository's rules (`AGENTS.md`) say to merge it after each merge, do it right after the ticket's merge, without a hand-back: no worker owns it, so `armada merge` does not apply.\n\n- **What it looks like.** Title `chore(main): release <version>`, opened by `github-actions`, label `autorelease: pending`, and a diff that only touches the changelog, the manifest and version fields. It is opened with the workflow's own token, so **no CI check runs on it** (only checks from apps such as Vercel, if any) and `mergeStateStatus` is `UNSTABLE`. Both are expected: the publish job runs the repository's checks again before publishing. Anything else in the diff, or a `DIRTY` state, is not expected: stop and tell the owner.\n- **Find it and its head:**\n\n```sh\ngh pr list --state open --label \"autorelease: pending\" --json number,title,headRefOid,mergeStateStatus\n```\n\n- **Merge it** pinned to that head, like any merge, and without `--delete-branch`:\n\n```sh\ngh pr merge <n> --squash --match-head-commit <full-sha>\n```\n\n- **Check the publish.** After a minute or two the new version is on the registry, for example `npm view <package> version` for an npm package (the package is named in `AGENTS.md` or the release workflow). If it is not, open the Release run (`gh run list --workflow release.yml --limit 3`), fix the cause and re-run its failed jobs: a later push does not publish a version already tagged.\n- Release-please updates the same pull request on each merge to the default branch; one release pull request can carry several merges.\n";
4952
4276
 
4953
4277
  // ../../skills/armada-coordinator/SKILL.md
4954
4278
  var SKILL_default = `---
@@ -4964,7 +4288,7 @@ The coordinator turns the owner's intent into merged pull requests. Each worker
4964
4288
 
4965
4289
  ## Take over a run
4966
4290
 
4967
- A coordinator may start cold, on a laptop or in a fresh cloud session, with nothing but the repository and a sign-in to Armada. Everything it needs is in the tracker, GitHub and Turso; the Armada [runbook](https://github.com/The-Vibe-Company/armada/blob/main/docs/runbook.md) says how to start one.
4291
+ A coordinator may start cold, on a laptop or in a fresh cloud session, with nothing but the repository and a sign-in to Armada. Everything it needs is in the tracker, GitHub and Armada; the Armada [runbook](https://github.com/The-Vibe-Company/armada/blob/main/docs/runbook.md) says how to start one.
4968
4292
 
4969
4293
  1. **Sign in to Armada.** \`armada doctor\` (or \`armada whoami\`) says whether this terminal is signed in and to which organization. If not: a person runs \`armada login\` and approves the code in the browser; a headless coordinator (a cloud workspace, CI) sets \`ARMADA_API_KEY\` to an organization API key an owner created on the Organization page. Signed in, Armada gives your commands the organization's keys, and every brief carries a one-time launch token, so no worker needs a key in its environment. Keys set in the environment still win over Armada's: they are the override for CI and a self-hosted Armada without accounts.
4970
4294
  2. **Find your coordination ticket.** When the owner gives the coordinator a ticket of its own (a run to carry out, for example "run this ticket end to end"), that ticket holds the run's history. Read its comments, newest first. A last comment \`Agent status: released — <text>\` is a hand-over: the previous coordinator stopped on purpose, \`<text>\` is the state it left (who runs, what was asked and answered, what remains), and the ticket is back without agent labels, waiting for you.
@@ -5003,7 +4327,7 @@ Repeat from step 1. Between rounds, \`armada inbox --wait\` blocks until a new i
5003
4327
  `;
5004
4328
 
5005
4329
  // ../../skills/armada-runtime-conductor/SKILL.md
5006
- var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- A worker needs no key in its workspace: the prompt of `armada brief` carries a one-time launch token, and the worker's first command exchanges it for a session limited to its ticket, through which Armada gives each command its keys. The token works once, within the hour, so a copy left in a transcript is useless once used.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12` (with `--profile <name> --reason \"<why>\"` when you override the routed profile), right before the launch. Read the profile (agent, model, effort, fast mode), the `Launch:` line and the warnings. Resolve every warning first: an open blocker, a ticket already in flight.\n - `Launch: one-time token in the prompt` is the normal case: the worker signs in to Armada with it and fetches its own keys. Its workspace receives no key at all.\n - `Launch: no launch token (…)` says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then brief again; `armada doctor` checks the sign-in. Launch with keys (step 4, second block) only on an Armada that keeps no keys yet (no accounts or no vault: a self-hosted one, CI, or before the owner's switch to the Keys page).\n3. Write the prompt to a file only you can read, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token in it works once, within the hour: brief again when that hour has passed before the launch.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt > /tmp/abc-12-brief.md)\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode. Run the whole block as one command: shell state does not carry over between separate calls.\n\n```sh\nconductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\nrm -f /tmp/abc-12-brief.md\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\nWithout a launch token (an Armada that keeps no keys), pass the keys the brief's environment table marks `required` or `optional`, from your shell or from Armada's credentials file (`in credentials file`: the `set -a` line loads it without printing it; drop it when every variable is set in your shell). The subshell keeps the keys out of the rest of your session; drop an optional `--env` line whose variable you do not have. When Conductor's organization environment still holds the keys, every workspace already has them: use the first block.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n --env ARMADA_TURSO_URL=\"$ARMADA_TURSO_URL\" \\\n --env ARMADA_TURSO_TOKEN=\"$ARMADA_TURSO_TOKEN\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\nrm -f /tmp/abc-12-brief.md\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace, and signs `gh` in for the worker's pushes. The brief's first commands install your Armada version (`npm install -g`), sign in with the launch token (`armada login --launch-token`) and claim the ticket. `--env` values are not shown back by `workspace get`.\n- Keys in Conductor's organization environment reach every workspace, workers included: once Armada keeps the organization's keys, they belong on Armada's Keys page, not there.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after ten minutes: read the transcript (Status section). A worker whose launch token was refused (already used, or more than an hour old) needs a new one: `armada brief ABC-12 --prompt` again, and message it only the `armada login --launch-token …` line of the new prompt (Message section). A worker cut off from Armada was revoked on the dashboard (Organization > Workers says by whom) or left idle for three days: ask the owner before you give a revoked worker a new token. If the worker cannot claim for another reason, fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n";
4330
+ var SKILL_default2 = "---\nname: armada-runtime-conductor\ndescription: Runtime guide for running Armada workers on Conductor Cloud. Use when an Armada coordinator must launch a worker on a ticket, send it a message, check whether a silent worker is still alive, or stop and archive it. Four fixed sections, each with the exact conductor command and how to read its output.\n---\n\nArmada never calls a runtime. This guide tells the coordinator how to launch, message, check and stop a worker with the `conductor` command line tool, and what to record in Armada afterwards. It was checked against `conductor` 0.89.x (the desktop app's CLI, macOS) and 0.1.x (the CLI inside a Conductor Cloud workspace, Linux); every command below works in both. `conductor --version` prints yours; if a flag is refused, compare with `conductor <command> --help`.\n\n- Always pass `--json` and read fields with `jq`. Exit codes: 0 ok, 1 runtime error, 2 usage error, 3 authentication, 4 server error.\n- On exit code 3, `conductor auth whoami` checks the token the CLI uses (it exits 0 when the token works). Do not rely on `conductor auth status`: it only looks for a macOS Keychain entry and fails on Linux (\"Keychain storage is only supported on macOS\"). In a Conductor Cloud workspace the CLI reads `CONDUCTOR_API_KEY` from the environment and needs no login; on a Mac, `conductor auth login` stores a token in the Keychain.\n- A worker is one workspace with one session. Its Armada handle is `<workspaceId>/<sessionId>`; the worker's claim comment carries it, so `armada status` and the ticket always lead back to the session.\n- A worker needs no key in its workspace: the prompt of `armada brief` carries a one-time launch token, and the worker's first command exchanges it for a session limited to its ticket, through which Armada gives each command its keys. The token works once, within the hour, so a copy left in a transcript is useless once used.\n- Never type a secret value into a command, a file or a message: name the variable and let your shell expand it. The expanded value is still in the `conductor` process's arguments while it runs, so launch from a machine only you use.\n\n## Launch\n\n1. Pick a ready ticket from `armada status` that does not collide with work in flight.\n2. Run `armada brief ABC-12` (with `--profile <name> --reason \"<why>\"` when you override the routed profile), right before the launch. Read the profile (agent, model, effort, fast mode), the `Launch:` line and the warnings. Resolve every warning first: an open blocker, a ticket already in flight.\n - `Launch: one-time token in the prompt` is the normal case: the worker signs in to Armada with it and fetches its own keys. Its workspace receives no key at all.\n - `Launch: no launch token (…)` says why. Not signed in: `armada login` (a headless coordinator sets `ARMADA_API_KEY`), then brief again; `armada doctor` checks the sign-in. Launch with keys (step 4, second block) only on an Armada that keeps no keys yet (no accounts or no vault: a self-hosted one, CI, or before the owner's switch to the Keys page).\n3. Write the prompt to a file only you can read, and add what only you know (the boundary with a parallel worker, a decision not yet on the ticket). The token in it works once, within the hour: brief again when that hour has passed before the launch.\n\n```sh\n(umask 077; armada brief ABC-12 --prompt > /tmp/abc-12-brief.md)\n```\n\n4. Create the workspace with every value from the profile. Never leave the agent, model or effort to Conductor's defaults. Add `--fast-mode` when the profile says fast mode. Run the whole block as one command: shell state does not carry over between separate calls.\n\n```sh\nconductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\nrm -f /tmp/abc-12-brief.md\njq -r '\"\\(.workspaceId)/\\(.sessionId)\"' /tmp/abc-12-launch.json\n```\n\nWithout a launch token (an Armada that keeps no keys), pass the keys the brief's environment table marks `required`, from your shell or from Armada's credentials file (`in credentials file`: the `set -a` line loads it without printing it; drop it when every variable is set in your shell). The subshell keeps the keys out of the rest of your session. Without a launch token the worker is not signed in to Armada: its claims and reports reach Linear only, with a warning. When Conductor's organization environment still holds the keys, every workspace already has them: use the first block.\n\n```sh\n(\n set -a; . \"${XDG_CONFIG_HOME:-$HOME/.config}/armada/credentials\"; set +a\n [ -n \"$LINEAR_API_KEY\" ] || { echo \"LINEAR_API_KEY is missing\" >&2; exit 1; }\n conductor --json workspace create \\\n --repo-url https://github.com/<owner>/<name> \\\n --branch main \\\n --name \"ABC-12 <short title>\" \\\n --agent claude --model opus-5-5-1m --effort high \\\n --message-file - \\\n --env ARMADA_TICKET=ABC-12 \\\n --env LINEAR_API_KEY=\"$LINEAR_API_KEY\" \\\n < /tmp/abc-12-brief.md > /tmp/abc-12-launch.json\n)\nrm -f /tmp/abc-12-brief.md\n```\n\n- `--branch` is the base branch (the default branch). Conductor creates a branch named `conductor/<slug of --name>`; the brief tells the worker to rename it to the ticket's branch.\n- The output has `workspaceId`, `sessionId`, `deepLink` and `initialMessage` (`messageId`, `state: \"queued\"`). Keep the handle the `jq` line prints, and give the owner the `deepLink` when they want to watch.\n- Conductor sets `CONDUCTOR_WORKSPACE_ID` and `CONDUCTOR_SESSION_ID` inside the workspace, and signs `gh` in for the worker's pushes. The brief's first commands install your Armada version (`npm install -g`), sign in with the launch token (`armada login --launch-token`) and claim the ticket. `--env` values are not shown back by `workspace get`.\n- Keys in Conductor's organization environment reach every workspace, workers included: once Armada keeps the organization's keys, they belong on Armada's Keys page, not there.\n- An unknown agent, model or effort fails the command. Check the ids with `conductor model` (each agent's models, efforts and defaults) and fix the profile in `armada.toml`.\n\n5. **Check the claim.** Within a few minutes, `armada status` lists the ticket in flight, phase `planning`, runtime `Conductor`, and the ticket's claim comment reads `session: <workspaceId>/<sessionId>` and `profile: <name>`. No claim after ten minutes: read the transcript (Status section). A worker whose launch token was refused (already used, or more than an hour old) needs a new one: `armada brief ABC-12 --prompt` again, and message it only the `armada login --launch-token …` line of the new prompt (Message section). A worker cut off from Armada was revoked on the dashboard (Organization > Workers says by whom) or left idle for three days: ask the owner before you give a revoked worker a new token. If the worker cannot claim for another reason, fix the cause and message it; as a last resort record the handle yourself with `armada claim ABC-12 --runtime conductor --handle <workspaceId>/<sessionId> --profile <name>`, adding the brief's `--reason` for an override.\n\n## Message\n\n```sh\nprintf '%s\\n' \"Plan approved. Go on.\" | conductor --json message create --session <sessionId> --message-file -\nconductor --json message create --session <sessionId> --message-file - < /tmp/abc-12-answer.md\n```\n\nThe output is `{\"messageId\": …, \"state\": \"sent\"}`. Exit code 0 means Conductor accepted the message, not that the worker read it: check that the session turns `working`, then read its reply in the transcript. Use it to deliver an answer, a plan approval, or a heads-up that the default branch moved. Then record it in Armada: `armada answer <item> \"<answer>\"` for a question from `armada inbox`, `armada answer --note ABC-12 \"<message>\"` for a message the worker did not ask for.\n\n## Status\n\n```sh\nconductor --json session status <sessionId>\n```\n\nThe output is `{\"workspaceId\", \"sessionId\", \"status\", \"updatedAt\"}`. For a worker:\n\n- `working`: a turn is running. A silent worker that is `working` is busy (a long build or test run): leave it, and read the transcript if it stays silent past twice `policy.silence_minutes`.\n- `idle`: no turn is running. The worker finished its turn: it handed back, it waits for an answer, or it stopped without finishing. If `armada status` does not show it `ready-to-merge`, `awaiting-approval` or `blocked`, it has stopped: read its last reply, then message it to go on, or release and relaunch the ticket.\n- `error`: the last turn failed (agent or provider failure). Read the transcript and message it to resume; if it fails again, cancel, archive, release and relaunch.\n- Right after launch the session is `idle` for a few seconds while the workspace is initializing and the first message is queued; it turns `working` when the agent starts.\n\nThe workspace itself: `conductor --json workspace status <workspaceId>` gives `status` `initializing`, `ready` or `archived`.\n\n**Read the transcript** to see what a worker did or said. Events come oldest first, 100 per page; `hasMore` tells when to fetch the next page with `--after` the last event id. Keep the last id you read and poll from it.\n\n```sh\nconductor --json session message <sessionId> --limit 100 > /tmp/abc-12-events.json\njq -r '.hasMore, .data[-1].id' /tmp/abc-12-events.json\nconductor --json session message <sessionId> --after <lastEventId> --limit 100\n```\n\nThe second line prints whether more pages exist and the id to continue from. `.content.rawPayload` is the agent's own event format, so the filters depend on the worker's agent (the `agent` of its profile in `armada.toml`).\n\nA `claude` worker: each turn's final reply, then the commands and tools it ran.\n\n```sh\njq -r '.data[] | select(.content.rawPayload.type == \"result\") | .content.rawPayload | \"error=\\(.is_error)\\n\\(.result)\"' /tmp/abc-12-events.json\njq -r '.data[] | select(.content.rawPayload.type == \"assistant\") | .content.rawPayload.message.content[] | select(.type == \"tool_use\") | .input.command // .name' /tmp/abc-12-events.json\n```\n\nA `codex` worker: its events are `.content.rawPayload.event`, each item once as `item.started` and once as `item.completed`; read the completed ones. Its messages (`phase` is `commentary` along the way, `final_answer` at the end of a turn), then each command with its exit code, and its tool calls (Linear and other MCP servers).\n\n```sh\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"agentMessage\") | \"[\\(.phase)] \\(.text)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"commandExecution\") | \"exit=\\(.exitCode) \\(.command)\"' /tmp/abc-12-events.json\njq -r '.data[] | .content.rawPayload.event | select(.type == \"item.completed\") | .item | select(.type == \"mcpToolCall\") | \"\\(.server) \\(.tool)\"' /tmp/abc-12-events.json\n```\n\nAnother agent, or a filter that prints nothing: count the event types, look at one event of the type you need, and adapt the filter.\n\n```sh\njq -r '.data[].content.rawPayload | .type // .event.type // \"(no payload)\"' /tmp/abc-12-events.json | sort | uniq -c\n```\n\n## Stop and archive\n\n```sh\nconductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n\n- `session cancel` stops the running turn: `{\"status\", \"canceledQueuedMessages\"}`, and the session is `idle` within seconds. The workspace stays; a message starts a new turn. Use it on a worker that runs the wrong thing.\n- `workspace archive` answers `{\"status\": \"archived\"}`. Archive a worker's workspace after its pull request is merged, or after `armada release --ticket ABC-12 --reason \"<why>\"` for a worker that stops without handing back. The branch and the pull request stay on GitHub.\n- **Wait for `idle` before archiving.** A hand-back often arrives while the worker's session is still `working`: `armada report ready-to-merge` runs inside its last turn, which then writes its final reply. Archive only once `session status` answers `idle`. Poll it every 15 seconds; if it is still `working` after 10 minutes, cancel the turn and archive (the transcript keeps what it was doing). Run the whole block as one command; it can take up to 10 minutes, so run it in the background or give it a longer command timeout:\n\n```sh\nfor i in $(seq 40); do\n [ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] || break\n sleep 15\ndone\n[ \"$(conductor --json session status <sessionId> | jq -r .status)\" = working ] && conductor --json session cancel <sessionId>\nconductor --json workspace archive <workspaceId>\n```\n- After an archive, `session status` still answers `idle`; `workspace status` says `archived`.\n";
5007
4331
 
5008
4332
  // ../../skills/armada-worker/SKILL.md
5009
4333
  var SKILL_default3 = `---
@@ -5393,7 +4717,7 @@ async function readStatusSources(config, opts) {
5393
4717
  async function loadStatus(config, opts) {
5394
4718
  const now = opts.now ?? (() => new Date);
5395
4719
  const eventsP = opts.lastEvents ? opts.lastEvents().then((events) => ({ events }), (err) => ({
5396
- warning: `Turso could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
4720
+ warning: `Armada's live data could not be read (${err instanceof Error ? err.message : String(err)}); silence is measured from Linear only`
5397
4721
  })) : Promise.resolve({});
5398
4722
  const [{ program, forge, forgeError }, events] = await Promise.all([readStatusSources(config, opts), eventsP]);
5399
4723
  return buildStatus({
@@ -5407,7 +4731,7 @@ async function loadStatus(config, opts) {
5407
4731
  });
5408
4732
  }
5409
4733
  // package.json
5410
- var version = "0.1.21";
4734
+ var version = "0.2.0";
5411
4735
 
5412
4736
  // src/io.ts
5413
4737
  class UsageError extends Error {
@@ -5430,73 +4754,33 @@ async function loadMachine(io) {
5430
4754
  ]);
5431
4755
  return { paths, store, personal };
5432
4756
  }
5433
- var hhmm = (iso) => `${iso.slice(0, 16).replace("T", " ")} UTC`;
5434
- var wantsArmada = (env) => !env.LINEAR_API_KEY?.trim() || !env.ARMADA_TURSO_URL?.trim() && !env.ARMADA_TURSO_TOKEN?.trim();
5435
- var fromLease = (lease) => ({
5436
- url: lease.url,
5437
- token: lease.token,
5438
- detail: `a token made for this terminal, expires ${hhmm(lease.expiresAt)}`
5439
- });
5440
- async function fromArmada(io, machine, credentials, purpose) {
4757
+ var wantsArmada = (env) => !env.LINEAR_API_KEY?.trim();
4758
+ async function fromArmada(io, credentials, purpose) {
5441
4759
  const signIn = credentials.armadaSignIn;
5442
4760
  if (!signIn)
5443
4761
  return null;
5444
- const now = (io.now ?? (() => new Date))();
5445
- const address = armadaAddress(credentials.armadaApi.url);
5446
- const stored = parseLease(machine.store?.values[TURSO_LEASE_VARIABLE]);
5447
- const lease = stored && stored.api === address && Date.parse(stored.expiresAt) > now.getTime() ? stored : null;
5448
- const keep = async (next) => {
5449
- if (!machine.paths || next === null && !machine.store?.assigned.includes(TURSO_LEASE_VARIABLE))
5450
- return;
5451
- await updateCredentialStore(machine.paths, { [TURSO_LEASE_VARIABLE]: next ? formatLease(next) : null }).catch((err) => io.stderr(`! the Turso token from Armada could not be kept in ${machine.paths?.credentials} (${err.code ?? "error"}); it is asked again next time
5452
- `));
5453
- };
5454
4762
  let answer;
5455
4763
  try {
5456
- answer = await armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} }).credentials(signIn, lease ? { revision: lease.revision, expiresAt: lease.expiresAt } : null, purpose);
4764
+ answer = await armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} }).credentials(signIn, purpose);
5457
4765
  } catch (err) {
5458
4766
  if (!(err instanceof ArmadaApiError))
5459
4767
  throw err;
5460
- if (err.signedOut || err.status === 403) {
5461
- await keep(null);
5462
- if (signIn.kind === "worker")
5463
- throw err;
5464
- io.stderr(`! Armada gave no keys (${err.message}); using this machine's${err.next ? `. Next: ${err.next}` : ""}
5465
- `);
5466
- return null;
5467
- }
5468
- if (err.status === 503 && !lease)
4768
+ if ((err.signedOut || err.status === 403) && signIn.kind === "worker")
4769
+ throw err;
4770
+ if (err.status === 503)
5469
4771
  return null;
5470
- io.stderr(`! Armada gave no keys (${err.message}); using this machine's${lease ? " and the Turso token it made earlier" : ""}${err.next ? `. Next: ${err.next}` : ""}
4772
+ io.stderr(`! Armada gave no keys (${err.message}); using this machine's${err.next ? `. Next: ${err.next}` : ""}
5471
4773
  `);
5472
- return lease ? { linearApiKey: null, turso: fromLease(lease) } : null;
4774
+ return null;
5473
4775
  }
5474
4776
  for (const w of answer.warnings)
5475
4777
  io.stderr(`! Armada: ${w}
5476
4778
  `);
5477
- const linearApiKey = answer.linear ? {
5478
- value: answer.linear.apiKey,
5479
- detail: answer.linear.scope === "own" ? "your own key" : `the key of ${answer.organization.name}`
5480
- } : null;
5481
- const t = answer.turso;
5482
- if (t?.kind === "minted") {
5483
- const next = {
5484
- api: address,
5485
- organization: answer.organization.id,
5486
- url: t.url,
5487
- token: t.token,
5488
- expiresAt: t.expiresAt,
5489
- revision: t.revision
5490
- };
5491
- await keep(next);
5492
- return { linearApiKey, turso: fromLease(next) };
5493
- }
5494
- if (t?.kind === "kept" && lease)
5495
- return { linearApiKey, turso: fromLease(lease) };
5496
- await keep(null);
5497
4779
  return {
5498
- linearApiKey,
5499
- turso: t?.kind === "stored" ? { url: t.url, token: t.token, detail: `the stored Turso access of ${answer.organization.name}` } : null
4780
+ linearApiKey: answer.linear ? {
4781
+ value: answer.linear.apiKey,
4782
+ detail: answer.linear.scope === "own" ? "your own key" : `the key of ${answer.organization.name}`
4783
+ } : null
5500
4784
  };
5501
4785
  }
5502
4786
  async function loadCredentials(io, { armada = true, worker } = {}) {
@@ -5526,12 +4810,12 @@ async function loadCredentials(io, { armada = true, worker } = {}) {
5526
4810
  if (signIn?.kind === "worker" && armada) {
5527
4811
  if (signIn.project !== worker?.project)
5528
4812
  throw new UsageError(`the worker session of ${signIn.ticket} is for the project ${signIn.project}, not ${worker?.project} (armada.toml): this repository is not its own`, `cd into the repository of ${signIn.project}`);
5529
- const keys = await fromArmada(io, machine, local, purpose);
4813
+ const keys = await fromArmada(io, local, purpose);
5530
4814
  return { machine, credentials: keys ? resolveCredentials({ ...sources, armada: keys }) : local };
5531
4815
  }
5532
4816
  if (!armada || !signIn || !wantsArmada(io.env))
5533
4817
  return { machine, credentials: local };
5534
- const keys = await fromArmada(io, machine, local, purpose);
4818
+ const keys = await fromArmada(io, local, purpose);
5535
4819
  return { machine, credentials: keys ? resolveCredentials({ ...sources, armada: keys }) : local };
5536
4820
  }
5537
4821
  var describeSource = (s) => {
@@ -5676,7 +4960,7 @@ async function authStatus(io, json) {
5676
4960
  async function authLogout(io) {
5677
4961
  const paths = requirePaths(machinePaths(io.env));
5678
4962
  const store = await readCredentialStore(paths.credentials);
5679
- const variables = [...STORED_KEYS.map((k) => k.variable), TURSO_LEASE_VARIABLE];
4963
+ const variables = [...STORED_KEYS.map((k) => k.variable), ...RETIRED_VARIABLES];
5680
4964
  const stored = variables.filter((v) => store.assigned.includes(v));
5681
4965
  if (!stored.length) {
5682
4966
  io.stdout(`No Armada key is stored in ${paths.credentials}.
@@ -5806,6 +5090,7 @@ var hostOf = (url) => {
5806
5090
  return url;
5807
5091
  }
5808
5092
  };
5093
+ var RETIRED = Object.fromEntries(RETIRED_VARIABLES.map((v) => [v, null]));
5809
5094
  var apiOf = (io, url) => armadaApi({ url, ...io.fetch ? { fetch: io.fetch } : {} });
5810
5095
  var storedAt = (machine) => armadaAddress(machine.store?.values[SIGNED_IN_TO_VARIABLE]?.trim() || DEFAULT_ARMADA_API_URL);
5811
5096
  var sleepOf = (io) => io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
@@ -5860,7 +5145,7 @@ async function loginWithApiKey(io, credentials) {
5860
5145
  [API_KEY_VARIABLE]: key,
5861
5146
  [SESSION_TOKEN_VARIABLE]: null,
5862
5147
  [SIGNED_IN_TO_VARIABLE]: armadaAddress(url),
5863
- [TURSO_LEASE_VARIABLE]: null
5148
+ ...RETIRED
5864
5149
  });
5865
5150
  io.stdout(`Signed in to ${hostOf(credentials.armadaApi.url)} as ${describeIdentity(identity)}.
5866
5151
  The key is stored in ${p.credentials}.
@@ -5929,7 +5214,7 @@ Then confirm it at ${code.verificationUriComplete}
5929
5214
  [SESSION_TOKEN_VARIABLE]: token,
5930
5215
  [API_KEY_VARIABLE]: null,
5931
5216
  [SIGNED_IN_TO_VARIABLE]: armadaAddress(url),
5932
- [TURSO_LEASE_VARIABLE]: null
5217
+ ...RETIRED
5933
5218
  });
5934
5219
  if (previous && previous !== token)
5935
5220
  await apiOf(io, storedAt(machine)).signOut({ kind: "session", token: previous }).catch(() => {});
@@ -5965,7 +5250,7 @@ async function logout(io) {
5965
5250
  const p = paths(io);
5966
5251
  const at = storedAt(machine);
5967
5252
  const workers = (machine.store?.assigned ?? []).filter((k) => k.startsWith(WORKER_SESSION_PREFIX));
5968
- const stored = [SESSION_TOKEN_VARIABLE, API_KEY_VARIABLE, TURSO_LEASE_VARIABLE, ...workers].filter((k) => machine.store?.assigned.includes(k));
5253
+ const stored = [SESSION_TOKEN_VARIABLE, API_KEY_VARIABLE, ...RETIRED_VARIABLES, ...workers].filter((k) => machine.store?.assigned.includes(k));
5969
5254
  const session = machine.store?.values[SESSION_TOKEN_VARIABLE]?.trim();
5970
5255
  if (session) {
5971
5256
  await apiOf(io, at).signOut({ kind: "session", token: session }).catch((err) => io.stderr(`! the session could not be revoked on Armada (${err instanceof Error ? err.message : String(err)}); it expires on its own
@@ -5976,7 +5261,7 @@ async function logout(io) {
5976
5261
  [SESSION_TOKEN_VARIABLE]: null,
5977
5262
  [API_KEY_VARIABLE]: null,
5978
5263
  [SIGNED_IN_TO_VARIABLE]: null,
5979
- [TURSO_LEASE_VARIABLE]: null,
5264
+ ...RETIRED,
5980
5265
  ...Object.fromEntries(workers.map((k) => [k, null]))
5981
5266
  });
5982
5267
  io.stdout(`Signed out of ${hostOf(at)}: removed the sign-in from ${p.credentials}.
@@ -6114,12 +5399,24 @@ The worker session${credentials.workerTickets.length === 1 ? "" : "s"} of ${cred
6114
5399
  }
6115
5400
  function keyFileChecks(machine, credentials) {
6116
5401
  const store = machine.store;
6117
- if (!store?.exists || !credentials.armadaSignIn)
5402
+ if (!store?.exists)
6118
5403
  return [];
5404
+ const retired = RETIRED_VARIABLES.filter((v) => store.assigned.includes(v));
5405
+ const checks = retired.length ? [
5406
+ {
5407
+ id: "retired-keys",
5408
+ level: "warning",
5409
+ message: `${store.path} still holds ${retired.join(", ")}, which this version never reads: the CLI reaches the fleet's data through Armada`,
5410
+ fix: `\`armada login\` removes ${retired.length === 1 ? "it" : "them"} as it signs this terminal in; or delete ${retired.length === 1 ? "its line" : "their lines"} from ${store.path}`
5411
+ }
5412
+ ] : [];
5413
+ if (!credentials.armadaSignIn)
5414
+ return checks;
6119
5415
  const unneeded = STORED_KEYS.filter((k) => store.values[k.variable]?.trim() && credentials.sources[k.name]?.kind === "armada").map((k) => k.variable);
6120
5416
  if (!unneeded.length)
6121
- return [];
5417
+ return checks;
6122
5418
  return [
5419
+ ...checks,
6123
5420
  {
6124
5421
  id: "local-keys",
6125
5422
  level: "warning",
@@ -6214,41 +5511,26 @@ async function doctor(io, json, armadaVersion) {
6214
5511
  }
6215
5512
 
6216
5513
  // src/worker.ts
6217
- var TURSO_OPEN_TIMEOUT_MS = 1e4;
6218
- async function openLive(credentials) {
6219
- if (!credentials.tursoUrl)
6220
- return { db: null, warning: "Turso is not configured (ARMADA_TURSO_URL); live activity is not recorded" };
6221
- let timer;
6222
- const opening = openTurso({ url: credentials.tursoUrl, token: credentials.tursoToken });
5514
+ function liveFleet(io, config, credentials) {
5515
+ const signIn = credentials.armadaSignIn;
5516
+ if (!signIn)
5517
+ return {
5518
+ fleet: null,
5519
+ warning: "not signed in to Armada (armada login); live activity is not recorded, Linear is"
5520
+ };
6223
5521
  try {
6224
- const db = await Promise.race([
6225
- opening,
6226
- new Promise((_, reject) => {
6227
- timer = setTimeout(() => reject(new Error(`no answer within ${TURSO_OPEN_TIMEOUT_MS / 1000} s`)), TURSO_OPEN_TIMEOUT_MS);
6228
- })
6229
- ]);
6230
- return { db, warning: null };
5522
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
5523
+ return { fleet: fleetClient({ api, signIn, project: projectOf(config) }), warning: null };
6231
5524
  } catch (err) {
6232
- opening.then((db) => db.close(), () => {});
6233
- const reason = err instanceof Error ? err.message : String(err);
6234
- return { db: null, warning: `Turso unavailable (${reason}); live activity is not recorded, Linear is` };
6235
- } finally {
6236
- clearTimeout(timer);
5525
+ return {
5526
+ fleet: null,
5527
+ warning: `${err instanceof Error ? err.message : String(err)}; live activity is not recorded`
5528
+ };
6237
5529
  }
6238
5530
  }
6239
- function statusEvents(config, credentials) {
6240
- if (!credentials.tursoUrl)
6241
- return;
6242
- return async () => {
6243
- const { db, warning } = await openLive(credentials);
6244
- if (!db)
6245
- throw new Error(warning ?? "Turso unavailable");
6246
- try {
6247
- return await lastEventTimes(db, config.project.slug);
6248
- } finally {
6249
- db.close();
6250
- }
6251
- };
5531
+ function statusEvents(io, config, credentials) {
5532
+ const { fleet } = liveFleet(io, config, credentials);
5533
+ return fleet ? () => fleet.lastEventTimes() : undefined;
6252
5534
  }
6253
5535
  function currentTicket(io, config, explicit, workers = []) {
6254
5536
  const fromEnv = io.env.ARMADA_TICKET?.trim();
@@ -6260,7 +5542,7 @@ function currentTicket(io, config, explicit, workers = []) {
6260
5542
  throw new UsageError("which ticket? pass --ticket <id>, set ARMADA_TICKET, or run on the ticket's branch");
6261
5543
  return id.toUpperCase();
6262
5544
  }
6263
- async function context(io, config, credentials) {
5545
+ function context(io, config, credentials) {
6264
5546
  if (!credentials.linearApiKey)
6265
5547
  throw missingKey(LINEAR_KEY);
6266
5548
  const linearOpts = {
@@ -6269,15 +5551,12 @@ async function context(io, config, credentials) {
6269
5551
  ...io.fetch ? { fetch: io.fetch } : {}
6270
5552
  };
6271
5553
  const linear = io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts);
6272
- let live = null;
5554
+ const live = liveFleet(io, config, credentials);
6273
5555
  const token = credentials.githubToken;
6274
- const ctx = {
5556
+ return {
6275
5557
  config,
6276
5558
  linear,
6277
- turso: () => {
6278
- live ??= openLive(credentials);
6279
- return live;
6280
- },
5559
+ fleet: async () => live,
6281
5560
  readPull: token ? (number) => fetchPullRequest({
6282
5561
  token,
6283
5562
  repository: config.github.repository,
@@ -6286,11 +5565,6 @@ async function context(io, config, credentials) {
6286
5565
  }) : null,
6287
5566
  now: io.now ?? (() => new Date)
6288
5567
  };
6289
- const close = async () => {
6290
- const opened = await live;
6291
- opened?.db?.close();
6292
- };
6293
- return { ctx, close };
6294
5568
  }
6295
5569
  function print(io, outcome, json) {
6296
5570
  if (json) {
@@ -6334,13 +5608,8 @@ async function readMessage(io, options) {
6334
5608
  return text;
6335
5609
  }
6336
5610
  async function withContext(io, config, credentials, json, act) {
6337
- const { ctx, close } = await context(io, config, credentials);
6338
- try {
6339
- print(io, await act(ctx), json);
6340
- return 0;
6341
- } finally {
6342
- await close();
6343
- }
5611
+ print(io, await act(context(io, config, credentials)), json);
5612
+ return 0;
6344
5613
  }
6345
5614
  async function claim(io, config, credentials, a) {
6346
5615
  const [ticket, ...extra] = a.rest;
@@ -6507,31 +5776,26 @@ async function inbox2(io, config, credentials, a) {
6507
5776
  if (!wait && a.options.timeout !== undefined)
6508
5777
  throw new UsageError("--timeout applies to --wait");
6509
5778
  const timeoutMs = waitSeconds(a.options.timeout) * 1000;
6510
- if (!credentials.tursoUrl)
6511
- throw new UsageError("the inbox lives in Turso: set ARMADA_TURSO_URL", "armada auth login");
6512
- const { db, warning } = await openLive(credentials);
6513
- if (!db)
6514
- throw new Refusal(`the inbox lives in Turso, which is unavailable: ${warning ?? "no answer"}`, "armada inbox again once Turso answers (armada auth status shows the URL in use)");
6515
- try {
6516
- const workspace = io.env.CONDUCTOR_WORKSPACE_ID?.trim();
6517
- const session = io.env.CONDUCTOR_SESSION_ID?.trim();
6518
- const coordinator = io.env.ARMADA_COORDINATOR_HANDLE?.trim() || (workspace && session ? `${workspace}/${session}` : null);
6519
- const report = await checkInbox(db, {
6520
- project: config.project.slug,
6521
- coordinator,
6522
- silentAfterMinutes: config.policy.silentAfterMinutes,
6523
- now: io.now ?? (() => new Date),
6524
- ...wait ? { wait: { timeoutMs, sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))) } } : {}
6525
- });
6526
- io.stdout(a.json ? `${JSON.stringify(report, null, 2)}
5779
+ requireSignIn(credentials);
5780
+ const { fleet, warning } = liveFleet(io, config, credentials);
5781
+ if (!fleet)
5782
+ throw new Refusal(`the inbox is on Armada, which cannot be reached: ${warning ?? "no answer"}`, "armada whoami");
5783
+ const workspace = io.env.CONDUCTOR_WORKSPACE_ID?.trim();
5784
+ const session = io.env.CONDUCTOR_SESSION_ID?.trim();
5785
+ const coordinator = io.env.ARMADA_COORDINATOR_HANDLE?.trim() || (workspace && session ? `${workspace}/${session}` : null);
5786
+ const report = await checkInbox(fleet, {
5787
+ project: config.project.slug,
5788
+ coordinator,
5789
+ silentAfterMinutes: config.policy.silentAfterMinutes,
5790
+ now: io.now ?? (() => new Date),
5791
+ ...wait ? { wait: { timeoutMs, sleep: io.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms))) } } : {}
5792
+ });
5793
+ io.stdout(a.json ? `${JSON.stringify(report, null, 2)}
6527
5794
  ` : renderInbox(report));
6528
- for (const w of report.warnings)
6529
- io.stderr(`armada: warning: ${w}
5795
+ for (const w of report.warnings)
5796
+ io.stderr(`armada: warning: ${w}
6530
5797
  `);
6531
- return 0;
6532
- } finally {
6533
- db.close();
6534
- }
5798
+ return 0;
6535
5799
  }
6536
5800
 
6537
5801
  // src/init.ts
@@ -6610,19 +5874,17 @@ function prText(plan, version) {
6610
5874
  }
6611
5875
  async function init(io, opts) {
6612
5876
  const exec = requireExec(io);
6613
- const tursoKey = STORED_KEYS.find((k) => k.name === "tursoUrl") ?? LINEAR_KEY;
6614
- const required = (c) => [c.linearApiKey ? null : LINEAR_KEY, c.tursoUrl ? null : tursoKey];
6615
- if (io.interactive || required((await loadCredentials(io)).credentials).some(Boolean)) {
5877
+ const first = (await loadCredentials(io)).credentials;
5878
+ requireSignIn(first);
5879
+ if (io.interactive || !first.linearApiKey) {
6616
5880
  const login = await authLogin(io);
6617
5881
  if (login !== 0)
6618
5882
  return login;
6619
5883
  }
6620
5884
  const { credentials } = await loadCredentials(io);
6621
- const missing = required(credentials).find(Boolean);
6622
- if (missing)
6623
- throw missingKey(missing);
6624
- const linearApiKey = credentials.linearApiKey ?? "";
6625
- const tursoUrl = credentials.tursoUrl ?? "";
5885
+ if (!credentials.linearApiKey)
5886
+ throw missingKey(LINEAR_KEY);
5887
+ const linearApiKey = credentials.linearApiKey;
6626
5888
  const root = await gitRoot(exec, io.cwd);
6627
5889
  if (!root)
6628
5890
  throw new UsageError(`${io.cwd} is not inside a git repository`, "armada init again from the checkout of the repository to set up");
@@ -6706,19 +5968,11 @@ async function init(io, opts) {
6706
5968
  if (plan.updated.length)
6707
5969
  log(`Updates: ${plan.updated.join(", ")}`);
6708
5970
  }
6709
- const db = await openTurso({ url: tursoUrl, token: credentials.tursoToken });
6710
- try {
6711
- const project = {
6712
- slug: config.project.slug,
6713
- name: config.project.name,
6714
- repository: config.github.repository,
6715
- programRoot: config.tracker.programRoot
6716
- };
6717
- await upsertProject(db, project, io.now?.() ?? new Date);
6718
- } finally {
6719
- db.close();
6720
- }
6721
- log(`Registered project ${config.project.slug}; armada status --all lists it.`);
5971
+ const { fleet, warning } = liveFleet(io, config, credentials);
5972
+ if (!fleet)
5973
+ throw new UsageError(`the project could not be registered: ${warning}`, "armada whoami");
5974
+ await fleet.register();
5975
+ log(`Registered project ${config.project.slug} on Armada; armada status --all lists it.`);
6722
5976
  return 0;
6723
5977
  } finally {
6724
5978
  await exec("git", ["worktree", "remove", "--force", checkout], { cwd: root }).catch(() => null);
@@ -6882,7 +6136,7 @@ async function merge2(io, config, credentials, a, configPath) {
6882
6136
  const gh = { token, repository: config.github.repository, ...fetchOpt };
6883
6137
  const linearOpts = { apiKey: linearApiKey, labels: config.tracker.labels, ...fetchOpt };
6884
6138
  const now = io.now ?? (() => new Date);
6885
- const turso = { live: null };
6139
+ const live = liveFleet(io, config, credentials);
6886
6140
  const ctx = {
6887
6141
  config,
6888
6142
  linear: io.linearWriter ? io.linearWriter(linearOpts) : createLinearWriter(linearOpts),
@@ -6893,11 +6147,8 @@ async function merge2(io, config, credentials, a, configPath) {
6893
6147
  merge: ghMerge(exec, repoDir, config.github.repository)
6894
6148
  },
6895
6149
  repo: gitRepo(exec, repoDir),
6896
- tursoConfigured: !!credentials.tursoUrl,
6897
- turso: () => {
6898
- turso.live ??= openLive(credentials);
6899
- return turso.live;
6900
- },
6150
+ lockRequired: !!credentials.armadaSignIn,
6151
+ fleet: async () => live,
6901
6152
  inFlight: async () => (await loadStatus(config, { linearApiKey, githubToken: null, ...fetchOpt, now })).inFlight.map((t) => ({
6902
6153
  id: t.id,
6903
6154
  title: t.title,
@@ -6916,31 +6167,27 @@ async function merge2(io, config, credentials, a, configPath) {
6916
6167
  return false;
6917
6168
  }
6918
6169
  };
6919
- try {
6920
- const o = await mergePullRequest(ctx, {
6921
- pr: number,
6922
- ticket: a.options.ticket ?? null,
6923
- dryRun: !!a.options["dry-run"],
6924
- noLock: !!a.options["no-lock"]
6925
- });
6926
- io.stdout(a.json ? `${JSON.stringify(o, null, 2)}
6170
+ const o = await mergePullRequest(ctx, {
6171
+ pr: number,
6172
+ ticket: a.options.ticket ?? null,
6173
+ dryRun: !!a.options["dry-run"],
6174
+ noLock: !!a.options["no-lock"]
6175
+ });
6176
+ io.stdout(a.json ? `${JSON.stringify(o, null, 2)}
6927
6177
  ` : render(o));
6928
- for (const w of o.warnings)
6929
- io.stderr(`armada: warning: ${w}
6178
+ for (const w of o.warnings)
6179
+ io.stderr(`armada: warning: ${w}
6930
6180
  `);
6931
- if (o.merged)
6932
- await endWorkerSessions(io, config, credentials, o.ticket.id, "merged", a.json);
6933
- return 0;
6934
- } finally {
6935
- (await turso.live)?.db?.close();
6936
- }
6181
+ if (o.merged)
6182
+ await endWorkerSessions(io, config, credentials, o.ticket.id, "merged", a.json);
6183
+ return 0;
6937
6184
  }
6938
6185
 
6939
6186
  // src/render.ts
6940
- var MIN3 = 60000;
6187
+ var MIN2 = 60000;
6941
6188
  function relative2(iso, now) {
6942
6189
  const diff = now - Date.parse(iso);
6943
- const m = Math.round(Math.abs(diff) / MIN3);
6190
+ const m = Math.round(Math.abs(diff) / MIN2);
6944
6191
  const suffix = diff >= 0 ? "ago" : "from now";
6945
6192
  if (m < 1)
6946
6193
  return "just now";
@@ -7033,19 +6280,12 @@ function renderStatus(r) {
7033
6280
  var message2 = (err) => err instanceof Error ? err.message : String(err);
7034
6281
  async function statusAll(io, json) {
7035
6282
  const { credentials } = await loadCredentials(io);
6283
+ const signIn = requireSignIn(credentials);
7036
6284
  const linearApiKey = credentials.linearApiKey;
7037
6285
  if (!linearApiKey)
7038
6286
  throw missingKey(LINEAR_KEY);
7039
- const tursoKey = STORED_KEYS.find((k) => k.name === "tursoUrl");
7040
- if (!credentials.tursoUrl && tursoKey)
7041
- throw missingKey(tursoKey);
7042
- const db = await openTurso({ url: credentials.tursoUrl ?? "", token: credentials.tursoToken });
7043
- let records;
7044
- try {
7045
- records = await listProjects(db);
7046
- } finally {
7047
- db.close();
7048
- }
6287
+ const api = armadaApi({ url: credentials.armadaApi.url, ...io.fetch ? { fetch: io.fetch } : {} });
6288
+ const records = await api.projects(signIn);
7049
6289
  const projects = await Promise.all(records.map(async (p) => {
7050
6290
  const base = { slug: p.slug, name: p.name, repository: p.repository };
7051
6291
  let warning = null;
@@ -7126,7 +6366,8 @@ var COMMAND_HELP = {
7126
6366
  inbox: ` inbox [--wait [--timeout <seconds>]]
7127
6367
  Coordinator: open questions, plans, requests, hand-backs and silent workers,
7128
6368
  oldest first; records that the coordinator is at work. --wait returns
7129
- when a new item arrives or after --timeout (default 300 s). Needs Turso
6369
+ when a new item arrives or after --timeout (default 300 s). Needs a
6370
+ sign-in to Armada
7130
6371
  `,
7131
6372
  answer: ` answer <item|ticket> "<answer>"
7132
6373
  Coordinator: record an answer already delivered in the worker's
@@ -7140,8 +6381,8 @@ var COMMAND_HELP = {
7140
6381
  CLEAN, required checks green, no open review thread, base contained
7141
6382
  or test-merged), squash-merge it pinned to that SHA under the merge
7142
6383
  lock, close the ticket and list the workers to tell. Never deletes
7143
- the branch. --dry-run only runs the checklist. Refused when Turso is
7144
- configured but down; --no-lock then merges without the lock.
6384
+ the branch. --dry-run only runs the checklist. Signed in to Armada,
6385
+ refused while Armada is down; --no-lock then merges without the lock.
7145
6386
  `,
7146
6387
  brief: ` brief <ticket> [--profile <name> [--reason <why>]] [--prompt]
7147
6388
  A new worker's launch prompt, the Conductor profile (agent, model,
@@ -7186,20 +6427,21 @@ ${TICKET_HELP} -h, --help Show this help; \`armada <command> --help\` sh
7186
6427
  Keys (the environment first, then Armada when signed in, then the file):
7187
6428
  LINEAR_API_KEY Linear API key (required by status, init, brief, claim, report,
7188
6429
  release, ask and answer)
7189
- ARMADA_TURSO_URL Turso database URL (required by init, inbox and status --all;
7190
- optional elsewhere; a file: URL works locally)
7191
- ARMADA_TURSO_TOKEN Turso database token
7192
6430
  GITHUB_TOKEN GitHub token; falls back to GH_TOKEN, then \`gh auth token\`
7193
6431
  (merge also runs gh and git, with gh's own login)
7194
6432
  ARMADA_API_KEY Organization API key: signs a headless coordinator in to Armada
7195
6433
  ARMADA_API_URL The Armada to sign in to (default https://armada.thevibecompany.co)
7196
6434
 
6435
+ The fleet's live data (claims, reports, the inbox, the merge lock, the project
6436
+ registry) is reached through Armada with the sign-in: no database key is needed.
6437
+ init, inbox and status --all need a sign-in; elsewhere, signed out, live activity
6438
+ is not recorded and Linear stays the record.
6439
+
7197
6440
  Files:
7198
6441
  $XDG_CONFIG_HOME/armada (default ~/.config/armada)
7199
6442
  credentials KEY=value lines, mode 0600, written by \`armada auth login\` and
7200
- \`armada login\` (the sign-in: ARMADA_SESSION_TOKEN or ARMADA_API_KEY; the
7201
- Turso token Armada made for this terminal: ARMADA_TURSO_LEASE)
7202
- config.toml personal defaults: language, [turso] url, [dashboard] url, [api] url
6443
+ \`armada login\` (the sign-in: ARMADA_SESSION_TOKEN or ARMADA_API_KEY)
6444
+ config.toml personal defaults: language, [dashboard] url, [api] url
7203
6445
  `;
7204
6446
  function commandHelp(command) {
7205
6447
  const block = Object.hasOwn(COMMAND_HELP, command) ? COMMAND_HELP[command] : undefined;
@@ -7319,7 +6561,7 @@ async function status2(io, args) {
7319
6561
  const { linearApiKey, githubToken } = credentials;
7320
6562
  if (!linearApiKey)
7321
6563
  throw missingKey(LINEAR_KEY);
7322
- const events = statusEvents(config, credentials);
6564
+ const events = statusEvents(io, config, credentials);
7323
6565
  const report = await loadStatus(config, {
7324
6566
  linearApiKey,
7325
6567
  githubToken,