wildcrane-runner 0.6.70 → 0.6.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.56 — built by runner/scripts/build.mjs. Do not edit.
2
+ // ai4kanban 0.11.58 — built by runner/scripts/build.mjs. Do not edit.
3
3
  import { createRequire as __ai4kanbanRequire } from 'node:module'
4
4
  const require = __ai4kanbanRequire(import.meta.url)
5
5
  var __create = Object.create;
@@ -505,27 +505,30 @@ __export(preview_stages_exports, {
505
505
  submitPreviewStage: () => submitPreviewStage
506
506
  });
507
507
  function selectPreviewStages(progress, ids) {
508
- if (progress.stages.length) throw Error("The stage selection is frozen. Revise the task to change its scope.");
509
508
  const wanted = new Set(ids);
510
509
  if (!ids.length || wanted.size !== ids.length || ids.some((id) => !progress.definitions.some((stage) => stage.id === id))) throw Error("Choose a nonempty list of unique known stage IDs.");
511
- const chosen = progress.definitions.filter((stage) => wanted.has(stage.id));
512
- if (chosen.some((stage, i) => stage.id !== ids[i]) || progress.definitions.some((stage) => !stage.when && !wanted.has(stage.id))) throw Error("Keep definition order and include every required stage.");
513
- progress.stages = chosen.map((stage, i) => ({ ...stage, status: i === 0 ? "running" : "pending", version: null }));
514
- progress.currentStageId = chosen[0].id;
510
+ const chosen = ids.map((id) => progress.definitions.find((stage) => stage.id === id));
511
+ if (progress.stages.length) {
512
+ if (JSON.stringify(progress.stages.map((stage) => stage.id)) === JSON.stringify(ids)) return;
513
+ progress.archivedSelections = [...progress.archivedSelections ?? [], structuredClone(progress.stages)];
514
+ progress.generation++;
515
+ }
516
+ progress.stages = chosen.map((stage, i) => structuredClone(progress.stages.find((held4) => held4.id === stage.id) ?? { ...stage, status: i === 0 ? "running" : "pending", version: null }));
517
+ progress.currentStageId = progress.stages.find((stage) => !["confirmed", "ready"].includes(stage.status))?.id ?? chosen.at(-1).id;
515
518
  }
516
519
  function previewBaseline(progress, stageId, execution) {
517
520
  const stage = progress.stages.find((stage2) => stage2.id === stageId);
518
- if (progress.currentStageId !== stageId || !stage || !["pending", "queued", "running", "failed", "stale"].includes(stage.status)) throw Error("This stage is not available for execution.");
521
+ if (progress.currentStageId !== stageId || !stage) throw Error("Unknown current stage.");
519
522
  progress.execution = execution;
520
523
  delete progress.failure;
521
- stage.status = "running";
524
+ if (!["awaiting_confirmation", "ready", "confirmed"].includes(stage.status)) stage.status = "running";
522
525
  return { definitionRevision: progress.definitionRevision, generation: progress.generation, stageId, execution };
523
526
  }
524
527
  function submitPreviewStage(progress, baseline, body, assets) {
525
528
  const stage = progress.stages.find((stage2) => stage2.id === baseline.stageId);
526
529
  if (baseline.definitionRevision !== progress.definitionRevision || baseline.generation !== progress.generation || baseline.execution !== progress.execution || progress.currentStageId !== baseline.stageId || !stage) throw Error("This execution is outdated. Reload the task.");
527
530
  if (["awaiting_confirmation", "ready"].includes(stage.status) && stage.artifact) return stage.artifact;
528
- if (stage.status !== "running" || !body.trim()) throw Error("Submit nonempty work for the running stage.");
531
+ if (stage.status !== "running") throw Error("This stage is not the current execution.");
529
532
  const artifact = { stageId: stage.id, version: (stage.version ?? 0) + 1, body, assets: structuredClone(assets) };
530
533
  stage.history = [...stage.history ?? [], artifact];
531
534
  stage.version = artifact.version;
@@ -576,10 +579,13 @@ function beginPreviewRevision(progress, execution) {
576
579
  progress.execution = execution;
577
580
  }
578
581
  function choosePreviewRevision(progress, from, execution) {
579
- if (!progress.revisionBase || progress.execution !== execution) throw Error("Only a newly requested revision can choose its starting stage.");
580
- const at2 = progress.revisionBase.findIndex((stage) => stage.id === from);
581
- if (at2 < 0 || progress.revisionBase.slice(0, at2).some((stage) => stage.status !== "confirmed")) throw Error("Revise from the earliest unconfirmed or affected stage.");
582
- progress.stages = structuredClone(progress.revisionBase);
582
+ if (progress.execution !== execution) throw Error("This execution is outdated. Reload the task.");
583
+ const saved = progress.revisionBase ?? progress.stages;
584
+ const at2 = saved.findIndex((stage) => stage.id === from);
585
+ if (at2 < 0) throw Error("Unknown stage.");
586
+ progress.archivedSelections = [...progress.archivedSelections ?? [], structuredClone(saved)];
587
+ progress.stages = structuredClone(saved);
588
+ progress.generation++;
583
589
  for (const stage of progress.stages.slice(at2)) {
584
590
  stage.status = "stale";
585
591
  delete stage.confirmation;
@@ -3351,10 +3357,10 @@ function findRollout(threadId) {
3351
3357
  }
3352
3358
  for (const name of names3) {
3353
3359
  if (!name.startsWith("rollout-") || !name.endsWith(tail)) continue;
3354
- const path90 = join2(dir, name);
3360
+ const path91 = join2(dir, name);
3355
3361
  try {
3356
- const at2 = statSync2(path90).mtimeMs;
3357
- if (!newest2 || at2 > newest2.at) newest2 = { path: path90, at: at2 };
3362
+ const at2 = statSync2(path91).mtimeMs;
3363
+ if (!newest2 || at2 > newest2.at) newest2 = { path: path91, at: at2 };
3358
3364
  } catch {
3359
3365
  }
3360
3366
  }
@@ -3362,11 +3368,11 @@ function findRollout(threadId) {
3362
3368
  return newest2?.path;
3363
3369
  }
3364
3370
  function readCodexRunFacts(threadId) {
3365
- const path90 = findRollout(threadId);
3366
- if (!path90) return void 0;
3371
+ const path91 = findRollout(threadId);
3372
+ if (!path91) return void 0;
3367
3373
  let raw;
3368
3374
  try {
3369
- raw = readFileSync2(path90, "utf8");
3375
+ raw = readFileSync2(path91, "utf8");
3370
3376
  } catch {
3371
3377
  return void 0;
3372
3378
  }
@@ -3492,8 +3498,8 @@ function renderCompleted(item) {
3492
3498
  const changes = Array.isArray(item.changes) ? item.changes : [];
3493
3499
  return changes.map((raw) => {
3494
3500
  const change2 = obj2(raw);
3495
- const path90 = str2(change2.path);
3496
- return path90 ? `\u23FA ${str2(change2.kind) || "change"}(${path90})
3501
+ const path91 = str2(change2.path);
3502
+ return path91 ? `\u23FA ${str2(change2.kind) || "change"}(${path91})
3497
3503
  ` : "";
3498
3504
  }).join("");
3499
3505
  }
@@ -3828,10 +3834,10 @@ function readKimiRunFacts(sessionId) {
3828
3834
  const total = { input: 0, cacheCreation: 0, cacheRead: 0, output: 0 };
3829
3835
  let model;
3830
3836
  let holding = 0;
3831
- for (const { path: path90, main } of wireFiles(entry.sessionDir)) {
3837
+ for (const { path: path91, main } of wireFiles(entry.sessionDir)) {
3832
3838
  let raw;
3833
3839
  try {
3834
- raw = readFileSync3(path90, "utf8");
3840
+ raw = readFileSync3(path91, "utf8");
3835
3841
  } catch {
3836
3842
  continue;
3837
3843
  }
@@ -4205,8 +4211,8 @@ var init_package = __esm({
4205
4211
  "../cli/package.json"() {
4206
4212
  package_default = {
4207
4213
  name: "wildcrane",
4208
- version: "0.11.56",
4209
- akbContract: 15,
4214
+ version: "0.11.58",
4215
+ akbContract: 16,
4210
4216
  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.",
4211
4217
  keywords: [
4212
4218
  "kanban",
@@ -4282,8 +4288,8 @@ var init_version = __esm({
4282
4288
  import fs16 from "node:fs";
4283
4289
  function whereHint(update2, title) {
4284
4290
  const locations = Array.isArray(update2.locations) ? update2.locations : [];
4285
- const path90 = str2(obj2(locations[0]).path);
4286
- return path90 && !title.includes(path90) ? hint(path90) : "";
4291
+ const path91 = str2(obj2(locations[0]).path);
4292
+ return path91 && !title.includes(path91) ? hint(path91) : "";
4287
4293
  }
4288
4294
  function saidBy(update2) {
4289
4295
  const content = Array.isArray(update2.content) ? update2.content : [];
@@ -5436,7 +5442,7 @@ async function run(io, options, tasks) {
5436
5442
  startupTimer = setTimeout(() => {
5437
5443
  if (!started) io.event?.({ kind: "log", data: { text: "[conversation] start_unconfirmed" } });
5438
5444
  }, CONVERSATION_MS.start);
5439
- await bounded(rpc.call("turn/start", { threadId, input: [{ type: "text", text: text5 }, ...images.map((path90) => ({ type: "localImage", path: path90 }))] }), CONVERSATION_MS.start, "Codex turn/start timed out; submission outcome is unknown.").catch((error) => {
5445
+ await bounded(rpc.call("turn/start", { threadId, input: [{ type: "text", text: text5 }, ...images.map((path91) => ({ type: "localImage", path: path91 }))] }), CONVERSATION_MS.start, "Codex turn/start timed out; submission outcome is unknown.").catch((error) => {
5440
5446
  if (!started) throw error;
5441
5447
  });
5442
5448
  };
@@ -8310,7 +8316,7 @@ var init_flows = __esm({
8310
8316
  group: "card",
8311
8317
  action: "refine",
8312
8318
  argument: "<id>",
8313
- gloss: "plan the card in one session",
8319
+ gloss: "plan the card",
8314
8320
  options: CARRY_OPTIONS
8315
8321
  },
8316
8322
  {
@@ -8412,8 +8418,8 @@ var init_file_limits = __esm({
8412
8418
  });
8413
8419
 
8414
8420
  // ../cli/src/lib/shared/board-files.ts
8415
- function studioRenamed(path90, content) {
8416
- const to = path90.replace(/^(rules\/)?workflows\//, "$1studios/").replace(/^(studios\/[^/]+)\/WORKFLOW\.md$/, "$1/STUDIO.md");
8421
+ function studioRenamed(path91, content) {
8422
+ const to = path91.replace(/^(rules\/)?workflows\//, "$1studios/").replace(/^(studios\/[^/]+)\/WORKFLOW\.md$/, "$1/STUDIO.md");
8417
8423
  if (!to.endsWith(".md")) return { path: to, content };
8418
8424
  if (to.startsWith("studios/")) return { path: to, content: content.replace(/^(icon:\s*["']?)workflow(-kit)?(["']?\s*)$/gm, "$1studio$2$3") };
8419
8425
  const front = /^(?:todo|triage)\//.test(to) ? /^---\r?\n[\s\S]*?\r?\n---/.exec(content)?.[0] : void 0;
@@ -8673,7 +8679,7 @@ function parseSpecAgent(text5, from, file2, builtIn = false, list2 = () => []) {
8673
8679
  const after2 = names(akb.after);
8674
8680
  const declaredSession = str3(akb.session);
8675
8681
  if (declaredSession && declaredSession !== "new") {
8676
- return bad(`\`${name}\` declares \`akb.session: ${declaredSession}\` \u2014 it is \`new\`, or left out to run in the planning session`);
8682
+ return bad(`\`${name}\` declares \`akb.session: ${declaredSession}\` \u2014 use \`new\` to recommend a separate session, or omit the preference`);
8677
8683
  }
8678
8684
  let stages;
8679
8685
  if (akb.stages !== void 0) {
@@ -8914,7 +8920,7 @@ function diagramFrom(files) {
8914
8920
  if ("problem" in read3) return null;
8915
8921
  return studioDiagram(read3.def, (name) => {
8916
8922
  const text5 = files[`agents/${name}/AGENT.md`];
8917
- const parsed = text5 === void 0 ? null : parseSpecAgent(text5, name, (path90) => files[`agents/${name}/${path90}`] ?? null, false);
8923
+ const parsed = text5 === void 0 ? null : parseSpecAgent(text5, name, (path91) => files[`agents/${name}/${path91}`] ?? null, false);
8918
8924
  return parsed && "agent" in parsed ? parsed.agent : null;
8919
8925
  });
8920
8926
  }
@@ -10945,7 +10951,7 @@ function specAgentSelector(id, studio, meta) {
10945
10951
  `\`akb raw previews --triggers --studio ${flow.id}\` whose conditions the card meets, always including those marked \`Always\`. Save them with`,
10946
10952
  `\`akb raw update ${id} --previews <agents>\` (\`""\` when that leaves none); its stages follow from them.`,
10947
10953
  "Then run only the chosen agents whose `After` is empty \u2014 the first stage; the rest run after its approval.",
10948
- `Command: \`akb raw previews <agent> ${id} <short note>\` \u2014 add \`--print\` to run it in this session, as \`akb guide refine\` says.`,
10954
+ `Command: \`akb raw previews <agent> ${id} <short note>\` \u2014 choose \`--print\` for this session or omit it for a separate session.`,
10949
10955
  "</preview-agents>"
10950
10956
  ].join("\n");
10951
10957
  }
@@ -10957,8 +10963,8 @@ function specAgentSelector(id, studio, meta) {
10957
10963
  // own job.
10958
10964
  "<preview-agents>",
10959
10965
  "The preview agents of this card's current stage, each writing one part of the card.",
10960
- ...agents.map((a2) => `- \`${a2.name}\` \u2014 ${a2.description}${a2.session || agentRun(a2.name).own ? " \xB7 runs in a session of its own: leave out `--print`" : ""}`),
10961
- `Command: \`akb raw previews <agent> ${id} <short note>\` \u2014 add \`--print\` to run it in this session, as \`akb guide refine\` says.`,
10966
+ ...agents.map((a2) => `- \`${a2.name}\` \u2014 ${a2.description}${a2.session === "new" ? " \xB7 separate session recommended" : ""}`),
10967
+ `Command: \`akb raw previews <agent> ${id} <short note>\` \u2014 choose \`--print\` for this session or omit it for a separate session.`,
10962
10968
  "</preview-agents>"
10963
10969
  ].join("\n");
10964
10970
  }
@@ -11064,7 +11070,6 @@ var init_candidate = __esm({
11064
11070
 
11065
11071
  // ../cli/src/lib/agent/outputs.ts
11066
11072
  import fs32 from "node:fs";
11067
- import os4 from "node:os";
11068
11073
  import path36 from "node:path";
11069
11074
  function cardBody(cardId2) {
11070
11075
  const found2 = locate(cardId2) ?? locateArchived(cardId2);
@@ -11088,23 +11093,11 @@ function recordedOutputs(delivery) {
11088
11093
  }
11089
11094
  return out;
11090
11095
  }
11091
- function filesStop(delivery) {
11092
- const outputs = recordedOutputs(delivery);
11093
- if (!outputs.length) {
11094
- return { reason: "output", why: "the card records no output file", paths: [] };
11095
- }
11096
- const missing = outputs.filter((f2) => !fs32.existsSync(resolveOutput(f2)));
11097
- if (missing.length) {
11098
- return { reason: "output", why: `recorded output files are missing: ${missing.join(", ")}`, paths: missing };
11099
- }
11100
- return void 0;
11101
- }
11102
- var TODO2, todos, plannedTodos, looksLikePath, resolveOutput;
11096
+ var TODO2, todos, plannedTodos, looksLikePath;
11103
11097
  var init_outputs = __esm({
11104
11098
  "../cli/src/lib/agent/outputs.ts"() {
11105
11099
  "use strict";
11106
11100
  init_cards();
11107
- init_paths();
11108
11101
  TODO2 = /^\s*[-*]\s+\[([ xX])\]\s+(.*)$/;
11109
11102
  todos = (cardId2) => cardBody(cardId2).split("\n").flatMap((line) => {
11110
11103
  const m = TODO2.exec(line);
@@ -11112,12 +11105,6 @@ var init_outputs = __esm({
11112
11105
  });
11113
11106
  plannedTodos = (cardId2) => todos(cardId2).map((t) => t.text);
11114
11107
  looksLikePath = (token2) => !/\s/.test(token2) && !token2.includes("://") && !token2.startsWith("-") && token2.includes("/");
11115
- resolveOutput = (file2) => {
11116
- if (file2.startsWith("~/")) return path36.join(os4.homedir(), file2.slice(2));
11117
- if (path36.isAbsolute(file2)) return file2;
11118
- if (file2.startsWith(".assets/")) return path36.join(ASSETS, file2.slice(".assets/".length));
11119
- return path36.join(REPO_ROOT, file2);
11120
- };
11121
11108
  }
11122
11109
  });
11123
11110
 
@@ -11263,7 +11250,7 @@ function nextDeliveryRun(deliveryId) {
11263
11250
  for (const delivery of store.deliveries) {
11264
11251
  if (deliveryId && delivery.deliveryId !== deliveryId) continue;
11265
11252
  if (delivery.status !== "active" || delivery.cardId === null) continue;
11266
- if (openQuestions(delivery.cardId) || store.runs.some((r2) => r2.deliveryId === delivery.deliveryId && r2.status === "running")) continue;
11253
+ if (store.runs.some((r2) => r2.deliveryId === delivery.deliveryId && r2.status === "running")) continue;
11267
11254
  if (answerOutcome(delivery) === "changed") {
11268
11255
  const superseded = withStore((live) => {
11269
11256
  const row = live.deliveries.find((d2) => d2.deliveryId === delivery.deliveryId);
@@ -11639,28 +11626,14 @@ function resumeRefusal(delivery, store) {
11639
11626
  const id = delivery.deliveryId;
11640
11627
  const what = delivery.cardId === null ? "the build" : `#${delivery.cardId}`;
11641
11628
  const task = delivery.cardId === null ? "" : String(delivery.cardId);
11642
- if (delivery.status === "active") {
11643
- return refusal("deliveryActive", `delivery ${id} has not ended \u2014 it is still in flight on ${what}.`, { id, task });
11644
- }
11645
- if (delivery.status === "finished") {
11646
- return refusal("deliveryFinished", `delivery ${id} finished; resume carries on one that ended abnormally.`, { id });
11647
- }
11648
11629
  if (delivery.status === "cancelled") {
11649
11630
  return refusal("deliveryCancelled", `delivery ${id} was cancelled, and its files were preserved. Start ${what} again.`, { id, task });
11650
11631
  }
11651
11632
  if (delivery.cardId === null) return void 0;
11652
11633
  const card = String(delivery.cardId);
11653
- const pendingArchive = delivery.completions?.some((c2) => !c2.finished && c2.step + 1 >= (delivery.studio?.land?.length ?? 1));
11654
- if (cardOnBoard(delivery.cardId) === false && !(pendingArchive && locateArchived(delivery.cardId))) {
11655
- return refusal(
11656
- "deliveryCardGone",
11657
- `#${card} is no longer on the board, so delivery ${id} has nothing left to finish.`,
11658
- { id, card }
11659
- );
11660
- }
11661
11634
  const live = store ?? readStore();
11662
11635
  const holder = activeIn(live, delivery.cardId);
11663
- if (holder) {
11636
+ if (holder && holder.deliveryId !== id) {
11664
11637
  const command = `${boardCommand()} raw delivery cancel ${holder.deliveryId}`;
11665
11638
  return refusal(
11666
11639
  "deliveryHeld",
@@ -11680,16 +11653,10 @@ function resumeRefusal(delivery, store) {
11680
11653
  }
11681
11654
  return void 0;
11682
11655
  }
11683
- function cardOnBoard(cardId2) {
11684
- try {
11685
- return !!locate(cardId2);
11686
- } catch {
11687
- return void 0;
11688
- }
11689
- }
11690
11656
  function resumeRecord(id, execution) {
11691
11657
  const found2 = namedDelivery(id) ?? endedDelivery(id);
11692
11658
  if (!found2) return { ok: false, ...unknownDelivery(id) };
11659
+ if (found2.status === "finished") return { ok: true, delivery: found2 };
11693
11660
  const refused = resumeRefusal(found2);
11694
11661
  if (refused && found2.status !== "active") return { ok: false, ...refused };
11695
11662
  const out = withStore((store) => {
@@ -11703,6 +11670,7 @@ function resumeRecord(id, execution) {
11703
11670
  return { ok: false, ...refusal("deliveryRunGoing", "the delivery still has a running agent; stop it before continuing") };
11704
11671
  }
11705
11672
  } else if (again) return { ok: false, ...again };
11673
+ if (row.status === "finished") return { ok: true, delivery: row };
11706
11674
  const at2 = Date.now();
11707
11675
  const resumed = {
11708
11676
  ...row,
@@ -13409,7 +13377,7 @@ function kindOf2(ext) {
13409
13377
  if (type.startsWith("image/")) return "image";
13410
13378
  return type.startsWith("video/") || type.startsWith("audio/") ? "video" : "asset";
13411
13379
  }
13412
- var STORYBOARD, STUDIO, ARRANGED, ASSET, isObject, TYPES;
13380
+ var STORYBOARD, STUDIO, ARRANGED, ASSET, isObject, bodySources, TYPES;
13413
13381
  var init_references = __esm({
13414
13382
  "../artifact-sdk/src/internal/references.ts"() {
13415
13383
  "use strict";
@@ -13418,6 +13386,7 @@ var init_references = __esm({
13418
13386
  ARRANGED = ["storyboard", "compare", "spritesheet", "studio"];
13419
13387
  ASSET = ["spritesheet", "asset"];
13420
13388
  isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
13389
+ bodySources = (body) => [...new Set(bodyReferences(body).map((r2) => r2.src))];
13421
13390
  TYPES = {
13422
13391
  ".png": "image/png",
13423
13392
  ".jpg": "image/jpeg",
@@ -13569,14 +13538,14 @@ function collectSources(sources2, card, host2) {
13569
13538
  const active2 = /* @__PURE__ */ new Set();
13570
13539
  const out = [];
13571
13540
  const visit = (src, types, owner, partial = false) => {
13572
- const path90 = src.replace(/[?#].*$/, "");
13541
+ const path91 = src.replace(/[?#].*$/, "");
13573
13542
  let resolved2;
13574
13543
  try {
13575
- resolved2 = host2.resolve(path90, owner);
13544
+ resolved2 = host2.resolve(path91, owner);
13576
13545
  } catch (error) {
13577
13546
  if (owner !== card) return { key: null, error: why(error) };
13578
13547
  if (!nodes.has(src)) {
13579
- const node2 = { key: src, file: null, kind: kindAt(path90, types), error: why(error), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
13548
+ const node2 = { key: src, file: null, kind: kindAt(path91, types), error: why(error), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
13580
13549
  nodes.set(src, node2);
13581
13550
  out.push(node2);
13582
13551
  }
@@ -14062,7 +14031,7 @@ function validateStoryboards(file2, id, text5) {
14062
14031
  function formatContractErrors(errors) {
14063
14032
  return ["Spec format validation failed. Fix these errors without changing the planned behavior:", ...errors.map((e2) => `${e2.file}:${e2.line} [${e2.rule}] ${e2.message}`)].join("\n");
14064
14033
  }
14065
- var ASSET_LINE, BLOCK_LINE, boardCheckErrors, boardProblems;
14034
+ var ASSET_LINE, BLOCK_LINE;
14066
14035
  var init_spec_contract = __esm({
14067
14036
  "../cli/src/lib/spec-contract.ts"() {
14068
14037
  "use strict";
@@ -14075,8 +14044,6 @@ var init_spec_contract = __esm({
14075
14044
  init_validate();
14076
14045
  ASSET_LINE = /^\s*<(?:Asset|Mockup)\b[^<>]*\/>\s*$/;
14077
14046
  BLOCK_LINE = /^\s*<(?:Asset\b|Mockup\b|Set\b|\/Set>)/;
14078
- boardCheckErrors = (errors) => ["Board check failed. Fix these errors without changing the planned behavior:", ...errors.map((e2) => `${e2.file}:${e2.line} [${e2.rule}] ${e2.message}`)].join("\n");
14079
- boardProblems = (errors) => ["Board problems:", ...errors.map((e2) => `- ${e2.message}`)].join("\n");
14080
14047
  }
14081
14048
  });
14082
14049
 
@@ -14171,14 +14138,6 @@ function reconcileBoard() {
14171
14138
  if (!fs44.existsSync(README)) return;
14172
14139
  for (const line of [...readmeComplaints(true), ...crossRefComplaints()]) warn2(line);
14173
14140
  }
14174
- function boardComplaints() {
14175
- if (!fs44.existsSync(README)) return [];
14176
- try {
14177
- return [...readmeComplaints(false), ...crossRefComplaints()];
14178
- } catch {
14179
- return [];
14180
- }
14181
- }
14182
14141
  var README_LINK;
14183
14142
  var init_reconcile = __esm({
14184
14143
  "../cli/src/lib/reconcile.ts"() {
@@ -15671,22 +15630,6 @@ function stampLeaving(cards, rejection) {
15671
15630
  if (stamped !== text5) fs54.writeFileSync(card.file, stamped);
15672
15631
  }
15673
15632
  }
15674
- function unfinishedDelivery(id) {
15675
- const card = findCard(id);
15676
- if (card?.deliversIn !== "plan") return null;
15677
- const gap = planDeliveryGap(card);
15678
- if (gap) {
15679
- const what = {
15680
- questions: "it still has open questions",
15681
- deliverable: "no finished deliverable is on the card",
15682
- command: "no ticked todo records where it was delivered or the command that rebuilds it",
15683
- todos: "not every todo is ticked"
15684
- }[gap];
15685
- return `#${id} is not finished: ${what}.`;
15686
- }
15687
- const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs54.existsSync(path56.join(ASSETS, src.slice(".assets/".length))));
15688
- return missing ? `#${id} is not finished: ${missing} is not on this machine.` : null;
15689
- }
15690
15633
  function agentDecisions(text5) {
15691
15634
  let section = null;
15692
15635
  const counts = { stood: 0, overruled: 0 };
@@ -15712,8 +15655,6 @@ function removeCard2(id, metric, options) {
15712
15655
  if (creating) die(creating, { kind: "card-being-created" });
15713
15656
  const found2 = locate(id);
15714
15657
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
15715
- const unfinished = metric === "completed" ? unfinishedDelivery(id) : null;
15716
- if (unfinished) die(unfinished, { kind: "plan-delivery-unfinished" });
15717
15658
  const dest = options.cleanupDiscarded && locateArchived(id) ? null : archiveDest(found2);
15718
15659
  const cardFile3 = found2.kind === "group" ? path56.join(found2.target, "root.md") : found2.target;
15719
15660
  const cardText = fs54.existsSync(cardFile3) ? fs54.readFileSync(cardFile3, "utf8") : "";
@@ -15899,7 +15840,6 @@ var init_remove = __esm({
15899
15840
  init_creation_lock();
15900
15841
  init_lock();
15901
15842
  init_rules();
15902
- init_read();
15903
15843
  init_cadence();
15904
15844
  init_paths();
15905
15845
  init_io();
@@ -16134,6 +16074,96 @@ var init_memory_file = __esm({
16134
16074
  }
16135
16075
  });
16136
16076
 
16077
+ // ../cli/src/commands/inspect.ts
16078
+ import fs57 from "node:fs";
16079
+ import os4 from "node:os";
16080
+ import path59 from "node:path";
16081
+ function cmdInspect(id) {
16082
+ const findings = [];
16083
+ const unavailable = [];
16084
+ function read3(source2, file3, empty) {
16085
+ try {
16086
+ return JSON.parse(fs57.readFileSync(file3, "utf8"));
16087
+ } catch (error) {
16088
+ if (error.code === "ENOENT") return empty;
16089
+ findings.push({ source: source2, message: String(error) });
16090
+ unavailable.push(source2);
16091
+ return empty;
16092
+ }
16093
+ }
16094
+ function fact(source2, get, empty) {
16095
+ try {
16096
+ return get();
16097
+ } catch (error) {
16098
+ findings.push({ source: source2, message: String(error) });
16099
+ unavailable.push(source2);
16100
+ return empty;
16101
+ }
16102
+ }
16103
+ const found2 = locate(id) ?? locateArchived(id);
16104
+ if (!found2) return die(`no task with id ${id}`, { kind: "card-not-found", id });
16105
+ const file2 = found2.kind === "group" ? path59.join(found2.target, "root.md") : found2.target;
16106
+ let card = null;
16107
+ try {
16108
+ const { meta, body } = parseFrontmatter(fs57.readFileSync(file2, "utf8"));
16109
+ if (!meta) throw Error("The card frontmatter could not be parsed.");
16110
+ card = { path: rel(file2), questions: meta.questions, todos: [...body.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+(.*)$/gm)].map((m) => ({ text: m[2], done: m[1] !== " " })) };
16111
+ } catch (error) {
16112
+ findings.push({ source: "card", message: String(error) });
16113
+ unavailable.push("card");
16114
+ }
16115
+ const progress = read3("previews", path59.join(BOARD_STATE, "previews", `${id}.json`), {});
16116
+ const store = read3("runs", SESSIONS, {});
16117
+ const runs = fact("runs", () => (store.runs ?? []).filter((run4) => run4.cardId === id).slice(-10).reverse().map((run4) => ({ id: run4.sessionId, status: run4.status, sessionRecorded: run4.harness ? !!(run4.resumeId || run4.continues?.resumeId) : null })), []);
16118
+ const records = [];
16119
+ const directory = path59.join(KANBAN, "deliveries");
16120
+ try {
16121
+ for (const name of fs57.readdirSync(directory).filter((name2) => name2.endsWith(".json"))) {
16122
+ const held5 = read3("delivery", path59.join(directory, name), null);
16123
+ if (held5?.cardId === id) records.push(held5);
16124
+ }
16125
+ } catch (error) {
16126
+ if (error.code !== "ENOENT") {
16127
+ findings.push({ source: "delivery", message: String(error) });
16128
+ unavailable.push("delivery");
16129
+ }
16130
+ }
16131
+ records.push(...fact("delivery", () => (store.deliveries ?? []).filter((held5) => held5.cardId === id), []));
16132
+ const held4 = [...new Map(records.map((held5) => [held5.deliveryId, held5])).values()].sort((a2, b2) => b2.startedAt - a2.startedAt)[0];
16133
+ const job = executionOf()?.job;
16134
+ const checkpoint = job ? read3("recovery", path59.join(process.env.WILDCRANE_HOME || os4.homedir() + "/.wildcrane", "checkpoints", `${encodeURIComponent(job)}.json`), null) : null;
16135
+ const delivery = fact("delivery", () => held4 ? { id: held4.deliveryId, status: held4.status, directory: held4.worktree ?? REPO_ROOT, completedSteps: (held4.completions ?? []).map((c2) => c2.step) } : null, null);
16136
+ const recovery = fact("recovery", () => checkpoint ? { pendingOperations: checkpoint.pending ?? [], submitted: checkpoint.submitted ?? null } : null, null);
16137
+ const result = {
16138
+ id,
16139
+ card,
16140
+ previews: fact("previews", () => Object.entries(progress).map(([agent, p2]) => ({
16141
+ agent,
16142
+ currentStageId: p2.currentStageId,
16143
+ stages: p2.stages.map(({ id: id2, status, version }) => ({ id: id2, status, version })),
16144
+ artifact: p2.displayedArtifact ? { stageId: p2.displayedArtifact.stageId, version: p2.displayedArtifact.version, section: `## By \`${agent}\` agent`, files: [.../* @__PURE__ */ new Set([...Object.keys(p2.displayedArtifact.assets).filter((key) => key !== "folder"), ...bodySources(p2.displayedArtifact.body)])].filter((file3) => !path59.isAbsolute(file3) && !/^[a-z][\w+.-]*:/i.test(file3)) } : null
16145
+ })), []),
16146
+ delivery,
16147
+ runs,
16148
+ recovery,
16149
+ findings,
16150
+ unavailable: [...new Set(unavailable)]
16151
+ };
16152
+ say(JSON.stringify(result, null, 2));
16153
+ return result;
16154
+ }
16155
+ var init_inspect = __esm({
16156
+ "../cli/src/commands/inspect.ts"() {
16157
+ "use strict";
16158
+ init_cards();
16159
+ init_frontmatter();
16160
+ init_io();
16161
+ init_paths();
16162
+ init_execution();
16163
+ init_references();
16164
+ }
16165
+ });
16166
+
16137
16167
  // ../cli/src/commands/validate.ts
16138
16168
  function cmdValidate(id) {
16139
16169
  const cards = [...snapshotSpecs()].filter(([, card]) => id === void 0 || card.id === id);
@@ -16201,11 +16231,11 @@ var init_ops = __esm({
16201
16231
  });
16202
16232
 
16203
16233
  // ../cli/src/lib/view/stamp.ts
16204
- import fs57 from "node:fs";
16205
- import path59 from "node:path";
16234
+ import fs58 from "node:fs";
16235
+ import path60 from "node:path";
16206
16236
  function boardStamp() {
16207
16237
  const parts = [];
16208
- for (const dir of [TODO, MEMORY, ASSETS, MOCKUPS, path59.join(KANBAN, ".mockups")]) walk(dir, parts, 0);
16238
+ for (const dir of [TODO, MEMORY, ASSETS, MOCKUPS, path60.join(KANBAN, ".mockups")]) walk(dir, parts, 0);
16209
16239
  for (const file2 of [MODULES_MD, ARCHIVE_MD, CONFIG]) {
16210
16240
  stamp3(file2, parts);
16211
16241
  }
@@ -16215,19 +16245,19 @@ function walk(dir, parts, depth3) {
16215
16245
  if (depth3 > MAX_DEPTH) return;
16216
16246
  let entries;
16217
16247
  try {
16218
- entries = fs57.readdirSync(dir, { withFileTypes: true });
16248
+ entries = fs58.readdirSync(dir, { withFileTypes: true });
16219
16249
  } catch {
16220
16250
  return;
16221
16251
  }
16222
16252
  for (const entry of entries.sort((a2, b2) => a2.name.localeCompare(b2.name))) {
16223
- const full = path59.join(dir, entry.name);
16253
+ const full = path60.join(dir, entry.name);
16224
16254
  if (entry.isDirectory()) walk(full, parts, depth3 + 1);
16225
16255
  else stamp3(full, parts);
16226
16256
  }
16227
16257
  }
16228
16258
  function stamp3(file2, parts) {
16229
16259
  try {
16230
- const s = fs57.statSync(file2);
16260
+ const s = fs58.statSync(file2);
16231
16261
  parts.push(`${file2}:${s.size}:${Math.round(s.mtimeMs)}`);
16232
16262
  } catch {
16233
16263
  }
@@ -16259,8 +16289,8 @@ var init_contract = __esm({
16259
16289
  });
16260
16290
 
16261
16291
  // ../cli/src/lib/board/revision.ts
16262
- import fs58 from "node:fs";
16263
- import path60 from "node:path";
16292
+ import fs59 from "node:fs";
16293
+ import path61 from "node:path";
16264
16294
  function revisionOf(text5) {
16265
16295
  let h3 = 2166136261;
16266
16296
  for (let i = 0; i < text5.length; i++) {
@@ -16272,13 +16302,13 @@ function revisionOf(text5) {
16272
16302
  function cardFile2(id) {
16273
16303
  const found2 = locate(id);
16274
16304
  if (!found2) return null;
16275
- return found2.kind === "group" ? path60.join(found2.target, "root.md") : found2.target;
16305
+ return found2.kind === "group" ? path61.join(found2.target, "root.md") : found2.target;
16276
16306
  }
16277
16307
  function cardRevision(id) {
16278
16308
  const file2 = cardFile2(id);
16279
16309
  if (!file2) return NO_REVISION;
16280
16310
  try {
16281
- return revisionOf(fs58.readFileSync(file2, "utf8"));
16311
+ return revisionOf(fs59.readFileSync(file2, "utf8"));
16282
16312
  } catch {
16283
16313
  return NO_REVISION;
16284
16314
  }
@@ -16330,7 +16360,7 @@ function localBoard() {
16330
16360
  }
16331
16361
  const provider = {
16332
16362
  kind: "local",
16333
- readCards: () => Promise.resolve(allCards2()),
16363
+ readCards: () => Promise.resolve(allCards()),
16334
16364
  // ---- the writer lease ---------------------------------------------------
16335
16365
  // Local grants every lease, an unknown card included: a single machine's board is
16336
16366
  // already serialized by the writing lock, so there is nothing here to fence off — and
@@ -16427,6 +16457,7 @@ var init_local2 = __esm({
16427
16457
  init_agent_file();
16428
16458
  init_studio_file2();
16429
16459
  init_memory_file();
16460
+ init_inspect();
16430
16461
  init_validate2();
16431
16462
  init_io();
16432
16463
  init_lock();
@@ -16435,6 +16466,7 @@ var init_local2 = __esm({
16435
16466
  init_revision();
16436
16467
  as = (opts) => opts;
16437
16468
  MOVES = {
16469
+ inspect: ({ args: args2 }) => cmdInspect(Number(args2[0])),
16438
16470
  validate: ({ args: args2 }) => cmdValidate(args2[0] === void 0 ? void 0 : Number(args2[0])),
16439
16471
  init: () => cmdInit(),
16440
16472
  create: ({ opts }) => cmdCreate(as(opts)),
@@ -16448,7 +16480,7 @@ var init_local2 = __esm({
16448
16480
  "memory-file": ({ args: args2 }) => cmdMemoryFile(args2[0] ?? "")
16449
16481
  };
16450
16482
  BOARD_MOVES = new Set(Object.keys(MOVES));
16451
- READ_ONLY_MOVES = /* @__PURE__ */ new Set(["list", "validate", "file", "agent-file", "memory-file"]);
16483
+ READ_ONLY_MOVES = /* @__PURE__ */ new Set(["inspect", "list", "validate", "file", "agent-file", "memory-file"]);
16452
16484
  leases = /* @__PURE__ */ new Map();
16453
16485
  leaseCounter = 0;
16454
16486
  }
@@ -16479,14 +16511,14 @@ var init_board = __esm({
16479
16511
  });
16480
16512
 
16481
16513
  // ../cli/src/lib/plans.ts
16482
- import fs59 from "node:fs";
16483
- import path61 from "node:path";
16514
+ import fs60 from "node:fs";
16515
+ import path62 from "node:path";
16484
16516
  function planFile(rel2) {
16485
16517
  if (!/^plans\/(archive\/)?[^/\\]+\.md$/.test(rel2)) return null;
16486
16518
  const dir = isArchivedPlan(rel2) ? PLANS_ARCHIVE : PLANS;
16487
16519
  const name = rel2.replace(/^plans\/(archive\/)?/, "");
16488
16520
  if (!name || name.includes("/") || !name.endsWith(".md")) return null;
16489
- return path61.join(dir, name);
16521
+ return path62.join(dir, name);
16490
16522
  }
16491
16523
  function readPlan(rel2) {
16492
16524
  const file2 = planFile(rel2);
@@ -16494,12 +16526,12 @@ function readPlan(rel2) {
16494
16526
  let text5 = "";
16495
16527
  let found2 = rel2;
16496
16528
  try {
16497
- text5 = fs59.readFileSync(file2, "utf8");
16529
+ text5 = fs60.readFileSync(file2, "utf8");
16498
16530
  } catch {
16499
16531
  const moved = renamedPlan(rel2);
16500
16532
  if (moved) {
16501
16533
  found2 = moved;
16502
- text5 = fs59.readFileSync(planFile(moved), "utf8");
16534
+ text5 = fs60.readFileSync(planFile(moved), "utf8");
16503
16535
  }
16504
16536
  }
16505
16537
  return { path: found2, text: text5, lines: text5.trim() ? text5.trimEnd().split("\n").length : 0 };
@@ -16514,13 +16546,13 @@ function renamedPlan(rel2) {
16514
16546
  ]) {
16515
16547
  let names3;
16516
16548
  try {
16517
- names3 = fs59.readdirSync(dir);
16549
+ names3 = fs60.readdirSync(dir);
16518
16550
  } catch {
16519
16551
  continue;
16520
16552
  }
16521
16553
  for (const n of names3) {
16522
16554
  if (!n.startsWith(`${id}-`) || !n.endsWith(".md")) continue;
16523
- found2.push({ rel: `${prefix}${n}`, at: fs59.statSync(path61.join(dir, n)).mtimeMs });
16555
+ found2.push({ rel: `${prefix}${n}`, at: fs60.statSync(path62.join(dir, n)).mtimeMs });
16524
16556
  }
16525
16557
  }
16526
16558
  if (!found2.length) return null;
@@ -16529,7 +16561,7 @@ function renamedPlan(rel2) {
16529
16561
  function planFromText(text5) {
16530
16562
  const legacy2 = `${legacyProjectStateDir(KANBAN)}/`;
16531
16563
  if (text5.startsWith(legacy2)) text5 = text5.slice(legacy2.length);
16532
- const local = `${path61.dirname(PLANS)}/`;
16564
+ const local = `${path62.dirname(PLANS)}/`;
16533
16565
  if (text5.startsWith(local)) text5 = text5.slice(local.length);
16534
16566
  if (text5.startsWith(`${KANBAN}/`)) text5 = text5.slice(KANBAN.length + 1);
16535
16567
  const here = `${boardPath()}/`;
@@ -16588,36 +16620,58 @@ var init_roster = __esm({
16588
16620
  }
16589
16621
  });
16590
16622
 
16623
+ // ../cli/src/lib/agent/own-cost.ts
16624
+ function ownCost(total, before) {
16625
+ if (total === void 0 || before === null) return void 0;
16626
+ if (before === void 0 || total < before) return total;
16627
+ return total >= before ? total - before : void 0;
16628
+ }
16629
+ function lastSessionTotal(id, runs) {
16630
+ let best;
16631
+ const take = (at2, usd) => {
16632
+ if (typeof usd === "number" && usd >= 0 && (!best || at2 >= best.at)) best = { at: at2, usd };
16633
+ };
16634
+ for (const r2 of runs) if (r2.resumeId === id || r2.sessionId === id) take(r2.endedAt ?? r2.startedAt, r2.sessionCostUsd);
16635
+ return best?.usd ?? null;
16636
+ }
16637
+ var reportsSessionTotal;
16638
+ var init_own_cost = __esm({
16639
+ "../cli/src/lib/agent/own-cost.ts"() {
16640
+ "use strict";
16641
+ reportsSessionTotal = (harness) => harness === "claude-code";
16642
+ }
16643
+ });
16644
+
16591
16645
  // ../cli/src/lib/agent/pictures.ts
16592
- import fs60 from "node:fs";
16593
- import path62 from "node:path";
16646
+ import fs61 from "node:fs";
16647
+ import path63 from "node:path";
16594
16648
  function claimRunPictures(box2, sessionId, names3 = []) {
16595
16649
  if (!box2 || !freeBox(box2) || names3.length === 0) return [];
16596
16650
  const from = pictureBox(box2);
16597
16651
  const to = pictureBox(sessionId);
16598
16652
  try {
16599
- fs60.mkdirSync(SESSIONS_DIR, { recursive: true });
16600
- fs60.renameSync(from, to);
16653
+ fs61.mkdirSync(SESSIONS_DIR, { recursive: true });
16654
+ fs61.renameSync(from, to);
16601
16655
  } catch {
16602
16656
  return [];
16603
16657
  }
16604
- return names3.filter(pictureName).map((name) => path62.join(to, name)).filter((file2) => fs60.existsSync(file2));
16658
+ return names3.filter(pictureName).map((name) => path63.join(to, name)).filter((file2) => fs61.existsSync(file2));
16605
16659
  }
16606
16660
  function returnRunPictures(sessionId, box2) {
16607
16661
  if (!box2 || !boxId(box2)) return;
16608
16662
  try {
16609
- fs60.renameSync(pictureBox(sessionId), pictureBox(box2));
16663
+ fs61.renameSync(pictureBox(sessionId), pictureBox(box2));
16610
16664
  } catch {
16611
16665
  }
16612
16666
  }
16613
16667
  function moveRunPictures(from, to, files = []) {
16614
16668
  if (files.length === 0) return [];
16615
16669
  try {
16616
- fs60.renameSync(pictureBox(from), pictureBox(to));
16670
+ fs61.renameSync(pictureBox(from), pictureBox(to));
16617
16671
  } catch {
16618
16672
  return files;
16619
16673
  }
16620
- return files.map((file2) => path62.join(pictureBox(to), path62.basename(file2)));
16674
+ return files.map((file2) => path63.join(pictureBox(to), path63.basename(file2)));
16621
16675
  }
16622
16676
  var pictureName, boxId, freeBox, pictureBox;
16623
16677
  var init_pictures = __esm({
@@ -16626,8 +16680,8 @@ var init_pictures = __esm({
16626
16680
  init_paths();
16627
16681
  pictureName = (name) => /^[0-9a-f-]{36}\.[a-z0-9]{2,5}$/.test(name);
16628
16682
  boxId = (box2) => /^[0-9a-f-]{36}$/.test(box2);
16629
- freeBox = (box2) => boxId(box2) && !fs60.existsSync(path62.join(SESSIONS_DIR, `${box2}.log`));
16630
- pictureBox = (box2) => path62.join(SESSIONS_DIR, `${box2}.images`);
16683
+ freeBox = (box2) => boxId(box2) && !fs61.existsSync(path63.join(SESSIONS_DIR, `${box2}.log`));
16684
+ pictureBox = (box2) => path63.join(SESSIONS_DIR, `${box2}.images`);
16631
16685
  }
16632
16686
  });
16633
16687
 
@@ -16747,16 +16801,16 @@ var init_facts = __esm({
16747
16801
  });
16748
16802
 
16749
16803
  // ../cli/src/lib/view/archive.ts
16750
- import fs61 from "node:fs";
16751
- import path63 from "node:path";
16804
+ import fs62 from "node:fs";
16805
+ import path64 from "node:path";
16752
16806
  function archivedId(file2) {
16753
- const own = idPrefix(path63.basename(file2));
16754
- return own !== null ? own : idPrefix(path63.basename(path63.dirname(file2)));
16807
+ const own = idPrefix(path64.basename(file2));
16808
+ return own !== null ? own : idPrefix(path64.basename(path64.dirname(file2)));
16755
16809
  }
16756
16810
  function readFile(file2) {
16757
16811
  const id = archivedId(file2);
16758
16812
  if (id === null) return null;
16759
- const { meta, body } = parseFrontmatter(fs61.readFileSync(file2, "utf8"));
16813
+ const { meta, body } = parseFrontmatter(fs62.readFileSync(file2, "utf8"));
16760
16814
  if (!meta) return null;
16761
16815
  return {
16762
16816
  row: {
@@ -16764,15 +16818,15 @@ function readFile(file2) {
16764
16818
  title: meta.title,
16765
16819
  archived: meta.archived,
16766
16820
  rejected: meta.rejected,
16767
- relPath: rel(file2).split(path63.sep).join("/")
16821
+ relPath: rel(file2).split(path64.sep).join("/")
16768
16822
  },
16769
16823
  body: body.replace(/^\n+/, "").replace(/\s+$/, ""),
16770
16824
  meta
16771
16825
  };
16772
16826
  }
16773
16827
  function readArchive() {
16774
- const relPath = rel(ARCHIVE).split(path63.sep).join("/");
16775
- if (!fs61.existsSync(ARCHIVE)) return { relPath, cards: [] };
16828
+ const relPath = rel(ARCHIVE).split(path64.sep).join("/");
16829
+ if (!fs62.existsSync(ARCHIVE)) return { relPath, cards: [] };
16776
16830
  const cards = walkMd(ARCHIVE).map(readFile).filter((found2) => found2 !== null).map((found2) => found2.row);
16777
16831
  cards.sort((a2, b2) => b2.id - a2.id);
16778
16832
  return { relPath, cards };
@@ -16787,7 +16841,7 @@ var init_archive = __esm({
16787
16841
  });
16788
16842
 
16789
16843
  // ../cli/src/lib/agent/prompts.ts
16790
- import path64 from "node:path";
16844
+ import path65 from "node:path";
16791
16845
  function stopReason(deliveryId) {
16792
16846
  const delivery = findDelivery(deliveryId);
16793
16847
  if (!delivery) return void 0;
@@ -16818,13 +16872,6 @@ ${approved}`;
16818
16872
  }
16819
16873
  return `Follow \`akb guide implement\`: create no card and build exactly this approved requirement and nothing more \u2014 "${approved}".`;
16820
16874
  }
16821
- function contractRepairPrompt(req, errors) {
16822
- return boardText([
16823
- "The task left the board broken. Fix only the errors below. Preserve planned behavior and completed work; do not repeat the task or request other agents.",
16824
- errors,
16825
- ruleBlock(req, frozenRules(req))
16826
- ].filter(Boolean).join("\n\n"));
16827
- }
16828
16875
  function restartPrompt(req, deliveryId) {
16829
16876
  if (req.id === void 0 && !req.deliveryId && !deliveryId) return void 0;
16830
16877
  if (deliveryId && req.action === "implement") return [RESTART_LEAD, `Continue delivery ${deliveryId}. ${deliveryRequirements(deliveryId, req.id ?? null)}`.trim()].join("\n\n");
@@ -16848,7 +16895,7 @@ ${text5}` : "";
16848
16895
  }
16849
16896
  function cardFileOf(id) {
16850
16897
  const found2 = id === void 0 ? null : locate(id);
16851
- return found2 ? found2.kind === "group" ? path64.join(found2.target, "root.md") : found2.target : "";
16898
+ return found2 ? found2.kind === "group" ? path65.join(found2.target, "root.md") : found2.target : "";
16852
16899
  }
16853
16900
  function realPaths(text5, req) {
16854
16901
  if (req.action !== "scheduled" && req.action !== "sub") return text5;
@@ -16946,7 +16993,7 @@ function frozenRules(req) {
16946
16993
  function archivedCardFile(id) {
16947
16994
  const found2 = locateArchived(id);
16948
16995
  if (!found2) return `${rel(ARCHIVE)}/`;
16949
- return rel(found2.kind === "group" ? path64.join(found2.target, "root.md") : found2.target);
16996
+ return rel(found2.kind === "group" ? path65.join(found2.target, "root.md") : found2.target);
16950
16997
  }
16951
16998
  function shippedLines(cardId2) {
16952
16999
  const delivery = endedDelivery(`${cardId2}`);
@@ -16980,7 +17027,12 @@ function roster(req) {
16980
17027
  }
16981
17028
  function buildRun(req) {
16982
17029
  const notes = [...migrateFlowRules(), ...req.specAgent ? foldedSettingsNotes(req.specAgent) : []];
16983
- return { prompt: buildPrompt(req, notes), notes };
17030
+ let prompt = buildPrompt(req, notes);
17031
+ if (req.action === "spec" && req.id !== void 0 && req.specAgent) {
17032
+ const stage = realPaths(boardText(previewStagePrompt(req.id, req.specAgent, boardCommand())), req);
17033
+ if (stage) prompt = prompt.replace(stage, "");
17034
+ }
17035
+ return { prompt, notes };
16984
17036
  }
16985
17037
  function answeredNote(cardId2, command) {
16986
17038
  const delivery = cardId2 === void 0 ? void 0 : activeDelivery(cardId2);
@@ -17030,7 +17082,7 @@ function actionPrompt(req, command, notes) {
17030
17082
  ].filter(Boolean).join(" ");
17031
17083
  case "clarify": {
17032
17084
  return [
17033
- `Plan task ${req.id} ${named2} in this one session following \`akb guide refine\`. Work the board only through \`akb\`; a command with \`--print\` prints its flow for you to follow here, and without it starts a separate agent.`,
17085
+ `Plan task ${req.id} ${named2} following \`akb guide refine\`. Work the board only through \`akb\`; a command with \`--print\` prints its flow for you to follow here, and without it starts a separate session.`,
17034
17086
  carriedNote(req),
17035
17087
  // A refine has no note box of its own, but one SCHEDULED on a blocked card
17036
17088
  // carries whatever was typed when it was scheduled — often the very reason the user
@@ -17089,7 +17141,7 @@ function actionPrompt(req, command, notes) {
17089
17141
  case "spec": {
17090
17142
  const agent = findSpecAgent(req.specAgent ?? "");
17091
17143
  const found2 = req.id === void 0 ? null : locate(req.id);
17092
- const cardFile3 = found2 ? rel(found2.kind === "group" ? path64.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
17144
+ const cardFile3 = found2 ? rel(found2.kind === "group" ? path65.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
17093
17145
  const own = agent ? specAgentInstructions(agent) : null;
17094
17146
  if (own) notes.push(...own.notes);
17095
17147
  const memory = agent ? agentMemoryBlock(agent) : "";
@@ -17235,8 +17287,7 @@ var init_prompts = __esm({
17235
17287
  init_store();
17236
17288
  init_types3();
17237
17289
  RESUME_PROMPT = [
17238
- `Continue. The previous run ended before it finished the task.`,
17239
- `Pick up where you left off and carry it through.`
17290
+ `Continue work.`
17240
17291
  ].join(" ");
17241
17292
  DELIVERY_RESUME = `Continue delivery %s. %r`;
17242
17293
  DELIVERY_RESUME_CARD = `Build the card as the delivery holds it, not as the file reads now: \`%c\` prints the approved copy.`;
@@ -17251,8 +17302,7 @@ var init_prompts = __esm({
17251
17302
  "scheduled"
17252
17303
  ]);
17253
17304
  RESTART_LEAD = [
17254
- `The session you were continuing is gone, and this one holds nothing of it.`,
17255
- `Do the task below from the top, checking each step's precondition before you do it \u2014 work an earlier run already finished is done, so don't repeat it.`
17305
+ `Continue work.`
17256
17306
  ].join(" ");
17257
17307
  restartable = (run4) => (run4.cardId !== null || !!run4.deliveryId) && RESTARTABLE.has(run4.action);
17258
17308
  NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
@@ -17267,16 +17317,16 @@ var init_prompts = __esm({
17267
17317
 
17268
17318
  // ../cli/src/lib/agent/stop.ts
17269
17319
  import { spawnSync as spawnSync5 } from "node:child_process";
17270
- import fs62 from "node:fs";
17320
+ import fs63 from "node:fs";
17271
17321
  function markedInProc(entry, strict = false, since) {
17272
17322
  const pids = [];
17273
- for (const name of fs62.readdirSync("/proc")) {
17323
+ for (const name of fs63.readdirSync("/proc")) {
17274
17324
  if (!/^\d+$/.test(name)) continue;
17275
17325
  try {
17276
- if (fs62.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
17326
+ if (fs63.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
17277
17327
  } catch (error) {
17278
17328
  if (strict && !["ENOENT", "ESRCH"].includes(error.code ?? "")) {
17279
- const stat = fs62.statSync(`/proc/${name}`, { throwIfNoEntry: false });
17329
+ const stat = fs63.statSync(`/proc/${name}`, { throwIfNoEntry: false });
17280
17330
  if (stat?.uid === process.getuid?.() && !startedBefore(Number(name), since)) throw error;
17281
17331
  }
17282
17332
  }
@@ -17501,8 +17551,8 @@ __export(sessions_exports, {
17501
17551
  withRuns: () => withRuns
17502
17552
  });
17503
17553
  import { randomUUID as randomUUID4 } from "node:crypto";
17504
- import fs63 from "node:fs";
17505
- import path65 from "node:path";
17554
+ import fs64 from "node:fs";
17555
+ import path66 from "node:path";
17506
17556
  function reap(runs, reaped = [], restore = []) {
17507
17557
  let changed = false;
17508
17558
  const now = Date.now();
@@ -17522,7 +17572,7 @@ function reap(runs, reaped = [], restore = []) {
17522
17572
  }
17523
17573
  function stampDuration(run4, endedAt) {
17524
17574
  try {
17525
- fs63.appendFileSync(run4.logPath, durationLine(endedAt - run4.startedAt));
17575
+ fs64.appendFileSync(run4.logPath, durationLine(endedAt - run4.startedAt));
17526
17576
  } catch {
17527
17577
  }
17528
17578
  }
@@ -17536,7 +17586,7 @@ function cardNow(cardId2) {
17536
17586
  try {
17537
17587
  const file2 = cardFile2(cardId2);
17538
17588
  if (!file2) return null;
17539
- const { meta } = parseFrontmatter(fs63.readFileSync(file2, "utf8"));
17589
+ const { meta } = parseFrontmatter(fs64.readFileSync(file2, "utf8"));
17540
17590
  if (!meta) return null;
17541
17591
  return { status: meta.status || "todo", questions: meta.questions.length, title: meta.title };
17542
17592
  } catch {
@@ -17607,7 +17657,7 @@ function resumeSessionId(run4) {
17607
17657
  return resumesUnder(run4.harness) && !neverStarted(run4) ? resumeIdOf(run4) : void 0;
17608
17658
  }
17609
17659
  function endedDeliveryRefusal(r2, refusals) {
17610
- if (!r2.deliveryId || !canPickUp(r2)) return void 0;
17660
+ if (!r2.deliveryId) return void 0;
17611
17661
  if (refusals?.has(r2.deliveryId)) return refusals.get(r2.deliveryId);
17612
17662
  const delivery = findDelivery(r2.deliveryId);
17613
17663
  const ended = delivery && delivery.status !== "active" && (delivery.status !== "failed" || delivery.worktree);
@@ -17617,8 +17667,7 @@ function endedDeliveryRefusal(r2, refusals) {
17617
17667
  return why2;
17618
17668
  }
17619
17669
  function retryAsk(r2) {
17620
- if (r2.resumedFrom || isRetired(r2.action)) return void 0;
17621
- if (r2.formatRepair && !neverStarted(r2)) return void 0;
17670
+ if (isRetired(r2.action)) return void 0;
17622
17671
  const id = r2.cardId ?? void 0;
17623
17672
  const base = {
17624
17673
  action: r2.action,
@@ -17647,7 +17696,7 @@ function retryAsk(r2) {
17647
17696
  }
17648
17697
  }
17649
17698
  function toView(r2, gone, refusals) {
17650
- const cardOffBoard = r2.cardId !== null && !!gone?.has(r2.cardId);
17699
+ const cardOffBoard = r2.status !== "done" && r2.cardId !== null && !!gone?.has(r2.cardId);
17651
17700
  const open3 = r2.action !== "sub" && canPickUp(r2) && !endedDeliveryRefusal(r2, refusals);
17652
17701
  const session = !lacksSession(r2);
17653
17702
  return {
@@ -17669,9 +17718,9 @@ function leftBoardOnLanding(id) {
17669
17718
  function archivedRejected(id) {
17670
17719
  const filed = locateArchived(id);
17671
17720
  if (!filed) return null;
17672
- const file2 = filed.kind === "group" ? path65.join(filed.target, "root.md") : filed.target;
17721
+ const file2 = filed.kind === "group" ? path66.join(filed.target, "root.md") : filed.target;
17673
17722
  try {
17674
- return !!parseFrontmatter(fs63.readFileSync(file2, "utf8")).meta?.rejected;
17723
+ return !!parseFrontmatter(fs64.readFileSync(file2, "utf8")).meta?.rejected;
17675
17724
  } catch {
17676
17725
  return false;
17677
17726
  }
@@ -17921,7 +17970,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID4(), said2) {
17921
17970
  return { run: record, spec };
17922
17971
  }
17923
17972
  function planningSession(cardId2, cwd = REPO_ROOT) {
17924
- const here = (dir) => !dir || path65.resolve(dir) === cwd;
17973
+ const here = (dir) => !dir || path66.resolve(dir) === cwd;
17925
17974
  const planned = readRuns().filter((r2) => r2.status === "done" && r2.cardId === cardId2 && PLANNING.has(r2.action)).sort((a2, b2) => b2.startedAt - a2.startedAt)[0];
17926
17975
  if (!planned) return { none: "unrecorded" };
17927
17976
  if (!here(planned.cwd)) return { none: "elsewhere" };
@@ -17974,6 +18023,7 @@ function requestOf(record) {
17974
18023
  // the CLI actually spawned takes it.
17975
18024
  runtime: record.runtime,
17976
18025
  specAgent: record.specAgent,
18026
+ notes: record.input,
17977
18027
  ...record.action === "scheduled" ? { studio: record.studio } : {},
17978
18028
  triage: record.triage,
17979
18029
  cards: record.cards,
@@ -17983,8 +18033,8 @@ function requestOf(record) {
17983
18033
  };
17984
18034
  }
17985
18035
  async function openResume(id, options) {
17986
- const build = typeof options === "object" ? options : void 0;
17987
- const requireSession = options === true || !!build;
18036
+ const build = typeof options === "object" && options.deliveryId ? { deliveryId: options.deliveryId, notes: options.notes } : void 0;
18037
+ const forced = typeof options === "object" && options.fresh;
17988
18038
  const restore = [];
17989
18039
  const runs = withRuns((all2) => {
17990
18040
  reap(all2, [], restore);
@@ -18002,14 +18052,6 @@ async function openResume(id, options) {
18002
18052
  if (build && (prev.action !== "implement" || prev.deliveryId !== build.deliveryId || delivery?.status !== "active")) {
18003
18053
  return refusal("deliveryTakenOver", "\u539F\u6784\u5EFA\u4E0D\u5C5E\u4E8E\u5F53\u524D\u5F85\u7EED\u8DD1\u7684\u4EA4\u4ED8\uFF0C\u4E0D\u4F1A\u542F\u52A8\u65B0\u4F1A\u8BDD\u3002", { id: build.deliveryId });
18004
18054
  }
18005
- const completedBuild = prev.status === "done" && prev.action === "implement" && delivery?.status === "active" && prev.deliveryId === delivery.deliveryId;
18006
- if (!canPickUp(prev) && !completedBuild) return refusal("runNotResumable", "only a failed, interrupted or stopped run can be continued");
18007
- const retrying = lacksSession(prev);
18008
- if (requireSession && (!resumeSessionId(prev) || !resumesUnder(prev.harness))) {
18009
- return refusal("runNoSession", "\u539F\u6784\u5EFA\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4F1A\u8BDD\u6807\u8BC6\uFF0C\u6216\u539F Agent \u4E0D\u652F\u6301\u7EED\u8DD1\uFF1B\u672C\u6B21\u672A\u542F\u52A8\u65B0\u4F1A\u8BDD\u3002");
18010
- }
18011
- const ask2 = retrying && prev.status !== "stopped" ? retryAsk(prev) : void 0;
18012
- if (retrying && !ask2) return refusal("runNoSession", "that run never reported a session id to continue by");
18013
18055
  const ended = endedDeliveryRefusal(prev);
18014
18056
  if (ended) return ended;
18015
18057
  const resuming = prev.deliveryId ? findDelivery(prev.deliveryId) : void 0;
@@ -18017,24 +18059,17 @@ async function openResume(id, options) {
18017
18059
  const sessionId = randomUUID4();
18018
18060
  let plan;
18019
18061
  let fresh;
18020
- if (ask2) {
18021
- if (prev.cardId !== null && goneCards([prev]).has(prev.cardId)) {
18022
- return { error: `#${prev.cardId} has left the board, so there is nothing to try again` };
18023
- }
18062
+ const session = forced ? void 0 : resumeSessionId(prev);
18063
+ if (session) {
18064
+ plan = planResume({ harness: prev.harness, resumeId: session, cwd }, prev.agent, prev.runtime ? { pin: prev.runtime } : {});
18065
+ } else {
18066
+ const ask2 = retryAsk(prev) ?? requestOf(prev);
18024
18067
  const started = await planRetry(prev, ask2, sessionId, cwd);
18025
18068
  if ("error" in started) return started;
18026
18069
  ({ plan, fresh } = started);
18027
- } else if (resumesUnder(prev.harness)) {
18028
- plan = planResume(
18029
- { harness: prev.harness, resumeId: resumeIdOf(prev), cwd },
18030
- prev.agent,
18031
- prev.runtime ? { pin: prev.runtime } : {}
18032
- );
18033
- } else {
18034
- const prompt = restartPrompt({ ...requestOf(prev), runtime: void 0 }, prev.deliveryId);
18035
- const started = prompt ? planRun(sessionId, cwd, prev.agent) : null;
18036
- plan = started;
18037
- if (started && prompt) fresh = { prompt, notes: started.note ? [started.note] : [] };
18070
+ const restart = prev.action === "spec" ? void 0 : restartPrompt({ ...requestOf(prev), runtime: plan.runtime }, prev.deliveryId);
18071
+ fresh.prompt = restart ?? ["Continue work.", fresh.prompt].join("\n\n");
18072
+ if (!lacksSession(prev) && !forced) fresh.retry = false;
18038
18073
  }
18039
18074
  if (!plan) {
18040
18075
  const agent = prev.harness || "the agent that started it";
@@ -18043,7 +18078,6 @@ async function openResume(id, options) {
18043
18078
  const buildResume = prev.action === "implement" && prev.deliveryId ? resumePrompt(prev.deliveryId, prev.action) : void 0;
18044
18079
  const opened = await resumeHeld(prev, plan, sessionId, resuming, fresh);
18045
18080
  if ("error" in opened) return opened;
18046
- if (build) opened.spec.notes = [...opened.spec.notes ?? [], "\u7EE7\u7EED\u539F\u6784\u5EFA\u4F1A\u8BDD\uFF1B\u82E5\u539F\u4F1A\u8BDD\u4E0D\u53EF\u7528\uFF0C\u672C\u6B21\u4E0D\u4F1A\u65B0\u5EFA\u4F1A\u8BDD\u3002"];
18047
18081
  if (!opened.spec.prompt && buildResume) opened.spec.prompt = buildResume;
18048
18082
  if (build?.notes?.trim()) opened.spec.prompt = [opened.spec.prompt || resumePrompt(prev.deliveryId, prev.action), build.notes.trim()].join("\n\n");
18049
18083
  if (build || buildResume) writeSpec(opened.spec);
@@ -18070,10 +18104,9 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
18070
18104
  action: prev.action,
18071
18105
  status: "running",
18072
18106
  startedAt: Date.now(),
18073
- // No `input` on a resume: the note the user typed is already in the conversation being
18074
- // resumed — repeating it would read as a second instruction they never gave. A retry is
18075
- // the ask itself again, so it keeps everything the ask was written down with.
18076
- ...retry2 ? { input: prev.input, studio: prev.studio } : {},
18107
+ // Keep the original ask available if a later resume loses its session.
18108
+ input: prev.input,
18109
+ studio: prev.studio,
18077
18110
  harness: plan.harness,
18078
18111
  runtime: plan.runtime,
18079
18112
  agent: plan.agent,
@@ -18086,8 +18119,7 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
18086
18119
  resumeId: plan.resumeId ?? void 0,
18087
18120
  resumedFrom: prev.sessionId,
18088
18121
  // Taken now: the run being continued is dropped once this one starts (#1483).
18089
- sessionCostFrom: prev.sessionCostUsd ?? prev.sessionCostFrom,
18090
- formatRepair: prev.formatRepair ? { ...prev.formatRepair, attempt: prev.formatRepair.attempt + 1 } : void 0,
18122
+ sessionCostFrom: reportsSessionTotal(prev.harness) ? prev.sessionCostUsd ?? prev.sessionCostFrom : void 0,
18091
18123
  // The retry chain carries on rather than starting over (#525): this run IS the attempt
18092
18124
  // the failed one scheduled, so its count and its window come with it.
18093
18125
  retry: prev.retry
@@ -18109,22 +18141,12 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
18109
18141
  return refusal("discardUnfinished", "A card discard did not finish. Retry discarding it before resuming creation.");
18110
18142
  }
18111
18143
  record.discardedCards = latest.discardedCards;
18112
- const discarded = new Set(record.discardedCards?.map((c2) => c2.id) ?? []);
18113
- if (record.formatRepair && discarded.size) {
18114
- const repair = record.formatRepair;
18115
- repair.cardIds = repair.cardIds.filter((id) => !discarded.has(id));
18116
- repair.changedIds = repair.changedIds.filter((id) => !discarded.has(id));
18117
- repair.existingIds = repair.existingIds.filter((id) => !discarded.has(id));
18118
- repair.errors = repair.errors.split("\n").filter((line) => !record.discardedCards.some((c2) => line.includes(c2.path) || new RegExp(`Task #${c2.id}(?![0-9])`).test(line))).join("\n");
18119
- if (!repair.cardIds.length) record.formatRepair = void 0;
18120
- }
18121
18144
  const heldCreation = all2.find((r2) => runIsLive(r2) && (r2.cardId !== null && (latest.createdCardIds ?? []).includes(r2.cardId) || (r2.createdCardIds ?? []).some((id) => (latest.createdCardIds ?? []).includes(id))));
18122
18145
  if (heldCreation) return refusal("creationHeld", "A card from this creation is already being worked on. Wait for that run to finish.");
18123
18146
  const locked = lockedBy(all2, prev.action, prev.cardId, prev.discard);
18124
18147
  if (locked) return locked;
18125
18148
  all2.push(record);
18126
18149
  const delivery = store.deliveries.find((d2) => d2.deliveryId === prev.deliveryId && d2.status === "active");
18127
- if (!delivery && record.formatRepair) record.deliveryId = prev.deliveryId;
18128
18150
  if (delivery) {
18129
18151
  delivery.sessions.push(record.sessionId);
18130
18152
  delivery.steps.push({ step: "resume", at: record.startedAt });
@@ -18140,11 +18162,6 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
18140
18162
  const inherited = readAsks(prev.sessionId);
18141
18163
  if (inherited.asks.length || inherited.refines.length) writeAsks(sessionId, inherited);
18142
18164
  clearAsks(prev.sessionId);
18143
- try {
18144
- fs63.unlinkSync(prev.logPath);
18145
- fs63.rmSync(eventsPathOf(prev.sessionId), { force: true });
18146
- } catch {
18147
- }
18148
18165
  if (retry2 && prev.pictures?.length) {
18149
18166
  record.pictures = moveRunPictures(prev.sessionId, sessionId, prev.pictures);
18150
18167
  patch(sessionId, (r2) => {
@@ -18165,8 +18182,8 @@ function forgetRun(sessionId) {
18165
18182
  if (!gone) return;
18166
18183
  clearAsks(sessionId);
18167
18184
  try {
18168
- fs63.unlinkSync(gone.logPath);
18169
- fs63.rmSync(eventsPathOf(gone.sessionId), { force: true });
18185
+ fs64.unlinkSync(gone.logPath);
18186
+ fs64.rmSync(eventsPathOf(gone.sessionId), { force: true });
18170
18187
  } catch {
18171
18188
  }
18172
18189
  }
@@ -18195,14 +18212,14 @@ function noteSpecRefusals(sessionId, refused) {
18195
18212
  }
18196
18213
  function clearAsks(sessionId) {
18197
18214
  try {
18198
- fs63.unlinkSync(asksPathOf(sessionId));
18215
+ fs64.unlinkSync(asksPathOf(sessionId));
18199
18216
  } catch {
18200
18217
  }
18201
18218
  }
18202
18219
  function readAsks(sessionId) {
18203
18220
  let data;
18204
18221
  try {
18205
- data = JSON.parse(fs63.readFileSync(asksPathOf(sessionId), "utf8"));
18222
+ data = JSON.parse(fs64.readFileSync(asksPathOf(sessionId), "utf8"));
18206
18223
  } catch {
18207
18224
  return { asks: [], refines: [], refused: [] };
18208
18225
  }
@@ -18229,10 +18246,10 @@ function readAsks(sessionId) {
18229
18246
  return { asks: asks.filter((a2) => !discarded.has(a2.cardId)), refines: refines.filter((a2) => !discarded.has(a2.cardId)), refused };
18230
18247
  }
18231
18248
  function writeAsks(sessionId, file2) {
18232
- fs63.mkdirSync(SESSIONS_DIR, { recursive: true });
18249
+ fs64.mkdirSync(SESSIONS_DIR, { recursive: true });
18233
18250
  const tmp = `${asksPathOf(sessionId)}.tmp`;
18234
- fs63.writeFileSync(tmp, JSON.stringify(file2, null, 2) + "\n");
18235
- fs63.renameSync(tmp, asksPathOf(sessionId));
18251
+ fs64.writeFileSync(tmp, JSON.stringify(file2, null, 2) + "\n");
18252
+ fs64.renameSync(tmp, asksPathOf(sessionId));
18236
18253
  }
18237
18254
  function markSpawned(sessionId, pid) {
18238
18255
  patch(sessionId, (r2) => {
@@ -18357,18 +18374,19 @@ async function resumeDelivery(id) {
18357
18374
  const put = resumeRecord(id, execution);
18358
18375
  if (!put.ok) return put;
18359
18376
  const delivery = put.delivery;
18377
+ if (delivery.status === "finished") return { ok: true, deliveryId: delivery.deliveryId, landed: true };
18360
18378
  const carryOn = carryOnFrom(delivery.deliveryId);
18361
18379
  if (delivery.cardId !== null) await setCardStatus(delivery.cardId, "implementing");
18362
18380
  syncAudit(delivery.deliveryId);
18363
18381
  return { ok: true, deliveryId: delivery.deliveryId, carryOn };
18364
18382
  }
18365
18383
  function writeSpec(spec) {
18366
- fs63.mkdirSync(SESSIONS_DIR, { recursive: true });
18367
- fs63.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
18384
+ fs64.mkdirSync(SESSIONS_DIR, { recursive: true });
18385
+ fs64.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
18368
18386
  }
18369
18387
  function readSpec(sessionId) {
18370
18388
  try {
18371
- const spec = JSON.parse(fs63.readFileSync(specPathOf(sessionId), "utf8"));
18389
+ const spec = JSON.parse(fs64.readFileSync(specPathOf(sessionId), "utf8"));
18372
18390
  return spec && Array.isArray(spec.plan?.argv) ? spec : null;
18373
18391
  } catch {
18374
18392
  return null;
@@ -18376,28 +18394,28 @@ function readSpec(sessionId) {
18376
18394
  }
18377
18395
  function dropSpec(sessionId) {
18378
18396
  try {
18379
- fs63.unlinkSync(specPathOf(sessionId));
18397
+ fs64.unlinkSync(specPathOf(sessionId));
18380
18398
  } catch {
18381
18399
  }
18382
18400
  }
18383
18401
  async function acquireIndexLock(giveUp) {
18384
18402
  const until = Date.now() + INDEX_WAIT_MS;
18385
- const holder = path65.join(INDEX_LOCK2, "holder");
18403
+ const holder = path66.join(INDEX_LOCK2, "holder");
18386
18404
  for (; ; ) {
18387
18405
  if (giveUp()) return null;
18388
18406
  try {
18389
- fs63.mkdirSync(INDEX_LOCK2, { recursive: false });
18390
- fs63.writeFileSync(holder, String(process.pid));
18391
- return () => fs63.rmSync(INDEX_LOCK2, { recursive: true, force: true });
18407
+ fs64.mkdirSync(INDEX_LOCK2, { recursive: false });
18408
+ fs64.writeFileSync(holder, String(process.pid));
18409
+ return () => fs64.rmSync(INDEX_LOCK2, { recursive: true, force: true });
18392
18410
  } catch (err) {
18393
18411
  const code = err.code;
18394
18412
  if (code === "ENOENT") {
18395
- fs63.mkdirSync(path65.dirname(INDEX_LOCK2), { recursive: true });
18413
+ fs64.mkdirSync(path66.dirname(INDEX_LOCK2), { recursive: true });
18396
18414
  continue;
18397
18415
  }
18398
18416
  if (code !== "EEXIST") throw err;
18399
18417
  if (!pidAlive(Number(readHolder(holder)))) {
18400
- fs63.rmSync(INDEX_LOCK2, { recursive: true, force: true });
18418
+ fs64.rmSync(INDEX_LOCK2, { recursive: true, force: true });
18401
18419
  continue;
18402
18420
  }
18403
18421
  if (Date.now() > until) return null;
@@ -18407,7 +18425,7 @@ async function acquireIndexLock(giveUp) {
18407
18425
  }
18408
18426
  function readHolder(file2) {
18409
18427
  try {
18410
- return fs63.readFileSync(file2, "utf8").trim();
18428
+ return fs64.readFileSync(file2, "utf8").trim();
18411
18429
  } catch {
18412
18430
  return String(process.pid);
18413
18431
  }
@@ -18431,6 +18449,7 @@ var init_sessions = __esm({
18431
18449
  init_deliveries();
18432
18450
  init_flows();
18433
18451
  init_commit_mode();
18452
+ init_own_cost();
18434
18453
  init_log();
18435
18454
  init_resolve();
18436
18455
  init_pictures();
@@ -18492,8 +18511,8 @@ var init_sessions = __esm({
18492
18511
  implement: "implementing",
18493
18512
  hook: "implementing"
18494
18513
  };
18495
- specPathOf = (sessionId) => path65.join(SESSIONS_DIR, `${sessionId}.plan.json`);
18496
- asksPathOf = (sessionId) => path65.join(SESSIONS_DIR, `${sessionId}.asks.json`);
18514
+ specPathOf = (sessionId) => path66.join(SESSIONS_DIR, `${sessionId}.plan.json`);
18515
+ asksPathOf = (sessionId) => path66.join(SESSIONS_DIR, `${sessionId}.asks.json`);
18497
18516
  carriesSession = (r2) => !!(r2.resumedFrom || r2.continues && !r2.continues.fork);
18498
18517
  canPickUp = (r2) => r2.status === "error" || r2.status === "interrupted" || r2.status === "stopped";
18499
18518
  neverStarted = (r2) => r2.unspawned === true || !!r2.errorWhy?.some((why2) => why2.kind === "notInstalled");
@@ -18520,8 +18539,8 @@ var init_sessions = __esm({
18520
18539
  });
18521
18540
 
18522
18541
  // ../cli/src/lib/card-sources.ts
18523
- import fs64 from "node:fs";
18524
- import path66 from "node:path";
18542
+ import fs65 from "node:fs";
18543
+ import path67 from "node:path";
18525
18544
  function planById(id) {
18526
18545
  const found2 = readPlan(`plans/${id}-.md`);
18527
18546
  return found2?.text.trim() ? found2 : null;
@@ -18531,8 +18550,8 @@ function cardLink(id) {
18531
18550
  const found2 = open3 ?? locateArchived(id);
18532
18551
  if (!found2) return null;
18533
18552
  try {
18534
- const file2 = found2.kind === "group" ? path66.join(found2.target, "root.md") : found2.target;
18535
- const title = parseFrontmatter(fs64.readFileSync(file2, "utf8")).meta?.title ?? "";
18553
+ const file2 = found2.kind === "group" ? path67.join(found2.target, "root.md") : found2.target;
18554
+ const title = parseFrontmatter(fs65.readFileSync(file2, "utf8")).meta?.title ?? "";
18536
18555
  return { kind: "card", ref: String(id), title, ...open3 ? {} : { archived: true } };
18537
18556
  } catch {
18538
18557
  return null;
@@ -18557,7 +18576,7 @@ function link(ref, items) {
18557
18576
  if (ref.kind === "plan") return planLink(ref.id);
18558
18577
  if (ref.kind === "card") return cardLink(ref.id);
18559
18578
  if (ref.kind === "url") return urlLink(ref.url);
18560
- const item = items().find((signal2) => path66.basename(signal2.relPath) === ref.file);
18579
+ const item = items().find((signal2) => path67.basename(signal2.relPath) === ref.file);
18561
18580
  return item ? itemLink(item) : null;
18562
18581
  }
18563
18582
  function cardSources(meta, body) {
@@ -18598,12 +18617,12 @@ var init_card_sources = __esm({
18598
18617
  });
18599
18618
 
18600
18619
  // ../cli/src/lib/view/read.ts
18601
- import fs65 from "node:fs";
18602
- import path67 from "node:path";
18620
+ import fs66 from "node:fs";
18621
+ import path68 from "node:path";
18603
18622
  function readCard(file2, relFromTodo) {
18604
- const id = idPrefix(path67.basename(relFromTodo));
18623
+ const id = idPrefix(path68.basename(relFromTodo));
18605
18624
  if (id === null) {
18606
- const parts = relFromTodo.split(path67.sep);
18625
+ const parts = relFromTodo.split(path68.sep);
18607
18626
  const folderId = idPrefix(parts[parts.length - 2] || "");
18608
18627
  if (folderId === null) return null;
18609
18628
  return buildCard(folderId, file2, relFromTodo);
@@ -18611,10 +18630,10 @@ function readCard(file2, relFromTodo) {
18611
18630
  return buildCard(id, file2, relFromTodo);
18612
18631
  }
18613
18632
  function buildCard(id, file2, relFromTodo) {
18614
- const text5 = fs65.readFileSync(file2, "utf8");
18633
+ const text5 = fs66.readFileSync(file2, "utf8");
18615
18634
  const { meta, body } = parseFrontmatter(text5);
18616
18635
  if (!meta) return null;
18617
- const relPath = relFromTodo.split(path67.sep).join("/");
18636
+ const relPath = relFromTodo.split(path68.sep).join("/");
18618
18637
  const flow = studioFor(meta.studio);
18619
18638
  const plan = !!meta.studio && archivesOnApproval(flow);
18620
18639
  const stages = cardStages(meta, flow).length;
@@ -18623,7 +18642,7 @@ function buildCard(id, file2, relFromTodo) {
18623
18642
  // Derived from the file exactly as it is on disk (lib/board/revision.ts), so a card
18624
18643
  // read here and a card read by the contract agree on what version this is.
18625
18644
  revision: revisionOf(text5),
18626
- updatedAt: fs65.statSync(file2).mtime.toISOString(),
18645
+ updatedAt: fs66.statSync(file2).mtime.toISOString(),
18627
18646
  relPath,
18628
18647
  title: meta.title,
18629
18648
  priority: meta.priority,
@@ -18644,22 +18663,22 @@ function buildCard(id, file2, relFromTodo) {
18644
18663
  };
18645
18664
  }
18646
18665
  function readGroup2(folderName) {
18647
- const groupDir = path67.join(TODO, folderName);
18648
- const rootFile = path67.join(groupDir, "root.md");
18649
- if (!fs65.existsSync(rootFile)) return null;
18650
- const root2 = readCard(rootFile, path67.join(folderName, "root.md"));
18666
+ const groupDir = path68.join(TODO, folderName);
18667
+ const rootFile = path68.join(groupDir, "root.md");
18668
+ if (!fs66.existsSync(rootFile)) return null;
18669
+ const root2 = readCard(rootFile, path68.join(folderName, "root.md"));
18651
18670
  if (!root2) return null;
18652
18671
  root2.isGroup = true;
18653
18672
  const { total, resolved: resolved2 } = subtaskLines(root2.body);
18654
18673
  root2.subtaskLines = { total, resolved: resolved2 };
18655
18674
  const subCards = [];
18656
18675
  const recurse = (dir, relDir) => {
18657
- for (const entry of fs65.readdirSync(dir, { withFileTypes: true })) {
18658
- const childRel = path67.join(relDir, entry.name);
18676
+ for (const entry of fs66.readdirSync(dir, { withFileTypes: true })) {
18677
+ const childRel = path68.join(relDir, entry.name);
18659
18678
  if (entry.isDirectory()) {
18660
- recurse(path67.join(dir, entry.name), childRel);
18679
+ recurse(path68.join(dir, entry.name), childRel);
18661
18680
  } else if (entry.name.endsWith(".md") && entry.name !== "README.md" && entry.name !== "root.md") {
18662
- const c2 = readCard(path67.join(dir, entry.name), childRel);
18681
+ const c2 = readCard(path68.join(dir, entry.name), childRel);
18663
18682
  if (c2) {
18664
18683
  c2.parent = { id: root2.id, title: root2.title };
18665
18684
  subCards.push(c2);
@@ -18680,12 +18699,12 @@ function readGroup2(folderName) {
18680
18699
  return { root: root2, subCards };
18681
18700
  }
18682
18701
  function standaloneCards(dirRel) {
18683
- const dir = dirRel ? path67.join(TODO, dirRel) : TODO;
18684
- if (!fs65.existsSync(dir)) return [];
18702
+ const dir = dirRel ? path68.join(TODO, dirRel) : TODO;
18703
+ if (!fs66.existsSync(dir)) return [];
18685
18704
  const cards = [];
18686
- for (const entry of fs65.readdirSync(dir, { withFileTypes: true })) {
18705
+ for (const entry of fs66.readdirSync(dir, { withFileTypes: true })) {
18687
18706
  if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md") {
18688
- const c2 = readCard(path67.join(dir, entry.name), path67.join(dirRel, entry.name));
18707
+ const c2 = readCard(path68.join(dir, entry.name), path68.join(dirRel, entry.name));
18689
18708
  if (c2) cards.push(c2);
18690
18709
  }
18691
18710
  }
@@ -18697,7 +18716,7 @@ function collectCards() {
18697
18716
  const top = standaloneCards("");
18698
18717
  board2.push(...top);
18699
18718
  every.push(...top);
18700
- for (const entry of fs65.readdirSync(TODO, { withFileTypes: true })) {
18719
+ for (const entry of fs66.readdirSync(TODO, { withFileTypes: true })) {
18701
18720
  if (!entry.isDirectory()) continue;
18702
18721
  if (isGroupFolder(entry.name)) {
18703
18722
  const g3 = readGroup2(entry.name);
@@ -18729,7 +18748,7 @@ function findCard(id) {
18729
18748
  }
18730
18749
  function attachSources(card) {
18731
18750
  try {
18732
- const { meta, body } = parseFrontmatter(fs65.readFileSync(path67.join(TODO, card.relPath), "utf8"));
18751
+ const { meta, body } = parseFrontmatter(fs66.readFileSync(path68.join(TODO, card.relPath), "utf8"));
18733
18752
  const sources2 = meta ? cardSources(meta, body) : [];
18734
18753
  if (sources2.length) card.sources = sources2;
18735
18754
  } catch {
@@ -18812,7 +18831,7 @@ function attachDiscard(card, active2) {
18812
18831
  resumable: holder.status !== "active" && isResumable(holder)
18813
18832
  };
18814
18833
  }
18815
- function allCards2() {
18834
+ function allCards() {
18816
18835
  return collectCards().every;
18817
18836
  }
18818
18837
  var init_read = __esm({
@@ -18833,25 +18852,25 @@ var init_read = __esm({
18833
18852
  });
18834
18853
 
18835
18854
  // ../cli/src/lib/agent/preview-progress.ts
18836
- import fs66 from "node:fs";
18837
- import path68 from "node:path";
18855
+ import fs67 from "node:fs";
18856
+ import path69 from "node:path";
18838
18857
  import { createHash as createHash7, randomUUID as randomUUID5 } from "node:crypto";
18839
18858
  function readPreviewProgress(id) {
18840
18859
  try {
18841
- return JSON.parse(fs66.readFileSync(file(id), "utf8"));
18860
+ return JSON.parse(fs67.readFileSync(file(id), "utf8"));
18842
18861
  } catch (error) {
18843
18862
  if (error.code === "ENOENT") return {};
18844
18863
  throw error;
18845
18864
  }
18846
18865
  }
18847
18866
  function updatePreviewProgress(id, change2) {
18848
- fs66.mkdirSync(path68.dirname(file(id)), { recursive: true });
18867
+ fs67.mkdirSync(path69.dirname(file(id)), { recursive: true });
18849
18868
  return withLock(`${file(id)}.lock`, "updating preview progress", () => {
18850
18869
  const all2 = readPreviewProgress(id);
18851
18870
  const result = change2(all2);
18852
18871
  const temp = `${file(id)}.${process.pid}.tmp`;
18853
- fs66.writeFileSync(temp, JSON.stringify(all2) + "\n");
18854
- fs66.renameSync(temp, file(id));
18872
+ fs67.writeFileSync(temp, JSON.stringify(all2) + "\n");
18873
+ fs67.renameSync(temp, file(id));
18855
18874
  return result;
18856
18875
  });
18857
18876
  }
@@ -18861,7 +18880,7 @@ function freezePreviewProgress(id, name) {
18861
18880
  const agent = findSpecAgent(name);
18862
18881
  if (!agent) return null;
18863
18882
  const studio = studioFiles(cardStudioId(id)) ?? {};
18864
- const protocol = Object.entries(studio).some(([path90, text5]) => path90.endsWith("/AGENT.md") && /^[ \t]+stages:/m.test(text5.split(/\r?\n---/)[0]));
18883
+ const protocol = Object.entries(studio).some(([path91, text5]) => path91.endsWith("/AGENT.md") && /^[ \t]+stages:/m.test(text5.split(/\r?\n---/)[0]));
18865
18884
  if (!agent.stages && !protocol) return null;
18866
18885
  const definitions = agent.stages ?? [{ id: "preview", title: { en: "Preview", zh: "\u6210\u679C" }, instructions: "preview.md" }];
18867
18886
  const files = Object.fromEntries(agent.files.map((file2) => [file2, agent.file(file2)]).filter((entry) => entry[1] !== null));
@@ -18875,33 +18894,66 @@ function freezePreviewProgress(id, name) {
18875
18894
  function previewStagePrompt(id, name, command) {
18876
18895
  const progress = freezePreviewProgress(id, name);
18877
18896
  if (!progress) return "";
18878
- if (progress.revisionBase) return `A revision is requested. Inspect the saved work and feedback. Choose the earliest affected stage with: ${command} raw previews ${name} ${id} --revise-from <stage-id>. Preserve confirmed earlier stages; do not produce work before choosing. Saved stages: ${JSON.stringify(progress.revisionBase.map(({ id: id2, title, status, artifact }) => ({ id: id2, title, status, artifact })))}`;
18879
- if (!progress.stages.length) return `Stage definitions (frozen):
18897
+ if (progress.revisionBase) return `Revise from the first affected stage: ${command} raw previews ${name} ${id} --revise-from <stage-id>. Saved stages: ${JSON.stringify(progress.revisionBase.map(({ id: id2, title, status, artifact }) => ({ id: id2, title, status, artifact })))}`;
18898
+ if (!progress.stages.length) return `Stages:
18880
18899
  ${JSON.stringify(progress.definitions)}
18881
- Choose the work this task needs, then run: ${command} raw previews ${name} ${id} --stages <id,...>. Do not produce work before saving the selection.`;
18900
+ Select with: ${command} raw previews ${name} ${id} --stages <id,...>.`;
18882
18901
  const current = progress.stages.find((stage) => stage.id === progress.currentStageId);
18883
- if (current.status === "awaiting_confirmation" || previewReady(progress)) return "The submitted preview is awaiting review. Do not revise or advance it without user feedback.";
18902
+ if (!current) return `Saved stages: ${JSON.stringify(progress.stages)}
18903
+ Select with: ${command} raw previews ${name} ${id} --stages <id,...>.`;
18904
+ if (current.status === "awaiting_confirmation" || previewReady(progress)) return "The submitted preview is awaiting review.";
18884
18905
  return [
18885
18906
  `Selected stages: ${progress.stages.map((stage) => stage.id).join(", ")}. Current stage: ${current.id}.`,
18886
- progress.files[current.instructions],
18907
+ progress.files[current.instructions] === progress.body ? "" : progress.files[current.instructions],
18887
18908
  ...name === "ui-designer" ? [current.id === "copywriting" ? legacyPreviewMemory("copywriting") : current.id === "illustration" ? legacyPreviewMemory("illustrator") : ""] : [],
18888
18909
  ...progress.stages.filter((stage) => stage.status === "confirmed").map((stage) => `Confirmed ${stage.id} v${stage.version}:
18889
18910
  ${stage.artifact?.body ?? ""}`),
18890
- `Write only the current work in your existing section. Submit it with: ${command} raw previews ${name} ${id} --submit --stage ${current.id}. Stop after success.`
18911
+ `Submit with: ${command} raw previews ${name} ${id} --submit --stage ${current.id}.`
18891
18912
  ].join("\n\n");
18892
18913
  }
18914
+ function previewOwner(id, name, inside2 = insideRun()) {
18915
+ const found2 = locate(id);
18916
+ if (!found2) throw Error("The task is no longer open.");
18917
+ const card = found2.kind === "group" ? path69.join(found2.target, "root.md") : found2.target;
18918
+ const { meta } = parseFrontmatter(fs67.readFileSync(card, "utf8"));
18919
+ if (!specAgentAssigned(name, meta?.studio) || !meta?.previews?.some((agent) => canonicalSpecAgent(agent) === name)) throw Error("Choose this preview agent on the task first.");
18920
+ if (inside2) {
18921
+ const run4 = readRuns().find((run5) => run5.sessionId === inside2);
18922
+ if (!run4 || run4.status !== "running" || run4.cardId !== id) throw Error("Only the active task session can prepare its selected previews.");
18923
+ return `run:${inside2}`;
18924
+ }
18925
+ const execution = executionOf();
18926
+ if (execution) return `job:${execution.job}`;
18927
+ return process.env[STOP_ENV] || Object.values(SESSION_VARS).map((key) => process.env[key]).find(Boolean) || "external";
18928
+ }
18929
+ function readContext(file2) {
18930
+ try {
18931
+ return JSON.parse(fs67.readFileSync(file2, "utf8"));
18932
+ } catch (error) {
18933
+ if (error.code === "ENOENT") return void 0;
18934
+ throw error;
18935
+ }
18936
+ }
18937
+ function writeJson2(file2, value) {
18938
+ fs67.mkdirSync(path69.dirname(file2), { recursive: true });
18939
+ const temp = `${file2}.${process.pid}.tmp`;
18940
+ fs67.writeFileSync(temp, JSON.stringify(value) + "\n");
18941
+ fs67.renameSync(temp, file2);
18942
+ }
18893
18943
  function previewRun(id, name) {
18894
- const run4 = readRuns().find((run5) => run5.sessionId === insideRun());
18895
- if (!run4 || run4.status !== "running" || run4.action !== "spec" || run4.specAgent !== name || run4.cardId !== id) throw Error("Only the active preview agent can select or submit its stages.");
18896
- return run4;
18944
+ const context = readContext(contextFile(id, name, previewOwner(id, name)));
18945
+ if (!context?.active) throw new PreviewContextMissing("This preview has no saved execution context.");
18946
+ const progress = readPreviewProgress(id)[name];
18947
+ if (progress?.execution && progress.execution !== context.sessionId && !progress.execution.endsWith(`:${context.sessionId}`)) throw Error("This execution is outdated. Reload the task.");
18948
+ return context;
18897
18949
  }
18898
18950
  function selectLocalPreview(id, name, ids) {
18899
18951
  const run4 = previewRun(id, name);
18900
- freezePreviewProgress(id, name);
18901
18952
  return updatePreviewProgress(id, (all2) => {
18902
18953
  const progress = all2[name];
18903
18954
  if (!progress) throw Error("This agent has no staged preview.");
18904
- if (progress.stages.length && progress.execution === run4.sessionId && JSON.stringify(progress.stages.map((stage) => stage.id)) === JSON.stringify(ids)) return { progress, baseline: readPreviewBaseline(run4.sessionId) };
18955
+ if (progress.execution !== run4.sessionId) throw Error("This execution is outdated. Reload the task.");
18956
+ if (progress.stages.length && JSON.stringify(progress.stages.map((stage) => stage.id)) === JSON.stringify(ids)) return { progress, baseline: readPreviewBaseline(id, name, run4.sessionId) };
18905
18957
  selectPreviewStages(progress, ids);
18906
18958
  const baseline = previewBaseline(progress, progress.currentStageId, run4.sessionId);
18907
18959
  return { progress, baseline };
@@ -18910,7 +18962,7 @@ function selectLocalPreview(id, name, ids) {
18910
18962
  function previewSection(body, name) {
18911
18963
  const lines = body.split("\n");
18912
18964
  const start = lines.findIndex((line) => specHeadingRe(name).test(line));
18913
- if (start < 0) throw Error("Write the preview in its own section before submitting it.");
18965
+ if (start < 0) return "";
18914
18966
  const end2 = lines.findIndex((line, index) => index > start && (/^## /.test(line) || line.trim() === "<!-- agent -->"));
18915
18967
  return lines.slice(start + 1, end2 < 0 ? void 0 : end2).join("\n").trim();
18916
18968
  }
@@ -18919,43 +18971,53 @@ function submitLocalPreview(id, name, stage, baseline) {
18919
18971
  const card = findCard(id);
18920
18972
  if (!card) throw Error("The task is no longer open.");
18921
18973
  const body = previewSection(card.body, name);
18922
- const problems = validatePreviewFiles(path68.join(TODO, card.relPath), id, body);
18923
- if (problems.length) throw Error(problems.map((problem) => problem.message).join("\n"));
18924
18974
  const snapshot = randomUUID5();
18925
- const source2 = path68.join(ASSETS, String(id));
18926
- const dest = path68.join(BOARD_STATE, "previews", "assets", String(id), snapshot);
18927
- if (fs66.existsSync(source2)) fs66.cpSync(source2, dest, { recursive: true, dereference: true });
18975
+ const source2 = path69.join(ASSETS, String(id));
18976
+ const dest = path69.join(BOARD_STATE, "previews", "assets", String(id), snapshot);
18977
+ if (fs67.existsSync(source2) && fs67.lstatSync(source2).isSymbolicLink()) throw Error("Preview assets must stay inside this task\u2019s asset folder.");
18978
+ if (fs67.existsSync(source2)) fs67.cpSync(source2, dest, { recursive: true, dereference: true, filter: (file2) => {
18979
+ const real2 = fs67.realpathSync(file2);
18980
+ if (real2 !== fs67.realpathSync(source2) && !real2.startsWith(fs67.realpathSync(source2) + path69.sep)) throw Error("Preview assets must stay inside this task\u2019s asset folder.");
18981
+ return true;
18982
+ } });
18928
18983
  return updatePreviewProgress(id, (all2) => {
18929
18984
  const progress = all2[name];
18930
18985
  if (!progress) throw Error("Select the stages first.");
18931
- const base = baseline ?? { definitionRevision: progress.definitionRevision, generation: progress.generation, stageId: stage, execution: run4.sessionId };
18986
+ const base = baseline ?? readPreviewBaseline(id, name, run4.sessionId);
18932
18987
  if (base.stageId !== stage) throw Error("Wrong stage.");
18933
18988
  return submitPreviewStage(progress, base, body, { folder: dest });
18934
18989
  });
18935
18990
  }
18936
- function savePreviewBaseline(run4, baseline) {
18937
- fs66.mkdirSync(path68.dirname(baselineFile(run4)), { recursive: true });
18938
- fs66.writeFileSync(baselineFile(run4), JSON.stringify(baseline) + "\n");
18991
+ function savePreviewBaseline(id, name, run4, baseline) {
18992
+ writeJson2(baselineFile(id, name, run4), baseline);
18939
18993
  }
18940
- function readPreviewBaseline(run4) {
18941
- return JSON.parse(fs66.readFileSync(baselineFile(run4), "utf8"));
18994
+ function readPreviewBaseline(id, name, run4) {
18995
+ return JSON.parse(fs67.readFileSync(baselineFile(id, name, run4), "utf8"));
18942
18996
  }
18943
- async function activatePreviewRun(id, name, run4) {
18997
+ async function activatePreviewRun(id, name, run4, request2 = "") {
18998
+ const owner = previewOwner(id, name, run4 ?? insideRun());
18999
+ const file2 = contextFile(id, name, owner);
19000
+ const held4 = readContext(file2);
19001
+ const context = held4 && held4.request === request2 ? held4 : { sessionId: run4 ?? randomUUID5(), request: request2 };
19002
+ writeJson2(file2, context);
19003
+ run4 = context.sessionId;
18944
19004
  const { previewBridge: previewBridge2 } = await Promise.resolve().then(() => (init_preview(), preview_exports));
18945
- const remote2 = await previewBridge2(name, "start", { run: run4 });
18946
- if (remote2?.progress) {
18947
- updatePreviewProgress(id, (all2) => {
19005
+ const remote2 = await previewBridge2(name, "start", { run: run4, cardId: id });
19006
+ if (remote2) {
19007
+ if (remote2.progress) updatePreviewProgress(id, (all2) => {
18948
19008
  all2[name] = remote2.progress;
18949
19009
  });
18950
- if (remote2.baseline) savePreviewBaseline(run4, remote2.baseline);
19010
+ if (remote2.baseline) savePreviewBaseline(id, name, run4, remote2.baseline);
18951
19011
  } else {
18952
19012
  freezePreviewProgress(id, name);
18953
19013
  updatePreviewProgress(id, (all2) => {
18954
19014
  const progress = all2[name];
18955
- if (progress?.currentStageId && ["awaiting_confirmation", "ready"].includes(progress.stages.find((stage) => stage.id === progress.currentStageId)?.status ?? "") && progress.execution !== run4) beginPreviewRevision(progress, run4);
18956
- if (progress?.currentStageId && !progress.revisionBase) savePreviewBaseline(run4, previewBaseline(progress, progress.currentStageId, run4));
19015
+ if (!progress) return;
19016
+ if (progress.currentStageId && !progress.revisionBase) savePreviewBaseline(id, name, run4, previewBaseline(progress, progress.currentStageId, run4));
19017
+ else progress.execution = run4;
18957
19018
  });
18958
19019
  }
19020
+ writeJson2(file2, { ...context, active: true });
18959
19021
  }
18960
19022
  function frozenPreviewFile(agent, relative) {
18961
19023
  const run4 = readRuns().find((run5) => run5.sessionId === insideRun());
@@ -18965,13 +19027,13 @@ function frozenPreviewFile(agent, relative) {
18965
19027
  function legacyPreviewMemory(agent) {
18966
19028
  const folder = agentMemoryDir(agent);
18967
19029
  try {
18968
- return fs66.readdirSync(folder).filter((name) => name.endsWith(".md")).map((name) => `Existing ${agent} preferences (${name}):
18969
- ${fs66.readFileSync(path68.join(folder, name), "utf8")}`).join("\n\n");
19030
+ return fs67.readdirSync(folder).filter((name) => name.endsWith(".md")).map((name) => `Existing ${agent} preferences (${name}):
19031
+ ${fs67.readFileSync(path69.join(folder, name), "utf8")}`).join("\n\n");
18970
19032
  } catch {
18971
19033
  return "";
18972
19034
  }
18973
19035
  }
18974
- var file, baselineFile;
19036
+ var file, contextFile, PreviewContextMissing, baselineFile;
18975
19037
  var init_preview_progress = __esm({
18976
19038
  "../cli/src/lib/agent/preview-progress.ts"() {
18977
19039
  "use strict";
@@ -18979,21 +19041,27 @@ var init_preview_progress = __esm({
18979
19041
  init_memory();
18980
19042
  init_lock();
18981
19043
  init_agents();
19044
+ init_spec_agent_names();
18982
19045
  init_read();
18983
19046
  init_studios();
18984
19047
  init_studio_shared();
18985
19048
  init_store();
18986
19049
  init_env();
18987
- init_preview_files();
19050
+ init_cards();
19051
+ init_frontmatter();
19052
+ init_execution();
18988
19053
  init_preview_stages();
18989
- file = (id) => path68.join(BOARD_STATE, "previews", `${id}.json`);
18990
- baselineFile = (run4) => path68.join(BOARD_STATE, "previews", "runs", `${run4}.json`);
19054
+ file = (id) => path69.join(BOARD_STATE, "previews", `${id}.json`);
19055
+ contextFile = (id, name, owner) => path69.join(BOARD_STATE, "previews", "contexts", String(id), name, `${createHash7("sha256").update(owner).digest("hex")}.json`);
19056
+ PreviewContextMissing = class extends Error {
19057
+ };
19058
+ baselineFile = (id, name, run4) => path69.join(BOARD_STATE, "previews", "runs", String(id), name, `${run4}.json`);
18991
19059
  }
18992
19060
  });
18993
19061
 
18994
19062
  // ../cli/src/lib/agent/approve.ts
18995
- import fs67 from "node:fs";
18996
- import path69 from "node:path";
19063
+ import fs68 from "node:fs";
19064
+ import path70 from "node:path";
18997
19065
  function approvalRequest(req) {
18998
19066
  const id = req.id;
18999
19067
  const card = id === void 0 ? null : findCard(id);
@@ -19011,12 +19079,12 @@ function advancePhase(id) {
19011
19079
  const card = findCard(id);
19012
19080
  const found2 = locate(id);
19013
19081
  if (!card || !found2 || !awaitingApproval(card)) return { error: `#${id} is no longer waiting on approval.` };
19014
- const file2 = found2.kind === "group" ? path69.join(found2.target, "root.md") : found2.target;
19015
- const { meta, body } = parseFrontmatter(fs67.readFileSync(file2, "utf8"));
19082
+ const file2 = found2.kind === "group" ? path70.join(found2.target, "root.md") : found2.target;
19083
+ const { meta, body } = parseFrontmatter(fs68.readFileSync(file2, "utf8"));
19016
19084
  if (!meta) return { error: `#${id} has no frontmatter` };
19017
19085
  meta.phase = card.stage + 1;
19018
19086
  meta.status = "todo";
19019
- fs67.writeFileSync(file2, serializeFrontmatter(meta) + "\n" + body);
19087
+ fs68.writeFileSync(file2, serializeFrontmatter(meta) + "\n" + body);
19020
19088
  return null;
19021
19089
  }
19022
19090
  var init_approve = __esm({
@@ -19059,8 +19127,7 @@ function studioRefusal(req) {
19059
19127
  if (archivesOnApproval(flow) && req.action === "implement") {
19060
19128
  return refusal("planDelivered", `#${req.id} lands nothing, so its last approval archives it rather than building it.`, { card: String(req.id) });
19061
19129
  }
19062
- const [problem] = studioIssues(flow.id);
19063
- return problem ?? null;
19130
+ return null;
19064
19131
  }
19065
19132
  async function scheduledRefusal(req) {
19066
19133
  if (req.action !== "scheduled" || req.deliveryId || !req.studio || !req.specAgent) return null;
@@ -19259,10 +19326,10 @@ var init_avatar = __esm({
19259
19326
  });
19260
19327
 
19261
19328
  // ../cli/src/lib/cloud/pro.ts
19262
- import fs68 from "node:fs";
19263
- import path70 from "node:path";
19329
+ import fs69 from "node:fs";
19330
+ import path71 from "node:path";
19264
19331
  function forgetPro() {
19265
- fs68.rmSync(heldFile(), { force: true });
19332
+ fs69.rmSync(heldFile(), { force: true });
19266
19333
  }
19267
19334
  var FRESH_MS2, GRACE_MS, heldFile;
19268
19335
  var init_pro = __esm({
@@ -19273,7 +19340,7 @@ var init_pro = __esm({
19273
19340
  init_session();
19274
19341
  FRESH_MS2 = 10 * 6e4;
19275
19342
  GRACE_MS = 7 * 24 * 60 * 6e4;
19276
- heldFile = () => path70.join(machineHome(), "pro.json");
19343
+ heldFile = () => path71.join(machineHome(), "pro.json");
19277
19344
  }
19278
19345
  });
19279
19346
 
@@ -19364,8 +19431,8 @@ var init_account = __esm({
19364
19431
  });
19365
19432
 
19366
19433
  // ../cli/src/commands/cloud.ts
19367
- import fs69 from "node:fs";
19368
- import path71 from "node:path";
19434
+ import fs70 from "node:fs";
19435
+ import path72 from "node:path";
19369
19436
  async function cmdCloud(args2, program2) {
19370
19437
  const [sub] = args2;
19371
19438
  if (sub === "sign-out") {
@@ -19427,10 +19494,10 @@ async function cloudImage(opts, program2) {
19427
19494
  const prompt = opts.prompt.trim();
19428
19495
  if (!prompt) usage("Missing the prompt.", line);
19429
19496
  const references = opts.refs.map((file2) => {
19430
- const type = REF_TYPES[path71.extname(file2).toLowerCase()];
19497
+ const type = REF_TYPES[path72.extname(file2).toLowerCase()];
19431
19498
  if (!type) usage(`--ref ${file2}: use a PNG, JPEG or WebP file.`, line);
19432
19499
  try {
19433
- return `data:${type};base64,${fs69.readFileSync(file2).toString("base64")}`;
19500
+ return `data:${type};base64,${fs70.readFileSync(file2).toString("base64")}`;
19434
19501
  } catch (e2) {
19435
19502
  usage(`--ref ${file2}: ${e2 instanceof Error ? e2.message : String(e2)}`, line);
19436
19503
  }
@@ -19538,8 +19605,8 @@ async function generate(g3) {
19538
19605
  refuse(g3.failed, g3.fallback);
19539
19606
  }
19540
19607
  const out = g3.outFor?.(res, g3.out) ?? g3.out;
19541
- fs69.mkdirSync(path71.dirname(path71.resolve(out)), { recursive: true });
19542
- fs69.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
19608
+ fs70.mkdirSync(path72.dirname(path72.resolve(out)), { recursive: true });
19609
+ fs70.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
19543
19610
  say(`${out} (${g3.label(res)})`);
19544
19611
  return { out };
19545
19612
  }
@@ -19587,11 +19654,11 @@ var init_cloud = __esm({
19587
19654
  });
19588
19655
 
19589
19656
  // ../cli/src/commands/task.ts
19590
- import fs70 from "node:fs";
19657
+ import fs71 from "node:fs";
19591
19658
  import os5 from "node:os";
19592
- import path72 from "node:path";
19659
+ import path73 from "node:path";
19593
19660
  async function cloud(method, route2, body) {
19594
- process.env.AI4KANBAN_HOME ??= process.env.WILDCRANE_HOME || path72.join(os5.homedir(), ".wildcrane");
19661
+ process.env.AI4KANBAN_HOME ??= process.env.WILDCRANE_HOME || path73.join(os5.homedir(), ".wildcrane");
19595
19662
  const token2 = await accessToken();
19596
19663
  if (!token2.ok) return refuse2(SAID[token2.reason].en, token2.reason.replace("-", "_"));
19597
19664
  let response;
@@ -19621,12 +19688,12 @@ async function all(route2) {
19621
19688
  return rows;
19622
19689
  }
19623
19690
  function linked() {
19624
- for (let dir = process.cwd(); ; dir = path72.dirname(dir)) {
19625
- if (fs70.existsSync(path72.join(dir, ".akb", "base.json"))) {
19691
+ for (let dir = process.cwd(); ; dir = path73.dirname(dir)) {
19692
+ if (fs71.existsSync(path73.join(dir, ".akb", "base.json"))) {
19626
19693
  const link2 = linkedProject("", dir);
19627
19694
  return link2.ok ? link2.value : null;
19628
19695
  }
19629
- if (path72.dirname(dir) === dir) return null;
19696
+ if (path73.dirname(dir) === dir) return null;
19630
19697
  }
19631
19698
  }
19632
19699
  async function project(asked) {
@@ -19770,11 +19837,11 @@ var init_task = __esm({
19770
19837
  });
19771
19838
 
19772
19839
  // ../cli/src/commands/goal.ts
19773
- import fs71 from "node:fs";
19840
+ import fs72 from "node:fs";
19774
19841
  function loadGoals() {
19775
19842
  const file2 = goalsFile();
19776
19843
  if (!file2) die("Goals exist only inside a WildCrane goal discussion.");
19777
- const held4 = JSON.parse(fs71.readFileSync(file2, "utf8"));
19844
+ const held4 = JSON.parse(fs72.readFileSync(file2, "utf8"));
19778
19845
  if (held4.goals !== void 0 && held4.ideas !== void 0 && JSON.stringify(held4.goals) !== JSON.stringify(held4.ideas)) die("goals and ideas do not match.");
19779
19846
  const goals = held4.goals ?? held4.ideas;
19780
19847
  if (!Array.isArray(goals)) die("The goals array is missing or invalid.");
@@ -19804,7 +19871,7 @@ function splitBody2(text5) {
19804
19871
  }
19805
19872
  function readBody(bodyFile) {
19806
19873
  if (!bodyFile) die("--body-file is required; write the goal in a writable temporary file first.");
19807
- const text5 = fs71.readFileSync(bodyFile, "utf8");
19874
+ const text5 = fs72.readFileSync(bodyFile, "utf8");
19808
19875
  if (!text5.trim()) die("The goal must not be empty.");
19809
19876
  return splitBody2(text5);
19810
19877
  }
@@ -19816,7 +19883,7 @@ function named(held4, id) {
19816
19883
  function cmdGoal(args2, opts) {
19817
19884
  const sub = args2[0] ?? "";
19818
19885
  const { file: file2, held: held4 } = loadGoals();
19819
- const write2 = () => fs71.writeFileSync(file2, `${JSON.stringify({ ...held4, goals: void 0, ideas: held4.goals }, null, 2)}
19886
+ const write2 = () => fs72.writeFileSync(file2, `${JSON.stringify({ ...held4, goals: void 0, ideas: held4.goals }, null, 2)}
19820
19887
  `);
19821
19888
  if (sub === "new") {
19822
19889
  const title = opts.title?.trim();
@@ -19904,9 +19971,9 @@ var init_goal = __esm({
19904
19971
  });
19905
19972
 
19906
19973
  // ../cli/src/commands/goal-cloud.ts
19907
- import fs72 from "node:fs";
19974
+ import fs73 from "node:fs";
19908
19975
  import os6 from "node:os";
19909
- import path73 from "node:path";
19976
+ import path74 from "node:path";
19910
19977
  import crypto3 from "node:crypto";
19911
19978
  function hostSession() {
19912
19979
  const { CLAUDE_CODE_SESSION_ID: claude, CODEX_THREAD_ID: codex, CURSOR_CONVERSATION_ID: cursor, KIMI_SESSION_ID: kimi, WILDCRANE_DISCUSSION: discussion2 } = process.env;
@@ -19935,24 +20002,24 @@ function goalsOf(d2) {
19935
20002
  async function discussion() {
19936
20003
  const session = hostSession();
19937
20004
  if (!session) die("Goals exist only inside a WildCrane goal discussion.");
19938
- const home3 = process.env.WILDCRANE_HOME || path73.join(os6.homedir(), ".wildcrane");
20005
+ const home3 = process.env.WILDCRANE_HOME || path74.join(os6.homedir(), ".wildcrane");
19939
20006
  process.env.AI4KANBAN_HOME ??= home3;
19940
20007
  if (session.host === "discussion") return request("GET", `/v1/discussions/${encodeURIComponent(session.id)}`);
19941
- const machineFile2 = path73.join(home3, "machine.json");
20008
+ const machineFile2 = path74.join(home3, "machine.json");
19942
20009
  let machine;
19943
20010
  try {
19944
- machine = JSON.parse(fs72.readFileSync(machineFile2, "utf8")).id;
20011
+ machine = JSON.parse(fs73.readFileSync(machineFile2, "utf8")).id;
19945
20012
  } catch {
19946
20013
  machine = crypto3.randomUUID();
19947
- fs72.mkdirSync(home3, { recursive: true });
19948
- fs72.writeFileSync(machineFile2, JSON.stringify({ id: machine }));
20014
+ fs73.mkdirSync(home3, { recursive: true });
20015
+ fs73.writeFileSync(machineFile2, JSON.stringify({ id: machine }));
19949
20016
  }
19950
20017
  const held4 = await request("GET", `/v1/runner/folders?machine=${encodeURIComponent(machine)}`);
19951
- const cwd = fs72.realpathSync(process.cwd());
20018
+ const cwd = fs73.realpathSync(process.cwd());
19952
20019
  const folder = held4.folders.filter((f2) => {
19953
20020
  try {
19954
- const dir = fs72.realpathSync(f2.path);
19955
- return cwd === dir || cwd.startsWith(dir + path73.sep);
20021
+ const dir = fs73.realpathSync(f2.path);
20022
+ return cwd === dir || cwd.startsWith(dir + path74.sep);
19956
20023
  } catch {
19957
20024
  return false;
19958
20025
  }
@@ -19961,16 +20028,16 @@ async function discussion() {
19961
20028
  }
19962
20029
  async function withGoalDiscussion(action, save3 = false) {
19963
20030
  const d2 = await discussion();
19964
- const dir = fs72.mkdtempSync(path73.join(os6.tmpdir(), "akb-goals-"));
19965
- const file2 = path73.join(dir, "goals.json");
20031
+ const dir = fs73.mkdtempSync(path74.join(os6.tmpdir(), "akb-goals-"));
20032
+ const file2 = path74.join(dir, "goals.json");
19966
20033
  const before = process.env.KANBAN_GOALS;
19967
20034
  try {
19968
20035
  const previous = goalsOf(d2);
19969
- fs72.writeFileSync(file2, JSON.stringify({ workspace: d2.workspace, studios: await studios2(d2.workspace), ideas: previous.map((g3) => ({ ...g3, task: typeof g3.task === "object" && g3.task ? g3.task.id : g3.task })) }));
20036
+ fs73.writeFileSync(file2, JSON.stringify({ workspace: d2.workspace, studios: await studios2(d2.workspace), ideas: previous.map((g3) => ({ ...g3, task: typeof g3.task === "object" && g3.task ? g3.task.id : g3.task })) }));
19970
20037
  process.env.KANBAN_GOALS = file2;
19971
20038
  const result = save3 ? await quietlyAsync(async () => action()) : await action();
19972
20039
  if (save3) {
19973
- const goals = JSON.parse(fs72.readFileSync(file2, "utf8")).ideas;
20040
+ const goals = JSON.parse(fs73.readFileSync(file2, "utf8")).ideas;
19974
20041
  const saved = await request("PUT", `/v1/discussions/${d2.id}/draft`, { expectedVersion: d2.version, goals: goals.filter((g3) => !g3.dropped) });
19975
20042
  const savedGoals = goalsOf(saved);
19976
20043
  const fresh = goals.filter((g3) => !g3.dropped && !previous.some((p2) => p2.id === g3.id));
@@ -19989,7 +20056,7 @@ async function withGoalDiscussion(action, save3 = false) {
19989
20056
  } finally {
19990
20057
  if (before === void 0) delete process.env.KANBAN_GOALS;
19991
20058
  else process.env.KANBAN_GOALS = before;
19992
- fs72.rmSync(dir, { recursive: true, force: true });
20059
+ fs73.rmSync(dir, { recursive: true, force: true });
19993
20060
  }
19994
20061
  }
19995
20062
  async function queryPreviews(studio, workspace2) {
@@ -21138,8 +21205,8 @@ var require_command = __commonJS({
21138
21205
  "../cli/node_modules/commander/lib/command.js"(exports) {
21139
21206
  var EventEmitter = __require("node:events").EventEmitter;
21140
21207
  var childProcess = __require("node:child_process");
21141
- var path90 = __require("node:path");
21142
- var fs92 = __require("node:fs");
21208
+ var path91 = __require("node:path");
21209
+ var fs93 = __require("node:fs");
21143
21210
  var process2 = __require("node:process");
21144
21211
  var { Argument: Argument2, humanReadableArgName } = require_argument();
21145
21212
  var { CommanderError: CommanderError2 } = require_error();
@@ -22120,7 +22187,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
22120
22187
  * @param {string} subcommandName
22121
22188
  */
22122
22189
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
22123
- if (fs92.existsSync(executableFile)) return;
22190
+ if (fs93.existsSync(executableFile)) return;
22124
22191
  const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
22125
22192
  const executableMissing = `'${executableFile}' does not exist
22126
22193
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
@@ -22138,11 +22205,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
22138
22205
  let launchWithNode = false;
22139
22206
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
22140
22207
  function findFile(baseDir, baseName) {
22141
- const localBin = path90.resolve(baseDir, baseName);
22142
- if (fs92.existsSync(localBin)) return localBin;
22143
- if (sourceExt.includes(path90.extname(baseName))) return void 0;
22208
+ const localBin = path91.resolve(baseDir, baseName);
22209
+ if (fs93.existsSync(localBin)) return localBin;
22210
+ if (sourceExt.includes(path91.extname(baseName))) return void 0;
22144
22211
  const foundExt = sourceExt.find(
22145
- (ext) => fs92.existsSync(`${localBin}${ext}`)
22212
+ (ext) => fs93.existsSync(`${localBin}${ext}`)
22146
22213
  );
22147
22214
  if (foundExt) return `${localBin}${foundExt}`;
22148
22215
  return void 0;
@@ -22154,21 +22221,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
22154
22221
  if (this._scriptPath) {
22155
22222
  let resolvedScriptPath;
22156
22223
  try {
22157
- resolvedScriptPath = fs92.realpathSync(this._scriptPath);
22224
+ resolvedScriptPath = fs93.realpathSync(this._scriptPath);
22158
22225
  } catch {
22159
22226
  resolvedScriptPath = this._scriptPath;
22160
22227
  }
22161
- executableDir = path90.resolve(
22162
- path90.dirname(resolvedScriptPath),
22228
+ executableDir = path91.resolve(
22229
+ path91.dirname(resolvedScriptPath),
22163
22230
  executableDir
22164
22231
  );
22165
22232
  }
22166
22233
  if (executableDir) {
22167
22234
  let localFile = findFile(executableDir, executableFile);
22168
22235
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
22169
- const legacyName = path90.basename(
22236
+ const legacyName = path91.basename(
22170
22237
  this._scriptPath,
22171
- path90.extname(this._scriptPath)
22238
+ path91.extname(this._scriptPath)
22172
22239
  );
22173
22240
  if (legacyName !== this._name) {
22174
22241
  localFile = findFile(
@@ -22179,7 +22246,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
22179
22246
  }
22180
22247
  executableFile = localFile || executableFile;
22181
22248
  }
22182
- launchWithNode = sourceExt.includes(path90.extname(executableFile));
22249
+ launchWithNode = sourceExt.includes(path91.extname(executableFile));
22183
22250
  let proc;
22184
22251
  if (process2.platform !== "win32") {
22185
22252
  if (launchWithNode) {
@@ -23026,7 +23093,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
23026
23093
  * @return {Command}
23027
23094
  */
23028
23095
  nameFromFilename(filename) {
23029
- this._name = path90.basename(filename, path90.extname(filename));
23096
+ this._name = path91.basename(filename, path91.extname(filename));
23030
23097
  return this;
23031
23098
  }
23032
23099
  /**
@@ -23040,9 +23107,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
23040
23107
  * @param {string} [path]
23041
23108
  * @return {(string|null|Command)}
23042
23109
  */
23043
- executableDir(path91) {
23044
- if (path91 === void 0) return this._executableDir;
23045
- this._executableDir = path91;
23110
+ executableDir(path92) {
23111
+ if (path92 === void 0) return this._executableDir;
23112
+ this._executableDir = path92;
23046
23113
  return this;
23047
23114
  }
23048
23115
  /**
@@ -23339,11 +23406,11 @@ var init_esm = __esm({
23339
23406
  });
23340
23407
 
23341
23408
  // ../cli/src/lib/cloud/pointer.ts
23342
- import fs73 from "node:fs";
23343
- import path74 from "node:path";
23409
+ import fs74 from "node:fs";
23410
+ import path75 from "node:path";
23344
23411
  function hasRetiredPointer(root2) {
23345
23412
  try {
23346
- const held4 = JSON.parse(fs73.readFileSync(path74.join(root2, POINTER_FILE), "utf8"));
23413
+ const held4 = JSON.parse(fs74.readFileSync(path75.join(root2, POINTER_FILE), "utf8"));
23347
23414
  return typeof held4.workspace === "string" && held4.workspace.trim() !== "";
23348
23415
  } catch {
23349
23416
  return false;
@@ -23358,39 +23425,39 @@ var init_pointer = __esm({
23358
23425
  });
23359
23426
 
23360
23427
  // ../cli/src/lib/card-studio-backfill.ts
23361
- import fs74 from "node:fs";
23362
- import path75 from "node:path";
23428
+ import fs75 from "node:fs";
23429
+ import path76 from "node:path";
23363
23430
  function renameToStudio() {
23364
23431
  if (!KANBAN || !BOARD_STATE) return;
23365
- const mark = path75.join(BOARD_STATE, RENAMED);
23432
+ const mark = path76.join(BOARD_STATE, RENAMED);
23366
23433
  try {
23367
- if (fs74.existsSync(mark)) return;
23368
- for (const [from, to] of [[path75.join(KANBAN, "workflows"), STUDIOS], [path75.join(RULES, "workflows"), path75.join(RULES, "studios")]]) {
23369
- if (fs74.existsSync(from) && !fs74.existsSync(to)) fs74.renameSync(from, to);
23434
+ if (fs75.existsSync(mark)) return;
23435
+ for (const [from, to] of [[path76.join(KANBAN, "workflows"), STUDIOS], [path76.join(RULES, "workflows"), path76.join(RULES, "studios")]]) {
23436
+ if (fs75.existsSync(from) && !fs75.existsSync(to)) fs75.renameSync(from, to);
23370
23437
  }
23371
- for (const file2 of [STUDIOS, TODO, TRIAGE].flatMap((dir) => fs74.existsSync(dir) ? walkMd(dir) : [])) {
23372
- const at2 = path75.relative(KANBAN, file2).split(path75.sep).join("/");
23373
- const text5 = fs74.readFileSync(file2, "utf8");
23438
+ for (const file2 of [STUDIOS, TODO, TRIAGE].flatMap((dir) => fs75.existsSync(dir) ? walkMd(dir) : [])) {
23439
+ const at2 = path76.relative(KANBAN, file2).split(path76.sep).join("/");
23440
+ const text5 = fs75.readFileSync(file2, "utf8");
23374
23441
  const to = studioRenamed(at2, text5);
23375
23442
  if (to.path === at2 && to.content === text5) continue;
23376
- const target = path75.join(KANBAN, to.path);
23377
- if (target !== file2 && fs74.existsSync(target)) continue;
23378
- fs74.writeFileSync(target, to.content);
23379
- if (target !== file2) fs74.rmSync(file2);
23443
+ const target = path76.join(KANBAN, to.path);
23444
+ if (target !== file2 && fs75.existsSync(target)) continue;
23445
+ fs75.writeFileSync(target, to.content);
23446
+ if (target !== file2) fs75.rmSync(file2);
23380
23447
  }
23381
- fs74.mkdirSync(BOARD_STATE, { recursive: true });
23382
- fs74.writeFileSync(mark, "");
23448
+ fs75.mkdirSync(BOARD_STATE, { recursive: true });
23449
+ fs75.writeFileSync(mark, "");
23383
23450
  } catch {
23384
23451
  }
23385
23452
  }
23386
23453
  function backfillCardStudios() {
23387
23454
  renameToStudio();
23388
23455
  if (!TODO || !BOARD_STATE) return;
23389
- const mark = path75.join(BOARD_STATE, MARK);
23456
+ const mark = path76.join(BOARD_STATE, MARK);
23390
23457
  try {
23391
- if (fs74.existsSync(mark) || !fs74.existsSync(TODO)) return;
23458
+ if (fs75.existsSync(mark) || !fs75.existsSync(TODO)) return;
23392
23459
  for (const file2 of walkMd(TODO)) {
23393
- const text5 = fs74.readFileSync(file2, "utf8");
23460
+ const text5 = fs75.readFileSync(file2, "utf8");
23394
23461
  if (!text5.startsWith("---\n")) continue;
23395
23462
  const end2 = text5.indexOf("\n---", 3);
23396
23463
  if (end2 < 0) continue;
@@ -23398,11 +23465,11 @@ function backfillCardStudios() {
23398
23465
  if (!/\ntitle:/.test(head2) || /\nstudio:/.test(head2)) continue;
23399
23466
  const modules = /\nmodules:[^\n]*/.exec(head2);
23400
23467
  const at2 = modules ? modules.index + modules[0].length : end2;
23401
- fs74.writeFileSync(file2, `${text5.slice(0, at2)}
23468
+ fs75.writeFileSync(file2, `${text5.slice(0, at2)}
23402
23469
  studio: coding${text5.slice(at2)}`);
23403
23470
  }
23404
- fs74.mkdirSync(BOARD_STATE, { recursive: true });
23405
- fs74.writeFileSync(mark, "");
23471
+ fs75.mkdirSync(BOARD_STATE, { recursive: true });
23472
+ fs75.writeFileSync(mark, "");
23406
23473
  } catch {
23407
23474
  }
23408
23475
  }
@@ -23439,8 +23506,8 @@ var init_created_cards = __esm({
23439
23506
 
23440
23507
  // ../cli/src/lib/agent/creation.ts
23441
23508
  import crypto4 from "node:crypto";
23442
- import fs75 from "node:fs";
23443
- import path76 from "node:path";
23509
+ import fs76 from "node:fs";
23510
+ import path77 from "node:path";
23444
23511
  function creationError(error, triage) {
23445
23512
  const zh = readLanguage() === "zh";
23446
23513
  const messages = {
@@ -23466,12 +23533,12 @@ ${zh ? `\u539F\u6761\u76EE\u4ECD\u5728 triage\uFF1A${triage}\u3002${unreachable
23466
23533
  function creationReceipt(request2, slot) {
23467
23534
  const hash2 = crypto4.createHash("sha256").update(`${request2}
23468
23535
  ${slot}`).digest("hex");
23469
- return path76.join(projectStateDir(KANBAN, REPO_ROOT), "creations", `${hash2}.json`);
23536
+ return path77.join(projectStateDir(KANBAN, REPO_ROOT), "creations", `${hash2}.json`);
23470
23537
  }
23471
23538
  function readCreation(file2, said2) {
23472
23539
  return withCreationLock(() => {
23473
23540
  try {
23474
- const held4 = JSON.parse(fs75.readFileSync(file2, "utf8"));
23541
+ const held4 = JSON.parse(fs76.readFileSync(file2, "utf8"));
23475
23542
  if (!held4.said || typeof held4.said.title !== "string") throw new Error("Invalid creation journal");
23476
23543
  return held4;
23477
23544
  } catch (error) {
@@ -23483,10 +23550,10 @@ function readCreation(file2, said2) {
23483
23550
  });
23484
23551
  }
23485
23552
  function saveCreation(file2, journal) {
23486
- fs75.mkdirSync(path76.dirname(file2), { recursive: true });
23553
+ fs76.mkdirSync(path77.dirname(file2), { recursive: true });
23487
23554
  const temp = `${file2}.${crypto4.randomUUID()}.tmp`;
23488
- fs75.writeFileSync(temp, JSON.stringify(journal));
23489
- fs75.renameSync(temp, file2);
23555
+ fs76.writeFileSync(temp, JSON.stringify(journal));
23556
+ fs76.renameSync(temp, file2);
23490
23557
  }
23491
23558
  function archiveCreation(source2, id) {
23492
23559
  if (readArchived().some((s) => s.sourceId === source2 && s.cardId === id)) return;
@@ -23500,7 +23567,7 @@ function archiveCreation(source2, id) {
23500
23567
  function triageFile(sourceId) {
23501
23568
  const found2 = [...readInbox(), ...readAllDismissed(), ...readArchived()].find((s) => s.sourceId === sourceId.trim());
23502
23569
  if (!found2) throw new BoardError(`nothing in triage is ${sourceId}`, { kind: "refused" });
23503
- return path76.basename(found2.relPath, ".md");
23570
+ return path77.basename(found2.relPath, ".md");
23504
23571
  }
23505
23572
  var init_creation = __esm({
23506
23573
  "../cli/src/lib/agent/creation.ts"() {
@@ -23668,14 +23735,14 @@ __export(board_exports, {
23668
23735
  buildBoardProgram: () => buildBoardProgram
23669
23736
  });
23670
23737
  import crypto5 from "node:crypto";
23671
- import fs76 from "node:fs";
23672
- import path77 from "node:path";
23738
+ import fs77 from "node:fs";
23739
+ import path78 from "node:path";
23673
23740
  async function dispatch(move, cmd, args2, opts, cli) {
23674
23741
  const ctx = ctxOf(cmd, cli.program);
23675
23742
  const data = await runAction(ctx, {}, async () => {
23676
23743
  const found2 = resolveBoard(move, { board: ctx.board, dir: ctx.dir, cwd: cli.cwd, installHint: cli.installHint });
23677
- useBoard(found2, ctx.dir !== null);
23678
- await syncStudios();
23744
+ useBoard(found2, ctx.dir !== null, move === "inspect");
23745
+ if (move !== "inspect") await syncStudios();
23679
23746
  const root2 = found2.root;
23680
23747
  sayIfRetiredPointer(root2);
23681
23748
  const creating = move === "create" && insideRun() ? peekRun(insideRun()) : void 0;
@@ -23709,7 +23776,7 @@ async function cloudCard(task, opts) {
23709
23776
  let request2;
23710
23777
  if (typeof opts.bodyFile === "string") {
23711
23778
  try {
23712
- request2 = fs76.readFileSync(opts.bodyFile, "utf8");
23779
+ request2 = fs77.readFileSync(opts.bodyFile, "utf8");
23713
23780
  } catch {
23714
23781
  }
23715
23782
  }
@@ -23739,7 +23806,7 @@ async function cloudCard(task, opts) {
23739
23806
  const file2 = creationReceipt(`${checked.value}:${requestId}`, slot);
23740
23807
  const journal = readCreation(file2, said2);
23741
23808
  if (!journal.made) {
23742
- const key = `akb-${path77.basename(file2, ".json").slice(0, 40)}`;
23809
+ const key = `akb-${path78.basename(file2, ".json").slice(0, 40)}`;
23743
23810
  const made = await createProjectTask(checked.value, journal.said, key);
23744
23811
  if (!made.ok) throw new BoardError(creationError(`Cloud did not make the task: ${made.error}`, triage), { kind: "refused" });
23745
23812
  journal.made = made.value;
@@ -23786,6 +23853,9 @@ function buildBoardProgram(cli) {
23786
23853
  ).option("--append <text>", "add one question to the end", opInOrder("append")).option("--update <n> <text...>", "rewrite question <n> whole", opInOrder("update")).option("--drop <positions>", "remove answered questions, e.g. 1 or 1,3", opInOrder("drop")).option("--clear", "remove every open question", opInOrder("clear")).option("--option <text>", "a choice for the op before it", opInOrder("option")).option("--recommended-option <text>", "a choice for the op before it, ticked to start", opInOrder("recommended-option")).option("--mode <mode>", "how many choices the op before it takes: single | multi", opInOrder("mode")).option("--agent <name>", "the preview agent whose section the op before it is about", opInOrder("agent")).action(async function(id) {
23787
23854
  await dispatch("update-questions", this, [String(id)], { ops: questionOps }, cli);
23788
23855
  });
23856
+ move("inspect").argument("<id>", ID, cardId).summary("read task facts, saved work and execution references").action(async function(id) {
23857
+ await dispatch("inspect", this, [String(id)], this.opts(), cli);
23858
+ });
23789
23859
  move("validate").argument("[id]", ID, cardId).summary("validate card format and report file, line, and repair instructions").description("Check one card, or every open card when no id is given. Reads only; exits non-zero with detailed errors until the format is valid.").action(async function(id) {
23790
23860
  await dispatch("validate", this, id === void 0 ? [] : [String(id)], this.opts(), cli);
23791
23861
  });
@@ -23868,17 +23938,19 @@ var init_board2 = __esm({
23868
23938
  });
23869
23939
 
23870
23940
  // ../cli/src/lib/board-cli.ts
23871
- import fs77 from "node:fs";
23872
- import path78 from "node:path";
23873
- function useBoard(found2, dirNamed) {
23874
- if (!found2.named && found2.board === path78.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23941
+ import fs78 from "node:fs";
23942
+ import path79 from "node:path";
23943
+ function useBoard(found2, dirNamed, readOnly = false) {
23944
+ if (!found2.named && found2.board === path79.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23875
23945
  else setBoardDir(found2.board, found2.root);
23876
- useProjectState();
23877
- backfillCardStudios();
23946
+ if (!readOnly) {
23947
+ useProjectState();
23948
+ backfillCardStudios();
23949
+ }
23878
23950
  }
23879
23951
  function whole(found2, move) {
23880
23952
  if (move === MAKES_A_BOARD) return found2;
23881
- if (!fs77.existsSync(path78.join(found2.board, "todo"))) {
23953
+ if (!fs78.existsSync(path79.join(found2.board, "todo"))) {
23882
23954
  die(`the board in ${found2.board} has no todo/ \u2014 run \`init\` to add what is missing.`, {
23883
23955
  kind: "board-incomplete",
23884
23956
  dir: found2.root
@@ -23887,13 +23959,13 @@ function whole(found2, move) {
23887
23959
  return found2;
23888
23960
  }
23889
23961
  function findBoardUpward(from, move) {
23890
- let dir = path78.resolve(from);
23962
+ let dir = path79.resolve(from);
23891
23963
  for (; ; ) {
23892
- if (hasBoard(dir)) return { root: dir, board: path78.join(dir, "docs", "kanban") };
23964
+ if (hasBoard(dir)) return { root: dir, board: path79.join(dir, "docs", "kanban") };
23893
23965
  if (isBoardDir(dir)) return { root: projectRootOf(dir), board: dir };
23894
- const kept2 = path78.join(dir, ".akb", "kanban");
23895
- if (move !== MAKES_A_BOARD && fs77.existsSync(path78.join(kept2, "todo"))) return { root: dir, board: kept2 };
23896
- const up = path78.dirname(dir);
23966
+ const kept2 = path79.join(dir, ".akb", "kanban");
23967
+ if (move !== MAKES_A_BOARD && fs78.existsSync(path79.join(kept2, "todo"))) return { root: dir, board: kept2 };
23968
+ const up = path79.dirname(dir);
23897
23969
  if (up === dir) return null;
23898
23970
  dir = up;
23899
23971
  }
@@ -23901,11 +23973,11 @@ function findBoardUpward(from, move) {
23901
23973
  function resolveBoard(move, { board: board2, dir, cwd, installHint }) {
23902
23974
  const named2 = board2 ?? boardFromEnv();
23903
23975
  if (named2) {
23904
- const folder = path78.resolve(cwd, named2);
23905
- if (!fs77.existsSync(folder) && move !== MAKES_A_BOARD) {
23976
+ const folder = path79.resolve(cwd, named2);
23977
+ if (!fs78.existsSync(folder) && move !== MAKES_A_BOARD) {
23906
23978
  die(`no such folder: ${folder}`, { kind: "no-such-folder", dir: folder });
23907
23979
  }
23908
- if (fs77.existsSync(folder) && !isBoardDir(folder) && move !== MAKES_A_BOARD) {
23980
+ if (fs78.existsSync(folder) && !isBoardDir(folder) && move !== MAKES_A_BOARD) {
23909
23981
  die(`${folder} is not a board \u2014 it has no todo/ and config.md. ${installHint}\u3002`, {
23910
23982
  kind: "no-board",
23911
23983
  dir: folder
@@ -23914,24 +23986,24 @@ function resolveBoard(move, { board: board2, dir, cwd, installHint }) {
23914
23986
  return { root: projectRootOf(folder), board: folder, named: true };
23915
23987
  }
23916
23988
  if (dir !== null) {
23917
- const root2 = path78.resolve(dir);
23918
- if (!fs77.existsSync(root2)) die(`no such folder: ${root2}`, { kind: "no-such-folder", dir: root2 });
23919
- const kept2 = path78.join(root2, ".akb", "kanban");
23920
- if (!hasBoard(root2) && move !== MAKES_A_BOARD && fs77.existsSync(path78.join(kept2, "todo"))) return whole({ root: root2, board: kept2 }, move);
23989
+ const root2 = path79.resolve(dir);
23990
+ if (!fs78.existsSync(root2)) die(`no such folder: ${root2}`, { kind: "no-such-folder", dir: root2 });
23991
+ const kept2 = path79.join(root2, ".akb", "kanban");
23992
+ if (!hasBoard(root2) && move !== MAKES_A_BOARD && fs78.existsSync(path79.join(kept2, "todo"))) return whole({ root: root2, board: kept2 }, move);
23921
23993
  if (!hasBoard(root2) && move !== MAKES_A_BOARD) {
23922
23994
  die(`no board in ${root2} \u2014 it has no docs/kanban/. ${installHint}\u3002`, {
23923
23995
  kind: "no-board",
23924
23996
  dir: root2
23925
23997
  });
23926
23998
  }
23927
- return whole({ root: root2, board: path78.join(root2, "docs", "kanban") }, move);
23999
+ return whole({ root: root2, board: path79.join(root2, "docs", "kanban") }, move);
23928
24000
  }
23929
24001
  const found2 = findBoardUpward(cwd, move);
23930
24002
  if (found2) return whole(found2, move);
23931
- if (move === MAKES_A_BOARD) return { root: path78.resolve(cwd), board: path78.join(path78.resolve(cwd), "docs", "kanban") };
24003
+ if (move === MAKES_A_BOARD) return { root: path79.resolve(cwd), board: path79.join(path79.resolve(cwd), "docs", "kanban") };
23932
24004
  die(
23933
- `no board here. Looked in ${path78.resolve(cwd)} and every folder above it for docs/kanban/. ${installHint}\uFF0C\u6216\u7528 --board \u6307\u5B9A\u5DF2\u6709\u770B\u677F\u3002`,
23934
- { kind: "no-board", dir: path78.resolve(cwd) }
24005
+ `no board here. Looked in ${path79.resolve(cwd)} and every folder above it for docs/kanban/. ${installHint}\uFF0C\u6216\u7528 --board \u6307\u5B9A\u5DF2\u6709\u770B\u677F\u3002`,
24006
+ { kind: "no-board", dir: path79.resolve(cwd) }
23935
24007
  );
23936
24008
  }
23937
24009
  function editDistance(a2, b2) {
@@ -24014,8 +24086,8 @@ var init_board_cli = __esm({
24014
24086
  init_pointer();
24015
24087
  init_card_studio_backfill();
24016
24088
  MAKES_A_BOARD = "init";
24017
- hasBoard = (dir) => fs77.existsSync(path78.join(dir, "docs", "kanban"));
24018
- isBoardDir = (dir) => fs77.existsSync(path78.join(dir, "todo")) && fs77.existsSync(path78.join(dir, "config.md"));
24089
+ hasBoard = (dir) => fs78.existsSync(path79.join(dir, "docs", "kanban"));
24090
+ isBoardDir = (dir) => fs78.existsSync(path79.join(dir, "todo")) && fs78.existsSync(path79.join(dir, "config.md"));
24019
24091
  boardFromEnv = () => {
24020
24092
  const named2 = process.env.AI4KANBAN_BOARD?.trim();
24021
24093
  return named2 ? named2 : null;
@@ -24032,30 +24104,14 @@ var init_manual = __esm({
24032
24104
  /** Under every flow: print it, or run it. The one choice each of them has. */
24033
24105
  flow: `
24034
24106
  Print it, or run it
24035
- --print say what to do and start nothing. What it prints is filled in for this board:
24107
+ --print print the flow to follow in the current session, filled in for this board:
24036
24108
  the card's own path, the steps it has left, the memory file its modules point
24037
24109
  at, the flows the job is done by in full, and the
24038
24110
  command that closes the job \u2014 because nothing is watching you finish.
24039
- (no flag) start a run: a second agent, its own context, working on its own.
24040
-
24041
- Print when the user is asking you for the action here, in a session. You do the job in the
24042
- conversation you are already in: it costs no second agent and can't collide with the
24043
- changes already in the working tree.
24044
-
24045
- Start a run when the user wants the work to happen on its own \u2014 in the background, while
24046
- they do something else, on a card they are not watching. That is the explicit ask. It also
24047
- wins on long read-heavy jobs that need nothing from the conversation.
24048
-
24049
- Some jobs are better done by the agent that was there. It just built the card, so it knows
24050
- which steps it really did; a fresh agent sees unticked boxes and works the rest out from
24051
- the diff.
24052
-
24053
- When it is not clear which was meant, print. A printed flow costs nothing and can still be
24054
- followed by starting a run; a started run costs a second agent, a second context, and money
24055
- nobody asked to spend.
24111
+ (no flag) start a separate session with its own context.
24056
24112
 
24057
- One caller does not choose: an agent already working inside a run the board started always
24058
- prints, because a run never starts another.
24113
+ Choose either mode for preview work. Other board actions inside a board run print their
24114
+ flows; preview requests can queue a separate session.
24059
24115
  `,
24060
24116
  /** Under `delivery`: what one is, which no verb of it says on its own. */
24061
24117
  deliveries: (program2) => `
@@ -24275,8 +24331,8 @@ var init_agent = __esm({
24275
24331
 
24276
24332
  // ../cli/src/commands/cloud-template.ts
24277
24333
  import { createHash as createHash8 } from "node:crypto";
24278
- import fs78 from "node:fs";
24279
- import path79 from "node:path";
24334
+ import fs79 from "node:fs";
24335
+ import path80 from "node:path";
24280
24336
  function usage2(problem, line) {
24281
24337
  die(`${problem}
24282
24338
  usage: ${line}`, { kind: "bad-args", bare: true, exitCode: 2 });
@@ -24353,10 +24409,10 @@ This template has no preview.`);
24353
24409
  const written = [];
24354
24410
  for (const p2 of previews) {
24355
24411
  const bytes2 = Buffer.from(await (await ask(`/${at2}/previews/${route(p2.path)}`, {}, WITHOUT)).arrayBuffer());
24356
- const file2 = path79.basename(p2.path);
24357
- const out = path79.join(opts.to, file2.startsWith(`${name}-`) ? file2 : `${name}-${file2}`);
24358
- fs78.mkdirSync(opts.to, { recursive: true });
24359
- fs78.writeFileSync(out, bytes2);
24412
+ const file2 = path80.basename(p2.path);
24413
+ const out = path80.join(opts.to, file2.startsWith(`${name}-`) ? file2 : `${name}-${file2}`);
24414
+ fs79.mkdirSync(opts.to, { recursive: true });
24415
+ fs79.writeFileSync(out, bytes2);
24360
24416
  written.push(out);
24361
24417
  say(out);
24362
24418
  }
@@ -24369,15 +24425,15 @@ async function templateGet(name, opts, program2) {
24369
24425
  const { template } = await asJson(await ask(`/${at2}`, {}, WITHOUT));
24370
24426
  const fetched = [];
24371
24427
  for (const f2 of template.files) {
24372
- const out = path79.resolve(to, f2.path);
24373
- if (!out.startsWith(path79.resolve(to) + path79.sep)) refuse3(T.corrupt, WITHOUT);
24428
+ const out = path80.resolve(to, f2.path);
24429
+ if (!out.startsWith(path80.resolve(to) + path80.sep)) refuse3(T.corrupt, WITHOUT);
24374
24430
  const bytes2 = Buffer.from(await (await ask(`/${at2}/files/${route(f2.path)}`, {}, WITHOUT)).arrayBuffer());
24375
24431
  if (bytes2.byteLength !== f2.size || createHash8("sha256").update(bytes2).digest("hex") !== f2.sha256) {
24376
24432
  refuse3(T.corrupt, WITHOUT);
24377
24433
  }
24378
24434
  fetched.push({ out, bytes: bytes2 });
24379
24435
  }
24380
- const taken = fetched.filter((f2) => fs78.existsSync(f2.out)).map((f2) => path79.relative(to, f2.out));
24436
+ const taken = fetched.filter((f2) => fs79.existsSync(f2.out)).map((f2) => path80.relative(to, f2.out));
24381
24437
  if (taken.length > 0) {
24382
24438
  refuse3({
24383
24439
  zh: `\u76EE\u6807\u6587\u4EF6\u5939\u5DF2\u6709\u540C\u540D\u6587\u4EF6\uFF1A${taken.join("\u3001")}\u3002\u8BF7\u6362\u4E00\u4E2A\u6587\u4EF6\u5939\uFF0C\u6216\u5148\u79FB\u8D70\u8FD9\u4E9B\u6587\u4EF6\u3002`,
@@ -24385,8 +24441,8 @@ async function templateGet(name, opts, program2) {
24385
24441
  });
24386
24442
  }
24387
24443
  for (const f2 of fetched) {
24388
- fs78.mkdirSync(path79.dirname(f2.out), { recursive: true });
24389
- fs78.writeFileSync(f2.out, f2.bytes);
24444
+ fs79.mkdirSync(path80.dirname(f2.out), { recursive: true });
24445
+ fs79.writeFileSync(f2.out, f2.bytes);
24390
24446
  }
24391
24447
  say(`\u5DF2\u53D6\u56DE ${name}\uFF1A${fetched.length} \u4E2A\u6587\u4EF6\uFF0C\u4F4D\u4E8E ${to}
24392
24448
  Fetched ${name}: ${fetched.length} files into ${to}`);
@@ -24403,25 +24459,25 @@ async function templateSource(name, opts) {
24403
24459
  say(`evidence: ${e2.path}`);
24404
24460
  continue;
24405
24461
  }
24406
- const out = path79.join(opts.to, `${name}-${path79.basename(e2.path)}`);
24407
- fs78.mkdirSync(opts.to, { recursive: true });
24408
- fs78.writeFileSync(out, Buffer.from(await (await ask(`/${at2}/evidence/${route(e2.path)}`)).arrayBuffer()));
24462
+ const out = path80.join(opts.to, `${name}-${path80.basename(e2.path)}`);
24463
+ fs79.mkdirSync(opts.to, { recursive: true });
24464
+ fs79.writeFileSync(out, Buffer.from(await (await ask(`/${at2}/evidence/${route(e2.path)}`)).arrayBuffer()));
24409
24465
  written.push(out);
24410
24466
  say(out);
24411
24467
  }
24412
24468
  return { name, source: source2, evidence: written.length > 0 ? written : evidence.map((e2) => e2.path) };
24413
24469
  }
24414
24470
  async function templatePublish(dir, opts) {
24415
- const root2 = path79.resolve(dir);
24416
- const manifest = path79.join(root2, "template.md");
24417
- if (!fs78.existsSync(manifest)) invalid("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
24418
- const meta = readTemplateMeta(fs78.readFileSync(manifest, "utf8"));
24471
+ const root2 = path80.resolve(dir);
24472
+ const manifest = path80.join(root2, "template.md");
24473
+ if (!fs79.existsSync(manifest)) invalid("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
24474
+ const meta = readTemplateMeta(fs79.readFileSync(manifest, "utf8"));
24419
24475
  const files = walk2(root2);
24420
- const total = files.reduce((sum, f2) => sum + fs78.statSync(path79.join(root2, f2)).size, 0);
24476
+ const total = files.reduce((sum, f2) => sum + fs79.statSync(path80.join(root2, f2)).size, 0);
24421
24477
  if (total > MAX_BYTES3) invalid("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
24422
24478
  for (const extra of [...opts.preview, ...opts.evidence]) {
24423
- if (!fs78.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
24424
- if (path79.resolve(extra).startsWith(root2 + path79.sep)) {
24479
+ if (!fs79.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
24480
+ if (path80.resolve(extra).startsWith(root2 + path80.sep)) {
24425
24481
  invalid(
24426
24482
  `${extra} \u5728\u6A21\u677F\u6587\u4EF6\u5939\u5185\uFF1B\u9884\u89C8\u56FE\u4E0E\u6765\u6E90\u51ED\u8BC1\u9700\u653E\u5728\u6A21\u677F\u6587\u4EF6\u5939\u4E4B\u5916\u3002`,
24427
24483
  `${extra} is inside the template folder; keep previews and evidence outside it.`
@@ -24433,10 +24489,10 @@ async function templatePublish(dir, opts) {
24433
24489
  }
24434
24490
  const form = new FormData();
24435
24491
  form.set("meta", JSON.stringify({ ...meta, replace: !!opts.replace }));
24436
- const add2 = (kind, name, file2) => form.append(`${kind}:${name}`, new Blob([fs78.readFileSync(file2)]), path79.basename(name));
24437
- for (const f2 of files) add2("files", f2, path79.join(root2, f2));
24438
- for (const f2 of opts.preview) add2("previews", path79.basename(f2), f2);
24439
- for (const f2 of opts.evidence) add2("evidence", path79.basename(f2), f2);
24492
+ const add2 = (kind, name, file2) => form.append(`${kind}:${name}`, new Blob([fs79.readFileSync(file2)]), path80.basename(name));
24493
+ for (const f2 of files) add2("files", f2, path80.join(root2, f2));
24494
+ for (const f2 of opts.preview) add2("previews", path80.basename(f2), f2);
24495
+ for (const f2 of opts.evidence) add2("evidence", path80.basename(f2), f2);
24440
24496
  const done = await asJson(await ask("", { method: "POST", body: form }));
24441
24497
  say(
24442
24498
  done.replaced ? `\u5DF2\u66FF\u6362 ${done.name}\uFF1A${files.length} \u4E2A\u6587\u4EF6\u3002
@@ -24452,11 +24508,11 @@ Deleted ${name} from the catalog.`);
24452
24508
  return { name, deleted: true };
24453
24509
  }
24454
24510
  async function templateShowcase(name, dir) {
24455
- const file2 = path79.join(dir, "showcase.json");
24456
- if (!fs78.existsSync(file2)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
24511
+ const file2 = path80.join(dir, "showcase.json");
24512
+ if (!fs79.existsSync(file2)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
24457
24513
  let meta;
24458
24514
  try {
24459
- meta = JSON.parse(fs78.readFileSync(file2, "utf8"));
24515
+ meta = JSON.parse(fs79.readFileSync(file2, "utf8"));
24460
24516
  } catch {
24461
24517
  return invalid("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
24462
24518
  }
@@ -24468,9 +24524,9 @@ async function templateShowcase(name, dir) {
24468
24524
  const form = new FormData();
24469
24525
  form.set("meta", JSON.stringify(meta));
24470
24526
  for (const p2 of new Set(named2)) {
24471
- const at2 = path79.join(dir, p2);
24472
- if (!fs78.existsSync(at2)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at2}\u3002`, `${at2} does not exist.`);
24473
- form.append(`media:${p2}`, new Blob([fs78.readFileSync(at2)]), p2);
24527
+ const at2 = path80.join(dir, p2);
24528
+ if (!fs79.existsSync(at2)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at2}\u3002`, `${at2} does not exist.`);
24529
+ form.append(`media:${p2}`, new Blob([fs79.readFileSync(at2)]), p2);
24474
24530
  }
24475
24531
  const done = await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form }));
24476
24532
  say(`\u5DF2\u66F4\u65B0 ${name} \u7684\u5C55\u793A\u8D44\u6599\uFF1A${done.files} \u4E2A\u6587\u4EF6\u3002
@@ -24479,7 +24535,7 @@ Updated ${name}'s showcase: ${done.files} files.`);
24479
24535
  }
24480
24536
  function walk2(root2, sub = "") {
24481
24537
  const out = [];
24482
- for (const entry of fs78.readdirSync(path79.join(root2, sub), { withFileTypes: true })) {
24538
+ for (const entry of fs79.readdirSync(path80.join(root2, sub), { withFileTypes: true })) {
24483
24539
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
24484
24540
  const rel2 = sub ? `${sub}/${entry.name}` : entry.name;
24485
24541
  if (entry.isDirectory()) out.push(...walk2(root2, rel2));
@@ -24672,7 +24728,7 @@ var init_board3 = __esm({
24672
24728
  var card_chat_default;
24673
24729
  var init_card_chat = __esm({
24674
24730
  "../cli/src/guide/card-chat.md"() {
24675
- card_chat_default = '# Answer a card\'s conversation\n\nWork on the current card and its assets by default. Project implementation requires approval on the review page.\n\n- **Where the task stands**: read it with `akb task show <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Choose a preview agent**: when a preview is needed and the agent is unclear, use `akb raw previews --triggers` to match the work to an agent.\n- **Create or revise a preview**: when the user asks to see or change a preview for the current card, use `akb raw previews <agent> <id> --print`; never write Preview Components tags by hand.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a studio**: use `akb guide update-studio` for shared studio or agent changes; a correction to this card\'s draft alone stays on this card.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n\n- **Start this task**: when the user explicitly asks to start, implement or approve it, use `akb task approve` or `akb raw card approve/implement`. In a task reply these register one approval for after the reply finishes and syncs. Pending means accepted, not started; finish the reply and do not wait or edit the card again. Preview approvals still apply.\n';
24731
+ card_chat_default = '# Answer a card\'s conversation\n\nWork on the current card and its assets by default. Project implementation requires approval on the review page.\n\n- **Where the task stands**: read it with `akb task show <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Choose a preview agent**: when a preview is needed and the agent is unclear, use `akb raw previews --triggers` to match the work to an agent.\n- **Create or revise a preview**: when the user asks to see or change a preview for the current card,\n use `akb raw previews <agent> <id>`; choose `--print` for this session or omit it for a separate\n session. The agent carrying out that role writes and maintains its section and Preview Components.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a studio**: use `akb guide update-studio` for shared studio or agent changes; a correction to this card\'s draft alone stays on this card.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n\n- **Start this task**: when the user explicitly asks to start, implement or approve it, use `akb task approve` or `akb raw card approve/implement`. In a task reply these register one approval for after the reply finishes and syncs. Pending means accepted, not started; finish the reply and do not wait or edit the card again. Preview approvals still apply.\n';
24676
24732
  }
24677
24733
  });
24678
24734
 
@@ -24712,7 +24768,7 @@ var init_follow_up = __esm({
24712
24768
  var implement_default;
24713
24769
  var init_implement = __esm({
24714
24770
  "../cli/src/guide/implement.md"() {
24715
- implement_default = "# Implement the approved requirements\n\nBuild the approved card or plan directly. Preserve settled decisions and unrelated questions;\ndo not replace or contradict the approved requirements. With no card, build only the given\nrequirement and create no card.\n\n- **Check applicability**: use the working directory, project instructions, configuration\n sources and change history as evidence; missing configuration alone does not make a check\n inapplicable. Explain any inapplicable check and its alternative verification; never report\n an unrun or failing check as passed. Do not bypass checks with empty configuration, disabled\n checks or lower standards.\n- **Authorization**: approval covers the necessary operations within the agreed scope and\n constraints; carry it across commands, tools and stages without repeated confirmation.\n- **User-action blockers**: resolve routine choices and problems yourself; ask only when\n reasonable investigation leaves a blocker requiring user action or a decision beyond the\n approved scope. On a card, use `akb guide update-questions`, stating what you tried, what\n is blocked and your recommendation; continue independent work.\n- **Defer what can wait**: follow `akb guide follow-up` for work this build does not require;\n never ask about it or let it block this build.\n- **Decisions made while building**: record an answered material decision the user could\n reasonably reverse under `## Worth noting after implementation` on the card.\n- **Resume**: inspect the existing result and the unchecked todos, carry completed steps\n forward, and finish the remaining todos before recording completion.\n";
24771
+ implement_default = "# Implement the approved requirements\n\nBuild the approved card or plan directly. Preserve settled decisions and unrelated questions;\ndo not replace or contradict the approved requirements. With no card, build only the given\nrequirement and create no card.\n\n- **Authorization**: approval covers the necessary operations within the agreed scope and\n constraints; carry it across commands, tools and stages without repeated confirmation.\n- **User-action blockers**: resolve routine choices and problems yourself; ask only when\n reasonable investigation leaves a blocker requiring user action or a decision beyond the\n approved scope. On a card, use `akb guide update-questions`, stating what you tried, what\n is blocked and your recommendation; continue independent work.\n- **Defer what can wait**: follow `akb guide follow-up` for work this build does not require;\n never ask about it or let it block this build.\n- **Decisions made while building**: record an answered material decision the user could\n reasonably reverse under `## Worth noting after implementation` on the card.\n";
24716
24772
  }
24717
24773
  });
24718
24774
 
@@ -24752,7 +24808,7 @@ var init_review_rejections = __esm({
24752
24808
  var refine_default;
24753
24809
  var init_refine = __esm({
24754
24810
  "../cli/src/guide/refine.md"() {
24755
- refine_default = "# Refine a card\n\nPlan one card in this session until it can be built.\n\n- **Unchecked card**: a card with `triage:` set and an empty `## Scope` was never checked\n against the project. Check it first; when the project already does\n the work, or what it concerns no longer exists, run\n `akb raw reject <id> --reason \"<what shows it>\"` and stop.\n- **Gone or already done**: for any other card, append a question asking the user whether to\n discard it, run no preview agent, and stop.\n- **Existing group**: read its subtasks and check that they cover the parent\u2019s outcome;\n keep a complete split, or fill gaps by updating subtasks and dependencies without\n duplicating work or resetting progress. Finish the pass without marking the parent\n ready merely because its split is complete; its completion still follows its subtasks.\n- **Studio rules**: write the card as the studio rules at the end of this prompt say.\n- **Preview agents**: an agent's `After` names the previews it waits for; the board approves\n previews in stages, one stage per Approve, and the card's `previews` were chosen when its\n goal was written. A card without `previews` has not chosen: choose and save them first, as\n the list says, then run only its first stage. Run each agent the list above names whose\n section is missing or outdated with `akb raw previews <agent> <id> --print`, one at a time in this\n session; leave out `--print` only for an agent the list says runs in a session of its own.\n- **Stale mentions**: rewrite any sentence that relies on a card no longer on the board.\n- **Questions**: settle every decision you can and record the answers as `akb guide writing`\n says; ask only what `akb guide update-questions` says to ask.\n- **Write**: shape the card as `akb guide writing` says, then run `akb raw validate <id>` and\n fix every reported line.\n- **Ready**: settle every fact from the project and authoritative sources. Once the card\n validates, judge whether it can be built as written, or before its last Approve: if so, run\n `akb raw update <id> --status ready`; otherwise leave what blocks it as an open question.\n\nFollow any closing steps the flow printed, then stop: the user approves the previews or starts\nthe build.\n";
24811
+ refine_default = "# Refine a card\n\nPlan one card until it can be built.\n\n- **Unchecked card**: a card with `triage:` set and an empty `## Scope` was never checked\n against the project. Check it first; when the project already does\n the work, or what it concerns no longer exists, run\n `akb raw reject <id> --reason \"<what shows it>\"` and stop.\n- **Gone or already done**: for any other card, append a question asking the user whether to\n discard it, run no preview agent, and stop.\n- **Existing group**: read its subtasks and check that they cover the parent\u2019s outcome;\n keep a complete split, or fill gaps by updating subtasks and dependencies without\n duplicating work or resetting progress. Finish the pass without marking the parent\n ready merely because its split is complete; its completion still follows its subtasks.\n- **Studio rules**: write the card as the studio rules at the end of this prompt say.\n- **Preview agents**: an agent's `After` names the previews it waits for; the board approves\n previews in stages, one stage per Approve, and the card's `previews` were chosen when its\n goal was written. A card without `previews` has not chosen: choose and save them first, as\n the list says, then run only its first stage. Run each listed agent whose section is missing\n or outdated with `akb raw previews <agent> <id>`; choose `--print` for this session or\n omit it for a separate session.\n- **Stale mentions**: rewrite any sentence that relies on a card no longer on the board.\n- **Questions**: settle every decision you can and record the answers as `akb guide writing`\n says; ask only what `akb guide update-questions` says to ask.\n- **Write**: shape the card as `akb guide writing` says, then run `akb raw validate <id>` and\n fix every reported line.\n- **Ready**: settle every fact from the project and authoritative sources. Once the card\n validates, judge whether it can be built as written, or before its last Approve: if so, run\n `akb raw update <id> --status ready`; otherwise leave what blocks it as an open question.\n\nFollow any closing steps the flow printed, then stop: the user approves the previews or starts\nthe build.\n";
24756
24812
  }
24757
24813
  });
24758
24814
 
@@ -24776,7 +24832,7 @@ var init_resolve2 = __esm({
24776
24832
  var revise_default;
24777
24833
  var init_revise = __esm({
24778
24834
  "../cli/src/guide/revise.md"() {
24779
- revise_default = "# Revise\n\nMake the requested change and fix what it contradicts in the card. Apply answers supported by\nthe project and leave only decisions the user owns.\n\n- **Owned content first**: before the edit, follow \"Preview ownership\" in `akb guide writing`.\n- **Dependencies**: when the card comes to need another card's output, add that id to its\n `blocked_by` as `akb guide add-task` says.\n- **Changed outcome**: if the request materially changes what the task delivers, write the\n revision, then plan the card in this session as `akb guide refine` says. Ordinary scope\n and wording changes need no replanning.\n- **Preview agents**: when the revision adds or changes work a preview agent's `When` covers,\n such as images, page copy or a screen, add it to the card's `previews` and run it as\n \"Preview agents\" in `akb guide refine` says; a plan of that work written into `## Scope` is\n no substitute.\n- **Drafts**: when the change affects a draft on the card, revise its files and previews in\n place on this run, with `akb raw previews` for each preview agent whose draft it affects, including\n one from an earlier stage. Keep the unaffected content and the IDs. A note or todo is no\n substitute.\n- **Superseded decisions**: An entry under `## Decided by the agent`, or a line under the\n human half's `## Worth noting`, that the revision makes invalid is a call the user\n overruled \u2014 keep it. Move the line, as it stands, under a `### Overruled by the user`\n heading at the end of `## Decided by the agent`, adding the heading if the card has none.\n The subsection stays last inside that section. Delete an overruled line once the card\n leaves the builder no room to repeat that call.\n- **The two halves**: write the card in the shape `akb guide writing` sets out; when the change\n lands in the agent half, re-read the opening paragraph and `## Worth noting` so both hold.\n- **Other actions**: for another board action asked, follow `akb <action> <id> --print`.\n";
24835
+ revise_default = "# Revise\n\nMake the requested change and fix what it contradicts in the card. Apply answers supported by\nthe project and leave only decisions the user owns.\n\n- **Owned content first**: before the edit, follow \"Preview ownership\" in `akb guide writing`.\n- **Dependencies**: when the card comes to need another card's output, add that id to its\n `blocked_by` as `akb guide add-task` says.\n- **Changed outcome**: if the request materially changes what the task delivers, write the\n revision, then plan the card as `akb guide refine` says. Ordinary scope\n and wording changes need no replanning.\n- **Preview agents**: when the revision adds or changes work a preview agent's `When` covers,\n such as images, page copy or a screen, add it to the card's `previews` and run it as\n \"Preview agents\" in `akb guide refine` says; a plan of that work written into `## Scope` is\n no substitute.\n- **Drafts**: when the change affects a draft on the card, revise its files and previews in\n place, with `akb raw previews` for each preview agent whose draft it affects, including\n one from an earlier stage. Keep the unaffected content and the IDs. A note or todo is no\n substitute.\n- **Superseded decisions**: An entry under `## Decided by the agent`, or a line under the\n human half's `## Worth noting`, that the revision makes invalid is a call the user\n overruled \u2014 keep it. Move the line, as it stands, under a `### Overruled by the user`\n heading at the end of `## Decided by the agent`, adding the heading if the card has none.\n The subsection stays last inside that section. Delete an overruled line once the card\n leaves the builder no room to repeat that call.\n- **The two halves**: write the card in the shape `akb guide writing` sets out; when the change\n lands in the agent half, re-read the opening paragraph and `## Worth noting` so both hold.\n- **Other actions**: for another board action asked, follow its guide.\n";
24780
24836
  }
24781
24837
  });
24782
24838
 
@@ -24784,7 +24840,7 @@ var init_revise = __esm({
24784
24840
  var preview_agent_default;
24785
24841
  var init_preview_agent = __esm({
24786
24842
  "../cli/src/guide/preview-agent.md"() {
24787
- preview_agent_default = '# Be a preview agent\n\nYou are one preview agent on a card. Change only your own part: the ``## By `<agent-name>`\nagent`` section your instructions cover, its assets, your memory, and any file your\ninstructions tell you to write.\n\n- **Write**: edit your section in place above `<!-- agent -->`; do not duplicate it. Use\n `###` for subheadings.\n- **Choose your stages**: when given a stage definition without a saved selection, choose\n the work this task needs and save its IDs with `akb raw previews <agent> <id> --stages <ids>`.\n Follow the current stage instructions it returns; reuse a saved selection on later runs.\n- **Finish your part**: write the assigned work now. When given a current stage ID, submit\n it with `akb raw previews <agent> <id> --submit --stage <stage-id>` and stop after success.\n Without a stage ID, finish your planning content as before.\n- **Revision routing**: when a new revision asks for its starting stage, use `akb raw previews <agent> <id> --revise-from <stage-id>`; keep the confirmed prefix and revise the affected stage and its successors.\n- **Rework**: when your section exists, redo only what the user names or an upstream change\n affects, and keep the rest, including its IDs, as it is.\n- **Components**: use the Preview Components documentation supplied with your run to show your Preview.\n- **Long drafts**: put a draft over about 20 lines in `<board-state>/assets/<card id>/<name>.md`\n and show it with `<Asset src=".assets/<card id>/<name>.md">`; a shorter one goes in a code block.\n- **Memory**: `docs/kanban/memory/agents/<agent-name>/` is yours; keep only the files your\n instructions name, and edit one directly when you learn something lasting. Edit your\n studio\'s memory only as its rules say.\n- **User decisions**: follow `akb guide update-questions`; leave at most one open question,\n pointing to your section, appended with `--agent <agent-name>`.\n- **Validate**: run `akb raw validate <task-id>` and fix what it reports.\n';
24843
+ preview_agent_default = '# Be a preview agent\n\nYou are one preview agent on a card. Change only your own part: the ``## By `<agent-name>`\nagent`` section your instructions cover, its assets, your memory, and any file your\ninstructions tell you to write.\n\n- **Write**: edit your section in place above `<!-- agent -->`; do not duplicate it. Use\n `###` for subheadings.\n- **Rework**: when your section exists, redo only what the user names or an upstream change\n affects, and keep the rest, including its IDs, as it is.\n- **Components**: use the Preview Components documentation supplied with your run to show your Preview.\n- **Long drafts**: put a draft over about 20 lines in `<board-state>/assets/<card id>/<name>.md`\n and show it with `<Asset src=".assets/<card id>/<name>.md">`; a shorter one goes in a code block.\n- **Memory**: `docs/kanban/memory/agents/<agent-name>/` is yours; keep only the files your\n instructions name, and edit one directly when you learn something lasting. Edit your\n studio\'s memory only as its rules say.\n- **User decisions**: follow `akb guide update-questions`; leave at most one open question,\n pointing to your section, appended with `--agent <agent-name>`.\n';
24788
24844
  }
24789
24845
  });
24790
24846
 
@@ -24808,7 +24864,7 @@ var init_troubleshoot = __esm({
24808
24864
  var write_agent_default;
24809
24865
  var init_write_agent = __esm({
24810
24866
  "../cli/src/guide/write-agent.md"() {
24811
- write_agent_default = "# Write an agent\n\nCreate `docs/kanban/agents/<name>/AGENT.md`; use an unused lowercase, hyphenated name matching\nthe folder. Its studio lists it under `previews`, `land` or `scheduled` in `STUDIO.md`.\n\n## Example: a preview agent\n\n```yaml\n---\nname: page-designer\ndescription: Makes complete page designs with their copy.\nakb:\n when: A card needs a page designed or changed.\n icon: screen\n components: [Asset, Set]\n i18n:\n en:\n title: Page design\n zh:\n title: \u9875\u9762\u8BBE\u8BA1\n stages:\n - id: copy\n title: {en: Copy, zh: \u6587\u6848}\n when: The page needs new or revised copy; existing text is insufficient.\n instructions: references/copy.md\n - id: layout\n title: {en: Page layout, zh: \u9875\u9762\u7A3F}\n instructions: references/layout.md\n---\n\nChoose the stages this task needs on first entry; reuse the saved selection on continuation.\nFollow the current stage's instructions, preserving confirmed copy in the page design.\n```\n\nWith existing copy, this agent selects only `layout`; otherwise it selects `copy,layout`.\nEach selected step except the last waits for user confirmation. The last is ready for the\ncard's approval. The agent chooses its steps, not the planner; the program saves and advances\nthem. Omit `stages` for a single preview. Stage IDs are unique; instruction paths stay inside\nthe agent folder. A task freezes its definition, files and selection.\n\n**Legacy**: `after` remains readable for frozen workflows; use internal stages for new agents.\n\n## Other fields\n\nOnly `name`, `description` and nonempty body instructions are required. Omit unused fields.\n\n| Field | Use |\n| --- | --- |\n| `akb.when` | When to request a preview; omitted means every task on its studio. |\n| `akb.session: new` | Run a preview in its own session. |\n| `akb.components` | Asset, Set, Compare or Storyboard; default `[Asset]`, `[]` loads no component docs. |\n| `akb.icon` | Glyph name, or 1\u201312 `{d, f?, o?: true, s?, w?}` parts using supported colours. |\n| `akb.i18n` | Display-only title, description and when by language; missing text falls back to English. Keep titles short and name the output. |\n| `akb.reads` | Scheduled input: `archived-cards`, `chats` or `dismissals`; omitted uses cadence alone. Set fixed cadence on the studio's scheduled entry. |\n| `akb.merges: true` | A land agent merges code; completion requires its merged commit and branch. |\n| `akb.memory` | Names of shared global memories. |\n| `akb.memoryFiles.workspace` | Paths such as `[style.md]` shared across projects within this agent's memory. |\n\n## Instructions and files\n\n- **Keep the body small**: say what the agent owns and delivers. Use `akb guide write-prompt`;\n do not repeat `preview-agent` rules. Stage-specific work belongs in its instruction file.\n- **Load on demand**: files beside AGENT.md are listed to the run. Put shared studio material\n in `shared/`; keep scripts and business validation with their owning agent, documenting\n runtime and invocation. Retrieve bundled files with `akb raw file <studio> <path>`.\n- **Memory**: keep only preferences or corrections that change future work. Name each file's\n purpose and when to read it; omit transcripts and duplicated rules. Agent memory is under\n `docs/kanban/memory/agents/<name>/`; studio memory follows its `shared/RULES.md`. Agree on\n any scheduled agent's persistent state rather than inventing its format.\n- **User decisions**: follow `akb guide update-questions`; do not ask again about settled\n choices. Show each changed file as a unified diff with one sentence explaining why.\n\n## Imported skills\n\nKeep each skill whole under `skills/<skill>/`, including instructions, scripts, resources and\nlicense; exclude caches and installed packages. Record its source and version in AGENT.md:\n`- **<skill>**: <when to use>. Source: <URL or pasted> @ <commit, tag or date>`.\nAdapt routing outside the skill, preserving its relative paths. Report missing files, tools\nor credentials; never copy keys or claim an unusable skill works. Update or remove only when\nasked, replacing the whole owned copy and showing the diff and version.\n\n## Check\n\nRun `akb raw previews` and `akb raw previews --triggers`; fix every reported problem.\nThen inspect `akb raw previews <name> <id> --print` on a real task and trim unnecessary context.\nUse `akb raw components --agent <name> --docs` for output formats. New agents start enabled\nin their studio; disabled previews cannot run. Keep registration and instructions consistent.\n";
24867
+ write_agent_default = "# Write an agent\n\nCreate `docs/kanban/agents/<name>/AGENT.md`; use an unused lowercase, hyphenated name matching\nthe folder. Its studio lists it under `previews`, `land` or `scheduled` in `STUDIO.md`.\n\n## Example: a preview agent\n\n```yaml\n---\nname: page-designer\ndescription: Makes complete page designs with their copy.\nakb:\n when: A card needs a page designed or changed.\n icon: screen\n components: [Asset, Set]\n i18n:\n en:\n title: Page design\n zh:\n title: \u9875\u9762\u8BBE\u8BA1\n stages:\n - id: copy\n title: {en: Copy, zh: \u6587\u6848}\n when: The page needs new or revised copy; existing text is insufficient.\n instructions: references/copy.md\n - id: layout\n title: {en: Page layout, zh: \u9875\u9762\u7A3F}\n instructions: references/layout.md\n---\n\nChoose the stages this task needs on first entry; reuse the saved selection on continuation.\nFollow the current stage's instructions, preserving confirmed copy in the page design.\n```\n\nWith existing copy, this agent selects only `layout`; otherwise it selects `copy,layout`.\nEach selected step except the last waits for user confirmation. The last is ready for the\ncard's approval. The agent chooses its steps, not the planner; the program saves and advances\nthem. Omit `stages` for a single preview. Stage IDs are unique; instruction paths stay inside\nthe agent folder. A task freezes its definition, files and selection.\n\n**Dependencies**: `akb.after` names other previews in the same studio to approve first when the card requests them too.\n\n## Other fields\n\nOnly `name`, `description` and nonempty body instructions are required. Omit unused fields.\n\n| Field | Use |\n| --- | --- |\n| `akb.when` | When to request a preview; omitted means every task on its studio. |\n| `akb.session: new` | A preference for a separate session; the calling agent decides. |\n| `akb.components` | Asset, Set, Compare or Storyboard; default `[Asset]`, `[]` loads no component docs. |\n| `akb.icon` | Glyph name, or 1\u201312 `{d, f?, o?: true, s?, w?}` parts using supported colours. |\n| `akb.i18n` | Display-only title, description and when by language; missing text falls back to English. Keep titles short and name the output. |\n| `akb.reads` | Scheduled input: `archived-cards`, `chats` or `dismissals`; omitted uses cadence alone. Set fixed cadence on the studio's scheduled entry. |\n| `akb.merges: true` | A land agent merges code; completion requires its merged commit and branch. |\n| `akb.memory` | Names of shared global memories. |\n| `akb.memoryFiles.workspace` | Paths such as `[style.md]` shared across projects within this agent's memory. |\n\n## Instructions and files\n\n- **Keep the body small**: say what the agent owns and delivers. Use `akb guide write-prompt`;\n do not repeat `preview-agent` rules. Stage-specific work belongs in its instruction file.\n- **Load on demand**: files beside AGENT.md are listed to the run. Put shared studio material\n in `shared/`; keep scripts and business validation with their owning agent, documenting\n runtime and invocation. Retrieve bundled files with `akb raw file <studio> <path>`.\n- **Memory**: keep only preferences or corrections that change future work. Name each file's\n purpose and when to read it; omit transcripts and duplicated rules. Agent memory is under\n `docs/kanban/memory/agents/<name>/`; studio memory follows its `shared/RULES.md`. Agree on\n any scheduled agent's persistent state rather than inventing its format.\n- **User decisions**: follow `akb guide update-questions`; do not ask again about settled\n choices. Show each changed file as a unified diff with one sentence explaining why.\n\n## Imported skills\n\nKeep each skill whole under `skills/<skill>/`, including instructions, scripts, resources and\nlicense; exclude caches and installed packages. Record its source and version in AGENT.md:\n`- **<skill>**: <when to use>. Source: <URL or pasted> @ <commit, tag or date>`.\nAdapt routing outside the skill, preserving its relative paths. Report missing files, tools\nor credentials; never copy keys or claim an unusable skill works. Update or remove only when\nasked, replacing the whole owned copy and showing the diff and version.\n\n## Check\n\nRun `akb raw previews` and `akb raw previews --triggers`; fix every reported problem.\nThen inspect `akb raw previews <name> <id> --print` on a real task and trim unnecessary context.\nUse `akb raw components --agent <name> --docs` for output formats. New agents start enabled\nin their studio; disabled previews cannot run. Keep registration and instructions consistent.\n";
24812
24868
  }
24813
24869
  });
24814
24870
 
@@ -24890,7 +24946,7 @@ var init_guide = __esm({
24890
24946
  { name: "implement", when: "build a settled card and stop cleanly on an execution blocker", text: implement_default },
24891
24947
  { name: "archive", when: "finish a task \u2014 write its shipped line, then take it off the board", text: archive_default },
24892
24948
  { name: "update-questions", when: "decide what to ask the user, and write the question", text: update_questions_default },
24893
- { name: "refine", when: "plan one card until it can be built, in one session", text: refine_default },
24949
+ { name: "refine", when: "plan one card until it can be built", text: refine_default },
24894
24950
  { name: "revise", when: "make the one change to a card the user asked for", text: revise_default },
24895
24951
  { name: "resolve", when: "apply the user's answers to a card's open questions", text: resolve_default },
24896
24952
  { name: "prune-memory", when: "compress the memory set back to what helps planning", text: prune_memory_default },
@@ -24942,8 +24998,8 @@ var init_guide2 = __esm({
24942
24998
 
24943
24999
  // ../cli/src/commands/studio.ts
24944
25000
  import crypto6 from "node:crypto";
24945
- import fs79 from "node:fs";
24946
- import path80 from "node:path";
25001
+ import fs80 from "node:fs";
25002
+ import path81 from "node:path";
24947
25003
  function cmdStudioList() {
24948
25004
  if (!studiosReachable().ok) die(NEEDS_CLOUD, "needs-cloud");
24949
25005
  const offline2 = studiosOffline();
@@ -24972,7 +25028,7 @@ function cmdStudioList() {
24972
25028
  };
24973
25029
  }
24974
25030
  function cmdStudioDiagram(id, card, folder) {
24975
- const files = folder ? readStudioFolder(path80.resolve(folder)) : null;
25031
+ const files = folder ? readStudioFolder(path81.resolve(folder)) : null;
24976
25032
  const local = files ? parseStudioFile("studio", files[STUDIO_FILE] ?? "", STUDIO_FILE) : null;
24977
25033
  if (local && "problem" in local) die(local.problem, "bad-studio");
24978
25034
  const flow = local && "def" in local ? local.def : found(id);
@@ -24982,17 +25038,17 @@ function cmdStudioDiagram(id, card, folder) {
24982
25038
  const agent = findSpecAgent(name);
24983
25039
  return agent ? { ...agent, after: agentAfter(name) } : null;
24984
25040
  });
24985
- const file2 = path80.join(ASSETS, String(cardId2), "studio.json");
24986
- fs79.mkdirSync(path80.dirname(file2), { recursive: true });
24987
- fs79.writeFileSync(file2, `${JSON.stringify(diagram, null, 2)}
25041
+ const file2 = path81.join(ASSETS, String(cardId2), "studio.json");
25042
+ fs80.mkdirSync(path81.dirname(file2), { recursive: true });
25043
+ fs80.writeFileSync(file2, `${JSON.stringify(diagram, null, 2)}
24988
25044
  `);
24989
25045
  const tag = `<Studio src=".assets/${cardId2}/studio.json" label="${flow.name.replace(/"/g, "")}" />`;
24990
25046
  say(tag);
24991
25047
  return { file: file2, tag, diagram };
24992
25048
  }
24993
25049
  function cmdStudioValidate(folder) {
24994
- const dir = path80.resolve(folder);
24995
- if (!fs79.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder} is not a folder`, "bad-args");
25050
+ const dir = path81.resolve(folder);
25051
+ if (!fs80.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder} is not a folder`, "bad-args");
24996
25052
  const files = readStudioFolder(dir);
24997
25053
  const read3 = parseStudioFile("studio", files[STUDIO_FILE] ?? "", STUDIO_FILE);
24998
25054
  const def = "def" in read3 ? read3.def : null;
@@ -25020,16 +25076,16 @@ function cmdStudioValidate(folder) {
25020
25076
  async function cmdStudioPull(id, folder) {
25021
25077
  const cloudId = cloudIdOf(id);
25022
25078
  if (!cloudId) found(id);
25023
- const dir = path80.resolve(folder ?? id);
25024
- if (fs79.existsSync(dir) && fs79.readdirSync(dir).length) die(`${folder ?? id} is not empty`, "bad-args");
25079
+ const dir = path81.resolve(folder ?? id);
25080
+ if (fs80.existsSync(dir) && fs80.readdirSync(dir).length) die(`${folder ?? id} is not empty`, "bad-args");
25025
25081
  const read3 = await call("GET", `/v1/studios/${encodeURIComponent(cloudId)}`);
25026
25082
  if (!read3.ok) die(read3.error, read3.code === "not_found" ? "no-such-studio" : "cloud-refused");
25027
25083
  const { version, files } = read3.value;
25028
25084
  for (const [file2, text5] of Object.entries({ ...files, [VERSION_FILE]: versionText(cloudId, version) })) {
25029
- const full = path80.join(dir, ...file2.split("/"));
25030
- fs79.mkdirSync(path80.dirname(full), { recursive: true });
25085
+ const full = path81.join(dir, ...file2.split("/"));
25086
+ fs80.mkdirSync(path81.dirname(full), { recursive: true });
25031
25087
  const data = isAboutFile(file2) && !file2.endsWith(".md") && /^data:[^;]+;base64,/.exec(text5);
25032
- fs79.writeFileSync(full, data ? Buffer.from(text5.slice(data[0].length), "base64") : text5);
25088
+ fs80.writeFileSync(full, data ? Buffer.from(text5.slice(data[0].length), "base64") : text5);
25033
25089
  }
25034
25090
  const shown = folder ?? `./${id}`;
25035
25091
  say(`Pulled ${id} v${version} into ${shown}.`);
@@ -25041,45 +25097,45 @@ function publicationFiles(dir) {
25041
25097
  return checked.files;
25042
25098
  }
25043
25099
  async function publishFolder(dir, route2, body, requestId) {
25044
- const pendingFile = path80.join(dir, ".publication.json");
25100
+ const pendingFile = path81.join(dir, ".publication.json");
25045
25101
  const hash2 = crypto6.createHash("sha256").update(JSON.stringify({ route: route2, files: body.files, workspace: body.workspace })).digest("hex");
25046
25102
  let held4;
25047
25103
  try {
25048
- held4 = JSON.parse(fs79.readFileSync(pendingFile, "utf8"));
25104
+ held4 = JSON.parse(fs80.readFileSync(pendingFile, "utf8"));
25049
25105
  } catch {
25050
25106
  }
25051
25107
  if (requestId && held4?.requestId === requestId && held4.hash !== hash2) die("This request ID already names different files; use a new request ID.", "bad-args");
25052
25108
  const replay = held4?.hash === hash2 && held4.route === route2 && (!requestId || held4.requestId === requestId) && (body.expectedVersion === held4.body.expectedVersion || body.expectedVersion === held4.resultVersion);
25053
25109
  const pending = replay ? held4 : { requestId: requestId ?? crypto6.randomUUID(), hash: hash2, body, route: route2 };
25054
- fs79.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
25110
+ fs80.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
25055
25111
  const res = await call(route2 === "/v1/studios" ? "POST" : "PATCH", route2, pending.body, pending.requestId);
25056
25112
  if (!res.ok) die(res.error, res.code === "version_conflict" || res.code === "conflict" ? "studio-moved" : "cloud-refused");
25057
25113
  const { id, version } = res.value;
25058
25114
  pending.resultVersion = version;
25059
- fs79.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
25060
- fs79.writeFileSync(path80.join(dir, VERSION_FILE), versionText(id, version));
25115
+ fs80.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
25116
+ fs80.writeFileSync(path81.join(dir, VERSION_FILE), versionText(id, version));
25061
25117
  say(`Saved ${studioName(id)} v${version}. New tasks take it.`);
25062
25118
  return { id, version, changed: true, requestId: pending.requestId };
25063
25119
  }
25064
25120
  async function cmdStudioCreate(folder, opts) {
25065
25121
  if (!opts.requestId) die("--request-id is required", "bad-args");
25066
- const dir = path80.resolve(folder);
25122
+ const dir = path81.resolve(folder);
25067
25123
  const files = publicationFiles(dir);
25068
25124
  const workspace2 = opts.workspace ?? (await cloudScope()).workspace;
25069
25125
  return publishFolder(dir, "/v1/studios", { files, workspace: workspace2 }, opts.requestId);
25070
25126
  }
25071
25127
  async function cmdStudioPush(folder, opts) {
25072
- const dir = path80.resolve(folder);
25128
+ const dir = path81.resolve(folder);
25073
25129
  let pulled = null;
25074
25130
  try {
25075
- pulled = JSON.parse(fs79.readFileSync(path80.join(dir, VERSION_FILE), "utf8"));
25131
+ pulled = JSON.parse(fs80.readFileSync(path81.join(dir, VERSION_FILE), "utf8"));
25076
25132
  } catch {
25077
25133
  }
25078
25134
  if (!pulled?.id || !Number.isInteger(pulled.version) || pulled.version < 1) die(`${folder} has no valid version.json; pull again.`, "bad-args");
25079
25135
  const { id, version } = pulled;
25080
25136
  if (id.startsWith("wf_builtin_")) die("Copy this studio before editing it.", "studio-read-only");
25081
25137
  const files = publicationFiles(dir);
25082
- if (!fs79.existsSync(path80.join(dir, ".publication.json")) && !opts.requestId) {
25138
+ if (!fs80.existsSync(path81.join(dir, ".publication.json")) && !opts.requestId) {
25083
25139
  const now = await call("GET", `/v1/studios/${encodeURIComponent(id)}`);
25084
25140
  if (now.ok && now.value.version === version && JSON.stringify(files) === JSON.stringify(Object.fromEntries(Object.entries(now.value.files).filter(([f2]) => f2 !== VERSION_FILE).sort()))) {
25085
25141
  say(`${studioName(id)} is unchanged (v${version}).`);
@@ -25098,7 +25154,7 @@ function noteText({ file: file2, text: text5 }) {
25098
25154
  if (file2 !== void 0 && text5 !== void 0) die("pass --file or --text, not both", "bad-args");
25099
25155
  if (file2 !== void 0) {
25100
25156
  try {
25101
- return fs79.readFileSync(file2, "utf8").trim();
25157
+ return fs80.readFileSync(file2, "utf8").trim();
25102
25158
  } catch {
25103
25159
  die(`can't read ${file2}`, "bad-args");
25104
25160
  }
@@ -25238,7 +25294,6 @@ function completeDelivery(named2, result = {}) {
25238
25294
  throw new Error("Only the current owning run can complete this delivery.");
25239
25295
  }
25240
25296
  if (answerOutcome(delivery2) === "changed") throw new Error("The approved requirements were superseded. Continue with the updated delivery.");
25241
- if (delivery2.cardId !== null && openQuestions(delivery2.cardId)) throw new Error("Answer the open questions before completing.");
25242
25297
  if (pending && run4 === current) {
25243
25298
  if (pending.commit !== commit || pending.branch !== branch) throw new Error("This step already recorded a different result.");
25244
25299
  pending.resumedSessions = [...pending.resumedSessions ?? [], sessionId];
@@ -25247,15 +25302,8 @@ function completeDelivery(named2, result = {}) {
25247
25302
  const agent = delivery2.scheduled?.agent ?? deliveryAgents(delivery2)[deliveryStep(delivery2)]?.agent;
25248
25303
  if (!agent) throw new Error("No studio step remains to complete.");
25249
25304
  if (delivery2.cardId !== null && !locate(delivery2.cardId)) throw new Error("The card is missing before completion.");
25250
- const finalStep = !!delivery2.scheduled || receipts.length + 1 >= deliveryAgents(delivery2).length;
25251
- const card = delivery2.cardId === null ? void 0 : findCard(delivery2.cardId);
25252
- if (finalStep && card && /[-*]\s+\[ \]/.test(card.body)) throw new Error("Complete every Todo before finishing the delivery.");
25253
25305
  const merges = specAgentCatalog().agents.find((a2) => a2.name === agent)?.merges;
25254
25306
  if (merges && !commit && delivery2.base) throw new Error(`\`${agent}\` must report its merged commit and target branch.`);
25255
- if (delivery2.studio?.needsArtifact && !delivery2.scheduled) {
25256
- const stop = filesStop(delivery2);
25257
- if (stop) throw new Error(stop.why);
25258
- }
25259
25307
  const receipt2 = { sessionId, step: receipts.length, at: Date.now(), commit, branch, finished: false };
25260
25308
  receipts.push(receipt2);
25261
25309
  return { delivery: delivery2, receipt: receipt2 };
@@ -25264,12 +25312,6 @@ function completeDelivery(named2, result = {}) {
25264
25312
  syncAudit(delivery.deliveryId);
25265
25313
  const final = !!delivery.scheduled || receipt.step + 1 >= deliveryAgents(delivery).length;
25266
25314
  if (final && !receipt.finished) {
25267
- if (delivery.studio?.needsArtifact && !delivery.scheduled) {
25268
- const stop = filesStop(delivery);
25269
- if (stop) throw new Error(stop.why);
25270
- }
25271
- const card = delivery.cardId === null ? void 0 : findCard(delivery.cardId);
25272
- if (card && /[-*]\s+\[ \]/.test(card.body)) throw new Error("Complete every Todo before finishing the delivery.");
25273
25315
  let handoff = receipt.handoff;
25274
25316
  if (delivery.cardId !== null) {
25275
25317
  const source2 = locate(delivery.cardId);
@@ -25311,8 +25353,6 @@ var init_complete = __esm({
25311
25353
  init_progress();
25312
25354
  init_answers();
25313
25355
  init_env();
25314
- init_outputs();
25315
- init_read();
25316
25356
  init_store();
25317
25357
  init_studios();
25318
25358
  init_catalog();
@@ -25320,16 +25360,16 @@ var init_complete = __esm({
25320
25360
  });
25321
25361
 
25322
25362
  // ../cli/src/lib/agent/task-chats.ts
25323
- import fs80 from "node:fs";
25324
- import path81 from "node:path";
25363
+ import fs81 from "node:fs";
25364
+ import path82 from "node:path";
25325
25365
  function taskChatFile(task, home3) {
25326
25366
  if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
25327
- return path81.join(taskChatsDir(home3), `${task}.jsonl`);
25367
+ return path82.join(taskChatsDir(home3), `${task}.jsonl`);
25328
25368
  }
25329
25369
  function readTaskChat(task, home3) {
25330
25370
  let text5;
25331
25371
  try {
25332
- text5 = fs80.readFileSync(taskChatFile(task, home3), "utf8");
25372
+ text5 = fs81.readFileSync(taskChatFile(task, home3), "utf8");
25333
25373
  } catch {
25334
25374
  return [];
25335
25375
  }
@@ -25350,13 +25390,13 @@ var init_task_chats = __esm({
25350
25390
  "use strict";
25351
25391
  init_home();
25352
25392
  TASK = /^[\w-]{1,100}$/;
25353
- taskChatsDir = (home3 = machineHome()) => path81.join(home3, "chats");
25393
+ taskChatsDir = (home3 = machineHome()) => path82.join(home3, "chats");
25354
25394
  }
25355
25395
  });
25356
25396
 
25357
25397
  // ../cli/src/lib/agent/memory-review.ts
25358
- import fs81 from "node:fs";
25359
- import path82 from "node:path";
25398
+ import fs82 from "node:fs";
25399
+ import path83 from "node:path";
25360
25400
  function taskChatsToReview(tasks) {
25361
25401
  const out = [];
25362
25402
  for (const ref of [...new Set(tasks)]) {
@@ -25378,8 +25418,8 @@ function readArchived2(id) {
25378
25418
  const found2 = Number.isInteger(id) && id > 0 ? locateArchived(id) : null;
25379
25419
  if (!found2) return null;
25380
25420
  try {
25381
- const file2 = found2.kind === "group" ? path82.join(found2.target, "root.md") : found2.target;
25382
- const { meta, body } = parseFrontmatter(fs81.readFileSync(file2, "utf8"));
25421
+ const file2 = found2.kind === "group" ? path83.join(found2.target, "root.md") : found2.target;
25422
+ const { meta, body } = parseFrontmatter(fs82.readFileSync(file2, "utf8"));
25383
25423
  if (!meta) return null;
25384
25424
  return { id, title: meta.title, modules: meta.modules ?? [], rejected: meta.rejected, body };
25385
25425
  } catch {
@@ -25448,17 +25488,17 @@ var init_memory_review = __esm({
25448
25488
  });
25449
25489
 
25450
25490
  // ../cli/src/lib/agent/dismissal-review.ts
25451
- import fs82 from "node:fs";
25452
- import path83 from "node:path";
25491
+ import fs83 from "node:fs";
25492
+ import path84 from "node:path";
25453
25493
  function rejectionsToReview() {
25454
- const dir = path83.join(ARCHIVE, REJECTIONS_TO_REVIEW);
25455
- if (!fs82.existsSync(dir)) return [];
25494
+ const dir = path84.join(ARCHIVE, REJECTIONS_TO_REVIEW);
25495
+ if (!fs83.existsSync(dir)) return [];
25456
25496
  const found2 = [];
25457
25497
  for (const file2 of walkMd(dir)) {
25458
25498
  const id = archivedId(file2);
25459
25499
  if (id === null) continue;
25460
25500
  try {
25461
- const { meta } = parseFrontmatter(fs82.readFileSync(file2, "utf8"));
25501
+ const { meta } = parseFrontmatter(fs83.readFileSync(file2, "utf8"));
25462
25502
  if (!meta?.rejected || meta.rejected_by !== "user" || !meta.rejected_reason.trim()) continue;
25463
25503
  found2.push({ id, title: meta.title, file: rel(file2), reason: meta.rejected_reason.trim(), rejectedAt: meta.rejected_at });
25464
25504
  } catch {
@@ -25488,7 +25528,7 @@ function citedSources(text5) {
25488
25528
  function withdrawnSources() {
25489
25529
  const cited = [...new Set(plannerCopies("rejected.md").flatMap((file2) => {
25490
25530
  try {
25491
- return citedSources(fs82.readFileSync(file2, "utf8"));
25531
+ return citedSources(fs83.readFileSync(file2, "utf8"));
25492
25532
  } catch {
25493
25533
  return [];
25494
25534
  }
@@ -25513,8 +25553,8 @@ var init_dismissal_review = __esm({
25513
25553
  });
25514
25554
 
25515
25555
  // ../cli/src/lib/agent/flow.ts
25516
- import fs83 from "node:fs";
25517
- import path84 from "node:path";
25556
+ import fs84 from "node:fs";
25557
+ import path85 from "node:path";
25518
25558
  function readCard2(id, home3 = "board") {
25519
25559
  const pending = activeDelivery(id)?.completions?.some((c2) => !c2.finished);
25520
25560
  const found2 = home3 === "archive" ? locateArchived(id) : locate(id) ?? (pending ? locateArchived(id) : null);
@@ -25524,10 +25564,10 @@ function readCard2(id, home3 = "board") {
25524
25564
  { kind: "card-not-found", id }
25525
25565
  );
25526
25566
  }
25527
- const file2 = found2.kind === "group" ? path84.join(found2.target, "root.md") : found2.target;
25567
+ const file2 = found2.kind === "group" ? path85.join(found2.target, "root.md") : found2.target;
25528
25568
  let text5;
25529
25569
  try {
25530
- text5 = fs83.readFileSync(file2, "utf8");
25570
+ text5 = fs84.readFileSync(file2, "utf8");
25531
25571
  } catch {
25532
25572
  die(`#${id} is on the board but ${rel(file2)} can't be read.`, { kind: "card-unreadable", id });
25533
25573
  }
@@ -26036,7 +26076,7 @@ var init_stage_end = __esm({
26036
26076
  import { createHash as createHash9 } from "node:crypto";
26037
26077
  function markBoard() {
26038
26078
  try {
26039
- return new Map(allCards2().map((card) => [card.id, wroteOf(card)]));
26079
+ return new Map(allCards().map((card) => [card.id, wroteOf(card)]));
26040
26080
  } catch {
26041
26081
  return /* @__PURE__ */ new Map();
26042
26082
  }
@@ -26097,7 +26137,7 @@ function refinementAfter(action, cardId2, flowId) {
26097
26137
  function refinesAfter(action, changed, before) {
26098
26138
  let cards;
26099
26139
  try {
26100
- cards = allCards2();
26140
+ cards = allCards();
26101
26141
  } catch {
26102
26142
  return [];
26103
26143
  }
@@ -26200,34 +26240,12 @@ var init_refine2 = __esm({
26200
26240
  }
26201
26241
  });
26202
26242
 
26203
- // ../cli/src/lib/agent/own-cost.ts
26204
- function ownCost(total, before) {
26205
- if (total === void 0 || before === null) return void 0;
26206
- if (before === void 0 || total < before) return total;
26207
- return total >= before ? total - before : void 0;
26208
- }
26209
- function lastSessionTotal(id, runs) {
26210
- let best;
26211
- const take = (at2, usd) => {
26212
- if (typeof usd === "number" && usd >= 0 && (!best || at2 >= best.at)) best = { at: at2, usd };
26213
- };
26214
- for (const r2 of runs) if (r2.resumeId === id || r2.sessionId === id) take(r2.endedAt ?? r2.startedAt, r2.sessionCostUsd);
26215
- return best?.usd ?? null;
26216
- }
26217
- var reportsSessionTotal;
26218
- var init_own_cost = __esm({
26219
- "../cli/src/lib/agent/own-cost.ts"() {
26220
- "use strict";
26221
- reportsSessionTotal = (harness) => harness === "claude-code";
26222
- }
26223
- });
26224
-
26225
26243
  // ../cli/src/lib/agent/follow.ts
26226
26244
  function specRunsAfter(asks) {
26227
26245
  if (!asks.length) return [];
26228
26246
  let cards;
26229
26247
  try {
26230
- cards = allCards2();
26248
+ cards = allCards();
26231
26249
  } catch {
26232
26250
  return [];
26233
26251
  }
@@ -26343,7 +26361,7 @@ __export(watch_exports, {
26343
26361
  watchRun: () => watchRun
26344
26362
  });
26345
26363
  import { spawn as spawn3 } from "node:child_process";
26346
- import fs84 from "node:fs";
26364
+ import fs85 from "node:fs";
26347
26365
  async function watchRun(sessionId, resume = startResume) {
26348
26366
  const spec = readSpec(sessionId);
26349
26367
  const run4 = peekRun(sessionId);
@@ -26379,11 +26397,11 @@ async function watchRun(sessionId, resume = startResume) {
26379
26397
  const record = claimed ?? run4;
26380
26398
  const sub = record.action === "sub";
26381
26399
  if (claim) await setCardStatus(claim.cardId, claim.status);
26382
- fs84.mkdirSync(SESSIONS_DIR, { recursive: true });
26383
- const logFile = fs84.createWriteStream(record.logPath, { flags: "a" });
26400
+ fs85.mkdirSync(SESSIONS_DIR, { recursive: true });
26401
+ const logFile = fs85.createWriteStream(record.logPath, { flags: "a" });
26384
26402
  logFile.on("error", () => {
26385
26403
  });
26386
- const eventsFile = fs84.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
26404
+ const eventsFile = fs85.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
26387
26405
  eventsFile.on("error", () => {
26388
26406
  });
26389
26407
  const pendingOperations = /* @__PURE__ */ new Set();
@@ -26419,11 +26437,9 @@ async function watchRun(sessionId, resume = startResume) {
26419
26437
  }
26420
26438
  }
26421
26439
  const stagePrompt = record.action === "spec" && record.cardId !== null && record.specAgent ? previewStagePrompt(record.cardId, record.specAgent, boardCommandFor(record.cardId)) : "";
26422
- const basePrompt = record.formatRepair ? contractRepairPrompt(requestOf(record), record.formatRepair.errors) : record.resumedFrom ? spec.prompt || resumePrompt(record.deliveryId, record.action) : spec.prompt;
26423
- const prompt = [basePrompt, stagePrompt, discardedCardsPrompt(record.discardedCards)].filter(Boolean).join("\n\n");
26440
+ const basePrompt = record.resumedFrom ? spec.prompt || resumePrompt(record.deliveryId, record.action) : spec.prompt;
26441
+ const prompt = [basePrompt, basePrompt.includes(stagePrompt) ? "" : stagePrompt, discardedCardsPrompt(record.discardedCards)].filter(Boolean).join("\n\n");
26424
26442
  const before = markBoard();
26425
- const sources2 = snapshotSpecs();
26426
- const wasBroken = new Set(boardComplaints());
26427
26443
  const takes = active2.images;
26428
26444
  const shots = takes?.as === "args" ? (record.pictures ?? []).flatMap((file2) => takes.args(file2)) : [];
26429
26445
  const [cmd, ...args2] = [...active2.argv, ...shots];
@@ -26432,7 +26448,7 @@ async function watchRun(sessionId, resume = startResume) {
26432
26448
  const silenceMs = silenceFor * 6e4;
26433
26449
  void refreshCatalog();
26434
26450
  const client = active2.client;
26435
- const restartBase = !client || record.formatRepair || record.action === "implement" && record.resumedFrom ? void 0 : record.resumedFrom ? restartPrompt(requestOf(record), record.deliveryId) : record.continues && !record.continues.fork ? spec.prompt : void 0;
26451
+ const restartBase = !client ? void 0 : record.resumedFrom ? restartPrompt(requestOf(record), record.deliveryId) : record.continues && !record.continues.fork ? spec.prompt : void 0;
26436
26452
  const restart = restartBase ? [restartBase, discardedCardsPrompt(record.discardedCards)].filter(Boolean).join("\n\n") : void 0;
26437
26453
  const stdinPrompt = client ? void 0 : active2.stdinPrompt;
26438
26454
  const stdio = [client || stdinPrompt ? "pipe" : "ignore", "pipe", "pipe"];
@@ -26652,82 +26668,9 @@ async function watchRun(sessionId, resume = startResume) {
26652
26668
  const totalCost = sessionTotal === void 0 ? reported : ownCost(sessionTotal, totalFrom);
26653
26669
  const usage3 = spoken ? spoken.usage : renderer?.usage?.();
26654
26670
  if (spoken) gotContext(spoken.context);
26655
- const repairable = status === "done";
26656
- const required = new Set(record.formatRepair?.cardIds ?? []);
26657
- const heldElsewhere = withStore((store) => new Set(store.runs.filter((r2) => r2.sessionId !== sessionId && r2.status === "running" && holdsCard(r2.action)).flatMap((r2) => [r2.cardId, ...r2.createdCardIds ?? []]).filter((id) => id !== null)));
26658
- let formatErrors = [];
26659
- let broken = [];
26660
- if (!sub) {
26661
- try {
26662
- const discarded = new Set(cleanupDiscardedCards(sessionId));
26663
- for (const [file2, card] of sources2) if (discarded.has(card.id)) sources2.delete(file2);
26664
- for (const id of discarded) required.delete(id);
26665
- const current = snapshotSpecs();
26666
- const onBoard3 = (id) => [...current.values()].some((card) => card.id === id);
26667
- const departed = /* @__PURE__ */ new Set();
26668
- const rejected = /* @__PURE__ */ new Set();
26669
- const missing = (id) => {
26670
- if (discarded.has(id) || onBoard3(id)) return false;
26671
- if (leftBoardRejected(id)) {
26672
- rejected.add(id);
26673
- return false;
26674
- }
26675
- if (leftBoardOnLanding(id)) {
26676
- departed.add(id);
26677
- return false;
26678
- }
26679
- return true;
26680
- };
26681
- for (const id of [...required]) if (!onBoard3(id) && !missing(id)) required.delete(id);
26682
- for (const [file2, card] of current) {
26683
- if (card.id === record.cardId || !heldElsewhere.has(card.id) && sources2.get(file2)?.text !== card.text) required.add(card.id);
26684
- }
26685
- for (const id of record.formatRepair?.cardIds ?? []) {
26686
- if (missing(id)) {
26687
- formatErrors.push({ file: rel(TODO), line: 1, rule: "missing-card", message: `Task #${id} disappeared. Restore its card file.` });
26688
- }
26689
- }
26690
- if (record.cardId !== null && !["archive", "reject"].includes(record.action) && [...sources2.values()].some((card) => card.id === record.cardId) && missing(record.cardId)) {
26691
- required.add(record.cardId);
26692
- formatErrors.push({ file: rel(TODO), line: 1, rule: "missing-card", message: `Task #${record.cardId} disappeared. Restore its card file; this run must not delete it.` });
26693
- }
26694
- if (repairable) {
26695
- const owed = new Set(record.formatRepair?.broken ?? []);
26696
- broken = boardComplaints().filter((line) => owed.has(line) || !wasBroken.has(line));
26697
- formatErrors.push(...broken.map((line) => ({ file: rel(TODO), line: 1, rule: "board-broken", message: `${line} Take a card off the board with \`${boardCommand()} raw archive <id>\` or \`${boardCommand()} raw reject <id>\`, never by deleting its file.` })));
26698
- }
26699
- for (const id of departed) log.write(`
26700
- [board] Task #${id} left the board with its landing; there is nothing to restore.
26701
- `);
26702
- for (const id of rejected) log.write(`
26703
- [board] Task #${id} was rejected; there is nothing to restore.
26704
- `);
26705
- } catch (error) {
26706
- formatErrors = [{ file: rel(TODO), line: 1, rule: "read-error", message: `Cannot validate the card files: ${String(error)}. Restore readable Markdown files and retry.` }];
26707
- }
26708
- }
26709
- const contractError = formatErrors.length ? boardCheckErrors(formatErrors) : void 0;
26710
- const repairing = !!contractError && repairable && (record.formatRepair?.attempt ?? 0) < MAX_FORMAT_REPAIRS;
26711
- const problems = formatErrors.length && !repairing ? boardProblems(formatErrors) : void 0;
26712
- if (contractError) {
26713
- log.write(`
26714
- [validation] ${contractError}
26715
- `);
26716
- if (status === "done") status = "error";
26717
- if (record.cardId !== null && !record.deliveryId) await setCardStatus(record.cardId, "todo");
26718
- }
26719
- const changed = sub ? [] : [.../* @__PURE__ */ new Set([...record.formatRepair?.changedIds ?? [], ...claimChanges(before, sessionId)])].filter((id) => !peekRun(sessionId)?.discardedCards?.some((c2) => c2.id === id));
26720
- const original = record.formatRepair ? new Map(record.formatRepair.existingIds.map((id) => [id, ""])) : before;
26721
- patch(sessionId, (r2) => {
26722
- r2.formatRepair = contractError ? {
26723
- attempt: record.formatRepair?.attempt ?? 0,
26724
- errors: contractError,
26725
- ...broken.length ? { broken } : {},
26726
- cardIds: [...required],
26727
- changedIds: changed,
26728
- existingIds: [...original.keys()]
26729
- } : void 0;
26730
- });
26671
+ if (!sub) cleanupDiscardedCards(sessionId);
26672
+ const changed = sub ? [] : claimChanges(before, sessionId).filter((id) => !peekRun(sessionId)?.discardedCards?.some((c2) => c2.id === id));
26673
+ const original = before;
26731
26674
  logFile.write(durationLine(endedAt - record.startedAt));
26732
26675
  if (totalCost !== void 0) logFile.write(costLine(totalCost));
26733
26676
  if (usage3) logFile.write(usageLine(usage3));
@@ -26746,13 +26689,6 @@ ${result}
26746
26689
  if (usage3) r2.usage = usage3;
26747
26690
  if (result) r2.result = result;
26748
26691
  });
26749
- if (status === "done" && record.action === "spec" && record.cardId !== null && record.specAgent) {
26750
- const progress = readPreviewProgress(record.cardId)[record.specAgent];
26751
- if (progress && !["awaiting_confirmation", "ready"].includes(progress.stages.find((stage) => stage.id === progress.currentStageId)?.status ?? "")) {
26752
- status = "error";
26753
- failure = "The preview agent exited without submitting its current stage.";
26754
- }
26755
- }
26756
26692
  if (status !== "done" && record.action === "spec" && record.cardId !== null && record.specAgent) {
26757
26693
  updatePreviewProgress(record.cardId, (all2) => {
26758
26694
  const progress = all2[record.specAgent];
@@ -26765,7 +26701,6 @@ ${result}
26765
26701
  const noteWhy = status === "done" ? settled?.stalledWhy ?? [] : [];
26766
26702
  const saidOurs = !asked && silent && !spawnError;
26767
26703
  const errorWhy = [
26768
- ...problems ? [{ kind: "format" }] : [],
26769
26704
  ...spawnWhy ? [spawnWhy] : [],
26770
26705
  ...saidOurs ? [waited ? { kind: "backgroundSilent", args: { n: String(BACKGROUND_WAIT.minutes / 60) } } : { kind: "silent", args: { n: String(silenceFor) } }] : []
26771
26706
  ];
@@ -26791,24 +26726,13 @@ ${result}
26791
26726
  // What went wrong, in whoever's words know: ours when the command wouldn't start or
26792
26727
  // when it went quiet, the agent's own when the conversation ended badly or its
26793
26728
  // stream said so. That cause leads; a card it left half-written follows.
26794
- error: joinNotes(
26795
- spawnError ?? (asked ? void 0 : silent ? quietSaid : spoken?.error ?? failure),
26796
- problems
26797
- ),
26729
+ error: spawnError ?? (asked ? void 0 : silent ? quietSaid : spoken?.error ?? failure),
26798
26730
  note,
26799
26731
  errorWhy,
26800
26732
  noteWhy,
26801
26733
  endedAt
26802
26734
  });
26803
26735
  letGo();
26804
- if (repairing) {
26805
- const next = await resume(sessionId);
26806
- if ("error" in next) patch(sessionId, (r2) => {
26807
- r2.error = `${boardProblems(formatErrors)}
26808
- Cannot resume board repair: ${next.error}`;
26809
- r2.errorWhy = [{ kind: "format" }, { kind: "repairUnstarted", refusals: [next] }];
26810
- });
26811
- }
26812
26736
  if (retrying) {
26813
26737
  const next = await resume(sessionId);
26814
26738
  if ("error" in next) patch(sessionId, (r2) => {
@@ -26816,9 +26740,10 @@ Cannot resume board repair: ${next.error}`;
26816
26740
  r2.errorWhy = [...r2.errorWhy ?? [], { kind: "retryUnstarted", refusals: [next] }];
26817
26741
  });
26818
26742
  }
26819
- if (lost && status === "error") {
26820
- const next = await startRun(spec.again);
26821
- if (!("error" in next)) forgetRun(sessionId);
26743
+ const missingSession = record.resumedFrom && !/auth|unauthorized|forbidden|login|log.in/i.test(failure ?? spoken?.error ?? "") && /(?:no (?:conversation|session|thread) found|(?:session|conversation|thread)[^\n]*(?:not found|does not exist))/i.test(failure ?? spoken?.error ?? "");
26744
+ if (status === "error" && !asked && (lost || missingSession)) {
26745
+ const next = missingSession ? await startResume(sessionId, { deliveryId: record.deliveryId, fresh: true }) : await startRun(spec.again);
26746
+ if (!missingSession && !("error" in next)) forgetRun(sessionId);
26822
26747
  }
26823
26748
  if (status === "done") queueCompleted(before.keys());
26824
26749
  if (status === "done") await followUp(sessionId, record.flowId, settled?.runs ?? []);
@@ -26985,7 +26910,7 @@ function catchModel(sessionId, model) {
26985
26910
  });
26986
26911
  return true;
26987
26912
  }
26988
- var STOP_GRACE_MS, STOP_CLOSE_MS, STOP_FINISH_MS, silenceSaid, MAX_FORMAT_REPAIRS, joinNotes;
26913
+ var STOP_GRACE_MS, STOP_CLOSE_MS, STOP_FINISH_MS, silenceSaid, joinNotes;
26989
26914
  var init_watch = __esm({
26990
26915
  "../cli/src/lib/agent/watch.ts"() {
26991
26916
  "use strict";
@@ -26994,14 +26919,11 @@ var init_watch = __esm({
26994
26919
  init_progress();
26995
26920
  init_deliveries();
26996
26921
  init_paths();
26997
- init_reconcile();
26998
- init_spec_contract();
26999
26922
  init_store();
27000
26923
  init_own_cost();
27001
26924
  init_remove();
27002
26925
  init_prompts();
27003
26926
  init_catalog2();
27004
- init_command();
27005
26927
  init_settings2();
27006
26928
  init_flow();
27007
26929
  init_spawnable();
@@ -27017,19 +26939,17 @@ var init_watch = __esm({
27017
26939
  init_refine2();
27018
26940
  init_sessions();
27019
26941
  init_start();
27020
- init_types3();
27021
26942
  STOP_GRACE_MS = 5e3;
27022
26943
  STOP_CLOSE_MS = 2e3;
27023
26944
  STOP_FINISH_MS = 1e4;
27024
26945
  silenceSaid = (minutes) => `the agent said nothing for ${minutes} minute${minutes === 1 ? "" : "s"}, so the run was ended.`;
27025
- MAX_FORMAT_REPAIRS = 3;
27026
26946
  joinNotes = (...parts) => parts.filter(Boolean).join("\n\n") || void 0;
27027
26947
  }
27028
26948
  });
27029
26949
 
27030
26950
  // ../cli/src/commands/run.ts
27031
- import fs85 from "node:fs";
27032
- import path85 from "node:path";
26951
+ import fs86 from "node:fs";
26952
+ import path86 from "node:path";
27033
26953
  async function cmdStartRun(action, args2, opts, program2 = "akb") {
27034
26954
  if (action === "approve" && (opts.preview || opts.previewStage || opts.previewVersion || opts.definitionRevision)) return confirmLocalPreview(Number(args2[0]), opts);
27035
26955
  const { req, follow: follow2, print } = readRequest(action, args2, opts);
@@ -27188,6 +27108,12 @@ function readRequest(action, args2, opts) {
27188
27108
  return { req, follow: follow2, print };
27189
27109
  }
27190
27110
  async function cmdResume(id, opts) {
27111
+ const previous = await getRun(id ?? "last");
27112
+ const completed = previous?.deliveryId ? findDelivery(previous.deliveryId) : void 0;
27113
+ if (completed?.status === "finished" && completed.completions?.some((receipt) => receipt.finished)) {
27114
+ say(`delivery ${completed.deliveryId} is complete.`);
27115
+ return { sessionId: previous.sessionId, resumedFrom: previous.resumedFrom, delivery: deliveryOutcome(completed.deliveryId) };
27116
+ }
27191
27117
  const opened = await startResume(id ?? "last", opts.requireSession);
27192
27118
  if ("error" in opened) die(opened.error, { kind: "run-refused", ..."reason" in opened ? { reason: opened.reason } : {} });
27193
27119
  const { run: run4 } = opened;
@@ -27209,6 +27135,7 @@ async function cmdResumeDelivery(named2) {
27209
27135
  kind: "run-refused",
27210
27136
  ...res.kind === "refused" ? { reason: res.reason, args: res.args } : {}
27211
27137
  });
27138
+ if (res.landed) return { deliveryId: res.deliveryId, landed: true };
27212
27139
  const delivery = findDelivery(res.deliveryId);
27213
27140
  const started = await startRun({
27214
27141
  action: "implement",
@@ -27250,7 +27177,7 @@ async function cmdSubStart(words, opts) {
27250
27177
  let prompt = words.join(" ");
27251
27178
  if (opts.file) {
27252
27179
  try {
27253
- prompt = fs85.readFileSync(path85.resolve(opts.file), "utf8");
27180
+ prompt = fs86.readFileSync(path86.resolve(opts.file), "utf8");
27254
27181
  } catch {
27255
27182
  die(`--file: cannot read ${opts.file}`, { kind: "run-refused" });
27256
27183
  }
@@ -27388,7 +27315,7 @@ async function followRun(sessionId, already = "", program2 = "akb", events = fal
27388
27315
  const deliveryId = first.deliveryId ?? last.deliveryId;
27389
27316
  const delivery = deliveryId ? deliveryOutcome(deliveryId) : void 0;
27390
27317
  if (delivery) say(`delivery ${delivery.id}: ${delivery.line}`);
27391
- const failed = last.status !== "done" ? `run ${short(last.sessionId)} ended ${last.status}${last.error ? `: ${last.error}` : ""}` : delivery && delivery.status !== "finished" ? `delivery ${delivery.id} did not land${idle.timedOut ? ` \u2014 nothing moved it for ${ago(follow.idleMs)}` : ""}: ${delivery.line}` : void 0;
27318
+ const failed = last.status !== "done" ? `run ${short(last.sessionId)} ended ${last.status}${last.error ? `: ${last.error}` : ""}` : void 0;
27392
27319
  const held4 = peekRun(last.sessionId);
27393
27320
  const agentSession = held4 ? resumeSessionId(held4) : void 0;
27394
27321
  return {
@@ -27619,7 +27546,7 @@ var init_signals = __esm({
27619
27546
  });
27620
27547
 
27621
27548
  // ../cli/src/commands/triage.ts
27622
- import fs86 from "node:fs";
27549
+ import fs87 from "node:fs";
27623
27550
  async function cmdTriageAdd(opts) {
27624
27551
  const title = (opts.title ?? "").trim();
27625
27552
  if (!title) die('say what it is: --title "<one line>"', { kind: "needs-input" });
@@ -27629,7 +27556,7 @@ async function cmdTriageAdd(opts) {
27629
27556
  let body = opts.text;
27630
27557
  if (opts.file !== void 0) {
27631
27558
  try {
27632
- body = fs86.readFileSync(opts.file, "utf8");
27559
+ body = fs87.readFileSync(opts.file, "utf8");
27633
27560
  } catch {
27634
27561
  die(`can't read ${opts.file} \u2014 write the item to a file, then pass its path`, { kind: "needs-input" });
27635
27562
  }
@@ -27696,24 +27623,31 @@ async function cmdSpec(opts, program2 = "akb") {
27696
27623
  if (!locate(id)) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
27697
27624
  if (opts.stages !== void 0 || opts.submit || opts.reviseFrom) {
27698
27625
  try {
27699
- const run5 = previewRun(id, name);
27626
+ let run5;
27627
+ try {
27628
+ run5 = previewRun(id, name);
27629
+ } catch (error) {
27630
+ if (!(error instanceof PreviewContextMissing)) throw error;
27631
+ await activatePreviewRun(id, name);
27632
+ run5 = previewRun(id, name);
27633
+ }
27700
27634
  const ids = opts.stages?.split(",").map((id2) => id2.trim());
27701
- const result = await previewBridge(name, ids ? "select" : opts.reviseFrom ? "revise" : "submit", { run: run5.sessionId, ...ids ? { stages: ids } : opts.reviseFrom ? { stageId: opts.reviseFrom } : { baseline: readPreviewBaseline(run5.sessionId), stageId: opts.stage } });
27635
+ const result = await previewBridge(name, ids ? "select" : opts.reviseFrom ? "revise" : "submit", { run: run5.sessionId, cardId: id, ...ids ? { stages: ids } : opts.reviseFrom ? { stageId: opts.reviseFrom } : { baseline: readPreviewBaseline(id, name, run5.sessionId), stageId: opts.stage } });
27702
27636
  if (result?.progress) {
27703
27637
  updatePreviewProgress(id, (all2) => {
27704
27638
  all2[name] = result.progress;
27705
27639
  });
27706
- if (result.baseline) savePreviewBaseline(run5.sessionId, result.baseline);
27640
+ if (result.baseline) savePreviewBaseline(id, name, run5.sessionId, result.baseline);
27707
27641
  } else if (opts.reviseFrom) {
27708
27642
  updatePreviewProgress(id, (all2) => {
27709
27643
  const progress = all2[name];
27710
27644
  choosePreviewRevision(progress, opts.reviseFrom, run5.sessionId);
27711
- savePreviewBaseline(run5.sessionId, previewBaseline(progress, opts.reviseFrom, run5.sessionId));
27645
+ savePreviewBaseline(id, name, run5.sessionId, previewBaseline(progress, opts.reviseFrom, run5.sessionId));
27712
27646
  });
27713
27647
  } else if (ids) {
27714
27648
  const selected = selectLocalPreview(id, name, ids);
27715
- savePreviewBaseline(run5.sessionId, selected.baseline);
27716
- } else submitLocalPreview(id, name, opts.stage, readPreviewBaseline(run5.sessionId));
27649
+ savePreviewBaseline(id, name, run5.sessionId, selected.baseline);
27650
+ } else submitLocalPreview(id, name, opts.stage, readPreviewBaseline(id, name, run5.sessionId));
27717
27651
  if (ids || opts.reviseFrom) say(previewStagePrompt(id, name, boardCommandFor(id)));
27718
27652
  else say("Preview stage submitted. Stop here; the program controls confirmation and continuation.");
27719
27653
  return { specAgent: name, cardId: id, submitted: !!opts.submit };
@@ -27732,13 +27666,20 @@ async function cmdSpec(opts, program2 = "akb") {
27732
27666
  const req = { action: "spec", id, title: titleOf(id), specAgent: name, notes };
27733
27667
  const inside2 = insideRun();
27734
27668
  if (!inside2 && process.env[PREVIEW_BRIDGE_ENV]) opts.follow = true;
27669
+ if (opts.print === true) {
27670
+ try {
27671
+ await activatePreviewRun(id, name, void 0, notes);
27672
+ } catch (error) {
27673
+ die(error instanceof Error ? error.message : "Could not prepare the preview.", { kind: "preview-refused" });
27674
+ }
27675
+ return printFlow(req, program2);
27676
+ }
27735
27677
  if (inside2 && readRuns().find((r2) => r2.sessionId === inside2)?.action === "spec") {
27736
27678
  die(
27737
27679
  "a preview agent does not ask for another preview agent \u2014 answer the part you own and leave the rest of the card to the session planning it.",
27738
27680
  { kind: "spec-agent-recursion", specAgent: name }
27739
27681
  );
27740
27682
  }
27741
- if (opts.print === true) return printFlow(req, program2);
27742
27683
  const live = readRuns().find(
27743
27684
  (r2) => r2.status === "running" && r2.action === "spec" && r2.cardId === id && r2.specAgent === name
27744
27685
  );
@@ -44442,7 +44383,7 @@ var require_react_dom_server_legacy_node_development = __commonJS({
44442
44383
  numberOfReRenders = 0;
44443
44384
  workInProgressHook = renderPhaseUpdates = null;
44444
44385
  }
44445
- function readContext(context) {
44386
+ function readContext2(context) {
44446
44387
  isInHookUserCodeInDev && console.error(
44447
44388
  "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
44448
44389
  );
@@ -48795,7 +48736,7 @@ A.finished.finally(function(){document.__reactViewTransition===A&&(document.__re
48795
48736
  }, emptyTreeContext = { id: 1, overflow: "" }, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2, currentTaskInDEV = null, SuspenseException = Error(
48796
48737
  "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
48797
48738
  ), suspendedThenable = null, shouldCaptureSuspendedCallSite = false, suspendedCallSiteStack = null, suspendedCallSiteDebugTask = null, objectIs = "function" === typeof Object.is ? Object.is : is, currentlyRenderingComponent = null, currentlyRenderingTask = null, currentlyRenderingRequest = null, currentlyRenderingKeyPath = null, firstWorkInProgressHook = null, workInProgressHook = null, isReRender = false, didScheduleRenderPhaseUpdate = false, localIdCounter = 0, actionStateCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, thenableState = null, renderPhaseUpdates = null, numberOfReRenders = 0, isInHookUserCodeInDev = false, currentHookNameInDev, HooksDispatcher = {
48798
- readContext,
48739
+ readContext: readContext2,
48799
48740
  use: function(usable) {
48800
48741
  if (null !== usable && "object" === typeof usable) {
48801
48742
  if ("function" === typeof usable.then)
@@ -48803,7 +48744,7 @@ A.finished.finally(function(){document.__reactViewTransition===A&&(document.__re
48803
48744
  if (usable.$$typeof === REACT_RECOVERABLE_TYPE)
48804
48745
  throw createRecoverableError(usable);
48805
48746
  if (usable.$$typeof === REACT_CONTEXT_TYPE)
48806
- return readContext(usable);
48747
+ return readContext2(usable);
48807
48748
  }
48808
48749
  throw Error(
48809
48750
  "An unsupported type was passed to use(): " + String(usable)
@@ -52011,7 +51952,7 @@ var require_react_dom_server_node_development = __commonJS({
52011
51952
  numberOfReRenders = 0;
52012
51953
  workInProgressHook = renderPhaseUpdates = null;
52013
51954
  }
52014
- function readContext(context) {
51955
+ function readContext2(context) {
52015
51956
  isInHookUserCodeInDev && console.error(
52016
51957
  "Context can only be read while React is rendering. In classes, you can read it in the render method or getDerivedStateFromProps. In function components, you can read it directly in the function body, but not inside Hooks like useReducer() or useMemo()."
52017
51958
  );
@@ -56744,7 +56685,7 @@ A.finished.finally(function(){document.__reactViewTransition===A&&(document.__re
56744
56685
  }, emptyTreeContext = { id: 1, overflow: "" }, clz32 = Math.clz32 ? Math.clz32 : clz32Fallback, log = Math.log, LN2 = Math.LN2, currentTaskInDEV = null, SuspenseException = Error(
56745
56686
  "Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."
56746
56687
  ), suspendedThenable = null, shouldCaptureSuspendedCallSite = false, suspendedCallSiteStack = null, suspendedCallSiteDebugTask = null, objectIs = "function" === typeof Object.is ? Object.is : is, currentlyRenderingComponent = null, currentlyRenderingTask = null, currentlyRenderingRequest = null, currentlyRenderingKeyPath = null, firstWorkInProgressHook = null, workInProgressHook = null, isReRender = false, didScheduleRenderPhaseUpdate = false, localIdCounter = 0, actionStateCounter = 0, actionStateMatchingIndex = -1, thenableIndexCounter = 0, thenableState = null, renderPhaseUpdates = null, numberOfReRenders = 0, isInHookUserCodeInDev = false, currentHookNameInDev, HooksDispatcher = {
56747
- readContext,
56688
+ readContext: readContext2,
56748
56689
  use: function(usable) {
56749
56690
  if (null !== usable && "object" === typeof usable) {
56750
56691
  if ("function" === typeof usable.then)
@@ -56752,7 +56693,7 @@ A.finished.finally(function(){document.__reactViewTransition===A&&(document.__re
56752
56693
  if (usable.$$typeof === REACT_RECOVERABLE_TYPE)
56753
56694
  throw createRecoverableError(usable);
56754
56695
  if (usable.$$typeof === REACT_CONTEXT_TYPE)
56755
- return readContext(usable);
56696
+ return readContext2(usable);
56756
56697
  }
56757
56698
  throw Error(
56758
56699
  "An unsupported type was passed to use(): " + String(usable)
@@ -69002,8 +68943,8 @@ var require_JSXTransformer = __commonJS({
69002
68943
  }
69003
68944
  if (this.isAutomaticRuntime) {
69004
68945
  if (this.importProcessor) {
69005
- for (const [path90, resolvedName] of Object.entries(this.cjsAutomaticModuleNameResolutions)) {
69006
- prefix += `var ${resolvedName} = require("${path90}");`;
68946
+ for (const [path91, resolvedName] of Object.entries(this.cjsAutomaticModuleNameResolutions)) {
68947
+ prefix += `var ${resolvedName} = require("${path91}");`;
69007
68948
  }
69008
68949
  } else {
69009
68950
  const { createElement: createElementResolution, ...otherResolutions } = this.esmAutomaticImportNameResolutions;
@@ -69196,11 +69137,11 @@ var require_JSXTransformer = __commonJS({
69196
69137
  }
69197
69138
  claimAutoImportedName(funcName, importPathSuffix) {
69198
69139
  if (this.importProcessor) {
69199
- const path90 = this.jsxImportSource + importPathSuffix;
69200
- if (!this.cjsAutomaticModuleNameResolutions[path90]) {
69201
- this.cjsAutomaticModuleNameResolutions[path90] = this.importProcessor.getFreeIdentifierForPath(path90);
69140
+ const path91 = this.jsxImportSource + importPathSuffix;
69141
+ if (!this.cjsAutomaticModuleNameResolutions[path91]) {
69142
+ this.cjsAutomaticModuleNameResolutions[path91] = this.importProcessor.getFreeIdentifierForPath(path91);
69202
69143
  }
69203
- return `${this.cjsAutomaticModuleNameResolutions[path90]}.${funcName}`;
69144
+ return `${this.cjsAutomaticModuleNameResolutions[path91]}.${funcName}`;
69204
69145
  } else {
69205
69146
  if (!this.esmAutomaticImportNameResolutions[funcName]) {
69206
69147
  this.esmAutomaticImportNameResolutions[funcName] = this.nameManager.claimFreeName(
@@ -69636,7 +69577,7 @@ var require_CJSImportProcessor = __commonJS({
69636
69577
  */
69637
69578
  pruneTypeOnlyImports() {
69638
69579
  this.nonTypeIdentifiers = _getNonTypeIdentifiers.getNonTypeIdentifiers.call(void 0, this.tokens, this.options);
69639
- for (const [path90, importInfo] of this.importInfoByPath.entries()) {
69580
+ for (const [path91, importInfo] of this.importInfoByPath.entries()) {
69640
69581
  if (importInfo.hasBareImport || importInfo.hasStarExport || importInfo.exportStarNames.length > 0 || importInfo.namedExports.length > 0) {
69641
69582
  continue;
69642
69583
  }
@@ -69646,7 +69587,7 @@ var require_CJSImportProcessor = __commonJS({
69646
69587
  ...importInfo.namedImports.map(({ localName }) => localName)
69647
69588
  ];
69648
69589
  if (names3.every((name) => this.shouldAutomaticallyElideImportedName(name))) {
69649
- this.importsToReplace.set(path90, "");
69590
+ this.importsToReplace.set(path91, "");
69650
69591
  }
69651
69592
  }
69652
69593
  }
@@ -69654,7 +69595,7 @@ var require_CJSImportProcessor = __commonJS({
69654
69595
  return this.isTypeScriptTransformEnabled && !this.keepUnusedImports && !this.nonTypeIdentifiers.has(name);
69655
69596
  }
69656
69597
  generateImportReplacements() {
69657
- for (const [path90, importInfo] of this.importInfoByPath.entries()) {
69598
+ for (const [path91, importInfo] of this.importInfoByPath.entries()) {
69658
69599
  const {
69659
69600
  defaultNames,
69660
69601
  wildcardNames,
@@ -69664,17 +69605,17 @@ var require_CJSImportProcessor = __commonJS({
69664
69605
  hasStarExport
69665
69606
  } = importInfo;
69666
69607
  if (defaultNames.length === 0 && wildcardNames.length === 0 && namedImports.length === 0 && namedExports.length === 0 && exportStarNames.length === 0 && !hasStarExport) {
69667
- this.importsToReplace.set(path90, `require('${path90}');`);
69608
+ this.importsToReplace.set(path91, `require('${path91}');`);
69668
69609
  continue;
69669
69610
  }
69670
- const primaryImportName = this.getFreeIdentifierForPath(path90);
69611
+ const primaryImportName = this.getFreeIdentifierForPath(path91);
69671
69612
  let secondaryImportName;
69672
69613
  if (this.enableLegacyTypeScriptModuleInterop) {
69673
69614
  secondaryImportName = primaryImportName;
69674
69615
  } else {
69675
- secondaryImportName = wildcardNames.length > 0 ? wildcardNames[0] : this.getFreeIdentifierForPath(path90);
69616
+ secondaryImportName = wildcardNames.length > 0 ? wildcardNames[0] : this.getFreeIdentifierForPath(path91);
69676
69617
  }
69677
- let requireCode = `var ${primaryImportName} = require('${path90}');`;
69618
+ let requireCode = `var ${primaryImportName} = require('${path91}');`;
69678
69619
  if (wildcardNames.length > 0) {
69679
69620
  for (const wildcardName of wildcardNames) {
69680
69621
  const moduleExpr = this.enableLegacyTypeScriptModuleInterop ? primaryImportName : `${this.helperManager.getHelperName("interopRequireWildcard")}(${primaryImportName})`;
@@ -69702,7 +69643,7 @@ var require_CJSImportProcessor = __commonJS({
69702
69643
  "createStarExport"
69703
69644
  )}(${primaryImportName});`;
69704
69645
  }
69705
- this.importsToReplace.set(path90, requireCode);
69646
+ this.importsToReplace.set(path91, requireCode);
69706
69647
  for (const defaultName of defaultNames) {
69707
69648
  this.identifierReplacements.set(defaultName, `${secondaryImportName}.default`);
69708
69649
  }
@@ -69711,8 +69652,8 @@ var require_CJSImportProcessor = __commonJS({
69711
69652
  }
69712
69653
  }
69713
69654
  }
69714
- getFreeIdentifierForPath(path90) {
69715
- const components = path90.split("/");
69655
+ getFreeIdentifierForPath(path91) {
69656
+ const components = path91.split("/");
69716
69657
  const lastComponent = components[components.length - 1];
69717
69658
  const baseName = lastComponent.replace(/\W/g, "");
69718
69659
  return this.nameManager.claimFreeName(`_${baseName}`);
@@ -69757,8 +69698,8 @@ var require_CJSImportProcessor = __commonJS({
69757
69698
  if (!this.tokens.matches1AtIndex(index, _types.TokenType.string)) {
69758
69699
  throw new Error("Expected string token at the end of import statement.");
69759
69700
  }
69760
- const path90 = this.tokens.stringValueAtIndex(index);
69761
- const importInfo = this.getImportInfo(path90);
69701
+ const path91 = this.tokens.stringValueAtIndex(index);
69702
+ const importInfo = this.getImportInfo(path91);
69762
69703
  importInfo.defaultNames.push(...defaultNames);
69763
69704
  importInfo.wildcardNames.push(...wildcardNames);
69764
69705
  importInfo.namedImports.push(...namedImports);
@@ -69825,8 +69766,8 @@ var require_CJSImportProcessor = __commonJS({
69825
69766
  if (!this.tokens.matches1AtIndex(index, _types.TokenType.string)) {
69826
69767
  throw new Error("Expected string token at the end of import statement.");
69827
69768
  }
69828
- const path90 = this.tokens.stringValueAtIndex(index);
69829
- const importInfo = this.getImportInfo(path90);
69769
+ const path91 = this.tokens.stringValueAtIndex(index);
69770
+ const importInfo = this.getImportInfo(path91);
69830
69771
  importInfo.namedExports.push(...namedImports);
69831
69772
  }
69832
69773
  preprocessExportStarAtIndex(index) {
@@ -69841,8 +69782,8 @@ var require_CJSImportProcessor = __commonJS({
69841
69782
  if (!this.tokens.matches1AtIndex(index, _types.TokenType.string)) {
69842
69783
  throw new Error("Expected string token at the end of star export statement.");
69843
69784
  }
69844
- const path90 = this.tokens.stringValueAtIndex(index);
69845
- const importInfo = this.getImportInfo(path90);
69785
+ const path91 = this.tokens.stringValueAtIndex(index);
69786
+ const importInfo = this.getImportInfo(path91);
69846
69787
  if (exportedName !== null) {
69847
69788
  importInfo.exportStarNames.push(exportedName);
69848
69789
  } else {
@@ -69882,8 +69823,8 @@ var require_CJSImportProcessor = __commonJS({
69882
69823
  * Get a mutable import info object for this path, creating one if it doesn't
69883
69824
  * exist yet.
69884
69825
  */
69885
- getImportInfo(path90) {
69886
- const existingInfo = this.importInfoByPath.get(path90);
69826
+ getImportInfo(path91) {
69827
+ const existingInfo = this.importInfoByPath.get(path91);
69887
69828
  if (existingInfo) {
69888
69829
  return existingInfo;
69889
69830
  }
@@ -69896,7 +69837,7 @@ var require_CJSImportProcessor = __commonJS({
69896
69837
  exportStarNames: [],
69897
69838
  hasStarExport: false
69898
69839
  };
69899
- this.importInfoByPath.set(path90, newInfo);
69840
+ this.importInfoByPath.set(path91, newInfo);
69900
69841
  return newInfo;
69901
69842
  }
69902
69843
  addExportBinding(localName, exportedName) {
@@ -70476,16 +70417,16 @@ var require_resolve_uri_umd = __commonJS({
70476
70417
  }
70477
70418
  function parseFileUrl(input) {
70478
70419
  const match = fileRegex.exec(input);
70479
- const path90 = match[2];
70480
- return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path90) ? path90 : "/" + path90, match[3] || "", match[4] || "");
70420
+ const path91 = match[2];
70421
+ return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path91) ? path91 : "/" + path91, match[3] || "", match[4] || "");
70481
70422
  }
70482
- function makeUrl(scheme, user, host2, port, path90, query, hash2) {
70423
+ function makeUrl(scheme, user, host2, port, path91, query, hash2) {
70483
70424
  return {
70484
70425
  scheme,
70485
70426
  user,
70486
70427
  host: host2,
70487
70428
  port,
70488
- path: path90,
70429
+ path: path91,
70489
70430
  query,
70490
70431
  hash: hash2,
70491
70432
  type: 7
@@ -70515,11 +70456,11 @@ var require_resolve_uri_umd = __commonJS({
70515
70456
  url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
70516
70457
  return url;
70517
70458
  }
70518
- function stripPathFilename(path90) {
70519
- if (path90.endsWith("/.."))
70520
- return path90;
70521
- const index = path90.lastIndexOf("/");
70522
- return path90.slice(0, index + 1);
70459
+ function stripPathFilename(path91) {
70460
+ if (path91.endsWith("/.."))
70461
+ return path91;
70462
+ const index = path91.lastIndexOf("/");
70463
+ return path91.slice(0, index + 1);
70523
70464
  }
70524
70465
  function mergePaths(url, base) {
70525
70466
  normalizePath(base, base.type);
@@ -70557,14 +70498,14 @@ var require_resolve_uri_umd = __commonJS({
70557
70498
  pieces[pointer++] = piece;
70558
70499
  positive++;
70559
70500
  }
70560
- let path90 = "";
70501
+ let path91 = "";
70561
70502
  for (let i = 1; i < pointer; i++) {
70562
- path90 += "/" + pieces[i];
70503
+ path91 += "/" + pieces[i];
70563
70504
  }
70564
- if (!path90 || addTrailingSlash && !path90.endsWith("/..")) {
70565
- path90 += "/";
70505
+ if (!path91 || addTrailingSlash && !path91.endsWith("/..")) {
70506
+ path91 += "/";
70566
70507
  }
70567
- url.path = path90;
70508
+ url.path = path91;
70568
70509
  }
70569
70510
  function resolve2(input, base) {
70570
70511
  if (!input && !base)
@@ -70605,13 +70546,13 @@ var require_resolve_uri_umd = __commonJS({
70605
70546
  case 3:
70606
70547
  return queryHash;
70607
70548
  case 4: {
70608
- const path90 = url.path.slice(1);
70609
- if (!path90)
70549
+ const path91 = url.path.slice(1);
70550
+ if (!path91)
70610
70551
  return queryHash || ".";
70611
- if (isRelative(base || input) && !isRelative(path90)) {
70612
- return "./" + path90 + queryHash;
70552
+ if (isRelative(base || input) && !isRelative(path91)) {
70553
+ return "./" + path91 + queryHash;
70613
70554
  }
70614
- return path90 + queryHash;
70555
+ return path91 + queryHash;
70615
70556
  }
70616
70557
  case 5:
70617
70558
  return url.path + queryHash;
@@ -70710,10 +70651,10 @@ var require_trace_mapping_umd = __commonJS({
70710
70651
  module2.exports = __toCommonJS(trace_mapping_exports);
70711
70652
  var import_sourcemap_codec = __toESM2(require_sourcemap_codec());
70712
70653
  var import_resolve_uri = __toESM2(require_resolve_uri());
70713
- function stripFilename(path90) {
70714
- if (!path90) return "";
70715
- const index = path90.lastIndexOf("/");
70716
- return path90.slice(0, index + 1);
70654
+ function stripFilename(path91) {
70655
+ if (!path91) return "";
70656
+ const index = path91.lastIndexOf("/");
70657
+ return path91.slice(0, index + 1);
70717
70658
  }
70718
70659
  function resolver2(mapUrl, sourceRoot) {
70719
70660
  const from = stripFilename(mapUrl);
@@ -71921,9 +71862,9 @@ var require_util2 = __commonJS({
71921
71862
  /** @class */
71922
71863
  (function(_super) {
71923
71864
  __extends(VError2, _super);
71924
- function VError2(path90, message) {
71865
+ function VError2(path91, message) {
71925
71866
  var _this = _super.call(this, message) || this;
71926
- _this.path = path90;
71867
+ _this.path = path91;
71927
71868
  Object.setPrototypeOf(_this, VError2.prototype);
71928
71869
  return _this;
71929
71870
  }
@@ -71983,26 +71924,26 @@ var require_util2 = __commonJS({
71983
71924
  (_b = this._messages).push.apply(_b, best._messages);
71984
71925
  }
71985
71926
  };
71986
- DetailContext2.prototype.getError = function(path90) {
71927
+ DetailContext2.prototype.getError = function(path91) {
71987
71928
  var msgParts = [];
71988
71929
  for (var i = this._propNames.length - 1; i >= 0; i--) {
71989
71930
  var p2 = this._propNames[i];
71990
- path90 += typeof p2 === "number" ? "[" + p2 + "]" : p2 ? "." + p2 : "";
71931
+ path91 += typeof p2 === "number" ? "[" + p2 + "]" : p2 ? "." + p2 : "";
71991
71932
  var m = this._messages[i];
71992
71933
  if (m) {
71993
- msgParts.push(path90 + " " + m);
71934
+ msgParts.push(path91 + " " + m);
71994
71935
  }
71995
71936
  }
71996
- return new VError(path90, msgParts.join("; "));
71937
+ return new VError(path91, msgParts.join("; "));
71997
71938
  };
71998
- DetailContext2.prototype.getErrorDetail = function(path90) {
71939
+ DetailContext2.prototype.getErrorDetail = function(path91) {
71999
71940
  var details = [];
72000
71941
  for (var i = this._propNames.length - 1; i >= 0; i--) {
72001
71942
  var p2 = this._propNames[i];
72002
- path90 += typeof p2 === "number" ? "[" + p2 + "]" : p2 ? "." + p2 : "";
71943
+ path91 += typeof p2 === "number" ? "[" + p2 + "]" : p2 ? "." + p2 : "";
72003
71944
  var message = this._messages[i];
72004
71945
  if (message) {
72005
- details.push({ path: path90, message });
71946
+ details.push({ path: path91, message });
72006
71947
  }
72007
71948
  }
72008
71949
  var detail = null;
@@ -72815,8 +72756,8 @@ var require_dist = __commonJS({
72815
72756
  this.checkerPlain = this.ttype.getChecker(suite, false);
72816
72757
  this.checkerStrict = this.ttype.getChecker(suite, true);
72817
72758
  }
72818
- Checker2.prototype.setReportedPath = function(path90) {
72819
- this._path = path90;
72759
+ Checker2.prototype.setReportedPath = function(path91) {
72760
+ this._path = path91;
72820
72761
  };
72821
72762
  Checker2.prototype.check = function(value) {
72822
72763
  return this._doCheck(this.checkerPlain, value);
@@ -78249,9 +78190,9 @@ var require_CJSImportTransformer = __commonJS({
78249
78190
  if (shouldElideImport) {
78250
78191
  this.tokens.removeToken();
78251
78192
  } else {
78252
- const path90 = this.tokens.stringValue();
78253
- this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path90));
78254
- this.tokens.appendCode(this.importProcessor.claimImportCode(path90));
78193
+ const path91 = this.tokens.stringValue();
78194
+ this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path91));
78195
+ this.tokens.appendCode(this.importProcessor.claimImportCode(path91));
78255
78196
  }
78256
78197
  _removeMaybeImportAttributes.removeMaybeImportAttributes.call(void 0, this.tokens);
78257
78198
  if (this.tokens.matches1(_types.TokenType.semi)) {
@@ -78831,8 +78772,8 @@ var require_CJSImportTransformer = __commonJS({
78831
78772
  }
78832
78773
  if (this.tokens.matchesContextual(_keywords.ContextualKeyword._from)) {
78833
78774
  this.tokens.removeToken();
78834
- const path90 = this.tokens.stringValue();
78835
- this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path90));
78775
+ const path91 = this.tokens.stringValue();
78776
+ this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path91));
78836
78777
  _removeMaybeImportAttributes.removeMaybeImportAttributes.call(void 0, this.tokens);
78837
78778
  } else {
78838
78779
  this.tokens.appendCode(exportStatements.join(" "));
@@ -78846,8 +78787,8 @@ var require_CJSImportTransformer = __commonJS({
78846
78787
  while (!this.tokens.matches1(_types.TokenType.string)) {
78847
78788
  this.tokens.removeToken();
78848
78789
  }
78849
- const path90 = this.tokens.stringValue();
78850
- this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path90));
78790
+ const path91 = this.tokens.stringValue();
78791
+ this.tokens.replaceTokenTrimmingLeftWhitespace(this.importProcessor.claimImportCode(path91));
78851
78792
  _removeMaybeImportAttributes.removeMaybeImportAttributes.call(void 0, this.tokens);
78852
78793
  if (this.tokens.matches1(_types.TokenType.semi)) {
78853
78794
  this.tokens.removeToken();
@@ -108701,9 +108642,9 @@ var init_bundle_mjs = __esm({
108701
108642
  processClassesRecursively(value, getPart(classPartObject, key), classGroupId, theme);
108702
108643
  }
108703
108644
  };
108704
- getPart = (classPartObject, path90) => {
108645
+ getPart = (classPartObject, path91) => {
108705
108646
  let current = classPartObject;
108706
- const parts = path90.split(CLASS_PART_SEPARATOR);
108647
+ const parts = path91.split(CLASS_PART_SEPARATOR);
108707
108648
  const len = parts.length;
108708
108649
  for (let i = 0; i < len; i++) {
108709
108650
  const part = parts[i];
@@ -111953,8 +111894,8 @@ var init_dist = __esm({
111953
111894
  });
111954
111895
 
111955
111896
  // ../cli/src/lib/draw-mockup.ts
111956
- import fs87 from "node:fs";
111957
- import path86 from "node:path";
111897
+ import fs88 from "node:fs";
111898
+ import path87 from "node:path";
111958
111899
  import vm from "node:vm";
111959
111900
  async function loadPackage(id) {
111960
111901
  if (id === "react") return import_react3.default;
@@ -111967,23 +111908,23 @@ async function loadPackage(id) {
111967
111908
  return { __esModule: true, ...await load() };
111968
111909
  }
111969
111910
  function resolveFile(id, from, folder) {
111970
- const at2 = path86.resolve(path86.dirname(from), id);
111971
- if (at2 !== folder && !at2.startsWith(folder + path86.sep)) throw new Error(`${id} is outside the mockup's folder`);
111972
- const tries = path86.extname(at2) ? [at2] : [...CODE_EXTS.map((e2) => at2 + e2), ...CODE_EXTS.map((e2) => path86.join(at2, `index${e2}`))];
111973
- const file2 = tries.find((f2) => fs87.statSync(f2, { throwIfNoEntry: false })?.isFile());
111911
+ const at2 = path87.resolve(path87.dirname(from), id);
111912
+ if (at2 !== folder && !at2.startsWith(folder + path87.sep)) throw new Error(`${id} is outside the mockup's folder`);
111913
+ const tries = path87.extname(at2) ? [at2] : [...CODE_EXTS.map((e2) => at2 + e2), ...CODE_EXTS.map((e2) => path87.join(at2, `index${e2}`))];
111914
+ const file2 = tries.find((f2) => fs88.statSync(f2, { throwIfNoEntry: false })?.isFile());
111974
111915
  if (!file2) throw new Error(`no such file: ${id}`);
111975
- if (!fs87.realpathSync(file2).startsWith(fs87.realpathSync(folder) + path86.sep)) throw new Error(`${id} is outside the mockup's folder`);
111916
+ if (!fs88.realpathSync(file2).startsWith(fs88.realpathSync(folder) + path87.sep)) throw new Error(`${id} is outside the mockup's folder`);
111976
111917
  return file2;
111977
111918
  }
111978
111919
  async function readGraph(entry) {
111979
- const folder = path86.dirname(entry);
111920
+ const folder = path87.dirname(entry);
111980
111921
  const graph = { code: /* @__PURE__ */ new Map(), links: /* @__PURE__ */ new Map(), sheets: [], packages: /* @__PURE__ */ new Map() };
111981
111922
  const walk3 = async (file2) => {
111982
111923
  if (graph.code.has(file2)) return;
111983
111924
  if (graph.code.size >= MAX_FILES) throw new Error(`a mockup imports more than ${MAX_FILES} files`);
111984
111925
  let location = file2;
111985
111926
  try {
111986
- const js = (0, import_sucrase.transform)(fs87.readFileSync(file2, "utf8"), { transforms: ["typescript", "jsx", "imports"], jsxRuntime: "automatic", production: true, filePath: file2 }).code;
111927
+ const js = (0, import_sucrase.transform)(fs88.readFileSync(file2, "utf8"), { transforms: ["typescript", "jsx", "imports"], jsxRuntime: "automatic", production: true, filePath: file2 }).code;
111987
111928
  graph.code.set(file2, js);
111988
111929
  const link2 = /* @__PURE__ */ new Map();
111989
111930
  graph.links.set(file2, link2);
@@ -111997,7 +111938,7 @@ async function readGraph(entry) {
111997
111938
  const target = resolveFile(id, file2, folder);
111998
111939
  link2.set(id, target);
111999
111940
  if (!target.endsWith(".css")) await walk3(target);
112000
- else if (!graph.sheets.some((s) => s.path === target)) graph.sheets.push({ path: target, content: fs87.readFileSync(target, "utf8") });
111941
+ else if (!graph.sheets.some((s) => s.path === target)) graph.sheets.push({ path: target, content: fs88.readFileSync(target, "utf8") });
112001
111942
  }
112002
111943
  } catch (error) {
112003
111944
  throw new Error(`${location}: ${error instanceof Error ? error.message : String(error)}`);
@@ -112014,13 +111955,13 @@ function run2(script, context, name, deadline, lineOffset = 0) {
112014
111955
  async function tailwindFor(markup, sheets, folder) {
112015
111956
  const source2 = sheets.length ? sheets.map((s) => s.content).join("\n") : '@import "tailwindcss";';
112016
111957
  const compiler = await rc(source2, {
112017
- base: sheets.length ? path86.dirname(sheets[0].path) : "/",
111958
+ base: sheets.length ? path87.dirname(sheets[0].path) : "/",
112018
111959
  loadStylesheet: async (id, from) => {
112019
111960
  if (id === "tailwindcss" || id.startsWith("tailwindcss/")) return { path: "tailwindcss/index.css", base: "/", content: tailwindcss_default };
112020
111961
  if (!id.startsWith(".")) throw new Error(`a mockup cannot import ${id}`);
112021
- const at2 = path86.resolve(from, id);
112022
- if (!fs87.realpathSync(at2).startsWith(fs87.realpathSync(folder) + path86.sep)) throw new Error(`${id} is outside the mockup's folder`);
112023
- return { path: at2, base: path86.dirname(at2), content: fs87.readFileSync(at2, "utf8") };
111962
+ const at2 = path87.resolve(from, id);
111963
+ if (!fs88.realpathSync(at2).startsWith(fs88.realpathSync(folder) + path87.sep)) throw new Error(`${id} is outside the mockup's folder`);
111964
+ return { path: at2, base: path87.dirname(at2), content: fs88.readFileSync(at2, "utf8") };
112024
111965
  }
112025
111966
  });
112026
111967
  const classes = [...markup.matchAll(/class="([^"]*)"/g)].flatMap((m) => m[1].split(/\s+/));
@@ -112069,7 +112010,7 @@ ${graph.code.get(file2)}
112069
112010
  if (typeof Component !== "function") throw new Error("the mockup has no default export to draw");
112070
112011
  sandbox.__draw = () => (0, import_server.renderToStaticMarkup)(import_react3.default.createElement(Component));
112071
112012
  const markup = run2("__draw()", context, entry, deadline);
112072
- const css = (await tailwindFor(markup, graph.sheets, path86.dirname(entry))).replace(/<\/style/gi, "<\\/style");
112013
+ const css = (await tailwindFor(markup, graph.sheets, path87.dirname(entry))).replace(/<\/style/gi, "<\\/style");
112073
112014
  return `<!doctype html><html><head>${head}<style>${css}</style></head><body>${markup}</body></html>`;
112074
112015
  }
112075
112016
  var import_react3, JSX, import_server, import_sucrase, DRAW_MS, MAX_FILES, CODE_EXTS, REQUIRES, NOTHING, NEXT_LINK, NEXT_IMAGE, NEXT_NAVIGATION, PACKAGES, MOCKUP_IMPORTS;
@@ -112130,21 +112071,21 @@ var init_draw_mockup = __esm({
112130
112071
  });
112131
112072
 
112132
112073
  // ../cli/src/commands/studio-preview.ts
112133
- import fs88 from "node:fs";
112134
- import path87 from "node:path";
112074
+ import fs89 from "node:fs";
112075
+ import path88 from "node:path";
112135
112076
  import { createHash as createHash10, randomUUID as randomUUID8 } from "node:crypto";
112136
112077
  import { spawnSync as spawnSync6 } from "node:child_process";
112137
112078
  function readFolder2(folder) {
112138
- const root2 = fs88.realpathSync(folder);
112079
+ const root2 = fs89.realpathSync(folder);
112139
112080
  let count3 = 0, total = 0;
112140
112081
  const scan = (dir) => {
112141
- for (const e2 of fs88.readdirSync(dir, { withFileTypes: true })) {
112082
+ for (const e2 of fs89.readdirSync(dir, { withFileTypes: true })) {
112142
112083
  if (e2.name.startsWith(".")) continue;
112143
- const file2 = path87.join(dir, e2.name);
112084
+ const file2 = path88.join(dir, e2.name);
112144
112085
  if (e2.isSymbolicLink()) throw Error(`${file2}: symbolic links are not allowed`);
112145
112086
  if (e2.isDirectory()) scan(file2);
112146
112087
  else {
112147
- const size = fs88.statSync(file2).size;
112088
+ const size = fs89.statSync(file2).size;
112148
112089
  total += size;
112149
112090
  if (++count3 > FILE_LIMITS.count || size > FILE_LIMITS.file || total > FILE_LIMITS.total) throw Error(`${file2}: Studio file limit exceeded`);
112150
112091
  }
@@ -112166,9 +112107,9 @@ function agentsOf2(held4) {
112166
112107
  });
112167
112108
  }
112168
112109
  function unified(before, after2, file2, folder) {
112169
- const a2 = path87.join(folder, "a"), b2 = path87.join(folder, "b");
112170
- fs88.writeFileSync(a2, before ?? "");
112171
- fs88.writeFileSync(b2, after2 ?? "");
112110
+ const a2 = path88.join(folder, "a"), b2 = path88.join(folder, "b");
112111
+ fs89.writeFileSync(a2, before ?? "");
112112
+ fs89.writeFileSync(b2, after2 ?? "");
112172
112113
  const result = spawnSync6("git", ["diff", "--no-index", "--text", "--no-ext-diff", "--no-color", "--unified=3", before === null ? "/dev/null" : a2, after2 === null ? "/dev/null" : b2], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
112173
112114
  if (result.error || result.status !== 0 && result.status !== 1) throw Error(`${file2}: ${result.error?.message ?? result.stderr}`);
112174
112115
  const lines = result.stdout.split("\n"), start = lines.findIndex((l2) => l2.startsWith("--- "));
@@ -112178,20 +112119,20 @@ ${start < 0 ? "" : lines.slice(start + 2).join("\n")}`;
112178
112119
  }
112179
112120
  async function cmdStudioPreview(id, opts) {
112180
112121
  if (!locate(id)) die(`no card ${id}`, "no-such-card");
112181
- const destination = path87.join(ASSETS, String(id), "studio-review"), staging = `${destination}.${randomUUID8()}.tmp`, backup = `${destination}.${randomUUID8()}.previous`;
112122
+ const destination = path88.join(ASSETS, String(id), "studio-review"), staging = `${destination}.${randomUUID8()}.tmp`, backup = `${destination}.${randomUUID8()}.previous`;
112182
112123
  let moved = false;
112183
112124
  try {
112184
- const draft = readFolder2(path87.resolve(opts.folder)), base = opts.base === "empty" ? null : readFolder2(path87.resolve(opts.base));
112125
+ const draft = readFolder2(path88.resolve(opts.folder)), base = opts.base === "empty" ? null : readFolder2(path88.resolve(opts.base));
112185
112126
  const version = readVersion2(draft.files), baseVersion = base && readVersion2(base.files);
112186
112127
  if (base ? !version || !baseVersion || JSON.stringify(version) !== JSON.stringify(baseVersion) : version !== null) throw Error("version.json: existing Studios need matching baseline and draft versions; use --base empty only for a new Studio without version.json");
112187
112128
  const agents = [...agentsOf2(draft)];
112188
112129
  for (const a2 of base ? agentsOf2(base) : []) if (!agents.some((b2) => b2.agent === a2.agent)) agents.push(a2);
112189
- fs88.mkdirSync(staging, { recursive: true });
112130
+ fs89.mkdirSync(staging, { recursive: true });
112190
112131
  const review = { version: 2, base: base && baseVersion ? { ...baseVersion, fingerprint: base.fingerprint } : null, fingerprint: draft.fingerprint, agents, files: [], results: [] };
112191
112132
  const save3 = (file2, bytes2) => {
112192
- const target = path87.join(staging, file2);
112193
- fs88.mkdirSync(path87.dirname(target), { recursive: true });
112194
- fs88.writeFileSync(target, bytes2);
112133
+ const target = path88.join(staging, file2);
112134
+ fs89.mkdirSync(path88.dirname(target), { recursive: true });
112135
+ fs89.writeFileSync(target, bytes2);
112195
112136
  return file2;
112196
112137
  };
112197
112138
  const paths = [.../* @__PURE__ */ new Set([...Object.keys(base?.files ?? {}), ...Object.keys(draft.files)])].filter((p2) => p2 !== VERSION_FILE).sort();
@@ -112199,30 +112140,30 @@ async function cmdStudioPreview(id, opts) {
112199
112140
  const before = base?.files[file2] ?? null, after2 = draft.files[file2] ?? null;
112200
112141
  review.files.push({ path: file2, before: before === null ? null : save3(`files/${i}/before.txt`, before), after: after2 === null ? null : save3(`files/${i}/after.txt`, after2), ...before !== after2 ? { diff: save3(`files/${i}/change.diff`, unified(before, after2, file2, staging)) } : {} });
112201
112142
  }
112202
- for (const p2 of ["a", "b"]) fs88.rmSync(path87.join(staging, p2), { force: true });
112143
+ for (const p2 of ["a", "b"]) fs89.rmSync(path88.join(staging, p2), { force: true });
112203
112144
  if (opts.results) {
112204
- const manifest = fs88.realpathSync(opts.results), root2 = path87.dirname(manifest);
112205
- const results = JSON.parse(fs88.readFileSync(manifest, "utf8")), bad = resultProblem(results, new Set(agents.map((a2) => a2.agent)));
112145
+ const manifest = fs89.realpathSync(opts.results), root2 = path88.dirname(manifest);
112146
+ const results = JSON.parse(fs89.readFileSync(manifest, "utf8")), bad = resultProblem(results, new Set(agents.map((a2) => a2.agent)));
112206
112147
  if (bad) throw Error(`${opts.results}: invalid ${bad}`);
112207
112148
  const rendered = /* @__PURE__ */ new Map();
112208
112149
  const textOf = (file2) => {
112209
- const raw = rendered.get(file2) ?? fs88.readFileSync(file2, "utf8");
112150
+ const raw = rendered.get(file2) ?? fs89.readFileSync(file2, "utf8");
112210
112151
  if (/\.(html|tsx)$/i.test(file2)) for (const ref of referencesOf(manifestOf("html"), raw, true)) {
112211
112152
  if (/^(?:data:|#)/i.test(ref.src)) continue;
112212
112153
  if (/^(?:[a-z][\w+.-]*:|\/)/i.test(ref.src)) throw Error(`${file2}: external result dependency ${ref.src}`);
112213
- const target = path87.resolve(path87.dirname(file2), ref.src.replace(/[?#].*$/, ""));
112214
- if (!within(root2, target) || fs88.existsSync(target) && !within(root2, fs88.realpathSync(target))) throw Error(`${file2}: outside result folder: ${ref.src}`);
112154
+ const target = path88.resolve(path88.dirname(file2), ref.src.replace(/[?#].*$/, ""));
112155
+ if (!within(root2, target) || fs89.existsSync(target) && !within(root2, fs89.realpathSync(target))) throw Error(`${file2}: outside result folder: ${ref.src}`);
112215
112156
  }
112216
112157
  return rendered.get(file2) ?? referenceText(file2);
112217
112158
  };
112218
112159
  const collectResults = () => collectSources(referencesOf(manifestOf("studio"), { results }), manifest, {
112219
112160
  resolve: (src, owner) => {
112220
112161
  if (/^(?:[a-z][\w+.-]*:|\/|#)/i.test(src)) throw Error(`${src}: only local result files are allowed`);
112221
- const target = path87.resolve(path87.dirname(owner), src);
112162
+ const target = path88.resolve(path88.dirname(owner), src);
112222
112163
  if (!within(root2, target)) throw Error(`${src}: outside result folder`);
112223
- const real2 = fs88.realpathSync(target);
112224
- if (!within(root2, real2) || !fs88.statSync(real2).isFile()) throw Error(`${src}: outside result folder or not a file`);
112225
- if (fs88.statSync(real2).size > ASSET_FILE_LIMIT) throw Error(`${src}: over 100 MiB`);
112164
+ const real2 = fs89.realpathSync(target);
112165
+ if (!within(root2, real2) || !fs89.statSync(real2).isFile()) throw Error(`${src}: outside result folder or not a file`);
112166
+ if (fs89.statSync(real2).size > ASSET_FILE_LIMIT) throw Error(`${src}: over 100 MiB`);
112226
112167
  return { key: real2, file: real2 };
112227
112168
  },
112228
112169
  read: textOf,
@@ -112238,33 +112179,33 @@ async function cmdStudioPreview(id, opts) {
112238
112179
  }
112239
112180
  if (graph.length > 2e3) throw Error(`${opts.results}: too many result dependencies`);
112240
112181
  for (const node of graph) if (node.error || node.problems.length) throw Error(`${node.file}: ${node.error ?? node.problems[0].message}`);
112241
- const names3 = new Map(graph.map((n, i) => [n.key, `results/${i}${rendered.has(n.file) ? ".html" : path87.extname(n.file)}`]));
112242
- const resolve2 = (src, owner) => names3.get(fs88.realpathSync(path87.resolve(path87.dirname(owner), src.replace(/[?#].*$/, ""))));
112182
+ const names3 = new Map(graph.map((n, i) => [n.key, `results/${i}${rendered.has(n.file) ? ".html" : path88.extname(n.file)}`]));
112183
+ const resolve2 = (src, owner) => names3.get(fs89.realpathSync(path88.resolve(path88.dirname(owner), src.replace(/[?#].*$/, ""))));
112243
112184
  for (const node of graph) {
112244
112185
  const own = names3.get(node.key);
112245
- const content = node.data === void 0 ? fs88.readFileSync(node.file) : mapReferences(manifestOf(node.kind), node.data, (src) => path87.posix.relative(path87.posix.dirname(own), resolve2(src, node.file)));
112186
+ const content = node.data === void 0 ? fs89.readFileSync(node.file) : mapReferences(manifestOf(node.kind), node.data, (src) => path88.posix.relative(path88.posix.dirname(own), resolve2(src, node.file)));
112246
112187
  save3(own, typeof content === "string" || Buffer.isBuffer(content) ? content : JSON.stringify(content));
112247
112188
  }
112248
112189
  review.results = mapReferences(manifestOf("studio"), { results }, (src) => resolve2(src, manifest)).results;
112249
112190
  }
112250
112191
  if (!parseReview(review)) throw Error("generated review is invalid");
112251
112192
  save3("review.json", JSON.stringify(review, null, 2) + "\n");
112252
- fs88.mkdirSync(path87.dirname(destination), { recursive: true });
112253
- if (fs88.existsSync(destination)) {
112254
- fs88.renameSync(destination, backup);
112193
+ fs89.mkdirSync(path88.dirname(destination), { recursive: true });
112194
+ if (fs89.existsSync(destination)) {
112195
+ fs89.renameSync(destination, backup);
112255
112196
  moved = true;
112256
112197
  }
112257
- fs88.renameSync(staging, destination);
112258
- fs88.rmSync(backup, { recursive: true, force: true });
112198
+ fs89.renameSync(staging, destination);
112199
+ fs89.rmSync(backup, { recursive: true, force: true });
112259
112200
  const tag = `<Studio src=".assets/${id}/studio-review/review.json" />`;
112260
112201
  say(tag);
112261
- return { file: path87.join(destination, "review.json"), tag };
112202
+ return { file: path88.join(destination, "review.json"), tag };
112262
112203
  } catch (error) {
112263
- if (moved && !fs88.existsSync(destination)) fs88.renameSync(backup, destination);
112204
+ if (moved && !fs89.existsSync(destination)) fs89.renameSync(backup, destination);
112264
112205
  if (error && typeof error === "object" && "kind" in error) throw error;
112265
112206
  die(error instanceof Error ? error.message : String(error), "bad-args");
112266
112207
  } finally {
112267
- fs88.rmSync(staging, { recursive: true, force: true });
112208
+ fs89.rmSync(staging, { recursive: true, force: true });
112268
112209
  }
112269
112210
  }
112270
112211
  var within, readVersion2;
@@ -112283,7 +112224,7 @@ var init_studio_preview = __esm({
112283
112224
  init_cards();
112284
112225
  init_paths();
112285
112226
  init_io();
112286
- within = (root2, file2) => file2.startsWith(root2 + path87.sep);
112227
+ within = (root2, file2) => file2.startsWith(root2 + path88.sep);
112287
112228
  readVersion2 = (files) => {
112288
112229
  if (files[VERSION_FILE] === void 0) return null;
112289
112230
  try {
@@ -112685,9 +112626,7 @@ function declareRunning(run4, cli) {
112685
112626
  const [id] = positional(vals);
112686
112627
  await onBoard2(this, cli, () => cmdStop(id));
112687
112628
  });
112688
- verb("resume").argument("[id]", RUN_ID, String).summary("continue a run that failed, was cut off or was stopped").description(
112689
- "The one command that reaches past the board: it picks the coding agent's own session back up \u2014 the conversation it was having, with everything it had already read \u2014 while the board counts the work as a fresh run. Before resuming a creation with no card, check sign-in, project access and connection. A refusal starts no run and leaves triage unchanged. Keep the triage source and request identity; reuse any task already created in Cloud. Repairing an existing card creates no other task. Example: akb raw run resume abc12345"
112690
- ).option("-f, --follow", "watch its log instead of returning").option("--events", "with --follow: print its structured events, one JSON object per line").option("--require-session", "refuse if the original conversation cannot be resumed").action(async function(...vals) {
112629
+ verb("resume").argument("[id]", RUN_ID, String).summary("continue a run from its saved work").description("Reuse its session when available; otherwise continue the original task in the same directory. Preserve task, delivery, triage source and request identities.").option("-f, --follow", "watch its log instead of returning").option("--events", "with --follow: print its structured events, one JSON object per line").option("--require-session", "legacy option; missing sessions still use the saved task context").action(async function(...vals) {
112691
112630
  const [id] = positional(vals);
112692
112631
  await onBoard2(this, cli, () => cmdResume(id, this.opts()));
112693
112632
  });
@@ -112834,15 +112773,15 @@ var init_agent2 = __esm({
112834
112773
  });
112835
112774
 
112836
112775
  // ../cli/src/kanban.ts
112837
- import fs91 from "node:fs";
112776
+ import fs92 from "node:fs";
112838
112777
  import { fileURLToPath as fileURLToPath4 } from "node:url";
112839
112778
 
112840
112779
  // ../cli/src/lib/cli/akb.ts
112841
112780
  init_agent2();
112842
112781
 
112843
112782
  // ../cli/src/lib/cli/setup.ts
112844
- import fs90 from "node:fs";
112845
- import path89 from "node:path";
112783
+ import fs91 from "node:fs";
112784
+ import path90 from "node:path";
112846
112785
  import { fileURLToPath as fileURLToPath3 } from "node:url";
112847
112786
 
112848
112787
  // ../cli/src/commands/update.ts
@@ -112856,8 +112795,8 @@ init_paths();
112856
112795
  init_memory();
112857
112796
  init_yaml2();
112858
112797
  init_version();
112859
- import fs89 from "node:fs";
112860
- import path88 from "node:path";
112798
+ import fs90 from "node:fs";
112799
+ import path89 from "node:path";
112861
112800
  import { spawnSync as spawnSync8 } from "node:child_process";
112862
112801
  var NAME = "wildcrane";
112863
112802
  var REPO = "https://github.com/wildcrane-ai/wildcrane";
@@ -112879,10 +112818,10 @@ var Report = class {
112879
112818
  for (const line of this.notes) say(` ! ${line}`);
112880
112819
  }
112881
112820
  };
112882
- var read2 = (file2) => fs89.existsSync(file2) ? fs89.readFileSync(file2, "utf8") : null;
112821
+ var read2 = (file2) => fs90.existsSync(file2) ? fs90.readFileSync(file2, "utf8") : null;
112883
112822
  function statOf(p2) {
112884
112823
  try {
112885
- return fs89.lstatSync(p2);
112824
+ return fs90.lstatSync(p2);
112886
112825
  } catch {
112887
112826
  return null;
112888
112827
  }
@@ -112907,10 +112846,10 @@ async function cmdUpdate2(ctx) {
112907
112846
  return { updated: ctx.dir, from, to: SKILL_VERSION };
112908
112847
  }
112909
112848
  async function repairBoard(root2, report3, named2) {
112910
- const legacy2 = path88.join(root2, "docs", "kanban");
112911
- const kept2 = path88.join(root2, ".akb", "kanban");
112912
- const board2 = named2 ?? (fs89.existsSync(legacy2) ? legacy2 : kept2);
112913
- if (!fs89.existsSync(board2)) {
112849
+ const legacy2 = path89.join(root2, "docs", "kanban");
112850
+ const kept2 = path89.join(root2, ".akb", "kanban");
112851
+ const board2 = named2 ?? (fs90.existsSync(legacy2) ? legacy2 : kept2);
112852
+ if (!fs90.existsSync(board2)) {
112914
112853
  report3.notes.push("\u672A\u627E\u5230\u770B\u677F\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002");
112915
112854
  return false;
112916
112855
  }
@@ -112941,20 +112880,20 @@ function moveRuntimes(root2, board2, report3) {
112941
112880
  }
112942
112881
  }
112943
112882
  function moveLegacyMemory(board2, report3) {
112944
- const memory = path88.join(board2, "memory");
112883
+ const memory = path89.join(board2, "memory");
112945
112884
  const moved = [];
112946
112885
  for (const name of MEMORY_FILES) {
112947
- const from = path88.join(board2, name);
112886
+ const from = path89.join(board2, name);
112948
112887
  const st2 = statOf(from);
112949
112888
  if (!st2 || !st2.isFile()) continue;
112950
- fs89.mkdirSync(memory, { recursive: true });
112951
- const to = path88.join(memory, name);
112889
+ fs90.mkdirSync(memory, { recursive: true });
112890
+ const to = path89.join(memory, name);
112952
112891
  const there = read2(to);
112953
112892
  if (there === null) {
112954
- fs89.renameSync(from, to);
112893
+ fs90.renameSync(from, to);
112955
112894
  moved.push(name);
112956
112895
  } else if (there === read2(from)) {
112957
- fs89.rmSync(from);
112896
+ fs90.rmSync(from);
112958
112897
  moved.push(name);
112959
112898
  } else {
112960
112899
  report3.notes.push(`both docs/kanban/${name} and docs/kanban/memory/${name} exist and differ \u2014 merge them by hand`);
@@ -112963,23 +112902,23 @@ function moveLegacyMemory(board2, report3) {
112963
112902
  if (moved.length) report3.did.push(`moved the memory set into docs/kanban/memory/: ${moved.join(", ")}`);
112964
112903
  }
112965
112904
  function dropRecordFile(board2) {
112966
- const file2 = path88.join(board2, "record.csv");
112967
- if (!fs89.existsSync(file2)) return null;
112968
- fs89.rmSync(file2);
112905
+ const file2 = path89.join(board2, "record.csv");
112906
+ if (!fs90.existsSync(file2)) return null;
112907
+ fs90.rmSync(file2);
112969
112908
  return "removed docs/kanban/record.csv (the planning scores it fed are gone)";
112970
112909
  }
112971
112910
  function dropModuleGoals(board2, report3) {
112972
- const memory = path88.join(board2, "memory");
112973
- if (!fs89.existsSync(memory)) return;
112974
- const root2 = read2(path88.join(memory, "goal.md"));
112911
+ const memory = path89.join(board2, "memory");
112912
+ if (!fs90.existsSync(memory)) return;
112913
+ const root2 = read2(path89.join(memory, "goal.md"));
112975
112914
  let dropped = 0;
112976
- for (const entry of fs89.readdirSync(memory, { withFileTypes: true })) {
112915
+ for (const entry of fs90.readdirSync(memory, { withFileTypes: true })) {
112977
112916
  if (!entry.isDirectory()) continue;
112978
- const file2 = path88.join(memory, entry.name, "goal.md");
112917
+ const file2 = path89.join(memory, entry.name, "goal.md");
112979
112918
  const text5 = read2(file2);
112980
112919
  if (text5 === null) continue;
112981
112920
  if (text5 === root2 || text5.includes(UNFILLED) || !goalWords(text5)) {
112982
- fs89.rmSync(file2);
112921
+ fs90.rmSync(file2);
112983
112922
  dropped++;
112984
112923
  } else {
112985
112924
  report3.notes.push(
@@ -113001,10 +112940,10 @@ var PLAN_LEADS = {
113001
112940
  var GONE_LEADS = ["software-planner", "planner"];
113002
112941
  function planLeads(board2) {
113003
112942
  const leads = { ...PLAN_LEADS };
113004
- const root2 = path88.join(board2, "studios");
113005
- for (const entry of fs89.existsSync(root2) ? fs89.readdirSync(root2, { withFileTypes: true }) : []) {
112943
+ const root2 = path89.join(board2, "studios");
112944
+ for (const entry of fs90.existsSync(root2) ? fs90.readdirSync(root2, { withFileTypes: true }) : []) {
113006
112945
  if (!entry.isDirectory()) continue;
113007
- const meta = splitFrontmatter(read2(path88.join(root2, entry.name, "STUDIO.md")) ?? "").meta;
112946
+ const meta = splitFrontmatter(read2(path89.join(root2, entry.name, "STUDIO.md")) ?? "").meta;
113008
112947
  const stages = meta === null ? void 0 : parseYamlBlock(meta).stages;
113009
112948
  const plan = stages && typeof stages === "object" && !Array.isArray(stages) ? stages.plan : void 0;
113010
112949
  const lead = plan && typeof plan === "object" && !Array.isArray(plan) && typeof plan.lead === "string" ? plan.lead.trim() : "";
@@ -113013,30 +112952,30 @@ function planLeads(board2) {
113013
112952
  return leads;
113014
112953
  }
113015
112954
  function movePlanRules(board2, report3) {
113016
- const rules = path88.join(board2, "rules");
112955
+ const rules = path89.join(board2, "rules");
113017
112956
  const moved = [];
113018
112957
  for (const [id, leads] of Object.entries(planLeads(board2))) {
113019
112958
  for (const lead of leads) {
113020
- const from = path88.join(rules, `${lead}.md`);
112959
+ const from = path89.join(rules, `${lead}.md`);
113021
112960
  const rule = read2(from)?.trim();
113022
112961
  if (!rule) continue;
113023
- const to = path88.join(rules, "studios", `${id}.md`);
112962
+ const to = path89.join(rules, "studios", `${id}.md`);
113024
112963
  const there = read2(to)?.trim() ?? "";
113025
112964
  if (!there.includes(rule)) {
113026
- fs89.mkdirSync(path88.dirname(to), { recursive: true });
113027
- fs89.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
112965
+ fs90.mkdirSync(path89.dirname(to), { recursive: true });
112966
+ fs90.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
113028
112967
  `);
113029
112968
  moved.push(`${lead} \u2192 ${id}`);
113030
112969
  }
113031
112970
  }
113032
112971
  }
113033
- for (const lead of GONE_LEADS) fs89.rmSync(path88.join(rules, `${lead}.md`), { force: true });
112972
+ for (const lead of GONE_LEADS) fs90.rmSync(path89.join(rules, `${lead}.md`), { force: true });
113034
112973
  if (moved.length) report3.did.push(`made each plan agent's rule its studio's card rule (docs/kanban/rules/studios/): ${moved.join(", ")}`);
113035
112974
  }
113036
112975
  function noteOldStudios(board2, report3) {
113037
112976
  const old = (dir, file2, keys) => {
113038
- const root2 = path88.join(board2, dir);
113039
- return (fs89.existsSync(root2) ? fs89.readdirSync(root2, { withFileTypes: true }) : []).filter((e2) => e2.isDirectory() && keys.test(splitFrontmatter(read2(path88.join(root2, e2.name, file2)) ?? "").meta ?? "")).map((e2) => `docs/kanban/${dir}/${e2.name}/${file2}`);
112977
+ const root2 = path89.join(board2, dir);
112978
+ return (fs90.existsSync(root2) ? fs90.readdirSync(root2, { withFileTypes: true }) : []).filter((e2) => e2.isDirectory() && keys.test(splitFrontmatter(read2(path89.join(root2, e2.name, file2)) ?? "").meta ?? "")).map((e2) => `docs/kanban/${dir}/${e2.name}/${file2}`);
113040
112979
  };
113041
112980
  const files = [...old("studios", "STUDIO.md", /^(stages|delivers):/m), ...old("agents", "AGENT.md", /^\s+(hook|lead):/m)];
113042
112981
  if (files.length) {
@@ -113046,7 +112985,7 @@ function noteOldStudios(board2, report3) {
113046
112985
  }
113047
112986
  }
113048
112987
  function checkConfig(board2, report3) {
113049
- const current = read2(path88.join(board2, "config.md"));
112988
+ const current = read2(path89.join(board2, "config.md"));
113050
112989
  if (!current) return;
113051
112990
  const added = missingConfigKeys(current);
113052
112991
  if (added.length) {
@@ -113056,7 +112995,7 @@ function checkConfig(board2, report3) {
113056
112995
  }
113057
112996
  }
113058
112997
  function checkModules(board2, report3) {
113059
- const map2 = read2(path88.join(board2, "modules.md"));
112998
+ const map2 = read2(path89.join(board2, "modules.md"));
113060
112999
  if (map2 && map2.includes(UNFILLED)) {
113061
113000
  report3.notes.push(
113062
113001
  "docs/kanban/modules.md is still blank \u2014 write it from the repo (`akb guide module-map`)"
@@ -113110,14 +113049,14 @@ function declareSetup(program2, cli) {
113110
113049
  program2.version(SKILL_VERSION, "-v, --version", "print this version").addHelpText("beforeAll", spelled(cli.program));
113111
113050
  const dirOption = (cmd) => cmd.option("--dir <path>", "the project to work on (default: the current folder)").option("--json", "answer as one JSON object instead of prose");
113112
113051
  const where = (cmd) => {
113113
- const dir = path89.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
113114
- if (!fs90.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
113052
+ const dir = path90.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
113053
+ if (!fs91.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
113115
113054
  return dir;
113116
113055
  };
113117
113056
  dirOption(program2.command("update")).summary("\u4FEE\u590D\u5DF2\u6709\u770B\u677F\u5E76\u68C0\u67E5 CLI \u65B0\u7248\u672C").description("\u4FEE\u590D\u5DF2\u6709\u770B\u677F\u5E76\u63D0\u793A CLI \u5347\u7EA7\u547D\u4EE4\u3002\u6CA1\u6709\u770B\u677F\u65F6\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002").action(async function() {
113118
113057
  const dir = where(this);
113119
113058
  const named2 = this.optsWithGlobals().board ?? process.env.AI4KANBAN_BOARD?.trim();
113120
- const board2 = named2 ? path89.resolve(cli.cwd, named2) : null;
113059
+ const board2 = named2 ? path90.resolve(cli.cwd, named2) : null;
113121
113060
  await runAction(ctxOf(this, cli.program), {}, () => cmdUpdate2({ dir, program: cli.program, board: board2 }));
113122
113061
  });
113123
113062
  program2.command("__rules", { hidden: true }).action(function() {
@@ -113162,7 +113101,7 @@ function invokedDirectly() {
113162
113101
  const entry = process.argv[1];
113163
113102
  if (!entry) return false;
113164
113103
  try {
113165
- return fs91.realpathSync(entry) === fs91.realpathSync(SELF2);
113104
+ return fs92.realpathSync(entry) === fs92.realpathSync(SELF2);
113166
113105
  } catch {
113167
113106
  return false;
113168
113107
  }