@the-vibe-company/armada 0.2.69 → 0.2.71

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.
package/dist/armada.js CHANGED
@@ -6646,15 +6646,21 @@ var init_zod = __esm(() => {
6646
6646
  });
6647
6647
 
6648
6648
  // ../plugin-api/dist/runtime.js
6649
- var RuntimeLaunchRefusal;
6649
+ var RuntimeLaunchRefusal, WorkerRuntimeGone, WorkerRuntimeAlive;
6650
6650
  var init_runtime = __esm(() => {
6651
6651
  RuntimeLaunchRefusal = class RuntimeLaunchRefusal extends Error {
6652
6652
  name = "RuntimeLaunchRefusal";
6653
6653
  };
6654
+ WorkerRuntimeGone = class WorkerRuntimeGone extends Error {
6655
+ name = "WorkerRuntimeGone";
6656
+ };
6657
+ WorkerRuntimeAlive = class WorkerRuntimeAlive extends Error {
6658
+ name = "WorkerRuntimeAlive";
6659
+ };
6654
6660
  });
6655
6661
 
6656
6662
  // ../plugin-api/dist/index.js
6657
- var PLUGIN_API_VERSION = "0.2.0", SEAMS, name, contributionSchema, kinds, manifestSchema, pluginSettingSchema, pluginEventSchema, pluginEventInputSchema;
6663
+ var PLUGIN_API_VERSION = "0.3.0", SEAMS, name, contributionSchema, kinds, manifestSchema, pluginSettingSchema, pluginEventSchema, pluginEventInputSchema;
6658
6664
  var init_dist = __esm(() => {
6659
6665
  init_runtime();
6660
6666
  init_zod();
@@ -9730,6 +9736,105 @@ var require_picomatch2 = __commonJS(function(exports, module) {
9730
9736
  module.exports = picomatch;
9731
9737
  });
9732
9738
 
9739
+ // ../plugins/claude/src/driver.ts
9740
+ var DRIVER;
9741
+ var init_driver = __esm(() => {
9742
+ DRIVER = String.raw`
9743
+ import { spawn } from "node:child_process";
9744
+ import { createInterface } from "node:readline";
9745
+ const options = JSON.parse(process.argv[1]);
9746
+ let child;
9747
+ let session;
9748
+ let finishing = false;
9749
+ let failed = false;
9750
+ let closed = false;
9751
+ let completed = 0;
9752
+ const waiting = [];
9753
+ const emit = (value) => console.log(JSON.stringify(value));
9754
+ const failure = () => {
9755
+ failed = true;
9756
+ emit({ type: "result", is_error: true, result: "Claude CLI turn could not be continued" });
9757
+ };
9758
+ function send(line) {
9759
+ if (failed) return;
9760
+ if (child || finishing) { waiting.push(line); return; }
9761
+ if (!child) start();
9762
+ if (!child || failed) return;
9763
+ child.stdin.write(line + "\n", (error) => { if (error) failure(); });
9764
+ }
9765
+ function start() {
9766
+ if (completed && !session) { failure(); return; }
9767
+ // A resumed print process starts fresh cumulative usage counters.
9768
+ if (completed) emit({ type: "armada_turn_start" });
9769
+ const cli = spawn(options.command, [...options.args, ...(session ? ["--resume", session] : [])], {
9770
+ stdio: ["pipe", "pipe", "pipe"], shell: false,
9771
+ });
9772
+ child = cli;
9773
+ let pending = "";
9774
+ let result = false;
9775
+ let retire;
9776
+ let kill;
9777
+ let retired = false;
9778
+ const event = (line) => {
9779
+ try {
9780
+ const value = JSON.parse(line);
9781
+ if (typeof value.session_id === "string" && value.session_id) session = value.session_id;
9782
+ if (value.type === "result") {
9783
+ result = true;
9784
+ completed++;
9785
+ finishing = true;
9786
+ cli.stdin.end();
9787
+ // Some print CLIs retain an idle process after their final result and EOF.
9788
+ // Retire only this completed subprocess; the supervisor's group pin stays alive.
9789
+ if (!retire) retire = setTimeout(() => {
9790
+ retired = true;
9791
+ cli.kill("SIGTERM");
9792
+ kill = setTimeout(() => cli.kill("SIGKILL"), 1000);
9793
+ }, 1000);
9794
+ }
9795
+ emit(value);
9796
+ if (value.type === "result") emit({ type: "armada_turn_state", completed });
9797
+ } catch { /* Non-JSON diagnostics cannot prove a completed turn. */ }
9798
+ };
9799
+ cli.stdout.setEncoding("utf8");
9800
+ cli.stdout.on("data", (chunk) => {
9801
+ const lines = (pending + chunk).split(/\r?\n/);
9802
+ pending = lines.pop() ?? "";
9803
+ if (pending.length > 1048576) { pending = ""; failure(); }
9804
+ for (const line of lines) event(line);
9805
+ });
9806
+ // Diagnostics stay available to the host's masked transcript/watchdog.
9807
+ cli.stderr.pipe(process.stderr);
9808
+ cli.stdin.on("error", () => { if (!result) failure(); });
9809
+ cli.once("error", failure);
9810
+ cli.once("close", (code) => {
9811
+ if (pending) event(pending);
9812
+ clearTimeout(retire);
9813
+ clearTimeout(kill);
9814
+ child = undefined;
9815
+ finishing = false;
9816
+ if ((!retired && code !== 0) || !result) failure();
9817
+ if (failed) { process.exitCode = 1; input.close(); return; }
9818
+ for (const line of waiting.splice(0)) send(line);
9819
+ if (closed && !child) process.exit(0);
9820
+ });
9821
+ }
9822
+ const input = createInterface({ input: process.stdin });
9823
+ input.on("line", (line) => {
9824
+ try {
9825
+ const value = JSON.parse(line);
9826
+ if (value.type !== "user" || value.message?.role !== "user") throw new Error();
9827
+ send(line);
9828
+ } catch { failure(); }
9829
+ });
9830
+ input.on("close", () => {
9831
+ closed = true;
9832
+ if (child) child.stdin.end();
9833
+ else process.exit(failed ? 1 : 0);
9834
+ });
9835
+ `;
9836
+ });
9837
+
9733
9838
  // ../plugin-api/dist/cli-auth.js
9734
9839
  import { execFile, spawn } from "node:child_process";
9735
9840
  import { StringDecoder } from "node:string_decoder";
@@ -10043,6 +10148,7 @@ var init_status = __esm(() => {
10043
10148
  // ../plugins/claude/src/index.ts
10044
10149
  var exports_src = {};
10045
10150
  __export(exports_src, {
10151
+ HEADLESS_VARIABLE: () => HEADLESS_VARIABLE,
10046
10152
  activate: () => activate,
10047
10153
  claudeRuntime: () => claudeRuntime
10048
10154
  });
@@ -10076,7 +10182,13 @@ function claudeRuntime(options = {}, node) {
10076
10182
  for (const line of lines) {
10077
10183
  try {
10078
10184
  const event = JSON.parse(line);
10079
- if (event.type === "conversation_reset") {
10185
+ if (event.type === "armada_turn_state" && Number.isSafeInteger(event.completed) && event.completed >= 0) {
10186
+ value.turns = Math.max(0, (value.accepted ?? value.deliveries.size) - event.completed);
10187
+ value.activity = value.turns ? "working" : "idle";
10188
+ } else if (event.type === "armada_turn_start") {
10189
+ value.usageOffset = value.usage === "unknown" ? "unknown" : { ...value.usage };
10190
+ value.usageResetPending = true;
10191
+ } else if (event.type === "conversation_reset") {
10080
10192
  const identity = `reset:${event.uuid ?? event.new_conversation_id}`;
10081
10193
  if (!value.usageResults.has(identity)) {
10082
10194
  value.usageResults.add(identity);
@@ -10192,19 +10304,29 @@ function claudeRuntime(options = {}, node) {
10192
10304
  },
10193
10305
  async launch(request) {
10194
10306
  const stream = !request.command;
10307
+ const args = stream ? [
10308
+ ...options.args ?? [],
10309
+ ...![...options.args ?? [], ...request.args].some((arg) => arg === "--permission-mode" || arg.startsWith("--permission-mode=") || arg === "--dangerously-skip-permissions") ? ["--permission-mode", options.permissionMode ?? "bypassPermissions"] : [],
10310
+ "--add-dir",
10311
+ request.workspace.path,
10312
+ "--print",
10313
+ "--verbose",
10314
+ "--input-format",
10315
+ "stream-json",
10316
+ "--output-format",
10317
+ "stream-json",
10318
+ ...request.args
10319
+ ] : request.args;
10195
10320
  const ref = await facilities().launch({
10196
10321
  ...request,
10197
- command: request.command || options.binary || options.command || "claude",
10322
+ env: { [HEADLESS_VARIABLE]: "1", ...request.env },
10323
+ command: stream ? "node" : request.command,
10198
10324
  args: stream ? [
10199
- ...options.args ?? [],
10200
- "--print",
10201
- "--verbose",
10202
- "--input-format",
10203
- "stream-json",
10204
- "--output-format",
10205
- "stream-json",
10206
- ...request.args
10207
- ] : request.args
10325
+ "--input-type=module",
10326
+ "--eval",
10327
+ DRIVER,
10328
+ JSON.stringify({ command: options.binary || options.command || "claude", args })
10329
+ ] : args
10208
10330
  });
10209
10331
  workers.set(ref.handle, {
10210
10332
  ref: { ...ref },
@@ -10276,15 +10398,16 @@ function activate(ctx) {
10276
10398
  const options = ctx.config.runtime?.claude ?? {};
10277
10399
  ctx.register.runtime("claude", claudeRuntime(options));
10278
10400
  }
10279
- var same2 = (a, b) => a.project === b.project && a.ticket === b.ticket && a.session === b.session && a.generation === b.generation && a.handle === b.handle;
10401
+ var HEADLESS_VARIABLE = "ARMADA_DESKTOP_HEADLESS", same2 = (a, b) => a.project === b.project && a.ticket === b.ticket && a.session === b.session && a.generation === b.generation && a.handle === b.handle;
10280
10402
  var init_src = __esm(() => {
10403
+ init_driver();
10281
10404
  init_status();
10282
10405
  });
10283
10406
 
10284
10407
  // ../plugins/codex/src/driver.ts
10285
- var DRIVER;
10286
- var init_driver = __esm(() => {
10287
- DRIVER = String.raw`
10408
+ var DRIVER2;
10409
+ var init_driver2 = __esm(() => {
10410
+ DRIVER2 = String.raw`
10288
10411
  import { execFile, spawn } from "node:child_process";
10289
10412
  import { createInterface } from "node:readline";
10290
10413
  const options = JSON.parse(process.argv[1]);
@@ -10320,8 +10443,31 @@ input.on("line", (line) => {
10320
10443
  input.on("close", () => { chain.finally(() => process.exit(failed ? 1 : 0)); });
10321
10444
  async function turn(message) {
10322
10445
  if (failed) throw new Error("CLI session is no longer usable");
10323
- const args = ["exec", ...(session ? ["resume", session] : []), ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", "model_reasoning_effort=" + JSON.stringify(options.effort)] : []), "-c", "check_for_update_on_startup=false", ...options.extraArgs, "--json", "-"];
10324
- const child = spawn(options.command, args, { stdio: ["pipe", "pipe", "ignore"], shell: false });
10446
+ // Approval/sandbox switches are top-level flags; resume does not accept them after its subcommand.
10447
+ const globalArgs = [];
10448
+ const extraArgs = [];
10449
+ for (let i = 0; i < options.extraArgs.length; i++) {
10450
+ const arg = options.extraArgs[i];
10451
+ if (arg === "--approve-for-me") globalArgs.push(arg);
10452
+ else if (/^(?:-a|-s|--ask-for-approval|--sandbox)$/.test(arg)) {
10453
+ globalArgs.push(arg, options.extraArgs[++i]);
10454
+ } else if (/^(?:--ask-for-approval=|--sandbox=|-[as].+)/.test(arg)) globalArgs.push(arg);
10455
+ else extraArgs.push(arg);
10456
+ }
10457
+ const args = [...globalArgs, "exec", ...(session ? ["resume", session] : []), ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["-c", "model_reasoning_effort=" + JSON.stringify(options.effort)] : []), "-c", "check_for_update_on_startup=false", ...extraArgs, "--json", "-"];
10458
+ const child = spawn(options.command, args, { stdio: ["pipe", "pipe", "pipe"], shell: false });
10459
+ // Retain only a fixed marker; provider errors/stderr may contain credentials.
10460
+ let permissionDenied = false;
10461
+ let diagnosticTail = "";
10462
+ const permissionEvidence = (text) => {
10463
+ diagnosticTail = (diagnosticTail + text).slice(-4096);
10464
+ if (!permissionDenied && /requested permissions|(?:have|has)n['’]t granted|permission gate refused|permission (?:prompt|request)|Permission(?:Denied|Rejected|Required)(?:Error)?|approval (?:required|denied|request)/i.test(diagnosticTail)) {
10465
+ permissionDenied = true;
10466
+ emit("failure", { permission: true });
10467
+ }
10468
+ };
10469
+ child.stderr.setEncoding("utf8");
10470
+ child.stderr.on("data", permissionEvidence);
10325
10471
  let pending = "";
10326
10472
  let reply = "";
10327
10473
  let completed = false;
@@ -10332,7 +10478,11 @@ async function turn(message) {
10332
10478
  if (value.type === "thread.started" && typeof value.thread_id === "string") session = value.thread_id;
10333
10479
  if (value.type === "item.completed" && value.item?.type === "agent_message") reply = typeof value.item.text === "string" ? value.item.text.slice(-8192) : "";
10334
10480
  if (value.type === "turn.completed") completed = true;
10335
- if (value.type === "turn.failed" || value.type === "error") turnFailed = true;
10481
+ if (value.type === "turn.failed" || value.type === "error") {
10482
+ turnFailed = true;
10483
+ if (typeof value.error?.message === "string") permissionEvidence(value.error.message);
10484
+ if (typeof value.message === "string") permissionEvidence(value.message);
10485
+ }
10336
10486
  } catch { /* CLI progress diagnostics are not JSON events. */ }
10337
10487
  };
10338
10488
  child.stdout.setEncoding("utf8");
@@ -10351,7 +10501,7 @@ async function turn(message) {
10351
10501
  if (pending) event(pending);
10352
10502
  if (code !== 0 || turnFailed || !completed || !session) {
10353
10503
  failed = true;
10354
- emit("failure");
10504
+ emit("failure", permissionDenied ? { permission: true } : {});
10355
10505
  } else emit("reply", { text: reply });
10356
10506
  emit("done", { completed: ++completedTurns });
10357
10507
  }
@@ -10501,13 +10651,24 @@ function codexRuntime(options = {}, node) {
10501
10651
  } else
10502
10652
  extraArgs.push(arg);
10503
10653
  }
10654
+ const mode = options.permissionMode ?? "workspace-write";
10655
+ const has = (pattern) => extraArgs.some((arg) => pattern.test(arg));
10656
+ if (native && mode !== "default" && !has(/^--(?:full-auto|approve-for-me|dangerously-bypass-approvals-and-sandbox)(?:=|$)/)) {
10657
+ if (!has(/^(?:-a(?:$|=|never|on-request|untrusted|on-failure)|--ask-for-approval(?:=|$)|(?:--config=|-c)?approval_policy\s*=)/))
10658
+ extraArgs.push("-c", 'approval_policy="never"');
10659
+ if (!has(/^(?:-s(?:$|=|read-only|workspace-write|danger-full-access)|--sandbox(?:=|$)|(?:--config=|-c)?sandbox_mode\s*=)/)) {
10660
+ extraArgs.push("-c", `sandbox_mode=${JSON.stringify(mode)}`);
10661
+ if (mode === "workspace-write" && !has(/^(?:--config=|-c)?sandbox_workspace_write\.network_access\s*=/))
10662
+ extraArgs.push("-c", "sandbox_workspace_write.network_access=true");
10663
+ }
10664
+ }
10504
10665
  const ref = await facilities().launch(native ? {
10505
10666
  ...request,
10506
10667
  command: "node",
10507
10668
  args: [
10508
10669
  "--input-type=module",
10509
10670
  "-e",
10510
- DRIVER,
10671
+ DRIVER2,
10511
10672
  JSON.stringify({ command: options.binary ?? options.command ?? "codex", model, effort, extraArgs })
10512
10673
  ]
10513
10674
  } : request);
@@ -10606,7 +10767,7 @@ function activate2(ctx) {
10606
10767
  }
10607
10768
  var same3 = (a, b) => a.project === b.project && a.ticket === b.ticket && a.session === b.session && a.generation === b.generation && a.handle === b.handle;
10608
10769
  var init_src2 = __esm(() => {
10609
- init_driver();
10770
+ init_driver2();
10610
10771
  init_status2();
10611
10772
  });
10612
10773
 
@@ -11403,22 +11564,35 @@ class GithubForge {
11403
11564
  cursors.add(after);
11404
11565
  }
11405
11566
  context?.onDetails?.();
11406
- await Promise.all(previousOpen.filter((number) => !pulls.has(number) && !state.prs[number]?.abandoned).map(async (number) => {
11567
+ const held = await options.openPullRequests?.() ?? context?.openPullRequests;
11568
+ if (context)
11569
+ context.openPullRequests = held;
11570
+ const missing = [
11571
+ ...new Set(held ? held.filter((pr) => pr.state === "open").map((pr) => pr.number) : previousOpen)
11572
+ ].filter((number) => !pulls.has(number));
11573
+ for (const number of missing) {
11574
+ if (state.pausedUntil && Date.parse(state.pausedUntil) > Date.parse(at)) {
11575
+ if (context)
11576
+ context.reconciliationError = "GitHub reading failed";
11577
+ break;
11578
+ }
11407
11579
  try {
11408
11580
  const pr = await this.#isolated(number, signal, async (child) => {
11409
- const { pullRequest } = await query(ONE, { number }, child);
11410
- if (!pullRequest || pullRequest.number !== number)
11411
- throw new GithubReadError("GitHub lost a previously open pull request");
11412
- return normalize(pullRequest, options.repository, tickets, token);
11581
+ const response = await http.request(`${http.rest}/repos/${options.repository}/pulls/${number}`, child);
11582
+ const raw = await response.json();
11583
+ child.throwIfAborted();
11584
+ return terminalPull(raw, number, options.repository, tickets, token, held?.find((pr) => pr.number === number));
11413
11585
  });
11414
- pulls.set(number, pr);
11415
- if (pr.state !== "open" || !active.has(pr.ticket))
11416
- recovered(number);
11586
+ if (pr)
11587
+ pulls.set(number, pr);
11588
+ recovered(number);
11417
11589
  } catch (error) {
11418
11590
  signal.throwIfAborted();
11419
11591
  failed(number, error);
11592
+ if (context)
11593
+ context.reconciliationError = error instanceof GithubReadError ? error.message : "GitHub reading failed";
11420
11594
  }
11421
- }));
11595
+ }
11422
11596
  await Promise.all([...pulls.values()].filter((pr) => pr.state === "open" && active.has(pr.ticket)).map(async (pr) => {
11423
11597
  const prior = state.prs[pr.number] ?? emptyPr();
11424
11598
  if (prior.abandoned || state.pausedUntil && Date.parse(state.pausedUntil) > Date.parse(at))
@@ -11440,6 +11614,43 @@ class GithubForge {
11440
11614
  return [...pulls.values()].sort((a, b) => a.number - b.number);
11441
11615
  }
11442
11616
  }
11617
+ function terminalPull(raw, number, repository, tickets, token, held) {
11618
+ const fail = () => {
11619
+ throw new GithubReadError("GitHub returned an incomplete reading");
11620
+ };
11621
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
11622
+ return fail();
11623
+ const pr = raw;
11624
+ if (pr.number !== number || !["open", "closed"].includes(String(pr.state)))
11625
+ return fail();
11626
+ if (pr.state === "open")
11627
+ return;
11628
+ const head = pr.head;
11629
+ if (typeof pr.merged !== "boolean" || typeof pr.title !== "string" || typeof pr.html_url !== "string" || typeof pr.draft !== "boolean" || typeof head?.sha !== "string" || !head.sha || typeof head.ref !== "string")
11630
+ return fail();
11631
+ if (pr.merged && (typeof pr.merge_commit_sha !== "string" || !/^[0-9a-f]{40}$/i.test(pr.merge_commit_sha) || typeof pr.merged_at !== "string" || !exports_iso.datetime().safeParse(pr.merged_at).success))
11632
+ return fail();
11633
+ const clean = (value) => value.replaceAll(token, "[redacted]");
11634
+ const ticket = held?.ticket || [...head.ref.matchAll(/(?:^|[/_-])([a-z][a-z0-9]*-\d+)(?=[-_/]|$)/gi)].map((match) => (match[1] ?? "").toUpperCase()).find((id) => tickets.has(id)) || "";
11635
+ return {
11636
+ review: "none",
11637
+ checks: [],
11638
+ checksComplete: false,
11639
+ ci: held?.ci ?? "none",
11640
+ ...held,
11641
+ number,
11642
+ repository,
11643
+ ticket: clean(ticket),
11644
+ title: clean(pr.title),
11645
+ url: clean(pr.html_url),
11646
+ head: clean(head.sha),
11647
+ headRef: clean(head.ref),
11648
+ draft: pr.draft,
11649
+ state: pr.merged ? "merged" : "closed",
11650
+ conflicting: false,
11651
+ ...pr.merged ? { mergeCommit: clean(String(pr.merge_commit_sha).toLowerCase()), mergedAt: clean(String(pr.merged_at)) } : {}
11652
+ };
11653
+ }
11443
11654
  function transitions(before, pr) {
11444
11655
  const kinds = [];
11445
11656
  if (pr.state === "open" && pr.conflicting && (!before?.conflicting || before.head !== pr.head))
@@ -11554,6 +11765,11 @@ class GithubReader {
11554
11765
  previous.set(pr.number, pr);
11555
11766
  }
11556
11767
  } else if (event.kind.startsWith("pull-request.")) {
11768
+ if (event.kind !== "pull-request.commented") {
11769
+ const pr = event.payload;
11770
+ if (pr.repository === options.repository)
11771
+ previous.set(pr.number, pr);
11772
+ }
11557
11773
  const key = fingerprint(event);
11558
11774
  for (const [id, pending] of this.#pending) {
11559
11775
  if (fingerprint(pending) !== key)
@@ -11574,7 +11790,13 @@ class GithubReader {
11574
11790
  return { ok: true, changed: 0 };
11575
11791
  draft = structuredClone(this.#state);
11576
11792
  delete draft.pausedUntil;
11577
- const context = { checkpoint: draft, at, events: [], onDetails: cancelDeadline };
11793
+ const context = {
11794
+ checkpoint: draft,
11795
+ at,
11796
+ events: [],
11797
+ onDetails: cancelDeadline,
11798
+ openPullRequests: [...previous.values()]
11799
+ };
11578
11800
  this.#providerPending = true;
11579
11801
  const reading = await Promise.race([
11580
11802
  this.#forge.read([...previous.values()].filter((pr) => pr.state === "open").map((pr) => pr.number), controller.signal, context).finally(() => {
@@ -11585,11 +11807,16 @@ class GithubReader {
11585
11807
  controller.signal.throwIfAborted();
11586
11808
  let changed = 0;
11587
11809
  for (const pr of reading) {
11588
- const before = previous.get(pr.number);
11810
+ const before = context.openPullRequests?.find((held) => held.number === pr.number) ?? previous.get(pr.number);
11589
11811
  if (pr.unresolvedThreads === undefined && before?.unresolvedThreads !== undefined)
11590
11812
  pr.unresolvedThreads = before.unresolvedThreads;
11591
11813
  if (JSON.stringify(before) === JSON.stringify(pr))
11592
11814
  continue;
11815
+ if (pr.state !== "open") {
11816
+ await append(transitionEvent(pr.state === "merged" ? "pull-request.merged" : "pull-request.closed", pr, options.project, options.actor, at));
11817
+ changed++;
11818
+ continue;
11819
+ }
11593
11820
  await append({
11594
11821
  project: options.project,
11595
11822
  actor: options.actor,
@@ -11637,7 +11864,7 @@ class GithubReader {
11637
11864
  });
11638
11865
  this.#state = draft;
11639
11866
  }
11640
- return { ok: true, changed };
11867
+ return context.reconciliationError ? { ok: false, error: context.reconciliationError } : { ok: true, changed };
11641
11868
  } catch (error) {
11642
11869
  if (draft && error instanceof GithubReadError && !controller.signal.aborted) {
11643
11870
  const state = {
@@ -11690,8 +11917,9 @@ class GithubReader {
11690
11917
  this.#controller?.abort();
11691
11918
  }
11692
11919
  }
11693
- var WORKFLOW = `status conclusion commit { oid } workflowRun { databaseId runNumber runAttempt workflow { id } }`, FIELDS2, OPEN, ONE;
11920
+ var WORKFLOW = `status conclusion commit { oid } workflowRun { databaseId runNumber runAttempt workflow { id } }`, FIELDS2, OPEN;
11694
11921
  var init_github = __esm(() => {
11922
+ init_zod();
11695
11923
  init_checkpoint();
11696
11924
  init_http();
11697
11925
  init_keychain();
@@ -11715,10 +11943,6 @@ query Pulls($owner: String!, $name: String!, $after: String) {
11715
11943
  pageInfo { hasNextPage endCursor } nodes { ...P }
11716
11944
  }
11717
11945
  }
11718
- }`;
11719
- ONE = `${FIELDS2}
11720
- query Pull($owner: String!, $name: String!, $number: Int!) {
11721
- repository(owner: $owner, name: $name) { pullRequest(number: $number) { ...P } }
11722
11946
  }`;
11723
11947
  });
11724
11948
 
@@ -11949,9 +12173,20 @@ async function inspectGithub(options) {
11949
12173
  const review = await readReviewThreads(options, threads);
11950
12174
  const behindBy = await readBehindBy(options, base, head);
11951
12175
  const required = await readRequiredChecks(options, raw.baseRef.name);
12176
+ const commit = object5(raw.commits.nodes.at(-1)?.commit);
12177
+ let headParents;
12178
+ if (commit.parents !== undefined) {
12179
+ const parents = object5(commit.parents);
12180
+ const nodes = array2(parents.nodes).map((node) => cleanSha(object5(node).oid));
12181
+ if (!Number.isSafeInteger(parents.totalCount) || parents.totalCount < nodes.length)
12182
+ throw new Error("invalid commit parents");
12183
+ if (parents.totalCount === nodes.length)
12184
+ headParents = nodes;
12185
+ }
11952
12186
  const inspection = {
11953
12187
  number: normalized.number,
11954
12188
  head,
12189
+ ...headParents ? { headParents } : {},
11955
12190
  base,
11956
12191
  baseRef: raw.baseRef.name,
11957
12192
  state: normalized.state,
@@ -11979,6 +12214,7 @@ var SHA, REST_DEFAULT = "https://api.github.com", GRAPHQL_DEFAULT, INSPECT_QUERY
11979
12214
  baseRef { name target { oid } }
11980
12215
  mergeCommit { oid }
11981
12216
  commits(last: 1) { nodes { commit { oid
12217
+ parents(first: 3) { totalCount nodes { oid } }
11982
12218
  checkSuites(first: 50) { nodes { status conclusion commit { oid } workflowRun { databaseId runNumber runAttempt workflow { id } } } pageInfo { hasNextPage endCursor } }
11983
12219
  statusCheckRollup { state contexts(first: 50) { pageInfo { hasNextPage endCursor } nodes {
11984
12220
  __typename
@@ -12100,6 +12336,10 @@ function activate4(ctx) {
12100
12336
  actor: "owner",
12101
12337
  endpoint: config.endpoint,
12102
12338
  token: (signal) => token(project, signal),
12339
+ openPullRequests: async () => {
12340
+ const tables = await ctx.events.fold(project);
12341
+ return (tables?.projects?.[project]?.pullRequests ?? []).filter((pr) => !("repository" in pr) || pr.repository === settings.repository);
12342
+ },
12103
12343
  activeTickets: async () => {
12104
12344
  const tables = await ctx.events.fold(project);
12105
12345
  return new Set((tables?.projects?.[project]?.sessions ?? []).filter((session) => !["released", "merged"].includes(session.phase)).map((session) => session.ticket));
@@ -12147,6 +12387,31 @@ function activate4(ctx) {
12147
12387
  throw new Error("GitHub inspection failed");
12148
12388
  }
12149
12389
  },
12390
+ async updateBranch({ project, number, expectedHead, signal, beforeWrite }) {
12391
+ try {
12392
+ const repository = config.projects?.[project]?.repository;
12393
+ if (!repository || !Number.isSafeInteger(number) || number <= 0 || !/^[a-f0-9]{40}$/i.test(expectedHead))
12394
+ throw new Error;
12395
+ const key = await token(project, signal);
12396
+ signal?.throwIfAborted();
12397
+ beforeWrite?.();
12398
+ const response = await fetch(`${restEndpoint(config.endpoint)}/repos/${repository}/pulls/${number}/update-branch`, {
12399
+ method: "PUT",
12400
+ redirect: "error",
12401
+ signal,
12402
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
12403
+ body: JSON.stringify({ expected_head_sha: expectedHead })
12404
+ });
12405
+ signal?.throwIfAborted();
12406
+ if (response.status === 202)
12407
+ return { updated: true };
12408
+ if ([401, 403, 404, 409, 422].includes(response.status))
12409
+ return { updated: false };
12410
+ throw new Error;
12411
+ } catch {
12412
+ throw new Error("GitHub branch update failed");
12413
+ }
12414
+ },
12150
12415
  async merge({ project, number, head, signal, beforeWrite }) {
12151
12416
  try {
12152
12417
  const repository = config.projects?.[project]?.repository;
@@ -12401,6 +12666,40 @@ var init_chat = __esm(() => {
12401
12666
  var DELIVERIES_MINOR = 17;
12402
12667
  var init_deliveries = () => {};
12403
12668
 
12669
+ // ../protocol/dist/import.js
12670
+ var IMPORT_MINOR = 27, trackerImportSchema, importPayloadSchemas, trackerImportRequestSchema, trackerImportResultSchema;
12671
+ var init_import = __esm(() => {
12672
+ init_zod();
12673
+ init_envelope();
12674
+ trackerImportSchema = object({
12675
+ id: identifier2,
12676
+ programRoot: identifier2,
12677
+ state: _enum(["running", "completed", "paused", "failed", "interrupted"]),
12678
+ imported: counter,
12679
+ skipped: counter,
12680
+ comments: counter,
12681
+ total: counter,
12682
+ pausedUntil: exports_iso.datetime().optional(),
12683
+ error: string2().optional()
12684
+ });
12685
+ importPayloadSchemas = {
12686
+ "tracker.import-started": trackerImportSchema,
12687
+ "tracker.import-progress": trackerImportSchema.extend({ source: identifier2.optional() }),
12688
+ "tracker.import-ended": trackerImportSchema
12689
+ };
12690
+ trackerImportRequestSchema = /* @__PURE__ */ requestSchema("tracker.import", {
12691
+ project: identifier2,
12692
+ programRoot: identifier2
12693
+ });
12694
+ trackerImportResultSchema = object({
12695
+ type: literal("tracker.import.result"),
12696
+ version: versionSchema,
12697
+ id: identifier2,
12698
+ project: identifier2,
12699
+ importId: identifier2
12700
+ });
12701
+ });
12702
+
12404
12703
  // ../protocol/dist/readers.js
12405
12704
  var READER_MINOR = 14, roomPresenceRequestSchema, readerUsageSchema;
12406
12705
  var init_readers = __esm(() => {
@@ -12419,7 +12718,7 @@ var init_readers = __esm(() => {
12419
12718
  });
12420
12719
 
12421
12720
  // ../protocol/dist/models.js
12422
- var modelKindSchema, modelConfigSchema, pluginCoordinatorModelSchema, piCoordinatorModelSchema, coordinatorModelSchema, modelKindEntrySchema, counter3, request4, modelProviderEntrySchema, modelsProvidersSchema, modelsLoginSchema, modelsLogoutSchema, modelsSelectSchema, modelsCatalogSchema, modelsRequestSchemas;
12721
+ var modelKindSchema, modelConfigSchema, pluginCoordinatorModelSchema, piCoordinatorModelSchema, coordinatorModelSchema, modelKindEntrySchema, MODEL_SCOPE_MINOR = 24, counter3, request4, modelProviderEntrySchema, modelsProvidersSchema, modelsLoginSchema, modelsLogoutSchema, modelsSelectSchema, modelsCatalogSchema, modelsRequestSchemas;
12423
12722
  var init_models = __esm(() => {
12424
12723
  init_zod();
12425
12724
  modelKindSchema = string2().regex(/^[a-z][a-z0-9._-]*$/);
@@ -12461,7 +12760,8 @@ var init_models = __esm(() => {
12461
12760
  modelsSelectSchema = object({
12462
12761
  ...request4,
12463
12762
  type: literal("models.select"),
12464
- ...piCoordinatorModelSchema.shape
12763
+ ...piCoordinatorModelSchema.shape,
12764
+ project: string2().min(1).optional()
12465
12765
  });
12466
12766
  modelsCatalogSchema = object({
12467
12767
  ...request4,
@@ -12540,7 +12840,7 @@ var init_rules = __esm(() => {
12540
12840
  });
12541
12841
 
12542
12842
  // ../protocol/dist/fleet.js
12543
- var GITHUB_READER_MINOR = 18, text, integer2, phaseSchema, activePhaseSchema, shippingStageSchema, ciSchema, sessionRefSchema, workerLaunchCheckpointSchema, sessionStateSchema, flowStepSchema;
12843
+ var GITHUB_READER_MINOR = 18, INTERNAL_TRACKER_MINOR = 22, FOLLOW_UP_MINOR = 25, text, integer2, phaseSchema, activePhaseSchema, shippingStageSchema, internalTicketFieldsSchema, ticketCreatedSchema, ticketPatchSchema, ciSchema, sessionRefSchema, workerLaunchCheckpointSchema, followUpSchema, sessionStateSchema, flowStepSchema;
12544
12844
  var init_fleet = __esm(() => {
12545
12845
  init_zod();
12546
12846
  text = string2();
@@ -12558,6 +12858,18 @@ var init_fleet = __esm(() => {
12558
12858
  ]);
12559
12859
  activePhaseSchema = phaseSchema.exclude(["released", "merged"]);
12560
12860
  shippingStageSchema = _enum(["review", "ci"]);
12861
+ internalTicketFieldsSchema = strictObject({
12862
+ title: string2().trim().min(1),
12863
+ description: text,
12864
+ labels: array(string2().min(1)),
12865
+ state: _enum(["backlog", "unstarted", "started", "completed", "canceled"]),
12866
+ parent: string2().min(1).nullable(),
12867
+ blockers: array(string2().min(1)),
12868
+ url: text.optional(),
12869
+ source: text.optional()
12870
+ });
12871
+ ticketCreatedSchema = internalTicketFieldsSchema.extend({ id: string2().min(1) });
12872
+ ticketPatchSchema = internalTicketFieldsSchema.partial();
12561
12873
  ciSchema = _enum(["none", "pending", "success", "failure"]);
12562
12874
  sessionRefSchema = object({
12563
12875
  ticket: text,
@@ -12573,6 +12885,27 @@ var init_fleet = __esm(() => {
12573
12885
  branch: text.optional(),
12574
12886
  step: _enum(["preparing", "starting", "launched"])
12575
12887
  });
12888
+ followUpSchema = object({
12889
+ cause: text,
12890
+ tool: text.optional(),
12891
+ candidate: text.optional(),
12892
+ args: record(string2(), json()).optional(),
12893
+ code: text,
12894
+ reason: text,
12895
+ facts: text,
12896
+ next: text,
12897
+ fix: text.optional(),
12898
+ toldOwnerAt: text.optional(),
12899
+ attempts: number2().int().positive(),
12900
+ lastAt: text,
12901
+ pr: integer2.optional(),
12902
+ session: text.optional(),
12903
+ generation: integer2.optional(),
12904
+ plugin: text.optional(),
12905
+ capability: text.optional(),
12906
+ readyToMerge: boolean2().optional(),
12907
+ head: text.optional()
12908
+ });
12576
12909
  sessionStateSchema = _enum([
12577
12910
  "blocked",
12578
12911
  "waiting-for-owner",
@@ -12672,14 +13005,20 @@ function addProjectRequest() {
12672
13005
  projectId: addProjectInputSchema.shape.id
12673
13006
  });
12674
13007
  }
12675
- var PROJECTS_MINOR = 12, text2, identifier3, request6, projectSchema, addProjectInputSchema, inspectProjectRequestSchema, addProjectRequestSchema, removeProjectRequestSchema, projectInspectionSchema, projectsInspectionSchema, projectRequestSchemas;
13008
+ var PROJECTS_MINOR = 12, PROJECT_TRACKER_MINOR = 23, text2, identifier3, request6, projectSchema, addProjectInputSchema, inspectProjectRequestSchema, addProjectRequestSchema, removeProjectRequestSchema, projectInspectionSchema, projectsInspectionSchema, projectRequestSchemas;
12676
13009
  var init_projects = __esm(() => {
12677
13010
  init_zod();
12678
13011
  init_envelope();
12679
13012
  text2 = string2().trim().min(1).max(4096);
12680
13013
  identifier3 = string2().trim().min(1).max(200);
12681
13014
  request6 = { version: versionSchema, id: identifier3 };
12682
- projectSchema = object({ id: identifier3, name: text2, repository: text2, root: text2.optional() });
13015
+ projectSchema = object({
13016
+ id: identifier3,
13017
+ name: text2,
13018
+ repository: text2,
13019
+ root: text2.optional(),
13020
+ tracker: identifier3.optional()
13021
+ });
12683
13022
  addProjectInputSchema = /* @__PURE__ */ addProjectInput();
12684
13023
  inspectProjectRequestSchema = /* @__PURE__ */ requestSchema("projects.inspect", { path: text2 });
12685
13024
  addProjectRequestSchema = /* @__PURE__ */ addProjectRequest();
@@ -12804,13 +13143,69 @@ var init_session = __esm(() => {
12804
13143
  });
12805
13144
  });
12806
13145
 
13146
+ // ../protocol/dist/tickets.js
13147
+ function createRequest() {
13148
+ return object({
13149
+ ...request8,
13150
+ ...target2,
13151
+ type: literal("ticket.create"),
13152
+ title: fields.title,
13153
+ description: fields.description,
13154
+ labels: labels2.optional(),
13155
+ parent: fields.parent.optional(),
13156
+ blockers: fields.blockers.optional(),
13157
+ ready: boolean2().optional()
13158
+ });
13159
+ }
13160
+ function updateRequest() {
13161
+ return object({
13162
+ ...request8,
13163
+ ...target2,
13164
+ type: literal("ticket.update"),
13165
+ ticket: id6,
13166
+ title: fields.title.optional(),
13167
+ description: fields.description.optional(),
13168
+ labels: labels2.optional(),
13169
+ addLabels: labels2.optional(),
13170
+ removeLabels: labels2.optional(),
13171
+ state: _enum(["backlog", "unstarted", "started", "completed", "canceled"]).optional(),
13172
+ parent: fields.parent.optional(),
13173
+ blockers: fields.blockers.optional()
13174
+ });
13175
+ }
13176
+ var TICKETS_MINOR = 26, request8, id6, labels2, fields, target2, ticketCreateRequestSchema, ticketUpdateRequestSchema, ticketResultSchema, ticketRequestSchemas;
13177
+ var init_tickets = __esm(() => {
13178
+ init_zod();
13179
+ init_envelope();
13180
+ request8 = { version: versionSchema, id: identifier2 };
13181
+ id6 = string2().min(1).max(200).regex(/\S/);
13182
+ labels2 = array(id6).max(100);
13183
+ fields = {
13184
+ title: string2().min(1).max(4000).regex(/\S/),
13185
+ description: string2().max(1e5),
13186
+ labels: labels2,
13187
+ parent: id6.nullable(),
13188
+ blockers: array(id6).max(100)
13189
+ };
13190
+ target2 = { project: identifier2, requestId: identifier2.max(200) };
13191
+ ticketCreateRequestSchema = /* @__PURE__ */ createRequest();
13192
+ ticketUpdateRequestSchema = /* @__PURE__ */ updateRequest();
13193
+ ticketResultSchema = object({
13194
+ ...request8,
13195
+ ...target2,
13196
+ type: literal("ticket.result"),
13197
+ ticket: id6
13198
+ });
13199
+ ticketRequestSchemas = [ticketCreateRequestSchema, ticketUpdateRequestSchema];
13200
+ });
13201
+
12807
13202
  // ../protocol/dist/usage.js
12808
13203
  var init_usage = () => {};
12809
13204
 
12810
13205
  // ../protocol/dist/index.js
12811
13206
  function credentialsSetSchema() {
12812
13207
  return object({
12813
- ...request8,
13208
+ ...request9,
12814
13209
  type: literal("credentials.set"),
12815
13210
  provider: modelProviderSchema,
12816
13211
  target: _enum(["pi", "plugin"]).optional(),
@@ -12840,7 +13235,7 @@ function checkHistory(value, ctx) {
12840
13235
  previous = event.seq;
12841
13236
  }
12842
13237
  }
12843
- var REPLAY_MINOR = 21, WORKER_RECOVERY_MINOR = 15, PROTOCOL_VERSION, eventSchema, request8, listProjectsRequestSchema, subscribeRequestSchema, readSessionRequestSchema, historyRequestSchema, modelProviderSchema, credentialsStatusRequestSchema, credentialsSetRequestSchema, credentialsResultSchema, fleetShutdownRequestSchema, fleetShutdownResultSchema, clientMessageSchema, projectsResultSchema, snapshotSchema, subscribedSchema, history, sessionResultSchema, historyResultSchema, eventBatchSchema, errorSchema, serverMessageSchema, envelopeSchema, correlationSchema;
13238
+ var REPLAY_MINOR = 21, WORKER_RECOVERY_MINOR = 15, PROTOCOL_VERSION, eventSchema, request9, listProjectsRequestSchema, subscribeRequestSchema, readSessionRequestSchema, historyRequestSchema, modelProviderSchema, credentialsStatusRequestSchema, credentialsSetRequestSchema, credentialsResultSchema, fleetShutdownRequestSchema, fleetShutdownResultSchema, clientMessageSchema, projectsResultSchema, snapshotSchema, subscribedSchema, history, sessionResultSchema, historyResultSchema, eventBatchSchema, errorSchema, serverMessageSchema, envelopeSchema, correlationSchema;
12844
13239
  var init_dist2 = __esm(() => {
12845
13240
  init_dist();
12846
13241
  init_zod();
@@ -12850,6 +13245,7 @@ var init_dist2 = __esm(() => {
12850
13245
  init_deliveries();
12851
13246
  init_envelope();
12852
13247
  init_fleet();
13248
+ init_import();
12853
13249
  init_models();
12854
13250
  init_plugins();
12855
13251
  init_projects();
@@ -12857,10 +13253,12 @@ var init_dist2 = __esm(() => {
12857
13253
  init_readers();
12858
13254
  init_rules();
12859
13255
  init_session();
13256
+ init_tickets();
12860
13257
  init_account();
12861
13258
  init_auth();
12862
13259
  init_chat();
12863
13260
  init_fleet();
13261
+ init_import();
12864
13262
  init_models();
12865
13263
  init_plugins();
12866
13264
  init_projects();
@@ -12868,13 +13266,14 @@ var init_dist2 = __esm(() => {
12868
13266
  init_readers();
12869
13267
  init_rules();
12870
13268
  init_session();
13269
+ init_tickets();
12871
13270
  init_usage();
12872
13271
  PROTOCOL_VERSION = {
12873
13272
  major: 1,
12874
- minor: Math.max(READER_MINOR, PROJECTS_MINOR, BRIEF_INSTRUCTIONS_MINOR, WORKER_RECOVERY_MINOR, GITHUB_READER_MINOR, DELIVERIES_MINOR, WATCHDOG_MINOR, USAGE_MINOR, REPLAY_MINOR)
13273
+ minor: Math.max(READER_MINOR, PROJECTS_MINOR, BRIEF_INSTRUCTIONS_MINOR, WORKER_RECOVERY_MINOR, GITHUB_READER_MINOR, DELIVERIES_MINOR, WATCHDOG_MINOR, USAGE_MINOR, REPLAY_MINOR, INTERNAL_TRACKER_MINOR, FOLLOW_UP_MINOR, PROJECT_TRACKER_MINOR, MODEL_SCOPE_MINOR, TICKETS_MINOR, IMPORT_MINOR)
12875
13274
  };
12876
13275
  eventSchema = pluginEventSchema;
12877
- request8 = { version: versionSchema, id: identifier2 };
13276
+ request9 = { version: versionSchema, id: identifier2 };
12878
13277
  listProjectsRequestSchema = /* @__PURE__ */ requestSchema("projects.list", {});
12879
13278
  subscribeRequestSchema = /* @__PURE__ */ requestSchema("project.subscribe", {
12880
13279
  project: identifier2,
@@ -12894,7 +13293,7 @@ var init_dist2 = __esm(() => {
12894
13293
  credentialsStatusRequestSchema = /* @__PURE__ */ requestSchema("credentials.status", {});
12895
13294
  credentialsSetRequestSchema = /* @__PURE__ */ credentialsSetSchema();
12896
13295
  credentialsResultSchema = object({
12897
- ...request8,
13296
+ ...request9,
12898
13297
  type: literal("credentials.result"),
12899
13298
  provider: modelProviderSchema.nullable(),
12900
13299
  config: modelConfigSchema.optional(),
@@ -12904,7 +13303,7 @@ var init_dist2 = __esm(() => {
12904
13303
  });
12905
13304
  fleetShutdownRequestSchema = /* @__PURE__ */ fleetShutdownRequest();
12906
13305
  fleetShutdownResultSchema = object({
12907
- ...request8,
13306
+ ...request9,
12908
13307
  type: literal("fleet.shutdown.result"),
12909
13308
  project: identifier2,
12910
13309
  ok: boolean2(),
@@ -12912,6 +13311,7 @@ var init_dist2 = __esm(() => {
12912
13311
  failed: array(identifier2)
12913
13312
  });
12914
13313
  clientMessageSchema = /* @__PURE__ */ discriminatedUnion("type", [
13314
+ trackerImportRequestSchema,
12915
13315
  fleetShutdownRequestSchema,
12916
13316
  accountStatusRequestSchema,
12917
13317
  accountLoginRequestSchema,
@@ -12933,16 +13333,17 @@ var init_dist2 = __esm(() => {
12933
13333
  ...projectRequestSchemas,
12934
13334
  ...authRequestSchemas,
12935
13335
  ...modelsRequestSchemas,
12936
- ...providerRequestSchemas
13336
+ ...providerRequestSchemas,
13337
+ ...ticketRequestSchemas
12937
13338
  ]);
12938
13339
  projectsResultSchema = object({
12939
- ...request8,
13340
+ ...request9,
12940
13341
  type: literal("projects.result"),
12941
13342
  projects: array(projectSchema)
12942
13343
  });
12943
13344
  snapshotSchema = object({ seq: counter, state: json() });
12944
13345
  subscribedSchema = object({
12945
- ...request8,
13346
+ ...request9,
12946
13347
  type: literal("project.subscribed"),
12947
13348
  subscriptionId: identifier2,
12948
13349
  project: identifier2,
@@ -12950,9 +13351,9 @@ var init_dist2 = __esm(() => {
12950
13351
  snapshot: snapshotSchema.optional()
12951
13352
  });
12952
13353
  history = { project: identifier2, seq: counter, events: array(eventSchema) };
12953
- sessionResultSchema = object({ ...request8, ...history, type: literal("session.result"), sessionId: identifier2 }).superRefine(checkHistory);
13354
+ sessionResultSchema = object({ ...request9, ...history, type: literal("session.result"), sessionId: identifier2 }).superRefine(checkHistory);
12954
13355
  historyResultSchema = object({
12955
- ...request8,
13356
+ ...request9,
12956
13357
  type: literal("fleet.history.result"),
12957
13358
  project: identifier2,
12958
13359
  events: array(eventSchema),
@@ -12987,6 +13388,7 @@ var init_dist2 = __esm(() => {
12987
13388
  message: identifier2
12988
13389
  });
12989
13390
  serverMessageSchema = discriminatedUnion("type", [
13391
+ trackerImportResultSchema,
12990
13392
  fleetShutdownResultSchema,
12991
13393
  accountResultSchema,
12992
13394
  accountDeviceSchema,
@@ -13010,12 +13412,140 @@ var init_dist2 = __esm(() => {
13010
13412
  projectsInspectionSchema,
13011
13413
  ...authResultSchemas,
13012
13414
  modelsCatalogSchema,
13013
- providersCatalogSchema
13415
+ providersCatalogSchema,
13416
+ ticketResultSchema
13014
13417
  ]);
13015
13418
  envelopeSchema = object({ version: versionSchema });
13016
13419
  correlationSchema = object({ id: identifier2 });
13017
13420
  });
13018
13421
 
13422
+ // ../plugins/internal-tracker/src/index.ts
13423
+ var exports_src6 = {};
13424
+ __export(exports_src6, {
13425
+ activate: () => activate6
13426
+ });
13427
+ import { randomUUID as randomUUID7 } from "node:crypto";
13428
+ function activate6(ctx) {
13429
+ const append = (project, build) => {
13430
+ if (!ctx.events.appendWith)
13431
+ throw new Error("Internal tracker requires atomic event append support");
13432
+ return ctx.events.appendWith(project, (tables) => build(tables));
13433
+ };
13434
+ const historyFor = async (project, ticket, signal) => {
13435
+ signal?.throwIfAborted();
13436
+ const history = await ctx.events.read(project, 0);
13437
+ signal?.throwIfAborted();
13438
+ if (!history.some((e) => e.kind === "ticket.created" && typeof e.payload === "object" && e.payload !== null && !Array.isArray(e.payload) && e.payload.id === ticket))
13439
+ throw new Error("Internal ticket not found");
13440
+ return history;
13441
+ };
13442
+ const provider = {
13443
+ async read({ signal }) {
13444
+ signal?.throwIfAborted();
13445
+ },
13446
+ async status() {
13447
+ return { installed: true, state: "connected" };
13448
+ },
13449
+ async create(request) {
13450
+ const { project, actor } = mutationSchema.parse(request);
13451
+ const fields = createSchema.parse(request);
13452
+ const prefix = project.toUpperCase().replace(/[^A-Z]/g, "").slice(0, 5);
13453
+ if (!prefix)
13454
+ throw new Error("Internal ticket project id must contain a letter");
13455
+ const events = await append(project, (tables) => {
13456
+ request.signal?.throwIfAborted();
13457
+ let highest = 0;
13458
+ for (const ticket of tables.projects[project]?.tickets ?? []) {
13459
+ if (!ticket.id.startsWith(`${prefix}-`))
13460
+ continue;
13461
+ const suffix = ticket.id.slice(prefix.length + 1);
13462
+ if (/^[0-9]+$/.test(suffix))
13463
+ highest = Math.max(highest, Number(suffix));
13464
+ }
13465
+ if (!Number.isSafeInteger(highest + 1))
13466
+ throw new Error("Internal ticket numbers exhausted");
13467
+ const payload = ticketCreatedSchema.parse({ ...fields, id: `${prefix}-${highest + 1}` });
13468
+ request.beforeWrite?.();
13469
+ return [{ project, actor, at: new Date().toISOString(), kind: "ticket.created", payload }];
13470
+ });
13471
+ return { id: ticketCreatedSchema.parse(events[0]?.payload).id };
13472
+ },
13473
+ async update(request) {
13474
+ const { project, actor } = mutationSchema.parse(request);
13475
+ const ticket = identity.parse(request.ticket);
13476
+ const patch = ticketPatchSchema.parse(request.patch);
13477
+ await historyFor(project, ticket, request.signal);
13478
+ await append(project, (tables) => {
13479
+ request.signal?.throwIfAborted();
13480
+ if (!tables.projects[project]?.tickets.some((t) => t.id === ticket))
13481
+ throw new Error("Internal ticket not found");
13482
+ request.beforeWrite?.();
13483
+ return [{ project, actor, at: new Date().toISOString(), kind: "ticket.edited", payload: { ticket, patch } }];
13484
+ });
13485
+ },
13486
+ async write(request) {
13487
+ const { project, actor } = mutationSchema.parse(request);
13488
+ const { ticket, phase, state, comment, commentId } = writeSchema.parse(request);
13489
+ const history = await historyFor(project, ticket, request.signal);
13490
+ if (phase !== undefined || state !== undefined)
13491
+ await append(project, (tables) => {
13492
+ request.signal?.throwIfAborted();
13493
+ const current = tables.projects[project]?.tickets.find((t) => t.id === ticket);
13494
+ if (!current)
13495
+ throw new Error("Internal ticket not found");
13496
+ const patch = {
13497
+ ...phase !== undefined ? { labels: [...(current.labels ?? []).filter((label) => !phaseSchema.safeParse(label).success), phase] } : {},
13498
+ ...state !== undefined ? { state } : {}
13499
+ };
13500
+ request.beforeWrite?.();
13501
+ return [{ project, actor, at: new Date().toISOString(), kind: "ticket.edited", payload: { ticket, patch } }];
13502
+ });
13503
+ if (comment !== undefined) {
13504
+ const id = commentId ?? randomUUID7();
13505
+ if (history.some((e) => e.kind === "ticket.commented" && typeof e.payload === "object" && e.payload !== null && !Array.isArray(e.payload) && e.payload.ticket === ticket && e.payload.id === id))
13506
+ return;
13507
+ await append(project, (tables) => {
13508
+ request.signal?.throwIfAborted();
13509
+ if (!tables.projects[project]?.tickets.some((t) => t.id === ticket))
13510
+ throw new Error("Internal ticket not found");
13511
+ request.beforeWrite?.();
13512
+ return [
13513
+ {
13514
+ project,
13515
+ actor,
13516
+ at: new Date().toISOString(),
13517
+ kind: "ticket.commented",
13518
+ payload: { ticket, id, body: comment, author: actor }
13519
+ }
13520
+ ];
13521
+ });
13522
+ }
13523
+ request.signal?.throwIfAborted();
13524
+ }
13525
+ };
13526
+ ctx.register.tracker("internal", provider);
13527
+ }
13528
+ var identity, mutationSchema, createFields, createSchema, writeSchema;
13529
+ var init_src5 = __esm(() => {
13530
+ init_dist2();
13531
+ init_zod();
13532
+ identity = string2().trim().min(1);
13533
+ mutationSchema = object({ project: identity, actor: identity.default("coordinator") });
13534
+ createFields = ticketCreatedSchema.omit({ id: true }).extend({
13535
+ state: ticketCreatedSchema.shape.state.default("backlog"),
13536
+ parent: ticketCreatedSchema.shape.parent.default(null),
13537
+ blockers: ticketCreatedSchema.shape.blockers.default([])
13538
+ });
13539
+ createSchema = object(createFields.shape);
13540
+ writeSchema = object({
13541
+ ticket: identity,
13542
+ phase: phaseSchema.optional(),
13543
+ state: literal("completed").optional(),
13544
+ comment: string2().optional(),
13545
+ commentId: identity.optional()
13546
+ }).refine((r) => r.commentId === undefined || r.comment !== undefined, "commentId needs a comment");
13547
+ });
13548
+
13019
13549
  // ../plugins/linear/src/checkpoint.ts
13020
13550
  var status2, readingSchema, linearReaderCheckpointSchema;
13021
13551
  var init_checkpoint2 = __esm(() => {
@@ -13176,6 +13706,178 @@ var init_budget = __esm(() => {
13176
13706
  init_errors3();
13177
13707
  });
13178
13708
 
13709
+ // ../plugins/linear/src/linear/mutations.ts
13710
+ function applicableLabel(labels, team) {
13711
+ return labels.find((label) => label.team?.id === team) ?? labels.find((label) => !label.team);
13712
+ }
13713
+ function linearMutations(options) {
13714
+ const { request } = options;
13715
+ let root;
13716
+ async function program(signal) {
13717
+ if (!root) {
13718
+ const data = await request(`query MutationRoot($id: String!) { issue(id: $id) { id team { ${stateFields} } } }`, { id: options.rootId }, signal);
13719
+ if (!data.issue?.id || !data.issue.team?.id)
13720
+ throw new LinearReadError("Linear program root unavailable");
13721
+ root = data.issue;
13722
+ }
13723
+ return root;
13724
+ }
13725
+ async function pages(query, variables, select, signal) {
13726
+ const nodes = [];
13727
+ const cursors = new Set;
13728
+ let after = null;
13729
+ for (let i = 0;i < 100; i++) {
13730
+ const connection = select(await request(query, { ...variables, after }, signal));
13731
+ if (!connection || !Array.isArray(connection.nodes) || typeof connection.pageInfo?.hasNextPage !== "boolean")
13732
+ throw new LinearReadError("Linear mutation lookup incomplete");
13733
+ nodes.push(...connection.nodes);
13734
+ if (!connection.pageInfo.hasNextPage)
13735
+ return nodes;
13736
+ after = connection.pageInfo.endCursor;
13737
+ if (!after || cursors.has(after))
13738
+ break;
13739
+ cursors.add(after);
13740
+ }
13741
+ throw new LinearReadError("Linear mutation lookup pagination did not advance");
13742
+ }
13743
+ async function labels(names, team, signal) {
13744
+ if (!names.length)
13745
+ return [];
13746
+ const candidates = await pages(`query TicketLabels($names: [String!]!, $after: String) {
13747
+ issueLabels(first: 100, after: $after, filter: { name: { in: $names } }) {
13748
+ nodes { ${labelFields} } pageInfo { hasNextPage endCursor }
13749
+ }
13750
+ }`, { names: [...new Set(names)] }, (data) => data.issueLabels, signal);
13751
+ return [...new Set(names)].map((name) => {
13752
+ const label = applicableLabel(candidates.filter((label) => label.name === name), team);
13753
+ if (!label)
13754
+ throw new LinearReadError(`Linear label not found: ${name}`);
13755
+ return label.id;
13756
+ });
13757
+ }
13758
+ function state(team, ...types) {
13759
+ if (team.states?.pageInfo?.hasNextPage !== false || !Array.isArray(team.states.nodes))
13760
+ throw new LinearReadError("Linear workflow states incomplete");
13761
+ const sorted = [...team.states.nodes].sort((a, b) => (a.position ?? Infinity) - (b.position ?? Infinity));
13762
+ for (const type of types) {
13763
+ const found = sorted.find((s) => s.type === type);
13764
+ if (found?.id)
13765
+ return found.id;
13766
+ }
13767
+ throw new LinearReadError(`Linear workflow state not found: ${types.join(" or ")}`);
13768
+ }
13769
+ async function blockers(ticket, desired, existing, mutation) {
13770
+ for (const relation of existing.filter((r) => r.type === "blocks" && !desired.includes(r.issue.identifier))) {
13771
+ const data = await request("mutation RemoveBlocker($id: String!) { issueRelationDelete(id: $id) { success } }", { id: relation.id }, mutation.signal, mutation.beforeWrite);
13772
+ if (!data.issueRelationDelete?.success)
13773
+ throw new LinearReadError("Linear refused to remove blocker relation");
13774
+ }
13775
+ for (const blocker of new Set(desired)) {
13776
+ if (existing.some((r) => r.type === "blocks" && r.issue.identifier === blocker))
13777
+ continue;
13778
+ const data = await request("mutation AddBlocker($input: IssueRelationCreateInput!) { issueRelationCreate(input: $input) { success } }", { input: { issueId: blocker, relatedIssueId: ticket, type: "blocks" } }, mutation.signal, mutation.beforeWrite);
13779
+ if (!data.issueRelationCreate?.success)
13780
+ throw new LinearReadError(`Linear refused blocker relation from ${blocker}`);
13781
+ }
13782
+ }
13783
+ const ticketBlockers = (ticket, signal) => pages(`query TicketBlockers($id: String!, $after: String) { issue(id: $id) { inverseRelations(first: 100, after: $after) {
13784
+ nodes { id type issue { identifier } } pageInfo { hasNextPage endCursor }
13785
+ } } }`, { id: ticket }, (data) => data.issue?.inverseRelations, signal);
13786
+ return {
13787
+ async create(mutation) {
13788
+ const { title, description, signal, beforeWrite } = mutation;
13789
+ const programRoot = await program(signal);
13790
+ const since = options.now().getTime() - HOUR2;
13791
+ const recent = await request(`query RecentTickets($team: ID!, $title: String!, $since: DateTimeOrDuration!) {
13792
+ issues(first: 50, filter: { team: { id: { eq: $team } }, title: { eq: $title }, createdAt: { gte: $since } }) {
13793
+ nodes { id identifier url title description createdAt parent { ${ancestors} } }
13794
+ }
13795
+ }`, { team: programRoot.team.id, title, since: new Date(since).toISOString() }, signal);
13796
+ if (!Array.isArray(recent.issues?.nodes))
13797
+ throw new LinearReadError("Linear recent ticket lookup incomplete");
13798
+ const duplicate = recent.issues.nodes.find((issue) => {
13799
+ if (issue.title !== title || (issue.description ?? "") !== description || Date.parse(issue.createdAt) < since || !Number.isFinite(Date.parse(issue.createdAt)))
13800
+ return false;
13801
+ let parent = issue.parent;
13802
+ for (let depth = 0;parent && depth < 11; depth++, parent = parent.parent)
13803
+ if (parent.id === programRoot.id)
13804
+ return true;
13805
+ return false;
13806
+ });
13807
+ if (duplicate) {
13808
+ if (mutation.blockers?.length) {
13809
+ const existing = await ticketBlockers(duplicate.id, signal);
13810
+ const desired = [
13811
+ ...existing.filter((relation) => relation.type === "blocks").map((relation) => relation.issue.identifier),
13812
+ ...mutation.blockers
13813
+ ];
13814
+ await blockers(duplicate.id, desired, existing, mutation);
13815
+ }
13816
+ return { id: duplicate.identifier, url: duplicate.url };
13817
+ }
13818
+ const labelIds = await labels(mutation.labels, programRoot.team.id, signal);
13819
+ const data = await request("mutation CreateTicket($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { id identifier url } } }", {
13820
+ input: {
13821
+ teamId: programRoot.team.id,
13822
+ title,
13823
+ description,
13824
+ parentId: mutation.parent ?? programRoot.id,
13825
+ labelIds,
13826
+ stateId: mutation.state ? state(programRoot.team, mutation.state) : state(programRoot.team, "backlog", "unstarted")
13827
+ }
13828
+ }, signal, beforeWrite);
13829
+ const issue = data.issueCreate?.issue;
13830
+ if (!data.issueCreate?.success || !issue?.id || !issue.identifier || !issue.url)
13831
+ throw new LinearReadError("Linear refused ticket creation");
13832
+ await blockers(issue.id, mutation.blockers ?? [], [], mutation);
13833
+ return { id: issue.identifier, url: issue.url };
13834
+ },
13835
+ async update(mutation) {
13836
+ const { patch, signal, beforeWrite } = mutation;
13837
+ const data = await request(`query EditTicket($id: String!) { issue(id: $id) {
13838
+ id team { ${stateFields} }
13839
+ labels(first: 250) { nodes { ${labelFields} } pageInfo { hasNextPage endCursor } }
13840
+ inverseRelations(first: 100) { nodes { id type issue { identifier } } pageInfo { hasNextPage endCursor } }
13841
+ } }`, { id: mutation.ticket }, signal);
13842
+ const issue = data.issue;
13843
+ if (!issue?.id || !issue.team?.id)
13844
+ throw new LinearReadError("Linear ticket unavailable");
13845
+ const input = {};
13846
+ if (patch.title !== undefined)
13847
+ input.title = patch.title;
13848
+ if (patch.description !== undefined)
13849
+ input.description = patch.description;
13850
+ if (patch.parent !== undefined)
13851
+ input.parentId = patch.parent;
13852
+ if (patch.state !== undefined)
13853
+ input.stateId = state(issue.team, patch.state);
13854
+ if (patch.labels !== undefined) {
13855
+ if (issue.labels?.pageInfo?.hasNextPage !== false || !Array.isArray(issue.labels.nodes))
13856
+ throw new LinearReadError("Linear ticket labels incomplete");
13857
+ const added = patch.labels.filter((name) => !issue.labels.nodes.some((label) => label.name === name));
13858
+ input.addedLabelIds = await labels(added, issue.team.id, signal);
13859
+ input.removedLabelIds = issue.labels.nodes.filter((label) => !patch.labels?.includes(label.name)).map((label) => label.id);
13860
+ }
13861
+ let existing = [];
13862
+ if (patch.blockers !== undefined) {
13863
+ existing = issue.inverseRelations?.pageInfo?.hasNextPage === false ? issue.inverseRelations.nodes : await ticketBlockers(issue.id, signal);
13864
+ }
13865
+ if (Object.keys(input).length) {
13866
+ const changed = await request("mutation UpdateTicket($id: String!, $input: IssueUpdateInput!) { issueUpdate(id: $id, input: $input) { success } }", { id: issue.id, input }, signal, beforeWrite);
13867
+ if (!changed.issueUpdate?.success)
13868
+ throw new LinearReadError("Linear refused ticket update");
13869
+ }
13870
+ if (patch.blockers !== undefined)
13871
+ await blockers(issue.id, patch.blockers, existing, mutation);
13872
+ }
13873
+ };
13874
+ }
13875
+ var HOUR2 = 3600000, stateFields = "id states(first: 100) { nodes { id type position } pageInfo { hasNextPage endCursor } }", labelFields = "id name parent { name } team { id }", ancestors;
13876
+ var init_mutations = __esm(() => {
13877
+ init_errors3();
13878
+ ancestors = Array.from({ length: 10 }).reduce((fields) => `id parent { ${fields} }`, "id");
13879
+ });
13880
+
13179
13881
  // ../plugins/linear/src/linear/index.ts
13180
13882
  import { createHash as createHash10 } from "node:crypto";
13181
13883
  function linearTracker(options) {
@@ -13198,7 +13900,47 @@ function linearTracker(options) {
13198
13900
  options.budgets.set(quota, budget);
13199
13901
  }
13200
13902
  }
13903
+ const request = async (query, variables, signal, beforeWrite) => {
13904
+ if (!key)
13905
+ await prepare();
13906
+ signal?.throwIfAborted();
13907
+ beforeWrite?.();
13908
+ budget.beforeRequest(options.project);
13909
+ let response;
13910
+ try {
13911
+ response = await options.fetch(options.endpoint ?? "https://api.linear.app/graphql", {
13912
+ method: "POST",
13913
+ redirect: "error",
13914
+ headers: { "Content-Type": "application/json", Authorization: key },
13915
+ body: JSON.stringify({ query, variables }),
13916
+ signal
13917
+ });
13918
+ } catch {
13919
+ budget.response(options.project);
13920
+ throw new LinearReadError("Linear network request failed");
13921
+ }
13922
+ signal?.throwIfAborted();
13923
+ budget.response(options.project, response.headers);
13924
+ if (response.status === 429 || response.headers.has("retry-after"))
13925
+ throw budget.pause(response.headers);
13926
+ let body;
13927
+ try {
13928
+ body = await response.json();
13929
+ } catch {
13930
+ if (!response.ok)
13931
+ throw new LinearReadError(`Linear answered ${response.status}`);
13932
+ throw new LinearReadError("Linear returned an invalid or incomplete response");
13933
+ }
13934
+ if (body.errors?.some((error) => error?.extensions?.code === "RATELIMITED"))
13935
+ throw budget.pause(response.headers);
13936
+ if (!response.ok)
13937
+ throw new LinearReadError(`Linear answered ${response.status}`);
13938
+ if (!body.data || body.errors?.length)
13939
+ throw new LinearReadError("Linear returned an invalid or incomplete response");
13940
+ return body.data;
13941
+ };
13201
13942
  return {
13943
+ ...linearMutations({ rootId: options.rootId, now: options.now, request }),
13202
13944
  identity: JSON.stringify([
13203
13945
  options.endpoint ?? "https://api.linear.app/graphql",
13204
13946
  options.rootId,
@@ -13215,40 +13957,7 @@ function linearTracker(options) {
13215
13957
  if (!key)
13216
13958
  await prepare();
13217
13959
  const startedAt = options.now().toISOString();
13218
- async function gql(query, variables) {
13219
- signal.throwIfAborted();
13220
- budget.beforeRequest(options.project);
13221
- let response;
13222
- try {
13223
- response = await options.fetch(options.endpoint ?? "https://api.linear.app/graphql", {
13224
- method: "POST",
13225
- headers: { "Content-Type": "application/json", Authorization: key },
13226
- body: JSON.stringify({ query, variables }),
13227
- signal
13228
- });
13229
- } catch {
13230
- budget.response(options.project);
13231
- throw new LinearReadError("Linear network request failed");
13232
- }
13233
- budget.response(options.project, response.headers);
13234
- if (response.status === 429 || response.headers.has("retry-after"))
13235
- throw budget.pause(response.headers);
13236
- let body;
13237
- try {
13238
- body = await response.json();
13239
- } catch {
13240
- if (!response.ok)
13241
- throw new LinearReadError(`Linear answered ${response.status}`);
13242
- throw new LinearReadError("Linear returned an invalid or incomplete response");
13243
- }
13244
- if (body.errors?.some((error) => error?.extensions?.code === "RATELIMITED"))
13245
- throw budget.pause(response.headers);
13246
- if (!response.ok)
13247
- throw new LinearReadError(`Linear answered ${response.status}`);
13248
- if (!body.data || body.errors?.length)
13249
- throw new LinearReadError("Linear returned an invalid or incomplete response");
13250
- return body.data;
13251
- }
13960
+ const gql = (query, variables) => request(query, variables, signal);
13252
13961
  async function pages(query, field, variables) {
13253
13962
  const result = [];
13254
13963
  const cursors = new Set;
@@ -13454,7 +14163,7 @@ function linearTracker(options) {
13454
14163
  }
13455
14164
  };
13456
14165
  }
13457
- var fields = `fragment F on Issue {
14166
+ var fields2 = `fragment F on Issue {
13458
14167
  id identifier updatedAt title description branchName url state { type }
13459
14168
  inverseRelations(first: 5) { pageInfo { hasNextPage endCursor } nodes { type issue { identifier state { type } } } } assignee { name } parent { identifier }
13460
14169
  labels(first: 10) { pageInfo { hasNextPage endCursor } nodes { name parent { name } } }
@@ -13463,15 +14172,16 @@ var fields = `fragment F on Issue {
13463
14172
  var init_linear = __esm(() => {
13464
14173
  init_budget();
13465
14174
  init_errors3();
14175
+ init_mutations();
13466
14176
  init_errors3();
13467
14177
  init_dist2();
13468
- rootQuery = `${fields} query Root($id: String!) { issue(id: $id) { ...F } }`;
13469
- childrenQuery = `${fields} query Children($parents: [ID!], $after: String) {
14178
+ rootQuery = `${fields2} query Root($id: String!) { issue(id: $id) { ...F } }`;
14179
+ childrenQuery = `${fields2} query Children($parents: [ID!], $after: String) {
13470
14180
  issues(first: 50, after: $after, filter: { parent: { id: { in: $parents } } }) {
13471
14181
  pageInfo { hasNextPage endCursor } nodes { ...F }
13472
14182
  }
13473
14183
  }`;
13474
- changedQuery = `${fields} query Changed($filter: IssueFilter, $commentFilter: CommentFilter,
14184
+ changedQuery = `${fields2} query Changed($filter: IssueFilter, $commentFilter: CommentFilter,
13475
14185
  $after: String, $commentsAfter: String, $readIssues: Boolean!, $readComments: Boolean!) {
13476
14186
  issues(first: 25, after: $after, filter: $filter) @include(if: $readIssues) {
13477
14187
  pageInfo { hasNextPage endCursor } nodes { ...F }
@@ -13499,13 +14209,20 @@ function status3(body) {
13499
14209
  const summary = match[2]?.trim() ?? "";
13500
14210
  if (!parsed.success)
13501
14211
  return null;
13502
- return { phase: parsed.data, summary, coordinator: /^(answer|note)\s*:/i.test(summary) };
14212
+ const approval = parsed.data === "awaiting-approval" && /^approved[.!]?$/i.test(summary);
14213
+ return {
14214
+ phase: parsed.data,
14215
+ summary,
14216
+ approval,
14217
+ coordinator: /^(answer|note)\s*:/i.test(summary) || approval || /^acceptance: \d+ more runs allowed by the coordinator:/i.test(summary)
14218
+ };
13503
14219
  }
13504
14220
  function trackerChanges(project, history, reading) {
13505
14221
  const tickets = new Map;
13506
14222
  const reports = new Map;
13507
14223
  const answered = new Set;
13508
- const questions = new Map;
14224
+ const items = new Map;
14225
+ const merges = new Map;
13509
14226
  for (const event of history) {
13510
14227
  if (event.project !== project)
13511
14228
  continue;
@@ -13514,9 +14231,14 @@ function trackerChanges(project, history, reading) {
13514
14231
  if (event.kind === "ticket.report-posted")
13515
14232
  reports.set(event.payload.comment, event.payload);
13516
14233
  if (event.kind === "inbox.opened" && event.payload.id.startsWith("linear:"))
13517
- questions.set(event.payload.id, event.payload);
14234
+ items.set(event.payload.id, event.payload);
14235
+ if (event.kind === "merge.confirmed") {
14236
+ const confirmed = merges.get(event.payload.ticket) ?? [];
14237
+ confirmed.push(event.payload);
14238
+ merges.set(event.payload.ticket, confirmed);
14239
+ }
13518
14240
  if (event.kind === "inbox.answered") {
13519
- questions.delete(event.payload.id);
14241
+ items.delete(event.payload.id);
13520
14242
  answered.add(event.payload.id);
13521
14243
  }
13522
14244
  }
@@ -13565,35 +14287,66 @@ function trackerChanges(project, history, reading) {
13565
14287
  if (!equal(reports.get(comment.id), payload))
13566
14288
  emit("ticket.report-posted", payload, comment.updatedAt, comment.author);
13567
14289
  }
13568
- let pending;
14290
+ const pending = new Map;
13569
14291
  for (const comment of comments) {
13570
14292
  const s = status3(comment.body);
14293
+ if (/^approved\b/i.test(comment.body.trimStart()) || s?.approval)
14294
+ pending.delete("plan");
13571
14295
  if (!s)
13572
14296
  continue;
13573
- if (/^answer\s*:/i.test(s.summary) || !s.coordinator && s.phase !== "blocked")
13574
- pending = undefined;
13575
- if (!s.coordinator && s.phase === "blocked" && /^question\s*:/i.test(s.summary))
13576
- pending = comment;
14297
+ if (s.coordinator) {
14298
+ if (/^answer\s*:/i.test(s.summary)) {
14299
+ pending.delete("question");
14300
+ pending.delete("plan");
14301
+ }
14302
+ continue;
14303
+ }
14304
+ if (s.phase !== "blocked")
14305
+ pending.delete("question");
14306
+ else if (/^question\s*:/i.test(s.summary))
14307
+ pending.set("question", comment);
14308
+ if (s.phase !== "awaiting-approval")
14309
+ pending.delete("plan");
14310
+ else if (/^plan\b/i.test(s.summary) || /^## Plan[ \t]*$/m.test(comment.body))
14311
+ pending.set("plan", comment);
14312
+ if (s.phase === "ready-to-merge")
14313
+ pending.set("hand-back", comment);
14314
+ else
14315
+ pending.delete("hand-back");
13577
14316
  }
13578
14317
  if (phase !== "blocked")
13579
- pending = undefined;
13580
- const wantedId = pending ? `linear:${pending.id}:${pending.updatedAt}` : undefined;
13581
- for (const [id, question] of questions) {
13582
- if (question.ticket === source.id && id !== wantedId)
14318
+ pending.delete("question");
14319
+ if (phase !== "awaiting-approval")
14320
+ pending.delete("plan");
14321
+ if (phase !== "ready-to-merge")
14322
+ pending.delete("hand-back");
14323
+ const handBack = pending.get("hand-back");
14324
+ const handedHead = handBack?.body.match(/\bhead ([0-9a-f]{40})\b/i)?.[1]?.toLowerCase();
14325
+ const handedPr = handBack?.body.match(/\bPR #(\d+)/i)?.[1];
14326
+ if (handedHead && merges.get(source.id)?.some((merged) => merged.head === handedHead && (handedPr === undefined || Number(handedPr) === merged.pr)))
14327
+ pending.delete("hand-back");
14328
+ const identity = (comment) => `linear:${comment.id}:${comment.updatedAt}`;
14329
+ const wanted = new Set([...pending.values()].map(identity));
14330
+ for (const [id, item] of items) {
14331
+ if (item.ticket === source.id && !wanted.has(id))
13583
14332
  emit("inbox.answered", { id, answer: "Superseded by a later Linear record" }, reading.startedAt);
13584
14333
  }
13585
- if (pending && wantedId && !questions.has(wantedId) && !answered.has(wantedId))
14334
+ for (const [kind, comment] of pending) {
14335
+ const id = identity(comment);
14336
+ if (items.has(id) || answered.has(id))
14337
+ continue;
13586
14338
  emit("inbox.opened", {
13587
- id: wantedId,
14339
+ id,
13588
14340
  ticket: source.id,
13589
- kind: "question",
13590
- body: [
13591
- (status3(pending.body)?.summary ?? "").replace(/^question\s*:\s*/i, ""),
13592
- ...pending.body.trimStart().split(`
14341
+ kind,
14342
+ body: kind === "question" ? [
14343
+ (status3(comment.body)?.summary ?? "").replace(/^question\s*:\s*/i, ""),
14344
+ ...comment.body.trimStart().split(`
13593
14345
  `).slice(1)
13594
14346
  ].join(`
13595
- `).trim()
13596
- }, pending.updatedAt, pending.author);
14347
+ `).trim() : comment.body
14348
+ }, comment.updatedAt, comment.author);
14349
+ }
13597
14350
  if (!equal(before, ticket))
13598
14351
  emit("ticket.seen", ticket, reading.startedAt);
13599
14352
  }
@@ -13601,8 +14354,8 @@ function trackerChanges(project, history, reading) {
13601
14354
  for (const [id, ticket] of tickets) {
13602
14355
  if (present.has(id) || ticket.reason === "No longer in tracker scope")
13603
14356
  continue;
13604
- for (const [key, question] of questions)
13605
- if (question.ticket === id)
14357
+ for (const [key, item] of items)
14358
+ if (item.ticket === id)
13606
14359
  emit("inbox.answered", { id: key, answer: "Ticket left tracker scope" }, reading.startedAt);
13607
14360
  emit("ticket.seen", { ...ticket, status: "canceled", phase: "released", reason: "No longer in tracker scope" }, reading.startedAt);
13608
14361
  }
@@ -13648,6 +14401,9 @@ class TrackerPoller {
13648
14401
  const usage = this.#options.tracker.budget?.snapshot(this.#options.project);
13649
14402
  return { ...this.#status, ...usage ? { usage, pausedUntil: usage.pausedUntil } : {} };
13650
14403
  }
14404
+ get reading() {
14405
+ return this.#previous;
14406
+ }
13651
14407
  start() {
13652
14408
  if (this.#running)
13653
14409
  return;
@@ -13902,32 +14658,35 @@ function linearConnection(secrets, endpoint = "https://api.linear.app/graphql",
13902
14658
  }
13903
14659
 
13904
14660
  // ../plugins/linear/src/index.ts
13905
- var exports_src6 = {};
13906
- __export(exports_src6, {
13907
- activate: () => activate6
14661
+ var exports_src7 = {};
14662
+ __export(exports_src7, {
14663
+ activate: () => activate7
13908
14664
  });
13909
- function activate6(ctx) {
14665
+ function activate7(ctx) {
13910
14666
  const config = ctx.config.tracker?.linear;
13911
14667
  const readers = new Map;
13912
14668
  let pool = readerPools.get(ctx.events);
13913
14669
  if (!pool) {
13914
- pool = { budgets: new Map, pending: new Set };
14670
+ pool = { budgets: new Map, pending: new Set, projects: new Set };
13915
14671
  readerPools.set(ctx.events, pool);
13916
14672
  }
13917
14673
  const { budgets, pending } = pool;
14674
+ for (const project of [...config.quotaProjects ?? [], ...Object.keys(config.projects ?? {})])
14675
+ pool.projects.add(project);
13918
14676
  const trackers = new Map;
13919
- const trackerFor = (project) => {
14677
+ const programs = new Map;
14678
+ const trackerFor = (project, quotaOnly = false) => {
13920
14679
  let tracker = trackers.get(project);
13921
14680
  if (tracker)
13922
14681
  return tracker;
13923
14682
  const settings = config.projects?.[project];
13924
- if (!settings)
14683
+ if (!settings && !quotaOnly)
13925
14684
  throw new Error("Linear project is not configured");
13926
14685
  tracker = linearTracker({
13927
14686
  project,
13928
14687
  budgets,
13929
- rootId: settings.programRoot,
13930
- phaseGroup: settings.phaseGroup ?? "Agent phase",
14688
+ rootId: settings?.programRoot ?? "",
14689
+ phaseGroup: settings?.phaseGroup ?? "Agent phase",
13931
14690
  endpoint: config.endpoint,
13932
14691
  secrets: async () => ctx.secrets.get("LINEAR_API_KEY", project),
13933
14692
  fetch: (...args) => fetch(...args),
@@ -13941,8 +14700,8 @@ function activate6(ctx) {
13941
14700
  const restoreBudget = () => {
13942
14701
  if (restoredBudget)
13943
14702
  return restoredBudget;
13944
- const attempt = Promise.all(Object.keys(config.projects ?? {}).map(async (project) => {
13945
- const tracker = trackerFor(project);
14703
+ const attempt = Promise.all([...pool.projects].map(async (project) => {
14704
+ const tracker = trackerFor(project, true);
13946
14705
  try {
13947
14706
  await tracker.prepare?.();
13948
14707
  } catch {
@@ -13981,8 +14740,111 @@ function activate6(ctx) {
13981
14740
  signal?.removeEventListener("abort", stop);
13982
14741
  }
13983
14742
  };
14743
+ const mutate = async (request, action) => {
14744
+ await waitForRestore(request.signal);
14745
+ const tracker = trackerFor(request.project);
14746
+ await tracker.prepare?.();
14747
+ const before = JSON.stringify(tracker.budget?.snapshot(request.project));
14748
+ try {
14749
+ return await action(tracker);
14750
+ } finally {
14751
+ const usage = tracker.budget?.snapshot(request.project);
14752
+ if (JSON.stringify(usage) !== before && tracker.quota && tracker.identity)
14753
+ await ctx.events.append({
14754
+ project: request.project,
14755
+ kind: "coordinator.checkpoint",
14756
+ actor: "Linear",
14757
+ at: new Date().toISOString(),
14758
+ payload: {
14759
+ checkpoint: JSON.parse(JSON.stringify({
14760
+ format: "armada.linear-reader",
14761
+ version: 1,
14762
+ source: tracker.identity,
14763
+ quota: tracker.quota,
14764
+ usage
14765
+ }))
14766
+ }
14767
+ });
14768
+ }
14769
+ };
13984
14770
  const provider = {
13985
14771
  ...linearConnection(ctx.secrets, config.endpoint),
14772
+ async readProgram({ project, programRoot, phaseGroup, signal }) {
14773
+ await waitForRestore(signal);
14774
+ signal?.throwIfAborted();
14775
+ const group = phaseGroup ?? config.projects?.[project]?.phaseGroup ?? "Agent phase";
14776
+ const identity = JSON.stringify([programRoot, group]);
14777
+ let program = programs.get(project);
14778
+ if (!program || program.root !== identity) {
14779
+ program?.reader.stop();
14780
+ const tracker = linearTracker({
14781
+ project,
14782
+ budgets,
14783
+ rootId: programRoot,
14784
+ phaseGroup: group,
14785
+ endpoint: config.endpoint,
14786
+ secrets: () => ctx.secrets.get("LINEAR_API_KEY", project),
14787
+ fetch: (...args) => fetch(...args),
14788
+ now: () => new Date,
14789
+ log: (line) => ctx.log.info(line)
14790
+ });
14791
+ program = {
14792
+ root: identity,
14793
+ reader: new TrackerPoller({
14794
+ project,
14795
+ tracker,
14796
+ store: {
14797
+ append: async (event) => event.kind === "coordinator.checkpoint" ? await ctx.events.append(event) : { ...event, seq: 0 },
14798
+ readSince: async (after) => await ctx.events.read(project, after)
14799
+ },
14800
+ clock: {
14801
+ now: () => new Date,
14802
+ set(callback, delay) {
14803
+ const timer = setTimeout(callback, delay);
14804
+ return () => clearTimeout(timer);
14805
+ }
14806
+ }
14807
+ })
14808
+ };
14809
+ programs.set(project, program);
14810
+ }
14811
+ const { reader } = program;
14812
+ const stop = () => reader.stop();
14813
+ signal?.addEventListener("abort", stop, { once: true });
14814
+ try {
14815
+ await reader.readNow();
14816
+ signal?.throwIfAborted();
14817
+ const status = reader.status;
14818
+ if (status.pausedUntil)
14819
+ return { pausedUntil: status.pausedUntil };
14820
+ if (status.error || !reader.reading)
14821
+ throw new Error(status.error ?? "Tracker read failed");
14822
+ return {
14823
+ reading: {
14824
+ tickets: reader.reading.tickets.map((ticket) => ({
14825
+ id: ticket.id,
14826
+ title: ticket.title,
14827
+ description: ticket.description ?? "",
14828
+ state: ticket.status === "triage" ? "backlog" : ticket.status,
14829
+ labels: [...ticket.labels],
14830
+ parent: ticket.parent,
14831
+ blockers: (ticket.blockers ?? []).map((blocker) => blocker.id),
14832
+ url: ticket.url,
14833
+ source: ticket.id
14834
+ })),
14835
+ comments: reader.reading.comments.map((comment) => ({
14836
+ id: comment.id,
14837
+ ticket: comment.ticket,
14838
+ body: comment.body,
14839
+ author: comment.author,
14840
+ at: comment.createdAt
14841
+ }))
14842
+ }
14843
+ };
14844
+ } finally {
14845
+ signal?.removeEventListener("abort", stop);
14846
+ }
14847
+ },
13986
14848
  async read({ project, signal }) {
13987
14849
  signal?.throwIfAborted();
13988
14850
  await waitForRestore(signal);
@@ -14020,6 +14882,12 @@ function activate6(ctx) {
14020
14882
  signal?.removeEventListener("abort", stop);
14021
14883
  }
14022
14884
  },
14885
+ create(request) {
14886
+ return mutate(request, (tracker) => tracker.create(request));
14887
+ },
14888
+ update(request) {
14889
+ return mutate(request, (tracker) => tracker.update(request));
14890
+ },
14023
14891
  async write({ project, ticket, phase, state, comment, commentId, signal, beforeWrite }) {
14024
14892
  try {
14025
14893
  const settings = config.projects?.[project];
@@ -14109,7 +14977,7 @@ function activate6(ctx) {
14109
14977
  cursors.add(after);
14110
14978
  }
14111
14979
  const applicable = candidates.filter((label) => label.name === phase && label.parent?.name === group);
14112
- const label = applicable.find((label) => label.team?.id === issue.team.id) ?? applicable.find((label) => !label.team);
14980
+ const label = applicableLabel(applicable, issue.team.id);
14113
14981
  if (!label)
14114
14982
  throw new Error;
14115
14983
  const labelIds = issue.labels.nodes.filter((label) => label.parent?.name !== group).map((label) => label.id);
@@ -14161,9 +15029,10 @@ function activate6(ctx) {
14161
15029
  ctx.register.tracker("linear", provider);
14162
15030
  }
14163
15031
  var readerPools;
14164
- var init_src5 = __esm(() => {
15032
+ var init_src6 = __esm(() => {
14165
15033
  init_checkpoint2();
14166
15034
  init_linear();
15035
+ init_mutations();
14167
15036
  init_poll();
14168
15037
  readerPools = new WeakMap;
14169
15038
  });
@@ -25543,11 +26412,11 @@ function secretConnection(secrets, name, label, changed) {
25543
26412
  }
25544
26413
 
25545
26414
  // ../plugins/model-anthropic/src/index.ts
25546
- var exports_src7 = {};
25547
- __export(exports_src7, {
25548
- activate: () => activate7
26415
+ var exports_src8 = {};
26416
+ __export(exports_src8, {
26417
+ activate: () => activate8
25549
26418
  });
25550
- async function activate7(ctx) {
26419
+ async function activate8(ctx) {
25551
26420
  const secrets = new Map;
25552
26421
  for (const name of ["ANTHROPIC_API_KEY", "ARMADA_MODEL_API_KEY"])
25553
26422
  secrets.set(name, await ctx.secrets.get(name));
@@ -25574,7 +26443,7 @@ async function activate7(ctx) {
25574
26443
  });
25575
26444
  }
25576
26445
  var schema;
25577
- var init_src6 = __esm(() => {
26446
+ var init_src7 = __esm(() => {
25578
26447
  init_dist7();
25579
26448
  init_zod();
25580
26449
  schema = strictObject({
@@ -30561,11 +31430,11 @@ var init_dist9 = __esm(() => {
30561
31430
  });
30562
31431
 
30563
31432
  // ../plugins/model-openai-compatible/src/index.ts
30564
- var exports_src8 = {};
30565
- __export(exports_src8, {
30566
- activate: () => activate8
31433
+ var exports_src9 = {};
31434
+ __export(exports_src9, {
31435
+ activate: () => activate9
30567
31436
  });
30568
- async function activate8(ctx) {
31437
+ async function activate9(ctx) {
30569
31438
  const secrets = new Map;
30570
31439
  for (const name of secretNames)
30571
31440
  secrets.set(name, await ctx.secrets.get(name));
@@ -30600,7 +31469,7 @@ async function activate8(ctx) {
30600
31469
  });
30601
31470
  }
30602
31471
  var secretNames, schema2;
30603
- var init_src7 = __esm(() => {
31472
+ var init_src8 = __esm(() => {
30604
31473
  init_dist9();
30605
31474
  init_zod();
30606
31475
  secretNames = ["OPENAI_API_KEY", "ARMADA_MODEL_API_KEY", "ZAI_API_KEY", "AZURE_AI_API_KEY"];
@@ -30829,6 +31698,19 @@ var init_supervisor = __esm(() => {
30829
31698
  return error && typeof error === "object" ? error.code : undefined;
30830
31699
  }
30831
31700
 
31701
+ /** The last line a dying supervisor leaves: the reason, never the configuration or output. */
31702
+ function crash(reason, error) {
31703
+ try {
31704
+ const detail = error instanceof Error ? error.stack || error.message : String(error);
31705
+ const line = new Date().toISOString() + " supervisor exiting: " + reason + ": " + detail + "\n";
31706
+ if (config && config.paths && config.paths.directory)
31707
+ fs.appendFileSync(path.join(config.paths.directory, "supervisor.log"), line, { mode: 0o600 });
31708
+ } catch {}
31709
+ process.exit(1);
31710
+ }
31711
+ process.on("uncaughtException", (error) => crash("uncaught exception", error));
31712
+ process.on("unhandledRejection", (error) => crash("unhandled rejection", error));
31713
+
30832
31714
  function uuid(value) {
30833
31715
  return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
30834
31716
  }
@@ -30907,6 +31789,28 @@ var init_supervisor = __esm(() => {
30907
31789
  }
30908
31790
  }
30909
31791
 
31792
+ // The liveness contract (version 1) is written once the CLI runs inside the pinned
31793
+ // process group. A later host that finds this endpoint dead without a final record
31794
+ // may check whether that group still exists; without the contract it knows nothing.
31795
+ // The file names the group only: no command, environment, output or token.
31796
+ let contractWrite = Promise.resolve();
31797
+ function persistContract(group) {
31798
+ if (!config.paths.pin || !Number.isInteger(group) || group < 1) return;
31799
+ const temporary = config.paths.pin + ".tmp-" + crypto.randomBytes(6).toString("hex");
31800
+ contractWrite = (async () => {
31801
+ const contract = {
31802
+ version: 1,
31803
+ worker: config.worker,
31804
+ workspace: config.workspace,
31805
+ group,
31806
+ platform: process.platform,
31807
+ establishedAt: new Date().toISOString(),
31808
+ };
31809
+ await fs.promises.writeFile(temporary, JSON.stringify(contract), { flag: "wx", mode: 0o600 });
31810
+ await fs.promises.rename(temporary, config.paths.pin);
31811
+ })().catch(() => fs.promises.unlink(temporary).catch(() => {}));
31812
+ }
31813
+
30910
31814
  let serverClosing = false;
30911
31815
  function maybeCloseServer() {
30912
31816
  if (serverClosing || !closed || activeConnections !== 0 || !launchAnswered || !server || !server.listening) return;
@@ -30918,7 +31822,10 @@ var init_supervisor = __esm(() => {
30918
31822
  return;
30919
31823
  }
30920
31824
  server.close(() => {
30921
- fs.promises.unlink(config.paths.socket).catch(() => {}).finally(() => {
31825
+ // The group ended under this supervisor; its final record (if any) is the proof now.
31826
+ const removals = [fs.promises.unlink(config.paths.socket).catch(() => {})];
31827
+ if (config.paths.pin) removals.push(contractWrite.then(() => fs.promises.unlink(config.paths.pin)).catch(() => {}));
31828
+ Promise.all(removals).finally(() => {
30922
31829
  // The final metadata is intentionally retained for a new host to adopt
30923
31830
  // a completed worker once. It contains no command or environment data.
30924
31831
  fs.promises.lstat(config.paths.state).catch(() => null).then((metadata) => {
@@ -31127,6 +32034,7 @@ var init_supervisor = __esm(() => {
31127
32034
  }
31128
32035
  if (message.type === "started") {
31129
32036
  state = "running";
32037
+ persistContract(livePinPid());
31130
32038
  resolveStarted();
31131
32039
  } else if (message.type === "launch-error") {
31132
32040
  startError = new Error(typeof message.message === "string" ? message.message : "worker failed to start");
@@ -31225,6 +32133,9 @@ var init_supervisor = __esm(() => {
31225
32133
  function reply(socket, value) {
31226
32134
  if (socket.destroyed) return;
31227
32135
  const payload = JSON.stringify(value) + "\n";
32136
+ // A peer that already reset the connection (a timed-out or satisfied host
32137
+ // request) surfaces as EPIPE/ECONNRESET here; the socket's error listener
32138
+ // below keeps that a closed connection, never a supervisor crash.
31228
32139
  socket.end(payload);
31229
32140
  }
31230
32141
 
@@ -31241,6 +32152,9 @@ var init_supervisor = __esm(() => {
31241
32152
  maybeCloseServer();
31242
32153
  };
31243
32154
  socket.setEncoding("utf8");
32155
+ // Without this listener one reset peer raises an uncaught error and ends
32156
+ // the supervisor while its process group keeps running (THE-2233).
32157
+ socket.on("error", () => socket.destroy());
31244
32158
  socket.on("close", done);
31245
32159
  socket.on("data", (chunk) => {
31246
32160
  if (replied) return;
@@ -31266,7 +32180,7 @@ var init_supervisor = __esm(() => {
31266
32180
  );
31267
32181
  });
31268
32182
  });
31269
- server.on("error", () => process.exit(1));
32183
+ server.on("error", (error) => crash("socket server error", error));
31270
32184
  server.listen(config.paths.socket, async () => {
31271
32185
  try {
31272
32186
  if (process.platform !== "win32") await fs.promises.chmod(config.paths.socket, 0o600);
@@ -31369,7 +32283,7 @@ var init_supervisor = __esm(() => {
31369
32283
  if (!directory.isDirectory() || directory.isSymbolicLink() ||
31370
32284
  (typeof process.getuid === "function" && directory.uid !== process.getuid()) ||
31371
32285
  (directory.mode & 0o077) !== 0) throw new Error("local supervisor directory is not private");
31372
- for (const path of [config.paths.socket, config.paths.state]) {
32286
+ for (const path of [config.paths.socket, config.paths.state, config.paths.pin].filter(Boolean)) {
31373
32287
  try {
31374
32288
  await fs.promises.lstat(path);
31375
32289
  throw new Error("local supervisor endpoint already exists");
@@ -31392,29 +32306,79 @@ var init_supervisor = __esm(() => {
31392
32306
  });
31393
32307
 
31394
32308
  // ../plugins/node-local/src/test-merge.ts
31395
- import { spawn as spawn2 } from "node:child_process";
32309
+ import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
31396
32310
  import { mkdtemp as mkdtemp2, rm as rm6 } from "node:fs/promises";
31397
32311
  import { tmpdir as tmpdir3 } from "node:os";
31398
- import { join as join14 } from "node:path";
32312
+ import { join as join14, win32 } from "node:path";
31399
32313
  async function testMerge(request) {
31400
32314
  if (!/^[0-9a-f]{40}$/.test(request.base) || !/^[0-9a-f]{40}$/.test(request.head) || !request.commands.length)
31401
32315
  throw new Error("invalid test merge request");
31402
32316
  request.signal?.throwIfAborted();
31403
32317
  const directory = await mkdtemp2(join14(tmpdir3(), "armada-merge-"));
31404
32318
  const path = join14(directory, "worktree");
32319
+ let cleanupSafe = true;
31405
32320
  const run = (file, args, cwd = request.repository, signal = request.signal) => new Promise((resolve, reject) => {
31406
32321
  signal?.throwIfAborted();
31407
- const child = spawn2(file, args, { cwd, detached: process.platform !== "win32", stdio: "ignore" });
32322
+ const windows = process.platform === "win32";
32323
+ const child = spawn2(windows ? process.execPath : file, windows ? ["-e", windowsRunner, file, ...args] : args, {
32324
+ cwd,
32325
+ detached: !windows,
32326
+ stdio: windows ? ["ignore", "pipe", "pipe", "ipc"] : ["ignore", "pipe", "pipe"],
32327
+ windowsHide: true
32328
+ });
32329
+ let output = Buffer.alloc(0);
32330
+ let truncated = false;
32331
+ const capture = (chunk) => {
32332
+ truncated ||= output.length + chunk.length > 64 * 1024;
32333
+ output = Buffer.concat([output, chunk]).subarray(-64 * 1024);
32334
+ };
32335
+ const text = () => {
32336
+ let start = 0;
32337
+ while (start < output.length && ((output[start] ?? 0) & 192) === 128)
32338
+ start++;
32339
+ return output.subarray(start).toString("utf8");
32340
+ };
32341
+ child.stdout?.on("data", capture);
32342
+ child.stderr?.on("data", capture);
31408
32343
  let stopped = false;
32344
+ let commandCode = null;
32345
+ let killed;
32346
+ let drainTimer;
31409
32347
  const kill = () => {
32348
+ if (killed)
32349
+ return killed;
31410
32350
  if (!child.pid)
31411
- return;
31412
- try {
31413
- if (process.platform !== "win32")
31414
- process.kill(-child.pid, "SIGKILL");
31415
- else
32351
+ return Promise.resolve(true);
32352
+ if (windows) {
32353
+ const root = process.env.SystemRoot || process.env.WINDIR || "C:\\Windows";
32354
+ killed = new Promise((done) => {
32355
+ if (!win32.isAbsolute(root))
32356
+ return done(false);
32357
+ execFile4(win32.join(root, "System32", "taskkill.exe"), ["/PID", String(child.pid), "/T", "/F"], { timeout: 1e4, windowsHide: true }, (error) => done(!error));
32358
+ }).then((confirmed) => {
32359
+ if (!confirmed)
32360
+ cleanupSafe = false;
32361
+ return confirmed;
32362
+ });
32363
+ drainTimer = setTimeout(() => {
32364
+ cleanupSafe = false;
32365
+ stopped = true;
31416
32366
  child.kill("SIGKILL");
32367
+ child.stdout?.destroy();
32368
+ child.stderr?.destroy();
32369
+ if (child.connected)
32370
+ child.disconnect();
32371
+ clearTimeout(timer);
32372
+ signal?.removeEventListener("abort", abort);
32373
+ reject(new CommandFailure(text(), false));
32374
+ }, 15000);
32375
+ return killed;
32376
+ }
32377
+ try {
32378
+ process.kill(-child.pid, "SIGKILL");
31417
32379
  } catch {}
32380
+ killed = Promise.resolve(true);
32381
+ return killed;
31418
32382
  };
31419
32383
  const abort = () => {
31420
32384
  stopped = true;
@@ -31422,19 +32386,29 @@ async function testMerge(request) {
31422
32386
  };
31423
32387
  const timer = setTimeout(abort, 15 * 60000);
31424
32388
  signal?.addEventListener("abort", abort, { once: true });
31425
- child.once("error", (error) => {
32389
+ if (windows)
32390
+ child.on("message", (message) => {
32391
+ if (message && typeof message === "object" && "code" in message) {
32392
+ commandCode = typeof message.code === "number" ? message.code : null;
32393
+ kill();
32394
+ }
32395
+ });
32396
+ child.once("exit", kill);
32397
+ child.once("error", () => {
31426
32398
  clearTimeout(timer);
31427
32399
  signal?.removeEventListener("abort", abort);
31428
- reject(error);
32400
+ reject(new CommandFailure(text(), false));
31429
32401
  });
31430
- child.once("close", (code) => {
32402
+ child.once("close", async (code) => {
31431
32403
  clearTimeout(timer);
31432
32404
  signal?.removeEventListener("abort", abort);
31433
- kill();
31434
- if (!stopped && code === 0)
31435
- resolve();
32405
+ const confirmed = await kill();
32406
+ clearTimeout(drainTimer);
32407
+ const exitCode = windows ? commandCode : code;
32408
+ if (!stopped && confirmed && exitCode === 0)
32409
+ resolve({ output: text(), truncated });
31436
32410
  else
31437
- reject(new Error("local command failed"));
32411
+ reject(new CommandFailure(text(), !stopped && confirmed && exitCode !== null));
31438
32412
  });
31439
32413
  });
31440
32414
  let added = false;
@@ -31467,32 +32441,72 @@ async function testMerge(request) {
31467
32441
  ], path);
31468
32442
  for (const command of request.commands) {
31469
32443
  step = command;
31470
- await run("sh", ["-c", command], path);
32444
+ const prerequisites = await run("git", ["ls-files", "--others", "--directory", "-z"], path).catch(() => null);
32445
+ try {
32446
+ await run("sh", ["-c", command], path);
32447
+ } catch (error) {
32448
+ let baseCheck = "unavailable";
32449
+ if (error instanceof CommandFailure && error.exited && !request.signal?.aborted && prerequisites && !prerequisites.truncated) {
32450
+ try {
32451
+ const exclusions = prerequisites.output.split("\x00").filter(Boolean).flatMap((path) => ["-e", `/${path.replace(/[\\*?[\]!]/g, "\\$&")}`]);
32452
+ await run("git", ["reset", "--hard", request.base], path);
32453
+ await run("git", ["clean", "-ffdx", ...exclusions], path);
32454
+ try {
32455
+ await run("sh", ["-c", command], path);
32456
+ baseCheck = "passed";
32457
+ } catch (baseError) {
32458
+ if (baseError instanceof CommandFailure && baseError.exited && !request.signal?.aborted)
32459
+ baseCheck = "failed";
32460
+ }
32461
+ } catch {}
32462
+ }
32463
+ return { ok: false, step, output: error instanceof CommandFailure ? error.output : "", baseCheck };
32464
+ }
31471
32465
  }
31472
32466
  return { ok: true };
31473
- } catch {
31474
- return { ok: false, step, output: "The local merge or gate failed; inspect it locally." };
32467
+ } catch (error) {
32468
+ return { ok: false, step, output: error instanceof CommandFailure ? error.output : "" };
31475
32469
  } finally {
31476
- try {
31477
- if (added)
31478
- await run("git", ["worktree", "remove", "--force", path], request.repository, null);
31479
- } finally {
31480
- await rm6(directory, { recursive: true, force: true });
32470
+ if (cleanupSafe) {
32471
+ try {
32472
+ if (added)
32473
+ await run("git", ["worktree", "remove", "--force", path], request.repository, null);
32474
+ } finally {
32475
+ if (cleanupSafe)
32476
+ await rm6(directory, { recursive: true, force: true });
32477
+ }
31481
32478
  }
31482
32479
  }
31483
32480
  }
31484
- var init_test_merge = () => {};
32481
+ var CommandFailure, windowsRunner = `
32482
+ const { spawn } = require("node:child_process");
32483
+ setInterval(() => {}, 60000);
32484
+ const child = spawn(process.argv[1], process.argv.slice(2), { stdio: ["ignore", "inherit", "inherit"], windowsHide: true });
32485
+ child.once("error", () => process.send({ code: null }));
32486
+ child.once("exit", (code) => process.send({ code }));
32487
+ `;
32488
+ var init_test_merge = __esm(() => {
32489
+ CommandFailure = class CommandFailure extends Error {
32490
+ output;
32491
+ exited;
32492
+ constructor(output, exited) {
32493
+ super("local command failed");
32494
+ this.output = output;
32495
+ this.exited = exited;
32496
+ }
32497
+ };
32498
+ });
31485
32499
 
31486
32500
  // ../plugins/node-local/src/index.ts
31487
- var exports_src9 = {};
31488
- __export(exports_src9, {
32501
+ var exports_src10 = {};
32502
+ __export(exports_src10, {
31489
32503
  LocalNode: () => LocalNode,
31490
- activate: () => activate9,
32504
+ activate: () => activate10,
31491
32505
  createLocalNode: () => createLocalNode,
31492
32506
  plugin: () => plugin
31493
32507
  });
31494
32508
  import { execFile as execFileCallback, spawn as spawn3 } from "node:child_process";
31495
- import { createHash as createHash11, randomUUID as randomUUID7 } from "node:crypto";
32509
+ import { createHash as createHash11, randomUUID as randomUUID8 } from "node:crypto";
31496
32510
  import { appendFile, lstat as lstat2, mkdir as mkdir4, readFile as readFile6, realpath as realpath2, rmdir, unlink } from "node:fs/promises";
31497
32511
  import { createConnection } from "node:net";
31498
32512
  import { homedir as homedir4, tmpdir as tmpdir4 } from "node:os";
@@ -31571,7 +32585,7 @@ function supervisorPaths(workspaceRoot, handle) {
31571
32585
  const digest = createHash11("sha256").update(workspaceRoot).update("\x00").update(handle).digest("hex").slice(0, 24);
31572
32586
  const directory = join15(process.platform === "win32" ? tmpdir4() : "/tmp", `armada-nl-${digest}`);
31573
32587
  const socket = process.platform === "win32" ? `\\\\.\\pipe\\armada-nl-${digest}` : join15(directory, "s");
31574
- return { directory, socket, state: join15(directory, "state.json") };
32588
+ return { directory, socket, state: join15(directory, "state.json"), pin: join15(directory, "pin.json") };
31575
32589
  }
31576
32590
  async function privateDirectory(directory) {
31577
32591
  try {
@@ -31695,8 +32709,56 @@ async function readFinalMetadata(paths, worker, workspace) {
31695
32709
  }
31696
32710
  async function removeFinalMetadata(paths) {
31697
32711
  await unlink(paths.state).catch(() => {});
32712
+ await unlink(paths.pin).catch(() => {});
31698
32713
  await rmdir(paths.directory).catch(() => {});
31699
32714
  }
32715
+ async function readLivenessContract(paths, worker, workspace) {
32716
+ if (!await privateDirectory(paths.directory))
32717
+ return { kind: "none" };
32718
+ let text;
32719
+ try {
32720
+ const details = await lstat2(paths.pin);
32721
+ if (!details.isFile() || details.isSymbolicLink() || details.size > 64 * 1024)
32722
+ return { kind: "invalid", reason: "its liveness contract is not a private file" };
32723
+ text = await readFile6(paths.pin, "utf8");
32724
+ } catch (error) {
32725
+ if (isErrno(error, "ENOENT"))
32726
+ return { kind: "none" };
32727
+ return { kind: "invalid", reason: "its liveness contract could not be read" };
32728
+ }
32729
+ let contract;
32730
+ try {
32731
+ contract = JSON.parse(text);
32732
+ } catch {
32733
+ return { kind: "invalid", reason: "its liveness contract is not valid JSON" };
32734
+ }
32735
+ if (!contract || typeof contract !== "object" || contract.version !== 1)
32736
+ return { kind: "invalid", reason: "its liveness contract has an unknown version" };
32737
+ if (!contract.worker || typeof contract.worker !== "object" || !contract.workspace || typeof contract.workspace !== "object" || !sameWorker(contract.worker, worker) || !sameWorkspace(contract.workspace, workspace))
32738
+ return { kind: "invalid", reason: "its liveness contract belongs to another worker generation" };
32739
+ if (!Number.isInteger(contract.group) || contract.group < 2 || contract.platform !== process.platform)
32740
+ return { kind: "invalid", reason: "its liveness contract names no process group of this platform" };
32741
+ return { kind: "contract", contract };
32742
+ }
32743
+ async function unreachableWorker(paths, worker, workspace, error) {
32744
+ const finding = isErrno(error, "ENOENT") ? `no supervisor endpoint at ${paths.socket}` : `the supervisor endpoint ${paths.socket} refused the connection`;
32745
+ const head = `local worker ${worker.ticket} generation ${worker.generation} is unreachable: ${finding}, and no final record exists`;
32746
+ const read = await readLivenessContract(paths, worker, workspace);
32747
+ if (read.kind === "none")
32748
+ return new Error(`${head}; no liveness contract was recorded for it (launched before version 1 or ended before its CLI started), so its process tree may still run; nothing was signaled`);
32749
+ if (read.kind === "invalid")
32750
+ return new Error(`${head}; ${read.reason}, so its process tree may still run; nothing was signaled`);
32751
+ if (process.platform === "win32")
32752
+ return new Error(`${head}; process-group liveness cannot be checked on Windows, so its tree may still run`);
32753
+ try {
32754
+ process.kill(-read.contract.group, 0);
32755
+ return new WorkerRuntimeAlive(`${head}; its pinned process group still exists, so the worker's CLI or a descendant still runs; nothing was signaled`);
32756
+ } catch (probe) {
32757
+ if (isErrno(probe, "ESRCH"))
32758
+ return new WorkerRuntimeGone(`${head}; its liveness contract (version 1) names a process group that no longer exists: every process still pinned to it has ended; nothing was signaled`);
32759
+ return new Error(`${head}; its process group could not be inspected (${isErrno(probe, "EPERM") ? "EPERM" : "unknown error"}), so its tree may still run; nothing was signaled`);
32760
+ }
32761
+ }
31700
32762
  function staleWorker() {
31701
32763
  return new Error("worker reference is stale or mismatched; left the worker untouched");
31702
32764
  }
@@ -31826,11 +32888,14 @@ class LocalNode {
31826
32888
  cwd: source,
31827
32889
  signal: request.signal
31828
32890
  });
31829
- const id = randomUUID7();
32891
+ const id = randomUUID8();
31830
32892
  const path = join15(workspaceRoot, projectRoot ? safePart(request.ticket, "ticket") : `${safePart(request.project, "project")}-${safePart(request.ticket, "ticket")}-${id}`);
31831
32893
  if (projectRoot) {
31832
32894
  await projectWorktreeRoot(projectRoot, path, request.signal);
31833
32895
  await excludeWorktrees(source, workspaceRoot, request.signal);
32896
+ const kept = await this.#keptWorktree(source, path, workspaceRoot, request);
32897
+ if (kept)
32898
+ return kept;
31834
32899
  } else
31835
32900
  await mkdir4(workspaceRoot, { recursive: true });
31836
32901
  const base = (await git(["rev-parse", "HEAD"], { cwd: source, signal: request.signal })).stdout.trim();
@@ -31885,7 +32950,7 @@ class LocalNode {
31885
32950
  throw invalidInput("worker session is empty");
31886
32951
  if (!Number.isInteger(request.worker.generation) || request.worker.generation < 1)
31887
32952
  throw invalidInput("worker generation must be a positive integer");
31888
- const handle = request.handle ?? randomUUID7();
32953
+ const handle = request.handle ?? randomUUID8();
31889
32954
  if (!isUuid(handle))
31890
32955
  throw invalidInput("worker handle must be a UUID");
31891
32956
  if (!request.command || request.command.includes("\x00"))
@@ -31954,8 +33019,26 @@ class LocalNode {
31954
33019
  throw error;
31955
33020
  this.#applySnapshot(existing, final);
31956
33021
  }
31957
- } else
31958
- await this.#refresh(existing, "adopt");
33022
+ } else {
33023
+ try {
33024
+ await this.#refresh(existing, "adopt");
33025
+ } catch (error) {
33026
+ if (!supervisorUnavailable(error))
33027
+ throw error;
33028
+ const final = await readFinalMetadata(existing.paths, worker, workspace);
33029
+ if (final)
33030
+ this.#applySnapshot(existing, final);
33031
+ else {
33032
+ const verdict = await unreachableWorker(existing.paths, worker, workspace, error);
33033
+ if (verdict instanceof WorkerRuntimeGone) {
33034
+ existing.state = "failed";
33035
+ existing.closedValue = true;
33036
+ } else
33037
+ existing.state = "unknown";
33038
+ throw verdict;
33039
+ }
33040
+ }
33041
+ }
31959
33042
  return { deliveries: existing.deliveries };
31960
33043
  }
31961
33044
  let snapshot;
@@ -31973,11 +33056,8 @@ class LocalNode {
31973
33056
  if (!supervisorUnavailable(error))
31974
33057
  throw error;
31975
33058
  const final = await readFinalMetadata(paths, worker, workspace);
31976
- if (!final) {
31977
- if (recovery.starting)
31978
- throw error;
31979
- throw staleWorker();
31980
- }
33059
+ if (!final)
33060
+ throw recovery.starting ? error : await unreachableWorker(paths, worker, workspace, error);
31981
33061
  snapshot = final;
31982
33062
  }
31983
33063
  const workspaceRecord = this.#workspaceFromMetadata(workspace, snapshot.provenance, worker.project);
@@ -32109,10 +33189,69 @@ class LocalNode {
32109
33189
  }
32110
33190
  #activeWorker(workspace) {
32111
33191
  for (const record of this.#workers.values())
32112
- if (record.workspace === workspace && !record.closedValue)
33192
+ if ((record.workspace === workspace || record.workspace.workspace.path === workspace.workspace.path) && !record.closedValue)
32113
33193
  return record;
32114
33194
  return;
32115
33195
  }
33196
+ async#keptWorktree(source, path, workspaceRoot, request) {
33197
+ const previous = reuseAdmissions.get(path) ?? Promise.resolve();
33198
+ const operation = previous.catch(() => {}).then(async () => {
33199
+ try {
33200
+ if ((await lstat2(path)).isSymbolicLink())
33201
+ throw invalidInput("project worktree must not be a symbolic link");
33202
+ } catch (error) {
33203
+ if (isErrno(error, "ENOENT"))
33204
+ return;
33205
+ throw error;
33206
+ }
33207
+ const real = await realPathOf(path);
33208
+ const describe = `${path} already exists`;
33209
+ const listing = (await git(["worktree", "list", "--porcelain"], { cwd: source, signal: request.signal })).stdout;
33210
+ let entry;
33211
+ for (const block of listing.split(/\r?\n\r?\n/)) {
33212
+ const lines = block.split(/\r?\n/);
33213
+ const first = lines[0];
33214
+ if (!first?.startsWith("worktree "))
33215
+ continue;
33216
+ if (await realPathOf(first.slice("worktree ".length)) === real) {
33217
+ entry = lines;
33218
+ break;
33219
+ }
33220
+ }
33221
+ if (!entry)
33222
+ throw invalidInput(`${describe} but is not a worktree of ${source}; move it aside before launching ${request.ticket}`);
33223
+ const branch = entry.find((line) => line.startsWith("branch "))?.slice("branch ".length);
33224
+ if (entry.includes("detached") || entry.some((line) => line.startsWith("prunable")) || branch !== `refs/heads/${request.branch}`)
33225
+ throw invalidInput(`${describe} as a kept worktree on ${branch ? branch.replace(/^refs\/heads\//, "") : "(detached HEAD)"}, not ${request.branch}; move it aside or finish it before launching ${request.ticket}`);
33226
+ request.signal?.throwIfAborted();
33227
+ const current = (await git(["branch", "--show-current"], { cwd: path, signal: request.signal })).stdout.trim();
33228
+ const top = (await git(["rev-parse", "--show-toplevel"], { cwd: path, signal: request.signal })).stdout.trim();
33229
+ if (current !== request.branch || !top || await realPathOf(top) !== real)
33230
+ throw invalidInput(`${describe} but its checkout is not ${request.branch} at that path; inspect it before launching`);
33231
+ const busy = [...this.#workers.values()].find((record) => record.workspace.workspace.path === path && !record.closedValue);
33232
+ if (busy)
33233
+ throw new Error("workspace already has an active worker");
33234
+ const base = (await git(["rev-parse", "HEAD"], { cwd: source, signal: request.signal })).stdout.trim();
33235
+ const workspace = { id: randomUUID8(), path, node: "local" };
33236
+ this.#workspaces.set(workspace.id, {
33237
+ workspace: { ...workspace },
33238
+ workspaceRoot,
33239
+ repository: source,
33240
+ branch: request.branch,
33241
+ base,
33242
+ lock: Promise.resolve(),
33243
+ removed: false
33244
+ });
33245
+ return workspace;
33246
+ });
33247
+ reuseAdmissions.set(path, operation);
33248
+ try {
33249
+ return await operation;
33250
+ } finally {
33251
+ if (reuseAdmissions.get(path) === operation)
33252
+ reuseAdmissions.delete(path);
33253
+ }
33254
+ }
32116
33255
  #record(ref, workspace, paths) {
32117
33256
  return {
32118
33257
  ref: { ...ref },
@@ -32239,16 +33378,21 @@ function supervisorUnavailable(error) {
32239
33378
  return isErrno(error, "ENOENT") || isErrno(error, "ECONNREFUSED") || isErrno(error, "ECONNRESET") || isErrno(error, "EPIPE");
32240
33379
  }
32241
33380
  async function withWorkspaceLock(workspace, action) {
32242
- const previous = workspace.lock;
33381
+ const key = workspace.workspace.path;
33382
+ const previous = pathLocks.get(key) ?? workspace.lock;
32243
33383
  let release;
32244
- workspace.lock = new Promise((resolvePromise) => {
33384
+ const lock = new Promise((resolvePromise) => {
32245
33385
  release = resolvePromise;
32246
33386
  });
33387
+ workspace.lock = lock;
33388
+ pathLocks.set(key, lock);
32247
33389
  await previous;
32248
33390
  try {
32249
33391
  return await action();
32250
33392
  } finally {
32251
33393
  release();
33394
+ if (pathLocks.get(key) === lock)
33395
+ pathLocks.delete(key);
32252
33396
  }
32253
33397
  }
32254
33398
  function createLocalNode(options = {}) {
@@ -32265,12 +33409,13 @@ function createLocalNode(options = {}) {
32265
33409
  dispose: node.dispose.bind(node)
32266
33410
  };
32267
33411
  }
32268
- function activate9(ctx) {
33412
+ function activate10(ctx) {
32269
33413
  const options = ctx.config.node?.local ?? {};
32270
33414
  ctx.register.node("local", createLocalNode(options));
32271
33415
  }
32272
- var execute2, DEFAULT_OUTPUT_TAIL, DEFAULT_STOP_TIMEOUT_MS = 1000, DEFAULT_KILL_TIMEOUT_MS = 1000, MAX_OUTPUT_TAIL, MAX_SUPERVISOR_RESPONSE_BYTES, GIT_MAX_BUFFER, BASE_ENV_KEYS, WINDOWS_ENV_KEYS, excludeWrites, plugin;
32273
- var init_src8 = __esm(() => {
33416
+ var execute2, DEFAULT_OUTPUT_TAIL, DEFAULT_STOP_TIMEOUT_MS = 1000, DEFAULT_KILL_TIMEOUT_MS = 1000, MAX_OUTPUT_TAIL, MAX_SUPERVISOR_RESPONSE_BYTES, GIT_MAX_BUFFER, BASE_ENV_KEYS, WINDOWS_ENV_KEYS, excludeWrites, reuseAdmissions, pathLocks, plugin;
33417
+ var init_src9 = __esm(() => {
33418
+ init_dist();
32274
33419
  init_guard();
32275
33420
  init_supervisor();
32276
33421
  init_test_merge();
@@ -32320,13 +33465,15 @@ var init_src8 = __esm(() => {
32320
33465
  "NUMBER_OF_PROCESSORS"
32321
33466
  ]);
32322
33467
  excludeWrites = new Map;
32323
- plugin = { activate: activate9 };
33468
+ reuseAdmissions = new Map;
33469
+ pathLocks = new Map;
33470
+ plugin = { activate: activate10 };
32324
33471
  });
32325
33472
 
32326
33473
  // ../plugins/opencode/src/driver.ts
32327
- var DRIVER2;
32328
- var init_driver2 = __esm(() => {
32329
- DRIVER2 = String.raw`
33474
+ var DRIVER3;
33475
+ var init_driver3 = __esm(() => {
33476
+ DRIVER3 = String.raw`
32330
33477
  import { execFile, spawn } from "node:child_process";
32331
33478
  import { createInterface } from "node:readline";
32332
33479
  const options = JSON.parse(process.argv[1]);
@@ -32365,7 +33512,19 @@ input.on("close", () => { chain.finally(() => process.exit(failed ? 1 : 0)); });
32365
33512
  async function turn(message) {
32366
33513
  if (failed) throw new Error("CLI session is no longer usable");
32367
33514
  const args = ["run", ...(session ? ["--session", session] : []), ...(options.model ? ["--model", options.model] : []), ...(options.effort ? ["--variant", options.effort] : []), ...options.extraArgs, "--format", "json"];
32368
- const child = spawn(options.command, args, { stdio: ["pipe", "pipe", "ignore"], shell: false });
33515
+ const child = spawn(options.command, args, { stdio: ["pipe", "pipe", "pipe"], shell: false });
33516
+ // Retain only a fixed marker; provider errors/stderr may contain credentials.
33517
+ let permissionDenied = false;
33518
+ let diagnosticTail = "";
33519
+ const permissionEvidence = (text) => {
33520
+ diagnosticTail = (diagnosticTail + text).slice(-4096);
33521
+ if (!permissionDenied && /requested permissions|(?:have|has)n['’]t granted|permission gate refused|permission (?:prompt|request)|Permission(?:Denied|Rejected|Required)(?:Error)?|approval (?:required|denied|request)/i.test(diagnosticTail)) {
33522
+ permissionDenied = true;
33523
+ emit("failure", { permission: true });
33524
+ }
33525
+ };
33526
+ child.stderr.setEncoding("utf8");
33527
+ child.stderr.on("data", permissionEvidence);
32369
33528
  let pending = "";
32370
33529
  let reply = "";
32371
33530
  let completed = false;
@@ -32376,7 +33535,11 @@ async function turn(message) {
32376
33535
  if (typeof value.sessionID === "string") session = value.sessionID;
32377
33536
  if (value.type === "text" && typeof value.part?.text === "string") reply = (reply + value.part.text).slice(-8192);
32378
33537
  if (value.type === "step_finish" && value.part?.reason === "stop") completed = true;
32379
- if (value.type === "error") turnFailed = true;
33538
+ if (value.type === "error") {
33539
+ turnFailed = true;
33540
+ for (const detail of [value.error?.name, value.error?.message, value.error?.data?.message])
33541
+ if (typeof detail === "string") permissionEvidence(detail);
33542
+ }
32380
33543
  } catch { /* CLI progress diagnostics are not JSON events. */ }
32381
33544
  };
32382
33545
  child.stdout.setEncoding("utf8");
@@ -32395,7 +33558,7 @@ async function turn(message) {
32395
33558
  if (pending) event(pending);
32396
33559
  if (code !== 0 || turnFailed || !completed || !session) {
32397
33560
  failed = true;
32398
- emit("failure");
33561
+ emit("failure", permissionDenied ? { permission: true } : {});
32399
33562
  } else emit("reply", { text: reply });
32400
33563
  emit("done", { completed: ++completedTurns });
32401
33564
  }
@@ -32434,9 +33597,9 @@ var init_status4 = __esm(() => {
32434
33597
  });
32435
33598
 
32436
33599
  // ../plugins/opencode/src/index.ts
32437
- var exports_src10 = {};
32438
- __export(exports_src10, {
32439
- activate: () => activate10,
33600
+ var exports_src11 = {};
33601
+ __export(exports_src11, {
33602
+ activate: () => activate11,
32440
33603
  opencodeRuntime: () => opencodeRuntime
32441
33604
  });
32442
33605
  function opencodeRuntime(options = {}, node) {
@@ -32514,10 +33677,14 @@ function opencodeRuntime(options = {}, node) {
32514
33677
  const ref = await facilities().launch(native ? {
32515
33678
  ...request,
32516
33679
  command: "node",
33680
+ env: {
33681
+ ...request.env,
33682
+ ...(options.permissionMode ?? "allow") === "default" || request.env.OPENCODE_PERMISSION !== undefined ? {} : { OPENCODE_PERMISSION: JSON.stringify({ "*": options.permissionMode ?? "allow" }) }
33683
+ },
32517
33684
  args: [
32518
33685
  "--input-type=module",
32519
33686
  "-e",
32520
- DRIVER2,
33687
+ DRIVER3,
32521
33688
  JSON.stringify({ command: options.binary ?? options.command ?? "opencode", model, effort, extraArgs })
32522
33689
  ]
32523
33690
  } : request);
@@ -32611,12 +33778,12 @@ function opencodeRuntime(options = {}, node) {
32611
33778
  }
32612
33779
  };
32613
33780
  }
32614
- function activate10(ctx) {
33781
+ function activate11(ctx) {
32615
33782
  ctx.register.runtime("opencode", opencodeRuntime(ctx.config.runtime?.opencode ?? {}));
32616
33783
  }
32617
33784
  var same5 = (a, b) => a.project === b.project && a.ticket === b.ticket && a.session === b.session && a.generation === b.generation && a.handle === b.handle;
32618
- var init_src9 = __esm(() => {
32619
- init_driver2();
33785
+ var init_src10 = __esm(() => {
33786
+ init_driver3();
32620
33787
  init_status4();
32621
33788
  });
32622
33789
 
@@ -32624,16 +33791,17 @@ var init_src9 = __esm(() => {
32624
33791
  var BUNDLED_PLUGINS;
32625
33792
  var init_catalog_generated = __esm(() => {
32626
33793
  BUNDLED_PLUGINS = [
32627
- { id: "claude", manifest: { id: "claude", version: "0.1.0", pluginApi: "^0.2.0", description: "Run the official Claude CLI using host-selected node facilities.", enabledByDefault: true, contributions: { runtime: { claude: { config: { type: "object", properties: { command: { type: "string", minLength: 1 }, args: { type: "array", items: { type: "string" } }, binary: { type: "string", minLength: 1 } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src(), exports_src)) },
32628
- { id: "codex", manifest: { id: "codex", version: "0.1.0", pluginApi: "^0.2.0", description: "Run the official codex CLI using host-selected node facilities.", enabledByDefault: true, contributions: { runtime: { codex: { config: { type: "object", properties: { command: { type: "string", minLength: 1 }, model: { type: "string", minLength: 1 }, effort: { type: "string", minLength: 1 }, extraArgs: { type: "array", items: { type: "string" } }, binary: { type: "string", minLength: 1 } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src2(), exports_src2)) },
33794
+ { id: "claude", manifest: { id: "claude", version: "0.1.0", pluginApi: "^0.2.0", description: "Run the official Claude CLI using host-selected node facilities.", enabledByDefault: true, contributions: { runtime: { claude: { config: { type: "object", properties: { command: { type: "string", minLength: 1 }, args: { type: "array", items: { type: "string" } }, binary: { type: "string", minLength: 1 }, permissionMode: { type: "string", enum: ["bypassPermissions", "acceptEdits", "default"], default: "bypassPermissions", description: "Worker permission mode. Applies after restarting Armada; explicit runtime arguments take precedence." } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src(), exports_src)) },
33795
+ { id: "codex", manifest: { id: "codex", version: "0.1.0", pluginApi: "^0.2.0", description: "Run the official codex CLI using host-selected node facilities.", enabledByDefault: true, contributions: { runtime: { codex: { config: { type: "object", properties: { command: { type: "string", minLength: 1 }, model: { type: "string", minLength: 1 }, effort: { type: "string", minLength: 1 }, extraArgs: { type: "array", items: { type: "string" } }, binary: { type: "string", minLength: 1 }, permissionMode: { type: "string", enum: ["workspace-write", "read-only", "default"], default: "workspace-write", description: "Worker permission mode. Applies after restarting Armada; explicit runtime arguments take precedence." } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src2(), exports_src2)) },
32629
33796
  { id: "conductor", manifest: { id: "conductor", version: "0.1.0", pluginApi: "^0.2.0", description: "Run workers in Conductor using the desktop's Armada sign-in.", enabledByDefault: false, contributions: { runtime: { conductor: { config: { type: "object", properties: { binary: { type: "string", minLength: 1, description: "Path to the Conductor executable." }, defaultProfile: { type: "string", minLength: 1 }, profiles: { type: "object", additionalProperties: { type: "object", properties: { agent: { enum: ["claude", "codex", "opencode", "cursor"] }, model: { type: "string", minLength: 1 }, effort: { type: "string", minLength: 1 }, instructions: { type: "string", maxLength: 16000 } }, required: ["agent", "model", "effort"], additionalProperties: false } }, routing: { type: "array", items: { type: "object", properties: { labels: { type: "array", minItems: 1, items: { type: "string", minLength: 1 } }, profile: { type: "string", minLength: 1 } }, required: ["labels", "profile"], additionalProperties: false } } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src3(), exports_src3)) },
32630
33797
  { id: "github", manifest: { id: "github", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Read Github observations into the fleet event log.", contributions: { forge: { github: { config: { type: "object", properties: { projects: { type: "object", additionalProperties: { type: "object", properties: { repository: { type: "string", pattern: "^[\\w.-]+/[\\w.-]+$" } }, required: ["repository"], additionalProperties: false } }, endpoint: { type: "string" } }, additionalProperties: false }, secrets: ["GITHUB_TOKEN"] } } } }, load: () => Promise.resolve().then(() => (init_src4(), exports_src4)) },
32631
33798
  { id: "hello", manifest: { id: "hello", version: "0.1.0", pluginApi: "^0.2.0", description: "Proves the bundled plugin boot path without contributing a provider.", contributions: {}, enabledByDefault: false }, load: () => Promise.resolve().then(() => exports_src5) },
32632
- { id: "linear", manifest: { id: "linear", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Read Linear observations into the fleet event log.", contributions: { tracker: { linear: { config: { type: "object", properties: { projects: { type: "object", additionalProperties: { type: "object", properties: { programRoot: { type: "string", minLength: 1 }, phaseGroup: { type: "string", minLength: 1 }, runtimeGroup: { type: "string", minLength: 1 }, readyLabel: { type: "string", minLength: 1 } }, required: ["programRoot"], additionalProperties: false } }, endpoint: { type: "string" } }, additionalProperties: false }, secrets: ["LINEAR_API_KEY"] } } } }, load: () => Promise.resolve().then(() => (init_src5(), exports_src6)) },
32633
- { id: "model-anthropic", manifest: { id: "model-anthropic", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Anthropic models for the coordinator.", contributions: { model: { anthropic: { description: "Anthropic", config: { type: "object", properties: { model: { type: "string", minLength: 1 }, baseURL: { type: "string", minLength: 1 }, apiKeySecret: { type: "string", enum: ["ANTHROPIC_API_KEY", "ARMADA_MODEL_API_KEY"] } }, additionalProperties: false }, secrets: ["ANTHROPIC_API_KEY", "ARMADA_MODEL_API_KEY"] } } } }, load: () => Promise.resolve().then(() => (init_src6(), exports_src7)) },
32634
- { id: "model-openai-compatible", manifest: { id: "model-openai-compatible", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "OpenAI-compatible endpoints models for the coordinator.", contributions: { model: { "openai-compatible": { description: "OpenAI compatible", config: { type: "object", properties: { model: { type: "string", minLength: 1 }, baseURL: { type: "string", minLength: 1 }, apiKeySecret: { type: ["string", "null"], enum: ["OPENAI_API_KEY", "ARMADA_MODEL_API_KEY", "ZAI_API_KEY", "AZURE_AI_API_KEY", null] }, apiKeyHeader: { type: "string", enum: ["authorization", "api-key"] }, supportsStructuredOutputs: { type: "boolean" } }, additionalProperties: false }, secrets: ["OPENAI_API_KEY", "ARMADA_MODEL_API_KEY", "ZAI_API_KEY", "AZURE_AI_API_KEY"] } } } }, load: () => Promise.resolve().then(() => (init_src7(), exports_src8)) },
32635
- { id: "node-local", manifest: { id: "node-local", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Prepares local git worktrees and runs workers as local processes.", contributions: { node: { local: { config: { type: "object", properties: { workspaceRoot: { type: "string", minLength: 1 }, projects: { type: "object", additionalProperties: { type: "object", required: ["root"], properties: { root: { type: "string", minLength: 1 } }, additionalProperties: false } }, transport: { enum: ["auto", "pipe", "pty"] }, outputTail: { type: "integer", minimum: 1 }, stopTimeoutMs: { type: "integer", minimum: 1 }, killTimeoutMs: { type: "integer", minimum: 1 } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src8(), exports_src9)) },
32636
- { id: "opencode", manifest: { id: "opencode", version: "0.1.0", pluginApi: "^0.2.0", description: "Run the official opencode CLI using host-selected node facilities.", enabledByDefault: true, contributions: { runtime: { opencode: { config: { type: "object", properties: { command: { type: "string", minLength: 1 }, model: { type: "string", minLength: 1 }, effort: { type: "string", minLength: 1 }, extraArgs: { type: "array", items: { type: "string" } }, binary: { type: "string", minLength: 1 } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src9(), exports_src10)) }
33799
+ { id: "internal-tracker", manifest: { id: "internal-tracker", version: "0.1.0", pluginApi: "^0.3.0", enabledByDefault: true, description: "Keep project tickets in the daemon event log, without credentials.", contributions: { tracker: { internal: { config: { type: "object", additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src5(), exports_src6)) },
33800
+ { id: "linear", manifest: { id: "linear", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Read Linear observations into the fleet event log.", contributions: { tracker: { linear: { config: { type: "object", properties: { projects: { type: "object", additionalProperties: { type: "object", properties: { programRoot: { type: "string", minLength: 1 }, phaseGroup: { type: "string", minLength: 1 }, runtimeGroup: { type: "string", minLength: 1 }, readyLabel: { type: "string", minLength: 1 } }, required: ["programRoot"], additionalProperties: false } }, endpoint: { type: "string" }, quotaProjects: { type: "array", items: { type: "string" } } }, additionalProperties: false }, secrets: ["LINEAR_API_KEY"] } } } }, load: () => Promise.resolve().then(() => (init_src6(), exports_src7)) },
33801
+ { id: "model-anthropic", manifest: { id: "model-anthropic", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Anthropic models for the coordinator.", contributions: { model: { anthropic: { description: "Anthropic", config: { type: "object", properties: { model: { type: "string", minLength: 1 }, baseURL: { type: "string", minLength: 1 }, apiKeySecret: { type: "string", enum: ["ANTHROPIC_API_KEY", "ARMADA_MODEL_API_KEY"] } }, additionalProperties: false }, secrets: ["ANTHROPIC_API_KEY", "ARMADA_MODEL_API_KEY"] } } } }, load: () => Promise.resolve().then(() => (init_src7(), exports_src8)) },
33802
+ { id: "model-openai-compatible", manifest: { id: "model-openai-compatible", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "OpenAI-compatible endpoints models for the coordinator.", contributions: { model: { "openai-compatible": { description: "OpenAI compatible", config: { type: "object", properties: { model: { type: "string", minLength: 1 }, baseURL: { type: "string", minLength: 1 }, apiKeySecret: { type: ["string", "null"], enum: ["OPENAI_API_KEY", "ARMADA_MODEL_API_KEY", "ZAI_API_KEY", "AZURE_AI_API_KEY", null] }, apiKeyHeader: { type: "string", enum: ["authorization", "api-key"] }, supportsStructuredOutputs: { type: "boolean" } }, additionalProperties: false }, secrets: ["OPENAI_API_KEY", "ARMADA_MODEL_API_KEY", "ZAI_API_KEY", "AZURE_AI_API_KEY"] } } } }, load: () => Promise.resolve().then(() => (init_src8(), exports_src9)) },
33803
+ { id: "node-local", manifest: { id: "node-local", version: "0.1.0", pluginApi: "^0.2.0", enabledByDefault: true, description: "Prepares local git worktrees and runs workers as local processes.", contributions: { node: { local: { config: { type: "object", properties: { workspaceRoot: { type: "string", minLength: 1 }, projects: { type: "object", additionalProperties: { type: "object", required: ["root"], properties: { root: { type: "string", minLength: 1 } }, additionalProperties: false } }, transport: { enum: ["auto", "pipe", "pty"] }, outputTail: { type: "integer", minimum: 1 }, stopTimeoutMs: { type: "integer", minimum: 1 }, killTimeoutMs: { type: "integer", minimum: 1 } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src9(), exports_src10)) },
33804
+ { id: "opencode", manifest: { id: "opencode", version: "0.1.0", pluginApi: "^0.2.0", description: "Run the official opencode CLI using host-selected node facilities.", enabledByDefault: true, contributions: { runtime: { opencode: { config: { type: "object", properties: { command: { type: "string", minLength: 1 }, model: { type: "string", minLength: 1 }, effort: { type: "string", minLength: 1 }, extraArgs: { type: "array", items: { type: "string" } }, binary: { type: "string", minLength: 1 }, permissionMode: { type: "string", enum: ["allow", "ask", "deny", "default"], default: "allow", description: "Worker permission mode. Applies after restarting Armada; explicit runtime arguments take precedence." } }, additionalProperties: false }, secrets: [] } } } }, load: () => Promise.resolve().then(() => (init_src10(), exports_src11)) }
32637
33805
  ];
32638
33806
  });
32639
33807
 
@@ -41161,6 +42329,9 @@ function validateConfig(manifest, config, defaults) {
41161
42329
  ...saved,
41162
42330
  ...base.projects && {
41163
42331
  projects: base.projects
42332
+ },
42333
+ ...base.quotaProjects && {
42334
+ quotaProjects: base.quotaProjects
41164
42335
  }
41165
42336
  } : saved;
41166
42337
  validateContribution(contribution.config, seam, kind, value);
@@ -41203,7 +42374,7 @@ async function loadPlugins(services, configPath = appConfigPath(), catalog = BUN
41203
42374
  throw new Error(`invalid plugin version ${manifest.version}`);
41204
42375
  if (!import_semver.validRange(manifest.pluginApi))
41205
42376
  throw new Error(`invalid pluginApi range ${manifest.pluginApi}`);
41206
- if (!import_semver.satisfies(PLUGIN_API_VERSION, manifest.pluginApi))
42377
+ if (![PLUGIN_API_VERSION, "0.2.0"].some((version) => import_semver.satisfies(version, manifest.pluginApi)))
41207
42378
  throw new Error(`pluginApi ${manifest.pluginApi} excludes daemon Plugin API ${PLUGIN_API_VERSION}`);
41208
42379
  const config = validateConfig(manifest, setting?.config ?? {}, defaults);
41209
42380
  const declared = new Set(SEAMS.flatMap((seam) => Object.values(manifest.contributions[seam] ?? {}).flatMap((c) => c.secrets)));
@@ -41942,6 +43113,66 @@ var init_status5 = __esm(() => {
41942
43113
  init_list();
41943
43114
  });
41944
43115
 
43116
+ // ../daemon/src/merge/refusal.ts
43117
+ var init_refusal = () => {};
43118
+ // ../daemon/coordinator/follow-ups.ts
43119
+ function sameFollowUpAction(a, b) {
43120
+ return !!a && !!b && a.capability === b.capability && a.reason === b.reason && (a.fix ?? a.next) === (b.fix ?? b.next);
43121
+ }
43122
+ function recoverFollowUps(inbox, event, sessions) {
43123
+ for (const [id, item] of inbox) {
43124
+ const f = item.followUp;
43125
+ const current = sessions.get(item.ticket);
43126
+ if (item.kind !== "follow-up" || !f || event.seq <= item.seq)
43127
+ continue;
43128
+ let recovered = event.kind === "merge.confirmed" && event.payload.ticket === item.ticket && (!f.session || event.payload.session === f.session) && (f.pr === undefined || event.payload.pr === f.pr) && (!f.head || f.code === "branch_update" || event.payload.head === f.head) && current?.phase === "merged";
43129
+ if (f.code === "delivery_failed") {
43130
+ recovered ||= (event.kind === "delivery.sent" || event.kind === "delivery.failed" && event.payload.nextAt === null) && event.payload.id === f.args?.delivery;
43131
+ recovered ||= event.kind === "session.released" && event.payload.ticket === item.ticket && event.payload.session === f.session;
43132
+ }
43133
+ if (event.kind === "pull-request.seen")
43134
+ recovered = event.payload.number === f.pr && (event.payload.state === "merged" || f.code !== "branch_update" && !!f.head && event.payload.head !== f.head);
43135
+ if (f.code === "branch_update" && (event.kind === "pull-request.closed" || event.kind === "pull-request.merged"))
43136
+ recovered = event.payload.number === f.pr;
43137
+ if (event.kind === "ticket.seen" && event.payload.id === item.ticket && f.readyToMerge)
43138
+ recovered = current ? current.session === f.session && current.phase !== "ready-to-merge" : !!f.session?.startsWith("tracker:");
43139
+ if (event.kind === "session.reported" && event.payload.ticket === item.ticket && f.readyToMerge)
43140
+ recovered = !!current && current.session === f.session && current.phase !== "ready-to-merge";
43141
+ if (event.kind === "session.claimed" && event.payload.ticket === item.ticket)
43142
+ recovered = current?.session === event.payload.session && current.generation > (f.generation ?? -1);
43143
+ if (event.kind === "session.released" && event.payload.ticket === item.ticket && f.readyToMerge)
43144
+ recovered = !!current && current.session === f.session && current.phase === "released";
43145
+ if (event.kind === "coordinator.checkpoint") {
43146
+ const c = event.payload.checkpoint;
43147
+ if (c && typeof c === "object" && !Array.isArray(c) && c.format === "armada.worker" && c.version === 1 && c.type === "launch" && current?.session === c.session && c.ticket === item.ticket && typeof c.generation === "number" && c.generation > (f.generation ?? -1))
43148
+ recovered = true;
43149
+ }
43150
+ const availability = readProviders(event);
43151
+ if (availability)
43152
+ recovered = availability.providers.some((v) => f.plugin && v.id === f.plugin && v.enabled || f.capability && v.capabilities.includes(f.capability) && v.loaded);
43153
+ if (recovered)
43154
+ inbox.delete(id);
43155
+ }
43156
+ }
43157
+ function readProviders(event) {
43158
+ if (event.kind !== "coordinator.checkpoint")
43159
+ return;
43160
+ const parsed = providersSchema.safeParse(event.payload.checkpoint);
43161
+ return parsed.success ? parsed.data : undefined;
43162
+ }
43163
+ var providersSchema;
43164
+ var init_follow_ups = __esm(() => {
43165
+ init_zod();
43166
+ init_fold();
43167
+ init_refusal();
43168
+ providersSchema = object({
43169
+ format: literal("armada.tools"),
43170
+ version: literal(1),
43171
+ type: literal("providers"),
43172
+ providers: array(object({ id: string2(), enabled: boolean2(), loaded: boolean2(), capabilities: array(string2()) }))
43173
+ });
43174
+ });
43175
+
41945
43176
  // ../../node_modules/.bun/typebox@1.3.27/node_modules/typebox/build/system/memory/metrics.mjs
41946
43177
  var Metrics;
41947
43178
  var init_metrics = __esm(() => {
@@ -44854,6 +46085,8 @@ function checkpointRules(checkpoint) {
44854
46085
  return null;
44855
46086
  if (c.version !== 1)
44856
46087
  throw new Error("Unsupported native tools checkpoint");
46088
+ if (c.type === "wake-evidence" || c.type === "providers")
46089
+ return null;
44857
46090
  const state = rulesStateSchema.safeParse(c.rules);
44858
46091
  if (c.type !== "rules" || !state.success || state.data.revision < 1)
44859
46092
  throw new Error("Invalid native tools checkpoint");
@@ -44892,6 +46125,7 @@ function applyDelivery(deliveries, e) {
44892
46125
  }
44893
46126
  }
44894
46127
  }
46128
+ var deliveryFollowUpId = (id) => `follow-up:delivery:${id}`;
44895
46129
 
44896
46130
  // ../daemon/src/rules.ts
44897
46131
  function flowStep(phase, stage, pr, earlier) {
@@ -44959,8 +46193,8 @@ function normalizeUsage(raw, model, provider) {
44959
46193
  if (!raw || typeof raw !== "object")
44960
46194
  return "unknown";
44961
46195
  const u = raw;
44962
- const result = Object.fromEntries(fields2.map((k) => [k, Number.isSafeInteger(u[k]) && u[k] >= 0 ? u[k] : null]));
44963
- if (fields2.every((k) => result[k] === null))
46196
+ const result = Object.fromEntries(fields3.map((k) => [k, Number.isSafeInteger(u[k]) && u[k] >= 0 ? u[k] : null]));
46197
+ if (fields3.every((k) => result[k] === null))
44964
46198
  return "unknown";
44965
46199
  return {
44966
46200
  ...result,
@@ -44975,18 +46209,18 @@ function modelUsage(message) {
44975
46209
  if (m?.api === "armada-ai-sdk")
44976
46210
  return "unknown";
44977
46211
  const usage = normalizeUsage(m?.usage, m?.model, m?.provider);
44978
- return usage !== "unknown" && fields2.every((key) => usage[key] === 0) ? "unknown" : usage;
46212
+ return usage !== "unknown" && fields3.every((key) => usage[key] === 0) ? "unknown" : usage;
44979
46213
  }
44980
46214
  function add(total, usage) {
44981
46215
  if (usage === "unknown") {
44982
46216
  total.unknown++;
44983
46217
  return;
44984
46218
  }
44985
- if (fields2.some((k) => usage[k] !== null))
46219
+ if (fields3.some((k) => usage[k] !== null))
44986
46220
  total.reported++;
44987
- if (usage.incomplete || fields2.some((k) => usage[k] === null))
46221
+ if (usage.incomplete || fields3.some((k) => usage[k] === null))
44988
46222
  total.unknown++;
44989
- for (const k of fields2)
46223
+ for (const k of fields3)
44990
46224
  if (usage[k] !== null)
44991
46225
  total[k] = (total[k] ?? 0) + usage[k];
44992
46226
  if (usage.model && !total.models.includes(usage.model))
@@ -45040,9 +46274,9 @@ function checkpointUsage(checkpoint, documents) {
45040
46274
  continue;
45041
46275
  const before = normalizeUsage(prior?.models[key], current.model, current.provider);
45042
46276
  const delta = { ...current };
45043
- for (const field of fields2)
46277
+ for (const field of fields3)
45044
46278
  delta[field] = current[field] === null ? null : Math.max(0, current[field] - (before === "unknown" ? 0 : before[field] ?? 0));
45045
- if (fields2.some((field) => (delta[field] ?? 0) > 0))
46279
+ if (fields3.some((field) => (delta[field] ?? 0) > 0))
45046
46280
  diffs.push(delta);
45047
46281
  }
45048
46282
  documents.set(id, { session, models });
@@ -45065,52 +46299,43 @@ function checkpointUsage(checkpoint, documents) {
45065
46299
  }
45066
46300
  return completions;
45067
46301
  }
45068
- function projectUsage(events, zone) {
45069
- const days = new Map;
45070
- const sessions = new Map;
45071
- const turns = new Set;
45072
- const documents = new Map;
45073
- const previous = new Map;
45074
- const reported = new Map;
45075
- const dayAt = (at) => {
45076
- const key = usageTime(at, zone).day;
45077
- let row = days.get(key);
45078
- if (!row) {
45079
- row = { day: key, coordinator: emptyTotals(), workers: emptyTotals(), workerLaunches: 0, workersReported: 0 };
45080
- days.set(key, row);
45081
- }
45082
- return row;
45083
- };
45084
- const sessionAt = (id, kind) => {
46302
+
46303
+ class UsageLedger {
46304
+ #turns = new Set;
46305
+ #documents = new Map;
46306
+ #previous = new Map;
46307
+ #sessions = new Map;
46308
+ #entries = [];
46309
+ #sessionAt(id, kind) {
45085
46310
  const key = `${kind}:${id}`;
45086
- let row = sessions.get(key);
46311
+ let row = this.#sessions.get(key);
45087
46312
  if (!row) {
45088
46313
  row = { session: id, kind, totals: emptyTotals() };
45089
- sessions.set(key, row);
46314
+ this.#sessions.set(key, row);
45090
46315
  }
45091
46316
  return row;
45092
- };
45093
- const launched = (id, at) => {
45094
- const row = sessionAt(id, "worker");
46317
+ }
46318
+ #launched(id, at) {
46319
+ const row = this.#sessionAt(id, "worker");
45095
46320
  if (!row.launchedAt) {
45096
46321
  row.launchedAt = at;
45097
- dayAt(at).workerLaunches++;
46322
+ this.#entries.push({ at, kind: "launch" });
45098
46323
  }
45099
46324
  return row;
45100
- };
45101
- for (const e of events) {
46325
+ }
46326
+ apply(e) {
45102
46327
  if (e.kind === "coordinator.checkpoint") {
45103
46328
  const c = e.payload.checkpoint;
45104
- const derived = checkpointUsage(c, documents);
46329
+ const derived = checkpointUsage(c, this.#documents);
45105
46330
  const completions = e.payload.turn ? [{ turn: e.payload.turn, usage: e.payload.usage ?? "unknown" }] : derived;
45106
46331
  for (const { turn, usage } of completions)
45107
- if (!turns.has(turn.id)) {
45108
- turns.add(turn.id);
45109
- add(dayAt(e.at).coordinator, usage);
45110
- add(sessionAt(turn.session, "coordinator").totals, usage);
46332
+ if (!this.#turns.has(turn.id)) {
46333
+ this.#turns.add(turn.id);
46334
+ this.#entries.push({ at: e.at, kind: "coordinator", usage });
46335
+ add(this.#sessionAt(turn.session, "coordinator").totals, usage);
45111
46336
  }
45112
46337
  if (c && typeof c === "object" && !Array.isArray(c) && c.format === "armada.worker" && c.type === "launch" && typeof c.session === "string") {
45113
- const row = c.step === "launched" ? launched(c.session, e.at) : sessionAt(c.session, "worker");
46338
+ const row = c.step === "launched" ? this.#launched(c.session, e.at) : this.#sessionAt(c.session, "worker");
45114
46339
  if (typeof c.ticket === "string")
45115
46340
  row.ticket = c.ticket;
45116
46341
  if (typeof c.runtime === "string")
@@ -45118,21 +46343,20 @@ function projectUsage(events, zone) {
45118
46343
  }
45119
46344
  }
45120
46345
  if (e.kind === "worker.readopted") {
45121
- launched(e.payload.session, e.at).ticket = e.payload.ticket;
46346
+ this.#launched(e.payload.session, e.at).ticket = e.payload.ticket;
45122
46347
  }
45123
46348
  if (e.kind === "session.usage") {
45124
46349
  const { session, ticket, usage } = e.payload;
45125
- const row = sessionAt(session, "worker");
46350
+ const row = this.#sessionAt(session, "worker");
45126
46351
  row.ticket = ticket;
45127
- const day = dayAt(e.at);
45128
46352
  if (usage === "unknown") {
45129
46353
  row.totals.unknown = 1;
45130
- add(day.workers, usage);
46354
+ this.#entries.push({ at: e.at, kind: "worker", usage });
45131
46355
  } else {
45132
- const prior = previous.get(session);
46356
+ const prior = this.#previous.get(session);
45133
46357
  const delta = { ...usage };
45134
46358
  const cumulative = { ...usage };
45135
- for (const k of fields2) {
46359
+ for (const k of fields3) {
45136
46360
  const amount = usage[k];
45137
46361
  const floor = prior?.[k];
45138
46362
  delta[k] = amount === null ? null : Math.max(0, amount - (floor ?? 0));
@@ -45142,23 +46366,97 @@ function projectUsage(events, zone) {
45142
46366
  cumulative.incomplete = true;
45143
46367
  }
45144
46368
  }
45145
- add(day.workers, delta);
46369
+ this.#entries.push({
46370
+ at: e.at,
46371
+ kind: "worker",
46372
+ usage: delta,
46373
+ ...fields3.some((k) => usage[k] !== null) ? { session } : {}
46374
+ });
45146
46375
  row.totals = emptyTotals();
45147
46376
  add(row.totals, cumulative);
45148
- if (cumulative.incomplete || fields2.some((k) => usage[k] === null))
46377
+ if (cumulative.incomplete || fields3.some((k) => usage[k] === null))
45149
46378
  row.totals.unknown = 1;
45150
- previous.set(session, cumulative);
45151
- const known = reported.get(day.day) ?? new Set;
45152
- if (fields2.some((k) => usage[k] !== null))
45153
- known.add(session);
45154
- reported.set(day.day, known);
45155
- day.workersReported = known.size;
46379
+ this.#previous.set(session, cumulative);
45156
46380
  }
45157
46381
  }
45158
46382
  }
45159
- return { zone, days: [...days.values()], sessions: [...sessions.values()] };
45160
- }
45161
- var fields2, emptyTotals = () => ({
46383
+ usage(zone) {
46384
+ const days = new Map;
46385
+ const reported = new Map;
46386
+ const dayAt = (at) => {
46387
+ const key = usageTime(at, zone).day;
46388
+ let row = days.get(key);
46389
+ if (!row) {
46390
+ row = { day: key, coordinator: emptyTotals(), workers: emptyTotals(), workerLaunches: 0, workersReported: 0 };
46391
+ days.set(key, row);
46392
+ }
46393
+ return row;
46394
+ };
46395
+ for (const entry of this.#entries) {
46396
+ const day = dayAt(entry.at);
46397
+ if (entry.kind === "launch")
46398
+ day.workerLaunches++;
46399
+ else if (entry.kind === "coordinator")
46400
+ add(day.coordinator, entry.usage);
46401
+ else {
46402
+ add(day.workers, entry.usage);
46403
+ if (entry.session) {
46404
+ const known = reported.get(day.day) ?? new Set;
46405
+ known.add(entry.session);
46406
+ reported.set(day.day, known);
46407
+ day.workersReported = known.size;
46408
+ }
46409
+ }
46410
+ }
46411
+ return {
46412
+ zone,
46413
+ days: [...days.values()],
46414
+ sessions: [...this.#sessions.values()].map((row) => ({
46415
+ ...row,
46416
+ totals: { ...row.totals, models: [...row.totals.models] }
46417
+ }))
46418
+ };
46419
+ }
46420
+ serialize() {
46421
+ return {
46422
+ turns: [...this.#turns],
46423
+ documents: [...this.#documents],
46424
+ previous: [...this.#previous],
46425
+ sessions: [...this.#sessions],
46426
+ entries: this.#entries
46427
+ };
46428
+ }
46429
+ static restore(state) {
46430
+ if (!isObject3(state))
46431
+ throw new Error("usage ledger is not an object");
46432
+ if (!Array.isArray(state.turns) || state.turns.some((t) => typeof t !== "string"))
46433
+ throw new Error("usage ledger turns are not strings");
46434
+ if (!Array.isArray(state.entries) || state.entries.some((e) => !isObject3(e) || typeof e.at !== "string"))
46435
+ throw new Error("usage ledger entries are malformed");
46436
+ const ledger = new UsageLedger;
46437
+ for (const turn of state.turns)
46438
+ ledger.#turns.add(turn);
46439
+ for (const [id, document2] of pairs(state.documents, "documents")) {
46440
+ if (!isObject3(document2) || typeof document2.session !== "string" || !isObject3(document2.models))
46441
+ throw new Error("usage ledger document is malformed");
46442
+ ledger.#documents.set(id, document2);
46443
+ }
46444
+ for (const [session, usage] of pairs(state.previous, "previous")) {
46445
+ if (!isObject3(usage))
46446
+ throw new Error("usage ledger floor is malformed");
46447
+ ledger.#previous.set(session, usage);
46448
+ }
46449
+ for (const [key, row] of pairs(state.sessions, "sessions")) {
46450
+ if (!isObject3(row) || typeof row.session !== "string" || !isObject3(row.totals))
46451
+ throw new Error("usage ledger session is malformed");
46452
+ ledger.#sessions.set(key, row);
46453
+ }
46454
+ for (const entry of state.entries)
46455
+ ledger.#entries.push(entry);
46456
+ return ledger;
46457
+ }
46458
+ }
46459
+ var fields3, emptyTotals = () => ({
45162
46460
  input: null,
45163
46461
  output: null,
45164
46462
  cacheRead: null,
@@ -45166,10 +46464,14 @@ var fields2, emptyTotals = () => ({
45166
46464
  reported: 0,
45167
46465
  unknown: 0,
45168
46466
  models: []
45169
- }), object8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
46467
+ }), object8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined, isObject3 = (value) => object8(value) !== undefined, pairs = (value, name) => {
46468
+ if (!Array.isArray(value) || value.some((e) => !Array.isArray(e) || e.length !== 2 || typeof e[0] !== "string"))
46469
+ throw new Error(`usage ledger ${name} is not a list of named entries`);
46470
+ return value;
46471
+ };
45170
46472
  var init_usage2 = __esm(() => {
45171
46473
  init_usage_view();
45172
- fields2 = ["input", "output", "cacheRead", "cacheWrite"];
46474
+ fields3 = ["input", "output", "cacheRead", "cacheWrite"];
45173
46475
  });
45174
46476
 
45175
46477
  // ../daemon/src/fold.ts
@@ -45180,229 +46482,316 @@ function fold(events) {
45180
46482
  if (!Number.isSafeInteger(source.seq) || source.seq <= seq)
45181
46483
  throw new Error("events must have increasing positive sequence numbers");
45182
46484
  seq = source.seq;
45183
- const e = structuredClone(source);
45184
- let p = projects.get(e.project);
45185
- if (!p) {
45186
- p = empty();
45187
- projects.set(e.project, p);
45188
- }
45189
- applyDelivery(p.deliveries, e);
45190
- switch (e.kind) {
45191
- case "ticket.seen": {
45192
- const t = e.payload;
45193
- p.tickets.set(t.id, t);
45194
- const current = p.sessions.get(t.id);
45195
- const trackerId = `tracker:${t.id}`;
45196
- if (!current || current.session === trackerId) {
45197
- if (t.phase)
45198
- p.sessions.set(t.id, {
45199
- ticket: t.id,
45200
- session: trackerId,
45201
- generation: 0,
45202
- owner: t.owner ?? e.actor,
45203
- runtime: "tracker",
45204
- handle: "",
45205
- phase: t.phase,
45206
- reason: t.reason ?? t.phase,
45207
- at: e.at,
45208
- heartbeat: null,
45209
- earlier: current ? [...current.earlier, current.phase] : []
45210
- });
45211
- else if (current)
45212
- p.sessions.delete(t.id);
45213
- }
45214
- break;
45215
- }
45216
- case "pull-request.opened":
45217
- case "pull-request.conflicting":
45218
- case "pull-request.behind":
45219
- case "pull-request.head-moved":
45220
- case "pull-request.checks-green":
45221
- case "pull-request.checks-red":
45222
- case "pull-request.review-changed":
45223
- case "pull-request.closed":
45224
- case "pull-request.merged":
45225
- case "pull-request.seen": {
45226
- const priorHead = p.prs.get(e.payload.number)?.head ?? [...p.prs.values()].findLast((pr) => pr.ticket === e.payload.ticket)?.head;
45227
- if (priorHead !== e.payload.head)
45228
- clearProgressNotices(p, e.payload.ticket);
45229
- if (e.payload.state === "merged" && p.prs.get(e.payload.number)?.state !== "merged")
45230
- p.mergedAt.set(e.payload.number, { at: e.at, seq: e.seq });
45231
- p.prs.delete(e.payload.number);
45232
- p.prs.set(e.payload.number, { ...e.payload, conflicting: e.payload.state === "open" && e.payload.conflicting });
45233
- break;
46485
+ applyEvent(projects, source.kind === "coordinator.checkpoint" ? source : structuredClone(source));
46486
+ }
46487
+ return projectTables(projects, seq);
46488
+ }
46489
+ function applyEvent(projects, e) {
46490
+ let p = projects.get(e.project);
46491
+ if (!p) {
46492
+ p = empty();
46493
+ projects.set(e.project, p);
46494
+ }
46495
+ applyDelivery(p.deliveries, e);
46496
+ p.usage.apply(e);
46497
+ if (e.kind === "inbox.opened" && e.payload.followUp?.code === "delivery_failed")
46498
+ p.deliveryFollowUps.add(e.payload.id);
46499
+ switch (e.kind) {
46500
+ case "tracker.import-started":
46501
+ case "tracker.import-progress":
46502
+ case "tracker.import-ended": {
46503
+ if (e.kind === "tracker.import-started" || p.trackerImport?.id === e.payload.id) {
46504
+ const { source: _source, ...value } = e.payload;
46505
+ p.trackerImport = value;
45234
46506
  }
45235
- case "review-thread.opened":
45236
- case "review-thread.resolved": {
45237
- const pr = p.prs.get(e.payload.pr);
45238
- if (pr)
45239
- pr.unresolvedThreads = e.payload.unresolvedThreads;
46507
+ break;
46508
+ }
46509
+ case "ticket.seen": {
46510
+ const t = e.payload;
46511
+ if (p.internal.has(t.id))
45240
46512
  break;
45241
- }
45242
- case "session.claimed":
45243
- if (!Number.isSafeInteger(e.payload.generation) || e.payload.generation < 1)
45244
- throw new Error("claim generation must be a positive safe integer");
45245
- if (!p.claims.has(e.payload.session) && (e.payload.generation > (p.sessions.get(e.payload.ticket)?.generation ?? 0) || p.sessions.get(e.payload.ticket)?.session === e.payload.session && p.sessions.get(e.payload.ticket)?.claimSeq === undefined && !["released", "merged"].includes(p.sessions.get(e.payload.ticket)?.phase ?? "released")))
45246
- p.sessions.set(e.payload.ticket, {
45247
- ...e.payload,
45248
- claimSeq: e.seq,
45249
- phase: "planning",
45250
- reason: "Claimed",
46513
+ p.tickets.set(t.id, t);
46514
+ const current = p.sessions.get(t.id);
46515
+ const trackerId = `tracker:${t.id}`;
46516
+ if (!current || current.session === trackerId) {
46517
+ if (t.phase)
46518
+ p.sessions.set(t.id, {
46519
+ ticket: t.id,
46520
+ session: trackerId,
46521
+ generation: 0,
46522
+ owner: t.owner ?? e.actor,
46523
+ runtime: "tracker",
46524
+ handle: "",
46525
+ phase: t.phase,
46526
+ reason: t.reason ?? t.phase,
45251
46527
  at: e.at,
45252
46528
  heartbeat: null,
45253
- earlier: []
46529
+ earlier: current ? [...current.earlier, current.phase] : []
45254
46530
  });
45255
- if (!p.claims.has(e.payload.session) && p.sessions.get(e.payload.ticket)?.session === e.payload.session)
45256
- clearProgressNotices(p, e.payload.ticket);
45257
- p.claims.add(e.payload.session);
45258
- break;
45259
- case "session.reported": {
45260
- const s = active(p, e.payload);
45261
- if (s) {
45262
- if (s.phase !== e.payload.phase || s.reason.trim() !== e.payload.reason.trim())
45263
- clearProgressNotices(p, e.payload.ticket);
45264
- s.earlier.push(s.phase);
45265
- s.phase = e.payload.phase;
45266
- s.reason = e.payload.reason;
45267
- s.at = e.at;
45268
- if (e.payload.stage !== undefined)
45269
- s.stage = e.payload.stage;
45270
- }
45271
- break;
46531
+ else if (current)
46532
+ p.sessions.delete(t.id);
45272
46533
  }
45273
- case "session.liveness": {
45274
- const s = active(p, e.payload);
45275
- if (s && s.generation === e.payload.generation && !["blocked", "awaiting-approval", "awaiting-validation", "ready-to-merge"].includes(s.phase)) {
45276
- p.inbox.set(e.payload.id, {
45277
- id: e.payload.id,
45278
- ticket: s.ticket,
45279
- kind: "liveness",
45280
- actor: e.actor,
45281
- at: e.at,
45282
- seq: e.seq,
45283
- body: `${s.ticket} ${e.payload.verdict}: ${e.payload.summary}; evidence: ${JSON.stringify(e.payload.evidence)}`
45284
- });
45285
- }
46534
+ break;
46535
+ }
46536
+ case "ticket.created": {
46537
+ if (p.internal.has(e.payload.id))
45286
46538
  break;
45287
- }
45288
- case "session.heartbeat": {
45289
- const s = active(p, e.payload);
45290
- if (s)
45291
- s.heartbeat = e.at;
46539
+ p.internal.set(e.payload.id, e.payload);
46540
+ if (p.sessions.get(e.payload.id)?.session === `tracker:${e.payload.id}`)
46541
+ p.sessions.delete(e.payload.id);
46542
+ break;
46543
+ }
46544
+ case "ticket.edited": {
46545
+ const ticket = p.internal.get(e.payload.ticket);
46546
+ if (ticket)
46547
+ p.internal.set(ticket.id, { ...ticket, ...e.payload.patch });
46548
+ break;
46549
+ }
46550
+ case "ticket.commented": {
46551
+ if (!p.internal.has(e.payload.ticket))
45292
46552
  break;
45293
- }
45294
- case "session.released": {
45295
- const s = active(p, e.payload);
45296
- if (s) {
45297
- s.earlier.push(s.phase);
46553
+ const comments = p.comments.get(e.payload.ticket) ?? new Map;
46554
+ if (!comments.has(e.payload.id))
46555
+ comments.set(e.payload.id, { body: e.payload.body, author: e.actor, at: e.at, seq: e.seq });
46556
+ p.comments.set(e.payload.ticket, comments);
46557
+ break;
46558
+ }
46559
+ case "pull-request.opened":
46560
+ case "pull-request.conflicting":
46561
+ case "pull-request.behind":
46562
+ case "pull-request.head-moved":
46563
+ case "pull-request.checks-green":
46564
+ case "pull-request.checks-red":
46565
+ case "pull-request.review-changed":
46566
+ case "pull-request.closed":
46567
+ case "pull-request.merged":
46568
+ case "pull-request.seen": {
46569
+ const priorHead = p.prs.get(e.payload.number)?.head ?? [...p.prs.values()].findLast((pr) => pr.ticket === e.payload.ticket)?.head;
46570
+ if (priorHead !== e.payload.head)
46571
+ clearProgressNotices(p, e.payload.ticket);
46572
+ if (e.payload.state === "merged" && p.prs.get(e.payload.number)?.state !== "merged")
46573
+ p.mergedAt.set(e.payload.number, { at: e.at, seq: e.seq });
46574
+ if (e.kind === "pull-request.merged" && e.payload.mergedAt) {
46575
+ const merged = p.mergedAt.get(e.payload.number) ?? { at: e.at, seq: e.seq };
46576
+ p.mergedAt.set(e.payload.number, { ...merged, at: e.payload.mergedAt });
46577
+ }
46578
+ p.prs.delete(e.payload.number);
46579
+ p.prs.set(e.payload.number, { ...e.payload, conflicting: e.payload.state === "open" && e.payload.conflicting });
46580
+ break;
46581
+ }
46582
+ case "review-thread.opened":
46583
+ case "review-thread.resolved": {
46584
+ const pr = p.prs.get(e.payload.pr);
46585
+ if (pr)
46586
+ pr.unresolvedThreads = e.payload.unresolvedThreads;
46587
+ break;
46588
+ }
46589
+ case "session.claimed":
46590
+ if (!Number.isSafeInteger(e.payload.generation) || e.payload.generation < 1)
46591
+ throw new Error("claim generation must be a positive safe integer");
46592
+ if (!p.claims.has(e.payload.session) && (e.payload.generation > (p.sessions.get(e.payload.ticket)?.generation ?? 0) || p.sessions.get(e.payload.ticket)?.session === e.payload.session && p.sessions.get(e.payload.ticket)?.claimSeq === undefined && !["released", "merged"].includes(p.sessions.get(e.payload.ticket)?.phase ?? "released")))
46593
+ p.sessions.set(e.payload.ticket, {
46594
+ ...e.payload,
46595
+ claimSeq: e.seq,
46596
+ startedAt: p.sessions.get(e.payload.ticket)?.session === e.payload.session ? p.sessions.get(e.payload.ticket)?.startedAt ?? e.at : e.at,
46597
+ phase: "planning",
46598
+ reason: "Claimed",
46599
+ at: e.at,
46600
+ heartbeat: null,
46601
+ earlier: []
46602
+ });
46603
+ if (!p.claims.has(e.payload.session) && p.sessions.get(e.payload.ticket)?.session === e.payload.session)
46604
+ clearProgressNotices(p, e.payload.ticket);
46605
+ p.claims.add(e.payload.session);
46606
+ break;
46607
+ case "session.reported": {
46608
+ const s = active(p, e.payload);
46609
+ if (s) {
46610
+ if (s.phase !== e.payload.phase || s.reason.trim() !== e.payload.reason.trim())
45298
46611
  clearProgressNotices(p, e.payload.ticket);
45299
- s.phase = "released";
45300
- s.reason = e.payload.reason;
45301
- s.at = e.at;
45302
- }
45303
- break;
46612
+ s.earlier.push(s.phase);
46613
+ s.phase = e.payload.phase;
46614
+ s.reason = e.payload.reason;
46615
+ s.at = e.at;
46616
+ if (e.payload.stage !== undefined)
46617
+ s.stage = e.payload.stage;
45304
46618
  }
45305
- case "inbox.opened":
45306
- if (!p.inbox.has(e.payload.id))
45307
- p.inbox.set(e.payload.id, { ...e.payload, at: e.at, actor: e.actor, seq: e.seq });
45308
- break;
45309
- case "inbox.answered":
45310
- p.inbox.delete(e.payload.id);
45311
- break;
45312
- case "merge.queued":
45313
- if (!p.queue.has(e.payload.id))
45314
- p.queue.set(e.payload.id, { ...e.payload, at: e.at, seq: e.seq, state: "queued" });
45315
- break;
45316
- case "merge.started": {
45317
- const q = p.queue.get(e.payload.id);
45318
- if (q)
45319
- q.state = "running";
45320
- break;
46619
+ break;
46620
+ }
46621
+ case "session.liveness": {
46622
+ const s = active(p, e.payload);
46623
+ if (s && s.generation === e.payload.generation && !["blocked", "awaiting-approval", "awaiting-validation", "ready-to-merge"].includes(s.phase)) {
46624
+ p.inbox.set(e.payload.id, {
46625
+ id: e.payload.id,
46626
+ ticket: s.ticket,
46627
+ kind: "liveness",
46628
+ actor: e.actor,
46629
+ at: e.at,
46630
+ seq: e.seq,
46631
+ body: `${s.ticket} ${e.payload.verdict}: ${e.payload.summary}; evidence: ${JSON.stringify(e.payload.evidence)}`
46632
+ });
45321
46633
  }
45322
- case "merge.refused":
45323
- case "merge.canceled":
45324
- p.queue.delete(e.payload.id);
45325
- break;
45326
- case "merge.confirmed": {
45327
- const q = p.queue.get(e.payload.id);
45328
- if (q && (q.head !== e.payload.head || q.pr !== e.payload.pr || q.session !== e.payload.session || q.ticket !== e.payload.ticket))
45329
- break;
45330
- p.queue.delete(e.payload.id);
45331
- const s = active(p, e.payload);
45332
- if (s) {
45333
- s.earlier.push(s.phase);
45334
- clearProgressNotices(p, e.payload.ticket);
45335
- s.phase = "merged";
45336
- s.reason = `Merged #${e.payload.pr}`;
45337
- s.at = e.at;
45338
- }
45339
- break;
46634
+ break;
46635
+ }
46636
+ case "session.heartbeat": {
46637
+ const s = active(p, e.payload);
46638
+ if (s)
46639
+ s.heartbeat = e.at;
46640
+ break;
46641
+ }
46642
+ case "session.released": {
46643
+ const s = active(p, e.payload);
46644
+ if (s) {
46645
+ s.earlier.push(s.phase);
46646
+ clearProgressNotices(p, e.payload.ticket);
46647
+ s.phase = "released";
46648
+ s.reason = e.payload.reason;
46649
+ s.at = e.at;
45340
46650
  }
45341
- case "hold.opened":
45342
- if (!p.holds.has(e.payload.id))
45343
- p.holds.set(e.payload.id, { ...e.payload, at: e.at, actor: e.actor });
45344
- break;
45345
- case "hold.cleared":
45346
- p.holds.delete(e.payload.id);
45347
- break;
45348
- case "validation.opened":
45349
- if (!p.validations.has(e.payload.id))
45350
- p.validations.set(e.payload.id, { ...e.payload, at: e.at, actor: e.actor, decision: null });
45351
- break;
45352
- case "validation.decided": {
45353
- const v = p.validations.get(e.payload.id);
45354
- if (v && !v.decision)
45355
- v.decision = { decision: e.payload.decision, note: e.payload.note, at: e.at, actor: e.actor };
45356
- break;
46651
+ break;
46652
+ }
46653
+ case "inbox.opened": {
46654
+ const prior = p.inbox.get(e.payload.id);
46655
+ if (!prior || e.payload.kind === "follow-up" && prior.kind === "follow-up") {
46656
+ const changedAction = prior?.followUp && e.payload.followUp && !sameFollowUpAction(prior.followUp, e.payload.followUp);
46657
+ let followUp = e.payload.followUp;
46658
+ if (followUp && changedAction) {
46659
+ const { toldOwnerAt: _oldReceipt, ...detail } = followUp;
46660
+ followUp = detail;
46661
+ } else if (followUp && prior?.followUp?.toldOwnerAt)
46662
+ followUp = { ...followUp, toldOwnerAt: prior.followUp.toldOwnerAt };
46663
+ p.inbox.set(e.payload.id, {
46664
+ ...e.payload,
46665
+ ...followUp ? { followUp } : {},
46666
+ at: changedAction ? e.at : prior?.at ?? e.at,
46667
+ actor: e.actor,
46668
+ seq: e.seq
46669
+ });
45357
46670
  }
45358
- case "coordinator.checkpoint": {
45359
- const checkpoint = e.payload.checkpoint;
45360
- const launch = checkpoint && typeof checkpoint === "object" && !Array.isArray(checkpoint) && checkpoint.format === "armada.worker" ? workerLaunchCheckpointSchema.safeParse(checkpoint) : null;
45361
- if (launch?.success) {
45362
- const l = launch.data;
45363
- const current = p.sessions.get(l.ticket);
45364
- if ((!current || l.generation > current.generation || current.session === l.session && !["released", "merged"].includes(current.phase)) && !p.claims.has(l.session))
45365
- p.sessions.set(l.ticket, {
45366
- ticket: l.ticket,
45367
- launchSeq: current?.session === l.session ? current.launchSeq : e.seq,
45368
- session: l.session,
45369
- generation: l.generation,
45370
- runtime: l.runtime,
45371
- handle: l.handle ?? "",
45372
- owner: e.actor,
45373
- phase: "planning",
45374
- at: e.at,
45375
- heartbeat: null,
45376
- earlier: [],
45377
- reason: {
45378
- preparing: "Preparing workspace",
45379
- starting: "Starting worker CLI",
45380
- launched: "Launched; waiting for worker claim"
45381
- }[l.step]
45382
- });
45383
- }
45384
- const usage = linearUsageCheckpoint.safeParse(e.payload.checkpoint);
45385
- if (usage.success)
45386
- p.readers.linear = usage.data.usage;
45387
- const reading = readerCheckpoint.safeParse(e.payload.checkpoint);
45388
- if (reading.success && !reading.data.failures && Number.isFinite(Date.parse(e.at)))
45389
- p.readAt[reading.data.provider] = e.at;
45390
- const rules = checkpointRules(e.payload.checkpoint);
45391
- if (rules)
45392
- p.rules = rules;
46671
+ break;
46672
+ }
46673
+ case "inbox.answered":
46674
+ p.inbox.delete(e.payload.id);
46675
+ break;
46676
+ case "merge.queued":
46677
+ if (!p.queue.has(e.payload.id))
46678
+ p.queue.set(e.payload.id, { ...e.payload, at: e.at, seq: e.seq, state: "queued" });
46679
+ break;
46680
+ case "merge.started": {
46681
+ const q = p.queue.get(e.payload.id);
46682
+ if (q)
46683
+ q.state = "running";
46684
+ break;
46685
+ }
46686
+ case "merge.refused":
46687
+ case "merge.canceled":
46688
+ p.queue.delete(e.payload.id);
46689
+ break;
46690
+ case "merge.confirmed": {
46691
+ const q = p.queue.get(e.payload.id);
46692
+ if (q && (q.head !== e.payload.head || q.pr !== e.payload.pr || q.session !== e.payload.session || q.ticket !== e.payload.ticket))
45393
46693
  break;
46694
+ p.queue.delete(e.payload.id);
46695
+ const s = active(p, e.payload);
46696
+ if (s) {
46697
+ s.earlier.push(s.phase);
46698
+ clearProgressNotices(p, e.payload.ticket);
46699
+ s.phase = "merged";
46700
+ s.reason = `Merged #${e.payload.pr}`;
46701
+ s.at = e.at;
45394
46702
  }
45395
- case "coordinator.message":
45396
- break;
45397
- case "default-branch.seen":
45398
- p.defaultBranch = e.payload;
45399
- break;
46703
+ break;
46704
+ }
46705
+ case "hold.opened":
46706
+ if (!p.holds.has(e.payload.id))
46707
+ p.holds.set(e.payload.id, { ...e.payload, at: e.at, actor: e.actor });
46708
+ break;
46709
+ case "hold.cleared":
46710
+ p.holds.delete(e.payload.id);
46711
+ break;
46712
+ case "validation.opened":
46713
+ if (!p.validations.has(e.payload.id))
46714
+ p.validations.set(e.payload.id, { ...e.payload, at: e.at, actor: e.actor, decision: null });
46715
+ break;
46716
+ case "validation.decided": {
46717
+ const v = p.validations.get(e.payload.id);
46718
+ if (v && !v.decision)
46719
+ v.decision = { decision: e.payload.decision, note: e.payload.note, at: e.at, actor: e.actor };
46720
+ break;
45400
46721
  }
46722
+ case "coordinator.checkpoint": {
46723
+ const checkpoint = e.payload.checkpoint;
46724
+ const format = checkpoint && typeof checkpoint === "object" && !Array.isArray(checkpoint) ? checkpoint.format : undefined;
46725
+ const launch = format === "armada.worker" ? workerLaunchCheckpointSchema.safeParse(checkpoint) : null;
46726
+ if (launch?.success) {
46727
+ const l = launch.data;
46728
+ const current = p.sessions.get(l.ticket);
46729
+ if ((!current || l.generation > current.generation || current.session === l.session && !["released", "merged"].includes(current.phase)) && !p.claims.has(l.session))
46730
+ p.sessions.set(l.ticket, {
46731
+ ticket: l.ticket,
46732
+ launchSeq: current?.session === l.session ? current.launchSeq : e.seq,
46733
+ startedAt: current?.session === l.session ? current.startedAt : e.at,
46734
+ session: l.session,
46735
+ generation: l.generation,
46736
+ runtime: l.runtime,
46737
+ handle: l.handle ?? "",
46738
+ owner: e.actor,
46739
+ phase: "planning",
46740
+ at: e.at,
46741
+ heartbeat: null,
46742
+ earlier: [],
46743
+ reason: {
46744
+ preparing: "Preparing workspace",
46745
+ starting: "Starting worker CLI",
46746
+ launched: "Launched; waiting for worker claim"
46747
+ }[l.step]
46748
+ });
46749
+ }
46750
+ const usage = format === "armada.linear-reader" ? linearUsageCheckpoint.safeParse(checkpoint) : null;
46751
+ if (usage?.success)
46752
+ p.readers.linear = usage.data.usage;
46753
+ const reading = format === "armada.readers" ? readerCheckpoint.safeParse(checkpoint) : null;
46754
+ if (reading?.success && !reading.data.failures && Number.isFinite(Date.parse(e.at)))
46755
+ p.readAt[reading.data.provider] = e.at;
46756
+ const rules = checkpointRules(e.payload.checkpoint);
46757
+ if (rules)
46758
+ p.rules = rules;
46759
+ break;
46760
+ }
46761
+ case "coordinator.message":
46762
+ break;
46763
+ case "default-branch.seen":
46764
+ p.defaultBranch = e.payload;
46765
+ break;
45401
46766
  }
46767
+ recoverFollowUps(p.inbox, e, p.sessions);
46768
+ }
46769
+ function projectTables(projects, seq) {
45402
46770
  const tables = { seq, projects: Object.create(null) };
45403
46771
  for (const [project, p] of projects) {
46772
+ const tickets = new Map(p.tickets);
46773
+ for (const t of p.internal.values()) {
46774
+ const labelPhase = t.labels.map((label) => phaseSchema.safeParse(label)).find((result) => result.success)?.data ?? null;
46775
+ const phase = t.state === "completed" ? "merged" : t.state === "canceled" ? "released" : labelPhase;
46776
+ tickets.set(t.id, {
46777
+ id: t.id,
46778
+ title: t.title,
46779
+ description: t.description,
46780
+ labels: t.labels,
46781
+ status: t.state,
46782
+ phase,
46783
+ parent: t.parent,
46784
+ ...t.url !== undefined ? { url: t.url } : {},
46785
+ ...t.source !== undefined ? { source: t.source } : {},
46786
+ blockers: t.blockers.map((id) => ({
46787
+ id,
46788
+ status: p.internal.get(id)?.state ?? tickets.get(id)?.status ?? "unstarted"
46789
+ })),
46790
+ comments: [...p.comments.get(t.id)?.values() ?? []].sort((a, b) => Date.parse(b.at) - Date.parse(a.at) || b.seq - a.seq).slice(0, 12).map(({ body, author, at }) => ({ body, author, at }))
46791
+ });
46792
+ }
45404
46793
  const sessions = [...p.sessions.values()].map((s) => {
45405
- const pr = [...p.prs.values()].reverse().find((pr) => pr.ticket === s.ticket && pr.state !== "closed" && !(pr.state === "merged" && (s.claimSeq ?? s.launchSeq) !== undefined && (p.mergedAt.get(pr.number)?.seq ?? 0) < (s.claimSeq ?? s.launchSeq ?? 0)));
46794
+ const pr = [...p.prs.values()].reverse().find((pr) => pr.ticket === s.ticket && pr.state !== "closed" && !(pr.state === "merged" && (s.claimSeq ?? s.launchSeq) !== undefined && ((p.mergedAt.get(pr.number)?.seq ?? 0) < (s.claimSeq ?? s.launchSeq ?? 0) || s.startedAt !== undefined && Date.parse(p.mergedAt.get(pr.number)?.at ?? "") < Date.parse(s.startedAt))));
45406
46795
  const validation = [...p.validations.values()].find((v) => v.ticket === s.ticket && v.session === s.session && !v.decision);
45407
46796
  const decision = [...p.validations.values()].reverse().find((v) => v.ticket === s.ticket && v.session === s.session)?.decision;
45408
46797
  const question = [...p.inbox.values()].find((i) => i.ticket === s.ticket && i.kind === "question");
@@ -45433,7 +46822,7 @@ function fold(events) {
45433
46822
  owner: s.owner,
45434
46823
  runtime: s.runtime,
45435
46824
  handle: s.handle,
45436
- title: p.tickets.get(s.ticket)?.title ?? s.ticket,
46825
+ title: tickets.get(s.ticket)?.title ?? s.ticket,
45437
46826
  phase,
45438
46827
  state,
45439
46828
  reason,
@@ -45453,11 +46842,11 @@ function fold(events) {
45453
46842
  };
45454
46843
  for (const s of sessions)
45455
46844
  sessionsByState[s.state].push(s);
45456
- const usage = projectUsage(events.filter((e) => e.project === project), p.rules.value.policy?.budget?.zone ?? "UTC");
46845
+ const usage = p.usage.usage(p.rules.value.policy?.budget?.zone ?? "UTC");
45457
46846
  const deliveries = [...p.deliveries.values()].filter((d) => !d.sentAt && sessions.some((s) => s.ticket === d.ticket && s.session === d.session && s.generation === d.generation && !["released", "merged"].includes(s.phase)));
45458
46847
  const failures = deliveries.flatMap((d) => {
45459
46848
  const session = sessions.find((s) => s.ticket === d.ticket && s.session === d.session && s.generation === d.generation);
45460
- return d.failureSeq !== undefined && session && !["released", "merged"].includes(session.phase) ? [
46849
+ return d.failureSeq !== undefined && !p.deliveryFollowUps.has(deliveryFollowUpId(d.id)) && session && !["released", "merged"].includes(session.phase) ? [
45461
46850
  {
45462
46851
  id: `delivery:${d.id}`,
45463
46852
  ticket: d.ticket,
@@ -45472,10 +46861,11 @@ function fold(events) {
45472
46861
  tables.projects[project] = {
45473
46862
  ...p.defaultBranch ? { defaultBranch: p.defaultBranch } : {},
45474
46863
  rules: p.rules,
46864
+ ...p.trackerImport ? { trackerImport: p.trackerImport } : {},
45475
46865
  ...usage.days.length ? { usage } : {},
45476
46866
  ...Object.keys(p.readers).length ? { readers: p.readers } : {},
45477
46867
  ...Object.keys(p.readAt).length ? { readAt: p.readAt } : {},
45478
- tickets: [...p.tickets.values()],
46868
+ tickets: [...tickets.values()],
45479
46869
  pullRequests: [...p.prs.values()],
45480
46870
  sessions,
45481
46871
  sessionsByState,
@@ -45489,10 +46879,13 @@ function fold(events) {
45489
46879
  return tables;
45490
46880
  }
45491
46881
  var linearUsageCheckpoint, readerCheckpoint, empty = () => ({
46882
+ usage: new UsageLedger,
45492
46883
  rules: emptyRules(),
45493
46884
  readAt: Object.create(null),
45494
46885
  readers: Object.create(null),
45495
46886
  tickets: new Map,
46887
+ internal: new Map,
46888
+ comments: new Map,
45496
46889
  prs: new Map,
45497
46890
  mergedAt: new Map,
45498
46891
  sessions: new Map,
@@ -45501,7 +46894,8 @@ var linearUsageCheckpoint, readerCheckpoint, empty = () => ({
45501
46894
  queue: new Map,
45502
46895
  holds: new Map,
45503
46896
  validations: new Map,
45504
- deliveries: new Map
46897
+ deliveries: new Map,
46898
+ deliveryFollowUps: new Set
45505
46899
  }), active = (p, ref) => {
45506
46900
  const session = p.sessions.get(ref.ticket);
45507
46901
  return session?.session === ref.session && session.phase !== "released" && session.phase !== "merged" ? session : undefined;
@@ -45513,6 +46907,7 @@ var linearUsageCheckpoint, readerCheckpoint, empty = () => ({
45513
46907
  var init_fold = __esm(() => {
45514
46908
  init_dist2();
45515
46909
  init_zod();
46910
+ init_follow_ups();
45516
46911
  init_rules2();
45517
46912
  init_rules3();
45518
46913
  init_usage2();
@@ -45543,7 +46938,7 @@ var init_boot = __esm(() => {
45543
46938
  });
45544
46939
 
45545
46940
  // ../daemon/src/index.ts
45546
- var init_src10 = __esm(() => {
46941
+ var init_src11 = __esm(() => {
45547
46942
  init_boot();
45548
46943
  init_store();
45549
46944
  init_fold();
@@ -56659,16 +58054,17 @@ You are a worker. You own exactly one ticket, named in your launch brief. You tu
56659
58054
 
56660
58055
  - **Never merge**, never enable auto-merge, never approve your own plan. The coordinator merges.
56661
58056
  - **A listing is not an answer.** The coordinator's watch reminds about unanswered questions, plans and hand-backs after doubling intervals. Only the coordinator can \`armada ack\` a dismissible notice with a reason; it cannot skip your question, plan or hand-back. A ticket comment saying \`note: acknowledged\` does not change your phase or answer you.
56662
- - **The ticket is the source of truth.** Read it, its parent spec and the hand-back comments of its merged blockers in full before planning.
58057
+ - **The ticket is the source of truth.** On a local V2 worker, run \`armada ticket\` (or \`armada ticket <your-id>\`) to read it through your capability; \`--json\` prints the protocol Ticket. Another ticket id is refused. Internal tickets include all recorded comments; Linear tickets include the folded comments, with older comments linked in Linear. Read it, its parent spec and the hand-back comments of its merged blockers in full before planning.
56663
58058
  - **Report a milestone once.** A second report with nothing new is noise; the heartbeat proves you are alive. Use the report vocabulary below for the plan, real implementation progress, blockers, tests, shipping and the hand-back.
56664
58059
  - **Keep going on setup choices.** When setup needs a choice (an install fallback, a retry, a missing tool), take the safe option, say which in your next report, and go on. Never stop to ask about it.
56665
58060
  - **Stop by impact, not effort.** There is no budget of attempts. Failing tests, many files and layout defects are reasons to keep going. Stop and ask only when the fix breaks a contract another ticket or caller relies on, moves a module's responsibility, or a design choice the ticket does not settle remains; name the interface and who it affects. Never widen the ticket to avoid asking. Decide reversible technical choices yourself and record each one, with its reason, on the ticket and in the pull request.
56666
58061
  - **Work only in your own branch and worktree.** Never touch another agent's checkout, and stop only the processes you started.
58062
+ - **Never drive the owner's desktop.** A local worker runs on the owner's logged-in machine. Never open a window or an app (\`open -a\`, a packaged app's binary), bring one to the front, script System Events (\`osascript\`, AppleScript) or capture the screen (\`screencapture\`). Verify a GUI app headless or offscreen: an Electron window under test is \`new BrowserWindow({ show: false })\` behind a flag (the Armada desktop shell honours \`ARMADA_DESKTOP_HEADLESS=1\`, which a local Claude launch sets in your environment; set it yourself otherwise: no window, no dock icon, its data apart, only the catalog and log it is given), and the assertions go through the app's own HTTP and WebSocket endpoints, as its lifecycle tests do. What needs eyes on a screen goes to the coordinator or the owner as a written procedure in your hand-back.
56667
58063
  - **Shared numbers and names come from \`armada reserve\`, never a guess**: a migration number, a port, a fixture name. \`armada reserve db-migration --next --floor <last number used on main>\` prints the next free number; \`--value <name>\` takes a name; a key alone takes an exclusive resource. \`armada reserve --list\` shows the holders. Reservations end when you release, stay used after merge, and \`armada unreserve <key>\` frees yours early. After a lost answer, list before retrying. If Armada is down, ask the coordinator before choosing.
56668
58064
  - **Long runs go through \`armada job\`, never in your session**: an evaluation, a backfill, a load test. \`armada job start <name> --ticket <id>\` dispatches one of the project's \`[jobs.<name>]\` on its own runner; \`armada job status\` asks the runner, \`armada job list\` reads stored progress, \`armada job stop <id>\` stops it. You only see your own ticket's jobs. Unchanged progress past \`[jobs.<name>] stall_minutes\` (60 by default) alerts the coordinator as \`job-stalled\`; keep reporting meaningful progress. Nothing is stopped for you.
56669
58065
  - **Secrets come from Armada**, never from your launch environment; \`armada secrets\` lists their names. Run commands that need them with \`armada run -- <command>\` (tests, builds, dev servers): the values reach that command only, and its output is masked. A tool that reads a dotenv file gets \`armada secrets export --file <path>\`, at a path git ignores. A secret you need and do not have: \`armada ask --secret <NAME> "<why>"\`; the coordinator sends the owner a link to set it, and tells you when to re-run. Never ask for a value in chat; a value pasted anywhere must be rotated.
56670
58066
  - **Your tool output is your transcript.** Never print environment variables (\`env\`, \`printenv\`, \`echo $VAR\`), process lists with their arguments (\`ps -ef\`, \`ps aux\`, \`/proc/*/environ\`), or credential files, and never run \`armada secrets get\`. Never commit or log a secret. Masking is a safety net, not permission: values under eight characters and encoded values are not masked.
56671
- - **Evidence goes through Armada, not git.** For every visible change, capture screenshots under a gitignored folder, then \`armada attach <ticket> <files|https-urls>... --caption "<what to check>"\`, and link the printed private URLs in the pull request. Images are PNG, JPEG, WebP or GIF, 2 MB each.
58067
+ - **Evidence goes through Armada, not git.** For every visible change, capture screenshots under a gitignored folder (from a headless browser or the app's own offscreen capture, never the owner's screen), then \`armada attach <ticket> <files|https-urls>... --caption "<what to check>"\`, and link the printed private URLs in the pull request. Images are PNG, JPEG, WebP or GIF, 2 MB each.
56672
58068
 
56673
58069
  ## Report vocabulary
56674
58070
 
@@ -61073,7 +62469,7 @@ ${attachments.join(`
61073
62469
  };
61074
62470
  }
61075
62471
  // package.json
61076
- var version2 = "0.2.69";
62472
+ var version2 = "0.2.71";
61077
62473
 
61078
62474
  // src/io.ts
61079
62475
  class UsageError extends Error {
@@ -62493,13 +63889,14 @@ async function preflight(io, branch) {
62493
63889
  const root = io.coordinatorRoot ?? io.cwd;
62494
63890
  if (!branch)
62495
63891
  return "cannot push worker branch: the claim has no branch";
63892
+ const gitTimeoutMs = 20000;
62496
63893
  for (const [action, args] of [
62497
- ["fetch origin", ["ls-remote", "origin", "HEAD"]],
62498
- [`push ${branch}`, ["push", "--dry-run", "origin", `HEAD:refs/heads/${branch}`]]
63894
+ ["ls-remote origin HEAD", ["ls-remote", "origin", "HEAD"]],
63895
+ [`push --dry-run origin HEAD:refs/heads/${branch}`, ["push", "--dry-run", "origin", `HEAD:refs/heads/${branch}`]]
62499
63896
  ]) {
62500
63897
  const result = await io.exec("git", [...args], {
62501
63898
  cwd: root,
62502
- timeoutMs: 1e4,
63899
+ timeoutMs: gitTimeoutMs,
62503
63900
  maxOutputBytes: 16384,
62504
63901
  processGroup: true,
62505
63902
  env: { ...io.env, GIT_TERMINAL_PROMPT: "0" }
@@ -62507,7 +63904,7 @@ async function preflight(io, branch) {
62507
63904
  if (!result)
62508
63905
  return `cannot ${action}: git could not be run`;
62509
63906
  if (result.timedOut)
62510
- return `cannot ${action}: timed out after 10 seconds`;
63907
+ return `cannot ${action}: timed out after ${gitTimeoutMs / 1000} seconds`;
62511
63908
  if (result.outputExceeded)
62512
63909
  return `cannot ${action}: Git output exceeded the check's limit`;
62513
63910
  if (result.code !== 0) {
@@ -71211,18 +72608,19 @@ class TransportUnavailable extends Error {
71211
72608
 
71212
72609
  class BeforeConnect extends TransportUnavailable {
71213
72610
  }
71214
- var commands = new Set(["claim", "report", "heartbeat", "ask", "release"]);
72611
+ var commands = new Set(["ticket", "claim", "report", "heartbeat", "ask", "release"]);
71215
72612
  async function localWorker(io, args) {
71216
72613
  if (!commands.has(args.command) || !io.env.ARMADA_WORKER_SOCKET && !io.env.ARMADA_WORKER_TOKEN)
71217
72614
  return null;
71218
72615
  const expected = args.command === "claim" || args.command === "report" ? 1 : 0;
71219
- if (args.command === "ask" ? args.rest.length > 1 : args.rest.length !== expected)
71220
- throw new UsageError(`local ${args.command} takes ${expected} positional arguments`);
72616
+ const optionalArgument = args.command === "ask" || args.command === "ticket";
72617
+ if (optionalArgument ? args.rest.length > 1 : args.rest.length !== expected)
72618
+ throw new UsageError(`local ${args.command} takes ${optionalArgument ? "at most one positional argument" : `${expected} positional arguments`}`);
71221
72619
  const socketPath = io.env.ARMADA_WORKER_SOCKET;
71222
72620
  const token = io.env.ARMADA_WORKER_TOKEN;
71223
72621
  if (!socketPath || !token)
71224
72622
  throw new UsageError("local worker requires its issued socket and token");
71225
- const ticket = args.options.ticket ?? (args.command === "claim" ? args.rest[0] : undefined) ?? io.env.ARMADA_TICKET;
72623
+ const ticket = args.options.ticket ?? (args.command === "claim" || args.command === "ticket" ? args.rest[0] : undefined) ?? io.env.ARMADA_TICKET;
71226
72624
  if (!ticket)
71227
72625
  throw new UsageError("local worker needs its ticket");
71228
72626
  const now = () => (io.now?.() ?? new Date).getTime();
@@ -71246,23 +72644,34 @@ async function localWorker(io, args) {
71246
72644
  "Content-Type": "application/json"
71247
72645
  }
71248
72646
  }, (res) => {
71249
- if (res.statusCode !== 200) {
72647
+ const scopeRefusal = args.command === "ticket" && res.statusCode === 409;
72648
+ if (res.statusCode !== 200 && !scopeRefusal) {
71250
72649
  reject(new Error("Local worker authorization refused or generation ended"));
71251
72650
  res.on("error", () => {});
71252
72651
  res.destroy();
71253
72652
  return;
71254
72653
  }
71255
72654
  let output = "";
72655
+ let bytes = 0;
72656
+ const limit = args.command === "ticket" && !scopeRefusal ? 16 * 1024 * 1024 : 65536;
72657
+ res.setEncoding("utf8");
71256
72658
  res.on("data", (chunk) => {
72659
+ bytes += Buffer.byteLength(chunk);
72660
+ if (bytes > limit) {
72661
+ reject(new Error(args.command === "ticket" ? "Local ticket response exceeds 16 MiB" : "Invalid local worker response"));
72662
+ req.destroy();
72663
+ return;
72664
+ }
71257
72665
  output += chunk;
71258
- if (output.length > 65536)
71259
- req.destroy(new Error("Invalid local worker response"));
71260
72666
  });
71261
72667
  res.on("end", () => {
71262
- if (res.statusCode !== 200)
71263
- return reject(new Error("Local worker authorization refused or generation ended"));
71264
72668
  try {
71265
- resolve(JSON.parse(output));
72669
+ const result = JSON.parse(output);
72670
+ if (scopeRefusal) {
72671
+ const own = result.ticket;
72672
+ return reject(new Error(result.code === "ticket-scope" && typeof own === "string" && own.length <= 200 && !/[\r\n]/.test(own) ? `your capability is for ${own}` : "Local worker authorization refused or generation ended"));
72673
+ }
72674
+ resolve(result);
71266
72675
  } catch {
71267
72676
  reject(new Error("Invalid local worker response"));
71268
72677
  }
@@ -71398,11 +72807,42 @@ Options: ${args.options.options}`;
71398
72807
  return 0;
71399
72808
  }
71400
72809
  const result = await call(body);
71401
- io.stdout(args.json ? `${JSON.stringify(result)}
72810
+ if (args.command === "ticket") {
72811
+ const detail = result;
72812
+ if (!detail.ticket || typeof detail.ticket.title !== "string")
72813
+ throw new Error("Invalid local ticket response");
72814
+ io.stdout(args.json ? `${JSON.stringify(detail.ticket)}
72815
+ ` : renderTicket(detail));
72816
+ } else
72817
+ io.stdout(args.json ? `${JSON.stringify(result)}
71402
72818
  ` : `${ticket}: ${args.command} recorded by the local daemon.
71403
72819
  `);
71404
72820
  return 0;
71405
72821
  }
72822
+ function renderTicket({ ticket, parent, internal }) {
72823
+ const lines = [
72824
+ `# ${ticket.id} — ${ticket.title}`,
72825
+ "",
72826
+ `State: ${ticket.status}`,
72827
+ `Labels: ${ticket.labels?.join(", ") || "none"}`,
72828
+ `Parent: ${parent ? `${parent.id} — ${parent.title} (${parent.status})` : ticket.parent ? `${ticket.parent} (state unavailable)` : "none"}`,
72829
+ `Blockers: ${ticket.blockers?.map((blocker) => `${blocker.id} (${blocker.status})`).join(", ") || "none"}`,
72830
+ "",
72831
+ "## Description",
72832
+ "",
72833
+ ticket.description ?? "",
72834
+ "",
72835
+ "## Comments",
72836
+ ""
72837
+ ];
72838
+ for (const comment of ticket.comments ?? [])
72839
+ lines.push(`### ${comment.author} — ${comment.at}`, "", comment.body, "");
72840
+ if (!internal && ticket.url)
72841
+ lines.push(`older comments are in Linear: [${ticket.id}](${ticket.url})`, "");
72842
+ return `${lines.join(`
72843
+ `).trimEnd()}
72844
+ `;
72845
+ }
71406
72846
 
71407
72847
  // src/peek.ts
71408
72848
  function requirePeekCoordinator(credentials) {
@@ -71672,8 +73112,8 @@ import { fileURLToPath, pathToFileURL as pathToFileURL2 } from "node:url";
71672
73112
  init_dist();
71673
73113
  init_guard();
71674
73114
  import assert from "node:assert/strict";
71675
- import { execFile as execFile4 } from "node:child_process";
71676
- import { randomUUID as randomUUID8 } from "node:crypto";
73115
+ import { execFile as execFile5 } from "node:child_process";
73116
+ import { randomUUID as randomUUID9 } from "node:crypto";
71677
73117
  import { copyFile, mkdir as mkdir5, readFile as readFile7, rm as rm7, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
71678
73118
  import { join as join16, relative as relative5 } from "node:path";
71679
73119
  import { setTimeout as delay3 } from "node:timers/promises";
@@ -80223,13 +81663,51 @@ var originalGenerateCallId = createIdGenerator2({
80223
81663
  var project = "plugin-conformance";
80224
81664
  var ticket = "CHECK-1";
80225
81665
  var head = "0123456789abcdef0123456789abcdef01234567";
80226
- var execute3 = promisify2(execFile4);
81666
+ var execute3 = promisify2(execFile5);
80227
81667
  async function runSeamChecks(options) {
80228
81668
  for (const seam of SEAMS) {
80229
81669
  for (const kind of Object.keys(options.manifest.contributions[seam] ?? {})) {
80230
81670
  const name = `${seam}.${kind}`;
80231
81671
  if (seam === "tracker" || seam === "forge") {
80232
81672
  const provider = options.registry.get(seam, kind);
81673
+ let trackerTicket = ticket;
81674
+ let created = false;
81675
+ if (seam === "tracker") {
81676
+ const tracker = options.registry.get("tracker", kind);
81677
+ if (!tracker?.create)
81678
+ options.skip?.(`${name}.create`, "not implemented");
81679
+ else {
81680
+ created = await options.check(`${name}.create`, async (signal) => {
81681
+ const result = await tracker.create({
81682
+ project,
81683
+ title: "Conformance ticket",
81684
+ description: "Created through the tracker seam",
81685
+ labels: ["ready-for-agent"],
81686
+ signal
81687
+ });
81688
+ assert(result.id, "create did not return a ticket identifier");
81689
+ trackerTicket = result.id;
81690
+ await tracker.read({ project, signal });
81691
+ assert(options.events.some((event) => event.project === project && (event.kind === "ticket.created" || event.kind === "ticket.seen") && contains(event.payload, { id: result.id, title: "Conformance ticket" })), "create did not make the ticket readable");
81692
+ });
81693
+ }
81694
+ if (!tracker?.update)
81695
+ options.skip?.(`${name}.update`, "not implemented");
81696
+ else if (created)
81697
+ await options.check(`${name}.update`, async (signal) => {
81698
+ await tracker.update({
81699
+ project,
81700
+ ticket: trackerTicket,
81701
+ patch: { title: "Edited conformance ticket", labels: ["ready-for-agent", "implementing"] },
81702
+ signal
81703
+ });
81704
+ await tracker.read({ project, signal });
81705
+ assert(options.events.some((event) => event.project === project && (event.kind === "ticket.edited" && contains(event.payload, {
81706
+ ticket: trackerTicket,
81707
+ patch: { title: "Edited conformance ticket" }
81708
+ }) || event.kind === "ticket.seen" && contains(event.payload, { id: trackerTicket, title: "Edited conformance ticket" }))), "update did not make the patch readable");
81709
+ });
81710
+ }
80233
81711
  const ready = await options.check(`${name}.read-events`, async () => {
80234
81712
  assert(provider, "provider was not registered");
80235
81713
  const recording = JSON.parse(await readFile7(join16(options.fixtureRoot, seam, "response.json"), "utf8"));
@@ -80245,26 +81723,32 @@ async function runSeamChecks(options) {
80245
81723
  const eventStart = options.events.length;
80246
81724
  const requestStart = options.requests.length;
80247
81725
  await provider.read({ project, signal: AbortSignal.timeout(4000) });
81726
+ if (created && options.requests.length === requestStart && options.events.length === eventStart)
81727
+ return;
80248
81728
  assertContact(options, requestStart, seam);
80249
81729
  for (const expected of recording.expectedEvents) {
80250
- assert(options.events.slice(eventStart).some((event) => event.project === project && event.kind === expected.kind && contains(event.payload, expected.payload)), `read did not append the recorded ${expected.kind} payload for ${project}`);
81730
+ assert(options.events.slice(created ? 0 : eventStart).some((event) => event.project === project && event.kind === expected.kind && contains(event.payload, expected.payload)), `read did not append the recorded ${expected.kind} payload for ${project}`);
80251
81731
  }
80252
81732
  });
80253
81733
  if (!ready)
80254
81734
  continue;
80255
81735
  if (seam === "tracker") {
80256
81736
  await options.check(`${name}.write`, async () => {
80257
- const comment = `conformance-write-${randomUUID8()}`;
81737
+ const comment = `conformance-write-${randomUUID9()}`;
80258
81738
  const start = options.requests.length;
81739
+ const eventStart = options.events.length;
80259
81740
  await options.registry.get("tracker", kind)?.write({
80260
81741
  project,
80261
- ticket,
81742
+ ticket: trackerTicket,
80262
81743
  phase: "implementing",
80263
81744
  comment,
80264
81745
  signal: AbortSignal.timeout(4000)
80265
81746
  });
80266
81747
  const writes = writeRequests(options, start, seam);
80267
- assert([comment, "implementing", ticket].every((value) => writes.some((request) => `${request.path} ${JSON.stringify(request.body)}`.includes(value))), "write did not send its unique comment to the fixture");
81748
+ assert([comment, "implementing", trackerTicket].every((value) => writes.some((request) => `${request.path} ${JSON.stringify(request.body)}`.includes(value))) || options.events.slice(eventStart).some((event) => event.project === project && event.kind === "ticket.commented" && contains(event.payload, { ticket: trackerTicket, body: comment })) && options.events.slice(eventStart).some((event) => event.project === project && event.kind === "ticket.edited" && contains(event.payload, {
81749
+ ticket: trackerTicket,
81750
+ patch: { labels: ["ready-for-agent", "implementing"] }
81751
+ })), "write did not record its phase and unique comment");
80268
81752
  });
80269
81753
  } else {
80270
81754
  await options.check(`${name}.merge`, async () => {
@@ -80379,7 +81863,7 @@ async function workerChecks(options, seam, kind) {
80379
81863
  "-m",
80380
81864
  "Initialize fixture"
80381
81865
  ]);
80382
- const branch = `${fixture.branchPrefix}-${randomUUID8()}`;
81866
+ const branch = `${fixture.branchPrefix}-${randomUUID9()}`;
80383
81867
  workspace = await provider.prepare({
80384
81868
  project,
80385
81869
  ticket,
@@ -80407,10 +81891,43 @@ async function workerChecks(options, seam, kind) {
80407
81891
  });
80408
81892
  if (!launched || !worker || !workspace || !provider)
80409
81893
  return;
81894
+ if (seam === "runtime" && ["claude", "codex", "opencode"].includes(kind) && hostNode && await stat2(join16(options.directory, `${kind}-worker.mjs`)).then(() => true, () => false)) {
81895
+ await options.check(`${name}.permissions`, async (signal) => {
81896
+ assert(provider && workspace);
81897
+ const native = await provider.launch({
81898
+ workspace,
81899
+ worker: { project, ticket, session: randomUUID9(), generation: 1 },
81900
+ command: "",
81901
+ args: [],
81902
+ env: { FAKE_AUTH: "yes" }
81903
+ });
81904
+ try {
81905
+ await provider.deliver(native, "permission-check", randomUUID9());
81906
+ let reply = "";
81907
+ await poll(provider, native, (observation) => {
81908
+ reply = observation.reply ?? "";
81909
+ return reply.includes("permission-check");
81910
+ }, undefined, signal);
81911
+ const launched = JSON.parse(reply);
81912
+ if (kind === "claude")
81913
+ assert.equal(launched.args[launched.args.indexOf("--permission-mode") + 1], "bypassPermissions");
81914
+ else if (kind === "codex") {
81915
+ assert(launched.args.includes('approval_policy="never"'));
81916
+ assert(launched.args.includes('sandbox_mode="workspace-write"'));
81917
+ assert(launched.args.includes("sandbox_workspace_write.network_access=true"));
81918
+ } else if (kind === "opencode")
81919
+ assert.deepEqual(launched.permission, { "*": "allow" });
81920
+ else
81921
+ throw new Error("Unknown native permission fixture");
81922
+ } finally {
81923
+ await provider.stop(native);
81924
+ }
81925
+ });
81926
+ }
80410
81927
  await options.check(`${name}.deliver`, async (signal) => {
80411
81928
  assert(worker);
80412
- const nonce = `nonce-${randomUUID8()}`;
80413
- await provider.deliver(worker, nonce, randomUUID8());
81929
+ const nonce = `nonce-${randomUUID9()}`;
81930
+ await provider.deliver(worker, nonce, randomUUID9());
80414
81931
  await poll(provider, worker, (observation) => observation.reply?.includes(`ARMADA_CONFORMANCE_ACK:${nonce}`) === true, undefined, signal);
80415
81932
  });
80416
81933
  const stopped = await options.check(`${name}.stop`, async () => {
@@ -80429,7 +81946,7 @@ async function workerChecks(options, seam, kind) {
80429
81946
  }, signal);
80430
81947
  await poll(provider, worker, (observation) => observation.state === "running" && observation.reply?.includes("ARMADA_CONFORMANCE_READY") === true, deadline, signal);
80431
81948
  signal.throwIfAborted();
80432
- await provider.deliver(worker, "exit", randomUUID8());
81949
+ await provider.deliver(worker, "exit", randomUUID9());
80433
81950
  await poll(provider, worker, (observation) => observation.state === "stopped", deadline, signal);
80434
81951
  });
80435
81952
  } finally {
@@ -80447,7 +81964,7 @@ async function workerChecks(options, seam, kind) {
80447
81964
  }
80448
81965
  }
80449
81966
  async function launchWorker2(options, provider, workspace, remember, signal) {
80450
- const session = randomUUID8();
81967
+ const session = randomUUID9();
80451
81968
  const worker = await provider.launch({
80452
81969
  workspace,
80453
81970
  worker: { project, ticket, session, generation: 1 },
@@ -80481,7 +81998,7 @@ async function poll(provider, worker, accepted, deadline = Date.now() + 3500, si
80481
81998
  throw new Error(`worker observation did not reach the expected state (last state: ${state})`);
80482
81999
  }
80483
82000
  async function hostedWorkerChecks(options, provider, name) {
80484
- const worker = { project, ticket, session: randomUUID8(), generation: 1 };
82001
+ const worker = { project, ticket, session: randomUUID9(), generation: 1 };
80485
82002
  let ref;
80486
82003
  await options.check(`${name}.hosted-lifecycle`, async () => {
80487
82004
  const workspace = await provider.prepare({
@@ -80497,13 +82014,13 @@ async function hostedWorkerChecks(options, provider, name) {
80497
82014
  command: "",
80498
82015
  args: [],
80499
82016
  env: {},
80500
- brief: `armada login --launch-token armada_launch_${randomUUID8()} --api-url https://example.invalid`
82017
+ brief: `armada login --launch-token armada_launch_${randomUUID9()} --api-url https://example.invalid`
80501
82018
  }));
80502
82019
  assert.equal(ref.session, worker.session);
80503
82020
  assert.equal(ref.generation, worker.generation);
80504
82021
  assert.equal((await provider.observe(ref)).state, "running");
80505
82022
  const current = ref;
80506
- const key = randomUUID8();
82023
+ const key = randomUUID9();
80507
82024
  await guarded2(current, () => {}, () => provider.deliver(current, "Continue fixture", key));
80508
82025
  await guarded2(current, () => {}, () => provider.deliver(current, "Continue fixture", key));
80509
82026
  await assert.rejects(guarded2(current, () => {
@@ -80655,9 +82172,19 @@ async function testPlugin(io, path, reportPath, json = false) {
80655
82172
  events.push(event);
80656
82173
  return structuredClone(event);
80657
82174
  },
82175
+ appendWith: async (project, build) => {
82176
+ await Promise.resolve().then(() => init_src11());
82177
+ const tables = fold(events.filter((e) => e.project === project));
82178
+ const inputs = build(tables).map((input) => pluginEventInputSchema.parse(input));
82179
+ if (inputs.some((input) => input.project !== project))
82180
+ throw new Error("appendWith project mismatch");
82181
+ const appended = inputs.map((input, i) => ({ ...input, seq: events.length + i + 1 }));
82182
+ events.push(...appended);
82183
+ return structuredClone(appended);
82184
+ },
80658
82185
  read: async (project, after) => structuredClone(events.filter((e) => e.project === project && e.seq > after)),
80659
82186
  fold: async (project) => {
80660
- await Promise.resolve().then(() => init_src10());
82187
+ await Promise.resolve().then(() => init_src11());
80661
82188
  return fold(events.filter((e) => e.project === project));
80662
82189
  }
80663
82190
  },
@@ -80685,6 +82212,12 @@ async function testPlugin(io, path, reportPath, json = false) {
80685
82212
  endpoint,
80686
82213
  requests,
80687
82214
  nodeCommand: "node",
82215
+ skip: (name, reason) => {
82216
+ report.checks.push({ name, passed: false, skipped: reason });
82217
+ if (!json)
82218
+ io.stdout(`SKIP ${name}: ${reason}
82219
+ `);
82220
+ },
80688
82221
  check: async (name, action) => {
80689
82222
  const result = { name, passed: false };
80690
82223
  try {
@@ -80808,7 +82341,7 @@ ${"─".repeat(60)}
80808
82341
  }
80809
82342
 
80810
82343
  // src/relaunch.ts
80811
- import { randomUUID as randomUUID9 } from "node:crypto";
82344
+ import { randomUUID as randomUUID10 } from "node:crypto";
80812
82345
  import { basename as basename4, dirname as dirname14, join as join18 } from "node:path";
80813
82346
  async function relaunch(io, config, credentials, args, version, configPath) {
80814
82347
  const [input, ...extra] = args.rest;
@@ -80944,7 +82477,7 @@ async function relaunch(io, config, credentials, args, version, configPath) {
80944
82477
  });
80945
82478
  prepared.spec.from = mode === "in-place" ? { kind: "in-place", previous: old } : head ? { kind: "branch", head } : { kind: "base" };
80946
82479
  if (mode === "fresh" && prepared.local) {
80947
- const suffix = randomUUID9().slice(0, 8);
82480
+ const suffix = randomUUID10().slice(0, 8);
80948
82481
  const configHome = io.env.XDG_CONFIG_HOME ?? (io.env.HOME ? join18(io.env.HOME, ".config") : null);
80949
82482
  const path = io.env.HERDR_CONFIG_PATH ?? (configHome ? join18(configHome, "herdr", "config.toml") : null);
80950
82483
  const text = path ? await io.readFile(path).catch(() => null) : null;
@@ -81025,7 +82558,7 @@ async function relaunch(io, config, credentials, args, version, configPath) {
81025
82558
  }
81026
82559
  Object.assign(prepared.briefInput, await reservationsForBrief(() => fleet.reservations(), config.reservations.length > 0));
81027
82560
  if (mode === "fresh" && old.runtime === "herdr" && !remoteHerdr && workspace?.ready && oldRuntime instanceof HerdrAdapter) {
81028
- const retained = `armada-retained/${ticket.toLowerCase()}-${randomUUID9().slice(0, 8)}`;
82561
+ const retained = `armada-retained/${ticket.toLowerCase()}-${randomUUID10().slice(0, 8)}`;
81029
82562
  try {
81030
82563
  old = await guarded(fleet, old, "ended", () => oldRuntime.retainBranch(old, retained), {
81031
82564
  allowHistorical: true
@@ -81081,7 +82614,7 @@ ${worker.watch.line}
81081
82614
  if (dry)
81082
82615
  return replace();
81083
82616
  return withLaunchLease(io, fleet, ticket, async (launchLease) => {
81084
- const holder = `relaunch:${randomUUID9()}`;
82617
+ const holder = `relaunch:${randomUUID10()}`;
81085
82618
  const lock = { name: MERGE_LEASE, holder, ttlMs: 5 * 60000, throughHold: `relaunch exclusion: ${reason}` };
81086
82619
  if (!(await fleet.acquireLease(lock)).acquired)
81087
82620
  throw new UsageError(`${ticket}: a merge is in progress; nothing was changed`, `armada relaunch ${ticket} --reason "<why>"`);
@@ -81606,6 +83139,67 @@ ${created.url}
81606
83139
  return 0;
81607
83140
  }
81608
83141
 
83142
+ // src/tickets.ts
83143
+ init_dist2();
83144
+ import { randomUUID as randomUUID11 } from "node:crypto";
83145
+ async function importTickets(io, rest, project, address) {
83146
+ if (rest.length !== 2 || rest[0] !== "import" || !rest[1]?.trim() || !project)
83147
+ throw new UsageError("armada tickets import <program-root> --project <id>");
83148
+ const endpoint = address ?? io.env.ARMADA_DAEMON_URL;
83149
+ if (!endpoint)
83150
+ throw new UsageError("Set ARMADA_DAEMON_URL to the running daemon's loopback URL, or pass --api-url <url>");
83151
+ let url;
83152
+ try {
83153
+ url = new URL(endpoint);
83154
+ } catch {
83155
+ throw new UsageError("The daemon URL must be a loopback HTTP or WebSocket URL");
83156
+ }
83157
+ if (!["http:", "ws:"].includes(url.protocol) || url.hostname !== "127.0.0.1" || url.username || url.password || url.pathname !== "/" || url.search || url.hash)
83158
+ throw new UsageError("The daemon URL must be a loopback HTTP or WebSocket URL");
83159
+ url.protocol = "ws:";
83160
+ const id = randomUUID11();
83161
+ return new Promise((resolve, reject) => {
83162
+ const socket = new WebSocket(url);
83163
+ let importId;
83164
+ let settled = false;
83165
+ const finish = (error, code = 1) => {
83166
+ if (settled)
83167
+ return;
83168
+ settled = true;
83169
+ clearTimeout(timer);
83170
+ socket.close();
83171
+ if (error)
83172
+ reject(error);
83173
+ else
83174
+ resolve(code);
83175
+ };
83176
+ const timer = setTimeout(() => finish(new UsageError("Import did not finish within 60 seconds; check its progress in the room before retrying")), 60000);
83177
+ socket.addEventListener("open", () => socket.send(JSON.stringify({ version: PROTOCOL_VERSION, id, type: "tracker.import", project, programRoot: rest[1] })));
83178
+ socket.addEventListener("error", () => finish(new UsageError("Cannot reach the Armada daemon; start the app and check ARMADA_DAEMON_URL")));
83179
+ socket.addEventListener("close", () => finish(new UsageError("Daemon connection closed; check import progress in the room before retrying")));
83180
+ socket.addEventListener("message", (message) => {
83181
+ try {
83182
+ const frame = JSON.parse(String(message.data));
83183
+ if (frame.type === "error")
83184
+ return finish(new UsageError(typeof frame.message === "string" ? frame.message : "Daemon refused the import"));
83185
+ if (frame.type === "tracker.import.result" && frame.id === id && frame.project === project) {
83186
+ importId = frame.importId;
83187
+ socket.send(JSON.stringify({ version: PROTOCOL_VERSION, id: `${id}:progress`, type: "project.subscribe", project, after: 0 }));
83188
+ }
83189
+ const parsed = trackerImportSchema.safeParse(frame.snapshot?.state?.trackerImport);
83190
+ if (!parsed.success || parsed.data.id !== importId || parsed.data.state === "running")
83191
+ return;
83192
+ const result = parsed.data;
83193
+ io.stdout(`Linear import ${rest[1]}: ${result.state}; ${result.imported} imported, ${result.skipped} skipped, ${result.comments} comments${result.pausedUntil ? `; paused until ${result.pausedUntil}` : ""}${result.error ? `; ${result.error}` : ""}
83194
+ `);
83195
+ finish(undefined, result.state === "completed" ? 0 : 1);
83196
+ } catch {
83197
+ finish(new UsageError("Invalid daemon import response; check progress in the room"));
83198
+ }
83199
+ });
83200
+ });
83201
+ }
83202
+
81609
83203
  // src/upgrade.ts
81610
83204
  var ATTEMPTS = 5;
81611
83205
  var WAIT_MS = 30000;
@@ -81828,6 +83422,18 @@ async function done(io, config, credentials, a) {
81828
83422
 
81829
83423
  // src/cli.ts
81830
83424
  var COMMAND_HELP = {
83425
+ tickets: ` tickets import <program-root> --project <id> [--api-url <url>]
83426
+ Import Linear into an internal project through the running daemon.
83427
+ ARMADA_DAEMON_URL supplies its loopback URL. No Linear writes.
83428
+ `,
83429
+ worker: ` worker Show the worker protocol commands:
83430
+ ticket [<id>] [--json]: read your ticket through its local capability
83431
+ claim, report, heartbeat, ask, release: work with the daemon
83432
+ `,
83433
+ ticket: ` ticket [<id>] Read your capability's ticket from the local daemon as Markdown.
83434
+ Defaults to ARMADA_TICKET; another ticket is refused.
83435
+ --json prints the protocol Ticket. No tracker or credential read.
83436
+ `,
81831
83437
  plugin: ` plugin list [--json]
81832
83438
  plugin enable|disable <id>
81833
83439
  List bundled plugins or change a switch (restart the daemon to apply).
@@ -82263,6 +83869,7 @@ var CONFIG_OPTION = new Set([
82263
83869
  "upgrade"
82264
83870
  ]);
82265
83871
  var JSON_OPTION = new Set([
83872
+ "ticket",
82266
83873
  "peek",
82267
83874
  "skills",
82268
83875
  ...[...CONFIG_OPTION].filter((c) => c !== "run" && c !== "attach" && c !== "upgrade"),
@@ -82438,6 +84045,7 @@ var FLAG_OPTIONS = [
82438
84045
  "rerun"
82439
84046
  ];
82440
84047
  var COMMAND_OPTIONS = {
84048
+ tickets: ["api-url"],
82441
84049
  plugin: ["report"],
82442
84050
  acceptance: ["ticket", "name", "runs", "reason"],
82443
84051
  doctor: ["deep"],
@@ -82728,9 +84336,18 @@ async function dispatch(argv, io) {
82728
84336
  args.options.all = "true";
82729
84337
  if (args.passthrough && args.command !== "run")
82730
84338
  throw new UsageError(`-- does not apply to ${args.command}: only \`armada run\` runs a command`);
84339
+ if (args.command === "tickets")
84340
+ return await importTickets(io, args.rest, args.project, args.options["api-url"]);
82731
84341
  const local = await localWorker(io, { ...args, command: args.command });
82732
84342
  if (local !== null)
82733
84343
  return local;
84344
+ if (args.command === "worker") {
84345
+ noExtra(args.rest);
84346
+ io.stdout(commandHelp("worker"));
84347
+ return 0;
84348
+ }
84349
+ if (args.command === "ticket")
84350
+ throw new UsageError("armada ticket requires a local worker capability");
82734
84351
  if (args.command === "plugin")
82735
84352
  return await pluginCommand(io, args.rest, args.json, args.options.report);
82736
84353
  if (args.command === "secrets" || args.command === "run") {