wildcrane-runner 0.6.104 → 0.6.106

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.84 — built by runner/scripts/build.mjs. Do not edit.
2
+ // ai4kanban 0.11.86 — 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;
@@ -16691,12 +16691,12 @@ function toJSONSchema(input2, params) {
16691
16691
  processSchema(schema, ctx2);
16692
16692
  }
16693
16693
  const schemas = {};
16694
- const external = {
16694
+ const external2 = {
16695
16695
  registry: registry2,
16696
16696
  uri: params?.uri,
16697
16697
  defs
16698
16698
  };
16699
- ctx2.external = external;
16699
+ ctx2.external = external2;
16700
16700
  for (const entry of registry2._idmap.entries()) {
16701
16701
  const [key, schema] = entry;
16702
16702
  extractDefs(ctx2, schema);
@@ -22372,6 +22372,36 @@ var init_language = __esm({
22372
22372
  });
22373
22373
 
22374
22374
  // ../cli/src/lib/agent/retry.ts
22375
+ function clipSummary(text5) {
22376
+ const clean = text5.replace(/\s+/g, " ").trim();
22377
+ return clean.length > MAX_SUMMARY_CHARS ? `${clean.slice(0, MAX_SUMMARY_CHARS - 1)}\u2026` : clean;
22378
+ }
22379
+ function clipDetail(text5) {
22380
+ if (!text5) return void 0;
22381
+ const trimmed2 = text5.trim();
22382
+ if (!trimmed2) return void 0;
22383
+ return trimmed2.length > MAX_DETAIL_CHARS ? `${trimmed2.slice(0, MAX_DETAIL_CHARS - 1)}\u2026` : trimmed2;
22384
+ }
22385
+ function makeFailure(source2, rawSummary, options) {
22386
+ const summary2 = clipSummary(rawSummary) || "Execution failed.";
22387
+ const rawDetail = options?.detail?.trim() || (rawSummary.trim().length > summary2.length || rawSummary.includes("\n") ? rawSummary.trim() : void 0);
22388
+ const detail = clipDetail(rawDetail);
22389
+ return {
22390
+ ...options?.code ? { code: options.code } : {},
22391
+ source: source2,
22392
+ summary: summary2,
22393
+ ...detail && detail !== summary2 ? { detail } : {},
22394
+ ...typeof options?.retryAfterMs === "number" && Number.isFinite(options.retryAfterMs) && options.retryAfterMs >= 0 ? { retryAfterMs: options.retryAfterMs } : {}
22395
+ };
22396
+ }
22397
+ function isSessionMissingText(text5) {
22398
+ return !!text5 && SESSION_MISSING_RE.test(text5);
22399
+ }
22400
+ function isSessionMissingFailure(failure2) {
22401
+ if (!failure2) return false;
22402
+ if (failure2.code === "session_not_found" || failure2.code === "session_mismatch") return true;
22403
+ return isSessionMissingText(failure2.summary) || isSessionMissingText(failure2.detail);
22404
+ }
22375
22405
  function agentRecovery(evidence) {
22376
22406
  if (!evidence.stopped) return "unsafe";
22377
22407
  if (evidence.completed) return "report";
@@ -22379,63 +22409,142 @@ function agentRecovery(evidence) {
22379
22409
  if (evidence.session) return "resume";
22380
22410
  return evidence.replayable ? "replay" : "unsafe";
22381
22411
  }
22412
+ function retryContinuePrompt(failure2, attempt2, maxAttempts = MAX_RETRY_ATTEMPTS) {
22413
+ const head2 = attempt2 ? `Previous attempt (${attempt2}/${maxAttempts}) failed [${failure2.source}${failure2.code ? `:${failure2.code}` : ""}]: ${failure2.summary}` : `Previous execution failed [${failure2.source}${failure2.code ? `:${failure2.code}` : ""}]: ${failure2.summary}`;
22414
+ const parts = [head2];
22415
+ if (failure2.detail && failure2.detail !== failure2.summary) parts.push(`Diagnostics:
22416
+ ${failure2.detail}`);
22417
+ parts.push(recoveryPrompt);
22418
+ return parts.join("\n\n");
22419
+ }
22382
22420
  function backoffMs(attempt2, random = Math.random) {
22383
22421
  const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt2 - 2));
22384
22422
  return Math.round(step * (1 - 0.25 * random()));
22385
22423
  }
22386
22424
  function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs, task = false) {
22387
- if (!Number.isSafeInteger(attempt2) || attempt2 < 1 || failure2.level === 3) return { pause: "needs-review" };
22388
- const of = failure2.level === 1 ? 2 : 4;
22425
+ if (!Number.isSafeInteger(attempt2) || attempt2 < 1) return { pause: "unsafe" };
22426
+ const of = MAX_RETRY_ATTEMPTS;
22389
22427
  if (attempt2 >= of) return { pause: "limit" };
22390
22428
  const delay3 = failure2.retryAfterMs;
22391
22429
  const valid = delay3 !== void 0 && !Number.isNaN(delay3) && delay3 >= 0;
22392
- const wait = valid ? delay3 : failure2.level === 1 ? 0 : backoff(attempt2 + 1);
22430
+ const immediate = failure2.source === "validation" || failure2.source === "sync";
22431
+ const wait = valid ? delay3 : immediate ? 0 : backoff(attempt2 + 1);
22393
22432
  const cap = task && failure2.code === "rate_limited" && valid ? 24 * 60 * 6e4 : CAP_MS;
22394
- if (wait > cap) return { pause: "wait-too-long" };
22433
+ if (wait > cap) return { pause: "wait_too_long" };
22395
22434
  return { plan: { at: now + wait, of, failure: failure2 } };
22396
22435
  }
22436
+ function normalizeSource(raw) {
22437
+ if (SOURCES.has(raw)) return raw;
22438
+ if (raw === "provider" || raw === "harness") return "runtime";
22439
+ if (raw === "invariant") return "runner";
22440
+ return "runtime";
22441
+ }
22397
22442
  function readFailure(raw) {
22398
22443
  if (!raw || typeof raw !== "object") return;
22399
- const { code, level: level2, reason, source: source2, retryAfterMs: retryAfterMs2 } = raw;
22400
- if (typeof code !== "string" || !code || typeof reason !== "string" || level2 !== 1 && level2 !== 2 && level2 !== 3) return;
22401
- return { code, level: level2, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source2) ? { source: source2 } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
22444
+ const r = raw;
22445
+ const rawSummary = typeof r.summary === "string" && r.summary.trim() ? r.summary : typeof r.reason === "string" && r.reason.trim() ? r.reason : "";
22446
+ if (!rawSummary) return;
22447
+ const code = typeof r.code === "string" && r.code.trim() ? r.code.trim() : void 0;
22448
+ const detail = typeof r.detail === "string" ? clipDetail(r.detail) : void 0;
22449
+ const retryAfterMs2 = typeof r.retryAfterMs === "number" && Number.isFinite(r.retryAfterMs) && r.retryAfterMs >= 0 ? r.retryAfterMs : void 0;
22450
+ return {
22451
+ ...code ? { code } : {},
22452
+ source: normalizeSource(r.source),
22453
+ summary: clipSummary(rawSummary),
22454
+ ...detail && detail !== clipSummary(rawSummary) ? { detail } : {},
22455
+ ...retryAfterMs2 !== void 0 ? { retryAfterMs: retryAfterMs2 } : {}
22456
+ };
22457
+ }
22458
+ function readRetryRuntime(raw) {
22459
+ if (!raw || typeof raw !== "object") return void 0;
22460
+ const r = raw;
22461
+ if (typeof r.connector !== "string" || !r.connector.trim()) return void 0;
22462
+ return {
22463
+ connector: r.connector.trim(),
22464
+ name: typeof r.name === "string" && r.name.trim() ? r.name.trim() : null,
22465
+ model: typeof r.model === "string" && r.model.trim() ? r.model.trim() : null
22466
+ };
22467
+ }
22468
+ function readRetryRecord(raw) {
22469
+ if (!raw || typeof raw !== "object") return void 0;
22470
+ const r = raw;
22471
+ const attempt2 = r.attempt;
22472
+ const summary2 = typeof r.summary === "string" ? clipSummary(r.summary) : "";
22473
+ const at = typeof r.at === "string" && r.at.trim() ? r.at.trim() : "";
22474
+ if (typeof attempt2 !== "number" || !Number.isInteger(attempt2) || attempt2 < 1 || !summary2 || !at) return void 0;
22475
+ const runtime = readRetryRuntime(r.runtime);
22476
+ const detail = typeof r.detail === "string" ? clipDetail(r.detail) : void 0;
22477
+ const code = typeof r.code === "string" && r.code.trim() ? r.code.trim() : void 0;
22478
+ const sessionAction = SESSION_ACTIONS.has(r.sessionAction) ? r.sessionAction : void 0;
22479
+ return {
22480
+ attempt: attempt2,
22481
+ source: normalizeSource(r.source),
22482
+ ...runtime ? { runtime } : {},
22483
+ summary: summary2,
22484
+ ...detail && detail !== summary2 ? { detail } : {},
22485
+ ...code ? { code } : {},
22486
+ ...sessionAction ? { sessionAction } : {},
22487
+ at
22488
+ };
22489
+ }
22490
+ function readRetryHistory(raw) {
22491
+ if (!Array.isArray(raw)) return void 0;
22492
+ const records = raw.flatMap((entry) => {
22493
+ const parsed = readRetryRecord(entry);
22494
+ return parsed ? [parsed] : [];
22495
+ });
22496
+ return records.length ? records : void 0;
22497
+ }
22498
+ function readRetryPause(raw) {
22499
+ if (raw === "wait-too-long") return "wait_too_long";
22500
+ if (raw === "needs-review") return "limit";
22501
+ if (raw === "limit" || raw === "wait_too_long" || raw === "unsafe" || raw === "authorization" || raw === "stopped") return raw;
22502
+ return void 0;
22402
22503
  }
22403
22504
  function readRetryPlan(raw, attempt2, task = false) {
22404
22505
  if (!raw || typeof raw !== "object") return;
22405
- const { at, of, failure: rawFailure } = raw;
22506
+ const { at, of, failure: rawFailure, sessionAction } = raw;
22406
22507
  const failure2 = readFailure(rawFailure);
22407
22508
  if (!failure2 || typeof at !== "number" || !Number.isFinite(at)) return;
22408
22509
  const decision = planRetry(failure2, attempt2, Date.now(), backoffMs, task);
22409
- if ("plan" in decision && of === decision.plan.of) return { at, of, failure: failure2 };
22510
+ if ("plan" in decision && of === decision.plan.of) {
22511
+ return { at, of, failure: failure2, ...SESSION_ACTIONS.has(sessionAction) ? { sessionAction } : {} };
22512
+ }
22410
22513
  }
22411
22514
  function pauseLine(pause2, zh = translating()) {
22412
22515
  switch (pause2) {
22413
- case "needs-review":
22414
- return zh ? "\u5DF2\u6682\u505C\uFF0C\u8BF7\u68C0\u67E5\u5931\u8D25\u539F\u56E0\u540E\u7EED\u8DD1\u3002" : "Paused. Review the failure before resuming.";
22415
22516
  case "limit":
22416
22517
  return zh ? "\u5DF2\u8FBE\u5230\u81EA\u52A8\u91CD\u8BD5\u6B21\u6570\u4E0A\u9650\u3002" : "The automatic retry limit was reached.";
22417
- case "wait-too-long":
22518
+ case "wait_too_long":
22418
22519
  return zh ? "\u6240\u9700\u7B49\u5F85\u65F6\u95F4\u8D85\u8FC7\u4E24\u5206\u949F\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because the required wait exceeds two minutes.";
22419
22520
  case "unsafe":
22420
22521
  return zh ? "\u65E0\u6CD5\u786E\u8BA4\u53EF\u4EE5\u5B89\u5168\u7EED\u8DD1\uFF0C\u8BF7\u5148\u6838\u5BF9\u5DF2\u6709\u8FDB\u5EA6\u548C\u64CD\u4F5C\u7ED3\u679C\u3002" : "Check saved progress and operation results before resuming safely.";
22421
22522
  case "authorization":
22422
22523
  return zh ? "\u65E0\u6CD5\u786E\u8BA4\u7EED\u8DD1\u6388\u6743\uFF0C\u5DF2\u6682\u505C\u3002" : "Paused because authorization to resume could not be confirmed.";
22524
+ case "stopped":
22525
+ return zh ? "\u6267\u884C\u5DF2\u505C\u6B62\u3002" : "Execution stopped.";
22423
22526
  }
22424
22527
  }
22425
22528
  function retryLine(plan, attempt2, now = Date.now()) {
22426
22529
  const seconds = Math.max(0, Math.ceil((plan.at - now) / 1e3));
22427
- return `${plan.failure.reason} \u2014 retrying ${seconds ? `in ${seconds}s` : "now"} (attempt ${attempt2 + 1} of ${plan.of}).`;
22530
+ return `${plan.failure.summary} \u2014 retrying ${seconds ? `in ${seconds}s` : "now"} (attempt ${attempt2 + 1} of ${plan.of}).`;
22428
22531
  }
22429
22532
  function syncRepairPrompt(reason) {
22430
22533
  return `The Harness could not synchronize the saved result. Correct the diagnostics below, verify the original result and its attachments, then continue from the saved work. Preserve completed work and archive state. Read the task review before changing an approved output and revise its stage first.
22431
22534
 
22432
22535
  ${reason}`;
22433
22536
  }
22434
- var recoveryPrompt, BASE_MS, CAP_MS;
22537
+ var MAX_RETRY_ATTEMPTS, MAX_SUMMARY_CHARS, MAX_DETAIL_CHARS, SOURCES, SESSION_ACTIONS, SESSION_MISSING_RE, recoveryPrompt, BASE_MS, CAP_MS;
22435
22538
  var init_retry = __esm({
22436
22539
  "../cli/src/lib/agent/retry.ts"() {
22437
22540
  "use strict";
22438
22541
  init_language();
22542
+ MAX_RETRY_ATTEMPTS = 4;
22543
+ MAX_SUMMARY_CHARS = 300;
22544
+ MAX_DETAIL_CHARS = 4e3;
22545
+ SOURCES = /* @__PURE__ */ new Set(["runtime", "runner", "sync", "validation"]);
22546
+ SESSION_ACTIONS = /* @__PURE__ */ new Set(["resume", "reset_replay", "pause_unsafe"]);
22547
+ SESSION_MISSING_RE = /no rollout found for thread id|no conversation found with session id|session[_\s-]*not[_\s-]*found|session[_\s-]*mismatch|(?:session|thread|conversation)\s+\S+\s+not\s+found|unknown\s+(?:session|thread)|did not resume the requested conversation|did not return the requested session/i;
22439
22548
  recoveryPrompt = "Continue the interrupted turn in this session. Check the current state and the results of previous operations first. Preserve completed work and user decisions. Do not repeat an operation whose result has already taken effect.";
22440
22549
  BASE_MS = 15e3;
22441
22550
  CAP_MS = 12e4;
@@ -22722,8 +22831,8 @@ var init_package = __esm({
22722
22831
  "../cli/package.json"() {
22723
22832
  package_default = {
22724
22833
  name: "wildcrane",
22725
- version: "0.11.84",
22726
- akbContract: 28,
22834
+ version: "0.11.86",
22835
+ akbContract: 29,
22727
22836
  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.",
22728
22837
  keywords: [
22729
22838
  "kanban",
@@ -24341,7 +24450,7 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
24341
24450
  const events = createEventCollector();
24342
24451
  const fail = (reason, code = "provider_failed") => {
24343
24452
  failure2 = failureHint(reason);
24344
- classified = { code, level: 3, reason: failure2 };
24453
+ classified = makeFailure("runtime", failure2, { code, detail: reason });
24345
24454
  events.error(failure2);
24346
24455
  };
24347
24456
  const reader = createLineReader((line) => {
@@ -24496,7 +24605,7 @@ ${imageError(target, reason || str2(step.state))}
24496
24605
  },
24497
24606
  failure: () => failure2 || imageFailure,
24498
24607
  terminalFailure: () => terminal && !!classified,
24499
- executionFailure: () => classified ?? (imageFailure ? { code: "image_read_failed", level: 3, reason: imageFailure } : void 0),
24608
+ executionFailure: () => classified ?? (imageFailure ? makeFailure("runtime", imageFailure, { code: "image_read_failed", detail: imageFailure }) : void 0),
24500
24609
  events: events.events,
24501
24610
  activity: events.activity
24502
24611
  };
@@ -24505,6 +24614,7 @@ var CONTEXT_LOOK_EVERY_MS, KINDS, zero, usageOf, add, imagePath;
24505
24614
  var init_antigravity = __esm({
24506
24615
  "../cli/src/lib/agent/wire/antigravity.ts"() {
24507
24616
  "use strict";
24617
+ init_retry();
24508
24618
  init_prices();
24509
24619
  init_language();
24510
24620
  init_events();
@@ -24751,13 +24861,9 @@ var init_check = __esm({
24751
24861
  function executionFailure(error62) {
24752
24862
  if (error62 instanceof ExecutionError) return error62.failure;
24753
24863
  const code = str2(obj2(error62).code);
24754
- const reason = error62 instanceof Error ? error62.message : String(error62);
24755
- return {
24756
- code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
24757
- level: NETWORK.has(code) ? 2 : 3,
24758
- source: "harness",
24759
- reason
24760
- };
24864
+ const raw = error62 instanceof Error ? error62.message : String(error62);
24865
+ const resolvedCode = isSessionMissingText(raw) ? "session_not_found" : NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed";
24866
+ return makeFailure("runner", raw, { code: resolvedCode, detail: raw });
24761
24867
  }
24762
24868
  function retryAfterMs(value, now = Date.now()) {
24763
24869
  if (typeof value !== "string") return;
@@ -24767,37 +24873,48 @@ function retryAfterMs(value, now = Date.now()) {
24767
24873
  const date5 = Date.parse(header);
24768
24874
  if (Number.isFinite(date5)) return Math.max(0, date5 - now);
24769
24875
  }
24770
- function providerFailure(error62, reason) {
24876
+ function providerFailure(error62, reason, detail) {
24771
24877
  const info = obj2(error62);
24772
24878
  const status = typeof info.status === "number" ? info.status : void 0;
24773
24879
  const headers = obj2(info.headers);
24774
24880
  const wait = retryAfterMs(headers["retry-after"] ?? headers["Retry-After"]);
24775
- const code = info.code ?? info.type;
24776
- if (code === "session_not_found") return { code, source: "provider", level: 3, reason };
24777
- if (status === 401 || status === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str2(code))) {
24778
- return { code: "provider_refused", source: "provider", level: 3, reason };
24881
+ const rawCode = info.code ?? info.type;
24882
+ const fullDetail = detail || reason;
24883
+ if (rawCode === "session_not_found" || isSessionMissingText(reason) || isSessionMissingText(fullDetail)) {
24884
+ return makeFailure("runtime", reason, { code: "session_not_found", detail: fullDetail });
24885
+ }
24886
+ if (status === 401 || status === 403 || ["authentication_error", "permission_error", "invalid_request_error"].includes(str2(rawCode))) {
24887
+ return makeFailure("runtime", reason, { code: "provider_refused", detail: fullDetail });
24888
+ }
24889
+ if (status === 429 || rawCode === "rate_limit_error") {
24890
+ return makeFailure("runtime", reason, { code: "rate_limited", detail: fullDetail, retryAfterMs: wait });
24891
+ }
24892
+ if (TEMPORARY_HTTP.has(status ?? 0) || rawCode === "overloaded_error") {
24893
+ return makeFailure("runtime", reason, { code: "service_overloaded", detail: fullDetail, retryAfterMs: wait });
24894
+ }
24895
+ if (NETWORK.has(str2(rawCode))) {
24896
+ return makeFailure("runtime", reason, { code: "connection_lost", detail: fullDetail, retryAfterMs: wait });
24779
24897
  }
24780
- if (code === "rate_limit_error") return { code: "rate_limited", source: "provider", level: 2, reason, retryAfterMs: wait };
24781
- if (TEMPORARY_HTTP.has(status ?? 0) || code === "overloaded_error") return { code: "service_overloaded", source: "provider", level: 2, reason, retryAfterMs: wait };
24782
- if (NETWORK.has(str2(code))) return { code: "connection_lost", source: "provider", level: 2, reason, retryAfterMs: wait };
24783
- return { code: "provider_failed", source: "provider", level: 3, reason };
24898
+ return makeFailure("runtime", reason, { code: "provider_failed", detail: fullDetail, retryAfterMs: wait });
24784
24899
  }
24785
24900
  function codexFailure(raw, fallback) {
24786
24901
  const error62 = obj2(raw);
24787
24902
  const failure2 = readFailure(error62.wildcraneFailure);
24788
- if (failure2?.source === "harness" || failure2?.source === "invariant") return failure2;
24903
+ if (failure2) return failure2;
24789
24904
  const reason = str2(error62.message) || fallback;
24905
+ const additional = str2(error62.additionalDetails);
24906
+ const detail = [reason, additional].filter(Boolean).join("\n");
24790
24907
  const info = error62.codexErrorInfo;
24791
- if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason);
24792
- if (info === "rateLimitExceeded") return providerFailure({ ...error62, type: "rate_limit_error" }, reason);
24908
+ if (info === "serverOverloaded") return providerFailure({ ...error62, type: "overloaded_error" }, reason, detail);
24909
+ if (info === "rateLimitExceeded") return providerFailure({ ...error62, type: "rate_limit_error" }, reason, detail);
24793
24910
  const types = obj2(info);
24794
24911
  for (const kind of ["httpConnectionFailed", "responseStreamConnectionFailed", "responseStreamDisconnected", "responseTooManyFailedAttempts"]) {
24795
24912
  if (!(kind in types)) continue;
24796
24913
  const status = obj2(types[kind]).httpStatusCode;
24797
- if (typeof status === "number") return providerFailure({ ...error62, status }, reason);
24798
- if (kind !== "responseTooManyFailedAttempts") return providerFailure({ ...error62, code: "ECONNRESET" }, reason);
24914
+ if (typeof status === "number") return providerFailure({ ...error62, status }, reason, detail);
24915
+ if (kind !== "responseTooManyFailedAttempts") return providerFailure({ ...error62, code: "ECONNRESET" }, reason, detail);
24799
24916
  }
24800
- return providerFailure(error62, reason);
24917
+ return providerFailure(error62, reason, detail);
24801
24918
  }
24802
24919
  var ExecutionError, NETWORK, TEMPORARY_HTTP;
24803
24920
  var init_failures = __esm({
@@ -24807,7 +24924,7 @@ var init_failures = __esm({
24807
24924
  init_json();
24808
24925
  ExecutionError = class extends Error {
24809
24926
  constructor(failure2) {
24810
- super(failure2.reason);
24927
+ super(failure2.summary);
24811
24928
  this.failure = failure2;
24812
24929
  }
24813
24930
  failure;
@@ -24953,7 +25070,12 @@ function createStreamRenderer() {
24953
25070
  const turnUsage = usageOf2(ev.usage);
24954
25071
  if (turnUsage) usage3 = usage3 ? addUsage(usage3, turnUsage) : turnUsage;
24955
25072
  failure2 = ev.is_error === true ? whyItFailed(ev) : void 0;
24956
- classified = failure2 ? ev.subtype === "error_max_structured_output_retries" ? { code: "validation_failed", level: 1, source: "validation", reason: failure2 } : { ...apiFailure ?? providerFailure(ev.error, failure2), reason: failure2 } : void 0;
25073
+ classified = failure2 ? ev.subtype === "error_max_structured_output_retries" ? makeFailure("validation", failure2, { code: "validation_failed", detail: failure2 }) : (() => {
25074
+ const base = apiFailure ?? providerFailure(ev.error, failure2, failure2);
25075
+ const summary2 = clipSummary(failure2);
25076
+ const detail = clipDetail(failure2);
25077
+ return { ...base, summary: summary2, ...detail && detail !== summary2 ? { detail } : {} };
25078
+ })() : void 0;
24957
25079
  apiFailure = void 0;
24958
25080
  if (failure2) events.error(failure2);
24959
25081
  turns.push({
@@ -25011,6 +25133,7 @@ var ARG_KEYS, TOOL_KINDS2, SUBAGENT_TOOLS, USER_FIXES, addUsage;
25011
25133
  var init_claude_stream = __esm({
25012
25134
  "../cli/src/lib/agent/wire/claude-stream.ts"() {
25013
25135
  "use strict";
25136
+ init_retry();
25014
25137
  init_failures();
25015
25138
  init_events();
25016
25139
  init_json();
@@ -25439,7 +25562,7 @@ function createCodexStreamRenderer(carried = false) {
25439
25562
  return "";
25440
25563
  // 最终失败保留;连接提示只在没有后续成功完成时才作为失败。
25441
25564
  case "turn.failed": {
25442
- const said2 = str2(obj2(ev.error).message) || failure2?.reason || "Codex execution failed.";
25565
+ const said2 = str2(obj2(ev.error).message) || failure2?.summary || "Codex execution failed.";
25443
25566
  failure2 = codexFailure(ev.error, said2);
25444
25567
  events.error(said2);
25445
25568
  return `[error] ${said2}
@@ -25494,7 +25617,7 @@ function createCodexStreamRenderer(carried = false) {
25494
25617
  },
25495
25618
  costIncomplete: () => childSpend(subagents, since).costIncomplete || childSpend(subagents, since).costUsd !== void 0 && priceUsd(facts?.provider, turn2()?.model ?? facts?.model, own2()) === void 0 || void 0,
25496
25619
  resumeId: () => threadId,
25497
- failure: () => failure2?.reason ?? background.failure(),
25620
+ failure: () => failure2?.summary ?? background.failure(),
25498
25621
  executionFailure: () => failure2,
25499
25622
  background: () => subagents.size ? background.count() : void 0,
25500
25623
  events: events.events,
@@ -25883,7 +26006,7 @@ function connect(stdout, stdin, onCall, dialect = {}) {
25883
26006
  } else pending.ok(obj2(msg.result));
25884
26007
  }
25885
26008
  });
25886
- stdout.on("close", () => closed2(new ExecutionError({ code: "connection_lost", level: 2, reason: "The agent closed the connection." })));
26009
+ stdout.on("close", () => closed2(new ExecutionError({ code: "connection_lost", source: "runtime", summary: "The agent closed the connection." })));
25887
26010
  stdout.on("error", (err) => closed2(new ExecutionError(executionFailure(err))));
25888
26011
  stdin.on("error", (err) => closed2(new ExecutionError(executionFailure(err))));
25889
26012
  return {
@@ -26160,7 +26283,7 @@ async function oneTurn(io, options) {
26160
26283
  } catch (e) {
26161
26284
  const reason = e instanceof Error ? e.message : String(e);
26162
26285
  const failure2 = e instanceof RpcError ? providerFailure(e.data, reason) : executionFailure(e);
26163
- if (failure2.code !== "session_not_found") throw e;
26286
+ if (!(e instanceof RpcError) || obj2(e.data).code !== "session_not_found") throw e;
26164
26287
  if (!io.restartPrompt) throw new ExecutionError(failure2);
26165
26288
  const fresh = await bounded(newSession(rpc, io.cwd, mcpServers), preparingUntil - Date.now(), "ACP session/new timed out.");
26166
26289
  opened = fresh.opened;
@@ -26208,7 +26331,7 @@ async function oneTurn(io, options) {
26208
26331
  `);
26209
26332
  events.error(why2);
26210
26333
  emit();
26211
- return { ok: false, result, error: why2, failure: { code: stopReason2, level: 3, reason: why2 }, usage: usage3, context, costUsd };
26334
+ return { ok: false, result, error: why2, failure: makeFailure("runtime", why2, { code: stopReason2 }), usage: usage3, context, costUsd };
26212
26335
  }
26213
26336
  emit();
26214
26337
  return { ok: true, result, usage: usage3, context, costUsd };
@@ -26276,6 +26399,7 @@ var PROTOCOL_VERSION, CLIENT_CAPABILITIES, RESTARTED, TICKS_PER_USD, STOPPED;
26276
26399
  var init_acp = __esm({
26277
26400
  "../cli/src/lib/agent/wire/acp.ts"() {
26278
26401
  "use strict";
26402
+ init_retry();
26279
26403
  init_failures();
26280
26404
  init_acp_cost();
26281
26405
  init_conversation();
@@ -26580,7 +26704,7 @@ function event(envelope2, parts, tail, live, ended) {
26580
26704
  case "turn.failed": {
26581
26705
  const error62 = obj2(payload.error);
26582
26706
  const failure2 = providerFailure(error62, str2(error62.message) || "the turn failed");
26583
- return ended({ ok: false, error: failure2.reason, failure: failure2 });
26707
+ return ended({ ok: false, error: failure2.summary, failure: failure2 });
26584
26708
  }
26585
26709
  case "session.closed":
26586
26710
  return ended({ ok: false, error: str2(payload.reason) || "the agent closed the session" });
@@ -26673,6 +26797,18 @@ function createIdleWatchdog(expired, busy = () => false, milliseconds = IDLE_TIM
26673
26797
  check2();
26674
26798
  return;
26675
26799
  }
26800
+ if (e.kind === "retry") {
26801
+ if (e.data.state === "waiting" || e.data.state === "retrying") {
26802
+ recoveringAt ??= now();
26803
+ const target = e.data.nextRetryAt ? Date.parse(e.data.nextRetryAt) : NaN;
26804
+ const waitUntil = Number.isFinite(target) ? Math.max(target + 3e4, now() + PROVIDER_RETRY_MS.announcement) : now() + PROVIDER_RETRY_MS.announcement;
26805
+ retryUntil = Math.min(waitUntil, recoveringAt + PROVIDER_RETRY_MS.episode);
26806
+ } else {
26807
+ touch();
26808
+ }
26809
+ check2();
26810
+ return;
26811
+ }
26676
26812
  if (e.kind === "log" || e.kind === "context") return;
26677
26813
  if (e.kind === "phase" && !e.data.contentAt) return;
26678
26814
  const key = e.kind === "tool_call" || e.kind === "tool_call_update" ? `${e.kind}:${e.data.toolCallId}` : e.kind;
@@ -26700,7 +26836,7 @@ var init_idle = __esm({
26700
26836
  IDLE_MS = 5 * 6e4;
26701
26837
  IDLE_TIMEOUT = { milliseconds: IDLE_MS };
26702
26838
  IDLE_ERROR = "No response for 5 minutes (idle timeout).";
26703
- IDLE_FAILURE = { code: "idle_timeout", level: 2, reason: IDLE_ERROR };
26839
+ IDLE_FAILURE = { code: "idle_timeout", source: "runtime", summary: IDLE_ERROR };
26704
26840
  PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
26705
26841
  }
26706
26842
  });
@@ -27061,12 +27197,12 @@ async function run(io, options, count3) {
27061
27197
  const costUsd = cost === void 0 ? child.costUsd : cost + (child.costUsd ?? 0);
27062
27198
  const failure2 = error62 || (cleanup.status === "unconfirmed" ? cleanup.detail : void 0) || work.work().filter((w) => !w.intentionalStop && ["failed", "interrupted"].includes(w.status)).map((w) => w.result || `Background work ${w.id} ${w.status}.`).join("\n") || void 0;
27063
27199
  if (failure2) io.event?.({ kind: "error", data: { text: failure2 } });
27064
- resolve2({ ok: !failure2, error: failure2, failure: failure2 ? classified ?? { code: "execution_failed", level: 3, reason: failure2 } : void 0, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
27200
+ resolve2({ ok: !failure2, error: failure2, failure: failure2 ? classified ?? makeFailure("runtime", failure2, { code: "execution_failed", detail: failure2 }) : void 0, cleanup, result: renderer.result(), replyParts: renderer.replyParts?.(), usage: combinedUsage, context, costUsd, costIncomplete: child.costIncomplete || cost === void 0 && child.costUsd !== void 0 || void 0 });
27065
27201
  };
27066
27202
  const closed2 = () => {
27067
27203
  const reason = "Codex connection closed before all work and results finished.";
27068
27204
  if (work.work().some((w) => ["running", "unknown"].includes(w.status))) note("Connection lost; managed cleanup is unconfirmed.");
27069
- end2(reason, { code: "connection_lost", level: 2, reason });
27205
+ end2(reason, makeFailure("runtime", reason, { code: "connection_lost", detail: reason }));
27070
27206
  };
27071
27207
  const inputFailed = (e) => {
27072
27208
  if (work.work().some((w) => ["running", "unknown"].includes(w.status))) note("Connection input failed; managed cleanup is unconfirmed.");
@@ -27105,7 +27241,7 @@ async function run(io, options, count3) {
27105
27241
  } catch (error62) {
27106
27242
  if (!ended) note(error62 instanceof Error ? error62.message : String(error62));
27107
27243
  }
27108
- if (!ended) end2(IDLE_FAILURE.reason, IDLE_FAILURE);
27244
+ if (!ended) end2(IDLE_FAILURE.summary, IDLE_FAILURE);
27109
27245
  };
27110
27246
  io.idleSignal?.addEventListener("abort", idle, { once: true });
27111
27247
  const childUpdates = () => {
@@ -27365,10 +27501,24 @@ async function run(io, options, count3) {
27365
27501
  const failure2 = codexFailure(p.error, "Codex failed.");
27366
27502
  if (p.willRetry === true && submitted && active3 && !idling) {
27367
27503
  status = "retrying";
27368
- io.log(`[Codex recovery] ${failure2.code}: ${failure2.reason}
27504
+ io.log(`[Codex recovery] ${failure2.code ?? "error"}: ${failure2.summary}
27369
27505
  `);
27370
27506
  io.event?.({ kind: "status", data: { state: "retrying", source: "codex", code: failure2.code } });
27371
- } else if (p.willRetry !== true) end2(failure2.reason, failure2);
27507
+ io.event?.({
27508
+ kind: "retry",
27509
+ data: {
27510
+ state: "retrying",
27511
+ source: "runtime",
27512
+ runtime: { connector: "codex", name: null, model: model ?? null },
27513
+ attempt: 1,
27514
+ maxAttempts: MAX_RETRY_ATTEMPTS,
27515
+ summary: failure2.summary,
27516
+ ...failure2.detail ? { detail: failure2.detail } : {},
27517
+ ...failure2.code ? { code: failure2.code } : {},
27518
+ at: (/* @__PURE__ */ new Date()).toISOString()
27519
+ }
27520
+ });
27521
+ } else if (p.willRetry !== true) end2(failure2.summary, failure2);
27372
27522
  }
27373
27523
  if (msg.method === "turn/completed") {
27374
27524
  const turn2 = obj2(p.turn);
@@ -27382,7 +27532,7 @@ async function run(io, options, count3) {
27382
27532
  if (idling) return;
27383
27533
  if (turn2.status !== "completed") {
27384
27534
  const reason = str2(obj2(turn2.error).message) || `Codex turn ${str2(turn2.status)}.`;
27385
- const failure2 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : { code: "turn_stopped", level: 3, reason };
27535
+ const failure2 = turn2.status === "failed" ? codexFailure(turn2.error, reason) : makeFailure("runtime", reason, { code: "turn_stopped", detail: reason });
27386
27536
  end2(reason, failure2);
27387
27537
  return;
27388
27538
  }
@@ -27419,11 +27569,15 @@ async function run(io, options, count3) {
27419
27569
  try {
27420
27570
  response = await bounded(rpc.call(method, params), preparingUntil - Date.now(), `Codex ${method} timed out.`);
27421
27571
  } catch (error62) {
27572
+ if (mode === "fork" && error62 instanceof RpcError && error62.code === -32600 && error62.message === `no rollout found for thread id ${params.threadId}`) {
27573
+ end2(error62.message, { code: "codex_fork_source_missing", source: "runtime", summary: error62.message, detail: error62.message });
27574
+ return done;
27575
+ }
27422
27576
  const failure2 = error62 instanceof RpcError ? codexFailure(error62.data, error62.message) : void 0;
27423
- if (mode !== "fork" || failure2?.source !== "harness" || failure2.code !== "codex_source_busy") throw error62;
27577
+ if (mode !== "fork" || failure2?.code !== "codex_source_busy") throw error62;
27424
27578
  if (!waiting) {
27425
27579
  waiting = true;
27426
- io.event?.({ kind: "log", data: { text: failure2.reason } });
27580
+ io.event?.({ kind: "log", data: { text: failure2.summary } });
27427
27581
  }
27428
27582
  io.activity?.();
27429
27583
  await delay(500, void 0, { signal: io.signal });
@@ -27449,7 +27603,7 @@ async function run(io, options, count3) {
27449
27603
  await start(io.prompt, options.images);
27450
27604
  } catch (e) {
27451
27605
  const failure2 = e instanceof RpcError ? codexFailure(e.data, e.message) : executionFailure(e);
27452
- end2(failure2.reason, failure2);
27606
+ end2(failure2.summary, failure2);
27453
27607
  }
27454
27608
  return done;
27455
27609
  }
@@ -27458,6 +27612,7 @@ var init_codex = __esm({
27458
27612
  "../cli/src/lib/agent/wire/codex.ts"() {
27459
27613
  "use strict";
27460
27614
  init_idle();
27615
+ init_retry();
27461
27616
  init_failures();
27462
27617
  init_conversation();
27463
27618
  init_codex_background();
@@ -29129,6 +29284,22 @@ var init_settings2 = __esm({
29129
29284
  });
29130
29285
 
29131
29286
  // ../cli/src/lib/agent/runtimes.ts
29287
+ import fs27 from "node:fs";
29288
+ function executionRuntimes() {
29289
+ const encoded = process.env[EXECUTION_RUNTIMES_ENV];
29290
+ return encoded ? JSON.parse(encoded) : void 0;
29291
+ }
29292
+ function readRuntimeCredentials(file2) {
29293
+ try {
29294
+ return configBlock(JSON.parse(fs27.readFileSync(file2, "utf8")));
29295
+ } catch {
29296
+ return {};
29297
+ }
29298
+ }
29299
+ function runRuntimeById(id2) {
29300
+ const scope = executionRuntimes();
29301
+ return scope ? [scope.default, ...Object.values(scope.picks)].find((row) => row.id === id2) : runtimeById(id2);
29302
+ }
29132
29303
  function readRuntimes(cfg = safeConfig()) {
29133
29304
  const saved = Array.isArray(cfg.runtimes) ? cfg.runtimes.map(parseRuntime).filter(isRuntime) : null;
29134
29305
  const list3 = saved?.length ? dedupe(saved) : [];
@@ -29243,7 +29414,7 @@ function writePicks(cfg, picks, list3 = readRuntimes(cfg)) {
29243
29414
  if (Object.keys(block).length) cfg.agentRuntime = block;
29244
29415
  else delete cfg.agentRuntime;
29245
29416
  }
29246
- var GLOBAL_ID, GLOBAL_NAME, isRuntime, runtimeSecretVar, keepsPick, noRuntime, noHarness;
29417
+ var GLOBAL_ID, GLOBAL_NAME, EXECUTION_RUNTIMES_ENV, isRuntime, runtimeSecretVar, keepsPick, noRuntime, noHarness;
29247
29418
  var init_runtimes = __esm({
29248
29419
  "../cli/src/lib/agent/runtimes.ts"() {
29249
29420
  "use strict";
@@ -29252,6 +29423,7 @@ var init_runtimes = __esm({
29252
29423
  init_types3();
29253
29424
  GLOBAL_ID = "global";
29254
29425
  GLOBAL_NAME = "Global default";
29426
+ EXECUTION_RUNTIMES_ENV = "AI4KANBAN_EXECUTION_RUNTIMES";
29255
29427
  isRuntime = (r) => r !== null;
29256
29428
  runtimeSecretVar = (env2, runtime) => runtime.secretRefs?.[env2] ?? secretVar(env2, runtime.id);
29257
29429
  keepsPick = (id2) => !!id2 && id2 !== GLOBAL_ID;
@@ -29272,11 +29444,11 @@ var init_slug = __esm({
29272
29444
  });
29273
29445
 
29274
29446
  // ../cli/src/lib/validate.ts
29275
- import fs27 from "node:fs";
29447
+ import fs28 from "node:fs";
29276
29448
  import path30 from "node:path";
29277
29449
  function moduleNames() {
29278
- if (!fs27.existsSync(MODULES_MD)) return null;
29279
- return moduleNamesFrom(fs27.readFileSync(MODULES_MD, "utf8"));
29450
+ if (!fs28.existsSync(MODULES_MD)) return null;
29451
+ return moduleNamesFrom(fs28.readFileSync(MODULES_MD, "utf8"));
29280
29452
  }
29281
29453
  function validModules(mods) {
29282
29454
  const known2 = moduleNames();
@@ -29311,7 +29483,7 @@ function dependencyCycle(id2, dep) {
29311
29483
  const found2 = locate(at);
29312
29484
  if (!found2) return null;
29313
29485
  const file2 = found2.kind === "group" ? path30.join(found2.target, "root.md") : found2.target;
29314
- const nexts = parseFrontmatter(fs27.readFileSync(file2, "utf8")).meta?.blocked_by ?? [];
29486
+ const nexts = parseFrontmatter(fs28.readFileSync(file2, "utf8")).meta?.blocked_by ?? [];
29315
29487
  if (found2.kind === "group") nexts.push(...groupMembers(found2.target));
29316
29488
  for (const next of nexts) {
29317
29489
  const rest2 = walk3(next);
@@ -29339,7 +29511,7 @@ var init_validate = __esm({
29339
29511
  });
29340
29512
 
29341
29513
  // ../cli/src/lib/memory.ts
29342
- import fs28 from "node:fs";
29514
+ import fs29 from "node:fs";
29343
29515
  import path31 from "node:path";
29344
29516
  function scaffoldProjectMemory() {
29345
29517
  const board2 = scaffoldMemoryDir(MEMORY, setOf(BOARD_MEMORY_FILES));
@@ -29347,13 +29519,13 @@ function scaffoldProjectMemory() {
29347
29519
  return board2 ?? planner;
29348
29520
  }
29349
29521
  function scaffoldMemoryDir(dir, set2) {
29350
- const existed = fs28.existsSync(dir);
29351
- fs28.mkdirSync(dir, { recursive: true });
29522
+ const existed = fs29.existsSync(dir);
29523
+ fs29.mkdirSync(dir, { recursive: true });
29352
29524
  const made = [];
29353
29525
  for (const [name, body] of Object.entries(set2)) {
29354
29526
  const file2 = path31.join(dir, name);
29355
- if (!fs28.existsSync(file2)) {
29356
- fs28.writeFileSync(file2, body);
29527
+ if (!fs29.existsSync(file2)) {
29528
+ fs29.writeFileSync(file2, body);
29357
29529
  made.push(name);
29358
29530
  }
29359
29531
  }
@@ -29363,7 +29535,7 @@ function scaffoldMemoryDir(dir, set2) {
29363
29535
  function plannerModules() {
29364
29536
  let dirs2;
29365
29537
  try {
29366
- dirs2 = fs28.readdirSync(agentMemoryDir(PLANNER), { withFileTypes: true }).filter((e) => e.isDirectory() && isModule(e.name)).map((e) => e.name);
29538
+ dirs2 = fs29.readdirSync(agentMemoryDir(PLANNER), { withFileTypes: true }).filter((e) => e.isDirectory() && isModule(e.name)).map((e) => e.name);
29367
29539
  } catch {
29368
29540
  return [];
29369
29541
  }
@@ -29375,7 +29547,7 @@ function memoryDirectories(board2) {
29375
29547
  const walk3 = (dir, depth3, scoped = true) => {
29376
29548
  let entries2;
29377
29549
  try {
29378
- entries2 = fs28.readdirSync(dir, { withFileTypes: true });
29550
+ entries2 = fs29.readdirSync(dir, { withFileTypes: true });
29379
29551
  } catch {
29380
29552
  return [];
29381
29553
  }
@@ -29389,7 +29561,7 @@ function memoryDirectories(board2) {
29389
29561
  ...walk3(path31.join(root2, "previews"), 3),
29390
29562
  ...walk3(path31.join(root2, "studios"), 1, false),
29391
29563
  path31.join(root2, "agents", PLANNER)
29392
- ].filter((dir) => fs28.existsSync(dir)).map((dir) => `${dir}/`);
29564
+ ].filter((dir) => fs29.existsSync(dir)).map((dir) => `${dir}/`);
29393
29565
  }
29394
29566
  var PLANNER, PLANNER_MEMORY_FILES, BOARD_MEMORY_FILES, STARTERS, setOf, RESERVED_MEMORY_DIR, STUDIO_MEMORY_DIR, agentMemoryDir, agentMemoryFile, writtenMemoryNames, memoryNamesOf, agentMemoryFiles, RESERVED_MODULE_NAMES, isModule, moduleMemoryFile, plannerCopies;
29395
29567
  var init_memory = __esm({
@@ -29438,7 +29610,7 @@ edits here do not last.
29438
29610
  agentMemoryFile = (agent, name) => path31.join(agentMemoryDir(agent), name);
29439
29611
  writtenMemoryNames = (agent) => {
29440
29612
  try {
29441
- return fs28.readdirSync(agentMemoryDir(agent), { withFileTypes: true }).filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) => e.name).sort();
29613
+ return fs29.readdirSync(agentMemoryDir(agent), { withFileTypes: true }).filter((e) => e.isFile() && e.name.endsWith(".md")).map((e) => e.name).sort();
29442
29614
  } catch {
29443
29615
  return [];
29444
29616
  }
@@ -29450,7 +29622,7 @@ edits here do not last.
29450
29622
  moduleMemoryFile = (module, name) => path31.join(agentMemoryDir(PLANNER), module, name);
29451
29623
  plannerCopies = (name) => [
29452
29624
  agentMemoryFile(PLANNER, name),
29453
- ...plannerModules().map((m) => moduleMemoryFile(m, name)).filter((file2) => fs28.existsSync(file2))
29625
+ ...plannerModules().map((m) => moduleMemoryFile(m, name)).filter((file2) => fs29.existsSync(file2))
29454
29626
  ];
29455
29627
  }
29456
29628
  });
@@ -43121,14 +43293,14 @@ var require_parser = __commonJS({
43121
43293
  case "scalar":
43122
43294
  case "single-quoted-scalar":
43123
43295
  case "double-quoted-scalar": {
43124
- const fs90 = this.flowScalar(this.type);
43296
+ const fs91 = this.flowScalar(this.type);
43125
43297
  if (atNextItem || it.value) {
43126
- map3.items.push({ start, key: fs90, sep: [] });
43298
+ map3.items.push({ start, key: fs91, sep: [] });
43127
43299
  this.onKeyLine = true;
43128
43300
  } else if (it.sep) {
43129
- this.stack.push(fs90);
43301
+ this.stack.push(fs91);
43130
43302
  } else {
43131
- Object.assign(it, { key: fs90, sep: [] });
43303
+ Object.assign(it, { key: fs91, sep: [] });
43132
43304
  this.onKeyLine = true;
43133
43305
  }
43134
43306
  return;
@@ -43256,13 +43428,13 @@ var require_parser = __commonJS({
43256
43428
  case "scalar":
43257
43429
  case "single-quoted-scalar":
43258
43430
  case "double-quoted-scalar": {
43259
- const fs90 = this.flowScalar(this.type);
43431
+ const fs91 = this.flowScalar(this.type);
43260
43432
  if (!it || it.value)
43261
- fc.items.push({ start: [], key: fs90, sep: [] });
43433
+ fc.items.push({ start: [], key: fs91, sep: [] });
43262
43434
  else if (it.sep)
43263
- this.stack.push(fs90);
43435
+ this.stack.push(fs91);
43264
43436
  else
43265
- Object.assign(it, { key: fs90, sep: [] });
43437
+ Object.assign(it, { key: fs91, sep: [] });
43266
43438
  return;
43267
43439
  }
43268
43440
  case "flow-map-end":
@@ -43948,10 +44120,10 @@ var init_studio_files = __esm({
43948
44120
  });
43949
44121
 
43950
44122
  // ../cli/src/lib/agent/studio-folder.ts
43951
- import fs29 from "node:fs";
44123
+ import fs30 from "node:fs";
43952
44124
  import path32 from "node:path";
43953
44125
  function filesOf(dir, base = dir) {
43954
- return fs29.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".")).flatMap((e) => {
44126
+ return fs30.readdirSync(dir, { withFileTypes: true }).filter((e) => !e.name.startsWith(".")).flatMap((e) => {
43955
44127
  const full = path32.join(dir, e.name);
43956
44128
  if (e.isSymbolicLink()) throw new Error(`${full}: symbolic links are not allowed`);
43957
44129
  return e.isDirectory() ? filesOf(full, base) : [path32.relative(base, full).split(path32.sep).join("/")];
@@ -43959,7 +44131,7 @@ function filesOf(dir, base = dir) {
43959
44131
  }
43960
44132
  function readStudioFile(dir, file2) {
43961
44133
  const full = path32.join(dir, file2);
43962
- return isAboutFile(file2) && !file2.endsWith(".md") ? `data:${MIME[path32.extname(file2)]};base64,${fs29.readFileSync(full).toString("base64")}` : fs29.readFileSync(full, "utf8");
44134
+ return isAboutFile(file2) && !file2.endsWith(".md") ? `data:${MIME[path32.extname(file2)]};base64,${fs30.readFileSync(full).toString("base64")}` : fs30.readFileSync(full, "utf8");
43963
44135
  }
43964
44136
  var MIME, readStudioFolder;
43965
44137
  var init_studio_folder = __esm({
@@ -43973,7 +44145,7 @@ var init_studio_folder = __esm({
43973
44145
 
43974
44146
  // ../official/pack.ts
43975
44147
  import crypto2 from "node:crypto";
43976
- import fs30 from "node:fs";
44148
+ import fs31 from "node:fs";
43977
44149
  import path33 from "node:path";
43978
44150
  import { fileURLToPath } from "node:url";
43979
44151
  function packOfficial(root2 = OFFICIAL, loose = false) {
@@ -44005,32 +44177,32 @@ var init_pack = __esm({
44005
44177
  init_studio_folder();
44006
44178
  init_studio_files();
44007
44179
  OFFICIAL = path33.dirname(fileURLToPath(import.meta.url));
44008
- dirs = (dir) => fs30.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
44180
+ dirs = (dir) => fs31.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
44009
44181
  hashOf = (files) => crypto2.createHash("sha256").update(hashInput(files)).digest("hex");
44010
44182
  }
44011
44183
  });
44012
44184
 
44013
44185
  // ../cli/src/lib/agent/cloud-studios.ts
44014
- import fs31 from "node:fs";
44186
+ import fs32 from "node:fs";
44015
44187
  import path34 from "node:path";
44016
44188
  function readJson(file2) {
44017
44189
  try {
44018
- return JSON.parse(fs31.readFileSync(file2, "utf8"));
44190
+ return JSON.parse(fs32.readFileSync(file2, "utf8"));
44019
44191
  } catch {
44020
44192
  return null;
44021
44193
  }
44022
44194
  }
44023
44195
  function writeJson(file2, value) {
44024
- fs31.mkdirSync(path34.dirname(file2), { recursive: true });
44196
+ fs32.mkdirSync(path34.dirname(file2), { recursive: true });
44025
44197
  const tmp = `${file2}.${process.pid}.tmp`;
44026
- fs31.writeFileSync(tmp, `${JSON.stringify(value)}
44198
+ fs32.writeFileSync(tmp, `${JSON.stringify(value)}
44027
44199
  `);
44028
- fs31.renameSync(tmp, file2);
44200
+ fs32.renameSync(tmp, file2);
44029
44201
  }
44030
44202
  function heldStudioName(name) {
44031
44203
  let files;
44032
44204
  try {
44033
- files = fs31.readdirSync(path34.join(root(), "versions"));
44205
+ files = fs32.readdirSync(path34.join(root(), "versions"));
44034
44206
  } catch {
44035
44207
  return "";
44036
44208
  }
@@ -44041,7 +44213,7 @@ function heldStudioName(name) {
44041
44213
  }
44042
44214
  function saveVersion(held4) {
44043
44215
  const file2 = versionFile(held4.id, held4.version);
44044
- if (!fs31.existsSync(file2)) writeJson(file2, { id: held4.id, version: held4.version, name: held4.name, names: held4.names, files: held4.files });
44216
+ if (!fs32.existsSync(file2)) writeJson(file2, { id: held4.id, version: held4.version, name: held4.name, names: held4.names, files: held4.files });
44045
44217
  }
44046
44218
  function savePin(task, held4) {
44047
44219
  saveVersion(held4);
@@ -44246,7 +44418,7 @@ var init_studio_file = __esm({
44246
44418
  });
44247
44419
 
44248
44420
  // ../cli/src/lib/agent/studios.ts
44249
- import fs32 from "node:fs";
44421
+ import fs33 from "node:fs";
44250
44422
  import path35 from "node:path";
44251
44423
  function noStudioMessage(id2) {
44252
44424
  const name = heldStudioName(id2 ?? "") || id2;
@@ -44259,7 +44431,7 @@ function knownStudio(id2) {
44259
44431
  }
44260
44432
  function userStudioRules(flow) {
44261
44433
  try {
44262
- return fs32.readFileSync(studioRuleFile(flow.id), "utf8").trim();
44434
+ return fs33.readFileSync(studioRuleFile(flow.id), "utf8").trim();
44263
44435
  } catch {
44264
44436
  return "";
44265
44437
  }
@@ -44269,7 +44441,7 @@ function cardMeta(id2) {
44269
44441
  const found2 = locate(id2) ?? locateArchived(id2);
44270
44442
  if (!found2) return null;
44271
44443
  const file2 = found2.kind === "group" ? path35.join(found2.target, "root.md") : found2.target;
44272
- return parseFrontmatter(fs32.readFileSync(file2, "utf8")).meta;
44444
+ return parseFrontmatter(fs33.readFileSync(file2, "utf8")).meta;
44273
44445
  } catch {
44274
44446
  return null;
44275
44447
  }
@@ -44933,7 +45105,7 @@ var init_parse3 = __esm({
44933
45105
  });
44934
45106
 
44935
45107
  // ../cli/src/lib/agents/catalog.ts
44936
- import fs33 from "node:fs";
45108
+ import fs34 from "node:fs";
44937
45109
  import path37 from "node:path";
44938
45110
  function readCatalog() {
44939
45111
  const agents = [];
@@ -44991,7 +45163,7 @@ function readBundled(folder2) {
44991
45163
  function projectFolders(root2) {
44992
45164
  let entries2;
44993
45165
  try {
44994
- entries2 = fs33.readdirSync(root2, { withFileTypes: true });
45166
+ entries2 = fs34.readdirSync(root2, { withFileTypes: true });
44995
45167
  } catch {
44996
45168
  return [];
44997
45169
  }
@@ -45002,9 +45174,9 @@ function agentFileReader(dir) {
45002
45174
  const target = path37.resolve(dir, relative);
45003
45175
  if (target !== dir && !target.startsWith(dir + path37.sep)) return null;
45004
45176
  try {
45005
- const real2 = fs33.realpathSync(target);
45006
- if (!real2.startsWith(fs33.realpathSync(dir) + path37.sep)) return null;
45007
- return fs33.readFileSync(real2, "utf8");
45177
+ const real2 = fs34.realpathSync(target);
45178
+ if (!real2.startsWith(fs34.realpathSync(dir) + path37.sep)) return null;
45179
+ return fs34.readFileSync(real2, "utf8");
45008
45180
  } catch {
45009
45181
  return null;
45010
45182
  }
@@ -45013,7 +45185,7 @@ function agentFileReader(dir) {
45013
45185
  function walkFolder(dir, prefix) {
45014
45186
  let entries2;
45015
45187
  try {
45016
- entries2 = fs33.readdirSync(dir, { withFileTypes: true });
45188
+ entries2 = fs34.readdirSync(dir, { withFileTypes: true });
45017
45189
  } catch {
45018
45190
  return [];
45019
45191
  }
@@ -45124,7 +45296,7 @@ var init_candidate = __esm({
45124
45296
 
45125
45297
  // ../cli/src/lib/agent/launch.ts
45126
45298
  import { spawn as spawn2 } from "node:child_process";
45127
- import fs34 from "node:fs";
45299
+ import fs35 from "node:fs";
45128
45300
  import path38 from "node:path";
45129
45301
  import { fileURLToPath as fileURLToPath2 } from "node:url";
45130
45302
  function boardArgs() {
@@ -45137,8 +45309,8 @@ function watcherEnv(env2 = process.env) {
45137
45309
  }
45138
45310
  function spawnWatcher(sessionId) {
45139
45311
  if (!BUILT) return void 0;
45140
- fs34.mkdirSync(SESSIONS_DIR, { recursive: true });
45141
- const out = fs34.openSync(path38.join(SESSIONS_DIR, `${sessionId}.watch.log`), "a");
45312
+ fs35.mkdirSync(SESSIONS_DIR, { recursive: true });
45313
+ const out = fs35.openSync(path38.join(SESSIONS_DIR, `${sessionId}.watch.log`), "a");
45142
45314
  try {
45143
45315
  const child = spawn2(process.execPath, [SELF, "__watch", sessionId, ...boardArgs()], {
45144
45316
  cwd: REPO_ROOT,
@@ -45154,7 +45326,7 @@ function spawnWatcher(sessionId) {
45154
45326
  return void 0;
45155
45327
  } finally {
45156
45328
  try {
45157
- fs34.closeSync(out);
45329
+ fs35.closeSync(out);
45158
45330
  } catch {
45159
45331
  }
45160
45332
  }
@@ -45171,11 +45343,11 @@ var init_launch = __esm({
45171
45343
  });
45172
45344
 
45173
45345
  // ../cli/src/lib/agent/command.ts
45174
- import fs35 from "node:fs";
45346
+ import fs36 from "node:fs";
45175
45347
  import path39 from "node:path";
45176
45348
  function selfCommand() {
45177
45349
  const bin = path39.resolve(path39.dirname(SELF), "..", "bin", "ai4kanban.mjs");
45178
- const file2 = fs35.existsSync(bin) ? bin : SELF;
45350
+ const file2 = fs36.existsSync(bin) ? bin : SELF;
45179
45351
  const inside2 = rel(file2);
45180
45352
  const shortHop = !inside2.startsWith("..") && !path39.isAbsolute(inside2) && inside2.split(/[\\/]/).length <= 3;
45181
45353
  return `node ${shortHop ? inside2 : file2}`;
@@ -45189,7 +45361,7 @@ function boardCommandFor(_cardId) {
45189
45361
  }
45190
45362
  function absoluteSelf() {
45191
45363
  const bin = path39.resolve(path39.dirname(SELF), "..", "bin", "ai4kanban.mjs");
45192
- return fs35.existsSync(bin) ? bin : SELF;
45364
+ return fs36.existsSync(bin) ? bin : SELF;
45193
45365
  }
45194
45366
  function commandNote(command) {
45195
45367
  if (command === "akb") return "";
@@ -45205,13 +45377,13 @@ var init_command = __esm({
45205
45377
  });
45206
45378
 
45207
45379
  // ../cli/src/lib/agent/outputs.ts
45208
- import fs36 from "node:fs";
45380
+ import fs37 from "node:fs";
45209
45381
  import path40 from "node:path";
45210
45382
  function cardBody(cardId2) {
45211
45383
  const found2 = locate(cardId2) ?? locateArchived(cardId2);
45212
45384
  if (!found2) return "";
45213
45385
  try {
45214
- return fs36.readFileSync(found2.kind === "group" ? path40.join(found2.target, "root.md") : found2.target, "utf8");
45386
+ return fs37.readFileSync(found2.kind === "group" ? path40.join(found2.target, "root.md") : found2.target, "utf8");
45215
45387
  } catch {
45216
45388
  return "";
45217
45389
  }
@@ -45245,20 +45417,20 @@ var init_outputs = __esm({
45245
45417
  });
45246
45418
 
45247
45419
  // ../cli/src/lib/agent/log.ts
45248
- import fs37 from "node:fs";
45420
+ import fs38 from "node:fs";
45249
45421
  import path41 from "node:path";
45250
45422
  function pruneLogs() {
45251
45423
  try {
45252
- const runs = fs37.readdirSync(SESSIONS_DIR).filter((f) => f.endsWith(".log") && !f.endsWith(".watch.log")).map((f) => ({ id: f.slice(0, -".log".length), t: fs37.statSync(path41.join(SESSIONS_DIR, f)).mtimeMs })).sort((a, b) => b.t - a.t);
45424
+ const runs = fs38.readdirSync(SESSIONS_DIR).filter((f) => f.endsWith(".log") && !f.endsWith(".watch.log")).map((f) => ({ id: f.slice(0, -".log".length), t: fs38.statSync(path41.join(SESSIONS_DIR, f)).mtimeMs })).sort((a, b) => b.t - a.t);
45253
45425
  const kept2 = new Set(runs.slice(0, KEEP_LOGS).map((r) => r.id));
45254
45426
  const drop = new Set(runs.slice(KEEP_LOGS).map((r) => r.id));
45255
- for (const f of fs37.readdirSync(SESSIONS_DIR)) {
45427
+ for (const f of fs38.readdirSync(SESSIONS_DIR)) {
45256
45428
  const dot = f.indexOf(".");
45257
45429
  const id2 = dot === -1 ? f : f.slice(0, dot);
45258
45430
  const stray = f.endsWith(".images") && !kept2.has(id2) && !drop.has(id2) && stale2(f);
45259
45431
  if (!stray && !drop.has(id2)) continue;
45260
45432
  try {
45261
- fs37.rmSync(path41.join(SESSIONS_DIR, f), { recursive: true, force: true });
45433
+ fs38.rmSync(path41.join(SESSIONS_DIR, f), { recursive: true, force: true });
45262
45434
  } catch {
45263
45435
  }
45264
45436
  }
@@ -45267,7 +45439,7 @@ function pruneLogs() {
45267
45439
  }
45268
45440
  function stale2(name) {
45269
45441
  try {
45270
- return Date.now() - fs37.statSync(path41.join(SESSIONS_DIR, name)).mtimeMs > STRAY_MS;
45442
+ return Date.now() - fs38.statSync(path41.join(SESSIONS_DIR, name)).mtimeMs > STRAY_MS;
45271
45443
  } catch {
45272
45444
  return false;
45273
45445
  }
@@ -45294,13 +45466,13 @@ function asContext(v) {
45294
45466
  function readLogTail(logPath, maxBytes = TAIL_BYTES) {
45295
45467
  let fd;
45296
45468
  try {
45297
- const size = fs37.statSync(logPath).size;
45469
+ const size = fs38.statSync(logPath).size;
45298
45470
  const start = Math.max(0, size - maxBytes);
45299
45471
  const len = size - start;
45300
45472
  if (len === 0) return "";
45301
- fd = fs37.openSync(logPath, "r");
45473
+ fd = fs38.openSync(logPath, "r");
45302
45474
  const buf = Buffer.alloc(len);
45303
- fs37.readSync(fd, buf, 0, len, start);
45475
+ fs38.readSync(fd, buf, 0, len, start);
45304
45476
  let text5 = buf.toString("utf8");
45305
45477
  if (start > 0) {
45306
45478
  const nl = text5.indexOf("\n");
@@ -45312,7 +45484,7 @@ function readLogTail(logPath, maxBytes = TAIL_BYTES) {
45312
45484
  } finally {
45313
45485
  if (fd !== void 0) {
45314
45486
  try {
45315
- fs37.closeSync(fd);
45487
+ fs38.closeSync(fd);
45316
45488
  } catch {
45317
45489
  }
45318
45490
  }
@@ -45403,7 +45575,7 @@ ${DURATION_MARKER} ${Math.max(0, ms)}
45403
45575
  });
45404
45576
 
45405
45577
  // ../cli/src/lib/agent/store.ts
45406
- import fs38 from "node:fs";
45578
+ import fs39 from "node:fs";
45407
45579
  import path42 from "node:path";
45408
45580
  function logPathIn(held4, sessionId) {
45409
45581
  return typeof held4 === "string" && held4.startsWith(SESSIONS_DIR + path42.sep) ? held4 : logPathOf(sessionId);
@@ -45411,7 +45583,7 @@ function logPathIn(held4, sessionId) {
45411
45583
  function parseStore() {
45412
45584
  let data;
45413
45585
  try {
45414
- data = JSON.parse(fs38.readFileSync(SESSIONS, "utf8"));
45586
+ data = JSON.parse(fs39.readFileSync(SESSIONS, "utf8"));
45415
45587
  } catch {
45416
45588
  return { runs: [], deliveries: [], marks: {} };
45417
45589
  }
@@ -45445,7 +45617,8 @@ function parseStore() {
45445
45617
  error: typeof entry.error === "string" ? entry.error : void 0,
45446
45618
  failure: readFailure(entry.failure),
45447
45619
  validationFailure: readFailure(entry.validationFailure),
45448
- retryPause: entry.retryPause,
45620
+ retryPause: readRetryPause(entry.retryPause),
45621
+ retryHistory: readRetryHistory(entry.retryHistory),
45449
45622
  blocker: readBlocker(entry.blocker),
45450
45623
  // A run that never reported a cost shows none, rather than a zero it didn't earn.
45451
45624
  costUsd: typeof entry.costUsd === "number" && entry.costUsd >= 0 ? entry.costUsd : void 0,
@@ -45765,16 +45938,16 @@ function writeStore(store) {
45765
45938
  marks: store.marks,
45766
45939
  ...store.refined ? { refined: store.refined } : {}
45767
45940
  };
45768
- fs38.mkdirSync(path42.dirname(SESSIONS), { recursive: true });
45941
+ fs39.mkdirSync(path42.dirname(SESSIONS), { recursive: true });
45769
45942
  const tmp = `${SESSIONS}.tmp`;
45770
- fs38.writeFileSync(tmp, JSON.stringify(kept2, null, 2) + "\n");
45771
- fs38.renameSync(tmp, SESSIONS);
45943
+ fs39.writeFileSync(tmp, JSON.stringify(kept2, null, 2) + "\n");
45944
+ fs39.renameSync(tmp, SESSIONS);
45772
45945
  forgetFileMemos();
45773
45946
  }
45774
45947
  function prune(runs, deliveries) {
45775
45948
  const held4 = new Set(deliveries.filter(holdsCheckout).map((d) => d.deliveryId));
45776
45949
  const live = runs.filter((r) => r.status === "running");
45777
- const finished = runs.filter((r) => r.status !== "running" && (fs38.existsSync(r.logPath) || r.deliveryId && held4.has(r.deliveryId))).sort((a, b) => b.startedAt - a.startedAt).slice(0, KEEP_RUNS);
45950
+ const finished = runs.filter((r) => r.status !== "running" && (fs39.existsSync(r.logPath) || r.deliveryId && held4.has(r.deliveryId))).sort((a, b) => b.startedAt - a.startedAt).slice(0, KEEP_RUNS);
45778
45951
  const spared = runs.filter(
45779
45952
  (r) => r.status !== "running" && !finished.includes(r) && (!!r.discardedCards?.length || r.deliveryId && held4.has(r.deliveryId))
45780
45953
  );
@@ -45871,11 +46044,11 @@ var init_store = __esm({
45871
46044
  });
45872
46045
 
45873
46046
  // ../cli/src/lib/agent/commit-mode.ts
45874
- import fs39 from "node:fs";
46047
+ import fs40 from "node:fs";
45875
46048
  function recordedIds() {
45876
46049
  try {
45877
46050
  return new Set(
45878
- fs39.readdirSync(DELIVERIES).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -".json".length))
46051
+ fs40.readdirSync(DELIVERIES).filter((f) => f.endsWith(".json")).map((f) => f.slice(0, -".json".length))
45879
46052
  );
45880
46053
  } catch {
45881
46054
  return /* @__PURE__ */ new Set();
@@ -45908,7 +46081,7 @@ var init_commit_mode = __esm({
45908
46081
  init_worktree();
45909
46082
  ID_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";
45910
46083
  ID_LENGTH = 8;
45911
- deliveryCwd = (delivery) => delivery.worktree && fs39.existsSync(worktreeDir(delivery.worktree)) ? worktreeDir(delivery.worktree) : REPO_ROOT;
46084
+ deliveryCwd = (delivery) => delivery.worktree && fs40.existsSync(worktreeDir(delivery.worktree)) ? worktreeDir(delivery.worktree) : REPO_ROOT;
45912
46085
  }
45913
46086
  });
45914
46087
 
@@ -46002,12 +46175,12 @@ var init_runner = __esm({
46002
46175
  });
46003
46176
 
46004
46177
  // ../cli/src/lib/agent/rules.ts
46005
- import fs40 from "node:fs";
46178
+ import fs41 from "node:fs";
46006
46179
  import path43 from "node:path";
46007
46180
  function ruleFile(agent) {
46008
46181
  if (!agent || hiddenRole(agent)) return "";
46009
46182
  try {
46010
- return fs40.readFileSync(rulePath(agent), "utf8").trim();
46183
+ return fs41.readFileSync(rulePath(agent), "utf8").trim();
46011
46184
  } catch {
46012
46185
  return "";
46013
46186
  }
@@ -46072,7 +46245,7 @@ var init_rules2 = __esm({
46072
46245
  });
46073
46246
 
46074
46247
  // ../cli/src/lib/agent/deliveries.ts
46075
- import fs41 from "node:fs";
46248
+ import fs42 from "node:fs";
46076
46249
  import path44 from "node:path";
46077
46250
  function writeAudit(delivery, runs) {
46078
46251
  const known2 = new Map(readAudit(delivery.deliveryId)?.sessions.map((s) => [s.sessionId, s]) ?? []);
@@ -46102,10 +46275,10 @@ function writeAudit(delivery, runs) {
46102
46275
  }
46103
46276
  function writeAuditFile(record2) {
46104
46277
  try {
46105
- fs41.mkdirSync(DELIVERIES, { recursive: true });
46278
+ fs42.mkdirSync(DELIVERIES, { recursive: true });
46106
46279
  const tmp = `${auditPath(record2.deliveryId)}.tmp`;
46107
- fs41.writeFileSync(tmp, JSON.stringify(record2, null, 2) + "\n");
46108
- fs41.renameSync(tmp, auditPath(record2.deliveryId));
46280
+ fs42.writeFileSync(tmp, JSON.stringify(record2, null, 2) + "\n");
46281
+ fs42.renameSync(tmp, auditPath(record2.deliveryId));
46109
46282
  return true;
46110
46283
  } catch {
46111
46284
  return false;
@@ -46113,7 +46286,7 @@ function writeAuditFile(record2) {
46113
46286
  }
46114
46287
  function readAudit(deliveryId) {
46115
46288
  try {
46116
- const data = JSON.parse(fs41.readFileSync(auditPath(deliveryId), "utf8"));
46289
+ const data = JSON.parse(fs42.readFileSync(auditPath(deliveryId), "utf8"));
46117
46290
  return { sessions: Array.isArray(data?.sessions) ? data.sessions : [] };
46118
46291
  } catch {
46119
46292
  return null;
@@ -46128,7 +46301,7 @@ function syncAudit(deliveryId, just) {
46128
46301
  }
46129
46302
  function wholeAudit(file2) {
46130
46303
  try {
46131
- const data = JSON.parse(fs41.readFileSync(file2, "utf8"));
46304
+ const data = JSON.parse(fs42.readFileSync(file2, "utf8"));
46132
46305
  return typeof data?.deliveryId === "string" && Array.isArray(data.sessions) ? data : null;
46133
46306
  } catch {
46134
46307
  return null;
@@ -46141,7 +46314,7 @@ function activeAudit(file2) {
46141
46314
  function allAudits() {
46142
46315
  let names2;
46143
46316
  try {
46144
- names2 = fs41.readdirSync(DELIVERIES);
46317
+ names2 = fs42.readdirSync(DELIVERIES);
46145
46318
  } catch {
46146
46319
  return [];
46147
46320
  }
@@ -46270,7 +46443,7 @@ function resumeRecord(id2, execution) {
46270
46443
  const found2 = namedDelivery(id2) ?? endedDelivery(id2);
46271
46444
  if (!found2) return { ok: false, ...unknownDelivery(id2) };
46272
46445
  const file2 = found2.cardId === null ? null : cardFile(found2.cardId);
46273
- const restored = file2 && parseFrontmatter(fs41.readFileSync(file2, "utf8")).meta?.restored;
46446
+ const restored = file2 && parseFrontmatter(fs42.readFileSync(file2, "utf8")).meta?.restored;
46274
46447
  if (restored && Date.parse(restored) > found2.startedAt) return { ok: false, ...unknownDelivery(id2) };
46275
46448
  if (found2.status === "finished") return { ok: true, delivery: found2 };
46276
46449
  const refused = resumeRefusal(found2);
@@ -46316,7 +46489,7 @@ function approvedRequirements(cardId2) {
46316
46489
  const file2 = found2.kind === "group" ? path44.join(found2.target, "root.md") : found2.target;
46317
46490
  let text5;
46318
46491
  try {
46319
- text5 = fs41.readFileSync(file2, "utf8");
46492
+ text5 = fs42.readFileSync(file2, "utf8");
46320
46493
  } catch {
46321
46494
  return "";
46322
46495
  }
@@ -46327,7 +46500,7 @@ function cardMeta2(cardId2) {
46327
46500
  const found2 = locate(cardId2);
46328
46501
  if (!found2) return null;
46329
46502
  const file2 = found2.kind === "group" ? path44.join(found2.target, "root.md") : found2.target;
46330
- return parseFrontmatter(fs41.readFileSync(file2, "utf8")).meta;
46503
+ return parseFrontmatter(fs42.readFileSync(file2, "utf8")).meta;
46331
46504
  } catch {
46332
46505
  return null;
46333
46506
  }
@@ -46485,7 +46658,7 @@ var init_deliveries = __esm({
46485
46658
  activeAudits = () => allAudits().filter((a) => a.status === "active");
46486
46659
  auditRow = (audit) => readDeliveryRow({ ...audit, sessions: audit.sessions.map((s) => s.sessionId) });
46487
46660
  lastSessionRunning = (audit) => audit.sessions[audit.sessions.length - 1]?.status === "running";
46488
- localAudit = (audit) => worktreeExists(audit.worktree) || audit.sessions.some((session) => path44.resolve(REPO_ROOT, session.log) === logPathOf(session.sessionId) && fs41.existsSync(logPathOf(session.sessionId)));
46661
+ localAudit = (audit) => worktreeExists(audit.worktree) || audit.sessions.some((session) => path44.resolve(REPO_ROOT, session.log) === logPathOf(session.sessionId) && fs42.existsSync(logPathOf(session.sessionId)));
46489
46662
  unknownDelivery = (id2) => refusal("deliveryNotFound", `no delivery here answers to "${id2}"`, { id: id2 });
46490
46663
  isResumable = (delivery) => !resumeRefusal(delivery);
46491
46664
  cardStatus = (cardId2) => cardMeta2(cardId2)?.status || "todo";
@@ -46816,14 +46989,15 @@ function startableBinary(binary, harness, pinned2 = false) {
46816
46989
  const note = brokenEntryNote(copy2, own2, harness);
46817
46990
  return { binary: spawnName(copy2, own2), ...note ? { note } : {} };
46818
46991
  }
46819
- function readBlock2(harness, block, argv, runtimeId, secretRefs = {}) {
46992
+ function readBlock2(harness, block, argv, runtimeId, secretRefs = {}, executionSecrets) {
46820
46993
  const values = {};
46821
46994
  const ignored = [];
46822
46995
  const secretsSet = [];
46823
- const env2 = harness.settings.some((s) => s.kind === "secret") ? readEnvFile() : {};
46996
+ const env2 = !executionSecrets && harness.settings.some((s) => s.kind === "secret") ? readEnvFile() : {};
46824
46997
  for (const setting of harness.settings) {
46825
46998
  if (setting.kind === "secret") {
46826
- if (setting.env && env2[secretRefs[setting.env] ?? secretVar(setting.env, runtimeId)]) secretsSet.push(setting.key);
46999
+ const value2 = executionSecrets ? executionSecrets[setting.key] : setting.env && env2[secretRefs[setting.env] ?? secretVar(setting.env, runtimeId)];
47000
+ if (value2) secretsSet.push(setting.key);
46827
47001
  continue;
46828
47002
  }
46829
47003
  const value = block[setting.key]?.trim() ?? "";
@@ -46840,11 +47014,8 @@ function readBlock2(harness, block, argv, runtimeId, secretRefs = {}) {
46840
47014
  }
46841
47015
  function onOwnEndpoint(runtimeId) {
46842
47016
  try {
46843
- const runtime = runtimeId ? runtimeById(runtimeId) : void 0;
46844
- const harness = harnessByName(runtime?.harness);
46845
- if (!runtime || !harness) return false;
46846
- const { values, secretsSet } = readBlock2(harness, runtime.settings, [], runtime.id, runtime.secretRefs);
46847
- return !!activeProviderOf({ harness, values, secretsSet })?.needs.includes("baseUrl");
47017
+ if (!runtimeId || !runRuntimeById(runtimeId)) return false;
47018
+ return !!activeProviderOf(resolveHarness({ pin: runtimeId }))?.needs.includes("baseUrl");
46848
47019
  } catch {
46849
47020
  return true;
46850
47021
  }
@@ -46853,12 +47024,15 @@ function resolveHarness(ask2 = {}) {
46853
47024
  const cfg = safeConfig();
46854
47025
  const staleCommand = typeof cfg.command === "string" && cfg.command.trim() ? true : void 0;
46855
47026
  const agent = ask2.agent ?? "";
46856
- const list3 = readRuntimes(cfg);
46857
- const table = readAgentRuntime(cfg);
47027
+ const execution = executionRuntimes();
47028
+ const scoped = execution && [execution.default, ...Object.values(execution.picks)];
47029
+ const list3 = scoped ?? readRuntimes(cfg);
46858
47030
  const owner = agent ? runtimeOwner(agent) : "";
46859
- const picked = owner ? runtimeOfAgent(owner, table) : void 0;
47031
+ const picked = owner ? execution ? execution.picks[owner]?.id : runtimeOfAgent(owner, readAgentRuntime(cfg)) : void 0;
46860
47032
  const asked = ask2.pin ?? picked;
46861
47033
  const runtime = pickRuntime(list3, asked, ask2.harness);
47034
+ const credentialId = scoped?.find((row) => row === runtime)?.credentialId;
47035
+ const executionSecrets = execution && (credentialId ? readRuntimeCredentials(execution.credentialsFile)[credentialId] ?? {} : {});
46862
47036
  const unknownAgentRuntime = picked && !ask2.pin && !list3.some((r) => r.id === picked || r.harness === picked) ? picked : void 0;
46863
47037
  const known2 = harnessByName(runtime.harness);
46864
47038
  const harness = known2 ?? DEFAULT_HARNESS;
@@ -46868,7 +47042,8 @@ function resolveHarness(ask2 = {}) {
46868
47042
  runtime.settings,
46869
47043
  splitCommand(command),
46870
47044
  runtime.id,
46871
- runtime.secretRefs
47045
+ runtime.secretRefs,
47046
+ executionSecrets
46872
47047
  );
46873
47048
  return {
46874
47049
  runtime,
@@ -46879,6 +47054,7 @@ function resolveHarness(ask2 = {}) {
46879
47054
  unknownAgentRuntime,
46880
47055
  values,
46881
47056
  secretsSet,
47057
+ executionSecrets,
46882
47058
  ignored,
46883
47059
  unknownName: known2 ? void 0 : runtime.harness || void 0,
46884
47060
  staleCommand
@@ -46922,6 +47098,7 @@ function settingSaveError(key, value, ask2 = {}) {
46922
47098
  }
46923
47099
  function runEnv2(resolved, cwd = REPO_ROOT) {
46924
47100
  const { harness, runtime } = resolved;
47101
+ if (resolved.executionSecrets) return settingEnv(harness, resolved, resolved.executionSecrets, cwd);
46925
47102
  const file2 = readEnvFile();
46926
47103
  const secrets = {};
46927
47104
  for (const setting of harness.settings) {
@@ -46951,7 +47128,7 @@ function planResume(session, agent, own2 = {}) {
46951
47128
  if (!harnessByName(harnessName)) return null;
46952
47129
  const resolved = resolveHarness({ agent, ...own2, harness: harnessName });
46953
47130
  const { harness, command, runtime } = resolved;
46954
- if (!harness.resumes) return null;
47131
+ if (!harness.resumes || resolved.executionSecrets && !runtime.id) return null;
46955
47132
  const argv = splitCommand(command);
46956
47133
  return {
46957
47134
  harness: harness.name,
@@ -46970,7 +47147,7 @@ function planFork(session, agent, own2 = {}, sessionId = randomUUID5()) {
46970
47147
  if (!harnessByName(harnessName)) return null;
46971
47148
  const resolved = resolveHarness({ agent, ...own2, harness: harnessName });
46972
47149
  const { harness, command, runtime } = resolved;
46973
- if (!harness.forkArgs || harness.name !== harnessName) return null;
47150
+ if (!harness.forkArgs || harness.name !== harnessName || resolved.executionSecrets && !runtime.id) return null;
46974
47151
  const argv = splitCommand(command);
46975
47152
  return {
46976
47153
  harness: harness.name,
@@ -47198,31 +47375,31 @@ var init_resolve = __esm({
47198
47375
  });
47199
47376
 
47200
47377
  // ../cli/src/lib/agent/pictures.ts
47201
- import fs42 from "node:fs";
47378
+ import fs43 from "node:fs";
47202
47379
  import path46 from "node:path";
47203
47380
  function claimRunPictures(box, sessionId, names2 = []) {
47204
47381
  if (!box || !freeBox(box) || names2.length === 0) return [];
47205
47382
  const from = pictureBox(box);
47206
47383
  const to = pictureBox(sessionId);
47207
47384
  try {
47208
- fs42.mkdirSync(SESSIONS_DIR, { recursive: true });
47209
- fs42.renameSync(from, to);
47385
+ fs43.mkdirSync(SESSIONS_DIR, { recursive: true });
47386
+ fs43.renameSync(from, to);
47210
47387
  } catch {
47211
47388
  return [];
47212
47389
  }
47213
- return names2.filter(pictureName).map((name) => path46.join(to, name)).filter((file2) => fs42.existsSync(file2));
47390
+ return names2.filter(pictureName).map((name) => path46.join(to, name)).filter((file2) => fs43.existsSync(file2));
47214
47391
  }
47215
47392
  function returnRunPictures(sessionId, box) {
47216
47393
  if (!box || !boxId(box)) return;
47217
47394
  try {
47218
- fs42.renameSync(pictureBox(sessionId), pictureBox(box));
47395
+ fs43.renameSync(pictureBox(sessionId), pictureBox(box));
47219
47396
  } catch {
47220
47397
  }
47221
47398
  }
47222
47399
  function moveRunPictures(from, to, files = []) {
47223
47400
  if (files.length === 0) return [];
47224
47401
  try {
47225
- fs42.renameSync(pictureBox(from), pictureBox(to));
47402
+ fs43.renameSync(pictureBox(from), pictureBox(to));
47226
47403
  } catch {
47227
47404
  return files;
47228
47405
  }
@@ -47235,7 +47412,7 @@ var init_pictures = __esm({
47235
47412
  init_paths();
47236
47413
  pictureName = (name) => /^[0-9a-f-]{36}\.[a-z0-9]{2,5}$/.test(name);
47237
47414
  boxId = (box) => /^[0-9a-f-]{36}$/.test(box);
47238
- freeBox = (box) => boxId(box) && !fs42.existsSync(path46.join(SESSIONS_DIR, `${box}.log`));
47415
+ freeBox = (box) => boxId(box) && !fs43.existsSync(path46.join(SESSIONS_DIR, `${box}.log`));
47239
47416
  pictureBox = (box) => path46.join(SESSIONS_DIR, `${box}.images`);
47240
47417
  }
47241
47418
  });
@@ -47337,7 +47514,7 @@ var init_facts = __esm({
47337
47514
  });
47338
47515
 
47339
47516
  // ../cli/src/lib/view/archive.ts
47340
- import fs43 from "node:fs";
47517
+ import fs44 from "node:fs";
47341
47518
  import path47 from "node:path";
47342
47519
  function archivedId(file2) {
47343
47520
  const own2 = idPrefix(path47.basename(file2));
@@ -47346,7 +47523,7 @@ function archivedId(file2) {
47346
47523
  function readFile(file2) {
47347
47524
  const id2 = archivedId(file2);
47348
47525
  if (id2 === null) return null;
47349
- const { meta: meta3, body } = parseFrontmatter(fs43.readFileSync(file2, "utf8"));
47526
+ const { meta: meta3, body } = parseFrontmatter(fs44.readFileSync(file2, "utf8"));
47350
47527
  if (!meta3) return null;
47351
47528
  return {
47352
47529
  row: {
@@ -47362,7 +47539,7 @@ function readFile(file2) {
47362
47539
  }
47363
47540
  function readArchive() {
47364
47541
  const relPath = rel(ARCHIVE).split(path47.sep).join("/");
47365
- if (!fs43.existsSync(ARCHIVE)) return { relPath, cards: [] };
47542
+ if (!fs44.existsSync(ARCHIVE)) return { relPath, cards: [] };
47366
47543
  const cards = walkMd(ARCHIVE).map(readFile).filter((found2) => found2 !== null).map((found2) => found2.row);
47367
47544
  cards.sort((a, b) => b.id - a.id);
47368
47545
  return { relPath, cards };
@@ -47717,16 +47894,16 @@ var init_prompts = __esm({
47717
47894
 
47718
47895
  // ../cli/src/lib/agent/stop.ts
47719
47896
  import { spawnSync as spawnSync6 } from "node:child_process";
47720
- import fs44 from "node:fs";
47897
+ import fs45 from "node:fs";
47721
47898
  function markedInProc(entry, strict = false, since) {
47722
47899
  const pids = [];
47723
- for (const name of fs44.readdirSync("/proc")) {
47900
+ for (const name of fs45.readdirSync("/proc")) {
47724
47901
  if (!/^\d+$/.test(name)) continue;
47725
47902
  try {
47726
- if (fs44.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
47903
+ if (fs45.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
47727
47904
  } catch (error62) {
47728
47905
  if (strict && !["ENOENT", "ESRCH"].includes(error62.code ?? "")) {
47729
- const stat = fs44.statSync(`/proc/${name}`, { throwIfNoEntry: false });
47906
+ const stat = fs45.statSync(`/proc/${name}`, { throwIfNoEntry: false });
47730
47907
  if (stat?.uid === process.getuid?.() && !startedBefore(Number(name), since)) throw error62;
47731
47908
  }
47732
47909
  }
@@ -47936,7 +48113,7 @@ var init_creation_lock = __esm({
47936
48113
 
47937
48114
  // ../cli/src/lib/agent/sessions.ts
47938
48115
  import { randomUUID as randomUUID6 } from "node:crypto";
47939
- import fs45 from "node:fs";
48116
+ import fs46 from "node:fs";
47940
48117
  import path50 from "node:path";
47941
48118
  function reap(runs, reaped = [], restore = []) {
47942
48119
  let changed = false;
@@ -47963,7 +48140,7 @@ function reap(runs, reaped = [], restore = []) {
47963
48140
  }
47964
48141
  function stampDuration(run3, endedAt) {
47965
48142
  try {
47966
- fs45.appendFileSync(run3.logPath, durationLine(endedAt - run3.startedAt));
48143
+ fs46.appendFileSync(run3.logPath, durationLine(endedAt - run3.startedAt));
47967
48144
  } catch {
47968
48145
  }
47969
48146
  }
@@ -47977,7 +48154,7 @@ function cardNow(cardId2) {
47977
48154
  try {
47978
48155
  const file2 = cardFile(cardId2);
47979
48156
  if (!file2) return null;
47980
- const { meta: meta3 } = parseFrontmatter(fs45.readFileSync(file2, "utf8"));
48157
+ const { meta: meta3 } = parseFrontmatter(fs46.readFileSync(file2, "utf8"));
47981
48158
  if (!meta3) return null;
47982
48159
  return { status: meta3.status || "todo", questions: meta3.questions.length, title: meta3.title };
47983
48160
  } catch {
@@ -48222,7 +48399,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said2) {
48222
48399
  if (retired) return retired;
48223
48400
  if (req.deliveryId && findDelivery(req.deliveryId)?.scheduled) return retiredStudioRun("scheduled");
48224
48401
  const cardId2 = Number.isInteger(req.id) ? req.id : null;
48225
- if (req.runtime && !runtimeById(req.runtime)) {
48402
+ if (req.runtime && !runRuntimeById(req.runtime)) {
48226
48403
  const runtimes = readRuntimes().map((r) => r.id).join(", ");
48227
48404
  return refusal("runtimeNotFound", `this board has no runtime called "${req.runtime}". It has: ${runtimes}.`, {
48228
48405
  id: req.runtime,
@@ -48245,7 +48422,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said2) {
48245
48422
  const parent = req.action === "sub" && req.parentId ? peekRun(req.parentId) : void 0;
48246
48423
  const cwd = parent?.cwd ?? deliveryCwd(start ?? joining ?? {});
48247
48424
  const plan = said2 ? { ...said2.plan(cwd, sessionId), note: null } : planRun(sessionId, cwd, agentForRun(req), req.runtime ? { pin: req.runtime } : {});
48248
- const away = plan.runtime ? runtimeById(plan.runtime)?.away : void 0;
48425
+ const away = plan.runtime ? runRuntimeById(plan.runtime)?.away : void 0;
48249
48426
  if (away) return refusal("runtimeAway", away, { id: plan.runtime });
48250
48427
  if (plan.note) notes = [...notes, plan.note];
48251
48428
  const record2 = {
@@ -48316,7 +48493,16 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said2) {
48316
48493
  }
48317
48494
  function planningSession(cardId2, cwd = REPO_ROOT) {
48318
48495
  const here = (dir) => !dir || path50.resolve(dir) === cwd;
48319
- const planned = readRuns().filter((r) => r.status === "done" && r.cardId === cardId2 && PLANNING.has(r.action)).sort((a, b) => b.startedAt - a.startedAt)[0];
48496
+ const safeToContinue = (r) => {
48497
+ if (r.status === "done") return true;
48498
+ if (r.status !== "stopped" && r.status !== "error" && r.status !== "interrupted") return false;
48499
+ if (r.pendingWrites || r.cleanup?.status === "unconfirmed") return false;
48500
+ if (isSessionMissingFailure(r.failure)) return false;
48501
+ const root2 = r.agentPid ? { pid: r.agentPid, since: r.agentStartedAt ?? r.startedAt, identity: r.agentIdentity } : void 0;
48502
+ const stopped2 = r.managedProcess ? connectionStopped(root2) : processesStopped(runMark(r.sessionId, r.agentStartedAt ?? r.startedAt), root2);
48503
+ return stopped2;
48504
+ };
48505
+ const planned = readRuns().filter((r) => r.status !== "running" && r.cardId === cardId2 && PLANNING.has(r.action)).sort((a, b) => b.startedAt - a.startedAt).find((r) => safeToContinue(r) && !!resumeSessionId(r));
48320
48506
  if (!planned) return { none: "unrecorded" };
48321
48507
  if (!here(planned.cwd)) return { none: "elsewhere" };
48322
48508
  const resumeId = resumeSessionId(planned);
@@ -48404,14 +48590,15 @@ async function openResume(id2, options) {
48404
48590
  const automatic = typeof options === "object" && options.automatic === true;
48405
48591
  const pending = !forced && prev.status !== "stopped" ? prev.retry?.pending : void 0;
48406
48592
  if (automatic && !pending) return refusal("runContinued", "The automatic retry is no longer pending.");
48407
- const session = forced ? void 0 : resumeSessionId(prev);
48593
+ const resetReplay = pending?.sessionAction === "reset_replay";
48594
+ const session = forced || resetReplay ? void 0 : resumeSessionId(prev);
48408
48595
  if (pending || requireSession) {
48409
48596
  const root2 = prev.agentPid ? { pid: prev.agentPid, since: prev.agentStartedAt ?? prev.startedAt, identity: prev.agentIdentity } : void 0;
48410
48597
  const stopped2 = prev.managedProcess ? connectionStopped(root2) : processesStopped(runMark(prev.sessionId, prev.agentStartedAt), root2);
48411
48598
  const recovery = agentRecovery({
48412
48599
  stopped: stopped2,
48413
48600
  session,
48414
- replayable: !requireSession && neverStarted(prev),
48601
+ replayable: !requireSession && (neverStarted(prev) || resetReplay),
48415
48602
  unconfirmedCleanup: prev.pendingWrites || prev.cleanup?.status === "unconfirmed" || prev.managedProcess && (pending?.failure ?? prev.failure)?.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session)
48416
48603
  });
48417
48604
  if (recovery === "unsafe") {
@@ -48426,10 +48613,10 @@ async function openResume(id2, options) {
48426
48613
  const sessionId = randomUUID6();
48427
48614
  let plan;
48428
48615
  let fresh;
48429
- if (!forced && prev.harness === "antigravity" && !session && !neverStarted(prev)) {
48616
+ if (!forced && !resetReplay && prev.harness === "antigravity" && !session && !neverStarted(prev)) {
48430
48617
  return refusal("runNoSession", "Antigravity did not record a conversation ID before interruption. The original session cannot be resumed.");
48431
48618
  }
48432
- if (!session && !forced && prev.cardId !== null && !neverStarted(prev)) return refusal("runNoSession", "The original session is unavailable. Explicitly take over the saved task in a new session.");
48619
+ if (!session && !forced && !resetReplay && prev.cardId !== null && !neverStarted(prev)) return refusal("runNoSession", "The original session is unavailable. Explicitly take over the saved task in a new session.");
48433
48620
  if (session) {
48434
48621
  plan = planResume({ harness: prev.harness, resumeId: session, cwd }, prev.agent, prev.runtime ? { pin: prev.runtime } : {});
48435
48622
  } else {
@@ -48450,12 +48637,12 @@ async function openResume(id2, options) {
48450
48637
  if ("error" in opened) return opened;
48451
48638
  if (!opened.spec.prompt && buildResume) opened.spec.prompt = buildResume;
48452
48639
  if (build?.notes?.trim()) opened.spec.prompt = [opened.spec.prompt || resumePrompt(prev.deliveryId, prev.action), build.notes.trim()].join("\n\n");
48453
- if (session && (pending || requireSession)) opened.spec.prompt = [recoveryPrompt, opened.spec.prompt].filter(Boolean).join("\n\n");
48640
+ if (session && requireSession && !pending) opened.spec.prompt = [recoveryPrompt, opened.spec.prompt].filter(Boolean).join("\n\n");
48454
48641
  if (build || buildResume || pending || requireSession) writeSpec(opened.spec);
48455
48642
  return opened;
48456
48643
  }
48457
48644
  async function planRetry2(prev, ask2, sessionId, cwd) {
48458
- const runtime = prev.runtime && runtimeById(prev.runtime) ? prev.runtime : void 0;
48645
+ const runtime = prev.runtime && runRuntimeById(prev.runtime) ? prev.runtime : void 0;
48459
48646
  const { note, ...plan } = planRun(sessionId, cwd, prev.agent ?? agentForRun(ask2), {
48460
48647
  ...runtime ? { pin: runtime } : {},
48461
48648
  ...shipsHarness(prev.harness) ? { harness: prev.harness } : {}
@@ -48505,6 +48692,7 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh, automatic = fa
48505
48692
  },
48506
48693
  failure: automatic ? prev.retry?.pending?.failure : void 0,
48507
48694
  retry: prev.retry ? { ...prev.retry, pending: void 0, launching: automatic ? true : void 0 } : void 0,
48695
+ ...prev.retryHistory?.length ? { retryHistory: prev.retryHistory } : {},
48508
48696
  logPath: logPathOf(sessionId),
48509
48697
  specAgent: prev.specAgent,
48510
48698
  cards: prev.cards,
@@ -48569,14 +48757,14 @@ function askForRefine(sessionId, ask2) {
48569
48757
  }
48570
48758
  function clearAsks(sessionId) {
48571
48759
  try {
48572
- fs45.unlinkSync(asksPathOf(sessionId));
48760
+ fs46.unlinkSync(asksPathOf(sessionId));
48573
48761
  } catch {
48574
48762
  }
48575
48763
  }
48576
48764
  function readAsks(sessionId) {
48577
48765
  let data;
48578
48766
  try {
48579
- data = JSON.parse(fs45.readFileSync(asksPathOf(sessionId), "utf8"));
48767
+ data = JSON.parse(fs46.readFileSync(asksPathOf(sessionId), "utf8"));
48580
48768
  } catch {
48581
48769
  return { refines: [] };
48582
48770
  }
@@ -48593,10 +48781,10 @@ function readAsks(sessionId) {
48593
48781
  return { refines: refines.filter((a) => !discarded.has(a.cardId)) };
48594
48782
  }
48595
48783
  function writeAsks(sessionId, file2) {
48596
- fs45.mkdirSync(SESSIONS_DIR, { recursive: true });
48784
+ fs46.mkdirSync(SESSIONS_DIR, { recursive: true });
48597
48785
  const tmp = `${asksPathOf(sessionId)}.tmp`;
48598
- fs45.writeFileSync(tmp, JSON.stringify(file2, null, 2) + "\n");
48599
- fs45.renameSync(tmp, asksPathOf(sessionId));
48786
+ fs46.writeFileSync(tmp, JSON.stringify(file2, null, 2) + "\n");
48787
+ fs46.renameSync(tmp, asksPathOf(sessionId));
48600
48788
  }
48601
48789
  function markSpawned(sessionId, pid) {
48602
48790
  patch(sessionId, (r) => {
@@ -48623,6 +48811,7 @@ async function closeRun(sessionId, res) {
48623
48811
  if (res.error) run3.error = res.error;
48624
48812
  run3.failure = res.failure;
48625
48813
  run3.retryPause = res.retryPause;
48814
+ if (res.retryHistory?.length) run3.retryHistory = res.retryHistory;
48626
48815
  if (run3.retry) {
48627
48816
  delete run3.retry.launching;
48628
48817
  if (res.status === "stopped") delete run3.retry.pending;
@@ -48751,7 +48940,7 @@ async function reconcileCardDelivery(cardId2) {
48751
48940
  result = withStore((store) => {
48752
48941
  reap(store.runs, reaped, restore);
48753
48942
  const file2 = cardFile(cardId2);
48754
- const restoredRaw = file2 ? parseFrontmatter(fs45.readFileSync(file2, "utf8")).meta?.restored : void 0;
48943
+ const restoredRaw = file2 ? parseFrontmatter(fs46.readFileSync(file2, "utf8")).meta?.restored : void 0;
48755
48944
  const restoredAt = restoredRaw ? Date.parse(restoredRaw) : Number.NaN;
48756
48945
  const merged = /* @__PURE__ */ new Map();
48757
48946
  for (const audit of cardAudits(cardId2)) merged.set(audit.deliveryId, audit);
@@ -48879,12 +49068,12 @@ async function resumeDelivery(id2) {
48879
49068
  return { ok: true, deliveryId: delivery.deliveryId, carryOn };
48880
49069
  }
48881
49070
  function writeSpec(spec) {
48882
- fs45.mkdirSync(SESSIONS_DIR, { recursive: true });
48883
- fs45.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
49071
+ fs46.mkdirSync(SESSIONS_DIR, { recursive: true });
49072
+ fs46.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
48884
49073
  }
48885
49074
  function readSpec(sessionId) {
48886
49075
  try {
48887
- const spec = JSON.parse(fs45.readFileSync(specPathOf(sessionId), "utf8"));
49076
+ const spec = JSON.parse(fs46.readFileSync(specPathOf(sessionId), "utf8"));
48888
49077
  return spec && Array.isArray(spec.plan?.argv) ? spec : null;
48889
49078
  } catch {
48890
49079
  return null;
@@ -48892,7 +49081,7 @@ function readSpec(sessionId) {
48892
49081
  }
48893
49082
  function dropSpec(sessionId) {
48894
49083
  try {
48895
- fs45.unlinkSync(specPathOf(sessionId));
49084
+ fs46.unlinkSync(specPathOf(sessionId));
48896
49085
  } catch {
48897
49086
  }
48898
49087
  }
@@ -48902,18 +49091,18 @@ async function acquireIndexLock(giveUp) {
48902
49091
  for (; ; ) {
48903
49092
  if (giveUp()) return null;
48904
49093
  try {
48905
- fs45.mkdirSync(INDEX_LOCK2, { recursive: false });
48906
- fs45.writeFileSync(holder, String(process.pid));
48907
- return () => fs45.rmSync(INDEX_LOCK2, { recursive: true, force: true });
49094
+ fs46.mkdirSync(INDEX_LOCK2, { recursive: false });
49095
+ fs46.writeFileSync(holder, String(process.pid));
49096
+ return () => fs46.rmSync(INDEX_LOCK2, { recursive: true, force: true });
48908
49097
  } catch (err) {
48909
49098
  const code = err.code;
48910
49099
  if (code === "ENOENT") {
48911
- fs45.mkdirSync(path50.dirname(INDEX_LOCK2), { recursive: true });
49100
+ fs46.mkdirSync(path50.dirname(INDEX_LOCK2), { recursive: true });
48912
49101
  continue;
48913
49102
  }
48914
49103
  if (code !== "EEXIST") throw err;
48915
49104
  if (!pidAlive(Number(readHolder(holder)))) {
48916
- fs45.rmSync(INDEX_LOCK2, { recursive: true, force: true });
49105
+ fs46.rmSync(INDEX_LOCK2, { recursive: true, force: true });
48917
49106
  continue;
48918
49107
  }
48919
49108
  if (Date.now() > until) return null;
@@ -48923,7 +49112,7 @@ async function acquireIndexLock(giveUp) {
48923
49112
  }
48924
49113
  function readHolder(file2) {
48925
49114
  try {
48926
- return fs45.readFileSync(file2, "utf8").trim();
49115
+ return fs46.readFileSync(file2, "utf8").trim();
48927
49116
  } catch {
48928
49117
  return String(process.pid);
48929
49118
  }
@@ -49062,7 +49251,7 @@ var init_sources = __esm({
49062
49251
  });
49063
49252
 
49064
49253
  // ../cli/src/lib/signals/inbox.ts
49065
- import fs46 from "node:fs";
49254
+ import fs47 from "node:fs";
49066
49255
  import path51 from "node:path";
49067
49256
  function metaPair(key, value) {
49068
49257
  const name = typeof key === "string" ? key.trim() : "";
@@ -49094,7 +49283,7 @@ ${signal2.summary.trim()}
49094
49283
  function parse3(file2, lenient = false) {
49095
49284
  let text5;
49096
49285
  try {
49097
- text5 = fs46.readFileSync(file2, "utf8");
49286
+ text5 = fs47.readFileSync(file2, "utf8");
49098
49287
  } catch {
49099
49288
  return null;
49100
49289
  }
@@ -49149,13 +49338,13 @@ function freeName(dir, wanted) {
49149
49338
  const ext = path51.extname(wanted);
49150
49339
  const stem = wanted.slice(0, wanted.length - ext.length);
49151
49340
  let name = wanted;
49152
- for (let n = 2; fs46.existsSync(path51.join(dir, name)); n++) name = `${stem}-${n}${ext}`;
49341
+ for (let n = 2; fs47.existsSync(path51.join(dir, name)); n++) name = `${stem}-${n}${ext}`;
49153
49342
  return name;
49154
49343
  }
49155
49344
  function readFolder(dir, lenient = false) {
49156
49345
  let entries2;
49157
49346
  try {
49158
- entries2 = fs46.readdirSync(dir, { withFileTypes: true });
49347
+ entries2 = fs47.readdirSync(dir, { withFileTypes: true });
49159
49348
  } catch {
49160
49349
  return [];
49161
49350
  }
@@ -49167,7 +49356,7 @@ function readInbox() {
49167
49356
  return signals;
49168
49357
  }
49169
49358
  function writeSignal(incoming, importedAt, slug = "") {
49170
- fs46.mkdirSync(TRIAGE, { recursive: true });
49359
+ fs47.mkdirSync(TRIAGE, { recursive: true });
49171
49360
  const signal2 = {
49172
49361
  ...incoming,
49173
49362
  importedAt,
@@ -49180,11 +49369,11 @@ function writeSignal(incoming, importedAt, slug = "") {
49180
49369
  relPath: ""
49181
49370
  };
49182
49371
  const file2 = path51.join(TRIAGE, freeName(TRIAGE, fileName(signal2.title, slug)));
49183
- fs46.writeFileSync(file2, serialize({ ...signal2, relPath: boardRel(file2) }));
49372
+ fs47.writeFileSync(file2, serialize({ ...signal2, relPath: boardRel(file2) }));
49184
49373
  return { ...signal2, relPath: boardRel(file2) };
49185
49374
  }
49186
49375
  function stamp3(file2, fields2) {
49187
- const text5 = fs46.readFileSync(file2, "utf8");
49376
+ const text5 = fs47.readFileSync(file2, "utf8");
49188
49377
  const lines = text5.split("\n");
49189
49378
  const close = lines.indexOf("---", 1);
49190
49379
  if (close < 0) return;
@@ -49193,13 +49382,13 @@ function stamp3(file2, fields2) {
49193
49382
  return !key || fields2[key[1]] === void 0;
49194
49383
  });
49195
49384
  const added = Object.entries(fields2).flatMap(([key, value]) => value === null ? [] : [`${key}: ${yamlScalar(value)}`]);
49196
- fs46.writeFileSync(file2, ["---", ...kept2, ...added, ...lines.slice(close)].join("\n"));
49385
+ fs47.writeFileSync(file2, ["---", ...kept2, ...added, ...lines.slice(close)].join("\n"));
49197
49386
  }
49198
49387
  function moveSignal(from, into, fields2) {
49199
- if (!fs46.existsSync(from)) return "";
49200
- fs46.mkdirSync(into, { recursive: true });
49388
+ if (!fs47.existsSync(from)) return "";
49389
+ fs47.mkdirSync(into, { recursive: true });
49201
49390
  const at = path51.join(into, freeName(into, path51.basename(from)));
49202
- fs46.renameSync(from, at);
49391
+ fs47.renameSync(from, at);
49203
49392
  stamp3(at, fields2);
49204
49393
  return boardRel(at);
49205
49394
  }
@@ -49235,6 +49424,54 @@ var init_inbox = __esm({
49235
49424
  }
49236
49425
  });
49237
49426
 
49427
+ // ../cli/src/lib/question-ops.ts
49428
+ function questionPositions(raw, count3, flag) {
49429
+ const ns = String(raw).split(",").map((s) => s.trim()).filter((s) => s.length > 0).map(Number);
49430
+ if (ns.length === 0 || ns.some((n) => !Number.isInteger(n) || n < 1)) {
49431
+ throw new QuestionOpError(`--${flag} needs one or more 1-based question numbers (e.g. 1 or 1,3)`);
49432
+ }
49433
+ const over = ns.find((n) => n > count3);
49434
+ if (over !== void 0) throw new QuestionOpError(`the card has ${count3} open question(s) \u2014 there's no question ${over}`);
49435
+ return ns;
49436
+ }
49437
+ function applyQuestionOps(start, ops, asker) {
49438
+ let questions = [...start];
49439
+ const changes = [];
49440
+ const closed2 = [];
49441
+ const positions = (op, flag) => questionPositions(op.ns ?? String(op.n), questions.length, flag);
49442
+ for (const op of ops) {
49443
+ if (op.kind === "clear") {
49444
+ closed2.push(...questions);
49445
+ questions = [];
49446
+ changes.push("cleared");
49447
+ } else if (op.kind === "drop") {
49448
+ const ns = positions(op, "drop");
49449
+ closed2.push(...ns.map((n) => questions[n - 1]));
49450
+ questions = questions.filter((_, i) => !ns.includes(i + 1));
49451
+ changes.push(`dropped ${ns.join(",")}`);
49452
+ } else if (op.kind === "append") {
49453
+ const agent = op.question.agent ?? asker;
49454
+ questions.push(agent ? { ...op.question, agent } : op.question);
49455
+ changes.push("appended");
49456
+ } else {
49457
+ const [n] = positions(op, "update");
49458
+ const agent = op.question.agent ?? questions[n - 1].agent;
49459
+ questions[n - 1] = { ...op.question, ...agent ? { agent } : {} };
49460
+ changes.push(`rewrote ${n}`);
49461
+ }
49462
+ }
49463
+ return { questions, changes, closed: closed2 };
49464
+ }
49465
+ var QUESTION_EDIT_LIMITS, QuestionOpError;
49466
+ var init_question_ops = __esm({
49467
+ "../cli/src/lib/question-ops.ts"() {
49468
+ "use strict";
49469
+ QUESTION_EDIT_LIMITS = { operations: 50, text: 4e3, options: 20, option: 200 };
49470
+ QuestionOpError = class extends Error {
49471
+ };
49472
+ }
49473
+ });
49474
+
49238
49475
  // ../cli/src/lib/questions.ts
49239
49476
  function newDraft(flag, value) {
49240
49477
  const text5 = value.trim();
@@ -49289,7 +49526,7 @@ function missingChoices(text5) {
49289
49526
  `"${text5}" needs choices to tick \u2014 add 2 or more --option "a \u2014 why". The user always gets a free-text choice too, so never write one yourself.`
49290
49527
  );
49291
49528
  }
49292
- function readQuestionOps(typed) {
49529
+ function readQuestionOps(typed, compatibility = false) {
49293
49530
  const ops = [];
49294
49531
  for (let i = 0; i < typed.length; i++) {
49295
49532
  const [key, value] = typed[i];
@@ -49315,71 +49552,40 @@ function readQuestionOps(typed) {
49315
49552
  if (!ops.length) {
49316
49553
  die('update-questions needs at least one op: --append ".." | --update <n> ".." | --drop n[,n...] | --clear');
49317
49554
  }
49555
+ if (!compatibility && ops.length > QUESTION_EDIT_LIMITS.operations) {
49556
+ die(`Submit at most ${QUESTION_EDIT_LIMITS.operations} edits at a time.`);
49557
+ }
49318
49558
  for (const op of ops) {
49319
49559
  if (op.draft) {
49560
+ if (!compatibility) validateQuestionEdit(op.draft);
49320
49561
  op.question = finalizeDraft(op.draft);
49321
49562
  delete op.draft;
49322
49563
  }
49323
49564
  }
49324
49565
  return ops;
49325
49566
  }
49567
+ function validateQuestionEdit(draft) {
49568
+ const { text: text5, option, options } = QUESTION_EDIT_LIMITS;
49569
+ if (Buffer.byteLength(draft.question) > text5) die(`Question text must be at most ${text5} bytes.`);
49570
+ if (draft.options.length > options) die(`A question can have at most ${options} choices.`);
49571
+ if (draft.options.some((choice) => Buffer.byteLength(choice) > option)) die(`Each choice must be at most ${option} bytes.`);
49572
+ if (draft.recommended.length > 1) die("A question takes at most one --recommended-option.");
49573
+ if (draft.agent && (draft.agent.length > 64 || !AGENT_NAME.test(draft.agent))) {
49574
+ die("--agent must be at most 64 characters with lowercase letters or digits joined by hyphens.");
49575
+ }
49576
+ }
49326
49577
  var init_questions = __esm({
49327
49578
  "../cli/src/lib/questions.ts"() {
49328
49579
  "use strict";
49329
49580
  init_paths();
49581
+ init_parse3();
49582
+ init_question_ops();
49330
49583
  init_question_block();
49331
49584
  init_question_block();
49332
49585
  init_rules();
49333
49586
  }
49334
49587
  });
49335
49588
 
49336
- // ../cli/src/lib/question-ops.ts
49337
- function questionPositions(raw, count3, flag) {
49338
- const ns = String(raw).split(",").map((s) => s.trim()).filter((s) => s.length > 0).map(Number);
49339
- if (ns.length === 0 || ns.some((n) => !Number.isInteger(n) || n < 1)) {
49340
- throw new QuestionOpError(`--${flag} needs one or more 1-based question numbers (e.g. 1 or 1,3)`);
49341
- }
49342
- const over = ns.find((n) => n > count3);
49343
- if (over !== void 0) throw new QuestionOpError(`the card has ${count3} open question(s) \u2014 there's no question ${over}`);
49344
- return ns;
49345
- }
49346
- function applyQuestionOps(start, ops, asker) {
49347
- let questions = [...start];
49348
- const changes = [];
49349
- const closed2 = [];
49350
- const positions = (op, flag) => questionPositions(op.ns ?? String(op.n), questions.length, flag);
49351
- for (const op of ops) {
49352
- if (op.kind === "clear") {
49353
- closed2.push(...questions);
49354
- questions = [];
49355
- changes.push("cleared");
49356
- } else if (op.kind === "drop") {
49357
- const ns = positions(op, "drop");
49358
- closed2.push(...ns.map((n) => questions[n - 1]));
49359
- questions = questions.filter((_, i) => !ns.includes(i + 1));
49360
- changes.push(`dropped ${ns.join(",")}`);
49361
- } else if (op.kind === "append") {
49362
- const agent = op.question.agent ?? asker;
49363
- questions.push(agent ? { ...op.question, agent } : op.question);
49364
- changes.push("appended");
49365
- } else {
49366
- const [n] = positions(op, "update");
49367
- const agent = op.question.agent ?? questions[n - 1].agent;
49368
- questions[n - 1] = { ...op.question, ...agent ? { agent } : {} };
49369
- changes.push(`rewrote ${n}`);
49370
- }
49371
- }
49372
- return { questions, changes, closed: closed2 };
49373
- }
49374
- var QuestionOpError;
49375
- var init_question_ops = __esm({
49376
- "../cli/src/lib/question-ops.ts"() {
49377
- "use strict";
49378
- QuestionOpError = class extends Error {
49379
- };
49380
- }
49381
- });
49382
-
49383
49589
  // ../cli/src/lib/source.ts
49384
49590
  function parseSourceRef(raw) {
49385
49591
  const text5 = raw.trim();
@@ -49430,12 +49636,12 @@ var init_studio_cards = __esm({
49430
49636
  });
49431
49637
 
49432
49638
  // ../cli/src/lib/readme.ts
49433
- import fs47 from "node:fs";
49639
+ import fs48 from "node:fs";
49434
49640
  import path52 from "node:path";
49435
49641
  function stripReadmeRefs(target) {
49436
- if (!fs47.existsSync(README)) return [];
49642
+ if (!fs48.existsSync(README)) return [];
49437
49643
  const needle = target.kind === "group" ? `](${target.rel}/` : `](${target.rel})`;
49438
- const lines = fs47.readFileSync(README, "utf8").split("\n");
49644
+ const lines = fs48.readFileSync(README, "utf8").split("\n");
49439
49645
  const out = [];
49440
49646
  const removed = [];
49441
49647
  let i = 0;
@@ -49457,20 +49663,20 @@ function stripReadmeRefs(target) {
49457
49663
  out.push(line);
49458
49664
  i++;
49459
49665
  }
49460
- if (removed.length) fs47.writeFileSync(README, out.join("\n"));
49666
+ if (removed.length) fs48.writeFileSync(README, out.join("\n"));
49461
49667
  return removed;
49462
49668
  }
49463
49669
  function addReadmeRef(id2, title, relPath) {
49464
- if (!fs47.existsSync(README)) return false;
49670
+ if (!fs48.existsSync(README)) return false;
49465
49671
  const link2 = relPath.split(path52.sep).join("/");
49466
49672
  const bullet = `- [#${id2} ${title}](${link2})`;
49467
49673
  const heading = `## ${TASKS_HEADING}`;
49468
- let lines = fs47.readFileSync(README, "utf8").split("\n");
49674
+ let lines = fs48.readFileSync(README, "utf8").split("\n");
49469
49675
  const hi = lines.findIndex((l) => l.trim().toLowerCase() === heading.toLowerCase());
49470
49676
  if (hi === -1) {
49471
49677
  while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
49472
49678
  lines.push("", heading, "", bullet);
49473
- fs47.writeFileSync(README, lines.join("\n") + "\n");
49679
+ fs48.writeFileSync(README, lines.join("\n") + "\n");
49474
49680
  return true;
49475
49681
  }
49476
49682
  let end2 = hi + 1;
@@ -49484,15 +49690,15 @@ function addReadmeRef(id2, title, relPath) {
49484
49690
  const at = lastBullet !== -1 ? lastBullet + 1 : lines[hi + 1] === "" ? hi + 2 : hi + 1;
49485
49691
  lines.splice(at, 0, bullet);
49486
49692
  }
49487
- fs47.writeFileSync(README, lines.join("\n"));
49693
+ fs48.writeFileSync(README, lines.join("\n"));
49488
49694
  return true;
49489
49695
  }
49490
49696
  function repointReadmeLink(id2, oldRel, newRel, title) {
49491
- if (!fs47.existsSync(README)) return false;
49697
+ if (!fs48.existsSync(README)) return false;
49492
49698
  const oldLink = oldRel.split(path52.sep).join("/");
49493
49699
  const newLink = newRel.split(path52.sep).join("/");
49494
49700
  const linkRe = new RegExp(`\\[#${id2}\\b[^\\]]*\\]\\(${escapeRegex2(oldLink)}\\)`);
49495
- const lines = fs47.readFileSync(README, "utf8").split("\n");
49701
+ const lines = fs48.readFileSync(README, "utf8").split("\n");
49496
49702
  let changed = false;
49497
49703
  for (let i = 0; i < lines.length; i++) {
49498
49704
  if (!lines[i].includes(`](${oldLink})`)) continue;
@@ -49502,7 +49708,7 @@ function repointReadmeLink(id2, oldRel, newRel, title) {
49502
49708
  changed = true;
49503
49709
  }
49504
49710
  }
49505
- if (changed) fs47.writeFileSync(README, lines.join("\n"));
49711
+ if (changed) fs48.writeFileSync(README, lines.join("\n"));
49506
49712
  return changed;
49507
49713
  }
49508
49714
  var isTableRow, isBulletStart, bulletIndent, TASKS_HEADING, escapeRegex2;
@@ -50041,6 +50247,37 @@ var init_manifest = __esm({
50041
50247
  }
50042
50248
  });
50043
50249
 
50250
+ // ../artifact-sdk/src/internal/file-references.ts
50251
+ function splitFileReference(src) {
50252
+ const end2 = src.search(/[?#]/);
50253
+ return end2 < 0 ? [src, ""] : [src.slice(0, end2), src.slice(end2)];
50254
+ }
50255
+ function relativeFileReference(src, owner) {
50256
+ const parts = owner.split("/").slice(0, -1);
50257
+ for (const part of src.split("/")) {
50258
+ if (part === ".." && parts.length && parts.at(-1) !== "..") parts.pop();
50259
+ else if (part && part !== ".") parts.push(part);
50260
+ }
50261
+ return parts.join("/");
50262
+ }
50263
+ var CSS, fileManifest;
50264
+ var init_file_references = __esm({
50265
+ "../artifact-sdk/src/internal/file-references.ts"() {
50266
+ "use strict";
50267
+ init_manifest();
50268
+ CSS = {
50269
+ name: "css",
50270
+ types: ["css"],
50271
+ references: [
50272
+ { text: `@import\\s+["']([^"']+)["']` },
50273
+ { text: `url\\(\\s*["']?([^"')]+?)["']?\\s*\\)` }
50274
+ ],
50275
+ skip: ["/\\*[\\s\\S]*?\\*/"]
50276
+ };
50277
+ fileManifest = (type, name) => type === "asset" && /\.css$/i.test(name) ? CSS : manifestOf(type);
50278
+ }
50279
+ });
50280
+
50044
50281
  // ../artifact-sdk/src/internal/collect.ts
50045
50282
  function collect(body, card, host2) {
50046
50283
  return collectSources(bodyReferences(body), card, host2);
@@ -50050,7 +50287,7 @@ function collectSources(sources2, card, host2) {
50050
50287
  const active3 = /* @__PURE__ */ new Set();
50051
50288
  const out = [];
50052
50289
  const visit2 = (src, types, owner, partial2 = false) => {
50053
- const path88 = src.replace(/[?#].*$/, "");
50290
+ const [path88] = splitFileReference(src);
50054
50291
  let resolved;
50055
50292
  try {
50056
50293
  resolved = host2.resolve(path88, owner);
@@ -50100,13 +50337,13 @@ function collectSources(sources2, card, host2) {
50100
50337
  } else {
50101
50338
  node2.kind = textKind(extOf(file2), types);
50102
50339
  try {
50103
- if (manifestOf(node2.kind)?.references) node2.data = host2.read(file2);
50340
+ if (fileManifest(node2.kind, file2)?.references) node2.data = host2.read(file2);
50104
50341
  } catch (error62) {
50105
50342
  node2.problems.push({ src: file2, message: why(error62) });
50106
50343
  }
50107
50344
  }
50108
50345
  node2.error = node2.problems[0]?.message;
50109
- if (!node2.error) for (const ref of referencesOf(manifestOf(node2.kind), node2.data)) child(ref, file2);
50346
+ if (!node2.error) for (const ref of referencesOf(fileManifest(node2.kind, file2), node2.data)) child(ref, file2);
50110
50347
  } else {
50111
50348
  for (const ref of host2.retained(key, types)) child(ref, card);
50112
50349
  }
@@ -50133,6 +50370,7 @@ var extOf, why, textKind, kindAt;
50133
50370
  var init_collect = __esm({
50134
50371
  "../artifact-sdk/src/internal/collect.ts"() {
50135
50372
  "use strict";
50373
+ init_file_references();
50136
50374
  init_manifest();
50137
50375
  init_references();
50138
50376
  extOf = (file2) => /\.[^./\\]+$/.exec(file2)?.[0].toLowerCase() ?? "";
@@ -50146,16 +50384,16 @@ var init_collect = __esm({
50146
50384
  });
50147
50385
 
50148
50386
  // ../cli/src/lib/dress-page.ts
50149
- import fs48 from "node:fs";
50387
+ import fs49 from "node:fs";
50150
50388
  import path53 from "node:path";
50151
50389
  function dressPage(file2) {
50152
50390
  const folder2 = path53.dirname(file2);
50153
- const html = fs48.readFileSync(file2, "utf8").replace(/<link\b[^>]*>/gi, (tag) => {
50391
+ const html = fs49.readFileSync(file2, "utf8").replace(/<link\b[^>]*>/gi, (tag) => {
50154
50392
  const href = /\bhref\s*=\s*["']?([^"'\s>]+)/i.exec(tag)?.[1];
50155
50393
  if (!/\brel\s*=\s*["']?stylesheet/i.test(tag) || !href || /^[a-z][\w+.-]*:|^\/\//i.test(href)) return tag;
50156
50394
  const at2 = path53.resolve(folder2, href);
50157
- if (!at2.startsWith(folder2 + path53.sep) || !fs48.existsSync(at2)) return tag;
50158
- const css = fs48.readFileSync(at2, "utf8").replace(/url\(\s*(["']?)([^"')]+?)\1\s*\)/gi, (whole2, quote, src) => /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src) ? whole2 : `url(${quote}${path53.relative(folder2, path53.resolve(path53.dirname(at2), src)).split(path53.sep).join("/")}${quote})`);
50395
+ if (!at2.startsWith(folder2 + path53.sep) || !fs49.existsSync(at2)) return tag;
50396
+ const css = fs49.readFileSync(at2, "utf8").replace(/url\(\s*(["']?)([^"')]+?)\1\s*\)/gi, (whole2, quote, src) => /^(?:[a-z][\w+.-]*:|\/|#)/i.test(src) ? whole2 : `url(${quote}${path53.relative(folder2, path53.resolve(path53.dirname(at2), src)).split(path53.sep).join("/")}${quote})`);
50159
50397
  return `<style>${css.replace(/\r?\n/g, " ").replace(/<\/style/gi, "<\\/style")}</style>`;
50160
50398
  });
50161
50399
  const at = /^\uFEFF?\s*(?:<!--[\s\S]*?-->\s*)*(?:<!doctype\b[^>]*>)?/i.exec(html)[0].length;
@@ -50168,25 +50406,25 @@ var init_dress_page = __esm({
50168
50406
  isHtmlFile = (file2) => /\.html?$/i.test(file2);
50169
50407
  CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data: blob:; worker-src 'none'; base-uri 'none'; form-action 'none'";
50170
50408
  head = `<meta http-equiv="Content-Security-Policy" content="${CSP}"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>html{overflow-x:hidden;overscroll-behavior:contain}</style>`;
50171
- referenceText = (file2) => isHtmlFile(file2) ? dressPage(file2) : fs48.readFileSync(file2, "utf8");
50409
+ referenceText = (file2) => isHtmlFile(file2) ? dressPage(file2) : fs49.readFileSync(file2, "utf8");
50172
50410
  }
50173
50411
  });
50174
50412
 
50175
50413
  // ../cli/src/lib/preview-files.ts
50176
- import fs49 from "node:fs";
50414
+ import fs50 from "node:fs";
50177
50415
  import path54 from "node:path";
50178
50416
  function resolver(card, id2) {
50179
50417
  const roots = [KANBAN, path54.join(ASSETS, String(id2))];
50180
- const real2 = (p) => fs49.existsSync(p) ? fs49.realpathSync(p) : p;
50418
+ const real2 = (p) => fs50.existsSync(p) ? fs50.realpathSync(p) : p;
50181
50419
  const inside2 = (p) => roots.some((root2) => p.startsWith(real2(root2) + path54.sep));
50182
50420
  return (src, owner) => {
50183
50421
  if (/^[a-z][\w+.-]*:/i.test(src) || src.startsWith("#") || src.startsWith("//")) return null;
50184
50422
  if (path54.isAbsolute(src)) throw new Error("an absolute path; name it relative to the file");
50185
50423
  const held4 = /^\.assets\//.exec(src);
50186
50424
  const file2 = held4 ? path54.resolve(ASSETS, src.slice(held4[0].length)) : path54.resolve(path54.dirname(owner), src);
50187
- if (!inside2(path54.resolve(file2)) || fs49.existsSync(file2) && !inside2(fs49.realpathSync(file2))) throw new Error(`outside this card's files (${rel(KANBAN)}, .assets/${id2}/)`);
50188
- if (!fs49.statSync(file2, { throwIfNoEntry: false })?.isFile()) throw new Error("no such file");
50189
- return { key: fs49.realpathSync(file2), file: file2 };
50425
+ if (!inside2(path54.resolve(file2)) || fs50.existsSync(file2) && !inside2(fs50.realpathSync(file2))) throw new Error(`outside this card's files (${rel(KANBAN)}, .assets/${id2}/)`);
50426
+ if (!fs50.statSync(file2, { throwIfNoEntry: false })?.isFile()) throw new Error("no such file");
50427
+ return { key: fs50.realpathSync(file2), file: file2 };
50190
50428
  };
50191
50429
  }
50192
50430
  function validatePreviewFiles(card, id2, text5) {
@@ -50229,7 +50467,7 @@ var init_preview_files = __esm({
50229
50467
  });
50230
50468
 
50231
50469
  // ../cli/src/lib/spec-contract.ts
50232
- import fs50 from "node:fs";
50470
+ import fs51 from "node:fs";
50233
50471
  import path55 from "node:path";
50234
50472
  function scanCardLines(lines, start = 0) {
50235
50473
  const visible = lines.map(() => "");
@@ -50263,11 +50501,11 @@ function scanCardLines(lines, start = 0) {
50263
50501
  }
50264
50502
  function snapshotSpecs() {
50265
50503
  const out = /* @__PURE__ */ new Map();
50266
- if (!fs50.existsSync(TODO)) return out;
50504
+ if (!fs51.existsSync(TODO)) return out;
50267
50505
  for (const file2 of walkMd(TODO)) {
50268
50506
  if (isLegacyRecurring(path55.relative(TODO, file2))) continue;
50269
50507
  const id2 = idPrefix(path55.basename(file2) === "root.md" ? path55.basename(path55.dirname(file2)) : path55.basename(file2));
50270
- if (id2 !== null) out.set(file2, { id: id2, text: fs50.readFileSync(file2, "utf8") });
50508
+ if (id2 !== null) out.set(file2, { id: id2, text: fs51.readFileSync(file2, "utf8") });
50271
50509
  }
50272
50510
  return out;
50273
50511
  }
@@ -50461,9 +50699,9 @@ function setEnd(lines, at) {
50461
50699
  }
50462
50700
  function inside(dir, name) {
50463
50701
  try {
50464
- const root2 = fs50.realpathSync(dir);
50465
- const real2 = fs50.realpathSync(path55.join(dir, name));
50466
- return real2.startsWith(root2 + path55.sep) && fs50.statSync(real2).isFile() ? real2 : null;
50702
+ const root2 = fs51.realpathSync(dir);
50703
+ const real2 = fs51.realpathSync(path55.join(dir, name));
50704
+ return real2.startsWith(root2 + path55.sep) && fs51.statSync(real2).isFile() ? real2 : null;
50467
50705
  } catch {
50468
50706
  return null;
50469
50707
  }
@@ -50496,7 +50734,7 @@ function compareProblem(attrs, id2) {
50496
50734
  const shots = (message) => ({ rule: "compare-shots", message });
50497
50735
  const json2 = (file2) => {
50498
50736
  try {
50499
- return file2.endsWith(".json") ? JSON.parse(fs50.readFileSync(file2, "utf8")) : null;
50737
+ return file2.endsWith(".json") ? JSON.parse(fs51.readFileSync(file2, "utf8")) : null;
50500
50738
  } catch {
50501
50739
  return null;
50502
50740
  }
@@ -50521,7 +50759,7 @@ function compareProblem(attrs, id2) {
50521
50759
  const file2 = inside(dir, named2.name);
50522
50760
  if (!file2) return { message: `Compare shots ${at} names no file in this card's asset folder. Write the JSON there or fix the path.` };
50523
50761
  try {
50524
- return { data: JSON.parse(fs50.readFileSync(file2, "utf8")) };
50762
+ return { data: JSON.parse(fs51.readFileSync(file2, "utf8")) };
50525
50763
  } catch {
50526
50764
  return { message: `${at} is not valid JSON.` };
50527
50765
  }
@@ -50576,7 +50814,7 @@ var init_spec_contract = __esm({
50576
50814
  });
50577
50815
 
50578
50816
  // ../cli/src/lib/reconcile.ts
50579
- import fs51 from "node:fs";
50817
+ import fs52 from "node:fs";
50580
50818
  import path56 from "node:path";
50581
50819
  function liveIds() {
50582
50820
  const ids = /* @__PURE__ */ new Set();
@@ -50592,7 +50830,7 @@ function indexableCards() {
50592
50830
  const out = [];
50593
50831
  for (const dir of walkDirs(TODO)) {
50594
50832
  const id2 = idPrefix(path56.basename(dir));
50595
- if (id2 != null && fs51.existsSync(path56.join(dir, "root.md"))) {
50833
+ if (id2 != null && fs52.existsSync(path56.join(dir, "root.md"))) {
50596
50834
  out.push({ id: id2, rel: path56.join(path56.relative(TODO, dir), "root.md").split(path56.sep).join("/") });
50597
50835
  }
50598
50836
  }
@@ -50609,7 +50847,7 @@ function indexableCards() {
50609
50847
  }
50610
50848
  function readmeComplaints(fix) {
50611
50849
  const said2 = [];
50612
- const lines = fs51.readFileSync(README, "utf8").split("\n");
50850
+ const lines = fs52.readFileSync(README, "utf8").split("\n");
50613
50851
  const indexed = /* @__PURE__ */ new Set();
50614
50852
  let fixed = 0;
50615
50853
  for (let i = 0; i < lines.length; i++) {
@@ -50618,7 +50856,7 @@ function readmeComplaints(fix) {
50618
50856
  const id2 = Number(m[1]);
50619
50857
  const linkPath = m[2];
50620
50858
  indexed.add(id2);
50621
- if (fs51.existsSync(path56.join(TODO, linkPath))) continue;
50859
+ if (fs52.existsSync(path56.join(TODO, linkPath))) continue;
50622
50860
  const found2 = locate(id2);
50623
50861
  if (!found2) {
50624
50862
  said2.push(`README links #${id2} \u2192 ${linkPath}, but no card with that id exists (removed by hand?). Drop the entry or restore the file.`);
@@ -50634,7 +50872,7 @@ function readmeComplaints(fix) {
50634
50872
  said2.push(`README link #${id2} pointed at missing ${linkPath} \u2192 repointed to ${want}.`);
50635
50873
  fixed++;
50636
50874
  }
50637
- if (fixed) fs51.writeFileSync(README, lines.join("\n"));
50875
+ if (fixed) fs52.writeFileSync(README, lines.join("\n"));
50638
50876
  for (const c of indexableCards()) {
50639
50877
  if (!indexed.has(c.id)) {
50640
50878
  said2.push(`card ${c.rel} (#${c.id}) is not in the README index. Add it under "## ${TASKS_HEADING}".`);
@@ -50650,7 +50888,7 @@ function crossRefComplaints() {
50650
50888
  if (base === "README.md") continue;
50651
50889
  const ownerId = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file2))) : idPrefix(base);
50652
50890
  if (ownerId == null) continue;
50653
- const { meta: meta3 } = parseFrontmatter(fs51.readFileSync(file2, "utf8"));
50891
+ const { meta: meta3 } = parseFrontmatter(fs52.readFileSync(file2, "utf8"));
50654
50892
  if (!meta3) continue;
50655
50893
  for (const field2 of ["blocked_by", "related"]) {
50656
50894
  for (const ref of meta3[field2] || []) {
@@ -50663,7 +50901,7 @@ function crossRefComplaints() {
50663
50901
  return said2;
50664
50902
  }
50665
50903
  function reconcileBoard() {
50666
- if (!fs51.existsSync(README)) return;
50904
+ if (!fs52.existsSync(README)) return;
50667
50905
  for (const line of [...readmeComplaints(true), ...crossRefComplaints()]) warn2(line);
50668
50906
  }
50669
50907
  var README_LINK;
@@ -50679,7 +50917,7 @@ var init_reconcile = __esm({
50679
50917
  });
50680
50918
 
50681
50919
  // ../cli/src/commands/card.ts
50682
- import fs52 from "node:fs";
50920
+ import fs53 from "node:fs";
50683
50921
  import path57 from "node:path";
50684
50922
  function defaultBody(summary2 = "<\u7528\u4E00\u5C0F\u6BB5\u8BDD\u5148\u8BB2\u53D1\u751F\u4E86\u4EC0\u4E48\u3001\u7528\u6237\u9047\u5230\u4EC0\u4E48\uFF0C\u518D\u8BB2\u8FD9\u5F20\u5361\u8981\u8FBE\u5230\u7684\u7ED3\u679C\u3002>") {
50685
50923
  return [
@@ -50706,7 +50944,7 @@ function bodyFromFile(opts) {
50706
50944
  if (opts.body === false) die("pass --body-file or --no-body, not both");
50707
50945
  let text5;
50708
50946
  try {
50709
- text5 = fs52.readFileSync(opts.bodyFile, "utf8");
50947
+ text5 = fs53.readFileSync(opts.bodyFile, "utf8");
50710
50948
  } catch {
50711
50949
  die(`can't read ${opts.bodyFile} \u2014 write the body to a file, then pass its path`, { kind: "needs-input" });
50712
50950
  }
@@ -50778,12 +51016,12 @@ function cmdCreate(opts) {
50778
51016
  return { id: start, ids: [start], title, file: rel(held4.target), indexed: false };
50779
51017
  }
50780
51018
  if (held4) die(`#${start} is already a card here (${rel(held4.target)})`, { kind: "id-taken", id: start });
50781
- if (fs52.existsSync(file2)) die(`${rel(file2)} already exists \u2014 pick a different --slug`);
51019
+ if (fs53.existsSync(file2)) die(`${rel(file2)} already exists \u2014 pick a different --slug`);
50782
51020
  countBoardEvent(triage ? "cards_created_proposed" : "cards_created_asked");
50783
51021
  const meta3 = { title, priority, status: "todo", blocked_by, related, modules, studio, previews, triage, source: source2, questions };
50784
51022
  const scaffolded = !written && opts.body !== false;
50785
51023
  const body = written ?? (scaffolded ? defaultBody() : "");
50786
- fs52.writeFileSync(file2, serializeFrontmatter(meta3) + "\n\n" + body);
51024
+ fs53.writeFileSync(file2, serializeFrontmatter(meta3) + "\n\n" + body);
50787
51025
  const indexed = addReadmeRef(start, title, fileRel);
50788
51026
  say(start);
50789
51027
  say(
@@ -50836,7 +51074,7 @@ function cmdUpdate(id2, flags) {
50836
51074
  const found2 = locate(id2);
50837
51075
  if (!found2) die(`no task with id ${id2} under ${rel(TODO)}`, { kind: "card-not-found", id: id2 });
50838
51076
  const file2 = found2.kind === "group" ? path57.join(found2.target, "root.md") : found2.target;
50839
- const { meta: meta3, body } = parseFrontmatter(fs52.readFileSync(file2, "utf8"));
51077
+ const { meta: meta3, body } = parseFrontmatter(fs53.readFileSync(file2, "utf8"));
50840
51078
  if (!meta3) die(`${rel(file2)} has no frontmatter \u2014 recreate it with \`akb raw create\``);
50841
51079
  if (flags.blockedBy !== void 0 && flags.addBlockedBy !== void 0) die("--blocked-by replaces the list and --add-blocked-by appends to it \u2014 pass one");
50842
51080
  if (flags.related !== void 0 && flags.addRelated !== void 0) die("--related replaces the list and --add-related appends to it \u2014 pass one");
@@ -50912,9 +51150,9 @@ function cmdUpdate(id2, flags) {
50912
51150
  const destRel = path57.join(path57.dirname(curRel), base);
50913
51151
  const dest = path57.join(TODO, destRel);
50914
51152
  const moving = dest !== file2;
50915
- if (moving && fs52.existsSync(dest)) die(`${rel(dest)} already exists`);
50916
- fs52.writeFileSync(file2, serializeFrontmatter(meta3) + "\n" + body);
50917
- if (moving) fs52.renameSync(file2, dest);
51153
+ if (moving && fs53.existsSync(dest)) die(`${rel(dest)} already exists`);
51154
+ fs53.writeFileSync(file2, serializeFrontmatter(meta3) + "\n" + body);
51155
+ if (moving) fs53.renameSync(file2, dest);
50918
51156
  if (isSubtask) {
50919
51157
  if (moving || changes.includes("title")) repointReadmeLink(id2, curRel, destRel, meta3.title);
50920
51158
  if (moving) changes.push(`renamed \u2192 ${destRel.split(path57.sep).join("/")}`);
@@ -50930,14 +51168,16 @@ function cmdUpdate(id2, flags) {
50930
51168
  return { id: id2, changes, file: rel(dest) };
50931
51169
  }
50932
51170
  function cmdUpdateQuestions(id2, input2) {
50933
- const ops = readQuestionOps(input2.ops ?? []);
51171
+ return updateCardQuestions(id2, readQuestionOps(input2.ops ?? [], true), true);
51172
+ }
51173
+ function updateCardQuestions(id2, ops, compatibility = false) {
50934
51174
  const found2 = locate(id2);
50935
51175
  if (!found2) die(`no task with id ${id2} under ${rel(TODO)}`, { kind: "card-not-found", id: id2 });
50936
51176
  const file2 = found2.kind === "group" ? path57.join(found2.target, "root.md") : found2.target;
50937
- const { meta: meta3, body } = parseFrontmatter(fs52.readFileSync(file2, "utf8"));
51177
+ const { meta: meta3, body } = parseFrontmatter(fs53.readFileSync(file2, "utf8"));
50938
51178
  if (!meta3) die(`${rel(file2)} has no frontmatter \u2014 recreate it with \`akb raw create\``);
50939
51179
  for (const op of ops) {
50940
- if (!op.question?.agent) continue;
51180
+ if (!compatibility || !op.question?.agent) continue;
50941
51181
  const agent = findSpecAgent(op.question.agent);
50942
51182
  if (!agent) die(`--agent "${op.question.agent}" is not an agent on this board`, { kind: "no-such-spec-agent", specAgent: op.question.agent });
50943
51183
  op.question.agent = agent.name;
@@ -50956,7 +51196,7 @@ function cmdUpdateQuestions(id2, input2) {
50956
51196
  meta3.status = "todo";
50957
51197
  changes.push("status\u2192todo (open questions)");
50958
51198
  }
50959
- fs52.writeFileSync(file2, serializeFrontmatter(meta3) + "\n" + body);
51199
+ fs53.writeFileSync(file2, serializeFrontmatter(meta3) + "\n" + body);
50960
51200
  const closed2 = activeDelivery(id2) ? "questions_closed_verify" : "questions_closed_user";
50961
51201
  for (const _ of done.closed) countBoardEvent(closed2);
50962
51202
  say(`updated #${id2} questions: ${changes.join(", ")} (${open4} open)`);
@@ -51015,7 +51255,7 @@ var init_config_template = __esm({
51015
51255
  });
51016
51256
 
51017
51257
  // ../cli/src/commands/init.ts
51018
- import fs53 from "node:fs";
51258
+ import fs54 from "node:fs";
51019
51259
  function boardReadme() {
51020
51260
  return `# Board
51021
51261
 
@@ -51028,20 +51268,20 @@ _(none)_
51028
51268
  `;
51029
51269
  }
51030
51270
  function writeConfigIfMissing() {
51031
- if (fs53.existsSync(CONFIG)) return false;
51032
- fs53.mkdirSync(KANBAN, { recursive: true });
51033
- fs53.writeFileSync(CONFIG, CONFIG_TEMPLATE);
51271
+ if (fs54.existsSync(CONFIG)) return false;
51272
+ fs54.mkdirSync(KANBAN, { recursive: true });
51273
+ fs54.writeFileSync(CONFIG, CONFIG_TEMPLATE);
51034
51274
  return true;
51035
51275
  }
51036
51276
  function writeModulesIfMissing() {
51037
- if (fs53.existsSync(MODULES_MD)) return false;
51038
- fs53.mkdirSync(KANBAN, { recursive: true });
51039
- fs53.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
51277
+ if (fs54.existsSync(MODULES_MD)) return false;
51278
+ fs54.mkdirSync(KANBAN, { recursive: true });
51279
+ fs54.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
51040
51280
  return true;
51041
51281
  }
51042
51282
  function writeGitignoreIfMissing() {
51043
- fs53.mkdirSync(KANBAN, { recursive: true });
51044
- const text5 = fs53.existsSync(KANBAN_GITIGNORE) ? fs53.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
51283
+ fs54.mkdirSync(KANBAN, { recursive: true });
51284
+ const text5 = fs54.existsSync(KANBAN_GITIGNORE) ? fs54.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
51045
51285
  const has = (rule) => text5.split("\n").some((line) => line.trim() === rule.line);
51046
51286
  const missing = IGNORE_RULES.filter((rule) => !has(rule));
51047
51287
  if (!missing.length) return false;
@@ -51049,23 +51289,23 @@ function writeGitignoreIfMissing() {
51049
51289
  ${rule.line}
51050
51290
  `).join("");
51051
51291
  const separator = !text5 || text5.endsWith("\n") ? "" : "\n";
51052
- fs53.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
51292
+ fs54.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
51053
51293
  return true;
51054
51294
  }
51055
51295
  function writeSkeletonIfMissing() {
51056
51296
  const added = [];
51057
- if (!fs53.existsSync(TODO)) {
51058
- fs53.mkdirSync(TODO, { recursive: true });
51297
+ if (!fs54.existsSync(TODO)) {
51298
+ fs54.mkdirSync(TODO, { recursive: true });
51059
51299
  added.push(`${rel(TODO)}/`);
51060
51300
  }
51061
- if (!fs53.existsSync(README)) {
51062
- fs53.writeFileSync(README, boardReadme());
51301
+ if (!fs54.existsSync(README)) {
51302
+ fs54.writeFileSync(README, boardReadme());
51063
51303
  added.push(rel(README));
51064
51304
  }
51065
51305
  return added;
51066
51306
  }
51067
51307
  function cmdInit() {
51068
- if (fs53.existsSync(KANBAN)) {
51308
+ if (fs54.existsSync(KANBAN)) {
51069
51309
  const added = [
51070
51310
  ...writeSkeletonIfMissing(),
51071
51311
  writeConfigIfMissing() && rel(CONFIG),
@@ -51082,8 +51322,8 @@ function cmdInit() {
51082
51322
  }
51083
51323
  return { board: rel(KANBAN), created: false, added, memory_paths: scaffolded.map((s) => rel(s.dir)) };
51084
51324
  }
51085
- fs53.mkdirSync(TODO, { recursive: true });
51086
- fs53.writeFileSync(README, boardReadme());
51325
+ fs54.mkdirSync(TODO, { recursive: true });
51326
+ fs54.writeFileSync(README, boardReadme());
51087
51327
  writeConfigIfMissing();
51088
51328
  scaffoldProjectMemory();
51089
51329
  writeModulesIfMissing();
@@ -51118,15 +51358,15 @@ _(not filled in yet \u2014 build the map from the repo before tagging a card.)_
51118
51358
  });
51119
51359
 
51120
51360
  // ../cli/src/lib/card-age.ts
51121
- import fs54 from "node:fs";
51361
+ import fs55 from "node:fs";
51122
51362
  import path58 from "node:path";
51123
51363
  function staleAfterIn(config2) {
51124
51364
  const days = Number(LINE.exec(config2)?.[1]);
51125
51365
  return Number.isInteger(days) && days > 0 ? days : STALE_AFTER_DEFAULT;
51126
51366
  }
51127
51367
  function staleAfter() {
51128
- if (!fs54.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
51129
- return staleAfterIn(fs54.readFileSync(CONFIG, "utf8"));
51368
+ if (!fs55.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
51369
+ return staleAfterIn(fs55.readFileSync(CONFIG, "utf8"));
51130
51370
  }
51131
51371
  function todoPathspec(top) {
51132
51372
  const from = path58.relative(real(top), real(TODO));
@@ -51183,7 +51423,7 @@ var init_card_age = __esm({
51183
51423
  gitTop = () => git(["rev-parse", "--show-toplevel"])?.trim() || null;
51184
51424
  real = (p) => {
51185
51425
  try {
51186
- return fs54.realpathSync(p);
51426
+ return fs55.realpathSync(p);
51187
51427
  } catch {
51188
51428
  return path58.resolve(p);
51189
51429
  }
@@ -51219,7 +51459,7 @@ var init_card_holds = __esm({
51219
51459
  });
51220
51460
 
51221
51461
  // ../cli/src/commands/list.ts
51222
- import fs55 from "node:fs";
51462
+ import fs56 from "node:fs";
51223
51463
  import path59 from "node:path";
51224
51464
  function summaryLine(body) {
51225
51465
  const lines = body.split("\n");
@@ -51242,7 +51482,7 @@ function openRows() {
51242
51482
  const id2 = isRoot ? idPrefix(path59.basename(path59.dirname(file2))) : idPrefix(base);
51243
51483
  if (id2 == null) continue;
51244
51484
  if (isLegacyRecurring(path59.relative(TODO, file2))) continue;
51245
- const { meta: meta3, body } = parseFrontmatter(fs55.readFileSync(file2, "utf8"));
51485
+ const { meta: meta3, body } = parseFrontmatter(fs56.readFileSync(file2, "utf8"));
51246
51486
  rows.push({
51247
51487
  id: id2,
51248
51488
  file: file2,
@@ -51284,7 +51524,7 @@ function cmdStale(rows, all2, scope, mod) {
51284
51524
  }
51285
51525
  function archivedFiles() {
51286
51526
  const files = /* @__PURE__ */ new Map();
51287
- if (!fs55.existsSync(ARCHIVE)) return files;
51527
+ if (!fs56.existsSync(ARCHIVE)) return files;
51288
51528
  for (const file2 of walkMd(ARCHIVE)) {
51289
51529
  const id2 = idPrefix(path59.basename(file2));
51290
51530
  if (id2 !== null) files.set(id2, file2);
@@ -51292,7 +51532,7 @@ function archivedFiles() {
51292
51532
  for (const dir of walkDirs(ARCHIVE)) {
51293
51533
  const id2 = idPrefix(path59.basename(dir));
51294
51534
  const root2 = path59.join(dir, "root.md");
51295
- if (id2 !== null && fs55.existsSync(root2)) files.set(id2, root2);
51535
+ if (id2 !== null && fs56.existsSync(root2)) files.set(id2, root2);
51296
51536
  }
51297
51537
  return files;
51298
51538
  }
@@ -51390,10 +51630,10 @@ var init_list = __esm({
51390
51630
  });
51391
51631
 
51392
51632
  // ../cli/src/lib/group-close.ts
51393
- import fs56 from "node:fs";
51633
+ import fs57 from "node:fs";
51394
51634
  function groupCloses(rootFile) {
51395
51635
  try {
51396
- return groupCloseOf(fs56.readFileSync(rootFile, "utf8"));
51636
+ return groupCloseOf(fs57.readFileSync(rootFile, "utf8"));
51397
51637
  } catch {
51398
51638
  return false;
51399
51639
  }
@@ -51406,7 +51646,7 @@ var init_group_close = __esm({
51406
51646
  });
51407
51647
 
51408
51648
  // ../cli/src/commands/remove.ts
51409
- import fs57 from "node:fs";
51649
+ import fs58 from "node:fs";
51410
51650
  import path60 from "node:path";
51411
51651
  function leavingIds(id2, found2) {
51412
51652
  const ids = /* @__PURE__ */ new Set([id2]);
@@ -51423,10 +51663,10 @@ function findMentions(ids) {
51423
51663
  const hits = [];
51424
51664
  const re = new RegExp(ids.map((id2) => `#${id2}(?!\\d)`).join("|"));
51425
51665
  for (const dir of [TODO, MEMORY]) {
51426
- if (!fs57.existsSync(dir)) continue;
51666
+ if (!fs58.existsSync(dir)) continue;
51427
51667
  for (const file2 of walkMd(dir)) {
51428
51668
  if (path60.basename(file2) === "README.md") continue;
51429
- const lines = fs57.readFileSync(file2, "utf8").split("\n");
51669
+ const lines = fs58.readFileSync(file2, "utf8").split("\n");
51430
51670
  const fmEnd = frontmatterEnd(lines);
51431
51671
  lines.forEach((line, i) => {
51432
51672
  if (!re.test(line)) return;
@@ -51456,10 +51696,10 @@ function stampLeaving(cards, rejection) {
51456
51696
  const day = formatDay();
51457
51697
  const stamp4 = rejection && !rejection.discard ? { reason: rejection.reason, at: (/* @__PURE__ */ new Date()).toISOString(), by: insideRun() || workspaceTask() ? "agent" : "user" } : rejection && { reason: rejection.reason };
51458
51698
  for (const card of cards) {
51459
- if (!fs57.existsSync(card.file)) continue;
51460
- const text5 = fs57.readFileSync(card.file, "utf8");
51699
+ if (!fs58.existsSync(card.file)) continue;
51700
+ const text5 = fs58.readFileSync(card.file, "utf8");
51461
51701
  const stamped = stampLeavingIn(text5, day, stamp4);
51462
- if (stamped !== text5) fs57.writeFileSync(card.file, stamped);
51702
+ if (stamped !== text5) fs58.writeFileSync(card.file, stamped);
51463
51703
  }
51464
51704
  }
51465
51705
  function agentDecisions(text5) {
@@ -51489,14 +51729,14 @@ function removeCard(id2, metric, options) {
51489
51729
  if (!found2) die(`no task with id ${id2} under ${rel(TODO)}`, { kind: "card-not-found", id: id2 });
51490
51730
  const dest = options.cleanupDiscarded && locateArchived(id2) ? null : archiveDest(found2);
51491
51731
  const cardFile3 = found2.kind === "group" ? path60.join(found2.target, "root.md") : found2.target;
51492
- const cardText = fs57.existsSync(cardFile3) ? fs57.readFileSync(cardFile3, "utf8") : "";
51732
+ const cardText = fs58.existsSync(cardFile3) ? fs58.readFileSync(cardFile3, "utf8") : "";
51493
51733
  const { meta: cardMeta3 } = parseFrontmatter(cardText);
51494
51734
  const alsoRemoved = found2.kind === "group" ? walkMd(found2.target).filter((f) => f !== cardFile3).map((f) => rel(f)).sort() : [];
51495
51735
  const leftIds = leavingIds(id2, found2);
51496
51736
  const leaving = leavingCards(id2, found2);
51497
51737
  if (options.archivingTask) {
51498
51738
  for (const card of leaving) {
51499
- const meta3 = parseFrontmatter(fs57.readFileSync(card.file, "utf8")).meta;
51739
+ const meta3 = parseFrontmatter(fs58.readFileSync(card.file, "utf8")).meta;
51500
51740
  if (!meta3 || meta3.rejected) die(`#${card.id} is not eligible for archive.`, { kind: "conflict" });
51501
51741
  if (meta3.questions.length) die(`Resolve the open questions on #${card.id} before archiving.`, { kind: "conflict" });
51502
51742
  if (card.id !== id2 && (activeDelivery(card.id) || creationRefusal(card.id, cardCreation(card.id), "archive", false))) {
@@ -51530,10 +51770,10 @@ function removeCard(id2, metric, options) {
51530
51770
  const groupRoot = found2.kind === "file" && !options.closing ? enclosingGroupRoot(found2.target) : null;
51531
51771
  if (dest) {
51532
51772
  stampLeaving(leaving, metric === "rejected" ? { reason: options.reason?.trim() ?? "", discard: options.discard === true } : null);
51533
- fs57.mkdirSync(ARCHIVE, { recursive: true });
51534
- fs57.renameSync(found2.target, dest);
51773
+ fs58.mkdirSync(ARCHIVE, { recursive: true });
51774
+ fs58.renameSync(found2.target, dest);
51535
51775
  } else {
51536
- fs57.rmSync(found2.target, { recursive: true, force: true });
51776
+ fs58.rmSync(found2.target, { recursive: true, force: true });
51537
51777
  }
51538
51778
  const removedRefs = stripReadmeRefs(found2);
51539
51779
  let marked2 = null;
@@ -51589,7 +51829,7 @@ function closeGroup(rootFile) {
51589
51829
  say(`
51590
51830
  every subtask line on #${rootId} is resolved \u2014 closing the group:`);
51591
51831
  try {
51592
- const { meta: meta3, body } = parseFrontmatter(fs57.readFileSync(rootFile, "utf8"));
51832
+ const { meta: meta3, body } = parseFrontmatter(fs58.readFileSync(rootFile, "utf8"));
51593
51833
  const res = cmdRemove(rootId, "completed", { closing: true });
51594
51834
  return {
51595
51835
  id: rootId,
@@ -51633,7 +51873,7 @@ next \u2014 what the script can't do:
51633
51873
  }
51634
51874
  if (mentions.some((m) => m.where !== "body")) {
51635
51875
  say(" A mention in frontmatter is the script's to rewrite, not yours:");
51636
- say(' `update-questions <id> --update <n> "..."` (see help).');
51876
+ say(' `akb task update-questions <task> --update <n> "..."` (see help).');
51637
51877
  }
51638
51878
  return note;
51639
51879
  }
@@ -51653,7 +51893,7 @@ function recoveredArchiveHandoff(id2, source2) {
51653
51893
  const found2 = locateArchived(id2);
51654
51894
  if (!found2) throw new Error(`No archived card #${id2} was found.`);
51655
51895
  const file2 = found2.kind === "group" ? path60.join(found2.target, "root.md") : found2.target;
51656
- const { meta: meta3 } = parseFrontmatter(fs57.readFileSync(file2, "utf8"));
51896
+ const { meta: meta3 } = parseFrontmatter(fs58.readFileSync(file2, "utf8"));
51657
51897
  stripReadmeRefs(source2 ?? found2);
51658
51898
  const root2 = source2?.kind === "file" ? enclosingGroupRoot(source2.target) : null;
51659
51899
  if (root2) markSubtask(root2, id2, "tick");
@@ -51772,7 +52012,7 @@ var init_bundled2 = __esm({
51772
52012
  });
51773
52013
 
51774
52014
  // ../cli/src/lib/memories.ts
51775
- import fs58 from "node:fs";
52015
+ import fs59 from "node:fs";
51776
52016
  import path61 from "node:path";
51777
52017
  function readMemory(text5, builtIn, folder2) {
51778
52018
  const { meta: meta3, body } = splitFrontmatter(text5);
@@ -51804,14 +52044,14 @@ function globalMemories() {
51804
52044
  }
51805
52045
  let folders2 = [];
51806
52046
  try {
51807
- folders2 = fs58.readdirSync(MEMORY, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
52047
+ folders2 = fs59.readdirSync(MEMORY, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
51808
52048
  } catch {
51809
52049
  }
51810
52050
  for (const name of folders2) {
51811
52051
  if (name in BUNDLED_MEMORY_FILES || name === RESERVED_MEMORY_DIR || name === STUDIO_MEMORY_DIR) continue;
51812
52052
  const file2 = path61.join(MEMORY, name, GLOBAL_MEMORY_FILE);
51813
- if (!fs58.existsSync(file2)) continue;
51814
- const memory = readMemory(fs58.readFileSync(file2, "utf8"), false, name);
52053
+ if (!fs59.existsSync(file2)) continue;
52054
+ const memory = readMemory(fs59.readFileSync(file2, "utf8"), false, name);
51815
52055
  if (memory) out.push(memory);
51816
52056
  }
51817
52057
  return out;
@@ -51852,7 +52092,7 @@ var init_memory_file = __esm({
51852
52092
  });
51853
52093
 
51854
52094
  // ../cli/src/commands/inspect.ts
51855
- import fs59 from "node:fs";
52095
+ import fs60 from "node:fs";
51856
52096
  import os4 from "node:os";
51857
52097
  import path62 from "node:path";
51858
52098
  function cmdInspect(id2) {
@@ -51860,7 +52100,7 @@ function cmdInspect(id2) {
51860
52100
  const unavailable = [];
51861
52101
  function read5(source2, file3, empty) {
51862
52102
  try {
51863
- return JSON.parse(fs59.readFileSync(file3, "utf8"));
52103
+ return JSON.parse(fs60.readFileSync(file3, "utf8"));
51864
52104
  } catch (error62) {
51865
52105
  if (error62.code === "ENOENT") return empty;
51866
52106
  findings.push({ source: source2, message: String(error62) });
@@ -51882,7 +52122,7 @@ function cmdInspect(id2) {
51882
52122
  const file2 = found2.kind === "group" ? path62.join(found2.target, "root.md") : found2.target;
51883
52123
  let card = null;
51884
52124
  try {
51885
- const { meta: meta3, body } = parseFrontmatter(fs59.readFileSync(file2, "utf8"));
52125
+ const { meta: meta3, body } = parseFrontmatter(fs60.readFileSync(file2, "utf8"));
51886
52126
  if (!meta3) throw Error("The card frontmatter could not be parsed.");
51887
52127
  card = { path: rel(file2), questions: meta3.questions, todos: [...body.matchAll(/^\s*[-*]\s+\[([ xX])\]\s+(.*)$/gm)].map((m) => ({ text: m[2], done: m[1] !== " " })) };
51888
52128
  } catch (error62) {
@@ -51895,7 +52135,7 @@ function cmdInspect(id2) {
51895
52135
  const records = [];
51896
52136
  const directory = path62.join(KANBAN, "deliveries");
51897
52137
  try {
51898
- for (const name of fs59.readdirSync(directory).filter((name2) => name2.endsWith(".json"))) {
52138
+ for (const name of fs60.readdirSync(directory).filter((name2) => name2.endsWith(".json"))) {
51899
52139
  const held5 = read5("delivery", path62.join(directory, name), null);
51900
52140
  if (held5?.cardId === id2) records.push(held5);
51901
52141
  }
@@ -51949,7 +52189,7 @@ function cmdValidate(id2) {
51949
52189
  const reason = errors.length ? formatContractErrors(errors) : void 0;
51950
52190
  const session = insideRun();
51951
52191
  if (session) patch(session, (run3) => {
51952
- run3.validationFailure = reason ? { code: "validation_failed", level: 1, source: "validation", reason } : void 0;
52192
+ run3.validationFailure = reason ? makeFailure("validation", reason, { code: "validation_failed", detail: reason }) : void 0;
51953
52193
  });
51954
52194
  if (reason) die(reason, { kind: "spec-contract", errors });
51955
52195
  say(`Spec format valid (${cards.length} card${cards.length === 1 ? "" : "s"}).`);
@@ -51958,6 +52198,7 @@ function cmdValidate(id2) {
51958
52198
  var init_validate2 = __esm({
51959
52199
  "../cli/src/commands/validate.ts"() {
51960
52200
  "use strict";
52201
+ init_retry();
51961
52202
  init_env();
51962
52203
  init_sessions();
51963
52204
  init_io();
@@ -51967,7 +52208,7 @@ var init_validate2 = __esm({
51967
52208
  });
51968
52209
 
51969
52210
  // ../cli/src/lib/card-sources.ts
51970
- import fs60 from "node:fs";
52211
+ import fs61 from "node:fs";
51971
52212
  import path63 from "node:path";
51972
52213
  function planById(id2) {
51973
52214
  const found2 = readPlan(`plans/${id2}-.md`);
@@ -51979,7 +52220,7 @@ function cardLink(id2) {
51979
52220
  if (!found2) return null;
51980
52221
  try {
51981
52222
  const file2 = found2.kind === "group" ? path63.join(found2.target, "root.md") : found2.target;
51982
- const title = parseFrontmatter(fs60.readFileSync(file2, "utf8")).meta?.title ?? "";
52223
+ const title = parseFrontmatter(fs61.readFileSync(file2, "utf8")).meta?.title ?? "";
51983
52224
  return { kind: "card", ref: String(id2), title, ...open4 ? {} : { archived: true } };
51984
52225
  } catch {
51985
52226
  return null;
@@ -52042,7 +52283,7 @@ var init_card_sources = __esm({
52042
52283
  });
52043
52284
 
52044
52285
  // ../cli/src/lib/view/read.ts
52045
- import fs61 from "node:fs";
52286
+ import fs62 from "node:fs";
52046
52287
  import path64 from "node:path";
52047
52288
  function readCard(file2, relFromTodo) {
52048
52289
  const id2 = idPrefix(path64.basename(relFromTodo));
@@ -52055,7 +52296,7 @@ function readCard(file2, relFromTodo) {
52055
52296
  return buildCard(id2, file2, relFromTodo);
52056
52297
  }
52057
52298
  function buildCard(id2, file2, relFromTodo) {
52058
- const text5 = fs61.readFileSync(file2, "utf8");
52299
+ const text5 = fs62.readFileSync(file2, "utf8");
52059
52300
  const { meta: meta3, body } = parseFrontmatter(text5);
52060
52301
  if (!meta3) return null;
52061
52302
  const relPath = relFromTodo.split(path64.sep).join("/");
@@ -52066,7 +52307,7 @@ function buildCard(id2, file2, relFromTodo) {
52066
52307
  // Derived from the file exactly as it is on disk (lib/board/revision.ts), so a card
52067
52308
  // read here and a card read by the contract agree on what version this is.
52068
52309
  revision: revisionOf(text5),
52069
- updatedAt: fs61.statSync(file2).mtime.toISOString(),
52310
+ updatedAt: fs62.statSync(file2).mtime.toISOString(),
52070
52311
  relPath,
52071
52312
  title: meta3.title,
52072
52313
  priority: meta3.priority,
@@ -52088,7 +52329,7 @@ function buildCard(id2, file2, relFromTodo) {
52088
52329
  function readGroup(folderName) {
52089
52330
  const groupDir = path64.join(TODO, folderName);
52090
52331
  const rootFile = path64.join(groupDir, "root.md");
52091
- if (!fs61.existsSync(rootFile)) return null;
52332
+ if (!fs62.existsSync(rootFile)) return null;
52092
52333
  const root2 = readCard(rootFile, path64.join(folderName, "root.md"));
52093
52334
  if (!root2) return null;
52094
52335
  root2.isGroup = true;
@@ -52096,7 +52337,7 @@ function readGroup(folderName) {
52096
52337
  root2.subtaskLines = { total, resolved };
52097
52338
  const subCards = [];
52098
52339
  const recurse = (dir, relDir) => {
52099
- for (const entry of fs61.readdirSync(dir, { withFileTypes: true })) {
52340
+ for (const entry of fs62.readdirSync(dir, { withFileTypes: true })) {
52100
52341
  const childRel = path64.join(relDir, entry.name);
52101
52342
  if (entry.isDirectory()) {
52102
52343
  recurse(path64.join(dir, entry.name), childRel);
@@ -52123,9 +52364,9 @@ function readGroup(folderName) {
52123
52364
  }
52124
52365
  function standaloneCards(dirRel) {
52125
52366
  const dir = dirRel ? path64.join(TODO, dirRel) : TODO;
52126
- if (!fs61.existsSync(dir)) return [];
52367
+ if (!fs62.existsSync(dir)) return [];
52127
52368
  const cards = [];
52128
- for (const entry of fs61.readdirSync(dir, { withFileTypes: true })) {
52369
+ for (const entry of fs62.readdirSync(dir, { withFileTypes: true })) {
52129
52370
  if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md") {
52130
52371
  const c = readCard(path64.join(dir, entry.name), path64.join(dirRel, entry.name));
52131
52372
  if (c) cards.push(c);
@@ -52139,7 +52380,7 @@ function collectCards() {
52139
52380
  const top = standaloneCards("");
52140
52381
  board2.push(...top);
52141
52382
  every.push(...top);
52142
- for (const entry of fs61.readdirSync(TODO, { withFileTypes: true })) {
52383
+ for (const entry of fs62.readdirSync(TODO, { withFileTypes: true })) {
52143
52384
  if (!entry.isDirectory()) continue;
52144
52385
  if (isGroupFolder(entry.name)) {
52145
52386
  const g = readGroup(entry.name);
@@ -52171,7 +52412,7 @@ function findCard(id2) {
52171
52412
  }
52172
52413
  function attachSources(card) {
52173
52414
  try {
52174
- const { meta: meta3, body } = parseFrontmatter(fs61.readFileSync(path64.join(TODO, card.relPath), "utf8"));
52415
+ const { meta: meta3, body } = parseFrontmatter(fs62.readFileSync(path64.join(TODO, card.relPath), "utf8"));
52175
52416
  const sources2 = meta3 ? cardSources(meta3, body) : [];
52176
52417
  if (sources2.length) card.sources = sources2;
52177
52418
  } catch {
@@ -52545,7 +52786,7 @@ var init_project_agent = __esm({
52545
52786
 
52546
52787
  // ../cli/src/lib/agent/creation.ts
52547
52788
  import crypto3 from "node:crypto";
52548
- import fs62 from "node:fs";
52789
+ import fs63 from "node:fs";
52549
52790
  import path65 from "node:path";
52550
52791
  function creationError(error62, triage) {
52551
52792
  const zh = readLanguage() === "zh";
@@ -52577,7 +52818,7 @@ ${slot}`).digest("hex");
52577
52818
  function readCreation(file2, said2) {
52578
52819
  return withCreationLock(() => {
52579
52820
  try {
52580
- const held4 = JSON.parse(fs62.readFileSync(file2, "utf8"));
52821
+ const held4 = JSON.parse(fs63.readFileSync(file2, "utf8"));
52581
52822
  if (!held4.said || typeof held4.said.title !== "string") throw new Error("Invalid creation journal");
52582
52823
  return held4;
52583
52824
  } catch (error62) {
@@ -52589,10 +52830,10 @@ function readCreation(file2, said2) {
52589
52830
  });
52590
52831
  }
52591
52832
  function saveCreation(file2, journal) {
52592
- fs62.mkdirSync(path65.dirname(file2), { recursive: true });
52833
+ fs63.mkdirSync(path65.dirname(file2), { recursive: true });
52593
52834
  const temp = `${file2}.${crypto3.randomUUID()}.tmp`;
52594
- fs62.writeFileSync(temp, JSON.stringify(journal));
52595
- fs62.renameSync(temp, file2);
52835
+ fs63.writeFileSync(temp, JSON.stringify(journal));
52836
+ fs63.renameSync(temp, file2);
52596
52837
  }
52597
52838
  function archiveCreation(source2, id2) {
52598
52839
  if (readArchived().some((s) => s.sourceId === source2 && s.cardId === id2)) return;
@@ -53738,7 +53979,7 @@ var require_command = __commonJS({
53738
53979
  var EventEmitter = __require("node:events").EventEmitter;
53739
53980
  var childProcess = __require("node:child_process");
53740
53981
  var path88 = __require("node:path");
53741
- var fs90 = __require("node:fs");
53982
+ var fs91 = __require("node:fs");
53742
53983
  var process2 = __require("node:process");
53743
53984
  var { Argument: Argument2, humanReadableArgName } = require_argument();
53744
53985
  var { CommanderError: CommanderError2 } = require_error();
@@ -54719,7 +54960,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
54719
54960
  * @param {string} subcommandName
54720
54961
  */
54721
54962
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
54722
- if (fs90.existsSync(executableFile)) return;
54963
+ if (fs91.existsSync(executableFile)) return;
54723
54964
  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";
54724
54965
  const executableMissing = `'${executableFile}' does not exist
54725
54966
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
@@ -54738,10 +54979,10 @@ Expecting one of '${allowedValues.join("', '")}'`);
54738
54979
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
54739
54980
  function findFile(baseDir, baseName) {
54740
54981
  const localBin = path88.resolve(baseDir, baseName);
54741
- if (fs90.existsSync(localBin)) return localBin;
54982
+ if (fs91.existsSync(localBin)) return localBin;
54742
54983
  if (sourceExt.includes(path88.extname(baseName))) return void 0;
54743
54984
  const foundExt = sourceExt.find(
54744
- (ext) => fs90.existsSync(`${localBin}${ext}`)
54985
+ (ext) => fs91.existsSync(`${localBin}${ext}`)
54745
54986
  );
54746
54987
  if (foundExt) return `${localBin}${foundExt}`;
54747
54988
  return void 0;
@@ -54753,7 +54994,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
54753
54994
  if (this._scriptPath) {
54754
54995
  let resolvedScriptPath;
54755
54996
  try {
54756
- resolvedScriptPath = fs90.realpathSync(this._scriptPath);
54997
+ resolvedScriptPath = fs91.realpathSync(this._scriptPath);
54757
54998
  } catch {
54758
54999
  resolvedScriptPath = this._scriptPath;
54759
55000
  }
@@ -56089,7 +56330,7 @@ var init_shared2 = __esm({
56089
56330
  });
56090
56331
 
56091
56332
  // ../cli/src/lib/agents/shared-memory.ts
56092
- import fs63 from "node:fs";
56333
+ import fs64 from "node:fs";
56093
56334
  import path66 from "node:path";
56094
56335
  function sharedMemory(board2) {
56095
56336
  const declared = /* @__PURE__ */ new Map();
@@ -56098,7 +56339,7 @@ function sharedMemory(board2) {
56098
56339
  const read5 = parseSpecAgent(text5, folder2, (relative) => {
56099
56340
  if (builtIn) return shippedAgentFiles()[`${folder2}/${relative}`] ?? null;
56100
56341
  try {
56101
- return fs63.readFileSync(path66.join(board2, "agents", folder2, relative), "utf8");
56342
+ return fs64.readFileSync(path66.join(board2, "agents", folder2, relative), "utf8");
56102
56343
  } catch {
56103
56344
  return null;
56104
56345
  }
@@ -56112,13 +56353,13 @@ function sharedMemory(board2) {
56112
56353
  const root2 = path66.join(board2, "agents");
56113
56354
  let folders2 = [];
56114
56355
  try {
56115
- folders2 = fs63.readdirSync(root2, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
56356
+ folders2 = fs64.readdirSync(root2, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
56116
56357
  } catch {
56117
56358
  }
56118
56359
  for (const folder2 of folders2.sort()) {
56119
56360
  let text5 = null;
56120
56361
  try {
56121
- text5 = fs63.readFileSync(path66.join(root2, folder2, "AGENT.md"), "utf8");
56362
+ text5 = fs64.readFileSync(path66.join(root2, folder2, "AGENT.md"), "utf8");
56122
56363
  } catch {
56123
56364
  }
56124
56365
  take(folder2, text5, false);
@@ -56144,30 +56385,30 @@ var init_shared_memory = __esm({
56144
56385
 
56145
56386
  // ../cli/src/lib/shared/board-conflicts.ts
56146
56387
  import crypto4 from "node:crypto";
56147
- import fs64 from "node:fs";
56388
+ import fs65 from "node:fs";
56148
56389
  import path67 from "node:path";
56149
56390
  function atomicJson(file2, data) {
56150
- fs64.mkdirSync(path67.dirname(file2), { recursive: true });
56391
+ fs65.mkdirSync(path67.dirname(file2), { recursive: true });
56151
56392
  const temp = `${file2}.${crypto4.randomUUID()}.tmp`;
56152
- const fd = fs64.openSync(temp, "wx", 384);
56393
+ const fd = fs65.openSync(temp, "wx", 384);
56153
56394
  try {
56154
- fs64.writeFileSync(fd, JSON.stringify(data));
56155
- fs64.fsyncSync(fd);
56395
+ fs65.writeFileSync(fd, JSON.stringify(data));
56396
+ fs65.fsyncSync(fd);
56156
56397
  } finally {
56157
- fs64.closeSync(fd);
56398
+ fs65.closeSync(fd);
56158
56399
  }
56159
- fs64.renameSync(temp, file2);
56400
+ fs65.renameSync(temp, file2);
56160
56401
  }
56161
56402
  function boardTextAt(board2, name) {
56162
56403
  if (!isBoardPath(name)) throw new BoardError(`Invalid board path: ${name}`, { kind: "invalid-usage" });
56163
56404
  const file2 = path67.join(board2, name);
56164
56405
  let ancestor = file2;
56165
- while (!fs64.existsSync(ancestor) && path67.dirname(ancestor) !== ancestor) ancestor = path67.dirname(ancestor);
56166
- const real2 = path67.resolve(fs64.realpathSync(ancestor), path67.relative(ancestor, file2));
56167
- if (!real2.startsWith(fs64.realpathSync(board2) + path67.sep)) throw new BoardError(`Link outside the board: ${name}`, { kind: "invalid-usage" });
56168
- if ((fs64.statSync(file2, { throwIfNoEntry: false })?.size ?? 0) > BOARD_FILE_LIMIT) throw new BoardError(`${name} exceeds the board file limit.`, { kind: "cloud-refused" });
56406
+ while (!fs65.existsSync(ancestor) && path67.dirname(ancestor) !== ancestor) ancestor = path67.dirname(ancestor);
56407
+ const real2 = path67.resolve(fs65.realpathSync(ancestor), path67.relative(ancestor, file2));
56408
+ if (!real2.startsWith(fs65.realpathSync(board2) + path67.sep)) throw new BoardError(`Link outside the board: ${name}`, { kind: "invalid-usage" });
56409
+ if ((fs65.statSync(file2, { throwIfNoEntry: false })?.size ?? 0) > BOARD_FILE_LIMIT) throw new BoardError(`${name} exceeds the board file limit.`, { kind: "cloud-refused" });
56169
56410
  try {
56170
- return fs64.readFileSync(file2, "utf8");
56411
+ return fs65.readFileSync(file2, "utf8");
56171
56412
  } catch (e) {
56172
56413
  if (e.code === "ENOENT") return null;
56173
56414
  throw e;
@@ -56178,9 +56419,9 @@ function save2(board2, record2) {
56178
56419
  }
56179
56420
  function read2(board2, id2) {
56180
56421
  const file2 = fileOf(board2, id2);
56181
- if (!fs64.existsSync(file2)) throw new BoardError("Unknown board conflict.", { kind: "conflict-not-found", id: id2 });
56422
+ if (!fs65.existsSync(file2)) throw new BoardError("Unknown board conflict.", { kind: "conflict-not-found", id: id2 });
56182
56423
  try {
56183
- const r = JSON.parse(fs64.readFileSync(file2, "utf8"));
56424
+ const r = JSON.parse(fs65.readFileSync(file2, "utf8"));
56184
56425
  if (r.id !== id2 || !r.project || !["open", "unconfirmed", "resolved"].includes(r.state) || !Array.isArray(r.files) || !r.files.length) throw Error();
56185
56426
  const names2 = /* @__PURE__ */ new Set();
56186
56427
  for (const f of r.files) {
@@ -56202,7 +56443,7 @@ function read2(board2, id2) {
56202
56443
  function conflictRecords(board2) {
56203
56444
  let names2;
56204
56445
  try {
56205
- names2 = fs64.readdirSync(folder(board2));
56446
+ names2 = fs65.readdirSync(folder(board2));
56206
56447
  } catch (e) {
56207
56448
  if (e.code === "ENOENT") return [];
56208
56449
  throw e;
@@ -56291,7 +56532,7 @@ function confirmLocal(board2, r) {
56291
56532
  const draft = r.draft;
56292
56533
  const root2 = stateRootOf(board2);
56293
56534
  const file2 = path67.join(root2, ".akb", "base.json");
56294
- const base = JSON.parse(fs64.readFileSync(file2, "utf8"));
56535
+ const base = JSON.parse(fs65.readFileSync(file2, "utf8"));
56295
56536
  if (base.project && base.project !== r.project) refuse(r, "The project binding changed.", "cloud-refused");
56296
56537
  base.deleted ??= {};
56297
56538
  for (const [i, f] of r.files.entries()) {
@@ -56308,10 +56549,10 @@ function confirmLocal(board2, r) {
56308
56549
  }
56309
56550
  if (boardTextAt(board2, f.path) !== draft.working[i]) continue;
56310
56551
  const local = path67.join(board2, f.path);
56311
- if (sent.content === null) fs64.rmSync(local, { force: true });
56552
+ if (sent.content === null) fs65.rmSync(local, { force: true });
56312
56553
  else {
56313
- fs64.mkdirSync(path67.dirname(local), { recursive: true });
56314
- fs64.writeFileSync(local, sent.content);
56554
+ fs65.mkdirSync(path67.dirname(local), { recursive: true });
56555
+ fs65.writeFileSync(local, sent.content);
56315
56556
  }
56316
56557
  }
56317
56558
  atomicJson(file2, base);
@@ -56470,13 +56711,26 @@ var init_board_conflicts2 = __esm({
56470
56711
  }
56471
56712
  });
56472
56713
 
56714
+ // ../cli/src/lib/cli/question-options.ts
56715
+ function withQuestionOptions(command, ops) {
56716
+ const inOrder = ordered(ops);
56717
+ return command.option("--append <text>", "append a new question", inOrder("append")).option("--update <n> <text...>", "rewrite question <n>", inOrder("update")).option("--drop <positions>", "remove questions, e.g. 1 or 1,3", inOrder("drop")).option("--clear", "remove every open question", inOrder("clear")).option("--option <text>", "a choice for the preceding append or update", inOrder("option")).option("--recommended-option <text>", "a choice selected by default", inOrder("recommended-option")).option("--mode <mode>", "single (default) or multi", inOrder("mode")).addOption(new Option("--agent <name>").hideHelp().argParser(inOrder("agent")));
56718
+ }
56719
+ var init_question_options = __esm({
56720
+ "../cli/src/lib/cli/question-options.ts"() {
56721
+ "use strict";
56722
+ init_esm();
56723
+ init_shared2();
56724
+ }
56725
+ });
56726
+
56473
56727
  // ../cli/src/lib/cli/board.ts
56474
56728
  var board_exports = {};
56475
56729
  __export(board_exports, {
56476
56730
  buildBoardProgram: () => buildBoardProgram
56477
56731
  });
56478
56732
  import crypto5 from "node:crypto";
56479
- import fs65 from "node:fs";
56733
+ import fs66 from "node:fs";
56480
56734
  import path68 from "node:path";
56481
56735
  async function dispatch(move, cmd, args2, opts, cli) {
56482
56736
  const ctx = ctxOf(cmd, cli.program);
@@ -56497,7 +56751,7 @@ async function dispatch(move, cmd, args2, opts, cli) {
56497
56751
  }
56498
56752
  let resolution;
56499
56753
  try {
56500
- resolution = JSON.parse(fs65.readFileSync(String(opts.file), "utf8"));
56754
+ resolution = JSON.parse(fs66.readFileSync(String(opts.file), "utf8"));
56501
56755
  } catch {
56502
56756
  throw new BoardError("Cannot read the UTF-8 JSON resolution file.", { kind: "invalid-usage" });
56503
56757
  }
@@ -56538,7 +56792,7 @@ async function cloudCard(task, opts) {
56538
56792
  let request2;
56539
56793
  if (typeof opts.bodyFile === "string") {
56540
56794
  try {
56541
- request2 = fs65.readFileSync(opts.bodyFile, "utf8");
56795
+ request2 = fs66.readFileSync(opts.bodyFile, "utf8");
56542
56796
  } catch {
56543
56797
  }
56544
56798
  }
@@ -56619,10 +56873,7 @@ function buildBoardProgram(cli) {
56619
56873
  await dispatch("update", this, [String(id2)], this.opts(), cli);
56620
56874
  });
56621
56875
  const questionOps = [];
56622
- const opInOrder = ordered(questionOps);
56623
- move("update-questions").argument("<id>", ID, cardId).summary("patch a card's open questions: append, rewrite, drop, skip, or clear").description(
56624
- "Patch the open-question list in place. Ops apply in the order they were typed, and a position is read against the list as it stands when its op runs. Positions are 1-based. A question handed to the user always carries choices to tick \u2014 follow `akb guide update-questions`. --option, --recommended-option and --mode attach to the --append or --update before them."
56625
- ).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")).addOption(new Option("--agent <name>").hideHelp().argParser(opInOrder("agent"))).action(async function(id2) {
56876
+ withQuestionOptions(withShared(program2.command("update-questions", { hidden: true })).argument("<id>", ID, cardId).summary("edit open questions on a local card (compatibility)").description("For older Runner instructions. Use akb task update-questions.\nSee akb guide update-questions."), questionOps).action(async function(id2) {
56626
56877
  await dispatch("update-questions", this, [String(id2)], { ops: questionOps }, cli);
56627
56878
  });
56628
56879
  move("inspect").argument("<id>", ID, cardId).summary("read task facts, saved work and execution references").action(async function(id2) {
@@ -56700,12 +56951,13 @@ var init_board2 = __esm({
56700
56951
  init_agent2();
56701
56952
  init_board_conflicts();
56702
56953
  init_board_conflicts2();
56954
+ init_question_options();
56703
56955
  ID = "the card's id";
56704
56956
  }
56705
56957
  });
56706
56958
 
56707
56959
  // ../cli/src/lib/board-cli.ts
56708
- import fs66 from "node:fs";
56960
+ import fs67 from "node:fs";
56709
56961
  import path69 from "node:path";
56710
56962
  function useBoard(found2, dirNamed, readOnly = false) {
56711
56963
  if (!found2.named && found2.board === path69.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
@@ -56717,7 +56969,7 @@ function useBoard(found2, dirNamed, readOnly = false) {
56717
56969
  }
56718
56970
  function whole(found2, move) {
56719
56971
  if (move === MAKES_A_BOARD) return found2;
56720
- if (!fs66.existsSync(path69.join(found2.board, "todo"))) {
56972
+ if (!fs67.existsSync(path69.join(found2.board, "todo"))) {
56721
56973
  die(`the board in ${found2.board} has no todo/ \u2014 run \`init\` to add what is missing.`, {
56722
56974
  kind: "board-incomplete",
56723
56975
  dir: found2.root
@@ -56731,7 +56983,7 @@ function findBoardUpward(from, move) {
56731
56983
  if (hasBoard(dir)) return { root: dir, board: path69.join(dir, "docs", "kanban") };
56732
56984
  if (isBoardDir(dir)) return { root: projectRootOf(dir), board: dir };
56733
56985
  const kept2 = path69.join(dir, ".akb", "kanban");
56734
- if (move !== MAKES_A_BOARD && fs66.existsSync(path69.join(kept2, "todo"))) return { root: dir, board: kept2 };
56986
+ if (move !== MAKES_A_BOARD && fs67.existsSync(path69.join(kept2, "todo"))) return { root: dir, board: kept2 };
56735
56987
  const up = path69.dirname(dir);
56736
56988
  if (up === dir) return null;
56737
56989
  dir = up;
@@ -56741,10 +56993,10 @@ function resolveBoard(move, { board: board2, dir, cwd, installHint }) {
56741
56993
  const named2 = board2 ?? boardFromEnv();
56742
56994
  if (named2) {
56743
56995
  const folder2 = path69.resolve(cwd, named2);
56744
- if (!fs66.existsSync(folder2) && move !== MAKES_A_BOARD) {
56996
+ if (!fs67.existsSync(folder2) && move !== MAKES_A_BOARD) {
56745
56997
  die(`no such folder: ${folder2}`, { kind: "no-such-folder", dir: folder2 });
56746
56998
  }
56747
- if (fs66.existsSync(folder2) && !isBoardDir(folder2) && move !== MAKES_A_BOARD) {
56999
+ if (fs67.existsSync(folder2) && !isBoardDir(folder2) && move !== MAKES_A_BOARD) {
56748
57000
  die(`${folder2} is not a board \u2014 it has no todo/ and config.md. ${installHint}\u3002`, {
56749
57001
  kind: "no-board",
56750
57002
  dir: folder2
@@ -56754,9 +57006,9 @@ function resolveBoard(move, { board: board2, dir, cwd, installHint }) {
56754
57006
  }
56755
57007
  if (dir !== null) {
56756
57008
  const root2 = path69.resolve(dir);
56757
- if (!fs66.existsSync(root2)) die(`no such folder: ${root2}`, { kind: "no-such-folder", dir: root2 });
57009
+ if (!fs67.existsSync(root2)) die(`no such folder: ${root2}`, { kind: "no-such-folder", dir: root2 });
56758
57010
  const kept2 = path69.join(root2, ".akb", "kanban");
56759
- if (!hasBoard(root2) && move !== MAKES_A_BOARD && fs66.existsSync(path69.join(kept2, "todo"))) return whole({ root: root2, board: kept2 }, move);
57011
+ if (!hasBoard(root2) && move !== MAKES_A_BOARD && fs67.existsSync(path69.join(kept2, "todo"))) return whole({ root: root2, board: kept2 }, move);
56760
57012
  if (!hasBoard(root2) && move !== MAKES_A_BOARD) {
56761
57013
  die(`no board in ${root2} \u2014 it has no docs/kanban/. ${installHint}\u3002`, {
56762
57014
  kind: "no-board",
@@ -56847,8 +57099,8 @@ var init_board_cli = __esm({
56847
57099
  init_io();
56848
57100
  init_card_studio_backfill();
56849
57101
  MAKES_A_BOARD = "init";
56850
- hasBoard = (dir) => fs66.existsSync(path69.join(dir, "docs", "kanban"));
56851
- isBoardDir = (dir) => fs66.existsSync(path69.join(dir, "todo")) && fs66.existsSync(path69.join(dir, "config.md"));
57102
+ hasBoard = (dir) => fs67.existsSync(path69.join(dir, "docs", "kanban"));
57103
+ isBoardDir = (dir) => fs67.existsSync(path69.join(dir, "todo")) && fs67.existsSync(path69.join(dir, "config.md"));
56852
57104
  boardFromEnv = () => {
56853
57105
  const named2 = process.env.AI4KANBAN_BOARD?.trim();
56854
57106
  return named2 ? named2 : null;
@@ -56857,11 +57109,11 @@ var init_board_cli = __esm({
56857
57109
  });
56858
57110
 
56859
57111
  // ../cli/src/lib/cloud/task-operation.ts
56860
- import fs67 from "node:fs";
57112
+ import fs68 from "node:fs";
56861
57113
  import path70 from "node:path";
56862
57114
  function readRemoval(board2, task) {
56863
57115
  try {
56864
- const value = JSON.parse(fs67.readFileSync(removalFile(board2, task), "utf8"));
57116
+ const value = JSON.parse(fs68.readFileSync(removalFile(board2, task), "utf8"));
56865
57117
  if (["pending", "confirmed", "rejected"].includes(value.status) && typeof value.reason === "string" && typeof value.discard === "boolean") return value;
56866
57118
  } catch {
56867
57119
  }
@@ -56870,8 +57122,8 @@ function readRemoval(board2, task) {
56870
57122
  function writeRemoval(board2, task, removal) {
56871
57123
  const file2 = removalFile(board2, task);
56872
57124
  const temp = `${file2}.${process.pid}.tmp`;
56873
- fs67.writeFileSync(temp, JSON.stringify(removal) + "\n");
56874
- fs67.renameSync(temp, file2);
57125
+ fs68.writeFileSync(temp, JSON.stringify(removal) + "\n");
57126
+ fs68.renameSync(temp, file2);
56875
57127
  }
56876
57128
  var removalFile;
56877
57129
  var init_task_operation = __esm({
@@ -56927,10 +57179,10 @@ var init_avatar = __esm({
56927
57179
  });
56928
57180
 
56929
57181
  // ../cli/src/lib/cloud/pro.ts
56930
- import fs68 from "node:fs";
57182
+ import fs69 from "node:fs";
56931
57183
  import path71 from "node:path";
56932
57184
  function forgetPro() {
56933
- fs68.rmSync(heldFile(), { force: true });
57185
+ fs69.rmSync(heldFile(), { force: true });
56934
57186
  }
56935
57187
  var FRESH_MS2, GRACE_MS, heldFile;
56936
57188
  var init_pro = __esm({
@@ -57036,7 +57288,7 @@ var init_account = __esm({
57036
57288
  });
57037
57289
 
57038
57290
  // ../cli/src/commands/cloud.ts
57039
- import fs69 from "node:fs";
57291
+ import fs70 from "node:fs";
57040
57292
  import path72 from "node:path";
57041
57293
  async function cmdCloud(args2, program2) {
57042
57294
  const [sub] = args2;
@@ -57112,7 +57364,7 @@ async function cloudImage(opts, program2) {
57112
57364
  const type = REF_TYPES[path72.extname(file2).toLowerCase()];
57113
57365
  if (!type) usage(`--ref ${file2}: use a PNG, JPEG or WebP file.`, line);
57114
57366
  try {
57115
- return `data:${type};base64,${fs69.readFileSync(file2).toString("base64")}`;
57367
+ return `data:${type};base64,${fs70.readFileSync(file2).toString("base64")}`;
57116
57368
  } catch (e) {
57117
57369
  usage(`--ref ${file2}: ${e instanceof Error ? e.message : String(e)}`, line);
57118
57370
  }
@@ -57236,8 +57488,8 @@ usage: ${g.usage}` }, { bare: true, exitCode: 2 });
57236
57488
  refuse2(g.failed, g.fallback, { code: error62.kind, message: error62.message, retryable: true });
57237
57489
  }
57238
57490
  const out = g.outFor?.(res, g.out) ?? g.out;
57239
- fs69.mkdirSync(path72.dirname(path72.resolve(out)), { recursive: true });
57240
- fs69.writeFileSync(out, bytes2);
57491
+ fs70.mkdirSync(path72.dirname(path72.resolve(out)), { recursive: true });
57492
+ fs70.writeFileSync(out, bytes2);
57241
57493
  say(`${out} (${g.label(res)})`);
57242
57494
  return { out };
57243
57495
  }
@@ -57299,7 +57551,7 @@ var init_cloud = __esm({
57299
57551
  });
57300
57552
 
57301
57553
  // ../cli/src/commands/task.ts
57302
- import fs70 from "node:fs";
57554
+ import fs71 from "node:fs";
57303
57555
  import os5 from "node:os";
57304
57556
  import path73 from "node:path";
57305
57557
  async function cloud(method, route2, body, signal2) {
@@ -57358,7 +57610,7 @@ function linked(location) {
57358
57610
  return link2.ok ? link2.value : null;
57359
57611
  }
57360
57612
  for (let dir = path73.resolve(cwd, location.dir ?? "."); ; dir = path73.dirname(dir)) {
57361
- if (fs70.existsSync(path73.join(dir, ".akb", "base.json"))) {
57613
+ if (fs71.existsSync(path73.join(dir, ".akb", "base.json"))) {
57362
57614
  const link2 = linkedProject("", dir);
57363
57615
  return link2.ok ? link2.value : null;
57364
57616
  }
@@ -57465,7 +57717,7 @@ async function taskReview(id2, opts = {}, location = {}) {
57465
57717
  if (opts.review !== void 0) {
57466
57718
  fields2 = { operation: "plan", review_flow: opts.review };
57467
57719
  } else if (opts.file !== void 0) {
57468
- fields2 = { operation: "plan", review_plan: parseReviewPlan(JSON.parse(fs70.readFileSync(opts.file, "utf8"))) };
57720
+ fields2 = { operation: "plan", review_plan: parseReviewPlan(JSON.parse(fs71.readFileSync(opts.file, "utf8"))) };
57469
57721
  } else if (opts.reviseFrom !== void 0) {
57470
57722
  fields2 = { operation: "revise", stage: opts.reviseFrom };
57471
57723
  } else if (opts.previewDefinitionsFile !== void 0) {
@@ -57474,7 +57726,7 @@ async function taskReview(id2, opts = {}, location = {}) {
57474
57726
  if (!opts.stage || !["running", "done"].includes(opts.status)) die("--stage and --status running|done are required.");
57475
57727
  fields2 = { operation: "status", stage: opts.stage, status: opts.status };
57476
57728
  }
57477
- if (opts.previewDefinitionsFile !== void 0) fields2.preview_definitions = previewDefinitionsSchema.parse(JSON.parse(fs70.readFileSync(opts.previewDefinitionsFile, "utf8")));
57729
+ if (opts.previewDefinitionsFile !== void 0) fields2.preview_definitions = previewDefinitionsSchema.parse(JSON.parse(fs71.readFileSync(opts.previewDefinitionsFile, "utf8")));
57478
57730
  task = await cloud("POST", `/v1/tasks/${enc(ref)}/review`, { ...fields2, review_revision });
57479
57731
  }
57480
57732
  say(JSON.stringify(task.review, null, 2));
@@ -57498,13 +57750,43 @@ async function taskApprove(id2, comment, opts = {}, location = {}) {
57498
57750
  }
57499
57751
  async function taskUpdateQuestions(id2, typed, location = {}) {
57500
57752
  const ops = readQuestionOps(typed);
57753
+ const current = executionOf() ? workspaceTask() : null;
57501
57754
  const ref = await taskRef(id2, location);
57502
- const card = await cloud("GET", `/v1/tasks/${enc(ref)}/card`);
57503
- const questions = parseFrontmatter(card.body).meta?.questions ?? [];
57755
+ const selected = current && !ref.startsWith("task_") ? requireTask(await cloud("GET", `/v1/tasks/${enc(ref)}`)) : null;
57756
+ const target = selected?.id ?? ref;
57757
+ if (current && target === current) {
57758
+ const board2 = runnerTaskBoard(location);
57759
+ const unavailable = () => refuse3("Cannot find the current task\u2019s local card on its Runner board.", "local_card_unavailable");
57760
+ if (!board2) return unavailable();
57761
+ return withSyncLock(board2, async () => {
57762
+ const project2 = runnerProject(board2);
57763
+ const mapped = localTaskRecord(board2, current);
57764
+ if (!mapped || !project2 || selected && (selected.project !== project2 || numberOf(selected.key) !== mapped.number)) {
57765
+ return unavailable();
57766
+ }
57767
+ const root2 = projectRootOf(board2);
57768
+ useBoard({ board: board2, root: root2, named: true }, false, true);
57769
+ return withBoardLock(() => {
57770
+ const run3 = insideRun();
57771
+ const runCard = run3 ? peekRun(run3)?.cardId : null;
57772
+ if (runCard != null && runCard !== mapped.number || !fs71.existsSync(path73.join(board2, "todo")) || !locate(mapped.number)) {
57773
+ return unavailable();
57774
+ }
57775
+ return updateCardQuestions(mapped.number, ops);
57776
+ });
57777
+ });
57778
+ }
57779
+ const card = requireResponse(
57780
+ await cloud("GET", `/v1/tasks/${enc(target)}/card`),
57781
+ "the card body and version",
57782
+ (value) => hasText(value.body) && Number.isSafeInteger(value.version) && value.version >= 0
57783
+ );
57784
+ const meta3 = parseFrontmatter(card.body).meta;
57785
+ if (!meta3) return refuse3("The card has no frontmatter.", "bad_request");
57504
57786
  let changes;
57505
57787
  let open4;
57506
57788
  try {
57507
- const done = applyQuestionOps(questions, ops);
57789
+ const done = applyQuestionOps(meta3.questions, ops);
57508
57790
  changes = done.changes;
57509
57791
  open4 = done.questions.length;
57510
57792
  } catch (e) {
@@ -57516,22 +57798,27 @@ async function taskUpdateQuestions(id2, typed, location = {}) {
57516
57798
  if (op.kind === "append") return { append: q };
57517
57799
  if (op.kind === "update") return { update: op.n, question: q };
57518
57800
  if (op.kind === "drop") return { drop: questionPositions(op.ns, Infinity, "drop") };
57519
- if (op.kind === "clear") return { clear: true };
57520
- return die(`akb task update-questions has no --${op.kind}; --drop removes a question`);
57801
+ return { clear: true };
57521
57802
  });
57522
- const task = await cloud("PATCH", `/v1/tasks/${enc(ref)}/questions`, { base_version: card.version, ops: body });
57803
+ const task = await cloud("PATCH", `/v1/tasks/${enc(target)}/questions`, { base_version: card.version, ops: body });
57523
57804
  say(`updated ${task.key} questions: ${changes.join(", ")} (${open4} open)`);
57524
57805
  return { ...task, changes, open: open4 };
57525
57806
  }
57526
- function localTaskTarget(location) {
57527
- const task = workspaceTask();
57807
+ function runnerTaskBoard(location) {
57528
57808
  const runnerBoard = process.env.AI4KANBAN_BOARD?.trim();
57529
- if (!task || !/^task_[\w-]+$/.test(task) || !runnerBoard || !executionOf()) return null;
57809
+ if (!runnerBoard) return null;
57530
57810
  const cwd = location.cwd ?? process.cwd();
57531
- const board2 = path73.resolve(cwd, location.board ?? runnerBoard);
57532
57811
  try {
57533
- if (fs70.realpathSync(board2) !== fs70.realpathSync(path73.resolve(cwd, runnerBoard)) || !runnerProject(board2)) return null;
57534
- const record2 = JSON.parse(fs70.readFileSync(path73.join(board2, ".sync", task + ".json"), "utf8"));
57812
+ const board2 = path73.resolve(cwd, location.board ?? runnerBoard);
57813
+ return fs71.realpathSync(board2) === fs71.realpathSync(path73.resolve(cwd, runnerBoard)) && runnerProject(board2) ? board2 : null;
57814
+ } catch {
57815
+ return null;
57816
+ }
57817
+ }
57818
+ function localTaskRecord(board2, task) {
57819
+ if (!/^task_[\w-]+$/.test(task)) return null;
57820
+ try {
57821
+ const record2 = JSON.parse(fs71.readFileSync(path73.join(board2, ".sync", task + ".json"), "utf8"));
57535
57822
  if (record2.task === task && Number.isSafeInteger(record2.number) && record2.number > 0 && !record2.deleted) {
57536
57823
  return { board: board2, task, number: record2.number };
57537
57824
  }
@@ -57539,6 +57826,12 @@ function localTaskTarget(location) {
57539
57826
  }
57540
57827
  return null;
57541
57828
  }
57829
+ function localTaskTarget(location) {
57830
+ const task = workspaceTask();
57831
+ if (!task || !executionOf()) return null;
57832
+ const board2 = runnerTaskBoard(location);
57833
+ return board2 ? localTaskRecord(board2, task) : null;
57834
+ }
57542
57835
  function linkedBoard(location) {
57543
57836
  const cwd = location.cwd ?? process.cwd();
57544
57837
  const named2 = location.board ?? process.env.AI4KANBAN_BOARD;
@@ -57558,7 +57851,7 @@ function operationStatus(result) {
57558
57851
  }
57559
57852
  function archiveReceipt(board2, task, file2) {
57560
57853
  try {
57561
- const base = JSON.parse(fs70.readFileSync(path73.join(board2, "..", "base.json"), "utf8"));
57854
+ const base = JSON.parse(fs71.readFileSync(path73.join(board2, "..", "base.json"), "utf8"));
57562
57855
  const receipt = base.archiveReceipts?.[task];
57563
57856
  const root2 = `projects/${runnerProject(board2)}/`;
57564
57857
  const synced = receipt && base.files?.[root2 + receipt.path];
@@ -57567,7 +57860,7 @@ function archiveReceipt(board2, task, file2) {
57567
57860
  if (synced && (!file2 || receipt.path === file2) && synced.seq === receipt.seq && (assets?.seq ?? 0) === receipt.assets_seq) {
57568
57861
  const local = (name) => {
57569
57862
  try {
57570
- return fs70.readFileSync(path73.join(board2, name), "utf8");
57863
+ return fs71.readFileSync(path73.join(board2, name), "utf8");
57571
57864
  } catch {
57572
57865
  return null;
57573
57866
  }
@@ -57592,7 +57885,7 @@ async function taskArchive(asked, location = {}) {
57592
57885
  const existing = locateArchived(local.number);
57593
57886
  if (!existing) return null;
57594
57887
  const file2 = existing.kind === "group" ? path73.join(existing.target, "root.md") : existing.target;
57595
- const { meta: meta3 } = parseFrontmatter(fs70.readFileSync(file2, "utf8"));
57888
+ const { meta: meta3 } = parseFrontmatter(fs71.readFileSync(file2, "utf8"));
57596
57889
  if (!meta3?.archived || meta3.rejected) return refuse3("This task is not eligible for archive.", "conflict");
57597
57890
  return {
57598
57891
  receipt: { archived_to: path73.relative(local.board, existing.target) },
@@ -57735,6 +58028,7 @@ var init_task = __esm({
57735
58028
  init_board_files();
57736
58029
  init_board_conflicts();
57737
58030
  init_remove();
58031
+ init_card();
57738
58032
  init_io();
57739
58033
  init_response();
57740
58034
  init_paths();
@@ -57793,20 +58087,20 @@ var init_goal = __esm({
57793
58087
  });
57794
58088
 
57795
58089
  // ../cli/src/lib/goal-draft.ts
57796
- import fs71 from "node:fs";
58090
+ import fs72 from "node:fs";
57797
58091
  import { randomUUID as randomUUID7 } from "node:crypto";
57798
58092
  function readGoalDraft(file2) {
57799
- return decodeGoals(JSON.parse(fs71.readFileSync(file2, "utf8")));
58093
+ return decodeGoals(JSON.parse(fs72.readFileSync(file2, "utf8")));
57800
58094
  }
57801
58095
  function writeGoalDraft(file2, { goals, ...draft }, field2) {
57802
58096
  const entries2 = field2 === "goals" ? goals : goals.map(({ task, ...goal }) => ({ ...goal, task: task?.key ? task : task?.id ?? null }));
57803
58097
  const temporary = `${file2}.${randomUUID7()}.tmp`;
57804
58098
  try {
57805
- fs71.writeFileSync(temporary, `${JSON.stringify({ ...draft, [field2]: entries2 }, null, 2)}
58099
+ fs72.writeFileSync(temporary, `${JSON.stringify({ ...draft, [field2]: entries2 }, null, 2)}
57806
58100
  `, { mode: 384, flag: "wx" });
57807
- fs71.renameSync(temporary, file2);
58101
+ fs72.renameSync(temporary, file2);
57808
58102
  } finally {
57809
- fs71.rmSync(temporary, { force: true });
58103
+ fs72.rmSync(temporary, { force: true });
57810
58104
  }
57811
58105
  }
57812
58106
  var goalDraftPath;
@@ -57819,7 +58113,7 @@ var init_goal_draft = __esm({
57819
58113
  });
57820
58114
 
57821
58115
  // ../cli/src/commands/goal.ts
57822
- import fs72 from "node:fs";
58116
+ import fs73 from "node:fs";
57823
58117
  function loadGoals() {
57824
58118
  const file2 = goalDraftPath();
57825
58119
  if (!file2) die("Goals exist only inside a WildCrane goal discussion.");
@@ -57851,7 +58145,7 @@ function splitBody2(text5) {
57851
58145
  }
57852
58146
  function readBody(bodyFile) {
57853
58147
  if (!bodyFile) die("--body-file is required; write the goal in a writable temporary file first.");
57854
- const text5 = fs72.readFileSync(bodyFile, "utf8");
58148
+ const text5 = fs73.readFileSync(bodyFile, "utf8");
57855
58149
  if (!text5.trim()) die("The goal must not be empty.");
57856
58150
  return splitBody2(text5);
57857
58151
  }
@@ -57917,7 +58211,7 @@ function cmdGoalStudios(held4 = loadGoals().held) {
57917
58211
  return { studios: held4.studios.map((w) => ({ ...w, id: shortStudioId(w.id) })) };
57918
58212
  }
57919
58213
  function goalDefinitions(opts, previous = []) {
57920
- return opts.previewDefinitionsFile === void 0 ? previous : previewDefinitionsSchema.parse(JSON.parse(fs72.readFileSync(opts.previewDefinitionsFile, "utf8")));
58214
+ return opts.previewDefinitionsFile === void 0 ? previous : previewDefinitionsSchema.parse(JSON.parse(fs73.readFileSync(opts.previewDefinitionsFile, "utf8")));
57921
58215
  }
57922
58216
  function goalCatalog(held4, studio, definitions) {
57923
58217
  const builtIn = held4.studios.find((w) => w.id === studio)?.previews;
@@ -57930,7 +58224,7 @@ function goalReview(held4, studio, opts, previous, definitions) {
57930
58224
  if (opts.reviewFile !== void 0) die("Use either --review or --review-file.");
57931
58225
  return parseReviewFlow(opts.review, catalog);
57932
58226
  }
57933
- const value = opts.reviewFile === void 0 ? readReviewPlan(previous) : JSON.parse(fs72.readFileSync(opts.reviewFile, "utf8"));
58227
+ const value = opts.reviewFile === void 0 ? readReviewPlan(previous) : JSON.parse(fs73.readFileSync(opts.reviewFile, "utf8"));
57934
58228
  const saved = opts.reviewFile === void 0 && opts.previewDefinitionsFile === void 0 && opts.studio === void 0;
57935
58229
  return validateReviewPreviews(parseReviewPlan(value), catalog, { saved });
57936
58230
  }
@@ -57960,7 +58254,7 @@ var init_goal2 = __esm({
57960
58254
  });
57961
58255
 
57962
58256
  // ../cli/src/commands/goal-cloud.ts
57963
- import fs73 from "node:fs";
58257
+ import fs74 from "node:fs";
57964
58258
  import os6 from "node:os";
57965
58259
  import path74 from "node:path";
57966
58260
  import crypto6 from "node:crypto";
@@ -57994,17 +58288,17 @@ async function discussion() {
57994
58288
  const machineFile2 = path74.join(home3, "machine.json");
57995
58289
  let machine;
57996
58290
  try {
57997
- machine = JSON.parse(fs73.readFileSync(machineFile2, "utf8")).id;
58291
+ machine = JSON.parse(fs74.readFileSync(machineFile2, "utf8")).id;
57998
58292
  } catch {
57999
58293
  machine = crypto6.randomUUID();
58000
- fs73.mkdirSync(home3, { recursive: true });
58001
- fs73.writeFileSync(machineFile2, JSON.stringify({ id: machine }));
58294
+ fs74.mkdirSync(home3, { recursive: true });
58295
+ fs74.writeFileSync(machineFile2, JSON.stringify({ id: machine }));
58002
58296
  }
58003
58297
  const held4 = await request("GET", `/v1/runner/folders?machine=${encodeURIComponent(machine)}`);
58004
- const cwd = fs73.realpathSync(process.cwd());
58298
+ const cwd = fs74.realpathSync(process.cwd());
58005
58299
  const folder2 = held4.folders.filter((f) => {
58006
58300
  try {
58007
- const dir = fs73.realpathSync(f.path);
58301
+ const dir = fs74.realpathSync(f.path);
58008
58302
  return cwd === dir || cwd.startsWith(dir + path74.sep);
58009
58303
  } catch {
58010
58304
  return false;
@@ -58318,7 +58612,7 @@ var init_agent = __esm({
58318
58612
 
58319
58613
  // ../cli/src/commands/cloud-template.ts
58320
58614
  import { createHash as createHash5 } from "node:crypto";
58321
- import fs74 from "node:fs";
58615
+ import fs75 from "node:fs";
58322
58616
  import path75 from "node:path";
58323
58617
  function usage2(problem, line) {
58324
58618
  die(`${problem}
@@ -58383,9 +58677,9 @@ async function downloadEntries(name, kind, files, to, fallback) {
58383
58677
  if (file2.sha256 && createHash5("sha256").update(bytes2).digest("hex") !== file2.sha256) refuse4(T.corrupt, fallback, invalidResponse(expected));
58384
58678
  fetched.push({ out, bytes: bytes2 });
58385
58679
  }
58386
- if (fetched.length) fs74.mkdirSync(to, { recursive: true });
58680
+ if (fetched.length) fs75.mkdirSync(to, { recursive: true });
58387
58681
  return fetched.map(({ out, bytes: bytes2 }) => {
58388
- fs74.writeFileSync(out, bytes2);
58682
+ fs75.writeFileSync(out, bytes2);
58389
58683
  say(out);
58390
58684
  return out;
58391
58685
  });
@@ -58458,7 +58752,7 @@ async function templateGet(name, opts, program2) {
58458
58752
  }
58459
58753
  fetched.push({ out, bytes: bytes2 });
58460
58754
  }
58461
- const taken = fetched.filter((f) => fs74.existsSync(f.out)).map((f) => path75.relative(to, f.out));
58755
+ const taken = fetched.filter((f) => fs75.existsSync(f.out)).map((f) => path75.relative(to, f.out));
58462
58756
  if (taken.length > 0) {
58463
58757
  refuse4({
58464
58758
  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`,
@@ -58466,8 +58760,8 @@ async function templateGet(name, opts, program2) {
58466
58760
  });
58467
58761
  }
58468
58762
  for (const f of fetched) {
58469
- fs74.mkdirSync(path75.dirname(f.out), { recursive: true });
58470
- fs74.writeFileSync(f.out, f.bytes);
58763
+ fs75.mkdirSync(path75.dirname(f.out), { recursive: true });
58764
+ fs75.writeFileSync(f.out, f.bytes);
58471
58765
  }
58472
58766
  say(`\u5DF2\u53D6\u56DE ${name}\uFF1A${fetched.length} \u4E2A\u6587\u4EF6\uFF0C\u4F4D\u4E8E ${to}
58473
58767
  Fetched ${name}: ${fetched.length} files into ${to}`);
@@ -58489,13 +58783,13 @@ async function templateSource(name, opts) {
58489
58783
  async function templatePublish(dir, opts) {
58490
58784
  const root2 = path75.resolve(dir);
58491
58785
  const manifest = path75.join(root2, "template.md");
58492
- if (!fs74.existsSync(manifest)) invalid2("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
58493
- const meta3 = readTemplateMeta(fs74.readFileSync(manifest, "utf8"));
58786
+ if (!fs75.existsSync(manifest)) invalid2("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
58787
+ const meta3 = readTemplateMeta(fs75.readFileSync(manifest, "utf8"));
58494
58788
  const files = walk2(root2);
58495
- const total = files.reduce((sum, f) => sum + fs74.statSync(path75.join(root2, f)).size, 0);
58789
+ const total = files.reduce((sum, f) => sum + fs75.statSync(path75.join(root2, f)).size, 0);
58496
58790
  if (total > MAX_BYTES2) invalid2("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
58497
58791
  for (const extra of [...opts.preview, ...opts.evidence]) {
58498
- if (!fs74.existsSync(extra)) invalid2(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
58792
+ if (!fs75.existsSync(extra)) invalid2(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
58499
58793
  if (path75.resolve(extra).startsWith(root2 + path75.sep)) {
58500
58794
  invalid2(
58501
58795
  `${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`,
@@ -58508,7 +58802,7 @@ async function templatePublish(dir, opts) {
58508
58802
  }
58509
58803
  const form = new FormData();
58510
58804
  form.set("meta", JSON.stringify({ ...meta3, replace: !!opts.replace }));
58511
- const add2 = (kind, name, file2) => form.append(`${kind}:${name}`, new Blob([fs74.readFileSync(file2)]), path75.basename(name));
58805
+ const add2 = (kind, name, file2) => form.append(`${kind}:${name}`, new Blob([fs75.readFileSync(file2)]), path75.basename(name));
58512
58806
  for (const f of files) add2("files", f, path75.join(root2, f));
58513
58807
  for (const f of opts.preview) add2("previews", path75.basename(f), f);
58514
58808
  for (const f of opts.evidence) add2("evidence", path75.basename(f), f);
@@ -58536,10 +58830,10 @@ Deleted ${name} from the catalog.`);
58536
58830
  }
58537
58831
  async function templateShowcase(name, dir) {
58538
58832
  const file2 = path75.join(dir, "showcase.json");
58539
- if (!fs74.existsSync(file2)) invalid2(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
58833
+ if (!fs75.existsSync(file2)) invalid2(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
58540
58834
  let meta3;
58541
58835
  try {
58542
- meta3 = JSON.parse(fs74.readFileSync(file2, "utf8"));
58836
+ meta3 = JSON.parse(fs75.readFileSync(file2, "utf8"));
58543
58837
  } catch {
58544
58838
  return invalid2("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
58545
58839
  }
@@ -58552,8 +58846,8 @@ async function templateShowcase(name, dir) {
58552
58846
  form.set("meta", JSON.stringify(meta3));
58553
58847
  for (const p of new Set(named2)) {
58554
58848
  const at = path75.join(dir, p);
58555
- if (!fs74.existsSync(at)) invalid2(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
58556
- form.append(`media:${p}`, new Blob([fs74.readFileSync(at)]), p);
58849
+ if (!fs75.existsSync(at)) invalid2(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
58850
+ form.append(`media:${p}`, new Blob([fs75.readFileSync(at)]), p);
58557
58851
  }
58558
58852
  const done = requireResponse(
58559
58853
  await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form })),
@@ -58566,7 +58860,7 @@ Updated ${name}'s showcase: ${done.files} files.`);
58566
58860
  }
58567
58861
  function walk2(root2, sub = "") {
58568
58862
  const out = [];
58569
- for (const entry of fs74.readdirSync(path75.join(root2, sub), { withFileTypes: true })) {
58863
+ for (const entry of fs75.readdirSync(path75.join(root2, sub), { withFileTypes: true })) {
58570
58864
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
58571
58865
  const rel3 = sub ? `${sub}/${entry.name}` : entry.name;
58572
58866
  if (entry.isDirectory()) out.push(...walk2(root2, rel3));
@@ -62783,7 +63077,7 @@ var init_archive2 = __esm({
62783
63077
  var board_default;
62784
63078
  var init_board3 = __esm({
62785
63079
  "../cli/src/guide/board.md"() {
62786
- board_default = "# How this board works\n\nThese rules apply to every card studio. Read them once; each studio's guide covers\nthe remaining details.\n\n## Layout\n\n```\ndocs/kanban/\n\u251C\u2500\u2500 todo/ open tasks\n\u2502 \u251C\u2500\u2500 README.md the index \u2014 read it first\n\u2502 \u2514\u2500\u2500 <id>-<slug>.md\n\u2502 one card per file; a group keeps its cards in one folder\n\u251C\u2500\u2500 rules/ `studios/<studio>.md` \u2014 Studio notes, set with `akb studio rule`\n\u2502 `<agent>.md` \u2014 project background-task instructions, set with\n\u2502 `akb studio instructions`\n\u251C\u2500\u2500 triage/ items waiting to be sorted, one file each \u2014 not cards. Only\n\u2502 \u2502 Cloud's sort or Refine idea on the web's Triage page turns one\n\u2502 \u2502 into a card; `akb raw triage check <source-id>` finds an existing one\n\u2502 \u251C\u2500\u2500 archived/ items a card was made of\n\u2502 \u251C\u2500\u2500 dismissed/ items ignored, with the reason\n\u2502 \u2514\u2500\u2500 files/ dropped-in files\n\u2514\u2500\u2500 modules.md one line per module \u2014 `akb guide module-map` writes it\n```\n\n## Task ID\n\nEvery task's id is the number at the front of its filename (`04-plan-cap-enforcement.md` \u2192\nid 4): its Cloud task's number (`WC-4`). Only Cloud assigns one.\n\n## Never hand-write a card's frontmatter\n\n`akb raw update`, `update-questions` and `akb raw conflict resolve` manage an existing card's frontmatter,\nincluding its `previews`. Edit only the card's **body** by hand. `akb raw help`\nlists all operations; `akb raw help <move>` explains one operation.\n\n## Content conflicts\n\nFor synchronization conflicts, follow `akb guide resolve-conflict`.\n\n## Inside a board run\n\nA board run carries `KANBAN_RUN` in its environment. Never unset or bypass it (for example\n`env -u KANBAN_RUN`): when a command only prints a flow, follow the printed flow.\n\n## Group task\n\nA group lives in `todo/<id>-<slug>/`: `root.md` tracks the whole job and each subtask is its\nown card beside it; `akb guide add-task` says how to build one. The root's `## Todo` lists the\nsubtasks, one line each ending in `#<subid>`: archiving a subtask ticks its line, rejecting\none strikes it through, and resolving the last line archives the root in the same run, with\nany open question or unticked todo of its own. A board a Runner keeps leaves that close to\nCloud, which waits for the root to be queued with no step on it. A root listing no subtasks is\nonly closed by hand.\n\n## Task context\n\nContinue from the task's saved discussion, results and approved requirements. Follow explicit\nproject and Studio rules. Read relevant memory on demand; do not write memory in task runs.\n";
63080
+ board_default = "# How this board works\n\nThese rules apply to every card studio. Read them once; each studio's guide covers\nthe remaining details.\n\n## Layout\n\n```\ndocs/kanban/\n\u251C\u2500\u2500 todo/ open tasks\n\u2502 \u251C\u2500\u2500 README.md the index \u2014 read it first\n\u2502 \u2514\u2500\u2500 <id>-<slug>.md\n\u2502 one card per file; a group keeps its cards in one folder\n\u251C\u2500\u2500 rules/ `studios/<studio>.md` \u2014 Studio notes, set with `akb studio rule`\n\u2502 `<agent>.md` \u2014 project background-task instructions, set with\n\u2502 `akb studio instructions`\n\u251C\u2500\u2500 triage/ items waiting to be sorted, one file each \u2014 not cards. Only\n\u2502 \u2502 Cloud's sort or Refine idea on the web's Triage page turns one\n\u2502 \u2502 into a card; `akb raw triage check <source-id>` finds an existing one\n\u2502 \u251C\u2500\u2500 archived/ items a card was made of\n\u2502 \u251C\u2500\u2500 dismissed/ items ignored, with the reason\n\u2502 \u2514\u2500\u2500 files/ dropped-in files\n\u2514\u2500\u2500 modules.md one line per module \u2014 `akb guide module-map` writes it\n```\n\n## Task ID\n\nEvery task's id is the number at the front of its filename (`04-plan-cap-enforcement.md` \u2192\nid 4): its Cloud task's number (`WC-4`). Only Cloud assigns one.\n\n## Never hand-write a card's frontmatter\n\n`akb raw update`, `akb task update-questions` and `akb raw conflict resolve` manage a card's frontmatter,\nincluding its `previews`. Edit only the card's **body** by hand. `akb raw help`\nlists all operations; `akb raw help <move>` explains one operation.\n\n## Content conflicts\n\nFor synchronization conflicts, follow `akb guide resolve-conflict`.\n\n## Inside a board run\n\nA board run carries `KANBAN_RUN` in its environment. Never unset or bypass it (for example\n`env -u KANBAN_RUN`): when a command only prints a flow, follow the printed flow.\n\n## Group task\n\nA group lives in `todo/<id>-<slug>/`: `root.md` tracks the whole job and each subtask is its\nown card beside it; `akb guide add-task` says how to build one. The root's `## Todo` lists the\nsubtasks, one line each ending in `#<subid>`: archiving a subtask ticks its line, rejecting\none strikes it through, and resolving the last line archives the root in the same run, with\nany open question or unticked todo of its own. A board a Runner keeps leaves that close to\nCloud, which waits for the root to be queued with no step on it. A root listing no subtasks is\nonly closed by hand.\n\n## Task context\n\nContinue from the task's saved discussion, results and approved requirements. Follow explicit\nproject and Studio rules. Read relevant memory on demand; do not write memory in task runs.\n";
62787
63081
  }
62788
63082
  });
62789
63083
 
@@ -62791,7 +63085,7 @@ var init_board3 = __esm({
62791
63085
  var card_chat_default;
62792
63086
  var init_card_chat = __esm({
62793
63087
  "../cli/src/guide/card-chat.md"() {
62794
- card_chat_default = '# Answer a card\'s conversation\n\nRead the task\u2019s review plan and work only on unlocked stages. An empty plan needs no extra approval; an undecided plan allows planning only.\n\n- **Where the task stands**: read `akb task show <id>` and `akb task review <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- **Previews**: prepare or revise only requested outputs, using the task-bound Studio\u2019s Preview instructions and supplied component documentation. Before changing approved output, invalidate its stage with `akb task review <id> --revise-from <stage> --revision <n>`. Preserve unrelated work.\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 instructions; 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- **Approve**: only on an explicit request, use `akb task approve <id> --stage <stage> --revision <reviewed revision>`. In a reply this commits after successful synchronization. Finish the reply without further edits or waiting. Never substitute the latest revision for the one reviewed.\n- **Change the plan**: submit a complete replacement with `akb task review <id> --file <json> --revision <n>`. It takes effect immediately. Answers to questions never approve work.\n';
63088
+ card_chat_default = '# Answer a card\'s conversation\n\nRead the task\u2019s review plan and work only on unlocked stages. An empty plan needs no extra approval; an undecided plan allows planning only.\n\n- **Where the task stands**: read `akb task show <id>` and `akb task review <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 task update-questions <task>` 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- **Previews**: prepare or revise only requested outputs, using the task-bound Studio\u2019s Preview instructions and supplied component documentation. Before changing approved output, invalidate its stage with `akb task review <id> --revise-from <stage> --revision <n>`. Preserve unrelated work.\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 instructions; 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- **Approve**: only on an explicit request, use `akb task approve <id> --stage <stage> --revision <reviewed revision>`. In a reply this commits after successful synchronization. Finish the reply without further edits or waiting. Never substitute the latest revision for the one reviewed.\n- **Change the plan**: submit a complete replacement with `akb task review <id> --file <json> --revision <n>`. It takes effect immediately. Answers to questions never approve work.\n';
62795
63089
  }
62796
63090
  });
62797
63091
 
@@ -62831,7 +63125,7 @@ var init_follow_up = __esm({
62831
63125
  var implement_default;
62832
63126
  var init_implement = __esm({
62833
63127
  "../cli/src/guide/implement.md"() {
62834
- implement_default = "# Implement the approved requirements\n\nBuild the approved requirements without reopening settled decisions or unrelated questions; without a card, create none.\n\nFor Git deliveries, adapt the approved work to the current target branch and preserve its\nbehavior and removals unless the task's core intent requires changing them. Stop the\naffected work and use `akb guide update-questions` only if those changes conflict with the\ntask's core intent.\n\nDo not push, publish or deploy.\n\nOnce a task meets its Studio's delivery conditions, follow `akb guide archive` to record\ndelivery completion before ending the run.\n\n- **Verification**: run required and minimal representative checks, reuse valid results, distinguish defects from environment or tool limits, stop retries that add no evidence, and finish when acceptance is proven.\n- **Authorization**: carry approval for necessary in-scope operations across tools and stages without asking again.\n- **Blockers**: resolve routine problems and use `akb guide update-questions` only for user-action blockers or out-of-scope decisions, stating attempts, impact and recommendation while continuing independent work.\n- **Defer**: follow `akb guide follow-up` for unrelated work and keep it from blocking delivery.\n- **Decisions**: record material, reversible build decisions under `## Worth noting after implementation`.\n";
63128
+ implement_default = "# Implement the approved requirements\n\nBuild the approved requirements without reopening settled decisions or unrelated questions; without a card, create none.\n\nBefore implementing a Cloud task, read its recent chat with `akb task chat <task>`.\nRead older messages as needed. Use relevant clarifications within the scope of\nthe current card and approved plan.\n\nFor Git deliveries, adapt the approved work to the current target branch and preserve its\nbehavior and removals unless the task's core intent requires changing them. Stop the\naffected work and use `akb guide update-questions` only if those changes conflict with the\ntask's core intent.\n\nDo not push, publish or deploy.\n\nOnce a task meets its Studio's delivery conditions, follow `akb guide archive` to record\ndelivery completion before ending the run.\n\n- **Verification**: run required and minimal representative checks, reuse valid results, distinguish defects from environment or tool limits, stop retries that add no evidence, and finish when acceptance is proven.\n- **Authorization**: carry approval for necessary in-scope operations across tools and stages without asking again.\n- **Blockers**: resolve routine problems and use `akb guide update-questions` only for user-action blockers or out-of-scope decisions, stating attempts, impact and recommendation while continuing independent work.\n- **Defer**: follow `akb guide follow-up` for unrelated work and keep it from blocking delivery.\n- **Decisions**: record material, reversible build decisions under `## Worth noting after implementation`.\n";
62835
63129
  }
62836
63130
  });
62837
63131
 
@@ -62887,7 +63181,7 @@ var init_reflect = __esm({
62887
63181
  var resolve_default;
62888
63182
  var init_resolve2 = __esm({
62889
63183
  "../cli/src/guide/resolve.md"() {
62890
- resolve_default = '# Resolve questions\n\nApply the answers the user supplied to existing open questions. Leave every unanswered\nquestion unchanged. While applying answers, do not research, choose for the user, raise\nanother question, or change project code.\n\n## Apply each answer\n\n1. Match each supplied answer to its open question. If the answer is missing or unclear,\n leave that question open.\n2. Follow `akb guide writing`. Merge the answer into the existing decision, keep only the\n selected choice, remove obsolete or contradictory text, preserve completed work, and add\n newly required work as unchecked todos. When the answer changes an agent\'s section, read\n that agent\'s rules first, as "Preview ownership" there says.\n3. Drop each answered question after its answer is fully applied:\n\n```text\nakb raw update-questions <id> --drop <n[,n...]>\n```\n\nWhen an answer accepts a step the user was asked to review and asks for no changes, tick that\nstep\'s review todo; an answer asking for changes leaves it unticked.\n\nWhen an answer chooses to discard the card, first run `akb raw delivery cancel <delivery>` if a\ndelivery is in flight, then `akb task remove <id> "<why>" --discard`, and stop. Skip every\nremaining step of this guide.\n\nWhen an answer sends an agent\'s (`agent:`) section back for rework that the user must confirm\nagain, keep or `--update` the question instead of dropping it. Once no question is left for\nthat agent, request each matching agent listed below it whose section is missing or says it\nis waiting.\n\nWhen an answer selects one of several options in a Preview block, remove the rejected\noptions and their spec-tmp files.\n\n## Say what the answers did to a build in flight\n\nA delivery builds the card as it was approved when it started, and applying answers is the\nonly thing that rewrites that card underneath it. You read the question and you wrote the\nanswer, so you are the only one who can tell a confirmation from a change \u2014 the board reads\nyour conclusion and never the card\'s text.\n\n```text\nakb raw delivery answered <delivery> --unchanged "<why>"\nakb raw delivery answered <delivery> --changed "<why>"\n```\n\n- **Record it before you drop the questions**: dropping the last one is what puts the board\n back in motion, and until the conclusion is written the build does not land.\n- **Judge the meaning, not the words**: confirming an option that is already built, writing\n down a decision the card already carries, and tidying prose are all `--unchanged`.\n Adding, dropping or changing a requirement is `--changed`.\n- **A wrong implementation confirmed is still a change**: an answer that blesses work\n contradicting the approved copy is `--changed`, however finished that work is.\n- **One conclusion per round**: it covers every answer you applied in this session. The\n delivery a `--changed` reopens starts on the card as it then reads, with none of its own.\n\n`akb raw card implement <id> --print` prints the delivery\'s id and the copy it is building.\nNothing to record when no delivery is in flight.\n\n## Curate the human half\n\nPut each answer `akb guide writing` places in `Worth noting` in that section; put other\nnecessary lasting decisions below the boundary.\n\nRe-read the whole human half against the same rule. Remove or move down entries that\nfail it, repeat scope, or overlap another entry. Merge entries governed by one decision. One to\nthree independent items is normal; every additional item needs distinct user-facing stakes.\n\n## Refine\n\nIf any question remains open, stop and leave the card waiting. When a delivery is in flight,\nnever refine \u2014 even if `--changed` updated requirements, execution resumes directly from the\nupdated card.\n\nOnce no question is left and no delivery is building the card, refine it in this session by\n`akb guide refine`, which decides readiness:\n\n- **Partial**: when the card was refined before, revisit only what the answers changed.\n- **Full**: when the answers reshape the card or its `## Scope` is still the creation scaffold.\n';
63184
+ resolve_default = '# Resolve questions\n\nApply the answers the user supplied to existing open questions. Leave every unanswered\nquestion unchanged. While applying answers, do not research, choose for the user, raise\nanother question, or change project code.\n\n## Apply each answer\n\n1. Match each supplied answer to its open question. If the answer is missing or unclear,\n leave that question open.\n2. Follow `akb guide writing`. Merge the answer into the existing decision, keep only the\n selected choice, remove obsolete or contradictory text, preserve completed work, and add\n newly required work as unchecked todos. When the answer changes an agent\'s section, read\n that agent\'s rules first, as "Preview ownership" there says.\n\nWhen an answer accepts a step the user was asked to review and asks for no changes, tick that\nstep\'s review todo; an answer asking for changes leaves it unticked.\n\nWhen an answer chooses to discard the card, first run `akb raw delivery cancel <delivery>` if a\ndelivery is in flight, then `akb task remove <id> "<why>" --discard`, and stop. Skip every\nremaining step of this guide.\n\nWhen an answer sends an agent\'s (`agent:`) section back for rework that the user must confirm\nagain, keep or `--update` the question instead of dropping it. Once no question is left for\nthat agent, request each matching agent listed below it whose section is missing or says it\nis waiting.\n\nWhen an answer selects one of several options in a Preview block, remove the rejected\noptions and their spec-tmp files.\n\n## Say what the answers did to a build in flight\n\nA delivery builds the card as it was approved when it started, and applying answers is the\nonly thing that rewrites that card underneath it. You read the question and you wrote the\nanswer, so you are the only one who can tell a confirmation from a change \u2014 the board reads\nyour conclusion and never the card\'s text.\n\n```text\nakb raw delivery answered <delivery> --unchanged "<why>"\nakb raw delivery answered <delivery> --changed "<why>"\n```\n\n- **Record it before you drop the questions**: dropping the last one is what puts the board\n back in motion, and until the conclusion is written the build does not land.\n- **Judge the meaning, not the words**: confirming an option that is already built, writing\n down a decision the card already carries, and tidying prose are all `--unchanged`.\n Adding, dropping or changing a requirement is `--changed`.\n- **A wrong implementation confirmed is still a change**: an answer that blesses work\n contradicting the approved copy is `--changed`, however finished that work is.\n- **One conclusion per round**: it covers every answer you applied in this session. The\n delivery a `--changed` reopens starts on the card as it then reads, with none of its own.\n\n`akb raw card implement <id> --print` prints the delivery\'s id and the copy it is building.\nNothing to record when no delivery is in flight.\n\n## Curate the human half\n\nPut each answer `akb guide writing` places in `Worth noting` in that section; put other\nnecessary lasting decisions below the boundary.\n\nRe-read the whole human half against the same rule. Remove or move down entries that\nfail it, repeat scope, or overlap another entry. Merge entries governed by one decision. One to\nthree independent items is normal; every additional item needs distinct user-facing stakes.\n\n## Close the answered questions\n\nSave the body and any delivery conclusion first. Drop only the questions whose answers\nare fully applied. Runner synchronizes the updated body and question list together.\n\n```text\nakb task update-questions <task> --drop <n[,n...]>\n```\n\n## Refine\n\nIf any question remains open, stop and leave the card waiting. When a delivery is in flight,\nnever refine \u2014 even if `--changed` updated requirements, execution resumes directly from the\nupdated card.\n\nOnce no question is left and no delivery is building the card, refine it in this session by\n`akb guide refine`, which decides readiness:\n\n- **Partial**: when the card was refined before, revisit only what the answers changed.\n- **Full**: when the answers reshape the card or its `## Scope` is still the creation scaffold.\n';
62891
63185
  }
62892
63186
  });
62893
63187
 
@@ -62911,7 +63205,7 @@ var init_revise = __esm({
62911
63205
  var update_questions_default;
62912
63206
  var init_update_questions = __esm({
62913
63207
  "../cli/src/guide/update-questions.md"() {
62914
- update_questions_default = '# Decide what to ask the user\n\nA decision is a choice the work needs made. A question is a decision handed to the user:\nproject evidence cannot settle it, it materially affects what the user gets, and it has at\nleast two coherent options.\n\n### The material-decision test\n\nAsk when the tradeoff materially changes the delivered result, the accepted scope, the user\'s\nrisk, or a meaningful ongoing cost, and a reasonable reviewer may reject it; a studio\'s rules\nadd what else counts. Settle everything else yourself. Leave the question open and stop only\nthe work that depends on it. An obstacle only the user can clear is a question too: say what\ncannot proceed and offer ways forward.\n\n- **Write for users**: each option\'s outcome and main cost, your recommendation ticked; no\n card ids, agent names, or board jargon.\n- **Options**: exclusive unless they genuinely combine (`--mode multi`); never write an\n "other" option, the user always gets one.\n- **Not a question**: where a fix goes (`akb guide follow-up`).\n\n```text\nakb raw update-questions <id> \\\n --append "Which behavior should apply?" \\\n --recommended-option "A \u2014 outcome and cost" \\\n --option "B \u2014 outcome and cost"\n```\n';
63208
+ update_questions_default = '# Decide what to ask the user\n\nA decision is a choice the work needs made. A question is a decision handed to the user:\nproject evidence cannot settle it, it materially affects what the user gets, and it has at\nleast two coherent options.\n\n### The material-decision test\n\nAsk when the tradeoff materially changes the delivered result, the accepted scope, the user\'s\nrisk, or a meaningful ongoing cost, and a reasonable reviewer may reject it; a studio\'s rules\nadd what else counts. Settle everything else yourself. Leave the question open and stop only\nthe work that depends on it. An obstacle only the user can clear is a question too: say what\ncannot proceed and offer ways forward.\n\n- **Write for users**: each option\'s outcome and main cost, your recommendation ticked; no\n card ids, agent names, or board jargon.\n- **Options**: exclusive unless they genuinely combine (`--mode multi`); never write an\n "other" option, the user always gets one.\n- **Not a question**: where a fix goes (`akb guide follow-up`).\n\n```text\nakb task update-questions <task> \\\n --append "Which behavior should apply?" \\\n --recommended-option "A \u2014 outcome and cost" \\\n --option "B \u2014 outcome and cost"\n```\n\nUse the current task\'s key, ID, or project number. Runner saves the current card locally\nand synchronizes it with the rest of the card. For a Cloud version conflict, read the card\nagain and check the question positions before resubmitting.\n';
62915
63209
  }
62916
63210
  });
62917
63211
 
@@ -62943,7 +63237,7 @@ var init_write_prompt = __esm({
62943
63237
  var writing_default;
62944
63238
  var init_writing = __esm({
62945
63239
  "../cli/src/guide/writing.md"() {
62946
- writing_default = '# Write a card\n\nA card has a **human half** for review and a folded **agent half** for implementation.\nUse this order and keep the English section titles and empty scaffold sections:\n\n```text\n<One short paragraph: the problem and the intended result.>\n\n## Worth noting <- user\'s answers first, then material decisions; empty if none\n- **<decision>**: <chosen behavior and main cost in one sentence>\n\n## Worth noting after implementation\n- **<decision>**: <chosen behavior and main cost in one sentence>\n <- settled by the build; omit when empty; no logs or open questions\n\n<Preview id="<id>"> <- requested deliverable\n<result Markdown and assets>\n</Preview>\n\n<!-- agent --> <- folded content starts here\n\n## Scope <- requirements, not rationale\n### Done when <- acceptance checklist, when supplied\n- [ ] <observable result>\n\n## Todo <- implementation only; finish planning before writing steps\n- [ ] <one build step>\n\n## Decided by the agent <- other decisions and non-obvious findings the build needs\n- **<decision>**: <answer and required action>\n### Overruled by the user <- superseded decisions, always last\n```\n\n- **Decisions**: use the material-decision test in `akb guide update-questions` for Worth noting;\n merge entries governed by one policy and keep only the decision and its main cost.\n- **Delivery boundary**: Worth noting after implementation never changes approved scope or\n blocks an ongoing delivery; the build must fix deviations or refer them to the user.\n- **Preview sections**: use matching Preview tags and a stable Studio ID; keep the ID when revising.\n The app supplies localized titles and icons. Group files of one deliverable with Set.\n- **Previews**: read the relevant Studio `<Preview>` block and needed references before revising\n its section and assets in place.\n- **Preview presentation**: at every review point, show the deliverable directly; omit surrounding\n introductions, summaries and notes unless requested or needed for review, keeping necessary\n context brief and stating it once.\n- **Preserve work**: leave checked todos and supplied Done when checklists unchanged; append a\n todo to reverse completed work, and move user-overruled decisions to Overruled by the user\n until the card leaves no room to repeat them.\n- **Writing**: write clear behavior and necessary tradeoffs for a fresh reader, keep the human\n half self-contained, and state each fact once.\n- **Agent half**: keep only implementation-critical information not stated elsewhere; omit\n process logs and routine implementation planning, and leave unneeded sections empty.\n- **Frontmatter**: never edit frontmatter by hand; use `akb raw update` or `update-questions`.\n- **Validate**: run `akb raw validate <id>` after edits and fix every reported file and line.\n';
63240
+ writing_default = '# Write a card\n\nA card has a **human half** for review and a folded **agent half** for implementation.\nUse this order and keep the English section titles and empty scaffold sections:\n\n```text\n<One short paragraph: the problem and the intended result.>\n\n## Worth noting <- user\'s answers first, then material decisions; empty if none\n- **<decision>**: <chosen behavior and main cost in one sentence>\n\n## Worth noting after implementation\n- **<decision>**: <chosen behavior and main cost in one sentence>\n <- settled by the build; omit when empty; no logs or open questions\n\n<Preview id="<id>"> <- requested deliverable\n<result Markdown and assets>\n</Preview>\n\n<!-- agent --> <- folded content starts here\n\n## Scope <- requirements, not rationale\n### Done when <- acceptance checklist, when supplied\n- [ ] <observable result>\n\n## Todo <- implementation only; finish planning before writing steps\n- [ ] <one build step>\n\n## Decided by the agent <- other decisions and non-obvious findings the build needs\n- **<decision>**: <answer and required action>\n### Overruled by the user <- superseded decisions, always last\n```\n\n- **Decisions**: use the material-decision test in `akb guide update-questions` for Worth noting;\n merge entries governed by one policy and keep only the decision and its main cost.\n- **Delivery boundary**: Worth noting after implementation never changes approved scope or\n blocks an ongoing delivery; the build must fix deviations or refer them to the user.\n- **Preview sections**: use matching Preview tags and a stable Studio ID; keep the ID when revising.\n The app supplies localized titles and icons. Group files of one deliverable with Set.\n- **Previews**: read the relevant Studio `<Preview>` block and needed references before revising\n its section and assets in place.\n- **Preview presentation**: at every review point, show the deliverable directly; omit surrounding\n introductions, summaries and notes unless requested or needed for review, keeping necessary\n context brief and stating it once.\n- **Preserve work**: leave checked todos and supplied Done when checklists unchanged; append a\n todo to reverse completed work, and move user-overruled decisions to Overruled by the user\n until the card leaves no room to repeat them.\n- **Writing**: write clear behavior and necessary tradeoffs for a fresh reader, keep the human\n half self-contained, and state each fact once.\n- **Agent half**: keep only implementation-critical information not stated elsewhere; omit\n process logs and routine implementation planning, and leave unneeded sections empty.\n- **Frontmatter**: never edit frontmatter by hand; use `akb raw update` or `akb task update-questions`.\n- **Validate**: run `akb raw validate <id>` after edits and fix every reported file and line.\n';
62947
63241
  }
62948
63242
  });
62949
63243
 
@@ -63057,7 +63351,7 @@ var init_guide2 = __esm({
63057
63351
 
63058
63352
  // ../cli/src/commands/studio.ts
63059
63353
  import crypto7 from "node:crypto";
63060
- import fs75 from "node:fs";
63354
+ import fs76 from "node:fs";
63061
63355
  import path76 from "node:path";
63062
63356
  function cmdStudioList() {
63063
63357
  if (!studiosReachable().ok) die(NEEDS_CLOUD, "needs-cloud");
@@ -63076,7 +63370,7 @@ function cmdStudioDiagram(_id, _card, _folder) {
63076
63370
  }
63077
63371
  function cmdStudioValidate(folder2) {
63078
63372
  const dir = path76.resolve(folder2);
63079
- if (!fs75.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder2} is not a folder`, "bad-args");
63373
+ if (!fs76.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder2} is not a folder`, "bad-args");
63080
63374
  const files = readStudioFolder(dir);
63081
63375
  let builtin = false;
63082
63376
  try {
@@ -63098,7 +63392,7 @@ async function cmdStudioPull(id2, folder2) {
63098
63392
  found(id2);
63099
63393
  }
63100
63394
  const dir = path76.resolve(folder2 ?? id2);
63101
- if (fs75.existsSync(dir) && fs75.readdirSync(dir).length) die(`${folder2 ?? id2} is not empty`, "bad-args");
63395
+ if (fs76.existsSync(dir) && fs76.readdirSync(dir).length) die(`${folder2 ?? id2} is not empty`, "bad-args");
63102
63396
  const read5 = await call("GET", `/v1/studios/${encodeURIComponent(cloudId)}`);
63103
63397
  const { version: version2, files } = requireResponse(
63104
63398
  cloudOk(read5, read5.ok || read5.code !== "not_found" ? void 0 : "no-such-studio"),
@@ -63107,9 +63401,9 @@ async function cmdStudioPull(id2, folder2) {
63107
63401
  );
63108
63402
  for (const [file2, text5] of Object.entries({ ...files, [VERSION_FILE]: versionText(cloudId, version2) })) {
63109
63403
  const full = path76.join(dir, ...file2.split("/"));
63110
- fs75.mkdirSync(path76.dirname(full), { recursive: true });
63404
+ fs76.mkdirSync(path76.dirname(full), { recursive: true });
63111
63405
  const data = isAboutFile(file2) && !file2.endsWith(".md") && /^data:[^;]+;base64,/.exec(text5);
63112
- fs75.writeFileSync(full, data ? Buffer.from(text5.slice(data[0].length), "base64") : text5);
63406
+ fs76.writeFileSync(full, data ? Buffer.from(text5.slice(data[0].length), "base64") : text5);
63113
63407
  }
63114
63408
  const shown = folder2 ?? `./${id2}`;
63115
63409
  say(`Pulled ${id2} v${version2} into ${shown}.`);
@@ -63125,13 +63419,13 @@ async function publishFolder(dir, route2, body, requestId) {
63125
63419
  const hash3 = crypto7.createHash("sha256").update(JSON.stringify({ route: route2, files: body.files, workspace: body.workspace })).digest("hex");
63126
63420
  let held4;
63127
63421
  try {
63128
- held4 = JSON.parse(fs75.readFileSync(pendingFile, "utf8"));
63422
+ held4 = JSON.parse(fs76.readFileSync(pendingFile, "utf8"));
63129
63423
  } catch {
63130
63424
  }
63131
63425
  if (requestId && held4?.requestId === requestId && held4.hash !== hash3) die("This request ID already names different files; use a new request ID.", "bad-args");
63132
63426
  const replay = held4?.hash === hash3 && held4.route === route2 && (!requestId || held4.requestId === requestId) && (body.expectedVersion === held4.body.expectedVersion || body.expectedVersion === held4.resultVersion);
63133
63427
  const pending = replay ? held4 : { requestId: requestId ?? crypto7.randomUUID(), hash: hash3, body, route: route2 };
63134
- fs75.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
63428
+ fs76.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
63135
63429
  const res = await call(route2 === "/v1/studios" ? "POST" : "PATCH", route2, pending.body, pending.requestId);
63136
63430
  const { id: id2, version: version2 } = requireResponse(
63137
63431
  cloudOk(res, !res.ok && ["version_conflict", "conflict"].includes(res.code ?? "") ? "studio-moved" : void 0),
@@ -63139,8 +63433,8 @@ async function publishFolder(dir, route2, body, requestId) {
63139
63433
  (value) => hasText(value.id) && /^wf_[\w-]+$/.test(value.id) && isStudioVersion(value.version) && (pending.body.expectedVersion === void 0 || route2 === `/v1/studios/${encodeURIComponent(value.id)}` && value.version === pending.body.expectedVersion + 1)
63140
63434
  );
63141
63435
  pending.resultVersion = version2;
63142
- fs75.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
63143
- fs75.writeFileSync(path76.join(dir, VERSION_FILE), versionText(id2, version2));
63436
+ fs76.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
63437
+ fs76.writeFileSync(path76.join(dir, VERSION_FILE), versionText(id2, version2));
63144
63438
  say(`Saved ${studioName(id2)} v${version2}. New tasks take it.`);
63145
63439
  return { id: id2, version: version2, changed: true, requestId: pending.requestId };
63146
63440
  }
@@ -63155,14 +63449,14 @@ async function cmdStudioPush(folder2, opts) {
63155
63449
  const dir = path76.resolve(folder2);
63156
63450
  let pulled = null;
63157
63451
  try {
63158
- pulled = JSON.parse(fs75.readFileSync(path76.join(dir, VERSION_FILE), "utf8"));
63452
+ pulled = JSON.parse(fs76.readFileSync(path76.join(dir, VERSION_FILE), "utf8"));
63159
63453
  } catch {
63160
63454
  }
63161
63455
  if (!pulled?.id || !Number.isInteger(pulled.version) || pulled.version < 1) die(`${folder2} has no valid version.json; pull again.`, "bad-args");
63162
63456
  const { id: id2, version: version2 } = pulled;
63163
63457
  if (id2.startsWith("wf_builtin_")) die("Copy this studio before editing it.", "studio-read-only");
63164
63458
  const files = publicationFiles(dir);
63165
- if (!fs75.existsSync(path76.join(dir, ".publication.json")) && !opts.requestId) {
63459
+ if (!fs76.existsSync(path76.join(dir, ".publication.json")) && !opts.requestId) {
63166
63460
  const now = await call("GET", `/v1/studios/${encodeURIComponent(id2)}`);
63167
63461
  if (now.ok && now.value.version === version2 && isStudioFiles(now.value.files) && JSON.stringify(files) === JSON.stringify(Object.fromEntries(Object.entries(now.value.files).filter(([f]) => f !== VERSION_FILE).sort()))) {
63168
63462
  say(`${studioName(id2)} is unchanged (v${version2}).`);
@@ -63185,7 +63479,7 @@ function noteText({ file: file2, text: text5 }) {
63185
63479
  if (file2 !== void 0 && text5 !== void 0) die("pass --file or --text, not both", "bad-args");
63186
63480
  if (file2 !== void 0) {
63187
63481
  try {
63188
- return fs75.readFileSync(file2, "utf8").trim();
63482
+ return fs76.readFileSync(file2, "utf8").trim();
63189
63483
  } catch {
63190
63484
  die(`can't read ${file2}`, "bad-args");
63191
63485
  }
@@ -63371,7 +63665,12 @@ var init_progress = __esm({
63371
63665
  });
63372
63666
 
63373
63667
  // ../cli/src/lib/agent/complete.ts
63374
- import fs76 from "node:fs";
63668
+ import fs77 from "node:fs";
63669
+ function checkRecordedResult(receipt, commit, branch) {
63670
+ if (receipt.commit === commit && receipt.branch === branch) return;
63671
+ const describe4 = (hash3, target) => hash3 ? `${hash3} on ${target}` : "no Git result";
63672
+ throw new Error(`This step already recorded a different result. Recorded: ${describe4(receipt.commit, receipt.branch)}. Reported: ${describe4(commit, branch)}.`);
63673
+ }
63375
63674
  function completeDelivery(named2, result = {}) {
63376
63675
  const commit = result.commit?.toLowerCase();
63377
63676
  const branch = result.branch;
@@ -63394,13 +63693,13 @@ function completeDelivery(named2, result = {}) {
63394
63693
  const run3 = store.runs.find((r) => r.sessionId === sessionId);
63395
63694
  const current = store.runs.filter((r) => r.deliveryId === delivery2.deliveryId && ["implement", "scheduled"].includes(r.action)).pop();
63396
63695
  const liveCard = delivery2.cardId === null ? null : cardFile(delivery2.cardId);
63397
- const restored = liveCard && parseFrontmatter(fs76.readFileSync(liveCard, "utf8")).meta?.restored;
63696
+ const restored = liveCard && parseFrontmatter(fs77.readFileSync(liveCard, "utf8")).meta?.restored;
63398
63697
  if (restored && Date.parse(restored) > (run3?.startedAt ?? 0)) throw new Error("This delivery predates task restoration.");
63399
63698
  if (!run3 || run3.deliveryId !== delivery2.deliveryId) throw new Error("This run does not own the delivery.");
63400
63699
  const pending = receipts[deliveryStep(delivery2)];
63401
63700
  const previous = receipts.find((c) => c.sessionId === sessionId || c.resumedSessions?.includes(sessionId));
63402
63701
  if (previous) {
63403
- if (previous.commit !== commit || previous.branch !== branch) throw new Error("This step already recorded a different result.");
63702
+ checkRecordedResult(previous, commit, branch);
63404
63703
  if (!previous.finished && previous.step === deliveryStep(delivery2) && (delivery2.status !== "active" || run3 !== current || run3.status !== "running")) {
63405
63704
  throw new Error("Only the current owning run can finish pending completion.");
63406
63705
  }
@@ -63411,7 +63710,7 @@ function completeDelivery(named2, result = {}) {
63411
63710
  }
63412
63711
  if (answerOutcome(delivery2) === "changed") throw new Error("The approved requirements were superseded. Continue with the updated delivery.");
63413
63712
  if (pending && run3 === current) {
63414
- if (pending.commit !== commit || pending.branch !== branch) throw new Error("This step already recorded a different result.");
63713
+ checkRecordedResult(pending, commit, branch);
63415
63714
  pending.resumedSessions = [...pending.resumedSessions ?? [], sessionId];
63416
63715
  return { delivery: delivery2, receipt: pending };
63417
63716
  }
@@ -63502,7 +63801,7 @@ function startSubRun(parentId, prompt, runtime) {
63502
63801
  const parent = peekRun(parentId);
63503
63802
  if (!parent || parent.status !== "running") return refusal("runNotFound", `run ${parentId.slice(0, 8)} is not running here`, { id: parentId });
63504
63803
  if (parent.action === "sub") return refusal("subRunNested", "a sub-run cannot start sub-runs of its own");
63505
- const inherited = parent.runtime && runtimeById(parent.runtime) ? parent.runtime : void 0;
63804
+ const inherited = parent.runtime && runRuntimeById(parent.runtime) ? parent.runtime : void 0;
63506
63805
  return open3(
63507
63806
  {
63508
63807
  action: "sub",
@@ -63565,7 +63864,7 @@ var init_start = __esm({
63565
63864
  });
63566
63865
 
63567
63866
  // ../cli/src/lib/agent/task-chats.ts
63568
- import fs77 from "node:fs";
63867
+ import fs78 from "node:fs";
63569
63868
  import path77 from "node:path";
63570
63869
  function taskChatFile(task, home3) {
63571
63870
  if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
@@ -63574,7 +63873,7 @@ function taskChatFile(task, home3) {
63574
63873
  function readTaskChat(task, home3) {
63575
63874
  let text5;
63576
63875
  try {
63577
- text5 = fs77.readFileSync(taskChatFile(task, home3), "utf8");
63876
+ text5 = fs78.readFileSync(taskChatFile(task, home3), "utf8");
63578
63877
  } catch {
63579
63878
  return [];
63580
63879
  }
@@ -63600,7 +63899,7 @@ var init_task_chats = __esm({
63600
63899
  });
63601
63900
 
63602
63901
  // ../cli/src/lib/agent/memory-review.ts
63603
- import fs78 from "node:fs";
63902
+ import fs79 from "node:fs";
63604
63903
  import path78 from "node:path";
63605
63904
  function taskChatsToReview(tasks) {
63606
63905
  const out = [];
@@ -63624,7 +63923,7 @@ function readArchived2(id2) {
63624
63923
  if (!found2) return null;
63625
63924
  try {
63626
63925
  const file2 = found2.kind === "group" ? path78.join(found2.target, "root.md") : found2.target;
63627
- const { meta: meta3, body } = parseFrontmatter(fs78.readFileSync(file2, "utf8"));
63926
+ const { meta: meta3, body } = parseFrontmatter(fs79.readFileSync(file2, "utf8"));
63628
63927
  if (!meta3) return null;
63629
63928
  return { id: id2, title: meta3.title, modules: meta3.modules ?? [], studio: meta3.studio ?? "", previews: meta3.previews ?? [], rejected: meta3.rejected, body };
63630
63929
  } catch {
@@ -63685,18 +63984,18 @@ var init_memory_review = __esm({
63685
63984
  });
63686
63985
 
63687
63986
  // ../cli/src/lib/agent/dismissal-review.ts
63688
- import fs79 from "node:fs";
63987
+ import fs80 from "node:fs";
63689
63988
  import path79 from "node:path";
63690
63989
  function rejectionsToReview() {
63691
63990
  const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
63692
63991
  const dir = path79.join(scratch ? path79.join(scratch, ".archive") : ARCHIVE, REJECTIONS_TO_REVIEW);
63693
- if (!fs79.existsSync(dir)) return [];
63992
+ if (!fs80.existsSync(dir)) return [];
63694
63993
  const found2 = [];
63695
63994
  for (const file2 of walkMd(dir)) {
63696
63995
  const id2 = archivedId(file2);
63697
63996
  if (id2 === null) continue;
63698
63997
  try {
63699
- const { meta: meta3 } = parseFrontmatter(fs79.readFileSync(file2, "utf8"));
63998
+ const { meta: meta3 } = parseFrontmatter(fs80.readFileSync(file2, "utf8"));
63700
63999
  if (!meta3?.rejected || meta3.rejected_by !== "user" || !meta3.rejected_reason.trim()) continue;
63701
64000
  found2.push({ id: id2, title: meta3.title, file: rel(file2), reason: meta3.rejected_reason.trim(), rejectedAt: meta3.rejected_at });
63702
64001
  } catch {
@@ -63718,7 +64017,7 @@ function citedSources(text5) {
63718
64017
  const ids = /* @__PURE__ */ new Set();
63719
64018
  for (const line of text5.split("\n")) {
63720
64019
  if (!/^\s*[-*]\s/.test(line)) continue;
63721
- const m = line.match(SOURCES);
64020
+ const m = line.match(SOURCES2);
63722
64021
  for (const id2 of m?.[1].split(",") ?? []) if (id2.trim()) ids.add(id2.trim());
63723
64022
  }
63724
64023
  return [...ids];
@@ -63726,7 +64025,7 @@ function citedSources(text5) {
63726
64025
  function withdrawnSources() {
63727
64026
  const cited = [...new Set(plannerCopies("rejected.md").flatMap((file2) => {
63728
64027
  try {
63729
- return citedSources(fs79.readFileSync(file2, "utf8"));
64028
+ return citedSources(fs80.readFileSync(file2, "utf8"));
63730
64029
  } catch {
63731
64030
  return [];
63732
64031
  }
@@ -63737,7 +64036,7 @@ function withdrawnSources() {
63737
64036
  const restored = new Set([...readInbox(), ...readArchived(scratch ? path79.join(scratch, "triage", "archived") : void 0)].map((s) => s.sourceId));
63738
64037
  return cited.filter((id2) => restored.has(id2) && !dismissed.has(id2));
63739
64038
  }
63740
- var reviewDismissed, SOURCES;
64039
+ var reviewDismissed, SOURCES2;
63741
64040
  var init_dismissal_review = __esm({
63742
64041
  "../cli/src/lib/agent/dismissal-review.ts"() {
63743
64042
  "use strict";
@@ -63751,12 +64050,12 @@ var init_dismissal_review = __esm({
63751
64050
  const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
63752
64051
  return readAllDismissed(scratch ? path79.join(scratch, "triage", "dismissed") : void 0);
63753
64052
  };
63754
- SOURCES = /\(([^()]+)\)\s*$/;
64053
+ SOURCES2 = /\(([^()]+)\)\s*$/;
63755
64054
  }
63756
64055
  });
63757
64056
 
63758
64057
  // ../cli/src/lib/agent/flow.ts
63759
- import fs80 from "node:fs";
64058
+ import fs81 from "node:fs";
63760
64059
  import path80 from "node:path";
63761
64060
  function readCard2(id2, home3 = "board") {
63762
64061
  const pending = activeDelivery(id2)?.completions?.some((c) => !c.finished);
@@ -63770,7 +64069,7 @@ function readCard2(id2, home3 = "board") {
63770
64069
  const file2 = found2.kind === "group" ? path80.join(found2.target, "root.md") : found2.target;
63771
64070
  let text5;
63772
64071
  try {
63773
- text5 = fs80.readFileSync(file2, "utf8");
64072
+ text5 = fs81.readFileSync(file2, "utf8");
63774
64073
  } catch {
63775
64074
  die(`#${id2} is on the board but ${rel(file2)} can't be read.`, { kind: "card-unreadable", id: id2 });
63776
64075
  }
@@ -64425,13 +64724,32 @@ var init_coding_previews = __esm({
64425
64724
 
64426
64725
  // ../cli/src/lib/agent/approved-ui.ts
64427
64726
  import path81 from "node:path";
64727
+ function approvedUiSource(pins, src, owner) {
64728
+ const [ref] = splitFileReference(src);
64729
+ if (artifactId.test(ref)) {
64730
+ const version2 = approvedUiPin(pins, ref).version;
64731
+ const names2 = Object.keys(pins).filter((name) => {
64732
+ const pin = approvedUiPin(pins, name);
64733
+ return pin.artifact === ref && (version2 === void 0 || pin.version === version2);
64734
+ });
64735
+ return names2.find((name) => !artifactId.test(name)) ?? names2[0] ?? ref;
64736
+ }
64737
+ const local = owner && !ref.startsWith(".assets/") ? relativeFileReference(ref, owner) : ref;
64738
+ return [local, src, ref, path81.posix.normalize(local)].find((key) => Object.hasOwn(pins, key)) ?? local;
64739
+ }
64740
+ function approvedUiPin(pins, source2) {
64741
+ return object2(Object.hasOwn(pins, source2) ? pins[source2] : void 0);
64742
+ }
64743
+ function validUiPin(pin) {
64744
+ return !pin.error && pin.status !== "pending" && pin.status !== "failed" && typeof pin.artifact === "string" && artifactId.test(pin.artifact) && typeof pin.version === "number" && Number.isSafeInteger(pin.version) && pin.version > 0;
64745
+ }
64428
64746
  function approvedUiPreviews(review) {
64429
64747
  if (reviewAuthorization(review).kind !== "delivery") return [];
64430
64748
  const result = [];
64431
- for (const node2 of review.plan ?? []) {
64749
+ for (const [index, node2] of (review.plan ?? []).entries()) {
64432
64750
  const stage = review.stages.find((stage2) => stage2.id === node2.id);
64433
64751
  const snapshot2 = stage?.snapshot;
64434
- if (!stage || !snapshot2) continue;
64752
+ if (node2.kind === "work" || !stage || !snapshot2) continue;
64435
64753
  const evidence = object2(snapshot2.evidence);
64436
64754
  const content = object2(evidence.content);
64437
64755
  const frozenPreviews = Array.isArray(snapshot2.previews) ? snapshot2.previews.filter(isObject2) : [];
@@ -64439,17 +64757,17 @@ function approvedUiPreviews(review) {
64439
64757
  const preview = object2(content[id2]);
64440
64758
  const body = typeof preview.body === "string" ? preview.body : typeof snapshot2.body === "string" ? parsePreviewBlocks(snapshot2.body).blocks.find((block) => block.id === id2)?.instructions : void 0;
64441
64759
  if (!body) continue;
64442
- const pins = { ...object2(frozenPreviews.find((preview2) => preview2.id === id2)?.assets), ...object2(evidence.assets) };
64760
+ const pins = { ...object2(evidence.dependencies), ...object2(frozenPreviews.find((preview2) => preview2.id === id2)?.assets), ...object2(evidence.assets) };
64443
64761
  const files = /* @__PURE__ */ new Map();
64444
- const add2 = (src, label2, device) => {
64445
- const pin = object2(pins[src]);
64446
- const { artifact, version: version2 } = pin;
64447
- if (typeof artifact !== "string" || !/^art_[a-z0-9]+$/i.test(artifact) || typeof version2 !== "number" || !Number.isSafeInteger(version2) || version2 < 1) return;
64762
+ const add2 = (src, label2, device, required2 = true) => {
64763
+ if (external.test(src)) return;
64764
+ const source2 = approvedUiSource(pins, src);
64765
+ if (!required2 && !Object.hasOwn(pins, source2) && !/\.(?:html?|tsx)$/i.test(source2)) return;
64448
64766
  const name = label2.trim() || path81.posix.basename(src);
64449
64767
  const key = JSON.stringify([src, name]);
64450
64768
  let file2 = files.get(key);
64451
64769
  if (!file2) {
64452
- file2 = { src, artifact, version: version2, revision: stage.revision, label: name, devices: /* @__PURE__ */ new Set() };
64770
+ file2 = { src, source: source2, label: name, devices: /* @__PURE__ */ new Set() };
64453
64771
  files.set(key, file2);
64454
64772
  }
64455
64773
  file2.devices.add(device === "mobile" ? "Mobile" : device === "desktop" ? "Desktop" : "Device unspecified");
@@ -64469,33 +64787,53 @@ function approvedUiPreviews(review) {
64469
64787
  }
64470
64788
  }
64471
64789
  const listed = new Set([...files.values()].map((file2) => file2.src));
64472
- for (const src of bodySources(body)) if (!listed.has(src)) add2(src, "");
64473
- result.push(...files.values());
64790
+ for (const src of bodySources(body)) if (!listed.has(src)) add2(src, "", void 0, false);
64791
+ if (files.size) result.push({
64792
+ id: id2,
64793
+ revision: stage.revision,
64794
+ directory: `review-${stage.revision}-${index}/${id2}`,
64795
+ body,
64796
+ pins,
64797
+ files: [...files.values()]
64798
+ });
64474
64799
  }
64475
64800
  }
64476
64801
  return result;
64477
64802
  }
64478
- function approvedUiFile(directory, file2) {
64479
- const ext = path81.posix.extname(file2.src).toLowerCase();
64480
- const suffix = ext === ".tsx" ? ".html" : /^\.[a-z0-9]+$/.test(ext) ? ext : "";
64481
- return path81.join(directory, `${file2.artifact}-${file2.version}${suffix}`);
64482
- }
64483
- function approvedUiPrompt(review, directory) {
64484
- const files = approvedUiPreviews(review);
64485
- if (!files.length) return "";
64803
+ function approvedUiFile(directory, preview, source2) {
64804
+ const parts = path81.posix.normalize(splitFileReference(source2)[0]).split("/");
64805
+ let parents = 0;
64806
+ while (parts[0] === "..") {
64807
+ parts.shift();
64808
+ parents++;
64809
+ }
64810
+ const rendered = /\.tsx$/i.test(parts.at(-1) ?? "");
64811
+ if (rendered) parts[parts.length - 1] = parts.at(-1).replace(/\.tsx$/i, ".html");
64812
+ const safe2 = parts.map((part) => !part || part === "." ? "%00" : part.replace(/[\\:*?"<>|%\x00-\x1f]/g, (char) => `%${char.charCodeAt(0).toString(16).padStart(2, "0")}`));
64813
+ return path81.join(directory, preview.directory, `${rendered ? "rendered" : "files"}-${parents}`, ...safe2);
64814
+ }
64815
+ function approvedUiPrompt(review, directory, includeBody = false) {
64816
+ const previews = approvedUiPreviews(review);
64817
+ if (!previews.length) return "";
64486
64818
  return [
64487
64819
  "Approved UI previews",
64488
64820
  APPROVED_UI_RULE,
64489
- files.map((file2) => {
64490
- const ref = directory ? `frozen file: \`${approvedUiFile(directory, file2)}\`` : `artifact ${file2.artifact}, version ${file2.version}`;
64491
- return `- ${file2.label} \xB7 ${[...file2.devices].join(" / ")} \xB7 Review revision ${file2.revision} \xB7 ${file2.src} \xB7 ${ref}`;
64492
- }).join("\n")
64821
+ ...previews.flatMap((preview) => [
64822
+ ...includeBody ? [preview.body] : [],
64823
+ preview.files.flatMap((file2) => {
64824
+ const pin = approvedUiPin(preview.pins, file2.source);
64825
+ if (!validUiPin(pin)) return [];
64826
+ const ref = directory ? `frozen file: \`${approvedUiFile(directory, preview, file2.source)}\`` : `artifact ${pin.artifact}, version ${pin.version}`;
64827
+ return [`- ${file2.label} \xB7 ${[...file2.devices].join(" / ")} \xB7 Review revision ${preview.revision} \xB7 ${file2.src} \xB7 ${ref}`];
64828
+ }).join("\n")
64829
+ ])
64493
64830
  ].join("\n\n");
64494
64831
  }
64495
- var APPROVED_UI_DIR_ENV, APPROVED_UI_RULE, UI_PREVIEW, historicalUiIds, object2;
64832
+ var APPROVED_UI_DIR_ENV, APPROVED_UI_RULE, UI_PREVIEW, historicalUiIds, object2, artifactId, external;
64496
64833
  var init_approved_ui = __esm({
64497
64834
  "../cli/src/lib/agent/approved-ui.ts"() {
64498
64835
  "use strict";
64836
+ init_file_references();
64499
64837
  init_references();
64500
64838
  init_tags();
64501
64839
  init_coding_previews();
@@ -64506,6 +64844,8 @@ var init_approved_ui = __esm({
64506
64844
  UI_PREVIEW = "ui-design";
64507
64845
  historicalUiIds = Object.keys(CODING_PREVIEWS).filter((id2) => id2 !== UI_PREVIEW && CODING_PREVIEWS[id2] === UI_PREVIEW);
64508
64846
  object2 = (value) => isObject2(value) ? value : {};
64847
+ artifactId = /^art_[a-z0-9]+$/i;
64848
+ external = /^(?:[a-z][\w+.-]*:|\/|#)/i;
64509
64849
  }
64510
64850
  });
64511
64851
 
@@ -64574,7 +64914,7 @@ __export(watch_exports, {
64574
64914
  watchRun: () => watchRun
64575
64915
  });
64576
64916
  import { spawn as spawn3 } from "node:child_process";
64577
- import fs81 from "node:fs";
64917
+ import fs82 from "node:fs";
64578
64918
  async function watchRun(sessionId, resume = startResume, retryBackoff = backoffMs) {
64579
64919
  const spec = readSpec(sessionId);
64580
64920
  const run3 = peekRun(sessionId);
@@ -64610,20 +64950,24 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64610
64950
  const record2 = claimed ?? run3;
64611
64951
  const sub = record2.action === "sub";
64612
64952
  if (claim2) await setCardStatus(claim2.cardId, claim2.status);
64613
- fs81.mkdirSync(SESSIONS_DIR, { recursive: true });
64614
- const logFile = fs81.createWriteStream(record2.logPath, { flags: "a" });
64953
+ fs82.mkdirSync(SESSIONS_DIR, { recursive: true });
64954
+ const logFile = fs82.createWriteStream(record2.logPath, { flags: "a" });
64615
64955
  logFile.on("error", () => {
64616
64956
  });
64617
- const eventsFile = fs81.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
64957
+ const eventsFile = fs82.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
64618
64958
  eventsFile.on("error", () => {
64619
64959
  });
64620
64960
  let observeActivity = (_e) => {
64621
64961
  };
64622
64962
  const pendingOperations = /* @__PURE__ */ new Set();
64963
+ let hadEffects = false;
64623
64964
  const event2 = (e) => {
64624
64965
  observeActivity(e);
64625
64966
  const hadPending = pendingOperations.size > 0;
64626
- if (e.kind === "tool_call" && !["read", "search", "fetch"].includes(e.data.kind) && !["completed", "failed"].includes(e.data.status)) pendingOperations.add(e.data.toolCallId);
64967
+ if (e.kind === "tool_call" && !["read", "search", "fetch"].includes(e.data.kind)) {
64968
+ hadEffects = true;
64969
+ if (!["completed", "failed"].includes(e.data.status)) pendingOperations.add(e.data.toolCallId);
64970
+ }
64627
64971
  if ((e.kind === "tool_call" || e.kind === "tool_call_update") && ["completed", "failed"].includes(e.data.status ?? "")) pendingOperations.delete(e.data.toolCallId);
64628
64972
  if (record2.cloudExecution && hadPending !== pendingOperations.size > 0) {
64629
64973
  patch(sessionId, (run4) => {
@@ -64633,6 +64977,11 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64633
64977
  eventsFile.write(`${JSON.stringify(e)}
64634
64978
  `);
64635
64979
  };
64980
+ const runtimeInfo = () => ({
64981
+ connector: record2.harness,
64982
+ name: record2.runtime ? runtimeById(record2.runtime)?.name ?? null : null,
64983
+ model: peekRun(sessionId)?.model ?? record2.model ?? null
64984
+ });
64636
64985
  const log = {
64637
64986
  write(text5) {
64638
64987
  logFile.write(text5);
@@ -64661,11 +65010,14 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64661
65010
  const review = reviewContext?.review;
64662
65011
  const boundary = review && reviewBoundary(savedPreviews ? { ...review, stages: review.stages.map((stage) => ({ ...stage, snapshot: null })) } : review, reviewContext.assigned);
64663
65012
  const coding = record2.action === "implement" && studioForRun({ id: record2.cardId ?? void 0, deliveryId: record2.deliveryId }) === "coding";
64664
- const previewPrompt = savedPreviews ? [
65013
+ const uiDirectory = process.env[APPROVED_UI_DIR_ENV];
65014
+ const approvedUi = review && coding && (!savedPreviews || uiDirectory) ? approvedUiPrompt(review, uiDirectory, !!savedPreviews) : "";
65015
+ const savedPrompt = savedPreviews ? [
64665
65016
  `Read the saved task Previews and their pinned files in \`${savedPreviews}\`. Use these saved versions for the requirements they cover and verify the delivery against them.`,
64666
- ...coding && review?.plan?.some((node2) => node2.previews.includes("ui-design")) ? [APPROVED_UI_RULE] : []
64667
- ].join("\n") : review && coding ? approvedUiPrompt(review, process.env[APPROVED_UI_DIR_ENV]) : "";
64668
- const prompt = [process.env.AI4KANBAN_SYNC_DIAGNOSTIC ? syncRepairPrompt(process.env.AI4KANBAN_SYNC_DIAGNOSTIC) : "", record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, resumedStudio, previewPrompt, recoveryPrompt2, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
65017
+ ...coding && !approvedUi && review?.plan?.some((node2) => node2.previews.includes("ui-design")) ? [APPROVED_UI_RULE] : []
65018
+ ].join("\n") : "";
65019
+ const retryDiag = record2.retry ? record2.failure ? retryContinuePrompt(record2.failure, record2.retry.attempt, record2.retry.of) : `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "";
65020
+ const prompt = [process.env.AI4KANBAN_SYNC_DIAGNOSTIC ? syncRepairPrompt(process.env.AI4KANBAN_SYNC_DIAGNOSTIC) : "", retryDiag, conflictPrompt(KANBAN), boundary, basePrompt, resumedStudio, savedPrompt, approvedUi, recoveryPrompt2, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
64669
65021
  const before = markBoard();
64670
65022
  const takes = active3.images;
64671
65023
  active3.renderer?.setRequiredImages?.(record2.pictures ?? []);
@@ -64693,11 +65045,29 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64693
65045
  letGo();
64694
65046
  return 1;
64695
65047
  }
64696
- if (record2.retry?.launching) patch(sessionId, (r) => {
64697
- if (!r.retry?.launching) return;
64698
- r.retry.attempt++;
64699
- delete r.retry.launching;
64700
- });
65048
+ if (record2.retry?.launching) {
65049
+ const nextAttempt = record2.retry.attempt + 1;
65050
+ patch(sessionId, (r) => {
65051
+ if (!r.retry?.launching) return;
65052
+ r.retry.attempt++;
65053
+ delete r.retry.launching;
65054
+ });
65055
+ event2({
65056
+ kind: "retry",
65057
+ data: {
65058
+ state: "retrying",
65059
+ source: record2.failure?.source ?? "runtime",
65060
+ runtime: runtimeInfo(),
65061
+ attempt: nextAttempt,
65062
+ maxAttempts: record2.retry.of,
65063
+ summary: record2.failure?.summary ?? record2.retry.reason,
65064
+ ...record2.failure?.detail ? { detail: record2.failure.detail } : {},
65065
+ ...record2.failure?.code ? { code: record2.failure.code } : {},
65066
+ sessionAction: record2.resumedFrom ? "resume" : "reset_replay",
65067
+ at: (/* @__PURE__ */ new Date()).toISOString()
65068
+ }
65069
+ });
65070
+ }
64701
65071
  try {
64702
65072
  const start = spawnable(cmd, client || stdinPrompt ? args2 : [...args2, prompt], {
64703
65073
  // Where this run works: the project, or — inside a delivery with a worktree of its
@@ -64881,34 +65251,79 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64881
65251
  const rendered = renderer?.failure?.() ?? (!taskCompleted && renderer?.background?.() ? "The agent exited with unfinished background tasks." : void 0);
64882
65252
  const said2 = spawnError ?? (silent ? silenceSaid(silenceFor) : spoken?.error ?? rendered);
64883
65253
  const failed2 = code !== 0 || spoken?.ok === false || !!rendered || silent || !!blocker;
64884
- const failure2 = failed2 && !asked ? silent ? { ...IDLE_FAILURE, reason: said2 ?? IDLE_FAILURE.reason } : spawnFailure ?? spoken?.failure ?? renderer?.executionFailure?.() ?? (!blocker ? held4.validationFailure : void 0) ?? { code: blocker ? "execution_blocked" : "execution_failed", level: 3, reason: said2 ?? blocker?.cause ?? `Agent exited with code ${code}.` } : void 0;
65254
+ const failure2 = failed2 && !asked ? silent ? makeFailure("runtime", said2 ?? IDLE_FAILURE.summary, { code: IDLE_FAILURE.code, detail: said2 ?? IDLE_FAILURE.summary }) : spawnFailure ?? spoken?.failure ?? renderer?.executionFailure?.() ?? (!blocker ? held4.validationFailure : void 0) ?? makeFailure("runtime", said2 ?? blocker?.cause ?? `Agent exited with code ${code}.`, {
65255
+ code: blocker ? "execution_blocked" : "execution_failed",
65256
+ detail: said2 ?? blocker?.cause ?? `Agent exited with code ${code}.`
65257
+ }) : void 0;
64885
65258
  const result = spoken ? spoken.result : renderer?.result();
64886
65259
  let retryPause;
64887
65260
  let retrying = false;
65261
+ let retryHistory = held4.retryHistory ? [...held4.retryHistory] : void 0;
65262
+ let sessionAction;
64888
65263
  if (failure2 && !sub && !taskCompleted) {
64889
65264
  const attempt2 = held4.retry?.attempt ?? 1;
64890
- const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff, !!held4.cloudExecution);
64891
- if ("pause" in decision) retryPause = decision.pause;
64892
- else {
64893
- const mark = runMark(sessionId, agentStartedAt);
64894
- const root2 = child.pid ? { pid: child.pid, since: agentStartedAt, identity: held4.agentIdentity } : void 0;
64895
- const stopped3 = () => client?.managedProcess ? connectionStopped(root2) : processesStopped(mark, root2);
64896
- const until = Date.now() + STOP_GRACE_MS + STOP_CLOSE_MS;
64897
- while (!stopped3() && Date.now() < until) await sleep4(100);
64898
- const session = structured && !spawnFailure ? resumeSessionId(held4) : void 0;
64899
- const recovery = agentRecovery({
64900
- stopped: stopped3(),
64901
- session,
64902
- replayable: held4.unspawned === true && !pendingOperations.size,
64903
- unconfirmedCleanup: pendingOperations.size > 0 || !!blocker || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, session))
64904
- });
64905
- if (recovery === "unsafe") retryPause = "unsafe";
64906
- else {
64907
- const pending = decision.plan;
65265
+ const missingSession = isSessionMissingFailure(failure2);
65266
+ const mark = runMark(sessionId, agentStartedAt);
65267
+ const root2 = child.pid ? { pid: child.pid, since: agentStartedAt, identity: held4.agentIdentity } : void 0;
65268
+ const stopped3 = () => client?.managedProcess ? connectionStopped(root2) : processesStopped(mark, root2);
65269
+ const until = Date.now() + STOP_GRACE_MS + STOP_CLOSE_MS;
65270
+ while (!stopped3() && Date.now() < until) await sleep4(100);
65271
+ const isStopped = stopped3();
65272
+ const session = structured && !spawnFailure && !missingSession ? resumeSessionId(held4) : void 0;
65273
+ const unconfirmedCleanup = pendingOperations.size > 0 || !!blocker || spoken?.cleanup?.status === "unconfirmed" || failure2.code === "codex_ownership_unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, session));
65274
+ const canResetReplay = isStopped && !unconfirmedCleanup && !pendingOperations.size && (held4.unspawned === true || structured && !hadEffects && !record2.resumedFrom);
65275
+ const recovery = missingSession ? canResetReplay ? "replay" : "unsafe" : agentRecovery({
65276
+ stopped: isStopped,
65277
+ session,
65278
+ replayable: canResetReplay,
65279
+ unconfirmedCleanup
65280
+ });
65281
+ sessionAction = recovery === "unsafe" ? "pause_unsafe" : recovery === "replay" ? "reset_replay" : "resume";
65282
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
65283
+ const retryRecord = {
65284
+ attempt: attempt2,
65285
+ source: failure2.source,
65286
+ runtime: runtimeInfo(),
65287
+ summary: failure2.summary,
65288
+ ...failure2.detail ? { detail: failure2.detail } : {},
65289
+ ...failure2.code ? { code: failure2.code } : {},
65290
+ sessionAction,
65291
+ at: nowIso
65292
+ };
65293
+ retryHistory = [...retryHistory ?? [], retryRecord];
65294
+ if (recovery === "unsafe") {
65295
+ retryPause = "unsafe";
65296
+ } else {
65297
+ const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff, !!held4.cloudExecution);
65298
+ if ("pause" in decision) {
65299
+ retryPause = decision.pause;
65300
+ } else {
65301
+ const pending = { ...decision.plan, sessionAction };
64908
65302
  patch(sessionId, (r) => {
64909
65303
  r.failure = failure2;
64910
- r.error = said2 ?? failure2.reason;
64911
- r.retry = { attempt: attempt2, of: pending.of, reason: failure2.reason, at: pending.at, since: held4.retry?.since ?? held4.startedAt, pending };
65304
+ r.error = said2 ?? failure2.summary;
65305
+ r.retryHistory = retryHistory;
65306
+ if (sessionAction === "reset_replay") {
65307
+ r.resumeId = void 0;
65308
+ r.unspawned = true;
65309
+ }
65310
+ r.retry = { attempt: attempt2, of: pending.of, reason: failure2.summary, at: pending.at, since: held4.retry?.since ?? held4.startedAt, pending };
65311
+ });
65312
+ event2({
65313
+ kind: "retry",
65314
+ data: {
65315
+ state: "waiting",
65316
+ source: failure2.source,
65317
+ runtime: runtimeInfo(),
65318
+ attempt: attempt2 + 1,
65319
+ maxAttempts: pending.of,
65320
+ summary: failure2.summary,
65321
+ ...failure2.detail ? { detail: failure2.detail } : {},
65322
+ ...failure2.code ? { code: failure2.code } : {},
65323
+ nextRetryAt: new Date(pending.at).toISOString(),
65324
+ sessionAction,
65325
+ at: nowIso
65326
+ }
64912
65327
  });
64913
65328
  log.write(`
64914
65329
  [board] ${retryLine(pending, attempt2)}
@@ -64917,11 +65332,44 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64917
65332
  retrying = true;
64918
65333
  }
64919
65334
  }
65335
+ if (retryPause && !stoppedByUser()) {
65336
+ event2({
65337
+ kind: "retry",
65338
+ data: {
65339
+ state: "paused",
65340
+ source: failure2.source,
65341
+ runtime: runtimeInfo(),
65342
+ attempt: attempt2,
65343
+ maxAttempts: held4.retry?.of ?? MAX_RETRY_ATTEMPTS,
65344
+ summary: failure2.summary,
65345
+ ...failure2.detail ? { detail: failure2.detail } : {},
65346
+ ...failure2.code ? { code: failure2.code } : {},
65347
+ sessionAction,
65348
+ at: nowIso
65349
+ }
65350
+ });
65351
+ }
64920
65352
  }
64921
65353
  asked ||= stoppedByUser();
64922
65354
  retrying &&= !asked;
64923
- const error62 = asked ? void 0 : joinNotes(said2 ?? failure2?.reason, retryPause && failure2?.source !== "invariant" ? pauseLine(retryPause) : void 0);
65355
+ const error62 = asked ? void 0 : joinNotes(said2 ?? failure2?.summary, retryPause ? pauseLine(retryPause) : void 0);
64924
65356
  const status = asked ? "stopped" : failed2 || code !== 0 ? "error" : "done";
65357
+ if (status === "done" && !sub && retryHistory?.length) {
65358
+ const lastRetry = retryHistory[retryHistory.length - 1];
65359
+ event2({
65360
+ kind: "retry",
65361
+ data: {
65362
+ state: "recovered",
65363
+ source: lastRetry.source,
65364
+ runtime: runtimeInfo(),
65365
+ attempt: held4.retry?.attempt ?? retryHistory.length + 1,
65366
+ maxAttempts: held4.retry?.of ?? MAX_RETRY_ATTEMPTS,
65367
+ summary: lastRetry.summary,
65368
+ ...lastRetry.code ? { code: lastRetry.code } : {},
65369
+ at: (/* @__PURE__ */ new Date()).toISOString()
65370
+ }
65371
+ });
65372
+ }
64925
65373
  const reported = spoken ? spoken.costUsd : renderer?.costUsd?.();
64926
65374
  const totals = reportsSessionTotal(record2.harness);
64927
65375
  const sessionTotal = totals ? reported : void 0;
@@ -64984,6 +65432,7 @@ ${result}
64984
65432
  error: error62,
64985
65433
  failure: failure2,
64986
65434
  retryPause,
65435
+ retryHistory,
64987
65436
  note,
64988
65437
  errorWhy,
64989
65438
  noteWhy,
@@ -65176,6 +65625,7 @@ var init_watch = __esm({
65176
65625
  init_idle();
65177
65626
  init_codex_background_types();
65178
65627
  init_retry();
65628
+ init_runtimes();
65179
65629
  init_failures();
65180
65630
  init_execution();
65181
65631
  init_refine2();
@@ -65190,7 +65640,7 @@ var init_watch = __esm({
65190
65640
  });
65191
65641
 
65192
65642
  // ../cli/src/commands/run.ts
65193
- import fs82 from "node:fs";
65643
+ import fs83 from "node:fs";
65194
65644
  import path82 from "node:path";
65195
65645
  async function cmdStartRun(action, args2, opts, program2 = "akb") {
65196
65646
  const { req, follow: follow2, print } = readRequest(action, args2, opts);
@@ -65417,7 +65867,7 @@ async function cmdSubStart(words, opts) {
65417
65867
  let prompt = words.join(" ");
65418
65868
  if (opts.file) {
65419
65869
  try {
65420
- prompt = fs82.readFileSync(path82.resolve(opts.file), "utf8");
65870
+ prompt = fs83.readFileSync(path82.resolve(opts.file), "utf8");
65421
65871
  } catch {
65422
65872
  die(`--file: cannot read ${opts.file}`, { kind: "run-refused" });
65423
65873
  }
@@ -65766,12 +66216,12 @@ var init_config3 = __esm({
65766
66216
  });
65767
66217
 
65768
66218
  // ../cli/src/lib/signals/migrate.ts
65769
- import fs83 from "node:fs";
66219
+ import fs84 from "node:fs";
65770
66220
  import path83 from "node:path";
65771
66221
  function readHandled() {
65772
66222
  let text5;
65773
66223
  try {
65774
- text5 = fs83.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
66224
+ text5 = fs84.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
65775
66225
  } catch {
65776
66226
  return [];
65777
66227
  }
@@ -65788,45 +66238,45 @@ function readHandled() {
65788
66238
  return held4;
65789
66239
  }
65790
66240
  function lift(from, into) {
65791
- fs83.mkdirSync(into, { recursive: true });
65792
- fs83.renameSync(from, path83.join(into, freeName(into, path83.basename(from))));
66241
+ fs84.mkdirSync(into, { recursive: true });
66242
+ fs84.renameSync(from, path83.join(into, freeName(into, path83.basename(from))));
65793
66243
  }
65794
66244
  function repoint(dir, from, into) {
65795
66245
  let entries2;
65796
66246
  try {
65797
- entries2 = fs83.readdirSync(dir, { withFileTypes: true });
66247
+ entries2 = fs84.readdirSync(dir, { withFileTypes: true });
65798
66248
  } catch {
65799
66249
  return;
65800
66250
  }
65801
66251
  for (const entry of entries2) {
65802
66252
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
65803
66253
  const file2 = path83.join(dir, entry.name);
65804
- const text5 = fs83.readFileSync(file2, "utf8");
65805
- if (text5.includes(from)) fs83.writeFileSync(file2, text5.split(from).join(into));
66254
+ const text5 = fs84.readFileSync(file2, "utf8");
66255
+ if (text5.includes(from)) fs84.writeFileSync(file2, text5.split(from).join(into));
65806
66256
  }
65807
66257
  }
65808
66258
  function dropIfEmpty(dir) {
65809
66259
  try {
65810
- fs83.rmdirSync(dir);
66260
+ fs84.rmdirSync(dir);
65811
66261
  } catch {
65812
66262
  }
65813
66263
  }
65814
66264
  function liftInbox() {
65815
- if (!fs83.existsSync(SIGNALS_OLD_INBOX)) return;
66265
+ if (!fs84.existsSync(SIGNALS_OLD_INBOX)) return;
65816
66266
  const oldFiles = path83.join(SIGNALS_OLD_INBOX, "files");
65817
- if (fs83.existsSync(oldFiles)) {
65818
- for (const entry of fs83.readdirSync(oldFiles, { withFileTypes: true })) {
66267
+ if (fs84.existsSync(oldFiles)) {
66268
+ for (const entry of fs84.readdirSync(oldFiles, { withFileTypes: true })) {
65819
66269
  if (entry.isFile()) lift(path83.join(oldFiles, entry.name), SIGNALS_FILES);
65820
66270
  }
65821
66271
  dropIfEmpty(oldFiles);
65822
66272
  }
65823
66273
  const held4 = new Set(readFolder(TRIAGE).map((signal2) => signal2.sourceId));
65824
- for (const entry of fs83.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
66274
+ for (const entry of fs84.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
65825
66275
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
65826
66276
  const from = path83.join(SIGNALS_OLD_INBOX, entry.name);
65827
66277
  const item = parse3(from);
65828
66278
  if (item && held4.has(item.sourceId)) {
65829
- fs83.rmSync(from, { force: true });
66279
+ fs84.rmSync(from, { force: true });
65830
66280
  continue;
65831
66281
  }
65832
66282
  if (item) held4.add(item.sourceId);
@@ -65838,7 +66288,7 @@ function liftInbox() {
65838
66288
  dropIfEmpty(SIGNALS_OLD_INBOX);
65839
66289
  }
65840
66290
  function liftHandled() {
65841
- if (!fs83.existsSync(SIGNALS_OLD_HANDLED)) return;
66291
+ if (!fs84.existsSync(SIGNALS_OLD_HANDLED)) return;
65842
66292
  const lines = readHandled();
65843
66293
  const held4 = /* @__PURE__ */ new Set([
65844
66294
  ...readFolder(TRIAGE).map((signal2) => signal2.sourceId),
@@ -65848,7 +66298,7 @@ function liftHandled() {
65848
66298
  for (const { sourceId, when } of lines) {
65849
66299
  if (held4.has(sourceId)) continue;
65850
66300
  held4.add(sourceId);
65851
- fs83.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
66301
+ fs84.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
65852
66302
  const name = freeName(SIGNALS_DISMISSED, fileName("", sourceId));
65853
66303
  const front = [
65854
66304
  "---",
@@ -65858,13 +66308,13 @@ function liftHandled() {
65858
66308
  "---",
65859
66309
  ""
65860
66310
  ];
65861
- fs83.writeFileSync(path83.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
66311
+ fs84.writeFileSync(path83.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
65862
66312
  `);
65863
66313
  }
65864
- fs83.rmSync(SIGNALS_OLD_HANDLED, { force: true });
66314
+ fs84.rmSync(SIGNALS_OLD_HANDLED, { force: true });
65865
66315
  }
65866
66316
  function migrateTriage() {
65867
- if (!fs83.existsSync(SIGNALS_OLD_INBOX) && !fs83.existsSync(SIGNALS_OLD_HANDLED)) return;
66317
+ if (!fs84.existsSync(SIGNALS_OLD_INBOX) && !fs84.existsSync(SIGNALS_OLD_HANDLED)) return;
65868
66318
  try {
65869
66319
  liftInbox();
65870
66320
  liftHandled();
@@ -65932,7 +66382,7 @@ var init_identity2 = __esm({
65932
66382
  });
65933
66383
 
65934
66384
  // ../cli/src/lib/signals/add.ts
65935
- import fs84 from "node:fs";
66385
+ import fs85 from "node:fs";
65936
66386
  import path84 from "node:path";
65937
66387
  import { createHash as createHash8 } from "node:crypto";
65938
66388
  function linkTitle(url2) {
@@ -65991,8 +66441,8 @@ ${incoming.summary}`);
65991
66441
  if (seen.status === "pending" || seen.status === "archived") return { ok: false, error: `${sayHit(seen)}.` };
65992
66442
  try {
65993
66443
  if (keep2) {
65994
- fs84.mkdirSync(SIGNALS_FILES, { recursive: true });
65995
- fs84.writeFileSync(keep2.at, keep2.data);
66444
+ fs85.mkdirSync(SIGNALS_FILES, { recursive: true });
66445
+ fs85.writeFileSync(keep2.at, keep2.data);
65996
66446
  }
65997
66447
  return { ok: true, signal: writeSignal({ ...incoming, sourceId }, formatStamp(/* @__PURE__ */ new Date()), drop.slug) };
65998
66448
  } catch (e) {
@@ -66103,7 +66553,7 @@ var init_signals = __esm({
66103
66553
  });
66104
66554
 
66105
66555
  // ../cli/src/commands/triage.ts
66106
- import fs85 from "node:fs";
66556
+ import fs86 from "node:fs";
66107
66557
  async function cmdTriageAdd(opts) {
66108
66558
  const title = (opts.title ?? "").trim();
66109
66559
  if (!title) die('say what it is: --title "<one line>"', { kind: "needs-input" });
@@ -66113,7 +66563,7 @@ async function cmdTriageAdd(opts) {
66113
66563
  let body = opts.text;
66114
66564
  if (opts.file !== void 0) {
66115
66565
  try {
66116
- body = fs85.readFileSync(opts.file, "utf8");
66566
+ body = fs86.readFileSync(opts.file, "utf8");
66117
66567
  } catch {
66118
66568
  die(`can't read ${opts.file} \u2014 write the item to a file, then pass its path`, { kind: "needs-input" });
66119
66569
  }
@@ -66167,21 +66617,21 @@ var init_previews = __esm({
66167
66617
  });
66168
66618
 
66169
66619
  // ../cli/src/commands/studio-preview.ts
66170
- import fs86 from "node:fs";
66620
+ import fs87 from "node:fs";
66171
66621
  import path85 from "node:path";
66172
66622
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
66173
66623
  import { spawnSync as spawnSync7 } from "node:child_process";
66174
66624
  function readFolder2(folder2, baseline = false) {
66175
- const root2 = fs86.realpathSync(folder2);
66625
+ const root2 = fs87.realpathSync(folder2);
66176
66626
  let count3 = 0, total = 0;
66177
66627
  const scan = (dir) => {
66178
- for (const e of fs86.readdirSync(dir, { withFileTypes: true })) {
66628
+ for (const e of fs87.readdirSync(dir, { withFileTypes: true })) {
66179
66629
  if (e.name.startsWith(".")) continue;
66180
66630
  const file2 = path85.join(dir, e.name);
66181
66631
  if (e.isSymbolicLink()) throw Error(`${file2}: symbolic links are not allowed`);
66182
66632
  if (e.isDirectory()) scan(file2);
66183
66633
  else {
66184
- const size = fs86.statSync(file2).size;
66634
+ const size = fs87.statSync(file2).size;
66185
66635
  total += size;
66186
66636
  if (++count3 > FILE_LIMITS.count || size > FILE_LIMITS.file || total > FILE_LIMITS.total) throw Error(`${file2}: Studio file limit exceeded`);
66187
66637
  }
@@ -66195,8 +66645,8 @@ function readFolder2(folder2, baseline = false) {
66195
66645
  }
66196
66646
  function unified(before, after2, file2, folder2) {
66197
66647
  const a = path85.join(folder2, "a"), b = path85.join(folder2, "b");
66198
- fs86.writeFileSync(a, before ?? "");
66199
- fs86.writeFileSync(b, after2 ?? "");
66648
+ fs87.writeFileSync(a, before ?? "");
66649
+ fs87.writeFileSync(b, after2 ?? "");
66200
66650
  const result = spawnSync7("git", ["diff", "--no-index", "--text", "--no-ext-diff", "--no-color", "--unified=3", before === null ? "/dev/null" : a, after2 === null ? "/dev/null" : b], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
66201
66651
  if (result.error || result.status !== 0 && result.status !== 1) throw Error(`${file2}: ${result.error?.message ?? result.stderr}`);
66202
66652
  const lines = result.stdout.split("\n"), start = lines.findIndex((l) => l.startsWith("--- "));
@@ -66212,12 +66662,12 @@ async function cmdStudioPreview(id2, opts) {
66212
66662
  const draft = readFolder2(path85.resolve(opts.folder)), base = opts.base === "empty" ? null : readFolder2(path85.resolve(opts.base), true);
66213
66663
  const version2 = readVersion2(draft.files), baseVersion = base && readVersion2(base.files);
66214
66664
  if (base ? !version2 || !baseVersion || JSON.stringify(version2) !== JSON.stringify(baseVersion) : version2 !== null) throw Error("version.json: existing Studios need matching baseline and draft versions; use --base empty only for a new Studio without version.json");
66215
- fs86.mkdirSync(staging, { recursive: true });
66665
+ fs87.mkdirSync(staging, { recursive: true });
66216
66666
  const review = { version: 2, base: base && baseVersion ? { ...baseVersion, fingerprint: base.fingerprint } : null, fingerprint: draft.fingerprint, files: [] };
66217
66667
  const save3 = (file2, bytes2) => {
66218
66668
  const target = path85.join(staging, file2);
66219
- fs86.mkdirSync(path85.dirname(target), { recursive: true });
66220
- fs86.writeFileSync(target, bytes2);
66669
+ fs87.mkdirSync(path85.dirname(target), { recursive: true });
66670
+ fs87.writeFileSync(target, bytes2);
66221
66671
  return file2;
66222
66672
  };
66223
66673
  const paths = [.../* @__PURE__ */ new Set([...Object.keys(base?.files ?? {}), ...Object.keys(draft.files)])].filter((p) => p !== VERSION_FILE).sort();
@@ -66225,16 +66675,16 @@ async function cmdStudioPreview(id2, opts) {
66225
66675
  const before = base?.files[file2] ?? null, after2 = draft.files[file2] ?? null;
66226
66676
  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)) } : {} });
66227
66677
  }
66228
- for (const p of ["a", "b"]) fs86.rmSync(path85.join(staging, p), { force: true });
66678
+ for (const p of ["a", "b"]) fs87.rmSync(path85.join(staging, p), { force: true });
66229
66679
  if (!parseReview(review)) throw Error("generated review is invalid");
66230
66680
  save3("review.json", JSON.stringify(review, null, 2) + "\n");
66231
- fs86.mkdirSync(path85.dirname(destination), { recursive: true });
66232
- if (fs86.existsSync(destination)) {
66233
- fs86.renameSync(destination, backup);
66681
+ fs87.mkdirSync(path85.dirname(destination), { recursive: true });
66682
+ if (fs87.existsSync(destination)) {
66683
+ fs87.renameSync(destination, backup);
66234
66684
  moved = true;
66235
66685
  }
66236
- fs86.renameSync(staging, destination);
66237
- fs86.rmSync(backup, { recursive: true, force: true });
66686
+ fs87.renameSync(staging, destination);
66687
+ fs87.rmSync(backup, { recursive: true, force: true });
66238
66688
  const tag = `<Studio src=".assets/${id2}/studio-review/review.json" />`;
66239
66689
  const prefix = `.assets/${id2}/studio-review/`;
66240
66690
  const attachments = review.files.filter((f) => f.path !== "STUDIO.md" && f.diff);
@@ -66248,11 +66698,11 @@ ${items}
66248
66698
  say([tag, files].filter(Boolean).join("\n\n"));
66249
66699
  return { file: path85.join(destination, "review.json"), tag, files };
66250
66700
  } catch (error62) {
66251
- if (moved && !fs86.existsSync(destination)) fs86.renameSync(backup, destination);
66701
+ if (moved && !fs87.existsSync(destination)) fs87.renameSync(backup, destination);
66252
66702
  if (error62 && typeof error62 === "object" && "kind" in error62) throw error62;
66253
66703
  die(error62 instanceof Error ? error62.message : String(error62), "bad-args");
66254
66704
  } finally {
66255
- fs86.rmSync(staging, { recursive: true, force: true });
66705
+ fs87.rmSync(staging, { recursive: true, force: true });
66256
66706
  }
66257
66707
  }
66258
66708
  var readVersion2;
@@ -66483,8 +66933,7 @@ function declareRuns(program2, cli) {
66483
66933
  await boardless(this, cli, (_, location) => taskReview(id2, this.opts(), location));
66484
66934
  });
66485
66935
  const questionOps = [];
66486
- const opInOrder = ordered(questionOps);
66487
- withShared(task.command("update-questions")).argument("<task>").summary("edit the task's open questions, like `raw update-questions`").description("Positions are 1-based, in the order of the card\u2019s `questions:` (`akb task show`). --option, --recommended-option and --mode attach to the --append or --update before them.").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 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")).addOption(new Option("--agent <name>").hideHelp().argParser(opInOrder("agent"))).action(async function(id2) {
66936
+ withQuestionOptions(withShared(task.command("update-questions")).argument("<task>").summary("append, rewrite, or remove open questions").description("Edit the current Runner task locally for synchronization, or save another task in Cloud. Edits apply in order at 1-based positions. Choices and mode apply to the preceding --append or --update.\nSee akb guide update-questions."), questionOps).action(async function(id2) {
66488
66937
  await boardless(this, cli, (_, location) => taskUpdateQuestions(id2, questionOps, location));
66489
66938
  });
66490
66939
  withShared(task.command("chat")).argument("<task>").argument("[message...]").summary("read task chat history, follow or stop its reply, or send a message").description("Without a message, read the last 20 messages and the chat reply state separately from task execution. --follow tracks only the reply present at the start; Ctrl+C disconnects locally. --stop stops only that reply. --follow --json emits JSON Lines; other modes return one JSON object.").option("--limit <n>", "show the last n messages, oldest first (default: 20)", intInRange(1, Number.MAX_SAFE_INTEGER)).option("--all", "show all retained messages").option("--follow", "follow this reply to its result, then exit").option("--stop", "request stopping only the current chat reply").addHelpText("after", '\nExamples:\n akb task chat WC-12\n akb task chat 12 --all --json\n akb task chat 12 --follow --json\n akb task chat 12 --stop\n akb task chat 12 "Revise the draft"').action(async function(id2, message) {
@@ -66820,6 +67269,7 @@ var init_agent2 = __esm({
66820
67269
  init_agent_check();
66821
67270
  init_harnesses();
66822
67271
  init_moved();
67272
+ init_question_options();
66823
67273
  init_shared2();
66824
67274
  REVIEW_FLOW_HELP = `
66825
67275
  Review examples
@@ -66837,14 +67287,14 @@ Review examples
66837
67287
  });
66838
67288
 
66839
67289
  // ../cli/src/kanban.ts
66840
- import fs89 from "node:fs";
67290
+ import fs90 from "node:fs";
66841
67291
  import { fileURLToPath as fileURLToPath4 } from "node:url";
66842
67292
 
66843
67293
  // ../cli/src/lib/cli/akb.ts
66844
67294
  init_agent2();
66845
67295
 
66846
67296
  // ../cli/src/lib/cli/setup.ts
66847
- import fs88 from "node:fs";
67297
+ import fs89 from "node:fs";
66848
67298
  import path87 from "node:path";
66849
67299
  import { fileURLToPath as fileURLToPath3 } from "node:url";
66850
67300
 
@@ -66853,7 +67303,7 @@ init_board_cli();
66853
67303
  init_config_template();
66854
67304
  init_io();
66855
67305
  init_version();
66856
- import fs87 from "node:fs";
67306
+ import fs88 from "node:fs";
66857
67307
  import path86 from "node:path";
66858
67308
  import { spawnSync as spawnSync9 } from "node:child_process";
66859
67309
  var NAME = "wildcrane";
@@ -66875,7 +67325,7 @@ var Report = class {
66875
67325
  for (const line of this.notes) say(` ! ${line}`);
66876
67326
  }
66877
67327
  };
66878
- var read4 = (file2) => fs87.existsSync(file2) ? fs87.readFileSync(file2, "utf8") : null;
67328
+ var read4 = (file2) => fs88.existsSync(file2) ? fs88.readFileSync(file2, "utf8") : null;
66879
67329
  async function boardMove(root2, args2, board2) {
66880
67330
  const where = board2 ? ["--board", board2] : ["--dir", root2];
66881
67331
  const code = await runBoard([...args2, ...where], { program: "akb raw", cwd: root2 });
@@ -66898,8 +67348,8 @@ async function cmdUpdate2(ctx) {
66898
67348
  async function repairBoard(root2, report3, named2) {
66899
67349
  const legacy = path86.join(root2, "docs", "kanban");
66900
67350
  const kept2 = path86.join(root2, ".akb", "kanban");
66901
- const board2 = named2 ?? (fs87.existsSync(legacy) ? legacy : kept2);
66902
- if (!fs87.existsSync(board2)) {
67351
+ const board2 = named2 ?? (fs88.existsSync(legacy) ? legacy : kept2);
67352
+ if (!fs88.existsSync(board2)) {
66903
67353
  report3.notes.push("\u672A\u627E\u5230\u770B\u677F\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002");
66904
67354
  return false;
66905
67355
  }
@@ -66975,7 +67425,7 @@ function declareSetup(program2, cli) {
66975
67425
  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");
66976
67426
  const where = (cmd) => {
66977
67427
  const dir = path87.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
66978
- if (!fs88.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
67428
+ if (!fs89.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
66979
67429
  return dir;
66980
67430
  };
66981
67431
  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() {
@@ -67026,7 +67476,7 @@ function invokedDirectly() {
67026
67476
  const entry = process.argv[1];
67027
67477
  if (!entry) return false;
67028
67478
  try {
67029
- return fs89.realpathSync(entry) === fs89.realpathSync(SELF2);
67479
+ return fs90.realpathSync(entry) === fs90.realpathSync(SELF2);
67030
67480
  } catch {
67031
67481
  return false;
67032
67482
  }