wildcrane 0.11.80 → 0.11.82

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 +442 -128
  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.82 — 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
 
@@ -22489,13 +22511,20 @@ var init_goal = __esm({
22489
22511
 
22490
22512
  // src/lib/goal-draft.ts
22491
22513
  import fs8 from "node:fs";
22514
+ import { randomUUID } from "node:crypto";
22492
22515
  function readGoalDraft(file2) {
22493
22516
  return decodeGoals(JSON.parse(fs8.readFileSync(file2, "utf8")));
22494
22517
  }
22495
22518
  function writeGoalDraft(file2, { goals, ...draft }, field2) {
22496
22519
  const entries = field2 === "goals" ? goals : goals.map(({ task, ...goal }) => ({ ...goal, task: task?.key ? task : task?.id ?? null }));
22497
- fs8.writeFileSync(file2, `${JSON.stringify({ ...draft, [field2]: entries }, null, 2)}
22498
- `);
22520
+ const temporary = `${file2}.${randomUUID()}.tmp`;
22521
+ try {
22522
+ fs8.writeFileSync(temporary, `${JSON.stringify({ ...draft, [field2]: entries }, null, 2)}
22523
+ `, { mode: 384, flag: "wx" });
22524
+ fs8.renameSync(temporary, file2);
22525
+ } finally {
22526
+ fs8.rmSync(temporary, { force: true });
22527
+ }
22499
22528
  }
22500
22529
  var goalDraftPath;
22501
22530
  var init_goal_draft = __esm({
@@ -37757,7 +37786,7 @@ function cmdGoal(args2, opts) {
37757
37786
  write2();
37758
37787
  if ("dropped" in result) say(`Dropped goal ${result.id}.`);
37759
37788
  else if ("start" in result) say(`Goal ${result.id} starts as a task when this turn ends.`);
37760
- else say(`Saved goal ${result.id}: ${result.title} (${shortStudioId(result.studio)}).`);
37789
+ else say(`Goal ${result.id} will be saved when this turn ends: ${result.title} (${shortStudioId(result.studio)}).`);
37761
37790
  return result;
37762
37791
  }
37763
37792
  function editGoal(args2, opts, held4) {
@@ -37815,23 +37844,15 @@ function goalCatalog(held4, studio, definitions) {
37815
37844
  if (!builtIn && definitions.length) die("Preview outputs are unavailable; update Runner and try again.");
37816
37845
  return builtIn && effectivePreviewCatalog(builtIn, definitions);
37817
37846
  }
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
37847
  function goalReview(held4, studio, opts, previous, definitions) {
37848
+ const catalog = goalCatalog(held4, studio, definitions);
37829
37849
  if (opts.review !== void 0) {
37830
37850
  if (opts.reviewFile !== void 0) die("Use either --review or --review-file.");
37831
- return parseReviewFlow(opts.review, goalCatalog(held4, studio, definitions));
37851
+ return parseReviewFlow(opts.review, catalog);
37832
37852
  }
37833
- const value = opts.reviewFile === void 0 ? previous : JSON.parse(fs16.readFileSync(opts.reviewFile, "utf8"));
37834
- return checkGoalReview(held4, studio, value, definitions);
37853
+ const value = opts.reviewFile === void 0 ? readReviewPlan(previous) : JSON.parse(fs16.readFileSync(opts.reviewFile, "utf8"));
37854
+ const saved = opts.reviewFile === void 0 && opts.previewDefinitionsFile === void 0 && opts.studio === void 0;
37855
+ return validateReviewPreviews(parseReviewPlan(value), catalog, { saved });
37835
37856
  }
37836
37857
  function cmdGoalPreviews(studio, held4 = loadGoals().held) {
37837
37858
  const id2 = studioOf(held4, studio);
@@ -41327,7 +41348,7 @@ var init_codex_background_types = __esm({
41327
41348
  });
41328
41349
 
41329
41350
  // src/lib/lock.ts
41330
- import { randomUUID } from "node:crypto";
41351
+ import { randomUUID as randomUUID2 } from "node:crypto";
41331
41352
  import fs19 from "node:fs";
41332
41353
  import path18 from "node:path";
41333
41354
  function sleep2(ms) {
@@ -41385,7 +41406,7 @@ function removeClaim(dir, token2) {
41385
41406
  }
41386
41407
  function tryLock(dir) {
41387
41408
  fs19.mkdirSync(path18.dirname(dir), { recursive: true });
41388
- const token2 = `${process.pid}-${randomUUID()}`;
41409
+ const token2 = `${process.pid}-${randomUUID2()}`;
41389
41410
  const candidate = fs19.mkdtempSync(`${dir}.`);
41390
41411
  try {
41391
41412
  fs19.writeFileSync(path18.join(candidate, token2), "");
@@ -41547,14 +41568,15 @@ function backoffMs(attempt2, random = Math.random) {
41547
41568
  const step = Math.min(CAP_MS, BASE_MS * 2 ** Math.max(0, attempt2 - 2));
41548
41569
  return Math.round(step * (1 - 0.25 * random()));
41549
41570
  }
41550
- function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs) {
41571
+ function planRetry(failure2, attempt2, now = Date.now(), backoff = backoffMs, task = false) {
41551
41572
  if (!Number.isSafeInteger(attempt2) || attempt2 < 1 || failure2.level === 3) return { pause: "needs-review" };
41552
41573
  const of = failure2.level === 1 ? 2 : 4;
41553
41574
  if (attempt2 >= of) return { pause: "limit" };
41554
41575
  const delay3 = failure2.retryAfterMs;
41555
41576
  const valid = delay3 !== void 0 && !Number.isNaN(delay3) && delay3 >= 0;
41556
41577
  const wait = valid ? delay3 : failure2.level === 1 ? 0 : backoff(attempt2 + 1);
41557
- if (wait > CAP_MS) return { pause: "wait-too-long" };
41578
+ const cap = task && failure2.code === "rate_limited" && valid ? 24 * 60 * 6e4 : CAP_MS;
41579
+ if (wait > cap) return { pause: "wait-too-long" };
41558
41580
  return { plan: { at: now + wait, of, failure: failure2 } };
41559
41581
  }
41560
41582
  function readFailure(raw) {
@@ -41563,12 +41585,12 @@ function readFailure(raw) {
41563
41585
  if (typeof code !== "string" || !code || typeof reason !== "string" || level2 !== 1 && level2 !== 2 && level2 !== 3) return;
41564
41586
  return { code, level: level2, reason, ...["validation", "provider", "harness", "invariant"].some((value) => value === source2) ? { source: source2 } : {}, ...typeof retryAfterMs2 === "number" && retryAfterMs2 >= 0 ? { retryAfterMs: retryAfterMs2 } : {} };
41565
41587
  }
41566
- function readRetryPlan(raw, attempt2) {
41588
+ function readRetryPlan(raw, attempt2, task = false) {
41567
41589
  if (!raw || typeof raw !== "object") return;
41568
41590
  const { at, of, failure: rawFailure } = raw;
41569
41591
  const failure2 = readFailure(rawFailure);
41570
41592
  if (!failure2 || typeof at !== "number" || !Number.isFinite(at)) return;
41571
- const decision = planRetry(failure2, attempt2);
41593
+ const decision = planRetry(failure2, attempt2, Date.now(), backoffMs, task);
41572
41594
  if ("plan" in decision && of === decision.plan.of) return { at, of, failure: failure2 };
41573
41595
  }
41574
41596
  function pauseLine(pause2, zh = translating()) {
@@ -41922,7 +41944,7 @@ var init_package = __esm({
41922
41944
  "package.json"() {
41923
41945
  package_default = {
41924
41946
  name: "wildcrane",
41925
- version: "0.11.80",
41947
+ version: "0.11.82",
41926
41948
  akbContract: 27,
41927
41949
  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
41950
  keywords: [
@@ -42122,7 +42144,7 @@ var init_catalog = __esm({
42122
42144
  // src/lib/machine/telemetry.ts
42123
42145
  import fs24 from "node:fs";
42124
42146
  import path23 from "node:path";
42125
- import { randomUUID as randomUUID2 } from "node:crypto";
42147
+ import { randomUUID as randomUUID3 } from "node:crypto";
42126
42148
  function readUsageReporting() {
42127
42149
  const { unreadable, values } = heldSettings();
42128
42150
  if (unreadable) return { on: false, disclosed: false, installId: "", unreadable: true };
@@ -42144,7 +42166,7 @@ function ensureUsageInstallId() {
42144
42166
  const held4 = readUsageReporting();
42145
42167
  if (!held4.on) return "";
42146
42168
  if (held4.installId) return held4.installId;
42147
- const id2 = randomUUID2();
42169
+ const id2 = randomUUID3();
42148
42170
  return saveSettings({ usageInstallId: id2 }).ok ? id2 : "";
42149
42171
  }
42150
42172
  function write(on, disclosed) {
@@ -42174,7 +42196,7 @@ var init_telemetry = __esm({
42174
42196
  // src/lib/machine/usage.ts
42175
42197
  import fs25 from "node:fs";
42176
42198
  import path24 from "node:path";
42177
- import { randomUUID as randomUUID3 } from "node:crypto";
42199
+ import { randomUUID as randomUUID4 } from "node:crypto";
42178
42200
  function usageSurface() {
42179
42201
  return process.env.KANBAN_DESKTOP === "1" ? "app" : "command";
42180
42202
  }
@@ -42202,10 +42224,10 @@ function reportUsage(name, fields2 = {}, surface = usageSurface()) {
42202
42224
  const day = usageDay();
42203
42225
  const state = readState();
42204
42226
  if (state.dayEvent !== day && name !== "app_day") {
42205
- append({ name: "app_day", day, id: randomUUID3(), surface, version: SKILL_VERSION });
42227
+ append({ name: "app_day", day, id: randomUUID4(), surface, version: SKILL_VERSION });
42206
42228
  writeState({ ...state, dayEvent: day });
42207
42229
  }
42208
- append({ name, day, id: randomUUID3(), surface, version: SKILL_VERSION, ...fields2 });
42230
+ append({ name, day, id: randomUUID4(), surface, version: SKILL_VERSION, ...fields2 });
42209
42231
  } catch {
42210
42232
  return;
42211
42233
  }
@@ -42292,7 +42314,7 @@ function reportBoardNumbers(customAgentsOn2) {
42292
42314
  const on = customAgentsOn2();
42293
42315
  if (on > 0) fields2.custom_agents_on = on;
42294
42316
  if (!Object.keys(fields2).length) return;
42295
- const id2 = typeof held4.id === "string" && held4.id ? held4.id : randomUUID3();
42317
+ const id2 = typeof held4.id === "string" && held4.id ? held4.id : randomUUID4();
42296
42318
  writeBoard({ id: id2, day });
42297
42319
  reportUsage("board_numbers", { board: id2, ...fields2 });
42298
42320
  } catch {
@@ -42942,6 +42964,7 @@ function antigravityPrices(at) {
42942
42964
  return {
42943
42965
  "gemini-4-carbon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
42944
42966
  "gemini-4-argon": { input: pro, cachedInput: pro / 20, output: pro * 5 },
42967
+ "gemini-4-neon": { input: 3, cachedInput: 0.15, output: 15 },
42945
42968
  "gemini-4-hydrogen": { input: 1.5, cachedInput: 0.075, output: 7.5 },
42946
42969
  "gemini-3.8-flash": { input: flash, cachedInput: flash / 10, output: flash * 5 }
42947
42970
  };
@@ -43283,8 +43306,36 @@ function bytesField(data, field2) {
43283
43306
  if (number4 === field2 && value instanceof Uint8Array) return value;
43284
43307
  }
43285
43308
  }
43309
+ function varintField(data, field2) {
43310
+ if (!(data instanceof Uint8Array)) return;
43311
+ for (const [number4, value] of fields(data)) {
43312
+ if (number4 === field2 && typeof value === "number") return value;
43313
+ }
43314
+ }
43315
+ function stepIndices(data) {
43316
+ const out = [];
43317
+ for (const [field2, value] of fields(data)) {
43318
+ if (field2 !== 2) continue;
43319
+ if (typeof value === "number") out.push(value);
43320
+ else {
43321
+ const offset = { value: 0 };
43322
+ while (offset.value < value.length) out.push(varint(value, offset));
43323
+ }
43324
+ }
43325
+ return out;
43326
+ }
43327
+ function recordedContextLimit(data) {
43328
+ const limit = varintField(bytesField(bytesField(bytesField(data, 1), 9), 10), 4);
43329
+ return limit !== void 0 && Number.isSafeInteger(limit) && limit > 0 ? limit : void 0;
43330
+ }
43331
+ function stepUuid(stepRow, index) {
43332
+ if (!Number.isSafeInteger(index) || index < 0) return;
43333
+ const id2 = bytesField(stepRow.get(index)?.metadata, 12);
43334
+ return id2?.length === 36 ? id2 : void 0;
43335
+ }
43286
43336
  function antigravityRecordedModels(session, steps) {
43287
43337
  const found2 = /* @__PURE__ */ new Map();
43338
+ if (!steps.size) return found2;
43288
43339
  const file2 = antigravityConversationFile(session);
43289
43340
  if (!file2 || !existsSync(file2)) return found2;
43290
43341
  try {
@@ -43292,26 +43343,31 @@ function antigravityRecordedModels(session, steps) {
43292
43343
  if (!sqlite) return found2;
43293
43344
  const db = new sqlite.DatabaseSync(file2, { readOnly: true });
43294
43345
  try {
43295
- const prompt = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
43346
+ const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
43347
+ const promptIds = /* @__PURE__ */ new Map();
43348
+ const promptUuid = (prompt) => {
43349
+ if (!promptIds.has(prompt)) promptIds.set(prompt, stepUuid(stepRow, prompt));
43350
+ return promptIds.get(prompt);
43351
+ };
43352
+ const groups = /* @__PURE__ */ new Map();
43353
+ for (const [index, { prompt }] of steps) {
43354
+ if (!Number.isSafeInteger(index) || index < 0) continue;
43355
+ const id2 = stepUuid(stepRow, index) ?? promptUuid(prompt);
43356
+ if (!id2) continue;
43357
+ const uuid3 = utf8(id2);
43358
+ let group = groups.get(uuid3);
43359
+ if (!group) groups.set(uuid3, group = { id: id2, steps: /* @__PURE__ */ new Set() });
43360
+ group.steps.add(index);
43361
+ }
43296
43362
  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;
43363
+ for (const [uuid3, { id: id2, steps: groupSteps }] of groups) {
43300
43364
  const key = Buffer.concat([Buffer.from([34, 36]), id2]);
43301
43365
  for (const { data } of generations.iterate(key)) {
43302
- if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== utf8(id2)) continue;
43366
+ if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== uuid3) continue;
43303
43367
  const model = utf8(bytesField(bytesField(data, 1), 19)) || void 0;
43304
- const record2 = (step) => {
43305
- if (steps.get(step)?.prompt !== index) return;
43368
+ for (const step of stepIndices(data)) {
43369
+ if (!groupSteps.has(step)) continue;
43306
43370
  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
43371
  }
43316
43372
  }
43317
43373
  }
@@ -43323,6 +43379,38 @@ function antigravityRecordedModels(session, steps) {
43323
43379
  return /* @__PURE__ */ new Map();
43324
43380
  }
43325
43381
  }
43382
+ function antigravityRecordedContextLimit(session, step, prompt) {
43383
+ if (!Number.isSafeInteger(step) || step < 0) return;
43384
+ const file2 = antigravityConversationFile(session);
43385
+ if (!file2 || !existsSync(file2)) return;
43386
+ try {
43387
+ const sqlite = process.getBuiltinModule?.("node:sqlite");
43388
+ if (!sqlite) return;
43389
+ const db = new sqlite.DatabaseSync(file2, { readOnly: true });
43390
+ try {
43391
+ const stepRow = db.prepare("SELECT metadata FROM steps WHERE idx = ?");
43392
+ const id2 = stepUuid(stepRow, step) ?? stepUuid(stepRow, prompt);
43393
+ if (!id2) return;
43394
+ const key = Buffer.concat([Buffer.from([34, 36]), id2]);
43395
+ const generations = db.prepare("SELECT data FROM gen_metadata WHERE instr(data, ?) > 0");
43396
+ let found2;
43397
+ let matched = false;
43398
+ for (const { data } of generations.iterate(key)) {
43399
+ if (!(data instanceof Uint8Array) || utf8(bytesField(data, 4)) !== utf8(id2)) continue;
43400
+ if (!stepIndices(data).includes(step)) continue;
43401
+ const limit = recordedContextLimit(data);
43402
+ if (matched && found2 !== limit) return;
43403
+ found2 = limit;
43404
+ matched = true;
43405
+ }
43406
+ return found2;
43407
+ } finally {
43408
+ db.close();
43409
+ }
43410
+ } catch {
43411
+ return;
43412
+ }
43413
+ }
43326
43414
  var utf8;
43327
43415
  var init_antigravity_session = __esm({
43328
43416
  "src/lib/agent/wire/antigravity-session.ts"() {
@@ -43357,6 +43445,20 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
43357
43445
  let stderr = "";
43358
43446
  let context;
43359
43447
  let contextStep = -1;
43448
+ let contextPrompt = -1;
43449
+ let contextLimitStep = -1;
43450
+ let contextLimitLookedAt = 0;
43451
+ const resolveContextLimit = (now) => {
43452
+ if (!context || !session || contextStep < 0 || contextLimitStep === contextStep) return;
43453
+ const at = Date.now();
43454
+ if (!now && at - contextLimitLookedAt < CONTEXT_LOOK_EVERY_MS) return;
43455
+ contextLimitLookedAt = at;
43456
+ const limit = antigravityRecordedContextLimit(session, contextStep, contextPrompt);
43457
+ if (limit !== void 0) {
43458
+ context = { used: context.used, limit };
43459
+ contextLimitStep = contextStep;
43460
+ }
43461
+ };
43360
43462
  const started = Date.now();
43361
43463
  let cost;
43362
43464
  let incomplete = false;
@@ -43422,10 +43524,13 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
43422
43524
  const index = num2(step.step_index);
43423
43525
  if (step.state === "DONE" && Number.isSafeInteger(index) && step.step_index === index && index > contextStep) {
43424
43526
  contextStep = index;
43527
+ contextPrompt = prompt;
43528
+ contextLimitStep = -1;
43529
+ contextLimitLookedAt = 0;
43425
43530
  const u = obj2(step.usage);
43426
43531
  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;
43532
+ const promptTokens = counts.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0) ? num2(u.input_tokens) + num2(u.cache_read_tokens) : 0;
43533
+ context = promptTokens > 0 && Number.isFinite(promptTokens) ? { used: promptTokens } : void 0;
43429
43534
  }
43430
43535
  if (step.state === "DONE" && step.usage && !counted.has(index)) {
43431
43536
  counted.add(index);
@@ -43478,6 +43583,7 @@ ${imageError(target, reason || str2(step.state))}
43478
43583
  return "";
43479
43584
  }
43480
43585
  session ||= str2(result.conversation_id) || void 0;
43586
+ resolveContextLimit(true);
43481
43587
  terminal = true;
43482
43588
  final = typeof result.response === "string" ? result.response : void 0;
43483
43589
  const total = usageOf(result.usage);
@@ -43509,6 +43615,7 @@ ${imageError(target, reason || str2(step.state))}
43509
43615
  },
43510
43616
  flush() {
43511
43617
  const text5 = reader.flush();
43618
+ resolveContextLimit(true);
43512
43619
  if (pendingCosts.size) {
43513
43620
  const models = session ? antigravityRecordedModels(session, pendingCosts) : void 0;
43514
43621
  for (const [index, { usage: usage3 }] of pendingCosts) estimate(models?.get(index), usage3);
@@ -43531,7 +43638,10 @@ ${imageError(target, reason || str2(step.state))}
43531
43638
  usage: () => used,
43532
43639
  costUsd: () => cost,
43533
43640
  costIncomplete: () => incomplete || void 0,
43534
- context: () => context,
43641
+ context: () => {
43642
+ resolveContextLimit(false);
43643
+ return context;
43644
+ },
43535
43645
  failure: () => failure2 || imageFailure,
43536
43646
  terminalFailure: () => terminal && !!classified,
43537
43647
  executionFailure: () => classified ?? (imageFailure ? { code: "image_read_failed", level: 3, reason: imageFailure } : void 0),
@@ -43539,7 +43649,7 @@ ${imageError(target, reason || str2(step.state))}
43539
43649
  activity: events.activity
43540
43650
  };
43541
43651
  }
43542
- var KINDS, zero, usageOf, add, imagePath;
43652
+ var CONTEXT_LOOK_EVERY_MS, KINDS, zero, usageOf, add, imagePath;
43543
43653
  var init_antigravity = __esm({
43544
43654
  "src/lib/agent/wire/antigravity.ts"() {
43545
43655
  "use strict";
@@ -43549,6 +43659,7 @@ var init_antigravity = __esm({
43549
43659
  init_json();
43550
43660
  init_stream();
43551
43661
  init_antigravity_session();
43662
+ CONTEXT_LOOK_EVERY_MS = 250;
43552
43663
  KINDS = {
43553
43664
  run_command: "execute",
43554
43665
  command_status: "execute",
@@ -45950,7 +46061,7 @@ var init_codex_work = __esm({
45950
46061
  });
45951
46062
 
45952
46063
  // src/lib/agent/wire/codex.ts
45953
- import { randomUUID as randomUUID4 } from "node:crypto";
46064
+ import { randomUUID as randomUUID5 } from "node:crypto";
45954
46065
  import { setTimeout as delay } from "node:timers/promises";
45955
46066
  function createCodexConnection(argv) {
45956
46067
  const execAt = argv.indexOf("exec");
@@ -46043,7 +46154,7 @@ async function run(io, options, count3) {
46043
46154
  };
46044
46155
  const work = codexWork();
46045
46156
  const children = work.children;
46046
- const execution = randomUUID4();
46157
+ const execution = randomUUID5();
46047
46158
  let host2 = {};
46048
46159
  let cleanup = { status: "confirmed", execution, kept: [] };
46049
46160
  let settlement;
@@ -49240,6 +49351,47 @@ var init_roster = __esm({
49240
49351
  }
49241
49352
  });
49242
49353
 
49354
+ // src/lib/shared/delivery-evidence.ts
49355
+ function approvedCardRequirements(text5) {
49356
+ const { meta: meta3, body } = parseFrontmatter(text5);
49357
+ const out = [];
49358
+ if (meta3?.title) out.push(`# ${meta3.title}`, "");
49359
+ const opening = [];
49360
+ const sections = [];
49361
+ let keeping = false;
49362
+ let started = false;
49363
+ for (const line of body.split("\n")) {
49364
+ if (/^##(?!#)\s/.test(line)) {
49365
+ started = true;
49366
+ keeping = isApproved(line);
49367
+ if (keeping) sections.push("", line);
49368
+ continue;
49369
+ }
49370
+ if (line.trim() === "<!-- agent -->") continue;
49371
+ if (!started) opening.push(line);
49372
+ else if (keeping) sections.push(line);
49373
+ }
49374
+ out.push(opening.join("\n").trim());
49375
+ out.push(sections.join("\n").trim());
49376
+ return out.filter(Boolean).join("\n\n").replace(/\n{3,}/g, "\n\n").trim() + "\n";
49377
+ }
49378
+ var APPROVED, isApproved;
49379
+ var init_delivery_evidence = __esm({
49380
+ "src/lib/shared/delivery-evidence.ts"() {
49381
+ "use strict";
49382
+ init_frontmatter();
49383
+ APPROVED = [
49384
+ /^##\s+Worth noting\s*$/i,
49385
+ /^##\s+Scope\s*$/i,
49386
+ /^##\s+Scope out\s*$/i,
49387
+ // `skill` is the word a spec section carries now; `agent` is the word it carried before
49388
+ // #403, and a card written by an older release still has to travel whole.
49389
+ /^##\s+By\s+`[^`]+`\s+(skill|agent)\s*$/i
49390
+ ];
49391
+ isApproved = (heading) => APPROVED.some((re) => re.test(heading));
49392
+ }
49393
+ });
49394
+
49243
49395
  // src/lib/agent/candidate.ts
49244
49396
  function candidateBase() {
49245
49397
  return git(["rev-parse", "HEAD"])?.trim() || null;
@@ -49554,6 +49706,7 @@ function parseStore() {
49554
49706
  runs.push({
49555
49707
  sessionId: entry.sessionId,
49556
49708
  cloudExecution: executionOf(entry.cloudExecution ?? null),
49709
+ pendingWrites: entry.pendingWrites === true || void 0,
49557
49710
  cardId: typeof entry.cardId === "number" ? entry.cardId : null,
49558
49711
  createdCardIds: Array.isArray(entry.createdCardIds) ? [...new Set(entry.createdCardIds.filter((id2) => Number.isInteger(id2) && id2 > 0))] : void 0,
49559
49712
  discard: entry.discard === true || void 0,
@@ -49609,7 +49762,7 @@ function parseStore() {
49609
49762
  resumedFrom: typeof entry.resumedFrom === "string" ? entry.resumedFrom : void 0,
49610
49763
  continues: typeof entry.continues?.resumeId === "string" && entry.continues.resumeId ? { resumeId: entry.continues.resumeId, ...entry.continues.fork === true ? { fork: true } : {} } : void 0,
49611
49764
  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),
49765
+ retry: readRetry2(entry.retry, !!executionOf(entry.cloudExecution ?? null)),
49613
49766
  priorStatus: typeof entry.priorStatus === "string" ? entry.priorStatus : void 0,
49614
49767
  // The pictures the create sheet handed this run (#517), as paths in its own folder.
49615
49768
  pictures: readPictures(entry.pictures),
@@ -49651,11 +49804,11 @@ function readReasons(raw) {
49651
49804
  });
49652
49805
  return reasons.length ? reasons : void 0;
49653
49806
  }
49654
- function readRetry2(raw) {
49807
+ function readRetry2(raw, task) {
49655
49808
  if (!raw || typeof raw !== "object") return void 0;
49656
49809
  const r = raw;
49657
49810
  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;
49811
+ 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
49812
  }
49660
49813
  function readMarks(raw) {
49661
49814
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
@@ -50282,6 +50435,12 @@ function allAudits() {
50282
50435
  }
50283
50436
  return out;
50284
50437
  }
50438
+ function cardAudits(cardId2) {
50439
+ return allAudits().filter((a) => a.cardId === cardId2).flatMap((a) => {
50440
+ const row = auditRow(a);
50441
+ return row ? [row] : [];
50442
+ }).sort((a, b) => a.startedAt - b.startedAt);
50443
+ }
50285
50444
  function landedDeliveries(filter = {}) {
50286
50445
  const out = [];
50287
50446
  for (const audit of allAudits()) {
@@ -50443,27 +50602,7 @@ function approvedRequirements(cardId2) {
50443
50602
  } catch {
50444
50603
  return "";
50445
50604
  }
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";
50605
+ return approvedCardRequirements(text5);
50467
50606
  }
50468
50607
  function cardMeta2(cardId2) {
50469
50608
  try {
@@ -50602,7 +50741,7 @@ function heldByDelivery(cardId2, program2) {
50602
50741
  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
50742
  return `delivery ${delivery.deliveryId} ${doing}Discard on the card page, or \`${cmd} raw delivery cancel ${delivery.deliveryId}\` to end it here.`;
50604
50743
  }
50605
- var auditPath, activeAudits, auditRow, lastSessionRunning, localAudit, unknownDelivery, isResumable, APPROVED, isApproved, cardStatus, openQuestions, activeIn, listDeliveries, withStudio;
50744
+ var auditPath, activeAudits, auditRow, lastSessionRunning, localAudit, unknownDelivery, isResumable, cardStatus, openQuestions, activeIn, listDeliveries, withStudio;
50606
50745
  var init_deliveries = __esm({
50607
50746
  "src/lib/agent/deliveries.ts"() {
50608
50747
  "use strict";
@@ -50610,6 +50749,7 @@ var init_deliveries = __esm({
50610
50749
  init_cards();
50611
50750
  init_revision();
50612
50751
  init_frontmatter();
50752
+ init_delivery_evidence();
50613
50753
  init_paths();
50614
50754
  init_candidate();
50615
50755
  init_command();
@@ -50630,15 +50770,6 @@ var init_deliveries = __esm({
50630
50770
  localAudit = (audit) => worktreeExists(audit.worktree) || audit.sessions.some((session) => path48.resolve(REPO_ROOT, session.log) === logPathOf(session.sessionId) && fs47.existsSync(logPathOf(session.sessionId)));
50631
50771
  unknownDelivery = (id2) => refusal("deliveryNotFound", `no delivery here answers to "${id2}"`, { id: id2 });
50632
50772
  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
50773
  cardStatus = (cardId2) => cardMeta2(cardId2)?.status || "todo";
50643
50774
  openQuestions = (cardId2) => cardMeta2(cardId2)?.questions.length ?? 0;
50644
50775
  activeIn = (store, cardId2) => store.deliveries.find((d) => d.status === "active" && d.cardId === cardId2);
@@ -50937,7 +51068,7 @@ var init_run_settings = __esm({
50937
51068
  });
50938
51069
 
50939
51070
  // src/lib/agent/resolve.ts
50940
- import { randomUUID as randomUUID5 } from "node:crypto";
51071
+ import { randomUUID as randomUUID6 } from "node:crypto";
50941
51072
  function activeProviderOf({
50942
51073
  harness,
50943
51074
  values,
@@ -51116,7 +51247,7 @@ function planResume(session, agent, own2 = {}) {
51116
51247
  cwd
51117
51248
  };
51118
51249
  }
51119
- function planFork(session, agent, own2 = {}, sessionId = randomUUID5()) {
51250
+ function planFork(session, agent, own2 = {}, sessionId = randomUUID6()) {
51120
51251
  const { harness: harnessName, resumeId, cwd = REPO_ROOT } = session;
51121
51252
  if (!harnessByName(harnessName)) return null;
51122
51253
  const resolved = resolveHarness({ agent, ...own2, harness: harnessName });
@@ -52023,21 +52154,27 @@ function endAgent(child, mark, graceMs) {
52023
52154
  round(KILL_ROUNDS);
52024
52155
  });
52025
52156
  }
52026
- function processesStopped(mark, root2) {
52157
+ function probeProcesses(mark, root2) {
52027
52158
  try {
52028
52159
  if (WINDOWS3) {
52029
52160
  const list3 = procsOnWindows();
52030
- if (!list3 || !root2) return false;
52161
+ if (!list3) return { ok: false, error: "\u65E0\u6CD5\u67E5\u8BE2\u8FDB\u7A0B\u5217\u8868\u3002" };
52162
+ if (!root2) return { ok: false, error: "\u7F3A\u5C11\u8FDB\u7A0B\u8D77\u70B9\uFF0C\u65E0\u6CD5\u6838\u5BF9\u9000\u51FA\u72B6\u6001\u3002" };
52031
52163
  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;
52164
+ if (current && current.startedAt > root2.since) return { ok: false, error: "\u8FDB\u7A0B\u53F7\u5DF2\u88AB\u590D\u7528\u3002" };
52165
+ return { ok: true, alive: startedUnder(list3, root2.pid, root2.since).length > 0 };
52034
52166
  }
52035
52167
  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;
52168
+ const pids = process.platform === "linux" ? markedInProc(entry, true, mark.since) : markedInPs(entry, root2 ? [root2.pid] : []);
52169
+ return { ok: true, alive: pids.length > 0 };
52170
+ } catch (e) {
52171
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
52039
52172
  }
52040
52173
  }
52174
+ function processesStopped(mark, root2) {
52175
+ const probed = probeProcesses(mark, root2);
52176
+ return probed.ok && !probed.alive;
52177
+ }
52041
52178
  var runMark, WINDOWS3, KILL_ROUND_MS, KILL_ROUNDS, LIST_PROCS;
52042
52179
  var init_stop = __esm({
52043
52180
  "src/lib/agent/stop.ts"() {
@@ -52080,7 +52217,7 @@ var init_creation_lock = __esm({
52080
52217
  });
52081
52218
 
52082
52219
  // src/lib/agent/sessions.ts
52083
- import { randomUUID as randomUUID6 } from "node:crypto";
52220
+ import { randomUUID as randomUUID7 } from "node:crypto";
52084
52221
  import fs51 from "node:fs";
52085
52222
  import path54 from "node:path";
52086
52223
  function reap(runs, reaped = [], restore = []) {
@@ -52362,7 +52499,7 @@ function approvedDirect(req) {
52362
52499
  const typed = req.description?.trim();
52363
52500
  return typed ? { title: typed, approved: typed } : void 0;
52364
52501
  }
52365
- function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said2) {
52502
+ function openRun(req, prompt, notes = [], sessionId = randomUUID7(), said2) {
52366
52503
  const retired = retiredStudioRun(req.action);
52367
52504
  if (retired) return retired;
52368
52505
  if (req.deliveryId && findDelivery(req.deliveryId)?.scheduled) return retiredStudioRun("scheduled");
@@ -52427,7 +52564,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said2) {
52427
52564
  // Internal refinement sessions name their position in the request. A standalone
52428
52565
  // resolve carries no round.
52429
52566
  refineRound: req.refineRound,
52430
- flowId: parent?.flowId ?? req.flowId ?? randomUUID6(),
52567
+ flowId: parent?.flowId ?? req.flowId ?? randomUUID7(),
52431
52568
  ...parent ? { parentId: parent.sessionId, deliveryId: parent.deliveryId, specAgent: req.specAgent } : {}
52432
52569
  };
52433
52570
  const out = withCreationLock(() => withStore((store) => {
@@ -52472,7 +52609,7 @@ function carriedSession(req) {
52472
52609
  const fresh = (why2) => ({ note: `new session \u2014 ${why2}` });
52473
52610
  if (req.session === "new") return fresh("the earlier one is gone, so this step was started again");
52474
52611
  const agent = agentForRun(req);
52475
- const own2 = planRun(randomUUID6(), REPO_ROOT, agent, req.runtime ? { pin: req.runtime } : {});
52612
+ const own2 = planRun(randomUUID7(), REPO_ROOT, agent, req.runtime ? { pin: req.runtime } : {});
52476
52613
  const resumeId = req.carry?.resumeId;
52477
52614
  const found2 = resumeId ? { session: { harness: own2.harness, resumeId }, fork: req.carry?.fork === true } : planningSession(req.id);
52478
52615
  if ("none" in found2) {
@@ -52486,7 +52623,7 @@ function carriedSession(req) {
52486
52623
  const pin = { pin: own2.runtime };
52487
52624
  return found2.fork ? planFork(session, agent, pin, sessionId) : planResume(session, agent, pin);
52488
52625
  };
52489
- if (!plan(REPO_ROOT, randomUUID6())) {
52626
+ if (!plan(REPO_ROOT, randomUUID7())) {
52490
52627
  return fresh(`${harnessLabel(own2.harness)} cannot ${found2.fork ? "copy a session" : "continue an earlier session"}`);
52491
52628
  }
52492
52629
  return {
@@ -52557,7 +52694,7 @@ async function openResume(id2, options) {
52557
52694
  stopped: stopped2,
52558
52695
  session,
52559
52696
  replayable: !requireSession && neverStarted(prev),
52560
- unconfirmedCleanup: prev.cleanup?.status === "unconfirmed" || prev.managedProcess && (pending?.failure ?? prev.failure)?.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session)
52697
+ unconfirmedCleanup: prev.pendingWrites || prev.cleanup?.status === "unconfirmed" || prev.managedProcess && (pending?.failure ?? prev.failure)?.code === "idle_timeout" && !idleStopConfirmed(prev.cleanup, session)
52561
52698
  });
52562
52699
  if (recovery === "unsafe") {
52563
52700
  if (pending) return retryRefusal(prev, "unsafe");
@@ -52568,7 +52705,7 @@ async function openResume(id2, options) {
52568
52705
  }
52569
52706
  const resuming = prev.deliveryId ? findDelivery(prev.deliveryId) : void 0;
52570
52707
  const cwd = deliveryCwd(resuming ?? {});
52571
- const sessionId = randomUUID6();
52708
+ const sessionId = randomUUID7();
52572
52709
  let plan;
52573
52710
  let fresh;
52574
52711
  if (!forced && prev.harness === "antigravity" && !session && !neverStarted(prev)) {
@@ -52864,6 +53001,152 @@ async function runIsDown(sessionId) {
52864
53001
  await sleep3(STOP_POLL_MS);
52865
53002
  }
52866
53003
  }
53004
+ function verifyDeliveryRunsStopped(runs, deliveryId, cardId2) {
53005
+ const related = runs.filter(
53006
+ (r) => r.action !== "sub" && (r.deliveryId === deliveryId || r.cardId === cardId2 && holdsCard(r.action))
53007
+ );
53008
+ for (const r of related) {
53009
+ if (r.managedProcess) {
53010
+ if (!connectionStopped(r.agentPid ? { pid: r.agentPid, identity: r.agentIdentity } : void 0)) {
53011
+ return `Associated managed agent process for run ${r.sessionId} is still alive without an active watcher.`;
53012
+ }
53013
+ continue;
53014
+ }
53015
+ if (r.pid || r.agentPid) {
53016
+ const probed = probeProcesses(
53017
+ runMark(r.sessionId, r.agentStartedAt ?? r.startedAt),
53018
+ r.agentPid && r.agentStartedAt ? { pid: r.agentPid, since: r.agentStartedAt } : void 0
53019
+ );
53020
+ if (!probed.ok) return probed.error;
53021
+ if (probed.alive) {
53022
+ return `Associated delivery process for run ${r.sessionId} is still alive without an active watcher.`;
53023
+ }
53024
+ }
53025
+ }
53026
+ return void 0;
53027
+ }
53028
+ async function reconcileCardDelivery(cardId2) {
53029
+ const reaped = [];
53030
+ const restore = [];
53031
+ let result;
53032
+ try {
53033
+ result = withStore((store) => {
53034
+ reap(store.runs, reaped, restore);
53035
+ const file2 = cardFile(cardId2);
53036
+ const restoredRaw = file2 ? parseFrontmatter(fs51.readFileSync(file2, "utf8")).meta?.restored : void 0;
53037
+ const restoredAt = restoredRaw ? Date.parse(restoredRaw) : Number.NaN;
53038
+ const merged = /* @__PURE__ */ new Map();
53039
+ for (const audit of cardAudits(cardId2)) merged.set(audit.deliveryId, audit);
53040
+ for (const row of store.deliveries) {
53041
+ if (row.cardId === cardId2) merged.set(row.deliveryId, row);
53042
+ }
53043
+ const deliveries = [...merged.values()].filter((d) => !(Number.isFinite(restoredAt) && restoredAt > d.startedAt)).sort((a, b) => a.startedAt - b.startedAt);
53044
+ const activeOrLatest = deliveries.find((d) => d.status === "active") ?? deliveries.filter((d) => d.status !== "cancelled").pop();
53045
+ const liveRun = store.runs.find(
53046
+ (r) => r.status === "running" && r.action !== "sub" && !!r.deliveryId && (r.cardId === cardId2 || activeOrLatest && r.deliveryId === activeOrLatest.deliveryId)
53047
+ );
53048
+ if (liveRun) {
53049
+ return {
53050
+ kind: "running",
53051
+ deliveryId: liveRun.deliveryId ?? activeOrLatest?.deliveryId,
53052
+ sessionId: liveRun.sessionId,
53053
+ action: liveRun.action
53054
+ };
53055
+ }
53056
+ if (!activeOrLatest) return { kind: "none" };
53057
+ if (activeOrLatest.status === "finished" || activeOrLatest.completions?.some((c) => c.finished)) {
53058
+ const lastSession = activeOrLatest.sessions[activeOrLatest.sessions.length - 1];
53059
+ const code = activeOrLatest.completions?.slice().reverse().find((c) => c.commit);
53060
+ return {
53061
+ kind: "completed",
53062
+ deliveryId: activeOrLatest.deliveryId,
53063
+ sessionId: lastSession,
53064
+ commit: activeOrLatest.landing?.commit ?? code?.commit,
53065
+ branch: activeOrLatest.targetBranch ?? code?.branch
53066
+ };
53067
+ }
53068
+ const refused = resumeRefusal(activeOrLatest, store);
53069
+ if (refused) {
53070
+ return {
53071
+ kind: "unverified",
53072
+ deliveryId: activeOrLatest.deliveryId,
53073
+ diagnostic: refused.error
53074
+ };
53075
+ }
53076
+ const processError = verifyDeliveryRunsStopped(store.runs, activeOrLatest.deliveryId, cardId2);
53077
+ if (processError) {
53078
+ return {
53079
+ kind: "unverified",
53080
+ deliveryId: activeOrLatest.deliveryId,
53081
+ diagnostic: processError
53082
+ };
53083
+ }
53084
+ const lastRun = store.runs.filter((r) => r.deliveryId === activeOrLatest.deliveryId && r.action !== "sub").sort((a, b) => a.startedAt - b.startedAt).pop();
53085
+ return {
53086
+ kind: "resumable",
53087
+ deliveryId: activeOrLatest.deliveryId,
53088
+ status: activeOrLatest.status,
53089
+ sessionId: lastRun?.sessionId,
53090
+ hasSession: !!(lastRun && resumeSessionId(lastRun)),
53091
+ worktree: activeOrLatest.worktree,
53092
+ branch: activeOrLatest.branch,
53093
+ base: activeOrLatest.base
53094
+ };
53095
+ });
53096
+ } catch (error62) {
53097
+ return {
53098
+ kind: "unverified",
53099
+ diagnostic: error62 instanceof Error ? error62.message : String(error62)
53100
+ };
53101
+ }
53102
+ for (const run3 of restore) await restoreCardStatus(run3);
53103
+ for (const run3 of reaped) await settleDelivery(run3);
53104
+ return result;
53105
+ }
53106
+ async function releaseCardDelivery(cardId2) {
53107
+ const execution = executionOf();
53108
+ if (execution && !await executionHeld(execution)) {
53109
+ 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" };
53110
+ }
53111
+ const reaped = [];
53112
+ const restore = [];
53113
+ let releasedDelivery;
53114
+ let outcome;
53115
+ try {
53116
+ outcome = withStore((store) => {
53117
+ reap(store.runs, reaped, restore);
53118
+ const active3 = activeIn(store, cardId2);
53119
+ if (!active3) return { ok: true, released: false };
53120
+ const liveRun = store.runs.find(
53121
+ (r) => r.status === "running" && r.action !== "sub" && (r.cardId === cardId2 || r.deliveryId === active3.deliveryId)
53122
+ );
53123
+ if (liveRun) {
53124
+ return {
53125
+ ok: false,
53126
+ deliveryId: active3.deliveryId,
53127
+ error: `\u539F\u4EA4\u4ED8\u4ECD\u6709\u8FD0\u884C\u4E2D\u7684\u8FDB\u7A0B (${liveRun.sessionId})\uFF0C\u65E0\u6CD5\u91CA\u653E\u5199\u9501\u3002`
53128
+ };
53129
+ }
53130
+ const processError = verifyDeliveryRunsStopped(store.runs, active3.deliveryId, cardId2);
53131
+ if (processError) {
53132
+ return { ok: false, deliveryId: active3.deliveryId, error: processError };
53133
+ }
53134
+ const at = Date.now();
53135
+ active3.status = "failed";
53136
+ active3.endedAt = at;
53137
+ active3.steps.push({ step: "released", at });
53138
+ writeAudit(active3, store.runs);
53139
+ releasedDelivery = { ...active3 };
53140
+ return { ok: true, released: true, deliveryId: active3.deliveryId };
53141
+ });
53142
+ } catch (error62) {
53143
+ return { ok: false, error: error62 instanceof Error ? error62.message : String(error62) };
53144
+ }
53145
+ for (const run3 of restore) await restoreCardStatus(run3);
53146
+ for (const run3 of reaped) await settleDelivery(run3);
53147
+ if (releasedDelivery) await releaseCard(releasedDelivery);
53148
+ return outcome;
53149
+ }
52867
53150
  async function resumeDelivery(id2) {
52868
53151
  if (!id2.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to carry on", { action: "resume" }) };
52869
53152
  const execution = executionOf();
@@ -62076,7 +62359,7 @@ var init_describe_project = __esm({
62076
62359
  var discuss_goal_default;
62077
62360
  var init_discuss_goal = __esm({
62078
62361
  "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';
62362
+ 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- **Save**: in a web discussion, use `akb goal` in the current session, including on retry. Say the goal is ready to save when the reply ends. If the command still fails, say it was not saved.\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
62363
  }
62081
62364
  });
62082
62365
 
@@ -62092,7 +62375,7 @@ var init_follow_up = __esm({
62092
62375
  var implement_default;
62093
62376
  var init_implement = __esm({
62094
62377
  "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";
62378
+ 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";
62096
62379
  }
62097
62380
  });
62098
62381
 
@@ -62132,7 +62415,7 @@ var init_review_rejections = __esm({
62132
62415
  var refine_default;
62133
62416
  var init_refine = __esm({
62134
62417
  "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';
62418
+ 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
62419
  }
62137
62420
  });
62138
62421
 
@@ -62693,7 +62976,7 @@ var init_complete = __esm({
62693
62976
  });
62694
62977
 
62695
62978
  // src/lib/agent/start.ts
62696
- import { randomUUID as randomUUID7 } from "node:crypto";
62979
+ import { randomUUID as randomUUID8 } from "node:crypto";
62697
62980
  async function startRun(req) {
62698
62981
  const short2 = retiredStudioRun(req.action) ?? studioRefusal(req);
62699
62982
  if (short2) return short2;
@@ -62702,7 +62985,7 @@ async function startRun(req) {
62702
62985
  const previous = readRuns().filter((r) => r.deliveryId === delivery.deliveryId && r.action === "implement").reverse().sort((a, b) => b.startedAt - a.startedAt)[0];
62703
62986
  if (previous && !delivery.completions?.some((c) => c.sessionId === previous.sessionId || c.resumedSessions?.includes(previous.sessionId))) return startResume(previous.sessionId, { deliveryId: delivery.deliveryId, notes: req.notes });
62704
62987
  }
62705
- return open3(req, randomUUID7());
62988
+ return open3(req, randomUUID8());
62706
62989
  }
62707
62990
  function studioRefusal(req) {
62708
62991
  if (!Number.isInteger(req.id)) return null;
@@ -62731,7 +63014,7 @@ function startSubRun(parentId, prompt, runtime) {
62731
63014
  specAgent: parent.agent,
62732
63015
  runtime: runtime ?? inherited
62733
63016
  },
62734
- randomUUID7()
63017
+ randomUUID8()
62735
63018
  );
62736
63019
  }
62737
63020
  function runAsk(req, sessionId) {
@@ -63720,7 +64003,7 @@ var init_approved_ui = __esm({
63720
64003
  init_preview_blocks();
63721
64004
  init_review_plan();
63722
64005
  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.";
64006
+ APPROVED_UI_RULE = "Open the approved mockups and follow the Coding Studio delivery requirements for matching the task's intended UI changes.";
63724
64007
  UI_PREVIEW = "ui-design";
63725
64008
  historicalUiIds = Object.keys(CODING_PREVIEWS).filter((id2) => id2 !== UI_PREVIEW && CODING_PREVIEWS[id2] === UI_PREVIEW);
63726
64009
  object2 = (value) => isObject2(value) ? value : {};
@@ -63840,8 +64123,14 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
63840
64123
  const pendingOperations = /* @__PURE__ */ new Set();
63841
64124
  const event2 = (e) => {
63842
64125
  observeActivity(e);
64126
+ const hadPending = pendingOperations.size > 0;
63843
64127
  if (e.kind === "tool_call" && !["read", "search", "fetch"].includes(e.data.kind) && !["completed", "failed"].includes(e.data.status)) pendingOperations.add(e.data.toolCallId);
63844
64128
  if ((e.kind === "tool_call" || e.kind === "tool_call_update") && ["completed", "failed"].includes(e.data.status ?? "")) pendingOperations.delete(e.data.toolCallId);
64129
+ if (record2.cloudExecution && hadPending !== pendingOperations.size > 0) {
64130
+ patch(sessionId, (run4) => {
64131
+ run4.pendingWrites = pendingOperations.size > 0;
64132
+ });
64133
+ }
63845
64134
  eventsFile.write(`${JSON.stringify(e)}
63846
64135
  `);
63847
64136
  };
@@ -64099,7 +64388,7 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64099
64388
  let retrying = false;
64100
64389
  if (failure2 && !sub && !taskCompleted) {
64101
64390
  const attempt2 = held4.retry?.attempt ?? 1;
64102
- const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff);
64391
+ const decision = planRetry(failure2, attempt2, Date.now(), retryBackoff, !!held4.cloudExecution);
64103
64392
  if ("pause" in decision) retryPause = decision.pause;
64104
64393
  else {
64105
64394
  const mark = runMark(sessionId, agentStartedAt);
@@ -64112,7 +64401,7 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64112
64401
  stopped: stopped3(),
64113
64402
  session,
64114
64403
  replayable: held4.unspawned === true && !pendingOperations.size,
64115
- unconfirmedCleanup: !!blocker || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, session))
64404
+ unconfirmedCleanup: pendingOperations.size > 0 || !!blocker || spoken?.cleanup?.status === "unconfirmed" || client?.managedProcess && silent && (uncertainAtIdle || !idleStopConfirmed(spoken?.cleanup, session))
64116
64405
  });
64117
64406
  if (recovery === "unsafe") retryPause = "unsafe";
64118
64407
  else {
@@ -64564,6 +64853,23 @@ async function cmdCancel(named2) {
64564
64853
  say(`delivery ${res.deliveryId} cancelled \u2014 files, branches and directories are preserved.`);
64565
64854
  return { deliveryId: res.deliveryId };
64566
64855
  }
64856
+ async function cmdReconcileDelivery(cardId2) {
64857
+ const result = await reconcileCardDelivery(cardId2);
64858
+ if (result.kind === "unverified") {
64859
+ say(`delivery${result.deliveryId ? ` ${result.deliveryId}` : ""}: unverified \u2014 ${result.diagnostic}`);
64860
+ } else if (result.kind === "none") {
64861
+ say(`#${cardId2}: no delivery to reconcile`);
64862
+ } else {
64863
+ say(`#${cardId2}: ${result.kind}${result.deliveryId ? ` (${result.deliveryId})` : ""}`);
64864
+ }
64865
+ return result;
64866
+ }
64867
+ async function cmdReleaseDelivery(cardId2) {
64868
+ const res = await releaseCardDelivery(cardId2);
64869
+ if (!res.ok) die(res.error, { kind: "run-refused", ...res.deliveryId ? { deliveryId: res.deliveryId } : {} });
64870
+ say(res.released ? `delivery ${res.deliveryId} lock released \u2014 files and branch preserved.` : `#${cardId2}: no active delivery lock to release.`);
64871
+ return res;
64872
+ }
64567
64873
  async function cmdResumeDelivery(named2) {
64568
64874
  const res = await resumeBoardDelivery(named2);
64569
64875
  if (!res.ok) die(res.error ?? "that delivery could not be carried on", {
@@ -65364,7 +65670,7 @@ var init_previews = __esm({
65364
65670
  // src/commands/studio-preview.ts
65365
65671
  import fs85 from "node:fs";
65366
65672
  import path84 from "node:path";
65367
- import { createHash as createHash9, randomUUID as randomUUID8 } from "node:crypto";
65673
+ import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
65368
65674
  import { spawnSync as spawnSync7 } from "node:child_process";
65369
65675
  function readFolder2(folder2, baseline = false) {
65370
65676
  const root2 = fs85.realpathSync(folder2);
@@ -65401,7 +65707,7 @@ ${start < 0 ? "" : lines.slice(start + 2).join("\n")}`;
65401
65707
  }
65402
65708
  async function cmdStudioPreview(id2, opts) {
65403
65709
  if (!locate(id2)) die(`no card ${id2}`, "no-such-card");
65404
- const destination = path84.join(ASSETS, String(id2), "studio-review"), staging = `${destination}.${randomUUID8()}.tmp`, backup = `${destination}.${randomUUID8()}.previous`;
65710
+ const destination = path84.join(ASSETS, String(id2), "studio-review"), staging = `${destination}.${randomUUID9()}.tmp`, backup = `${destination}.${randomUUID9()}.previous`;
65405
65711
  let moved = false;
65406
65712
  try {
65407
65713
  const draft = readFolder2(path84.resolve(opts.folder)), base = opts.base === "empty" ? null : readFolder2(path84.resolve(opts.base), true);
@@ -65902,6 +66208,14 @@ function declareDelivery(delivery, cli) {
65902
66208
  const [named2] = positional(vals);
65903
66209
  await onBoard(this, cli, () => cmdResumeDelivery(named2));
65904
66210
  });
66211
+ verb("reconcile").argument("<card>", "card number", cardId).summary("reconcile local delivery state for a card before recovery").action(async function(...vals) {
66212
+ const [id2] = positional(vals);
66213
+ await onBoard(this, cli, () => cmdReconcileDelivery(id2));
66214
+ });
66215
+ verb("release").argument("<card>", "card number", cardId).summary("safely release an active delivery write lock while preserving saved work").action(async function(...vals) {
66216
+ const [id2] = positional(vals);
66217
+ await onBoard(this, cli, () => cmdReleaseDelivery(id2));
66218
+ });
65905
66219
  }
65906
66220
  function declareFlow(parent, flow, cli) {
65907
66221
  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.82",
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": [