wildcrane-runner 0.6.103 → 0.6.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.83 — built by runner/scripts/build.mjs. Do not edit.
2
+ // ai4kanban 0.11.85 — built by runner/scripts/build.mjs. Do not edit.
3
3
  import { createRequire as __ai4kanbanRequire } from 'node:module'
4
4
  const require = __ai4kanbanRequire(import.meta.url)
5
5
  var __create = Object.create;
@@ -139,6 +139,57 @@ var init_io = __esm({
139
139
  }
140
140
  });
141
141
 
142
+ // ../cli/src/lib/cloud/response.ts
143
+ function temporaryCloudFailure({ code, status }) {
144
+ if (code && ["unauthenticated", "machine_offline", "quota_exceeded", "daily_write_budget_reached", "storage_limit_reached"].includes(code)) return false;
145
+ return ["unreachable", "invalid_response", "idempotency_in_progress", "service_unavailable", "artifacts_unavailable"].includes(code ?? "") || status === 408 || (status !== void 0 ? status >= 500 : !code);
146
+ }
147
+ async function readCloudJson(response) {
148
+ return response.json().catch(() => void 0);
149
+ }
150
+ function cloudProblem(response, body) {
151
+ const error62 = isRecord(body) && isRecord(body.error) ? body.error : null;
152
+ if (response.ok && !error62) return null;
153
+ const status = response.status;
154
+ const code = hasText(error62?.code) ? error62.code : status === 401 ? "unauthenticated" : status >= 500 ? "service_unavailable" : "refused";
155
+ const message = hasText(error62?.message) ? error62.message : `Cloud answered ${status}.`;
156
+ return { code, message, status, retryable: temporaryCloudFailure({ code, status }) };
157
+ }
158
+ function cloudError(problem, options = {}) {
159
+ return new BoardError(problem.message, {
160
+ bare: options.bare,
161
+ exitCode: options.exitCode,
162
+ ...options.details,
163
+ kind: options.kind ?? problem.code,
164
+ code: problem.code,
165
+ status: problem.status,
166
+ retryable: problem.retryable
167
+ });
168
+ }
169
+ function requireResponse(value, expected, check2) {
170
+ if (!isRecord(value) || !check2(value)) throw cloudError(invalidResponse(expected));
171
+ return value;
172
+ }
173
+ async function cloudBytes(response, expected, options = {}) {
174
+ const bytes2 = await response.arrayBuffer().then((data) => Buffer.from(data), () => null);
175
+ const length = response.headers.get("content-length");
176
+ const compressed = response.headers.has("content-encoding");
177
+ if (response.status !== 200 || response.headers.has("content-range") || !bytes2 || options.size === void 0 && !bytes2.length || length !== null && !compressed && (!/^\d+$/.test(length) || bytes2.length !== Number(length)) || options.size !== void 0 && bytes2.length !== options.size) {
178
+ throw cloudError(invalidResponse(expected));
179
+ }
180
+ return bytes2;
181
+ }
182
+ var isRecord, hasText, invalidResponse;
183
+ var init_response = __esm({
184
+ "../cli/src/lib/cloud/response.ts"() {
185
+ "use strict";
186
+ init_io();
187
+ isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
188
+ hasText = (value) => typeof value === "string" && !!value.trim();
189
+ invalidResponse = (expected) => ({ code: "invalid_response", message: `Cloud did not return ${expected}.`, retryable: true });
190
+ }
191
+ });
192
+
142
193
  // ../cli/src/lib/machine/project.ts
143
194
  import fs from "node:fs";
144
195
  import path from "node:path";
@@ -389,12 +440,17 @@ async function approveAfterReply(task, comment, target) {
389
440
  signal: AbortSignal.timeout(12e4)
390
441
  });
391
442
  const result = await response.json();
392
- if (!result.ok || !result.value) throw Error(result.error ?? "The request was not accepted.");
393
- const held4 = result.value;
443
+ if (!response.ok || result?.ok === false) throw cloudError({ code: "refused", message: result?.error ?? "The request was not accepted.", retryable: false });
444
+ const held4 = requireResponse(
445
+ result?.value,
446
+ "a reply approval receipt",
447
+ (value) => !!value && hasText(value.id) && hasText(value.task) && ["pending", "committed", "cancelled"].includes(value.status)
448
+ );
394
449
  if (held4.status === "cancelled") throw Error(held4.reason ?? "The request was cancelled. Ask again in a new reply.");
395
450
  say(held4.status === "pending" ? `Approval pending for ${task}; it will be checked after this reply finishes.` : `Approval already committed for ${task}.`);
396
451
  return { ...held4, pending: held4.status === "pending" };
397
452
  } catch (e) {
453
+ if (e instanceof BoardError) throw e;
398
454
  return die(e instanceof Error ? e.message : "Reply approval failed.", { kind: "refused" });
399
455
  }
400
456
  }
@@ -403,6 +459,7 @@ var init_reply_approval = __esm({
403
459
  "../cli/src/lib/cloud/reply-approval.ts"() {
404
460
  "use strict";
405
461
  init_io();
462
+ init_response();
406
463
  init_paths();
407
464
  REPLY_APPROVAL_ENV = "AI4KANBAN_REPLY_APPROVAL";
408
465
  }
@@ -504,9 +561,9 @@ function assertNever(_x) {
504
561
  }
505
562
  function assert(_) {
506
563
  }
507
- function getEnumValues(entries) {
508
- const numericValues = Object.values(entries).filter((v) => typeof v === "number");
509
- const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
564
+ function getEnumValues(entries2) {
565
+ const numericValues = Object.values(entries2).filter((v) => typeof v === "number");
566
+ const values = Object.entries(entries2).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
510
567
  return values;
511
568
  }
512
569
  function joinValues(array2, separator = "|") {
@@ -630,10 +687,10 @@ function mergeDefs(...defs) {
630
687
  function cloneDef(schema) {
631
688
  return mergeDefs(schema._zod.def);
632
689
  }
633
- function getElementAtPath(obj3, path87) {
634
- if (!path87)
690
+ function getElementAtPath(obj3, path88) {
691
+ if (!path88)
635
692
  return obj3;
636
- return path87.reduce((acc, key) => acc?.[key], obj3);
693
+ return path88.reduce((acc, key) => acc?.[key], obj3);
637
694
  }
638
695
  function promiseAllObject(promisesObj) {
639
696
  const keys = Object.keys(promisesObj);
@@ -892,11 +949,11 @@ function explicitlyAborted(x, startIndex = 0) {
892
949
  }
893
950
  return false;
894
951
  }
895
- function prefixIssues(path87, issues) {
952
+ function prefixIssues(path88, issues) {
896
953
  return issues.map((iss) => {
897
954
  var _a3;
898
955
  (_a3 = iss).path ?? (_a3.path = []);
899
- iss.path.unshift(path87);
956
+ iss.path.unshift(path88);
900
957
  return iss;
901
958
  });
902
959
  }
@@ -1429,16 +1486,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
1429
1486
  }
1430
1487
  function formatError(error62, mapper = (issue2) => issue2.message) {
1431
1488
  const fieldErrors = { _errors: [] };
1432
- const processError = (error63, path87 = []) => {
1489
+ const processError = (error63, path88 = []) => {
1433
1490
  for (const issue2 of error63.issues) {
1434
1491
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1435
- issue2.errors.map((issues) => processError({ issues }, [...path87, ...issue2.path]));
1492
+ issue2.errors.map((issues) => processError({ issues }, [...path88, ...issue2.path]));
1436
1493
  } else if (issue2.code === "invalid_key") {
1437
- processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
1494
+ processError({ issues: issue2.issues }, [...path88, ...issue2.path]);
1438
1495
  } else if (issue2.code === "invalid_element") {
1439
- processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
1496
+ processError({ issues: issue2.issues }, [...path88, ...issue2.path]);
1440
1497
  } else {
1441
- const fullpath = [...path87, ...issue2.path];
1498
+ const fullpath = [...path88, ...issue2.path];
1442
1499
  if (fullpath.length === 0) {
1443
1500
  fieldErrors._errors.push(mapper(issue2));
1444
1501
  } else {
@@ -1477,17 +1534,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
1477
1534
  }
1478
1535
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
1479
1536
  const result = { errors: [] };
1480
- const processError = (error63, path87 = []) => {
1537
+ const processError = (error63, path88 = []) => {
1481
1538
  var _a3;
1482
1539
  for (const issue2 of error63.issues) {
1483
1540
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1484
- issue2.errors.map((issues) => processError({ issues }, [...path87, ...issue2.path]));
1541
+ issue2.errors.map((issues) => processError({ issues }, [...path88, ...issue2.path]));
1485
1542
  } else if (issue2.code === "invalid_key") {
1486
- processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
1543
+ processError({ issues: issue2.issues }, [...path88, ...issue2.path]);
1487
1544
  } else if (issue2.code === "invalid_element") {
1488
- processError({ issues: issue2.issues }, [...path87, ...issue2.path]);
1545
+ processError({ issues: issue2.issues }, [...path88, ...issue2.path]);
1489
1546
  } else {
1490
- const fullpath = [...path87, ...issue2.path];
1547
+ const fullpath = [...path88, ...issue2.path];
1491
1548
  if (fullpath.length === 0) {
1492
1549
  result.errors.push(mapper(issue2));
1493
1550
  continue;
@@ -1526,8 +1583,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
1526
1583
  }
1527
1584
  function toDotPath(_path) {
1528
1585
  const segs = [];
1529
- const path87 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1530
- for (const seg of path87) {
1586
+ const path88 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1587
+ for (const seg of path88) {
1531
1588
  if (typeof seg === "number")
1532
1589
  segs.push(`[${seg}]`);
1533
1590
  else if (typeof seg === "symbol")
@@ -2378,16 +2435,16 @@ var init_checks = __esm({
2378
2435
  hide(inst, Symbol.iterator, function* () {
2379
2436
  yield inst;
2380
2437
  });
2381
- let entries;
2438
+ let entries2;
2382
2439
  inst._zod.check = (payload) => {
2383
2440
  if (payload.value == null) {
2384
2441
  payload.issues.push({ expected: "object", code: "invalid_type", input: payload.value, inst });
2385
2442
  return void 0;
2386
2443
  }
2387
- entries ?? (entries = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));
2444
+ entries2 ?? (entries2 = Reflect.ownKeys(def.shape).map((key) => [key, def.shape[key]]));
2388
2445
  const input2 = payload.value;
2389
2446
  let proms;
2390
- for (const [key, schema] of entries) {
2447
+ for (const [key, schema] of entries2) {
2391
2448
  const result = schema._zod.run({ value: input2[key], issues: [] }, {});
2392
2449
  if (result instanceof Promise) {
2393
2450
  proms ?? (proms = []);
@@ -15686,18 +15743,18 @@ function _set(Class2, valueType, params) {
15686
15743
  }
15687
15744
  // @__NO_SIDE_EFFECTS__
15688
15745
  function _enum(Class2, values, params) {
15689
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
15746
+ const entries2 = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
15690
15747
  return new Class2({
15691
15748
  type: "enum",
15692
- entries,
15749
+ entries: entries2,
15693
15750
  ...normalizeParams(params)
15694
15751
  });
15695
15752
  }
15696
15753
  // @__NO_SIDE_EFFECTS__
15697
- function _nativeEnum(Class2, entries, params) {
15754
+ function _nativeEnum(Class2, entries2, params) {
15698
15755
  return new Class2({
15699
15756
  type: "enum",
15700
- entries,
15757
+ entries: entries2,
15701
15758
  ...normalizeParams(params)
15702
15759
  });
15703
15760
  }
@@ -16634,12 +16691,12 @@ function toJSONSchema(input2, params) {
16634
16691
  processSchema(schema, ctx2);
16635
16692
  }
16636
16693
  const schemas = {};
16637
- const external = {
16694
+ const external2 = {
16638
16695
  registry: registry2,
16639
16696
  uri: params?.uri,
16640
16697
  defs
16641
16698
  };
16642
- ctx2.external = external;
16699
+ ctx2.external = external2;
16643
16700
  for (const entry of registry2._idmap.entries()) {
16644
16701
  const [key, schema] = entry;
16645
16702
  extractDefs(ctx2, schema);
@@ -18284,17 +18341,17 @@ function set(valueType, params) {
18284
18341
  });
18285
18342
  }
18286
18343
  function _enum2(values, params) {
18287
- const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
18344
+ const entries2 = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
18288
18345
  return new ZodEnum({
18289
18346
  type: "enum",
18290
- entries,
18347
+ entries: entries2,
18291
18348
  ...util_exports.normalizeParams(params)
18292
18349
  });
18293
18350
  }
18294
- function nativeEnum(entries, params) {
18351
+ function nativeEnum(entries2, params) {
18295
18352
  return new ZodEnum({
18296
18353
  type: "enum",
18297
- entries,
18354
+ entries: entries2,
18298
18355
  ...util_exports.normalizeParams(params)
18299
18356
  });
18300
18357
  }
@@ -19559,13 +19616,13 @@ function resolveRef(ref, ctx) {
19559
19616
  if (!ref.startsWith("#")) {
19560
19617
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19561
19618
  }
19562
- const path87 = ref.slice(1).split("/").filter(Boolean);
19563
- if (path87.length === 0) {
19619
+ const path88 = ref.slice(1).split("/").filter(Boolean);
19620
+ if (path88.length === 0) {
19564
19621
  return ctx.rootSchema;
19565
19622
  }
19566
19623
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19567
- if (path87[0] === defsKey) {
19568
- const key = path87[1] === void 0 ? void 0 : decodeJSONPointerSegment(path87[1]);
19624
+ if (path88[0] === defsKey) {
19625
+ const key = path88[1] === void 0 ? void 0 : decodeJSONPointerSegment(path88[1]);
19569
19626
  if (!key || !ctx.defs[key]) {
19570
19627
  throw new Error(`Reference not found: ${ref}`);
19571
19628
  }
@@ -21003,7 +21060,6 @@ function readReviewPlan(plan) {
21003
21060
  return plan?.map(({ id: id2, after: after2, previews, kind }) => ({ id: id2, after: after2, previews, ...kind && { kind } })) ?? null;
21004
21061
  }
21005
21062
  function reviewAuthorization(review, assigned, dispatchRevision) {
21006
- if (review.pending_plan) return { kind: "waiting" };
21007
21063
  const states2 = new Map(review.stages.map((stage) => [stage.id, stage]));
21008
21064
  const nodes = (review.plan ?? []).filter((node2) => {
21009
21065
  const stage = states2.get(node2.id);
@@ -21125,21 +21181,30 @@ import path4 from "node:path";
21125
21181
  function readRetry(session) {
21126
21182
  try {
21127
21183
  const retry2 = JSON.parse(fs3.readFileSync(retryFile(), "utf8"));
21184
+ if (!retry2.source && ["fetch failed", "The operation was aborted due to timeout"].includes(retry2.error)) return;
21128
21185
  if (retry2.key === refreshKey(session) && Number.isFinite(retry2.until) && Number.isInteger(retry2.attempt) && retry2.attempt > 0 && typeof retry2.error === "string") return retry2;
21129
21186
  } catch {
21130
21187
  }
21131
21188
  }
21132
- function deferRefresh(session, error62, after2) {
21189
+ function readTransportRetry(session) {
21190
+ if (transportRetry?.file === retryFile() && transportRetry.key === refreshKey(session)) return transportRetry;
21191
+ }
21192
+ function deferRefresh(session, error62, { after: after2, transport = false } = {}) {
21133
21193
  const current = readSession();
21134
21194
  if (current?.subject === session.subject && current.refreshToken === session.refreshToken) {
21135
- const attempt2 = Math.min((readRetry(session)?.attempt ?? 0) + 1, 4);
21195
+ const previous = transport ? readTransportRetry(session) : readRetry(session);
21196
+ const attempt2 = Math.min((previous?.attempt ?? 0) + 1, 4);
21136
21197
  const seconds = after2?.trim() ? Number(after2) : NaN;
21137
21198
  const serverDelay = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(after2 ?? "") - Date.now();
21138
- const delay3 = Math.max(Math.min(REFRESH_BACKOFF_MS * 2 ** (attempt2 - 1), 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
21199
+ const backoff = (transport ? 5e3 : REFRESH_BACKOFF_MS) * 2 ** (attempt2 - 1);
21200
+ const delay3 = Math.max(Math.min(backoff, transport ? 3e4 : 3e5), Number.isFinite(serverDelay) ? serverDelay : 0);
21139
21201
  const retry2 = { key: refreshKey(session), until: Date.now() + delay3, attempt: attempt2, error: error62 };
21140
- const temporary = `${retryFile()}.${process.pid}.tmp`;
21141
- fs3.writeFileSync(temporary, JSON.stringify(retry2), { mode: 384 });
21142
- fs3.renameSync(temporary, retryFile());
21202
+ if (transport) transportRetry = { ...retry2, file: retryFile() };
21203
+ else {
21204
+ const temporary = `${retryFile()}.${process.pid}.tmp`;
21205
+ fs3.writeFileSync(temporary, JSON.stringify({ ...retry2, source: "cloud" }), { mode: 384 });
21206
+ fs3.renameSync(temporary, retryFile());
21207
+ }
21143
21208
  }
21144
21209
  return { ok: false, reason: "unreachable", error: error62 };
21145
21210
  }
@@ -21166,21 +21231,23 @@ function writeSession(session) {
21166
21231
  `, { mode: 384 });
21167
21232
  fs3.renameSync(tmp, sessionFile());
21168
21233
  if (!expiringSoon(session) || !readRetry(session)) fs3.rmSync(retryFile(), { force: true });
21234
+ if (transportRetry?.file === retryFile() && (!expiringSoon(session) || !readTransportRetry(session))) transportRetry = void 0;
21169
21235
  }
21170
21236
  function clearSession() {
21237
+ if (transportRetry?.file === retryFile()) transportRetry = void 0;
21171
21238
  try {
21172
21239
  fs3.rmSync(sessionFile());
21173
21240
  fs3.rmSync(retryFile(), { force: true });
21174
21241
  } catch {
21175
21242
  }
21176
21243
  }
21177
- async function accessToken() {
21244
+ async function accessToken({ retryTransport = false } = {}) {
21178
21245
  const held4 = readSession();
21179
21246
  if (!held4) return { ok: false, reason: "signed-out" };
21180
21247
  if (!expiringSoon(held4)) return { ok: true, token: held4.accessToken, session: held4 };
21181
- return refresh();
21248
+ return refresh(retryTransport);
21182
21249
  }
21183
- async function refresh() {
21250
+ async function refresh(retryTransport) {
21184
21251
  const lock = await takeLock();
21185
21252
  if (!lock) return { ok: false, reason: "unreachable", error: "Cloud sign-in refresh is busy. Try again shortly." };
21186
21253
  try {
@@ -21189,6 +21256,8 @@ async function refresh() {
21189
21256
  if (!expiringSoon(now)) return { ok: true, token: now.accessToken, session: now };
21190
21257
  const retry2 = readRetry(now);
21191
21258
  if (retry2 && retry2.until > Date.now()) return { ok: false, reason: "unreachable", error: retry2.error };
21259
+ const localRetry = retryTransport ? void 0 : readTransportRetry(now);
21260
+ if (localRetry && localRetry.until > Date.now()) return { ok: false, reason: "unreachable", error: localRetry.error };
21192
21261
  const { api, anonKey } = cloudEndpoints();
21193
21262
  let response;
21194
21263
  try {
@@ -21199,12 +21268,12 @@ async function refresh() {
21199
21268
  signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS)
21200
21269
  });
21201
21270
  } catch (e) {
21202
- return deferRefresh(now, e instanceof Error ? e.message : String(e));
21271
+ return deferRefresh(now, e instanceof Error ? e.message : String(e), { transport: true });
21203
21272
  }
21204
21273
  if (!response.ok) {
21205
21274
  const body = await response.json().catch(() => null);
21206
21275
  const error62 = body?.error_description ?? body?.msg ?? body?.message;
21207
- if (![400, 401, 403].includes(response.status)) return deferRefresh(now, error62 ?? `Cloud answered ${response.status}`, response.headers.get("retry-after"));
21276
+ if (![400, 401, 403].includes(response.status)) return deferRefresh(now, error62 ?? `Cloud answered ${response.status}`, { after: response.headers.get("retry-after") });
21208
21277
  return { ok: false, reason: "expired", error: error62 };
21209
21278
  }
21210
21279
  const fresh = sessionFrom(await response.json().catch(() => null), now);
@@ -21289,7 +21358,7 @@ function alive(pid) {
21289
21358
  return e.code === "EPERM";
21290
21359
  }
21291
21360
  }
21292
- var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, REFRESH_TIMEOUT_MS, REFRESH_BACKOFF_MS, sessionFile, lockDir, lockOwner, retryFile, refreshKey, expiringSoon, sleep;
21361
+ var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, REFRESH_TIMEOUT_MS, REFRESH_BACKOFF_MS, sessionFile, lockDir, lockOwner, retryFile, transportRetry, refreshKey, expiringSoon, sleep;
21293
21362
  var init_session = __esm({
21294
21363
  "../cli/src/lib/cloud/session.ts"() {
21295
21364
  "use strict";
@@ -21327,7 +21396,7 @@ async function call(method, route2, body, key) {
21327
21396
  if (!cloudConfigured()) return { ok: false, error: NOT_CONFIGURED, code: "bad_request" };
21328
21397
  const token2 = await accessToken();
21329
21398
  if (!token2.ok) {
21330
- return token2.reason === "unreachable" ? { ok: false, error: `Cloud could not be reached: ${token2.error}` } : { ok: false, error: token2.reason === "expired" ? "Cloud sign-in has expired. Sign in again." : "This machine is not signed in to Cloud.", code: "unauthenticated" };
21399
+ return token2.reason === "unreachable" ? { ok: false, error: `Cloud could not be reached: ${token2.error}`, code: "unreachable", retryable: true } : { ok: false, error: token2.reason === "expired" ? "Cloud sign-in has expired. Sign in again." : "This machine is not signed in to Cloud.", code: "unauthenticated" };
21331
21400
  }
21332
21401
  let response;
21333
21402
  try {
@@ -21342,10 +21411,11 @@ async function call(method, route2, body, key) {
21342
21411
  signal: AbortSignal.timeout(2e4)
21343
21412
  });
21344
21413
  } catch (e) {
21345
- return { ok: false, error: `Cloud could not be reached: ${e instanceof Error ? e.message : String(e)}` };
21414
+ return { ok: false, error: `Cloud could not be reached: ${e instanceof Error ? e.message : String(e)}`, code: "unreachable", retryable: true };
21346
21415
  }
21347
- const parsed = await response.json().catch(() => ({}));
21348
- if (!response.ok) return { ok: false, code: parsed.error?.code ?? "refused", error: parsed.error?.message ?? `Cloud answered ${response.status}.` };
21416
+ const parsed = await readCloudJson(response);
21417
+ const problem = cloudProblem(response, parsed) ?? (isRecord(parsed) ? null : invalidResponse("a valid JSON response"));
21418
+ if (problem) return { ok: false, ...problem, error: problem.message };
21349
21419
  return { ok: true, value: parsed, replayed: response.headers.get("idempotent-replayed") === "true" };
21350
21420
  }
21351
21421
  async function createTask(from, said2) {
@@ -21431,6 +21501,7 @@ var init_tasks = __esm({
21431
21501
  "use strict";
21432
21502
  init_config();
21433
21503
  init_session();
21504
+ init_response();
21434
21505
  TASK_ENV = "AI4KANBAN_TASK";
21435
21506
  numberOf = (key) => Number(/-(\d+)$/.exec(key)?.[1] ?? NaN);
21436
21507
  }
@@ -22080,19 +22151,19 @@ function tryLock(dir) {
22080
22151
  const code = err.code;
22081
22152
  if (code !== "ENOTEMPTY" && code !== "EEXIST") throw err;
22082
22153
  }
22083
- let entries;
22154
+ let entries2;
22084
22155
  try {
22085
- entries = fs7.readdirSync(dir);
22156
+ entries2 = fs7.readdirSync(dir);
22086
22157
  } catch (err) {
22087
22158
  if (err.code === "ENOENT") continue;
22088
22159
  throw err;
22089
22160
  }
22090
- if (entries.length) {
22091
- if (entries.length !== 1 || !/^\d+-[a-f0-9-]{36}$/.test(entries[0])) return void 0;
22092
- const owner = Number(entries[0].split("-")[0]);
22161
+ if (entries2.length) {
22162
+ if (entries2.length !== 1 || !/^\d+-[a-f0-9-]{36}$/.test(entries2[0])) return void 0;
22163
+ const owner = Number(entries2[0].split("-")[0]);
22093
22164
  if (pidAlive(owner)) return void 0;
22094
22165
  }
22095
- if (!removeClaim(dir, entries[0])) return void 0;
22166
+ if (!removeClaim(dir, entries2[0])) return void 0;
22096
22167
  }
22097
22168
  } finally {
22098
22169
  fs7.rmSync(candidate, { recursive: true, force: true });
@@ -22384,13 +22455,13 @@ function boardStamp() {
22384
22455
  }
22385
22456
  function walk(dir, parts, depth3) {
22386
22457
  if (depth3 > MAX_DEPTH) return;
22387
- let entries;
22458
+ let entries2;
22388
22459
  try {
22389
- entries = fs9.readdirSync(dir, { withFileTypes: true });
22460
+ entries2 = fs9.readdirSync(dir, { withFileTypes: true });
22390
22461
  } catch {
22391
22462
  return;
22392
22463
  }
22393
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
22464
+ for (const entry of entries2.sort((a, b) => a.name.localeCompare(b.name))) {
22394
22465
  const full = path10.join(dir, entry.name);
22395
22466
  if (entry.isDirectory()) walk(full, parts, depth3 + 1);
22396
22467
  else stamp(full, parts);
@@ -22651,8 +22722,8 @@ var init_package = __esm({
22651
22722
  "../cli/package.json"() {
22652
22723
  package_default = {
22653
22724
  name: "wildcrane",
22654
- version: "0.11.83",
22655
- akbContract: 27,
22725
+ version: "0.11.85",
22726
+ akbContract: 28,
22656
22727
  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.",
22657
22728
  keywords: [
22658
22729
  "kanban",
@@ -23327,13 +23398,13 @@ function pathLookup() {
23327
23398
  const names2 = /* @__PURE__ */ new Set();
23328
23399
  for (const dir of (process.env.PATH ?? "").split(path17.delimiter)) {
23329
23400
  if (!dir) continue;
23330
- let entries;
23401
+ let entries2;
23331
23402
  try {
23332
- entries = fs16.readdirSync(dir);
23403
+ entries2 = fs16.readdirSync(dir);
23333
23404
  } catch {
23334
23405
  continue;
23335
23406
  }
23336
- for (const entry of entries) names2.add(WINDOWS ? entry.toLowerCase() : entry);
23407
+ for (const entry of entries2) names2.add(WINDOWS ? entry.toLowerCase() : entry);
23337
23408
  }
23338
23409
  const extensions = WINDOWS ? windowsExtensions() : [];
23339
23410
  return (command) => {
@@ -23939,9 +24010,9 @@ function createEventCollector() {
23939
24010
  close();
23940
24011
  queue.push({ kind: "tool_call_update", data: { toolCallId, status, ...result.trim() ? { result: result.trim() } : {} } });
23941
24012
  },
23942
- plan(entries) {
24013
+ plan(entries2) {
23943
24014
  close();
23944
- queue.push({ kind: "plan", data: { entries: entriesOf(entries) } });
24015
+ queue.push({ kind: "plan", data: { entries: entriesOf(entries2) } });
23945
24016
  },
23946
24017
  /** Cursor's `cursor/update_todos`: the whole list, or under `merge` only what changed, by id. */
23947
24018
  todos(raw, merge2) {
@@ -24792,10 +24863,10 @@ function promptSize(raw) {
24792
24863
  return size > 0 ? size : void 0;
24793
24864
  }
24794
24865
  function windowOf(raw, model) {
24795
- const entries = obj2(raw);
24796
- const names2 = Object.keys(entries);
24866
+ const entries2 = obj2(raw);
24867
+ const names2 = Object.keys(entries2);
24797
24868
  const name = model && names2.includes(model) ? model : names2.length === 1 ? names2[0] : void 0;
24798
- return name ? num2(obj2(entries[name]).contextWindow) || void 0 : void 0;
24869
+ return name ? num2(obj2(entries2[name]).contextWindow) || void 0 : void 0;
24799
24870
  }
24800
24871
  function createStreamRenderer() {
24801
24872
  let final;
@@ -25054,10 +25125,10 @@ function findRollout(threadId) {
25054
25125
  }
25055
25126
  for (const name of names2) {
25056
25127
  if (!name.startsWith("rollout-") || !name.endsWith(tail)) continue;
25057
- const path87 = join2(dir, name);
25128
+ const path88 = join2(dir, name);
25058
25129
  try {
25059
- const at = statSync2(path87).mtimeMs;
25060
- if (!newest2 || at > newest2.at) newest2 = { path: path87, at };
25130
+ const at = statSync2(path88).mtimeMs;
25131
+ if (!newest2 || at > newest2.at) newest2 = { path: path88, at };
25061
25132
  } catch {
25062
25133
  }
25063
25134
  }
@@ -25065,11 +25136,11 @@ function findRollout(threadId) {
25065
25136
  return newest2?.path;
25066
25137
  }
25067
25138
  function readCodexRunFacts(threadId) {
25068
- const path87 = findRollout(threadId);
25069
- if (!path87) return void 0;
25139
+ const path88 = findRollout(threadId);
25140
+ if (!path88) return void 0;
25070
25141
  let raw;
25071
25142
  try {
25072
- raw = readFileSync2(path87, "utf8");
25143
+ raw = readFileSync2(path88, "utf8");
25073
25144
  } catch {
25074
25145
  return void 0;
25075
25146
  }
@@ -25195,8 +25266,8 @@ function renderCompleted(item) {
25195
25266
  const changes = Array.isArray(item.changes) ? item.changes : [];
25196
25267
  return changes.map((raw) => {
25197
25268
  const change2 = obj2(raw);
25198
- const path87 = str2(change2.path);
25199
- return path87 ? `\u23FA ${str2(change2.kind) || "change"}(${path87})
25269
+ const path88 = str2(change2.path);
25270
+ return path88 ? `\u23FA ${str2(change2.kind) || "change"}(${path88})
25200
25271
  ` : "";
25201
25272
  }).join("");
25202
25273
  }
@@ -25472,12 +25543,12 @@ function home2() {
25472
25543
  return process.env.KIMI_CODE_HOME?.trim() || join3(homedir3(), ".kimi-code");
25473
25544
  }
25474
25545
  function readIndex() {
25475
- const entries = /* @__PURE__ */ new Map();
25546
+ const entries2 = /* @__PURE__ */ new Map();
25476
25547
  let raw;
25477
25548
  try {
25478
25549
  raw = readFileSync3(join3(home2(), "session_index.jsonl"), "utf8");
25479
25550
  } catch {
25480
- return entries;
25551
+ return entries2;
25481
25552
  }
25482
25553
  for (const line of raw.split("\n")) {
25483
25554
  if (!line.trim()) continue;
@@ -25492,14 +25563,14 @@ function readIndex() {
25492
25563
  const sessionId = str2(record2.sessionId).trim();
25493
25564
  if (!sessionId) continue;
25494
25565
  if (record2.deleted === true) {
25495
- entries.delete(sessionId);
25566
+ entries2.delete(sessionId);
25496
25567
  continue;
25497
25568
  }
25498
25569
  const sessionDir = str2(record2.sessionDir).trim();
25499
25570
  const workDir = str2(record2.workDir).trim();
25500
- if (sessionDir && workDir) entries.set(sessionId, { sessionId, sessionDir, workDir });
25571
+ if (sessionDir && workDir) entries2.set(sessionId, { sessionId, sessionDir, workDir });
25501
25572
  }
25502
- return entries;
25573
+ return entries2;
25503
25574
  }
25504
25575
  function findKimiSession(cwd, since) {
25505
25576
  const want = resolve(cwd);
@@ -25534,10 +25605,10 @@ function readKimiRunFacts(sessionId) {
25534
25605
  const total = { input: 0, cacheCreation: 0, cacheRead: 0, output: 0 };
25535
25606
  let model;
25536
25607
  let holding = 0;
25537
- for (const { path: path87, main } of wireFiles(entry.sessionDir)) {
25608
+ for (const { path: path88, main } of wireFiles(entry.sessionDir)) {
25538
25609
  let raw;
25539
25610
  try {
25540
- raw = readFileSync3(path87, "utf8");
25611
+ raw = readFileSync3(path88, "utf8");
25541
25612
  } catch {
25542
25613
  continue;
25543
25614
  }
@@ -25914,8 +25985,8 @@ var init_tail = __esm({
25914
25985
  import fs22 from "node:fs";
25915
25986
  function whereHint(update2, title) {
25916
25987
  const locations = Array.isArray(update2.locations) ? update2.locations : [];
25917
- const path87 = str2(obj2(locations[0]).path);
25918
- return path87 && !title.includes(path87) ? hint(path87) : "";
25988
+ const path88 = str2(obj2(locations[0]).path);
25989
+ return path88 && !title.includes(path88) ? hint(path88) : "";
25919
25990
  }
25920
25991
  function saidBy(update2) {
25921
25992
  const content = Array.isArray(update2.content) ? update2.content : [];
@@ -26679,19 +26750,19 @@ var init_codex_background = __esm({
26679
26750
  // ../cli/src/lib/agent/wire/codex-work.ts
26680
26751
  function codexWork() {
26681
26752
  const children = /* @__PURE__ */ new Set();
26682
- const entries = /* @__PURE__ */ new Map();
26753
+ const entries2 = /* @__PURE__ */ new Map();
26683
26754
  const background = /* @__PURE__ */ new Set();
26684
26755
  const seenCollab = /* @__PURE__ */ new Set();
26685
26756
  let root2 = "";
26686
26757
  const own2 = (threadId) => threadId === root2 || children.has(threadId);
26687
26758
  const agent = (threadId, raw) => {
26688
26759
  const id2 = `agent:${threadId}`;
26689
- const previous = entries.get(id2);
26760
+ const previous = entries2.get(id2);
26690
26761
  const status = str2(raw.status);
26691
26762
  if (["shutdown", "notFound", "not_found"].includes(status) && previous && previous.status !== "running") return;
26692
26763
  const state = ["pendingInit", "running", "pending_init"].includes(status) ? "running" : status === "completed" ? "completed" : ["interrupted", "shutdown"].includes(status) ? "interrupted" : ["errored", "notFound", "not_found"].includes(status) ? "failed" : void 0;
26693
26764
  if (!state) return;
26694
- entries.set(id2, { ...previous, id: id2, threadId, kind: "agent", status: state, result: summary(str2(raw.message)) });
26765
+ entries2.set(id2, { ...previous, id: id2, threadId, kind: "agent", status: state, result: summary(str2(raw.message)) });
26695
26766
  };
26696
26767
  const observe = (threadId, raw) => {
26697
26768
  if (!own2(threadId)) return;
@@ -26700,7 +26771,7 @@ function codexWork() {
26700
26771
  if (raw.kind === "started" && child && child !== root2 && !children.has(child)) {
26701
26772
  children.add(child);
26702
26773
  agent(child, { status: "running" });
26703
- entries.get(`agent:${child}`).agentPath = str2(raw.agentPath);
26774
+ entries2.get(`agent:${child}`).agentPath = str2(raw.agentPath);
26704
26775
  }
26705
26776
  return;
26706
26777
  }
@@ -26711,18 +26782,18 @@ function codexWork() {
26711
26782
  if (raw.tool === "spawnAgent") {
26712
26783
  for (const id3 of Array.isArray(raw.receiverThreadIds) ? raw.receiverThreadIds : []) if (typeof id3 === "string" && id3 !== root2) {
26713
26784
  children.add(id3);
26714
- if (!entries.has(`agent:${id3}`)) agent(id3, { status: "running" });
26785
+ if (!entries2.has(`agent:${id3}`)) agent(id3, { status: "running" });
26715
26786
  }
26716
26787
  }
26717
26788
  for (const [id3, state] of Object.entries(obj2(raw.agentsStates))) if (children.has(id3)) agent(id3, obj2(state));
26718
26789
  }
26719
26790
  if (raw.type !== "commandExecution" || !str2(raw.id)) return;
26720
26791
  const id2 = terminalKey(threadId, str2(raw.id));
26721
- const previous = entries.get(id2);
26792
+ const previous = entries2.get(id2);
26722
26793
  const running = raw.status === "inProgress";
26723
26794
  if (running && previous?.exitCode !== void 0) return;
26724
26795
  const exitCode = typeof raw.exitCode === "number" ? raw.exitCode : previous?.exitCode;
26725
- entries.set(id2, {
26796
+ entries2.set(id2, {
26726
26797
  ...previous,
26727
26798
  id: id2,
26728
26799
  threadId,
@@ -26764,7 +26835,7 @@ function codexWork() {
26764
26835
  };
26765
26836
  return {
26766
26837
  children,
26767
- entries,
26838
+ entries: entries2,
26768
26839
  background,
26769
26840
  own: own2,
26770
26841
  observe,
@@ -26774,9 +26845,9 @@ function codexWork() {
26774
26845
  for (const child of retained) if (child !== id2) children.add(child);
26775
26846
  },
26776
26847
  freeze() {
26777
- for (const [id2, entry] of entries) if (entry.status === "running") background.add(id2);
26848
+ for (const [id2, entry] of entries2) if (entry.status === "running") background.add(id2);
26778
26849
  },
26779
- work: () => [...entries.values()].filter((e) => background.has(e.id)),
26850
+ work: () => [...entries2.values()].filter((e) => background.has(e.id)),
26780
26851
  async refresh(rpc, alive2) {
26781
26852
  for (const id2 of children) {
26782
26853
  if (!alive2()) return;
@@ -26798,8 +26869,8 @@ function codexWork() {
26798
26869
  if (!itemId || !processId) throw Error("Codex returned a background terminal without its complete handles.");
26799
26870
  const id2 = terminalKey(threadId, itemId);
26800
26871
  present.add(id2);
26801
- const previous = entries.get(id2);
26802
- entries.set(id2, {
26872
+ const previous = entries2.get(id2);
26873
+ entries2.set(id2, {
26803
26874
  ...previous,
26804
26875
  id: id2,
26805
26876
  threadId,
@@ -26817,13 +26888,13 @@ function codexWork() {
26817
26888
  } while (cursor);
26818
26889
  } catch (e) {
26819
26890
  if (!(e instanceof RpcError) || ![-32601, -32600].includes(e.code ?? 0) || !/method|unknown|unsupported/i.test(e.message)) throw e;
26820
- if ([...entries.values()].some((w) => w.threadId === threadId && w.kind === "terminal" && w.status === "running")) throw Error("This Codex version cannot report unfinished background commands; cleanup is unconfirmed.");
26891
+ if ([...entries2.values()].some((w) => w.threadId === threadId && w.kind === "terminal" && w.status === "running")) throw Error("This Codex version cannot report unfinished background commands; cleanup is unconfirmed.");
26821
26892
  continue;
26822
26893
  }
26823
- const missing = [...entries.values()].filter((e) => background.has(e.id) && e.threadId === threadId && e.kind === "terminal" && e.status === "running" && !present.has(e.id));
26894
+ const missing = [...entries2.values()].filter((e) => background.has(e.id) && e.threadId === threadId && e.kind === "terminal" && e.status === "running" && !present.has(e.id));
26824
26895
  if (missing.length) {
26825
26896
  await readThread(rpc, threadId);
26826
- for (const entry of missing) if (entries.get(entry.id)?.status === "running") entries.get(entry.id).status = "unknown";
26897
+ for (const entry of missing) if (entries2.get(entry.id)?.status === "running") entries2.get(entry.id).status = "unknown";
26827
26898
  }
26828
26899
  }
26829
26900
  }
@@ -27096,7 +27167,7 @@ async function run(io, options, count3) {
27096
27167
  startupTimer = setTimeout(() => {
27097
27168
  if (!started) io.event?.({ kind: "log", data: { text: "[conversation] start_unconfirmed" } });
27098
27169
  }, CONVERSATION_MS.start);
27099
- await bounded(rpc.call("turn/start", { threadId, input: [{ type: "text", text: text5 }, ...images.map((path87) => ({ type: "localImage", path: path87 }))] }), CONVERSATION_MS.start, "Codex turn/start timed out; submission outcome is unknown.").catch((error62) => {
27170
+ await bounded(rpc.call("turn/start", { threadId, input: [{ type: "text", text: text5 }, ...images.map((path88) => ({ type: "localImage", path: path88 }))] }), CONVERSATION_MS.start, "Codex turn/start timed out; submission outcome is unknown.").catch((error62) => {
27100
27171
  if (!started) throw error62;
27101
27172
  });
27102
27173
  };
@@ -27190,11 +27261,11 @@ async function run(io, options, count3) {
27190
27261
  }
27191
27262
  const outstanding = work.work().filter((w) => offered.get(w.id) !== snapshot2(w) && presented.get(w.id) !== snapshot2(w) && w.disposition !== "keep" && !(w.intentionalStop && !["running", "unknown"].includes(w.status)));
27192
27263
  if (outstanding.length) {
27193
- const entries = batch(outstanding).map((w) => ({ ...w }));
27194
- for (const entry of entries) offered.set(entry.id, snapshot2(entry));
27195
- settlement = { work: entries, polled: /* @__PURE__ */ new Set(), messages: [] };
27264
+ const entries2 = batch(outstanding).map((w) => ({ ...w }));
27265
+ for (const entry of entries2) offered.set(entry.id, snapshot2(entry));
27266
+ settlement = { work: entries2, polled: /* @__PURE__ */ new Set(), messages: [] };
27196
27267
  armCleanup();
27197
- await start(settlementPrompt(entries, execution, !!host2.instance));
27268
+ await start(settlementPrompt(entries2, execution, !!host2.instance));
27198
27269
  return;
27199
27270
  }
27200
27271
  const awaited = work.work().filter((w) => w.status === "running" && w.disposition !== "keep");
@@ -29302,13 +29373,13 @@ function plannerModules() {
29302
29373
  function memoryDirectories(board2) {
29303
29374
  const root2 = board2 ? path31.join(board2, "memory") : MEMORY;
29304
29375
  const walk3 = (dir, depth3, scoped = true) => {
29305
- let entries;
29376
+ let entries2;
29306
29377
  try {
29307
- entries = fs28.readdirSync(dir, { withFileTypes: true });
29378
+ entries2 = fs28.readdirSync(dir, { withFileTypes: true });
29308
29379
  } catch {
29309
29380
  return [];
29310
29381
  }
29311
- return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).flatMap((e) => {
29382
+ return entries2.filter((e) => e.isDirectory() && !e.name.startsWith(".")).flatMap((e) => {
29312
29383
  const target = path31.join(dir, e.name);
29313
29384
  return depth3 === 1 ? !scoped || ["project", "workspace"].includes(e.name) ? [target] : [] : walk3(target, depth3 - 1, scoped);
29314
29385
  });
@@ -29395,31 +29466,32 @@ var init_file_limits = __esm({
29395
29466
  });
29396
29467
 
29397
29468
  // ../cli/src/lib/shared/board-files.ts
29398
- function isBoardPath(path87) {
29399
- if (!path87 || path87.length > 500 || path87.startsWith("/") || path87.includes("\\") || path87.includes("\0")) return false;
29400
- if (path87.split("/").some((part) => !part || part === "." || part === "..")) return false;
29401
- if (path87 === "todo/README.md" || path87.split("/").includes(".sync")) return false;
29402
- if (path87.startsWith("studios/")) return true;
29403
- if (SETTINGS.includes(path87)) return true;
29404
- if (path87.startsWith("rules/")) return isSettingsPath(path87);
29405
- if (path87.startsWith("assets/")) return taskOfAssets(path87) !== null;
29406
- return ROOTS.some((root2) => path87.startsWith(root2)) && path87.endsWith(".md");
29407
- }
29408
- function numberOfCard(path87) {
29409
- const n = ROOT.exec(path87)?.[1] ?? CARD.exec(path87)?.[1];
29469
+ function isBoardPath(path88) {
29470
+ if (!path88 || path88.length > 500 || path88.startsWith("/") || path88.includes("\\") || path88.includes("\0")) return false;
29471
+ if (path88.split("/").some((part) => !part || part === "." || part === "..")) return false;
29472
+ if (path88 === "todo/README.md" || path88.split("/").includes(".sync")) return false;
29473
+ if (path88.startsWith("studios/")) return true;
29474
+ if (SETTINGS.includes(path88)) return true;
29475
+ if (path88.startsWith("rules/")) return isSettingsPath(path88);
29476
+ if (path88.startsWith("assets/")) return taskOfAssets(path88) !== null;
29477
+ return ROOTS.some((root2) => path88.startsWith(root2)) && path88.endsWith(".md");
29478
+ }
29479
+ function numberOfCard(path88) {
29480
+ const n = ROOT.exec(path88)?.[1] ?? CARD.exec(path88)?.[1];
29410
29481
  return n ? Number(n) : null;
29411
29482
  }
29412
- var ROOTS, SETTINGS, isSettingsPath, CARD, ROOT, taskOfAssets, studioFolder, studioName;
29483
+ var ROOTS, SETTINGS, isSettingsPath, CARD, ROOT, assetsFile, taskOfAssets, studioFolder, studioName;
29413
29484
  var init_board_files = __esm({
29414
29485
  "../cli/src/lib/shared/board-files.ts"() {
29415
29486
  "use strict";
29416
29487
  init_file_limits();
29417
29488
  ROOTS = ["todo/", ".archive/", "memory/", "studios/", "triage/", "assets/", "rules/"];
29418
29489
  SETTINGS = ["modules.md", "config.md"];
29419
- isSettingsPath = (path87) => SETTINGS.includes(path87) || /^rules\/(?:studios\/[^/]+|proposer|project-writer|dismissal-reviewer|memory-pruner)\.md$/.test(path87);
29490
+ isSettingsPath = (path88) => SETTINGS.includes(path88) || /^rules\/(?:studios\/[^/]+|proposer|project-writer|dismissal-reviewer|memory-pruner)\.md$/.test(path88);
29420
29491
  CARD = /^(?:todo|\.archive)\/(?:[^/]+\/)*(\d+)-[^/]*\.md$/;
29421
29492
  ROOT = /^(?:todo|\.archive)\/(?:[^/]+\/)*(\d+)-[^/]+\/root\.md$/;
29422
- taskOfAssets = (path87) => /^assets\/(task_[0-9a-f]+)\.json$/.exec(path87)?.[1] ?? null;
29493
+ assetsFile = (task) => `assets/${task}.json`;
29494
+ taskOfAssets = (path88) => /^assets\/(task_[0-9a-f]+)\.json$/.exec(path88)?.[1] ?? null;
29423
29495
  studioFolder = (id2) => id2.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
29424
29496
  studioName = (id2) => id2.startsWith("wf_builtin_") ? id2.slice("wf_builtin_".length).replace(/_/g, "-") : studioFolder(id2);
29425
29497
  }
@@ -32642,8 +32714,8 @@ var require_utils = __commonJS({
32642
32714
  }
32643
32715
  return ind;
32644
32716
  }
32645
- function removeDotSegments(path87) {
32646
- let input2 = path87;
32717
+ function removeDotSegments(path88) {
32718
+ let input2 = path88;
32647
32719
  const output2 = [];
32648
32720
  let nextSlash = -1;
32649
32721
  let len = 0;
@@ -32717,11 +32789,11 @@ var require_utils = __commonJS({
32717
32789
  }
32718
32790
  return output2.join("");
32719
32791
  }
32720
- function removeDotSegmentsRelative(path87) {
32721
- if (path87 === "" || path87[0] === "/") {
32722
- return removeDotSegments(path87);
32792
+ function removeDotSegmentsRelative(path88) {
32793
+ if (path88 === "" || path88[0] === "/") {
32794
+ return removeDotSegments(path88);
32723
32795
  }
32724
- const segments = path87.split("/");
32796
+ const segments = path88.split("/");
32725
32797
  const last = segments.length - 1;
32726
32798
  const output2 = [];
32727
32799
  let trailingDirectory = false;
@@ -33084,8 +33156,8 @@ var require_schemes = __commonJS({
33084
33156
  }
33085
33157
  if (wsComponent.resourceName) {
33086
33158
  const queryIndex = wsComponent.resourceName.indexOf("?");
33087
- const path87 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
33088
- wsComponent.path = path87 && path87 !== "/" ? path87 : void 0;
33159
+ const path88 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
33160
+ wsComponent.path = path88 && path88 !== "/" ? path88 : void 0;
33089
33161
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
33090
33162
  wsComponent.resourceName = void 0;
33091
33163
  }
@@ -34490,8 +34562,8 @@ var require_multipleOf = __commonJS({
34490
34562
  const { gen, data, schemaCode, it } = cxt;
34491
34563
  const prec = it.opts.multipleOfPrecision;
34492
34564
  const res = gen.let("res");
34493
- const invalid2 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
34494
- cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid2}))`);
34565
+ const invalid3 = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
34566
+ cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid3}))`);
34495
34567
  }
34496
34568
  };
34497
34569
  exports.default = def;
@@ -36245,17 +36317,17 @@ var require_visit = __commonJS({
36245
36317
  visit2.BREAK = BREAK;
36246
36318
  visit2.SKIP = SKIP;
36247
36319
  visit2.REMOVE = REMOVE;
36248
- function visit_(key, node2, visitor, path87) {
36249
- const ctrl = callVisitor(key, node2, visitor, path87);
36320
+ function visit_(key, node2, visitor, path88) {
36321
+ const ctrl = callVisitor(key, node2, visitor, path88);
36250
36322
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
36251
- replaceNode(key, path87, ctrl);
36252
- return visit_(key, ctrl, visitor, path87);
36323
+ replaceNode(key, path88, ctrl);
36324
+ return visit_(key, ctrl, visitor, path88);
36253
36325
  }
36254
36326
  if (typeof ctrl !== "symbol") {
36255
36327
  if (identity.isCollection(node2)) {
36256
- path87 = Object.freeze(path87.concat(node2));
36328
+ path88 = Object.freeze(path88.concat(node2));
36257
36329
  for (let i = 0; i < node2.items.length; ++i) {
36258
- const ci = visit_(i, node2.items[i], visitor, path87);
36330
+ const ci = visit_(i, node2.items[i], visitor, path88);
36259
36331
  if (typeof ci === "number")
36260
36332
  i = ci - 1;
36261
36333
  else if (ci === BREAK)
@@ -36266,13 +36338,13 @@ var require_visit = __commonJS({
36266
36338
  }
36267
36339
  }
36268
36340
  } else if (identity.isPair(node2)) {
36269
- path87 = Object.freeze(path87.concat(node2));
36270
- const ck = visit_("key", node2.key, visitor, path87);
36341
+ path88 = Object.freeze(path88.concat(node2));
36342
+ const ck = visit_("key", node2.key, visitor, path88);
36271
36343
  if (ck === BREAK)
36272
36344
  return BREAK;
36273
36345
  else if (ck === REMOVE)
36274
36346
  node2.key = null;
36275
- const cv = visit_("value", node2.value, visitor, path87);
36347
+ const cv = visit_("value", node2.value, visitor, path88);
36276
36348
  if (cv === BREAK)
36277
36349
  return BREAK;
36278
36350
  else if (cv === REMOVE)
@@ -36293,17 +36365,17 @@ var require_visit = __commonJS({
36293
36365
  visitAsync.BREAK = BREAK;
36294
36366
  visitAsync.SKIP = SKIP;
36295
36367
  visitAsync.REMOVE = REMOVE;
36296
- async function visitAsync_(key, node2, visitor, path87) {
36297
- const ctrl = await callVisitor(key, node2, visitor, path87);
36368
+ async function visitAsync_(key, node2, visitor, path88) {
36369
+ const ctrl = await callVisitor(key, node2, visitor, path88);
36298
36370
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
36299
- replaceNode(key, path87, ctrl);
36300
- return visitAsync_(key, ctrl, visitor, path87);
36371
+ replaceNode(key, path88, ctrl);
36372
+ return visitAsync_(key, ctrl, visitor, path88);
36301
36373
  }
36302
36374
  if (typeof ctrl !== "symbol") {
36303
36375
  if (identity.isCollection(node2)) {
36304
- path87 = Object.freeze(path87.concat(node2));
36376
+ path88 = Object.freeze(path88.concat(node2));
36305
36377
  for (let i = 0; i < node2.items.length; ++i) {
36306
- const ci = await visitAsync_(i, node2.items[i], visitor, path87);
36378
+ const ci = await visitAsync_(i, node2.items[i], visitor, path88);
36307
36379
  if (typeof ci === "number")
36308
36380
  i = ci - 1;
36309
36381
  else if (ci === BREAK)
@@ -36314,13 +36386,13 @@ var require_visit = __commonJS({
36314
36386
  }
36315
36387
  }
36316
36388
  } else if (identity.isPair(node2)) {
36317
- path87 = Object.freeze(path87.concat(node2));
36318
- const ck = await visitAsync_("key", node2.key, visitor, path87);
36389
+ path88 = Object.freeze(path88.concat(node2));
36390
+ const ck = await visitAsync_("key", node2.key, visitor, path88);
36319
36391
  if (ck === BREAK)
36320
36392
  return BREAK;
36321
36393
  else if (ck === REMOVE)
36322
36394
  node2.key = null;
36323
- const cv = await visitAsync_("value", node2.value, visitor, path87);
36395
+ const cv = await visitAsync_("value", node2.value, visitor, path88);
36324
36396
  if (cv === BREAK)
36325
36397
  return BREAK;
36326
36398
  else if (cv === REMOVE)
@@ -36347,23 +36419,23 @@ var require_visit = __commonJS({
36347
36419
  }
36348
36420
  return visitor;
36349
36421
  }
36350
- function callVisitor(key, node2, visitor, path87) {
36422
+ function callVisitor(key, node2, visitor, path88) {
36351
36423
  if (typeof visitor === "function")
36352
- return visitor(key, node2, path87);
36424
+ return visitor(key, node2, path88);
36353
36425
  if (identity.isMap(node2))
36354
- return visitor.Map?.(key, node2, path87);
36426
+ return visitor.Map?.(key, node2, path88);
36355
36427
  if (identity.isSeq(node2))
36356
- return visitor.Seq?.(key, node2, path87);
36428
+ return visitor.Seq?.(key, node2, path88);
36357
36429
  if (identity.isPair(node2))
36358
- return visitor.Pair?.(key, node2, path87);
36430
+ return visitor.Pair?.(key, node2, path88);
36359
36431
  if (identity.isScalar(node2))
36360
- return visitor.Scalar?.(key, node2, path87);
36432
+ return visitor.Scalar?.(key, node2, path88);
36361
36433
  if (identity.isAlias(node2))
36362
- return visitor.Alias?.(key, node2, path87);
36434
+ return visitor.Alias?.(key, node2, path88);
36363
36435
  return void 0;
36364
36436
  }
36365
- function replaceNode(key, path87, node2) {
36366
- const parent = path87[path87.length - 1];
36437
+ function replaceNode(key, path88, node2) {
36438
+ const parent = path88[path88.length - 1];
36367
36439
  if (identity.isCollection(parent)) {
36368
36440
  parent.items[key] = node2;
36369
36441
  } else if (identity.isPair(parent)) {
@@ -36975,10 +37047,10 @@ var require_Collection = __commonJS({
36975
37047
  var createNode = require_createNode();
36976
37048
  var identity = require_identity();
36977
37049
  var Node = require_Node();
36978
- function collectionFromPath(schema, path87, value) {
37050
+ function collectionFromPath(schema, path88, value) {
36979
37051
  let v = value;
36980
- for (let i = path87.length - 1; i >= 0; --i) {
36981
- const k = path87[i];
37052
+ for (let i = path88.length - 1; i >= 0; --i) {
37053
+ const k = path88[i];
36982
37054
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
36983
37055
  const a = [];
36984
37056
  a[k] = v;
@@ -36997,7 +37069,7 @@ var require_Collection = __commonJS({
36997
37069
  sourceObjects: /* @__PURE__ */ new Map()
36998
37070
  });
36999
37071
  }
37000
- var isEmptyPath = (path87) => path87 == null || typeof path87 === "object" && !!path87[Symbol.iterator]().next().done;
37072
+ var isEmptyPath = (path88) => path88 == null || typeof path88 === "object" && !!path88[Symbol.iterator]().next().done;
37001
37073
  var Collection = class extends Node.NodeBase {
37002
37074
  constructor(type, schema) {
37003
37075
  super(type);
@@ -37027,11 +37099,11 @@ var require_Collection = __commonJS({
37027
37099
  * be a Pair instance or a `{ key, value }` object, which may not have a key
37028
37100
  * that already exists in the map.
37029
37101
  */
37030
- addIn(path87, value) {
37031
- if (isEmptyPath(path87))
37102
+ addIn(path88, value) {
37103
+ if (isEmptyPath(path88))
37032
37104
  this.add(value);
37033
37105
  else {
37034
- const [key, ...rest] = path87;
37106
+ const [key, ...rest] = path88;
37035
37107
  const node2 = this.get(key, true);
37036
37108
  if (identity.isCollection(node2))
37037
37109
  node2.addIn(rest, value);
@@ -37045,8 +37117,8 @@ var require_Collection = __commonJS({
37045
37117
  * Removes a value from the collection.
37046
37118
  * @returns `true` if the item was found and removed.
37047
37119
  */
37048
- deleteIn(path87) {
37049
- const [key, ...rest] = path87;
37120
+ deleteIn(path88) {
37121
+ const [key, ...rest] = path88;
37050
37122
  if (rest.length === 0)
37051
37123
  return this.delete(key);
37052
37124
  const node2 = this.get(key, true);
@@ -37060,8 +37132,8 @@ var require_Collection = __commonJS({
37060
37132
  * scalar values from their surrounding node; to disable set `keepScalar` to
37061
37133
  * `true` (collections are always returned intact).
37062
37134
  */
37063
- getIn(path87, keepScalar) {
37064
- const [key, ...rest] = path87;
37135
+ getIn(path88, keepScalar) {
37136
+ const [key, ...rest] = path88;
37065
37137
  const node2 = this.get(key, true);
37066
37138
  if (rest.length === 0)
37067
37139
  return !keepScalar && identity.isScalar(node2) ? node2.value : node2;
@@ -37079,8 +37151,8 @@ var require_Collection = __commonJS({
37079
37151
  /**
37080
37152
  * Checks if the collection includes a value with the key `key`.
37081
37153
  */
37082
- hasIn(path87) {
37083
- const [key, ...rest] = path87;
37154
+ hasIn(path88) {
37155
+ const [key, ...rest] = path88;
37084
37156
  if (rest.length === 0)
37085
37157
  return this.has(key);
37086
37158
  const node2 = this.get(key, true);
@@ -37090,8 +37162,8 @@ var require_Collection = __commonJS({
37090
37162
  * Sets a value in this collection. For `!!set`, `value` needs to be a
37091
37163
  * boolean to add/remove the item from the set.
37092
37164
  */
37093
- setIn(path87, value) {
37094
- const [key, ...rest] = path87;
37165
+ setIn(path88, value) {
37166
+ const [key, ...rest] = path88;
37095
37167
  if (rest.length === 0) {
37096
37168
  this.set(key, value);
37097
37169
  } else {
@@ -39606,9 +39678,9 @@ var require_Document = __commonJS({
39606
39678
  this.contents.add(value);
39607
39679
  }
39608
39680
  /** Adds a value to the document. */
39609
- addIn(path87, value) {
39681
+ addIn(path88, value) {
39610
39682
  if (assertCollection(this.contents))
39611
- this.contents.addIn(path87, value);
39683
+ this.contents.addIn(path88, value);
39612
39684
  }
39613
39685
  /**
39614
39686
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -39683,14 +39755,14 @@ var require_Document = __commonJS({
39683
39755
  * Removes a value from the document.
39684
39756
  * @returns `true` if the item was found and removed.
39685
39757
  */
39686
- deleteIn(path87) {
39687
- if (Collection.isEmptyPath(path87)) {
39758
+ deleteIn(path88) {
39759
+ if (Collection.isEmptyPath(path88)) {
39688
39760
  if (this.contents == null)
39689
39761
  return false;
39690
39762
  this.contents = null;
39691
39763
  return true;
39692
39764
  }
39693
- return assertCollection(this.contents) ? this.contents.deleteIn(path87) : false;
39765
+ return assertCollection(this.contents) ? this.contents.deleteIn(path88) : false;
39694
39766
  }
39695
39767
  /**
39696
39768
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -39705,10 +39777,10 @@ var require_Document = __commonJS({
39705
39777
  * scalar values from their surrounding node; to disable set `keepScalar` to
39706
39778
  * `true` (collections are always returned intact).
39707
39779
  */
39708
- getIn(path87, keepScalar) {
39709
- if (Collection.isEmptyPath(path87))
39780
+ getIn(path88, keepScalar) {
39781
+ if (Collection.isEmptyPath(path88))
39710
39782
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
39711
- return identity.isCollection(this.contents) ? this.contents.getIn(path87, keepScalar) : void 0;
39783
+ return identity.isCollection(this.contents) ? this.contents.getIn(path88, keepScalar) : void 0;
39712
39784
  }
39713
39785
  /**
39714
39786
  * Checks if the document includes a value with the key `key`.
@@ -39719,10 +39791,10 @@ var require_Document = __commonJS({
39719
39791
  /**
39720
39792
  * Checks if the document includes a value at `path`.
39721
39793
  */
39722
- hasIn(path87) {
39723
- if (Collection.isEmptyPath(path87))
39794
+ hasIn(path88) {
39795
+ if (Collection.isEmptyPath(path88))
39724
39796
  return this.contents !== void 0;
39725
- return identity.isCollection(this.contents) ? this.contents.hasIn(path87) : false;
39797
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path88) : false;
39726
39798
  }
39727
39799
  /**
39728
39800
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -39739,13 +39811,13 @@ var require_Document = __commonJS({
39739
39811
  * Sets a value in this document. For `!!set`, `value` needs to be a
39740
39812
  * boolean to add/remove the item from the set.
39741
39813
  */
39742
- setIn(path87, value) {
39743
- if (Collection.isEmptyPath(path87)) {
39814
+ setIn(path88, value) {
39815
+ if (Collection.isEmptyPath(path88)) {
39744
39816
  this.contents = value;
39745
39817
  } else if (this.contents == null) {
39746
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path87), value);
39818
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path88), value);
39747
39819
  } else if (assertCollection(this.contents)) {
39748
- this.contents.setIn(path87, value);
39820
+ this.contents.setIn(path88, value);
39749
39821
  }
39750
39822
  }
39751
39823
  /**
@@ -41706,9 +41778,9 @@ var require_cst_visit = __commonJS({
41706
41778
  visit2.BREAK = BREAK;
41707
41779
  visit2.SKIP = SKIP;
41708
41780
  visit2.REMOVE = REMOVE;
41709
- visit2.itemAtPath = (cst, path87) => {
41781
+ visit2.itemAtPath = (cst, path88) => {
41710
41782
  let item = cst;
41711
- for (const [field2, index] of path87) {
41783
+ for (const [field2, index] of path88) {
41712
41784
  const tok = item?.[field2];
41713
41785
  if (tok && "items" in tok) {
41714
41786
  item = tok.items[index];
@@ -41717,23 +41789,23 @@ var require_cst_visit = __commonJS({
41717
41789
  }
41718
41790
  return item;
41719
41791
  };
41720
- visit2.parentCollection = (cst, path87) => {
41721
- const parent = visit2.itemAtPath(cst, path87.slice(0, -1));
41722
- const field2 = path87[path87.length - 1][0];
41792
+ visit2.parentCollection = (cst, path88) => {
41793
+ const parent = visit2.itemAtPath(cst, path88.slice(0, -1));
41794
+ const field2 = path88[path88.length - 1][0];
41723
41795
  const coll = parent?.[field2];
41724
41796
  if (coll && "items" in coll)
41725
41797
  return coll;
41726
41798
  throw new Error("Parent collection not found");
41727
41799
  };
41728
- function _visit(path87, item, visitor) {
41729
- let ctrl = visitor(item, path87);
41800
+ function _visit(path88, item, visitor) {
41801
+ let ctrl = visitor(item, path88);
41730
41802
  if (typeof ctrl === "symbol")
41731
41803
  return ctrl;
41732
41804
  for (const field2 of ["key", "value"]) {
41733
41805
  const token2 = item[field2];
41734
41806
  if (token2 && "items" in token2) {
41735
41807
  for (let i = 0; i < token2.items.length; ++i) {
41736
- const ci = _visit(Object.freeze(path87.concat([[field2, i]])), token2.items[i], visitor);
41808
+ const ci = _visit(Object.freeze(path88.concat([[field2, i]])), token2.items[i], visitor);
41737
41809
  if (typeof ci === "number")
41738
41810
  i = ci - 1;
41739
41811
  else if (ci === BREAK)
@@ -41744,10 +41816,10 @@ var require_cst_visit = __commonJS({
41744
41816
  }
41745
41817
  }
41746
41818
  if (typeof ctrl === "function" && field2 === "key")
41747
- ctrl = ctrl(item, path87);
41819
+ ctrl = ctrl(item, path88);
41748
41820
  }
41749
41821
  }
41750
- return typeof ctrl === "function" ? ctrl(item, path87) : ctrl;
41822
+ return typeof ctrl === "function" ? ctrl(item, path88) : ctrl;
41751
41823
  }
41752
41824
  exports.visit = visit2;
41753
41825
  }
@@ -43049,14 +43121,14 @@ var require_parser = __commonJS({
43049
43121
  case "scalar":
43050
43122
  case "single-quoted-scalar":
43051
43123
  case "double-quoted-scalar": {
43052
- const fs89 = this.flowScalar(this.type);
43124
+ const fs90 = this.flowScalar(this.type);
43053
43125
  if (atNextItem || it.value) {
43054
- map3.items.push({ start, key: fs89, sep: [] });
43126
+ map3.items.push({ start, key: fs90, sep: [] });
43055
43127
  this.onKeyLine = true;
43056
43128
  } else if (it.sep) {
43057
- this.stack.push(fs89);
43129
+ this.stack.push(fs90);
43058
43130
  } else {
43059
- Object.assign(it, { key: fs89, sep: [] });
43131
+ Object.assign(it, { key: fs90, sep: [] });
43060
43132
  this.onKeyLine = true;
43061
43133
  }
43062
43134
  return;
@@ -43184,13 +43256,13 @@ var require_parser = __commonJS({
43184
43256
  case "scalar":
43185
43257
  case "single-quoted-scalar":
43186
43258
  case "double-quoted-scalar": {
43187
- const fs89 = this.flowScalar(this.type);
43259
+ const fs90 = this.flowScalar(this.type);
43188
43260
  if (!it || it.value)
43189
- fc.items.push({ start: [], key: fs89, sep: [] });
43261
+ fc.items.push({ start: [], key: fs90, sep: [] });
43190
43262
  else if (it.sep)
43191
- this.stack.push(fs89);
43263
+ this.stack.push(fs90);
43192
43264
  else
43193
- Object.assign(it, { key: fs89, sep: [] });
43265
+ Object.assign(it, { key: fs90, sep: [] });
43194
43266
  return;
43195
43267
  }
43196
43268
  case "flow-map-end":
@@ -43609,7 +43681,7 @@ function landSections(body, previews) {
43609
43681
  }
43610
43682
  function parseStudioFile(id2, source2, from, { requirePreviewCopy = false, requireLand = false } = {}) {
43611
43683
  const problems = [];
43612
- const fail = (offset, path87, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source2, offset), path: path87, code, message, hint: hint2 });
43684
+ const fail = (offset, path88, code, message, hint2) => problems.push({ file: from, ...sourcePosition(source2, offset), path: path88, code, message, hint: hint2 });
43613
43685
  const result = () => ({ problem: problems.map((p) => `${p.file}:${p.line}:${p.column} ${p.path}: ${p.code} \u2014 ${p.message}. ${p.hint}`).join("\n"), problems });
43614
43686
  if (!STUDIO_ID.test(id2)) fail(0, "id", "studio-schema", `Invalid Studio ID ${id2}`, "Use lowercase letters, digits and dashes.");
43615
43687
  const front = /^---\r?\n([^]*?)\r?\n---(?:\r?\n|$)/.exec(source2);
@@ -43778,11 +43850,11 @@ function inspect(value, official, { allowLegacyPreviewCopy, allowLegacyLand } =
43778
43850
  };
43779
43851
  if (!value || typeof value !== "object" || Array.isArray(value)) return fail("files", "must be an object of path \u2192 text");
43780
43852
  const files = Object.fromEntries(Object.entries(value).filter(([file2]) => file2 !== VERSION_FILE));
43781
- const entries = Object.entries(files);
43782
- if (entries.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
43853
+ const entries2 = Object.entries(files);
43854
+ if (entries2.length > FILE_LIMITS.count) return fail("files", `holds at most ${FILE_LIMITS.count} files`, true);
43783
43855
  let total = 0;
43784
43856
  const skills = /* @__PURE__ */ new Set();
43785
- for (const [file2, text5] of entries) {
43857
+ for (const [file2, text5] of entries2) {
43786
43858
  if (typeof text5 !== "string" || text5.includes("\0")) {
43787
43859
  fail(file2, "is not a text file");
43788
43860
  continue;
@@ -43985,11 +44057,19 @@ function pinMissing() {
43985
44057
  const pin = readPin(task);
43986
44058
  return !(pin && readVersion(pin.studio, pin.version));
43987
44059
  }
44060
+ function invalid(expected) {
44061
+ const problem = invalidResponse(expected);
44062
+ return { ...problem, ok: false, error: problem.message };
44063
+ }
44064
+ function isStudioFiles(value) {
44065
+ return isRecord(value) && hasText(value["STUDIO.md"]) && Object.entries(value).every(([file2, text5]) => typeof text5 === "string" && !/[\\:\0]/.test(file2) && file2.split("/").every((part) => !!part && part !== "." && part !== ".."));
44066
+ }
43988
44067
  async function versionOf(id2, version2) {
43989
44068
  const held4 = readVersion(id2, version2);
43990
44069
  if (held4) return { ok: true, value: held4 };
43991
44070
  const read5 = await call("GET", `/v1/studios/${encodeURIComponent(id2)}`);
43992
44071
  if (!read5.ok) return read5;
44072
+ if (read5.value.id !== id2 || !isStudioVersion(read5.value.version) || !isStudioFiles(read5.value.files)) return invalid("a valid Studio version");
43993
44073
  saveVersion(read5.value);
43994
44074
  return read5;
43995
44075
  }
@@ -43999,55 +44079,68 @@ async function pinTask(task) {
43999
44079
  if (held4 && "def" in parseStudioFile("studio", held4.files["STUDIO.md"] ?? "", "STUDIO.md")) return { ok: true, value: held4 };
44000
44080
  const read5 = await call("GET", `/v1/tasks/${encodeURIComponent(task)}/studio`);
44001
44081
  if (!read5.ok) return read5;
44082
+ if (!hasText(read5.value.studio) || !isStudioVersion(read5.value.version) || !isStudioFiles(read5.value.files)) return invalid("the task\u2019s Studio version");
44002
44083
  const value = { id: read5.value.studio, version: read5.value.version, name: read5.value.name, files: read5.value.files, historicalPreviews: read5.value.historicalPreviews };
44003
44084
  savePin(task, value);
44004
44085
  return { ok: true, value };
44005
44086
  }
44006
44087
  async function syncStudios(force = false) {
44007
- offline = false;
44088
+ verification = { cached: false };
44008
44089
  const project2 = boardProject();
44009
44090
  if (devFolder() || !project2 || !cloudConfigured() || !readSession()) return;
44010
44091
  const task = workspaceTask();
44011
44092
  const held4 = readJson(listFile(project2));
44012
44093
  const fresh = held4 && Date.now() - Date.parse(held4.at) < FRESH_MS;
44094
+ const failed2 = (failure2) => {
44095
+ verification = { cached: !!held4, problem: {
44096
+ code: failure2.code ?? "unreachable",
44097
+ message: failure2.error,
44098
+ status: failure2.status,
44099
+ retryable: failure2.retryable ?? temporaryCloudFailure(failure2)
44100
+ } };
44101
+ };
44013
44102
  try {
44014
44103
  if (task) {
44015
44104
  const pinned2 = await pinTask(task);
44016
- if (!pinned2.ok && !pinned2.code) offline = true;
44105
+ if (!pinned2.ok) failed2(pinned2);
44106
+ }
44107
+ if (fresh && !force) {
44108
+ verification.cached = true;
44109
+ return;
44017
44110
  }
44018
- if (fresh && !force) return;
44019
44111
  let workspace2 = held4?.workspace;
44020
44112
  if (!workspace2) {
44021
44113
  const read5 = await call("GET", `/v1/projects/${encodeURIComponent(project2)}`);
44022
- if (!read5.ok) {
44023
- offline = !read5.code;
44024
- return;
44025
- }
44114
+ if (!read5.ok) return failed2(read5);
44115
+ if (!hasText(read5.value.workspace)) return failed2({ ok: false, error: "Cloud did not return a workspace.", code: "invalid_response" });
44026
44116
  workspace2 = read5.value.workspace;
44027
44117
  }
44028
44118
  const listed = [];
44119
+ const cursors = /* @__PURE__ */ new Set();
44029
44120
  let after2 = null;
44030
44121
  do {
44031
44122
  const page = await call(
44032
44123
  "GET",
44033
44124
  `/v1/studios?workspace=${encodeURIComponent(workspace2)}&limit=100${after2 ? `&after=${encodeURIComponent(after2)}` : ""}`
44034
44125
  );
44035
- if (!page.ok) {
44036
- offline = !page.code;
44037
- return;
44126
+ if (!page.ok) return failed2(page);
44127
+ if (!Array.isArray(page.value.data) || page.value.data.some((w) => !isRecord(w) || !hasText(w.id) || !isStudioVersion(w.version)) || page.value.next !== null && (!hasText(page.value.next) || cursors.has(page.value.next))) {
44128
+ return failed2({ ok: false, error: "Cloud did not return a valid Studio list.", code: "invalid_response" });
44038
44129
  }
44039
- listed.push(...page.value.data.map((w) => ({ id: w.id, version: w.version })));
44130
+ listed.push(...page.value.data.map(({ id: id2, version: version2 }) => ({ id: id2, version: version2 })));
44040
44131
  after2 = page.value.next;
44132
+ if (after2) cursors.add(after2);
44041
44133
  } while (after2);
44042
44134
  const kept2 = [];
44043
44135
  for (const w of listed) {
44044
44136
  const read5 = await versionOf(w.id, w.version);
44045
- if (read5.ok) kept2.push({ id: read5.value.id, version: read5.value.version });
44046
- else if (!read5.code) offline = true;
44137
+ if (!read5.ok) return failed2(read5);
44138
+ kept2.push({ id: read5.value.id, version: read5.value.version });
44047
44139
  }
44048
44140
  writeJson(listFile(project2), { at: (/* @__PURE__ */ new Date()).toISOString(), workspace: workspace2, studios: kept2 });
44049
- } catch {
44050
- offline = true;
44141
+ verification.cached = false;
44142
+ } catch (error62) {
44143
+ failed2({ ok: false, code: "studio_cache_error", error: error62 instanceof Error ? error62.message : String(error62) });
44051
44144
  }
44052
44145
  }
44053
44146
  function readFlows() {
@@ -44090,13 +44183,14 @@ function taskHistoricalPreviews() {
44090
44183
  const task = workspaceTask();
44091
44184
  return task ? Object.keys(readPin(task)?.historicalPreviews ?? {}) : [];
44092
44185
  }
44093
- var DEV, FRESH_MS, root, safe, versionFile, listFile, pinFile, readVersion, readPin, boardProject, devFolder, NEEDS_CLOUD, NOT_DOWNLOADED, offline, studiosOffline, flowOf, sources, flows, cloudStudioSources, cloudFlows;
44186
+ var DEV, FRESH_MS, root, safe, versionFile, listFile, pinFile, readVersion, readPin, boardProject, devFolder, NEEDS_CLOUD, NOT_DOWNLOADED, verification, studioVerification, isStudioVersion, flowOf, sources, flows, cloudStudioSources, cloudFlows;
44094
44187
  var init_cloud_studios = __esm({
44095
44188
  "../cli/src/lib/agent/cloud-studios.ts"() {
44096
44189
  "use strict";
44097
44190
  init_board_files();
44098
44191
  init_pack();
44099
44192
  init_tasks();
44193
+ init_response();
44100
44194
  init_config();
44101
44195
  init_session();
44102
44196
  init_file_memo();
@@ -44116,8 +44210,9 @@ var init_cloud_studios = __esm({
44116
44210
  devFolder = () => process.env[DEV]?.trim() || "";
44117
44211
  NEEDS_CLOUD = "Sign in to run studios.";
44118
44212
  NOT_DOWNLOADED = "This studio isn't downloaded yet. Connect and try again.";
44119
- offline = false;
44120
- studiosOffline = () => offline;
44213
+ verification = { cached: false };
44214
+ studioVerification = () => verification;
44215
+ isStudioVersion = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
44121
44216
  flowOf = (held4) => {
44122
44217
  const id2 = studioName(held4.id);
44123
44218
  const read5 = parseStudioFile(id2, held4.files["STUDIO.md"] ?? "", `the \`${id2}\` studio`);
@@ -44212,8 +44307,8 @@ function agentLines(agent, language2 = readLanguage()) {
44212
44307
  description: said2?.description || agent.description
44213
44308
  };
44214
44309
  }
44215
- function settingValues(name, settings, entries) {
44216
- const entry = entries[name];
44310
+ function settingValues(name, settings, entries2) {
44311
+ const entry = entries2[name];
44217
44312
  const values = {};
44218
44313
  const notes = [];
44219
44314
  for (const setting of settings) {
@@ -44232,8 +44327,8 @@ function settingValues(name, settings, entries) {
44232
44327
  }
44233
44328
  return { values, notes };
44234
44329
  }
44235
- function roleSettingsBlock(role, entries = specAgentEntries()) {
44236
- const { values } = roleSettings(role, entries);
44330
+ function roleSettingsBlock(role, entries2 = specAgentEntries()) {
44331
+ const { values } = roleSettings(role, entries2);
44237
44332
  const lines = (role.settings ?? []).map((setting) => setting.choices.find((c) => c.value === values[setting.key])?.prompt).filter((line) => Boolean(line));
44238
44333
  return lines.length ? ["Your settings on this board:", ...lines.map((line) => `- ${line}`)].join("\n") : "";
44239
44334
  }
@@ -44252,7 +44347,7 @@ var init_agents = __esm({
44252
44347
  findSpecAgent = (name) => {
44253
44348
  return specAgents().find((a) => a.name === name) ?? null;
44254
44349
  };
44255
- roleSettings = (role, entries = specAgentEntries()) => settingValues(role.name, role.settings ?? [], entries);
44350
+ roleSettings = (role, entries2 = specAgentEntries()) => settingValues(role.name, role.settings ?? [], entries2);
44256
44351
  }
44257
44352
  });
44258
44353
 
@@ -44632,9 +44727,9 @@ function readMap(lines, start, indent2) {
44632
44727
  }
44633
44728
  function readScalar(value) {
44634
44729
  if (value.startsWith("{") && value.endsWith("}")) {
44635
- const entries = value.slice(1, -1).match(/(?:[^,"']|"(?:\\.|[^"\\])*"|'(?:''|[^'])*')+/g) ?? [];
44730
+ const entries2 = value.slice(1, -1).match(/(?:[^,"']|"(?:\\.|[^"\\])*"|'(?:''|[^'])*')+/g) ?? [];
44636
44731
  const out = {};
44637
- for (const entry of entries) {
44732
+ for (const entry of entries2) {
44638
44733
  const pair = /^\s*([^:]+):\s*(.+)$/.exec(entry);
44639
44734
  if (!pair) return value;
44640
44735
  out[unquote(pair[1].trim())] = readScalar(pair[2].trim());
@@ -44894,13 +44989,13 @@ function readBundled(folder2) {
44894
44989
  return parseSpecAgent(text5, label2, file2, official, list3);
44895
44990
  }
44896
44991
  function projectFolders(root2) {
44897
- let entries;
44992
+ let entries2;
44898
44993
  try {
44899
- entries = fs33.readdirSync(root2, { withFileTypes: true });
44994
+ entries2 = fs33.readdirSync(root2, { withFileTypes: true });
44900
44995
  } catch {
44901
44996
  return [];
44902
44997
  }
44903
- return entries.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort();
44998
+ return entries2.filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name).sort();
44904
44999
  }
44905
45000
  function agentFileReader(dir) {
44906
45001
  return (relative) => {
@@ -44916,13 +45011,13 @@ function agentFileReader(dir) {
44916
45011
  };
44917
45012
  }
44918
45013
  function walkFolder(dir, prefix) {
44919
- let entries;
45014
+ let entries2;
44920
45015
  try {
44921
- entries = fs33.readdirSync(dir, { withFileTypes: true });
45016
+ entries2 = fs33.readdirSync(dir, { withFileTypes: true });
44922
45017
  } catch {
44923
45018
  return [];
44924
45019
  }
44925
- return entries.flatMap((e) => {
45020
+ return entries2.flatMap((e) => {
44926
45021
  const here = prefix ? `${prefix}/${e.name}` : e.name;
44927
45022
  return e.isDirectory() ? walkFolder(path37.join(dir, e.name), here) : [here];
44928
45023
  });
@@ -49058,13 +49153,13 @@ function freeName(dir, wanted) {
49058
49153
  return name;
49059
49154
  }
49060
49155
  function readFolder(dir, lenient = false) {
49061
- let entries;
49156
+ let entries2;
49062
49157
  try {
49063
- entries = fs46.readdirSync(dir, { withFileTypes: true });
49158
+ entries2 = fs46.readdirSync(dir, { withFileTypes: true });
49064
49159
  } catch {
49065
49160
  return [];
49066
49161
  }
49067
- return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".md")).map((entry) => parse3(path51.join(dir, entry.name), lenient)).filter((signal2) => signal2 !== null);
49162
+ return entries2.filter((entry) => entry.isFile() && entry.name.endsWith(".md")).map((entry) => parse3(path51.join(dir, entry.name), lenient)).filter((signal2) => signal2 !== null);
49068
49163
  }
49069
49164
  function readInbox() {
49070
49165
  const signals = readFolder(TRIAGE);
@@ -49140,6 +49235,54 @@ var init_inbox = __esm({
49140
49235
  }
49141
49236
  });
49142
49237
 
49238
+ // ../cli/src/lib/question-ops.ts
49239
+ function questionPositions(raw, count3, flag) {
49240
+ const ns = String(raw).split(",").map((s) => s.trim()).filter((s) => s.length > 0).map(Number);
49241
+ if (ns.length === 0 || ns.some((n) => !Number.isInteger(n) || n < 1)) {
49242
+ throw new QuestionOpError(`--${flag} needs one or more 1-based question numbers (e.g. 1 or 1,3)`);
49243
+ }
49244
+ const over = ns.find((n) => n > count3);
49245
+ if (over !== void 0) throw new QuestionOpError(`the card has ${count3} open question(s) \u2014 there's no question ${over}`);
49246
+ return ns;
49247
+ }
49248
+ function applyQuestionOps(start, ops, asker) {
49249
+ let questions = [...start];
49250
+ const changes = [];
49251
+ const closed2 = [];
49252
+ const positions = (op, flag) => questionPositions(op.ns ?? String(op.n), questions.length, flag);
49253
+ for (const op of ops) {
49254
+ if (op.kind === "clear") {
49255
+ closed2.push(...questions);
49256
+ questions = [];
49257
+ changes.push("cleared");
49258
+ } else if (op.kind === "drop") {
49259
+ const ns = positions(op, "drop");
49260
+ closed2.push(...ns.map((n) => questions[n - 1]));
49261
+ questions = questions.filter((_, i) => !ns.includes(i + 1));
49262
+ changes.push(`dropped ${ns.join(",")}`);
49263
+ } else if (op.kind === "append") {
49264
+ const agent = op.question.agent ?? asker;
49265
+ questions.push(agent ? { ...op.question, agent } : op.question);
49266
+ changes.push("appended");
49267
+ } else {
49268
+ const [n] = positions(op, "update");
49269
+ const agent = op.question.agent ?? questions[n - 1].agent;
49270
+ questions[n - 1] = { ...op.question, ...agent ? { agent } : {} };
49271
+ changes.push(`rewrote ${n}`);
49272
+ }
49273
+ }
49274
+ return { questions, changes, closed: closed2 };
49275
+ }
49276
+ var QUESTION_EDIT_LIMITS, QuestionOpError;
49277
+ var init_question_ops = __esm({
49278
+ "../cli/src/lib/question-ops.ts"() {
49279
+ "use strict";
49280
+ QUESTION_EDIT_LIMITS = { operations: 50, text: 4e3, options: 20, option: 200 };
49281
+ QuestionOpError = class extends Error {
49282
+ };
49283
+ }
49284
+ });
49285
+
49143
49286
  // ../cli/src/lib/questions.ts
49144
49287
  function newDraft(flag, value) {
49145
49288
  const text5 = value.trim();
@@ -49194,7 +49337,7 @@ function missingChoices(text5) {
49194
49337
  `"${text5}" needs choices to tick \u2014 add 2 or more --option "a \u2014 why". The user always gets a free-text choice too, so never write one yourself.`
49195
49338
  );
49196
49339
  }
49197
- function readQuestionOps(typed) {
49340
+ function readQuestionOps(typed, compatibility = false) {
49198
49341
  const ops = [];
49199
49342
  for (let i = 0; i < typed.length; i++) {
49200
49343
  const [key, value] = typed[i];
@@ -49220,71 +49363,40 @@ function readQuestionOps(typed) {
49220
49363
  if (!ops.length) {
49221
49364
  die('update-questions needs at least one op: --append ".." | --update <n> ".." | --drop n[,n...] | --clear');
49222
49365
  }
49366
+ if (!compatibility && ops.length > QUESTION_EDIT_LIMITS.operations) {
49367
+ die(`Submit at most ${QUESTION_EDIT_LIMITS.operations} edits at a time.`);
49368
+ }
49223
49369
  for (const op of ops) {
49224
49370
  if (op.draft) {
49371
+ if (!compatibility) validateQuestionEdit(op.draft);
49225
49372
  op.question = finalizeDraft(op.draft);
49226
49373
  delete op.draft;
49227
49374
  }
49228
49375
  }
49229
49376
  return ops;
49230
49377
  }
49378
+ function validateQuestionEdit(draft) {
49379
+ const { text: text5, option, options } = QUESTION_EDIT_LIMITS;
49380
+ if (Buffer.byteLength(draft.question) > text5) die(`Question text must be at most ${text5} bytes.`);
49381
+ if (draft.options.length > options) die(`A question can have at most ${options} choices.`);
49382
+ if (draft.options.some((choice) => Buffer.byteLength(choice) > option)) die(`Each choice must be at most ${option} bytes.`);
49383
+ if (draft.recommended.length > 1) die("A question takes at most one --recommended-option.");
49384
+ if (draft.agent && (draft.agent.length > 64 || !AGENT_NAME.test(draft.agent))) {
49385
+ die("--agent must be at most 64 characters with lowercase letters or digits joined by hyphens.");
49386
+ }
49387
+ }
49231
49388
  var init_questions = __esm({
49232
49389
  "../cli/src/lib/questions.ts"() {
49233
49390
  "use strict";
49234
49391
  init_paths();
49392
+ init_parse3();
49393
+ init_question_ops();
49235
49394
  init_question_block();
49236
49395
  init_question_block();
49237
49396
  init_rules();
49238
49397
  }
49239
49398
  });
49240
49399
 
49241
- // ../cli/src/lib/question-ops.ts
49242
- function questionPositions(raw, count3, flag) {
49243
- const ns = String(raw).split(",").map((s) => s.trim()).filter((s) => s.length > 0).map(Number);
49244
- if (ns.length === 0 || ns.some((n) => !Number.isInteger(n) || n < 1)) {
49245
- throw new QuestionOpError(`--${flag} needs one or more 1-based question numbers (e.g. 1 or 1,3)`);
49246
- }
49247
- const over = ns.find((n) => n > count3);
49248
- if (over !== void 0) throw new QuestionOpError(`the card has ${count3} open question(s) \u2014 there's no question ${over}`);
49249
- return ns;
49250
- }
49251
- function applyQuestionOps(start, ops, asker) {
49252
- let questions = [...start];
49253
- const changes = [];
49254
- const closed2 = [];
49255
- const positions = (op, flag) => questionPositions(op.ns ?? String(op.n), questions.length, flag);
49256
- for (const op of ops) {
49257
- if (op.kind === "clear") {
49258
- closed2.push(...questions);
49259
- questions = [];
49260
- changes.push("cleared");
49261
- } else if (op.kind === "drop") {
49262
- const ns = positions(op, "drop");
49263
- closed2.push(...ns.map((n) => questions[n - 1]));
49264
- questions = questions.filter((_, i) => !ns.includes(i + 1));
49265
- changes.push(`dropped ${ns.join(",")}`);
49266
- } else if (op.kind === "append") {
49267
- const agent = op.question.agent ?? asker;
49268
- questions.push(agent ? { ...op.question, agent } : op.question);
49269
- changes.push("appended");
49270
- } else {
49271
- const [n] = positions(op, "update");
49272
- const agent = op.question.agent ?? questions[n - 1].agent;
49273
- questions[n - 1] = { ...op.question, ...agent ? { agent } : {} };
49274
- changes.push(`rewrote ${n}`);
49275
- }
49276
- }
49277
- return { questions, changes, closed: closed2 };
49278
- }
49279
- var QuestionOpError;
49280
- var init_question_ops = __esm({
49281
- "../cli/src/lib/question-ops.ts"() {
49282
- "use strict";
49283
- QuestionOpError = class extends Error {
49284
- };
49285
- }
49286
- });
49287
-
49288
49400
  // ../cli/src/lib/source.ts
49289
49401
  function parseSourceRef(raw) {
49290
49402
  const text5 = raw.trim();
@@ -49946,6 +50058,37 @@ var init_manifest = __esm({
49946
50058
  }
49947
50059
  });
49948
50060
 
50061
+ // ../artifact-sdk/src/internal/file-references.ts
50062
+ function splitFileReference(src) {
50063
+ const end2 = src.search(/[?#]/);
50064
+ return end2 < 0 ? [src, ""] : [src.slice(0, end2), src.slice(end2)];
50065
+ }
50066
+ function relativeFileReference(src, owner) {
50067
+ const parts = owner.split("/").slice(0, -1);
50068
+ for (const part of src.split("/")) {
50069
+ if (part === ".." && parts.length && parts.at(-1) !== "..") parts.pop();
50070
+ else if (part && part !== ".") parts.push(part);
50071
+ }
50072
+ return parts.join("/");
50073
+ }
50074
+ var CSS, fileManifest;
50075
+ var init_file_references = __esm({
50076
+ "../artifact-sdk/src/internal/file-references.ts"() {
50077
+ "use strict";
50078
+ init_manifest();
50079
+ CSS = {
50080
+ name: "css",
50081
+ types: ["css"],
50082
+ references: [
50083
+ { text: `@import\\s+["']([^"']+)["']` },
50084
+ { text: `url\\(\\s*["']?([^"')]+?)["']?\\s*\\)` }
50085
+ ],
50086
+ skip: ["/\\*[\\s\\S]*?\\*/"]
50087
+ };
50088
+ fileManifest = (type, name) => type === "asset" && /\.css$/i.test(name) ? CSS : manifestOf(type);
50089
+ }
50090
+ });
50091
+
49949
50092
  // ../artifact-sdk/src/internal/collect.ts
49950
50093
  function collect(body, card, host2) {
49951
50094
  return collectSources(bodyReferences(body), card, host2);
@@ -49955,14 +50098,14 @@ function collectSources(sources2, card, host2) {
49955
50098
  const active3 = /* @__PURE__ */ new Set();
49956
50099
  const out = [];
49957
50100
  const visit2 = (src, types, owner, partial2 = false) => {
49958
- const path87 = src.replace(/[?#].*$/, "");
50101
+ const [path88] = splitFileReference(src);
49959
50102
  let resolved;
49960
50103
  try {
49961
- resolved = host2.resolve(path87, owner);
50104
+ resolved = host2.resolve(path88, owner);
49962
50105
  } catch (error62) {
49963
50106
  if (owner !== card) return { key: null, error: why(error62) };
49964
50107
  if (!nodes.has(src)) {
49965
- const node3 = { key: src, file: null, kind: kindAt(path87, types), error: why(error62), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
50108
+ const node3 = { key: src, file: null, kind: kindAt(path88, types), error: why(error62), problems: [], dependencies: /* @__PURE__ */ new Map(), aliases: /* @__PURE__ */ new Set([src]) };
49966
50109
  nodes.set(src, node3);
49967
50110
  out.push(node3);
49968
50111
  }
@@ -50005,13 +50148,13 @@ function collectSources(sources2, card, host2) {
50005
50148
  } else {
50006
50149
  node2.kind = textKind(extOf(file2), types);
50007
50150
  try {
50008
- if (manifestOf(node2.kind)?.references) node2.data = host2.read(file2);
50151
+ if (fileManifest(node2.kind, file2)?.references) node2.data = host2.read(file2);
50009
50152
  } catch (error62) {
50010
50153
  node2.problems.push({ src: file2, message: why(error62) });
50011
50154
  }
50012
50155
  }
50013
50156
  node2.error = node2.problems[0]?.message;
50014
- if (!node2.error) for (const ref of referencesOf(manifestOf(node2.kind), node2.data)) child(ref, file2);
50157
+ if (!node2.error) for (const ref of referencesOf(fileManifest(node2.kind, file2), node2.data)) child(ref, file2);
50015
50158
  } else {
50016
50159
  for (const ref of host2.retained(key, types)) child(ref, card);
50017
50160
  }
@@ -50038,6 +50181,7 @@ var extOf, why, textKind, kindAt;
50038
50181
  var init_collect = __esm({
50039
50182
  "../artifact-sdk/src/internal/collect.ts"() {
50040
50183
  "use strict";
50184
+ init_file_references();
50041
50185
  init_manifest();
50042
50186
  init_references();
50043
50187
  extOf = (file2) => /\.[^./\\]+$/.exec(file2)?.[0].toLowerCase() ?? "";
@@ -50835,14 +50979,16 @@ function cmdUpdate(id2, flags) {
50835
50979
  return { id: id2, changes, file: rel(dest) };
50836
50980
  }
50837
50981
  function cmdUpdateQuestions(id2, input2) {
50838
- const ops = readQuestionOps(input2.ops ?? []);
50982
+ return updateCardQuestions(id2, readQuestionOps(input2.ops ?? [], true), true);
50983
+ }
50984
+ function updateCardQuestions(id2, ops, compatibility = false) {
50839
50985
  const found2 = locate(id2);
50840
50986
  if (!found2) die(`no task with id ${id2} under ${rel(TODO)}`, { kind: "card-not-found", id: id2 });
50841
50987
  const file2 = found2.kind === "group" ? path57.join(found2.target, "root.md") : found2.target;
50842
50988
  const { meta: meta3, body } = parseFrontmatter(fs52.readFileSync(file2, "utf8"));
50843
50989
  if (!meta3) die(`${rel(file2)} has no frontmatter \u2014 recreate it with \`akb raw create\``);
50844
50990
  for (const op of ops) {
50845
- if (!op.question?.agent) continue;
50991
+ if (!compatibility || !op.question?.agent) continue;
50846
50992
  const agent = findSpecAgent(op.question.agent);
50847
50993
  if (!agent) die(`--agent "${op.question.agent}" is not an agent on this board`, { kind: "no-such-spec-agent", specAgent: op.question.agent });
50848
50994
  op.question.agent = agent.name;
@@ -51538,7 +51684,7 @@ next \u2014 what the script can't do:
51538
51684
  }
51539
51685
  if (mentions.some((m) => m.where !== "body")) {
51540
51686
  say(" A mention in frontmatter is the script's to rewrite, not yours:");
51541
- say(' `update-questions <id> --update <n> "..."` (see help).');
51687
+ say(' `akb task update-questions <task> --update <n> "..."` (see help).');
51542
51688
  }
51543
51689
  return note;
51544
51690
  }
@@ -53642,8 +53788,8 @@ var require_command = __commonJS({
53642
53788
  "../cli/node_modules/commander/lib/command.js"(exports) {
53643
53789
  var EventEmitter = __require("node:events").EventEmitter;
53644
53790
  var childProcess = __require("node:child_process");
53645
- var path87 = __require("node:path");
53646
- var fs89 = __require("node:fs");
53791
+ var path88 = __require("node:path");
53792
+ var fs90 = __require("node:fs");
53647
53793
  var process2 = __require("node:process");
53648
53794
  var { Argument: Argument2, humanReadableArgName } = require_argument();
53649
53795
  var { CommanderError: CommanderError2 } = require_error();
@@ -54624,7 +54770,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
54624
54770
  * @param {string} subcommandName
54625
54771
  */
54626
54772
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
54627
- if (fs89.existsSync(executableFile)) return;
54773
+ if (fs90.existsSync(executableFile)) return;
54628
54774
  const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
54629
54775
  const executableMissing = `'${executableFile}' does not exist
54630
54776
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
@@ -54642,11 +54788,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
54642
54788
  let launchWithNode = false;
54643
54789
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
54644
54790
  function findFile(baseDir, baseName) {
54645
- const localBin = path87.resolve(baseDir, baseName);
54646
- if (fs89.existsSync(localBin)) return localBin;
54647
- if (sourceExt.includes(path87.extname(baseName))) return void 0;
54791
+ const localBin = path88.resolve(baseDir, baseName);
54792
+ if (fs90.existsSync(localBin)) return localBin;
54793
+ if (sourceExt.includes(path88.extname(baseName))) return void 0;
54648
54794
  const foundExt = sourceExt.find(
54649
- (ext) => fs89.existsSync(`${localBin}${ext}`)
54795
+ (ext) => fs90.existsSync(`${localBin}${ext}`)
54650
54796
  );
54651
54797
  if (foundExt) return `${localBin}${foundExt}`;
54652
54798
  return void 0;
@@ -54658,21 +54804,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
54658
54804
  if (this._scriptPath) {
54659
54805
  let resolvedScriptPath;
54660
54806
  try {
54661
- resolvedScriptPath = fs89.realpathSync(this._scriptPath);
54807
+ resolvedScriptPath = fs90.realpathSync(this._scriptPath);
54662
54808
  } catch {
54663
54809
  resolvedScriptPath = this._scriptPath;
54664
54810
  }
54665
- executableDir = path87.resolve(
54666
- path87.dirname(resolvedScriptPath),
54811
+ executableDir = path88.resolve(
54812
+ path88.dirname(resolvedScriptPath),
54667
54813
  executableDir
54668
54814
  );
54669
54815
  }
54670
54816
  if (executableDir) {
54671
54817
  let localFile = findFile(executableDir, executableFile);
54672
54818
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
54673
- const legacyName = path87.basename(
54819
+ const legacyName = path88.basename(
54674
54820
  this._scriptPath,
54675
- path87.extname(this._scriptPath)
54821
+ path88.extname(this._scriptPath)
54676
54822
  );
54677
54823
  if (legacyName !== this._name) {
54678
54824
  localFile = findFile(
@@ -54683,7 +54829,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
54683
54829
  }
54684
54830
  executableFile = localFile || executableFile;
54685
54831
  }
54686
- launchWithNode = sourceExt.includes(path87.extname(executableFile));
54832
+ launchWithNode = sourceExt.includes(path88.extname(executableFile));
54687
54833
  let proc;
54688
54834
  if (process2.platform !== "win32") {
54689
54835
  if (launchWithNode) {
@@ -55530,7 +55676,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
55530
55676
  * @return {Command}
55531
55677
  */
55532
55678
  nameFromFilename(filename) {
55533
- this._name = path87.basename(filename, path87.extname(filename));
55679
+ this._name = path88.basename(filename, path88.extname(filename));
55534
55680
  return this;
55535
55681
  }
55536
55682
  /**
@@ -55544,9 +55690,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
55544
55690
  * @param {string} [path]
55545
55691
  * @return {(string|null|Command)}
55546
55692
  */
55547
- executableDir(path88) {
55548
- if (path88 === void 0) return this._executableDir;
55549
- this._executableDir = path88;
55693
+ executableDir(path89) {
55694
+ if (path89 === void 0) return this._executableDir;
55695
+ this._executableDir = path89;
55550
55696
  return this;
55551
55697
  }
55552
55698
  /**
@@ -56375,6 +56521,19 @@ var init_board_conflicts2 = __esm({
56375
56521
  }
56376
56522
  });
56377
56523
 
56524
+ // ../cli/src/lib/cli/question-options.ts
56525
+ function withQuestionOptions(command, ops) {
56526
+ const inOrder = ordered(ops);
56527
+ return command.option("--append <text>", "append a new question", inOrder("append")).option("--update <n> <text...>", "rewrite question <n>", inOrder("update")).option("--drop <positions>", "remove questions, e.g. 1 or 1,3", inOrder("drop")).option("--clear", "remove every open question", inOrder("clear")).option("--option <text>", "a choice for the preceding append or update", inOrder("option")).option("--recommended-option <text>", "a choice selected by default", inOrder("recommended-option")).option("--mode <mode>", "single (default) or multi", inOrder("mode")).addOption(new Option("--agent <name>").hideHelp().argParser(inOrder("agent")));
56528
+ }
56529
+ var init_question_options = __esm({
56530
+ "../cli/src/lib/cli/question-options.ts"() {
56531
+ "use strict";
56532
+ init_esm();
56533
+ init_shared2();
56534
+ }
56535
+ });
56536
+
56378
56537
  // ../cli/src/lib/cli/board.ts
56379
56538
  var board_exports = {};
56380
56539
  __export(board_exports, {
@@ -56524,10 +56683,7 @@ function buildBoardProgram(cli) {
56524
56683
  await dispatch("update", this, [String(id2)], this.opts(), cli);
56525
56684
  });
56526
56685
  const questionOps = [];
56527
- const opInOrder = ordered(questionOps);
56528
- move("update-questions").argument("<id>", ID, cardId).summary("patch a card's open questions: append, rewrite, drop, skip, or clear").description(
56529
- "Patch the open-question list in place. Ops apply in the order they were typed, and a position is read against the list as it stands when its op runs. Positions are 1-based. A question handed to the user always carries choices to tick \u2014 follow `akb guide update-questions`. --option, --recommended-option and --mode attach to the --append or --update before them."
56530
- ).option("--append <text>", "add one question to the end", opInOrder("append")).option("--update <n> <text...>", "rewrite question <n> whole", opInOrder("update")).option("--drop <positions>", "remove answered questions, e.g. 1 or 1,3", opInOrder("drop")).option("--clear", "remove every open question", opInOrder("clear")).option("--option <text>", "a choice for the op before it", opInOrder("option")).option("--recommended-option <text>", "a choice for the op before it, ticked to start", opInOrder("recommended-option")).option("--mode <mode>", "how many choices the op before it takes: single | multi", opInOrder("mode")).addOption(new Option("--agent <name>").hideHelp().argParser(opInOrder("agent"))).action(async function(id2) {
56686
+ withQuestionOptions(withShared(program2.command("update-questions", { hidden: true })).argument("<id>", ID, cardId).summary("edit open questions on a local card (compatibility)").description("For older Runner instructions. Use akb task update-questions.\nSee akb guide update-questions."), questionOps).action(async function(id2) {
56531
56687
  await dispatch("update-questions", this, [String(id2)], { ops: questionOps }, cli);
56532
56688
  });
56533
56689
  move("inspect").argument("<id>", ID, cardId).summary("read task facts, saved work and execution references").action(async function(id2) {
@@ -56605,6 +56761,7 @@ var init_board2 = __esm({
56605
56761
  init_agent2();
56606
56762
  init_board_conflicts();
56607
56763
  init_board_conflicts2();
56764
+ init_question_options();
56608
56765
  ID = "the card's id";
56609
56766
  }
56610
56767
  });
@@ -56739,7 +56896,8 @@ function report(err, { program: program2, json: json2, box = null }) {
56739
56896
  if (json2) {
56740
56897
  answer({ ok: false, error: { kind: err.kind, message: err.message, ...err.details }, ...prose(box) });
56741
56898
  } else {
56742
- console.error(err.bare ? err.message : `${program2}: ${err.message}`);
56899
+ const code = typeof err.details.code === "string" ? `[${err.details.code}] ` : "";
56900
+ console.error(err.bare ? `${err.message}${code ? ` [${err.details.code}]` : ""}` : `${program2}: ${code}${err.message}`);
56743
56901
  }
56744
56902
  return err.exitCode;
56745
56903
  }
@@ -56760,6 +56918,31 @@ var init_board_cli = __esm({
56760
56918
  }
56761
56919
  });
56762
56920
 
56921
+ // ../cli/src/lib/cloud/task-operation.ts
56922
+ import fs67 from "node:fs";
56923
+ import path70 from "node:path";
56924
+ function readRemoval(board2, task) {
56925
+ try {
56926
+ const value = JSON.parse(fs67.readFileSync(removalFile(board2, task), "utf8"));
56927
+ if (["pending", "confirmed", "rejected"].includes(value.status) && typeof value.reason === "string" && typeof value.discard === "boolean") return value;
56928
+ } catch {
56929
+ }
56930
+ return null;
56931
+ }
56932
+ function writeRemoval(board2, task, removal) {
56933
+ const file2 = removalFile(board2, task);
56934
+ const temp = `${file2}.${process.pid}.tmp`;
56935
+ fs67.writeFileSync(temp, JSON.stringify(removal) + "\n");
56936
+ fs67.renameSync(temp, file2);
56937
+ }
56938
+ var removalFile;
56939
+ var init_task_operation = __esm({
56940
+ "../cli/src/lib/cloud/task-operation.ts"() {
56941
+ "use strict";
56942
+ removalFile = (board2, task) => path70.join(board2, ".sync", `${task}.removal.json`);
56943
+ }
56944
+ });
56945
+
56763
56946
  // ../cli/src/lib/cloud/avatar.ts
56764
56947
  async function heldAvatar(url2) {
56765
56948
  if (!url2) return null;
@@ -56806,10 +56989,10 @@ var init_avatar = __esm({
56806
56989
  });
56807
56990
 
56808
56991
  // ../cli/src/lib/cloud/pro.ts
56809
- import fs67 from "node:fs";
56810
- import path70 from "node:path";
56992
+ import fs68 from "node:fs";
56993
+ import path71 from "node:path";
56811
56994
  function forgetPro() {
56812
- fs67.rmSync(heldFile(), { force: true });
56995
+ fs68.rmSync(heldFile(), { force: true });
56813
56996
  }
56814
56997
  var FRESH_MS2, GRACE_MS, heldFile;
56815
56998
  var init_pro = __esm({
@@ -56820,7 +57003,7 @@ var init_pro = __esm({
56820
57003
  init_session();
56821
57004
  FRESH_MS2 = 10 * 6e4;
56822
57005
  GRACE_MS = 7 * 24 * 60 * 6e4;
56823
- heldFile = () => path70.join(machineHome(), "pro.json");
57006
+ heldFile = () => path71.join(machineHome(), "pro.json");
56824
57007
  }
56825
57008
  });
56826
57009
 
@@ -56839,39 +57022,42 @@ async function readCloudAccount() {
56839
57022
  configured: cloudConfigured()
56840
57023
  };
56841
57024
  if (!blank.configured) return { ...blank, message: NOT_CONFIGURED };
57025
+ const unverified = (problem2, state = "signed-in") => ({
57026
+ ...blank,
57027
+ ...held3(),
57028
+ state,
57029
+ ...state === "signed-in" ? { error: problem2.message } : { message: problem2.message },
57030
+ verificationFailure: problem2
57031
+ });
56842
57032
  const token2 = await accessToken();
56843
57033
  if (!token2.ok) {
56844
57034
  if (token2.reason === "signed-out") return blank;
56845
57035
  if (token2.reason === "unreachable") {
56846
- return { ...blank, ...held3(), state: "signed-in", error: token2.error };
57036
+ return unverified({ code: "unreachable", message: token2.error, retryable: true });
56847
57037
  }
56848
- return { ...blank, ...held3(), state: "expired" };
57038
+ return unverified({ code: "expired", message: token2.error ?? "Your Cloud sign-in has expired. Sign in again.", retryable: false }, "expired");
56849
57039
  }
56850
57040
  let response;
56851
57041
  try {
56852
57042
  response = await fetch(`${cloudEndpoints().api}/v1/session`, {
56853
- headers: { authorization: `Bearer ${token2.token}` }
57043
+ headers: { authorization: `Bearer ${token2.token}` },
57044
+ signal: AbortSignal.timeout(2e4)
56854
57045
  });
56855
57046
  } catch (e) {
56856
- return {
56857
- ...blank,
56858
- ...held3(),
56859
- state: "signed-in",
56860
- error: e instanceof Error ? e.message : String(e)
56861
- };
57047
+ return unverified({ code: "unreachable", message: e instanceof Error ? e.message : String(e), retryable: true });
56862
57048
  }
56863
- const body = await response.json().catch(() => ({}));
56864
- if (!response.ok) {
56865
- const refusal2 = body.error;
56866
- if (refusal2?.code === "unauthenticated") {
56867
- return { ...blank, ...held3(), state: "expired", message: refusal2.message ?? null };
56868
- }
56869
- if (refusal2?.code === "not_admitted") {
56870
- return { ...blank, ...held3(), state: "not-admitted", message: refusal2.message ?? null };
56871
- }
56872
- return { ...blank, ...held3(), state: "signed-in", error: refusal2?.message };
57049
+ const value = await readCloudJson(response);
57050
+ const problem = cloudProblem(response, value);
57051
+ if (problem) {
57052
+ if (problem.code === "unauthenticated") return unverified(problem, "expired");
57053
+ if (problem.code === "not_admitted") return unverified(problem, "not-admitted");
57054
+ return unverified(problem);
56873
57055
  }
56874
- const session = body.session ?? {};
57056
+ if (!isRecord(value) || !isRecord(value.session) || typeof value.session.admitted !== "boolean") {
57057
+ return unverified(invalidResponse("an account verification receipt"));
57058
+ }
57059
+ const body = value;
57060
+ const session = body.session;
56875
57061
  const avatarUrl = session.avatar_url ?? session.avatarUrl ?? null;
56876
57062
  const attested = {
56877
57063
  handle: session.handle ?? null,
@@ -56907,12 +57093,13 @@ var init_account = __esm({
56907
57093
  init_config();
56908
57094
  init_pro();
56909
57095
  init_session();
57096
+ init_response();
56910
57097
  }
56911
57098
  });
56912
57099
 
56913
57100
  // ../cli/src/commands/cloud.ts
56914
- import fs68 from "node:fs";
56915
- import path71 from "node:path";
57101
+ import fs69 from "node:fs";
57102
+ import path72 from "node:path";
56916
57103
  async function cmdCloud(args2, program2) {
56917
57104
  const [sub] = args2;
56918
57105
  if (sub === "sign-out") {
@@ -56927,6 +57114,16 @@ async function cmdCloud(args2, program2) {
56927
57114
  );
56928
57115
  }
56929
57116
  const account = await readCloudAccount();
57117
+ if (account.verificationFailure) {
57118
+ if (account.handle || account.email) say(`Cached account: ${account.handle ? "@" + account.handle : account.email}`);
57119
+ throw cloudError(
57120
+ {
57121
+ ...account.verificationFailure,
57122
+ message: `Cloud verification failed. Showing cached account details. ${account.verificationFailure.message}`
57123
+ },
57124
+ { details: { cached: true, cloud: account } }
57125
+ );
57126
+ }
56930
57127
  for (const line of report2(account, program2)) say(line);
56931
57128
  return { cloud: account };
56932
57129
  }
@@ -56974,10 +57171,10 @@ async function cloudImage(opts, program2) {
56974
57171
  const prompt = opts.prompt.trim();
56975
57172
  if (!prompt) usage("Missing the prompt.", line);
56976
57173
  const references = opts.refs.map((file2) => {
56977
- const type = REF_TYPES[path71.extname(file2).toLowerCase()];
57174
+ const type = REF_TYPES[path72.extname(file2).toLowerCase()];
56978
57175
  if (!type) usage(`--ref ${file2}: use a PNG, JPEG or WebP file.`, line);
56979
57176
  try {
56980
- return `data:${type};base64,${fs68.readFileSync(file2).toString("base64")}`;
57177
+ return `data:${type};base64,${fs69.readFileSync(file2).toString("base64")}`;
56981
57178
  } catch (e) {
56982
57179
  usage(`--ref ${file2}: ${e instanceof Error ? e.message : String(e)}`, line);
56983
57180
  }
@@ -57056,40 +57253,69 @@ async function cloudMusic(opts, program2) {
57056
57253
  label: () => `${seconds}s`
57057
57254
  });
57058
57255
  }
57059
- function refuse2(m, fallback) {
57060
- die([m.zh, m.en, fallback.zh, fallback.en].join("\n"), { kind: "cloud-refused", bare: true });
57256
+ function refuse2(m, fallback, problem, exitCode = 1) {
57257
+ const message = [m.zh, m.en, problem.message, fallback.zh, fallback.en].filter(Boolean).join("\n");
57258
+ throw cloudError({ ...problem, message }, { bare: true, exitCode });
57061
57259
  }
57062
57260
  async function generate(g) {
57063
57261
  const token2 = await accessToken();
57064
- if (!token2.ok) refuse2(SAID[token2.reason], g.fallback);
57262
+ if (!token2.ok) refuse2(SAID[token2.reason], g.fallback, {
57263
+ code: token2.reason.replace("-", "_"),
57264
+ message: "error" in token2 ? token2.error ?? "" : "",
57265
+ retryable: token2.reason === "unreachable"
57266
+ });
57065
57267
  const task = workspaceTask();
57066
57268
  let res;
57067
57269
  try {
57068
57270
  res = await fetch(`${cloudEndpoints().api}${g.endpoint}`, {
57069
57271
  method: "POST",
57070
- // The task this spends credits for, inside a Runner task (#629).
57071
57272
  headers: { authorization: `Bearer ${token2.token}`, "content-type": "application/json", ...task ? { "x-wildcrane-task": task } : {} },
57072
57273
  body: JSON.stringify(g.body)
57073
57274
  });
57074
57275
  } catch {
57075
- refuse2(SAID.unreachable, g.fallback);
57276
+ refuse2(SAID.unreachable, g.fallback, { code: "unreachable", message: "", retryable: true });
57076
57277
  }
57077
- if (!res.ok) {
57078
- const { error: error62 } = await res.json().catch(() => ({}));
57079
- if (res.status === 401) refuse2(SAID.expired, g.fallback);
57080
- if (error62?.code === "pro_required") refuse2(g.pro_required, g.fallback);
57081
- if (error62?.code === "credits_used_up") {
57082
- refuse2(res.headers.has("retry-after") ? SAID.credits_used_up : SAID.trial_credits_used_up, g.fallback);
57278
+ const contentType = res.headers.get("content-type") ?? "";
57279
+ const problem = !res.ok || /^application\/(?:[\w.+-]+\+)?json(?:;|$)/i.test(contentType) ? cloudProblem(res, await readCloudJson(res)) ?? invalidResponse("a complete media file") : null;
57280
+ if (problem) {
57281
+ if (res.status === 401) refuse2(SAID.expired, g.fallback, problem);
57282
+ if (problem.code === "pro_required") refuse2(g.pro_required, g.fallback, problem);
57283
+ if (problem.code === "credits_used_up") {
57284
+ refuse2(res.headers.has("retry-after") ? SAID.credits_used_up : SAID.trial_credits_used_up, g.fallback, problem);
57285
+ }
57286
+ if (res.status === 400) {
57287
+ throw cloudError({ ...problem, message: `${problem.message}
57288
+ usage: ${g.usage}` }, { bare: true, exitCode: 2 });
57083
57289
  }
57084
- if (res.status === 400) usage(error62?.message ?? "The request was refused.", g.usage);
57085
- refuse2(g.failed, g.fallback);
57290
+ refuse2(g.failed, g.fallback, problem);
57291
+ }
57292
+ let bytes2;
57293
+ try {
57294
+ bytes2 = await cloudBytes(res, "a complete media file");
57295
+ if (!mediaMatches(contentType, bytes2, g.endpoint.endsWith("image"))) throw cloudError(invalidResponse("a complete media file"));
57296
+ } catch (error62) {
57297
+ if (!(error62 instanceof BoardError)) throw error62;
57298
+ refuse2(g.failed, g.fallback, { code: error62.kind, message: error62.message, retryable: true });
57086
57299
  }
57087
57300
  const out = g.outFor?.(res, g.out) ?? g.out;
57088
- fs68.mkdirSync(path71.dirname(path71.resolve(out)), { recursive: true });
57089
- fs68.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
57301
+ fs69.mkdirSync(path72.dirname(path72.resolve(out)), { recursive: true });
57302
+ fs69.writeFileSync(out, bytes2);
57090
57303
  say(`${out} (${g.label(res)})`);
57091
57304
  return { out };
57092
57305
  }
57306
+ function mediaMatches(contentType, bytes2, image) {
57307
+ const type = contentType.toLowerCase().split(";", 1)[0]?.trim();
57308
+ const starts = (signature, offset = 0) => bytes2.toString("ascii", offset, offset + signature.length) === signature;
57309
+ const riff = (format) => starts("RIFF") && starts(format, 8);
57310
+ if (image) {
57311
+ if (type === "image/png") return bytes2.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"));
57312
+ if (type === "image/jpeg") return bytes2[0] === 255 && bytes2[1] === 216 && bytes2[2] === 255;
57313
+ if (type === "image/webp") return riff("WEBP");
57314
+ return false;
57315
+ }
57316
+ if (type === "audio/wav") return riff("WAVE");
57317
+ return type === "audio/mpeg" && (starts("ID3") || bytes2.length > 2 && bytes2[0] === 255 && (bytes2[1] & 224) === 224);
57318
+ }
57093
57319
  var SAID, REF_TYPES, TIERS, SPEECH_TIERS;
57094
57320
  var init_cloud = __esm({
57095
57321
  "../cli/src/commands/cloud.ts"() {
@@ -57100,6 +57326,7 @@ var init_cloud = __esm({
57100
57326
  init_tasks();
57101
57327
  init_paths();
57102
57328
  init_io();
57329
+ init_response();
57103
57330
  SAID = {
57104
57331
  "signed-out": {
57105
57332
  zh: "\u672A\u767B\u5F55 WildCrane Cloud\u3002\u8BF7\u5728 WildCrane \u5E94\u7528\u7684\u201C\u914D\u7F6E \u2192 Cloud\u201D\u4E2D\u767B\u5F55\u540E\u91CD\u8BD5\u3002",
@@ -57134,13 +57361,17 @@ var init_cloud = __esm({
57134
57361
  });
57135
57362
 
57136
57363
  // ../cli/src/commands/task.ts
57137
- import fs69 from "node:fs";
57364
+ import fs70 from "node:fs";
57138
57365
  import os5 from "node:os";
57139
- import path72 from "node:path";
57366
+ import path73 from "node:path";
57140
57367
  async function cloud(method, route2, body, signal2) {
57141
- process.env.AI4KANBAN_HOME ??= process.env.WILDCRANE_HOME || path72.join(os5.homedir(), ".wildcrane");
57368
+ process.env.AI4KANBAN_HOME ??= process.env.WILDCRANE_HOME || path73.join(os5.homedir(), ".wildcrane");
57142
57369
  const token2 = await accessToken();
57143
- if (!token2.ok) return refuse3(SAID[token2.reason].en, token2.reason.replace("-", "_"));
57370
+ if (!token2.ok) throw cloudError({
57371
+ code: token2.reason.replace("-", "_"),
57372
+ message: ("error" in token2 ? token2.error : void 0) ?? SAID[token2.reason].en,
57373
+ retryable: token2.reason === "unreachable"
57374
+ });
57144
57375
  let response;
57145
57376
  const request2 = new AbortController();
57146
57377
  const abort = () => request2.abort();
@@ -57156,11 +57387,12 @@ async function cloud(method, route2, body, signal2) {
57156
57387
  signal: request2.signal
57157
57388
  });
57158
57389
  } catch {
57159
- refuse3(SAID.unreachable.en, "unreachable");
57390
+ throw cloudError({ code: "unreachable", message: SAID.unreachable.en, retryable: true });
57160
57391
  }
57161
- const value = await response.json().catch(() => ({}));
57162
- if (response.status === 401) refuse3(SAID.expired.en, "expired");
57163
- if (!response.ok) refuse3(value.error?.message ?? `Cloud answered ${response.status}.`, value.error?.code ?? "refused");
57392
+ const value = await readCloudJson(response);
57393
+ const problem = cloudProblem(response, value);
57394
+ if (problem) throw cloudError(problem);
57395
+ if (!isRecord(value)) throw cloudError(invalidResponse("a valid JSON response"));
57164
57396
  return value;
57165
57397
  } finally {
57166
57398
  clearTimeout(timeout);
@@ -57169,11 +57401,14 @@ async function cloud(method, route2, body, signal2) {
57169
57401
  }
57170
57402
  async function all(route2) {
57171
57403
  const rows = [];
57404
+ const cursors = /* @__PURE__ */ new Set();
57172
57405
  let after2 = null;
57173
57406
  do {
57174
57407
  const page = await cloud("GET", `${route2}${route2.includes("?") ? "&" : "?"}limit=100${after2 ? `&after=${enc(after2)}` : ""}`);
57408
+ requireResponse(page, "a valid results page", (value) => Array.isArray(value.data) && (value.next === null || hasText(value.next) && !cursors.has(value.next)));
57175
57409
  rows.push(...page.data);
57176
57410
  after2 = page.next;
57411
+ if (after2) cursors.add(after2);
57177
57412
  } while (after2);
57178
57413
  return rows;
57179
57414
  }
@@ -57181,15 +57416,15 @@ function linked(location) {
57181
57416
  const cwd = location.cwd ?? process.cwd();
57182
57417
  const board2 = location.board ?? (process.env.AI4KANBAN_BOARD?.trim() || null);
57183
57418
  if (board2) {
57184
- const link2 = linkedProject("", projectRootOf(path72.resolve(cwd, board2)));
57419
+ const link2 = linkedProject("", projectRootOf(path73.resolve(cwd, board2)));
57185
57420
  return link2.ok ? link2.value : null;
57186
57421
  }
57187
- for (let dir = path72.resolve(cwd, location.dir ?? "."); ; dir = path72.dirname(dir)) {
57188
- if (fs69.existsSync(path72.join(dir, ".akb", "base.json"))) {
57422
+ for (let dir = path73.resolve(cwd, location.dir ?? "."); ; dir = path73.dirname(dir)) {
57423
+ if (fs70.existsSync(path73.join(dir, ".akb", "base.json"))) {
57189
57424
  const link2 = linkedProject("", dir);
57190
57425
  return link2.ok ? link2.value : null;
57191
57426
  }
57192
- if (path72.dirname(dir) === dir) return null;
57427
+ if (path73.dirname(dir) === dir) return null;
57193
57428
  }
57194
57429
  }
57195
57430
  async function project(asked, location) {
@@ -57219,12 +57454,33 @@ async function taskList(opts, location = {}) {
57219
57454
  }
57220
57455
  async function taskShow(id2, location = {}) {
57221
57456
  const task = await cloud("GET", `/v1/tasks/${enc(await taskRef(id2, location))}`);
57222
- const card = task.studio ? await cloud("GET", `/v1/tasks/${enc(task.id)}/card`).catch(() => null) : null;
57457
+ requireTask(task);
57458
+ if (task.studio != null && (!isRecord(task.studio) || !hasText(task.studio.name))) {
57459
+ throw cloudError(invalidResponse("the task\u2019s Studio"));
57460
+ }
57461
+ let card = null;
57462
+ if (task.studio) {
57463
+ try {
57464
+ card = requireResponse(
57465
+ await cloud("GET", `/v1/tasks/${enc(task.id)}/card`),
57466
+ "the card body",
57467
+ (value) => hasText(value.body)
57468
+ );
57469
+ } catch (error62) {
57470
+ if (!(error62 instanceof BoardError) || error62.details.code !== "not_found" || (task.card_version ?? 0) > 0) throw error62;
57471
+ }
57472
+ }
57473
+ const board2 = linkedBoard(location);
57474
+ const removal = board2 && /^task_[\w-]+$/.test(task.id) ? readRemoval(board2, task.id) : null;
57475
+ const archive = board2 ? archiveReceipt(board2, task.id) : null;
57476
+ const sync = removal && (removal.status !== "confirmed" || task.status === "cancelled") ? { kind: "remove", ...operationStatus(removal) } : archive && archive.status === "confirmed" === (task.status === "done") ? { kind: "archive", ...operationStatus(archive) } : null;
57223
57477
  say(`${task.key} ${task.title}`);
57224
57478
  say(`${task.status}${task.studio ? ` ${task.studio.name}` : ""} ${taskUrl(task.key)}`);
57225
- if (card?.body) say(`
57479
+ if (card) say(`
57226
57480
  ${card.body.trim()}`);
57227
- return { ...task, card };
57481
+ else if (task.studio) say("The card has not been generated yet.");
57482
+ if (sync) say(`${sync.kind === "remove" ? "Removal" : "Archive"}: ${sync.status}${"code" in sync && sync.code ? ` [${sync.code}] ${sync.message ?? ""}` : ""}.`);
57483
+ return { ...task, card, card_read_status: card ? "available" : task.studio ? "not_generated" : "no_studio", ...sync ? { sync } : {} };
57228
57484
  }
57229
57485
  async function taskCreate(request2, opts, location = {}) {
57230
57486
  const text5 = request2.trim();
@@ -57245,10 +57501,13 @@ async function taskCreate(request2, opts, location = {}) {
57245
57501
  say(`Status: ${task.status}${task.failure ? ` \u2014 ${task.failure}` : ""}`);
57246
57502
  return { ...task };
57247
57503
  }
57248
- async function act(id2, route2, body, done, location = {}) {
57504
+ function requireTask(task) {
57505
+ return requireResponse(task, "a task receipt", (value) => hasText(value.id) && hasText(value.key) && hasText(value.status));
57506
+ }
57507
+ async function act(id2, route2, body, done, location) {
57249
57508
  const ref = await taskRef(id2, location);
57250
57509
  const value = await cloud("POST", `/v1/tasks/${enc(ref)}/${route2}`, body);
57251
- say(done(ref));
57510
+ say(done(ref, value));
57252
57511
  return value;
57253
57512
  }
57254
57513
  function reviewRevision(value) {
@@ -57268,7 +57527,7 @@ async function taskReview(id2, opts = {}, location = {}) {
57268
57527
  if (opts.review !== void 0) {
57269
57528
  fields2 = { operation: "plan", review_flow: opts.review };
57270
57529
  } else if (opts.file !== void 0) {
57271
- fields2 = { operation: "plan", review_plan: parseReviewPlan(JSON.parse(fs69.readFileSync(opts.file, "utf8"))) };
57530
+ fields2 = { operation: "plan", review_plan: parseReviewPlan(JSON.parse(fs70.readFileSync(opts.file, "utf8"))) };
57272
57531
  } else if (opts.reviseFrom !== void 0) {
57273
57532
  fields2 = { operation: "revise", stage: opts.reviseFrom };
57274
57533
  } else if (opts.previewDefinitionsFile !== void 0) {
@@ -57277,7 +57536,7 @@ async function taskReview(id2, opts = {}, location = {}) {
57277
57536
  if (!opts.stage || !["running", "done"].includes(opts.status)) die("--stage and --status running|done are required.");
57278
57537
  fields2 = { operation: "status", stage: opts.stage, status: opts.status };
57279
57538
  }
57280
- if (opts.previewDefinitionsFile !== void 0) fields2.preview_definitions = previewDefinitionsSchema.parse(JSON.parse(fs69.readFileSync(opts.previewDefinitionsFile, "utf8")));
57539
+ if (opts.previewDefinitionsFile !== void 0) fields2.preview_definitions = previewDefinitionsSchema.parse(JSON.parse(fs70.readFileSync(opts.previewDefinitionsFile, "utf8")));
57281
57540
  task = await cloud("POST", `/v1/tasks/${enc(ref)}/review`, { ...fields2, review_revision });
57282
57541
  }
57283
57542
  say(JSON.stringify(task.review, null, 2));
@@ -57294,17 +57553,50 @@ async function taskApprove(id2, comment, opts = {}, location = {}) {
57294
57553
  review_revision,
57295
57554
  ...opts.stage ? { stage: opts.stage } : {},
57296
57555
  ...comment?.trim() ? { comment: comment.trim() } : {}
57297
- }, (k) => `Approved ${k}.`, location);
57556
+ }, (key, value) => {
57557
+ requireResponse(value, "an approval receipt", (receipt) => hasText(receipt.id) && receipt.decision === "approve");
57558
+ return `Approved ${key}.`;
57559
+ }, location);
57298
57560
  }
57299
57561
  async function taskUpdateQuestions(id2, typed, location = {}) {
57300
57562
  const ops = readQuestionOps(typed);
57563
+ const current = executionOf() ? workspaceTask() : null;
57301
57564
  const ref = await taskRef(id2, location);
57302
- const card = await cloud("GET", `/v1/tasks/${enc(ref)}/card`);
57303
- const questions = parseFrontmatter(card.body).meta?.questions ?? [];
57565
+ const selected = current && !ref.startsWith("task_") ? requireTask(await cloud("GET", `/v1/tasks/${enc(ref)}`)) : null;
57566
+ const target = selected?.id ?? ref;
57567
+ if (current && target === current) {
57568
+ const board2 = runnerTaskBoard(location);
57569
+ const unavailable = () => refuse3("Cannot find the current task\u2019s local card on its Runner board.", "local_card_unavailable");
57570
+ if (!board2) return unavailable();
57571
+ return withSyncLock(board2, async () => {
57572
+ const project2 = runnerProject(board2);
57573
+ const mapped = localTaskRecord(board2, current);
57574
+ if (!mapped || !project2 || selected && (selected.project !== project2 || numberOf(selected.key) !== mapped.number)) {
57575
+ return unavailable();
57576
+ }
57577
+ const root2 = projectRootOf(board2);
57578
+ useBoard({ board: board2, root: root2, named: true }, false, true);
57579
+ return withBoardLock(() => {
57580
+ const run3 = insideRun();
57581
+ const runCard = run3 ? peekRun(run3)?.cardId : null;
57582
+ if (runCard != null && runCard !== mapped.number || !fs70.existsSync(path73.join(board2, "todo")) || !locate(mapped.number)) {
57583
+ return unavailable();
57584
+ }
57585
+ return updateCardQuestions(mapped.number, ops);
57586
+ });
57587
+ });
57588
+ }
57589
+ const card = requireResponse(
57590
+ await cloud("GET", `/v1/tasks/${enc(target)}/card`),
57591
+ "the card body and version",
57592
+ (value) => hasText(value.body) && Number.isSafeInteger(value.version) && value.version >= 0
57593
+ );
57594
+ const meta3 = parseFrontmatter(card.body).meta;
57595
+ if (!meta3) return refuse3("The card has no frontmatter.", "bad_request");
57304
57596
  let changes;
57305
57597
  let open4;
57306
57598
  try {
57307
- const done = applyQuestionOps(questions, ops);
57599
+ const done = applyQuestionOps(meta3.questions, ops);
57308
57600
  changes = done.changes;
57309
57601
  open4 = done.questions.length;
57310
57602
  } catch (e) {
@@ -57316,22 +57608,27 @@ async function taskUpdateQuestions(id2, typed, location = {}) {
57316
57608
  if (op.kind === "append") return { append: q };
57317
57609
  if (op.kind === "update") return { update: op.n, question: q };
57318
57610
  if (op.kind === "drop") return { drop: questionPositions(op.ns, Infinity, "drop") };
57319
- if (op.kind === "clear") return { clear: true };
57320
- return die(`akb task update-questions has no --${op.kind}; --drop removes a question`);
57611
+ return { clear: true };
57321
57612
  });
57322
- const task = await cloud("PATCH", `/v1/tasks/${enc(ref)}/questions`, { base_version: card.version, ops: body });
57613
+ const task = await cloud("PATCH", `/v1/tasks/${enc(target)}/questions`, { base_version: card.version, ops: body });
57323
57614
  say(`updated ${task.key} questions: ${changes.join(", ")} (${open4} open)`);
57324
57615
  return { ...task, changes, open: open4 };
57325
57616
  }
57326
- function localTaskTarget(location) {
57327
- const task = workspaceTask();
57617
+ function runnerTaskBoard(location) {
57328
57618
  const runnerBoard = process.env.AI4KANBAN_BOARD?.trim();
57329
- if (!task || !/^task_[\w-]+$/.test(task) || !runnerBoard || !executionOf()) return null;
57619
+ if (!runnerBoard) return null;
57330
57620
  const cwd = location.cwd ?? process.cwd();
57331
- const board2 = path72.resolve(cwd, location.board ?? runnerBoard);
57332
57621
  try {
57333
- if (fs69.realpathSync(board2) !== fs69.realpathSync(path72.resolve(cwd, runnerBoard)) || !runnerProject(board2)) return null;
57334
- const record2 = JSON.parse(fs69.readFileSync(path72.join(board2, ".sync", task + ".json"), "utf8"));
57622
+ const board2 = path73.resolve(cwd, location.board ?? runnerBoard);
57623
+ return fs70.realpathSync(board2) === fs70.realpathSync(path73.resolve(cwd, runnerBoard)) && runnerProject(board2) ? board2 : null;
57624
+ } catch {
57625
+ return null;
57626
+ }
57627
+ }
57628
+ function localTaskRecord(board2, task) {
57629
+ if (!/^task_[\w-]+$/.test(task)) return null;
57630
+ try {
57631
+ const record2 = JSON.parse(fs70.readFileSync(path73.join(board2, ".sync", task + ".json"), "utf8"));
57335
57632
  if (record2.task === task && Number.isSafeInteger(record2.number) && record2.number > 0 && !record2.deleted) {
57336
57633
  return { board: board2, task, number: record2.number };
57337
57634
  }
@@ -57339,16 +57636,51 @@ function localTaskTarget(location) {
57339
57636
  }
57340
57637
  return null;
57341
57638
  }
57342
- async function confirmedLocalArchive(local, file2, known2) {
57639
+ function localTaskTarget(location) {
57640
+ const task = workspaceTask();
57641
+ if (!task || !executionOf()) return null;
57642
+ const board2 = runnerTaskBoard(location);
57643
+ return board2 ? localTaskRecord(board2, task) : null;
57644
+ }
57645
+ function linkedBoard(location) {
57646
+ const cwd = location.cwd ?? process.cwd();
57647
+ const named2 = location.board ?? process.env.AI4KANBAN_BOARD;
57648
+ if (named2) {
57649
+ const board2 = path73.resolve(cwd, named2);
57650
+ return runnerProject(board2) ? board2 : null;
57651
+ }
57652
+ for (let dir = path73.resolve(cwd, location.dir ?? "."); ; dir = path73.dirname(dir)) {
57653
+ const board2 = path73.join(dir, ".akb", "kanban");
57654
+ if (runnerProject(board2)) return board2;
57655
+ if (path73.dirname(dir) === dir) return null;
57656
+ }
57657
+ }
57658
+ function operationStatus(result) {
57659
+ if (result.status === "confirmed") return { status: result.status };
57660
+ return { status: result.status, code: result.code, message: result.message };
57661
+ }
57662
+ function archiveReceipt(board2, task, file2) {
57343
57663
  try {
57344
- const base = JSON.parse(fs69.readFileSync(path72.join(local.board, "..", "base.json"), "utf8"));
57345
- const project2 = runnerProject(local.board);
57346
- const synced = base.files?.[`projects/${project2}/${file2}`];
57347
- if (!synced || synced.content !== fs69.readFileSync(path72.join(local.board, file2), "utf8")) return false;
57348
- const task = known2 ?? await cloud("GET", `/v1/tasks/${enc(local.task)}`);
57349
- return task.status === "done" && task.card_version === synced.seq;
57664
+ const base = JSON.parse(fs70.readFileSync(path73.join(board2, "..", "base.json"), "utf8"));
57665
+ const receipt = base.archiveReceipts?.[task];
57666
+ const root2 = `projects/${runnerProject(board2)}/`;
57667
+ const synced = receipt && base.files?.[root2 + receipt.path];
57668
+ const manifest = assetsFile(task);
57669
+ const assets = base.files?.[root2 + manifest];
57670
+ if (synced && (!file2 || receipt.path === file2) && synced.seq === receipt.seq && (assets?.seq ?? 0) === receipt.assets_seq) {
57671
+ const local = (name) => {
57672
+ try {
57673
+ return fs70.readFileSync(path73.join(board2, name), "utf8");
57674
+ } catch {
57675
+ return null;
57676
+ }
57677
+ };
57678
+ if (synced.content === local(receipt.path) && (assets?.content ?? null) === local(manifest)) return operationStatus(receipt);
57679
+ if (file2) return { status: "pending" };
57680
+ }
57681
+ return base.pendingArchives?.[task] ? { status: "pending" } : null;
57350
57682
  } catch {
57351
- return false;
57683
+ return null;
57352
57684
  }
57353
57685
  }
57354
57686
  async function taskArchive(asked, location = {}) {
@@ -57362,25 +57694,34 @@ async function taskArchive(asked, location = {}) {
57362
57694
  if (locate(local.number)) return { receipt: cmdRemove(local.number, "completed", { archivingTask: true }) };
57363
57695
  const existing = locateArchived(local.number);
57364
57696
  if (!existing) return null;
57365
- const file2 = existing.kind === "group" ? path72.join(existing.target, "root.md") : existing.target;
57366
- const { meta: meta3 } = parseFrontmatter(fs69.readFileSync(file2, "utf8"));
57697
+ const file2 = existing.kind === "group" ? path73.join(existing.target, "root.md") : existing.target;
57698
+ const { meta: meta3 } = parseFrontmatter(fs70.readFileSync(file2, "utf8"));
57367
57699
  if (!meta3?.archived || meta3.rejected) return refuse3("This task is not eligible for archive.", "conflict");
57368
57700
  return {
57369
- receipt: { archived_to: path72.relative(local.board, existing.target) },
57370
- existing: path72.relative(local.board, file2)
57701
+ receipt: { archived_to: path73.relative(local.board, existing.target) },
57702
+ existing: path73.relative(local.board, file2)
57371
57703
  };
57372
57704
  }));
57373
57705
  });
57374
57706
  if (archive) {
57375
- if (archive.existing && await confirmedLocalArchive(local, archive.existing, keyMatch)) {
57707
+ const receipt = archive.existing && archiveReceipt(local.board, local.task, archive.existing);
57708
+ if (receipt && receipt.status === "confirmed") {
57376
57709
  say("Archive confirmed by Cloud.");
57377
57710
  return { task: local.task, archive_status: "archived" };
57378
57711
  }
57379
- say("Archived locally. Waiting for Runner synchronization.");
57380
- return { ...archive.receipt, task: local.task, archive_status: "pending_sync" };
57712
+ if (receipt && receipt.status === "rejected") {
57713
+ if (receipt.code === "version_conflict" || receipt.code === "not_found") {
57714
+ return refuse3(receipt.message ?? "Cloud rejected the archive.", receipt.code);
57715
+ }
57716
+ } else {
57717
+ const pending = receipt && receipt.status === "pending" && receipt.code ? receipt : null;
57718
+ say(`Archived locally. Waiting for Runner synchronization.${pending ? ` [${pending.code}] ${pending.message}` : ""}`);
57719
+ return { ...archive.receipt, task: local.task, archive_status: "pending_sync", ...pending ? { sync: pending } : {} };
57720
+ }
57381
57721
  }
57382
57722
  }
57383
- const result = await cloud("POST", `/v1/tasks/${enc(keyMatch ? keyMatch.id : await taskRef(ref, location))}/archive`);
57723
+ const result = await cloud("POST", `/v1/tasks/${enc(keyMatch?.id ?? (local && /^\d+$/.test(ref) && Number(ref) === local.number ? local.task : await taskRef(ref, location)))}/archive`);
57724
+ requireResponse(requireTask(result), "confirmation that the task was archived", (task) => task.status === "done");
57384
57725
  say(`Archived ${result.key}.`);
57385
57726
  return { task: result.id, archive_status: "archived" };
57386
57727
  }
@@ -57394,10 +57735,21 @@ async function taskRemove(asked, reason, location = {}, discard = false) {
57394
57735
  const keyMatch = local && /^[a-z][a-z0-9]{0,9}-[1-9]\d{0,8}$/i.test(ref) && ref.endsWith(`-${local.number}`) ? await cloud("GET", `/v1/tasks/${enc(ref)}`) : null;
57395
57736
  if (local && (ref === local.task || numeric && Number(ref) === local.number || keyMatch?.id === local.task)) {
57396
57737
  return withSyncLock(local.board, async () => {
57397
- useBoard({ board: local.board, root: projectRootOf(local.board), named: true }, false);
57398
- const result = withCreationLock(() => withBoardLock(() => cmdRemove(local.number, "rejected", { reason: text5, discard })));
57399
- say(`Removed #${local.number} locally. Pending Runner sync.`);
57400
- return { board: local.board, ...result };
57738
+ const held4 = readRemoval(local.board, local.task);
57739
+ if (held4?.status === "confirmed") {
57740
+ const current = requireTask(keyMatch ?? await cloud("GET", `/v1/tasks/${enc(local.task)}`));
57741
+ if (current.status === "cancelled") {
57742
+ say("Removal confirmed by Cloud.");
57743
+ return { task: local.task, remove_status: "removed" };
57744
+ }
57745
+ } else if (held4?.status === "rejected") {
57746
+ const current = requireTask(keyMatch ?? await cloud("GET", `/v1/tasks/${enc(local.task)}`));
57747
+ if (current.status === "done" || current.status === "cancelled") return refuse3(held4.message ?? "Cloud rejected the removal.", held4.code ?? "conflict");
57748
+ }
57749
+ if (held4?.status !== "pending") writeRemoval(local.board, local.task, { status: "pending", reason: text5, discard: true });
57750
+ const pending = held4?.status === "pending" && held4.code ? operationStatus(held4) : null;
57751
+ say(`Removal queued for Runner synchronization.${pending && pending.status !== "confirmed" ? ` [${pending.code}] ${pending.message}` : ""}`);
57752
+ return { task: local.task, board: local.board, remove_status: "pending_sync", ...pending ? { sync: pending } : {} };
57401
57753
  });
57402
57754
  }
57403
57755
  if (!workspaceTask() && run3 && numeric) {
@@ -57420,15 +57772,35 @@ async function taskRemove(asked, reason, location = {}, discard = false) {
57420
57772
  keyMatch?.id ?? ref,
57421
57773
  "cancel",
57422
57774
  Object.keys(body).length ? body : void 0,
57423
- (key) => `Removed ${keyMatch ? ref : key} in Cloud. Restore it with akb task restore ${keyMatch ? ref : key}.`,
57775
+ (key, value) => {
57776
+ requireResponse(value, "confirmation that the task was removed", (task) => hasText(task.id) && task.status === "cancelled");
57777
+ return `Removed ${keyMatch ? ref : key} in Cloud. Restore it with akb task restore ${keyMatch ? ref : key}.`;
57778
+ },
57424
57779
  location
57425
57780
  );
57426
57781
  }
57427
57782
  async function taskRestore(id2, location = {}) {
57428
57783
  const task = await cloud("POST", `/v1/tasks/${enc(await taskRef(id2, location))}/restore`);
57784
+ requireResponse(requireTask(task), "confirmation that the task was restored", (value) => ["stopped", "waiting_review", "failed"].includes(value.status));
57429
57785
  say(`Restored ${task.key}. Status: ${task.status}.`);
57430
57786
  return { ...task };
57431
57787
  }
57788
+ async function taskResume(id2, location = {}) {
57789
+ const task = requireTask(await cloud("POST", `/v1/tasks/${enc(await taskRef(id2, location))}/resume`));
57790
+ if (!["queued", "running"].includes(task.status)) {
57791
+ const reason = task.failure || (task.status === "waiting_review" ? "The task is waiting for review." : ["done", "cancelled"].includes(task.status) ? "This task has finished." : `The task is ${task.status}.`);
57792
+ return refuse3(reason, task.status === "failed" ? "execution_failed" : "conflict");
57793
+ }
57794
+ say(task.status === "queued" ? `Resume queued for ${task.key}.` : `Resumed ${task.key}.`);
57795
+ return { ...task };
57796
+ }
57797
+ async function taskStop(id2, location = {}) {
57798
+ const task = requireTask(await cloud("POST", `/v1/tasks/${enc(await taskRef(id2, location))}/stop`));
57799
+ requireResponse(task, "a stop receipt", (value) => ["running", "queued", "waiting_review", "stopped"].includes(value.status));
57800
+ const stop_status = task.status === "stopped" ? "stopped" : "requested";
57801
+ say(stop_status === "stopped" ? `Stopped ${task.key}.` : `Stop requested for ${task.key}.`);
57802
+ return { ...task, stop_status };
57803
+ }
57432
57804
  async function workspaceList() {
57433
57805
  const data = await all("/v1/workspaces");
57434
57806
  for (const w of data) say(`${w.id} ${w.name}`);
@@ -57444,7 +57816,7 @@ async function runnerList(opts, location = {}) {
57444
57816
  for (const r of held4.runners) say(`${r.name} ${r.connected ? "online" : "offline"}`);
57445
57817
  return held4;
57446
57818
  }
57447
- var refuse3, enc, WEB, taskUrl, projectLine, taskChat, taskResume, taskStop, taskComment;
57819
+ var refuse3, enc, WEB, taskUrl, projectLine, taskChat, taskComment;
57448
57820
  var init_task = __esm({
57449
57821
  "../cli/src/commands/task.ts"() {
57450
57822
  "use strict";
@@ -57462,23 +57834,36 @@ var init_task = __esm({
57462
57834
  init_sessions();
57463
57835
  init_creation_lock();
57464
57836
  init_lock();
57837
+ init_task_operation();
57838
+ init_board_files();
57465
57839
  init_board_conflicts();
57466
57840
  init_remove();
57841
+ init_card();
57467
57842
  init_io();
57843
+ init_response();
57468
57844
  init_paths();
57469
57845
  init_frontmatter();
57470
57846
  init_questions();
57471
57847
  init_question_ops();
57472
57848
  init_cloud();
57473
- refuse3 = (message, code) => die(message, { kind: code, code });
57849
+ refuse3 = (message, code) => {
57850
+ throw cloudError({ code, message, retryable: false });
57851
+ };
57474
57852
  enc = encodeURIComponent;
57475
57853
  WEB = () => process.env.WILDCRANE_WEB_URL || "https://app.wildcrane.ai";
57476
57854
  taskUrl = (key) => `${WEB()}/tasks/${enc(key)}`;
57477
57855
  projectLine = (p) => `${p.id} ${p.prefix} ${p.name}`;
57478
- taskChat = (id2, message, location = {}) => act(id2, "chat", { body: message }, (k) => `Sent to ${k}.`, location);
57479
- taskResume = (id2, location = {}) => act(id2, "resume", void 0, (k) => `Resumed ${k}.`, location);
57480
- taskStop = (id2, location = {}) => act(id2, "stop", void 0, (k) => `Stopped ${k}.`, location);
57481
- taskComment = (id2, text5, location = {}) => act(id2, "comments", { body: text5 }, (k) => `Commented on ${k}.`, location);
57856
+ taskChat = (id2, message, location = {}) => act(id2, "chat", { body: message }, (key, chat) => {
57857
+ requireResponse(chat, "a chat message receipt", (value) => Array.isArray(value.messages) && value.messages.some((msg) => isRecord(msg) && hasText(msg.id) && msg.role === "user" && msg.body === message.trim()));
57858
+ if (hasText(chat.failure) || ["failed", "conflict", "runner_offline", "stopped"].includes(String(chat.status))) {
57859
+ return refuse3(hasText(chat.failure) ? chat.failure : `Chat reply: ${chat.status}.`, "reply_failed");
57860
+ }
57861
+ return ["queued", "replying"].includes(String(chat.status)) ? `Sent to ${key}. Reply pending.` : `Sent to ${key}.`;
57862
+ }, location);
57863
+ taskComment = (id2, text5, location = {}) => act(id2, "comments", { body: text5 }, (key, value) => {
57864
+ requireResponse(value, "a comment receipt", (receipt) => hasText(receipt.id) && receipt.body === text5.trim());
57865
+ return `Commented on ${key}.`;
57866
+ }, location);
57482
57867
  }
57483
57868
  });
57484
57869
 
@@ -57496,10 +57881,10 @@ function decodeGoals({ goals, ideas, ...rest }) {
57496
57881
  if (goals !== void 0 && ideas !== void 0 && JSON.stringify(goals) !== JSON.stringify(ideas)) {
57497
57882
  throw new Error("goals and ideas do not match.");
57498
57883
  }
57499
- const entries = goals ?? ideas;
57500
- if (!Array.isArray(entries)) throw new Error("The goals array is missing or invalid.");
57884
+ const entries2 = goals ?? ideas;
57885
+ if (!Array.isArray(entries2)) throw new Error("The goals array is missing or invalid.");
57501
57886
  const field2 = goals === void 0 ? "ideas" : "goals";
57502
- return { field: field2, value: { ...rest, goals: entries.map(readGoal) } };
57887
+ return { field: field2, value: { ...rest, goals: entries2.map(readGoal) } };
57503
57888
  }
57504
57889
  function goalRoute(discussion2, goal, field2) {
57505
57890
  return `/v1/discussions/${encodeURIComponent(discussion2)}/${field2}/${encodeURIComponent(goal)}`;
@@ -57512,20 +57897,20 @@ var init_goal = __esm({
57512
57897
  });
57513
57898
 
57514
57899
  // ../cli/src/lib/goal-draft.ts
57515
- import fs70 from "node:fs";
57900
+ import fs71 from "node:fs";
57516
57901
  import { randomUUID as randomUUID7 } from "node:crypto";
57517
57902
  function readGoalDraft(file2) {
57518
- return decodeGoals(JSON.parse(fs70.readFileSync(file2, "utf8")));
57903
+ return decodeGoals(JSON.parse(fs71.readFileSync(file2, "utf8")));
57519
57904
  }
57520
57905
  function writeGoalDraft(file2, { goals, ...draft }, field2) {
57521
- const entries = field2 === "goals" ? goals : goals.map(({ task, ...goal }) => ({ ...goal, task: task?.key ? task : task?.id ?? null }));
57906
+ const entries2 = field2 === "goals" ? goals : goals.map(({ task, ...goal }) => ({ ...goal, task: task?.key ? task : task?.id ?? null }));
57522
57907
  const temporary = `${file2}.${randomUUID7()}.tmp`;
57523
57908
  try {
57524
- fs70.writeFileSync(temporary, `${JSON.stringify({ ...draft, [field2]: entries }, null, 2)}
57909
+ fs71.writeFileSync(temporary, `${JSON.stringify({ ...draft, [field2]: entries2 }, null, 2)}
57525
57910
  `, { mode: 384, flag: "wx" });
57526
- fs70.renameSync(temporary, file2);
57911
+ fs71.renameSync(temporary, file2);
57527
57912
  } finally {
57528
- fs70.rmSync(temporary, { force: true });
57913
+ fs71.rmSync(temporary, { force: true });
57529
57914
  }
57530
57915
  }
57531
57916
  var goalDraftPath;
@@ -57538,7 +57923,7 @@ var init_goal_draft = __esm({
57538
57923
  });
57539
57924
 
57540
57925
  // ../cli/src/commands/goal.ts
57541
- import fs71 from "node:fs";
57926
+ import fs72 from "node:fs";
57542
57927
  function loadGoals() {
57543
57928
  const file2 = goalDraftPath();
57544
57929
  if (!file2) die("Goals exist only inside a WildCrane goal discussion.");
@@ -57570,7 +57955,7 @@ function splitBody2(text5) {
57570
57955
  }
57571
57956
  function readBody(bodyFile) {
57572
57957
  if (!bodyFile) die("--body-file is required; write the goal in a writable temporary file first.");
57573
- const text5 = fs71.readFileSync(bodyFile, "utf8");
57958
+ const text5 = fs72.readFileSync(bodyFile, "utf8");
57574
57959
  if (!text5.trim()) die("The goal must not be empty.");
57575
57960
  return splitBody2(text5);
57576
57961
  }
@@ -57636,7 +58021,7 @@ function cmdGoalStudios(held4 = loadGoals().held) {
57636
58021
  return { studios: held4.studios.map((w) => ({ ...w, id: shortStudioId(w.id) })) };
57637
58022
  }
57638
58023
  function goalDefinitions(opts, previous = []) {
57639
- return opts.previewDefinitionsFile === void 0 ? previous : previewDefinitionsSchema.parse(JSON.parse(fs71.readFileSync(opts.previewDefinitionsFile, "utf8")));
58024
+ return opts.previewDefinitionsFile === void 0 ? previous : previewDefinitionsSchema.parse(JSON.parse(fs72.readFileSync(opts.previewDefinitionsFile, "utf8")));
57640
58025
  }
57641
58026
  function goalCatalog(held4, studio, definitions) {
57642
58027
  const builtIn = held4.studios.find((w) => w.id === studio)?.previews;
@@ -57649,7 +58034,7 @@ function goalReview(held4, studio, opts, previous, definitions) {
57649
58034
  if (opts.reviewFile !== void 0) die("Use either --review or --review-file.");
57650
58035
  return parseReviewFlow(opts.review, catalog);
57651
58036
  }
57652
- const value = opts.reviewFile === void 0 ? readReviewPlan(previous) : JSON.parse(fs71.readFileSync(opts.reviewFile, "utf8"));
58037
+ const value = opts.reviewFile === void 0 ? readReviewPlan(previous) : JSON.parse(fs72.readFileSync(opts.reviewFile, "utf8"));
57653
58038
  const saved = opts.reviewFile === void 0 && opts.previewDefinitionsFile === void 0 && opts.studio === void 0;
57654
58039
  return validateReviewPreviews(parseReviewPlan(value), catalog, { saved });
57655
58040
  }
@@ -57679,9 +58064,9 @@ var init_goal2 = __esm({
57679
58064
  });
57680
58065
 
57681
58066
  // ../cli/src/commands/goal-cloud.ts
57682
- import fs72 from "node:fs";
58067
+ import fs73 from "node:fs";
57683
58068
  import os6 from "node:os";
57684
- import path73 from "node:path";
58069
+ import path74 from "node:path";
57685
58070
  import crypto6 from "node:crypto";
57686
58071
  function hostSession() {
57687
58072
  const { CLAUDE_CODE_SESSION_ID: claude, CODEX_THREAD_ID: codex, CURSOR_CONVERSATION_ID: cursor, KIMI_SESSION_ID: kimi, WILDCRANE_DISCUSSION: discussion2 } = process.env;
@@ -57693,43 +58078,54 @@ function hostSession() {
57693
58078
  }
57694
58079
  async function studios2(workspace2) {
57695
58080
  const all2 = [];
58081
+ const cursors = /* @__PURE__ */ new Set();
57696
58082
  let after2 = null;
57697
58083
  do {
57698
58084
  const page = await request("GET", `/v1/studios?workspace=${encodeURIComponent(workspace2)}&limit=100${after2 ? `&after=${encodeURIComponent(after2)}` : ""}`);
58085
+ requireResponse(page, "a valid Studio list", (value) => Array.isArray(value.data) && value.data.every((studio) => hasText(studio?.id) && hasText(studio.name)) && (value.next === null || hasText(value.next) && !cursors.has(value.next)));
57699
58086
  all2.push(...page.data);
57700
58087
  after2 = page.next;
58088
+ if (after2) cursors.add(after2);
57701
58089
  } while (after2);
57702
58090
  return all2;
57703
58091
  }
57704
58092
  async function discussion() {
57705
58093
  const session = hostSession();
57706
58094
  if (!session) die("Goals exist only inside a WildCrane goal discussion.");
57707
- const home3 = process.env.WILDCRANE_HOME || path73.join(os6.homedir(), ".wildcrane");
58095
+ const home3 = process.env.WILDCRANE_HOME || path74.join(os6.homedir(), ".wildcrane");
57708
58096
  process.env.AI4KANBAN_HOME ??= home3;
57709
58097
  if (session.host === "discussion") return request("GET", `/v1/discussions/${encodeURIComponent(session.id)}`);
57710
- const machineFile2 = path73.join(home3, "machine.json");
58098
+ const machineFile2 = path74.join(home3, "machine.json");
57711
58099
  let machine;
57712
58100
  try {
57713
- machine = JSON.parse(fs72.readFileSync(machineFile2, "utf8")).id;
58101
+ machine = JSON.parse(fs73.readFileSync(machineFile2, "utf8")).id;
57714
58102
  } catch {
57715
58103
  machine = crypto6.randomUUID();
57716
- fs72.mkdirSync(home3, { recursive: true });
57717
- fs72.writeFileSync(machineFile2, JSON.stringify({ id: machine }));
58104
+ fs73.mkdirSync(home3, { recursive: true });
58105
+ fs73.writeFileSync(machineFile2, JSON.stringify({ id: machine }));
57718
58106
  }
57719
58107
  const held4 = await request("GET", `/v1/runner/folders?machine=${encodeURIComponent(machine)}`);
57720
- const cwd = fs72.realpathSync(process.cwd());
58108
+ const cwd = fs73.realpathSync(process.cwd());
57721
58109
  const folder2 = held4.folders.filter((f) => {
57722
58110
  try {
57723
- const dir = fs72.realpathSync(f.path);
57724
- return cwd === dir || cwd.startsWith(dir + path73.sep);
58111
+ const dir = fs73.realpathSync(f.path);
58112
+ return cwd === dir || cwd.startsWith(dir + path74.sep);
57725
58113
  } catch {
57726
58114
  return false;
57727
58115
  }
57728
58116
  }).sort((a, b) => b.path.length - a.path.length)[0];
57729
58117
  return request("POST", "/v1/discussions/external", { requestId: session.id, host: session.host, ...folder2 ? { project: folder2.project } : {} });
57730
58118
  }
58119
+ function discussionReceipt(value) {
58120
+ try {
58121
+ const decoded = decodeGoals(value);
58122
+ if (hasText(decoded.value.id) && hasText(decoded.value.workspace) && Number.isSafeInteger(decoded.value.version)) return decoded;
58123
+ } catch {
58124
+ }
58125
+ throw cloudError(invalidResponse("a valid discussion draft"));
58126
+ }
57731
58127
  async function withGoalDiscussion(action, save3 = false) {
57732
- const { field: field2, value: d } = decodeGoals(await discussion());
58128
+ const { field: field2, value: d } = discussionReceipt(await discussion());
57733
58129
  const held4 = { workspace: d.workspace, studios: await studios2(d.workspace), goals: d.goals.map((goal) => ({ ...goal })) };
57734
58130
  const result = action(held4);
57735
58131
  if (save3) {
@@ -57738,15 +58134,21 @@ async function withGoalDiscussion(action, save3 = false) {
57738
58134
  expectedVersion: d.version,
57739
58135
  [field2]: goals
57740
58136
  });
57741
- const { field: savedField, value: latest } = decodeGoals(saved);
58137
+ const { field: savedField, value: latest } = discussionReceipt(saved);
57742
58138
  const existing = new Set(d.goals.map((g) => g.id));
57743
58139
  const fresh = goals.filter((g) => !existing.has(g.id));
57744
58140
  const made = latest.goals.filter((g) => !existing.has(g.id));
57745
58141
  const actualId = (id2) => made[fresh.findIndex((g) => g.id === id2)]?.id ?? id2;
57746
58142
  if (typeof result.id === "string") result.id = actualId(result.id);
57747
- for (const goal of goals.filter((g) => g.start && !g.task)) {
57748
- const actual = latest.goals.find((g) => g.id === actualId(goal.id));
57749
- if (actual) await request("POST", `${goalRoute(d.id, actual.id, savedField)}/start`, { expectedVersion: latest.version });
58143
+ if (result.start) {
58144
+ const actual = latest.goals.find((g) => g.id === result.id);
58145
+ if (!actual) throw cloudError(invalidResponse("the saved goal"));
58146
+ const task = actual.task ?? requireResponse(await request(
58147
+ "POST",
58148
+ `${goalRoute(d.id, actual.id, savedField)}/start`,
58149
+ { expectedVersion: latest.version }
58150
+ ), "a started task", (value) => hasText(value.id));
58151
+ result.task = task.id;
57750
58152
  }
57751
58153
  say(`${result.dropped ? "Dropped" : result.start ? "Started" : "Saved"} goal ${result.id}${result.title ? `: ${result.title}` : ""}.`);
57752
58154
  }
@@ -57773,6 +58175,7 @@ var init_goal_cloud = __esm({
57773
58175
  "../cli/src/commands/goal-cloud.ts"() {
57774
58176
  "use strict";
57775
58177
  init_task();
58178
+ init_response();
57776
58179
  init_paths();
57777
58180
  init_io();
57778
58181
  init_goal2();
@@ -58019,21 +58422,27 @@ var init_agent = __esm({
58019
58422
 
58020
58423
  // ../cli/src/commands/cloud-template.ts
58021
58424
  import { createHash as createHash5 } from "node:crypto";
58022
- import fs73 from "node:fs";
58023
- import path74 from "node:path";
58425
+ import fs74 from "node:fs";
58426
+ import path75 from "node:path";
58024
58427
  function usage2(problem, line) {
58025
58428
  die(`${problem}
58026
58429
  usage: ${line}`, { kind: "bad-args", bare: true, exitCode: 2 });
58027
58430
  }
58028
- function refuse4(m, also) {
58029
- die([m.zh, m.en, ...also ? [also.zh, also.en] : []].join("\n"), { kind: "cloud-refused", bare: true });
58431
+ function refuse4(m, also, problem) {
58432
+ const message = [m.zh, m.en, problem?.message, also?.zh, also?.en].filter(Boolean).join("\n");
58433
+ if (problem) throw cloudError({ ...problem, message }, { bare: true });
58434
+ die(message, { kind: "cloud-refused", bare: true });
58030
58435
  }
58031
- function invalid(zh, en) {
58436
+ function invalid2(zh, en) {
58032
58437
  refuse4({ zh: `\u6A21\u677F\u672A\u901A\u8FC7\u6821\u9A8C\uFF1A${zh}`, en: `The template is not valid: ${en}` });
58033
58438
  }
58034
58439
  async function ask(route2, init = {}, fallback) {
58035
58440
  const token2 = await accessToken();
58036
- if (!token2.ok) refuse4(SAID[token2.reason], fallback);
58441
+ if (!token2.ok) refuse4(SAID[token2.reason], fallback, {
58442
+ code: token2.reason.replace("-", "_"),
58443
+ message: "error" in token2 ? token2.error ?? "" : "",
58444
+ retryable: token2.reason === "unreachable"
58445
+ });
58037
58446
  let res;
58038
58447
  try {
58039
58448
  res = await fetch(`${cloudEndpoints().api}/v1/templates${route2}`, {
@@ -58041,18 +58450,49 @@ async function ask(route2, init = {}, fallback) {
58041
58450
  headers: { authorization: `Bearer ${token2.token}` }
58042
58451
  });
58043
58452
  } catch {
58044
- refuse4(SAID.unreachable, fallback);
58453
+ refuse4(SAID.unreachable, fallback, { code: "unreachable", message: "", retryable: true });
58045
58454
  }
58046
58455
  if (res.ok) return res;
58047
- const { error: error62 } = await res.json().catch(() => ({}));
58048
- if (res.status === 401) refuse4(SAID.expired, fallback);
58049
- if (error62?.code === "pro_required") refuse4(T.pro_required, fallback);
58456
+ const problem = cloudProblem(res, await readCloudJson(res));
58457
+ if (res.status === 401) refuse4(SAID.expired, fallback, problem);
58458
+ if (problem.code === "pro_required") refuse4(T.pro_required, fallback, problem);
58050
58459
  const named2 = route2.startsWith("/") && !route2.startsWith("/tags?");
58051
- if (error62?.code === "not_found" && named2) refuse4(T.not_found, fallback);
58052
- if (error62?.code === "owner_only") refuse4(T.publisher_only);
58053
- if (error62?.code === "template_exists") refuse4(T.exists);
58054
- if (res.status === 400) invalid(error62?.message ?? "", error62?.message ?? "");
58055
- refuse4(T.failed, fallback);
58460
+ if (problem.code === "not_found" && named2) refuse4(T.not_found, fallback, problem);
58461
+ if (problem.code === "owner_only") refuse4(T.publisher_only, void 0, problem);
58462
+ if (problem.code === "template_exists") refuse4(T.exists, void 0, problem);
58463
+ if (res.status === 400) refuse4({ zh: "\u6A21\u677F\u8BF7\u6C42\u672A\u901A\u8FC7\u6821\u9A8C\u3002", en: "The template request is not valid." }, fallback, problem);
58464
+ refuse4(T.failed, fallback, problem);
58465
+ }
58466
+ async function asJson(res) {
58467
+ const value = await readCloudJson(res);
58468
+ const problem = cloudProblem(res, value);
58469
+ if (problem) throw cloudError(problem);
58470
+ if (!isRecord(value)) throw cloudError(invalidResponse("a valid template response"));
58471
+ return value;
58472
+ }
58473
+ function entries(value) {
58474
+ return Array.isArray(value) && value.every((entry) => isRecord(entry) && hasText(entry.path) && !/[\\:\0]/.test(entry.path) && entry.path.split("/").every((part) => !!part && part !== "." && part !== "..") && typeof entry.size === "number" && Number.isSafeInteger(entry.size) && entry.size >= 0 && (entry.sha256 === void 0 || typeof entry.sha256 === "string" && /^[a-f0-9]{64}$/.test(entry.sha256)));
58475
+ }
58476
+ async function downloadEntries(name, kind, files, to, fallback) {
58477
+ if (!SLUG.test(name)) throw cloudError(invalidResponse("a valid template name"));
58478
+ const fetched = [];
58479
+ const names2 = /* @__PURE__ */ new Set();
58480
+ const expected = "a matching template download";
58481
+ for (const file2 of files) {
58482
+ const leaf = path75.basename(file2.path);
58483
+ const out = path75.join(to, kind === "previews" && leaf.startsWith(`${name}-`) ? leaf : `${name}-${leaf}`);
58484
+ if (names2.has(out)) refuse4(T.corrupt, fallback, invalidResponse(expected));
58485
+ names2.add(out);
58486
+ const bytes2 = await cloudBytes(await ask(`/${encodeURIComponent(name)}/${kind}/${route(file2.path)}`, {}, fallback), expected, { size: file2.size });
58487
+ if (file2.sha256 && createHash5("sha256").update(bytes2).digest("hex") !== file2.sha256) refuse4(T.corrupt, fallback, invalidResponse(expected));
58488
+ fetched.push({ out, bytes: bytes2 });
58489
+ }
58490
+ if (fetched.length) fs74.mkdirSync(to, { recursive: true });
58491
+ return fetched.map(({ out, bytes: bytes2 }) => {
58492
+ fs74.writeFileSync(out, bytes2);
58493
+ say(out);
58494
+ return out;
58495
+ });
58056
58496
  }
58057
58497
  function category(value, line) {
58058
58498
  if (!value) usage2("Missing --category.", line);
@@ -58091,37 +58531,38 @@ No template matches. ${WITHOUT.en}`);
58091
58531
  async function templatePreview(name, opts, program2) {
58092
58532
  if (!opts.to) usage2("Missing --to.", `${program2} template preview <name> --to <dir>`);
58093
58533
  const at = encodeURIComponent(name);
58094
- const { previews } = await asJson(await ask(`/${at}/previews`, {}, WITHOUT));
58095
- if (previews.length === 0) say(`\u8FD9\u4E2A\u6A21\u677F\u6CA1\u6709\u9884\u89C8\u56FE\u3002
58096
- This template has no preview.`);
58097
- const written = [];
58098
- for (const p of previews) {
58099
- const bytes2 = Buffer.from(await (await ask(`/${at}/previews/${route(p.path)}`, {}, WITHOUT)).arrayBuffer());
58100
- const file2 = path74.basename(p.path);
58101
- const out = path74.join(opts.to, file2.startsWith(`${name}-`) ? file2 : `${name}-${file2}`);
58102
- fs73.mkdirSync(opts.to, { recursive: true });
58103
- fs73.writeFileSync(out, bytes2);
58104
- written.push(out);
58105
- say(out);
58106
- }
58107
- return { name, previews: written };
58534
+ const { previews } = requireResponse(
58535
+ await asJson(await ask(`/${at}/previews`, {}, WITHOUT)),
58536
+ "the template preview list",
58537
+ (value) => entries(value.previews)
58538
+ );
58539
+ if (previews.length === 0) say("\u8FD9\u4E2A\u6A21\u677F\u6CA1\u6709\u9884\u89C8\u56FE\u3002\nThis template has no preview.");
58540
+ return { name, previews: await downloadEntries(name, "previews", previews, opts.to, WITHOUT) };
58108
58541
  }
58109
58542
  async function templateGet(name, opts, program2) {
58110
58543
  if (!opts.to) usage2("Missing --to.", `${program2} template get <name> --to <dir>`);
58111
58544
  const to = opts.to;
58112
58545
  const at = encodeURIComponent(name);
58113
- const { template } = await asJson(await ask(`/${at}`, {}, WITHOUT));
58546
+ const { template } = requireResponse(
58547
+ await asJson(await ask(`/${at}`, {}, WITHOUT)),
58548
+ "the template file list",
58549
+ (value) => isRecord(value.template) && entries(value.template.files)
58550
+ );
58114
58551
  const fetched = [];
58115
58552
  for (const f of template.files) {
58116
- const out = path74.resolve(to, f.path);
58117
- if (!out.startsWith(path74.resolve(to) + path74.sep)) refuse4(T.corrupt, WITHOUT);
58118
- const bytes2 = Buffer.from(await (await ask(`/${at}/files/${route(f.path)}`, {}, WITHOUT)).arrayBuffer());
58553
+ const out = path75.resolve(to, f.path);
58554
+ if (!out.startsWith(path75.resolve(to) + path75.sep)) refuse4(T.corrupt, WITHOUT);
58555
+ const response = await ask(`/${at}/files/${route(f.path)}`, {}, WITHOUT);
58556
+ const bytes2 = await cloudBytes(response, "a matching template file", { size: f.size }).catch((error62) => {
58557
+ if (!(error62 instanceof BoardError)) throw error62;
58558
+ return refuse4(T.corrupt, WITHOUT, invalidResponse("a matching template file"));
58559
+ });
58119
58560
  if (bytes2.byteLength !== f.size || createHash5("sha256").update(bytes2).digest("hex") !== f.sha256) {
58120
58561
  refuse4(T.corrupt, WITHOUT);
58121
58562
  }
58122
58563
  fetched.push({ out, bytes: bytes2 });
58123
58564
  }
58124
- const taken = fetched.filter((f) => fs73.existsSync(f.out)).map((f) => path74.relative(to, f.out));
58565
+ const taken = fetched.filter((f) => fs74.existsSync(f.out)).map((f) => path75.relative(to, f.out));
58125
58566
  if (taken.length > 0) {
58126
58567
  refuse4({
58127
58568
  zh: `\u76EE\u6807\u6587\u4EF6\u5939\u5DF2\u6709\u540C\u540D\u6587\u4EF6\uFF1A${taken.join("\u3001")}\u3002\u8BF7\u6362\u4E00\u4E2A\u6587\u4EF6\u5939\uFF0C\u6216\u5148\u79FB\u8D70\u8FD9\u4E9B\u6587\u4EF6\u3002`,
@@ -58129,8 +58570,8 @@ async function templateGet(name, opts, program2) {
58129
58570
  });
58130
58571
  }
58131
58572
  for (const f of fetched) {
58132
- fs73.mkdirSync(path74.dirname(f.out), { recursive: true });
58133
- fs73.writeFileSync(f.out, f.bytes);
58573
+ fs74.mkdirSync(path75.dirname(f.out), { recursive: true });
58574
+ fs74.writeFileSync(f.out, f.bytes);
58134
58575
  }
58135
58576
  say(`\u5DF2\u53D6\u56DE ${name}\uFF1A${fetched.length} \u4E2A\u6587\u4EF6\uFF0C\u4F4D\u4E8E ${to}
58136
58577
  Fetched ${name}: ${fetched.length} files into ${to}`);
@@ -58138,50 +58579,48 @@ Fetched ${name}: ${fetched.length} files into ${to}`);
58138
58579
  }
58139
58580
  async function templateSource(name, opts) {
58140
58581
  const at = encodeURIComponent(name);
58141
- const { source: source2, evidence } = await asJson(await ask(`/${at}/source`));
58582
+ const { source: source2, evidence } = requireResponse(
58583
+ await asJson(await ask(`/${at}/source`)),
58584
+ "the template source and evidence list",
58585
+ (value) => isRecord(value.source) && entries(value.evidence)
58586
+ );
58587
+ const written = opts.to ? await downloadEntries(name, "evidence", evidence, opts.to) : [];
58142
58588
  if (source2.original === true) say("\u539F\u521B\u6A21\u677F\uFF0C\u6CA1\u6709\u5916\u90E8\u53C2\u8003\u3002\nAn original template, with no outside reference.");
58143
58589
  for (const [k, v] of Object.entries(source2)) if (k !== "original") say(`${k}: ${Array.isArray(v) ? v.join(", ") : String(v)}`);
58144
- const written = [];
58145
- for (const e of evidence) {
58146
- if (!opts.to) {
58147
- say(`evidence: ${e.path}`);
58148
- continue;
58149
- }
58150
- const out = path74.join(opts.to, `${name}-${path74.basename(e.path)}`);
58151
- fs73.mkdirSync(opts.to, { recursive: true });
58152
- fs73.writeFileSync(out, Buffer.from(await (await ask(`/${at}/evidence/${route(e.path)}`)).arrayBuffer()));
58153
- written.push(out);
58154
- say(out);
58155
- }
58156
- return { name, source: source2, evidence: written.length > 0 ? written : evidence.map((e) => e.path) };
58590
+ if (!opts.to) for (const file2 of evidence) say(`evidence: ${file2.path}`);
58591
+ return { name, source: source2, evidence: opts.to ? written : evidence.map((e) => e.path) };
58157
58592
  }
58158
58593
  async function templatePublish(dir, opts) {
58159
- const root2 = path74.resolve(dir);
58160
- const manifest = path74.join(root2, "template.md");
58161
- if (!fs73.existsSync(manifest)) invalid("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
58162
- const meta3 = readTemplateMeta(fs73.readFileSync(manifest, "utf8"));
58594
+ const root2 = path75.resolve(dir);
58595
+ const manifest = path75.join(root2, "template.md");
58596
+ if (!fs74.existsSync(manifest)) invalid2("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
58597
+ const meta3 = readTemplateMeta(fs74.readFileSync(manifest, "utf8"));
58163
58598
  const files = walk2(root2);
58164
- const total = files.reduce((sum, f) => sum + fs73.statSync(path74.join(root2, f)).size, 0);
58165
- if (total > MAX_BYTES2) invalid("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
58599
+ const total = files.reduce((sum, f) => sum + fs74.statSync(path75.join(root2, f)).size, 0);
58600
+ if (total > MAX_BYTES2) invalid2("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
58166
58601
  for (const extra of [...opts.preview, ...opts.evidence]) {
58167
- if (!fs73.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
58168
- if (path74.resolve(extra).startsWith(root2 + path74.sep)) {
58169
- invalid(
58602
+ if (!fs74.existsSync(extra)) invalid2(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
58603
+ if (path75.resolve(extra).startsWith(root2 + path75.sep)) {
58604
+ invalid2(
58170
58605
  `${extra} \u5728\u6A21\u677F\u6587\u4EF6\u5939\u5185\uFF1B\u9884\u89C8\u56FE\u4E0E\u6765\u6E90\u51ED\u8BC1\u9700\u653E\u5728\u6A21\u677F\u6587\u4EF6\u5939\u4E4B\u5916\u3002`,
58171
58606
  `${extra} is inside the template folder; keep previews and evidence outside it.`
58172
58607
  );
58173
58608
  }
58174
58609
  }
58175
58610
  if (meta3.source.original !== true && opts.evidence.length === 0) {
58176
- invalid("\u53C2\u8003\u5916\u90E8\u4F5C\u54C1\u7684\u6A21\u677F\u9700\u8981\u7528 --evidence \u9644\u4E0A\u91C7\u96C6\u7684\u6765\u6E90\u51ED\u8BC1\u3002", "a template cloned from a reference needs its captured evidence, via --evidence.");
58611
+ invalid2("\u53C2\u8003\u5916\u90E8\u4F5C\u54C1\u7684\u6A21\u677F\u9700\u8981\u7528 --evidence \u9644\u4E0A\u91C7\u96C6\u7684\u6765\u6E90\u51ED\u8BC1\u3002", "a template cloned from a reference needs its captured evidence, via --evidence.");
58177
58612
  }
58178
58613
  const form = new FormData();
58179
58614
  form.set("meta", JSON.stringify({ ...meta3, replace: !!opts.replace }));
58180
- const add2 = (kind, name, file2) => form.append(`${kind}:${name}`, new Blob([fs73.readFileSync(file2)]), path74.basename(name));
58181
- for (const f of files) add2("files", f, path74.join(root2, f));
58182
- for (const f of opts.preview) add2("previews", path74.basename(f), f);
58183
- for (const f of opts.evidence) add2("evidence", path74.basename(f), f);
58184
- const done = await asJson(await ask("", { method: "POST", body: form }));
58615
+ const add2 = (kind, name, file2) => form.append(`${kind}:${name}`, new Blob([fs74.readFileSync(file2)]), path75.basename(name));
58616
+ for (const f of files) add2("files", f, path75.join(root2, f));
58617
+ for (const f of opts.preview) add2("previews", path75.basename(f), f);
58618
+ for (const f of opts.evidence) add2("evidence", path75.basename(f), f);
58619
+ const done = requireResponse(
58620
+ await asJson(await ask("", { method: "POST", body: form })),
58621
+ "a template publication receipt",
58622
+ (value) => value.name === meta3.name && typeof value.replaced === "boolean"
58623
+ );
58185
58624
  say(
58186
58625
  done.replaced ? `\u5DF2\u66FF\u6362 ${done.name}\uFF1A${files.length} \u4E2A\u6587\u4EF6\u3002
58187
58626
  Replaced ${done.name}: ${files.length} files.` : `\u5DF2\u53D1\u5E03 ${done.name}\uFF1A${files.length} \u4E2A\u6587\u4EF6\u3002
@@ -58190,19 +58629,23 @@ Published ${done.name}: ${files.length} files.`
58190
58629
  return { name: done.name, replaced: done.replaced, files };
58191
58630
  }
58192
58631
  async function templateDelete(name) {
58193
- await ask(`/${encodeURIComponent(name)}`, { method: "DELETE" });
58632
+ requireResponse(
58633
+ await asJson(await ask(`/${encodeURIComponent(name)}`, { method: "DELETE" })),
58634
+ "confirmation that the template was deleted",
58635
+ (value) => value.name === name && value.deleted === true
58636
+ );
58194
58637
  say(`\u5DF2\u4ECE\u6A21\u677F\u5E93\u5220\u9664 ${name}\u3002
58195
58638
  Deleted ${name} from the catalog.`);
58196
58639
  return { name, deleted: true };
58197
58640
  }
58198
58641
  async function templateShowcase(name, dir) {
58199
- const file2 = path74.join(dir, "showcase.json");
58200
- if (!fs73.existsSync(file2)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
58642
+ const file2 = path75.join(dir, "showcase.json");
58643
+ if (!fs74.existsSync(file2)) invalid2(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
58201
58644
  let meta3;
58202
58645
  try {
58203
- meta3 = JSON.parse(fs73.readFileSync(file2, "utf8"));
58646
+ meta3 = JSON.parse(fs74.readFileSync(file2, "utf8"));
58204
58647
  } catch {
58205
- return invalid("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
58648
+ return invalid2("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
58206
58649
  }
58207
58650
  const sides = [meta3.original, meta3.recreation].filter((s) => !!s && typeof s === "object");
58208
58651
  const pages = (Array.isArray(meta3.pages) ? meta3.pages : []).flatMap(
@@ -58212,18 +58655,22 @@ async function templateShowcase(name, dir) {
58212
58655
  const form = new FormData();
58213
58656
  form.set("meta", JSON.stringify(meta3));
58214
58657
  for (const p of new Set(named2)) {
58215
- const at = path74.join(dir, p);
58216
- if (!fs73.existsSync(at)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
58217
- form.append(`media:${p}`, new Blob([fs73.readFileSync(at)]), p);
58218
- }
58219
- const done = await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form }));
58658
+ const at = path75.join(dir, p);
58659
+ if (!fs74.existsSync(at)) invalid2(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
58660
+ form.append(`media:${p}`, new Blob([fs74.readFileSync(at)]), p);
58661
+ }
58662
+ const done = requireResponse(
58663
+ await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form })),
58664
+ "a showcase publication receipt",
58665
+ (value) => value.name === name && value.files === new Set(named2).size
58666
+ );
58220
58667
  say(`\u5DF2\u66F4\u65B0 ${name} \u7684\u5C55\u793A\u8D44\u6599\uFF1A${done.files} \u4E2A\u6587\u4EF6\u3002
58221
58668
  Updated ${name}'s showcase: ${done.files} files.`);
58222
58669
  return { name, files: done.files };
58223
58670
  }
58224
58671
  function walk2(root2, sub = "") {
58225
58672
  const out = [];
58226
- for (const entry of fs73.readdirSync(path74.join(root2, sub), { withFileTypes: true })) {
58673
+ for (const entry of fs74.readdirSync(path75.join(root2, sub), { withFileTypes: true })) {
58227
58674
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
58228
58675
  const rel3 = sub ? `${sub}/${entry.name}` : entry.name;
58229
58676
  if (entry.isDirectory()) out.push(...walk2(root2, rel3));
@@ -58233,40 +58680,40 @@ function walk2(root2, sub = "") {
58233
58680
  }
58234
58681
  function readTemplateMeta(text5) {
58235
58682
  const m = /^---\n([\s\S]*?)\n---/.exec(text5.replace(/\r\n/g, "\n"));
58236
- if (!m) invalid("template.md \u7F3A\u5C11 frontmatter\u3002", "template.md has no frontmatter.");
58683
+ if (!m) invalid2("template.md \u7F3A\u5C11 frontmatter\u3002", "template.md has no frontmatter.");
58237
58684
  const fm = parseYamlSubset(m[1] ?? "");
58238
58685
  const text_ = (k, oneLine2 = true) => {
58239
58686
  const v = typeof fm[k] === "string" ? fm[k].trim() : "";
58240
- if (!v) invalid(`\u7F3A\u5C11 ${k}\u3002`, `${k} is missing.`);
58241
- if (oneLine2 && v.includes("\n")) invalid(`${k} \u53EA\u80FD\u662F\u4E00\u884C\u3002`, `${k} is one line.`);
58687
+ if (!v) invalid2(`\u7F3A\u5C11 ${k}\u3002`, `${k} is missing.`);
58688
+ if (oneLine2 && v.includes("\n")) invalid2(`${k} \u53EA\u80FD\u662F\u4E00\u884C\u3002`, `${k} is one line.`);
58242
58689
  return v;
58243
58690
  };
58244
58691
  const name = text_("name");
58245
- if (!SLUG.test(name)) invalid(`name \u53EA\u80FD\u7531\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\u7EC4\u6210\uFF0C\u4F8B\u5982 hero-tilted-screen\u3002`, `name is lowercase words joined by hyphens, like hero-tilted-screen.`);
58692
+ if (!SLUG.test(name)) invalid2(`name \u53EA\u80FD\u7531\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26\u7EC4\u6210\uFF0C\u4F8B\u5982 hero-tilted-screen\u3002`, `name is lowercase words joined by hyphens, like hero-tilted-screen.`);
58246
58693
  const cat = text_("category");
58247
- if (!SLUG.test(cat)) invalid("category \u53EA\u80FD\u662F\u5C0F\u5199\u82F1\u6587\u77ED\u8BCD\uFF0C\u4F8B\u5982 ui \u6216 video\u3002", "category is a lowercase word, like ui or video.");
58694
+ if (!SLUG.test(cat)) invalid2("category \u53EA\u80FD\u662F\u5C0F\u5199\u82F1\u6587\u77ED\u8BCD\uFF0C\u4F8B\u5982 ui \u6216 video\u3002", "category is a lowercase word, like ui or video.");
58248
58695
  const rawTags = fm.tags === void 0 || fm.tags === "" ? [] : fm.tags;
58249
- if (!Array.isArray(rawTags)) return invalid("tags \u9700\u8981\u662F\u5217\u8868\uFF0C\u4F8B\u5982 [hero, saas]\u3002", "tags is a list, like [hero, saas].");
58696
+ if (!Array.isArray(rawTags)) return invalid2("tags \u9700\u8981\u662F\u5217\u8868\uFF0C\u4F8B\u5982 [hero, saas]\u3002", "tags is a list, like [hero, saas].");
58250
58697
  const tags = [...new Set(rawTags.map(String))];
58251
58698
  const bad = tags.filter((t) => !SLUG.test(t));
58252
- if (bad.length > 0) invalid(`\u6807\u7B7E ${bad.join("\u3001")} \u4E0D\u5408\u89C4\uFF1A\u53EA\u80FD\u7528\u5C0F\u5199\u82F1\u6587\u77ED\u8BCD\u3002`, `tag ${bad.join(", ")}: use lowercase words joined by hyphens.`);
58699
+ if (bad.length > 0) invalid2(`\u6807\u7B7E ${bad.join("\u3001")} \u4E0D\u5408\u89C4\uFF1A\u53EA\u80FD\u7528\u5C0F\u5199\u82F1\u6587\u77ED\u8BCD\u3002`, `tag ${bad.join(", ")}: use lowercase words joined by hyphens.`);
58253
58700
  const access = fm.access === void 0 || fm.access === "" ? "pro" : fm.access;
58254
- if (access !== "free" && access !== "pro") return invalid("access \u53EA\u80FD\u662F free \u6216 pro\u3002", "access is free or pro.");
58701
+ if (access !== "free" && access !== "pro") return invalid2("access \u53EA\u80FD\u662F free \u6216 pro\u3002", "access is free or pro.");
58255
58702
  const source2 = fm.source === void 0 || fm.source === "" ? { original: true } : fm.source;
58256
58703
  if (typeof source2 !== "object" || Array.isArray(source2)) {
58257
- invalid("source \u5199\u6CD5\u4E0D\u5BF9\uFF1B\u539F\u521B\u6A21\u677F\u53EF\u4EE5\u4E0D\u5199\uFF0C\u6216\u5199 source: { original: true }\u3002", "source is malformed; an original can omit it or say original: true.");
58704
+ invalid2("source \u5199\u6CD5\u4E0D\u5BF9\uFF1B\u539F\u521B\u6A21\u677F\u53EF\u4EE5\u4E0D\u5199\uFF0C\u6216\u5199 source: { original: true }\u3002", "source is malformed; an original can omit it or say original: true.");
58258
58705
  }
58259
58706
  const s = source2;
58260
58707
  if (s.original !== true) {
58261
- if (typeof s.site !== "string" || !/^https?:\/\//.test(s.site)) invalid("source.site \u9700\u8981\u662F\u539F\u7AD9\u7F51\u5740\u3002", "source.site is the referenced site\u2019s URL.");
58708
+ if (typeof s.site !== "string" || !/^https?:\/\//.test(s.site)) invalid2("source.site \u9700\u8981\u662F\u539F\u7AD9\u7F51\u5740\u3002", "source.site is the referenced site\u2019s URL.");
58262
58709
  if (!Array.isArray(s.references) || s.references.length === 0) {
58263
- invalid("source.references \u9700\u8981\u5217\u51FA\u5B9E\u9645\u53C2\u8003\u8D44\u6599\u7684\u7F51\u5740\u3002", "source.references lists the URLs actually referenced.");
58710
+ invalid2("source.references \u9700\u8981\u5217\u51FA\u5B9E\u9645\u53C2\u8003\u8D44\u6599\u7684\u7F51\u5740\u3002", "source.references lists the URLs actually referenced.");
58264
58711
  }
58265
58712
  if (typeof s.captured !== "string" || !CAPTURED.test(s.captured)) {
58266
- invalid("source.captured \u9700\u8981\u5E26\u65F6\u533A\u7684\u91C7\u96C6\u65F6\u95F4\uFF0C\u4F8B\u5982 2026-10-16T09:00:00+08:00\u3002", "source.captured is the capture time with its time zone, like 2026-10-16T09:00:00+08:00.");
58713
+ invalid2("source.captured \u9700\u8981\u5E26\u65F6\u533A\u7684\u91C7\u96C6\u65F6\u95F4\uFF0C\u4F8B\u5982 2026-10-16T09:00:00+08:00\u3002", "source.captured is the capture time with its time zone, like 2026-10-16T09:00:00+08:00.");
58267
58714
  }
58268
58715
  if (typeof s.note !== "string" || !s.note.trim()) {
58269
- invalid("source.note \u9700\u8981\u8BF4\u660E\u51ED\u8BC1\u662F\u4EC0\u4E48\u3001\u7531\u8C01\u91C7\u96C6\u3002", "source.note says what the evidence is and who captured it.");
58716
+ invalid2("source.note \u9700\u8981\u8BF4\u660E\u51ED\u8BC1\u662F\u4EC0\u4E48\u3001\u7531\u8C01\u91C7\u96C6\u3002", "source.note says what the evidence is and who captured it.");
58270
58717
  }
58271
58718
  }
58272
58719
  return {
@@ -58335,13 +58782,14 @@ function unquote3(v) {
58335
58782
  }
58336
58783
  return v;
58337
58784
  }
58338
- var SLUG, CAPTURED, MAX_BYTES2, WITHOUT, T, asJson, route;
58785
+ var SLUG, CAPTURED, MAX_BYTES2, WITHOUT, T, route;
58339
58786
  var init_cloud_template = __esm({
58340
58787
  "../cli/src/commands/cloud-template.ts"() {
58341
58788
  "use strict";
58342
58789
  init_config();
58343
58790
  init_session();
58344
58791
  init_io();
58792
+ init_response();
58345
58793
  init_paths();
58346
58794
  init_cloud();
58347
58795
  SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -58365,7 +58813,6 @@ var init_cloud_template = __esm({
58365
58813
  en: "A downloaded file did not match the catalog, so nothing was written. Try again."
58366
58814
  }
58367
58815
  };
58368
- asJson = async (res) => await res.json();
58369
58816
  route = (p) => p.split("/").map(encodeURIComponent).join("/");
58370
58817
  }
58371
58818
  });
@@ -62440,7 +62887,7 @@ var init_archive2 = __esm({
62440
62887
  var board_default;
62441
62888
  var init_board3 = __esm({
62442
62889
  "../cli/src/guide/board.md"() {
62443
- board_default = "# How this board works\n\nThese rules apply to every card studio. Read them once; each studio's guide covers\nthe remaining details.\n\n## Layout\n\n```\ndocs/kanban/\n\u251C\u2500\u2500 todo/ open tasks\n\u2502 \u251C\u2500\u2500 README.md the index \u2014 read it first\n\u2502 \u2514\u2500\u2500 <id>-<slug>.md\n\u2502 one card per file; a group keeps its cards in one folder\n\u251C\u2500\u2500 rules/ `studios/<studio>.md` \u2014 Studio notes, set with `akb studio rule`\n\u2502 `<agent>.md` \u2014 project background-task instructions, set with\n\u2502 `akb studio instructions`\n\u251C\u2500\u2500 triage/ items waiting to be sorted, one file each \u2014 not cards. Only\n\u2502 \u2502 Cloud's sort or Refine idea on the web's Triage page turns one\n\u2502 \u2502 into a card; `akb raw triage check <source-id>` finds an existing one\n\u2502 \u251C\u2500\u2500 archived/ items a card was made of\n\u2502 \u251C\u2500\u2500 dismissed/ items ignored, with the reason\n\u2502 \u2514\u2500\u2500 files/ dropped-in files\n\u2514\u2500\u2500 modules.md one line per module \u2014 `akb guide module-map` writes it\n```\n\n## Task ID\n\nEvery task's id is the number at the front of its filename (`04-plan-cap-enforcement.md` \u2192\nid 4): its Cloud task's number (`WC-4`). Only Cloud assigns one.\n\n## Never hand-write a card's frontmatter\n\n`akb raw update`, `update-questions` and `akb raw conflict resolve` manage an existing card's frontmatter,\nincluding its `previews`. Edit only the card's **body** by hand. `akb raw help`\nlists all operations; `akb raw help <move>` explains one operation.\n\n## Content conflicts\n\nFor synchronization conflicts, follow `akb guide resolve-conflict`.\n\n## Inside a board run\n\nA board run carries `KANBAN_RUN` in its environment. Never unset or bypass it (for example\n`env -u KANBAN_RUN`): when a command only prints a flow, follow the printed flow.\n\n## Group task\n\nA group lives in `todo/<id>-<slug>/`: `root.md` tracks the whole job and each subtask is its\nown card beside it; `akb guide add-task` says how to build one. The root's `## Todo` lists the\nsubtasks, one line each ending in `#<subid>`: archiving a subtask ticks its line, rejecting\none strikes it through, and resolving the last line archives the root in the same run, with\nany open question or unticked todo of its own. A board a Runner keeps leaves that close to\nCloud, which waits for the root to be queued with no step on it. A root listing no subtasks is\nonly closed by hand.\n\n## Task context\n\nContinue from the task's saved discussion, results and approved requirements. Follow explicit\nproject and Studio rules. Read relevant memory on demand; do not write memory in task runs.\n";
62890
+ board_default = "# How this board works\n\nThese rules apply to every card studio. Read them once; each studio's guide covers\nthe remaining details.\n\n## Layout\n\n```\ndocs/kanban/\n\u251C\u2500\u2500 todo/ open tasks\n\u2502 \u251C\u2500\u2500 README.md the index \u2014 read it first\n\u2502 \u2514\u2500\u2500 <id>-<slug>.md\n\u2502 one card per file; a group keeps its cards in one folder\n\u251C\u2500\u2500 rules/ `studios/<studio>.md` \u2014 Studio notes, set with `akb studio rule`\n\u2502 `<agent>.md` \u2014 project background-task instructions, set with\n\u2502 `akb studio instructions`\n\u251C\u2500\u2500 triage/ items waiting to be sorted, one file each \u2014 not cards. Only\n\u2502 \u2502 Cloud's sort or Refine idea on the web's Triage page turns one\n\u2502 \u2502 into a card; `akb raw triage check <source-id>` finds an existing one\n\u2502 \u251C\u2500\u2500 archived/ items a card was made of\n\u2502 \u251C\u2500\u2500 dismissed/ items ignored, with the reason\n\u2502 \u2514\u2500\u2500 files/ dropped-in files\n\u2514\u2500\u2500 modules.md one line per module \u2014 `akb guide module-map` writes it\n```\n\n## Task ID\n\nEvery task's id is the number at the front of its filename (`04-plan-cap-enforcement.md` \u2192\nid 4): its Cloud task's number (`WC-4`). Only Cloud assigns one.\n\n## Never hand-write a card's frontmatter\n\n`akb raw update`, `akb task update-questions` and `akb raw conflict resolve` manage a card's frontmatter,\nincluding its `previews`. Edit only the card's **body** by hand. `akb raw help`\nlists all operations; `akb raw help <move>` explains one operation.\n\n## Content conflicts\n\nFor synchronization conflicts, follow `akb guide resolve-conflict`.\n\n## Inside a board run\n\nA board run carries `KANBAN_RUN` in its environment. Never unset or bypass it (for example\n`env -u KANBAN_RUN`): when a command only prints a flow, follow the printed flow.\n\n## Group task\n\nA group lives in `todo/<id>-<slug>/`: `root.md` tracks the whole job and each subtask is its\nown card beside it; `akb guide add-task` says how to build one. The root's `## Todo` lists the\nsubtasks, one line each ending in `#<subid>`: archiving a subtask ticks its line, rejecting\none strikes it through, and resolving the last line archives the root in the same run, with\nany open question or unticked todo of its own. A board a Runner keeps leaves that close to\nCloud, which waits for the root to be queued with no step on it. A root listing no subtasks is\nonly closed by hand.\n\n## Task context\n\nContinue from the task's saved discussion, results and approved requirements. Follow explicit\nproject and Studio rules. Read relevant memory on demand; do not write memory in task runs.\n";
62444
62891
  }
62445
62892
  });
62446
62893
 
@@ -62448,7 +62895,7 @@ var init_board3 = __esm({
62448
62895
  var card_chat_default;
62449
62896
  var init_card_chat = __esm({
62450
62897
  "../cli/src/guide/card-chat.md"() {
62451
- card_chat_default = '# Answer a card\'s conversation\n\nRead the task\u2019s review plan and work only on unlocked stages. An empty plan needs no extra approval; an undecided plan allows planning only.\n\n- **Where the task stands**: read `akb task show <id>` and `akb task review <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb raw update-questions <id>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Previews**: prepare or revise only requested outputs, using the task-bound Studio\u2019s Preview instructions and supplied component documentation. Before changing approved output, invalidate its stage with `akb task review <id> --revise-from <stage> --revision <n>`. Preserve unrelated work.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a studio**: use `akb guide update-studio` for shared Studio instructions; a correction to this card\'s draft alone stays on this card.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n\n- **Approve**: only on an explicit request, use `akb task approve <id> --stage <stage> --revision <reviewed revision>`. In a reply this commits after successful synchronization. Finish the reply without further edits or waiting. Never substitute the latest revision for the one reviewed.\n- **Change the plan**: submit a complete replacement with `akb task review <id> --file <json> --revision <n>`. It takes effect immediately. Answers to questions never approve work.\n';
62898
+ card_chat_default = '# Answer a card\'s conversation\n\nRead the task\u2019s review plan and work only on unlocked stages. An empty plan needs no extra approval; an undecided plan allows planning only.\n\n- **Where the task stands**: read `akb task show <id>` and `akb task review <id>`.\n- **Button labels**: name actions by their labels on the page, in the user\'s language: "Approve" or "Approve, start \u2026" (\u6279\u51C6 / \u6279\u51C6\uFF0C\u5F00\u59CB\u2026), "Resume" (\u7EED\u8DD1), "Start again" (\u91CD\u65B0\u53D1\u8D77).\n\n- **Change requirements or drafts**: when the user changes the scope, expected behavior, or draft, use `akb raw card revise <id> --print "<change>"`.\n- **Record an answer**: when the user answers an open question on the card, use `akb raw card resolve <id> --print`.\n- **Manage open questions**: when a decision needs the user\'s input, follow `akb guide update-questions` and use `akb task update-questions <task>` to edit the question list.\n- **Change card fields**: when the user changes metadata such as priority, modules, or dependencies, use `akb raw update <id>`.\n- **Previews**: prepare or revise only requested outputs, using the task-bound Studio\u2019s Preview instructions and supplied component documentation. Before changing approved output, invalidate its stage with `akb task review <id> --revise-from <stage> --revision <n>`. Preserve unrelated work.\n- **Create a separate task**: when the user asks to capture work unrelated to this card, follow `akb guide add-task`.\n- **Split this card**: when the user asks to break this card\'s outcome into subtasks, follow the group procedure in `akb guide add-task`.\n- **Change a studio**: use `akb guide update-studio` for shared Studio instructions; a correction to this card\'s draft alone stays on this card.\n- **Check card edits**: after writing a card, run `akb raw validate <id>` and fix what it reports.\n- **Anything else**: for a request this guide does not cover, read `akb help` once, then the matching command\'s `--help`.\n\nReply in plain, natural language. Do not write memory, including through any flow this conversation starts.\n\n- **Approve**: only on an explicit request, use `akb task approve <id> --stage <stage> --revision <reviewed revision>`. In a reply this commits after successful synchronization. Finish the reply without further edits or waiting. Never substitute the latest revision for the one reviewed.\n- **Change the plan**: submit a complete replacement with `akb task review <id> --file <json> --revision <n>`. It takes effect immediately. Answers to questions never approve work.\n';
62452
62899
  }
62453
62900
  });
62454
62901
 
@@ -62472,7 +62919,7 @@ var init_describe_project = __esm({
62472
62919
  var discuss_goal_default;
62473
62920
  var init_discuss_goal = __esm({
62474
62921
  "../cli/src/guide/discuss-goal.md"() {
62475
- 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';
62922
+ discuss_goal_default = '# Discuss a goal\n\nResearch how the requested outcome can be achieved before defining a Goal. Explain viable approaches and key tradeoffs in the discussion, then save the requested outcome and acceptance criteria.\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**: read the chosen Studio\'s `STUDIO.md` with `akb raw file <studio> STUDIO.md` and linked Studio files as needed with `akb raw file <studio> <path>`. Match deliverables that need review to Studio Previews. Define a Goal Preview for a result that needs review and lacks a Studio Preview.\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**: ask only about choices the user must make, and recommend an option.\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';
62476
62923
  }
62477
62924
  });
62478
62925
 
@@ -62488,7 +62935,7 @@ var init_follow_up = __esm({
62488
62935
  var implement_default;
62489
62936
  var init_implement = __esm({
62490
62937
  "../cli/src/guide/implement.md"() {
62491
- 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";
62938
+ implement_default = "# Implement the approved requirements\n\nBuild the approved requirements without reopening settled decisions or unrelated questions; without a card, create none.\n\nBefore implementing a Cloud task, read its recent chat with `akb task chat <task>`.\nRead older messages as needed. Use relevant clarifications within the scope of\nthe current card and approved plan.\n\nFor Git deliveries, adapt the approved work to the current target branch and preserve its\nbehavior and removals unless the task's core intent requires changing them. Stop the\naffected work and use `akb guide update-questions` only if those changes conflict with the\ntask's core intent.\n\nDo not push, publish or deploy.\n\nOnce a task meets its Studio's delivery conditions, follow `akb guide archive` to record\ndelivery completion before ending the run.\n\n- **Verification**: run required and minimal representative checks, reuse valid results, distinguish defects from environment or tool limits, stop retries that add no evidence, and finish when acceptance is proven.\n- **Authorization**: carry approval for necessary in-scope operations across tools and stages without asking again.\n- **Blockers**: resolve routine problems and use `akb guide update-questions` only for user-action blockers or out-of-scope decisions, stating attempts, impact and recommendation while continuing independent work.\n- **Defer**: follow `akb guide follow-up` for unrelated work and keep it from blocking delivery.\n- **Decisions**: record material, reversible build decisions under `## Worth noting after implementation`.\n";
62492
62939
  }
62493
62940
  });
62494
62941
 
@@ -62544,7 +62991,7 @@ var init_reflect = __esm({
62544
62991
  var resolve_default;
62545
62992
  var init_resolve2 = __esm({
62546
62993
  "../cli/src/guide/resolve.md"() {
62547
- resolve_default = '# Resolve questions\n\nApply the answers the user supplied to existing open questions. Leave every unanswered\nquestion unchanged. While applying answers, do not research, choose for the user, raise\nanother question, or change project code.\n\n## Apply each answer\n\n1. Match each supplied answer to its open question. If the answer is missing or unclear,\n leave that question open.\n2. Follow `akb guide writing`. Merge the answer into the existing decision, keep only the\n selected choice, remove obsolete or contradictory text, preserve completed work, and add\n newly required work as unchecked todos. When the answer changes an agent\'s section, read\n that agent\'s rules first, as "Preview ownership" there says.\n3. Drop each answered question after its answer is fully applied:\n\n```text\nakb raw update-questions <id> --drop <n[,n...]>\n```\n\nWhen an answer accepts a step the user was asked to review and asks for no changes, tick that\nstep\'s review todo; an answer asking for changes leaves it unticked.\n\nWhen an answer chooses to discard the card, first run `akb raw delivery cancel <delivery>` if a\ndelivery is in flight, then `akb task remove <id> "<why>" --discard`, and stop. Skip every\nremaining step of this guide.\n\nWhen an answer sends an agent\'s (`agent:`) section back for rework that the user must confirm\nagain, keep or `--update` the question instead of dropping it. Once no question is left for\nthat agent, request each matching agent listed below it whose section is missing or says it\nis waiting.\n\nWhen an answer selects one of several options in a Preview block, remove the rejected\noptions and their spec-tmp files.\n\n## Say what the answers did to a build in flight\n\nA delivery builds the card as it was approved when it started, and applying answers is the\nonly thing that rewrites that card underneath it. You read the question and you wrote the\nanswer, so you are the only one who can tell a confirmation from a change \u2014 the board reads\nyour conclusion and never the card\'s text.\n\n```text\nakb raw delivery answered <delivery> --unchanged "<why>"\nakb raw delivery answered <delivery> --changed "<why>"\n```\n\n- **Record it before you drop the questions**: dropping the last one is what puts the board\n back in motion, and until the conclusion is written the build does not land.\n- **Judge the meaning, not the words**: confirming an option that is already built, writing\n down a decision the card already carries, and tidying prose are all `--unchanged`.\n Adding, dropping or changing a requirement is `--changed`.\n- **A wrong implementation confirmed is still a change**: an answer that blesses work\n contradicting the approved copy is `--changed`, however finished that work is.\n- **One conclusion per round**: it covers every answer you applied in this session. The\n delivery a `--changed` reopens starts on the card as it then reads, with none of its own.\n\n`akb raw card implement <id> --print` prints the delivery\'s id and the copy it is building.\nNothing to record when no delivery is in flight.\n\n## Curate the human half\n\nPut each answer `akb guide writing` places in `Worth noting` in that section; put other\nnecessary lasting decisions below the boundary.\n\nRe-read the whole human half against the same rule. Remove or move down entries that\nfail it, repeat scope, or overlap another entry. Merge entries governed by one decision. One to\nthree independent items is normal; every additional item needs distinct user-facing stakes.\n\n## Refine\n\nIf any question remains open, stop and leave the card waiting. When a delivery is in flight,\nnever refine \u2014 even if `--changed` updated requirements, execution resumes directly from the\nupdated card.\n\nOnce no question is left and no delivery is building the card, refine it in this session by\n`akb guide refine`, which decides readiness:\n\n- **Partial**: when the card was refined before, revisit only what the answers changed.\n- **Full**: when the answers reshape the card or its `## Scope` is still the creation scaffold.\n';
62994
+ resolve_default = '# Resolve questions\n\nApply the answers the user supplied to existing open questions. Leave every unanswered\nquestion unchanged. While applying answers, do not research, choose for the user, raise\nanother question, or change project code.\n\n## Apply each answer\n\n1. Match each supplied answer to its open question. If the answer is missing or unclear,\n leave that question open.\n2. Follow `akb guide writing`. Merge the answer into the existing decision, keep only the\n selected choice, remove obsolete or contradictory text, preserve completed work, and add\n newly required work as unchecked todos. When the answer changes an agent\'s section, read\n that agent\'s rules first, as "Preview ownership" there says.\n\nWhen an answer accepts a step the user was asked to review and asks for no changes, tick that\nstep\'s review todo; an answer asking for changes leaves it unticked.\n\nWhen an answer chooses to discard the card, first run `akb raw delivery cancel <delivery>` if a\ndelivery is in flight, then `akb task remove <id> "<why>" --discard`, and stop. Skip every\nremaining step of this guide.\n\nWhen an answer sends an agent\'s (`agent:`) section back for rework that the user must confirm\nagain, keep or `--update` the question instead of dropping it. Once no question is left for\nthat agent, request each matching agent listed below it whose section is missing or says it\nis waiting.\n\nWhen an answer selects one of several options in a Preview block, remove the rejected\noptions and their spec-tmp files.\n\n## Say what the answers did to a build in flight\n\nA delivery builds the card as it was approved when it started, and applying answers is the\nonly thing that rewrites that card underneath it. You read the question and you wrote the\nanswer, so you are the only one who can tell a confirmation from a change \u2014 the board reads\nyour conclusion and never the card\'s text.\n\n```text\nakb raw delivery answered <delivery> --unchanged "<why>"\nakb raw delivery answered <delivery> --changed "<why>"\n```\n\n- **Record it before you drop the questions**: dropping the last one is what puts the board\n back in motion, and until the conclusion is written the build does not land.\n- **Judge the meaning, not the words**: confirming an option that is already built, writing\n down a decision the card already carries, and tidying prose are all `--unchanged`.\n Adding, dropping or changing a requirement is `--changed`.\n- **A wrong implementation confirmed is still a change**: an answer that blesses work\n contradicting the approved copy is `--changed`, however finished that work is.\n- **One conclusion per round**: it covers every answer you applied in this session. The\n delivery a `--changed` reopens starts on the card as it then reads, with none of its own.\n\n`akb raw card implement <id> --print` prints the delivery\'s id and the copy it is building.\nNothing to record when no delivery is in flight.\n\n## Curate the human half\n\nPut each answer `akb guide writing` places in `Worth noting` in that section; put other\nnecessary lasting decisions below the boundary.\n\nRe-read the whole human half against the same rule. Remove or move down entries that\nfail it, repeat scope, or overlap another entry. Merge entries governed by one decision. One to\nthree independent items is normal; every additional item needs distinct user-facing stakes.\n\n## Close the answered questions\n\nSave the body and any delivery conclusion first. Drop only the questions whose answers\nare fully applied. Runner synchronizes the updated body and question list together.\n\n```text\nakb task update-questions <task> --drop <n[,n...]>\n```\n\n## Refine\n\nIf any question remains open, stop and leave the card waiting. When a delivery is in flight,\nnever refine \u2014 even if `--changed` updated requirements, execution resumes directly from the\nupdated card.\n\nOnce no question is left and no delivery is building the card, refine it in this session by\n`akb guide refine`, which decides readiness:\n\n- **Partial**: when the card was refined before, revisit only what the answers changed.\n- **Full**: when the answers reshape the card or its `## Scope` is still the creation scaffold.\n';
62548
62995
  }
62549
62996
  });
62550
62997
 
@@ -62568,7 +63015,7 @@ var init_revise = __esm({
62568
63015
  var update_questions_default;
62569
63016
  var init_update_questions = __esm({
62570
63017
  "../cli/src/guide/update-questions.md"() {
62571
- update_questions_default = '# Decide what to ask the user\n\nA decision is a choice the work needs made. A question is a decision handed to the user:\nproject evidence cannot settle it, it materially affects what the user gets, and it has at\nleast two coherent options.\n\n### The material-decision test\n\nAsk when the tradeoff materially changes the delivered result, the accepted scope, the user\'s\nrisk, or a meaningful ongoing cost, and a reasonable reviewer may reject it; a studio\'s rules\nadd what else counts. Settle everything else yourself. Leave the question open and stop only\nthe work that depends on it. An obstacle only the user can clear is a question too: say what\ncannot proceed and offer ways forward.\n\n- **Write for users**: each option\'s outcome and main cost, your recommendation ticked; no\n card ids, agent names, or board jargon.\n- **Options**: exclusive unless they genuinely combine (`--mode multi`); never write an\n "other" option, the user always gets one.\n- **Not a question**: where a fix goes (`akb guide follow-up`).\n\n```text\nakb raw update-questions <id> \\\n --append "Which behavior should apply?" \\\n --recommended-option "A \u2014 outcome and cost" \\\n --option "B \u2014 outcome and cost"\n```\n';
63018
+ update_questions_default = '# Decide what to ask the user\n\nA decision is a choice the work needs made. A question is a decision handed to the user:\nproject evidence cannot settle it, it materially affects what the user gets, and it has at\nleast two coherent options.\n\n### The material-decision test\n\nAsk when the tradeoff materially changes the delivered result, the accepted scope, the user\'s\nrisk, or a meaningful ongoing cost, and a reasonable reviewer may reject it; a studio\'s rules\nadd what else counts. Settle everything else yourself. Leave the question open and stop only\nthe work that depends on it. An obstacle only the user can clear is a question too: say what\ncannot proceed and offer ways forward.\n\n- **Write for users**: each option\'s outcome and main cost, your recommendation ticked; no\n card ids, agent names, or board jargon.\n- **Options**: exclusive unless they genuinely combine (`--mode multi`); never write an\n "other" option, the user always gets one.\n- **Not a question**: where a fix goes (`akb guide follow-up`).\n\n```text\nakb task update-questions <task> \\\n --append "Which behavior should apply?" \\\n --recommended-option "A \u2014 outcome and cost" \\\n --option "B \u2014 outcome and cost"\n```\n\nUse the current task\'s key, ID, or project number. Runner saves the current card locally\nand synchronizes it with the rest of the card. For a Cloud version conflict, read the card\nagain and check the question positions before resubmitting.\n';
62572
63019
  }
62573
63020
  });
62574
63021
 
@@ -62600,7 +63047,7 @@ var init_write_prompt = __esm({
62600
63047
  var writing_default;
62601
63048
  var init_writing = __esm({
62602
63049
  "../cli/src/guide/writing.md"() {
62603
- writing_default = '# Write a card\n\nA card has a **human half** for review and a folded **agent half** for implementation.\nUse this order and keep the English section titles and empty scaffold sections:\n\n```text\n<One short paragraph: the problem and the intended result.>\n\n## Worth noting <- user\'s answers first, then material decisions; empty if none\n- **<decision>**: <chosen behavior and main cost in one sentence>\n\n## Worth noting after implementation\n- **<decision>**: <chosen behavior and main cost in one sentence>\n <- settled by the build; omit when empty; no logs or open questions\n\n<Preview id="<id>"> <- requested deliverable\n<result Markdown and assets>\n</Preview>\n\n<!-- agent --> <- folded content starts here\n\n## Scope <- requirements, not rationale\n### Done when <- acceptance checklist, when supplied\n- [ ] <observable result>\n\n## Todo <- implementation only; finish planning before writing steps\n- [ ] <one build step>\n\n## Decided by the agent <- other decisions and non-obvious findings the build needs\n- **<decision>**: <answer and required action>\n### Overruled by the user <- superseded decisions, always last\n```\n\n- **Decisions**: use the material-decision test in `akb guide update-questions` for Worth noting;\n merge entries governed by one policy and keep only the decision and its main cost.\n- **Delivery boundary**: Worth noting after implementation never changes approved scope or\n blocks an ongoing delivery; the build must fix deviations or refer them to the user.\n- **Preview sections**: use matching Preview tags and a stable Studio ID; keep the ID when revising.\n The app supplies localized titles and icons. Group files of one deliverable with Set.\n- **Previews**: read the relevant Studio `<Preview>` block and needed references before revising\n its section and assets in place.\n- **Preview presentation**: at every review point, show the deliverable directly; omit surrounding\n introductions, summaries and notes unless requested or needed for review, keeping necessary\n context brief and stating it once.\n- **Preserve work**: leave checked todos and supplied Done when checklists unchanged; append a\n todo to reverse completed work, and move user-overruled decisions to Overruled by the user\n until the card leaves no room to repeat them.\n- **Writing**: write clear behavior and necessary tradeoffs for a fresh reader, keep the human\n half self-contained, and state each fact once.\n- **Agent half**: keep only implementation-critical information not stated elsewhere; omit\n process logs and routine implementation planning, and leave unneeded sections empty.\n- **Frontmatter**: never edit frontmatter by hand; use `akb raw update` or `update-questions`.\n- **Validate**: run `akb raw validate <id>` after edits and fix every reported file and line.\n';
63050
+ writing_default = '# Write a card\n\nA card has a **human half** for review and a folded **agent half** for implementation.\nUse this order and keep the English section titles and empty scaffold sections:\n\n```text\n<One short paragraph: the problem and the intended result.>\n\n## Worth noting <- user\'s answers first, then material decisions; empty if none\n- **<decision>**: <chosen behavior and main cost in one sentence>\n\n## Worth noting after implementation\n- **<decision>**: <chosen behavior and main cost in one sentence>\n <- settled by the build; omit when empty; no logs or open questions\n\n<Preview id="<id>"> <- requested deliverable\n<result Markdown and assets>\n</Preview>\n\n<!-- agent --> <- folded content starts here\n\n## Scope <- requirements, not rationale\n### Done when <- acceptance checklist, when supplied\n- [ ] <observable result>\n\n## Todo <- implementation only; finish planning before writing steps\n- [ ] <one build step>\n\n## Decided by the agent <- other decisions and non-obvious findings the build needs\n- **<decision>**: <answer and required action>\n### Overruled by the user <- superseded decisions, always last\n```\n\n- **Decisions**: use the material-decision test in `akb guide update-questions` for Worth noting;\n merge entries governed by one policy and keep only the decision and its main cost.\n- **Delivery boundary**: Worth noting after implementation never changes approved scope or\n blocks an ongoing delivery; the build must fix deviations or refer them to the user.\n- **Preview sections**: use matching Preview tags and a stable Studio ID; keep the ID when revising.\n The app supplies localized titles and icons. Group files of one deliverable with Set.\n- **Previews**: read the relevant Studio `<Preview>` block and needed references before revising\n its section and assets in place.\n- **Preview presentation**: at every review point, show the deliverable directly; omit surrounding\n introductions, summaries and notes unless requested or needed for review, keeping necessary\n context brief and stating it once.\n- **Preserve work**: leave checked todos and supplied Done when checklists unchanged; append a\n todo to reverse completed work, and move user-overruled decisions to Overruled by the user\n until the card leaves no room to repeat them.\n- **Writing**: write clear behavior and necessary tradeoffs for a fresh reader, keep the human\n half self-contained, and state each fact once.\n- **Agent half**: keep only implementation-critical information not stated elsewhere; omit\n process logs and routine implementation planning, and leave unneeded sections empty.\n- **Frontmatter**: never edit frontmatter by hand; use `akb raw update` or `akb task update-questions`.\n- **Validate**: run `akb raw validate <id>` after edits and fix every reported file and line.\n';
62604
63051
  }
62605
63052
  });
62606
63053
 
@@ -62714,20 +63161,26 @@ var init_guide2 = __esm({
62714
63161
 
62715
63162
  // ../cli/src/commands/studio.ts
62716
63163
  import crypto7 from "node:crypto";
62717
- import fs74 from "node:fs";
62718
- import path75 from "node:path";
63164
+ import fs75 from "node:fs";
63165
+ import path76 from "node:path";
62719
63166
  function cmdStudioList() {
62720
63167
  if (!studiosReachable().ok) die(NEEDS_CLOUD, "needs-cloud");
62721
63168
  const rows = studios();
62722
- for (const flow of rows) say(`${flow.id} ${flow.name} ${flow.previews.map((p) => p.id).join(", ")}`);
62723
- return { studios: rows.map(({ id: id2, name, names: names2, icon: icon3, needsArtifact, previews, description, builtIn }) => ({ id: id2, name, names: names2, icon: icon3, needsArtifact, previews, description, builtIn })), problems: studioFileProblems(), ...studiosOffline() ? { offline: true } : {} };
63169
+ const result = { studios: rows.map(({ id: id2, name, names: names2, icon: icon3, needsArtifact, previews, description, builtIn }) => ({ id: id2, name, names: names2, icon: icon3, needsArtifact, previews, description, builtIn })), problems: studioFileProblems() };
63170
+ const { cached: cached3, problem } = studioVerification();
63171
+ if (!problem || cached3) for (const flow of rows) say(`${flow.id} ${flow.name} ${flow.previews.map((p) => p.id).join(", ")}`);
63172
+ if (problem) throw cloudError(
63173
+ { ...problem, message: `Cloud Studio verification failed. ${cached3 ? "Showing cached Studios." : "No cached Studio list is available."} ${problem.message}` },
63174
+ { details: { ...result, cached: cached3, offline: problem.retryable } }
63175
+ );
63176
+ return result;
62724
63177
  }
62725
63178
  function cmdStudioDiagram(_id, _card, _folder) {
62726
63179
  die("Studios have no agent graph. Read STUDIO.md for instructions and Preview outputs.", "bad-args");
62727
63180
  }
62728
63181
  function cmdStudioValidate(folder2) {
62729
- const dir = path75.resolve(folder2);
62730
- if (!fs74.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder2} is not a folder`, "bad-args");
63182
+ const dir = path76.resolve(folder2);
63183
+ if (!fs75.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) die(`${folder2} is not a folder`, "bad-args");
62731
63184
  const files = readStudioFolder(dir);
62732
63185
  let builtin = false;
62733
63186
  try {
@@ -62743,17 +63196,24 @@ function cmdStudioValidate(folder2) {
62743
63196
  }
62744
63197
  async function cmdStudioPull(id2, folder2) {
62745
63198
  const cloudId = cloudIdOf(id2);
62746
- if (!cloudId) found(id2);
62747
- const dir = path75.resolve(folder2 ?? id2);
62748
- if (fs74.existsSync(dir) && fs74.readdirSync(dir).length) die(`${folder2 ?? id2} is not empty`, "bad-args");
63199
+ if (!cloudId) {
63200
+ const { problem } = studioVerification();
63201
+ if (problem) throw cloudError(problem);
63202
+ found(id2);
63203
+ }
63204
+ const dir = path76.resolve(folder2 ?? id2);
63205
+ if (fs75.existsSync(dir) && fs75.readdirSync(dir).length) die(`${folder2 ?? id2} is not empty`, "bad-args");
62749
63206
  const read5 = await call("GET", `/v1/studios/${encodeURIComponent(cloudId)}`);
62750
- if (!read5.ok) die(read5.error, read5.code === "not_found" ? "no-such-studio" : "cloud-refused");
62751
- const { version: version2, files } = read5.value;
63207
+ const { version: version2, files } = requireResponse(
63208
+ cloudOk(read5, read5.ok || read5.code !== "not_found" ? void 0 : "no-such-studio"),
63209
+ "the Studio version and files",
63210
+ (value) => value.id === cloudId && isStudioVersion(value.version) && isStudioFiles(value.files)
63211
+ );
62752
63212
  for (const [file2, text5] of Object.entries({ ...files, [VERSION_FILE]: versionText(cloudId, version2) })) {
62753
- const full = path75.join(dir, ...file2.split("/"));
62754
- fs74.mkdirSync(path75.dirname(full), { recursive: true });
63213
+ const full = path76.join(dir, ...file2.split("/"));
63214
+ fs75.mkdirSync(path76.dirname(full), { recursive: true });
62755
63215
  const data = isAboutFile(file2) && !file2.endsWith(".md") && /^data:[^;]+;base64,/.exec(text5);
62756
- fs74.writeFileSync(full, data ? Buffer.from(text5.slice(data[0].length), "base64") : text5);
63216
+ fs75.writeFileSync(full, data ? Buffer.from(text5.slice(data[0].length), "base64") : text5);
62757
63217
  }
62758
63218
  const shown = folder2 ?? `./${id2}`;
62759
63219
  say(`Pulled ${id2} v${version2} into ${shown}.`);
@@ -62765,53 +63225,60 @@ function publicationFiles(dir) {
62765
63225
  return checked.files;
62766
63226
  }
62767
63227
  async function publishFolder(dir, route2, body, requestId) {
62768
- const pendingFile = path75.join(dir, ".publication.json");
63228
+ const pendingFile = path76.join(dir, ".publication.json");
62769
63229
  const hash3 = crypto7.createHash("sha256").update(JSON.stringify({ route: route2, files: body.files, workspace: body.workspace })).digest("hex");
62770
63230
  let held4;
62771
63231
  try {
62772
- held4 = JSON.parse(fs74.readFileSync(pendingFile, "utf8"));
63232
+ held4 = JSON.parse(fs75.readFileSync(pendingFile, "utf8"));
62773
63233
  } catch {
62774
63234
  }
62775
63235
  if (requestId && held4?.requestId === requestId && held4.hash !== hash3) die("This request ID already names different files; use a new request ID.", "bad-args");
62776
63236
  const replay = held4?.hash === hash3 && held4.route === route2 && (!requestId || held4.requestId === requestId) && (body.expectedVersion === held4.body.expectedVersion || body.expectedVersion === held4.resultVersion);
62777
63237
  const pending = replay ? held4 : { requestId: requestId ?? crypto7.randomUUID(), hash: hash3, body, route: route2 };
62778
- fs74.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
63238
+ fs75.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
62779
63239
  const res = await call(route2 === "/v1/studios" ? "POST" : "PATCH", route2, pending.body, pending.requestId);
62780
- if (!res.ok) die(res.error, res.code === "version_conflict" || res.code === "conflict" ? "studio-moved" : "cloud-refused");
62781
- const { id: id2, version: version2 } = res.value;
63240
+ const { id: id2, version: version2 } = requireResponse(
63241
+ cloudOk(res, !res.ok && ["version_conflict", "conflict"].includes(res.code ?? "") ? "studio-moved" : void 0),
63242
+ "confirmation of the saved Studio version",
63243
+ (value) => hasText(value.id) && /^wf_[\w-]+$/.test(value.id) && isStudioVersion(value.version) && (pending.body.expectedVersion === void 0 || route2 === `/v1/studios/${encodeURIComponent(value.id)}` && value.version === pending.body.expectedVersion + 1)
63244
+ );
62782
63245
  pending.resultVersion = version2;
62783
- fs74.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
62784
- fs74.writeFileSync(path75.join(dir, VERSION_FILE), versionText(id2, version2));
63246
+ fs75.writeFileSync(pendingFile, JSON.stringify(pending, null, 2) + "\n");
63247
+ fs75.writeFileSync(path76.join(dir, VERSION_FILE), versionText(id2, version2));
62785
63248
  say(`Saved ${studioName(id2)} v${version2}. New tasks take it.`);
62786
63249
  return { id: id2, version: version2, changed: true, requestId: pending.requestId };
62787
63250
  }
62788
63251
  async function cmdStudioCreate(folder2, opts) {
62789
63252
  if (!opts.requestId) die("--request-id is required", "bad-args");
62790
- const dir = path75.resolve(folder2);
63253
+ const dir = path76.resolve(folder2);
62791
63254
  const files = publicationFiles(dir);
62792
63255
  const workspace2 = opts.workspace ?? (await cloudScope()).workspace;
62793
63256
  return publishFolder(dir, "/v1/studios", { files, workspace: workspace2 }, opts.requestId);
62794
63257
  }
62795
63258
  async function cmdStudioPush(folder2, opts) {
62796
- const dir = path75.resolve(folder2);
63259
+ const dir = path76.resolve(folder2);
62797
63260
  let pulled = null;
62798
63261
  try {
62799
- pulled = JSON.parse(fs74.readFileSync(path75.join(dir, VERSION_FILE), "utf8"));
63262
+ pulled = JSON.parse(fs75.readFileSync(path76.join(dir, VERSION_FILE), "utf8"));
62800
63263
  } catch {
62801
63264
  }
62802
63265
  if (!pulled?.id || !Number.isInteger(pulled.version) || pulled.version < 1) die(`${folder2} has no valid version.json; pull again.`, "bad-args");
62803
63266
  const { id: id2, version: version2 } = pulled;
62804
63267
  if (id2.startsWith("wf_builtin_")) die("Copy this studio before editing it.", "studio-read-only");
62805
63268
  const files = publicationFiles(dir);
62806
- if (!fs74.existsSync(path75.join(dir, ".publication.json")) && !opts.requestId) {
63269
+ if (!fs75.existsSync(path76.join(dir, ".publication.json")) && !opts.requestId) {
62807
63270
  const now = await call("GET", `/v1/studios/${encodeURIComponent(id2)}`);
62808
- if (now.ok && now.value.version === version2 && JSON.stringify(files) === JSON.stringify(Object.fromEntries(Object.entries(now.value.files).filter(([f]) => f !== VERSION_FILE).sort()))) {
63271
+ if (now.ok && now.value.version === version2 && isStudioFiles(now.value.files) && JSON.stringify(files) === JSON.stringify(Object.fromEntries(Object.entries(now.value.files).filter(([f]) => f !== VERSION_FILE).sort()))) {
62809
63272
  say(`${studioName(id2)} is unchanged (v${version2}).`);
62810
63273
  return { id: studioName(id2), version: version2, changed: false, ...opts.dryRun ? { dryRun: true } : {} };
62811
63274
  }
62812
63275
  }
62813
63276
  if (opts.dryRun) {
62814
- const now = cloudOk(await call("GET", `/v1/studios/${encodeURIComponent(id2)}`));
63277
+ const now = requireResponse(
63278
+ cloudOk(await call("GET", `/v1/studios/${encodeURIComponent(id2)}`)),
63279
+ "the current Studio version",
63280
+ (value) => isStudioVersion(value.version)
63281
+ );
62815
63282
  if (now.version !== version2) die(`The studio is at v${now.version}; pull again.`, "studio-moved");
62816
63283
  say(`${studioName(id2)} would push v${version2 + 1}.`);
62817
63284
  return { id: studioName(id2), version: version2 + 1, changed: true, dryRun: true };
@@ -62822,27 +63289,36 @@ function noteText({ file: file2, text: text5 }) {
62822
63289
  if (file2 !== void 0 && text5 !== void 0) die("pass --file or --text, not both", "bad-args");
62823
63290
  if (file2 !== void 0) {
62824
63291
  try {
62825
- return fs74.readFileSync(file2, "utf8").trim();
63292
+ return fs75.readFileSync(file2, "utf8").trim();
62826
63293
  } catch {
62827
63294
  die(`can't read ${file2}`, "bad-args");
62828
63295
  }
62829
63296
  }
62830
63297
  return text5?.trim();
62831
63298
  }
62832
- function cloudOk(res) {
62833
- if (!res.ok) die(res.error, res.code === "unauthenticated" ? "needs-cloud" : "cloud-refused");
63299
+ function cloudOk(res, kind) {
63300
+ if (!res.ok) throw cloudError({
63301
+ code: res.code ?? "unreachable",
63302
+ message: res.error,
63303
+ status: res.status,
63304
+ retryable: res.retryable ?? temporaryCloudFailure(res)
63305
+ }, { kind });
62834
63306
  return res.value;
62835
63307
  }
62836
63308
  async function cloudScope() {
62837
63309
  const project2 = boardProject();
62838
63310
  if (!project2) die("This board is not linked to a Cloud project.", "needs-cloud");
62839
63311
  const held4 = cloudOk(await call("GET", `/v1/projects/${enc2(project2)}`));
62840
- return { project: project2, workspace: held4.workspace };
63312
+ return { project: project2, workspace: requireResponse(held4, "the Studio workspace", (value) => hasText(value.workspace)).workspace };
62841
63313
  }
62842
63314
  async function cmdStudioRule(name, opts) {
62843
63315
  const rule = noteText(opts);
62844
63316
  const { workspace: workspace2 } = await cloudScope();
62845
- const held4 = cloudOk(await call("GET", `/v1/workspaces/${enc2(workspace2)}/studio-rules`));
63317
+ const held4 = requireResponse(
63318
+ cloudOk(await call("GET", `/v1/workspaces/${enc2(workspace2)}/studio-rules`)),
63319
+ "the workspace\u2019s Studio rules",
63320
+ (value) => Array.isArray(value.studios)
63321
+ );
62846
63322
  const flow = held4.studios.find((w) => studioName(w.id) === name);
62847
63323
  if (!flow) {
62848
63324
  die(`no studio called "${name}" here. There are: ${held4.studios.map((w) => studioName(w.id)).join(", ")}.`, {
@@ -62855,7 +63331,11 @@ async function cmdStudioRule(name, opts) {
62855
63331
  say(now || `${name} has no rules`);
62856
63332
  return { studio: name, rule: now };
62857
63333
  }
62858
- cloudOk(await call("PUT", `/v1/workspaces/${enc2(workspace2)}/studios/${enc2(flow.id)}/rule`, { rule }));
63334
+ requireResponse(
63335
+ cloudOk(await call("PUT", `/v1/workspaces/${enc2(workspace2)}/studios/${enc2(flow.id)}/rule`, { rule })),
63336
+ "the saved Studio rules",
63337
+ (value) => value.id === flow.id && value.rule === rule
63338
+ );
62859
63339
  say(`${rule ? "saved" : "cleared"} the rules of ${name}`);
62860
63340
  return { studio: name, rule };
62861
63341
  }
@@ -62863,7 +63343,11 @@ async function cmdStudioInstructions(agent, opts) {
62863
63343
  const rule = noteText(opts);
62864
63344
  const project2 = boardProject();
62865
63345
  if (!project2) die("This board is not linked to a Cloud project.", "needs-cloud");
62866
- const own2 = cloudOk(await call("GET", `/v1/projects/${enc2(project2)}/agents`));
63346
+ const own2 = requireResponse(
63347
+ cloudOk(await call("GET", `/v1/projects/${enc2(project2)}/agents`)),
63348
+ "the project\u2019s agent instructions",
63349
+ (value) => Array.isArray(value.board) && Array.isArray(value.data)
63350
+ );
62867
63351
  if (!own2.board.includes(agent)) {
62868
63352
  die(`no agent called "${agent}" here. There are: ${own2.board.join(", ")}.`, { kind: "no-such-agent", agent });
62869
63353
  }
@@ -62872,7 +63356,11 @@ async function cmdStudioInstructions(agent, opts) {
62872
63356
  say(now || `${agent} has no instructions`);
62873
63357
  return { agent, rule: now, scope: "project" };
62874
63358
  }
62875
- cloudOk(await call("PUT", `/v1/projects/${enc2(project2)}/agents/${enc2(agent)}`, { rule }));
63359
+ requireResponse(
63360
+ cloudOk(await call("PUT", `/v1/projects/${enc2(project2)}/agents/${enc2(agent)}`, { rule })),
63361
+ "the saved instructions",
63362
+ (value) => value.agent === agent && value.rule === rule
63363
+ );
62876
63364
  say(rule ? `saved ${agent}'s instructions (this project)` : `cleared ${agent}'s instructions`);
62877
63365
  return { agent, rule, scope: "project" };
62878
63366
  }
@@ -62888,6 +63376,7 @@ var init_studio3 = __esm({
62888
63376
  init_studio_files();
62889
63377
  init_board_files();
62890
63378
  init_tasks();
63379
+ init_response();
62891
63380
  found = (id2) => {
62892
63381
  const flow = studioById(id2);
62893
63382
  if (!flow) {
@@ -62986,7 +63475,12 @@ var init_progress = __esm({
62986
63475
  });
62987
63476
 
62988
63477
  // ../cli/src/lib/agent/complete.ts
62989
- import fs75 from "node:fs";
63478
+ import fs76 from "node:fs";
63479
+ function checkRecordedResult(receipt, commit, branch) {
63480
+ if (receipt.commit === commit && receipt.branch === branch) return;
63481
+ const describe4 = (hash3, target) => hash3 ? `${hash3} on ${target}` : "no Git result";
63482
+ throw new Error(`This step already recorded a different result. Recorded: ${describe4(receipt.commit, receipt.branch)}. Reported: ${describe4(commit, branch)}.`);
63483
+ }
62990
63484
  function completeDelivery(named2, result = {}) {
62991
63485
  const commit = result.commit?.toLowerCase();
62992
63486
  const branch = result.branch;
@@ -63009,13 +63503,13 @@ function completeDelivery(named2, result = {}) {
63009
63503
  const run3 = store.runs.find((r) => r.sessionId === sessionId);
63010
63504
  const current = store.runs.filter((r) => r.deliveryId === delivery2.deliveryId && ["implement", "scheduled"].includes(r.action)).pop();
63011
63505
  const liveCard = delivery2.cardId === null ? null : cardFile(delivery2.cardId);
63012
- const restored = liveCard && parseFrontmatter(fs75.readFileSync(liveCard, "utf8")).meta?.restored;
63506
+ const restored = liveCard && parseFrontmatter(fs76.readFileSync(liveCard, "utf8")).meta?.restored;
63013
63507
  if (restored && Date.parse(restored) > (run3?.startedAt ?? 0)) throw new Error("This delivery predates task restoration.");
63014
63508
  if (!run3 || run3.deliveryId !== delivery2.deliveryId) throw new Error("This run does not own the delivery.");
63015
63509
  const pending = receipts[deliveryStep(delivery2)];
63016
63510
  const previous = receipts.find((c) => c.sessionId === sessionId || c.resumedSessions?.includes(sessionId));
63017
63511
  if (previous) {
63018
- if (previous.commit !== commit || previous.branch !== branch) throw new Error("This step already recorded a different result.");
63512
+ checkRecordedResult(previous, commit, branch);
63019
63513
  if (!previous.finished && previous.step === deliveryStep(delivery2) && (delivery2.status !== "active" || run3 !== current || run3.status !== "running")) {
63020
63514
  throw new Error("Only the current owning run can finish pending completion.");
63021
63515
  }
@@ -63026,7 +63520,7 @@ function completeDelivery(named2, result = {}) {
63026
63520
  }
63027
63521
  if (answerOutcome(delivery2) === "changed") throw new Error("The approved requirements were superseded. Continue with the updated delivery.");
63028
63522
  if (pending && run3 === current) {
63029
- if (pending.commit !== commit || pending.branch !== branch) throw new Error("This step already recorded a different result.");
63523
+ checkRecordedResult(pending, commit, branch);
63030
63524
  pending.resumedSessions = [...pending.resumedSessions ?? [], sessionId];
63031
63525
  return { delivery: delivery2, receipt: pending };
63032
63526
  }
@@ -63180,16 +63674,16 @@ var init_start = __esm({
63180
63674
  });
63181
63675
 
63182
63676
  // ../cli/src/lib/agent/task-chats.ts
63183
- import fs76 from "node:fs";
63184
- import path76 from "node:path";
63677
+ import fs77 from "node:fs";
63678
+ import path77 from "node:path";
63185
63679
  function taskChatFile(task, home3) {
63186
63680
  if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
63187
- return path76.join(taskChatsDir(home3), `${task}.jsonl`);
63681
+ return path77.join(taskChatsDir(home3), `${task}.jsonl`);
63188
63682
  }
63189
63683
  function readTaskChat(task, home3) {
63190
63684
  let text5;
63191
63685
  try {
63192
- text5 = fs76.readFileSync(taskChatFile(task, home3), "utf8");
63686
+ text5 = fs77.readFileSync(taskChatFile(task, home3), "utf8");
63193
63687
  } catch {
63194
63688
  return [];
63195
63689
  }
@@ -63210,13 +63704,13 @@ var init_task_chats = __esm({
63210
63704
  "use strict";
63211
63705
  init_home();
63212
63706
  TASK = /^[\w-]{1,100}$/;
63213
- taskChatsDir = (home3 = machineHome()) => path76.join(home3, "chats");
63707
+ taskChatsDir = (home3 = machineHome()) => path77.join(home3, "chats");
63214
63708
  }
63215
63709
  });
63216
63710
 
63217
63711
  // ../cli/src/lib/agent/memory-review.ts
63218
- import fs77 from "node:fs";
63219
- import path77 from "node:path";
63712
+ import fs78 from "node:fs";
63713
+ import path78 from "node:path";
63220
63714
  function taskChatsToReview(tasks) {
63221
63715
  const out = [];
63222
63716
  for (const ref of [...new Set(tasks)]) {
@@ -63238,8 +63732,8 @@ function readArchived2(id2) {
63238
63732
  const found2 = Number.isInteger(id2) && id2 > 0 ? locateArchived(id2) : null;
63239
63733
  if (!found2) return null;
63240
63734
  try {
63241
- const file2 = found2.kind === "group" ? path77.join(found2.target, "root.md") : found2.target;
63242
- const { meta: meta3, body } = parseFrontmatter(fs77.readFileSync(file2, "utf8"));
63735
+ const file2 = found2.kind === "group" ? path78.join(found2.target, "root.md") : found2.target;
63736
+ const { meta: meta3, body } = parseFrontmatter(fs78.readFileSync(file2, "utf8"));
63243
63737
  if (!meta3) return null;
63244
63738
  return { id: id2, title: meta3.title, modules: meta3.modules ?? [], studio: meta3.studio ?? "", previews: meta3.previews ?? [], rejected: meta3.rejected, body };
63245
63739
  } catch {
@@ -63300,18 +63794,18 @@ var init_memory_review = __esm({
63300
63794
  });
63301
63795
 
63302
63796
  // ../cli/src/lib/agent/dismissal-review.ts
63303
- import fs78 from "node:fs";
63304
- import path78 from "node:path";
63797
+ import fs79 from "node:fs";
63798
+ import path79 from "node:path";
63305
63799
  function rejectionsToReview() {
63306
63800
  const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
63307
- const dir = path78.join(scratch ? path78.join(scratch, ".archive") : ARCHIVE, REJECTIONS_TO_REVIEW);
63308
- if (!fs78.existsSync(dir)) return [];
63801
+ const dir = path79.join(scratch ? path79.join(scratch, ".archive") : ARCHIVE, REJECTIONS_TO_REVIEW);
63802
+ if (!fs79.existsSync(dir)) return [];
63309
63803
  const found2 = [];
63310
63804
  for (const file2 of walkMd(dir)) {
63311
63805
  const id2 = archivedId(file2);
63312
63806
  if (id2 === null) continue;
63313
63807
  try {
63314
- const { meta: meta3 } = parseFrontmatter(fs78.readFileSync(file2, "utf8"));
63808
+ const { meta: meta3 } = parseFrontmatter(fs79.readFileSync(file2, "utf8"));
63315
63809
  if (!meta3?.rejected || meta3.rejected_by !== "user" || !meta3.rejected_reason.trim()) continue;
63316
63810
  found2.push({ id: id2, title: meta3.title, file: rel(file2), reason: meta3.rejected_reason.trim(), rejectedAt: meta3.rejected_at });
63317
63811
  } catch {
@@ -63341,7 +63835,7 @@ function citedSources(text5) {
63341
63835
  function withdrawnSources() {
63342
63836
  const cited = [...new Set(plannerCopies("rejected.md").flatMap((file2) => {
63343
63837
  try {
63344
- return citedSources(fs78.readFileSync(file2, "utf8"));
63838
+ return citedSources(fs79.readFileSync(file2, "utf8"));
63345
63839
  } catch {
63346
63840
  return [];
63347
63841
  }
@@ -63349,7 +63843,7 @@ function withdrawnSources() {
63349
63843
  if (cited.length === 0) return [];
63350
63844
  const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
63351
63845
  const dismissed = new Set(reviewDismissed().map((s) => s.sourceId));
63352
- const restored = new Set([...readInbox(), ...readArchived(scratch ? path78.join(scratch, "triage", "archived") : void 0)].map((s) => s.sourceId));
63846
+ const restored = new Set([...readInbox(), ...readArchived(scratch ? path79.join(scratch, "triage", "archived") : void 0)].map((s) => s.sourceId));
63353
63847
  return cited.filter((id2) => restored.has(id2) && !dismissed.has(id2));
63354
63848
  }
63355
63849
  var reviewDismissed, SOURCES;
@@ -63364,15 +63858,15 @@ var init_dismissal_review = __esm({
63364
63858
  init_archive();
63365
63859
  reviewDismissed = () => {
63366
63860
  const scratch = process.env.AI4KANBAN_REJECTION_INPUT;
63367
- return readAllDismissed(scratch ? path78.join(scratch, "triage", "dismissed") : void 0);
63861
+ return readAllDismissed(scratch ? path79.join(scratch, "triage", "dismissed") : void 0);
63368
63862
  };
63369
63863
  SOURCES = /\(([^()]+)\)\s*$/;
63370
63864
  }
63371
63865
  });
63372
63866
 
63373
63867
  // ../cli/src/lib/agent/flow.ts
63374
- import fs79 from "node:fs";
63375
- import path79 from "node:path";
63868
+ import fs80 from "node:fs";
63869
+ import path80 from "node:path";
63376
63870
  function readCard2(id2, home3 = "board") {
63377
63871
  const pending = activeDelivery(id2)?.completions?.some((c) => !c.finished);
63378
63872
  const found2 = home3 === "archive" ? locateArchived(id2) : locate(id2) ?? (pending ? locateArchived(id2) : null);
@@ -63382,10 +63876,10 @@ function readCard2(id2, home3 = "board") {
63382
63876
  { kind: "card-not-found", id: id2 }
63383
63877
  );
63384
63878
  }
63385
- const file2 = found2.kind === "group" ? path79.join(found2.target, "root.md") : found2.target;
63879
+ const file2 = found2.kind === "group" ? path80.join(found2.target, "root.md") : found2.target;
63386
63880
  let text5;
63387
63881
  try {
63388
- text5 = fs79.readFileSync(file2, "utf8");
63882
+ text5 = fs80.readFileSync(file2, "utf8");
63389
63883
  } catch {
63390
63884
  die(`#${id2} is on the board but ${rel(file2)} can't be read.`, { kind: "card-unreadable", id: id2 });
63391
63885
  }
@@ -64039,14 +64533,33 @@ var init_coding_previews = __esm({
64039
64533
  });
64040
64534
 
64041
64535
  // ../cli/src/lib/agent/approved-ui.ts
64042
- import path80 from "node:path";
64536
+ import path81 from "node:path";
64537
+ function approvedUiSource(pins, src, owner) {
64538
+ const [ref] = splitFileReference(src);
64539
+ if (artifactId.test(ref)) {
64540
+ const version2 = approvedUiPin(pins, ref).version;
64541
+ const names2 = Object.keys(pins).filter((name) => {
64542
+ const pin = approvedUiPin(pins, name);
64543
+ return pin.artifact === ref && (version2 === void 0 || pin.version === version2);
64544
+ });
64545
+ return names2.find((name) => !artifactId.test(name)) ?? names2[0] ?? ref;
64546
+ }
64547
+ const local = owner && !ref.startsWith(".assets/") ? relativeFileReference(ref, owner) : ref;
64548
+ return [local, src, ref, path81.posix.normalize(local)].find((key) => Object.hasOwn(pins, key)) ?? local;
64549
+ }
64550
+ function approvedUiPin(pins, source2) {
64551
+ return object2(Object.hasOwn(pins, source2) ? pins[source2] : void 0);
64552
+ }
64553
+ function validUiPin(pin) {
64554
+ return !pin.error && pin.status !== "pending" && pin.status !== "failed" && typeof pin.artifact === "string" && artifactId.test(pin.artifact) && typeof pin.version === "number" && Number.isSafeInteger(pin.version) && pin.version > 0;
64555
+ }
64043
64556
  function approvedUiPreviews(review) {
64044
64557
  if (reviewAuthorization(review).kind !== "delivery") return [];
64045
64558
  const result = [];
64046
- for (const node2 of review.plan ?? []) {
64559
+ for (const [index, node2] of (review.plan ?? []).entries()) {
64047
64560
  const stage = review.stages.find((stage2) => stage2.id === node2.id);
64048
64561
  const snapshot2 = stage?.snapshot;
64049
- if (!stage || !snapshot2) continue;
64562
+ if (node2.kind === "work" || !stage || !snapshot2) continue;
64050
64563
  const evidence = object2(snapshot2.evidence);
64051
64564
  const content = object2(evidence.content);
64052
64565
  const frozenPreviews = Array.isArray(snapshot2.previews) ? snapshot2.previews.filter(isObject2) : [];
@@ -64054,17 +64567,17 @@ function approvedUiPreviews(review) {
64054
64567
  const preview = object2(content[id2]);
64055
64568
  const body = typeof preview.body === "string" ? preview.body : typeof snapshot2.body === "string" ? parsePreviewBlocks(snapshot2.body).blocks.find((block) => block.id === id2)?.instructions : void 0;
64056
64569
  if (!body) continue;
64057
- const pins = { ...object2(frozenPreviews.find((preview2) => preview2.id === id2)?.assets), ...object2(evidence.assets) };
64570
+ const pins = { ...object2(evidence.dependencies), ...object2(frozenPreviews.find((preview2) => preview2.id === id2)?.assets), ...object2(evidence.assets) };
64058
64571
  const files = /* @__PURE__ */ new Map();
64059
- const add2 = (src, label2, device) => {
64060
- const pin = object2(pins[src]);
64061
- const { artifact, version: version2 } = pin;
64062
- if (typeof artifact !== "string" || !/^art_[a-z0-9]+$/i.test(artifact) || typeof version2 !== "number" || !Number.isSafeInteger(version2) || version2 < 1) return;
64063
- const name = label2.trim() || path80.posix.basename(src);
64572
+ const add2 = (src, label2, device, required2 = true) => {
64573
+ if (external.test(src)) return;
64574
+ const source2 = approvedUiSource(pins, src);
64575
+ if (!required2 && !Object.hasOwn(pins, source2) && !/\.(?:html?|tsx)$/i.test(source2)) return;
64576
+ const name = label2.trim() || path81.posix.basename(src);
64064
64577
  const key = JSON.stringify([src, name]);
64065
64578
  let file2 = files.get(key);
64066
64579
  if (!file2) {
64067
- file2 = { src, artifact, version: version2, revision: stage.revision, label: name, devices: /* @__PURE__ */ new Set() };
64580
+ file2 = { src, source: source2, label: name, devices: /* @__PURE__ */ new Set() };
64068
64581
  files.set(key, file2);
64069
64582
  }
64070
64583
  file2.devices.add(device === "mobile" ? "Mobile" : device === "desktop" ? "Desktop" : "Device unspecified");
@@ -64084,33 +64597,53 @@ function approvedUiPreviews(review) {
64084
64597
  }
64085
64598
  }
64086
64599
  const listed = new Set([...files.values()].map((file2) => file2.src));
64087
- for (const src of bodySources(body)) if (!listed.has(src)) add2(src, "");
64088
- result.push(...files.values());
64600
+ for (const src of bodySources(body)) if (!listed.has(src)) add2(src, "", void 0, false);
64601
+ if (files.size) result.push({
64602
+ id: id2,
64603
+ revision: stage.revision,
64604
+ directory: `review-${stage.revision}-${index}/${id2}`,
64605
+ body,
64606
+ pins,
64607
+ files: [...files.values()]
64608
+ });
64089
64609
  }
64090
64610
  }
64091
64611
  return result;
64092
64612
  }
64093
- function approvedUiFile(directory, file2) {
64094
- const ext = path80.posix.extname(file2.src).toLowerCase();
64095
- const suffix = ext === ".tsx" ? ".html" : /^\.[a-z0-9]+$/.test(ext) ? ext : "";
64096
- return path80.join(directory, `${file2.artifact}-${file2.version}${suffix}`);
64097
- }
64098
- function approvedUiPrompt(review, directory) {
64099
- const files = approvedUiPreviews(review);
64100
- if (!files.length) return "";
64613
+ function approvedUiFile(directory, preview, source2) {
64614
+ const parts = path81.posix.normalize(splitFileReference(source2)[0]).split("/");
64615
+ let parents = 0;
64616
+ while (parts[0] === "..") {
64617
+ parts.shift();
64618
+ parents++;
64619
+ }
64620
+ const rendered = /\.tsx$/i.test(parts.at(-1) ?? "");
64621
+ if (rendered) parts[parts.length - 1] = parts.at(-1).replace(/\.tsx$/i, ".html");
64622
+ const safe2 = parts.map((part) => !part || part === "." ? "%00" : part.replace(/[\\:*?"<>|%\x00-\x1f]/g, (char) => `%${char.charCodeAt(0).toString(16).padStart(2, "0")}`));
64623
+ return path81.join(directory, preview.directory, `${rendered ? "rendered" : "files"}-${parents}`, ...safe2);
64624
+ }
64625
+ function approvedUiPrompt(review, directory, includeBody = false) {
64626
+ const previews = approvedUiPreviews(review);
64627
+ if (!previews.length) return "";
64101
64628
  return [
64102
64629
  "Approved UI previews",
64103
64630
  APPROVED_UI_RULE,
64104
- files.map((file2) => {
64105
- const ref = directory ? `frozen file: \`${approvedUiFile(directory, file2)}\`` : `artifact ${file2.artifact}, version ${file2.version}`;
64106
- return `- ${file2.label} \xB7 ${[...file2.devices].join(" / ")} \xB7 Review revision ${file2.revision} \xB7 ${file2.src} \xB7 ${ref}`;
64107
- }).join("\n")
64631
+ ...previews.flatMap((preview) => [
64632
+ ...includeBody ? [preview.body] : [],
64633
+ preview.files.flatMap((file2) => {
64634
+ const pin = approvedUiPin(preview.pins, file2.source);
64635
+ if (!validUiPin(pin)) return [];
64636
+ const ref = directory ? `frozen file: \`${approvedUiFile(directory, preview, file2.source)}\`` : `artifact ${pin.artifact}, version ${pin.version}`;
64637
+ return [`- ${file2.label} \xB7 ${[...file2.devices].join(" / ")} \xB7 Review revision ${preview.revision} \xB7 ${file2.src} \xB7 ${ref}`];
64638
+ }).join("\n")
64639
+ ])
64108
64640
  ].join("\n\n");
64109
64641
  }
64110
- var APPROVED_UI_DIR_ENV, APPROVED_UI_RULE, UI_PREVIEW, historicalUiIds, object2;
64642
+ var APPROVED_UI_DIR_ENV, APPROVED_UI_RULE, UI_PREVIEW, historicalUiIds, object2, artifactId, external;
64111
64643
  var init_approved_ui = __esm({
64112
64644
  "../cli/src/lib/agent/approved-ui.ts"() {
64113
64645
  "use strict";
64646
+ init_file_references();
64114
64647
  init_references();
64115
64648
  init_tags();
64116
64649
  init_coding_previews();
@@ -64121,6 +64654,8 @@ var init_approved_ui = __esm({
64121
64654
  UI_PREVIEW = "ui-design";
64122
64655
  historicalUiIds = Object.keys(CODING_PREVIEWS).filter((id2) => id2 !== UI_PREVIEW && CODING_PREVIEWS[id2] === UI_PREVIEW);
64123
64656
  object2 = (value) => isObject2(value) ? value : {};
64657
+ artifactId = /^art_[a-z0-9]+$/i;
64658
+ external = /^(?:[a-z][\w+.-]*:|\/|#)/i;
64124
64659
  }
64125
64660
  });
64126
64661
 
@@ -64189,7 +64724,7 @@ __export(watch_exports, {
64189
64724
  watchRun: () => watchRun
64190
64725
  });
64191
64726
  import { spawn as spawn3 } from "node:child_process";
64192
- import fs80 from "node:fs";
64727
+ import fs81 from "node:fs";
64193
64728
  async function watchRun(sessionId, resume = startResume, retryBackoff = backoffMs) {
64194
64729
  const spec = readSpec(sessionId);
64195
64730
  const run3 = peekRun(sessionId);
@@ -64225,11 +64760,11 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64225
64760
  const record2 = claimed ?? run3;
64226
64761
  const sub = record2.action === "sub";
64227
64762
  if (claim2) await setCardStatus(claim2.cardId, claim2.status);
64228
- fs80.mkdirSync(SESSIONS_DIR, { recursive: true });
64229
- const logFile = fs80.createWriteStream(record2.logPath, { flags: "a" });
64763
+ fs81.mkdirSync(SESSIONS_DIR, { recursive: true });
64764
+ const logFile = fs81.createWriteStream(record2.logPath, { flags: "a" });
64230
64765
  logFile.on("error", () => {
64231
64766
  });
64232
- const eventsFile = fs80.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
64767
+ const eventsFile = fs81.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
64233
64768
  eventsFile.on("error", () => {
64234
64769
  });
64235
64770
  let observeActivity = (_e) => {
@@ -64276,11 +64811,13 @@ async function watchRun(sessionId, resume = startResume, retryBackoff = backoffM
64276
64811
  const review = reviewContext?.review;
64277
64812
  const boundary = review && reviewBoundary(savedPreviews ? { ...review, stages: review.stages.map((stage) => ({ ...stage, snapshot: null })) } : review, reviewContext.assigned);
64278
64813
  const coding = record2.action === "implement" && studioForRun({ id: record2.cardId ?? void 0, deliveryId: record2.deliveryId }) === "coding";
64279
- const previewPrompt = savedPreviews ? [
64814
+ const uiDirectory = process.env[APPROVED_UI_DIR_ENV];
64815
+ const approvedUi = review && coding && (!savedPreviews || uiDirectory) ? approvedUiPrompt(review, uiDirectory, !!savedPreviews) : "";
64816
+ const savedPrompt = savedPreviews ? [
64280
64817
  `Read the saved task Previews and their pinned files in \`${savedPreviews}\`. Use these saved versions for the requirements they cover and verify the delivery against them.`,
64281
- ...coding && review?.plan?.some((node2) => node2.previews.includes("ui-design")) ? [APPROVED_UI_RULE] : []
64282
- ].join("\n") : review && coding ? approvedUiPrompt(review, process.env[APPROVED_UI_DIR_ENV]) : "";
64283
- const prompt = [process.env.AI4KANBAN_SYNC_DIAGNOSTIC ? syncRepairPrompt(process.env.AI4KANBAN_SYNC_DIAGNOSTIC) : "", record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, resumedStudio, previewPrompt, recoveryPrompt2, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
64818
+ ...coding && !approvedUi && review?.plan?.some((node2) => node2.previews.includes("ui-design")) ? [APPROVED_UI_RULE] : []
64819
+ ].join("\n") : "";
64820
+ const prompt = [process.env.AI4KANBAN_SYNC_DIAGNOSTIC ? syncRepairPrompt(process.env.AI4KANBAN_SYNC_DIAGNOSTIC) : "", record2.retry ? `Previous execution failed: ${record2.retry.reason}. Check existing results before continuing; do not repeat completed operations.` : "", conflictPrompt(KANBAN), boundary, basePrompt, resumedStudio, savedPrompt, approvedUi, recoveryPrompt2, discardedCardsPrompt(record2.discardedCards)].filter(Boolean).join("\n\n");
64284
64821
  const before = markBoard();
64285
64822
  const takes = active3.images;
64286
64823
  active3.renderer?.setRequiredImages?.(record2.pictures ?? []);
@@ -64805,8 +65342,8 @@ var init_watch = __esm({
64805
65342
  });
64806
65343
 
64807
65344
  // ../cli/src/commands/run.ts
64808
- import fs81 from "node:fs";
64809
- import path81 from "node:path";
65345
+ import fs82 from "node:fs";
65346
+ import path82 from "node:path";
64810
65347
  async function cmdStartRun(action, args2, opts, program2 = "akb") {
64811
65348
  const { req, follow: follow2, print } = readRequest(action, args2, opts);
64812
65349
  if (!print && (action === "approve" || action === "implement")) {
@@ -65032,7 +65569,7 @@ async function cmdSubStart(words, opts) {
65032
65569
  let prompt = words.join(" ");
65033
65570
  if (opts.file) {
65034
65571
  try {
65035
- prompt = fs81.readFileSync(path81.resolve(opts.file), "utf8");
65572
+ prompt = fs82.readFileSync(path82.resolve(opts.file), "utf8");
65036
65573
  } catch {
65037
65574
  die(`--file: cannot read ${opts.file}`, { kind: "run-refused" });
65038
65575
  }
@@ -65381,12 +65918,12 @@ var init_config3 = __esm({
65381
65918
  });
65382
65919
 
65383
65920
  // ../cli/src/lib/signals/migrate.ts
65384
- import fs82 from "node:fs";
65385
- import path82 from "node:path";
65921
+ import fs83 from "node:fs";
65922
+ import path83 from "node:path";
65386
65923
  function readHandled() {
65387
65924
  let text5;
65388
65925
  try {
65389
- text5 = fs82.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
65926
+ text5 = fs83.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
65390
65927
  } catch {
65391
65928
  return [];
65392
65929
  }
@@ -65403,57 +65940,57 @@ function readHandled() {
65403
65940
  return held4;
65404
65941
  }
65405
65942
  function lift(from, into) {
65406
- fs82.mkdirSync(into, { recursive: true });
65407
- fs82.renameSync(from, path82.join(into, freeName(into, path82.basename(from))));
65943
+ fs83.mkdirSync(into, { recursive: true });
65944
+ fs83.renameSync(from, path83.join(into, freeName(into, path83.basename(from))));
65408
65945
  }
65409
65946
  function repoint(dir, from, into) {
65410
- let entries;
65947
+ let entries2;
65411
65948
  try {
65412
- entries = fs82.readdirSync(dir, { withFileTypes: true });
65949
+ entries2 = fs83.readdirSync(dir, { withFileTypes: true });
65413
65950
  } catch {
65414
65951
  return;
65415
65952
  }
65416
- for (const entry of entries) {
65953
+ for (const entry of entries2) {
65417
65954
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
65418
- const file2 = path82.join(dir, entry.name);
65419
- const text5 = fs82.readFileSync(file2, "utf8");
65420
- if (text5.includes(from)) fs82.writeFileSync(file2, text5.split(from).join(into));
65955
+ const file2 = path83.join(dir, entry.name);
65956
+ const text5 = fs83.readFileSync(file2, "utf8");
65957
+ if (text5.includes(from)) fs83.writeFileSync(file2, text5.split(from).join(into));
65421
65958
  }
65422
65959
  }
65423
65960
  function dropIfEmpty(dir) {
65424
65961
  try {
65425
- fs82.rmdirSync(dir);
65962
+ fs83.rmdirSync(dir);
65426
65963
  } catch {
65427
65964
  }
65428
65965
  }
65429
65966
  function liftInbox() {
65430
- if (!fs82.existsSync(SIGNALS_OLD_INBOX)) return;
65431
- const oldFiles = path82.join(SIGNALS_OLD_INBOX, "files");
65432
- if (fs82.existsSync(oldFiles)) {
65433
- for (const entry of fs82.readdirSync(oldFiles, { withFileTypes: true })) {
65434
- if (entry.isFile()) lift(path82.join(oldFiles, entry.name), SIGNALS_FILES);
65967
+ if (!fs83.existsSync(SIGNALS_OLD_INBOX)) return;
65968
+ const oldFiles = path83.join(SIGNALS_OLD_INBOX, "files");
65969
+ if (fs83.existsSync(oldFiles)) {
65970
+ for (const entry of fs83.readdirSync(oldFiles, { withFileTypes: true })) {
65971
+ if (entry.isFile()) lift(path83.join(oldFiles, entry.name), SIGNALS_FILES);
65435
65972
  }
65436
65973
  dropIfEmpty(oldFiles);
65437
65974
  }
65438
65975
  const held4 = new Set(readFolder(TRIAGE).map((signal2) => signal2.sourceId));
65439
- for (const entry of fs82.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
65976
+ for (const entry of fs83.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
65440
65977
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
65441
- const from = path82.join(SIGNALS_OLD_INBOX, entry.name);
65978
+ const from = path83.join(SIGNALS_OLD_INBOX, entry.name);
65442
65979
  const item = parse3(from);
65443
65980
  if (item && held4.has(item.sourceId)) {
65444
- fs82.rmSync(from, { force: true });
65981
+ fs83.rmSync(from, { force: true });
65445
65982
  continue;
65446
65983
  }
65447
65984
  if (item) held4.add(item.sourceId);
65448
65985
  lift(from, TRIAGE);
65449
65986
  }
65450
- const wasAt = asWritten(path82.join(SIGNALS_OLD_INBOX, "files"));
65987
+ const wasAt = asWritten(path83.join(SIGNALS_OLD_INBOX, "files"));
65451
65988
  const nowAt = asWritten(SIGNALS_FILES);
65452
65989
  for (const dir of [TRIAGE, SIGNALS_ARCHIVED, SIGNALS_DISMISSED]) repoint(dir, wasAt, nowAt);
65453
65990
  dropIfEmpty(SIGNALS_OLD_INBOX);
65454
65991
  }
65455
65992
  function liftHandled() {
65456
- if (!fs82.existsSync(SIGNALS_OLD_HANDLED)) return;
65993
+ if (!fs83.existsSync(SIGNALS_OLD_HANDLED)) return;
65457
65994
  const lines = readHandled();
65458
65995
  const held4 = /* @__PURE__ */ new Set([
65459
65996
  ...readFolder(TRIAGE).map((signal2) => signal2.sourceId),
@@ -65463,7 +66000,7 @@ function liftHandled() {
65463
66000
  for (const { sourceId, when } of lines) {
65464
66001
  if (held4.has(sourceId)) continue;
65465
66002
  held4.add(sourceId);
65466
- fs82.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
66003
+ fs83.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
65467
66004
  const name = freeName(SIGNALS_DISMISSED, fileName("", sourceId));
65468
66005
  const front = [
65469
66006
  "---",
@@ -65473,13 +66010,13 @@ function liftHandled() {
65473
66010
  "---",
65474
66011
  ""
65475
66012
  ];
65476
- fs82.writeFileSync(path82.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
66013
+ fs83.writeFileSync(path83.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
65477
66014
  `);
65478
66015
  }
65479
- fs82.rmSync(SIGNALS_OLD_HANDLED, { force: true });
66016
+ fs83.rmSync(SIGNALS_OLD_HANDLED, { force: true });
65480
66017
  }
65481
66018
  function migrateTriage() {
65482
- if (!fs82.existsSync(SIGNALS_OLD_INBOX) && !fs82.existsSync(SIGNALS_OLD_HANDLED)) return;
66019
+ if (!fs83.existsSync(SIGNALS_OLD_INBOX) && !fs83.existsSync(SIGNALS_OLD_HANDLED)) return;
65483
66020
  try {
65484
66021
  liftInbox();
65485
66022
  liftHandled();
@@ -65494,7 +66031,7 @@ var init_migrate = __esm({
65494
66031
  init_yaml();
65495
66032
  init_inbox();
65496
66033
  HANDLED_LINE = /^-\s+(.+?)\s+—\s+(.+)$/;
65497
- asWritten = (dir) => `${rel(dir).split(path82.sep).join("/")}/`;
66034
+ asWritten = (dir) => `${rel(dir).split(path83.sep).join("/")}/`;
65498
66035
  }
65499
66036
  });
65500
66037
 
@@ -65547,8 +66084,8 @@ var init_identity2 = __esm({
65547
66084
  });
65548
66085
 
65549
66086
  // ../cli/src/lib/signals/add.ts
65550
- import fs83 from "node:fs";
65551
- import path83 from "node:path";
66087
+ import fs84 from "node:fs";
66088
+ import path84 from "node:path";
65552
66089
  import { createHash as createHash8 } from "node:crypto";
65553
66090
  function linkTitle(url2) {
65554
66091
  let at;
@@ -65561,7 +66098,7 @@ function linkTitle(url2) {
65561
66098
  return oneLine(where) || url2.slice(0, TITLE_MAX);
65562
66099
  }
65563
66100
  function asText(file2) {
65564
- const ext = path83.extname(file2.name).toLowerCase();
66101
+ const ext = path84.extname(file2.name).toLowerCase();
65565
66102
  if (!file2.type.startsWith("text/") && file2.type !== "application/json" && !TEXT_EXTENSIONS.has(ext)) return null;
65566
66103
  try {
65567
66104
  const text5 = new TextDecoder("utf-8", { fatal: true }).decode(file2.data);
@@ -65571,9 +66108,9 @@ function asText(file2) {
65571
66108
  }
65572
66109
  }
65573
66110
  function fileName2(name, data) {
65574
- const base = path83.basename(name);
65575
- const ext = path83.extname(base).toLowerCase().slice(0, 12);
65576
- const word = path83.basename(base, path83.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
66111
+ const base = path84.basename(name);
66112
+ const ext = path84.extname(base).toLowerCase().slice(0, 12);
66113
+ const word = path84.basename(base, path84.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
65577
66114
  const hash3 = createHash8("sha256").update(data).digest("hex").slice(0, 8);
65578
66115
  return `${word}-${hash3}${ext}`;
65579
66116
  }
@@ -65582,9 +66119,9 @@ function addToInbox(drop) {
65582
66119
  const typed = (drop.text ?? "").trim();
65583
66120
  const file2 = drop.file;
65584
66121
  if (!typed && !file2) return { ok: false, error: "nothing to add \u2014 paste a link or some text, or drop a file." };
65585
- if (file2 && file2.data.length === 0) return { ok: false, error: `${path83.basename(file2.name)} is empty.` };
66122
+ if (file2 && file2.data.length === 0) return { ok: false, error: `${path84.basename(file2.name)} is empty.` };
65586
66123
  if (file2 && file2.data.length > MAX_BYTES3) {
65587
- return { ok: false, error: `${path83.basename(file2.name)} is over ${MAX_BYTES3 / 1024 / 1024} MB \u2014 too big for the board.` };
66124
+ return { ok: false, error: `${path84.basename(file2.name)} is over ${MAX_BYTES3 / 1024 / 1024} MB \u2014 too big for the board.` };
65588
66125
  }
65589
66126
  const read5 = describe3(typed, file2);
65590
66127
  const keep2 = read5.keep;
@@ -65606,8 +66143,8 @@ ${incoming.summary}`);
65606
66143
  if (seen.status === "pending" || seen.status === "archived") return { ok: false, error: `${sayHit(seen)}.` };
65607
66144
  try {
65608
66145
  if (keep2) {
65609
- fs83.mkdirSync(SIGNALS_FILES, { recursive: true });
65610
- fs83.writeFileSync(keep2.at, keep2.data);
66146
+ fs84.mkdirSync(SIGNALS_FILES, { recursive: true });
66147
+ fs84.writeFileSync(keep2.at, keep2.data);
65611
66148
  }
65612
66149
  return { ok: true, signal: writeSignal({ ...incoming, sourceId }, formatStamp(/* @__PURE__ */ new Date()), drop.slug) };
65613
66150
  } catch (e) {
@@ -65621,7 +66158,7 @@ function describe3(typed, file2) {
65621
66158
  return only ? [only] : [];
65622
66159
  };
65623
66160
  if (file2) {
65624
- const name = path83.basename(file2.name);
66161
+ const name = path84.basename(file2.name);
65625
66162
  const text5 = asText(file2);
65626
66163
  const note = typed ? `
65627
66164
 
@@ -65633,7 +66170,7 @@ ${typed}` : "";
65633
66170
  const at = keepAt(file2);
65634
66171
  return {
65635
66172
  incoming: {
65636
- title: path83.basename(name, path83.extname(name)) || name,
66173
+ title: path84.basename(name, path84.extname(name)) || name,
65637
66174
  summary: `${name} \u2014 ${boardRel2(at)}${note}`,
65638
66175
  ...named2
65639
66176
  },
@@ -65671,13 +66208,13 @@ var init_add = __esm({
65671
66208
  MAX_BYTES3 = 25 * 1024 * 1024;
65672
66209
  TITLE_MAX = 120;
65673
66210
  TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".txt", ".text", ".csv", ".json", ".yml", ".yaml", ".log"]);
65674
- boardRel2 = (file2) => rel(file2).split(path83.sep).join("/");
66211
+ boardRel2 = (file2) => rel(file2).split(path84.sep).join("/");
65675
66212
  oneLine = (text5) => {
65676
66213
  const first = text5.split("\n").find((line) => line.trim()) ?? "";
65677
66214
  const clean = first.replace(/^#+\s*/, "").trim();
65678
66215
  return clean.length > TITLE_MAX ? `${clean.slice(0, TITLE_MAX - 1).trimEnd()}\u2026` : clean;
65679
66216
  };
65680
- keepAt = (file2) => path83.join(SIGNALS_FILES, fileName2(file2.name, file2.data));
66217
+ keepAt = (file2) => path84.join(SIGNALS_FILES, fileName2(file2.name, file2.data));
65681
66218
  }
65682
66219
  });
65683
66220
 
@@ -65718,7 +66255,7 @@ var init_signals = __esm({
65718
66255
  });
65719
66256
 
65720
66257
  // ../cli/src/commands/triage.ts
65721
- import fs84 from "node:fs";
66258
+ import fs85 from "node:fs";
65722
66259
  async function cmdTriageAdd(opts) {
65723
66260
  const title = (opts.title ?? "").trim();
65724
66261
  if (!title) die('say what it is: --title "<one line>"', { kind: "needs-input" });
@@ -65728,7 +66265,7 @@ async function cmdTriageAdd(opts) {
65728
66265
  let body = opts.text;
65729
66266
  if (opts.file !== void 0) {
65730
66267
  try {
65731
- body = fs84.readFileSync(opts.file, "utf8");
66268
+ body = fs85.readFileSync(opts.file, "utf8");
65732
66269
  } catch {
65733
66270
  die(`can't read ${opts.file} \u2014 write the item to a file, then pass its path`, { kind: "needs-input" });
65734
66271
  }
@@ -65782,21 +66319,21 @@ var init_previews = __esm({
65782
66319
  });
65783
66320
 
65784
66321
  // ../cli/src/commands/studio-preview.ts
65785
- import fs85 from "node:fs";
65786
- import path84 from "node:path";
66322
+ import fs86 from "node:fs";
66323
+ import path85 from "node:path";
65787
66324
  import { createHash as createHash9, randomUUID as randomUUID9 } from "node:crypto";
65788
66325
  import { spawnSync as spawnSync7 } from "node:child_process";
65789
66326
  function readFolder2(folder2, baseline = false) {
65790
- const root2 = fs85.realpathSync(folder2);
66327
+ const root2 = fs86.realpathSync(folder2);
65791
66328
  let count3 = 0, total = 0;
65792
66329
  const scan = (dir) => {
65793
- for (const e of fs85.readdirSync(dir, { withFileTypes: true })) {
66330
+ for (const e of fs86.readdirSync(dir, { withFileTypes: true })) {
65794
66331
  if (e.name.startsWith(".")) continue;
65795
- const file2 = path84.join(dir, e.name);
66332
+ const file2 = path85.join(dir, e.name);
65796
66333
  if (e.isSymbolicLink()) throw Error(`${file2}: symbolic links are not allowed`);
65797
66334
  if (e.isDirectory()) scan(file2);
65798
66335
  else {
65799
- const size = fs85.statSync(file2).size;
66336
+ const size = fs86.statSync(file2).size;
65800
66337
  total += size;
65801
66338
  if (++count3 > FILE_LIMITS.count || size > FILE_LIMITS.file || total > FILE_LIMITS.total) throw Error(`${file2}: Studio file limit exceeded`);
65802
66339
  }
@@ -65809,9 +66346,9 @@ function readFolder2(folder2, baseline = false) {
65809
66346
  return { files, def: checked.def, fingerprint };
65810
66347
  }
65811
66348
  function unified(before, after2, file2, folder2) {
65812
- const a = path84.join(folder2, "a"), b = path84.join(folder2, "b");
65813
- fs85.writeFileSync(a, before ?? "");
65814
- fs85.writeFileSync(b, after2 ?? "");
66349
+ const a = path85.join(folder2, "a"), b = path85.join(folder2, "b");
66350
+ fs86.writeFileSync(a, before ?? "");
66351
+ fs86.writeFileSync(b, after2 ?? "");
65815
66352
  const result = spawnSync7("git", ["diff", "--no-index", "--text", "--no-ext-diff", "--no-color", "--unified=3", before === null ? "/dev/null" : a, after2 === null ? "/dev/null" : b], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
65816
66353
  if (result.error || result.status !== 0 && result.status !== 1) throw Error(`${file2}: ${result.error?.message ?? result.stderr}`);
65817
66354
  const lines = result.stdout.split("\n"), start = lines.findIndex((l) => l.startsWith("--- "));
@@ -65821,18 +66358,18 @@ ${start < 0 ? "" : lines.slice(start + 2).join("\n")}`;
65821
66358
  }
65822
66359
  async function cmdStudioPreview(id2, opts) {
65823
66360
  if (!locate(id2)) die(`no card ${id2}`, "no-such-card");
65824
- const destination = path84.join(ASSETS, String(id2), "studio-review"), staging = `${destination}.${randomUUID9()}.tmp`, backup = `${destination}.${randomUUID9()}.previous`;
66361
+ const destination = path85.join(ASSETS, String(id2), "studio-review"), staging = `${destination}.${randomUUID9()}.tmp`, backup = `${destination}.${randomUUID9()}.previous`;
65825
66362
  let moved = false;
65826
66363
  try {
65827
- const draft = readFolder2(path84.resolve(opts.folder)), base = opts.base === "empty" ? null : readFolder2(path84.resolve(opts.base), true);
66364
+ const draft = readFolder2(path85.resolve(opts.folder)), base = opts.base === "empty" ? null : readFolder2(path85.resolve(opts.base), true);
65828
66365
  const version2 = readVersion2(draft.files), baseVersion = base && readVersion2(base.files);
65829
66366
  if (base ? !version2 || !baseVersion || JSON.stringify(version2) !== JSON.stringify(baseVersion) : version2 !== null) throw Error("version.json: existing Studios need matching baseline and draft versions; use --base empty only for a new Studio without version.json");
65830
- fs85.mkdirSync(staging, { recursive: true });
66367
+ fs86.mkdirSync(staging, { recursive: true });
65831
66368
  const review = { version: 2, base: base && baseVersion ? { ...baseVersion, fingerprint: base.fingerprint } : null, fingerprint: draft.fingerprint, files: [] };
65832
66369
  const save3 = (file2, bytes2) => {
65833
- const target = path84.join(staging, file2);
65834
- fs85.mkdirSync(path84.dirname(target), { recursive: true });
65835
- fs85.writeFileSync(target, bytes2);
66370
+ const target = path85.join(staging, file2);
66371
+ fs86.mkdirSync(path85.dirname(target), { recursive: true });
66372
+ fs86.writeFileSync(target, bytes2);
65836
66373
  return file2;
65837
66374
  };
65838
66375
  const paths = [.../* @__PURE__ */ new Set([...Object.keys(base?.files ?? {}), ...Object.keys(draft.files)])].filter((p) => p !== VERSION_FILE).sort();
@@ -65840,16 +66377,16 @@ async function cmdStudioPreview(id2, opts) {
65840
66377
  const before = base?.files[file2] ?? null, after2 = draft.files[file2] ?? null;
65841
66378
  review.files.push({ path: file2, before: before === null ? null : save3(`files/${i}/before.txt`, before), after: after2 === null ? null : save3(`files/${i}/after.txt`, after2), ...before !== after2 ? { diff: save3(`files/${i}/change.diff`, unified(before, after2, file2, staging)) } : {} });
65842
66379
  }
65843
- for (const p of ["a", "b"]) fs85.rmSync(path84.join(staging, p), { force: true });
66380
+ for (const p of ["a", "b"]) fs86.rmSync(path85.join(staging, p), { force: true });
65844
66381
  if (!parseReview(review)) throw Error("generated review is invalid");
65845
66382
  save3("review.json", JSON.stringify(review, null, 2) + "\n");
65846
- fs85.mkdirSync(path84.dirname(destination), { recursive: true });
65847
- if (fs85.existsSync(destination)) {
65848
- fs85.renameSync(destination, backup);
66383
+ fs86.mkdirSync(path85.dirname(destination), { recursive: true });
66384
+ if (fs86.existsSync(destination)) {
66385
+ fs86.renameSync(destination, backup);
65849
66386
  moved = true;
65850
66387
  }
65851
- fs85.renameSync(staging, destination);
65852
- fs85.rmSync(backup, { recursive: true, force: true });
66388
+ fs86.renameSync(staging, destination);
66389
+ fs86.rmSync(backup, { recursive: true, force: true });
65853
66390
  const tag = `<Studio src=".assets/${id2}/studio-review/review.json" />`;
65854
66391
  const prefix = `.assets/${id2}/studio-review/`;
65855
66392
  const attachments = review.files.filter((f) => f.path !== "STUDIO.md" && f.diff);
@@ -65861,13 +66398,13 @@ ${items}
65861
66398
 
65862
66399
  </Set>` : items;
65863
66400
  say([tag, files].filter(Boolean).join("\n\n"));
65864
- return { file: path84.join(destination, "review.json"), tag, files };
66401
+ return { file: path85.join(destination, "review.json"), tag, files };
65865
66402
  } catch (error62) {
65866
- if (moved && !fs85.existsSync(destination)) fs85.renameSync(backup, destination);
66403
+ if (moved && !fs86.existsSync(destination)) fs86.renameSync(backup, destination);
65867
66404
  if (error62 && typeof error62 === "object" && "kind" in error62) throw error62;
65868
66405
  die(error62 instanceof Error ? error62.message : String(error62), "bad-args");
65869
66406
  } finally {
65870
- fs85.rmSync(staging, { recursive: true, force: true });
66407
+ fs86.rmSync(staging, { recursive: true, force: true });
65871
66408
  }
65872
66409
  }
65873
66410
  var readVersion2;
@@ -65985,12 +66522,12 @@ var init_agent_check = __esm({
65985
66522
  });
65986
66523
 
65987
66524
  // ../cli/src/lib/cli/agent.ts
65988
- async function onBoard(cmd, cli, work) {
66525
+ async function onBoard(cmd, cli, work, refreshStudios = false) {
65989
66526
  const ctx = ctxOf(cmd, cli.program);
65990
66527
  await runAction(ctx, {}, async () => {
65991
66528
  const found2 = resolveBoard("runs", { board: ctx.board, dir: ctx.dir, cwd: cli.cwd, installHint: cli.installHint });
65992
66529
  useBoard(found2, ctx.dir !== null);
65993
- await syncStudios();
66530
+ await syncStudios(refreshStudios);
65994
66531
  return { board: KANBAN, ...await work(cli.program) ?? {} };
65995
66532
  });
65996
66533
  }
@@ -66098,8 +66635,7 @@ function declareRuns(program2, cli) {
66098
66635
  await boardless(this, cli, (_, location) => taskReview(id2, this.opts(), location));
66099
66636
  });
66100
66637
  const questionOps = [];
66101
- const opInOrder = ordered(questionOps);
66102
- withShared(task.command("update-questions")).argument("<task>").summary("edit the task's open questions, like `raw update-questions`").description("Positions are 1-based, in the order of the card\u2019s `questions:` (`akb task show`). --option, --recommended-option and --mode attach to the --append or --update before them.").option("--append <text>", "add one question to the end", opInOrder("append")).option("--update <n> <text...>", "rewrite question <n> whole", opInOrder("update")).option("--drop <positions>", "remove questions, e.g. 1 or 1,3", opInOrder("drop")).option("--clear", "remove every open question", opInOrder("clear")).option("--option <text>", "a choice for the op before it", opInOrder("option")).option("--recommended-option <text>", "a choice for the op before it, ticked to start", opInOrder("recommended-option")).option("--mode <mode>", "how many choices the op before it takes: single | multi", opInOrder("mode")).addOption(new Option("--agent <name>").hideHelp().argParser(opInOrder("agent"))).action(async function(id2) {
66638
+ withQuestionOptions(withShared(task.command("update-questions")).argument("<task>").summary("append, rewrite, or remove open questions").description("Edit the current Runner task locally for synchronization, or save another task in Cloud. Edits apply in order at 1-based positions. Choices and mode apply to the preceding --append or --update.\nSee akb guide update-questions."), questionOps).action(async function(id2) {
66103
66639
  await boardless(this, cli, (_, location) => taskUpdateQuestions(id2, questionOps, location));
66104
66640
  });
66105
66641
  withShared(task.command("chat")).argument("<task>").argument("[message...]").summary("read task chat history, follow or stop its reply, or send a message").description("Without a message, read the last 20 messages and the chat reply state separately from task execution. --follow tracks only the reply present at the start; Ctrl+C disconnects locally. --stop stops only that reply. --follow --json emits JSON Lines; other modes return one JSON object.").option("--limit <n>", "show the last n messages, oldest first (default: 20)", intInRange(1, Number.MAX_SAFE_INTEGER)).option("--all", "show all retained messages").option("--follow", "follow this reply to its result, then exit").option("--stop", "request stopping only the current chat reply").addHelpText("after", '\nExamples:\n akb task chat WC-12\n akb task chat 12 --all --json\n akb task chat 12 --follow --json\n akb task chat 12 --stop\n akb task chat 12 "Revise the draft"').action(async function(id2, message) {
@@ -66435,6 +66971,7 @@ var init_agent2 = __esm({
66435
66971
  init_agent_check();
66436
66972
  init_harnesses();
66437
66973
  init_moved();
66974
+ init_question_options();
66438
66975
  init_shared2();
66439
66976
  REVIEW_FLOW_HELP = `
66440
66977
  Review examples
@@ -66442,10 +66979,7 @@ Review examples
66442
66979
  --review 'UI design -> Prompts' Approve in order
66443
66980
  --review 'UI design + API docs -> Prompts' Both approvals unlock Prompts
66444
66981
  --review '' No extra review`;
66445
- studioList = (cmd, cli) => !cmd.optsWithGlobals().board && externalGoalSession() ? boardless(cmd, cli, cloudGoalStudios) : goalDraftPath() ? boardless(cmd, cli, () => cmdGoalStudios()) : onBoard(cmd, cli, async () => {
66446
- await syncStudios(true);
66447
- return cmdStudioList();
66448
- });
66982
+ studioList = (cmd, cli) => !cmd.optsWithGlobals().board && externalGoalSession() ? boardless(cmd, cli, cloudGoalStudios) : goalDraftPath() ? boardless(cmd, cli, () => cmdGoalStudios()) : onBoard(cmd, cli, cmdStudioList, true);
66449
66983
  positional = (vals) => vals.slice(0, -2);
66450
66984
  RUN_ID = "a run's id, any prefix of one that names only one run, or `last`. Left out, it means the newest run";
66451
66985
  DELIVERY = "the delivery, or the card it is on";
@@ -66455,15 +66989,15 @@ Review examples
66455
66989
  });
66456
66990
 
66457
66991
  // ../cli/src/kanban.ts
66458
- import fs88 from "node:fs";
66992
+ import fs89 from "node:fs";
66459
66993
  import { fileURLToPath as fileURLToPath4 } from "node:url";
66460
66994
 
66461
66995
  // ../cli/src/lib/cli/akb.ts
66462
66996
  init_agent2();
66463
66997
 
66464
66998
  // ../cli/src/lib/cli/setup.ts
66465
- import fs87 from "node:fs";
66466
- import path86 from "node:path";
66999
+ import fs88 from "node:fs";
67000
+ import path87 from "node:path";
66467
67001
  import { fileURLToPath as fileURLToPath3 } from "node:url";
66468
67002
 
66469
67003
  // ../cli/src/commands/update.ts
@@ -66471,8 +67005,8 @@ init_board_cli();
66471
67005
  init_config_template();
66472
67006
  init_io();
66473
67007
  init_version();
66474
- import fs86 from "node:fs";
66475
- import path85 from "node:path";
67008
+ import fs87 from "node:fs";
67009
+ import path86 from "node:path";
66476
67010
  import { spawnSync as spawnSync9 } from "node:child_process";
66477
67011
  var NAME = "wildcrane";
66478
67012
  var REPO = "https://github.com/wildcrane-ai/wildcrane";
@@ -66493,7 +67027,7 @@ var Report = class {
66493
67027
  for (const line of this.notes) say(` ! ${line}`);
66494
67028
  }
66495
67029
  };
66496
- var read4 = (file2) => fs86.existsSync(file2) ? fs86.readFileSync(file2, "utf8") : null;
67030
+ var read4 = (file2) => fs87.existsSync(file2) ? fs87.readFileSync(file2, "utf8") : null;
66497
67031
  async function boardMove(root2, args2, board2) {
66498
67032
  const where = board2 ? ["--board", board2] : ["--dir", root2];
66499
67033
  const code = await runBoard([...args2, ...where], { program: "akb raw", cwd: root2 });
@@ -66514,10 +67048,10 @@ async function cmdUpdate2(ctx) {
66514
67048
  return { updated: ctx.dir, from, to: SKILL_VERSION };
66515
67049
  }
66516
67050
  async function repairBoard(root2, report3, named2) {
66517
- const legacy = path85.join(root2, "docs", "kanban");
66518
- const kept2 = path85.join(root2, ".akb", "kanban");
66519
- const board2 = named2 ?? (fs86.existsSync(legacy) ? legacy : kept2);
66520
- if (!fs86.existsSync(board2)) {
67051
+ const legacy = path86.join(root2, "docs", "kanban");
67052
+ const kept2 = path86.join(root2, ".akb", "kanban");
67053
+ const board2 = named2 ?? (fs87.existsSync(legacy) ? legacy : kept2);
67054
+ if (!fs87.existsSync(board2)) {
66521
67055
  report3.notes.push("\u672A\u627E\u5230\u770B\u677F\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002");
66522
67056
  return false;
66523
67057
  }
@@ -66528,7 +67062,7 @@ async function repairBoard(root2, report3, named2) {
66528
67062
  return true;
66529
67063
  }
66530
67064
  function checkConfig(board2, report3) {
66531
- const current = read4(path85.join(board2, "config.md"));
67065
+ const current = read4(path86.join(board2, "config.md"));
66532
67066
  if (!current) return;
66533
67067
  const added = missingConfigKeys(current);
66534
67068
  if (added.length) {
@@ -66538,7 +67072,7 @@ function checkConfig(board2, report3) {
66538
67072
  }
66539
67073
  }
66540
67074
  function checkModules(board2, report3) {
66541
- const map3 = read4(path85.join(board2, "modules.md"));
67075
+ const map3 = read4(path86.join(board2, "modules.md"));
66542
67076
  if (map3 && map3.includes(UNFILLED)) {
66543
67077
  report3.notes.push(
66544
67078
  "docs/kanban/modules.md is still blank \u2014 write it from the repo (`akb guide module-map`)"
@@ -66592,14 +67126,14 @@ function declareSetup(program2, cli) {
66592
67126
  program2.version(SKILL_VERSION, "-v, --version", "print this version").addHelpText("beforeAll", spelled(cli.program));
66593
67127
  const dirOption = (cmd) => cmd.option("--dir <path>", "the project to work on (default: the current folder)").option("--json", "answer as one JSON object instead of prose");
66594
67128
  const where = (cmd) => {
66595
- const dir = path86.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
66596
- if (!fs87.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
67129
+ const dir = path87.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
67130
+ if (!fs88.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
66597
67131
  return dir;
66598
67132
  };
66599
67133
  dirOption(program2.command("update")).summary("\u4FEE\u590D\u5DF2\u6709\u770B\u677F\u5E76\u68C0\u67E5 CLI \u65B0\u7248\u672C").description("\u4FEE\u590D\u5DF2\u6709\u770B\u677F\u5E76\u63D0\u793A CLI \u5347\u7EA7\u547D\u4EE4\u3002\u6CA1\u6709\u770B\u677F\u65F6\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002").action(async function() {
66600
67134
  const dir = where(this);
66601
67135
  const named2 = this.optsWithGlobals().board ?? process.env.AI4KANBAN_BOARD?.trim();
66602
- const board2 = named2 ? path86.resolve(cli.cwd, named2) : null;
67136
+ const board2 = named2 ? path87.resolve(cli.cwd, named2) : null;
66603
67137
  await runAction(ctxOf(this, cli.program), {}, () => cmdUpdate2({ dir, program: cli.program, board: board2 }));
66604
67138
  });
66605
67139
  program2.command("__rules", { hidden: true }).action(function() {
@@ -66644,7 +67178,7 @@ function invokedDirectly() {
66644
67178
  const entry = process.argv[1];
66645
67179
  if (!entry) return false;
66646
67180
  try {
66647
- return fs88.realpathSync(entry) === fs88.realpathSync(SELF2);
67181
+ return fs89.realpathSync(entry) === fs89.realpathSync(SELF2);
66648
67182
  } catch {
66649
67183
  return false;
66650
67184
  }