wildcrane-runner 0.6.111 → 0.6.112

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/runner.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.111 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.112 — built by runner/scripts/build.mjs. Do not edit.
2
2
  import { createRequire as __ai4kanbanRequire } from 'node:module'
3
3
  const require = __ai4kanbanRequire(import.meta.url)
4
4
  var __create = Object.create;
@@ -152742,8 +152742,6 @@ function machineId() {
152742
152742
  var machineName = () => os3.hostname().replace(/\.local$/, "");
152743
152743
 
152744
152744
  // ../runner/src/i18n.ts
152745
- var ZH_HOLDER = { "claude-code": "Claude Code", codex: "Codex", cursor: "Cursor", dsh: "dsh", zcode: "ZCode", kimi: "Kimi Code", terminal: "\u672C\u673A\u7EC8\u7AEF" };
152746
- var EN_HOLDER = { "claude-code": "Claude Code", codex: "Codex", cursor: "Cursor", dsh: "dsh", zcode: "ZCode", kimi: "Kimi Code", terminal: "the terminal" };
152747
152745
  var ZH = {
152748
152746
  signIn: (url2) => `\u8BF7\u5728\u6D4F\u89C8\u5668\u4E2D\u767B\u5F55 WildCrane\uFF1A
152749
152747
  ${url2}`,
@@ -152758,10 +152756,7 @@ ${url2}`,
152758
152756
  updated: (version2) => `\u5DF2\u66F4\u65B0\u5230 ${version2}`,
152759
152757
  rolledBack: (version2) => `\u65B0\u7248\u672C\u672A\u80FD\u542F\u52A8\uFF0C\u5DF2\u9000\u56DE ${version2}`,
152760
152758
  nodeTooOld: (range) => `\u65B0\u7248\u672C\u9700\u8981 Node ${range}\uFF0C\u8BF7\u5347\u7EA7 Node\u3002\u672C\u6B21\u7EE7\u7EED\u4F7F\u7528\u5F53\u524D\u7248\u672C\u3002`,
152761
- waitingHere: (holder) => {
152762
- const who = holder ? ZH_HOLDER[holder] : "\u672C\u673A\u53E6\u4E00\u4E2A\u7A0B\u5E8F";
152763
- return `${who}\u5DF2\u5728\u8FD0\u884C\u4E00\u4E2A WildCrane \u5B9E\u4F8B\uFF0C\u8D1F\u8D23\u63A5\u6536\u6240\u6709\u8FD0\u884C\u4EFB\u52A1\u3002\u5F53\u524D\u5B9E\u4F8B\u5DF2\u6682\u505C\uFF0C${who}\u5173\u95ED\u540E\u5C06\u7531\u5F53\u524D\u5B9E\u4F8B\u63A5\u66FF\u3002`;
152764
- },
152759
+ alreadyRunning: () => "\u672C\u673A\u5DF2\u6709 WildCrane Runner \u6B63\u5728\u8FD0\u884C\uFF0C\u65E0\u6CD5\u542F\u52A8\u7B2C\u4E8C\u4E2A\u5B9E\u4F8B\u3002",
152765
152760
  stopped: () => "\u5DF2\u505C\u6B62"
152766
152761
  };
152767
152762
  var EN = {
@@ -152778,10 +152773,7 @@ ${url2}`,
152778
152773
  updated: (version2) => `Updated to ${version2}`,
152779
152774
  rolledBack: (version2) => `The new version did not start \u2014 back on ${version2}`,
152780
152775
  nodeTooOld: (range) => `The new version needs Node ${range}. Update Node; running the current version for now.`,
152781
- waitingHere: (holder) => {
152782
- const who = holder ? EN_HOLDER[holder] : "another app on this computer";
152783
- return `${who[0].toUpperCase()}${who.slice(1)} is already running a WildCrane instance that takes all run tasks. This instance is paused and takes over when ${who} closes.`;
152784
- },
152776
+ alreadyRunning: () => "A WildCrane Runner is already running on this computer. A second instance cannot start.",
152785
152777
  stopped: () => "Stopped"
152786
152778
  };
152787
152779
  function isChinese(env2 = process.env) {
@@ -152799,12 +152791,13 @@ function status(line) {
152799
152791
  }
152800
152792
 
152801
152793
  // ../runner/src/protocol.ts
152802
- var VERSION = true ? "0.6.111" : "0.0.0";
152803
- var AKB_VERSION = true ? "0.11.91" : "0.0.0";
152794
+ var VERSION = true ? "0.6.112" : "0.0.0";
152795
+ var AKB_VERSION = true ? "0.11.92" : "0.0.0";
152804
152796
  var AKB_CONTRACT = true ? 30 : 0;
152805
152797
  var EXIT_REFUSED = 10;
152806
152798
  var EXIT_OUTDATED = 11;
152807
152799
  var EXIT_UPDATE = 12;
152800
+ var EXIT_ALREADY_RUNNING = 13;
152808
152801
 
152809
152802
  // ../runner/src/runtimes.ts
152810
152803
  import { spawn as spawn2 } from "node:child_process";
@@ -153689,23 +153682,27 @@ function retryBudget(file3, initialAttempt = 1) {
153689
153682
  try {
153690
153683
  const saved = fs11.readFileSync(file3, "utf8");
153691
153684
  const used = Number(saved);
153692
- return /^\d+$/.test(saved) && Number.isSafeInteger(used) && used <= MAX_RETRY_ATTEMPTS ? Math.max(used + 1, initialAttempt) : MAX_RETRY_ATTEMPTS + 1;
153685
+ return /^\d+$/.test(saved) && Number.isSafeInteger(used) && used <= MAX_RETRY_ATTEMPTS ? used + 1 : MAX_RETRY_ATTEMPTS + 1;
153693
153686
  } catch (error62) {
153694
- if (error62.code === "ENOENT") return initialAttempt;
153687
+ if (error62.code === "ENOENT") return 1;
153695
153688
  throw error62;
153696
153689
  }
153697
153690
  };
153698
- const take = () => {
153691
+ const update3 = (advance) => {
153699
153692
  fs11.mkdirSync(path12.dirname(file3), { recursive: true, mode: 448 });
153700
153693
  return withLock(file3 + ".lock", "recording a task retry", () => {
153701
- const next = attempt() + 1;
153694
+ const current2 = attempt();
153695
+ const next = advance(current2);
153702
153696
  if (next > MAX_RETRY_ATTEMPTS + 1) return;
153703
- fs11.writeFileSync(file3 + ".tmp", String(next - 1), { mode: 384 });
153704
- fs11.renameSync(file3 + ".tmp", file3);
153697
+ if (next !== current2) {
153698
+ fs11.writeFileSync(file3 + ".tmp", String(next - 1), { mode: 384 });
153699
+ fs11.renameSync(file3 + ".tmp", file3);
153700
+ }
153705
153701
  return next;
153706
153702
  });
153707
153703
  };
153708
- return { attempt, take };
153704
+ if (initialAttempt > 1) update3((current2) => Math.max(current2, initialAttempt));
153705
+ return { attempt, take: () => update3((current2) => current2 + 1) };
153709
153706
  }
153710
153707
  function retryRecord(failure3, attempt, runtime, sessionAction) {
153711
153708
  const { source: source2, summary: summary2, detail, code } = failure3;
@@ -154374,7 +154371,7 @@ function createTail(log) {
154374
154371
  // ../cli/package.json
154375
154372
  var package_default = {
154376
154373
  name: "wildcrane",
154377
- version: "0.11.91",
154374
+ version: "0.11.92",
154378
154375
  akbContract: 30,
154379
154376
  canonicalCommands: true,
154380
154377
  description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
@@ -155386,11 +155383,11 @@ function checkHarnesses(harnesses) {
155386
155383
  }
155387
155384
  }
155388
155385
  }
155389
- const probe2 = harness.login;
155390
- if (probe2) {
155391
- if (!probe2.args.length) throw new Error(`harness "${harness.name}": its login probe runs no arguments`);
155392
- if (!probe2.login.trim()) throw new Error(`harness "${harness.name}": its login probe names no command that logs the user back in`);
155393
- if (probe2.ready("") || probe2.loggedOut("")) {
155386
+ const probe3 = harness.login;
155387
+ if (probe3) {
155388
+ if (!probe3.args.length) throw new Error(`harness "${harness.name}": its login probe runs no arguments`);
155389
+ if (!probe3.login.trim()) throw new Error(`harness "${harness.name}": its login probe names no command that logs the user back in`);
155390
+ if (probe3.ready("") || probe3.loggedOut("")) {
155394
155391
  throw new Error(`harness "${harness.name}": its login probe reads empty output as an answer \u2014 a probe that couldn't run has to say nothing`);
155395
155392
  }
155396
155393
  }
@@ -179254,7 +179251,7 @@ var secretsSet = () => Object.fromEntries(Object.entries(readAll()).map(([id2, k
179254
179251
 
179255
179252
  // ../runner/src/api.ts
179256
179253
  var RUNTIMES = ["claude-code", "codex", "cursor", "opencode", "kimi", "dsh", "zcode", "grok", "antigravity"];
179257
- var PROTOCOL = 30;
179254
+ var PROTOCOL = 31;
179258
179255
  var TIMEOUT_MS = 2e4;
179259
179256
  async function send(method, route, body, signedIn, ms, type, extra = {}) {
179260
179257
  const headers = { accept: "application/json", ...extra };
@@ -179693,12 +179690,12 @@ function claudeModels(dir) {
179693
179690
  });
179694
179691
  }
179695
179692
  function probeLogin(binary, harness) {
179696
- const probe2 = harness.login;
179693
+ const probe3 = harness.login;
179697
179694
  return new Promise((resolve2) => {
179698
179695
  let output3 = "";
179699
179696
  let child;
179700
179697
  try {
179701
- const start = spawnable(binary, probe2.args, { stdio: ["ignore", "pipe", "pipe"], env: copyEnv(binary) });
179698
+ const start = spawnable(binary, probe3.args, { stdio: ["ignore", "pipe", "pipe"], env: copyEnv(binary) });
179702
179699
  child = spawn2(start.command, start.args, start.options);
179703
179700
  } catch {
179704
179701
  return resolve2(void 0);
@@ -179706,13 +179703,13 @@ function probeLogin(binary, harness) {
179706
179703
  const timer = setTimeout(() => {
179707
179704
  child.kill();
179708
179705
  resolve2(void 0);
179709
- }, probe2.timeoutMs ?? LOGIN_PROBE_MS);
179706
+ }, probe3.timeoutMs ?? LOGIN_PROBE_MS);
179710
179707
  child.stdout?.on("data", (d2) => output3 += d2);
179711
179708
  child.stderr?.on("data", (d2) => output3 += d2);
179712
179709
  child.on("error", () => resolve2(void 0));
179713
179710
  child.on("close", () => {
179714
179711
  clearTimeout(timer);
179715
- resolve2(probe2.ready(output3) ? true : probe2.loggedOut(output3) ? false : void 0);
179712
+ resolve2(probe3.ready(output3) ? true : probe3.loggedOut(output3) ? false : void 0);
179716
179713
  });
179717
179714
  });
179718
179715
  }
@@ -184351,7 +184348,7 @@ function pull(ws, machineId2, stopped2, mode) {
184351
184348
  return { ok: false, error: `This computer's board changes could not be sent: ${refused2.error}`, ...refused2.offline ? {} : { code: sent.conflict ? "board_content_conflict" : refused2.code ?? "version_conflict" } };
184352
184349
  }
184353
184350
  }
184354
- const read6 = await readCloud(ws, !!validation, taskChat);
184351
+ const read6 = await prepareTask(ws, !!validation, taskChat);
184355
184352
  if (!read6.ok && read6.code === "board_content_conflict") {
184356
184353
  const prepared = await prepareConflictTask(ws);
184357
184354
  if (!prepared.ok) return prepared;
@@ -184406,42 +184403,54 @@ function syncedCardVersion(ws) {
184406
184403
  const card = Object.entries(base.files).find(([p2]) => p2.startsWith(rootOf(ws) + "todo/") && numberOfCard(p2.slice(rootOf(ws).length)) === ws.number);
184407
184404
  return card?.[1].seq ?? null;
184408
184405
  }
184406
+ function syncedArchive(ws) {
184407
+ const p2 = path49.relative(ws.board, cardFile(ws));
184408
+ if (!p2.startsWith(".archive/")) return;
184409
+ const base = readBase(ws);
184410
+ const root2 = rootOf(ws);
184411
+ const card = base.files[root2 + p2];
184412
+ const list3 = assetsFile(ws.task);
184413
+ const assets = base.files[root2 + list3];
184414
+ if (!card || !archiveMeta(card.content) || card.content !== readText(path49.join(ws.board, p2)) || (assets?.content ?? null) !== readText(path49.join(ws.board, list3)) || base.pendingAssets?.includes(ws.task) || base.pendingPreviews?.some((held5) => held5 === p2 || held5 === list3)) return;
184415
+ return { path: p2, seq: card.seq, assets_seq: assets?.seq ?? 0 };
184416
+ }
184409
184417
  var readHead = (ws) => readBase(ws).head_seq;
184418
+ function restoredCards(ws, base, files) {
184419
+ const root2 = rootOf(ws);
184420
+ return files.flatMap(({ path: remote3, content, seq }) => {
184421
+ if (!remote3.startsWith(root2 + "todo/") || !content) return [];
184422
+ const p2 = remote3.slice(root2.length);
184423
+ const number4 = numberOfCard(p2);
184424
+ const stamp3 = /^restored:\s*(.+)$/m.exec(content)?.[1];
184425
+ const before = base.files[remote3]?.content;
184426
+ if (number4 === null || !stamp3 || before && /^restored:\s*(.+)$/m.exec(before)?.[1] === stamp3) return [];
184427
+ return [{ path: p2, number: number4, content, seq }];
184428
+ });
184429
+ }
184410
184430
  function applyRestorations(ws, base, files) {
184411
184431
  const restored = /* @__PURE__ */ new Set();
184412
184432
  const root2 = rootOf(ws);
184413
- const protectedPaths = new Set(pendingConflicts(ws.board).flatMap((r2) => r2.files.map((f2) => f2.path)));
184414
- for (const f2 of files) {
184415
- if (protectedPaths.has(f2.path.startsWith(root2) ? f2.path.slice(root2.length) : f2.path)) continue;
184416
- if (!f2.path.startsWith(root2 + "todo/") || !f2.content) continue;
184417
- const p2 = f2.path.slice(root2.length);
184418
- const number4 = numberOfCard(p2);
184419
- const stamp3 = /^restored:\s*(.+)$/m.exec(f2.content)?.[1];
184420
- if (number4 === null || !stamp3 || base.files[f2.path]?.content === f2.content) continue;
184421
- const old = Object.entries(base.files).find(([name]) => name.startsWith(root2) && numberOfCard(name.slice(root2.length)) === number4);
184422
- if (old && old[0] === f2.path && /^restored:\s*(.+)$/m.exec(old[1].content)?.[1] === stamp3) continue;
184433
+ for (const { path: p2, number: number4, content, seq } of restoredCards(ws, base, files)) {
184423
184434
  for (const local of ["todo", ".archive"].flatMap((dir) => filesUnder(path49.join(ws.board, dir), ws.board))) {
184424
184435
  if (numberOfCard(local) !== number4) continue;
184425
184436
  const here2 = readText(path49.join(ws.board, local));
184426
- if (here2 !== null && here2 !== base.files[root2 + local]?.content && here2 !== f2.content) {
184427
- write(path49.join(ws.board, ".sync", "restored", String(f2.seq), local), here2);
184437
+ if (here2 !== null && here2 !== base.files[root2 + local]?.content && here2 !== content) {
184438
+ write(path49.join(ws.board, ".sync", "restored", String(seq), local), here2);
184428
184439
  }
184429
184440
  restored.add(local);
184430
184441
  if (local !== p2) fs46.rmSync(path49.join(ws.board, local), { force: true });
184431
184442
  }
184432
- write(path49.join(ws.board, p2), f2.content);
184443
+ write(path49.join(ws.board, p2), content);
184433
184444
  restored.add(p2);
184434
184445
  }
184435
184446
  return restored;
184436
184447
  }
184437
- function observeConflicts(ws, base, files) {
184438
- const shared = sharedMemory(ws.board);
184448
+ function observeConflicts(ws, base, files, shared) {
184439
184449
  const root2 = rootOf(ws);
184440
184450
  const pending = new Set(base.pendingPreviews);
184441
184451
  const conflicting = files.some((f2) => {
184442
- const own4 = f2.path.startsWith(root2);
184443
- const p2 = own4 ? f2.path.slice(root2.length) : f2.path;
184444
- if (pending.has(p2) || !kept3(p2) || (p2.startsWith(MEMORY2) && shared(p2.slice(MEMORY2.length))) !== !own4) return false;
184452
+ const p2 = f2.path.startsWith(root2) ? f2.path.slice(root2.length) : f2.path;
184453
+ if (pending.has(p2) || !kept3(p2) || remoteOf(ws, shared, p2) !== f2.path) return false;
184445
184454
  return !!mergeFile(base.files[f2.path]?.content ?? null, readText(path49.join(ws.board, p2)), f2.content).conflict;
184446
184455
  });
184447
184456
  if (!conflicting) return false;
@@ -184478,51 +184487,75 @@ var pullChanges = (ws) => inFolder(ws.cwd, async () => {
184478
184487
  if (base.head_seq === null) return { ok: true, value: void 0 };
184479
184488
  const read6 = await readBoard(ws.project, base.head_seq);
184480
184489
  if (!read6.ok) return read6;
184481
- const shared = sharedMemory(ws.board);
184490
+ const result = await reconcileBoard(ws, base, read6.value, sharedMemory(ws.board));
184491
+ return result.ok ? { ok: true, value: void 0 } : result;
184492
+ });
184493
+ async function reconcileBoard(ws, base, board, shared, taskChat) {
184482
184494
  const root2 = rootOf(ws);
184483
184495
  if (pendingConflicts(ws.board).length) return { ok: false, code: "board_content_conflict", error: "Resolve the saved board content conflicts before refreshing." };
184484
- applyRestorations(ws, base, read6.value.files);
184485
- if (observeConflicts(ws, base, read6.value.files)) return { ok: false, code: "board_content_conflict", error: "Resolve the saved board content conflicts before refreshing." };
184496
+ const restored = applyRestorations(ws, base, board.files);
184497
+ const snapshot = base.head_seq === null ? base.files : void 0;
184498
+ if (!snapshot && observeConflicts(ws, base, board.files, shared)) return { ok: false, code: "board_content_conflict", error: "Resolve the saved board content conflicts before refreshing." };
184499
+ if (snapshot) base.files = {};
184500
+ const index = syncIndex(ws);
184501
+ const paths = [];
184502
+ const removed = [];
184486
184503
  let skipped = false;
184487
- for (const f2 of read6.value.files) {
184504
+ for (const f2 of board.files) {
184488
184505
  const p2 = f2.path.startsWith(root2) ? f2.path.slice(root2.length) : f2.path;
184489
- const index = syncIndex(ws);
184506
+ paths.push(p2);
184490
184507
  if (index) rememberDirectories(index.directories, p2);
184491
- const isShared = p2.startsWith(MEMORY2) && shared(p2.slice(MEMORY2.length));
184492
- if (kept3(p2) && isShared === !f2.path.startsWith(root2)) {
184508
+ if (!snapshot && kept3(p2) && remoteOf(ws, shared, p2) === f2.path) {
184493
184509
  const file3 = path49.join(ws.board, p2);
184494
184510
  const here2 = readText(file3);
184495
- if (here2 !== f2.content && here2 !== (base.files[f2.path]?.content ?? null)) {
184496
- skipped = true;
184497
- continue;
184511
+ if (here2 !== f2.content) {
184512
+ if (!restored.has(p2) && here2 !== (base.files[f2.path]?.content ?? null)) {
184513
+ skipped = true;
184514
+ continue;
184515
+ }
184516
+ if (f2.content === null) fs46.rmSync(file3, { force: true });
184517
+ else write(file3, f2.content);
184498
184518
  }
184499
- if (f2.content === null) fs46.rmSync(file3, { force: true });
184500
- else if (here2 !== f2.content) write(file3, f2.content);
184501
184519
  }
184502
184520
  base.deleted ??= {};
184503
184521
  if (f2.content === null) {
184504
184522
  delete base.files[f2.path];
184505
184523
  base.deleted[f2.path] = f2.seq;
184524
+ removed.push(f2.path);
184506
184525
  } else {
184507
184526
  base.files[f2.path] = { seq: f2.seq, content: f2.content };
184508
184527
  delete base.deleted[f2.path];
184509
184528
  }
184510
184529
  }
184511
- if (!skipped) base.head_seq = read6.value.head_seq;
184530
+ if (snapshot) {
184531
+ for (const p2 of Object.keys(snapshot)) if (!base.files[p2]) removed.push(p2);
184532
+ resetBoardSnapshot(ws, base, snapshot, shared);
184533
+ }
184534
+ if (!skipped) base.head_seq = board.head_seq;
184535
+ base.project = ws.project;
184512
184536
  writeBase(ws, base);
184513
184537
  writeIndex(ws.board);
184514
- await cleanRecords(ws, base, {
184515
- removed: read6.value.files.filter((f2) => f2.content === null).map((f2) => f2.path),
184516
- tasks: syncIndex(ws)?.ready ? affectedTasks(ws, read6.value.files.map((f2) => f2.path.startsWith(root2) ? f2.path.slice(root2.length) : f2.path)) : void 0
184517
- });
184518
- return { ok: true, value: void 0 };
184519
- });
184520
- async function readCloud(ws, preserveAssets, taskChat) {
184521
- if (pendingConflicts(ws.board).length) return { ok: false, code: "board_content_conflict", error: "Resolve the saved board content conflicts before refreshing." };
184538
+ const tasks = index?.ready ? affectedTasks(ws, paths) : void 0;
184539
+ if (ws.cloudTask === ws.task) tasks?.add(ws.task);
184540
+ return { ok: true, value: await cleanRecords(ws, base, { removed, tasks, taskChat }) };
184541
+ }
184542
+ function resetBoardSnapshot(ws, base, before, shared) {
184543
+ const root2 = rootOf(ws);
184544
+ const deferred = new Set(base.deferred);
184545
+ const view = viewOf(ws, base, shared);
184546
+ for (const p2 of /* @__PURE__ */ new Set([...localFiles(ws, base), ...view.keys()])) {
184547
+ if (!kept3(p2)) continue;
184548
+ const file3 = path49.join(ws.board, p2);
184549
+ const here2 = readText(file3);
184550
+ const content = view.get(p2) ?? null;
184551
+ const previous = before[root2 + p2];
184552
+ if (here2 === content || here2 !== (previous?.content ?? null) && (deferred.has(p2) || previous && content === null && p2.startsWith(".archive/"))) continue;
184553
+ if (content !== null) write(file3, content);
184554
+ else if (previous || !isSettingsPath(p2)) fs46.rmSync(file3, { force: true });
184555
+ }
184556
+ }
184557
+ async function prepareTask(ws, preserveAssets, taskChat) {
184522
184558
  const base = readBase(ws);
184523
- const previous = { ...base.files };
184524
- const known2 = new Set(Object.keys(base.files));
184525
- const keepDraft = new Set((base.deferred ?? []).filter((p2) => readText(path49.join(ws.board, p2)) !== (base.files[rootOf(ws) + p2]?.content ?? null)));
184526
184559
  if (base.workspace === void 0) {
184527
184560
  const project = await readProject(ws.project);
184528
184561
  if (!project.ok) return project;
@@ -184530,54 +184563,23 @@ async function readCloud(ws, preserveAssets, taskChat) {
184530
184563
  }
184531
184564
  const read6 = await readBoard(ws.project, base.head_seq);
184532
184565
  if (!read6.ok) return read6;
184533
- const restored = applyRestorations(ws, base, read6.value.files);
184534
- if (base.head_seq !== null && observeConflicts(ws, base, read6.value.files)) return { ok: false, code: "board_content_conflict", error: "Resolve the saved board content conflicts before refreshing." };
184535
- const dirty = new Set(base.head_seq === null ? [] : [.../* @__PURE__ */ new Set([...localFiles(ws, base), ...viewOf(ws, base, sharedMemory(ws.board)).keys()])].filter((p2) => !restored.has(p2) && readText(path49.join(ws.board, p2)) !== (previous[remoteOf(ws, sharedMemory(ws.board), p2)]?.content ?? null)));
184536
- for (const p2 of dirty) keepDraft.add(p2);
184537
- if (base.head_seq === null) base.files = {};
184538
- for (const f2 of read6.value.files) {
184539
- const local = f2.path.startsWith(rootOf(ws)) ? f2.path.slice(rootOf(ws).length) : f2.path;
184540
- if (dirty.has(local)) continue;
184541
- base.deleted ??= {};
184542
- if (f2.content === null) {
184543
- delete base.files[f2.path];
184544
- base.deleted[f2.path] = f2.seq;
184545
- } else {
184546
- base.files[f2.path] = { seq: f2.seq, content: f2.content };
184547
- delete base.deleted[f2.path];
184548
- }
184549
- }
184550
- const removed = [...known2].filter((p2) => !base.files[p2]);
184551
- for (const p2 of removed) {
184552
- const local = p2.startsWith(rootOf(ws)) ? p2.slice(rootOf(ws).length) : p2;
184553
- if (local.startsWith(".archive/") && readText(path49.join(ws.board, local)) !== null && readText(path49.join(ws.board, local)) !== previous[p2]?.content) keepDraft.add(local);
184554
- }
184555
- if (!dirty.size) base.head_seq = read6.value.head_seq;
184556
- base.project = ws.project;
184557
- writeBase(ws, base);
184558
- const reset = (view2) => {
184559
- for (const [p2, content] of view2) {
184560
- const file3 = path49.join(ws.board, p2);
184561
- if (!keepDraft.has(p2) && kept3(p2) && readText(file3) !== content) write(file3, content);
184562
- }
184563
- };
184564
- const view = viewOf(ws, base, sharedMemory(ws.board));
184565
- const first = (p2) => isSettingsPath(p2) && !known2.has(rootOf(ws) + p2);
184566
- for (const p2 of localFiles(ws, base)) if (!keepDraft.has(p2) && !view.has(p2) && !first(p2)) fs46.rmSync(path49.join(ws.board, p2), { force: true });
184567
- reset(view);
184568
- const retired = await cleanRecords(ws, base, { removed, taskChat });
184569
- if (retired.has(ws.task)) {
184570
- writeIndex(ws.board);
184571
- return { ok: true, value: void 0 };
184572
- }
184566
+ const shared = sharedMemory(ws.board);
184567
+ const refreshed = await reconcileBoard(ws, base, read6.value, shared, taskChat);
184568
+ if (!refreshed.ok) return refreshed;
184569
+ if (refreshed.value.has(ws.task)) return { ok: true, value: void 0 };
184573
184570
  const record2 = readRecord(ws);
184574
184571
  const studio = await pullStudio(ws, record2);
184575
184572
  if (!studio.ok) return studio;
184576
- reset(viewOf(ws, base, sharedMemory(ws.board)));
184573
+ const studioShared = sharedMemory(ws.board);
184574
+ const previousView = viewOf(ws, base, shared);
184575
+ for (const [p2, content] of viewOf(ws, base, studioShared)) {
184576
+ if (!kept3(p2) || !p2.startsWith(MEMORY2) || remoteOf(ws, studioShared, p2) === remoteOf(ws, shared, p2)) continue;
184577
+ const file3 = path49.join(ws.board, p2);
184578
+ if (readText(file3) === (previousView.get(p2) ?? null) && previousView.get(p2) !== content) write(file3, content);
184579
+ }
184577
184580
  const assets = await pullAssets(ws, record2, assetsOf(assetsListOf(ws, base)), preserveAssets);
184578
184581
  if (!assets.ok) return assets;
184579
184582
  writeRecord(ws, record2);
184580
- writeIndex(ws.board);
184581
184583
  return { ok: true, value: void 0 };
184582
184584
  }
184583
184585
  function writeIndex(board) {
@@ -185204,7 +185206,7 @@ function affectedTasks(ws, paths) {
185204
185206
  }
185205
185207
  return tasks;
185206
185208
  }
185207
- async function send2(ws, job, { paths, taskChat }) {
185209
+ async function send2(ws, job, { paths, taskChat }, retryRestore = true) {
185208
185210
  const record2 = readRecord(ws);
185209
185211
  const base = readBase(ws);
185210
185212
  const fail = (error62, conflict = false, code, status2) => ({ ok: false, conflict, error: error62, code, ...temporaryCloudFailure({ code, status: status2 }) ? { offline: true } : {} });
@@ -185444,6 +185446,16 @@ async function send2(ws, job, { paths, taskChat }) {
185444
185446
  let sent = await commit();
185445
185447
  if (sent === null) return success2(false);
185446
185448
  if (!sent.ok && sent.files) {
185449
+ const root2 = rootOf(ws);
185450
+ const deletedCards = new Set(sent.files.filter((f2) => f2.content === null && f2.path.startsWith(root2)).map((f2) => numberOfCard(f2.path.slice(root2.length))).filter((number4) => number4 !== null));
185451
+ if (boardSync && retryRestore && deletedCards.size) {
185452
+ const read6 = await readBoard(ws.project, base.head_seq);
185453
+ if (read6.ok && restoredCards(ws, base, read6.value.files).some((card) => deletedCards.has(card.number))) {
185454
+ const refreshed = await reconcileBoard(ws, base, read6.value, shared, taskChat);
185455
+ if (!refreshed.ok) return conflictFailure(ws);
185456
+ return send2(ws, job, { paths, taskChat }, false);
185457
+ }
185458
+ }
185447
185459
  for (const f2 of sent.files) if (stale2.has(f2.path)) {
185448
185460
  const at2 = changes.findIndex((c2) => c2.path === f2.path);
185449
185461
  if (at2 >= 0) changes.splice(at2, 1);
@@ -187850,7 +187862,7 @@ function crossRefComplaints() {
187850
187862
  }
187851
187863
  return said;
187852
187864
  }
187853
- function reconcileBoard() {
187865
+ function reconcileBoard2() {
187854
187866
  if (!fs59.existsSync(README)) return;
187855
187867
  for (const line of [...readmeComplaints(true), ...crossRefComplaints()]) warn2(line);
187856
187868
  }
@@ -187967,7 +187979,7 @@ function cmdCreate(opts) {
187967
187979
  );
187968
187980
  if ((scaffolded || written) && !TODO_ITEM.test(body)) warn2(`#${start} has no todos \u2014 every task needs a \`- [ ]\` list under ## Todo`);
187969
187981
  if (indexed) say(` indexed under "## ${TASKS_HEADING}"`);
187970
- reconcileBoard();
187982
+ reconcileBoard2();
187971
187983
  return { id: start, ids: [start], title, file: rel(file3), indexed };
187972
187984
  }
187973
187985
  function sourceFlag(said, flag) {
@@ -189061,6 +189073,10 @@ function syncRefusal(job, failure3) {
189061
189073
  }
189062
189074
  }
189063
189075
  var retryableSync = (failure3) => !failure3.failure && temporaryCloudFailure(failure3);
189076
+ function writeBlock(failure3) {
189077
+ if (failure3.code === "daily_write_budget_reached") return "allowance";
189078
+ if (failure3.code === "storage_limit_reached" || failure3.code === "quota_exceeded" && failure3.status !== 413 && /free up space/i.test(failure3.error)) return "storage";
189079
+ }
189064
189080
 
189065
189081
  // ../runner/src/saved-previews.ts
189066
189082
  var remote2 = /^(?:[a-z][\w+.-]*:|\/|#)/i;
@@ -189570,8 +189586,15 @@ function boardAkb(job, ws, deps, io, task) {
189570
189586
  async function setUp(job, ws, deps, io) {
189571
189587
  const akb = boardAkb(job, ws, deps, io);
189572
189588
  const runtime = job.runtime;
189573
- const missing = io.flowRun?.finished ? void 0 : unavailable(runtime, await deps.runtimes());
189574
- if (missing) return missing;
189589
+ const replayingReceipt = job.flow?.verify_delivery?.confirmed === true;
189590
+ if (!io.flowRun?.finished && !replayingReceipt) {
189591
+ let missing = unavailable(runtime, await deps.runtimes());
189592
+ if (missing?.endsWith(" is not signed in on this computer.") && io.waitForLogin) {
189593
+ if (!await io.waitForLogin()) return stopping(io) ? "" : missing;
189594
+ missing = unavailable(runtime, await deps.runtimes());
189595
+ }
189596
+ if (missing) return missing;
189597
+ }
189575
189598
  if (!fs71.existsSync(path72.join(ws.board, "config.md"))) {
189576
189599
  const init = await akb(["raw", "init"]);
189577
189600
  if (init.code !== 0) return refusal3(init);
@@ -189794,7 +189817,7 @@ async function runFlow(job, ws, deps, io) {
189794
189817
  }
189795
189818
  if (action === "implement") {
189796
189819
  if (!reviewAllows(authorization, action)) return "Finish the agreed review stages before delivery.";
189797
- if (!dispatchedReview && flow.review_revision !== void 0 && flow.review_revision !== review.revision) {
189820
+ if (flow.review_revision !== void 0 && (flow.verify_delivery ? flow.review_revision !== current2.value.review?.revision : !dispatchedReview && flow.review_revision !== review.revision)) {
189798
189821
  return "Review authorization changed. Read the task again.";
189799
189822
  }
189800
189823
  }
@@ -189909,8 +189932,37 @@ ${pictures(job, ws, ws.number)}`);
189909
189932
  const held5 = working.get(key) ?? 0;
189910
189933
  working.set(key, held5 + 1);
189911
189934
  try {
189912
- const reconciled = !io.flowRun && !held5 && existedBeforeCreate ? await reconcileDelivery(card) : void 0;
189935
+ const verification = flow.verify_delivery;
189936
+ if (verification) {
189937
+ const denied = await refreshReview("implement");
189938
+ if (denied) return fail(denied);
189939
+ if (stopping(io)) return fail("");
189940
+ if (verification.confirmed && verification.id) {
189941
+ return { ok: true, report: {
189942
+ card,
189943
+ deliveryId: verification.id,
189944
+ deliveryCompleted: true,
189945
+ ...verification.landing ? { landing: verification.landing } : {}
189946
+ } };
189947
+ }
189948
+ }
189949
+ const reconciled = (!io.flowRun || verification) && !held5 && existedBeforeCreate ? await reconcileDelivery(card) : void 0;
189913
189950
  if (io.lost()) return fail("");
189951
+ if (verification) {
189952
+ const saved = await flowRunEvidence(ws, job, deps, flow.sync_recovery_of, io.flowRun);
189953
+ const receipt = reconciled && "deliveryId" in reconciled ? reconciled.deliveryId : void 0;
189954
+ const expected = verification.id ?? saved.run?.deliveryId;
189955
+ if (!saved.stopped || !expected || receipt !== expected || reconciled?.kind !== "completed" && (reconciled?.kind !== "resumable" || !saved.run || saved.run.id !== reconciled.sessionId || !reconciled.hasSession)) {
189956
+ const reason = reconciled?.kind === "unverified" ? reconciled.diagnostic : "No delivery receipt or safe session matches the original run.";
189957
+ return { ok: false, reason, failure: makeFailure("sync", reason, { code: "task_delivery_unverified" }) };
189958
+ }
189959
+ if (reconciled.kind === "resumable") {
189960
+ io.flowRun = saved.run;
189961
+ io.repairDelivery = true;
189962
+ io.diagnostic = "Verify the original delivery using the Studio delivery requirements and the saved results. Record the existing result once you confirm it. Do not repeat land or publish when the earlier result is already in place.";
189963
+ return workOn(card, reconciled);
189964
+ }
189965
+ }
189914
189966
  if (reconciled?.kind === "unverified") {
189915
189967
  io.show(`[recovery] delivery reconciliation unverified${reconciled.deliveryId ? ` (delivery ${reconciled.deliveryId})` : ""}: ${reconciled.diagnostic}
189916
189968
  `);
@@ -190410,101 +190462,82 @@ import crypto8 from "node:crypto";
190410
190462
  import fs73 from "node:fs";
190411
190463
  import net from "node:net";
190412
190464
  import path74 from "node:path";
190413
- var RETRY_MS2 = 5e3;
190414
- var KIND_MS = 1e3;
190415
- var HOLDERS = ["claude-code", "codex", "cursor", "dsh", "zcode", "kimi", "terminal"];
190465
+ var RunnerAlreadyRunning = class extends Error {
190466
+ };
190416
190467
  function lockPath() {
190417
190468
  const home4 = runnerHome();
190418
190469
  if (process.platform === "win32") return `\\\\.\\pipe\\wildcrane-${crypto8.createHash("sha256").update(home4).digest("hex").slice(0, 16)}`;
190419
190470
  return path74.join(home4, "runner.sock");
190420
190471
  }
190421
- function holdMachine(kind, onHeld, onWaiting) {
190472
+ function socketIdentity(file3) {
190473
+ try {
190474
+ const stat2 = fs73.lstatSync(file3, { bigint: true });
190475
+ if (stat2.isSocket()) return `${stat2.dev}:${stat2.ino}`;
190476
+ } catch (error62) {
190477
+ if (error62.code !== "ENOENT") throw error62;
190478
+ }
190479
+ }
190480
+ function probe2(file3) {
190481
+ return new Promise((resolve2) => {
190482
+ const socket = net.connect(file3);
190483
+ const finish = (code) => {
190484
+ socket.destroy();
190485
+ resolve2(code);
190486
+ };
190487
+ socket.setTimeout(1e3, () => finish());
190488
+ socket.once("connect", () => finish());
190489
+ socket.once("error", (error62) => finish(error62.code));
190490
+ });
190491
+ }
190492
+ async function acquireMachine(kind) {
190422
190493
  const where = lockPath();
190423
- let closed = false;
190424
- let server = null;
190425
- let waiting = null;
190426
- let timer = null;
190494
+ const unix = process.platform !== "win32";
190495
+ let unlock;
190496
+ if (unix) {
190497
+ fs73.mkdirSync(path74.dirname(where), { recursive: true, mode: 448 });
190498
+ unlock = tryLock(`${where}.owner`);
190499
+ if (!unlock) throw new RunnerAlreadyRunning();
190500
+ }
190427
190501
  const peers = /* @__PURE__ */ new Set();
190428
- const later = (ms) => {
190429
- if (!closed) timer = setTimeout(attempt, ms);
190430
- };
190431
- const attempt = () => {
190432
- timer = null;
190433
- if (closed) return;
190434
- if (process.platform !== "win32") fs73.mkdirSync(path74.dirname(where), { recursive: true, mode: 448 });
190435
- const s = net.createServer((peer) => {
190502
+ const listen = () => new Promise((resolve2, reject) => {
190503
+ const server = net.createServer((peer) => {
190436
190504
  peers.add(peer);
190437
190505
  peer.on("error", () => {
190438
190506
  }).on("close", () => peers.delete(peer));
190439
190507
  peer.write(`${JSON.stringify({ kind, settings: 1 })}
190440
190508
  `);
190441
190509
  });
190442
- s.once("error", (e2) => {
190443
- if (e2.code !== "EADDRINUSE") return later(RETRY_MS2);
190444
- const probe2 = net.connect(where);
190445
- probe2.once("connect", () => {
190446
- waiting = probe2;
190447
- let told = false;
190448
- let said = "";
190449
- const tell2 = (holder) => {
190450
- if (told || waiting !== probe2) return;
190451
- told = true;
190452
- clearTimeout(silent);
190453
- onWaiting?.(holder);
190454
- };
190455
- const silent = setTimeout(tell2, KIND_MS);
190456
- probe2.on("data", (d2) => {
190457
- said += d2;
190458
- const line = said.split("\n");
190459
- if (line.length < 2) return;
190460
- let got;
190461
- try {
190462
- got = JSON.parse(line[0]).kind;
190463
- } catch {
190464
- }
190465
- tell2(typeof got === "string" && HOLDERS.includes(got) ? got : void 0);
190466
- });
190467
- probe2.once("close", () => {
190468
- clearTimeout(silent);
190469
- waiting = null;
190470
- later(0);
190471
- });
190472
- });
190473
- probe2.once("error", () => {
190474
- if (waiting === probe2) return;
190475
- if (process.platform !== "win32") {
190476
- const removeIfStill = net.connect(where);
190477
- removeIfStill.once("connect", () => {
190478
- removeIfStill.destroy();
190479
- later(0);
190480
- });
190481
- removeIfStill.once("error", () => {
190482
- fs73.rmSync(where, { force: true });
190483
- later(50 + Math.random() * 200);
190484
- });
190485
- return;
190486
- }
190487
- later(RETRY_MS2);
190488
- });
190510
+ server.once("error", reject);
190511
+ server.listen(where, () => {
190512
+ server.off("error", reject);
190513
+ resolve2(server);
190489
190514
  });
190490
- s.listen(where, () => {
190491
- if (closed) return void s.close();
190492
- server = s;
190493
- onHeld();
190515
+ });
190516
+ try {
190517
+ const server = await listen().catch(async (error62) => {
190518
+ if (error62.code !== "EADDRINUSE") throw error62;
190519
+ if (!unix) throw new RunnerAlreadyRunning();
190520
+ const identity = socketIdentity(where);
190521
+ const result = await probe2(where);
190522
+ if (result === "ECONNREFUSED" && identity !== void 0 && identity === socketIdentity(where)) fs73.unlinkSync(where);
190523
+ else if (result !== "ENOENT") throw new RunnerAlreadyRunning();
190524
+ return listen().catch((retry2) => {
190525
+ if (retry2.code === "EADDRINUSE") throw new RunnerAlreadyRunning();
190526
+ throw retry2;
190527
+ });
190494
190528
  });
190495
- };
190496
- attempt();
190497
- return {
190498
- waited: () => peers.size > 0,
190499
- release() {
190500
- if (closed) return;
190501
- closed = true;
190502
- if (timer) clearTimeout(timer);
190503
- waiting?.destroy();
190504
- server?.close();
190529
+ let closing;
190530
+ return () => closing ??= new Promise((resolve2) => {
190531
+ server.close(() => {
190532
+ unlock?.();
190533
+ resolve2();
190534
+ });
190505
190535
  for (const peer of peers) peer.destroy();
190506
- }
190507
- };
190536
+ });
190537
+ } catch (error62) {
190538
+ unlock?.();
190539
+ throw error62;
190540
+ }
190508
190541
  }
190509
190542
  function runnerSettingsSupport() {
190510
190543
  return new Promise((resolve2) => {
@@ -191065,7 +191098,7 @@ var RECONNECT_MS = [1e3, 2e3, 5e3, 1e4, 3e4];
191065
191098
  var RENEW_MS = 5 * 6e4;
191066
191099
  var LOG_PING_MS = 3e4;
191067
191100
  var LEASE_MS = 15 * 6e4;
191068
- var RETRY_MS3 = 3e4;
191101
+ var RETRY_MS2 = 3e4;
191069
191102
  var KILL_GRACE_MS = 5e3;
191070
191103
  var WATCH_MS = 1e3;
191071
191104
  var STOP_MS = 1e4;
@@ -191079,7 +191112,7 @@ var defaultDeps = (machineId2) => ({
191079
191112
  endMs: END_MS,
191080
191113
  renewMs: RENEW_MS,
191081
191114
  leaseMs: LEASE_MS,
191082
- retryMs: RETRY_MS3,
191115
+ retryMs: RETRY_MS2,
191083
191116
  testMs: TEST_MS,
191084
191117
  stopMs: STOP_MS,
191085
191118
  watchMs: WATCH_MS,
@@ -191446,10 +191479,18 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191446
191479
  delete checkpoint.ending;
191447
191480
  delete checkpoint.retryHistory;
191448
191481
  }
191482
+ const verification = job.flow?.verify_delivery;
191483
+ if (verification && !local) {
191484
+ delete checkpoint.ending;
191485
+ delete checkpoint.syncFailure;
191486
+ if (checkpoint.completed?.outcome !== "done" || !verification.confirmed || checkpoint.completed.report.deliveryId !== verification.id) {
191487
+ delete checkpoint.completed;
191488
+ }
191489
+ }
191449
191490
  checkpoint.retryRound ??= manual && !local ? id2 : sourceId ?? id2;
191450
191491
  const retryFile2 = retryFileOf(checkpoint.retryRound);
191451
191492
  const legacyAttempt = Math.max(
191452
- 1,
191493
+ 1 + Math.max(job.flow?.recovery_attempts ?? 0, manual ? 0 : verification?.attempts ?? 0),
191453
191494
  manual && !local ? 1 : checkpoint.retry?.attempt ?? 1,
191454
191495
  ...Object.values(checkpoint.syncRetries ?? {}).map((retry3) => retry3?.attempt ?? 1),
191455
191496
  checkpoint.reconcileRetry?.attempt ?? 1
@@ -191521,6 +191562,10 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191521
191562
  }
191522
191563
  const retries2 = retryHistory(report2);
191523
191564
  if (outcome === "done" && retries2.length) report2 = { ...report2, retries: retries2 };
191565
+ const recoveryAttempts = budget.attempt() - 1;
191566
+ if (flow && report2 && !report2.review && (report2.deliveryId && report2.deliveryCompleted === false || recoveryAttempts > 0 && (report2.deliveryId || report2.deliveryCompleted === false || flow.verify_delivery))) {
191567
+ report2 = { ...report2, recoveryAttempts };
191568
+ }
191524
191569
  const draft = report2;
191525
191570
  if (job.discussion && draft?.goals !== void 0) {
191526
191571
  const unsaved = unsavedGoals(draft);
@@ -191620,6 +191665,20 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191620
191665
  if (renewed.ok && renewed.value.renewed && state?.code !== "allowance") Object.assign(lease, sentAt);
191621
191666
  if (renewed.ok && renewed.value.stop) stream2.requestStop();
191622
191667
  if (renewed.ok && renewed.value.projectDir && !job.projectDir) job = { ...job, projectDir: renewed.value.projectDir };
191668
+ return renewed;
191669
+ };
191670
+ const waitForAccess = async (code, ready) => {
191671
+ const stream2 = watching();
191672
+ while (!stream2.asked() && !stream2.lost()) {
191673
+ if (await ready()) {
191674
+ if (checkpoint.taskRecovery?.code === code) await recoveryState(null);
191675
+ return !stream2.asked() && !stream2.lost();
191676
+ }
191677
+ const status2 = await recoveryState({ code });
191678
+ if (status2.ok && !status2.value.renewed) return false;
191679
+ await waitForRetry(Date.now() + deps.retryMs, stream2.whenAsked);
191680
+ }
191681
+ return false;
191623
191682
  };
191624
191683
  function retryEvent(stream2, record2, state, attempt2, at2) {
191625
191684
  stream2.event({ kind: "retry", data: {
@@ -191647,6 +191706,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191647
191706
  const reportsStop = step === "finish" && (checkpoint.ending?.outcome === "stopped" || checkpoint.ending?.report?.stopped);
191648
191707
  const stopped3 = () => stream2.lost() || stream2.asked() && !reportsStop;
191649
191708
  let recovered;
191709
+ let showedRecovery = false;
191650
191710
  while (!stopped3()) {
191651
191711
  const pending = checkpoint.syncRetries?.[step];
191652
191712
  let renewalFailure;
@@ -191677,6 +191737,14 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191677
191737
  }
191678
191738
  Object.assign(lease, requestedAt);
191679
191739
  if (renewed.value.stop) stream2.requestStop();
191740
+ if (flow && !stopped3() && !verification && !writeBlock({ code: record3?.code, error: record3?.summary ?? "" })) {
191741
+ await recoveryState({
191742
+ code: "recovering",
191743
+ attempt: next - 1,
191744
+ ...step === "publish" || step === "prepare" ? { step: "sync" } : {}
191745
+ });
191746
+ showedRecovery = true;
191747
+ }
191680
191748
  }
191681
191749
  if (stopped3()) return syncStopped;
191682
191750
  }
@@ -191688,6 +191756,9 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191688
191756
  }
191689
191757
  if (stopped3()) return syncStopped;
191690
191758
  if (result.ok) {
191759
+ if (showedRecovery || checkpoint.taskRecovery?.code === "storage" || checkpoint.taskRecovery?.code === "allowance") {
191760
+ await recoveryState(null);
191761
+ }
191691
191762
  if (recovered) {
191692
191763
  retryEvent(stream2, recovered, "recovered", budget.attempt() - 1);
191693
191764
  stream2.event({ kind: "status", data: { state: "running", source: "sync" } });
@@ -191695,12 +191766,14 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191695
191766
  return result;
191696
191767
  }
191697
191768
  const failure4 = result.failure ?? makeFailure("sync", result.error, { code: result.code });
191698
- if (!retryableSync(result)) {
191769
+ const blocked = flow && !reportsStop ? writeBlock(result) : void 0;
191770
+ if (!retryableSync(result) && !blocked) {
191699
191771
  checkpoint.retryHistory = [...checkpoint.retryHistory ?? [], retryRecord(failure4, budget.attempt(), runtimeInfo())];
191700
191772
  persist();
191701
191773
  return result;
191702
191774
  }
191703
- const { decision, record: record2, attempt: attempt2 } = schedule(step, failure4, step === "finish" ? () => deps.retryMs : void 0);
191775
+ if (blocked) await recoveryState({ code: blocked });
191776
+ const { decision, record: record2, attempt: attempt2 } = schedule(step, failure4, blocked || step === "finish" ? () => deps.retryMs : void 0);
191704
191777
  if ("pause" in decision) {
191705
191778
  retryEvent(stream2, record2, "paused", attempt2 - 1);
191706
191779
  return decision.pause === "limit" ? { ...result, code: "retry_exhausted" } : result;
@@ -191863,14 +191936,37 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191863
191936
  if (stream2?.asked()) return finishClaimed("stopped", "", report2);
191864
191937
  return finishClaimed("failed", allowed2.ok ? cloudLanguage(job) === "en" ? "Project folder access changed. Confirm access and retry." : "\u9879\u76EE\u76EE\u5F55\u6388\u6743\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u786E\u8BA4\u540E\u91CD\u8BD5\u3002" : syncRefusal(job, allowed2), report2);
191865
191938
  };
191939
+ const folderReady = () => !!job.projectDir && !("refused" in folderFor(job));
191940
+ if (flow?.review_revision !== void 0 && flow.verb !== "discard" && job.task && !await waitForAccess("folder", folderReady)) {
191941
+ if (watching().asked()) return finishClaimed("stopped");
191942
+ return unauthorized({ ok: true, value: false });
191943
+ }
191866
191944
  const allowed = await authorize();
191867
191945
  if (!allowed.ok || !allowed.value) return unauthorized(allowed);
191868
- if (job.flow && job.flow.verb !== "discard") {
191869
- if (job.task && (!job.projectDir || "refused" in folderFor(job))) return unauthorized({ ok: true, value: false });
191946
+ if (job.flow && job.flow.verb !== "discard" && job.task && !folderReady()) {
191947
+ return unauthorized({ ok: true, value: false });
191870
191948
  }
191871
191949
  if (job.secret) return runSecret(job, deps);
191872
191950
  if (job.test) return runTest(job, deps, lease);
191873
191951
  const waitingStream = pendingRetry || job.task || reply ? watching() : replyStream;
191952
+ if (verification && job.task) {
191953
+ const current2 = await sync("review", () => deps.api.readTask(job.task));
191954
+ if (!current2.ok) return unauthorized(current2);
191955
+ const review = current2.value.review;
191956
+ if (!review || flow?.review_revision !== review.revision || !reviewAllows(reviewAuthorization(review), "implement")) {
191957
+ return finishClaimed("failed", "This execution no longer has review authorization.");
191958
+ }
191959
+ }
191960
+ if (verification && !checkpoint.verifyingDelivery && !manual) {
191961
+ await recoveryState({ code: "recovering", attempt: Math.min(budget.attempt(), MAX_RETRY_ATTEMPTS) });
191962
+ const failure4 = makeFailure("sync", "Checking the saved delivery and archive.", { code: "task_delivery_unverified" });
191963
+ const ready = await recover(failure4, async () => {
191964
+ checkpoint.verifyingDelivery = true;
191965
+ persist();
191966
+ return { ok: true, value: void 0 };
191967
+ });
191968
+ if (!ready.ok) return finishClaimed(watching().asked() ? "stopped" : "failed", ready.error);
191969
+ }
191874
191970
  if (pendingRetry && waitingStream) {
191875
191971
  const stream2 = waitingStream;
191876
191972
  track(stream2.stop);
@@ -191917,7 +192013,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
191917
192013
  Object.assign(lease, requestedAt);
191918
192014
  }
191919
192015
  if (recovering && !pendingRetry) {
191920
- if (job.flow && !Object.keys(checkpoint.syncRetries ?? {}).length) await recoveryState({ code: "recovering", attempt: checkpoint.boardRepair ? 2 : 1 });
192016
+ if (job.flow && !verification && !Object.keys(checkpoint.syncRetries ?? {}).length) await recoveryState({ code: "recovering", attempt: Math.min(MAX_RETRY_ATTEMPTS, Math.max(1, budget.attempt() - 1)) });
191921
192017
  let requestedAt = leaseNow();
191922
192018
  const renewed = await sync("renew", () => {
191923
192019
  requestedAt = leaseNow();
@@ -192070,7 +192166,7 @@ The original session is unavailable. Saved work was preserved.`);
192070
192166
  ws = openTaskFolder({ ...job, task }, folder2?.cwd ?? null);
192071
192167
  cwd = ws.cwd;
192072
192168
  keep2(cwd);
192073
- if (usesBoardRun(job, checkpoint) && !await recoverBoard(ws)) {
192169
+ if (usesBoardRun(job, checkpoint) && !verification && !await recoverBoard(ws)) {
192074
192170
  return finishClaimed("failed", job.flow?.historical_conflict ? "Board content conflicts could not be resolved. Saved work was preserved." : recoveryBlocked(job));
192075
192171
  }
192076
192172
  if (!job.flow && !job.review && !checkpoint.completed && !checkpoint.boardContinuation?.report.deliveryCompleted) {
@@ -192391,6 +192487,15 @@ ${body}` : body;
192391
192487
  sync,
192392
192488
  retryFile: retryFile2,
192393
192489
  recover,
192490
+ waitForLogin: flow?.review_revision === void 0 ? void 0 : async () => {
192491
+ const ready = await waitForAccess("login", async () => {
192492
+ const runtime = (await deps.runtimes()).find((r2) => r2.name === job.runtime);
192493
+ return runtime?.loggedIn !== false || !runtime.installed;
192494
+ });
192495
+ if (!ready) return false;
192496
+ const allowed2 = await authorize();
192497
+ return allowed2.ok && allowed2.value;
192498
+ },
192394
192499
  starting: async () => {
192395
192500
  if (checkpoint.taskRecovery?.code === "recovering") await recoveryState(null);
192396
192501
  if (!stream.lost() && !stream.asked()) starting();
@@ -192439,18 +192544,20 @@ ${body}` : body;
192439
192544
  }
192440
192545
  }
192441
192546
  let result = await runFlow(job, ws, deps, io);
192442
- while (!result.ok && result.failure?.code === "delivery_incomplete" && !stream.asked() && !stream.lost()) {
192547
+ if (!result.ok && !verification && result.failure?.code === "delivery_incomplete" && !stream.asked() && !stream.lost()) {
192443
192548
  const saved = await flowRunEvidence(ws, job, deps, id2, checkpoint.flowRun);
192444
- if (!saved.stopped || !saved.run?.finished || !await stream.confirmed()) break;
192445
- const failure4 = result.failure;
192446
- checkpoint.flowRun = saved.run;
192447
- checkpoint.boardRepair = { reason: failure4.summary, run: saved.run.id };
192448
- const ready = await recover(failure4, async () => ({ ok: true, value: void 0 }));
192449
- if (!ready.ok) break;
192450
- io.flowRun = saved.run;
192451
- io.repairDelivery = true;
192452
- io.diagnostic = failure4.summary;
192453
- result = await runFlow(job, ws, deps, io);
192549
+ if (saved.stopped && saved.run?.finished && await stream.confirmed()) {
192550
+ const failure4 = result.failure;
192551
+ checkpoint.flowRun = saved.run;
192552
+ checkpoint.boardRepair = { reason: failure4.summary, run: saved.run.id };
192553
+ const ready = await recover(failure4, async () => ({ ok: true, value: void 0 }));
192554
+ if (ready.ok) {
192555
+ io.flowRun = saved.run;
192556
+ io.repairDelivery = true;
192557
+ io.diagnostic = failure4.summary;
192558
+ result = await runFlow(job, ws, deps, io);
192559
+ }
192560
+ }
192454
192561
  }
192455
192562
  if (result.ok) complete("done", result.report);
192456
192563
  const stopped3 = !result.ok && (stream.asked() || result.stopped === true);
@@ -192827,6 +192934,7 @@ async function sendBack(job, deps, ws, report2, sync, stream, finish, landed, re
192827
192934
  const result = await sync("publish", async () => {
192828
192935
  const pushed2 = await push(ws, { id: job.id, machineId: deps.machineId }, () => stream.asked() || stream.lost());
192829
192936
  if (pushed2.ok && closesTask && !taskAssetsSynced(ws)) return { ok: false, code: "service_unavailable", error: "Office preview uploads are pending." };
192937
+ if (!pushed2.ok && writeBlock(pushed2)) return pushed2;
192830
192938
  return !pushed2.ok && pushed2.offline ? { ok: false, error: pushed2.error, code: "service_unavailable" } : { ok: true, value: pushed2 };
192831
192939
  });
192832
192940
  const pushed = result.ok ? result.value : result;
@@ -192846,7 +192954,8 @@ async function sendBack(job, deps, ws, report2, sync, stream, finish, landed, re
192846
192954
  console.error("runner: task sync refused", { job: job.id, code: denied.code, error: denied.error });
192847
192955
  return finish("failed", syncRefusal(job, denied), report2);
192848
192956
  }
192849
- return finish("done", "", { ...report2, ...readCheckpoint(job.id)?.approvalRequested ? { replyApprovalSynced: report2.replyApprovalSynced !== false && taskAssetsSynced(ws) } : {} }, landed);
192957
+ const archive = closesTask && report2.deliveryId ? syncedArchive(ws) : void 0;
192958
+ return finish("done", "", { ...report2, ...archive ? { archive } : {}, ...readCheckpoint(job.id)?.approvalRequested ? { replyApprovalSynced: report2.replyApprovalSynced !== false && taskAssetsSynced(ws) } : {} }, landed);
192850
192959
  }
192851
192960
  var settingsOf = (job) => ({ settings: job.settings, secrets: secretsOf(job.runtimeId) });
192852
192961
  async function runSecret(job, deps) {
@@ -193190,12 +193299,12 @@ async function codexServer() {
193190
193299
  const previous = readPrivate(backendFile(key));
193191
193300
  if (previous && previous.generation === generation && liveBackend(previous)) {
193192
193301
  try {
193193
- const probe2 = await nativeConnection(previous, () => {
193302
+ const probe3 = await nativeConnection(previous, () => {
193194
193303
  });
193195
193304
  try {
193196
- await initializeNative(probe2);
193305
+ await initializeNative(probe3);
193197
193306
  } finally {
193198
- probe2.close();
193307
+ probe3.close();
193199
193308
  }
193200
193309
  idle2.delete(previous.instance);
193201
193310
  return previous;
@@ -193243,12 +193352,12 @@ async function codexServer() {
193243
193352
  continue;
193244
193353
  }
193245
193354
  try {
193246
- const probe2 = await nativeConnection(backend, () => {
193355
+ const probe3 = await nativeConnection(backend, () => {
193247
193356
  });
193248
193357
  try {
193249
- await initializeNative(probe2);
193358
+ await initializeNative(probe3);
193250
193359
  } finally {
193251
- probe2.close();
193360
+ probe3.close();
193252
193361
  }
193253
193362
  break;
193254
193363
  } catch (error62) {
@@ -193642,17 +193751,16 @@ var HEARTBEAT_MS2 = 10 * 6e4;
193642
193751
  var POLL_MS = 6e4;
193643
193752
  var BACKOFF_MS3 = [1e3, 2e3, 5e3, 1e4, 3e4];
193644
193753
  var LOOK_LATE_MS = 6e4;
193645
- function startRunner(options) {
193646
- adoptLegacy();
193754
+ function startRunner(options, lock) {
193647
193755
  const account = readSession()?.subject;
193648
193756
  const generation = accountGeneration();
193649
- const releaseRecord = executorRecord();
193757
+ let releaseRecord;
193758
+ let releaseMachine;
193650
193759
  let registration = null;
193651
193760
  let connected = false;
193652
193761
  let closed = false;
193653
193762
  let ownsExecution = false;
193654
193763
  let codex;
193655
- let startingCodex = Promise.resolve();
193656
193764
  let redetect = false;
193657
193765
  let preparing = false;
193658
193766
  let attempts = 0;
@@ -194075,10 +194183,13 @@ function startRunner(options) {
194075
194183
  await startingCodex;
194076
194184
  await codex?.close();
194077
194185
  for (const [key, value] of Object.entries(codex?.env ?? {})) if (process.env[key] === value) delete process.env[key];
194078
- if (release2 && !keptWorkers && !lock.waited() && registration) await release(registration.machineId);
194079
- clearInterval(accountWatch);
194080
- lock.release();
194081
- releaseRecord();
194186
+ try {
194187
+ if (release2 && !keptWorkers && registration) await release(registration.machineId);
194188
+ } finally {
194189
+ clearInterval(accountWatch);
194190
+ await releaseMachine?.();
194191
+ releaseRecord?.();
194192
+ }
194082
194193
  };
194083
194194
  let refresh2 = "";
194084
194195
  const accountWatch = setInterval(() => {
@@ -194095,22 +194206,21 @@ function startRunner(options) {
194095
194206
  if (!closed && !validAccount()) void finish({ reason: "refused", message: "\u8D26\u53F7\u5DF2\u9000\u51FA\u6216\u5207\u6362\u3002" });
194096
194207
  }, 200);
194097
194208
  accountWatch.unref();
194098
- removeLegacy();
194099
- pruneChats();
194100
- const lock = holdMachine(options.kind, () => {
194209
+ const startingCodex = (lock ? Promise.resolve(lock) : acquireMachine(options.kind)).then(async (release2) => {
194210
+ releaseMachine = release2;
194211
+ if (closed) return;
194212
+ adoptLegacy();
194213
+ releaseRecord = executorRecord();
194214
+ removeLegacy();
194215
+ pruneChats();
194216
+ codex = await codexServer();
194217
+ if (closed) return;
194101
194218
  ownsExecution = true;
194102
- startingCodex = codexServer().then(async (service) => {
194103
- codex = service;
194104
- if (closed) return;
194105
- Object.assign(process.env, service.env);
194106
- void tick();
194107
- }).catch((e2) => {
194108
- console.error(`runner: Codex service failed: ${e2 instanceof Error ? e2.message : String(e2)}`);
194109
- void finish({ reason: "refused", message: "Codex service failed to start." });
194110
- });
194111
- }, (holder) => {
194112
- status(t.waitingHere(holder));
194113
- options.onWaiting?.(holder);
194219
+ Object.assign(process.env, codex.env);
194220
+ void tick();
194221
+ }).catch((error62) => {
194222
+ if (closed) return;
194223
+ void finish(error62 instanceof RunnerAlreadyRunning ? { reason: "already-running" } : { reason: "refused", message: error62 instanceof Error ? error62.message : String(error62) });
194114
194224
  });
194115
194225
  return { stopped: stopped2, close: () => close(true), update: () => close(false, true), renew: () => {
194116
194226
  redetect = true;
@@ -194906,11 +195016,24 @@ function serveSettingsLink(open2, port = SETTINGS_LINK_PORT) {
194906
195016
 
194907
195017
  // ../runner/src/main.ts
194908
195018
  var tell = (message) => process.send?.(message);
195019
+ var rejectDuplicate = () => {
195020
+ process.stderr.write(`${t.alreadyRunning()}
195021
+ `, () => process.exit(EXIT_ALREADY_RUNNING));
195022
+ };
194909
195023
  async function main() {
194910
195024
  useRunnerHome();
195025
+ const kind = ["claude-code", "codex", "cursor", "dsh", "zcode", "kimi"].find((k2) => k2 === process.env.WILDCRANE_RUNNER_KIND) ?? "terminal";
195026
+ let lock;
195027
+ try {
195028
+ lock = await acquireMachine(kind);
195029
+ } catch (error62) {
195030
+ if (error62 instanceof RunnerAlreadyRunning) return rejectDuplicate();
195031
+ throw error62;
195032
+ }
194911
195033
  if (!readSession()) {
194912
195034
  const failure3 = await signIn();
194913
195035
  if (failure3) {
195036
+ await lock();
194914
195037
  status(t.signInFailed(failure3.detail));
194915
195038
  process.exit(EXIT_REFUSED);
194916
195039
  }
@@ -194921,13 +195044,12 @@ async function main() {
194921
195044
  const id2 = machineId();
194922
195045
  const runner = startRunner({
194923
195046
  registration: async () => ({ machineId: id2, machineName: machineName(), version: VERSION, runtimes: await detectRuntimes(true) }),
194924
- kind: ["claude-code", "codex", "cursor", "dsh", "zcode", "kimi"].find((k2) => k2 === process.env.WILDCRANE_RUNNER_KIND) ?? "terminal",
195047
+ kind,
194925
195048
  onConnected: () => tell({ type: "connected" }),
194926
195049
  onReconnecting: () => tell({ type: "reconnecting" }),
194927
- onWaiting: () => tell({ type: "waiting" }),
194928
195050
  // Tests shorten the job poll, which stands in when Realtime is out of reach.
194929
195051
  pollMs: Number(process.env.WILDCRANE_POLL_MS) || void 0
194930
- });
195052
+ }, lock);
194931
195053
  process.on("message", (message) => {
194932
195054
  if (message.type === "renew") return runner.renew();
194933
195055
  if (message.type !== "update") return;
@@ -194945,6 +195067,7 @@ async function main() {
194945
195067
  });
194946
195068
  }
194947
195069
  const stop2 = await runner.stopped;
195070
+ if (stop2.reason === "already-running") return rejectDuplicate();
194948
195071
  if (stop2.reason === "outdated") {
194949
195072
  status(t.outdated());
194950
195073
  process.exit(EXIT_OUTDATED);