wildcrane 0.11.80 → 0.11.81

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.
Files changed (2) hide show
  1. package/dist/kanban.mjs +409 -102
  2. package/package.json +1 -1
package/dist/kanban.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.80 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
2
+ // ai4kanban 0.11.81 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
3
3
  // Do not edit: every change belongs in cli/src/, and a build overwrites this file.
4
4
  import { createRequire as __ai4kanbanRequire } from 'node:module'
5
5
  const require = __ai4kanbanRequire(import.meta.url)
@@ -20943,41 +20943,61 @@ function reviewLayers(plan) {
20943
20943
  }
20944
20944
  return layers;
20945
20945
  }
20946
- function parseReviewPlan(value, previews) {
20947
- const plan = reviewPlanSchema.parse(value);
20948
- if (previews) for (const n of plan ?? []) for (const p of n.previews) {
20949
- if (!previews.includes(p)) throw new Error(`Preview ${p} is not defined in this Studio.`);
20946
+ function parseReviewPlan(value) {
20947
+ return reviewPlanSchema.parse(value);
20948
+ }
20949
+ function reviewNames(catalog) {
20950
+ return catalog.map(({ id: id2, title }) => {
20951
+ const labels = Object.values(title ?? {}).map((label2) => label2.trim()).filter(Boolean);
20952
+ return { id: id2, labels: labels.length ? [...new Set(labels)] : [id2] };
20953
+ });
20954
+ }
20955
+ function previewError(message, names2) {
20956
+ const available = names2.map(({ labels, id: id2 }) => `${labels.join(" / ")} (${id2})`).join(", ") || "none";
20957
+ return new Error(`${message} Available Previews: ${available}. Use a listed name in a flow or its ID in a JSON plan. Define custom Previews before using them. A Preview is a draft or result for review. Keep task context in the card body.`);
20958
+ }
20959
+ function validateReviewPreviews(plan, catalog, { saved = false } = {}) {
20960
+ const prerequisites = new Set((plan ?? []).flatMap((node2) => node2.after));
20961
+ const ids = new Set(catalog?.map((p) => p.id));
20962
+ for (const node2 of plan ?? []) {
20963
+ if (node2.previews.length) {
20964
+ if (!catalog) throw new Error("Preview outputs are unavailable; update Runner and try again.");
20965
+ const unknown2 = node2.previews.find((preview) => !ids.has(preview));
20966
+ if (unknown2) throw previewError(`Preview ${unknown2} is not defined for review node "${node2.id}".`, reviewNames(catalog));
20967
+ } else if (!saved && node2.kind !== "work") {
20968
+ const handoff2 = (node2.id === HANDOFF || node2.id === HANDOFF_WITH_COLLISION) && node2.after.length && !prerequisites.has(node2.id);
20969
+ if (!handoff2) throw previewError(
20970
+ `Review node "${node2.id}" needs at least one Preview. Use an empty plan for no extra review.`,
20971
+ reviewNames(catalog ?? [])
20972
+ );
20973
+ }
20950
20974
  }
20951
20975
  return plan;
20952
20976
  }
20953
20977
  function parseReviewFlow(flow, catalog) {
20954
20978
  if (flow === "") return [];
20955
20979
  if (!catalog) throw new Error("Preview outputs are unavailable; update Runner and try again.");
20956
- const names2 = catalog.map(({ id: id2, title }) => {
20957
- const labels = Object.values(title ?? {}).map((label2) => label2.trim()).filter(Boolean);
20958
- return { id: id2, labels: labels.length ? [...new Set(labels)] : [id2] };
20959
- });
20960
- const available = names2.map(({ labels }) => labels.join(" / ")).join(", ") || "none";
20980
+ const names2 = reviewNames(catalog);
20961
20981
  const seen = /* @__PURE__ */ new Set();
20962
20982
  const nodes = [];
20963
20983
  let after2 = [];
20964
- for (const group of flow.split("->")) {
20984
+ for (const [index, group] of flow.split("->").entries()) {
20965
20985
  const current = group.split("+").map((entry) => {
20966
20986
  const name = entry.trim();
20967
- if (!name) throw new Error("The review flow contains an empty Preview name.");
20987
+ if (!name) throw previewError(`Review flow group ${index + 1} contains an empty Preview name.`, names2);
20968
20988
  const matches = names2.filter(({ labels }) => labels.includes(name));
20969
20989
  if (matches.length !== 1) {
20970
- throw new Error(`${matches.length ? "Ambiguous" : "Unknown"} Preview "${name}". Available Previews: ${available}.`);
20990
+ throw previewError(`${matches.length ? "Ambiguous" : "Unknown"} Preview "${name}" in review flow group ${index + 1}.`, names2);
20971
20991
  }
20972
20992
  const { id: id2 } = matches[0];
20973
- if (seen.has(id2)) throw new Error(`Repeated Preview "${name}". Available Previews: ${available}.`);
20993
+ if (seen.has(id2)) throw previewError(`Repeated Preview "${name}" in review flow group ${index + 1}.`, names2);
20974
20994
  seen.add(id2);
20975
20995
  nodes.push({ id: id2, after: after2, previews: [id2] });
20976
20996
  return id2;
20977
20997
  });
20978
20998
  after2 = current;
20979
20999
  }
20980
- nodes.push({ id: seen.has("delivery-handoff") ? "delivery-handoff:flow" : "delivery-handoff", after: after2, previews: [] });
21000
+ nodes.push({ id: seen.has(HANDOFF) ? HANDOFF_WITH_COLLISION : HANDOFF, after: after2, previews: [] });
20981
21001
  return parseReviewPlan(nodes);
20982
21002
  }
20983
21003
  function readReviewPlan(plan) {
@@ -21013,7 +21033,7 @@ function reviewInstruction(authorization) {
21013
21033
  case "stages":
21014
21034
  return [
21015
21035
  "Work only on these unlocked stages: " + authorization.nodes.map((node2) => node2.id).join(", "),
21016
- ...authorization.nodes.map((node2) => `- ${node2.id}: ${node2.previews.length ? node2.previews.join(", ") : "card body"}`)
21036
+ ...authorization.nodes.map((node2) => `- ${node2.id}: ${node2.previews.length ? node2.previews.join(", ") : "no Preview"}`)
21017
21037
  ].join("\n");
21018
21038
  case "delivery":
21019
21039
  return "Stages complete. Follow Studio delivery checks.";
@@ -21039,7 +21059,7 @@ function reviewBoundary(review, assigned) {
21039
21059
  "Read akb task review before reporting running/done with its revision. Sync content and assets before done. Revise a stage before changing its approved output. Only stage approval accepts reviewable outputs."
21040
21060
  ].join("\n");
21041
21061
  }
21042
- var id, reviewNodeSchema, reviewPlanSchema;
21062
+ var id, reviewNodeSchema, reviewPlanSchema, HANDOFF, HANDOFF_WITH_COLLISION;
21043
21063
  var init_review_plan = __esm({
21044
21064
  "src/lib/shared/review-plan.ts"() {
21045
21065
  "use strict";
@@ -21058,6 +21078,8 @@ var init_review_plan = __esm({
21058
21078
  ctx.addIssue({ code: "custom", message: e.message });
21059
21079
  }
21060
21080
  }).nullable();
21081
+ HANDOFF = "delivery-handoff";
21082
+ HANDOFF_WITH_COLLISION = "delivery-handoff:flow";
21061
21083
  }
21062
21084
  });
21063
21085
 
@@ -37815,23 +37837,15 @@ function goalCatalog(held4, studio, definitions) {
37815
37837
  if (!builtIn && definitions.length) die("Preview outputs are unavailable; update Runner and try again.");
37816
37838
  return builtIn && effectivePreviewCatalog(builtIn, definitions);
37817
37839
  }
37818
- function checkGoalReview(held4, studio, value, definitions = []) {
37819
- const catalog = goalCatalog(held4, studio, definitions);
37820
- try {
37821
- const plan = parseReviewPlan(value);
37822
- if (plan?.some((n) => n.previews.length) && !catalog) die("Preview outputs are unavailable; update Runner and try again.");
37823
- return parseReviewPlan(plan, catalog?.map((p) => p.id));
37824
- } catch (e) {
37825
- return die(e.message);
37826
- }
37827
- }
37828
37840
  function goalReview(held4, studio, opts, previous, definitions) {
37841
+ const catalog = goalCatalog(held4, studio, definitions);
37829
37842
  if (opts.review !== void 0) {
37830
37843
  if (opts.reviewFile !== void 0) die("Use either --review or --review-file.");
37831
- return parseReviewFlow(opts.review, goalCatalog(held4, studio, definitions));
37844
+ return parseReviewFlow(opts.review, catalog);
37832
37845
  }
37833
- const value = opts.reviewFile === void 0 ? previous : JSON.parse(fs16.readFileSync(opts.reviewFile, "utf8"));
37834
- return checkGoalReview(held4, studio, value, definitions);
37846
+ const value = opts.reviewFile === void 0 ? readReviewPlan(previous) : JSON.parse(fs16.readFileSync(opts.reviewFile, "utf8"));
37847
+ const saved = opts.reviewFile === void 0 && opts.previewDefinitionsFile === void 0 && opts.studio === void 0;
37848
+ return validateReviewPreviews(parseReviewPlan(value), catalog, { saved });
37835
37849
  }
37836
37850
  function cmdGoalPreviews(studio, held4 = loadGoals().held) {
37837
37851
  const id2 = studioOf(held4, studio);
@@ -41547,14 +41561,15 @@ function backoffMs(attempt2, random = Math.random) {
41547
41561
  const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt2 - 2));
41548
41562
  return Math.round(step * (1 - 0.25 * random()));
41549
41563
  }
41550
- function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs) {
41564
+ function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs, task = false) {
41551
41565
  if (!Number.isSafeInteger(attempt2) || attempt2 < 1 || failure2.level === 3) return { pause: "needs-review" };
41552
41566
  const of = failure2.level === 1 ? 2 : 4;
41553
41567
  if (attempt2 >= of) return { pause: "limit" };
41554
41568
  const delay3 = failure2.retryAfterMs;
41555
41569
  const valid = delay3 !== void 0 && !Number.isNaN(delay3) && delay3 >= 0;
41556
41570
  const wait = valid ? delay3 : failure2.level === 1 ? 0 : backoff(attempt2 + 1);
41557
- if (wait > CAP_MS) return { pause: "wait-too-long" };
41571
+ const cap = task && failure2.code === "rate_limited" && valid ? 24 * 60 * 6e4 : CAP_MS;
41572
+ if (wait > cap) return { pause: "wait-too-long" };
41558
41573
  return { plan: { at: now + wait, of, failure: failure2 } };
41559
41574
  }
41560
41575
  function readFailure(raw) {
@@ -41563,12 +41578,12 @@ function readFailure(raw) {
41563
41578
  if (typeof code !== "string" || !code || typeof reason !== "string" || level2 !== 1 && level2 !== 2 && level2 !== 3) return;
41564
41579
  return { code, level: level2, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source2) ? { source: source2 } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
41565
41580
  }
41566
- function readRetryPlan(raw, attempt2) {
41581
+ function readRetryPlan(raw, attempt2, task = false) {
41567
41582
  if (!raw || typeof raw !== "object") return;
41568
41583
  const { at, of, failure: rawFailure } = raw;
41569
41584
  const failure2 = readFailure(rawFailure);
41570
41585
  if (!failure2 || typeof at !== "number" || !Number.isFinite(at)) return;
41571
- const decision = planRetry(failure2, attempt2);
41586
+ const decision = planRetry(failure2, attempt2, Date.now(), backoffMs, task);
41572
41587
  if ("plan" in decision && of === decision.plan.of) return { at, of, failure: failure2 };
41573
41588
  }
41574
41589
  function pauseLine(pause2, zh = translating()) {
@@ -41922,7 +41937,7 @@ var init_package = __esm({
41922
41937
  "package.json"() {
41923
41938
  package_default = {
41924
41939
  name: "wildcrane",
41925
- version: "0.11.80",
41940
+ version: "0.11.81",
41926
41941
  akbContract: 27,
41927
41942
  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.",
41928
41943
  keywords: [
@@ -42942,6 +42957,7 @@ function antigravityPrices(at) {
42942
42957
  return {
42943
42958
  "gemini-4-carbon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
42944
42959
  "gemini-4-argon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
42960
+ "gemini-4-neon": { input: 3, cachedInput: 0.15, output: 15 },
42945
42961
  "gemini-4-hydrogen": { input: 1.5, cachedInput: 0.075, output: 7.5 },
42946
42962
  "gemini-3.8-flash": { input: flash, cachedInput: flash / 10, output: flash * 5 }
42947
42963
  };
@@ -43283,8 +43299,36 @@ function bytesField(data, field2) {
43283
43299
  if (number4 === field2 && value instanceof Uint8Array) return value;
43284
43300
  }
43285
43301
  }
43302
+ function varintField(data, field2) {
43303
+ if (!(data instanceof Uint8Array)) return;
43304
+ for (const [number4, value] of fields(data)) {
43305
+ if (number4 === field2 && typeof value === "number") return value;
43306
+ }
43307
+ }
43308
+ function stepIndices(data) {
43309
+ const out = [];
43310
+ for (const [field2, value] of fields(data)) {
43311
+ if (field2 !== 2) continue;
43312
+ if (typeof value === "number") out.push(value);
43313
+ else {
43314
+ const offset = { value: 0 };
43315
+ while (offset.value < value.length) out.push(varint(value, offset));
43316
+ }
43317
+ }
43318
+ return out;
43319
+ }
43320
+ function recordedContextLimit(data) {
43321
+ const limit = varintField(bytesField(bytesField(bytesField(data, 1), 9), 10), 4);
43322
+ return limit !== void 0 && Number.isSafeInteger(limit) && limit > 0 ? limit : void 0;
43323
+ }
43324
+ function stepUuid(stepRow, index) {
43325
+ if (!Number.isSafeInteger(index) || index < 0) return;
43326
+ const id2 = bytesField(stepRow.get(index)?.metadata, 12);
43327
+ return id2?.length === 36 ? id2 : void 0;
43328
+ }
43286
43329
  function antigravityRecordedModels(session, steps) {
43287
43330
  const found2 = /* @__PURE__ */ new Map();
43331
+ if (!steps.size) return found2;
43288
43332
  const file2 = antigravityConversationFile(session);
43289
43333
  if (!file2 || !existsSync(file2)) return found2;
43290
43334
  try {
@@ -43292,26 +43336,31 @@ function antigravityRecordedModels(session, steps) {
43292
43336
  if (!sqlite) return found2;
43293
43337
  const db = new sqlite.DatabaseSync(file2, { readOnly: true });
43294
43338
  try {
43295
- const prompt = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
43339
+ const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
43340
+ const promptIds = /* @__PURE__ */ new Map();
43341
+ const promptUuid = (prompt) => {
43342
+ if (!promptIds.has(prompt)) promptIds.set(prompt, stepUuid(stepRow, prompt));
43343
+ return promptIds.get(prompt);
43344
+ };
43345
+ const groups = /* @__PURE__ */ new Map();
43346
+ for (const [index, { prompt }] of steps) {
43347
+ if (!Number.isSafeInteger(index) || index < 0) continue;
43348
+ const id2 = stepUuid(stepRow, index) ?? promptUuid(prompt);
43349
+ if (!id2) continue;
43350
+ const uuid3 = utf8(id2);
43351
+ let group = groups.get(uuid3);
43352
+ if (!group) groups.set(uuid3, group = { id: id2, steps: /* @__PURE__ */ new Set() });
43353
+ group.steps.add(index);
43354
+ }
43296
43355
  const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
43297
- for (const index of new Set([...steps.values()].map((step) => step.prompt))) {
43298
- const id2 = bytesField(prompt.get(index)?.metadata, 12);
43299
- if (id2?.length !== 36) continue;
43356
+ for (const [uuid3, { id: id2, steps: groupSteps }] of groups) {
43300
43357
  const key = Buffer.concat([Buffer.from([34, 36]), id2]);
43301
43358
  for (const { data } of generations.iterate(key)) {
43302
- if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== utf8(id2)) continue;
43359
+ if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== uuid3) continue;
43303
43360
  const model = utf8(bytesField(bytesField(data, 1), 19)) || void 0;
43304
- const record2 = (step) => {
43305
- if (steps.get(step)?.prompt !== index) return;
43361
+ for (const step of stepIndices(data)) {
43362
+ if (!groupSteps.has(step)) continue;
43306
43363
  found2.set(step, found2.has(step) && found2.get(step) !== model ? void 0 : model);
43307
- };
43308
- for (const [field2, value] of fields(data)) {
43309
- if (field2 !== 2) continue;
43310
- if (typeof value === "number") record2(value);
43311
- else {
43312
- const offset = { value: 0 };
43313
- while (offset.value < value.length) record2(varint(value, offset));
43314
- }
43315
43364
  }
43316
43365
  }
43317
43366
  }
@@ -43323,6 +43372,38 @@ function antigravityRecordedModels(session, steps) {
43323
43372
  return /* @__PURE__ */ new Map();
43324
43373
  }
43325
43374
  }
43375
+ function antigravityRecordedContextLimit(session, step, prompt) {
43376
+ if (!Number.isSafeInteger(step) || step < 0) return;
43377
+ const file2 = antigravityConversationFile(session);
43378
+ if (!file2 || !existsSync(file2)) return;
43379
+ try {
43380
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
43381
+ if (!sqlite) return;
43382
+ const db = new sqlite.DatabaseSync(file2, { readOnly: true });
43383
+ try {
43384
+ const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
43385
+ const id2 = stepUuid(stepRow, step) ?? stepUuid(stepRow, prompt);
43386
+ if (!id2) return;
43387
+ const key = Buffer.concat([Buffer.from([34, 36]), id2]);
43388
+ const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
43389
+ let found2;
43390
+ let matched = false;
43391
+ for (const { data } of generations.iterate(key)) {
43392
+ if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== utf8(id2)) continue;
43393
+ if (!stepIndices(data).includes(step)) continue;
43394
+ const limit = recordedContextLimit(data);
43395
+ if (matched && found2 !== limit) return;
43396
+ found2 = limit;
43397
+ matched = true;
43398
+ }
43399
+ return found2;
43400
+ } finally {
43401
+ db.close();
43402
+ }
43403
+ } catch {
43404
+ return;
43405
+ }
43406
+ }
43326
43407
  var utf8;
43327
43408
  var init_antigravity_session = __esm({
43328
43409
  "src/lib/agent/wire/antigravity-session.ts"() {
@@ -43357,6 +43438,20 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
43357
43438
  let stderr = "";
43358
43439
  let context;
43359
43440
  let contextStep = -1;
43441
+ let contextPrompt = -1;
43442
+ let contextLimitStep = -1;
43443
+ let contextLimitLookedAt = 0;
43444
+ const resolveContextLimit = (now) => {
43445
+ if (!context || !session || contextStep < 0 || contextLimitStep === contextStep) return;
43446
+ const at = Date.now();
43447
+ if (!now && at - contextLimitLookedAt < CONTEXT_LOOK_EVERY_MS) return;
43448
+ contextLimitLookedAt = at;
43449
+ const limit = antigravityRecordedContextLimit(session, contextStep, contextPrompt);
43450
+ if (limit !== void 0) {
43451
+ context = { used: context.used, limit };
43452
+ contextLimitStep = contextStep;
43453
+ }
43454
+ };
43360
43455
  const started = Date.now();
43361
43456
  let cost;
43362
43457
  let incomplete = false;
@@ -43422,10 +43517,13 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
43422
43517
  const index = num2(step.step_index);
43423
43518
  if (step.state === "DONE" && Number.isSafeInteger(index) && step.step_index === index && index > contextStep) {
43424
43519
  contextStep = index;
43520
+ contextPrompt = prompt;
43521
+ contextLimitStep = -1;
43522
+ contextLimitLookedAt = 0;
43425
43523
  const u = obj2(step.usage);
43426
43524
  const counts = [u.input_tokens, u.cache_read_tokens];
43427
- const prompt2 = counts.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0) ? num2(u.input_tokens) + num2(u.cache_read_tokens) : 0;
43428
- context = prompt2 > 0 && Number.isFinite(prompt2) ? { used: prompt2 } : void 0;
43525
+ const promptTokens = counts.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0) ? num2(u.input_tokens) + num2(u.cache_read_tokens) : 0;
43526
+ context = promptTokens > 0 && Number.isFinite(promptTokens) ? { used: promptTokens } : void 0;
43429
43527
  }
43430
43528
  if (step.state === "DONE" && step.usage && !counted.has(index)) {
43431
43529
  counted.add(index);
@@ -43478,6 +43576,7 @@ ${imageError(target, reason || str2(step.state))}
43478
43576
  return "";
43479
43577
  }
43480
43578
  session ||= str2(result.conversation_id) || void 0;
43579
+ resolveContextLimit(true);
43481
43580
  terminal = true;
43482
43581
  final = typeof result.response === "string" ? result.response : void 0;
43483
43582
  const total = usageOf(result.usage);
@@ -43509,6 +43608,7 @@ ${imageError(target, reason || str2(step.state))}
43509
43608
  },
43510
43609
  flush() {
43511
43610
  const text5 = reader.flush();
43611
+ resolveContextLimit(true);
43512
43612
  if (pendingCosts.size) {
43513
43613
  const models = session ? antigravityRecordedModels(session, pendingCosts) : void 0;
43514
43614
  for (const [index, { usage: usage3 }] of pendingCosts) estimate(models?.get(index), usage3);
@@ -43531,7 +43631,10 @@ ${imageError(target, reason || str2(step.state))}
43531
43631
  usage: () => used,
43532
43632
  costUsd: () => cost,
43533
43633
  costIncomplete: () => incomplete || void 0,
43534
- context: () => context,
43634
+ context: () => {
43635
+ resolveContextLimit(false);
43636
+ return context;
43637
+ },
43535
43638
  failure: () => failure2 || imageFailure,
43536
43639
  terminalFailure: () => terminal && !!classified,
43537
43640
  executionFailure: () => classified ?? (imageFailure ? { code: "image_read_failed", level: 3, reason: imageFailure } : void 0),
@@ -43539,7 +43642,7 @@ ${imageError(target, reason || str2(step.state))}
43539
43642
  activity: events.activity
43540
43643
  };
43541
43644
  }
43542
- var KINDS, zero, usageOf, add, imagePath;
43645
+ var CONTEXT_LOOK_EVERY_MS, KINDS, zero, usageOf, add, imagePath;
43543
43646
  var init_antigravity = __esm({
43544
43647
  "src/lib/agent/wire/antigravity.ts"() {
43545
43648
  "use strict";
@@ -43549,6 +43652,7 @@ var init_antigravity = __esm({
43549
43652
  init_json();
43550
43653
  init_stream();
43551
43654
  init_antigravity_session();
43655
+ CONTEXT_LOOK_EVERY_MS = 250;
43552
43656
  KINDS = {
43553
43657
  run_command: "execute",
43554
43658
  command_status: "execute",
@@ -49240,6 +49344,47 @@ var init_roster = __esm({
49240
49344
  }
49241
49345
  });
49242
49346
 
49347
+ // src/lib/shared/delivery-evidence.ts
49348
+ function approvedCardRequirements(text5) {
49349
+ const { meta: meta3, body } = parseFrontmatter(text5);
49350
+ const out = [];
49351
+ if (meta3?.title) out.push(`# ${meta3.title}`, "");
49352
+ const opening = [];
49353
+ const sections = [];
49354
+ let keeping = false;
49355
+ let started = false;
49356
+ for (const line of body.split("\n")) {
49357
+ if (/^##(?!#)\s/.test(line)) {
49358
+ started = true;
49359
+ keeping = isApproved(line);
49360
+ if (keeping) sections.push("", line);
49361
+ continue;
49362
+ }
49363
+ if (line.trim() === "<!-- agent -->") continue;
49364
+ if (!started) opening.push(line);
49365
+ else if (keeping) sections.push(line);
49366
+ }
49367
+ out.push(opening.join("\n").trim());
49368
+ out.push(sections.join("\n").trim());
49369
+ return out.filter(Boolean).join("\n\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
49370
+ }
49371
+ var APPROVED, isApproved;
49372
+ var init_delivery_evidence = __esm({
49373
+ "src/lib/shared/delivery-evidence.ts"() {
49374
+ "use strict";
49375
+ init_frontmatter();
49376
+ APPROVED = [
49377
+ /^##\s+Worth noting\s*$/i,
49378
+ /^##\s+Scope\s*$/i,
49379
+ /^##\s+Scope out\s*$/i,
49380
+ // `skill` is the word a spec section carries now; `agent` is the word it carried before
49381
+ // #403, and a card written by an older release still has to travel whole.
49382
+ /^##\s+By\s+`[^`]+`\s+(skill|agent)\s*$/i
49383
+ ];
49384
+ isApproved = (heading) => APPROVED.some((re) => re.test(heading));
49385
+ }
49386
+ });
49387
+
49243
49388
  // src/lib/agent/candidate.ts
49244
49389
  function candidateBase() {
49245
49390
  return git(["rev-parse", "HEAD"])?.trim() || null;
@@ -49554,6 +49699,7 @@ function parseStore() {
49554
49699
  runs.push({
49555
49700
  sessionId: entry.sessionId,
49556
49701
  cloudExecution: executionOf(entry.cloudExecution ?? null),
49702
+ pendingWrites: entry.pendingWrites === true || void 0,
49557
49703
  cardId: typeof entry.cardId === "number" ? entry.cardId : null,
49558
49704
  createdCardIds: Array.isArray(entry.createdCardIds) ? [...new Set(entry.createdCardIds.filter((id2) => Number.isInteger(id2) && id2 > 0))] : void 0,
49559
49705
  discard: entry.discard === true || void 0,
@@ -49609,7 +49755,7 @@ function parseStore() {
49609
49755
  resumedFrom: typeof entry.resumedFrom === "string" ? entry.resumedFrom : void 0,
49610
49756
  continues: typeof entry.continues?.resumeId === "string" && entry.continues.resumeId ? { resumeId: entry.continues.resumeId, ...entry.continues.fork === true ? { fork: true } : {} } : void 0,
49611
49757
  formatRepair: entry.formatRepair && typeof entry.formatRepair === "object" && Number.isInteger(entry.formatRepair.attempt) && entry.formatRepair.attempt >= 0 && typeof entry.formatRepair.errors === "string" && [entry.formatRepair.cardIds, entry.formatRepair.changedIds, entry.formatRepair.existingIds].every((ids) => Array.isArray(ids) && ids.every(Number.isInteger)) ? entry.formatRepair : void 0,
49612
- retry: readRetry2(entry.retry),
49758
+ retry: readRetry2(entry.retry, !!executionOf(entry.cloudExecution ?? null)),
49613
49759
  priorStatus: typeof entry.priorStatus === "string" ? entry.priorStatus : void 0,
49614
49760
  // The pictures the create sheet handed this run (#517), as paths in its own folder.
49615
49761
  pictures: readPictures(entry.pictures),
@@ -49651,11 +49797,11 @@ function readReasons(raw) {
49651
49797
  });
49652
49798
  return reasons.length ? reasons : void 0;
49653
49799
  }
49654
- function readRetry2(raw) {
49800
+ function readRetry2(raw, task) {
49655
49801
  if (!raw || typeof raw !== "object") return void 0;
49656
49802
  const r = raw;
49657
49803
  const whole2 = Number.isInteger(r.attempt) && r.attempt > 0 && Number.isInteger(r.of) && r.of > 0 && typeof r.reason === "string" && !!r.reason && typeof r.at === "number" && typeof r.since === "number";
49658
- return whole2 ? { attempt: r.attempt, of: r.of, reason: r.reason, at: r.at, since: r.since, pending: readRetryPlan(r.pending, r.attempt), launching: r.launching === true || void 0 } : void 0;
49804
+ return whole2 ? { attempt: r.attempt, of: r.of, reason: r.reason, at: r.at, since: r.since, pending: readRetryPlan(r.pending, r.attempt, task), launching: r.launching === true || void 0 } : void 0;
49659
49805
  }
49660
49806
  function readMarks(raw) {
49661
49807
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
@@ -50282,6 +50428,12 @@ function allAudits() {
50282
50428
  }
50283
50429
  return out;
50284
50430
  }
50431
+ function cardAudits(cardId2) {
50432
+ return allAudits().filter((a) => a.cardId === cardId2).flatMap((a) => {
50433
+ const row = auditRow(a);
50434
+ return row ? [row] : [];
50435
+ }).sort((a, b) => a.startedAt - b.startedAt);
50436
+ }
50285
50437
  function landedDeliveries(filter = {}) {
50286
50438
  const out = [];
50287
50439
  for (const audit of allAudits()) {
@@ -50443,27 +50595,7 @@ function approvedRequirements(cardId2) {
50443
50595
  } catch {
50444
50596
  return "";
50445
50597
  }
50446
- const { meta: meta3, body } = parseFrontmatter(text5);
50447
- const out = [];
50448
- if (meta3?.title) out.push(`# ${meta3.title}`, "");
50449
- const opening = [];
50450
- const sections = [];
50451
- let keeping = false;
50452
- let started = false;
50453
- for (const line of body.split("\n")) {
50454
- if (/^##(?!#)\s/.test(line)) {
50455
- started = true;
50456
- keeping = isApproved(line);
50457
- if (keeping) sections.push("", line);
50458
- continue;
50459
- }
50460
- if (line.trim() === "<!-- agent -->") continue;
50461
- if (!started) opening.push(line);
50462
- else if (keeping) sections.push(line);
50463
- }
50464
- out.push(opening.join("\n").trim());
50465
- out.push(sections.join("\n").trim());
50466
- return out.filter(Boolean).join("\n\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
50598
+ return approvedCardRequirements(text5);
50467
50599
  }
50468
50600
  function cardMeta2(cardId2) {
50469
50601
  try {
@@ -50602,7 +50734,7 @@ function heldByDelivery(cardId2, program2) {
50602
50734
  const doing = state.paused ? `is waiting on you on #${cardId2} \u2014 ${state.line} \u2014 so the board won't change the card. ${answer2} Or take the card back with ` : `is in flight on #${cardId2} \u2014 it is building the card as it was approved when it started, so the board won't change it. Take the card back with `;
50603
50735
  return `delivery ${delivery.deliveryId} ${doing}Discard on the card page, or \`${cmd} raw delivery cancel ${delivery.deliveryId}\` to end it here.`;
50604
50736
  }
50605
- var auditPath, activeAudits, auditRow, lastSessionRunning, localAudit, unknownDelivery, isResumable, APPROVED, isApproved, cardStatus, openQuestions, activeIn, listDeliveries, withStudio;
50737
+ var auditPath, activeAudits, auditRow, lastSessionRunning, localAudit, unknownDelivery, isResumable, cardStatus, openQuestions, activeIn, listDeliveries, withStudio;
50606
50738
  var init_deliveries = __esm({
50607
50739
  "src/lib/agent/deliveries.ts"() {
50608
50740
  "use strict";
@@ -50610,6 +50742,7 @@ var init_deliveries = __esm({
50610
50742
  init_cards();
50611
50743
  init_revision();
50612
50744
  init_frontmatter();
50745
+ init_delivery_evidence();
50613
50746
  init_paths();
50614
50747
  init_candidate();
50615
50748
  init_command();
@@ -50630,15 +50763,6 @@ var init_deliveries = __esm({
50630
50763
  localAudit = (audit) => worktreeExists(audit.worktree) || audit.sessions.some((session) => path48.resolve(REPO_ROOT, session.log) === logPathOf(session.sessionId) && fs47.existsSync(logPathOf(session.sessionId)));
50631
50764
  unknownDelivery = (id2) => refusal("deliveryNotFound", `no delivery here answers to "${id2}"`, { id: id2 });
50632
50765
  isResumable = (delivery) => !resumeRefusal(delivery);
50633
- APPROVED = [
50634
- /^##\s+Worth noting\s*$/i,
50635
- /^##\s+Scope\s*$/i,
50636
- /^##\s+Scope out\s*$/i,
50637
- // `skill` is the word a spec section carries now; `agent` is the word it carried before
50638
- // #403, and a card written by an older release still has to travel whole.
50639
- /^##\s+By\s+`[^`]+`\s+(skill|agent)\s*$/i
50640
- ];
50641
- isApproved = (heading) => APPROVED.some((re) => re.test(heading));
50642
50766
  cardStatus = (cardId2) => cardMeta2(cardId2)?.status || "todo";
50643
50767
  openQuestions = (cardId2) => cardMeta2(cardId2)?.questions.length ?? 0;
50644
50768
  activeIn = (store, cardId2) => store.deliveries.find((d) => d.status === "active" && d.cardId === cardId2);
@@ -52023,21 +52147,27 @@ function endAgent(child, mark, graceMs) {
52023
52147
  round(KILL_ROUNDS);
52024
52148
  });
52025
52149
  }
52026
- function processesStopped(mark, root2) {
52150
+ function probeProcesses(mark, root2) {
52027
52151
  try {
52028
52152
  if (WINDOWS3) {
52029
52153
  const list3 = procsOnWindows();
52030
- if (!list3 || !root2) return false;
52154
+ if (!list3) return { ok: false, error: "\u65E0\u6CD5\u67E5\u8BE2\u8FDB\u7A0B\u5217\u8868\u3002" };
52155
+ if (!root2) return { ok: false, error: "\u7F3A\u5C11\u8FDB\u7A0B\u8D77\u70B9\uFF0C\u65E0\u6CD5\u6838\u5BF9\u9000\u51FA\u72B6\u6001\u3002" };
52031
52156
  const current = list3.procs.find((p) => p.pid === root2.pid);
52032
- if (current && current.startedAt > root2.since) return false;
52033
- return startedUnder(list3, root2.pid, root2.since).length === 0;
52157
+ if (current && current.startedAt > root2.since) return { ok: false, error: "\u8FDB\u7A0B\u53F7\u5DF2\u88AB\u590D\u7528\u3002" };
52158
+ return { ok: true, alive: startedUnder(list3, root2.pid, root2.since).length > 0 };
52034
52159
  }
52035
52160
  const entry = `${mark.name}=${mark.value}`;
52036
- return (process.platform === "linux" ? markedInProc(entry, true, mark.since) : markedInPs(entry, root2 ? [root2.pid] : [])).length === 0;
52037
- } catch {
52038
- return false;
52161
+ const pids = process.platform === "linux" ? markedInProc(entry, true, mark.since) : markedInPs(entry, root2 ? [root2.pid] : []);
52162
+ return { ok: true, alive: pids.length > 0 };
52163
+ } catch (e) {
52164
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
52039
52165
  }
52040
52166
  }
52167
+ function processesStopped(mark, root2) {
52168
+ const probed = probeProcesses(mark, root2);
52169
+ return probed.ok && !probed.alive;
52170
+ }
52041
52171
  var runMark, WINDOWS3, KILL_ROUND_MS, KILL_ROUNDS, LIST_PROCS;
52042
52172
  var init_stop = __esm({
52043
52173
  "src/lib/agent/stop.ts"() {
@@ -52557,7 +52687,7 @@ async function openResume(id2, options) {
52557
52687
  stopped: stopped2,
52558
52688
  session,
52559
52689
  replayable: !requireSession && neverStarted(prev),
52560
- unconfirmedCleanup: prev.cleanup?.status === "unconfirmed" || prev.managedProcess && (pending?.failure ?? prev.failure)?.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session)
52690
+ unconfirmedCleanup: prev.pendingWrites || prev.cleanup?.status === "unconfirmed" || prev.managedProcess && (pending?.failure ?? prev.failure)?.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session)
52561
52691
  });
52562
52692
  if (recovery === "unsafe") {
52563
52693
  if (pending) return retryRefusal(prev, "unsafe");
@@ -52864,6 +52994,152 @@ async function runIsDown(sessionId) {
52864
52994
  await sleep3(STOP_POLL_MS);
52865
52995
  }
52866
52996
  }
52997
+ function verifyDeliveryRunsStopped(runs, deliveryId, cardId2) {
52998
+ const related = runs.filter(
52999
+ (r) => r.action !== "sub" && (r.deliveryId === deliveryId || r.cardId === cardId2 && holdsCard(r.action))
53000
+ );
53001
+ for (const r of related) {
53002
+ if (r.managedProcess) {
53003
+ if (!connectionStopped(r.agentPid ? { pid: r.agentPid, identity: r.agentIdentity } : void 0)) {
53004
+ return `Associated managed agent process for run ${r.sessionId} is still alive without an active watcher.`;
53005
+ }
53006
+ continue;
53007
+ }
53008
+ if (r.pid || r.agentPid) {
53009
+ const probed = probeProcesses(
53010
+ runMark(r.sessionId, r.agentStartedAt ?? r.startedAt),
53011
+ r.agentPid && r.agentStartedAt ? { pid: r.agentPid, since: r.agentStartedAt } : void 0
53012
+ );
53013
+ if (!probed.ok) return probed.error;
53014
+ if (probed.alive) {
53015
+ return `Associated delivery process for run ${r.sessionId} is still alive without an active watcher.`;
53016
+ }
53017
+ }
53018
+ }
53019
+ return void 0;
53020
+ }
53021
+ async function reconcileCardDelivery(cardId2) {
53022
+ const reaped = [];
53023
+ const restore = [];
53024
+ let result;
53025
+ try {
53026
+ result = withStore((store) => {
53027
+ reap(store.runs, reaped, restore);
53028
+ const file2 = cardFile(cardId2);
53029
+ const restoredRaw = file2 ? parseFrontmatter(fs51.readFileSync(file2, "utf8")).meta?.restored : void 0;
53030
+ const restoredAt = restoredRaw ? Date.parse(restoredRaw) : Number.NaN;
53031
+ const merged = /* @__PURE__ */ new Map();
53032
+ for (const audit of cardAudits(cardId2)) merged.set(audit.deliveryId, audit);
53033
+ for (const row of store.deliveries) {
53034
+ if (row.cardId === cardId2) merged.set(row.deliveryId, row);
53035
+ }
53036
+ const deliveries = [...merged.values()].filter((d) => !(Number.isFinite(restoredAt) && restoredAt > d.startedAt)).sort((a, b) => a.startedAt - b.startedAt);
53037
+ const activeOrLatest = deliveries.find((d) => d.status === "active") ?? deliveries.filter((d) => d.status !== "cancelled").pop();
53038
+ const liveRun = store.runs.find(
53039
+ (r) => r.status === "running" && r.action !== "sub" && !!r.deliveryId && (r.cardId === cardId2 || activeOrLatest && r.deliveryId === activeOrLatest.deliveryId)
53040
+ );
53041
+ if (liveRun) {
53042
+ return {
53043
+ kind: "running",
53044
+ deliveryId: liveRun.deliveryId ?? activeOrLatest?.deliveryId,
53045
+ sessionId: liveRun.sessionId,
53046
+ action: liveRun.action
53047
+ };
53048
+ }
53049
+ if (!activeOrLatest) return { kind: "none" };
53050
+ if (activeOrLatest.status === "finished" || activeOrLatest.completions?.some((c) => c.finished)) {
53051
+ const lastSession = activeOrLatest.sessions[activeOrLatest.sessions.length - 1];
53052
+ const code = activeOrLatest.completions?.slice().reverse().find((c) => c.commit);
53053
+ return {
53054
+ kind: "completed",
53055
+ deliveryId: activeOrLatest.deliveryId,
53056
+ sessionId: lastSession,
53057
+ commit: activeOrLatest.landing?.commit ?? code?.commit,
53058
+ branch: activeOrLatest.targetBranch ?? code?.branch
53059
+ };
53060
+ }
53061
+ const refused = resumeRefusal(activeOrLatest, store);
53062
+ if (refused) {
53063
+ return {
53064
+ kind: "unverified",
53065
+ deliveryId: activeOrLatest.deliveryId,
53066
+ diagnostic: refused.error
53067
+ };
53068
+ }
53069
+ const processError = verifyDeliveryRunsStopped(store.runs, activeOrLatest.deliveryId, cardId2);
53070
+ if (processError) {
53071
+ return {
53072
+ kind: "unverified",
53073
+ deliveryId: activeOrLatest.deliveryId,
53074
+ diagnostic: processError
53075
+ };
53076
+ }
53077
+ const lastRun = store.runs.filter((r) => r.deliveryId === activeOrLatest.deliveryId && r.action !== "sub").sort((a, b) => a.startedAt - b.startedAt).pop();
53078
+ return {
53079
+ kind: "resumable",
53080
+ deliveryId: activeOrLatest.deliveryId,
53081
+ status: activeOrLatest.status,
53082
+ sessionId: lastRun?.sessionId,
53083
+ hasSession: !!(lastRun && resumeSessionId(lastRun)),
53084
+ worktree: activeOrLatest.worktree,
53085
+ branch: activeOrLatest.branch,
53086
+ base: activeOrLatest.base
53087
+ };
53088
+ });
53089
+ } catch (error62) {
53090
+ return {
53091
+ kind: "unverified",
53092
+ diagnostic: error62 instanceof Error ? error62.message : String(error62)
53093
+ };
53094
+ }
53095
+ for (const run3 of restore) await restoreCardStatus(run3);
53096
+ for (const run3 of reaped) await settleDelivery(run3);
53097
+ return result;
53098
+ }
53099
+ async function releaseCardDelivery(cardId2) {
53100
+ const execution = executionOf();
53101
+ if (execution && !await executionHeld(execution)) {
53102
+ return { ok: false, error: "\u65E0\u6CD5\u786E\u8BA4\u5F53\u524D\u6267\u884C\u7684 Cloud \u6388\u6743\uFF0C\u65E0\u6CD5\u91CA\u653E\u539F\u4EA4\u4ED8\u5199\u9501\u3002" };
53103
+ }
53104
+ const reaped = [];
53105
+ const restore = [];
53106
+ let releasedDelivery;
53107
+ let outcome;
53108
+ try {
53109
+ outcome = withStore((store) => {
53110
+ reap(store.runs, reaped, restore);
53111
+ const active3 = activeIn(store, cardId2);
53112
+ if (!active3) return { ok: true, released: false };
53113
+ const liveRun = store.runs.find(
53114
+ (r) => r.status === "running" && r.action !== "sub" && (r.cardId === cardId2 || r.deliveryId === active3.deliveryId)
53115
+ );
53116
+ if (liveRun) {
53117
+ return {
53118
+ ok: false,
53119
+ deliveryId: active3.deliveryId,
53120
+ error: `\u539F\u4EA4\u4ED8\u4ECD\u6709\u8FD0\u884C\u4E2D\u7684\u8FDB\u7A0B (${liveRun.sessionId})\uFF0C\u65E0\u6CD5\u91CA\u653E\u5199\u9501\u3002`
53121
+ };
53122
+ }
53123
+ const processError = verifyDeliveryRunsStopped(store.runs, active3.deliveryId, cardId2);
53124
+ if (processError) {
53125
+ return { ok: false, deliveryId: active3.deliveryId, error: processError };
53126
+ }
53127
+ const at = Date.now();
53128
+ active3.status = "failed";
53129
+ active3.endedAt = at;
53130
+ active3.steps.push({ step: "released", at });
53131
+ writeAudit(active3, store.runs);
53132
+ releasedDelivery = { ...active3 };
53133
+ return { ok: true, released: true, deliveryId: active3.deliveryId };
53134
+ });
53135
+ } catch (error62) {
53136
+ return { ok: false, error: error62 instanceof Error ? error62.message : String(error62) };
53137
+ }
53138
+ for (const run3 of restore) await restoreCardStatus(run3);
53139
+ for (const run3 of reaped) await settleDelivery(run3);
53140
+ if (releasedDelivery) await releaseCard(releasedDelivery);
53141
+ return outcome;
53142
+ }
52867
53143
  async function resumeDelivery(id2) {
52868
53144
  if (!id2.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to carry on", { action: "resume" }) };
52869
53145
  const execution = executionOf();
@@ -62076,7 +62352,7 @@ var init_describe_project = __esm({
62076
62352
  var discuss_goal_default;
62077
62353
  var init_discuss_goal = __esm({
62078
62354
  "src/guide/discuss-goal.md"() {
62079
- discuss_goal_default = '# Discuss a goal\n\nExplain feasible options and key tradeoffs, then save the result the user can choose to start.\n\n- **Investigations**: finish checks and diagnosis here; save a change only when findings establish it. Report unverified work plainly.\n- **Goals**: save independent deliverables separately. Update existing goals rather than duplicate them.\n- **Studio**: choose the fitting installed Studio, preferring the user\'s choice; read its Additional Notes with `akb studio rule <studio>` and honor their scope.\n- **Select Previews**: match requested work to the Studio\u2019s Previews. Define a Goal Preview only when the Studio lacks a requested result.\n- **Review** independent Previews in parallel by default. Use Studio or Goal Preview names, e.g. `--review \'Tech choices + UI design\'`. Add `->` when the next group needs the previous group\'s approvals. Verify the saved plan.\n- **Review state**: pass `--review \'\'` for no extra approval, leave the plan undecided while a decision is missing, and omit the option when keeping a saved plan.\n- **Decisions**: explain the proposed outcome and review arrangement before saving. Ask only for choices the user must make, with a recommendation.\n- **Start**: the user starts each Goal from the page; its effective review arrangement governs output approval. Confirm changes to task-specific Preview definitions before making the affected output.\n- **Communication**: the remote user sees tasks and previews. Use plain words and button labels, omitting internal paths, commands and tools.\n\n## Goal format\n\nUse exactly these three fields on create and update. Include only what the user requested or confirmed.\n\nPass the one-line title separately with `--title`. Use this template for `--body-file`:\n\n```markdown\n<The requested outcome in at most 150 words.>\n\n## Done when\n\n- <A verifiable condition for the requested outcome.>\n```\n\n\n## Custom Preview definitions\n\nPass a JSON array with `--preview-definitions-file`. Use a stable ID, English and Chinese titles, and concise requirements. Omit the file to keep definitions, or pass `[]` to clear them.\n\n```json\n[{\n "id": "accessibility-report",\n "title": {"en": "Accessibility report", "zh": "\u65E0\u969C\u788D\u68C0\u67E5\u62A5\u544A"},\n "instructions": "Check keyboard navigation, visible focus and contrast. Include steps to reproduce issues."\n}]\n```\n\nUse the title in a Flow such as `--review \'UI design -> Accessibility report\'` when preparation requires an earlier approval.\n';
62355
+ discuss_goal_default = '# Discuss a goal\n\nExplain feasible options and key tradeoffs, then save the result the user can choose to start.\n\n- **Investigations**: finish checks and diagnosis here; save a change only when findings establish it. Report unverified work plainly.\n- **Goals**: save independent deliverables separately. Update existing goals rather than duplicate them.\n- **Studio**: choose the fitting installed Studio, preferring the user\'s choice; read its Additional Notes with `akb studio rule <studio>` and honor their scope.\n- **Select Previews**: choose Studio Previews for drafts or results that need review. Define a Goal Preview for a requested result the Studio lacks. Keep task context in the Goal body.\n- **Review** independent Previews in parallel by default. Use Studio or Goal Preview names, e.g. `--review \'Tech choices + UI design\'`. Add `->` when the next group needs the previous group\'s approvals. Verify the saved plan.\n- **Review state**: pass `--review \'\'` for no extra approval, leave the plan undecided while a decision is missing, and omit the option when keeping a saved plan.\n- **Decisions**: explain the proposed outcome and review arrangement before saving. Ask only for choices the user must make, with a recommendation.\n- **Start**: the user starts each Goal from the page; its effective review arrangement governs output approval. Confirm changes to task-specific Preview definitions before making the affected output.\n- **Communication**: the remote user sees tasks and previews. Use plain words and button labels, omitting internal paths, commands and tools.\n\n## Goal format\n\nUse exactly these three fields on create and update. Include only what the user requested or confirmed.\n\nPass the one-line title separately with `--title`. Use this template for `--body-file`:\n\n```markdown\n<The requested outcome in at most 150 words.>\n\n## Done when\n\n- <A verifiable condition for the requested outcome.>\n```\n\n\n## Custom Preview definitions\n\nPass a JSON array with `--preview-definitions-file`. Use a stable ID, English and Chinese titles, and concise requirements. Omit the file to keep definitions, or pass `[]` to clear them.\n\n```json\n[{\n "id": "accessibility-report",\n "title": {"en": "Accessibility report", "zh": "\u65E0\u969C\u788D\u68C0\u67E5\u62A5\u544A"},\n "instructions": "Check keyboard navigation, visible focus and contrast. Include steps to reproduce issues."\n}]\n```\n\nUse the title in a Flow such as `--review \'UI design -> Accessibility report\'` when preparation requires an earlier approval.\n';
62080
62356
  }
62081
62357
  });
62082
62358
 
@@ -62092,7 +62368,7 @@ var init_follow_up = __esm({
62092
62368
  var implement_default;
62093
62369
  var init_implement = __esm({
62094
62370
  "src/guide/implement.md"() {
62095
- implement_default = "# Implement the approved requirements\n\nBuild the approved requirements without reopening settled decisions or unrelated questions; without a card, create none.\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";
62371
+ 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 changes\nit made since approval, including removals. Stop the affected work and use\n`akb guide update-questions` only if those changes conflict with the task'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";
62096
62372
  }
62097
62373
  });
62098
62374
 
@@ -62132,7 +62408,7 @@ var init_review_rejections = __esm({
62132
62408
  var refine_default;
62133
62409
  var init_refine = __esm({
62134
62410
  "src/guide/refine.md"() {
62135
- refine_default = '# Refine a card\n\nPlan one card until it is buildable.\n\n- **Unchecked cards**: check cards with `triage:` and empty `## Scope` against the project, rejecting obsolete or completed work with `akb raw reject <id> --reason "<evidence>"` and stopping.\n- **Other obsolete or completed cards**: ask whether to discard, run no previews, and stop.\n- **Groups**: preserve subtask coverage and progress, fill gaps without duplication, and do not mark the parent ready merely because its split is complete.\n- **Verification**: plan representative checks for the outcome, project rules and material risks, confirm prerequisites, and keep optional coverage optional.\n- **Review**: read `akb task review <id>`. If the arrangement is undecided, set it with `--file <json> --revision <n>`. Work only on dispatched, unlocked nodes; keep independent work moving while other nodes await review.\n- **Previews**: prepare only the unlocked nodes\u2019 outputs per the Studio\u2019s `<Preview>` blocks. Before revising an approved output, use `--revise-from <stage> --revision <n>`; preserve unrelated outputs and approvals.\n- **Submit**: synchronize body and assets, then report `--stage <id> --status done --revision <n>`. Re-read after conflicts; obtain output approval at the required stages.\n- **Delivery handoff**: for Studios with separate delivery, finish the review plan with a handoff; implementation and its checks run in delivery.\n- **References**: rewrite mentions of cards no longer on the board.\n- **Decisions**: settle choices supported by evidence and ask only as `akb guide update-questions` allows.\n- **Card**: follow studio rules and `akb guide writing`, fixing all errors from `akb raw validate <id>`.\n- **Ready**: when validated and buildable with prerequisites settled, run `akb raw update <id> --status ready`; otherwise leave blockers as open questions.\n\nFollow the printed closing steps. Wait only for required approvals; completion still requires Studio delivery checks.\n';
62411
+ refine_default = "# Refine a card\n\nPlan one card until it is buildable.\n\n- **Unchecked cards**: check cards with `triage:` and empty `## Scope` against the project, rejecting obsolete or completed work with `akb raw reject <id> --reason \"<evidence>\"` and stopping.\n- **Other obsolete or completed cards**: ask whether to discard, run no previews, and stop.\n- **Groups**: preserve subtask coverage and progress, fill gaps without duplication, and do not mark the parent ready merely because its split is complete.\n- **Verification**: plan representative checks for the outcome, project rules and material risks, confirm prerequisites, and keep optional coverage optional.\n- **Review**: read `akb task review <id>`. If undecided, submit `--review <flow>` with Preview names or `--file <json>` with Preview IDs, plus `--revision <n>`. Use `--review ''` when no extra review is needed. Work only on dispatched, unlocked nodes and continue independent work during review.\n- **Preview selection**: choose Studio Previews for drafts or results that need review. For a requested result the Studio lacks, attach its definition with `--preview-definitions-file`. Keep task context in the card body.\n- **Previews**: prepare only the unlocked nodes\u2019 outputs per the Studio\u2019s `<Preview>` blocks. Before revising an approved output, use `--revise-from <stage> --revision <n>`; preserve unrelated outputs and approvals.\n- **Submit**: synchronize body and assets, then report `--stage <id> --status done --revision <n>`. Re-read after conflicts; obtain output approval at the required stages.\n- **Delivery**: the Studio's delivery flow handles separate implementation and its checks.\n- **References**: rewrite mentions of cards no longer on the board.\n- **Decisions**: settle choices supported by evidence and ask only as `akb guide update-questions` allows.\n- **Card**: follow studio rules and `akb guide writing`, fixing all errors from `akb raw validate <id>`.\n- **Ready**: when validated and buildable with prerequisites settled, run `akb raw update <id> --status ready`; otherwise leave blockers as open questions.\n\nFollow the printed closing steps. Wait only for required approvals; completion still requires Studio delivery checks.\n";
62136
62412
  }
62137
62413
  });
62138
62414
 
@@ -63720,7 +63996,7 @@ var init_approved_ui = __esm({
63720
63996
  init_preview_blocks();
63721
63997
  init_review_plan();
63722
63998
  APPROVED_UI_DIR_ENV = "AI4KANBAN_APPROVED_UI_DIR";
63723
- APPROVED_UI_RULE = "Open the approved mockups and match them exactly for the changes specified in the task card. Consider copying the relevant mockup code directly when the project framework permits. Compare the implementation with the approved desktop and mobile views and fix any differences.";
63999
+ APPROVED_UI_RULE = "Open the approved mockups and follow the Coding Studio delivery requirements for matching the task's intended UI changes.";
63724
64000
  UI_PREVIEW = "ui-design";
63725
64001
  historicalUiIds = Object.keys(CODING_PREVIEWS).filter((id2) => id2 !== UI_PREVIEW && CODING_PREVIEWS[id2] === UI_PREVIEW);
63726
64002
  object2 = (value) => isObject2(value) ? value : {};
@@ -63840,8 +64116,14 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
63840
64116
  const pendingOperations = /* @__PURE__ */ new Set();
63841
64117
  const event2 = (e) => {
63842
64118
  observeActivity(e);
64119
+ const hadPending = pendingOperations.size > 0;
63843
64120
  if (e.kind === "tool_call" && !["read", "search", "fetch"].includes(e.data.kind) && !["completed", "failed"].includes(e.data.status)) pendingOperations.add(e.data.toolCallId);
63844
64121
  if ((e.kind === "tool_call" || e.kind === "tool_call_update") && ["completed", "failed"].includes(e.data.status ?? "")) pendingOperations.delete(e.data.toolCallId);
64122
+ if (record2.cloudExecution && hadPending !== pendingOperations.size > 0) {
64123
+ patch(sessionId, (run4) => {
64124
+ run4.pendingWrites = pendingOperations.size > 0;
64125
+ });
64126
+ }
63845
64127
  eventsFile.write(`${JSON.stringify(e)}
63846
64128
  `);
63847
64129
  };
@@ -64099,7 +64381,7 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64099
64381
  let retrying = false;
64100
64382
  if (failure2 && !sub && !taskCompleted) {
64101
64383
  const attempt2 = held4.retry?.attempt ?? 1;
64102
- const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff);
64384
+ const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff, !!held4.cloudExecution);
64103
64385
  if ("pause" in decision) retryPause = decision.pause;
64104
64386
  else {
64105
64387
  const mark = runMark(sessionId, agentStartedAt);
@@ -64112,7 +64394,7 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64112
64394
  stopped: stopped3(),
64113
64395
  session,
64114
64396
  replayable: held4.unspawned === true && !pendingOperations.size,
64115
- unconfirmedCleanup: !!blocker || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, session))
64397
+ unconfirmedCleanup: pendingOperations.size > 0 || !!blocker || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, session))
64116
64398
  });
64117
64399
  if (recovery === "unsafe") retryPause = "unsafe";
64118
64400
  else {
@@ -64564,6 +64846,23 @@ async function cmdCancel(named2) {
64564
64846
  say(`delivery ${res.deliveryId} cancelled \u2014 files, branches and directories are preserved.`);
64565
64847
  return { deliveryId: res.deliveryId };
64566
64848
  }
64849
+ async function cmdReconcileDelivery(cardId2) {
64850
+ const result = await reconcileCardDelivery(cardId2);
64851
+ if (result.kind === "unverified") {
64852
+ say(`delivery${result.deliveryId ? ` ${result.deliveryId}` : ""}: unverified \u2014 ${result.diagnostic}`);
64853
+ } else if (result.kind === "none") {
64854
+ say(`#${cardId2}: no delivery to reconcile`);
64855
+ } else {
64856
+ say(`#${cardId2}: ${result.kind}${result.deliveryId ? ` (${result.deliveryId})` : ""}`);
64857
+ }
64858
+ return result;
64859
+ }
64860
+ async function cmdReleaseDelivery(cardId2) {
64861
+ const res = await releaseCardDelivery(cardId2);
64862
+ if (!res.ok) die(res.error, { kind: "run-refused", ...res.deliveryId ? { deliveryId: res.deliveryId } : {} });
64863
+ say(res.released ? `delivery ${res.deliveryId} lock released \u2014 files and branch preserved.` : `#${cardId2}: no active delivery lock to release.`);
64864
+ return res;
64865
+ }
64567
64866
  async function cmdResumeDelivery(named2) {
64568
64867
  const res = await resumeBoardDelivery(named2);
64569
64868
  if (!res.ok) die(res.error ?? "that delivery could not be carried on", {
@@ -65902,6 +66201,14 @@ function declareDelivery(delivery, cli) {
65902
66201
  const [named2] = positional(vals);
65903
66202
  await onBoard(this, cli, () => cmdResumeDelivery(named2));
65904
66203
  });
66204
+ verb("reconcile").argument("<card>", "card number", cardId).summary("reconcile local delivery state for a card before recovery").action(async function(...vals) {
66205
+ const [id2] = positional(vals);
66206
+ await onBoard(this, cli, () => cmdReconcileDelivery(id2));
66207
+ });
66208
+ verb("release").argument("<card>", "card number", cardId).summary("safely release an active delivery write lock while preserving saved work").action(async function(...vals) {
66209
+ const [id2] = positional(vals);
66210
+ await onBoard(this, cli, () => cmdReleaseDelivery(id2));
66211
+ });
65905
66212
  }
65906
66213
  function declareFlow(parent, flow, cli) {
65907
66214
  const byDelivery = flow.group === "delivery";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wildcrane",
3
- "version": "0.11.80",
3
+ "version": "0.11.81",
4
4
  "akbContract": 27,
5
5
  "description": "WildCrane's `akb` command — scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
6
6
  "keywords": [