wildcrane-runner 0.6.133 → 0.6.134

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.114 — built by runner/scripts/build.mjs. Do not edit.
2
+ // ai4kanban 0.11.115 — built by runner/scripts/build.mjs. Do not edit.
3
3
  import { createRequire as __ai4kanbanRequire } from 'node:module'
4
4
  const require = __ai4kanbanRequire(import.meta.url)
5
5
  var __create = Object.create;
@@ -127439,7 +127439,7 @@ var init_package = __esm({
127439
127439
  "../cli/package.json"() {
127440
127440
  package_default = {
127441
127441
  name: "wildcrane",
127442
- version: "0.11.114",
127442
+ version: "0.11.115",
127443
127443
  akbContract: 45,
127444
127444
  canonicalCommands: true,
127445
127445
  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.",
@@ -151527,7 +151527,7 @@ var init_discuss_goal = __esm({
151527
151527
  var follow_up_default;
151528
151528
  var init_follow_up = __esm({
151529
151529
  "../cli/src/guide/follow-up.md"() {
151530
- follow_up_default = '# Handle follow-up work\n\nApply `akb guide triage-decision` using this card as the source. Complete the judgment in this run; submit nothing for `skip`.\n\n- **Current task**: finish work required by this card; propose independent work separately, then resume this task.\n- **Existing card**: when another open card only needs updating, run `akb task revise <id> "<the change and why>"` instead.\n- **Queue**: write the title and body in the **Goal format** of `akb guide discuss-goal`, using the source card\'s `studio:` and stating the evidence or unresolved question.\n\n```text\nakb triage add --title "<one line>" --slug <short-english-slug> --source "#<id>" --studio <studio> --decision <plan|review> --text "<body>"\n```\n';
151530
+ follow_up_default = '# Handle follow-up work\n\nConsider only follow-ups surfaced by this work. Apply `akb guide triage-decision` with this card as the source, complete the judgment in this run, and submit nothing for `skip`.\n\n- **Current task**: finish work required by this card; propose independent work separately, then resume this task.\n- **Existing card**: when another open card only needs updating, run `akb task revise <id> "<the change and why>"` instead.\n- **Queue**: write the title and body in the **Goal format** of `akb guide discuss-goal`, using the source card\'s `studio:` and stating the evidence or unresolved question.\n\n```text\nakb triage add --title "<one line>" --slug <short-english-slug> --source "#<id>" --studio <studio> --decision <plan|review> --text "<body>"\n```\n';
151531
151531
  }
151532
151532
  });
151533
151533
 
@@ -151583,7 +151583,7 @@ var init_refine = __esm({
151583
151583
  var reflect_default;
151584
151584
  var init_reflect = __esm({
151585
151585
  "../cli/src/guide/reflect.md"() {
151586
- reflect_default = '# Reflect on completed cards\n\nRead each `<card>` and its `shipped` content; apply `akb guide triage-decision` separately to each source card and check coverage across this batch. Complete the judgment in this run; propose nothing at all when nothing follows: that is a complete result, and most batches are it.\n\n- **Existing card**: if shipped work invalidates an open task\'s plan, run `akb task revise <id> "<the change and why>"` instead.\n- **Queue**: write each item in the **Goal format** of `akb guide discuss-goal` to a temporary file ending with the archived card path, using the source card\'s `studio:` and stating the evidence or unresolved question.\n\n```text\nakb triage add --title "<one line>" --slug <short-english-slug> --source "#<id>" --studio <studio> --decision <plan|review> --file <body.md>\n```\n';
151586
+ reflect_default = '# Reflect on completed cards\n\nRead each `<card>` and its `shipped` content. Use `akb guide triage-decision` to evaluate only follow-ups surfaced by each card and check coverage across the batch. Complete the judgment in this run. When nothing qualifies, propose nothing at all. Most batches end there.\n\n- **Existing card**: if shipped work invalidates an open task\'s plan, run `akb task revise <id> "<the change and why>"` instead.\n- **Queue**: write each item in the **Goal format** of `akb guide discuss-goal` to a temporary file ending with the archived card path, using the source card\'s `studio:` and stating the evidence or unresolved question.\n\n```text\nakb triage add --title "<one line>" --slug <short-english-slug> --source "#<id>" --studio <studio> --decision <plan|review> --file <body.md>\n```\n';
151587
151587
  }
151588
151588
  });
151589
151589
 
@@ -151591,7 +151591,7 @@ var init_reflect = __esm({
151591
151591
  var triage_decision_default;
151592
151592
  var init_triage_decision = __esm({
151593
151593
  "../cli/src/guide/triage-decision.md"() {
151594
- triage_decision_default = "# Decide whether work should proceed\n\nUse these rules for follow-ups, reflection, and incoming triage items. Read the relevant project files and decisions before deciding.\n\n- **Admission**: for agent-proposed follow-ups, read `allowedFollowUps` in the source Studio's `STUDIO.md`; skip absent or blank rules and work outside them. For incoming suggestions, judge against the project's stated purpose and decisions.\n- **Evidence**: verify the requested outcome against current behavior or deliverables; cite evidence and skip resolved work.\n- **Prior decisions**: skip work turned down in `docs/kanban/memory/agents/planner/rejected.md` or its module folders, and calls reversed in `docs/kanban/memory/agents/` `redesign.md` files or a source card's `Overruled by the user`.\n- **Coverage**: compare scope and acceptance criteria with open and queued tasks, other pending triage items and this batch; skip fully covered outcomes and name what covers them. Partial overlap or a similar title is insufficient.\n- **Scope**: use an existing workflow when it meets the need; otherwise retain only the smallest change supported by evidence, without optional interactions or artifacts. Leave incoming items for review when only a narrower proposal is supported.\n- **User decisions**: leave unresolved product direction, pricing, external commitments, and material trade-offs for the user; ordinary implementation choices belong to the agent.\n- **Result**: choose `skip` for work ruled out above, `review` for unresolved decisions or insufficient evidence, and `plan` when the full scope is supported and no user decision remains. State the evidence or unresolved question.\n- **Studio**: retain the bound Studio; otherwise choose an available Studio whose scope fits the work, or leave the item for review when none fits.\n";
151594
+ triage_decision_default = "# Decide whether work should proceed\n\nUse these rules for follow-ups, reflection, and incoming triage items. Read the relevant project files and decisions before deciding.\n\n- **Admission**: for agent-proposed follow-ups, read `allowedFollowUps` in the source Studio's `STUDIO.md`; skip absent or blank rules and work outside them. For incoming suggestions, judge against the project's stated purpose and decisions.\n- **Evidence**: verify the requested outcome against current behavior or deliverables; cite evidence and skip resolved work.\n- **Agent-proposed bugs**: require evidence of a plausible trigger in real use and an impact worth fixing. Skip minor or self-resolving issues that require combining rare failure windows with extreme edge conditions.\n- **Prior decisions**: skip work turned down in `docs/kanban/memory/agents/planner/rejected.md` or its module folders, and calls reversed in `docs/kanban/memory/agents/` `redesign.md` files or a source card's `Overruled by the user`.\n- **Coverage**: compare scope and acceptance criteria with open and queued tasks, other pending triage items and this batch; skip fully covered outcomes and name what covers them. Partial overlap or a similar title is insufficient.\n- **Scope**: use an existing workflow when it meets the need; otherwise retain only the smallest change supported by evidence, without optional interactions or artifacts. Leave incoming items for review when only a narrower proposal is supported.\n- **User decisions**: leave unresolved product direction, pricing, external commitments, and material trade-offs for the user; ordinary implementation choices belong to the agent.\n- **Result**: choose `skip` for work ruled out above, `review` for unresolved decisions or insufficient evidence, and `plan` when the full scope is supported and no user decision remains. State the evidence or unresolved question.\n- **Studio**: retain the bound Studio; otherwise choose an available Studio whose scope fits the work, or leave the item for review when none fits.\n";
151595
151595
  }
151596
151596
  });
151597
151597
 
@@ -1 +1 @@
1
- {"name":"wildcrane","version":"0.11.114","akbContract":45,"type":"module","private":true}
1
+ {"name":"wildcrane","version":"0.11.115","akbContract":45,"type":"module","private":true}
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -167678,8 +167678,8 @@ async function readStudioDownload(response, size) {
167678
167678
  }
167679
167679
 
167680
167680
  // src/protocol.ts
167681
- var VERSION = true ? "0.6.133" : "0.0.0";
167682
- var AKB_VERSION = true ? "0.11.114" : "0.0.0";
167681
+ var VERSION = true ? "0.6.134" : "0.0.0";
167682
+ var AKB_VERSION = true ? "0.11.115" : "0.0.0";
167683
167683
  var AKB_CONTRACT = true ? 45 : 0;
167684
167684
 
167685
167685
  // src/secrets.ts
@@ -168935,7 +168935,7 @@ function createTail(log) {
168935
168935
  // ../cli/package.json
168936
168936
  var package_default = {
168937
168937
  name: "wildcrane",
168938
- version: "0.11.114",
168938
+ version: "0.11.115",
168939
168939
  akbContract: 45,
168940
168940
  canonicalCommands: true,
168941
168941
  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.",
@@ -173833,9 +173833,10 @@ var answerDiff = (machineId, id2, answer) => request("POST", `/v1/runner/diffs/$
173833
173833
  var listChats = (machineId) => request("GET", `/v1/runner/chats?machine=${encodeURIComponent(machineId)}`);
173834
173834
  var readChat = (task) => request("GET", `/v1/tasks/${encodeURIComponent(task)}/chat`);
173835
173835
  var readDecisions = (task, after) => request("GET", `/v1/tasks/${q(task)}/decisions?limit=100${after ? `&after=${q(after)}` : ""}`);
173836
- var dispatchReview = (machineId, project, tasks, runtime, model) => request("POST", "/v1/runner/reviews", { machineId, project, tasks, runtime, model });
173836
+ var dispatchReview = (machineId, project, tasks, runtime, model, expected) => request("POST", "/v1/runner/reviews", { machineId, project, tasks, runtime, model, expected, ...expected && { timeZone: runnerTimeZone() } });
173837
173837
  var readAgents = (machineId, project) => request("GET", `/v1/runner/agents?machine=${encodeURIComponent(machineId)}&project=${encodeURIComponent(project)}`);
173838
- var requestAgent = (machineId, project, agent, seen) => request("POST", "/v1/runner/jobs", { machineId, project, agent, studio: null, seen });
173838
+ var runnerTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
173839
+ var requestAgent = (machineId, project, agent, seen, expected) => request("POST", "/v1/runner/jobs", { machineId, project, agent, studio: null, seen, expected, ...expected && { timeZone: runnerTimeZone() } });
173839
173840
  var requestTriage = (machineId, project) => request("POST", "/v1/runner/triage", { machineId, project });
173840
173841
  var triageBatch = (machineId, job) => request("POST", `/v1/runner/jobs/${q(job)}/triage`, { machineId, action: "batch" });
173841
173842
  var q = encodeURIComponent;
@@ -175728,12 +175729,17 @@ function migrateGoalData(data) {
175728
175729
 
175729
175730
  // src/recovery.ts
175730
175731
  var recoveryBlocked = (job) => cloudLanguage(job) === "zh" ? "\u65E0\u6CD5\u6838\u5BF9\u4E0A\u6B21\u6267\u884C\uFF0C\u5DF2\u6709\u6210\u679C\u5DF2\u4FDD\u7559\u3002" : "The previous execution could not be verified. Saved work was preserved.";
175731
- var retryFileOf = (id2) => path31.join(runnerHome(), "checkpoints", `${encodeURIComponent(id2)}.retry`);
175732
- var fileOf2 = (id2) => path31.join(runnerHome(), "checkpoints", `${encodeURIComponent(id2)}.json`);
175732
+ var checkpointDir = () => path31.join(runnerHome(), "checkpoints");
175733
+ var retryFileOf = (id2) => path31.join(checkpointDir(), `${encodeURIComponent(id2)}.retry`);
175734
+ var fileOf2 = (id2) => path31.join(checkpointDir(), `${encodeURIComponent(id2)}.json`);
175735
+ function readCheckpointFile(file2) {
175736
+ const held5 = JSON.parse(fs31.readFileSync(file2, "utf8"));
175737
+ if (!held5 || !Array.isArray(held5.pending) || !held5.pending.every((id2) => typeof id2 === "string")) throw new Error("\u8FDB\u5EA6\u683C\u5F0F\u9519\u8BEF");
175738
+ return held5;
175739
+ }
175733
175740
  function readCheckpoint(id2) {
175734
175741
  try {
175735
- const held5 = JSON.parse(fs31.readFileSync(fileOf2(id2), "utf8"));
175736
- if (!held5 || !Array.isArray(held5.pending) || !held5.pending.every((id3) => typeof id3 === "string")) throw new Error("\u8FDB\u5EA6\u683C\u5F0F\u9519\u8BEF");
175742
+ const held5 = readCheckpointFile(fileOf2(id2));
175737
175743
  const pending = held5.syncRetry;
175738
175744
  if (pending && Number.isSafeInteger(pending.attempt) && pending.attempt >= 1 && Number.isFinite(pending.at)) {
175739
175745
  held5.syncRetries ??= {};
@@ -175762,8 +175768,9 @@ function saveCheckpoint(id2, checkpoint) {
175762
175768
  fs31.writeFileSync(`${file2}.tmp`, JSON.stringify(checkpoint), { mode: 384 });
175763
175769
  fs31.renameSync(`${file2}.tmp`, file2);
175764
175770
  }
175765
- function clearCheckpoint(id2) {
175771
+ function clearCheckpoint(id2, { keepReviewMarks = false } = {}) {
175766
175772
  const checkpoint = readCheckpoint(id2);
175773
+ if (keepReviewMarks && checkpoint?.reviewMarks) return;
175767
175774
  fs31.rmSync(fileOf2(id2), { force: true });
175768
175775
  if (checkpoint) fs31.rmSync(retryFileOf(checkpoint.retryRound ?? id2), { force: true });
175769
175776
  }
@@ -175853,7 +175860,7 @@ async function recoverInterruptedJob(machine, job, checkpoint, stopped3, valid,
175853
175860
  const prepared = await finishJob(machine, job.id, "update_prepare", "", report2);
175854
175861
  if (!valid() || !prepared.ok) return;
175855
175862
  if (prepared.value.finished) {
175856
- clearCheckpoint(job.id);
175863
+ clearCheckpoint(job.id, { keepReviewMarks: true });
175857
175864
  return prepared.value;
175858
175865
  }
175859
175866
  if (!prepared.value.prepared) return;
@@ -175863,7 +175870,7 @@ async function recoverInterruptedJob(machine, job, checkpoint, stopped3, valid,
175863
175870
  saveCheckpoint(job.id, checkpoint);
175864
175871
  const resumed = await finishJob(machine, job.id, "update_resume", "", report2 && { ...report2, session: void 0 });
175865
175872
  if (!valid() || !resumed.ok) return;
175866
- if (resumed.value.finished) clearCheckpoint(job.id);
175873
+ if (resumed.value.finished) clearCheckpoint(job.id, { keepReviewMarks: true });
175867
175874
  return resumed.value;
175868
175875
  }
175869
175876
  const renewed = await renewJob(machine, job.id);
@@ -193683,6 +193690,7 @@ function readTaskChat(task, home4) {
193683
193690
 
193684
193691
  // src/chats.ts
193685
193692
  var DAY_MS2 = 24 * 60 * 6e4;
193693
+ var REVIEW_EVERY_MS = 6 * 60 * 6e4;
193686
193694
  var KEEP_MS2 = CHAT_KEEP_DAYS * DAY_MS2;
193687
193695
  var home3 = () => runnerHome();
193688
193696
  var reviewedFile = () => path78.join(taskChatsDir(home3()), "reviewed.json");
@@ -193695,9 +193703,11 @@ function readReviewed2() {
193695
193703
  }
193696
193704
  }
193697
193705
  function writeReviewed(reviewed) {
193698
- fs77.mkdirSync(path78.dirname(reviewedFile()), { recursive: true });
193699
- fs77.writeFileSync(reviewedFile(), `${JSON.stringify(reviewed, null, 2)}
193706
+ const file2 = reviewedFile();
193707
+ fs77.mkdirSync(path78.dirname(file2), { recursive: true });
193708
+ fs77.writeFileSync(`${file2}.tmp`, `${JSON.stringify(reviewed, null, 2)}
193700
193709
  `);
193710
+ fs77.renameSync(`${file2}.tmp`, file2);
193701
193711
  }
193702
193712
  function keepChat(job, reply, at2 = Date.now()) {
193703
193713
  if (!job.task || !job.chat || !reply?.trim()) return;
@@ -194737,6 +194747,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
194737
194747
  return result;
194738
194748
  });
194739
194749
  if (sent.ok && sent.value) {
194750
+ if (outcome === "done" && checkpoint.reviewMarks) markReviewed2(checkpoint.reviewMarks);
194740
194751
  if (archive && ws) {
194741
194752
  noteLandArchive(ws.cwd, job, report2);
194742
194753
  queueDeliveryCleanup(ws.cwd);
@@ -194769,7 +194780,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
194769
194780
  };
194770
194781
  const remote3 = await readJob(id2);
194771
194782
  if (remote3.ok && remote3.value.job.state === "finished") {
194772
- clearCheckpoint(id2);
194783
+ clearCheckpoint(id2, { keepReviewMarks: remote3.value.job.outcome === "done" });
194773
194784
  return remote3.value.job.outcome === outcome;
194774
194785
  }
194775
194786
  checkpoint.ending = { outcome: "failed", reason: failure3.summary, report: failed, unconfirmed: true };
@@ -195545,7 +195556,7 @@ ${body}` : body;
195545
195556
  if (!stream.lost()) return finishClaimed(stream.asked() ? "stopped" : "failed", ended2.reason);
195546
195557
  return;
195547
195558
  }
195548
- return !stream.lost() ? sendResult(ended2.report, () => markReviewed2(marks)) : void 0;
195559
+ return !stream.lost() ? sendResult(ended2.report) : void 0;
195549
195560
  }
195550
195561
  if (!run3) {
195551
195562
  if (checkpoint.syncRetries?.repair && (io.repairDelivery || checkpoint.syncRetries.repair.record?.code === "board_command_interrupted")) {
package/dist/launcher.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -41151,8 +41151,8 @@ function saveAlphaUpdates(value) {
41151
41151
  }
41152
41152
 
41153
41153
  // src/protocol.ts
41154
- var VERSION = true ? "0.6.133" : "0.0.0";
41155
- var AKB_VERSION = true ? "0.11.114" : "0.0.0";
41154
+ var VERSION = true ? "0.6.134" : "0.0.0";
41155
+ var AKB_VERSION = true ? "0.11.115" : "0.0.0";
41156
41156
  var EXIT_REFUSED = 10;
41157
41157
  var EXIT_OUTDATED = 11;
41158
41158
  var EXIT_UPDATE = 12;
@@ -43687,7 +43687,7 @@ function createTail(log) {
43687
43687
  // ../cli/package.json
43688
43688
  var package_default = {
43689
43689
  name: "wildcrane",
43690
- version: "0.11.114",
43690
+ version: "0.11.115",
43691
43691
  akbContract: 45,
43692
43692
  canonicalCommands: true,
43693
43693
  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.",
package/dist/plugin.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -109878,7 +109878,7 @@ function createTail(log) {
109878
109878
  // ../cli/package.json
109879
109879
  var package_default = {
109880
109880
  name: "wildcrane",
109881
- version: "0.11.114",
109881
+ version: "0.11.115",
109882
109882
  akbContract: 45,
109883
109883
  canonicalCommands: true,
109884
109884
  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.",
@@ -114537,8 +114537,8 @@ function machineId() {
114537
114537
  var machineName = () => os5.hostname().replace(/\.local$/, "");
114538
114538
 
114539
114539
  // src/protocol.ts
114540
- var VERSION = true ? "0.6.133" : "0.0.0";
114541
- var AKB_VERSION = true ? "0.11.114" : "0.0.0";
114540
+ var VERSION = true ? "0.6.134" : "0.0.0";
114541
+ var AKB_VERSION = true ? "0.11.115" : "0.0.0";
114542
114542
  var EXIT_OUTDATED = 11;
114543
114543
  var EXIT_UPDATE = 12;
114544
114544
  var EXIT_ALREADY_RUNNING = 13;
package/dist/runner.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -146556,8 +146556,8 @@ function status(line) {
146556
146556
  }
146557
146557
 
146558
146558
  // src/protocol.ts
146559
- var VERSION = true ? "0.6.133" : "0.0.0";
146560
- var AKB_VERSION = true ? "0.11.114" : "0.0.0";
146559
+ var VERSION = true ? "0.6.134" : "0.0.0";
146560
+ var AKB_VERSION = true ? "0.11.115" : "0.0.0";
146561
146561
  var AKB_CONTRACT = true ? 45 : 0;
146562
146562
  var EXIT_REFUSED = 10;
146563
146563
  var EXIT_OUTDATED = 11;
@@ -148318,7 +148318,7 @@ function createTail(log) {
148318
148318
  // ../cli/package.json
148319
148319
  var package_default = {
148320
148320
  name: "wildcrane",
148321
- version: "0.11.114",
148321
+ version: "0.11.115",
148322
148322
  akbContract: 45,
148323
148323
  canonicalCommands: true,
148324
148324
  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.",
@@ -174593,15 +174593,11 @@ function parseStamp(raw) {
174593
174593
  const d2 = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), 0, 0);
174594
174594
  return Number.isNaN(d2.getTime()) ? null : d2;
174595
174595
  }
174596
- function nextDue(lastRun, cadence) {
174597
- const c2 = typeof cadence === "string" ? parseCadence(cadence) : cadence;
174598
- if (!c2) return null;
174599
- const last2 = parseStamp(lastRun);
174600
- if (!last2) return /* @__PURE__ */ new Date(0);
174596
+ function nextCadenceAt(last2, c2) {
174601
174597
  if (c2.unit === "m") return new Date(last2.getTime() + c2.n * 6e4);
174602
174598
  if (c2.unit === "h") return new Date(last2.getTime() + c2.n * 36e5);
174603
174599
  const [hour, minute] = c2.at ? c2.at.split(":").map(Number) : [last2.getHours(), last2.getMinutes()];
174604
- return new Date(last2.getFullYear(), last2.getMonth(), last2.getDate() + c2.n, hour, minute, 0, 0);
174600
+ return new Date(last2.getFullYear(), last2.getMonth(), last2.getDate() + c2.n, hour, minute, c2.at ? 0 : last2.getSeconds(), c2.at ? 0 : last2.getMilliseconds());
174605
174601
  }
174606
174602
 
174607
174603
  // ../cli/src/lib/agent/settings.ts
@@ -174781,9 +174777,10 @@ var answerDiff = (machineId2, id2, answer) => request("POST", `/v1/runner/diffs/
174781
174777
  var listChats = (machineId2) => request("GET", `/v1/runner/chats?machine=${encodeURIComponent(machineId2)}`);
174782
174778
  var readChat = (task) => request("GET", `/v1/tasks/${encodeURIComponent(task)}/chat`);
174783
174779
  var readDecisions = (task, after) => request("GET", `/v1/tasks/${q(task)}/decisions?limit=100${after ? `&after=${q(after)}` : ""}`);
174784
- var dispatchReview = (machineId2, project, tasks, runtime, model) => request("POST", "/v1/runner/reviews", { machineId: machineId2, project, tasks, runtime, model });
174780
+ var dispatchReview = (machineId2, project, tasks, runtime, model, expected) => request("POST", "/v1/runner/reviews", { machineId: machineId2, project, tasks, runtime, model, expected, ...expected && { timeZone: runnerTimeZone() } });
174785
174781
  var readAgents = (machineId2, project) => request("GET", `/v1/runner/agents?machine=${encodeURIComponent(machineId2)}&project=${encodeURIComponent(project)}`);
174786
- var requestAgent = (machineId2, project, agent, seen) => request("POST", "/v1/runner/jobs", { machineId: machineId2, project, agent, studio: null, seen });
174782
+ var runnerTimeZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
174783
+ var requestAgent = (machineId2, project, agent, seen, expected) => request("POST", "/v1/runner/jobs", { machineId: machineId2, project, agent, studio: null, seen, expected, ...expected && { timeZone: runnerTimeZone() } });
174787
174784
  var requestTriage = (machineId2, project) => request("POST", "/v1/runner/triage", { machineId: machineId2, project });
174788
174785
  var triageBatch = (machineId2, job) => request("POST", `/v1/runner/jobs/${q(job)}/triage`, { machineId: machineId2, action: "batch" });
174789
174786
  var q = encodeURIComponent;
@@ -175803,59 +175800,16 @@ function refusal2(picked, where = here()) {
175803
175800
  import fs90 from "node:fs";
175804
175801
  import path90 from "node:path";
175805
175802
 
175806
- // ../cli/src/lib/agent/due.ts
175807
- var AUTO_GAP = "6h";
175808
- var DAY = 864e5;
175809
- var autoSchedule = (reads, fallback) => reads ? { every: AUTO_GAP, reads } : { every: fallback };
175810
- var failures = (attempts) => {
175811
- let n = 0;
175812
- for (const a2 of [...attempts].sort((x2, y2) => y2.startedAt - x2.startedAt)) {
175813
- if (a2.status === "running") continue;
175814
- if (a2.status === "done") break;
175815
- n++;
175816
- }
175817
- return n;
175818
- };
175819
- function scheduleDue(ask, now = Date.now()) {
175820
- const gap = !isAuto(ask.cadence) ? ask.cadence : autoSchedule(ask.reads, ask.fallback).every;
175821
- const from = Math.max(ask.from, ...ask.attempts.map((a2) => a2.startedAt));
175822
- let next = ask.goesOn ? /* @__PURE__ */ new Date(0) : from ? nextDue(formatStamp(new Date(from)), gap) ?? /* @__PURE__ */ new Date(0) : /* @__PURE__ */ new Date(0);
175823
- const failed = failures(ask.attempts);
175824
- if (!ask.goesOn && from && failed > 1) {
175825
- const base = next.getTime() - from;
175826
- next = new Date(from + Math.min(base * 2 ** (failed - 1), Math.max(base, DAY)));
175827
- }
175828
- const newest2 = ask.attempts.reduce((a2, r2) => a2 && a2.startedAt >= r2.startedAt ? a2 : r2, null);
175829
- const retrying = isAuto(ask.cadence) && newest2?.status === "error";
175830
- const wait3 = next.getTime() > now ? retrying ? "retrying" : "tooSoon" : !ask.newWork() ? "nothingNew" : null;
175831
- const reason = !wait3 || wait3 === "tooSoon" ? void 0 : wait3 === "nothingNew" ? ask.reads : wait3;
175832
- return { next, wait: wait3, ...reason ? { reason } : {} };
175833
- }
175834
-
175835
175803
  // src/agents.ts
175836
- function nextHour(now = Date.now()) {
175837
- const at2 = new Date(now);
175838
- at2.setMinutes(60, 0, 0);
175839
- return at2.getTime();
175840
- }
175841
- function hourOf(at2) {
175842
- const hour = new Date(at2 ?? NaN);
175843
- if (Number.isNaN(hour.getTime())) return 0;
175844
- hour.setMinutes(hour.getMinutes() + 30, 0, 0);
175845
- hour.setMinutes(0, 0, 0);
175846
- return hour.getTime();
175804
+ function nextMinute(now = Date.now()) {
175805
+ return (Math.floor(now / 6e4) + 1) * 6e4;
175847
175806
  }
175848
175807
  function agentDue(agent, now = Date.now()) {
175849
- if (agent.attempts.some((a2) => a2.status === "running")) return false;
175850
- const due = scheduleDue({
175851
- cadence: agent.cadence,
175852
- fallback: agent.fallback,
175853
- reads: agent.reads,
175854
- from: Math.max(hourOf(agent.lastSuccess), hourOf(agent.since)),
175855
- attempts: agent.attempts.map((a2) => ({ startedAt: hourOf(a2.startedAt), status: a2.status })),
175856
- newWork: () => agent.newWork
175857
- }, now);
175858
- return !due.wait;
175808
+ if (!agent.newWork || agent.attempts.some((a2) => a2.status === "running")) return false;
175809
+ const cadence = parseCadence(isAuto(agent.cadence) ? agent.fallback : agent.cadence);
175810
+ if (!cadence) return false;
175811
+ const last2 = Math.max(0, ...[agent.since, agent.lastSuccess, ...agent.attempts.map((a2) => a2.startedAt)].map((at2) => Date.parse(at2 ?? "") || 0));
175812
+ return !last2 || +nextCadenceAt(new Date(last2), cadence) <= now;
175859
175813
  }
175860
175814
  async function askTriage(machineId2) {
175861
175815
  const folders2 = await listFolders(machineId2);
@@ -175875,7 +175829,7 @@ async function askDueAgents(machineId2, now = Date.now()) {
175875
175829
  const read6 = await readAgents(machineId2, project);
175876
175830
  if (!read6.ok) continue;
175877
175831
  for (const agent of read6.value.agents.filter((a2) => !a2.studio && agentDue(a2, now))) {
175878
- const asked = await requestAgent(machineId2, project, agent.name, agent.lastSuccess);
175832
+ const asked = await requestAgent(machineId2, project, agent.name, agent.lastSuccess, agent.expected);
175879
175833
  if (!asked.ok) console.error(`runner: ${agent.name} was not started on ${project}: ${asked.error}`);
175880
175834
  else if (asked.value.job) started = true;
175881
175835
  }
@@ -190243,8 +190197,8 @@ function queueDeliveryCleanup(cwd) {
190243
190197
  }
190244
190198
 
190245
190199
  // src/chats.ts
190246
- import fs55 from "node:fs";
190247
- import path57 from "node:path";
190200
+ import fs56 from "node:fs";
190201
+ import path58 from "node:path";
190248
190202
 
190249
190203
  // ../cli/src/lib/shared/chats.ts
190250
190204
  var CHAT_KEEP_DAYS = 30;
@@ -190277,24 +190231,228 @@ function readTaskChat(task, home4) {
190277
190231
  return lines;
190278
190232
  }
190279
190233
 
190234
+ // src/recovery.ts
190235
+ import fs55 from "node:fs";
190236
+ import path57 from "node:path";
190237
+ var recoveryBlocked = (job) => cloudLanguage(job) === "zh" ? "\u65E0\u6CD5\u6838\u5BF9\u4E0A\u6B21\u6267\u884C\uFF0C\u5DF2\u6709\u6210\u679C\u5DF2\u4FDD\u7559\u3002" : "The previous execution could not be verified. Saved work was preserved.";
190238
+ var checkpointDir = () => path57.join(runnerHome(), "checkpoints");
190239
+ var retryFileOf = (id2) => path57.join(checkpointDir(), `${encodeURIComponent(id2)}.retry`);
190240
+ var fileOf2 = (id2) => path57.join(checkpointDir(), `${encodeURIComponent(id2)}.json`);
190241
+ function readCheckpointFile(file3) {
190242
+ const held5 = JSON.parse(fs55.readFileSync(file3, "utf8"));
190243
+ if (!held5 || !Array.isArray(held5.pending) || !held5.pending.every((id2) => typeof id2 === "string")) throw new Error("\u8FDB\u5EA6\u683C\u5F0F\u9519\u8BEF");
190244
+ return held5;
190245
+ }
190246
+ function readCheckpoint(id2) {
190247
+ try {
190248
+ const held5 = readCheckpointFile(fileOf2(id2));
190249
+ const pending = held5.syncRetry;
190250
+ if (pending && Number.isSafeInteger(pending.attempt) && pending.attempt >= 1 && Number.isFinite(pending.at)) {
190251
+ held5.syncRetries ??= {};
190252
+ held5.syncRetries[pending.step] ??= { attempt: pending.attempt, at: pending.at };
190253
+ }
190254
+ delete held5.syncRetry;
190255
+ held5.failure = readFailure(held5.failure);
190256
+ held5.retryPause = readRetryPause(held5.retryPause);
190257
+ held5.retryHistory = readRetryHistory(held5.retryHistory);
190258
+ if (held5.retry?.pending) {
190259
+ const pending2 = readRetryPlan(held5.retry.pending, held5.retry.attempt);
190260
+ if (!pending2) held5.retry.at = held5.retry.pending.at ?? 0;
190261
+ held5.retry.pending = pending2;
190262
+ }
190263
+ const migrated = [held5.completed?.report, held5.ending?.report, held5.boardContinuation?.report].map((report2) => report2 && migrateGoalData(report2)).some(Boolean);
190264
+ if (migrated) saveCheckpoint(id2, held5);
190265
+ return held5;
190266
+ } catch (e2) {
190267
+ if (e2.code === "ENOENT") return null;
190268
+ return { updating: true, started: true, pending: ["unknown"] };
190269
+ }
190270
+ }
190271
+ function saveCheckpoint(id2, checkpoint) {
190272
+ const file3 = fileOf2(id2);
190273
+ fs55.mkdirSync(path57.dirname(file3), { recursive: true, mode: 448 });
190274
+ fs55.writeFileSync(`${file3}.tmp`, JSON.stringify(checkpoint), { mode: 384 });
190275
+ fs55.renameSync(`${file3}.tmp`, file3);
190276
+ }
190277
+ function reviewCheckpoints() {
190278
+ const dir = checkpointDir();
190279
+ let files;
190280
+ try {
190281
+ files = fs55.readdirSync(dir);
190282
+ } catch (e2) {
190283
+ if (e2.code === "ENOENT") return [];
190284
+ throw e2;
190285
+ }
190286
+ return files.filter((file3) => file3.endsWith(".json")).flatMap((file3) => {
190287
+ try {
190288
+ const marks = readCheckpointFile(path57.join(dir, file3)).reviewMarks;
190289
+ return marks ? [{ id: decodeURIComponent(path57.basename(file3, ".json")), marks }] : [];
190290
+ } catch {
190291
+ return [];
190292
+ }
190293
+ });
190294
+ }
190295
+ function clearCheckpoint(id2, { keepReviewMarks = false } = {}) {
190296
+ const checkpoint = readCheckpoint(id2);
190297
+ if (keepReviewMarks && checkpoint?.reviewMarks) return;
190298
+ fs55.rmSync(fileOf2(id2), { force: true });
190299
+ if (checkpoint) fs55.rmSync(retryFileOf(checkpoint.retryRound ?? id2), { force: true });
190300
+ }
190301
+ function checkpointEvent(checkpoint, event2) {
190302
+ if (turnSubmitted(event2)) checkpoint.submitted = true;
190303
+ if (event2.kind === "tool_call" && !isPollingTool(event2.data.title)) {
190304
+ const { toolCallId, status: status2, kind } = event2.data;
190305
+ if (!["read", "search", "fetch"].includes(kind)) checkpoint.effects = true;
190306
+ if (["completed", "failed"].includes(status2)) checkpoint.pending = checkpoint.pending.filter((id2) => id2 !== toolCallId);
190307
+ if (!["read", "search", "fetch"].includes(kind) && !["completed", "failed"].includes(status2) && !checkpoint.pending.includes(toolCallId)) checkpoint.pending.push(toolCallId);
190308
+ }
190309
+ if (event2.kind === "tool_call_update" && ["completed", "failed"].includes(event2.data.status)) {
190310
+ checkpoint.pending = checkpoint.pending.filter((id2) => id2 !== event2.data.toolCallId);
190311
+ }
190312
+ }
190313
+ async function stopReply(id2, timeout) {
190314
+ const checkpoint = readCheckpoint(id2);
190315
+ if (checkpoint?.managedProcess) return stopConnection(checkpoint.process, timeout);
190316
+ if (!checkpoint?.mark) return true;
190317
+ killMarked(checkpoint.mark, checkpoint.process);
190318
+ const until = Date.now() + timeout;
190319
+ while (!processesStopped(checkpoint.mark, checkpoint.process)) {
190320
+ if (Date.now() >= until) return false;
190321
+ await new Promise((resolve2) => setTimeout(resolve2, 50));
190322
+ }
190323
+ return true;
190324
+ }
190325
+ function replayable(checkpoint) {
190326
+ return !checkpoint.submissionUnknown && checkpoint.submitted !== true && checkpoint.effects !== true && (checkpoint.effects === false || checkpoint.started === false) && !checkpoint.pending.length && !checkpoint.opaque && !checkpoint.launching;
190327
+ }
190328
+ var isReply = (job) => !job.flow && !!(job.chat || job.discussion);
190329
+ var usesBoardRun = (job, checkpoint) => !checkpoint.boardContinuation && !!(job.flow || job.agent || job.review);
190330
+ function checkpointRecovery(job, checkpoint, stopped3, failure3, codex) {
190331
+ const board = usesBoardRun(job, checkpoint);
190332
+ const staticUnconfirmed = !!checkpoint.boardContinuation && checkpoint.pending.length > 0 || checkpoint.cleanup?.status === "unconfirmed" || failure3?.code === "codex_ownership_unconfirmed" || failure3?.code === "idle_timeout" && (checkpoint.pending.length > 0 || checkpoint.managedProcess && !idleStopConfirmed(checkpoint.cleanup, checkpoint.session));
190333
+ const verified = codex ?? (!board && !checkpoint.boardContinuation && stopped3 && job.runtime === "codex" && checkpoint.session && !isSessionMissingFailure(failure3) ? verifyCodexStopStateSync({
190334
+ session: checkpoint.session,
190335
+ cwd: job.projectDir ?? void 0,
190336
+ cleanup: checkpoint.cleanup,
190337
+ pendingIds: checkpoint.pending,
190338
+ taskId: job.task,
190339
+ needsBackendProbe: staticUnconfirmed
190340
+ }) : void 0);
190341
+ const effectiveStopped = stopped3 && (!verified || verified.stopped);
190342
+ if (verified && !verified.ownershipOk) return "unsafe";
190343
+ const unconfirmedCleanup = !!checkpoint.boardContinuation && checkpoint.pending.length > 0 || (verified?.found ? !verified.settled : staticUnconfirmed);
190344
+ const canReplay = failure3?.code !== "idle_timeout" && replayable(checkpoint) && (!board || checkpoint.started === false) && (job.runtime !== "antigravity" || checkpoint.started === false);
190345
+ if (isSessionMissingFailure(failure3)) {
190346
+ if (!effectiveStopped || unconfirmedCleanup) return "unsafe";
190347
+ return canReplay ? "replay" : "unsafe";
190348
+ }
190349
+ return agentRecovery({
190350
+ stopped: effectiveStopped,
190351
+ completed: !!checkpoint.ending || !!checkpoint.completed || board && checkpoint.flowRun?.finished,
190352
+ session: board ? checkpoint.flowRun?.id : checkpoint.opaque && !checkpoint.boardContinuation ? void 0 : checkpoint.session,
190353
+ replayable: canReplay,
190354
+ unconfirmedCleanup
190355
+ });
190356
+ }
190357
+ function replyRecovery(job, checkpoint, stopped3, codex) {
190358
+ const recovery = checkpointRecovery(job, checkpoint, stopped3, checkpoint.failure, codex);
190359
+ return { safe: recovery === "replay", stopped: stopped3 && (!codex || codex.stopped), resumable: recovery === "resume" };
190360
+ }
190361
+ async function recoverInterruptedJob(machine, job, checkpoint, stopped3, valid, reason) {
190362
+ if (!valid() || job.flow && !stopped3) return;
190363
+ const effectiveFailure = checkpoint ? checkpoint.retry?.pending?.failure ?? checkpoint.failure : void 0;
190364
+ const codex = checkpoint && !usesBoardRun(job, checkpoint) && !checkpoint.boardContinuation && stopped3 && job.runtime === "codex" && checkpoint.session && !isSessionMissingFailure(effectiveFailure) ? await verifyCodexStopState({
190365
+ session: checkpoint.session,
190366
+ cwd: job.projectDir ?? void 0,
190367
+ cleanup: checkpoint.cleanup,
190368
+ pendingIds: checkpoint.pending,
190369
+ taskId: job.task,
190370
+ needsBackendProbe: true
190371
+ }) : void 0;
190372
+ const recovery = checkpoint ? checkpointRecovery(job, checkpoint, stopped3, effectiveFailure, codex) : "unsafe";
190373
+ const effectiveStopped = stopped3 && (!codex || codex.stopped);
190374
+ const proof = effectiveStopped ? { processesStopped: true } : void 0;
190375
+ const reply = isReply(job);
190376
+ const report2 = reply && checkpoint ? {
190377
+ ...proof,
190378
+ session: checkpoint.session,
190379
+ reply: checkpoint.partialReply,
190380
+ ...replySpent(checkpoint, job.runtime),
190381
+ recovery: replyRecovery(job, checkpoint, effectiveStopped, codex)
190382
+ } : proof;
190383
+ if (checkpoint && recovery !== "unsafe" && job.flow?.phase !== "land") {
190384
+ const prepared = await finishJob(machine, job.id, "update_prepare", "", report2);
190385
+ if (!valid() || !prepared.ok) return;
190386
+ if (prepared.value.finished) {
190387
+ clearCheckpoint(job.id, { keepReviewMarks: true });
190388
+ return prepared.value;
190389
+ }
190390
+ if (!prepared.value.prepared) return;
190391
+ if (!checkpoint.updating) checkpoint.interrupted = true;
190392
+ if (job.flow) checkpoint.flowResume ??= job.flow.resume === true;
190393
+ checkpoint.updating = true;
190394
+ saveCheckpoint(job.id, checkpoint);
190395
+ const resumed = await finishJob(machine, job.id, "update_resume", "", report2 && { ...report2, session: void 0 });
190396
+ if (!valid() || !resumed.ok) return;
190397
+ if (resumed.value.finished) clearCheckpoint(job.id, { keepReviewMarks: true });
190398
+ return resumed.value;
190399
+ }
190400
+ const renewed = await renewJob(machine, job.id);
190401
+ if (!valid() || !renewed.ok) return;
190402
+ const requestedStop = renewed.value.stop;
190403
+ if (requestedStop && !stopped3) return;
190404
+ const message = reason ?? (reply ? "recovery_unsafe" : recoveryBlocked(job));
190405
+ const result = await finishJob(machine, job.id, requestedStop ? "stopped" : "failed", requestedStop ? "" : message, report2);
190406
+ if (!valid() || !result.ok) return;
190407
+ if (result.value.finished && checkpoint) {
190408
+ if (requestedStop) clearCheckpoint(job.id);
190409
+ else if (reply && report2 && !checkpoint.completed) {
190410
+ checkpoint.completed = { outcome: "failed", reason: message, report: report2 };
190411
+ saveCheckpoint(job.id, checkpoint);
190412
+ }
190413
+ }
190414
+ return result.value;
190415
+ }
190416
+ function replySpent(checkpoint, runtime) {
190417
+ const attempts = checkpoint.attempts ?? [];
190418
+ const used = attempts.filter((a2) => a2.usage);
190419
+ const costed = attempts.filter((a2) => a2.costUsd !== void 0);
190420
+ const sum = (key) => used.reduce((n, a2) => n + a2.usage[key], 0);
190421
+ const incomplete = costed.length > 0 && attempts.some((a2) => a2.costUsd === void 0 || a2.costIncomplete);
190422
+ const spent = {
190423
+ ...incomplete ? { costIncomplete: true } : {},
190424
+ ...used.length ? { usage: { input: sum("input"), cacheCreation: sum("cacheCreation"), cacheRead: sum("cacheRead"), output: sum("output") } } : {},
190425
+ ...costed.length ? { costUsd: costed.reduce((n, a2) => n + a2.costUsd, 0) } : {}
190426
+ };
190427
+ if (runtime !== "claude-code" || !attempts.length) return spent;
190428
+ return {
190429
+ ...incomplete ? { costIncomplete: true } : {},
190430
+ ...spent.usage ? { usage: spent.usage } : {},
190431
+ ...attempts.at(-1)?.costUsd !== void 0 ? { costUsd: attempts.at(-1).costUsd } : {},
190432
+ attemptCosts: attempts.map(({ resume, session, costUsd }) => ({ resume, session, costUsd }))
190433
+ };
190434
+ }
190435
+
190280
190436
  // src/chats.ts
190281
190437
  var DAY_MS2 = 24 * 60 * 6e4;
190282
- var REVIEW_EVERY_MS = DAY_MS2;
190438
+ var REVIEW_EVERY_MS = 6 * 60 * 6e4;
190283
190439
  var KEEP_MS2 = CHAT_KEEP_DAYS * DAY_MS2;
190284
190440
  var home3 = () => runnerHome();
190285
- var reviewedFile = () => path57.join(taskChatsDir(home3()), "reviewed.json");
190441
+ var reviewedFile = () => path58.join(taskChatsDir(home3()), "reviewed.json");
190286
190442
  function readReviewed2() {
190287
190443
  try {
190288
- const held5 = JSON.parse(fs55.readFileSync(reviewedFile(), "utf8"));
190444
+ const held5 = JSON.parse(fs56.readFileSync(reviewedFile(), "utf8"));
190289
190445
  return { checkedAt: Number(held5.checkedAt) || 0, tasks: held5.tasks ?? {} };
190290
190446
  } catch {
190291
190447
  return { checkedAt: 0, tasks: {} };
190292
190448
  }
190293
190449
  }
190294
190450
  function writeReviewed(reviewed) {
190295
- fs55.mkdirSync(path57.dirname(reviewedFile()), { recursive: true });
190296
- fs55.writeFileSync(reviewedFile(), `${JSON.stringify(reviewed, null, 2)}
190451
+ const file3 = reviewedFile();
190452
+ fs56.mkdirSync(path58.dirname(file3), { recursive: true });
190453
+ fs56.writeFileSync(`${file3}.tmp`, `${JSON.stringify(reviewed, null, 2)}
190297
190454
  `);
190455
+ fs56.renameSync(`${file3}.tmp`, file3);
190298
190456
  }
190299
190457
  function keepChat(job, reply, at2 = Date.now()) {
190300
190458
  if (!job.task || !job.chat || !reply?.trim()) return;
@@ -190303,16 +190461,16 @@ function keepChat(job, reply, at2 = Date.now()) {
190303
190461
  { id: job.id, role: "agent", text: reply, at: at2, runtime: job.runtime, model: job.model ?? null }
190304
190462
  ];
190305
190463
  const file3 = taskChatFile(job.task, home3());
190306
- fs55.mkdirSync(path57.dirname(file3), { recursive: true });
190307
- fs55.appendFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
190464
+ fs56.mkdirSync(path58.dirname(file3), { recursive: true });
190465
+ fs56.appendFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
190308
190466
  `).join(""));
190309
190467
  }
190310
190468
  function keepCloudChat(task, messages) {
190311
190469
  const file3 = taskChatFile(task, home3());
190312
- if (!messages.length) return fs55.rmSync(file3, { force: true });
190470
+ if (!messages.length) return fs56.rmSync(file3, { force: true });
190313
190471
  const lines = messages.map((m) => ({ id: m.id, role: m.role, text: m.body, at: Date.parse(m.created_at) || Date.now() }));
190314
- fs55.mkdirSync(path57.dirname(file3), { recursive: true });
190315
- fs55.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
190472
+ fs56.mkdirSync(path58.dirname(file3), { recursive: true });
190473
+ fs56.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
190316
190474
  `).join(""));
190317
190475
  }
190318
190476
  async function keepDecisions(task, read6) {
@@ -190330,14 +190488,14 @@ async function keepDecisions(task, read6) {
190330
190488
  const ids = new Set(comments2.map((c2) => c2.id));
190331
190489
  const lines = [...readTaskChat(task, home3()).filter((l2) => !ids.has(l2.id)), ...comments2].sort((a2, b2) => a2.at - b2.at);
190332
190490
  const file3 = taskChatFile(task, home3());
190333
- fs55.mkdirSync(path57.dirname(file3), { recursive: true });
190334
- fs55.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
190491
+ fs56.mkdirSync(path58.dirname(file3), { recursive: true });
190492
+ fs56.writeFileSync(file3, lines.map((l2) => `${JSON.stringify(l2)}
190335
190493
  `).join(""));
190336
190494
  return true;
190337
190495
  }
190338
190496
  var tasksKept = () => {
190339
190497
  try {
190340
- return fs55.readdirSync(taskChatsDir(home3())).map((n) => /^([\w-]{1,100})\.jsonl$/.exec(n)?.[1]).filter((t2) => !!t2);
190498
+ return fs56.readdirSync(taskChatsDir(home3())).map((n) => /^([\w-]{1,100})\.jsonl$/.exec(n)?.[1]).filter((t2) => !!t2);
190341
190499
  } catch {
190342
190500
  return [];
190343
190501
  }
@@ -190348,9 +190506,9 @@ function pruneChats(now = Date.now()) {
190348
190506
  const kept4 = lines.filter((l2) => now - l2.at < KEEP_MS2);
190349
190507
  if (kept4.length === lines.length) continue;
190350
190508
  const file3 = taskChatFile(task, home3());
190351
- if (kept4.length) fs55.writeFileSync(file3, kept4.map((l2) => `${JSON.stringify(l2)}
190509
+ if (kept4.length) fs56.writeFileSync(file3, kept4.map((l2) => `${JSON.stringify(l2)}
190352
190510
  `).join(""));
190353
- else fs55.rmSync(file3, { force: true });
190511
+ else fs56.rmSync(file3, { force: true });
190354
190512
  }
190355
190513
  }
190356
190514
  var lastOf = (task) => readTaskChat(task, home3()).at(-1);
@@ -190362,41 +190520,81 @@ function markReviewed2(marks) {
190362
190520
  const reviewed = readReviewed2();
190363
190521
  writeReviewed({ ...reviewed, tasks: { ...reviewed.tasks, ...marks } });
190364
190522
  }
190523
+ async function reconcileReviews(chats) {
190524
+ const checked = await Promise.all(reviewCheckpoints().map(async (saved) => ({ ...saved, status: await readJob(saved.id) })));
190525
+ const archives = new Map(chats.map(({ task, archivedAt }) => [task, archivedAt]));
190526
+ const deferred = /* @__PURE__ */ new Set();
190527
+ for (const { id: id2, marks, status: status2 } of checked) {
190528
+ const finished = status2.ok && status2.value.job.id === id2 && status2.value.job.state === "finished";
190529
+ if (finished && status2.value.job.outcome !== "done") {
190530
+ clearCheckpoint(id2);
190531
+ continue;
190532
+ }
190533
+ const matching = Object.entries(marks).filter(([task, mark]) => archives.get(task) === mark.archivedAt && lastOf(task)?.id === mark.message);
190534
+ if (!finished) {
190535
+ for (const [task] of matching) deferred.add(task);
190536
+ continue;
190537
+ }
190538
+ if (matching.length) markReviewed2(Object.fromEntries(matching));
190539
+ clearCheckpoint(id2);
190540
+ }
190541
+ return deferred;
190542
+ }
190365
190543
  async function reviewChats(machineId2, runtimes, now = Date.now()) {
190366
- const reviewed = readReviewed2();
190367
- if (now - reviewed.checkedAt < REVIEW_EVERY_MS) return;
190368
- pruneChats(now);
190369
190544
  const owned = await listChats(machineId2);
190370
- if (!owned.ok) return;
190545
+ if (!owned.ok) return false;
190546
+ const settings = owned.value.projects;
190547
+ const checkedAt = readReviewed2().checkedAt;
190548
+ if (!settings && now - checkedAt < REVIEW_EVERY_MS) return false;
190549
+ const swept = now - checkedAt >= REVIEW_EVERY_MS;
190550
+ if (swept) pruneChats(now);
190551
+ const deferred = await reconcileReviews(owned.value.chats);
190552
+ const reviewed = readReviewed2();
190371
190553
  const byProject = /* @__PURE__ */ new Map();
190554
+ const unresolved = /* @__PURE__ */ new Set();
190372
190555
  for (const { task, project, archivedAt } of owned.value.chats) {
190556
+ if (deferred.has(task)) {
190557
+ unresolved.add(project);
190558
+ continue;
190559
+ }
190373
190560
  const mark = reviewed.tasks[task];
190374
190561
  const last2 = lastOf(task);
190375
190562
  if (mark?.archivedAt === archivedAt && (!last2 || last2.id === mark.message)) continue;
190376
- byProject.set(project, [...byProject.get(project) ?? [], task]);
190563
+ const tasks = byProject.get(project) ?? [];
190564
+ if (tasks.length < 100) tasks.push(task);
190565
+ byProject.set(project, tasks);
190377
190566
  }
190378
190567
  const signedIn = runtimes.find((r2) => r2.installed && r2.loggedIn !== false)?.name;
190379
- for (const [project, tasks] of [...byProject].map(([p2, t2]) => [p2, t2.slice(0, 100)])) {
190568
+ const candidates = settings ? settings.filter((s) => s.manual || s.on && byProject.has(s.project) && agentDue(s, now)) : [...byProject.keys()].map((project) => ({ project, manual: false, expected: void 0 }));
190569
+ let queued2 = false;
190570
+ for (const { project, manual, expected } of candidates) {
190571
+ const tasks = byProject.get(project) ?? [];
190572
+ if (!tasks.length && (!manual || unresolved.has(project))) continue;
190380
190573
  const replied = tasks.flatMap((t2) => readTaskChat(t2, home3())).filter((l2) => l2.runtime).sort((a2, b2) => a2.at - b2.at).at(-1);
190381
190574
  const runtime = replied?.runtime ?? signedIn ?? "claude-code";
190382
- const sent = await dispatchReview(machineId2, project, tasks, runtime, replied?.model ?? null);
190575
+ const sent = await dispatchReview(machineId2, project, tasks, runtime, replied?.model ?? null, expected);
190383
190576
  if (!sent.ok) console.error(`runner: the chats of ${project} were not sent for review: ${sent.error}`);
190577
+ else if (sent.value.job) queued2 = true;
190384
190578
  }
190385
190579
  const listed = new Set(owned.value.chats.map((c2) => c2.task));
190386
190580
  const held5 = readReviewed2();
190387
- writeReviewed({ checkedAt: now, tasks: Object.fromEntries(Object.entries(held5.tasks).filter(([t2]) => listed.has(t2))) });
190581
+ const kept4 = Object.entries(held5.tasks).filter(([t2]) => listed.has(t2));
190582
+ if (swept || kept4.length !== Object.keys(held5.tasks).length) {
190583
+ writeReviewed({ checkedAt: swept ? now : held5.checkedAt, tasks: Object.fromEntries(kept4) });
190584
+ }
190585
+ return queued2;
190388
190586
  }
190389
190587
 
190390
190588
  // src/board-watch.ts
190391
- import fs56 from "node:fs";
190392
- import path58 from "node:path";
190589
+ import fs57 from "node:fs";
190590
+ import path59 from "node:path";
190393
190591
  var LOOK_MS = 6e4;
190394
190592
  var PULL_MS = 2e3;
190395
190593
  var BUSY_MS = 3e4;
190396
190594
  function keptFolders() {
190397
190595
  let cached3 = [];
190398
190596
  try {
190399
- cached3 = fs56.readdirSync(cacheRoot()).map((name) => fs56.realpathSync(path58.join(cacheRoot(), name)));
190597
+ cached3 = fs57.readdirSync(cacheRoot()).map((name) => fs57.realpathSync(path59.join(cacheRoot(), name)));
190400
190598
  } catch {
190401
190599
  }
190402
190600
  return [.../* @__PURE__ */ new Set([...allowedProjects(), ...cached3])].flatMap((dir) => [keptBoard(dir)].filter((ws) => !!ws));
@@ -190465,16 +190663,16 @@ function watchBoards(machineId2, ms, lookMs = LOOK_MS, pullMs = PULL_MS, busyMs
190465
190663
  const watchers = [];
190466
190664
  try {
190467
190665
  const state = ensureProjectState(ws.board);
190468
- const parent = path58.dirname(ws.board);
190469
- const assets = path58.relative(ws.board, path58.join(state, "assets")).split(path58.sep).join("/");
190470
- const watchRoot = (root2) => fs56.watch(root2, { recursive: true }, (_event, name) => {
190471
- const p2 = name && path58.relative(ws.board, path58.join(root2, String(name))).split(path58.sep).join("/");
190666
+ const parent = path59.dirname(ws.board);
190667
+ const assets = path59.relative(ws.board, path59.join(state, "assets")).split(path59.sep).join("/");
190668
+ const watchRoot = (root2) => fs57.watch(root2, { recursive: true }, (_event, name) => {
190669
+ const p2 = name && path59.relative(ws.board, path59.join(root2, String(name))).split(path59.sep).join("/");
190472
190670
  const held5 = watched.get(ws.cwd);
190473
190671
  if (closed || !p2 || !held5) return;
190474
190672
  const syncRecord = /^\.sync\/[\w-]+\.json$/.test(p2);
190475
190673
  if (!isBoardPath(p2) && !/^(?:todo|\.archive|memory|assets|studios|triage|rules)(?:\/|$)/.test(p2) && p2 !== assets && !p2.startsWith(`${assets}/`) && !taskOfRemoval(p2) && !syncRecord) return;
190476
190674
  if (p2 === "todo/README.md") return;
190477
- if (syncRecord && (held5.sending || Date.now() < held5.retryAt) && fs56.existsSync(path58.join(ws.board, p2))) return;
190675
+ if (syncRecord && (held5.sending || Date.now() < held5.retryAt) && fs57.existsSync(path59.join(ws.board, p2))) return;
190478
190676
  if (!p2.startsWith(".sync/")) held5.retryAt = 0;
190479
190677
  held5.paths.add(p2);
190480
190678
  const job = busy(ws.cwd);
@@ -190484,7 +190682,7 @@ function watchBoards(machineId2, ms, lookMs = LOOK_MS, pullMs = PULL_MS, busyMs
190484
190682
  held5.timer = setTimeout(() => void flush(ws), Math.max(ms, held5.retryAt - Date.now(), job ? held5.sentAt + busyMs - Date.now() : 0));
190485
190683
  });
190486
190684
  watchers.push(watchRoot(parent));
190487
- if (!state.startsWith(parent + path58.sep)) watchers.push(watchRoot(state));
190685
+ if (!state.startsWith(parent + path59.sep)) watchers.push(watchRoot(state));
190488
190686
  } catch (error62) {
190489
190687
  for (const watcher of watchers) watcher.close();
190490
190688
  console.error(`runner: the board in ${ws.cwd} could not be watched: ${error62}`);
@@ -190542,8 +190740,8 @@ function watchBoards(machineId2, ms, lookMs = LOOK_MS, pullMs = PULL_MS, busyMs
190542
190740
 
190543
190741
  // src/diff.ts
190544
190742
  import { execFile as execFile2 } from "node:child_process";
190545
- import fs57 from "node:fs";
190546
- import path59 from "node:path";
190743
+ import fs58 from "node:fs";
190744
+ import path60 from "node:path";
190547
190745
  var FILE_BYTES = 256 * 1024;
190548
190746
  var TOTAL_BYTES = 1024 * 1024;
190549
190747
  var EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
@@ -190560,7 +190758,7 @@ var git2 = (dir, args2, maxBuffer = 4 * TOTAL_BYTES) => new Promise(
190560
190758
  function projectDir(placed, project) {
190561
190759
  if (placed) {
190562
190760
  const real2 = realpath3(placed);
190563
- return real2 && allowedProjects().some((root2) => real2 === root2 || real2.startsWith(root2 + path59.sep)) ? real2 : null;
190761
+ return real2 && allowedProjects().some((root2) => real2 === root2 || real2.startsWith(root2 + path60.sep)) ? real2 : null;
190564
190762
  }
190565
190763
  let cached3;
190566
190764
  try {
@@ -190568,11 +190766,11 @@ function projectDir(placed, project) {
190568
190766
  } catch {
190569
190767
  return null;
190570
190768
  }
190571
- return fs57.existsSync(path59.join(cached3, ".git")) ? cached3 : null;
190769
+ return fs58.existsSync(path60.join(cached3, ".git")) ? cached3 : null;
190572
190770
  }
190573
190771
  function realpath3(p2) {
190574
190772
  try {
190575
- return fs57.realpathSync(p2);
190773
+ return fs58.realpathSync(p2);
190576
190774
  } catch {
190577
190775
  return null;
190578
190776
  }
@@ -190619,184 +190817,6 @@ async function answerHint(machineId2, hint2) {
190619
190817
  // ../cli/src/prompts/verify-delivery.md
190620
190818
  var verify_delivery_default = "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.\n";
190621
190819
 
190622
- // src/recovery.ts
190623
- import fs58 from "node:fs";
190624
- import path60 from "node:path";
190625
- var recoveryBlocked = (job) => cloudLanguage(job) === "zh" ? "\u65E0\u6CD5\u6838\u5BF9\u4E0A\u6B21\u6267\u884C\uFF0C\u5DF2\u6709\u6210\u679C\u5DF2\u4FDD\u7559\u3002" : "The previous execution could not be verified. Saved work was preserved.";
190626
- var retryFileOf = (id2) => path60.join(runnerHome(), "checkpoints", `${encodeURIComponent(id2)}.retry`);
190627
- var fileOf2 = (id2) => path60.join(runnerHome(), "checkpoints", `${encodeURIComponent(id2)}.json`);
190628
- function readCheckpoint(id2) {
190629
- try {
190630
- const held5 = JSON.parse(fs58.readFileSync(fileOf2(id2), "utf8"));
190631
- if (!held5 || !Array.isArray(held5.pending) || !held5.pending.every((id3) => typeof id3 === "string")) throw new Error("\u8FDB\u5EA6\u683C\u5F0F\u9519\u8BEF");
190632
- const pending = held5.syncRetry;
190633
- if (pending && Number.isSafeInteger(pending.attempt) && pending.attempt >= 1 && Number.isFinite(pending.at)) {
190634
- held5.syncRetries ??= {};
190635
- held5.syncRetries[pending.step] ??= { attempt: pending.attempt, at: pending.at };
190636
- }
190637
- delete held5.syncRetry;
190638
- held5.failure = readFailure(held5.failure);
190639
- held5.retryPause = readRetryPause(held5.retryPause);
190640
- held5.retryHistory = readRetryHistory(held5.retryHistory);
190641
- if (held5.retry?.pending) {
190642
- const pending2 = readRetryPlan(held5.retry.pending, held5.retry.attempt);
190643
- if (!pending2) held5.retry.at = held5.retry.pending.at ?? 0;
190644
- held5.retry.pending = pending2;
190645
- }
190646
- const migrated = [held5.completed?.report, held5.ending?.report, held5.boardContinuation?.report].map((report2) => report2 && migrateGoalData(report2)).some(Boolean);
190647
- if (migrated) saveCheckpoint(id2, held5);
190648
- return held5;
190649
- } catch (e2) {
190650
- if (e2.code === "ENOENT") return null;
190651
- return { updating: true, started: true, pending: ["unknown"] };
190652
- }
190653
- }
190654
- function saveCheckpoint(id2, checkpoint) {
190655
- const file3 = fileOf2(id2);
190656
- fs58.mkdirSync(path60.dirname(file3), { recursive: true, mode: 448 });
190657
- fs58.writeFileSync(`${file3}.tmp`, JSON.stringify(checkpoint), { mode: 384 });
190658
- fs58.renameSync(`${file3}.tmp`, file3);
190659
- }
190660
- function clearCheckpoint(id2) {
190661
- const checkpoint = readCheckpoint(id2);
190662
- fs58.rmSync(fileOf2(id2), { force: true });
190663
- if (checkpoint) fs58.rmSync(retryFileOf(checkpoint.retryRound ?? id2), { force: true });
190664
- }
190665
- function checkpointEvent(checkpoint, event2) {
190666
- if (turnSubmitted(event2)) checkpoint.submitted = true;
190667
- if (event2.kind === "tool_call" && !isPollingTool(event2.data.title)) {
190668
- const { toolCallId, status: status2, kind } = event2.data;
190669
- if (!["read", "search", "fetch"].includes(kind)) checkpoint.effects = true;
190670
- if (["completed", "failed"].includes(status2)) checkpoint.pending = checkpoint.pending.filter((id2) => id2 !== toolCallId);
190671
- if (!["read", "search", "fetch"].includes(kind) && !["completed", "failed"].includes(status2) && !checkpoint.pending.includes(toolCallId)) checkpoint.pending.push(toolCallId);
190672
- }
190673
- if (event2.kind === "tool_call_update" && ["completed", "failed"].includes(event2.data.status)) {
190674
- checkpoint.pending = checkpoint.pending.filter((id2) => id2 !== event2.data.toolCallId);
190675
- }
190676
- }
190677
- async function stopReply(id2, timeout) {
190678
- const checkpoint = readCheckpoint(id2);
190679
- if (checkpoint?.managedProcess) return stopConnection(checkpoint.process, timeout);
190680
- if (!checkpoint?.mark) return true;
190681
- killMarked(checkpoint.mark, checkpoint.process);
190682
- const until = Date.now() + timeout;
190683
- while (!processesStopped(checkpoint.mark, checkpoint.process)) {
190684
- if (Date.now() >= until) return false;
190685
- await new Promise((resolve2) => setTimeout(resolve2, 50));
190686
- }
190687
- return true;
190688
- }
190689
- function replayable(checkpoint) {
190690
- return !checkpoint.submissionUnknown && checkpoint.submitted !== true && checkpoint.effects !== true && (checkpoint.effects === false || checkpoint.started === false) && !checkpoint.pending.length && !checkpoint.opaque && !checkpoint.launching;
190691
- }
190692
- var isReply = (job) => !job.flow && !!(job.chat || job.discussion);
190693
- var usesBoardRun = (job, checkpoint) => !checkpoint.boardContinuation && !!(job.flow || job.agent || job.review);
190694
- function checkpointRecovery(job, checkpoint, stopped3, failure3, codex) {
190695
- const board = usesBoardRun(job, checkpoint);
190696
- const staticUnconfirmed = !!checkpoint.boardContinuation && checkpoint.pending.length > 0 || checkpoint.cleanup?.status === "unconfirmed" || failure3?.code === "codex_ownership_unconfirmed" || failure3?.code === "idle_timeout" && (checkpoint.pending.length > 0 || checkpoint.managedProcess && !idleStopConfirmed(checkpoint.cleanup, checkpoint.session));
190697
- const verified = codex ?? (!board && !checkpoint.boardContinuation && stopped3 && job.runtime === "codex" && checkpoint.session && !isSessionMissingFailure(failure3) ? verifyCodexStopStateSync({
190698
- session: checkpoint.session,
190699
- cwd: job.projectDir ?? void 0,
190700
- cleanup: checkpoint.cleanup,
190701
- pendingIds: checkpoint.pending,
190702
- taskId: job.task,
190703
- needsBackendProbe: staticUnconfirmed
190704
- }) : void 0);
190705
- const effectiveStopped = stopped3 && (!verified || verified.stopped);
190706
- if (verified && !verified.ownershipOk) return "unsafe";
190707
- const unconfirmedCleanup = !!checkpoint.boardContinuation && checkpoint.pending.length > 0 || (verified?.found ? !verified.settled : staticUnconfirmed);
190708
- const canReplay = failure3?.code !== "idle_timeout" && replayable(checkpoint) && (!board || checkpoint.started === false) && (job.runtime !== "antigravity" || checkpoint.started === false);
190709
- if (isSessionMissingFailure(failure3)) {
190710
- if (!effectiveStopped || unconfirmedCleanup) return "unsafe";
190711
- return canReplay ? "replay" : "unsafe";
190712
- }
190713
- return agentRecovery({
190714
- stopped: effectiveStopped,
190715
- completed: !!checkpoint.ending || !!checkpoint.completed || board && checkpoint.flowRun?.finished,
190716
- session: board ? checkpoint.flowRun?.id : checkpoint.opaque && !checkpoint.boardContinuation ? void 0 : checkpoint.session,
190717
- replayable: canReplay,
190718
- unconfirmedCleanup
190719
- });
190720
- }
190721
- function replyRecovery(job, checkpoint, stopped3, codex) {
190722
- const recovery = checkpointRecovery(job, checkpoint, stopped3, checkpoint.failure, codex);
190723
- return { safe: recovery === "replay", stopped: stopped3 && (!codex || codex.stopped), resumable: recovery === "resume" };
190724
- }
190725
- async function recoverInterruptedJob(machine, job, checkpoint, stopped3, valid, reason) {
190726
- if (!valid() || job.flow && !stopped3) return;
190727
- const effectiveFailure = checkpoint ? checkpoint.retry?.pending?.failure ?? checkpoint.failure : void 0;
190728
- const codex = checkpoint && !usesBoardRun(job, checkpoint) && !checkpoint.boardContinuation && stopped3 && job.runtime === "codex" && checkpoint.session && !isSessionMissingFailure(effectiveFailure) ? await verifyCodexStopState({
190729
- session: checkpoint.session,
190730
- cwd: job.projectDir ?? void 0,
190731
- cleanup: checkpoint.cleanup,
190732
- pendingIds: checkpoint.pending,
190733
- taskId: job.task,
190734
- needsBackendProbe: true
190735
- }) : void 0;
190736
- const recovery = checkpoint ? checkpointRecovery(job, checkpoint, stopped3, effectiveFailure, codex) : "unsafe";
190737
- const effectiveStopped = stopped3 && (!codex || codex.stopped);
190738
- const proof = effectiveStopped ? { processesStopped: true } : void 0;
190739
- const reply = isReply(job);
190740
- const report2 = reply && checkpoint ? {
190741
- ...proof,
190742
- session: checkpoint.session,
190743
- reply: checkpoint.partialReply,
190744
- ...replySpent(checkpoint, job.runtime),
190745
- recovery: replyRecovery(job, checkpoint, effectiveStopped, codex)
190746
- } : proof;
190747
- if (checkpoint && recovery !== "unsafe" && job.flow?.phase !== "land") {
190748
- const prepared = await finishJob(machine, job.id, "update_prepare", "", report2);
190749
- if (!valid() || !prepared.ok) return;
190750
- if (prepared.value.finished) {
190751
- clearCheckpoint(job.id);
190752
- return prepared.value;
190753
- }
190754
- if (!prepared.value.prepared) return;
190755
- if (!checkpoint.updating) checkpoint.interrupted = true;
190756
- if (job.flow) checkpoint.flowResume ??= job.flow.resume === true;
190757
- checkpoint.updating = true;
190758
- saveCheckpoint(job.id, checkpoint);
190759
- const resumed = await finishJob(machine, job.id, "update_resume", "", report2 && { ...report2, session: void 0 });
190760
- if (!valid() || !resumed.ok) return;
190761
- if (resumed.value.finished) clearCheckpoint(job.id);
190762
- return resumed.value;
190763
- }
190764
- const renewed = await renewJob(machine, job.id);
190765
- if (!valid() || !renewed.ok) return;
190766
- const requestedStop = renewed.value.stop;
190767
- if (requestedStop && !stopped3) return;
190768
- const message = reason ?? (reply ? "recovery_unsafe" : recoveryBlocked(job));
190769
- const result = await finishJob(machine, job.id, requestedStop ? "stopped" : "failed", requestedStop ? "" : message, report2);
190770
- if (!valid() || !result.ok) return;
190771
- if (result.value.finished && checkpoint) {
190772
- if (requestedStop) clearCheckpoint(job.id);
190773
- else if (reply && report2 && !checkpoint.completed) {
190774
- checkpoint.completed = { outcome: "failed", reason: message, report: report2 };
190775
- saveCheckpoint(job.id, checkpoint);
190776
- }
190777
- }
190778
- return result.value;
190779
- }
190780
- function replySpent(checkpoint, runtime) {
190781
- const attempts = checkpoint.attempts ?? [];
190782
- const used = attempts.filter((a2) => a2.usage);
190783
- const costed = attempts.filter((a2) => a2.costUsd !== void 0);
190784
- const sum = (key) => used.reduce((n, a2) => n + a2.usage[key], 0);
190785
- const incomplete = costed.length > 0 && attempts.some((a2) => a2.costUsd === void 0 || a2.costIncomplete);
190786
- const spent = {
190787
- ...incomplete ? { costIncomplete: true } : {},
190788
- ...used.length ? { usage: { input: sum("input"), cacheCreation: sum("cacheCreation"), cacheRead: sum("cacheRead"), output: sum("output") } } : {},
190789
- ...costed.length ? { costUsd: costed.reduce((n, a2) => n + a2.costUsd, 0) } : {}
190790
- };
190791
- if (runtime !== "claude-code" || !attempts.length) return spent;
190792
- return {
190793
- ...incomplete ? { costIncomplete: true } : {},
190794
- ...spent.usage ? { usage: spent.usage } : {},
190795
- ...attempts.at(-1)?.costUsd !== void 0 ? { costUsd: attempts.at(-1).costUsd } : {},
190796
- attemptCosts: attempts.map(({ resume, session, costUsd }) => ({ resume, session, costUsd }))
190797
- };
190798
- }
190799
-
190800
190820
  // src/flow.ts
190801
190821
  import fs81 from "node:fs";
190802
190822
  import os12 from "node:os";
@@ -192414,7 +192434,7 @@ function dirtyCards(top, spec) {
192414
192434
  }
192415
192435
  return dirty;
192416
192436
  }
192417
- var DAY2 = 24 * 60 * 60 * 1e3;
192437
+ var DAY = 24 * 60 * 60 * 1e3;
192418
192438
  function cardAges(now = Date.now()) {
192419
192439
  const top = gitTop();
192420
192440
  const spec = top && todoPathspec(top);
@@ -192434,7 +192454,7 @@ function cardAges(now = Date.now()) {
192434
192454
  if (!file3 || ages.has(file3) || dirty.has(file3)) continue;
192435
192455
  const at2 = Date.parse(when);
192436
192456
  if (Number.isNaN(at2)) continue;
192437
- ages.set(file3, { lastTouched: when.slice(0, 10), days: Math.max(0, Math.floor((now - at2) / DAY2)) });
192457
+ ages.set(file3, { lastTouched: when.slice(0, 10), days: Math.max(0, Math.floor((now - at2) / DAY)) });
192438
192458
  }
192439
192459
  return ages;
192440
192460
  }
@@ -197035,6 +197055,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
197035
197055
  return result;
197036
197056
  });
197037
197057
  if (sent.ok && sent.value) {
197058
+ if (outcome === "done" && checkpoint.reviewMarks) markReviewed2(checkpoint.reviewMarks);
197038
197059
  if (archive && ws) {
197039
197060
  noteLandArchive(ws.cwd, job, report2);
197040
197061
  queueDeliveryCleanup(ws.cwd);
@@ -197067,7 +197088,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
197067
197088
  };
197068
197089
  const remote3 = await readJob(id2);
197069
197090
  if (remote3.ok && remote3.value.job.state === "finished") {
197070
- clearCheckpoint(id2);
197091
+ clearCheckpoint(id2, { keepReviewMarks: remote3.value.job.outcome === "done" });
197071
197092
  return remote3.value.job.outcome === outcome;
197072
197093
  }
197073
197094
  checkpoint.ending = { outcome: "failed", reason: failure4.summary, report: failed, unconfirmed: true };
@@ -197843,7 +197864,7 @@ ${body}` : body;
197843
197864
  if (!stream.lost()) return finishClaimed(stream.asked() ? "stopped" : "failed", ended2.reason);
197844
197865
  return;
197845
197866
  }
197846
- return !stream.lost() ? sendResult(ended2.report, () => markReviewed2(marks)) : void 0;
197867
+ return !stream.lost() ? sendResult(ended2.report) : void 0;
197847
197868
  }
197848
197869
  if (!run3) {
197849
197870
  if (checkpoint.syncRetries?.repair && (io.repairDelivery || checkpoint.syncRetries.repair.record?.code === "board_command_interrupted")) {
@@ -199206,7 +199227,6 @@ async function reclaimFlowWorkers(machine, given, only, retryWaiting = false) {
199206
199227
  var HEARTBEAT_MS2 = 10 * 6e4;
199207
199228
  var POLL_MS = 6e4;
199208
199229
  var BACKOFF_MS3 = [1e3, 2e3, 5e3, 1e4, 3e4];
199209
- var LOOK_LATE_MS = 6e4;
199210
199230
  function startRunner(options, lock) {
199211
199231
  const account = readSession()?.subject;
199212
199232
  const generation = accountGeneration();
@@ -199300,15 +199320,29 @@ function startRunner(options, lock) {
199300
199320
  timer = setTimeout(tick, ms);
199301
199321
  };
199302
199322
  let looking = false;
199323
+ let lookAgain = false;
199303
199324
  const agentsDue = async () => {
199304
- if (looking || closed || !connected || !registration) return;
199325
+ if (closed || !connected || !registration || !validAccount()) return;
199326
+ if (looking) {
199327
+ lookAgain = true;
199328
+ return;
199329
+ }
199305
199330
  looking = true;
199306
199331
  try {
199307
- if (await askDueAgents(registration.machineId)) void readJobs();
199332
+ const { machineId: machineId2, runtimes } = registration;
199333
+ const results = await Promise.allSettled([askDueAgents(machineId2), reviewChats(machineId2, runtimes)]);
199334
+ for (const result of results) {
199335
+ if (result.status === "rejected") console.error("runner: scheduled runs could not be checked", result.reason);
199336
+ }
199337
+ if (results.some((result) => result.status === "fulfilled" && result.value)) void readJobs();
199308
199338
  } catch (e2) {
199309
199339
  console.error(`runner: the periodic agents were not looked at: ${e2 instanceof Error ? e2.message : String(e2)}`);
199310
199340
  } finally {
199311
199341
  looking = false;
199342
+ if (lookAgain) {
199343
+ lookAgain = false;
199344
+ void agentsDue();
199345
+ }
199312
199346
  }
199313
199347
  };
199314
199348
  let triageChecked = 0;
@@ -199328,12 +199362,12 @@ function startRunner(options, lock) {
199328
199362
  let agentsTimer = null;
199329
199363
  const lookNext = () => {
199330
199364
  if (closed) return;
199331
- const at2 = (options.nextLook ?? nextHour)(Date.now());
199365
+ const now = Date.now();
199366
+ const at2 = (options.nextLook ?? nextMinute)(now);
199332
199367
  agentsTimer = setTimeout(() => {
199333
- const late = Date.now() - at2;
199334
- if (late >= 0 && late < LOOK_LATE_MS) void agentsDue();
199368
+ void agentsDue();
199335
199369
  lookNext();
199336
- }, at2 - Date.now());
199370
+ }, Math.max(10, at2 - now));
199337
199371
  agentsTimer.unref?.();
199338
199372
  };
199339
199373
  lookNext();
@@ -199409,11 +199443,7 @@ function startRunner(options, lock) {
199409
199443
  const { watchMs } = deps();
199410
199444
  if (watchMs !== null) boards ??= watchBoards(registration.machineId, watchMs);
199411
199445
  void deps().runtimes();
199412
- }
199413
- try {
199414
- await reviewChats(registration.machineId, registration.runtimes);
199415
- } catch (error62) {
199416
- console.error("runner: conversation memory review could not be scheduled", error62);
199446
+ void agentsDue();
199417
199447
  }
199418
199448
  await readJobs();
199419
199449
  void triageDue();
@@ -199427,6 +199457,10 @@ function startRunner(options, lock) {
199427
199457
  live = connectCloudLive({
199428
199458
  topic: `runner:${subject}`,
199429
199459
  onHint: (payload) => {
199460
+ if (payload.schedule === true) {
199461
+ void agentsDue();
199462
+ return;
199463
+ }
199430
199464
  if (payload.diff) {
199431
199465
  if (registration) void answerHint(registration.machineId, payload);
199432
199466
  return;
@@ -199445,7 +199479,8 @@ function startRunner(options, lock) {
199445
199479
  void readJobs("realtime");
199446
199480
  }
199447
199481
  },
199448
- onReady: () => {
199482
+ onReady: (firstTime) => {
199483
+ if (!firstTime) void agentsDue();
199449
199484
  void sweep();
199450
199485
  void readJobs("reconnected");
199451
199486
  boards?.pullAll();
@@ -199526,7 +199561,7 @@ function startRunner(options, lock) {
199526
199561
  if (!current2.ok || current2.value.job.id !== job.id) continue;
199527
199562
  const original = current2.value.job;
199528
199563
  if (original.state === "finished" && (original.outcome === "done" || original.outcome === "stopped")) {
199529
- clearCheckpoint(job.id);
199564
+ clearCheckpoint(job.id, { keepReviewMarks: original.outcome === "done" });
199530
199565
  }
199531
199566
  if (original.state !== "claimed" && original.state !== "interrupted") continue;
199532
199567
  const step = deps();
package/dist/settings.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.133 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.134 — 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;
@@ -41822,8 +41822,8 @@ function cloudProblem(response, body) {
41822
41822
  }
41823
41823
 
41824
41824
  // src/protocol.ts
41825
- var VERSION = true ? "0.6.133" : "0.0.0";
41826
- var AKB_VERSION = true ? "0.11.114" : "0.0.0";
41825
+ var VERSION = true ? "0.6.134" : "0.0.0";
41826
+ var AKB_VERSION = true ? "0.11.115" : "0.0.0";
41827
41827
 
41828
41828
  // ../cli/src/lib/agent/harnesses/antigravity.ts
41829
41829
  import fs11 from "node:fs";
@@ -43035,7 +43035,7 @@ function createTail(log) {
43035
43035
  // ../cli/package.json
43036
43036
  var package_default = {
43037
43037
  name: "wildcrane",
43038
- version: "0.11.114",
43038
+ version: "0.11.115",
43039
43039
  akbContract: 45,
43040
43040
  canonicalCommands: true,
43041
43041
  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.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wildcrane-runner",
3
- "version": "0.6.133",
3
+ "version": "0.6.134",
4
4
  "description": "WildCrane's Local Runner — connects this computer to WildCrane and runs its jobs on your local Claude Code, Codex, OpenCode or Cursor.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://wildcrane.ai/",