wildcrane-runner 0.6.121 → 0.6.122

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.121 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.122 — 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;
@@ -152679,6 +152679,7 @@ function withSystemProxy(env2 = process.env, platform = process.platform, read6
152679
152679
 
152680
152680
  // src/proxy.ts
152681
152681
  var LOOPBACK = "localhost,127.0.0.1,[::1]";
152682
+ var withLoopback = (value) => [value, LOOPBACK].filter(Boolean).join(",");
152682
152683
  var HOST_PROXY_ENV = "WILDCRANE_HOST_PROXY";
152683
152684
  var HOST = null;
152684
152685
  var current = {};
@@ -152699,7 +152700,7 @@ function followProxy(read6) {
152699
152700
  const route = {
152700
152701
  httpProxy,
152701
152702
  httpsProxy: current.HTTPS_PROXY || current.https_proxy || httpProxy,
152702
- noProxy: [current.NO_PROXY ?? current.no_proxy, LOOPBACK].filter(Boolean).join(",")
152703
+ noProxy: withLoopback(current.NO_PROXY ?? current.no_proxy)
152703
152704
  };
152704
152705
  const key = JSON.stringify(route);
152705
152706
  if (key !== applied) {
@@ -152796,9 +152797,9 @@ function status(line) {
152796
152797
  }
152797
152798
 
152798
152799
  // src/protocol.ts
152799
- var VERSION = true ? "0.6.121" : "0.0.0";
152800
- var AKB_VERSION = true ? "0.11.103" : "0.0.0";
152801
- var AKB_CONTRACT = true ? 36 : 0;
152800
+ var VERSION = true ? "0.6.122" : "0.0.0";
152801
+ var AKB_VERSION = true ? "0.11.104" : "0.0.0";
152802
+ var AKB_CONTRACT = true ? 39 : 0;
152802
152803
  var EXIT_REFUSED = 10;
152803
152804
  var EXIT_OUTDATED = 11;
152804
152805
  var EXIT_UPDATE = 12;
@@ -152814,7 +152815,7 @@ import path23 from "node:path";
152814
152815
  // ../cli/src/lib/agent/harnesses/antigravity.ts
152815
152816
  import fs14 from "node:fs";
152816
152817
  import path15 from "node:path";
152817
- import { createHash as createHash5 } from "node:crypto";
152818
+ import { createHash as createHash6 } from "node:crypto";
152818
152819
  import { spawnSync as spawnSync3 } from "node:child_process";
152819
152820
 
152820
152821
  // ../cli/src/lib/agent/locate.ts
@@ -153412,7 +153413,7 @@ function rootAbove(board) {
153412
153413
  var NESTED_STATE = /(^|[/\\])\.akb[/\\](?:(?:boards|hidden-boards)[/\\])?\.akb(?=[/\\]|$)/;
153413
153414
  var InvalidBoardStatePath = class extends BoardError {
153414
153415
  constructor(file3, state, id2) {
153415
- const use = state ? `Use ${state}${id2 ? ` or an .assets/${id2}/\u2026 reference` : ""}.` : "Use the board\u2019s project-local state directory.";
153416
+ const use = state ? `Use ${state}${id2 ? ` or an asset:<path> reference` : ""}.` : "Use the board\u2019s project-local state directory.";
153416
153417
  super(`Invalid nested board state path: ${file3}. ${use}`, { kind: "board-state-path" });
153417
153418
  }
153418
153419
  };
@@ -153667,12 +153668,10 @@ var BOARD_PATH_IN_TEXT = "docs/kanban";
153667
153668
  function boardPath() {
153668
153669
  return rel(KANBAN).split(path10.sep).join("/");
153669
153670
  }
153670
- var ASSETS_PATH_IN_TEXT = "docs/kanban/.assets";
153671
153671
  var BOARD_STATE_IN_TEXT = "<board-state>";
153672
153672
  function boardText(text4) {
153673
153673
  const posix = (p2) => rel(p2).split(path10.sep).join("/");
153674
153674
  const swaps = [
153675
- [ASSETS_PATH_IN_TEXT, posix(ASSETS)],
153676
153675
  [BOARD_STATE_IN_TEXT, posix(BOARD_STATE)],
153677
153676
  [BOARD_PATH_IN_TEXT, boardPath()]
153678
153677
  ];
@@ -153912,11 +153911,16 @@ function isSessionMissingFailure(failure3) {
153912
153911
  if (failure3.code === "session_not_found" || failure3.code === "session_mismatch") return true;
153913
153912
  return isSessionMissingText(failure3.summary) || isSessionMissingText(failure3.detail);
153914
153913
  }
153914
+ function resumeBlocked({ stopped: stopped2, session, unconfirmedCleanup }, zh = false) {
153915
+ if (!stopped2) return zh ? "\u65E0\u6CD5\u786E\u8BA4\u539F\u6267\u884C\u5DF2\u9000\u51FA\u3002" : "The previous execution could not be confirmed stopped.";
153916
+ if (unconfirmedCleanup) return zh ? "\u65E0\u6CD5\u786E\u8BA4\u64CD\u4F5C\u7ED3\u679C\u5DF2\u6536\u9F50\u3002" : "The operation results could not be confirmed complete.";
153917
+ if (!session) return zh ? "\u65E0\u6CD5\u63A5\u56DE\u539F\u4F1A\u8BDD\u3002" : "The original session is unavailable.";
153918
+ }
153915
153919
  function agentRecovery(evidence) {
153916
153920
  if (!evidence.stopped) return "unsafe";
153917
153921
  if (evidence.completed) return "report";
153918
153922
  if (evidence.unconfirmedCleanup) return "unsafe";
153919
- if (evidence.session) return "resume";
153923
+ if (!resumeBlocked(evidence)) return "resume";
153920
153924
  return evidence.replayable ? "replay" : "unsafe";
153921
153925
  }
153922
153926
  var recoveryPrompt = "Continue the interrupted turn in this session. Check the current state and the results of previous operations first. Preserve completed work and user decisions. Do not repeat an operation whose result has already taken effect.";
@@ -153937,7 +153941,7 @@ function backoffMs(attempt, random2 = Math.random) {
153937
153941
  function planRetry(failure3, attempt, now = Date.now(), backoff = backoffMs, task = false) {
153938
153942
  if (!Number.isSafeInteger(attempt) || attempt < 1) return { pause: "unsafe" };
153939
153943
  const of = MAX_RETRY_ATTEMPTS;
153940
- if (failure3.code === "completed_operation_failed") return { pause: "unsafe" };
153944
+ if (failure3.code === "completed_operation_failed") return { pause: task ? "manual" : "unsafe" };
153941
153945
  if (["provider_refused", "executable_missing", "execution_blocked", "unauthenticated", "quota_exhausted", "insufficient_quota"].includes(failure3.code ?? "") || failure3.source === "runtime" && /\b(?:401 unauthorized|please (?:log in|login|sign in)|authentication failed|permission denied|(?:credits?|quota) (?:is |has been )?(?:exhausted|exceeded)|invalid model selection)\b/i.test(failure3.summary)) {
153942
153946
  return { pause: "authorization" };
153943
153947
  }
@@ -154015,7 +154019,7 @@ function readRetryHistory(raw) {
154015
154019
  function readRetryPause(raw) {
154016
154020
  if (raw === "wait-too-long") return "wait_too_long";
154017
154021
  if (raw === "needs-review") return "limit";
154018
- if (raw === "limit" || raw === "wait_too_long" || raw === "unsafe" || raw === "authorization" || raw === "stopped") return raw;
154022
+ if (raw === "limit" || raw === "wait_too_long" || raw === "unsafe" || raw === "authorization" || raw === "stopped" || raw === "manual") return raw;
154019
154023
  return void 0;
154020
154024
  }
154021
154025
  function readRetryPlan(raw, attempt, task = false) {
@@ -154040,6 +154044,8 @@ function pauseLine(pause, zh = false) {
154040
154044
  return zh ? "\u65E0\u6CD5\u786E\u8BA4\u7EED\u8DD1\u6388\u6743\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because authorization to resume could not be confirmed.";
154041
154045
  case "stopped":
154042
154046
  return zh ? "\u6267\u884C\u5DF2\u505C\u6B62\u3002" : "Execution stopped.";
154047
+ case "manual":
154048
+ return zh ? "\u8BF7\u6838\u5BF9\u5931\u8D25\u7684\u64CD\u4F5C\u540E\u7EE7\u7EED\u6267\u884C\u3002" : "Check the failed operation, then resume.";
154043
154049
  }
154044
154050
  }
154045
154051
  function syncRepairPrompt(reason) {
@@ -154205,11 +154211,26 @@ ${files.map((file3) => `- ${file3}`).join("\n")}` : "";
154205
154211
  import fs13 from "node:fs";
154206
154212
 
154207
154213
  // ../cli/src/lib/agent/wire/events.ts
154214
+ import { createHash as createHash5 } from "node:crypto";
154208
154215
  var EVENT_KINDS = ["message", "tool_call", "tool_call_update", "plan", "error", "log", "context", "phase", "status", "retry"];
154209
154216
  var TOOL_KINDS = ["read", "edit", "delete", "move", "search", "execute", "fetch", "other"];
154210
154217
  function turnSubmitted(event2) {
154211
154218
  return event2.kind === "phase" && event2.data.phase === "submitted" || event2.kind === "message" && !!event2.data.text.trim() || event2.kind === "tool_call" || event2.kind === "plan";
154212
154219
  }
154220
+ var isPollingTool = (title) => /^(?:.*\.)?(?:command_status|wait(?:_5_seconds|_agent)?|TaskOutput)$/i.test(title);
154221
+ var toolOutput = (text4) => text4.split(/\r?\n/).map((line) => line.trim()).filter(
154222
+ (line) => line && !/^(?:\[?heartbeat\]?(?:\b|\s|$)|(?:status:\s*)?(?:(?:command|task) (?:is )?(?:still )?running|running|in[_ ]progress|pending)[.!]?$)/i.test(line)
154223
+ ).join("\n");
154224
+ function progressSnapshots() {
154225
+ const seen = /* @__PURE__ */ new Set();
154226
+ return (key, text4) => {
154227
+ if (!text4) return false;
154228
+ const digest2 = createHash5("sha256").update(key).update("\0").update(text4).digest("base64");
154229
+ if (seen.has(digest2)) return false;
154230
+ seen.add(digest2);
154231
+ return true;
154232
+ };
154233
+ }
154213
154234
  var toolKind = (v) => TOOL_KINDS.includes(str2(v)) ? v : "other";
154214
154235
  function targetOf(raw) {
154215
154236
  const line = raw.split("\n")[0].trim();
@@ -154247,6 +154268,8 @@ function createEventCollector() {
154247
154268
  let queue = [];
154248
154269
  let said = "";
154249
154270
  let activity = 0;
154271
+ const fresh = progressSnapshots();
154272
+ const polls = /* @__PURE__ */ new Map();
154250
154273
  const todoCalls = /* @__PURE__ */ new Set();
154251
154274
  const held5 = /* @__PURE__ */ new Map();
154252
154275
  let todos = [];
@@ -154265,6 +154288,9 @@ function createEventCollector() {
154265
154288
  progress: () => {
154266
154289
  activity++;
154267
154290
  },
154291
+ progressSnapshot(key, text4) {
154292
+ if (fresh(key, toolOutput(text4))) activity++;
154293
+ },
154268
154294
  submitted() {
154269
154295
  queue.push({ kind: "phase", data: { phase: "submitted", at: (/* @__PURE__ */ new Date()).toISOString() } });
154270
154296
  },
@@ -154286,6 +154312,8 @@ function createEventCollector() {
154286
154312
  todoCalls.add(id2);
154287
154313
  return;
154288
154314
  }
154315
+ const title = str2(u2.title);
154316
+ if (isPollingTool(title)) polls.set(id2, `${title}:${str2(obj2(u2.rawInput).task_id) || str2(obj2(u2.rawInput).CommandId)}`);
154289
154317
  const target = targetIn(u2);
154290
154318
  const subagent = /^(?:Task|Agent|delegate_task|spawn_agent)$/i.test(str2(u2.title)) || !!obj2(u2.rawInput).subagent_type;
154291
154319
  const data = { toolCallId: id2, title: str2(u2.title) || "tool", kind: toolKind(u2.kind), status: str2(u2.status) || "pending", ...subagent ? { subagent: true } : {}, ...target ? { target } : {} };
@@ -154301,7 +154329,9 @@ function createEventCollector() {
154301
154329
  return;
154302
154330
  }
154303
154331
  release2(id2, targetIn(u2));
154304
- const result = contentText(u2.content);
154332
+ const result = contentText(u2.content) || str2(obj2(u2.rawOutput).output) || str2(u2.rawOutput);
154333
+ const poll = polls.get(id2);
154334
+ if (poll && fresh(poll, toolOutput(result))) activity++;
154305
154335
  if (!u2.status && !result) return;
154306
154336
  queue.push({
154307
154337
  kind: "tool_call_update",
@@ -154515,8 +154545,8 @@ function createTail(log) {
154515
154545
  // ../cli/package.json
154516
154546
  var package_default = {
154517
154547
  name: "wildcrane",
154518
- version: "0.11.103",
154519
- akbContract: 36,
154548
+ version: "0.11.104",
154549
+ akbContract: 39,
154520
154550
  canonicalCommands: true,
154521
154551
  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.",
154522
154552
  keywords: [
@@ -155283,11 +155313,22 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
155283
155313
  let out = "";
155284
155314
  if (!calls.has(id2)) {
155285
155315
  calls.add(id2);
155286
- events.toolCall(id2, name, KINDS[name] ?? "other", target);
155316
+ if (["invoke_subagent", "browser_subagent"].includes(name)) events.subagent(id2, target || name);
155317
+ else events.toolCall(id2, name, KINDS[name] ?? "other", target);
155287
155318
  out = `
155288
155319
  \u23FA ${name}${target ? ` ${target}` : ""}
155289
155320
  `;
155290
155321
  }
155322
+ const output3 = str2(tool.output);
155323
+ if (isPollingTool(name)) {
155324
+ const command = str2(p2.CommandId) || str2(p2.CommandID) || name;
155325
+ const commandOutput = /(?:^|\n)Command output:\s*([\s\S]*)/.exec(output3)?.[1].trim();
155326
+ const exit = /(?:^|\n)(Command exited with code -?\d+\.)/.exec(output3)?.[1];
155327
+ if (commandOutput) events.progressSnapshot(`command:${command}`, commandOutput);
155328
+ if (exit) events.progressSnapshot(`exit:${command}`, exit);
155329
+ } else if (!["DONE", "ERROR", "CANCELED", "INTERRUPTED"].includes(str2(step.state))) {
155330
+ events.progressSnapshot(id2, output3);
155331
+ }
155291
155332
  const error62 = obj2(tool.error);
155292
155333
  const reason = str2(error62.message) || str2(error62.type);
155293
155334
  if (["DONE", "ERROR", "CANCELED", "INTERRUPTED"].includes(str2(step.state)) && !closed.has(id2)) {
@@ -155305,7 +155346,7 @@ ${imageError(target, reason || str2(step.state))}
155305
155346
  imageErrors.delete(file3);
155306
155347
  }
155307
155348
  }
155308
- events.toolResult(id2, failed ? "failed" : "completed", str2(tool.output) || reason);
155349
+ events.toolResult(id2, failed ? "failed" : "completed", output3 || reason);
155309
155350
  }
155310
155351
  return out;
155311
155352
  }
@@ -155419,7 +155460,7 @@ function systemPrompt(text4, _argv, env2) {
155419
155460
  const rule = `${text4}
155420
155461
 
155421
155462
  The task working directory is ${env2.PWD ?? process.cwd()}. Use it as the base for project files and commands. This additional workspace contains only language rules; do not write task output here.`;
155422
- const hash2 = createHash5("sha256").update(rule).digest("hex").slice(0, 16);
155463
+ const hash2 = createHash6("sha256").update(rule).digest("hex").slice(0, 16);
155423
155464
  const root2 = path15.join(machineHome(), "prompts", `antigravity-${hash2}`);
155424
155465
  const file3 = path15.join(root2, ".agents", "rules", "language.md");
155425
155466
  fs14.mkdirSync(path15.dirname(file3), { recursive: true });
@@ -155671,6 +155712,7 @@ function createStreamRenderer() {
155671
155712
  const plans = /* @__PURE__ */ new Set();
155672
155713
  const subagents = /* @__PURE__ */ new Map();
155673
155714
  const detached = /* @__PURE__ */ new Set();
155715
+ const taskUsage = /* @__PURE__ */ new Map();
155674
155716
  const endSubagent = (id2, status2) => {
155675
155717
  if (subagents.get(id2) !== false) return;
155676
155718
  subagents.set(id2, true);
@@ -155682,8 +155724,18 @@ function createStreamRenderer() {
155682
155724
  if (!ev) return `${line}
155683
155725
  `;
155684
155726
  if (model === void 0) model = eventModel(ev);
155685
- if (str2(ev.parent_tool_use_id)) return "";
155686
- if (ev.type === "assistant" || ev.type === "stream_event" && obj2(ev.event).type === "content_block_delta") events.progress();
155727
+ const parent = str2(ev.parent_tool_use_id);
155728
+ const content = obj2(ev.message).content;
155729
+ const streamEvent = obj2(ev.event);
155730
+ const delta = obj2(streamEvent.delta);
155731
+ if (ev.type === "stream_event" && streamEvent.type === "content_block_delta" && (str2(delta.text) || str2(delta.thinking) || str2(delta.partial_json))) events.progress();
155732
+ if (parent) {
155733
+ if (["assistant", "user"].includes(str2(ev.type)) && Array.isArray(content)) {
155734
+ const useful = content.map(obj2).filter((block) => !!str2(block.text).trim() || !!str2(block.thinking).trim() || block.type === "tool_use" || block.type === "tool_result" && !!resultText(block.content).trim());
155735
+ if (useful.length) events.progressSnapshot(parent, JSON.stringify(useful));
155736
+ }
155737
+ return "";
155738
+ }
155687
155739
  switch (ev.type) {
155688
155740
  case "assistant": {
155689
155741
  apiFailure = typeof ev.error === "string" ? providerFailure({ type: ev.error }, "Claude could not complete the request.") : void 0;
@@ -155699,6 +155751,8 @@ function createStreamRenderer() {
155699
155751
 
155700
155752
  `);
155701
155753
  events.message(b2.text);
155754
+ } else if (b2?.type === "thinking" && str2(b2.thinking).trim()) {
155755
+ events.progressSnapshot("thinking", str2(b2.thinking));
155702
155756
  } else if (b2?.type === "tool_use" && typeof b2.name === "string") {
155703
155757
  out.push(`\u23FA ${b2.name}${argHint(b2.input, ARG_KEYS)}
155704
155758
  `);
@@ -155718,8 +155772,8 @@ function createStreamRenderer() {
155718
155772
  return out.join("");
155719
155773
  }
155720
155774
  case "user": {
155721
- const content = obj2(ev.message).content;
155722
- for (const raw of Array.isArray(content) ? content : []) {
155775
+ const content2 = obj2(ev.message).content;
155776
+ for (const raw of Array.isArray(content2) ? content2 : []) {
155723
155777
  const b2 = obj2(raw);
155724
155778
  if (b2.type !== "tool_result" || plans.has(str2(b2.tool_use_id))) continue;
155725
155779
  if (subagents.has(str2(b2.tool_use_id))) {
@@ -155763,8 +155817,20 @@ function createStreamRenderer() {
155763
155817
  if (ev.subtype === "task_notification" && subagents.has(str2(ev.tool_use_id))) {
155764
155818
  endSubagent(str2(ev.tool_use_id), str2(ev.status) === "completed" ? "completed" : "failed");
155765
155819
  }
155766
- if (ev.subtype === "task_notification" && backgrounded.has(str2(ev.task_id)) && str2(ev.summary)) {
155767
- return `\u23FA ${str2(ev.summary)}
155820
+ const task = str2(ev.task_id);
155821
+ if (ev.subtype === "task_progress" && task) {
155822
+ const usage2 = obj2(ev.usage);
155823
+ const previous = taskUsage.get(task) ?? { tokens: 0, tools: 0 };
155824
+ const tokens = Math.max(previous.tokens, Number(usage2.total_tokens) || 0);
155825
+ const tools = Math.max(previous.tools, Number(usage2.tool_uses) || 0);
155826
+ if (tokens > previous.tokens || tools > previous.tools) {
155827
+ taskUsage.set(task, { tokens, tools });
155828
+ events.progress();
155829
+ }
155830
+ }
155831
+ if (ev.subtype === "task_notification" && backgrounded.delete(task)) {
155832
+ events.progress();
155833
+ if (str2(ev.summary)) return `\u23FA ${str2(ev.summary)}
155768
155834
  `;
155769
155835
  }
155770
155836
  return "";
@@ -156109,23 +156175,20 @@ function createCodexStreamRenderer(carried = false) {
156109
156175
  const started = /* @__PURE__ */ new Set();
156110
156176
  const background = createBackgroundTasks();
156111
156177
  const subagents = /* @__PURE__ */ new Set();
156112
- const collabItems = /* @__PURE__ */ new Set();
156113
- const collab = (item, done) => {
156178
+ const collab = (item) => {
156114
156179
  if (item.type !== "collab_tool_call") return;
156115
- const key = `${str2(item.id)}:${done}`;
156116
- if (collabItems.has(key)) return;
156117
- collabItems.add(key);
156118
156180
  for (const [id2, raw] of Object.entries(obj2(item.agents_states))) {
156119
156181
  const state = obj2(raw);
156120
156182
  const status2 = str2(state.status);
156121
156183
  if (!["pending_init", "running", "completed", "interrupted", "errored", "shutdown", "not_found"].includes(status2)) continue;
156122
156184
  const previous = background.results().find((t2) => t2.id === id2);
156123
- if (["shutdown", "not_found"].includes(status2) && previous && previous.status !== "running") continue;
156185
+ const running = status2 === "pending_init" || status2 === "running";
156186
+ if ((running || ["shutdown", "not_found"].includes(status2)) && previous && previous.status !== "running") continue;
156124
156187
  if (!subagents.has(id2)) {
156125
156188
  subagents.add(id2);
156126
156189
  events.subagent(`agent:${id2}`, str2(item.prompt) || "Agent");
156127
156190
  }
156128
- const running = status2 === "pending_init" || status2 === "running";
156191
+ if (running) events.progressSnapshot(`agent:${id2}`, str2(state.message));
156129
156192
  const failed = !running && status2 !== "completed";
156130
156193
  if (background.update(id2, running ? "running" : failed ? "failed" : "completed", str2(state.message)) && !running) {
156131
156194
  events.toolResult(`agent:${id2}`, failed ? "failed" : "completed", str2(state.message));
@@ -156158,15 +156221,21 @@ function createCodexStreamRenderer(carried = false) {
156158
156221
  if (!threadId) threadId = str2(ev.thread_id).trim() || void 0;
156159
156222
  return "";
156160
156223
  case "item.started":
156161
- collab(obj2(ev.item), false);
156224
+ collab(obj2(ev.item));
156162
156225
  itemEvents(events, started, obj2(ev.item), false);
156163
156226
  return renderStarted(obj2(ev.item));
156164
- case "item.updated":
156165
- if (obj2(ev.item).type === "todo_list") itemEvents(events, started, obj2(ev.item), false);
156227
+ case "item.updated": {
156228
+ const item = obj2(ev.item);
156229
+ collab(item);
156230
+ if (item.type === "todo_list") itemEvents(events, started, item, false);
156231
+ if (item.type === "command_execution" && started.has(str2(item.id))) {
156232
+ events.progressSnapshot(`command:${str2(item.id)}`, str2(item.aggregated_output));
156233
+ }
156166
156234
  return "";
156235
+ }
156167
156236
  case "item.completed": {
156168
156237
  const item = obj2(ev.item);
156169
- collab(item, true);
156238
+ collab(item);
156170
156239
  if (item.type === "mcp_tool_call" && !/view_image|read_image|open_image/.test(str2(item.tool))) {
156171
156240
  const content = obj2(item.result).content;
156172
156241
  for (const block of Array.isArray(content) ? content : []) {
@@ -156435,7 +156504,8 @@ function createKimiStreamRenderer(cwd, resumeId) {
156435
156504
  `;
156436
156505
  switch (row.role) {
156437
156506
  case "assistant": {
156438
- events.progress();
156507
+ const thought = str2(row.reasoning_content);
156508
+ if (thought) events.progressSnapshot("reasoning", thought);
156439
156509
  const said = str2(row.content).trim();
156440
156510
  if (said) final = said;
156441
156511
  if (said) events.message(said);
@@ -156532,7 +156602,7 @@ function modelOf2(ref) {
156532
156602
  const provider = str2(model.providerId);
156533
156603
  return provider ? `${provider}/${id2}` : id2;
156534
156604
  }
156535
- function createParts(tail) {
156605
+ function createParts(tail, activity) {
156536
156606
  const written = /* @__PURE__ */ new Map();
156537
156607
  const tools = /* @__PURE__ */ new Set();
156538
156608
  const named = /* @__PURE__ */ new Map();
@@ -156541,6 +156611,7 @@ function createParts(tail) {
156541
156611
  const fresh = text4.startsWith(before) ? text4.slice(before.length) : text4;
156542
156612
  if (!fresh) return;
156543
156613
  written.set(partId, text4);
156614
+ activity();
156544
156615
  if (kind === "reasoning" || kind === "thought") tail.thought(fresh);
156545
156616
  else tail.text(fresh);
156546
156617
  };
@@ -156552,7 +156623,10 @@ function createParts(tail) {
156552
156623
  const partId = str2(part.partId);
156553
156624
  if (type === "text" || type === "reasoning" || type === "thought") {
156554
156625
  if (partId) say2(partId, type, str2(part.text));
156555
- else tail.text(str2(part.text));
156626
+ else if (str2(part.text)) {
156627
+ activity();
156628
+ tail.text(str2(part.text));
156629
+ }
156556
156630
  return;
156557
156631
  }
156558
156632
  if (type !== "tool") return;
@@ -156576,14 +156650,18 @@ function createParts(tail) {
156576
156650
  const delta = str2(event2.delta);
156577
156651
  if (!delta) return;
156578
156652
  written.set(partId, (written.get(partId) ?? "") + delta);
156653
+ activity();
156579
156654
  if (field2 === "reasoning") tail.thought(delta);
156580
156655
  else tail.text(delta);
156581
156656
  },
156582
156657
  /** A piece of the turn, as `model.streaming` sends it. */
156583
156658
  streaming(payload) {
156584
156659
  const kind = str2(payload.kind);
156585
- if (kind === "text_delta") return tail.text(str2(payload.delta));
156586
- if (kind === "reasoning_delta") return tail.thought(str2(payload.delta));
156660
+ const delta = str2(payload.delta);
156661
+ if (delta && (kind === "text_delta" || kind === "reasoning_delta")) {
156662
+ activity();
156663
+ return kind === "text_delta" ? tail.text(delta) : tail.thought(delta);
156664
+ }
156587
156665
  if (kind !== "tool_call") return;
156588
156666
  const callId = str2(payload.toolCallId);
156589
156667
  const name = str2(payload.toolName) || "tool";
@@ -156623,7 +156701,7 @@ function stopped(io, why2) {
156623
156701
  }
156624
156702
  async function oneTurn2(io, options) {
156625
156703
  const tail = createTail(io.log);
156626
- const parts = createParts(tail);
156704
+ const parts = createParts(tail, () => io.activity?.());
156627
156705
  const activityEvents = createEventCollector();
156628
156706
  const activeCalls = /* @__PURE__ */ new Set();
156629
156707
  let live = false;
@@ -156650,7 +156728,6 @@ async function oneTurn2(io, options) {
156650
156728
  const part = obj2(payload.part);
156651
156729
  const state = obj2(part.state);
156652
156730
  const type = str2(envelope.type);
156653
- if (["part.delta", "model.streaming"].includes(type) && str2(payload.delta)) io.activity?.();
156654
156731
  const id2 = str2(payload.toolCallId) || str2(part.callId) || str2(part.partId);
156655
156732
  const name = str2(payload.toolName) || str2(part.tool) || str2(state.title);
156656
156733
  if (id2 && name && !activeCalls.has(id2)) {
@@ -156659,7 +156736,21 @@ async function oneTurn2(io, options) {
156659
156736
  else activityEvents.toolCall(id2, name, /^(?:bash|shell|execute|run_command|terminal)$/i.test(name) ? "execute" : "other");
156660
156737
  }
156661
156738
  const status2 = str2(state.status) || str2(payload.kind);
156662
- if (id2 && ["completed", "error", "result"].includes(status2)) activityEvents.toolResult(id2, status2 === "error" ? "failed" : "completed", "");
156739
+ const output3 = str2(state.output) || str2(payload.output);
156740
+ if (type === "part.delta" && payload.field === "output") {
156741
+ const before = activityEvents.activity();
156742
+ activityEvents.progressSnapshot(id2 || str2(payload.partId), str2(payload.delta));
156743
+ if (activityEvents.activity() > before) io.activity?.();
156744
+ }
156745
+ if (id2 && ["completed", "error", "result"].includes(status2)) {
156746
+ activityEvents.toolResult(id2, status2 === "error" ? "failed" : "completed", output3);
156747
+ } else if (id2 && output3) {
156748
+ activityEvents.update({
156749
+ sessionUpdate: "tool_call_update",
156750
+ toolCallId: id2,
156751
+ content: [{ type: "content", content: { text: output3 } }]
156752
+ });
156753
+ }
156663
156754
  for (const e2 of activityEvents.events()) io.event?.(e2);
156664
156755
  }
156665
156756
  event(envelope, parts, tail, live, ended);
@@ -156728,6 +156819,7 @@ async function oneTurn2(io, options) {
156728
156819
  });
156729
156820
  const before = io.resumeId ? await tokensOf(rpc, sessionId) : ZERO_USAGE;
156730
156821
  live = true;
156822
+ io.event?.({ kind: "phase", data: { phase: "submitted", at: (/* @__PURE__ */ new Date()).toISOString() } });
156731
156823
  const accepted = await rpc.call("session/send", { sessionId, content: io.prompt });
156732
156824
  if (accepted.accepted === false) throw new Error("the agent would not take the prompt");
156733
156825
  const done = await finished;
@@ -156810,32 +156902,25 @@ function decide2(params, tail) {
156810
156902
  // ../cli/src/lib/agent/idle.ts
156811
156903
  var IDLE_MS = 5 * 6e4;
156812
156904
  var IDLE_TIMEOUT = { milliseconds: IDLE_MS };
156813
- var IDLE_ERROR = "No response for 5 minutes (idle timeout).";
156905
+ var IDLE_ERROR = "No verifiable progress for 5 minutes (idle timeout).";
156814
156906
  var IDLE_FAILURE = { code: "idle_timeout", source: "runtime", summary: IDLE_ERROR };
156815
- var PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
156816
- function createIdleWatchdog(expired, busy2 = () => false, milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now) {
156817
- const calls = /* @__PURE__ */ new Set();
156818
- const local = /* @__PURE__ */ new Set();
156819
- const seen = /* @__PURE__ */ new Map();
156907
+ function createIdleWatchdog(expired, options = {}) {
156908
+ const { milliseconds = IDLE_TIMEOUT.milliseconds, now = Date.now, onProgress, childProgress } = options;
156909
+ const calls = /* @__PURE__ */ new Map();
156910
+ const fresh = progressSnapshots();
156820
156911
  let last2 = now();
156821
- let working2 = false;
156822
156912
  let closed = false;
156823
- let recoveringAt;
156824
- let retryUntil = 0;
156825
- const touch = () => {
156826
- if (!closed) {
156827
- last2 = now();
156828
- recoveringAt = void 0;
156829
- retryUntil = 0;
156830
- }
156913
+ const advance = (at2) => {
156914
+ if (closed || at2 <= last2) return;
156915
+ last2 = at2;
156916
+ onProgress?.(at2);
156831
156917
  };
156918
+ const touch = () => advance(now());
156832
156919
  const check2 = () => {
156833
156920
  if (closed) return;
156834
- if (retryUntil > now()) return;
156835
- const active = calls.size > 0 || busy2();
156836
- if (active || working2) last2 = now();
156837
- working2 = active;
156838
- if (!active && now() - last2 >= milliseconds) {
156921
+ const at2 = now();
156922
+ advance(Math.min(childProgress?.() ?? last2, at2));
156923
+ if (at2 - last2 >= milliseconds) {
156839
156924
  close();
156840
156925
  expired();
156841
156926
  }
@@ -156846,8 +156931,6 @@ function createIdleWatchdog(expired, busy2 = () => false, milliseconds = IDLE_TI
156846
156931
  closed = true;
156847
156932
  clearInterval(timer);
156848
156933
  calls.clear();
156849
- local.clear();
156850
- seen.clear();
156851
156934
  };
156852
156935
  return {
156853
156936
  touch,
@@ -156855,44 +156938,24 @@ function createIdleWatchdog(expired, busy2 = () => false, milliseconds = IDLE_TI
156855
156938
  close,
156856
156939
  event(e2) {
156857
156940
  if (closed) return;
156858
- if (e2.kind === "status") {
156859
- if (e2.data.state !== "retrying") touch();
156860
- else {
156861
- recoveringAt ??= now();
156862
- retryUntil = Math.min(now() + PROVIDER_RETRY_MS.announcement, recoveringAt + PROVIDER_RETRY_MS.episode);
156863
- }
156864
- check2();
156865
- return;
156866
- }
156867
- if (e2.kind === "retry") {
156868
- if (e2.data.state === "waiting" || e2.data.state === "retrying") {
156869
- recoveringAt ??= now();
156870
- const target = e2.data.nextRetryAt ? Date.parse(e2.data.nextRetryAt) : NaN;
156871
- const waitUntil = Number.isFinite(target) ? Math.max(target + 3e4, now() + PROVIDER_RETRY_MS.announcement) : now() + PROVIDER_RETRY_MS.announcement;
156872
- retryUntil = Math.min(waitUntil, recoveringAt + PROVIDER_RETRY_MS.episode);
156873
- } else {
156874
- touch();
156875
- }
156876
- check2();
156877
- return;
156941
+ if (e2.kind === "tool_call") {
156942
+ const { toolCallId, title, status: status2 } = e2.data;
156943
+ if (!toolCallId || calls.has(toolCallId)) return;
156944
+ const state = isPollingTool(title) ? "polling" : ["completed", "failed"].includes(status2) ? "finished" : "working";
156945
+ calls.set(toolCallId, state);
156946
+ if (state !== "polling") touch();
156878
156947
  }
156879
- if (e2.kind === "log" || e2.kind === "context") return;
156880
- if (e2.kind === "phase" && !e2.data.contentAt) return;
156881
- const key = e2.kind === "tool_call" || e2.kind === "tool_call_update" ? `${e2.kind}:${e2.data.toolCallId}` : e2.kind;
156882
- const value = JSON.stringify(e2.data);
156883
- if (seen.get(key) === value) return;
156884
- seen.set(key, value);
156885
- if (e2.kind === "tool_call" && (e2.data.kind === "execute" || e2.data.subagent)) local.add(e2.data.toolCallId);
156886
- if (e2.kind === "tool_call" || e2.kind === "tool_call_update") {
156887
- const { toolCallId, status: status2 } = e2.data;
156888
- if (local.has(toolCallId) && ["in_progress", "running"].includes(status2)) calls.add(toolCallId);
156889
- if (["completed", "failed"].includes(status2)) {
156890
- calls.delete(toolCallId);
156891
- local.delete(toolCallId);
156892
- }
156948
+ if (e2.kind === "tool_call_update") {
156949
+ const { toolCallId, status: status2, result } = e2.data;
156950
+ const state = calls.get(toolCallId);
156951
+ if (state === "polling") return;
156952
+ const finished = state === "working" && ["completed", "failed"].includes(status2);
156953
+ if (finished) calls.set(toolCallId, "finished");
156954
+ const newOutput = !!toolCallId && fresh(`tool:${toolCallId}`, toolOutput(result ?? ""));
156955
+ if (finished || newOutput) touch();
156893
156956
  }
156894
- touch();
156895
- check2();
156957
+ if (e2.kind === "message" && e2.data.text.trim() && fresh(e2.kind, e2.data.text.trim())) touch();
156958
+ if (e2.kind === "plan" && e2.data.entries.length && fresh(e2.kind, JSON.stringify(e2.data.entries))) touch();
156896
156959
  }
156897
156960
  };
156898
156961
  }
@@ -157224,6 +157287,7 @@ async function run(io, options, count3) {
157224
157287
  const offered = /* @__PURE__ */ new Map();
157225
157288
  const snapshot = (w2) => JSON.stringify([w2.threadId, w2.processId, w2.status, w2.exitCode, w2.result]);
157226
157289
  const childEvents = /* @__PURE__ */ new Map();
157290
+ const freshOutput = progressSnapshots();
157227
157291
  const seenItems = /* @__PURE__ */ new Set();
157228
157292
  const completedTurns = /* @__PURE__ */ new Set();
157229
157293
  const historicalTurns = /* @__PURE__ */ new Set();
@@ -157258,6 +157322,9 @@ async function run(io, options, count3) {
157258
157322
  io.stdout.off("close", closed);
157259
157323
  io.stdin.off("error", inputFailed);
157260
157324
  if (settlement) flushMessages(work.work().some((w2) => !w2.intentionalStop && !["running", "unknown"].includes(w2.status) && presented.get(w2.id) !== snapshot(w2)));
157325
+ if (classified?.code === "codex_ownership_unconfirmed") {
157326
+ cleanup = { ...cleanup, status: "unconfirmed", detail: classified.detail ?? classified.summary };
157327
+ }
157261
157328
  cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status: status3, disposition }) => ({ id: id2, threadId: threadId2, processId, status: status3, disposition }));
157262
157329
  io.log(renderer.flush());
157263
157330
  const usage = ownUsage(total, baseline);
@@ -157318,7 +157385,9 @@ async function run(io, options, count3) {
157318
157385
  io.idleSignal?.addEventListener("abort", idle2, { once: true });
157319
157386
  const childUpdates = () => {
157320
157387
  for (const w2 of work.entries.values()) {
157321
- if (w2.kind !== "agent" || childEvents.get(w2.id) === w2.status) continue;
157388
+ if (w2.kind !== "agent") continue;
157389
+ if (w2.status === "running" && freshOutput(w2.id, toolOutput(w2.result))) io.activity?.();
157390
+ if (childEvents.get(w2.id) === w2.status) continue;
157322
157391
  if (!childEvents.has(w2.id)) io.event?.({ kind: "tool_call", data: { toolCallId: w2.id, title: "Agent", kind: "other", status: "in_progress", subagent: true } });
157323
157392
  if (w2.status !== "running") io.event?.({ kind: "tool_call_update", data: { toolCallId: w2.id, status: w2.status === "completed" ? "completed" : "failed", result: w2.result } });
157324
157393
  childEvents.set(w2.id, w2.status);
@@ -157556,7 +157625,26 @@ async function run(io, options, count3) {
157556
157625
  armCleanup();
157557
157626
  if (source2 === threadId && obj2(p2.item).type !== "agentMessage") item(obj2(p2.item), msg.method === "item/completed", false);
157558
157627
  }
157559
- if (source2 !== threadId) {
157628
+ const turnId = str2(p2.turnId) || str2(obj2(p2.turn).id);
157629
+ const main2 = source2 === threadId;
157630
+ const live = main2 ? !historicalTurns.has(turnId) && (!currentTurn2 || !turnId || currentTurn2 === turnId) : work.entries.get(`agent:${source2}`)?.status === "running";
157631
+ const delta = str2(p2.delta);
157632
+ if (submitted && live && delta) {
157633
+ if (["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "")) {
157634
+ if (main2) {
157635
+ if (msg.method?.startsWith("item/reasoning/")) thinking();
157636
+ else recovered();
157637
+ }
157638
+ io.activity?.();
157639
+ }
157640
+ const terminal = terminalKey(source2, str2(p2.itemId));
157641
+ if (msg.method === "item/commandExecution/outputDelta" && work.entries.get(terminal)?.status === "running" && freshOutput(terminal, toolOutput(delta))) io.activity?.();
157642
+ }
157643
+ if (!main2) {
157644
+ if (live && msg.method === "item/completed") {
157645
+ const item2 = obj2(p2.item);
157646
+ if (freshOutput(`${source2}:${str2(item2.id)}`, toolOutput(str2(item2.text) || str2(item2.aggregatedOutput)))) io.activity?.();
157647
+ }
157560
157648
  if (msg.method === "turn/completed") {
157561
157649
  work.observeTurn(source2, obj2(p2.turn));
157562
157650
  armCleanup();
@@ -157564,13 +157652,7 @@ async function run(io, options, count3) {
157564
157652
  childUpdates();
157565
157653
  return;
157566
157654
  }
157567
- const turnId = str2(p2.turnId) || str2(obj2(p2.turn).id);
157568
- if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
157569
- if (submitted && ["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "") && str2(p2.delta)) {
157570
- if (msg.method?.startsWith("item/reasoning/")) thinking();
157571
- else recovered();
157572
- io.activity?.();
157573
- }
157655
+ if (!live) return;
157574
157656
  if (msg.method === "turn/started") {
157575
157657
  if (!submitted || completedTurns.has(turnId)) return;
157576
157658
  currentTurn2 = turnId;
@@ -157672,7 +157754,6 @@ async function run(io, options, count3) {
157672
157754
  waiting = true;
157673
157755
  io.event?.({ kind: "log", data: { text: failure3.summary } });
157674
157756
  }
157675
- io.activity?.();
157676
157757
  await delay(500, void 0, { signal: io.signal });
157677
157758
  preparingUntil = Date.now() + CONVERSATION_MS.prepare;
157678
157759
  }
@@ -159019,6 +159100,7 @@ function insideRun() {
159019
159100
  const id2 = process.env[RUN_ENV];
159020
159101
  return id2 && id2.trim() ? id2.trim() : null;
159021
159102
  }
159103
+ var DELIVERY_PHASE_ENV = "AI4KANBAN_DELIVERY_PHASE";
159022
159104
  var TASK_REQUEST_ENV = "AI4KANBAN_TASK_REQUEST";
159023
159105
  var SAVED_PREVIEW_FILE_ENV = "AI4KANBAN_SAVED_PREVIEW_FILE";
159024
159106
  var STOP_ENV = "KANBAN_STOP_ID";
@@ -159583,10 +159665,8 @@ function landSections(body, previews) {
159583
159665
  const start = heading.index;
159584
159666
  const end2 = start + heading[0].length;
159585
159667
  if (!/^ {0,3}##[ \t]+Land(?:[ \t]+#+)?[ \t]*$/.test(visible.slice(start, end2))) return [];
159586
- return [{
159587
- offset: start + heading[0].indexOf("#"),
159588
- empty: !visible.slice(end2, headings[index + 1]?.index).replace(comments, "").trim()
159589
- }];
159668
+ const text4 = visible.slice(end2, headings[index + 1]?.index).replace(comments, "").trim();
159669
+ return [{ offset: start + heading[0].indexOf("#"), empty: !text4, text: text4 }];
159590
159670
  });
159591
159671
  }
159592
159672
  function parseStudioFile(id2, source2, from, { requirePreviewCopy = false, requireLand = false } = {}) {
@@ -160194,7 +160274,7 @@ var secretsSet = () => Object.fromEntries(Object.entries(readAll()).map(([id2, k
160194
160274
 
160195
160275
  // src/api.ts
160196
160276
  var RUNTIMES = ["claude-code", "codex", "cursor", "opencode", "kimi", "dsh", "zcode", "grok", "antigravity"];
160197
- var PROTOCOL = 31;
160277
+ var PROTOCOL = 33;
160198
160278
  var TIMEOUT_MS = 2e4;
160199
160279
  async function send(method, route, body, signedIn, ms, type, extra = {}) {
160200
160280
  const headers = { accept: "application/json", ...extra };
@@ -160411,7 +160491,6 @@ function plan(runtime, prompt, cwd, resume, model, given = {}, fork = false, lan
160411
160491
  ...base,
160412
160492
  managedProcess: client.managedProcess,
160413
160493
  idleRecovery: client.idleRecovery,
160414
- background: client.background,
160415
160494
  fallback: fallback && (() => adapt(fallback())),
160416
160495
  converse: (child, event2, restart = true, prepareUntil, signal2, activity, idleSignal) => client.turn({
160417
160496
  signal: signal2,
@@ -161412,8 +161491,11 @@ import { execFile } from "node:child_process";
161412
161491
  import fs35 from "node:fs";
161413
161492
  import path37 from "node:path";
161414
161493
 
161494
+ // ../cli/src/lib/cloud/review-sync.ts
161495
+ var REVIEW_SYNC_ENV = "AI4KANBAN_REVIEW_SYNC";
161496
+
161415
161497
  // ../cli/src/lib/agent/cloud-studios.ts
161416
- import { createHash as createHash6, randomUUID as randomUUID6 } from "node:crypto";
161498
+ import { createHash as createHash7, randomUUID as randomUUID6 } from "node:crypto";
161417
161499
  import { setTimeout as delay2 } from "node:timers/promises";
161418
161500
  import fs29 from "node:fs";
161419
161501
  import path31 from "node:path";
@@ -161840,7 +161922,7 @@ var versionFile = (id2, version2) => path31.join(root(), "versions", `${safe(id2
161840
161922
  var listFile = (project) => path31.join(root(), "lists", `${safe(project)}.json`);
161841
161923
  var pinFile = (task) => path31.join(root(), "tasks", `${safe(task)}.json`);
161842
161924
  var sessionDir = (task) => path31.join(root(), "sessions", safe(task));
161843
- var sessionFileOf = (task, session) => path31.join(sessionDir(task), createHash6("sha256").update(session).digest("hex") + ".json");
161925
+ var sessionFileOf = (task, session) => path31.join(sessionDir(task), createHash7("sha256").update(session).digest("hex") + ".json");
161844
161926
  var skillDir = (id2, version2) => path31.join(root(), "bundles", safe(id2) + "@" + version2);
161845
161927
  function readJson(file3) {
161846
161928
  try {
@@ -161859,7 +161941,7 @@ function writeJson(file3, value) {
161859
161941
  fs29.rmSync(tmp, { force: true });
161860
161942
  }
161861
161943
  }
161862
- var filesHash = (files) => createHash6("sha256").update(hashInput(files)).digest("hex");
161944
+ var filesHash = (files) => createHash7("sha256").update(hashInput(files)).digest("hex");
161863
161945
  var readVersion2 = (id2, version2) => {
161864
161946
  const held5 = readJson(versionFile(id2, version2));
161865
161947
  return held5?.id === id2 && held5.version === version2 && isStudioFiles(held5.files) && (!held5.filesSha256 || filesHash(held5.files) === held5.filesSha256) ? held5 : null;
@@ -161891,7 +161973,7 @@ function saveStudioSession(task, session, pin) {
161891
161973
  if (!fs29.existsSync(file3)) writeJson(file3, pin);
161892
161974
  }
161893
161975
  function runtimeContextFile(task, runtime, session) {
161894
- const key = createHash6("sha256").update(JSON.stringify([runtime, session])).digest("hex");
161976
+ const key = createHash7("sha256").update(JSON.stringify([runtime, session])).digest("hex");
161895
161977
  return path31.join(sessionDir(task), "context", key + ".json");
161896
161978
  }
161897
161979
  function readRuntimeContext(task, runtime, session) {
@@ -162023,7 +162105,7 @@ async function cachedPackage(held5, pack, download2) {
162023
162105
  const read6 = await download2(pack.downloadUrl, pack.zipBytes);
162024
162106
  if (!read6.ok) return read6;
162025
162107
  const zip = read6.value;
162026
- if (zip.length !== pack.zipBytes || createHash6("sha256").update(zip).digest("hex") !== pack.zipSha256) return invalid("the Studio ZIP digest");
162108
+ if (zip.length !== pack.zipBytes || createHash7("sha256").update(zip).digest("hex") !== pack.zipSha256) return invalid("the Studio ZIP digest");
162027
162109
  let files;
162028
162110
  try {
162029
162111
  files = decodeStudioZip(zip);
@@ -162178,11 +162260,15 @@ exec ${shellLine} "$@"
162178
162260
  }
162179
162261
  function akbEnv(akb, board, task, language2, base = process.env) {
162180
162262
  const env2 = {};
162181
- const dropped = ["AI4KANBAN_PREVIEW_BRIDGE", "AI4KANBAN_REPLY_APPROVAL", "AI4KANBAN_BOARD", "AI4KANBAN_TASK", "AI4KANBAN_EXECUTION", "AI4KANBAN_SCHEDULED_AGENTS", STUDIO_SNAPSHOT_ENV, LANGUAGE_ENV, SESSION_COST_ENV, EXECUTION_RUNTIMES_ENV];
162263
+ const dropped = [DELIVERY_PHASE_ENV, REVIEW_SYNC_ENV, "AI4KANBAN_PREVIEW_BRIDGE", "AI4KANBAN_REPLY_APPROVAL", "AI4KANBAN_BOARD", "AI4KANBAN_TASK", "AI4KANBAN_EXECUTION", "AI4KANBAN_SCHEDULED_AGENTS", STUDIO_SNAPSHOT_ENV, LANGUAGE_ENV, SESSION_COST_ENV, EXECUTION_RUNTIMES_ENV];
162182
162264
  for (const [k2, v] of Object.entries({ ...proxyEnv(), ...base })) if (!k2.startsWith("KANBAN_") && !dropped.includes(k2)) env2[k2] = v;
162183
162265
  const key = Object.keys(env2).find((k2) => k2.toUpperCase() === "PATH") ?? "PATH";
162184
162266
  env2[key] = [shimDir(akb), env2[key]].filter(Boolean).join(path32.delimiter);
162185
- if (Object.keys(proxyEnv()).some((k2) => !/^no_proxy$/i.test(k2)) && env2.NODE_USE_ENV_PROXY === void 0) env2.NODE_USE_ENV_PROXY = "1";
162267
+ if (PROXY_KEYS.some((key2) => env2[key2])) {
162268
+ env2.NODE_USE_ENV_PROXY ??= "1";
162269
+ env2.NO_PROXY = withLoopback(env2.NO_PROXY ?? env2.no_proxy);
162270
+ if (env2.no_proxy !== void 0) env2.no_proxy = withLoopback(env2.no_proxy);
162271
+ }
162186
162272
  env2[HOST_PROXY_ENV] = JSON.stringify(hostProxy());
162187
162273
  env2.AI4KANBAN_COMMAND = "akb";
162188
162274
  if (board) env2.AI4KANBAN_BOARD = board;
@@ -162192,8 +162278,9 @@ function akbEnv(akb, board, task, language2, base = process.env) {
162192
162278
  }
162193
162279
  var KEEP = 256 * 1024;
162194
162280
  function compatibleArgs(akb, args2) {
162195
- if (akb.canonicalCommands) return args2;
162196
162281
  const [group, verb, ...rest] = args2;
162282
+ if (group === "delivery" && verb === "resume") return ["raw", ...args2];
162283
+ if (akb.canonicalCommands) return args2;
162197
162284
  if (group === "run" || group === "delivery") return ["raw", ...args2];
162198
162285
  if (group === "task" && verb && ["refine", "revise", "resolve", "implement"].includes(verb)) return ["raw", "card", verb, ...rest];
162199
162286
  if (group === "memory" && verb === "describe-project") return ["raw", verb, ...rest];
@@ -163485,6 +163572,50 @@ function documentPreviewKey(artifact, version2) {
163485
163572
  return `wildcrane:document-preview/${artifact}/${version2}.pdf`;
163486
163573
  }
163487
163574
 
163575
+ // ../artifact-sdk/src/internal/markdown-destinations.ts
163576
+ var LINK_LITERAL = /<(?:\\[^\r\n]|[^<>\\\r\n])*>/y;
163577
+ var LINK_END = /(?:[ \t\r\n]+(?:"(?:\\[^]|[^"\\])*"|'(?:\\[^]|[^'\\])*'|\((?:\\[^]|[^()\\])*\)))?[ \t\r\n]*\)/y;
163578
+ function* markdownDestinations(text4, imagesOnly = false, inCode) {
163579
+ const opener = imagesOnly ? /!\[(?:\\[^\r\n]|[^\]\\\r\n])*\]\([ \t\r\n]*/g : /\]\([ \t\r\n]*/g;
163580
+ for (let match; match = opener.exec(text4); ) {
163581
+ if (inCode?.(match.index)) {
163582
+ opener.lastIndex = match.index + 2;
163583
+ continue;
163584
+ }
163585
+ let start = opener.lastIndex;
163586
+ let end2 = start;
163587
+ let after = end2;
163588
+ if (text4[start] === "<") {
163589
+ LINK_LITERAL.lastIndex = start;
163590
+ if (!LINK_LITERAL.test(text4)) continue;
163591
+ after = LINK_LITERAL.lastIndex;
163592
+ start++;
163593
+ end2 = after - 1;
163594
+ } else {
163595
+ let depth2 = 0;
163596
+ for (; end2 < text4.length; end2++) {
163597
+ const char = text4[end2];
163598
+ if (char === "\\" && /[()\\]/.test(text4[end2 + 1] ?? "")) end2++;
163599
+ else if (char === "(") {
163600
+ if (++depth2 > 32) break;
163601
+ } else if (char === ")") {
163602
+ if (!depth2) break;
163603
+ depth2--;
163604
+ } else if (/[\x00-\x20\x7f]/.test(char)) break;
163605
+ }
163606
+ if (depth2) continue;
163607
+ after = end2;
163608
+ }
163609
+ LINK_END.lastIndex = after;
163610
+ if (!LINK_END.test(text4)) continue;
163611
+ opener.lastIndex = LINK_END.lastIndex;
163612
+ if (start !== end2) {
163613
+ const src = text4.slice(start, end2).replace(/\\([!-/:-@\x5b-\x60{-~])/g, "$1");
163614
+ yield { src, start, end: end2, offset: match.index };
163615
+ }
163616
+ }
163617
+ }
163618
+
163488
163619
  // ../artifact-sdk/src/internal/references.ts
163489
163620
  var previewComponents = {
163490
163621
  asset: { name: "Asset" },
@@ -163516,7 +163647,7 @@ function variantsOf(raw, src) {
163516
163647
  return list3.map(([label, s]) => ({ label, src: s }));
163517
163648
  }
163518
163649
  function isCaptionPath(value) {
163519
- return typeof value === "string" && !/^(?:[a-z][\w+.-]*:|\s|[/\\])|[?#\\]/i.test(value) && /\.(?:srt|vtt)$/i.test(value);
163650
+ return typeof value === "string" && (value.startsWith("asset:") || !/^(?:[a-z][\w+.-]*:|\s|[/\\])/i.test(value)) && !/[?#\\]/.test(value) && /\.(?:srt|vtt)$/i.test(value);
163520
163651
  }
163521
163652
  function parseCaptions(raw, variants) {
163522
163653
  if (!raw) return;
@@ -163532,7 +163663,7 @@ function parseCaptions(raw, variants) {
163532
163663
  }
163533
163664
  }
163534
163665
  function isOverlayPath(value) {
163535
- return typeof value === "string" && !/^(?:[a-z][\w+.-]*:|[/\\#])/i.test(value) && /\.html?(?:[?#].*)?$/i.test(value);
163666
+ return typeof value === "string" && (value.startsWith("asset:") || !/^(?:[a-z][\w+.-]*:|[/\\#])/i.test(value)) && /\.html?(?:[?#].*)?$/i.test(value);
163536
163667
  }
163537
163668
  function parseOverlay(raw) {
163538
163669
  if (!raw) return;
@@ -163616,7 +163747,7 @@ function bodyReferences(body, located) {
163616
163747
  }
163617
163748
  }
163618
163749
  }
163619
- for (const m of text4.replace(TAG, (tag) => tag.replace(/[^\n]/g, " ")).matchAll(/\]\(\s*<?([^\s)>]+)>?(?:\s+["'][^]*?["'])?\s*\)/g)) add2(m[1], [], m.index);
163750
+ for (const { src, offset } of markdownDestinations(text4.replace(TAG, (tag) => tag.replace(/[^\n]/g, " ")))) add2(src, [], offset);
163620
163751
  return out;
163621
163752
  }
163622
163753
  var bodySources = (body) => [...new Set(bodyReferences(body).map((r2) => r2.src))];
@@ -163668,22 +163799,22 @@ function kindOf2(ext) {
163668
163799
  var TEXT_LIMIT = 1024 * 1024;
163669
163800
 
163670
163801
  // ../cli/src/components/Asset.md
163671
- var Asset_default = '# Asset\n\nShow a file as a Preview with `<Asset src=".assets/<card id>/<file>" label="..." />` alone in a paragraph.\nInline and fenced examples remain text.\n\n- **Label**: use a few words; an image\'s optional `alt` is its shipped caption and cannot contain `<`, `>` or its enclosing quote.\n- **Device**: use a separate tag for each device view, with `device="mobile"` or `device="desktop"`; both may reference the same responsive page.\n- **Variants**: versions of the same content on the same device share one tag with `variants=\'{"English": ".assets/<card id>/page.en.html", "\u4E2D\u6587": ".assets/<card id>/page.zh.html"}\'`, with `src` shown first; alternatives stay separate tags.\n- **Loop**: add `loop` for muted, looping video without controls.\n- **Playable**: add `playable` for an interactive HTML game in a 16:9 sandboxed viewport with click-to-focus keyboard capture and fullscreen pointer lock.\n- **Captions**: `captions` binds a UTF-8 SRT or WebVTT file to an audio or video Asset. The timecoded list seeks the player and highlights the current line. Both original files are available in the Asset menu.\n- **Video overlay**: `overlay=".assets/42/overlay.html"` shares a transparent HTML layer across versions. Use a JSON object keyed by exact `variants` labels for separate `.html` or `.htm` files. A missing or failed overlay leaves the video playable.\n- **Tiled map**: a `.tmx` or `.tmj` `src` draws as a map; keep its `.tsx`/`.tsj` tilesets and images beside it, at the relative paths it names.\n- **Sprite animation**: a TexturePacker JSON (Hash or Array) `src` plays as an animation; keep its sheet image beside it, at the relative path `meta.image` names.\n- **Web page**: an `.html` or `.htm` `src` loads only the relative paths named in its tags and styles.\n- **Mermaid**: a `.mmd` or `.mermaid` `src` draws a diagram and shows its source if it cannot render.\n- **Documents**: PDF, DOCX, and PPTX open in a read-only viewer with page and zoom controls. DOCX and PPTX previews use LibreOffice and the fonts installed on the Runner. The original remains downloadable.\n- **3D models**: a self-contained `.glb` or a `.blend` with saved meshes opens in a read-only viewer with rotation, zoom, reset, and original-file download.\n- **Excel**: a `.xlsx` draws a read-only workbook with sheet tabs, formulas, and saved results.\n- **Text**: code and other text files show as highlighted text; a `.diff` or `.patch` shows its added and removed lines.\n\n### Audio and video captions\n\nSave the media and caption files with the task and add an Asset in its Preview. Video captions appear in the timecoded list. An optional `overlay` still controls the video layer.\n\n```html\n<Asset src=".assets/42/interview.mp3" captions=".assets/42/interview.vtt" label="Interview" />\n```\n\nFor `variants`, give `captions` exactly the same labels and a caption path for each version.\n\n```html\n<Asset src=".assets/42/demo.en.mp4" variants=\'{"English":".assets/42/demo.en.mp4","\u4E2D\u6587":".assets/42/demo.zh.mp4"}\' captions=\'{"English":".assets/42/demo.en.srt","\u4E2D\u6587":".assets/42/demo.zh.srt"}\' label="Demo" />\n```\n\n### Video overlay\n\nOverlay HTML and CSS use the video\'s original dimensions. Keep images, stylesheets and fonts at paths relative to the HTML file. Scripts are disabled. Time bounds are in seconds, with the start included and the end excluded. Omit either bound to start at zero or continue through the end. Elements without time bounds are displayed as authored.\n\n```html\n<Asset src=".assets/42/demo.mp4" label="Demo" overlay=".assets/42/overlay.html" />\n```\n\nIn `overlay.html`:\n\n```html\n<div data-overlay-start="1.25" data-overlay-end="3.5"\n style="position:absolute; left:6%; bottom:12%; font-size:48px; color:white">\n <img src="images/star.png" width="48" alt=""> <strong style="color:gold">New</strong> chapter\n</div>\n```\n';
163802
+ var Asset_default = '# Asset\n\nShow a file as a Preview with `<Asset src="asset:<file>" label="..." />` alone in a paragraph.\nInline and fenced examples remain text.\n\n- **Label**: use a few words; an image\'s optional `alt` is its shipped caption and cannot contain `<`, `>` or its enclosing quote.\n- **Device**: use a separate tag for each device view, with `device="mobile"` or `device="desktop"`; both may reference the same responsive page.\n- **Variants**: versions of the same content on the same device share one tag with `variants=\'{"English": "asset:page.en.html", "\u4E2D\u6587": "asset:page.zh.html"}\'`, with `src` shown first; alternatives stay separate tags.\n- **Loop**: add `loop` for muted, looping video without controls.\n- **Playable**: add `playable` for an interactive HTML game in a 16:9 sandboxed viewport with click-to-focus keyboard capture and fullscreen pointer lock.\n- **Captions**: `captions` binds a UTF-8 SRT or WebVTT file to an audio or video Asset. The timecoded list seeks the player and highlights the current line. Both original files are available in the Asset menu.\n- **Video overlay**: `overlay="asset:overlay.html"` shares a transparent HTML layer across versions. Use a JSON object keyed by exact `variants` labels for separate `.html` or `.htm` files. A missing or failed overlay leaves the video playable.\n- **Tiled map**: a `.tmx` or `.tmj` `src` draws as a map; keep its `.tsx`/`.tsj` tilesets and images beside it, at the relative paths it names.\n- **Sprite animation**: a TexturePacker JSON (Hash or Array) `src` plays as an animation; keep its sheet image beside it, at the relative path `meta.image` names.\n- **Web page**: an `.html` or `.htm` `src` loads only the relative paths named in its tags and styles.\n- **Mermaid**: a `.mmd` or `.mermaid` `src` draws a diagram and shows its source if it cannot render.\n- **Documents**: PDF, DOCX, and PPTX open in a read-only viewer with page and zoom controls. DOCX and PPTX previews use LibreOffice and the fonts installed on the Runner. The original remains downloadable.\n- **3D models**: a self-contained `.glb` or a `.blend` with saved meshes opens in a read-only viewer with rotation, zoom, reset, and original-file download.\n- **Excel**: a `.xlsx` draws a read-only workbook with sheet tabs, formulas, and saved results.\n- **Text**: code and other text files show as highlighted text; a `.diff` or `.patch` shows its added and removed lines.\n\n### Audio and video captions\n\nSave the media and caption files with the task and add an Asset in its Preview. Video captions appear in the timecoded list. An optional `overlay` still controls the video layer.\n\n```html\n<Asset src="asset:interview.mp3" captions="asset:interview.vtt" label="Interview" />\n```\n\nFor `variants`, give `captions` exactly the same labels and a caption path for each version.\n\n```html\n<Asset src="asset:demo.en.mp4" variants=\'{"English":"asset:demo.en.mp4","\u4E2D\u6587":"asset:demo.zh.mp4"}\' captions=\'{"English":"asset:demo.en.srt","\u4E2D\u6587":"asset:demo.zh.srt"}\' label="Demo" />\n```\n\n### Video overlay\n\nOverlay HTML and CSS use the video\'s original dimensions. Keep images, stylesheets and fonts at paths relative to the HTML file. Scripts are disabled. Time bounds are in seconds, with the start included and the end excluded. Omit either bound to start at zero or continue through the end. Elements without time bounds are displayed as authored.\n\n```html\n<Asset src="asset:demo.mp4" label="Demo" overlay="asset:overlay.html" />\n```\n\nIn `overlay.html`:\n\n```html\n<div data-overlay-start="1.25" data-overlay-end="3.5"\n style="position:absolute; left:6%; bottom:12%; font-size:48px; color:white">\n <img src="images/star.png" width="48" alt=""> <strong style="color:gold">New</strong> chapter\n</div>\n```\n';
163672
163803
 
163673
163804
  // ../cli/src/components/Compare.md
163674
- var Compare_default = '# Compare\n\nShow two files with `<Compare a="<src>" b="<src>" label="..." a-label="..." b-label="..." />` alone in a paragraph; never render a side-by-side file for it. Inline and fenced examples remain text.\n\n- **Sides**: either side may be anything an Asset shows, of different kinds, but not another compare; two images or two videos share one viewer, any other pair shows as two Assets.\n- **Video shots**: add `shots="<src>"`, a JSON list of `{ "id": "S1", "start": 0, "end": 2.25, "name": "..." }` covering video A in order, or a storyboard of A.\n- **Storyboard pairing**: beside video A, B may be a storyboard of it; it shows the shot with the id A is on, beside that shot of a storyboard `shots`.\n- **Data contract**: follow the producing agent\'s file contract and validator for storyboards.\n';
163805
+ var Compare_default = '# Compare\n\nShow two files with `<Compare a="asset:before.mp4" b="asset:after.mp4" label="..." a-label="..." b-label="..." />` alone in a paragraph; never render a side-by-side file for it. Inline and fenced examples remain text.\n\n- **Sides**: either side may be anything an Asset shows, of different kinds, but not another compare; two images or two videos share one viewer, any other pair shows as two Assets.\n- **Video shots**: add `shots="asset:shots.json"`, a JSON list of `{ "id": "S1", "start": 0, "end": 2.25, "name": "..." }` covering video A in order, or a storyboard of A.\n- **Storyboard pairing**: beside video A, B may be a storyboard of it; it shows the shot with the id A is on, beside that shot of a storyboard `shots`.\n- **Data contract**: follow the producing agent\'s file contract and validator for storyboards.\n';
163675
163806
 
163676
163807
  // ../cli/src/components/Set.md
163677
163808
  var Set_default = '# Set\n\nGroup three or more previews of one purpose: a `<Set label="...">` line, one `<Asset ... />` per line, then `</Set>`; blank lines between them are fine. Inline and fenced examples remain text.\n\n- **One purpose**: one set per purpose, such as a screen\'s states or the files you changed; keep one or two previews as plain Assets.\n- **One item per label**: Assets sharing a `label` are one item; their `device` views, and a file beside its `.diff` or `.patch`, become switches on it.\n- **Items**: anything an Asset shows, but not a compare or storyboard.\n';
163678
163809
 
163679
163810
  // ../cli/src/components/Storyboard.md
163680
- var Storyboard_default = '# Storyboard\n\nShow a sequence with `<Storyboard src=".assets/<card id>/<storyboard>.json" label="..." />` alone in a paragraph; `label` is optional. Inline and fenced examples remain text.\n\n- **Frames**: a shot frame or slide preview may be anything an Asset shows, but not a storyboard or compare.\n- **Data contract**: follow the producing agent\'s storyboard contract and validator for its shots or slides, keeping stable IDs and reachable preview files.\n';
163811
+ var Storyboard_default = '# Storyboard\n\nShow a sequence with `<Storyboard src="asset:storyboard.json" label="..." />` alone in a paragraph; `label` is optional. Inline and fenced examples remain text.\n\n- **Frames**: a shot frame or slide preview may be anything an Asset shows, but not a storyboard or compare.\n- **Data contract**: follow the producing agent\'s storyboard contract and validator for its shots or slides, keeping stable IDs and reachable preview files.\n';
163681
163812
 
163682
163813
  // ../cli/src/components/Studio.md
163683
- var Studio_default = '# Studio\n\nShow STUDIO.md and its real differences with `<Studio src=".assets/<card id>/studio-review/review.json" />` alone in a paragraph. Inline and fenced examples remain text.\n\n- **Freeze**: `akb studio preview <card id> --folder <draft> --base <baseline>` freezes the complete draft and prints its Studio and attachment tags; use `--base empty` for a new Studio.\n- **Files**: put the attachment tags in the files Preview when present. Three or more changed files use a Set; paired file and diff Assets share a label.\n- **Results**: show trial results as ordinary Preview Components beside the Studio, without a separate manifest or Agent assignment.\n- **Refresh**: rerun after changing the draft; publish only the approved fingerprint. See [the contract](https://github.com/wildcrane-ai/wildcrane/blob/main/docs/api/studio-review.md).\n';
163814
+ var Studio_default = '# Studio\n\nShow STUDIO.md and its real differences with `<Studio src="asset:studio-review/review.json" />` alone in a paragraph. Inline and fenced examples remain text.\n\n- **Freeze**: `akb studio preview <card id> --folder <draft> --base <baseline>` freezes the complete draft and prints its Studio and attachment tags; use `--base empty` for a new Studio.\n- **Files**: put the attachment tags in the files Preview when present. Three or more changed files use a Set; paired file and diff Assets share a label.\n- **Results**: show trial results as ordinary Preview Components beside the Studio, without a separate manifest or Agent assignment.\n- **Refresh**: rerun after changing the draft; publish only the approved fingerprint. See [the contract](https://github.com/wildcrane-ai/wildcrane/blob/main/docs/api/studio-review.md).\n';
163684
163815
 
163685
163816
  // ../cli/src/components/shared.md
163686
- var shared_default = "A Studio is the workbench for one kind of work. A Preview is work shown for review and fine-tuning, as a draft or finished result. Preview Components are the UI components that display it.\n\nTags draw only in the card body; in any other Markdown file, show pictures as plain Markdown images with paths relative to that file.\n";
163817
+ var shared_default = "A Studio is the workbench for one kind of work. A Preview is work shown for review and fine-tuning, as a draft or finished result. Preview Components are the UI components that display it.\n\nUse `asset:<file>` for task assets in the card. In Preview files, use paths relative to the file containing the reference.\nPreview tags draw only in the card body. In other Markdown files, use ordinary Markdown images.\n";
163687
163818
 
163688
163819
  // ../cli/src/lib/agents/catalog.ts
163689
163820
  import fs40 from "node:fs";
@@ -164507,6 +164638,45 @@ var allComponents = () => previewComponentNames.map((name) => ({
164507
164638
  }));
164508
164639
  var componentDocsText = (docs) => docs.length ? [shared_default, ...docs.map((doc) => doc.text)].map((text4) => text4.trim()).join("\n\n") : "";
164509
164640
 
164641
+ // ../artifact-sdk/src/internal/task-assets.ts
164642
+ var PREFIX = "asset:";
164643
+ var LEGACY = ".assets/";
164644
+ var isAssetRef = (source2) => source2.startsWith(PREFIX);
164645
+ var isLegacyAssetRef = (source2) => source2.startsWith(LEGACY);
164646
+ var isTaskAssetRef = (source2) => isAssetRef(source2) || isLegacyAssetRef(source2);
164647
+ function decodeFilePath(source2) {
164648
+ try {
164649
+ return decodeURIComponent(source2);
164650
+ } catch {
164651
+ return source2;
164652
+ }
164653
+ }
164654
+ var assetRef = (file3) => PREFIX + file3.split("/").map(encodeURIComponent).join("/");
164655
+ function taskAssetPath(source2, id2) {
164656
+ const legacy2 = isLegacyAssetRef(source2);
164657
+ const name = legacy2 ? /^\.assets\/([1-9]\d*)\/(.+)$/.exec(source2) : null;
164658
+ if (legacy2 && (!name || id2 !== void 0 && name[1] !== String(id2))) return null;
164659
+ if (!legacy2 && !isAssetRef(source2)) return null;
164660
+ const file3 = decodeFilePath(name ? name[2] : source2.slice(PREFIX.length));
164661
+ if (/[\\:\u0000-\u001f]/.test(file3) || file3.split("/").some((part) => !part || part === "." || part === "..")) return null;
164662
+ return file3;
164663
+ }
164664
+ function relativeAssetRef(source2, owner2) {
164665
+ const file3 = taskAssetPath(owner2);
164666
+ if (file3 === null) return null;
164667
+ const relative = decodeFilePath(source2);
164668
+ if (relative.startsWith("/") || /[\\:\u0000-\u001f]/.test(relative)) return null;
164669
+ const parts = file3.split("/").slice(0, -1);
164670
+ for (const part of relative.split("/")) {
164671
+ if (!part || part === ".") continue;
164672
+ if (part === "..") {
164673
+ if (!parts.length) return null;
164674
+ parts.pop();
164675
+ } else parts.push(part);
164676
+ }
164677
+ return parts.length ? assetRef(parts.join("/")) : null;
164678
+ }
164679
+
164510
164680
  // ../artifact-sdk/src/builtin/compare.json
164511
164681
  var compare_default = '{\n "name": "compare",\n "title": { "en": "Compare", "zh": "\u5BF9\u6BD4" },\n "types": ["compare"],\n "schema": {\n "type": "object",\n "required": ["a", "b"],\n "properties": { "a": { "type": "string" }, "b": { "type": "string" } }\n },\n "references": [\n { "json": "/a", "types": ["storyboard", "compare", "spritesheet", "studio"] },\n { "json": "/b", "types": ["storyboard", "compare", "spritesheet", "studio"] },\n { "json": "/shots", "types": ["storyboard", "compare", "spritesheet", "studio"] }\n ]\n}\n';
164512
164682
 
@@ -164535,7 +164705,7 @@ var markdown_default = `{
164535
164705
  "title": { "en": "Document", "zh": "\u6587\u6863" },
164536
164706
  "types": ["markdown"],
164537
164707
  "references": [
164538
- { "text": "!\\\\[[^\\\\]\\\\n]*\\\\]\\\\(\\\\s*<?([^\\\\s)>]+)>?(?:\\\\s+[\\"'][^\\"'\\\\n]*[\\"'])?\\\\s*\\\\)" },
164708
+ { "markdown": "image" },
164539
164709
  { "text": "<img\\\\b[^<>]*?\\\\ssrc\\\\s*=\\\\s*[\\"']([^\\"']+)[\\"']" }
164540
164710
  ]
164541
164711
  }
@@ -164571,6 +164741,52 @@ var studio_default = '{\n "name": "studio",\n "title": {\n "en": "Studio",\
164571
164741
  var read2 = (m) => typeof m === "string" ? JSON.parse(m) : m;
164572
164742
  var builtin_default = [html_default, image_default, video_default, markdown_default, storyboard_default, compare_default, studio_default, tiled_default, spritesheet_default].map(read2);
164573
164743
 
164744
+ // ../artifact-sdk/src/internal/markdown-code.ts
164745
+ function* inlineCode(text4, start, end2) {
164746
+ const prose = text4.slice(start, end2);
164747
+ const runs = [...prose.matchAll(/`+/g)];
164748
+ const next = /* @__PURE__ */ new Map();
164749
+ const closers = new Array(runs.length);
164750
+ for (let i = runs.length - 1; i >= 0; i--) {
164751
+ const run3 = runs[i];
164752
+ let backslashes = 0;
164753
+ while (prose[run3.index - backslashes - 1] === "\\") backslashes++;
164754
+ const escaped = backslashes % 2;
164755
+ closers[i] = next.get(run3[0].length - escaped);
164756
+ next.set(run3[0].length, i);
164757
+ }
164758
+ for (let i = 0; i < runs.length; i++) {
164759
+ const closer = closers[i];
164760
+ if (closer === void 0) continue;
164761
+ const close = runs[closer];
164762
+ yield [start + runs[i].index, start + close.index + close[0].length];
164763
+ i = closer;
164764
+ }
164765
+ }
164766
+ function* markdownCodeRanges(text4) {
164767
+ let proseStart = 0;
164768
+ let fence;
164769
+ for (const line of text4.matchAll(/[^\r\n]*(?:\r\n?|\n)|[^\r\n]+$/g)) {
164770
+ const [full] = line;
164771
+ const [, marker, info] = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)/.exec(full) ?? [];
164772
+ if (fence) {
164773
+ if (marker?.startsWith(fence.marker) && /^[ \t]*$/.test(info)) {
164774
+ proseStart = line.index + full.length;
164775
+ yield [fence.start, proseStart];
164776
+ fence = void 0;
164777
+ }
164778
+ } else if (marker && (marker[0] === "~" || !info.includes("`"))) {
164779
+ yield* inlineCode(text4, proseStart, line.index);
164780
+ fence = { marker, start: line.index };
164781
+ } else if (!full.trim()) {
164782
+ yield* inlineCode(text4, proseStart, line.index);
164783
+ proseStart = line.index + full.length;
164784
+ }
164785
+ }
164786
+ if (fence) yield [fence.start, text4.length];
164787
+ else yield* inlineCode(text4, proseStart, text4.length);
164788
+ }
164789
+
164574
164790
  // ../artifact-sdk/src/internal/schema.ts
164575
164791
  var isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
164576
164792
  function typeOk(type, v) {
@@ -164678,7 +164894,7 @@ function typeOf(data, types) {
164678
164894
  return { type: types[0], problem: `does not match ${types[0]} at ${problem2(types[0])}` };
164679
164895
  }
164680
164896
  var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
164681
- var remote = (src) => !src || /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src);
164897
+ var remote = (src) => !src || !isAssetRef(src) && /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src);
164682
164898
  function mapJson(node2, keys, at2, visit2) {
164683
164899
  if (!keys.length) return typeof node2 === "string" && node2 ? visit2(node2, at2) : node2;
164684
164900
  const [key, ...rest] = keys;
@@ -164692,17 +164908,32 @@ function mapJson(node2, keys, at2, visit2) {
164692
164908
  for (const k2 of key === "*" ? Object.keys(node2) : key in node2 ? [key] : []) out[k2] = mapJson(node2[k2], rest, `${at2}/${k2}`, visit2);
164693
164909
  return out;
164694
164910
  }
164695
- function mapText(text4, rule, skipped, visit2, includeRemote) {
164911
+ function* regexDestinations(text4, pattern, inCode) {
164912
+ for (const match of text4.matchAll(new RegExp(pattern, "gid"))) {
164913
+ if (inCode?.(match.index)) continue;
164914
+ const span = match.indices?.[1];
164915
+ if (span) yield { src: match[1], start: span[0], end: span[1], offset: span[0] };
164916
+ }
164917
+ }
164918
+ function mapText(text4, rule, skipped, visit2, includeRemote, markdown) {
164919
+ const code = markdown ? markdownCodeRanges(text4) : void 0;
164920
+ let range = code?.next().value;
164921
+ const inCode = (offset) => {
164922
+ while (range && offset >= range[1]) range = code?.next().value;
164923
+ return !!range && offset >= range[0];
164924
+ };
164925
+ const destinations = "text" in rule ? regexDestinations(text4, rule.text, inCode) : markdownDestinations(text4, true, inCode);
164926
+ const list3 = "text" in rule ? rule.list : void 0;
164696
164927
  let out = "";
164697
164928
  let last2 = 0;
164698
- for (const m of text4.matchAll(new RegExp(rule.text, "gid"))) {
164699
- const span = m.indices?.[1];
164700
- if (!span || m[1] === void 0 || skipped.some(([a2, b2]) => span[0] >= a2 && span[0] < b2)) continue;
164701
- const line = text4.slice(0, span[0]).split("\n").length;
164702
- const one = (src) => remote(src) && !includeRemote ? src : visit2(src, line);
164703
- const value = rule.list ? m[1].split(rule.list).map((part) => part.replace(/^(\s*)(\S+)/, (_2, space, src) => space + one(src))).join(rule.list) : one(m[1]);
164704
- out += text4.slice(last2, span[0]) + value;
164705
- last2 = span[1];
164929
+ for (const { src, start, end: end2, offset } of destinations) {
164930
+ if (skipped.some(([a2, b2]) => start >= a2 && start < b2)) continue;
164931
+ const line = text4.slice(0, offset).split("\n").length;
164932
+ const one = (source2) => remote(source2) && !includeRemote ? source2 : visit2(source2, line);
164933
+ const value = list3 ? src.split(list3).map((part) => part.replace(/^(\s*)(\S+)/, (_2, space, source2) => space + one(source2))).join(list3) : one(src);
164934
+ if (value === src) continue;
164935
+ out += text4.slice(last2, start) + value;
164936
+ last2 = end2;
164706
164937
  }
164707
164938
  return out + text4.slice(last2);
164708
164939
  }
@@ -164713,7 +164944,7 @@ function mapReferences(manifest, content, map3, includeRemote = false) {
164713
164944
  if ("json" in rule) {
164714
164945
  if (typeof content !== "string") content = mapJson(content, rule.json.split("/").filter(Boolean), "", (src, at2) => map3(src, { src, types, text: false, at: at2 || "/" }));
164715
164946
  } else if (typeof content === "string") {
164716
- content = mapText(content, rule, skipped(content), (src, line) => map3(src, { src, types, text: true, line }), includeRemote);
164947
+ content = mapText(content, rule, skipped(content), (src, line) => map3(src, { src, types, text: true, line }), includeRemote, manifest?.name === "markdown");
164717
164948
  }
164718
164949
  }
164719
164950
  return content;
@@ -164739,6 +164970,10 @@ function splitFileReference(src) {
164739
164970
  const end2 = src.search(/[?#]/);
164740
164971
  return end2 < 0 ? [src, ""] : [src.slice(0, end2), src.slice(end2)];
164741
164972
  }
164973
+ function fileNameOf(src) {
164974
+ const [source2] = splitFileReference(src);
164975
+ return (taskAssetPath(source2) ?? source2).split("/").at(-1);
164976
+ }
164742
164977
  function relativeFileReference(src, owner2) {
164743
164978
  const parts = owner2.split("/").slice(0, -1);
164744
164979
  for (const part of src.split("/")) {
@@ -164780,7 +165015,7 @@ function collectSources(sources3, card, host) {
164780
165015
  if (!resolved) return { key: null };
164781
165016
  const { key, file: file3 } = resolved;
164782
165017
  if (active.has(key)) {
164783
- const error62 = `${owner2}: ${src}: \u8D44\u6E90\u4F9D\u8D56\u5FAA\u73AF`;
165018
+ const error62 = `${owner2}: ${src}: circular asset dependency`;
164784
165019
  if (partial2) return { key: null, error: error62 };
164785
165020
  throw new Error(error62);
164786
165021
  }
@@ -165070,7 +165305,7 @@ import fs44 from "node:fs";
165070
165305
  import path46 from "node:path";
165071
165306
 
165072
165307
  // ../cli/src/lib/agent/runtime-context.ts
165073
- import { createHash as createHash7 } from "node:crypto";
165308
+ import { createHash as createHash8 } from "node:crypto";
165074
165309
 
165075
165310
  // ../cli/node_modules/zod/v4/classic/external.js
165076
165311
  var external_exports = {};
@@ -184817,6 +185052,13 @@ var reviewNodeSchema = external_exports.object({
184817
185052
  previews: external_exports.array(id).max(50).default([]),
184818
185053
  kind: external_exports.literal("work").optional()
184819
185054
  }).strict();
185055
+ var flatReviewPlanSchema = external_exports.object({
185056
+ rule: external_exports.string().trim().max(2e4),
185057
+ previews: external_exports.array(id).max(50).transform((ids) => [...new Set(ids)])
185058
+ }).strict();
185059
+ function isFlatReviewPlan(plan2) {
185060
+ return plan2 != null && !Array.isArray(plan2);
185061
+ }
184820
185062
  function reviewLayers(plan2) {
184821
185063
  const remaining = new Set(plan2.map((n) => n.id));
184822
185064
  if (remaining.size !== plan2.length) throw new Error("Review node IDs must be unique.");
@@ -184837,14 +185079,18 @@ function reviewLayers(plan2) {
184837
185079
  }
184838
185080
  return layers;
184839
185081
  }
184840
- var reviewPlanSchema = external_exports.array(reviewNodeSchema).max(50).superRefine((nodes, ctx) => {
185082
+ var legacyReviewPlanSchema = external_exports.array(reviewNodeSchema).max(50).superRefine((nodes, ctx) => {
184841
185083
  try {
184842
185084
  reviewLayers(nodes);
184843
185085
  } catch (e2) {
184844
185086
  ctx.addIssue({ code: "custom", message: e2.message });
184845
185087
  }
184846
- }).nullable();
185088
+ });
185089
+ var reviewPlanSchema = external_exports.union([flatReviewPlanSchema, legacyReviewPlanSchema]).nullable();
184847
185090
  function reviewAuthorization(review, assigned, dispatchRevision) {
185091
+ if (isFlatReviewPlan(review.plan)) {
185092
+ return review.stages.some((stage) => stage.status === "ready") ? { kind: "waiting" } : { kind: "flat", plan: review.plan };
185093
+ }
184848
185094
  const states = new Map(review.stages.map((stage) => [stage.id, stage]));
184849
185095
  const nodes = (review.plan ?? []).filter((node2) => {
184850
185096
  const stage = states.get(node2.id);
@@ -184862,9 +185108,9 @@ function reviewAuthorization(review, assigned, dispatchRevision) {
184862
185108
  return { kind: "waiting" };
184863
185109
  }
184864
185110
  function reviewAllows(authorization, action) {
184865
- return action === "refine" ? authorization.kind === "plan" || authorization.kind === "stages" : authorization.kind === "unreviewed" || authorization.kind === "delivery";
185111
+ return action === "refine" ? authorization.kind === "plan" || authorization.kind === "stages" || authorization.kind === "flat" : authorization.kind === "unreviewed" || authorization.kind === "delivery" || authorization.kind === "flat";
184866
185112
  }
184867
- function reviewInstruction(authorization) {
185113
+ function reviewInstruction(authorization, review) {
184868
185114
  switch (authorization.kind) {
184869
185115
  case "plan":
184870
185116
  return "Planning only. Submit a review plan. Work only on dispatched stages.";
@@ -184875,19 +185121,29 @@ function reviewInstruction(authorization) {
184875
185121
  "Work only on these unlocked stages: " + authorization.nodes.map((node2) => node2.id).join(", "),
184876
185122
  ...authorization.nodes.map((node2) => `- ${node2.id}: ${node2.previews.length ? node2.previews.join(", ") : "no Preview"}`)
184877
185123
  ].join("\n");
185124
+ case "flat":
185125
+ return [
185126
+ "Selected Previews: " + (authorization.plan.previews.join(", ") || "none"),
185127
+ "Review rule: " + (authorization.plan.rule || "No extra approval."),
185128
+ ...authorization.plan.rule ? [
185129
+ "At each approval point, save the current Preview and assets. Read akb task review <task>, then run akb task review <task> --request-approval <question> --preview <id> --revision <n>.",
185130
+ "End this run after submitting an approval. On continuation, read the task review and the latest decision before continuing or revising the draft."
185131
+ ] : [],
185132
+ ...review.stages.filter((stage) => stage.preview && (stage.status === "approved" || stage.status === "changes_requested")).map((stage) => `- ${stage.preview} \xB7 ${stage.id} \xB7 ${stage.status === "approved" ? "approved" : "changes requested"}`)
185133
+ ].join("\n");
184878
185134
  case "delivery":
184879
185135
  return "Stages complete. Follow Studio delivery checks.";
184880
185136
  case "changed":
184881
185137
  return "Review authorization changed. Read the task again.";
184882
185138
  case "waiting":
184883
- return "Wait for review. Do not execute locked stages.";
185139
+ return isFlatReviewPlan(review.plan) ? "An approval question is pending. Read akb task review <task> before making any requested changes. Wait for an explicit decision before continuing work." : "Wait for review. Do not execute locked stages.";
184884
185140
  }
184885
185141
  }
184886
185142
  var reviewWriteRules = "Read akb task review before reporting running/done with its revision. Sync content and assets before done. Revise a stage before changing its approved output. Only stage approval accepts reviewable outputs.";
184887
185143
  function taskReviewBoundary(review, assigned) {
184888
185144
  return [
184889
- reviewInstruction(reviewAuthorization(review, assigned)),
184890
- reviewWriteRules
185145
+ reviewInstruction(reviewAuthorization(review, assigned), review),
185146
+ ...isFlatReviewPlan(review.plan) ? [] : [reviewWriteRules]
184891
185147
  ].join("\n");
184892
185148
  }
184893
185149
  function reviewBoundary(review, assigned, studio2 = []) {
@@ -184896,19 +185152,19 @@ function reviewBoundary(review, assigned, studio2 = []) {
184896
185152
  const definitions = taskOnlyPreviews(studio2, preview_definitions).filter((p2) => authorization.kind !== "stages" || !assigned || authorization.nodes.some((node2) => node2.previews.includes(p2.id)));
184897
185153
  return [
184898
185154
  "Task review: " + JSON.stringify(state),
184899
- reviewInstruction(authorization),
185155
+ reviewInstruction(authorization, review),
184900
185156
  ...definitions.map((p2) => [
184901
185157
  `<Preview id="${p2.id}">`,
184902
185158
  p2.instructions,
184903
185159
  ...p2.components ? [`Allowed Preview Components: ${p2.components.join(", ") || "none"}.`] : [],
184904
185160
  "</Preview>"
184905
185161
  ].join("\n")),
184906
- reviewWriteRules
185162
+ ...isFlatReviewPlan(review.plan) ? [] : [reviewWriteRules]
184907
185163
  ].join("\n");
184908
185164
  }
184909
185165
 
184910
185166
  // ../cli/src/lib/agent/runtime-context.ts
184911
- var contextFingerprint = (text4) => createHash7("sha256").update(text4).digest("hex");
185167
+ var contextFingerprint = (text4) => createHash8("sha256").update(text4).digest("hex");
184912
185168
  function contextUpdate(previous, blocks) {
184913
185169
  const sent = { ...previous };
184914
185170
  const parts = [];
@@ -184928,17 +185184,22 @@ function studioEntry(id2, name, version2, action, command = "akb studio file") {
184928
185184
  return ["studio", "Studio: " + name + ". Read `" + command + " " + studioName(id2) + " STUDIO.md`" + read6 + ".", void 0, JSON.stringify([id2, name, version2, command])];
184929
185185
  }
184930
185186
  function compactReview(review, assigned) {
185187
+ if (isFlatReviewPlan(review.plan)) return taskReviewBoundary(review, assigned);
184931
185188
  const authorization = reviewAuthorization(review, assigned);
184932
185189
  if (authorization.kind === "changed") return "Review r" + review.revision + " \xB7 authorization changed. Read the task again.";
184933
- if (!review.stages.length) return "Review \xB7 " + (review.plan === null ? "planning only" : "no extra review");
184934
- const starts = new Map(review.approvals?.map((action) => [action.stage, action.starts]));
185190
+ const custom2 = review.preview_definitions?.length ? "\nCustom Previews: " + review.preview_definitions.map((d2) => d2.id).join(", ") : "";
185191
+ if (!review.stages.length) return "Review \xB7 " + (review.plan === null ? "planning only" : "no extra review") + custom2;
185192
+ const nodePreviews = new Map((review.plan ?? []).map((node2) => [node2.id, node2.previews]));
185193
+ const starts = new Map(review.approvals?.map((action) => [action.stage, "starts" in action ? action.starts : []]));
184935
185194
  const unlocked = new Set(authorization.kind === "stages" ? authorization.nodes.map((node2) => node2.id) : []);
184936
185195
  const stages = review.stages.map((stage) => {
184937
185196
  const next = starts.get(stage.id);
185197
+ const previews = nodePreviews.get(stage.id);
185198
+ const previewNote = previews?.length ? ` (previews: ${previews.join(", ")})` : "";
184938
185199
  const status2 = stage.status === "ready" ? next?.length ? "ready for approval and start " + next.join(", ") : "ready for approval" : stage.status === "available" ? unlocked.has(stage.id) ? "available to start" : "not dispatched" : stage.status === "running" && assigned && !unlocked.has(stage.id) ? "running outside this dispatch" : stage.status;
184939
- return stage.id + " " + status2;
185200
+ return stage.id + previewNote + " " + status2;
184940
185201
  });
184941
- return ["Review r" + review.revision, ...stages].join(" \xB7 ");
185202
+ return ["Review r" + review.revision, ...stages].join(" \xB7 ") + custom2;
184942
185203
  }
184943
185204
  var configurationBlock = (text4) => ["config", text4, "Studio configuration cleared."];
184944
185205
  function reviewBlock(text4, review, previous) {
@@ -185043,7 +185304,11 @@ function stampItem(content, fields2) {
185043
185304
  // ../cli/src/lib/machine/asset-path.ts
185044
185305
  import path47 from "node:path";
185045
185306
  import { fileURLToPath as fileURLToPath3 } from "node:url";
185046
- function resolveBoardAsset(board, state, id2, name, owner2) {
185307
+ var inside = (file3, folder2) => file3.startsWith(folder2 + path47.sep);
185308
+ function resolveBoardAsset(board, state, id2, name, owner2, dependency = false) {
185309
+ const assets = path47.join(state, "assets");
185310
+ const folder2 = id2 === null ? assets : path47.join(assets, String(id2));
185311
+ assertBoardStatePath(name, state, id2);
185047
185312
  if (/^file:/i.test(name)) {
185048
185313
  let local;
185049
185314
  try {
@@ -185051,25 +185316,38 @@ function resolveBoardAsset(board, state, id2, name, owner2) {
185051
185316
  } catch {
185052
185317
  }
185053
185318
  if (local) assertBoardStatePath(local, state, id2);
185319
+ throw new Error(`absolute path: ${name}`);
185054
185320
  }
185055
- if (path47.isAbsolute(name) && !name.startsWith("//")) {
185056
- assertBoardStatePath(name, state, id2);
185057
- assertBoardStatePath(realPathOf(name), state, id2);
185321
+ const decoded = decodeFilePath(name);
185322
+ if (path47.posix.isAbsolute(decoded) && !decoded.startsWith("//") || path47.win32.isAbsolute(decoded) && !decoded.startsWith("//")) {
185323
+ assertBoardStatePath(decoded, state, id2);
185324
+ assertBoardStatePath(realPathOf(decoded), state, id2);
185058
185325
  throw new Error(`absolute path: ${name}`);
185059
185326
  }
185060
- if (/^[a-z][\w+.-]*:/i.test(name) || name.startsWith("#") || name.startsWith("//")) return null;
185061
- assertBoardStatePath(name, state, id2);
185062
- const assets = path47.join(state, "assets");
185063
- const file3 = name.startsWith(".assets/") ? path47.resolve(assets, name.slice(8)) : path47.resolve(path47.dirname(owner2), name);
185064
- const roots = [board, id2 === null ? assets : path47.join(assets, String(id2))];
185065
- const inside3 = (p2, root2) => p2.startsWith(root2 + path47.sep);
185327
+ const taskRef = isTaskAssetRef(name);
185328
+ let file3;
185329
+ if (taskRef) {
185330
+ if (dependency && isAssetRef(name)) throw new Error(`use a path relative to the preview file: ${name}`);
185331
+ const relative = id2 === null ? null : taskAssetPath(name, id2);
185332
+ if (relative === null) {
185333
+ if (isLegacyAssetRef(name)) throw new Error(`outside the board: ${name}`);
185334
+ throw new Error(`expected asset:<path> within this task's asset folder: ${name}`);
185335
+ }
185336
+ file3 = path47.resolve(folder2, relative);
185337
+ } else {
185338
+ if (/^[a-z][\w+.-]*:/i.test(name) || name.startsWith("#") || name.startsWith("//")) return null;
185339
+ file3 = path47.resolve(path47.dirname(owner2), decoded);
185340
+ }
185341
+ const taskOnly = taskRef || inside(owner2, folder2);
185342
+ const roots = taskOnly ? [folder2] : [board, folder2];
185343
+ const realAssets = path47.join(realPathOf(state), "assets");
185344
+ const realFolder = id2 === null ? realAssets : path47.join(realAssets, String(id2));
185345
+ const realRoots = taskOnly ? [realFolder] : [realPathOf(board), realFolder];
185066
185346
  const real2 = realPathOf(file3);
185067
185347
  assertBoardStatePath(file3, state, id2);
185068
185348
  assertBoardStatePath(real2, state, id2);
185069
- if (!roots.some((root2) => inside3(file3, root2))) throw new Error(`outside the board: ${name}`);
185070
- const realAssets = path47.join(realPathOf(state), "assets");
185071
- const realRoots = [realPathOf(board), id2 === null ? realAssets : path47.join(realAssets, String(id2))];
185072
- if (!realRoots.some((root2) => real2 === root2 || inside3(real2, root2))) throw new Error(`link outside the board: ${name}`);
185349
+ if (!roots.some((root2) => inside(file3, root2))) throw new Error(`outside the board: ${name}`);
185350
+ if (!realRoots.some((root2) => inside(real2, root2))) throw new Error(`link outside the board: ${name}`);
185073
185351
  return file3;
185074
185352
  }
185075
185353
 
@@ -185529,8 +185807,8 @@ function dropPlacedAgents(ws) {
185529
185807
  for (const name of Object.keys(placed)) if (hashFile(path52.join(ws.board, name)) === placed[name]) fs48.rmSync(path52.join(ws.board, name), { force: true });
185530
185808
  fs48.rmSync(agentsRecord(ws), { force: true });
185531
185809
  }
185532
- function assetPath(ws, name, owner2) {
185533
- return resolveBoardAsset(ws.board, projectStateDir(ws.board), ws.number, name, owner2);
185810
+ function assetPath(ws, name, owner2, dependency = false) {
185811
+ return resolveBoardAsset(ws.board, projectStateDir(ws.board), ws.number, name, owner2, dependency);
185534
185812
  }
185535
185813
  function cardAssetsDir(ws, id2) {
185536
185814
  return path52.join(projectStateDir(ws.board), "assets", String(id2));
@@ -185549,6 +185827,7 @@ function pull(ws, machineId2, stopped2, mode) {
185549
185827
  if (mode === "implement") ws.materialIssues = {};
185550
185828
  const taskChat = mode === "chat" ? ws.task : void 0;
185551
185829
  return whenPrepared(ws, { ok: false, code: "stopped", error: "Task preparation stopped." }, async () => {
185830
+ if (mode === "land") return prepareTask(ws, true);
185552
185831
  const sent = await sendBoard(boardFolder(ws), machineId2, { taskChat });
185553
185832
  let validation;
185554
185833
  if (!sent.ok) {
@@ -185860,7 +186139,7 @@ async function pullAssets(ws, record2, assets, preserve = false, stopped2) {
185860
186139
  try {
185861
186140
  target = assetPath(ws, name, file3);
185862
186141
  } catch (error62) {
185863
- if (ws.materialIssues && error62 instanceof InvalidBoardStatePath) ws.materialIssues[name] = error62.message;
186142
+ if (ws.materialIssues && error62 instanceof Error) ws.materialIssues[name] = error62.message;
185864
186143
  if (held5) out[name] = held5;
185865
186144
  continue;
185866
186145
  }
@@ -185940,6 +186219,7 @@ async function pullAssets(ws, record2, assets, preserve = false, stopped2) {
185940
186219
  }
185941
186220
  if (data !== void 0) {
185942
186221
  let changed = false;
186222
+ const ownerName = name;
185943
186223
  const restored = mapReferences(manifest, data, (src, found) => {
185944
186224
  const [ref2, suffix] = found.text ? splitFileReference(src) : [src, ""];
185945
186225
  const name2 = Object.entries(assets).find(([, r2]) => r2.artifact === ref2)?.[0];
@@ -185951,7 +186231,8 @@ async function pullAssets(ws, record2, assets, preserve = false, stopped2) {
185951
186231
  }
185952
186232
  if (!child) return src;
185953
186233
  dependencies.push(name2);
185954
- const back = !found.text && /^\.assets\//.test(name2) ? name2 : path52.relative(path52.dirname(target), child).split(path52.sep).join("/") + suffix;
186234
+ const relative = path52.relative(path52.dirname(target), child).split(path52.sep);
186235
+ const back = !found.text && isLegacyAssetRef(name2) && !isAssetRef(ownerName) ? name2 : (found.text ? relative.map(encodeURIComponent) : relative).join("/") + suffix;
185955
186236
  if (back !== src) changed = true;
185956
186237
  return back;
185957
186238
  });
@@ -186033,8 +186314,8 @@ async function sentOf(file3, kind) {
186033
186314
  }
186034
186315
  var undrawnPreviews = (ws) => Object.entries(assetsOf(readText(path52.join(ws.board, assetsFile(ws.task))))).flatMap(([key, ref]) => ref.error ? [`${key}: ${ref.error}`] : []);
186035
186316
  function undrawn(ws, reason) {
186036
- for (const [root2, shown] of [[path52.join(projectStateDir(ws.board), "assets"), ".assets"], [ws.board, ""]]) {
186037
- reason = reason.split(`file://${root2}${path52.sep}`).join(shown && `${shown}/`).split(`${root2}${path52.sep}`).join(shown && `${shown}/`);
186317
+ for (const [root2, prefix] of [[path52.join(projectStateDir(ws.board), "assets", String(ws.number)), "asset:"], [ws.board, ""]]) {
186318
+ reason = reason.split(`file://${root2}${path52.sep}`).join(prefix).split(`${root2}${path52.sep}`).join(prefix);
186038
186319
  }
186039
186320
  return reason.replace(/ \(at [^)]*file:\/\/[^)]*\)$/, "").slice(0, 500);
186040
186321
  }
@@ -186116,27 +186397,50 @@ async function pushAssets(ws, record2, before) {
186116
186397
  const refs = {};
186117
186398
  const currentDocumentPreviews = /* @__PURE__ */ new Set();
186118
186399
  let retryPreviews = false;
186400
+ const sources3 = bodyReferences(body);
186401
+ const legacy2 = !sources3.some((ref) => isAssetRef(ref.src)) && (sources3.some((ref) => isLegacyAssetRef(ref.src)) || Object.keys(before).some(isLegacyAssetRef));
186402
+ const folder2 = ws.number === null ? null : realPathOf(cardAssetsDir(ws, ws.number));
186119
186403
  const canonical = (target) => {
186120
- target = realPathOf(target);
186121
- const assets = realPathOf(path52.join(projectStateDir(ws.board), "assets"));
186122
- if (target.startsWith(assets + path52.sep)) return `.assets/${path52.relative(assets, target).split(path52.sep).join("/")}`;
186123
- return path52.relative(realPathOf(path52.dirname(file3)), target).split(path52.sep).join("/");
186124
- };
186125
- const required3 = new Map(parsePreviewBlocks(body).blocks.flatMap((block) => bodyReferences(block.instructions).filter((ref) => ref.types.length).map((ref) => [ref.src, sourcePosition(body, block.start).line])));
186404
+ const real2 = realPathOf(target);
186405
+ if (folder2 && real2.startsWith(folder2 + path52.sep)) {
186406
+ const local = path52.relative(folder2, real2).split(path52.sep).join("/");
186407
+ return legacy2 ? `.assets/${ws.number}/${local}` : assetRef(local);
186408
+ }
186409
+ return path52.relative(realPathOf(path52.dirname(file3)), real2).split(path52.sep).join("/");
186410
+ };
186411
+ const equivalent = /* @__PURE__ */ new Map();
186412
+ for (const source2 of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(record2.assets)])) {
186413
+ const name = taskAssetPath(source2, ws.number ?? void 0);
186414
+ if (name !== null) equivalent.set(name, [...equivalent.get(name) ?? [], source2]);
186415
+ }
186416
+ const keysOf = (source2) => [source2, ...equivalent.get(taskAssetPath(source2, ws.number ?? void 0) ?? "") ?? []];
186417
+ const required3 = /* @__PURE__ */ new Map();
186418
+ for (const block of parsePreviewBlocks(body).blocks) {
186419
+ const contentStart = body.indexOf(">", block.start) + 1;
186420
+ const content = body.slice(contentStart, body.lastIndexOf("</Preview", block.end - 1));
186421
+ const start = sourcePosition(body, contentStart).line;
186422
+ const locations = /* @__PURE__ */ new Map();
186423
+ for (const ref of bodyReferences(content, (src, line) => {
186424
+ if (!locations.has(src)) locations.set(src, start + line - 1);
186425
+ })) {
186426
+ if (ref.types.length || isTaskAssetRef(ref.src) || /^file:/i.test(ref.src) || path52.win32.isAbsolute(ref.src)) required3.set(ref.src, locations.get(ref.src));
186427
+ }
186428
+ }
186126
186429
  try {
186127
186430
  let recoveredReferences = false;
186128
186431
  const graph = collect(body, file3, {
186129
186432
  resolve: (src, owner2) => {
186130
186433
  const id2 = Object.entries(before).find(([, ref]) => ref.artifact === src);
186131
186434
  if (id2) return { key: id2[0], file: null };
186132
- const target = assetPath(ws, src, owner2);
186435
+ const target = assetPath(ws, src, owner2, owner2 !== file3);
186133
186436
  if (!target) return null;
186134
- const key = owner2 === file3 && before[src] ? src : canonical(target);
186437
+ const key = canonical(target);
186135
186438
  if (!fs48.statSync(target, { throwIfNoEntry: false })?.isFile()) {
186136
- if (before[key]) return { key, file: null };
186439
+ const saved = (owner2 === file3 ? [src, ...keysOf(key)] : keysOf(key)).find((name) => before[name]?.artifact);
186440
+ if (saved) return { key: saved, file: null };
186137
186441
  throw new Error(`file not found: ${target}`);
186138
186442
  }
186139
- return { key: canonical(fs48.realpathSync(target)), file: target };
186443
+ return { key, file: target };
186140
186444
  },
186141
186445
  read: referenceText,
186142
186446
  retained: (key, types) => {
@@ -186152,8 +186456,9 @@ async function pushAssets(ws, record2, before) {
186152
186456
  }
186153
186457
  });
186154
186458
  for (const node2 of graph) {
186155
- const previous = [...node2.aliases].map((key) => record2.assets[key]).find(Boolean);
186156
- const old = [...node2.aliases].map((key) => before[key]).find(Boolean);
186459
+ const aliases = [...node2.aliases];
186460
+ const previous = [...aliases, ...keysOf(node2.key)].map((key) => record2.assets[key]).find(Boolean);
186461
+ const old = [...aliases, ...keysOf(node2.key)].map((key) => before[key]).find(Boolean);
186157
186462
  const kind = node2.kind;
186158
186463
  let out;
186159
186464
  const partialStudio = node2.kind === "studio" && node2.data?.version === 2;
@@ -186355,6 +186660,15 @@ var pushBoard = (ws, machineId2, paths) => inFolder(ws.cwd, () => {
186355
186660
  }
186356
186661
  return sendBoard(ws, machineId2, { paths });
186357
186662
  });
186663
+ var landArchives = (board) => path52.join(board, ".sync", "land-archives");
186664
+ var landArchiveOwner = (ws) => path52.join(landArchives(ws.board), ws.task);
186665
+ function protectLandArchive(ws, job) {
186666
+ write(landArchiveOwner(ws), job);
186667
+ }
186668
+ function confirmLandArchive(ws, job) {
186669
+ const file3 = landArchiveOwner(ws);
186670
+ if (readText(file3) === job) fs48.rmSync(file3, { force: true });
186671
+ }
186358
186672
  async function sendBoard(ws, machineId2, scope) {
186359
186673
  if (readBase(ws).head_seq === null) return { ok: true, changed: false };
186360
186674
  return sendMarked(ws, { id: null, machineId: machineId2 }, scope);
@@ -186477,6 +186791,18 @@ async function send2(ws, job, { paths, taskChat }, retryRestore = true) {
186477
186791
  const retryAssets = new Set(base.pendingAssets);
186478
186792
  const deferredCards = /* @__PURE__ */ new Set();
186479
186793
  const deferredLists = /* @__PURE__ */ new Set();
186794
+ const protectedCards = /* @__PURE__ */ new Set();
186795
+ const protectedLists = /* @__PURE__ */ new Set();
186796
+ const archiveOwners = landArchives(ws.board);
186797
+ for (const task of filesUnder(archiveOwners)) {
186798
+ const number4 = syncIndex(ws)?.tasks.get(task)?.number;
186799
+ if (!number4 || readText(path52.join(archiveOwners, task)) === job.id) continue;
186800
+ const file3 = findCard(ws.board, number4);
186801
+ if (!file3 || path52.relative(ws.board, file3).split(path52.sep)[0] !== ".archive") continue;
186802
+ protectedCards.add(number4);
186803
+ protectedLists.add(assetsFile(task));
186804
+ if (boardSync) archives.set(task, path52.relative(ws.board, file3).split(path52.sep).join("/"));
186805
+ }
186480
186806
  const assetErrors = {};
186481
186807
  const processed = /* @__PURE__ */ new Set();
186482
186808
  const assetLists = /* @__PURE__ */ new Map();
@@ -186488,6 +186814,7 @@ async function send2(ws, job, { paths, taskChat }, retryRestore = true) {
186488
186814
  })
186489
186815
  ) : null;
186490
186816
  for (const item of tasks) {
186817
+ if (protectedCards.has(item.folder.number)) continue;
186491
186818
  processed.add(item.folder.task);
186492
186819
  if (processed.size === 1 || processed.size % 25 === 0) logSync("board.progress", { project: ws.project, processed: processed.size, total: tasks.length });
186493
186820
  const card = cards?.get(item.folder.number) ?? path52.relative(ws.board, cardFile(item.folder)).split(path52.sep).join("/");
@@ -186553,6 +186880,7 @@ async function send2(ws, job, { paths, taskChat }, retryRestore = true) {
186553
186880
  const retiredCards = new Set(tasks.filter((item) => item.record.deleted).map((item) => item.folder.number));
186554
186881
  const retiredLists = new Set(tasks.filter((item) => item.record.deleted).map((item) => assetsFile(item.folder.task)));
186555
186882
  const defer = (p2) => {
186883
+ if (protectedCards.has(numberOfCard(p2) ?? 0) || protectedLists.has(p2)) return true;
186556
186884
  if (retiredCards.has(numberOfCard(p2)) || retiredLists.has(p2)) {
186557
186885
  deferred.add(p2);
186558
186886
  return true;
@@ -186583,7 +186911,8 @@ async function send2(ws, job, { paths, taskChat }, retryRestore = true) {
186583
186911
  const archived = await reconcileArchives(ws, base, archives, pendingArchives, job.machineId);
186584
186912
  const removed = await reconcileRemovals(ws, base, selected2);
186585
186913
  operations = { ...archived, ...removed };
186586
- syncIndex(ws).archivesReady = true;
186914
+ const index = syncIndex(ws);
186915
+ if (index) index.archivesReady = true;
186587
186916
  }
186588
186917
  const reported = !ws.number ? previews : previews.filter((p2) => numberOfCard(p2.file) === ws.number);
186589
186918
  const tasks2 = { ...assetErrors, ...operations };
@@ -186861,6 +187190,7 @@ async function reconcileArchives(ws, base, archives, pending, machine) {
186861
187190
  const receipt = !found || repeated.has(task) ? { task, status: "pending", code: "invalid_response", message: invalidResponse("an archive receipt for this task").message } : found;
186862
187191
  receipts[task] = { ...version2, ...receipt };
186863
187192
  if (receipt.status !== "pending") pending.delete(task);
187193
+ if (receipt.status === "confirmed") fs48.rmSync(landArchiveOwner({ board: ws.board, task }), { force: true });
186864
187194
  if (receipt.status === "rejected" || receipt.status === "pending" && receipt.code === "invalid_response") {
186865
187195
  errors[task] = { error: `Archive ${task}: ${receipt.message}`, code: receipt.code, offline: receipt.status === "pending", blocking: false };
186866
187196
  }
@@ -186893,7 +187223,7 @@ function taskContextBlocks(ws, action, canonicalCommands = true) {
186893
187223
  const titles2 = [title?.en, title?.zh].map((text4) => text4?.replace(/\s+/g, " ").trim()).filter(Boolean);
186894
187224
  return "- " + id2 + (titles2.length ? " \xB7 " + titles2.join(" / ") : "");
186895
187225
  });
186896
- const catalog = previews.length ? ["Studio Previews:", ...previews].join("\n") : "Studio Previews: none.";
187226
+ const catalog = previews.length ? ["Studio Previews:", ...previews, "Add any listed Preview to the review plan with `akb task review <id> --add-previews <ids> --revision <n>`."].join("\n") : "Studio Previews: none.";
186897
187227
  return blocks.flatMap((block) => block[0] === "skills" ? [["studio-previews", catalog], ["skills", block[1] || "Studio skills: none."]] : [block]);
186898
187228
  }
186899
187229
  function taskStudioContext(ws, { docs = true, canonicalCommands = true, config: config2 = true } = {}) {
@@ -187141,6 +187471,67 @@ async function answerHint(machineId2, hint2) {
187141
187471
  if (!sent.ok) console.error(`runner: the diff of ${commit.slice(0, 7)} was not sent: ${sent.error}`);
187142
187472
  }
187143
187473
 
187474
+ // src/reply-approval.ts
187475
+ import http from "node:http";
187476
+ import crypto9 from "node:crypto";
187477
+ function previewSyncBridge(ws, job, stopped2) {
187478
+ return taskBridge(ws.task, ws.number, async () => {
187479
+ const result = await push(ws, job, stopped2);
187480
+ if (!result.ok) return result;
187481
+ return taskAssetsSynced(ws) ? { ok: true, value: void 0 } : { ok: false, error: "Preview uploads are pending." };
187482
+ });
187483
+ }
187484
+ function replyApprovalBridge(task, number4, approve) {
187485
+ return taskBridge(task, number4, (body) => {
187486
+ const { task: asked, comment, stage, review_revision } = body;
187487
+ if (comment !== void 0 && typeof comment !== "string") throw Error("Invalid comment.");
187488
+ if (typeof review_revision !== "number" || !Number.isSafeInteger(review_revision) || review_revision < 0 || stage !== void 0 && typeof stage !== "string") throw Error("Name the review version you read.");
187489
+ return approve(comment, asked, { stage, review_revision });
187490
+ });
187491
+ }
187492
+ async function taskBridge(task, number4, run3) {
187493
+ const token = crypto9.randomBytes(32).toString("hex");
187494
+ let serial = Promise.resolve();
187495
+ const server = http.createServer((req, res) => {
187496
+ const answer = (status2, body) => {
187497
+ res.writeHead(status2, { "content-type": "application/json" });
187498
+ res.end(JSON.stringify(body));
187499
+ };
187500
+ if (req.method !== "POST" || req.url !== "/" || req.headers.authorization !== `Bearer ${token}` || req.headers.origin) {
187501
+ answer(403, { ok: false, error: "This request cannot act on that task." });
187502
+ return;
187503
+ }
187504
+ let raw = "";
187505
+ req.on("data", (data) => {
187506
+ raw += data.toString();
187507
+ if (raw.length > 16e3) req.destroy();
187508
+ });
187509
+ req.on("end", () => {
187510
+ serial = serial.then(async () => {
187511
+ try {
187512
+ const body = JSON.parse(raw);
187513
+ if (body.task !== task && body.task !== String(number4) && !new RegExp(`^[A-Za-z][A-Za-z0-9]{0,9}-${number4}$`).test(body.task ?? "")) {
187514
+ answer(403, { ok: false, error: "Only the current task can be updated here." });
187515
+ return;
187516
+ }
187517
+ answer(200, await run3(body));
187518
+ } catch (e2) {
187519
+ answer(400, { ok: false, error: e2 instanceof Error ? e2.message : "Task request failed." });
187520
+ }
187521
+ });
187522
+ });
187523
+ });
187524
+ await new Promise((resolve2, reject) => {
187525
+ server.once("error", reject);
187526
+ server.listen(0, "127.0.0.1", resolve2);
187527
+ });
187528
+ const address = server.address();
187529
+ return { env: JSON.stringify({ url: `http://127.0.0.1:${address.port}/`, token }), close: () => {
187530
+ server.close();
187531
+ server.closeAllConnections();
187532
+ } };
187533
+ }
187534
+
187144
187535
  // ../cli/src/lib/agent/stop.ts
187145
187536
  import { spawnSync as spawnSync7 } from "node:child_process";
187146
187537
  import { randomUUID as randomUUID7 } from "node:crypto";
@@ -187906,6 +188297,7 @@ function parseStore() {
187906
188297
  cloudExecution: executionOf(entry.cloudExecution ?? null),
187907
188298
  studioPin: typeof entry.studioPin?.studio === "string" && Number.isSafeInteger(entry.studioPin.version) && entry.studioPin.version > 0 ? entry.studioPin : void 0,
187908
188299
  pendingWrites: entry.pendingWrites === true || void 0,
188300
+ lastProgressAt: typeof entry.lastProgressAt === "number" && Number.isFinite(entry.lastProgressAt) ? entry.lastProgressAt : void 0,
187909
188301
  submitted: entry.submitted === true || void 0,
187910
188302
  cardId: typeof entry.cardId === "number" ? entry.cardId : null,
187911
188303
  createdCardIds: Array.isArray(entry.createdCardIds) ? [...new Set(entry.createdCardIds.filter((id2) => Number.isInteger(id2) && id2 > 0))] : void 0,
@@ -188606,7 +188998,6 @@ var TAG3 = /^<Storyboard\b([^<>]*?)\/>$/;
188606
188998
  var attr = (name) => new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`);
188607
188999
  var SRC_ATTR = attr("src");
188608
189000
  var LABEL_ATTR = attr("label");
188609
- var SEGMENT = /^(?!\.)[^/\\]+$/;
188610
189001
  function storyboardAttrs(raw) {
188611
189002
  const m = TAG3.exec(raw.trim());
188612
189003
  if (!m) return null;
@@ -188641,14 +189032,13 @@ function storyboardMarkers(body, tagOf = storyboardTag) {
188641
189032
  });
188642
189033
  return found;
188643
189034
  }
188644
- function assetName(src, cardId, exts, nested = false) {
188645
- const expected = `.assets/${cardId}/<file>${!exts.length ? "" : `.${exts.length === 1 ? exts[0] : `{${exts.join(",")}}`}`} in this card's asset folder`;
188646
- if (/^[a-z][a-z0-9+.-]*:/i.test(src)) return { expected, actual: `an external address ${JSON.stringify(src)}` };
188647
- const parts = src.split("/");
188648
- if (parts[0] !== ".assets" || parts.length < 3 || !nested && parts.length !== 3) return { expected, actual: JSON.stringify(src) };
188649
- if (parts[1] !== String(cardId)) return { expected, actual: `another card's folder ${JSON.stringify(parts[1])}` };
188650
- if (!parts.slice(2).every((part) => SEGMENT.test(part))) return { expected, actual: JSON.stringify(src) };
188651
- const name = parts.slice(2).join("/");
189035
+ function assetName(src, cardId, exts) {
189036
+ const expected = `asset:<path>${!exts.length ? "" : `.${exts.length === 1 ? exts[0] : `{${exts.join(",")}}`}`} in this task's asset folder`;
189037
+ const name = taskAssetPath(src, cardId);
189038
+ if (name === null) {
189039
+ const actual = !isTaskAssetRef(src) && /^[a-z][\w+.-]*:/i.test(src) ? `an external address ${JSON.stringify(src)}` : JSON.stringify(src);
189040
+ return { expected, actual };
189041
+ }
188652
189042
  const ext = name.split(".").pop().toLowerCase();
188653
189043
  if (exts.length && (!name.includes(".") || !exts.includes(ext))) return { expected, actual: `file type ${JSON.stringify(name.includes(".") ? ext : "")}` };
188654
189044
  return { name };
@@ -188657,7 +189047,7 @@ function assetName(src, cardId, exts, nested = false) {
188657
189047
  // ../cli/src/lib/preview-files.ts
188658
189048
  import fs59 from "node:fs";
188659
189049
  init_dress_page();
188660
- function validatePreviewFiles(card, id2, text4) {
189050
+ function validatePreviewFiles(card, id2, text4, warn4) {
188661
189051
  const errors = [];
188662
189052
  const lines = /* @__PURE__ */ new Map();
188663
189053
  const sources3 = bodyReferences(text4, (src, line) => {
@@ -188665,22 +189055,40 @@ function validatePreviewFiles(card, id2, text4) {
188665
189055
  if (!lines.has(file3)) lines.set(file3, /* @__PURE__ */ new Set());
188666
189056
  lines.get(file3).add(line);
188667
189057
  });
189058
+ const warnings = /* @__PURE__ */ new Set();
189059
+ const fileLines = /* @__PURE__ */ new Map();
189060
+ const lineOf = (file3, source2) => {
189061
+ let content = fileLines.get(file3);
189062
+ if (!content) {
189063
+ content = fs59.readFileSync(file3, "utf8").split("\n");
189064
+ fileLines.set(file3, content);
189065
+ }
189066
+ return Math.max(1, content.findIndex((line) => line.includes(source2)) + 1);
189067
+ };
188668
189068
  const graph = collectSources(sources3, card, {
188669
189069
  resolve: (src, owner2) => {
189070
+ const dependency = owner2 !== card;
188670
189071
  try {
188671
- const file3 = resolveBoardAsset(KANBAN, BOARD_STATE, id2, src, owner2);
189072
+ const file3 = resolveBoardAsset(KANBAN, BOARD_STATE, id2, src, owner2, dependency);
188672
189073
  if (!file3) return null;
188673
189074
  if (!fs59.statSync(file3, { throwIfNoEntry: false })?.isFile()) throw new Error("no such file");
189075
+ if (warn4 && isLegacyAssetRef(src)) {
189076
+ const locations = dependency ? [lineOf(owner2, src)] : lines.get(src) ?? [];
189077
+ const replacement = dependency ? "a path relative to this file" : "asset:<path>";
189078
+ for (const line of locations) warnings.add(`${rel(owner2)}:${line} [legacy-asset-reference] ${src} is deprecated. Use ${replacement}.`);
189079
+ }
188674
189080
  return { key: fs59.realpathSync(file3), file: file3 };
188675
189081
  } catch (error62) {
188676
- if (owner2 !== card) {
189082
+ if (dependency) {
188677
189083
  if (error62 instanceof Error && /^(?:link )?outside the board:/.test(error62.message)) {
188678
- throw new Error(`outside this card's files (${rel(KANBAN)}, .assets/${id2}/)`);
189084
+ throw new Error("outside this card's files");
188679
189085
  }
188680
189086
  throw error62;
188681
189087
  }
188682
- if (error62 instanceof InvalidBoardStatePath) {
188683
- for (const line of lines.get(src) ?? []) errors.push({ file: rel(card), line, rule: error62.kind, message: error62.message });
189088
+ const rule = error62 instanceof InvalidBoardStatePath ? error62.kind : "asset-reference";
189089
+ const message = error62 instanceof Error ? error62.message : String(error62);
189090
+ if (rule !== "asset-reference" || isTaskAssetRef(src) || /^absolute path:/.test(message)) {
189091
+ for (const line of lines.get(src) ?? []) errors.push({ file: rel(card), line, rule, message: `${src}: ${message}. Fix the reference or add the file.` });
188684
189092
  lines.delete(src);
188685
189093
  }
188686
189094
  return null;
@@ -188689,10 +189097,11 @@ function validatePreviewFiles(card, id2, text4) {
188689
189097
  read: referenceText,
188690
189098
  retained: () => []
188691
189099
  });
189100
+ for (const message of warnings) warn4?.(message);
188692
189101
  const kinds = new Map(graph.map((n) => [n.key, n.kind]));
188693
189102
  for (const node2 of graph) {
188694
189103
  for (const p2 of node2.problems) {
188695
- errors.push({ file: rel(node2.file ?? card), line: p2.line ?? 1, rule: "preview-file", message: `${p2.at ? `${p2.at}: ` : ""}${p2.src}: ${p2.message}. Fix the reference or add the file.` });
189104
+ errors.push({ file: rel(node2.file ?? card), line: p2.line ?? (p2.at && node2.file ? lineOf(node2.file, JSON.stringify(p2.src)) : 1), rule: "preview-file", message: `${p2.at ? `${p2.at}: ` : ""}${p2.src}: ${p2.message}. Fix the reference or add the file.` });
188696
189105
  }
188697
189106
  if (node2.kind !== "storyboard" && node2.kind !== "compare") continue;
188698
189107
  for (const [src, key] of node2.dependencies) {
@@ -188726,7 +189135,7 @@ function enclosingGroups(file3) {
188726
189135
  }
188727
189136
  return ids;
188728
189137
  }
188729
- function validateSpec(file3, text4, id2, context) {
189138
+ function validateSpec(file3, text4, id2, context, warn4) {
188730
189139
  const errors = [];
188731
189140
  const add2 = (line, rule, message) => errors.push({ file: rel(file3), line, rule, message });
188732
189141
  const header = cardHeaderProblems(file3, text4, context, true);
@@ -188790,24 +189199,24 @@ function validateSpec(file3, text4, id2, context) {
188790
189199
  if (device !== void 0 && device !== "mobile" && device !== "desktop") add2(i + 1, "mockup-device", `device="${device}" is not a device. Use device="mobile" or device="desktop".`);
188791
189200
  const src = line.match(/\bsrc="([^"]*)"/)?.[1] ?? "";
188792
189201
  const variants = line.match(/\bvariants='([^']*)'/)?.[1];
188793
- const why2 = variants === void 0 ? null : variantsProblem(variants, src, id2);
189202
+ const why2 = variants === void 0 ? null : variantsProblem(variants, src, file3, id2);
188794
189203
  if (why2) add2(i + 1, "mockup-variants", why2);
188795
- else if (id2 !== void 0 && src.startsWith(".assets/") && !inside(ASSETS, src.slice(".assets/".length))) {
188796
- add2(i + 1, "asset-src", `src="${src}" names no file. Write it as ${rel(ASSETS)}/${src.slice(".assets/".length)}, or fix the path.`);
189204
+ else if (id2 !== void 0 && isTaskAssetRef(src) && !existingAsset(file3, id2, src)) {
189205
+ add2(i + 1, "asset-src", `src="${src}" must name a file within this task's asset folder. Fix the reference or add the file.`);
188797
189206
  }
188798
189207
  }
188799
189208
  if (/^\s*<Storyboard\b/.test(line) && (storyboardTag(line) === null || lines[i - 1]?.trim() || lines[i + 1]?.trim())) {
188800
- add2(i + 1, "storyboard-block", 'Put one self-closing <Storyboard src=".assets/<card id>/storyboard.json" /> tag on its own line, with blank lines around it.');
189209
+ add2(i + 1, "storyboard-block", 'Put one self-closing <Storyboard src="asset:storyboard.json" /> tag on its own line, with blank lines around it.');
188801
189210
  }
188802
189211
  if (/^\s*<Studio\b/.test(line) && (!studioTag(line) || lines[i - 1]?.trim() || lines[i + 1]?.trim())) {
188803
- add2(i + 1, "studio-block", 'Put one self-closing <Studio src=".assets/<card id>/studio-review/review.json" /> tag on its own line, with blank lines around it.');
189212
+ add2(i + 1, "studio-block", 'Put one self-closing <Studio src="asset:studio-review/review.json" /> tag on its own line, with blank lines around it.');
188804
189213
  }
188805
189214
  if (/^\s*<Compare\b/.test(line)) {
188806
189215
  const attrs = compareAttrs(line);
188807
189216
  if (!attrs || lines[i - 1]?.trim() || lines[i + 1]?.trim()) add2(i + 1, "compare-block", 'Put one self-closing <Compare a="..." b="..." label="..." /> tag on its own line, with blank lines around it.');
188808
189217
  else if (!attrs.a || !attrs.b || !attrs.label) add2(i + 1, "compare-attributes", 'Add non-empty a="...", b="..." and label="..." attributes to the Compare tag.');
188809
189218
  else if (id2 !== void 0) {
188810
- const why2 = compareProblem(attrs, id2);
189219
+ const why2 = compareProblem(attrs, file3, id2);
188811
189220
  if (why2) add2(i + 1, why2.rule, why2.message);
188812
189221
  }
188813
189222
  }
@@ -188841,7 +189250,11 @@ function validateSpec(file3, text4, id2, context) {
188841
189250
  for (const title of required3) if (!seen.has(title)) add2(end2 + 2, "missing-section", `Missing ## ${title}. Restore that section; keep its title in English.`);
188842
189251
  if (markers.length !== 1) add2(markers[1] ?? end2 + 2, "boundary", `Found ${markers.length} <!-- agent --> boundaries; expected exactly one, between the human and agent sections.`);
188843
189252
  for (const problem2 of cardTodoProblems(file3, visible, inPreview)) add2(problem2.line, problem2.code, `${problem2.message}. ${problem2.hint}`);
188844
- if (id2 !== void 0) errors.push(...validateStoryboards(file3, id2, text4), ...validatePreviewFiles(file3, id2, text4));
189253
+ if (id2 !== void 0) {
189254
+ errors.push(...validateStoryboards(file3, id2, text4));
189255
+ const attachments = validatePreviewFiles(file3, id2, text4, warn4);
189256
+ errors.push(...attachments.filter((problem2) => problem2.rule !== "asset-reference" || !errors.some((error62) => error62.file === problem2.file && error62.line === problem2.line)));
189257
+ }
188845
189258
  return errors;
188846
189259
  }
188847
189260
  var ASSET_LINE = /^\s*<(?:Asset|Mockup)\b[^<>]*\/>\s*$/;
@@ -188854,17 +189267,16 @@ function setEnd(lines, at2) {
188854
189267
  if (!assets || !/^\s*<\/Set>\s*$/.test(lines[i] ?? "") || lines[i + 1]?.trim()) return -1;
188855
189268
  return i;
188856
189269
  }
188857
- function inside(dir, name) {
189270
+ function existingAsset(card, id2, source2) {
188858
189271
  try {
188859
- const root2 = fs60.realpathSync(dir);
188860
- const real2 = fs60.realpathSync(path62.join(dir, name));
188861
- return real2.startsWith(root2 + path62.sep) && fs60.statSync(real2).isFile() ? real2 : null;
189272
+ const file3 = resolveBoardAsset(KANBAN, BOARD_STATE, id2, source2, card);
189273
+ return file3 && fs60.statSync(file3, { throwIfNoEntry: false })?.isFile() ? file3 : null;
188862
189274
  } catch {
188863
189275
  return null;
188864
189276
  }
188865
189277
  }
188866
- function variantsProblem(raw, src, id2) {
188867
- const shape = `Write variants='{"<label>": ".assets/<card id>/<file>", ...}' with at least two versions.`;
189278
+ function variantsProblem(raw, src, card, id2) {
189279
+ const shape = `Write variants='{"<label>": "asset:<path>", ...}' with at least two versions.`;
188868
189280
  let parsed;
188869
189281
  try {
188870
189282
  parsed = JSON.parse(raw);
@@ -188876,17 +189288,14 @@ function variantsProblem(raw, src, id2) {
188876
189288
  if (files.length < 2 || !files.every((f2) => typeof f2 === "string" && f2)) return `variants needs at least two labels, each naming a file. ${shape}`;
188877
189289
  if (!files.includes(src)) return `src="${src}" is not one of the variants. Set src to the version shown first.`;
188878
189290
  if (id2 === void 0) return null;
188879
- const dir = path62.join(ASSETS, String(id2));
188880
- for (const f2 of files) {
188881
- const parts = f2.split("/");
188882
- if (parts.length !== 3 || parts[0] !== ".assets" || parts[1] !== String(id2) || !inside(dir, parts[2])) {
188883
- return `Variant ${f2} names no file in this card's asset folder .assets/${id2}/. Write the file there or fix the path.`;
189291
+ for (const file3 of files) {
189292
+ if (!isTaskAssetRef(file3) || !existingAsset(card, id2, file3)) {
189293
+ return `Variant ${file3} must name a file within this task's asset folder. Fix the reference or add the file.`;
188884
189294
  }
188885
189295
  }
188886
189296
  return null;
188887
189297
  }
188888
- function compareProblem(attrs, id2) {
188889
- const dir = path62.join(ASSETS, String(id2));
189298
+ function compareProblem(attrs, card, id2) {
188890
189299
  const src = (message) => ({ rule: "compare-src", message });
188891
189300
  const shots = (message) => ({ rule: "compare-shots", message });
188892
189301
  const json2 = (file3) => {
@@ -188900,7 +189309,7 @@ function compareProblem(attrs, id2) {
188900
189309
  for (const side of ["a", "b"]) {
188901
189310
  const named = assetName(attrs[side], id2, []);
188902
189311
  if (!("name" in named)) return src(`Compare ${side} is ${named.actual}; expected ${named.expected}.`);
188903
- const file3 = inside(dir, named.name);
189312
+ const file3 = existingAsset(card, id2, attrs[side]);
188904
189313
  if (!file3) return src(`Compare ${side} ${attrs[side]} names no file in this card's asset folder. Write the file there or fix the path.`);
188905
189314
  const data = files[side] = json2(file3);
188906
189315
  if (typeof data?.a === "string" && typeof data.b === "string") return src(`Compare ${side} ${attrs[side]} is another compare. Compare its two files directly.`);
@@ -188913,7 +189322,7 @@ function compareProblem(attrs, id2) {
188913
189322
  const read6 = (at2) => {
188914
189323
  const named = assetName(at2, id2, ["json"]);
188915
189324
  if (!("name" in named)) return { message: `Compare shots is ${named.actual}; expected ${named.expected}.` };
188916
- const file3 = inside(dir, named.name);
189325
+ const file3 = existingAsset(card, id2, at2);
188917
189326
  if (!file3) return { message: `Compare shots ${at2} names no file in this card's asset folder. Write the JSON there or fix the path.` };
188918
189327
  try {
188919
189328
  return { data: JSON.parse(fs60.readFileSync(file3, "utf8")) };
@@ -188934,16 +189343,15 @@ function compareProblem(attrs, id2) {
188934
189343
  }
188935
189344
  function validateStoryboards(file3, id2, text4) {
188936
189345
  const errors = [];
188937
- const dir = path62.join(ASSETS, String(id2));
188938
189346
  for (const [tag, tagOf, rule, fix] of [
188939
189347
  ["Storyboard", storyboardTag, "storyboard-src", "Write the JSON there or fix the path."],
188940
189348
  ["Studio", studioTag, "studio-src", "Fix the path or freeze the draft with `akb studio preview <card> --folder <draft> --base <baseline>` and use the returned Studio tag."]
188941
189349
  ]) {
188942
189350
  for (const marker of storyboardMarkers(text4, tagOf)) {
188943
- const named = assetName(marker.src, id2, ["json"], tag === "Studio");
189351
+ const named = assetName(marker.src, id2, ["json"]);
188944
189352
  const add2 = (message) => errors.push({ file: rel(file3), line: marker.line, rule, message });
188945
189353
  if (!("name" in named)) add2(`${tag} src is ${named.actual}; expected ${named.expected}.`);
188946
- else if (!inside(dir, named.name)) add2(`${tag} src ${marker.src} names no file in this card's asset folder. ${fix}`);
189354
+ else if (!existingAsset(file3, id2, marker.src)) add2(`${tag} src ${marker.src} names no file in this card's asset folder. ${fix}`);
188947
189355
  }
188948
189356
  }
188949
189357
  return errors;
@@ -189773,11 +190181,7 @@ function cmdRemove(id2, metric, options = {}) {
189773
190181
  }
189774
190182
  function removeCard(id2, metric, options) {
189775
190183
  if (!Number.isInteger(id2)) die("need a numeric task id");
189776
- const delivery = activeDelivery(id2);
189777
- if (metric === "completed" && delivery && options.completing !== delivery.deliveryId) {
189778
- die(`Finish this step with delivery complete ${delivery.deliveryId}.`, { kind: "card-held" });
189779
- }
189780
- const held5 = heldByDelivery(id2);
190184
+ const held5 = metric === "completed" ? void 0 : heldByDelivery(id2);
189781
190185
  if (held5) die(held5, { kind: "card-held" });
189782
190186
  const creating = options.cleanupDiscarded ? null : creationRefusal(id2, cardCreation(id2, options.discard === true), metric === "completed" ? "archive" : "reject", metric === "rejected" && options.discard === true);
189783
190187
  if (creating) die(creating, { kind: "card-being-created" });
@@ -189795,7 +190199,7 @@ function removeCard(id2, metric, options) {
189795
190199
  const meta3 = parseFrontmatter(fs67.readFileSync(card.file, "utf8")).meta;
189796
190200
  if (!meta3 || meta3.rejected) die(`#${card.id} is not eligible for archive.`, { kind: "conflict" });
189797
190201
  if (meta3.questions.length) die(`Resolve the open questions on #${card.id} before archiving.`, { kind: "conflict" });
189798
- if (card.id !== id2 && (activeDelivery(card.id) || creationRefusal(card.id, cardCreation(card.id), "archive", false))) {
190202
+ if (card.id !== id2 && creationRefusal(card.id, cardCreation(card.id), "archive", false)) {
189799
190203
  die(`Finish the active work on #${card.id} before archiving.`, { kind: "card-held" });
189800
190204
  }
189801
190205
  }
@@ -190121,7 +190525,7 @@ function cmdInspect(id2) {
190121
190525
  agent,
190122
190526
  currentStageId: p2.currentStageId,
190123
190527
  stages: p2.stages.map(({ id: id3, status: status2, version: version2 }) => ({ id: id3, status: status2, version: version2 })),
190124
- artifact: p2.displayedArtifact ? { stageId: p2.displayedArtifact.stageId, version: p2.displayedArtifact.version, section: null, files: [.../* @__PURE__ */ new Set([...Object.keys(p2.displayedArtifact.assets).filter((key) => key !== "folder"), ...bodySources(p2.displayedArtifact.body)])].filter((file4) => !path70.isAbsolute(file4) && !/^[a-z][\w+.-]*:/i.test(file4)) } : null
190528
+ artifact: p2.displayedArtifact ? { stageId: p2.displayedArtifact.stageId, version: p2.displayedArtifact.version, section: null, files: [.../* @__PURE__ */ new Set([...Object.keys(p2.displayedArtifact.assets).filter((key) => key !== "folder"), ...bodySources(p2.displayedArtifact.body)])].filter((file4) => isAssetRef(file4) || !path70.isAbsolute(file4) && !/^[a-z][\w+.-]*:/i.test(file4)) } : null
190125
190529
  })), []),
190126
190530
  delivery,
190127
190531
  runs,
@@ -190173,7 +190577,7 @@ async function cmdValidate(id2) {
190173
190577
  const batch2 = await Promise.all(tasks.slice(i, i + 8).map(async ([number4, task]) => [number4, await readCardStudio(task)]));
190174
190578
  for (const [number4, context] of batch2) contexts.set(number4, context);
190175
190579
  }
190176
- const errors = cards.flatMap(([file3, card]) => validateSpec(file3, card.text, card.id, contexts.get(card.id)));
190580
+ const errors = cards.flatMap(([file3, card]) => validateSpec(file3, card.text, card.id, contexts.get(card.id), warn));
190177
190581
  const reason = errors.length ? formatContractErrors(errors) : void 0;
190178
190582
  const session = insideRun();
190179
190583
  if (session) patch(session, (run3) => {
@@ -190298,24 +190702,22 @@ var remote2 = /^(?:[a-z][\w+.-]*:|\/|#)/i;
190298
190702
  var artifactId = /^art_[a-z0-9]+$/i;
190299
190703
  var object2 = (value) => isObject(value) ? value : {};
190300
190704
  var own2 = (record2, key) => Object.hasOwn(record2, key) ? record2[key] : void 0;
190301
- function sourceOf(pins, source2, owner2) {
190705
+ function sourceOf(pins, source2, id2, owner2) {
190302
190706
  const [ref] = splitFileReference(source2);
190303
190707
  if (artifactId.test(ref)) {
190304
190708
  const pin = object2(own2(pins, ref));
190305
190709
  const names2 = Object.keys(pins).filter((key) => {
190306
- const alias = object2(pins[key]);
190307
- return !artifactId.test(key) && alias.artifact === ref && (pin.version === void 0 || alias.version === pin.version);
190710
+ const alias2 = object2(pins[key]);
190711
+ return !artifactId.test(key) && alias2.artifact === ref && (pin.version === void 0 || alias2.version === pin.version);
190308
190712
  });
190309
190713
  const first = names2[0];
190310
190714
  return first && names2.every((key) => object2(pins[key]).version === object2(pins[first]).version) ? first : ref;
190311
190715
  }
190312
- let name = ref;
190313
- try {
190314
- name = decodeURIComponent(ref);
190315
- } catch {
190316
- }
190317
- const local = owner2 && !name.startsWith(".assets/") ? relativeFileReference(name, owner2) : name;
190318
- return [local, path72.posix.normalize(local), source2].find((key) => Object.hasOwn(pins, key)) ?? local;
190716
+ const name = decodeFilePath(ref);
190717
+ const local = !owner2 || isTaskAssetRef(ref) ? ref : isTaskAssetRef(owner2) ? relativeAssetRef(ref, owner2) ?? "" : relativeFileReference(name, owner2);
190718
+ const taskFile = taskAssetPath(local, id2);
190719
+ const alias = taskFile === null ? void 0 : Object.keys(pins).find((key) => taskAssetPath(key, id2) === taskFile);
190720
+ return [local, path72.posix.normalize(local), source2].find((key) => Object.hasOwn(pins, key)) ?? alias ?? local;
190319
190721
  }
190320
190722
  async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
190321
190723
  const sections = [];
@@ -190343,8 +190745,8 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
190343
190745
  return { ok: true, value: file3 };
190344
190746
  };
190345
190747
  if (error62 || status2 === "pending" || status2 === "failed" || typeof artifact !== "string" || !artifactId.test(artifact) || typeof version2 !== "number" || !Number.isSafeInteger(version2) || version2 < 1) {
190346
- const missingEvidence = review.plan?.length && types.length && !local2 && (error62 || status2 === "pending" || status2 === "failed" || !artifact);
190347
- if (conflicting.has(source2) || missingEvidence) return invalid2(`${title} \xB7 ${source2}`);
190748
+ const missingEvidence = Array.isArray(review.plan) && review.plan.length && types.length && !local2 && (error62 || status2 === "pending" || status2 === "failed" || !artifact);
190749
+ if (conflicting.has(identity(source2)) || missingEvidence) return invalid2(`${title} \xB7 ${source2}`);
190348
190750
  return saved(typeof error62 === "string" ? error62 : artifact ? "Missing approved asset version." : "Missing asset record.");
190349
190751
  }
190350
190752
  const extension = path72.posix.extname(splitFileReference(source2)[0]).toLowerCase();
@@ -190353,13 +190755,13 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
190353
190755
  let kind = types.includes("tiled") ? "tiled" : !extension ? localPin?.kind ?? detected : detected;
190354
190756
  const matches2 = local2 && localPin?.version === version2;
190355
190757
  const issue2 = ws.materialIssues?.[source2];
190356
- const bytes = matches2 ? { ok: true, value: fs71.readFileSync(local2.file) } : issue2 && !conflicting.has(source2) ? { ok: false, error: issue2, code: void 0 } : await readAsset(artifact, version2, kind === "html" ? "html" : void 0);
190758
+ const bytes = matches2 ? { ok: true, value: fs71.readFileSync(local2.file) } : issue2 && !conflicting.has(identity(source2)) ? { ok: false, error: issue2, code: void 0 } : await readAsset(artifact, version2, kind === "html" ? "html" : void 0);
190357
190759
  if (!bytes.ok) {
190358
190760
  if (["unauthenticated", "forbidden", "unauthorized", "permission_denied"].includes(bytes.code ?? "")) return bytes;
190359
- if (conflicting.has(source2)) return invalid2(`${title} \xB7 ${source2} (version ${version2}): ${bytes.error}`);
190761
+ if (conflicting.has(identity(source2))) return invalid2(`${title} \xB7 ${source2} (version ${version2}): ${bytes.error}`);
190360
190762
  return saved(bytes.error);
190361
190763
  }
190362
- const basename = path72.posix.basename(splitFileReference(source2)[0]).replace(/[^\w. -]/g, "_");
190764
+ const basename = fileNameOf(source2).replace(/[^\w. -]/g, "_");
190363
190765
  const name = extension ? basename : basename + ({ html: ".html", storyboard: ".json", spritesheet: ".json", studio: ".json" }[kind] ?? "");
190364
190766
  const copy2 = path72.join(folder2, `${files.size + 1}-${name.replace(/\.tsx$/i, kind === "html" ? ".html" : ".tsx")}`);
190365
190767
  const entry = { file: matches2 ? local2.file : copy2, note: "" };
@@ -190380,9 +190782,9 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
190380
190782
  }
190381
190783
  const manifest2 = kind === "asset" ? knownManifest : fileManifest(kind, source2);
190382
190784
  const refs2 = referencesOf(manifest2, data).filter(({ src }) => !remote2.test(src));
190383
- const children = new Map(refs2.map(({ src, types: types2 }) => [src, { source: sourceOf(pins, src, source2), types: types2 }]));
190785
+ const children = new Map(refs2.map(({ src, types: types2 }) => [src, { source: sourceOf(pins, src, ws.number ?? void 0, source2), types: types2 }]));
190384
190786
  if (Array.isArray(dependencies)) for (const dep of dependencies) {
190385
- if (typeof dep === "string" && !children.has(dep)) children.set(dep, { source: sourceOf(pins, dep), types: [] });
190787
+ if (typeof dep === "string" && !children.has(dep)) children.set(dep, { source: sourceOf(pins, dep, ws.number ?? void 0), types: [] });
190386
190788
  }
190387
190789
  const targets = /* @__PURE__ */ new Map();
190388
190790
  for (const [ref, child] of children) {
@@ -190424,9 +190826,9 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
190424
190826
  if (typeof source2 === "string" && !refs.some((ref) => ref.src === source2)) refs.push({ src: source2, types: [] });
190425
190827
  }
190426
190828
  for (const { src, types } of refs) {
190427
- if (remote2.test(src)) continue;
190428
- const source2 = sourceOf(pins, src);
190429
- if (!types.length && !src.startsWith(".assets/") && !artifactId.test(src) && !Object.hasOwn(pins, source2)) continue;
190829
+ if (remote2.test(src) && !isAssetRef(src)) continue;
190830
+ const source2 = sourceOf(pins, src, ws.number ?? void 0);
190831
+ if (!types.length && !isTaskAssetRef(src) && !artifactId.test(src) && !Object.hasOwn(pins, source2)) continue;
190430
190832
  const result = await stage(source2, types);
190431
190833
  if (!result.ok) return result;
190432
190834
  }
@@ -190435,9 +190837,12 @@ async function stageSavedPreviews(directory3, ws, review, inputs, stopped2) {
190435
190837
 
190436
190838
  ${body}${attachments.length ? "\n\nPinned files:\n" + attachments.join("\n") : ""}` };
190437
190839
  }
190438
- if (review.plan?.length) {
190840
+ const flat = isFlatReviewPlan(review.plan);
190841
+ const plan2 = Array.isArray(review.plan) ? review.plan : [];
190842
+ const nodes = flat ? review.stages.flatMap((stage) => stage.preview && stage.status === "approved" ? [{ id: stage.id, previews: [stage.preview] }] : []) : plan2;
190843
+ if (nodes.length) {
190439
190844
  const stages = new Map(review.stages.map((stage) => [stage.id, stage]));
190440
- for (const node2 of review.plan) {
190845
+ for (const node2 of nodes) {
190441
190846
  const stage = stages.get(node2.id);
190442
190847
  if (!stage || !["approved", "done"].includes(stage.status)) return invalid2(node2.id);
190443
190848
  const snapshot = stage.snapshot;
@@ -190462,23 +190867,32 @@ ${body}${attachments.length ? "\n\nPinned files:\n" + attachments.join("\n") : "
190462
190867
  add2(`${title} \xB7 ${id2}`, saved, { ...legacyPins, ...pins }, section.sources);
190463
190868
  }
190464
190869
  }
190465
- } else if (inputs) {
190870
+ }
190871
+ if ((!nodes.length || flat) && inputs) {
190466
190872
  if (inputs.body) {
190467
190873
  const body = parsePreviewBlocks(inputs.body).blocks.reduceRight((text4, block) => text4.slice(0, block.start) + text4.slice(block.end), inputs.body).trim();
190468
190874
  if (body) add2("Task", body, inputs.assets, []);
190469
190875
  }
190470
190876
  for (const [id2, section] of Object.entries(inputs.sections)) {
190471
- add2(id2, section.body, inputs.assets, section.sources);
190877
+ add2(flat && nodes.some((node2) => node2.previews.includes(id2)) ? `${id2} \xB7 current draft` : id2, section.body, inputs.assets, section.sources);
190472
190878
  }
190473
190879
  }
190474
190880
  const selected2 = /* @__PURE__ */ new Map();
190881
+ const firstPins = /* @__PURE__ */ new Map();
190475
190882
  const conflicting = /* @__PURE__ */ new Set();
190883
+ const identity = (source2) => {
190884
+ const file3 = taskAssetPath(source2, ws.number ?? void 0);
190885
+ return file3 === null ? source2 : assetRef(file3);
190886
+ };
190476
190887
  for (const { pins } of sections) {
190477
190888
  for (const [source2, value] of Object.entries(pins)) {
190478
190889
  const pin = object2(value);
190479
- const previous = selected2.get(source2);
190480
- if (previous && (previous.artifact !== pin.artifact || previous.version !== pin.version)) conflicting.add(source2);
190481
- if (!previous && typeof pin.artifact === "string") selected2.set(source2, pin);
190890
+ const key = identity(source2);
190891
+ const previous = firstPins.get(key);
190892
+ if (previous && (previous.artifact !== pin.artifact || previous.version !== pin.version)) conflicting.add(key);
190893
+ if (typeof pin.artifact !== "string") continue;
190894
+ if (!previous) firstPins.set(key, pin);
190895
+ if (!selected2.has(source2)) selected2.set(source2, pin);
190482
190896
  }
190483
190897
  }
190484
190898
  const pulled = await pullMaterials(ws, Object.fromEntries(selected2), stopped2);
@@ -190494,10 +190908,10 @@ ${body}${attachments.length ? "\n\nPinned files:\n" + attachments.join("\n") : "
190494
190908
  const local = ws.number && cardAssetsDir(ws, ws.number);
190495
190909
  if (local && fs71.existsSync(local)) {
190496
190910
  for (const file3 of fs71.readdirSync(local, { recursive: true, withFileTypes: true })) {
190497
- if (file3.isFile()) sources3.add(`.assets/${ws.number}/${path72.relative(local, path72.join(file3.parentPath, file3.name)).split(path72.sep).join("/")}`);
190911
+ if (file3.isFile()) sources3.add(assetRef(path72.relative(local, path72.join(file3.parentPath, file3.name)).split(path72.sep).join("/")));
190498
190912
  }
190499
190913
  }
190500
- const supplemental = [...sources3].filter((source2) => !selected2.has(source2)).flatMap((source2) => {
190914
+ const supplemental = [...sources3].filter((source2) => !firstPins.has(identity(source2))).flatMap((source2) => {
190501
190915
  const local2 = material(source2);
190502
190916
  const problem2 = ws.materialIssues?.[source2];
190503
190917
  return local2 || problem2 ? [`- ${JSON.stringify(source2)} \xB7 ${local2 ? `local file: ${JSON.stringify(local2.file)}` : "unavailable"}${problem2 ? ` \xB7 ${problem2}` : ""}`] : [];
@@ -190514,9 +190928,9 @@ import fs72 from "node:fs";
190514
190928
  import path73 from "node:path";
190515
190929
 
190516
190930
  // ../cli/src/lib/signals/identity.ts
190517
- import { createHash as createHash8 } from "node:crypto";
190931
+ import { createHash as createHash9 } from "node:crypto";
190518
190932
  var DERIVED = "derived-";
190519
- var derivedSourceId = (seed) => `${DERIVED}${createHash8("sha256").update(seed).digest("hex").slice(0, 16)}`;
190933
+ var derivedSourceId = (seed) => `${DERIVED}${createHash9("sha256").update(seed).digest("hex").slice(0, 16)}`;
190520
190934
 
190521
190935
  // src/triage.ts
190522
190936
  var triageDir = (board) => path73.join(board, "triage");
@@ -190665,6 +191079,10 @@ function reviewOf2(file3, questionsOnly = false) {
190665
191079
  return null;
190666
191080
  }
190667
191081
  }
191082
+ function isSuccessfulArchive(file3) {
191083
+ const { meta: meta3 } = parseFrontmatter(fs74.readFileSync(file3, "utf8"));
191084
+ return !!meta3?.archived && !meta3.rejected;
191085
+ }
190668
191086
  function asks(file3) {
190669
191087
  try {
190670
191088
  return (parseFrontmatter(fs74.readFileSync(file3, "utf8")).meta?.questions ?? []).length > 0;
@@ -190795,6 +191213,7 @@ function boardAkb(job, ws, deps, io, task) {
190795
191213
  track: io.track,
190796
191214
  env: {
190797
191215
  ...env2,
191216
+ [DELIVERY_PHASE_ENV]: job.flow?.phase ?? (job.flow?.verb === "resolve" && job.flow.land_from ? "resolve" : void 0),
190798
191217
  [RETRY_FILE_ENV]: io.retryFile,
190799
191218
  [EXECUTION_RUNTIMES_ENV]: io.executionRuntimes,
190800
191219
  AI4KANBAN_SYNC_DIAGNOSTIC: io.diagnostic,
@@ -190811,7 +191230,7 @@ function boardAkb(job, ws, deps, io, task) {
190811
191230
  async function setUp(job, ws, deps, io) {
190812
191231
  const akb = boardAkb(job, ws, deps, io);
190813
191232
  const runtime = job.runtime;
190814
- const replayingReceipt = job.flow?.verify_delivery?.confirmed === true;
191233
+ const replayingReceipt = job.flow?.verify_delivery?.confirmed === true || job.flow?.phase === "land" && !!ws.number && isArchived(ws, ws.number) && !asks(cardFile(ws));
190815
191234
  if (!io.flowRun?.finished && !replayingReceipt) {
190816
191235
  let missing2 = unavailable(runtime, await deps.runtimes());
190817
191236
  if (missing2?.endsWith(" is not signed in on this computer.") && io.waitForLogin) {
@@ -190832,12 +191251,12 @@ async function setUp(job, ws, deps, io) {
190832
191251
  const hook = installCommitHook(ws.cwd, ws.board);
190833
191252
  if (hook.note) io.show(`${hook.note}
190834
191253
  `);
190835
- const pulled = await attemptSync(io, "prepare", () => pull(ws, deps.machineId, () => stopping(io), ws.materialIssues ? "implement" : void 0));
191254
+ const pulled = await attemptSync(io, "prepare", () => pull(ws, deps.machineId, () => stopping(io), job.flow?.phase === "land" ? "land" : ws.materialIssues ? "implement" : void 0));
190836
191255
  if (!pulled.ok) {
190837
191256
  if (pulled.failure?.source === "validation" || pulled.failure?.source === "sync") io.diagnostic = pulled.failure.summary;
190838
191257
  else if (pulled.code !== "board_content_conflict") return refusedSync(job, pulled);
190839
191258
  }
190840
- if (io.flowRun?.finished) return null;
191259
+ if (io.flowRun?.finished && job.flow?.phase !== "land") return null;
190841
191260
  const servers = mcpServersOf(ws);
190842
191261
  const mcpFile = path75.join(ws.board, ".sync", `${ws.task}.${job.id}.mcp.json`);
190843
191262
  const runtimes = {
@@ -190879,6 +191298,19 @@ function pickRow(job, r2, machine, reports, servers, mcpFile) {
190879
191298
  if (away) return { id: r2.id, name: r2.name, harness: runtime, settings: {}, away };
190880
191299
  return { id: r2.id, name: r2.name, harness: runtime, ...runtimeSettings(runtime, r2.model, r2.settings, r2.id, servers, mcpFile) };
190881
191300
  }
191301
+ function runStopped(run3) {
191302
+ if (!run3.status || run3.status === "running") return false;
191303
+ const root2 = run3.agentPid ? { pid: run3.agentPid, since: run3.agentStartedAt ?? run3.startedAt ?? 0, identity: run3.agentIdentity } : void 0;
191304
+ return run3.managedProcess ? connectionStopped(root2) : processesStopped(runMark(run3.sessionId, run3.agentStartedAt ?? run3.startedAt), root2);
191305
+ }
191306
+ function failedRunResumeDiagnostic(run3, stopped2, zh) {
191307
+ const session = run3 && !isSessionMissingFailure(run3.failure) ? run3.resumeId ?? (run3.canResume ? run3.sessionId : void 0) : void 0;
191308
+ return resumeBlocked({
191309
+ stopped: stopped2 && !!run3?.endedAt && run3.status === "error",
191310
+ session,
191311
+ unconfirmedCleanup: run3?.pendingWrites || run3?.cleanup?.status === "unconfirmed" || !!session && run3?.retryHistory?.at(-1)?.sessionAction !== "resume"
191312
+ }, zh);
191313
+ }
190882
191314
  function recoveryArgs(run3) {
190883
191315
  return run3.finished ? ["run", "log", run3.id] : ["run", "resume", run3.id, "--require-session"];
190884
191316
  }
@@ -190985,7 +191417,7 @@ function pictures(job, ws, id2) {
190985
191417
  const file3 = `${i + 1}-${path75.basename(a2.name).replace(/[^\w.-]+/g, "-")}`;
190986
191418
  fs74.writeFileSync(path75.join(dir, file3), Buffer.from(a2.content, "base64"));
190987
191419
  return `
190988
- <Asset src=".assets/${id2}/${file3}" label="${a2.name.replace(/["<>]/g, "") || file3}" />
191420
+ <Asset src="${assetRef(file3)}" label="${a2.name.replace(/["<>]/g, "") || file3}" />
190989
191421
  `;
190990
191422
  }).join("");
190991
191423
  }
@@ -191008,16 +191440,22 @@ async function runFlow(job, ws, deps, io) {
191008
191440
  if (io.flowRun?.failure) {
191009
191441
  const failure3 = io.flowRun.failure;
191010
191442
  const pause = io.flowRun.retryPause ?? "unsafe";
191443
+ const resumable = io.flowRun.resumeDiagnostic === null;
191444
+ const diagnostic = resumable ? void 0 : io.flowRun.resumeDiagnostic ?? resumeBlocked({ stopped: true, unconfirmedCleanup: true }, cloudLanguage(job) === "zh");
191445
+ const detail = [diagnostic, failure3.detail].filter(Boolean).join("\n");
191446
+ if (diagnostic) io.show(`[recovery] ${diagnostic}
191447
+ `);
191011
191448
  const failureDetail = {
191012
191449
  summary: failure3.summary,
191013
- ...failure3.detail ? { detail: failure3.detail } : {},
191450
+ ...detail ? { detail: clipDetail(detail) } : {},
191014
191451
  ...failure3.code ? { code: failure3.code } : {},
191015
191452
  source: failure3.source,
191016
191453
  runtime: { connector: job.runtime, name: null, model: job.model ?? null },
191017
191454
  attempt: 1,
191018
191455
  maxAttempts: MAX_RETRY_ATTEMPTS,
191019
191456
  pauseReason: pause,
191020
- safeToRetry: pause !== "unsafe",
191457
+ safeToRetry: resumable,
191458
+ sessionAction: resumable ? "resume" : "pause_unsafe",
191021
191459
  history: []
191022
191460
  };
191023
191461
  return { ok: false, reason: failure3.summary, exhausted: failure3.code === "retry_exhausted" || io.flowRun.retryPause === "limit", failure: failure3, report: { ...spentBy(runsSpent([], since, job, io), job), failure: failureDetail } };
@@ -191025,7 +191463,7 @@ async function runFlow(job, ws, deps, io) {
191025
191463
  const dispatchedReview = job.reviewAtDispatch ? job.taskReview : void 0;
191026
191464
  const hasReview = !!job.taskReview || flow.review_stages !== void 0;
191027
191465
  const initial = job.taskReview && reviewAuthorization(job.taskReview, flow.review_stages);
191028
- const skipPlan = initial ? initial.kind === "unreviewed" : flow.skip_plan;
191466
+ const skipPlan = initial ? initial.kind === "unreviewed" || initial.kind === "flat" && flow.skip_plan : flow.skip_plan;
191029
191467
  const verb = flow.verb === "create" ? skipPlan ? "implement" : "refine" : flow.verb;
191030
191468
  if (verb === "implement") ws.materialIssues = {};
191031
191469
  let currentTask;
@@ -191043,7 +191481,7 @@ async function runFlow(job, ws, deps, io) {
191043
191481
  }
191044
191482
  if (action === "implement") {
191045
191483
  if (!reviewAllows(authorization, action)) return "Finish the agreed review stages before delivery.";
191046
- if (flow.review_revision !== void 0 && (flow.verify_delivery ? flow.review_revision !== current2.value.review?.revision : !dispatchedReview && flow.review_revision !== review.revision)) {
191484
+ if (flow.review_revision !== void 0 && (flow.verify_delivery || flow.phase === "land" ? flow.review_revision !== current2.value.review?.revision : !dispatchedReview && flow.review_revision !== review.revision)) {
191047
191485
  return "Review authorization changed. Read the task again.";
191048
191486
  }
191049
191487
  }
@@ -191066,21 +191504,35 @@ async function runFlow(job, ws, deps, io) {
191066
191504
  const changed = await refreshReview(action);
191067
191505
  if (changed) return refuse(changed);
191068
191506
  if (!isDeepStrictEqual2(job.taskReview, review)) return refuse("Review authorization changed. Read the task again.");
191069
- if (!dispatchedReview && !review.plan?.length && (currentTask?.card_version !== task?.card_version || !isDeepStrictEqual2(currentTask?.preview_inputs, inputs))) {
191507
+ if (!dispatchedReview && (!Array.isArray(review.plan) || !review.plan.length) && (currentTask?.card_version !== task?.card_version || !isDeepStrictEqual2(currentTask?.preview_inputs, inputs))) {
191070
191508
  return refuse("The saved Previews changed. Read the task again.");
191071
191509
  }
191072
191510
  if (staged.value) env2 = { ...env2, [SAVED_PREVIEW_FILE_ENV]: staged.value };
191073
191511
  }
191074
- return akb(args2, show, env2);
191512
+ if (!show || !review || Array.isArray(review.plan) || !ws.number) return akb(args2, show, env2);
191513
+ const bridge = await previewSyncBridge(ws, { id: job.id, machineId: deps.machineId }, () => stopping(io));
191514
+ try {
191515
+ return await akb(args2, show, { ...env2, [REVIEW_SYNC_ENV]: bridge.env });
191516
+ } finally {
191517
+ bridge.close();
191518
+ }
191075
191519
  }
191520
+ if (flow.phase === "land") protectLandArchive(ws, job.id);
191076
191521
  const failed = await setUp(job, ws, deps, io);
191077
191522
  if (failed) return fail(failed);
191078
191523
  let id2 = akbCardOf(ws);
191524
+ if (flow.phase === "land") {
191525
+ try {
191526
+ return id2 ? await land(id2) : fail("This task has no card in the Land workspace.");
191527
+ } finally {
191528
+ if (previewDirectory) fs74.rmSync(previewDirectory, { recursive: true, force: true });
191529
+ }
191530
+ }
191079
191531
  let newRequest;
191080
191532
  const existedBeforeCreate = flow.verb !== "create" || !!id2;
191081
191533
  const learned = flow.verb === "create" && !id2 && !skipPlan ? await learnRejections(job, ws, deps, io, refreshReview) : [];
191082
191534
  if (io.lost()) return fail("");
191083
- if (flow.verb === "create" && !id2) {
191535
+ if (flow.verb === "create" && !id2 && !flow.resume_execution) {
191084
191536
  let said = { title: flow.title?.trim() ?? "", request: flow.text ?? "" };
191085
191537
  if (!said.title) {
191086
191538
  const task = await attemptSync(io, "review", () => deps.api.readTask(ws.task));
@@ -191123,7 +191575,7 @@ ${pictures(job, ws, ws.number)}`);
191123
191575
  id2 = created.value;
191124
191576
  newRequest = said.request.trim() ? said.request : void 0;
191125
191577
  }
191126
- if (flow.verb === "create" && id2 && !stopping(io)) {
191578
+ if (flow.verb === "create" && id2 && !flow.resume_execution && !stopping(io)) {
191127
191579
  const card = id2;
191128
191580
  const sent = await attemptSync(io, "create-sync", async () => await withBoard(ws, async (send3) => {
191129
191581
  const claim2 = { id: job.id, machineId: deps.machineId };
@@ -191140,8 +191592,17 @@ ${pictures(job, ws, ws.number)}`);
191140
191592
  if (sent.value) return sent.value;
191141
191593
  }
191142
191594
  if (stopping(io)) return fail("");
191143
- if (!id2) return fail("This task has no card on this computer.");
191595
+ if (!id2) return flow.resume_execution ? unverifiedResume() : fail("This task has no card on this computer.");
191144
191596
  return onCard(id2);
191597
+ function unverifiedResume(diagnostic = cloudLanguage(job) === "zh" ? "\u627E\u4E0D\u5230\u539F\u6267\u884C\u8BB0\u5F55\u3002" : "The original execution record could not be found.") {
191598
+ io.show(`[recovery] ${diagnostic}
191599
+ `);
191600
+ return {
191601
+ ok: false,
191602
+ reason: "task_recovery_unverified",
191603
+ failure: makeFailure("runner", diagnostic, { code: "task_recovery_unverified", detail: diagnostic })
191604
+ };
191605
+ }
191145
191606
  async function reconcileDelivery(card) {
191146
191607
  let deliveryId;
191147
191608
  const checked = await attemptSync(io, "reconcile", async () => {
@@ -191160,11 +191621,96 @@ ${pictures(job, ws, ws.number)}`);
191160
191621
  });
191161
191622
  return checked.ok ? checked.value : stopping(io) ? { kind: "none" } : { kind: "unverified", deliveryId, diagnostic: checked.error };
191162
191623
  }
191624
+ async function land(card) {
191625
+ io.onStop(async () => {
191626
+ if (!await stopRuns(deps.akb, ws, card, since, deps.stopMs)) throw new Error("The Land session did not stop.");
191627
+ });
191628
+ const reason = await refreshReview("implement");
191629
+ if (reason || stopping(io)) return fail(reason ?? "");
191630
+ const observed = await reconcileDelivery(card);
191631
+ const deliveryId = "deliveryId" in observed ? observed.deliveryId : void 0;
191632
+ if (stopping(io)) return fail("");
191633
+ if (!flow.land_from || flow.delivery_id && flow.delivery_id !== deliveryId) {
191634
+ return fail("The saved implementation does not match this Land job.");
191635
+ }
191636
+ const readRuns2 = async () => answerOf2(
191637
+ await akb(["run", "list", "--card", String(card), "--all", "--json"])
191638
+ )?.runs ?? [];
191639
+ const wroteArchive = async (runs) => {
191640
+ const saved = await reconcileDelivery(card);
191641
+ const landing = saved.kind === "completed" && saved.deliveryId === deliveryId && saved.commit && saved.branch ? { commit: saved.commit, branch: saved.branch } : void 0;
191642
+ const owned = runs.filter((r2) => !r2.parentId && r2.cloudExecution?.job === job.id && r2.cloudExecution.machine === deps.machineId);
191643
+ const last2 = owned.at(-1);
191644
+ return { ok: true, report: {
191645
+ ...spentBy(owned, job),
191646
+ card,
191647
+ deliveryId,
191648
+ landing,
191649
+ reply: last2?.result,
191650
+ session: last2?.resumeId
191651
+ } };
191652
+ };
191653
+ const localArchive = () => isArchived(ws, card) && !asks(cardFile(ws)) && isSuccessfulArchive(cardFile(ws));
191654
+ if (localArchive() && deliveryId && (observed.kind === "completed" || observed.kind === "resumable")) {
191655
+ if (observed.kind === "resumable") {
191656
+ const saved = await akb(["task", "archive", String(card), "--json"]);
191657
+ if (saved.code !== 0) return fail(refusal3(saved));
191658
+ }
191659
+ return wroteArchive(await readRuns2());
191660
+ }
191661
+ const work = observed.kind === "resumable" && observed.worktree ? path75.resolve(ws.cwd, observed.worktree) : null;
191662
+ const present = (file3) => fs74.statSync(file3, { throwIfNoEntry: false })?.isDirectory() === true;
191663
+ const within = work && path75.relative(ws.cwd, work).startsWith(`.akb${path75.sep}worktrees${path75.sep}`);
191664
+ const verified = within && work && present(work) && (observed.kind === "resumable" && observed.base ? !!observed.branch && git(["symbolic-ref", "--short", "HEAD"], work)?.trim() === observed.branch && git(["merge-base", "--is-ancestor", observed.base, "HEAD"], work) !== null : present(path75.join(path75.dirname(work), "base")));
191665
+ const source2 = await flowRunEvidence(ws, job, deps, flow.land_from);
191666
+ if (observed.kind !== "resumable" || observed.status !== "active" || !verified || !source2.stopped || !source2.run?.finished || source2.run.deliveryId !== deliveryId) {
191667
+ return fail(observed.kind === "unverified" ? observed.diagnostic : "The saved implementation workspace or its run could not be verified.");
191668
+ }
191669
+ let resume = io.flowRun;
191670
+ if (!resume && flow.sync_recovery_of) {
191671
+ const previous = await flowRunEvidence(ws, job, deps, flow.sync_recovery_of);
191672
+ if (!previous.stopped) return fail("The previous Land session has not stopped.");
191673
+ resume = previous.run;
191674
+ }
191675
+ while (!stopping(io)) {
191676
+ const args2 = resume ? ["run", "resume", resume.id, "--require-session"] : ["task", "implement", String(card)];
191677
+ const ran = await launch2([...args2, "--follow", "--events", "--json"], true, void 0, "implement");
191678
+ if (stopping(io)) return fail("");
191679
+ if (ran.reviewRefused) return fail(ran.reviewRefused);
191680
+ const runs = await readRuns2();
191681
+ if (localArchive()) return wroteArchive(runs);
191682
+ const owned = runs.filter((r2) => !r2.parentId && r2.cloudExecution?.job === job.id && r2.cloudExecution.machine === deps.machineId);
191683
+ const recent = owned.at(-1);
191684
+ const report2 = { ...spentBy(owned, job), card, deliveryId, session: recent?.resumeId, reply: recent?.result };
191685
+ if (asks(cardFile(ws))) {
191686
+ const review = reviewOf2(cardFile(ws), true);
191687
+ return { ok: true, report: { ...report2, review: review && review !== true ? review : {} } };
191688
+ }
191689
+ if (ran.code !== 0) return { ok: false, reason: refusal3(ran), failure: recent?.failure, report: report2 };
191690
+ const diagnostic = `The Land session ended before task #${card} was archived. Verify saved results and run akb task archive ${card}.`;
191691
+ const failure3 = makeFailure("validation", diagnostic, { code: "land_archive_missing" });
191692
+ const saved = await flowRunEvidence(ws, job, deps, job.id, io.flowRun);
191693
+ if (!io.recover || !saved.stopped || !saved.run?.finished) return { ok: false, reason: diagnostic, failure: failure3, report: report2 };
191694
+ const retry2 = await io.recover(failure3, async () => ({ ok: true, value: void 0 }));
191695
+ if (!retry2.ok) return { ok: false, reason: retry2.error, failure: failure3, exhausted: retry2.code === "retry_exhausted", report: report2 };
191696
+ resume = saved.run;
191697
+ io.flowRun = saved.run;
191698
+ io.diagnostic = diagnostic;
191699
+ }
191700
+ return fail("");
191701
+ }
191163
191702
  async function onCard(card) {
191164
191703
  const key = workKey(ws, card);
191165
191704
  const held5 = working.get(key) ?? 0;
191166
191705
  working.set(key, held5 + 1);
191167
191706
  try {
191707
+ if (flow.resume_execution && !io.flowRun) {
191708
+ const saved = await flowRunEvidence(ws, job, deps, flow.resume_execution);
191709
+ if (stopping(io)) return fail("");
191710
+ if (held5) return unverifiedResume(resumeBlocked({ stopped: false }, cloudLanguage(job) === "zh"));
191711
+ if (!saved.run) return unverifiedResume(saved.diagnostic);
191712
+ return await workOn(card, void 0, saved.run);
191713
+ }
191168
191714
  const verification = flow.verify_delivery;
191169
191715
  if (verification) {
191170
191716
  const denied = await refreshReview("implement");
@@ -191241,16 +191787,16 @@ ${pictures(job, ws, ws.number)}`);
191241
191787
  else working.delete(key);
191242
191788
  }
191243
191789
  }
191244
- async function workOn(id3, reconciled) {
191790
+ async function workOn(id3, reconciled, original) {
191245
191791
  io.onStop(async () => {
191246
191792
  if (!await stopRuns(deps.akb, ws, id3, since, deps.stopMs)) throw new Error("\u672A\u80FD\u786E\u8BA4\u539F\u6267\u884C\u5DF2\u505C\u6B62\u3002");
191247
191793
  });
191248
191794
  const text4 = flow.verb === "create" || !flow.text?.trim() ? "" : flow.text;
191249
- const archived = !io.flowRun && flow.resume && isArchived(ws, id3);
191795
+ const archived = !original && !io.flowRun && flow.resume && isArchived(ws, id3);
191250
191796
  if (archived && (verb !== "implement" || parseFrontmatter(fs74.readFileSync(cardFile(ws), "utf8")).meta?.rejected)) {
191251
191797
  return { ok: true, report: { card: id3, ...verb === "implement" ? { deliveryCompleted: false } : {} } };
191252
191798
  }
191253
- if (!io.flowRun && flow.resume && verb === "refine" && !hasReview && (!reconciled || reconciled.kind === "none")) {
191799
+ if (!original && !io.flowRun && flow.resume && verb === "refine" && !hasReview && (!reconciled || reconciled.kind === "none")) {
191254
191800
  const review2 = reviewOf2(cardFile(ws));
191255
191801
  if (review2) return { ok: true, report: { card: id3, ...review2 === true ? {} : { review: review2 } } };
191256
191802
  }
@@ -191264,10 +191810,12 @@ ${pictures(job, ws, ws.number)}`);
191264
191810
  const recorded = await attemptSync(io, "review", () => deps.api.readTask(ws.task));
191265
191811
  if (!recorded.ok) return fail(refusedSync(job, recorded));
191266
191812
  const review2 = recorded.value.review;
191813
+ const beforePlan = job.taskReview?.plan;
191814
+ const currentPlan = review2?.plan;
191267
191815
  const submitted = flow.review_stages.every((stage) => {
191268
191816
  const current2 = review2?.stages.find((state2) => state2.id === stage);
191269
- const before = job.taskReview?.plan?.find((node2) => node2.id === stage);
191270
- return current2 && current2.revision > flow.review_revision && ["ready", "approved", "done"].includes(current2.status) && (!before || isDeepStrictEqual2(before, review2?.plan?.find((node2) => node2.id === stage)));
191817
+ const before = Array.isArray(beforePlan) ? beforePlan.find((node2) => node2.id === stage) : void 0;
191818
+ return current2 && current2.revision > flow.review_revision && ["ready", "approved", "done"].includes(current2.status) && (!before || isDeepStrictEqual2(before, Array.isArray(currentPlan) ? currentPlan.find((node2) => node2.id === stage) : void 0));
191271
191819
  });
191272
191820
  if (submitted) {
191273
191821
  return { ok: true, report: { card: id3, session: io.flowRun.agentSession, ...spentBy(io.flowRun.priorSpend ?? [], job) } };
@@ -191304,7 +191852,11 @@ ${pictures(job, ws, ws.number)}`);
191304
191852
  }
191305
191853
  return void 0;
191306
191854
  };
191307
- if (io.flowRun) {
191855
+ if (original) {
191856
+ expectedDelivery = original.deliveryId;
191857
+ if (expectedDelivery) effectiveVerb = "implement";
191858
+ continuation = recoveryArgs(original);
191859
+ } else if (io.flowRun) {
191308
191860
  expectedDelivery = io.flowRun.deliveryId;
191309
191861
  if (expectedDelivery) effectiveVerb = "implement";
191310
191862
  continuation = io.repairDelivery ? ["run", "resume", io.flowRun.id, "--require-session"] : recoveryArgs(io.flowRun);
@@ -191326,7 +191878,7 @@ ${pictures(job, ws, ws.number)}`);
191326
191878
  effectiveVerb = "implement";
191327
191879
  const done = await resumeExistingDelivery();
191328
191880
  if (done) return done;
191329
- } else {
191881
+ } else if (!(verb === "resolve" && flow.land_from)) {
191330
191882
  const released = await akb(["delivery", "release", String(id3), "--json"]);
191331
191883
  if (released.code !== 0) {
191332
191884
  io.show(`[recovery] failed to release delivery lock${reconciled.deliveryId ? ` (delivery ${reconciled.deliveryId})` : ""}: ${refusal3(released)}
@@ -191392,6 +191944,21 @@ ${pictures(job, ws, ws.number)}`);
191392
191944
  const executed = runsSpent(runs, since, job, io);
191393
191945
  const spent = spentBy([...new Map([...learned, ...executed].map((run3) => [run3.sessionId, run3])).values()], job);
191394
191946
  const history = mergeRetryHistory(...executed.map((run3) => run3.retryHistory), recent?.retryHistory);
191947
+ if (!rejected && (isFlatReviewPlan(job.taskReview?.plan) || job.taskReview?.plan === null && effectiveVerb === "refine")) {
191948
+ const saved = await attemptSync(io, "review", () => deps.api.readTask(ws.task));
191949
+ if (!saved.ok) return fail(refusedSync(job, saved));
191950
+ if (saved.value.review?.stages.some((stage) => stage.job === job.id)) {
191951
+ const session2 = answer?.agentSession ?? answer?.error?.agentSession ?? recent?.resumeId;
191952
+ return { ok: true, report: {
191953
+ ...spent,
191954
+ card: id3,
191955
+ deliveryCompleted: false,
191956
+ ...deliveryId ? { deliveryId } : {},
191957
+ ...session2 ? { session: session2 } : {},
191958
+ ...recent?.result ? { reply: recent.result } : {}
191959
+ } };
191960
+ }
191961
+ }
191395
191962
  if (ran.code !== 0 && !recent?.retryPause && (ran.code === null || recent?.status === "interrupted")) {
191396
191963
  const reason = recent?.failure?.summary ?? "The task command was interrupted.";
191397
191964
  return { ok: false, reason, failure: makeFailure("runner", reason, { code: "board_command_interrupted", detail: ran.last }) };
@@ -191420,18 +191987,22 @@ ${pictures(job, ws, ws.number)}`);
191420
191987
  const failure3 = recent?.failure;
191421
191988
  const rawReason = failure3?.summary ?? reasonOf(answer?.error?.message?.replace(/^run \S+ ended \w+: /, "")) ?? refusal3(ran);
191422
191989
  const pause = readRetryPause(recent?.retryPause) ?? "unsafe";
191423
- const lastAction = history.at(-1)?.sessionAction;
191990
+ const stopped2 = recent?.cloudExecution?.job === job.id && recent.cloudExecution.machine === deps.machineId && runs.filter((run3) => run3.cloudExecution?.job === job.id).every(runStopped);
191991
+ const diagnostic = failedRunResumeDiagnostic(recent, stopped2, cloudLanguage(job) === "zh");
191992
+ const detail = [diagnostic, failure3?.detail ?? (rawReason.length > 300 ? rawReason : void 0)].filter(Boolean).join("\n");
191993
+ if (diagnostic) io.show(`[recovery] ${diagnostic}
191994
+ `);
191424
191995
  const failureDetail = {
191425
191996
  summary: clipSummary(rawReason) || "The run failed.",
191426
- ...failure3?.detail ? { detail: failure3.detail } : rawReason.length > 300 ? { detail: clipDetail(rawReason) } : {},
191997
+ ...detail ? { detail: clipDetail(detail) } : {},
191427
191998
  ...failure3?.code ? { code: failure3.code } : {},
191428
191999
  source: failure3?.source ?? "runtime",
191429
192000
  runtime: { connector: job.runtime, name: null, model: job.model ?? null },
191430
192001
  attempt: Math.max(1, (recent?.retry?.attempt ?? history.length) - 1),
191431
192002
  maxAttempts: recent?.retry?.of ?? MAX_RETRY_ATTEMPTS,
191432
192003
  pauseReason: pause,
191433
- safeToRetry: pause !== "unsafe" && lastAction !== "pause_unsafe",
191434
- ...lastAction ? { sessionAction: lastAction } : {},
192004
+ safeToRetry: !diagnostic,
192005
+ sessionAction: diagnostic ? "pause_unsafe" : "resume",
191435
192006
  history
191436
192007
  };
191437
192008
  return {
@@ -191442,6 +192013,17 @@ ${pictures(job, ws, ws.number)}`);
191442
192013
  report: { ...spent, ...tracked, failure: failureDetail }
191443
192014
  };
191444
192015
  }
192016
+ if (flow.phase === "implement" && effectiveVerb === "implement" && !rejected && !asked && !waiting && !completed) {
192017
+ if (!deliveryId || !recent || !runStopped(recent)) return fail("The implementation result or delivery workspace was not saved.");
192018
+ return { ok: true, report: {
192019
+ ...spent,
192020
+ card: id3,
192021
+ landReady: { deliveryId },
192022
+ session: answer?.agentSession,
192023
+ reply: recent.result,
192024
+ ...history.length ? { retries: history } : {}
192025
+ } };
192026
+ }
191445
192027
  if (!rejected && !completed && !asked && !waiting && (deliveryId || delivery)) {
191446
192028
  const reason = "The run ended without a delivery receipt. Verify the saved work and finish the original delivery.";
191447
192029
  return { ok: false, reason, failure: makeFailure("validation", reason, { code: "delivery_incomplete", detail: reason }), report: { ...spent, ...tracked } };
@@ -191506,6 +192088,8 @@ async function confirmFlowStopped(ws, job, deps) {
191506
192088
  )));
191507
192089
  }
191508
192090
  async function flowRunEvidence(ws, job, deps, execution = job.id, prior) {
192091
+ const manual = job.flow?.resume_execution === execution;
192092
+ const zh = cloudLanguage(job) === "zh";
191509
192093
  const id2 = job.flow && (akbCardOf(ws) ?? job.number);
191510
192094
  if (job.flow && !id2) return { stopped: false };
191511
192095
  const akb = boardAkb(job, ws, deps, { show() {
@@ -191522,13 +192106,17 @@ async function flowRunEvidence(ws, job, deps, execution = job.id, prior) {
191522
192106
  ...owned,
191523
192107
  ...allRuns.filter((run3) => !run3.parentId && !!run3.deliveryId && deliveryIds.has(run3.deliveryId) && ["conflict", "hook"].includes(run3.action ?? ""))
191524
192108
  ].map((r2) => [r2.sessionId, r2])).values()];
191525
- if (!runs.every((run3) => run3.status !== "running" && (run3.managedProcess ? connectionStopped(run3.agentPid ? { pid: run3.agentPid, identity: run3.agentIdentity } : void 0) : processesStopped(
191526
- runMark(run3.sessionId, run3.agentStartedAt ?? run3.startedAt),
191527
- run3.agentPid && run3.agentStartedAt ? { pid: run3.agentPid, since: run3.agentStartedAt } : void 0
191528
- )))) return { stopped: false };
192109
+ if (!runs.every(runStopped) || manual && allRuns.some((run3) => run3.status === "running")) {
192110
+ return { stopped: false, diagnostic: resumeBlocked({ stopped: false }, zh) };
192111
+ }
191529
192112
  const candidates = runs.filter((run3) => !run3.parentId).sort((a2, b2) => (b2.startedAt ?? 0) - (a2.startedAt ?? 0));
191530
192113
  const previous = candidates.find((run3) => run3.cloudExecution?.job === execution) ?? candidates.find((run3) => run3.sessionId === prior?.id) ?? candidates[0];
191531
- if (!previous) return { stopped: true };
192114
+ if (!previous || manual && previous.cloudExecution?.job !== execution) return { stopped: true };
192115
+ const resumeDiagnostic = failedRunResumeDiagnostic(previous, true, zh);
192116
+ if (manual) {
192117
+ if (resumeDiagnostic) return { stopped: true, diagnostic: resumeDiagnostic };
192118
+ return { stopped: true, run: { id: previous.sessionId, finished: false, deliveryId: previous.deliveryId } };
192119
+ }
191532
192120
  const terminal = job.flow && previous.status === "error" && previous.retryPause ? previous.failure : void 0;
191533
192121
  const failure3 = terminal && previous.retryPause === "limit" ? { ...terminal, code: terminal.code ?? "retry_exhausted" } : terminal;
191534
192122
  const recovery = agentRecovery({
@@ -191547,7 +192135,7 @@ async function flowRunEvidence(ws, job, deps, execution = job.id, prior) {
191547
192135
  from: previous.cloudExecution?.job,
191548
192136
  ...previous.resumeId ? { agentSession: previous.resumeId } : {},
191549
192137
  ...previous.deliveryId ? { deliveryId: previous.deliveryId } : {},
191550
- ...failure3 ? { failure: failure3 } : {},
192138
+ ...failure3 ? { failure: failure3, resumeDiagnostic: resumeDiagnostic ?? null } : {},
191551
192139
  ...previous.retryPause ? { retryPause: previous.retryPause } : {},
191552
192140
  priorSpend: [...priorSpend.values()]
191553
192141
  } };
@@ -191598,7 +192186,7 @@ function clearCheckpoint(id2) {
191598
192186
  }
191599
192187
  function checkpointEvent(checkpoint, event2) {
191600
192188
  if (turnSubmitted(event2)) checkpoint.submitted = true;
191601
- if (event2.kind === "tool_call") {
192189
+ if (event2.kind === "tool_call" && !isPollingTool(event2.data.title)) {
191602
192190
  const { toolCallId, status: status2, kind } = event2.data;
191603
192191
  if (!["read", "search", "fetch"].includes(kind)) checkpoint.effects = true;
191604
192192
  if (["completed", "failed"].includes(status2)) checkpoint.pending = checkpoint.pending.filter((id2) => id2 !== toolCallId);
@@ -191627,8 +192215,8 @@ var isReply = (job) => !job.flow && !!(job.chat || job.discussion);
191627
192215
  var usesBoardRun = (job, checkpoint) => !checkpoint.boardContinuation && !!(job.flow || job.agent || job.review);
191628
192216
  function checkpointRecovery(job, checkpoint, stopped2, failure3) {
191629
192217
  const board = usesBoardRun(job, checkpoint);
191630
- const unconfirmedCleanup = !!checkpoint.boardContinuation && checkpoint.pending.length > 0 || checkpoint.cleanup?.status === "unconfirmed" || failure3?.code === "codex_ownership_unconfirmed" || checkpoint.managedProcess && failure3?.code === "idle_timeout" && !idleStopConfirmed(checkpoint.cleanup, checkpoint.session);
191631
- const canReplay = replayable(checkpoint) && (!board || checkpoint.started === false) && (job.runtime !== "antigravity" || checkpoint.started === false);
192218
+ const unconfirmedCleanup = !!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));
192219
+ const canReplay = failure3?.code !== "idle_timeout" && replayable(checkpoint) && (!board || checkpoint.started === false) && (job.runtime !== "antigravity" || checkpoint.started === false);
191632
192220
  if (isSessionMissingFailure(failure3)) {
191633
192221
  if (!stopped2 || unconfirmedCleanup) return "unsafe";
191634
192222
  return canReplay ? "replay" : "unsafe";
@@ -191711,7 +192299,7 @@ function replySpent(checkpoint, runtime) {
191711
192299
  }
191712
192300
 
191713
192301
  // src/lock.ts
191714
- import crypto9 from "node:crypto";
192302
+ import crypto10 from "node:crypto";
191715
192303
  import fs76 from "node:fs";
191716
192304
  import net from "node:net";
191717
192305
  import path77 from "node:path";
@@ -191719,7 +192307,7 @@ var RunnerAlreadyRunning = class extends Error {
191719
192307
  };
191720
192308
  function lockPath() {
191721
192309
  const home4 = runnerHome();
191722
- if (process.platform === "win32") return `\\\\.\\pipe\\wildcrane-${crypto9.createHash("sha256").update(home4).digest("hex").slice(0, 16)}`;
192310
+ if (process.platform === "win32") return `\\\\.\\pipe\\wildcrane-${crypto10.createHash("sha256").update(home4).digest("hex").slice(0, 16)}`;
191723
192311
  return path77.join(home4, "runner.sock");
191724
192312
  }
191725
192313
  function socketIdentity(file3) {
@@ -191819,7 +192407,7 @@ function runnerSettingsSupport() {
191819
192407
  }
191820
192408
 
191821
192409
  // src/jobs.ts
191822
- import { createHash as createHash10 } from "node:crypto";
192410
+ import { createHash as createHash11 } from "node:crypto";
191823
192411
 
191824
192412
  // src/conversation-progress.ts
191825
192413
  function conversationProgress(attempt, send3, valid, unconfirmed) {
@@ -191918,7 +192506,7 @@ import fs77 from "node:fs";
191918
192506
  import path78 from "node:path";
191919
192507
  import os11 from "node:os";
191920
192508
  import { fileURLToPath as fileURLToPath5 } from "node:url";
191921
- import { createHash as createHash9 } from "node:crypto";
192509
+ import { createHash as createHash10 } from "node:crypto";
191922
192510
  init_file_limits();
191923
192511
  var inside2 = (root2, file3) => {
191924
192512
  const p2 = path78.relative(root2, file3);
@@ -191982,7 +192570,7 @@ function collectReplyImages(parts, cwd) {
191982
192570
  const bytes = read6();
191983
192571
  const mime = imageMime(bytes);
191984
192572
  if (!mime || p2.mime && p2.mime !== mime || bytes.length > ASSET_FILE_LIMIT) throw Error();
191985
- const id2 = `rim_${createHash9("sha256").update(bytes).digest("hex")}`;
192573
+ const id2 = `rim_${createHash10("sha256").update(bytes).digest("hex")}`;
191986
192574
  if (!files.has(id2)) files.set(id2, { read: read6, mime });
191987
192575
  return { type: "image", id: id2, mime, status: "saved" };
191988
192576
  } catch {
@@ -192037,7 +192625,7 @@ async function saveReplyImages(parts, cwd, upload2) {
192037
192625
  let bytes;
192038
192626
  try {
192039
192627
  bytes = f2.read();
192040
- if (`rim_${createHash9("sha256").update(bytes).digest("hex")}` !== key || imageMime(bytes) !== f2.mime) continue;
192628
+ if (`rim_${createHash10("sha256").update(bytes).digest("hex")}` !== key || imageMime(bytes) !== f2.mime) continue;
192041
192629
  } catch {
192042
192630
  continue;
192043
192631
  }
@@ -192116,7 +192704,7 @@ function replyGoals(goals) {
192116
192704
 
192117
192705
  // src/handoff.ts
192118
192706
  import { execFileSync as execFileSync2 } from "node:child_process";
192119
- import crypto10 from "node:crypto";
192707
+ import crypto11 from "node:crypto";
192120
192708
  import fs79 from "node:fs";
192121
192709
  import path80 from "node:path";
192122
192710
  var gitRead = (cwd, args2) => {
@@ -192131,7 +192719,7 @@ var gitRead = (cwd, args2) => {
192131
192719
  return null;
192132
192720
  }
192133
192721
  };
192134
- var digest = (value) => crypto10.createHash("sha256").update(value).digest("hex");
192722
+ var digest = (value) => crypto11.createHash("sha256").update(value).digest("hex");
192135
192723
  function authorizedFolder(folder2) {
192136
192724
  if (!folder2) return null;
192137
192725
  try {
@@ -192257,54 +192845,6 @@ import fs80 from "node:fs";
192257
192845
  import path81 from "node:path";
192258
192846
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
192259
192847
 
192260
- // src/reply-approval.ts
192261
- import http from "node:http";
192262
- import crypto11 from "node:crypto";
192263
- async function replyApprovalBridge(task, number4, approve) {
192264
- const token = crypto11.randomBytes(32).toString("hex");
192265
- let serial = Promise.resolve();
192266
- const server = http.createServer((req, res) => {
192267
- const answer = (status2, body) => {
192268
- res.writeHead(status2, { "content-type": "application/json" });
192269
- res.end(JSON.stringify(body));
192270
- };
192271
- if (req.method !== "POST" || req.url !== "/" || req.headers.authorization !== `Bearer ${token}` || req.headers.origin) {
192272
- answer(403, { ok: false, error: "This reply cannot approve that task." });
192273
- return;
192274
- }
192275
- let raw = "";
192276
- req.on("data", (data) => {
192277
- raw += data.toString();
192278
- if (raw.length > 16e3) req.destroy();
192279
- });
192280
- req.on("end", () => {
192281
- serial = serial.then(async () => {
192282
- try {
192283
- const body = JSON.parse(raw);
192284
- if (body.task !== task && body.task !== String(number4) && !new RegExp(`^[A-Za-z][A-Za-z0-9]{0,9}-${number4}$`).test(body.task ?? "")) {
192285
- answer(403, { ok: false, error: "Only the current task can be approved from this reply." });
192286
- return;
192287
- }
192288
- if (body.comment !== void 0 && typeof body.comment !== "string") throw Error("Invalid comment.");
192289
- if (!Number.isSafeInteger(body.review_revision) || body.review_revision < 0 || body.stage !== void 0 && typeof body.stage !== "string") throw Error("Name the review version you read.");
192290
- answer(200, await approve(body.comment, body.task, { stage: body.stage, review_revision: body.review_revision }));
192291
- } catch (e2) {
192292
- answer(400, { ok: false, error: e2 instanceof Error ? e2.message : "Approval failed." });
192293
- }
192294
- });
192295
- });
192296
- });
192297
- await new Promise((resolve2, reject) => {
192298
- server.once("error", reject);
192299
- server.listen(0, "127.0.0.1", resolve2);
192300
- });
192301
- const address = server.address();
192302
- return { env: JSON.stringify({ url: `http://127.0.0.1:${address.port}/`, token }), close: () => {
192303
- server.close();
192304
- server.closeAllConnections();
192305
- } };
192306
- }
192307
-
192308
192848
  // src/subagents.ts
192309
192849
  var BEFORE_CHARS = 4096;
192310
192850
  function trackSubagents(now = Date.now) {
@@ -192712,6 +193252,7 @@ async function runClaimed(job, deps, track, keep2, lease, replyStream) {
192712
193252
  } finally {
192713
193253
  scope.progress?.cancel();
192714
193254
  scope.bridge?.close();
193255
+ scope.reviewSync?.close();
192715
193256
  await scope.waitingStream?.end();
192716
193257
  }
192717
193258
  }
@@ -192719,7 +193260,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
192719
193260
  const id2 = job.id;
192720
193261
  const local = readCheckpoint(id2);
192721
193262
  const sourceId = job.flow?.sync_recovery_of ?? job.syncRecoveryOf ?? job.recoveryOf;
192722
- const source2 = sourceId ? readCheckpoint(sourceId) : null;
193263
+ const source2 = sourceId && job.flow?.phase !== "land" ? readCheckpoint(sourceId) : null;
192723
193264
  const previous = local ?? source2;
192724
193265
  const priorExecution = !!previous && previous.started !== false;
192725
193266
  const checkpoint = previous ?? { pending: [], started: false, effects: false };
@@ -192777,9 +193318,15 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
192777
193318
  };
192778
193319
  };
192779
193320
  const retryHistory = (report2) => mergeRetryHistory(checkpoint.retryHistory, report2?.retries);
192780
- const finishClaimed = async (outcome, reason = "", said2, landed) => {
193321
+ const finishClaimed = async (outcome, reason = "", said2, landed, onRefused) => {
192781
193322
  const before = spent();
192782
193323
  let report2 = before ? { ...before, ...said2 } : said2;
193324
+ if (flow?.phase === "land" && !report2?.processesStopped) {
193325
+ const stream2 = watching();
193326
+ if (stream2.asked()) await stream2.halted();
193327
+ if (!await stream2.confirmed() || ws && !await confirmFlowStopped(ws, job, deps)) return;
193328
+ report2 = { ...report2, processesStopped: true };
193329
+ }
192783
193330
  if (reply && checkpoint.replyParts && report2) {
192784
193331
  const stream2 = watching();
192785
193332
  const parts = await saveReplyImages(checkpoint.replyParts.parts, checkpoint.replyParts.cwd, async (key, bytes, mime) => {
@@ -192838,7 +193385,10 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
192838
193385
  checkpoint.completed = { outcome, reason, report: report2 };
192839
193386
  saveCheckpoint(id2, checkpoint);
192840
193387
  }
192841
- if (await settle2(outcome, reason, report2)) landed?.();
193388
+ if (await settle2(outcome, reason, report2, onRefused && (async (problem2) => {
193389
+ await onRefused(problem2);
193390
+ return false;
193391
+ }))) landed?.();
192842
193392
  };
192843
193393
  if (replyInput && manual && !previous && !job.retryReplay) checkpoint.submissionUnknown = true;
192844
193394
  const updating = checkpoint.updating === true;
@@ -193079,7 +193629,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
193079
193629
  return true;
193080
193630
  }
193081
193631
  if (watching().asked() && outcome !== "stopped" && !report2?.stopped) return settle2("stopped", "", { ...report2, stopped: true });
193082
- if (refused2 && onRefused && held4(deps, lease)) return onRefused();
193632
+ if (refused2 && onRefused && !sent.ok && held4(deps, lease)) return onRefused(sent);
193083
193633
  if (!sent.ok && sent.code === "retry_exhausted" && checkpoint.syncFailure && outcome !== "failed" && outcome !== "stopped") {
193084
193634
  const failure4 = checkpoint.syncFailure.failure;
193085
193635
  if (report2?.goals !== void 0) report2 = unsavedGoals(report2);
@@ -193322,7 +193872,7 @@ async function runClaimedStep(job, deps, track, keep2, lease, scope, replyStream
193322
193872
  const stream2 = watching();
193323
193873
  return sendBack(publishingJob, deps, ws, completed, sync, stream2, finishClaimed, landed, async (pushed) => {
193324
193874
  const records = pushed.conflict ? pendingConflicts(ws.board) : [];
193325
- const facts = createHash10("sha256").update(JSON.stringify(pushed.conflict ? records.map((r2) => ({ id: r2.id, state: r2.state, files: r2.files })) : pushed.failure)).digest("hex");
193875
+ const facts = createHash11("sha256").update(JSON.stringify(pushed.conflict ? records.map((r2) => ({ id: r2.id, state: r2.state, files: r2.files })) : pushed.failure)).digest("hex");
193326
193876
  const failRepair = async (reason) => {
193327
193877
  if (!stream2.asked()) stream2.event({ kind: "error", data: { text: reason } });
193328
193878
  await stream2.end();
@@ -193341,7 +193891,7 @@ ${diagnostic2}` : pushed.error);
193341
193891
  }
193342
193892
  const delivery = completed.deliveryCompleted && (!completed.session || job.runtime === "claude-code" && !checkpoint.boardContinuation) ? await deliverySession(ws, job, deps, completed) : void 0;
193343
193893
  const session = completed.deliveryCompleted ? completed.session ?? delivery?.session : report2.session ?? checkpoint.session;
193344
- if ((completed.deliveryCompleted || job.review || checkpoint.completed && flow) && !session) {
193894
+ if ((flow?.phase === "land" || completed.deliveryCompleted || job.review || checkpoint.completed && flow) && !session) {
193345
193895
  return failRepair(pushed.conflict ? `Board content conflicts could not be resolved because the original session is unavailable. Saved work was preserved.
193346
193896
  ${diagnostic2}` : `${diagnostic2}
193347
193897
  The original session is unavailable. Saved work was preserved.`);
@@ -193363,10 +193913,11 @@ The original session is unavailable. Saved work was preserved.`);
193363
193913
  conflictPrompt(ws.board, "Resolve and confirm synchronization, preserve completed work, then return the saved result."),
193364
193914
  ...completed.deliveryCompleted ? [`Resume only the board writeback for card #${completed.card ?? ws.number}. The delivery is complete${completed.landing ? ` (${completed.landing.commit} on ${completed.landing.branch})` : ""}. If blocked, report the concrete reason and keep the saved versions and draft.`] : []
193365
193915
  ].join("\n\n") : syncRepairPrompt(pushed.failure.summary);
193916
+ const repairPrompt = flow?.phase === "land" ? `${prompt} Verify the saved archive and fix its synchronization. Resume from the existing delivery result.` : prompt;
193366
193917
  const sessionTotal = job.runtime === "claude-code" ? checkpoint.boardContinuation && report2.costUsd !== void 0 ? report2.costUsd : checkpoint.boardContinuation?.sessionTotal ?? delivery?.sessionCostUsd ?? null : void 0;
193367
193918
  const failure4 = pushed.failure ?? makeFailure("validation", diagnostic2, { code: pushed.code });
193368
193919
  const prepared = await recover(failure4, async () => {
193369
- checkpoint.boardContinuation = { report: { ...completed, session }, facts, prompt, validation: !pushed.conflict || checkpoint.boardContinuation?.validation, sessionTotal };
193920
+ checkpoint.boardContinuation = { report: { ...completed, session }, facts, prompt: repairPrompt, validation: !pushed.conflict || checkpoint.boardContinuation?.validation, sessionTotal };
193370
193921
  checkpoint.session = session;
193371
193922
  Object.assign(checkpoint, { started: false, submitted: false, effects: false, pending: [] });
193372
193923
  delete checkpoint.completed;
@@ -193378,7 +193929,8 @@ The original session is unavailable. Saved work was preserved.`);
193378
193929
  if (!prepared.ok) return failRepair(prepared.error);
193379
193930
  scope.progress?.cancel();
193380
193931
  scope.bridge?.close();
193381
- await runClaimed({ ...publishingJob, prompt, resume: session, fork: false }, deps, track, keep2, lease, stream2);
193932
+ scope.reviewSync?.close();
193933
+ await runClaimed({ ...publishingJob, prompt: repairPrompt, resume: session, fork: false }, deps, track, keep2, lease, stream2);
193382
193934
  }, async () => {
193383
193935
  const reviewed = checkpoint.reviewedRejections;
193384
193936
  if (!reviewed) return { ok: true, value: void 0 };
@@ -193429,7 +193981,7 @@ The original session is unavailable. Saved work was preserved.`);
193429
193981
  };
193430
193982
  cwd = ws.cwd;
193431
193983
  keep2(cwd);
193432
- if (usesBoardRun(job, checkpoint) && !verification && !await recoverBoard(ws)) {
193984
+ if (usesBoardRun(job, checkpoint) && flow?.phase !== "land" && !verification && !await recoverBoard(ws)) {
193433
193985
  return finishClaimed("failed", job.flow?.historical_conflict ? "Board content conflicts could not be resolved. Saved work was preserved." : recoveryBlocked(job));
193434
193986
  }
193435
193987
  if (!job.flow && !job.review && !checkpoint.completed && !checkpoint.boardContinuation?.report.deliveryCompleted) {
@@ -193454,6 +194006,13 @@ The original session is unavailable. Saved work was preserved.`);
193454
194006
  }
193455
194007
  if (ws && job.chat && !job.flow && !checkpoint.completed) {
193456
194008
  const folder3 = ws;
194009
+ if (job.number && isFlatReviewPlan(job.taskReview?.plan)) {
194010
+ scope.reviewSync = await previewSyncBridge(
194011
+ folder3,
194012
+ { id: id2, machineId: deps.machineId },
194013
+ () => !held4(deps, lease) || !!waitingStream?.asked()
194014
+ );
194015
+ }
193457
194016
  scope.bridge = await replyApprovalBridge(job.task, job.number, async (comment, asked, target) => await withBoard(folder3, async (send3) => {
193458
194017
  if (checkpoint.approvalCancelled) return { ok: false, error: "This reply failed before. Ask again in a new reply." };
193459
194018
  const pushed = await send3({ id: id2, machineId: deps.machineId });
@@ -193582,6 +194141,7 @@ ${body}` : body;
193582
194141
  const configure = (p2) => {
193583
194142
  p2.renderer?.setRequiredImages?.(requiredImages);
193584
194143
  if (ws) p2 = { ...p2, env: akbEnv(deps.akb, ws.board, ws.cloudTask ?? void 0, cloudLanguage(job), p2.env) };
194144
+ if (scope.reviewSync) p2 = { ...p2, env: { ...p2.env, [REVIEW_SYNC_ENV]: scope.reviewSync.env } };
193585
194145
  if (scope.bridge) p2 = { ...p2, env: { ...p2.env, AI4KANBAN_REPLY_APPROVAL: scope.bridge.env } };
193586
194146
  if (goalFile) p2 = { ...p2, env: { ...akbEnv(deps.akb, discussed, void 0, cloudLanguage(job), p2.env), KANBAN_GOALS: goalFile } };
193587
194147
  const env2 = { ...p2.env, AI4KANBAN_EXECUTION: JSON.stringify({ job: job.id, machine: deps.machineId }), AI4KANBAN_TASK: job.task ?? "", [STUDIO_SNAPSHOT_ENV]: ws?.studioSnapshot && JSON.stringify(ws.studioSnapshot) };
@@ -193763,6 +194323,7 @@ ${body}` : body;
193763
194323
  persist();
193764
194324
  evidence.cancel();
193765
194325
  scope.bridge?.close();
194326
+ scope.reviewSync?.close();
193766
194327
  await runClaimed({ ...job, manualRecovery: false }, deps, track, keep2, lease, stream);
193767
194328
  await stream.end();
193768
194329
  return true;
@@ -193858,6 +194419,11 @@ ${body}` : body;
193858
194419
  }
193859
194420
  }
193860
194421
  const flowJob = job;
194422
+ if (flow?.phase === "land" && checkpoint.started && !io.flowRun) {
194423
+ const saved = await flowRunEvidence(ws, job, deps, id2);
194424
+ if (!saved.stopped) return finishClaimed("failed", "The previous Land session has not stopped.");
194425
+ io.flowRun = saved.run;
194426
+ }
193861
194427
  let result = await runFlow(flowJob, ws, deps, io);
193862
194428
  while (!result.ok && result.failure?.code === "board_command_interrupted" && !stream.asked() && !stream.lost()) {
193863
194429
  const failure4 = result.failure;
@@ -193974,23 +194540,17 @@ ${body}` : body;
193974
194540
  timedOut = resolve2;
193975
194541
  });
193976
194542
  idleWatch = createIdleWatchdog(() => {
193977
- if (plan3.idleRecovery) {
193978
- uncertainAtIdle = checkpoint.pending.length > 0;
193979
- checkpoint.failure = IDLE_FAILURE;
193980
- checkpoint.cleanup = { status: "unconfirmed", execution: id2, kept: [] };
193981
- persist();
193982
- idle2.abort();
193983
- return;
194543
+ uncertainAtIdle = checkpoint.pending.length > 0;
194544
+ checkpoint.failure = IDLE_FAILURE;
194545
+ if (plan3.managedProcess || uncertainAtIdle) checkpoint.cleanup = { status: "unconfirmed", execution: id2, kept: [] };
194546
+ persist();
194547
+ idle2.abort();
194548
+ if (!plan3.idleRecovery) {
194549
+ timedOut({ ok: false, error: IDLE_FAILURE.summary, failure: IDLE_FAILURE, cleanup: checkpoint.cleanup });
194550
+ cancellation.abort();
194551
+ stop(child, plan3.managedProcess);
193984
194552
  }
193985
- timedOut({
193986
- ok: false,
193987
- error: IDLE_FAILURE.summary,
193988
- failure: IDLE_FAILURE,
193989
- ...plan3.managedProcess ? { cleanup: { status: "unconfirmed", execution: id2, kept: [] } } : {}
193990
- });
193991
- cancellation.abort();
193992
- stop(child, plan3.managedProcess);
193993
- }, () => !!plan3.background?.());
194553
+ });
193994
194554
  const end2 = await Promise.race([
193995
194555
  timeout,
193996
194556
  plan3.converse(child, remember, false, Date.now() + CONVERSATION_MS.prepare, cancellation.signal, () => idleWatch?.touch(), idle2.signal),
@@ -194000,11 +194560,14 @@ ${body}` : body;
194000
194560
  ]);
194001
194561
  idleWatch.close();
194002
194562
  if (idle2.signal.aborted) {
194003
- if (!uncertainAtIdle && !checkpoint.pending.length && idleStopConfirmed(end2.cleanup, checkpoint.session)) checkpoint.cleanup = end2.cleanup;
194004
- else checkpoint.cleanup = { ...end2.cleanup, status: "unconfirmed", execution: end2.cleanup?.execution ?? id2, kept: end2.cleanup?.kept ?? [] };
194005
- } else checkpoint.cleanup = end2.cleanup;
194563
+ const unconfirmed = uncertainAtIdle || checkpoint.pending.length || plan3.managedProcess && !idleStopConfirmed(end2.cleanup, checkpoint.session);
194564
+ checkpoint.cleanup = unconfirmed ? { ...end2.cleanup, status: "unconfirmed", execution: end2.cleanup?.execution ?? id2, kept: end2.cleanup?.kept ?? [] } : end2.cleanup;
194565
+ persist();
194566
+ return { child, end: { ...end2, ok: false, canFallback: false }, failure: IDLE_FAILURE };
194567
+ }
194568
+ checkpoint.cleanup = end2.cleanup;
194006
194569
  persist();
194007
- return { child, end: end2, failure: idle2.signal.aborted ? IDLE_FAILURE : end2.failure };
194570
+ return { child, end: end2, failure: end2.failure };
194008
194571
  };
194009
194572
  const conversation = run3.converse ? await converse(run3) : void 0;
194010
194573
  let fallbackFailure;
@@ -194092,10 +194655,23 @@ ${body}` : body;
194092
194655
  child.stdout.setEncoding("utf8");
194093
194656
  const structured = !!renderer2.events;
194094
194657
  let backgroundFailure;
194658
+ let finishIdle;
194659
+ const idleEnded = new Promise((resolve2) => {
194660
+ finishIdle = () => resolve2({ code: null });
194661
+ });
194662
+ let idleExit;
194095
194663
  idleWatch = createIdleWatchdog(() => {
194096
194664
  backgroundFailure = IDLE_FAILURE;
194665
+ checkpoint.failure = IDLE_FAILURE;
194666
+ if (checkpoint.pending.length) checkpoint.cleanup = { status: "unconfirmed", execution: id2, kept: [] };
194667
+ persist();
194097
194668
  stop(child, plan3.managedProcess);
194098
- }, () => !!renderer2.background?.());
194669
+ idleExit = setTimeout(() => {
194670
+ finishIdle();
194671
+ child.stdout.destroy();
194672
+ child.stderr.destroy();
194673
+ }, KILL_GRACE_MS * 2);
194674
+ });
194099
194675
  let activityVersion = 0;
194100
194676
  let stderr = "";
194101
194677
  const fromAgent = (text4) => {
@@ -194117,32 +194693,37 @@ ${body}` : body;
194117
194693
  remember(e2);
194118
194694
  }
194119
194695
  };
194120
- child.stdout.on("data", (chunk) => {
194696
+ const readOutput = (chunk) => {
194121
194697
  fromAgent(renderer2.push(chunk));
194122
194698
  if (renderer2.terminalFailure?.()) {
194123
194699
  idleWatch?.close();
194124
194700
  stop(child, plan3.managedProcess);
194125
194701
  }
194126
- if (plan3.stdin && streamFinished(renderer2) && !child.stdin.writableEnded) {
194127
- idleWatch?.close();
194128
- child.stdin.end();
194129
- }
194130
- });
194702
+ if (plan3.stdin && streamFinished(renderer2) && !child.stdin.writableEnded) child.stdin.end();
194703
+ };
194704
+ child.stdout.on("data", readOutput);
194131
194705
  child.stderr.setEncoding("utf8");
194132
- child.stderr.on("data", (chunk) => {
194706
+ const readError = (chunk) => {
194133
194707
  renderer2.stderr?.(chunk);
194134
194708
  const visible = quietLines(plan3, chunk);
194135
194709
  stderr = (stderr + visible).slice(-4e3);
194136
194710
  stream.out(visible);
194137
- });
194138
- const ended2 = await new Promise((resolve2) => {
194139
- child.on("error", (e2) => resolve2({ code: null, failure: executionFailure(e2) }));
194140
- child.on("close", (code) => resolve2({ code }));
194141
- });
194711
+ };
194712
+ child.stderr.on("data", readError);
194713
+ const ended2 = await Promise.race([
194714
+ idleEnded,
194715
+ new Promise((resolve2) => {
194716
+ child.on("error", (e2) => resolve2({ code: null, failure: executionFailure(e2) }));
194717
+ child.on("close", (code) => resolve2({ code }));
194718
+ })
194719
+ ]);
194720
+ clearTimeout(idleExit);
194721
+ child.stdout.off("data", readOutput);
194722
+ child.stderr.off("data", readError);
194142
194723
  idleWatch?.close();
194143
194724
  fromAgent(renderer2.flush());
194144
194725
  const pending = renderer2.background?.() ? makeFailure("runtime", "The agent exited with unfinished background tasks.", { code: "background_unfinished" }) : void 0;
194145
- return { ...ended2, stderr: stderr.trim(), failure: ended2.failure ?? backgroundFailure ?? pending };
194726
+ return { ...ended2, stderr: stderr.trim(), failure: backgroundFailure ?? ("failure" in ended2 ? ended2.failure : void 0) ?? pending };
194146
194727
  };
194147
194728
  const plan2 = run3;
194148
194729
  const ended = await printed(plan2);
@@ -194275,11 +194856,12 @@ function writebackRecovery(job, report2) {
194275
194856
  return job.chat && !job.flow ? { ...report2, recovery: { safe: false, stopped: true, resumable: true, writeback: true } } : report2;
194276
194857
  }
194277
194858
  async function sendBack(job, deps, ws, report2, sync, stream, finish, landed, repair, confirm) {
194278
- const closesTask = job.flow && !report2.review && (report2.deliveryCompleted ?? (job.flow.verb === "implement" || job.flow.verb === "create" && job.flow.skip_plan));
194859
+ const lands = job.flow?.phase === "land" && !report2.review;
194860
+ const closesTask = job.flow && !report2.review && !report2.landReady && (report2.deliveryCompleted ?? (job.flow.verb === "implement" || job.flow.verb === "create" && job.flow.skip_plan));
194279
194861
  const taskReply = job.chat && !job.flow;
194280
194862
  const result = await sync("publish", async () => {
194281
194863
  const pushed2 = await push(ws, { id: job.id, machineId: deps.machineId }, () => stream.asked() || stream.lost());
194282
- if (pushed2.ok && (taskReply || closesTask) && !taskAssetsSynced(ws)) {
194864
+ if (pushed2.ok && (taskReply || closesTask || report2.landReady) && !taskAssetsSynced(ws)) {
194283
194865
  return { ok: false, code: "service_unavailable", error: "Preview uploads are pending." };
194284
194866
  }
194285
194867
  if (!pushed2.ok && writeBlock(pushed2)) return pushed2;
@@ -194295,6 +194877,26 @@ async function sendBack(job, deps, ws, report2, sync, stream, finish, landed, re
194295
194877
  stream.event({ kind: "error", data: { text: [repairable.error, ...savedErrors].join("\n") } });
194296
194878
  return repair(repairable);
194297
194879
  }
194880
+ if (lands && !denied && !stream.asked() && !stream.lost()) {
194881
+ const repairArchive = (error62, code) => repair({
194882
+ ok: false,
194883
+ conflict: false,
194884
+ error: error62,
194885
+ code,
194886
+ failure: makeFailure("validation", error62, { code: code ?? "land_archive_sync" })
194887
+ });
194888
+ const archive2 = syncedArchive(ws);
194889
+ if (!archive2) return repairArchive("The archived card and attachments did not synchronize.");
194890
+ return finish("done", "", { ...report2, archive: archive2 }, () => {
194891
+ confirmLandArchive(ws, job.id);
194892
+ landed();
194893
+ }, async (problem2) => {
194894
+ if (problem2.code === "conflict" || problem2.code === "version_conflict") {
194895
+ return repairArchive(problem2.error, problem2.code);
194896
+ }
194897
+ await finish("failed", syncRefusal(job, problem2), report2);
194898
+ });
194899
+ }
194298
194900
  await stream.end();
194299
194901
  if (stream.lost()) return;
194300
194902
  if (stream.asked()) return finish("stopped", "", report2);