wildcrane 0.11.16 → 0.11.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +6 -0
  2. package/dist/kanban.mjs +1288 -1157
  3. package/package.json +1 -1
package/dist/kanban.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.16 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
2
+ // ai4kanban 0.11.18 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
3
3
  // Do not edit: every change belongs in cli/src/, and a build overwrites this file.
4
4
  import { createRequire as __ai4kanbanRequire } from 'node:module'
5
5
  const require = __ai4kanbanRequire(import.meta.url)
@@ -1168,8 +1168,8 @@ var require_command = __commonJS({
1168
1168
  "node_modules/commander/lib/command.js"(exports) {
1169
1169
  var EventEmitter = __require("node:events").EventEmitter;
1170
1170
  var childProcess = __require("node:child_process");
1171
- var path86 = __require("node:path");
1172
- var fs86 = __require("node:fs");
1171
+ var path88 = __require("node:path");
1172
+ var fs87 = __require("node:fs");
1173
1173
  var process2 = __require("node:process");
1174
1174
  var { Argument: Argument2, humanReadableArgName } = require_argument();
1175
1175
  var { CommanderError: CommanderError2 } = require_error();
@@ -2150,7 +2150,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2150
2150
  * @param {string} subcommandName
2151
2151
  */
2152
2152
  _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2153
- if (fs86.existsSync(executableFile)) return;
2153
+ if (fs87.existsSync(executableFile)) return;
2154
2154
  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";
2155
2155
  const executableMissing = `'${executableFile}' does not exist
2156
2156
  - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
@@ -2168,11 +2168,11 @@ Expecting one of '${allowedValues.join("', '")}'`);
2168
2168
  let launchWithNode = false;
2169
2169
  const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2170
2170
  function findFile(baseDir, baseName) {
2171
- const localBin = path86.resolve(baseDir, baseName);
2172
- if (fs86.existsSync(localBin)) return localBin;
2173
- if (sourceExt.includes(path86.extname(baseName))) return void 0;
2171
+ const localBin = path88.resolve(baseDir, baseName);
2172
+ if (fs87.existsSync(localBin)) return localBin;
2173
+ if (sourceExt.includes(path88.extname(baseName))) return void 0;
2174
2174
  const foundExt = sourceExt.find(
2175
- (ext) => fs86.existsSync(`${localBin}${ext}`)
2175
+ (ext) => fs87.existsSync(`${localBin}${ext}`)
2176
2176
  );
2177
2177
  if (foundExt) return `${localBin}${foundExt}`;
2178
2178
  return void 0;
@@ -2184,21 +2184,21 @@ Expecting one of '${allowedValues.join("', '")}'`);
2184
2184
  if (this._scriptPath) {
2185
2185
  let resolvedScriptPath;
2186
2186
  try {
2187
- resolvedScriptPath = fs86.realpathSync(this._scriptPath);
2187
+ resolvedScriptPath = fs87.realpathSync(this._scriptPath);
2188
2188
  } catch {
2189
2189
  resolvedScriptPath = this._scriptPath;
2190
2190
  }
2191
- executableDir = path86.resolve(
2192
- path86.dirname(resolvedScriptPath),
2191
+ executableDir = path88.resolve(
2192
+ path88.dirname(resolvedScriptPath),
2193
2193
  executableDir
2194
2194
  );
2195
2195
  }
2196
2196
  if (executableDir) {
2197
2197
  let localFile = findFile(executableDir, executableFile);
2198
2198
  if (!localFile && !subcommand._executableFile && this._scriptPath) {
2199
- const legacyName = path86.basename(
2199
+ const legacyName = path88.basename(
2200
2200
  this._scriptPath,
2201
- path86.extname(this._scriptPath)
2201
+ path88.extname(this._scriptPath)
2202
2202
  );
2203
2203
  if (legacyName !== this._name) {
2204
2204
  localFile = findFile(
@@ -2209,7 +2209,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
2209
2209
  }
2210
2210
  executableFile = localFile || executableFile;
2211
2211
  }
2212
- launchWithNode = sourceExt.includes(path86.extname(executableFile));
2212
+ launchWithNode = sourceExt.includes(path88.extname(executableFile));
2213
2213
  let proc;
2214
2214
  if (process2.platform !== "win32") {
2215
2215
  if (launchWithNode) {
@@ -3056,7 +3056,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
3056
3056
  * @return {Command}
3057
3057
  */
3058
3058
  nameFromFilename(filename) {
3059
- this._name = path86.basename(filename, path86.extname(filename));
3059
+ this._name = path88.basename(filename, path88.extname(filename));
3060
3060
  return this;
3061
3061
  }
3062
3062
  /**
@@ -3070,9 +3070,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
3070
3070
  * @param {string} [path]
3071
3071
  * @return {(string|null|Command)}
3072
3072
  */
3073
- executableDir(path87) {
3074
- if (path87 === void 0) return this._executableDir;
3075
- this._executableDir = path87;
3073
+ executableDir(path89) {
3074
+ if (path89 === void 0) return this._executableDir;
3075
+ this._executableDir = path89;
3076
3076
  return this;
3077
3077
  }
3078
3078
  /**
@@ -3755,192 +3755,6 @@ var init_env = __esm({
3755
3755
  }
3756
3756
  });
3757
3757
 
3758
- // src/lib/lock.ts
3759
- import { randomUUID } from "node:crypto";
3760
- import fs4 from "node:fs";
3761
- import path5 from "node:path";
3762
- function sleep(ms) {
3763
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3764
- }
3765
- function ageOf(dir) {
3766
- try {
3767
- return Date.now() - fs4.statSync(dir).mtimeMs;
3768
- } catch {
3769
- return 0;
3770
- }
3771
- }
3772
- function pidAlive(pid) {
3773
- if (!pid) return false;
3774
- try {
3775
- process.kill(pid, 0);
3776
- return true;
3777
- } catch (e) {
3778
- return e.code === "EPERM";
3779
- }
3780
- }
3781
- function ownerOf(dir) {
3782
- try {
3783
- const pid = Number(fs4.readFileSync(path5.join(dir, OWNER), "utf8").trim());
3784
- return Number.isInteger(pid) && pid > 0 ? pid : void 0;
3785
- } catch {
3786
- return void 0;
3787
- }
3788
- }
3789
- function claimBreak(dir) {
3790
- try {
3791
- fs4.mkdirSync(path5.join(dir, BREAKING));
3792
- return true;
3793
- } catch {
3794
- return false;
3795
- }
3796
- }
3797
- function removeClaim(dir, token3) {
3798
- if (token3) {
3799
- try {
3800
- fs4.unlinkSync(path5.join(dir, token3));
3801
- } catch (err) {
3802
- if (err.code !== "ENOENT") throw err;
3803
- }
3804
- }
3805
- try {
3806
- fs4.rmdirSync(dir);
3807
- return true;
3808
- } catch (err) {
3809
- const code = err.code;
3810
- if (code === "ENOENT") return true;
3811
- if (code === "ENOTEMPTY" || code === "EEXIST") return false;
3812
- throw err;
3813
- }
3814
- }
3815
- function tryLock(dir) {
3816
- fs4.mkdirSync(path5.dirname(dir), { recursive: true });
3817
- const token3 = `${process.pid}-${randomUUID()}`;
3818
- const candidate = fs4.mkdtempSync(`${dir}.`);
3819
- try {
3820
- fs4.writeFileSync(path5.join(candidate, token3), "");
3821
- for (; ; ) {
3822
- try {
3823
- fs4.renameSync(candidate, dir);
3824
- return () => {
3825
- removeClaim(dir, token3);
3826
- };
3827
- } catch (err) {
3828
- const code = err.code;
3829
- if (code !== "ENOTEMPTY" && code !== "EEXIST") throw err;
3830
- }
3831
- let entries;
3832
- try {
3833
- entries = fs4.readdirSync(dir);
3834
- } catch (err) {
3835
- if (err.code === "ENOENT") continue;
3836
- throw err;
3837
- }
3838
- if (entries.length) {
3839
- if (entries.length !== 1 || !/^\d+-[a-f0-9-]{36}$/.test(entries[0])) return void 0;
3840
- const owner = Number(entries[0].split("-")[0]);
3841
- if (pidAlive(owner)) return void 0;
3842
- }
3843
- if (!removeClaim(dir, entries[0])) return void 0;
3844
- }
3845
- } finally {
3846
- fs4.rmSync(candidate, { recursive: true, force: true });
3847
- }
3848
- }
3849
- function withLock(dir, what, fn) {
3850
- const until = Date.now() + WAIT_MS;
3851
- let held4;
3852
- for (; ; ) {
3853
- try {
3854
- fs4.mkdirSync(dir, { recursive: false });
3855
- try {
3856
- fs4.writeFileSync(path5.join(dir, OWNER), `${process.pid}
3857
- `);
3858
- } catch {
3859
- }
3860
- break;
3861
- } catch (err) {
3862
- const code = err.code;
3863
- if (code === "ENOENT") {
3864
- fs4.mkdirSync(path5.dirname(dir), { recursive: true });
3865
- continue;
3866
- }
3867
- if (code !== "EEXIST") throw err;
3868
- if (ageOf(dir) > STALE_MS) {
3869
- fs4.rmSync(dir, { recursive: true, force: true });
3870
- continue;
3871
- }
3872
- held4 = ownerOf(dir);
3873
- if (held4 !== void 0 && !pidAlive(held4) && claimBreak(dir)) {
3874
- fs4.rmSync(dir, { recursive: true, force: true });
3875
- continue;
3876
- }
3877
- if (Date.now() > until) {
3878
- die(
3879
- `another command is ${what}${held4 ? ` (process ${held4})` : ""} and did not finish in ${WAIT_MS / 1e3}s. If nothing else is running, remove ${rel(dir)}/ and try again.`,
3880
- "board-busy"
3881
- );
3882
- }
3883
- sleep(RETRY_MS);
3884
- }
3885
- }
3886
- try {
3887
- return fn();
3888
- } finally {
3889
- const owner = ownerOf(dir);
3890
- if (owner === void 0 || owner === process.pid) fs4.rmSync(dir, { recursive: true, force: true });
3891
- }
3892
- }
3893
- function withBoardLock(fn) {
3894
- if (!fs4.existsSync(KANBAN)) return fn();
3895
- if (depth > 0) return fn();
3896
- try {
3897
- ensureAkbDir();
3898
- } catch {
3899
- }
3900
- depth++;
3901
- try {
3902
- return withLock(LOCK, "writing this board", fn);
3903
- } finally {
3904
- depth--;
3905
- }
3906
- }
3907
- var WAIT_MS, STALE_MS, RETRY_MS, OWNER, BREAKING, depth;
3908
- var init_lock = __esm({
3909
- "src/lib/lock.ts"() {
3910
- "use strict";
3911
- init_paths();
3912
- WAIT_MS = 1e4;
3913
- STALE_MS = 6e4;
3914
- RETRY_MS = 25;
3915
- OWNER = "owner";
3916
- BREAKING = "breaking";
3917
- depth = 0;
3918
- }
3919
- });
3920
-
3921
- // src/lib/agent/creation-lock.ts
3922
- import path6 from "node:path";
3923
- function withCreationLock(fn) {
3924
- if (depth2) return fn();
3925
- return withLock(path6.join(SESSIONS_DIR, "creation.lock"), "changing card creation", () => {
3926
- depth2++;
3927
- try {
3928
- return fn();
3929
- } finally {
3930
- depth2--;
3931
- }
3932
- });
3933
- }
3934
- var depth2;
3935
- var init_creation_lock = __esm({
3936
- "src/lib/agent/creation-lock.ts"() {
3937
- "use strict";
3938
- init_lock();
3939
- init_paths();
3940
- depth2 = 0;
3941
- }
3942
- });
3943
-
3944
3758
  // src/lib/cloud/config.ts
3945
3759
  function cloudEndpoints() {
3946
3760
  return {
@@ -3966,12 +3780,12 @@ var init_config = __esm({
3966
3780
  });
3967
3781
 
3968
3782
  // src/lib/cloud/session.ts
3969
- import fs5 from "node:fs";
3970
- import path7 from "node:path";
3783
+ import fs4 from "node:fs";
3784
+ import path5 from "node:path";
3971
3785
  function readSession() {
3972
3786
  let raw;
3973
3787
  try {
3974
- raw = fs5.readFileSync(sessionFile(), "utf8");
3788
+ raw = fs4.readFileSync(sessionFile(), "utf8");
3975
3789
  } catch {
3976
3790
  return null;
3977
3791
  }
@@ -3985,15 +3799,15 @@ function readSession() {
3985
3799
  }
3986
3800
  }
3987
3801
  function writeSession(session) {
3988
- fs5.mkdirSync(machineHome(), { recursive: true, mode: 448 });
3802
+ fs4.mkdirSync(machineHome(), { recursive: true, mode: 448 });
3989
3803
  const tmp = `${sessionFile()}.${process.pid}.tmp`;
3990
- fs5.writeFileSync(tmp, `${JSON.stringify(session, null, 2)}
3804
+ fs4.writeFileSync(tmp, `${JSON.stringify(session, null, 2)}
3991
3805
  `, { mode: 384 });
3992
- fs5.renameSync(tmp, sessionFile());
3806
+ fs4.renameSync(tmp, sessionFile());
3993
3807
  }
3994
3808
  function clearSession() {
3995
3809
  try {
3996
- fs5.rmSync(sessionFile());
3810
+ fs4.rmSync(sessionFile());
3997
3811
  } catch {
3998
3812
  }
3999
3813
  }
@@ -4061,42 +3875,42 @@ async function takeLock() {
4061
3875
  const until = Date.now() + LOCK_WAIT_MS;
4062
3876
  for (; ; ) {
4063
3877
  try {
4064
- fs5.mkdirSync(machineHome(), { recursive: true, mode: 448 });
4065
- fs5.mkdirSync(lockDir());
3878
+ fs4.mkdirSync(machineHome(), { recursive: true, mode: 448 });
3879
+ fs4.mkdirSync(lockDir());
4066
3880
  try {
4067
- fs5.writeFileSync(lockOwner(), `${process.pid}
3881
+ fs4.writeFileSync(lockOwner(), `${process.pid}
4068
3882
  `);
4069
3883
  } catch {
4070
3884
  }
4071
3885
  return () => {
4072
3886
  try {
4073
- fs5.rmSync(lockDir(), { recursive: true, force: true });
3887
+ fs4.rmSync(lockDir(), { recursive: true, force: true });
4074
3888
  } catch {
4075
3889
  }
4076
3890
  };
4077
3891
  } catch (err) {
4078
3892
  if (err.code !== "EEXIST") throw err;
4079
3893
  if (stale()) {
4080
- fs5.rmSync(lockDir(), { recursive: true, force: true });
3894
+ fs4.rmSync(lockDir(), { recursive: true, force: true });
4081
3895
  continue;
4082
3896
  }
4083
3897
  if (Date.now() > until) return () => {
4084
3898
  };
4085
- await sleep2(LOCK_RETRY_MS);
3899
+ await sleep(LOCK_RETRY_MS);
4086
3900
  }
4087
3901
  }
4088
3902
  }
4089
3903
  function stale() {
4090
3904
  let held4;
4091
3905
  try {
4092
- const pid = Number(fs5.readFileSync(lockOwner(), "utf8").trim());
3906
+ const pid = Number(fs4.readFileSync(lockOwner(), "utf8").trim());
4093
3907
  held4 = Number.isInteger(pid) && pid > 0 ? pid : void 0;
4094
3908
  } catch {
4095
3909
  held4 = void 0;
4096
3910
  }
4097
3911
  if (held4 !== void 0 && !alive(held4)) return true;
4098
3912
  try {
4099
- return Date.now() - fs5.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
3913
+ return Date.now() - fs4.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
4100
3914
  } catch {
4101
3915
  return false;
4102
3916
  }
@@ -4109,7 +3923,7 @@ function alive(pid) {
4109
3923
  return e.code === "EPERM";
4110
3924
  }
4111
3925
  }
4112
- var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep2;
3926
+ var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep;
4113
3927
  var init_session = __esm({
4114
3928
  "src/lib/cloud/session.ts"() {
4115
3929
  "use strict";
@@ -4119,11 +3933,234 @@ var init_session = __esm({
4119
3933
  LOCK_STALE_MS = 3e4;
4120
3934
  LOCK_WAIT_MS = 2e4;
4121
3935
  LOCK_RETRY_MS = 50;
4122
- sessionFile = () => path7.join(machineHome(), "session.json");
4123
- lockDir = () => path7.join(machineHome(), "session.lock");
4124
- lockOwner = () => path7.join(lockDir(), "owner");
3936
+ sessionFile = () => path5.join(machineHome(), "session.json");
3937
+ lockDir = () => path5.join(machineHome(), "session.lock");
3938
+ lockOwner = () => path5.join(lockDir(), "owner");
4125
3939
  expiringSoon = (session) => session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
4126
- sleep2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
3940
+ sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
3941
+ }
3942
+ });
3943
+
3944
+ // src/lib/cloud/execution.ts
3945
+ function executionOf(value = process.env.AI4KANBAN_EXECUTION) {
3946
+ try {
3947
+ const held4 = typeof value === "string" ? JSON.parse(value) : value;
3948
+ if (held4 && UUID.test(held4.job) && UUID.test(held4.machine)) return { job: held4.job, machine: held4.machine };
3949
+ } catch {
3950
+ }
3951
+ return void 0;
3952
+ }
3953
+ async function executionHeld(execution) {
3954
+ if (!execution) return true;
3955
+ try {
3956
+ const auth = await accessToken();
3957
+ if (!auth.ok) return false;
3958
+ const response = await fetch(`${cloudEndpoints().api}/v1/runner/jobs/${execution.job}/renew`, {
3959
+ method: "POST",
3960
+ headers: { authorization: `Bearer ${auth.token}`, "content-type": "application/json" },
3961
+ body: JSON.stringify({ machineId: execution.machine }),
3962
+ signal: AbortSignal.timeout(2e4)
3963
+ });
3964
+ if (!response.ok) return false;
3965
+ const held4 = await response.json();
3966
+ return held4.renewed === true && held4.stop !== true;
3967
+ } catch {
3968
+ return false;
3969
+ }
3970
+ }
3971
+ var UUID;
3972
+ var init_execution = __esm({
3973
+ "src/lib/cloud/execution.ts"() {
3974
+ "use strict";
3975
+ init_config();
3976
+ init_session();
3977
+ UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3978
+ }
3979
+ });
3980
+
3981
+ // src/lib/lock.ts
3982
+ import { randomUUID } from "node:crypto";
3983
+ import fs5 from "node:fs";
3984
+ import path6 from "node:path";
3985
+ function sleep2(ms) {
3986
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3987
+ }
3988
+ function ageOf(dir) {
3989
+ try {
3990
+ return Date.now() - fs5.statSync(dir).mtimeMs;
3991
+ } catch {
3992
+ return 0;
3993
+ }
3994
+ }
3995
+ function pidAlive(pid) {
3996
+ if (!pid) return false;
3997
+ try {
3998
+ process.kill(pid, 0);
3999
+ return true;
4000
+ } catch (e) {
4001
+ return e.code === "EPERM";
4002
+ }
4003
+ }
4004
+ function ownerOf(dir) {
4005
+ try {
4006
+ const pid = Number(fs5.readFileSync(path6.join(dir, OWNER), "utf8").trim());
4007
+ return Number.isInteger(pid) && pid > 0 ? pid : void 0;
4008
+ } catch {
4009
+ return void 0;
4010
+ }
4011
+ }
4012
+ function claimBreak(dir) {
4013
+ try {
4014
+ fs5.mkdirSync(path6.join(dir, BREAKING));
4015
+ return true;
4016
+ } catch {
4017
+ return false;
4018
+ }
4019
+ }
4020
+ function removeClaim(dir, token3) {
4021
+ if (token3) {
4022
+ try {
4023
+ fs5.unlinkSync(path6.join(dir, token3));
4024
+ } catch (err) {
4025
+ if (err.code !== "ENOENT") throw err;
4026
+ }
4027
+ }
4028
+ try {
4029
+ fs5.rmdirSync(dir);
4030
+ return true;
4031
+ } catch (err) {
4032
+ const code = err.code;
4033
+ if (code === "ENOENT") return true;
4034
+ if (code === "ENOTEMPTY" || code === "EEXIST") return false;
4035
+ throw err;
4036
+ }
4037
+ }
4038
+ function tryLock(dir) {
4039
+ fs5.mkdirSync(path6.dirname(dir), { recursive: true });
4040
+ const token3 = `${process.pid}-${randomUUID()}`;
4041
+ const candidate = fs5.mkdtempSync(`${dir}.`);
4042
+ try {
4043
+ fs5.writeFileSync(path6.join(candidate, token3), "");
4044
+ for (; ; ) {
4045
+ try {
4046
+ fs5.renameSync(candidate, dir);
4047
+ return () => {
4048
+ removeClaim(dir, token3);
4049
+ };
4050
+ } catch (err) {
4051
+ const code = err.code;
4052
+ if (code !== "ENOTEMPTY" && code !== "EEXIST") throw err;
4053
+ }
4054
+ let entries;
4055
+ try {
4056
+ entries = fs5.readdirSync(dir);
4057
+ } catch (err) {
4058
+ if (err.code === "ENOENT") continue;
4059
+ throw err;
4060
+ }
4061
+ if (entries.length) {
4062
+ if (entries.length !== 1 || !/^\d+-[a-f0-9-]{36}$/.test(entries[0])) return void 0;
4063
+ const owner = Number(entries[0].split("-")[0]);
4064
+ if (pidAlive(owner)) return void 0;
4065
+ }
4066
+ if (!removeClaim(dir, entries[0])) return void 0;
4067
+ }
4068
+ } finally {
4069
+ fs5.rmSync(candidate, { recursive: true, force: true });
4070
+ }
4071
+ }
4072
+ function withLock(dir, what, fn) {
4073
+ const until = Date.now() + WAIT_MS;
4074
+ let held4;
4075
+ for (; ; ) {
4076
+ try {
4077
+ fs5.mkdirSync(dir, { recursive: false });
4078
+ try {
4079
+ fs5.writeFileSync(path6.join(dir, OWNER), `${process.pid}
4080
+ `);
4081
+ } catch {
4082
+ }
4083
+ break;
4084
+ } catch (err) {
4085
+ const code = err.code;
4086
+ if (code === "ENOENT") {
4087
+ fs5.mkdirSync(path6.dirname(dir), { recursive: true });
4088
+ continue;
4089
+ }
4090
+ if (code !== "EEXIST") throw err;
4091
+ if (ageOf(dir) > STALE_MS) {
4092
+ fs5.rmSync(dir, { recursive: true, force: true });
4093
+ continue;
4094
+ }
4095
+ held4 = ownerOf(dir);
4096
+ if (held4 !== void 0 && !pidAlive(held4) && claimBreak(dir)) {
4097
+ fs5.rmSync(dir, { recursive: true, force: true });
4098
+ continue;
4099
+ }
4100
+ if (Date.now() > until) {
4101
+ die(
4102
+ `another command is ${what}${held4 ? ` (process ${held4})` : ""} and did not finish in ${WAIT_MS / 1e3}s. If nothing else is running, remove ${rel(dir)}/ and try again.`,
4103
+ "board-busy"
4104
+ );
4105
+ }
4106
+ sleep2(RETRY_MS);
4107
+ }
4108
+ }
4109
+ try {
4110
+ return fn();
4111
+ } finally {
4112
+ const owner = ownerOf(dir);
4113
+ if (owner === void 0 || owner === process.pid) fs5.rmSync(dir, { recursive: true, force: true });
4114
+ }
4115
+ }
4116
+ function withBoardLock(fn) {
4117
+ if (!fs5.existsSync(KANBAN)) return fn();
4118
+ if (depth > 0) return fn();
4119
+ try {
4120
+ ensureAkbDir();
4121
+ } catch {
4122
+ }
4123
+ depth++;
4124
+ try {
4125
+ return withLock(LOCK, "writing this board", fn);
4126
+ } finally {
4127
+ depth--;
4128
+ }
4129
+ }
4130
+ var WAIT_MS, STALE_MS, RETRY_MS, OWNER, BREAKING, depth;
4131
+ var init_lock = __esm({
4132
+ "src/lib/lock.ts"() {
4133
+ "use strict";
4134
+ init_paths();
4135
+ WAIT_MS = 1e4;
4136
+ STALE_MS = 6e4;
4137
+ RETRY_MS = 25;
4138
+ OWNER = "owner";
4139
+ BREAKING = "breaking";
4140
+ depth = 0;
4141
+ }
4142
+ });
4143
+
4144
+ // src/lib/agent/creation-lock.ts
4145
+ import path7 from "node:path";
4146
+ function withCreationLock(fn) {
4147
+ if (depth2) return fn();
4148
+ return withLock(path7.join(SESSIONS_DIR, "creation.lock"), "changing card creation", () => {
4149
+ depth2++;
4150
+ try {
4151
+ return fn();
4152
+ } finally {
4153
+ depth2--;
4154
+ }
4155
+ });
4156
+ }
4157
+ var depth2;
4158
+ var init_creation_lock = __esm({
4159
+ "src/lib/agent/creation-lock.ts"() {
4160
+ "use strict";
4161
+ init_lock();
4162
+ init_paths();
4163
+ depth2 = 0;
4127
4164
  }
4128
4165
  });
4129
4166
 
@@ -5481,7 +5518,7 @@ var init_package = __esm({
5481
5518
  "package.json"() {
5482
5519
  package_default = {
5483
5520
  name: "wildcrane",
5484
- version: "0.11.16",
5521
+ version: "0.11.18",
5485
5522
  akbContract: 5,
5486
5523
  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.",
5487
5524
  keywords: [
@@ -8322,10 +8359,10 @@ function findRollout(threadId) {
8322
8359
  }
8323
8360
  for (const name of names4) {
8324
8361
  if (!name.startsWith("rollout-") || !name.endsWith(tail2)) continue;
8325
- const path86 = join(dir, name);
8362
+ const path88 = join(dir, name);
8326
8363
  try {
8327
- const at = statSync(path86).mtimeMs;
8328
- if (!newest2 || at > newest2.at) newest2 = { path: path86, at };
8364
+ const at = statSync(path88).mtimeMs;
8365
+ if (!newest2 || at > newest2.at) newest2 = { path: path88, at };
8329
8366
  } catch {
8330
8367
  }
8331
8368
  }
@@ -8333,11 +8370,11 @@ function findRollout(threadId) {
8333
8370
  return newest2?.path;
8334
8371
  }
8335
8372
  function readCodexRunFacts(threadId) {
8336
- const path86 = findRollout(threadId);
8337
- if (!path86) return void 0;
8373
+ const path88 = findRollout(threadId);
8374
+ if (!path88) return void 0;
8338
8375
  let raw;
8339
8376
  try {
8340
- raw = readFileSync(path86, "utf8");
8377
+ raw = readFileSync(path88, "utf8");
8341
8378
  } catch {
8342
8379
  return void 0;
8343
8380
  }
@@ -8465,8 +8502,8 @@ function renderCompleted(item) {
8465
8502
  const changes = Array.isArray(item.changes) ? item.changes : [];
8466
8503
  return changes.map((raw) => {
8467
8504
  const change2 = obj(raw);
8468
- const path86 = str2(change2.path);
8469
- return path86 ? `\u23FA ${str2(change2.kind) || "change"}(${path86})
8505
+ const path88 = str2(change2.path);
8506
+ return path88 ? `\u23FA ${str2(change2.kind) || "change"}(${path88})
8470
8507
  ` : "";
8471
8508
  }).join("");
8472
8509
  }
@@ -8728,10 +8765,10 @@ function readKimiRunFacts(sessionId) {
8728
8765
  const total = { input: 0, cacheCreation: 0, cacheRead: 0, output: 0 };
8729
8766
  let model;
8730
8767
  let holding = 0;
8731
- for (const { path: path86, main } of wireFiles(entry.sessionDir)) {
8768
+ for (const { path: path88, main } of wireFiles(entry.sessionDir)) {
8732
8769
  let raw;
8733
8770
  try {
8734
- raw = readFileSync2(path86, "utf8");
8771
+ raw = readFileSync2(path88, "utf8");
8735
8772
  } catch {
8736
8773
  continue;
8737
8774
  }
@@ -9012,8 +9049,8 @@ var init_tail = __esm({
9012
9049
  import fs24 from "node:fs";
9013
9050
  function whereHint(update2, title) {
9014
9051
  const locations = Array.isArray(update2.locations) ? update2.locations : [];
9015
- const path86 = str2(obj(locations[0]).path);
9016
- return path86 && !title.includes(path86) ? hint(path86) : "";
9052
+ const path88 = str2(obj(locations[0]).path);
9053
+ return path88 && !title.includes(path88) ? hint(path88) : "";
9017
9054
  }
9018
9055
  function saidBy(update2) {
9019
9056
  const content = Array.isArray(update2.content) ? update2.content : [];
@@ -9999,27 +10036,40 @@ import crypto3 from "node:crypto";
9999
10036
  import fs25 from "node:fs";
10000
10037
  import os4 from "node:os";
10001
10038
  import path28 from "node:path";
10039
+ function spawnGit(args, options) {
10040
+ const out = spawnSync3("git", args, {
10041
+ ...options,
10042
+ encoding: "utf8",
10043
+ stdio: ["ignore", "pipe", "pipe"],
10044
+ timeout: gitLimits.timeoutMs,
10045
+ killSignal: "SIGKILL"
10046
+ });
10047
+ if (out.error?.code === "ETIMEDOUT") throw new GitTimeoutError(`Git ${args[0]} timed out after ${gitLimits.timeoutMs / 1e3}s; the command was killed.`);
10048
+ return out;
10049
+ }
10002
10050
  function git(args, cwd = REPO_ROOT) {
10003
10051
  try {
10004
- const out = spawnSync3("git", args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
10052
+ const out = spawnGit(args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
10005
10053
  if (out.error || out.status !== 0) return null;
10006
10054
  return out.stdout;
10007
- } catch {
10055
+ } catch (error) {
10056
+ if (error instanceof GitTimeoutError) throw error;
10008
10057
  return null;
10009
10058
  }
10010
10059
  }
10011
10060
  function gitDiff(args, cwd = REPO_ROOT) {
10012
10061
  try {
10013
- const out = spawnSync3("git", args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
10062
+ const out = spawnGit(args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
10014
10063
  if (out.error || out.status !== 0 && out.status !== 1) return null;
10015
10064
  return out.stdout;
10016
- } catch {
10065
+ } catch (error) {
10066
+ if (error instanceof GitTimeoutError) throw error;
10017
10067
  return null;
10018
10068
  }
10019
10069
  }
10020
10070
  function tryGit(args, cwd = REPO_ROOT, env2) {
10021
10071
  try {
10022
- const out = spawnSync3("git", args, {
10072
+ const out = spawnGit(args, {
10023
10073
  cwd,
10024
10074
  encoding: "utf8",
10025
10075
  maxBuffer: MAX_OUTPUT,
@@ -10030,6 +10080,7 @@ function tryGit(args, cwd = REPO_ROOT, env2) {
10030
10080
  if (out.status !== 0) return { ok: false, why: (out.stderr || out.stdout || "").trim() };
10031
10081
  return { ok: true };
10032
10082
  } catch (e) {
10083
+ if (e instanceof GitTimeoutError) throw e;
10033
10084
  return { ok: false, why: e instanceof Error ? e.message : String(e) };
10034
10085
  }
10035
10086
  }
@@ -10038,7 +10089,7 @@ function boardManagedPaths() {
10038
10089
  }
10039
10090
  function outsideBoardForAdd(cwd = REPO_ROOT) {
10040
10091
  const kept2 = boardManagedPaths().filter(
10041
- (p) => spawnSync3("git", ["check-ignore", "-q", p], { cwd, windowsHide: true }).status !== 0
10092
+ (p) => spawnGit(["check-ignore", "-q", p], { cwd, windowsHide: true }).status !== 0
10042
10093
  );
10043
10094
  return ["--", ".", ...kept2.map((p) => `:(exclude)${p}`)];
10044
10095
  }
@@ -10158,10 +10209,10 @@ function treeMark(base, cwd = REPO_ROOT) {
10158
10209
  const index = path28.join(ensureAkbDir(), `index-${process.pid}-${Date.now()}`);
10159
10210
  try {
10160
10211
  const env2 = { ...process.env, GIT_INDEX_FILE: index };
10161
- const run2 = (args) => spawnSync3("git", args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true, env: env2 }).status === 0;
10212
+ const run2 = (args) => spawnGit(args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true, env: env2 }).status === 0;
10162
10213
  if (!run2(["read-tree", base])) return null;
10163
10214
  if (!run2(["add", "-A", ...outsideBoardForAdd(cwd)])) return null;
10164
- const tree = spawnSync3("git", ["write-tree"], {
10215
+ const tree = spawnGit(["write-tree"], {
10165
10216
  cwd,
10166
10217
  encoding: "utf8",
10167
10218
  maxBuffer: MAX_OUTPUT,
@@ -10169,7 +10220,8 @@ function treeMark(base, cwd = REPO_ROOT) {
10169
10220
  env: env2
10170
10221
  });
10171
10222
  return tree.status === 0 ? tree.stdout.trim() || null : null;
10172
- } catch {
10223
+ } catch (error) {
10224
+ if (error instanceof GitTimeoutError) throw error;
10173
10225
  return null;
10174
10226
  } finally {
10175
10227
  try {
@@ -10180,23 +10232,26 @@ function treeMark(base, cwd = REPO_ROOT) {
10180
10232
  }
10181
10233
  function reverseApplies(patch2, ref, cwd = REPO_ROOT) {
10182
10234
  if (!patch2.trim()) return false;
10183
- const index = path28.join(os4.tmpdir(), `akb-apply-${process.pid}-${Date.now()}.index`);
10235
+ const folder = fs25.mkdtempSync(path28.join(os4.tmpdir(), `akb-apply-${process.pid}-`));
10236
+ const index = path28.join(folder, "index");
10237
+ const patchFile = path28.join(folder, "patch");
10184
10238
  const env2 = { GIT_INDEX_FILE: index };
10185
10239
  try {
10240
+ fs25.writeFileSync(patchFile, patch2);
10186
10241
  if (!tryGit(["read-tree", ref], cwd, env2).ok) return false;
10187
- const out = spawnSync3("git", ["apply", "--cached", "--reverse", "--check", "-"], {
10242
+ const out = spawnGit(["apply", "--cached", "--reverse", "--check", patchFile], {
10188
10243
  cwd,
10189
- input: patch2,
10190
10244
  encoding: "utf8",
10191
10245
  maxBuffer: MAX_OUTPUT,
10192
10246
  windowsHide: true,
10193
10247
  env: { ...process.env, ...env2 }
10194
10248
  });
10195
10249
  return !out.error && out.status === 0;
10196
- } catch {
10250
+ } catch (error) {
10251
+ if (error instanceof GitTimeoutError) throw error;
10197
10252
  return false;
10198
10253
  } finally {
10199
- fs25.rmSync(index, { force: true });
10254
+ fs25.rmSync(folder, { recursive: true, force: true });
10200
10255
  }
10201
10256
  }
10202
10257
  function squashOnto(dir, base, message) {
@@ -10278,12 +10333,15 @@ function moveBranchRef(branch, commit, expect) {
10278
10333
  if (branchTip(branch) !== expect) return { moved: true };
10279
10334
  return { ok: false, error: `couldn't move ${branch} to ${commit.slice(0, 12)}: ${done2.why ?? "git refused"}` };
10280
10335
  }
10281
- var MAX_OUTPUT, scripted, posix, outsideBoard, deliveryBranch, deliveryWorktree, worktreeDir, inGitRepo, headCommit, worktreeExists, branchExists, pruneWorktreeMetadata, branchTip, isAncestor, changedPaths, branchPatch, lastCommitTouching, continueRebase, abortRebase, conflictedPaths, headingKind;
10336
+ var MAX_OUTPUT, gitLimits, GitTimeoutError, scripted, posix, outsideBoard, deliveryBranch, deliveryWorktree, worktreeDir, inGitRepo, headCommit, worktreeExists, branchExists, pruneWorktreeMetadata, branchTip, isAncestor, changedPaths, branchPatch, lastCommitTouching, continueRebase, abortRebase, conflictedPaths, headingKind;
10282
10337
  var init_worktree = __esm({
10283
10338
  "src/lib/agent/worktree.ts"() {
10284
10339
  "use strict";
10285
10340
  init_paths();
10286
10341
  MAX_OUTPUT = 64 * 1024 * 1024;
10342
+ gitLimits = { timeoutMs: 3e4 };
10343
+ GitTimeoutError = class extends Error {
10344
+ };
10287
10345
  scripted = (args, cwd) => tryGit(["-c", "core.hooksPath=/dev/null", ...args], cwd, { GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" });
10288
10346
  posix = (p) => p.split(path28.sep).join("/");
10289
10347
  outsideBoard = () => [
@@ -10300,7 +10358,7 @@ var init_worktree = __esm({
10300
10358
  branchExists = (branch) => !!branch && git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]) !== null;
10301
10359
  pruneWorktreeMetadata = () => void git(["worktree", "prune"]);
10302
10360
  branchTip = (branch) => git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`])?.trim() || null;
10303
- isAncestor = (older, newer, cwd = REPO_ROOT) => spawnSync3("git", ["merge-base", "--is-ancestor", older, newer], { cwd, windowsHide: true }).status === 0;
10361
+ isAncestor = (older, newer, cwd = REPO_ROOT) => spawnGit(["merge-base", "--is-ancestor", older, newer], { cwd, windowsHide: true }).status === 0;
10304
10362
  changedPaths = (base, branch, cwd = REPO_ROOT) => {
10305
10363
  const out = git(["diff", "--name-only", base, branch, ...outsideBoard()], cwd);
10306
10364
  return out === null ? null : out.split("\n").filter(Boolean);
@@ -11647,51 +11705,14 @@ function withSystemLanguage(harness, argv, env2, language) {
11647
11705
  return { argv: [...argv.slice(0, at), ...added?.args ?? [], ...argv.slice(at)], env: { ...env2, ...added?.env } };
11648
11706
  }
11649
11707
  var init_run_settings = __esm({
11650
- "src/lib/agent/run-settings.ts"() {
11651
- "use strict";
11652
- init_home();
11653
- init_argv();
11654
- init_env();
11655
- init_language();
11656
- init_types2();
11657
- init_providers();
11658
- }
11659
- });
11660
-
11661
- // src/lib/cloud/execution.ts
11662
- function executionOf(value = process.env.AI4KANBAN_EXECUTION) {
11663
- try {
11664
- const held4 = typeof value === "string" ? JSON.parse(value) : value;
11665
- if (held4 && UUID.test(held4.job) && UUID.test(held4.machine)) return { job: held4.job, machine: held4.machine };
11666
- } catch {
11667
- }
11668
- return void 0;
11669
- }
11670
- async function executionHeld(execution) {
11671
- if (!execution) return true;
11672
- try {
11673
- const auth = await accessToken();
11674
- if (!auth.ok) return false;
11675
- const response = await fetch(`${cloudEndpoints().api}/v1/runner/jobs/${execution.job}/renew`, {
11676
- method: "POST",
11677
- headers: { authorization: `Bearer ${auth.token}`, "content-type": "application/json" },
11678
- body: JSON.stringify({ machineId: execution.machine }),
11679
- signal: AbortSignal.timeout(2e4)
11680
- });
11681
- if (!response.ok) return false;
11682
- const held4 = await response.json();
11683
- return held4.renewed === true && held4.stop !== true;
11684
- } catch {
11685
- return false;
11686
- }
11687
- }
11688
- var UUID;
11689
- var init_execution = __esm({
11690
- "src/lib/cloud/execution.ts"() {
11708
+ "src/lib/agent/run-settings.ts"() {
11691
11709
  "use strict";
11692
- init_config();
11693
- init_session();
11694
- UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11710
+ init_home();
11711
+ init_argv();
11712
+ init_env();
11713
+ init_language();
11714
+ init_types2();
11715
+ init_providers();
11695
11716
  }
11696
11717
  });
11697
11718
 
@@ -15639,6 +15660,252 @@ var init_complete = __esm({
15639
15660
  }
15640
15661
  });
15641
15662
 
15663
+ // src/lib/agent/stop.ts
15664
+ import { spawnSync as spawnSync4 } from "node:child_process";
15665
+ import { randomUUID as randomUUID5 } from "node:crypto";
15666
+ import fs39 from "node:fs";
15667
+ import os6 from "node:os";
15668
+ import path44 from "node:path";
15669
+ function markedInProc(entry, strict = false) {
15670
+ const pids = [];
15671
+ for (const name of fs39.readdirSync("/proc")) {
15672
+ if (!/^\d+$/.test(name)) continue;
15673
+ try {
15674
+ if (fs39.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
15675
+ } catch (error) {
15676
+ if (strict && !["ENOENT", "ESRCH"].includes(error.code ?? "")) {
15677
+ const stat = fs39.statSync(`/proc/${name}`, { throwIfNoEntry: false });
15678
+ if (stat?.uid === process.getuid?.()) throw error;
15679
+ }
15680
+ }
15681
+ }
15682
+ return pids;
15683
+ }
15684
+ function markedInPs(entry, roots) {
15685
+ const ps = spawnSync4("ps", ["-A", "-E", "-ww", "-o", "pid=,ppid=,command="], {
15686
+ encoding: "utf8",
15687
+ maxBuffer: 64 * 1024 * 1024,
15688
+ timeout: 5e3
15689
+ });
15690
+ if (ps.status !== 0 || !ps.stdout) throw new Error("\u65E0\u6CD5\u67E5\u8BE2\u8FDB\u7A0B\u6811\u3002");
15691
+ const children = /* @__PURE__ */ new Map();
15692
+ const listed2 = /* @__PURE__ */ new Set();
15693
+ const found2 = /* @__PURE__ */ new Set();
15694
+ for (const line of ps.stdout.split("\n")) {
15695
+ const m = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
15696
+ if (!m) continue;
15697
+ const pid = Number(m[1]);
15698
+ const ppid = Number(m[2]);
15699
+ listed2.add(pid);
15700
+ children.set(ppid, [...children.get(ppid) ?? [], pid]);
15701
+ if (`${m[3]} `.includes(` ${entry} `)) found2.add(pid);
15702
+ }
15703
+ const queue = [...found2, ...roots.filter((pid) => listed2.has(pid))];
15704
+ for (const pid of queue) {
15705
+ found2.add(pid);
15706
+ for (const child of children.get(pid) ?? []) if (!found2.has(child)) queue.push(child);
15707
+ }
15708
+ return [...found2];
15709
+ }
15710
+ function marked(mark, roots = []) {
15711
+ if (WINDOWS3 || !mark.value) return [];
15712
+ const entry = `${mark.name}=${mark.value}`;
15713
+ try {
15714
+ const pids = process.platform === "linux" ? markedInProc(entry) : markedInPs(entry, roots);
15715
+ return pids.filter((pid) => pid !== process.pid);
15716
+ } catch {
15717
+ return [];
15718
+ }
15719
+ }
15720
+ function signal(pids, sig) {
15721
+ for (const pid of pids) {
15722
+ try {
15723
+ process.kill(pid, sig);
15724
+ } catch {
15725
+ }
15726
+ }
15727
+ }
15728
+ function stopWatchers(sessions, onlyPid, stillOwns = () => true, startedBefore) {
15729
+ if (sessions ? !sessions.length : onlyPid === void 0) return [];
15730
+ const command = WINDOWS3 ? "powershell.exe" : "ps";
15731
+ const args = WINDOWS3 ? ["-NoProfile", "-NonInteractive", "-Command", "Get-CimInstance Win32_Process | Select-Object ProcessId,CommandLine,@{Name='StartedAt';Expression={([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()}} | ConvertTo-Json -Compress"] : ["-A", "-ww", "-o", "pid=,lstart=,command="];
15732
+ const out = spawnSync4(command, args, { encoding: "utf8", timeout: 5e3, maxBuffer: 16 * 1024 * 1024, windowsHide: true, env: { ...process.env, LC_ALL: "C" } });
15733
+ if (out.status !== 0) return [];
15734
+ let procs;
15735
+ try {
15736
+ procs = WINDOWS3 ? [].concat(JSON.parse(out.stdout)).map((p) => ({ pid: p.ProcessId, command: p.CommandLine ?? "", startedAt: p.StartedAt })) : out.stdout.split("\n").flatMap((line) => {
15737
+ const m = /^\s*(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d{4})\s+(.*)$/.exec(line);
15738
+ return m ? [{ pid: Number(m[1]), command: m[3], startedAt: Date.parse(m[2]) }] : [];
15739
+ });
15740
+ } catch {
15741
+ return [];
15742
+ }
15743
+ const known2 = sessions && new Set(sessions);
15744
+ const stopped2 = [];
15745
+ for (const proc of procs) {
15746
+ if (proc.pid === process.pid || onlyPid !== void 0 && proc.pid !== onlyPid) continue;
15747
+ if (startedBefore !== void 0 && (!Number.isFinite(proc.startedAt) || proc.startedAt > startedBefore)) continue;
15748
+ const match = /^"?[^\n]*?\bnode(?:\.exe)?"?\s+(?:"[^\n"]+\.mjs"|\S+\.mjs)\s+__watch\s+(\S+)(?:\s|$)/.exec(proc.command);
15749
+ const args2 = `${proc.command} `;
15750
+ const names4 = (flag, value) => args2.includes(` ${flag} ${value} `) || args2.includes(` ${flag} "${value}" `);
15751
+ const board2 = names4("--board", KANBAN) || KANBAN === path44.join(REPO_ROOT, "docs", "kanban") && names4("--dir", REPO_ROOT);
15752
+ if (!match || known2 && !known2.has(match[1]) || !board2 || !stillOwns()) continue;
15753
+ if (WINDOWS3) {
15754
+ if (killTreeOnWindows(proc.pid)) stopped2.push(proc.pid);
15755
+ } else {
15756
+ try {
15757
+ process.kill(-proc.pid, "SIGKILL");
15758
+ stopped2.push(proc.pid);
15759
+ } catch {
15760
+ }
15761
+ }
15762
+ }
15763
+ return stopped2;
15764
+ }
15765
+ function startedUnder(list, root, since) {
15766
+ const self = list.procs.find((p) => p.pid === root);
15767
+ const from = since ?? self?.startedAt;
15768
+ if (from === void 0 || list.bootedAt > from) return [];
15769
+ if (self && self.startedAt > from) return [];
15770
+ const found2 = self ? [root] : [];
15771
+ const seen = /* @__PURE__ */ new Set([root]);
15772
+ const queue = [{ pid: root, startedAt: from }];
15773
+ for (const parent of queue) {
15774
+ for (const p of list.procs) {
15775
+ if (p.ppid !== parent.pid || seen.has(p.pid) || p.startedAt < parent.startedAt) continue;
15776
+ seen.add(p.pid);
15777
+ found2.push(p.pid);
15778
+ queue.push(p);
15779
+ }
15780
+ }
15781
+ return found2.reverse();
15782
+ }
15783
+ function readProcList(out) {
15784
+ const procs = [];
15785
+ let bootedAt;
15786
+ for (const line of out.split(/\r?\n/)) {
15787
+ const boot = /^boot (\d+)$/.exec(line.trim());
15788
+ if (boot) bootedAt = Number(boot[1]);
15789
+ const m = /^(\d+) (\d+) (\d+)$/.exec(line.trim());
15790
+ if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), startedAt: Number(m[3]) });
15791
+ }
15792
+ return bootedAt !== void 0 && procs.length ? { procs, bootedAt } : void 0;
15793
+ }
15794
+ function procsOnWindows() {
15795
+ const ps = spawnSync4("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST_PROCS], {
15796
+ encoding: "utf8",
15797
+ maxBuffer: 64 * 1024 * 1024,
15798
+ timeout: 5e3,
15799
+ windowsHide: true
15800
+ });
15801
+ return ps.status === 0 && ps.stdout ? readProcList(ps.stdout) : void 0;
15802
+ }
15803
+ function killUnderOnWindows(pid, since) {
15804
+ if (!WINDOWS3 || !pid) return;
15805
+ const list = procsOnWindows();
15806
+ if (!list) return;
15807
+ const pids = startedUnder(list, pid, since).filter((p) => p !== process.pid);
15808
+ if (!pids.length) return;
15809
+ spawnSync4("taskkill", ["/F", ...pids.flatMap((p) => ["/PID", String(p)])], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
15810
+ }
15811
+ function killMarked(mark, agent) {
15812
+ if (WINDOWS3) {
15813
+ if (agent) killUnderOnWindows(agent.pid, agent.since);
15814
+ return;
15815
+ }
15816
+ signal(marked(mark), "SIGKILL");
15817
+ }
15818
+ function killTreeOnWindows(pid) {
15819
+ if (!WINDOWS3 || !pid) return false;
15820
+ const out = spawnSync4("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
15821
+ return out.status === 0;
15822
+ }
15823
+ function later(ms, fn) {
15824
+ const t = setTimeout(fn, ms);
15825
+ if (typeof t.unref === "function") t.unref();
15826
+ }
15827
+ function endAgent(child, mark, graceMs) {
15828
+ const term = (sig) => {
15829
+ try {
15830
+ child.kill(sig);
15831
+ } catch {
15832
+ }
15833
+ };
15834
+ if (killTreeOnWindows(child.pid)) return;
15835
+ killUnderOnWindows(child.pid);
15836
+ const seen = new Set(marked(mark, child.pid ? [child.pid] : []));
15837
+ term("SIGTERM");
15838
+ signal([...seen].filter((pid) => pid !== child.pid), "SIGTERM");
15839
+ const round = (left) => {
15840
+ const pids = marked(mark, [...seen]);
15841
+ signal(pids, "SIGKILL");
15842
+ for (const pid of pids) seen.add(pid);
15843
+ if (pids.length && left > 1) later(KILL_ROUND_MS, () => round(left - 1));
15844
+ };
15845
+ later(graceMs, () => {
15846
+ term("SIGKILL");
15847
+ round(KILL_ROUNDS);
15848
+ });
15849
+ }
15850
+ function killRunning() {
15851
+ for (const [child, mark] of running) {
15852
+ if (killTreeOnWindows(child.pid)) continue;
15853
+ killUnderOnWindows(child.pid);
15854
+ signal(marked(mark, child.pid ? [child.pid] : []), "SIGKILL");
15855
+ try {
15856
+ child.kill("SIGKILL");
15857
+ } catch {
15858
+ }
15859
+ }
15860
+ running.clear();
15861
+ }
15862
+ function unlisten() {
15863
+ for (const [sig, fn] of listening) process.removeListener(sig, fn);
15864
+ listening.clear();
15865
+ }
15866
+ function onQuit(sig) {
15867
+ killRunning();
15868
+ unlisten();
15869
+ if (process.listenerCount(sig) === 0) process.exit(128 + os6.constants.signals[sig]);
15870
+ }
15871
+ function trackAgent(child, mark) {
15872
+ if (!child.pid) return;
15873
+ running.set(child, mark);
15874
+ child.once("close", () => {
15875
+ running.delete(child);
15876
+ if (!running.size) unlisten();
15877
+ });
15878
+ for (const sig of QUIT_SIGNALS) {
15879
+ if (listening.has(sig) || sig === "SIGINT" && interruptIsTheCallers) continue;
15880
+ const fn = () => onQuit(sig);
15881
+ listening.set(sig, fn);
15882
+ process.on(sig, fn);
15883
+ }
15884
+ }
15885
+ var runMark, stopMark, markEnv, WINDOWS3, KILL_ROUND_MS, KILL_ROUNDS, LIST_PROCS, running, QUIT_SIGNALS, listening, interruptIsTheCallers;
15886
+ var init_stop = __esm({
15887
+ "src/lib/agent/stop.ts"() {
15888
+ "use strict";
15889
+ init_env();
15890
+ init_paths();
15891
+ runMark = (sessionId) => ({ name: RUN_ENV, value: sessionId });
15892
+ stopMark = () => ({ name: STOP_ENV, value: randomUUID5() });
15893
+ markEnv = (env2, mark) => ({ ...env2, [mark.name]: mark.value });
15894
+ WINDOWS3 = process.platform === "win32";
15895
+ KILL_ROUND_MS = 300;
15896
+ KILL_ROUNDS = 3;
15897
+ LIST_PROCS = [
15898
+ "$ErrorActionPreference = 'Stop'",
15899
+ "Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() } }",
15900
+ "'boot {0}' -f ([DateTimeOffset](Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToUnixTimeMilliseconds()"
15901
+ ].join("; ");
15902
+ running = /* @__PURE__ */ new Map();
15903
+ QUIT_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
15904
+ listening = /* @__PURE__ */ new Map();
15905
+ interruptIsTheCallers = false;
15906
+ }
15907
+ });
15908
+
15642
15909
  // src/lib/agent/pause.ts
15643
15910
  function deliveryState(delivery, questions) {
15644
15911
  const landing = delivery.landing;
@@ -15827,12 +16094,12 @@ var init_runner = __esm({
15827
16094
  });
15828
16095
 
15829
16096
  // src/lib/agent/rules.ts
15830
- import fs39 from "node:fs";
15831
- import path44 from "node:path";
16097
+ import fs40 from "node:fs";
16098
+ import path45 from "node:path";
15832
16099
  function ruleFile(agent) {
15833
16100
  if (!agent || hiddenRole(agent)) return "";
15834
16101
  try {
15835
- return fs39.readFileSync(rulePath(agent), "utf8").trim();
16102
+ return fs40.readFileSync(rulePath(agent), "utf8").trim();
15836
16103
  } catch {
15837
16104
  return "";
15838
16105
  }
@@ -15847,11 +16114,11 @@ function setAgentRule(agent, text5) {
15847
16114
  const rule = String(text5 ?? "").trim();
15848
16115
  try {
15849
16116
  if (!rule) {
15850
- fs39.rmSync(rulePath(agent), { force: true });
16117
+ fs40.rmSync(rulePath(agent), { force: true });
15851
16118
  return { ok: true };
15852
16119
  }
15853
- fs39.mkdirSync(RULES, { recursive: true });
15854
- fs39.writeFileSync(rulePath(agent), `${rule}
16120
+ fs40.mkdirSync(RULES, { recursive: true });
16121
+ fs40.writeFileSync(rulePath(agent), `${rule}
15855
16122
  `);
15856
16123
  return { ok: true };
15857
16124
  } catch (err) {
@@ -15899,7 +16166,7 @@ function migrateFlowRules() {
15899
16166
  adoptRenamedRules();
15900
16167
  let here;
15901
16168
  try {
15902
- here = new Set(fs39.readdirSync(RULES));
16169
+ here = new Set(fs40.readdirSync(RULES));
15903
16170
  } catch {
15904
16171
  return [];
15905
16172
  }
@@ -15910,9 +16177,9 @@ function migrateFlowRules() {
15910
16177
  if (!from.length) continue;
15911
16178
  const parts = [ruleFile(owner.name), ...from.map(ruleFile)].filter(Boolean);
15912
16179
  try {
15913
- if (parts.length) fs39.writeFileSync(rulePath(owner.name), `${parts.join("\n\n")}
16180
+ if (parts.length) fs40.writeFileSync(rulePath(owner.name), `${parts.join("\n\n")}
15914
16181
  `);
15915
- for (const flow of from) fs39.rmSync(rulePath(flow), { force: true });
16182
+ for (const flow of from) fs40.rmSync(rulePath(flow), { force: true });
15916
16183
  } catch (err) {
15917
16184
  notes.push(`could not move the ${from.join(", ")} rule(s) onto \`${owner.name}\`: ${String(err)}`);
15918
16185
  continue;
@@ -15926,7 +16193,7 @@ function migrateFlowRules() {
15926
16193
  function adoptRenamedRules() {
15927
16194
  let here;
15928
16195
  try {
15929
- here = fs39.readdirSync(RULES);
16196
+ here = fs40.readdirSync(RULES);
15930
16197
  } catch {
15931
16198
  return;
15932
16199
  }
@@ -15936,13 +16203,13 @@ function adoptRenamedRules() {
15936
16203
  const now = RENAMED_ROLES[was] ?? canonicalSpecAgent(was);
15937
16204
  if (now === was) continue;
15938
16205
  try {
15939
- if (!fs39.existsSync(rulePath(now))) fs39.renameSync(rulePath(was), rulePath(now));
16206
+ if (!fs40.existsSync(rulePath(now))) fs40.renameSync(rulePath(was), rulePath(now));
15940
16207
  else if (FOLDED_SPEC_AGENTS.has(was)) {
15941
16208
  const kept2 = ruleFile(now);
15942
16209
  const carried = ruleFile(was);
15943
- if (carried && !kept2.includes(carried)) fs39.writeFileSync(rulePath(now), `${[kept2, carried].filter(Boolean).join("\n\n")}
16210
+ if (carried && !kept2.includes(carried)) fs40.writeFileSync(rulePath(now), `${[kept2, carried].filter(Boolean).join("\n\n")}
15944
16211
  `);
15945
- fs39.rmSync(rulePath(was), { force: true });
16212
+ fs40.rmSync(rulePath(was), { force: true });
15946
16213
  }
15947
16214
  } catch {
15948
16215
  }
@@ -15959,7 +16226,7 @@ var init_rules2 = __esm({
15959
16226
  init_runner();
15960
16227
  init_workflows();
15961
16228
  init_types3();
15962
- rulePath = (agent) => path44.join(RULES, `${agent}.md`);
16229
+ rulePath = (agent) => path45.join(RULES, `${agent}.md`);
15963
16230
  notOnTheRoster = (name) => `"${name}" is not an agent on this board. It has: ${agentNames().join(", ")}.`;
15964
16231
  flowForRequest = (req) => req.refineRound !== void 0 && REFINE_ACTIONS.has(req.action) ? flowByCommand("refine") : flowByAction(req.action);
15965
16232
  ruleOwnerSays = (owner) => `\`${owner.name}\` agent carries one rule of its own${owner.role ? ", on every flow it runs" : ""}`;
@@ -16044,8 +16311,8 @@ var init_source = __esm({
16044
16311
  });
16045
16312
 
16046
16313
  // src/lib/card-sources.ts
16047
- import fs40 from "node:fs";
16048
- import path45 from "node:path";
16314
+ import fs41 from "node:fs";
16315
+ import path46 from "node:path";
16049
16316
  function planById(id) {
16050
16317
  const found2 = readPlan(`plans/${id}-.md`);
16051
16318
  return found2?.text.trim() ? found2 : null;
@@ -16055,8 +16322,8 @@ function cardLink(id) {
16055
16322
  const found2 = open3 ?? locateArchived(id);
16056
16323
  if (!found2) return null;
16057
16324
  try {
16058
- const file = found2.kind === "group" ? path45.join(found2.target, "root.md") : found2.target;
16059
- const title = parseFrontmatter(fs40.readFileSync(file, "utf8")).meta?.title ?? "";
16325
+ const file = found2.kind === "group" ? path46.join(found2.target, "root.md") : found2.target;
16326
+ const title = parseFrontmatter(fs41.readFileSync(file, "utf8")).meta?.title ?? "";
16060
16327
  return { kind: "card", ref: String(id), title, ...open3 ? {} : { archived: true } };
16061
16328
  } catch {
16062
16329
  return null;
@@ -16081,7 +16348,7 @@ function link(ref, items) {
16081
16348
  if (ref.kind === "plan") return planLink(ref.id);
16082
16349
  if (ref.kind === "card") return cardLink(ref.id);
16083
16350
  if (ref.kind === "url") return urlLink(ref.url);
16084
- const item = items().find((signal2) => path45.basename(signal2.relPath) === ref.file);
16351
+ const item = items().find((signal2) => path46.basename(signal2.relPath) === ref.file);
16085
16352
  return item ? itemLink(item) : null;
16086
16353
  }
16087
16354
  function cardSources(meta, body) {
@@ -16122,12 +16389,12 @@ var init_card_sources = __esm({
16122
16389
  });
16123
16390
 
16124
16391
  // src/lib/view/read.ts
16125
- import fs41 from "node:fs";
16126
- import path46 from "node:path";
16392
+ import fs42 from "node:fs";
16393
+ import path47 from "node:path";
16127
16394
  function readCard(file, relFromTodo) {
16128
- const id = idPrefix(path46.basename(relFromTodo));
16395
+ const id = idPrefix(path47.basename(relFromTodo));
16129
16396
  if (id === null) {
16130
- const parts = relFromTodo.split(path46.sep);
16397
+ const parts = relFromTodo.split(path47.sep);
16131
16398
  const folderId = idPrefix(parts[parts.length - 2] || "");
16132
16399
  if (folderId === null) return null;
16133
16400
  return buildCard(folderId, file, relFromTodo);
@@ -16135,10 +16402,10 @@ function readCard(file, relFromTodo) {
16135
16402
  return buildCard(id, file, relFromTodo);
16136
16403
  }
16137
16404
  function buildCard(id, file, relFromTodo) {
16138
- const text5 = fs41.readFileSync(file, "utf8");
16405
+ const text5 = fs42.readFileSync(file, "utf8");
16139
16406
  const { meta, body } = parseFrontmatter(text5);
16140
16407
  if (!meta) return null;
16141
- const relPath = relFromTodo.split(path46.sep).join("/");
16408
+ const relPath = relFromTodo.split(path47.sep).join("/");
16142
16409
  const flow = workflowFor(meta.workflow);
16143
16410
  const plan = !!meta.workflow && archivesOnApproval(flow);
16144
16411
  const stages = cardStages(meta, flow).length;
@@ -16147,7 +16414,7 @@ function buildCard(id, file, relFromTodo) {
16147
16414
  // Derived from the file exactly as it is on disk (lib/board/revision.ts), so a card
16148
16415
  // read here and a card read by the contract agree on what version this is.
16149
16416
  revision: revisionOf(text5),
16150
- updatedAt: fs41.statSync(file).mtime.toISOString(),
16417
+ updatedAt: fs42.statSync(file).mtime.toISOString(),
16151
16418
  relPath,
16152
16419
  title: meta.title,
16153
16420
  priority: meta.priority,
@@ -16168,22 +16435,22 @@ function buildCard(id, file, relFromTodo) {
16168
16435
  };
16169
16436
  }
16170
16437
  function readGroup2(folderName) {
16171
- const groupDir = path46.join(TODO, folderName);
16172
- const rootFile = path46.join(groupDir, "root.md");
16173
- if (!fs41.existsSync(rootFile)) return null;
16174
- const root = readCard(rootFile, path46.join(folderName, "root.md"));
16438
+ const groupDir = path47.join(TODO, folderName);
16439
+ const rootFile = path47.join(groupDir, "root.md");
16440
+ if (!fs42.existsSync(rootFile)) return null;
16441
+ const root = readCard(rootFile, path47.join(folderName, "root.md"));
16175
16442
  if (!root) return null;
16176
16443
  root.isGroup = true;
16177
16444
  const { total, resolved: resolved2 } = subtaskLines(root.body);
16178
16445
  root.subtaskLines = { total, resolved: resolved2 };
16179
16446
  const subCards = [];
16180
16447
  const recurse = (dir, relDir) => {
16181
- for (const entry of fs41.readdirSync(dir, { withFileTypes: true })) {
16182
- const childRel = path46.join(relDir, entry.name);
16448
+ for (const entry of fs42.readdirSync(dir, { withFileTypes: true })) {
16449
+ const childRel = path47.join(relDir, entry.name);
16183
16450
  if (entry.isDirectory()) {
16184
- recurse(path46.join(dir, entry.name), childRel);
16451
+ recurse(path47.join(dir, entry.name), childRel);
16185
16452
  } else if (entry.name.endsWith(".md") && entry.name !== "README.md" && entry.name !== "root.md") {
16186
- const c = readCard(path46.join(dir, entry.name), childRel);
16453
+ const c = readCard(path47.join(dir, entry.name), childRel);
16187
16454
  if (c) {
16188
16455
  c.parent = { id: root.id, title: root.title };
16189
16456
  subCards.push(c);
@@ -16204,12 +16471,12 @@ function readGroup2(folderName) {
16204
16471
  return { root, subCards };
16205
16472
  }
16206
16473
  function standaloneCards(dirRel) {
16207
- const dir = dirRel ? path46.join(TODO, dirRel) : TODO;
16208
- if (!fs41.existsSync(dir)) return [];
16474
+ const dir = dirRel ? path47.join(TODO, dirRel) : TODO;
16475
+ if (!fs42.existsSync(dir)) return [];
16209
16476
  const cards = [];
16210
- for (const entry of fs41.readdirSync(dir, { withFileTypes: true })) {
16477
+ for (const entry of fs42.readdirSync(dir, { withFileTypes: true })) {
16211
16478
  if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md") {
16212
- const c = readCard(path46.join(dir, entry.name), path46.join(dirRel, entry.name));
16479
+ const c = readCard(path47.join(dir, entry.name), path47.join(dirRel, entry.name));
16213
16480
  if (c) cards.push(c);
16214
16481
  }
16215
16482
  }
@@ -16221,7 +16488,7 @@ function collectCards() {
16221
16488
  const top = standaloneCards("");
16222
16489
  board2.push(...top);
16223
16490
  every.push(...top);
16224
- for (const entry of fs41.readdirSync(TODO, { withFileTypes: true })) {
16491
+ for (const entry of fs42.readdirSync(TODO, { withFileTypes: true })) {
16225
16492
  if (!entry.isDirectory()) continue;
16226
16493
  if (isGroupFolder(entry.name)) {
16227
16494
  const g = readGroup2(entry.name);
@@ -16253,7 +16520,7 @@ function findCard(id) {
16253
16520
  }
16254
16521
  function attachSources(card) {
16255
16522
  try {
16256
- const { meta, body } = parseFrontmatter(fs41.readFileSync(path46.join(TODO, card.relPath), "utf8"));
16523
+ const { meta, body } = parseFrontmatter(fs42.readFileSync(path47.join(TODO, card.relPath), "utf8"));
16257
16524
  const sources = meta ? cardSources(meta, body) : [];
16258
16525
  if (sources.length) card.sources = sources;
16259
16526
  } catch {
@@ -16441,8 +16708,8 @@ var init_review = __esm({
16441
16708
  });
16442
16709
 
16443
16710
  // src/lib/agent/deliveries.ts
16444
- import fs42 from "node:fs";
16445
- import path47 from "node:path";
16711
+ import fs43 from "node:fs";
16712
+ import path48 from "node:path";
16446
16713
  function writeAudit(delivery, runs) {
16447
16714
  const known2 = new Map(readAudit(delivery.deliveryId)?.sessions.map((s) => [s.sessionId, s]) ?? []);
16448
16715
  const sessions = delivery.sessions.flatMap((id) => {
@@ -16470,10 +16737,10 @@ function writeAudit(delivery, runs) {
16470
16737
  }
16471
16738
  function writeAuditFile(record) {
16472
16739
  try {
16473
- fs42.mkdirSync(DELIVERIES, { recursive: true });
16740
+ fs43.mkdirSync(DELIVERIES, { recursive: true });
16474
16741
  const tmp = `${auditPath(record.deliveryId)}.tmp`;
16475
- fs42.writeFileSync(tmp, JSON.stringify(record, null, 2) + "\n");
16476
- fs42.renameSync(tmp, auditPath(record.deliveryId));
16742
+ fs43.writeFileSync(tmp, JSON.stringify(record, null, 2) + "\n");
16743
+ fs43.renameSync(tmp, auditPath(record.deliveryId));
16477
16744
  return true;
16478
16745
  } catch {
16479
16746
  return false;
@@ -16481,7 +16748,7 @@ function writeAuditFile(record) {
16481
16748
  }
16482
16749
  function readAudit(deliveryId) {
16483
16750
  try {
16484
- const data = JSON.parse(fs42.readFileSync(auditPath(deliveryId), "utf8"));
16751
+ const data = JSON.parse(fs43.readFileSync(auditPath(deliveryId), "utf8"));
16485
16752
  return { sessions: Array.isArray(data?.sessions) ? data.sessions : [] };
16486
16753
  } catch {
16487
16754
  return null;
@@ -16496,7 +16763,7 @@ function syncAudit(deliveryId, just) {
16496
16763
  }
16497
16764
  function wholeAudit(file) {
16498
16765
  try {
16499
- const data = JSON.parse(fs42.readFileSync(file, "utf8"));
16766
+ const data = JSON.parse(fs43.readFileSync(file, "utf8"));
16500
16767
  return typeof data?.deliveryId === "string" && Array.isArray(data.sessions) ? data : null;
16501
16768
  } catch {
16502
16769
  return null;
@@ -16509,14 +16776,14 @@ function activeAudit(file) {
16509
16776
  function allAudits() {
16510
16777
  let names4;
16511
16778
  try {
16512
- names4 = fs42.readdirSync(DELIVERIES);
16779
+ names4 = fs43.readdirSync(DELIVERIES);
16513
16780
  } catch {
16514
16781
  return [];
16515
16782
  }
16516
16783
  const out = [];
16517
16784
  for (const name of names4) {
16518
16785
  if (!name.endsWith(".json")) continue;
16519
- const audit = wholeAudit(path47.join(DELIVERIES, name));
16786
+ const audit = wholeAudit(path48.join(DELIVERIES, name));
16520
16787
  if (audit) out.push(audit);
16521
16788
  }
16522
16789
  return out;
@@ -16627,11 +16894,11 @@ function resumeRefusal(delivery, store) {
16627
16894
  );
16628
16895
  }
16629
16896
  if (!worktreeExists(delivery.worktree)) {
16630
- const path86 = delivery.worktree ?? "";
16897
+ const path88 = delivery.worktree ?? "";
16631
16898
  return refusal(
16632
16899
  "deliveryWorktreeGone",
16633
- `delivery ${id}'s worktree ${path86} is gone, so there is nothing to carry on. ${rebuild}`,
16634
- { id, task, path: path86, command: discard }
16900
+ `delivery ${id}'s worktree ${path88} is gone, so there is nothing to carry on. ${rebuild}`,
16901
+ { id, task, path: path88, command: discard }
16635
16902
  );
16636
16903
  }
16637
16904
  if (!branchExists(delivery.branch)) {
@@ -16684,11 +16951,12 @@ function tidyCheckout(deliveryId) {
16684
16951
  const store = readStore();
16685
16952
  const row = store.deliveries.find((d) => d.deliveryId === deliveryId) ?? auditOnly(deliveryId);
16686
16953
  if (!row || row.status === "active") return NOTHING;
16687
- if (!row.worktree && !row.branch) return NOTHING;
16688
- if (isResumable(row)) return { removed: false, kept: true };
16689
16954
  if (store.runs.some((r) => r.deliveryId === deliveryId && runIsLive(r))) {
16690
16955
  return { removed: false, kept: false, error: `a run of delivery ${deliveryId} is still going`, reason: "deliveryRunGoing", args: { id: deliveryId } };
16691
16956
  }
16957
+ if (row.status !== "finished" || Date.now() - (row.endedAt ?? 0) > 3e4) stopWatchers(row.sessions);
16958
+ if (!row.worktree && !row.branch) return NOTHING;
16959
+ if (isResumable(row)) return { removed: false, kept: true };
16692
16960
  const removed = removeWorktree(row.worktree, row.branch, true);
16693
16961
  if (!removed.ok) return { removed: false, kept: false, error: removed.error };
16694
16962
  forgetCheckout(deliveryId);
@@ -16711,7 +16979,10 @@ function forgetCheckout(deliveryId) {
16711
16979
  function sweepCheckouts() {
16712
16980
  const seen = /* @__PURE__ */ new Set();
16713
16981
  const complaints = [];
16714
- const rows = [...readStore().deliveries, ...allAudits().flatMap((a) => auditRow(a) ?? [])];
16982
+ const store = readStore();
16983
+ const rows = [...store.deliveries, ...allAudits().flatMap((a) => auditRow(a) ?? [])];
16984
+ const ended = rows.filter((row) => row.status !== "active" && (row.status !== "finished" || Date.now() - (row.endedAt ?? 0) > 3e4) && !store.runs.some((r) => r.deliveryId === row.deliveryId && runIsLive(r)));
16985
+ stopWatchers([...new Set(ended.flatMap((row) => row.sessions))]);
16715
16986
  for (const row of rows) {
16716
16987
  if (seen.has(row.deliveryId) || row.status === "active" || !row.worktree) continue;
16717
16988
  seen.add(row.deliveryId);
@@ -16721,21 +16992,27 @@ function sweepCheckouts() {
16721
16992
  dropEmptyWorktreeFolders();
16722
16993
  return complaints;
16723
16994
  }
16724
- function resumeRecord(id) {
16725
- const found2 = endedDelivery(id);
16995
+ function resumeRecord(id, execution) {
16996
+ const continueActive = !!execution;
16997
+ const found2 = (continueActive ? namedDelivery(id) : void 0) ?? endedDelivery(id);
16726
16998
  if (!found2) return { ok: false, ...unknownDelivery(id) };
16727
16999
  const refused = resumeRefusal(found2);
16728
- if (refused) return { ok: false, ...refused };
17000
+ if (refused && !(continueActive && found2.status === "active")) return { ok: false, ...refused };
16729
17001
  const out = withStore((store) => {
16730
17002
  const audit = wholeAudit(auditPath(found2.deliveryId));
16731
- const row = (audit && auditRow(audit)) ?? store.deliveries.find((d) => d.deliveryId === found2.deliveryId);
17003
+ const live = store.deliveries.find((d) => d.deliveryId === found2.deliveryId);
17004
+ const row = continueActive && live?.status === "active" ? live : (audit && auditRow(audit)) ?? live;
16732
17005
  if (!row) return { ok: false, ...unknownDelivery(id) };
16733
17006
  const again = resumeRefusal(row, store);
16734
- if (again) return { ok: false, ...again };
17007
+ if (continueActive && row.status === "active") {
17008
+ if (store.runs.some((r) => r.deliveryId === row.deliveryId && runIsLive(r))) {
17009
+ return { ok: false, ...refusal("deliveryRunGoing", "the delivery still has a running agent; stop it before continuing") };
17010
+ }
17011
+ } else if (again) return { ok: false, ...again };
16735
17012
  const at = Date.now();
16736
17013
  const resumed = {
16737
17014
  ...row,
16738
- cloudExecution: executionOf() ?? row.cloudExecution,
17015
+ cloudExecution: execution ?? executionOf() ?? row.cloudExecution,
16739
17016
  status: "active",
16740
17017
  endedAt: void 0,
16741
17018
  steps: [...row.steps, { step: "resume", at }],
@@ -16764,10 +17041,10 @@ function carryOnFrom(deliveryId) {
16764
17041
  function approvedRequirements(cardId2) {
16765
17042
  const found2 = locate(cardId2);
16766
17043
  if (!found2) return "";
16767
- const file = found2.kind === "group" ? path47.join(found2.target, "root.md") : found2.target;
17044
+ const file = found2.kind === "group" ? path48.join(found2.target, "root.md") : found2.target;
16768
17045
  let text5;
16769
17046
  try {
16770
- text5 = fs42.readFileSync(file, "utf8");
17047
+ text5 = fs43.readFileSync(file, "utf8");
16771
17048
  } catch {
16772
17049
  return "";
16773
17050
  }
@@ -16797,8 +17074,8 @@ function cardMeta2(cardId2) {
16797
17074
  try {
16798
17075
  const found2 = locate(cardId2);
16799
17076
  if (!found2) return null;
16800
- const file = found2.kind === "group" ? path47.join(found2.target, "root.md") : found2.target;
16801
- return parseFrontmatter(fs42.readFileSync(file, "utf8")).meta;
17077
+ const file = found2.kind === "group" ? path48.join(found2.target, "root.md") : found2.target;
17078
+ return parseFrontmatter(fs43.readFileSync(file, "utf8")).meta;
16802
17079
  } catch {
16803
17080
  return null;
16804
17081
  }
@@ -17047,6 +17324,7 @@ var init_deliveries = __esm({
17047
17324
  init_complete();
17048
17325
  init_outputs();
17049
17326
  init_env();
17327
+ init_stop();
17050
17328
  init_flows();
17051
17329
  init_pause();
17052
17330
  init_rules2();
@@ -17056,7 +17334,7 @@ var init_deliveries = __esm({
17056
17334
  init_store();
17057
17335
  init_types3();
17058
17336
  init_worktree();
17059
- auditPath = (deliveryId) => path47.join(DELIVERIES, `${deliveryId}.json`);
17337
+ auditPath = (deliveryId) => path48.join(DELIVERIES, `${deliveryId}.json`);
17060
17338
  activeAudits = () => allAudits().filter((a) => a.status === "active");
17061
17339
  auditRow = (audit) => readDeliveryRow({ ...audit, sessions: audit.sessions.map((s) => s.sessionId) });
17062
17340
  lastSessionRunning = (audit) => audit.sessions[audit.sessions.length - 1]?.status === "running";
@@ -17084,6 +17362,41 @@ var init_deliveries = __esm({
17084
17362
  }
17085
17363
  });
17086
17364
 
17365
+ // src/lib/agent/landing-lock.ts
17366
+ import fs44 from "node:fs";
17367
+ import path49 from "node:path";
17368
+ function lockLanding() {
17369
+ const dir = path49.join(SESSIONS_DIR, ".landing.lock");
17370
+ try {
17371
+ const entries = fs44.readdirSync(dir);
17372
+ const token3 = entries.length === 1 ? entries[0] : "";
17373
+ const match = /^(\d+)-[a-f0-9-]{36}$/.exec(token3);
17374
+ const stat = fs44.statSync(dir);
17375
+ if (match && Date.now() - stat.mtimeMs > landingLimits.staleMs) {
17376
+ stopWatchers(void 0, Number(match[1]), () => {
17377
+ const now = fs44.readdirSync(dir);
17378
+ return now.length === 1 && now[0] === token3 && Date.now() - fs44.statSync(dir).mtimeMs > landingLimits.staleMs;
17379
+ }, stat.birthtimeMs || stat.mtimeMs);
17380
+ }
17381
+ } catch {
17382
+ }
17383
+ return tryLock(dir);
17384
+ }
17385
+ function renewLandingLock() {
17386
+ const now = /* @__PURE__ */ new Date();
17387
+ fs44.utimesSync(path49.join(SESSIONS_DIR, ".landing.lock"), now, now);
17388
+ }
17389
+ var landingLimits;
17390
+ var init_landing_lock = __esm({
17391
+ "src/lib/agent/landing-lock.ts"() {
17392
+ "use strict";
17393
+ init_lock();
17394
+ init_paths();
17395
+ init_stop();
17396
+ landingLimits = { staleMs: 5 * 6e4 };
17397
+ }
17398
+ });
17399
+
17087
17400
  // src/lib/agent/answers.ts
17088
17401
  function answerOutcome(delivery) {
17089
17402
  return pendingAnswers(delivery).some((a) => a.outcome === "changed") ? "changed" : "unchanged";
@@ -17148,8 +17461,8 @@ var init_retry = __esm({
17148
17461
  });
17149
17462
 
17150
17463
  // src/lib/agent/landing.ts
17151
- import fs43 from "node:fs";
17152
- import path48 from "node:path";
17464
+ import fs45 from "node:fs";
17465
+ import path50 from "node:path";
17153
17466
  function waitingOut(delivery, now = Date.now()) {
17154
17467
  const landing = delivery.landing;
17155
17468
  if (!landing) return false;
@@ -17285,8 +17598,9 @@ function noteQueue(held4) {
17285
17598
  }
17286
17599
  async function advanceLanding() {
17287
17600
  let release;
17601
+ let current;
17288
17602
  try {
17289
- release = tryLock(path48.join(SESSIONS_DIR, ".landing.lock"));
17603
+ release = lockLanding();
17290
17604
  if (!release) return null;
17291
17605
  const owed = await owedRestart();
17292
17606
  if (owed) return owed;
@@ -17301,11 +17615,19 @@ async function advanceLanding() {
17301
17615
  return null;
17302
17616
  }
17303
17617
  tried.add(picked.deliveryId);
17618
+ current = picked;
17619
+ renewLandingLock();
17304
17620
  const step = await landStep(picked);
17305
17621
  if (step.start) return step.start;
17306
17622
  if (!step.done) return null;
17307
17623
  }
17308
- } catch {
17624
+ } catch (error) {
17625
+ if (current && error instanceof GitTimeoutError) {
17626
+ giveUpSlot(current, error.message);
17627
+ patchLanding(current.deliveryId, (landing) => {
17628
+ landing.retryAt = Date.now() + 3e4;
17629
+ });
17630
+ }
17309
17631
  return null;
17310
17632
  } finally {
17311
17633
  release?.();
@@ -17622,7 +17944,7 @@ async function settleAlreadyLanded(delivery) {
17622
17944
  return true;
17623
17945
  }
17624
17946
  function repairLanding() {
17625
- const release = tryLock(path48.join(SESSIONS_DIR, ".landing.lock"));
17947
+ const release = lockLanding();
17626
17948
  if (!release) return [];
17627
17949
  try {
17628
17950
  return repairIdleLanding();
@@ -17655,7 +17977,7 @@ var init_landing = __esm({
17655
17977
  init_execution();
17656
17978
  init_board();
17657
17979
  init_io();
17658
- init_lock();
17980
+ init_landing_lock();
17659
17981
  init_paths();
17660
17982
  init_answers();
17661
17983
  init_commit_mode();
@@ -17696,9 +18018,9 @@ var init_landing = __esm({
17696
18018
  sameDir = (a, b) => {
17697
18019
  const real2 = (dir) => {
17698
18020
  try {
17699
- return fs43.realpathSync(dir);
18021
+ return fs45.realpathSync(dir);
17700
18022
  } catch {
17701
- return path48.resolve(dir);
18023
+ return path50.resolve(dir);
17702
18024
  }
17703
18025
  };
17704
18026
  return real2(a) === real2(b);
@@ -17707,35 +18029,35 @@ var init_landing = __esm({
17707
18029
  });
17708
18030
 
17709
18031
  // src/lib/agent/pictures.ts
17710
- import fs44 from "node:fs";
17711
- import path49 from "node:path";
18032
+ import fs46 from "node:fs";
18033
+ import path51 from "node:path";
17712
18034
  function claimRunPictures(box2, sessionId, names4 = []) {
17713
18035
  if (!box2 || !freeBox(box2) || names4.length === 0) return [];
17714
18036
  const from = pictureBox(box2);
17715
18037
  const to = pictureBox(sessionId);
17716
18038
  try {
17717
- fs44.mkdirSync(SESSIONS_DIR, { recursive: true });
17718
- fs44.renameSync(from, to);
18039
+ fs46.mkdirSync(SESSIONS_DIR, { recursive: true });
18040
+ fs46.renameSync(from, to);
17719
18041
  } catch {
17720
18042
  return [];
17721
18043
  }
17722
- return names4.filter(pictureName).map((name) => path49.join(to, name)).filter((file) => fs44.existsSync(file));
18044
+ return names4.filter(pictureName).map((name) => path51.join(to, name)).filter((file) => fs46.existsSync(file));
17723
18045
  }
17724
18046
  function returnRunPictures(sessionId, box2) {
17725
18047
  if (!box2 || !boxId(box2)) return;
17726
18048
  try {
17727
- fs44.renameSync(pictureBox(sessionId), pictureBox(box2));
18049
+ fs46.renameSync(pictureBox(sessionId), pictureBox(box2));
17728
18050
  } catch {
17729
18051
  }
17730
18052
  }
17731
18053
  function moveRunPictures(from, to, files2 = []) {
17732
18054
  if (files2.length === 0) return [];
17733
18055
  try {
17734
- fs44.renameSync(pictureBox(from), pictureBox(to));
18056
+ fs46.renameSync(pictureBox(from), pictureBox(to));
17735
18057
  } catch {
17736
18058
  return files2;
17737
18059
  }
17738
- return files2.map((file) => path49.join(pictureBox(to), path49.basename(file)));
18060
+ return files2.map((file) => path51.join(pictureBox(to), path51.basename(file)));
17739
18061
  }
17740
18062
  var pictureName, boxId, freeBox, pictureBox;
17741
18063
  var init_pictures = __esm({
@@ -17744,14 +18066,14 @@ var init_pictures = __esm({
17744
18066
  init_paths();
17745
18067
  pictureName = (name) => /^[0-9a-f-]{36}\.[a-z0-9]{2,5}$/.test(name);
17746
18068
  boxId = (box2) => /^[0-9a-f-]{36}$/.test(box2);
17747
- freeBox = (box2) => boxId(box2) && !fs44.existsSync(path49.join(SESSIONS_DIR, `${box2}.log`));
17748
- pictureBox = (box2) => path49.join(SESSIONS_DIR, `${box2}.images`);
18069
+ freeBox = (box2) => boxId(box2) && !fs46.existsSync(path51.join(SESSIONS_DIR, `${box2}.log`));
18070
+ pictureBox = (box2) => path51.join(SESSIONS_DIR, `${box2}.images`);
17749
18071
  }
17750
18072
  });
17751
18073
 
17752
18074
  // src/lib/memories.ts
17753
- import fs45 from "node:fs";
17754
- import path50 from "node:path";
18075
+ import fs47 from "node:fs";
18076
+ import path52 from "node:path";
17755
18077
  function readMemory(text5, builtIn, folder) {
17756
18078
  const { meta, body } = splitFrontmatter(text5);
17757
18079
  if (meta === null) return null;
@@ -17771,7 +18093,7 @@ function readMemory(text5, builtIn, folder) {
17771
18093
  rules: body.trim(),
17772
18094
  text: text5,
17773
18095
  builtIn,
17774
- dir: path50.join(MEMORY, folder)
18096
+ dir: path52.join(MEMORY, folder)
17775
18097
  };
17776
18098
  }
17777
18099
  function globalMemories() {
@@ -17782,14 +18104,14 @@ function globalMemories() {
17782
18104
  }
17783
18105
  let folders2 = [];
17784
18106
  try {
17785
- folders2 = fs45.readdirSync(MEMORY, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
18107
+ folders2 = fs47.readdirSync(MEMORY, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
17786
18108
  } catch {
17787
18109
  }
17788
18110
  for (const name of folders2) {
17789
18111
  if (name in BUNDLED_MEMORY_FILES || name === RESERVED_MEMORY_DIR) continue;
17790
- const file = path50.join(MEMORY, name, GLOBAL_MEMORY_FILE);
17791
- if (!fs45.existsSync(file)) continue;
17792
- const memory = readMemory(fs45.readFileSync(file, "utf8"), false, name);
18112
+ const file = path52.join(MEMORY, name, GLOBAL_MEMORY_FILE);
18113
+ if (!fs47.existsSync(file)) continue;
18114
+ const memory = readMemory(fs47.readFileSync(file, "utf8"), false, name);
17793
18115
  if (memory) out.push(memory);
17794
18116
  }
17795
18117
  return out;
@@ -17845,16 +18167,16 @@ var init_facts = __esm({
17845
18167
  });
17846
18168
 
17847
18169
  // src/lib/view/archive.ts
17848
- import fs46 from "node:fs";
17849
- import path51 from "node:path";
18170
+ import fs48 from "node:fs";
18171
+ import path53 from "node:path";
17850
18172
  function archivedId(file) {
17851
- const own = idPrefix(path51.basename(file));
17852
- return own !== null ? own : idPrefix(path51.basename(path51.dirname(file)));
18173
+ const own = idPrefix(path53.basename(file));
18174
+ return own !== null ? own : idPrefix(path53.basename(path53.dirname(file)));
17853
18175
  }
17854
18176
  function readFile(file) {
17855
18177
  const id = archivedId(file);
17856
18178
  if (id === null) return null;
17857
- const { meta, body } = parseFrontmatter(fs46.readFileSync(file, "utf8"));
18179
+ const { meta, body } = parseFrontmatter(fs48.readFileSync(file, "utf8"));
17858
18180
  if (!meta) return null;
17859
18181
  return {
17860
18182
  row: {
@@ -17862,15 +18184,15 @@ function readFile(file) {
17862
18184
  title: meta.title,
17863
18185
  archived: meta.archived,
17864
18186
  rejected: meta.rejected,
17865
- relPath: rel(file).split(path51.sep).join("/")
18187
+ relPath: rel(file).split(path53.sep).join("/")
17866
18188
  },
17867
18189
  body: body.replace(/^\n+/, "").replace(/\s+$/, ""),
17868
18190
  meta
17869
18191
  };
17870
18192
  }
17871
18193
  function readArchive() {
17872
- const relPath = rel(ARCHIVE).split(path51.sep).join("/");
17873
- if (!fs46.existsSync(ARCHIVE)) return { relPath, cards: [] };
18194
+ const relPath = rel(ARCHIVE).split(path53.sep).join("/");
18195
+ if (!fs48.existsSync(ARCHIVE)) return { relPath, cards: [] };
17874
18196
  const cards = walkMd(ARCHIVE).map(readFile).filter((found2) => found2 !== null).map((found2) => found2.row);
17875
18197
  cards.sort((a, b) => b.id - a.id);
17876
18198
  return { relPath, cards };
@@ -17885,7 +18207,7 @@ var init_archive = __esm({
17885
18207
  });
17886
18208
 
17887
18209
  // src/lib/agent/prompts.ts
17888
- import path52 from "node:path";
18210
+ import path54 from "node:path";
17889
18211
  function resumePrompt(deliveryId, cardId2, action) {
17890
18212
  if (!deliveryId) return RESUME_PROMPT;
17891
18213
  if (action === "conflict") {
@@ -17900,11 +18222,11 @@ function resumePrompt(deliveryId, cardId2, action) {
17900
18222
  const approved = delivery?.approved.trim();
17901
18223
  if (!approved) return lead;
17902
18224
  if (delivery?.plan) {
17903
- return `${lead} No card was written yet: write it from the plan this delivery was approved to build, as \`akb guide implement\` says, then build exactly that and nothing more. It came from \`${delivery.plan}\`, and this is the copy to build:
18225
+ return `${lead} Build exactly the approved plan below following \`akb guide implement\`; create no card. It came from \`${delivery.plan}\`, and this is the copy to build:
17904
18226
 
17905
18227
  ${approved}`;
17906
18228
  }
17907
- return `${lead} No card was written yet: write it from this sentence as \`akb guide implement\` says, then build exactly it and nothing more \u2014 "${approved}".`;
18229
+ return `${lead} Follow \`akb guide implement\`: create no card and build exactly this approved requirement and nothing more \u2014 "${approved}".`;
17908
18230
  }
17909
18231
  function contractRepairPrompt(req, errors) {
17910
18232
  const command = boardCommandFor(req.id);
@@ -17929,7 +18251,7 @@ function buildAsk(rawReq, notes = []) {
17929
18251
  }
17930
18252
  function cardFileOf(id) {
17931
18253
  const found2 = id === void 0 ? null : locate(id);
17932
- return found2 ? found2.kind === "group" ? path52.join(found2.target, "root.md") : found2.target : "";
18254
+ return found2 ? found2.kind === "group" ? path54.join(found2.target, "root.md") : found2.target : "";
17933
18255
  }
17934
18256
  function realPaths(text5, req) {
17935
18257
  if (req.action !== "scheduled" && req.action !== "sub") return text5;
@@ -18022,7 +18344,7 @@ function frozenRules(req) {
18022
18344
  function archivedCardFile(id) {
18023
18345
  const found2 = locateArchived(id);
18024
18346
  if (!found2) return `${rel(ARCHIVE)}/`;
18025
- return rel(found2.kind === "group" ? path52.join(found2.target, "root.md") : found2.target);
18347
+ return rel(found2.kind === "group" ? path54.join(found2.target, "root.md") : found2.target);
18026
18348
  }
18027
18349
  function shippedLines(cardId2) {
18028
18350
  const delivery = endedDelivery(`${cardId2}`);
@@ -18083,17 +18405,12 @@ function actionPrompt(req, command, notes) {
18083
18405
  const named2 = req.title ? `${tag} ("${req.title}")` : tag;
18084
18406
  if (isRetired(req.action)) return "";
18085
18407
  switch (req.action) {
18086
- // A build that writes its own card (#470): the typed sentence IS the requirement, so it
18087
- // is quoted here rather than pointed at, and the run's first act is the card it holds.
18088
- // Answered off the plan handoff it is a plan instead (#481), named the way a create off one
18089
- // is: the words are in the file, and a copy pasted in here would go stale.
18408
+ // A cardless build takes its requirement from the sentence or approved plan.
18090
18409
  case "implement":
18091
18410
  if (req.id === void 0) {
18092
18411
  return [
18093
18412
  req.plan ? `${kb}. Build the plan at \`${req.plan}\`, written in this conversation. The plan is the contract; use what was said here only to clarify its intent.` : `${kb}. Build this: "${req.description?.trim() ?? ""}".`,
18094
- req.plan ? `Follow \`akb guide implement\` \u2014 write its card first, from that plan, then build it.` : `Follow \`akb guide implement\` \u2014 write its card first, from that sentence, then build it.`,
18095
- createWorkflowNote(req),
18096
- `Resolve routine choices yourself; record blockers needing user action on the card following \`akb guide update-questions\`.`
18413
+ `Follow \`akb guide implement\` \u2014 build exactly the approved requirement; create no card.`
18097
18414
  ].filter(Boolean).join(" ");
18098
18415
  }
18099
18416
  return [
@@ -18193,7 +18510,7 @@ function actionPrompt(req, command, notes) {
18193
18510
  case "spec": {
18194
18511
  const agent = findSpecAgent(req.specAgent ?? "");
18195
18512
  const found2 = req.id === void 0 ? null : locate(req.id);
18196
- const cardFile3 = found2 ? rel(found2.kind === "group" ? path52.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
18513
+ const cardFile3 = found2 ? rel(found2.kind === "group" ? path54.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
18197
18514
  const own = agent ? specAgentInstructions(agent) : null;
18198
18515
  if (own) notes.push(...own.notes);
18199
18516
  const memory = agent ? agentMemoryBlock(agent) : "";
@@ -18309,285 +18626,78 @@ ${shared}` : ""
18309
18626
  case "resolve":
18310
18627
  return [
18311
18628
  `${kb}. Apply my answers to the open questions on task ${req.id} ${named2} following \`akb guide resolve\`.`,
18312
- carriedNote(req),
18313
- answeredNote(req.id, command),
18314
- req.notes ? `Extra notes: ${req.notes}` : ""
18315
- ].filter(Boolean).join(" ");
18316
- }
18317
- }
18318
- function discardedCardsPrompt(cards = []) {
18319
- if (!cards.length) return "";
18320
- return "The user discarded the cards listed below. Their absence is intentional. Do not restore or recreate them, including under new IDs or filenames. Continue the remaining work from the current board, preserving the other cards.\n\n" + cards.map((c) => `- #${c.id}: ${c.path}`).join("\n");
18321
- }
18322
- var RESUME_PROMPT, DELIVERY_RESUME, DELIVERY_RESUME_CARD, RESTARTABLE, RESTART_LEAD, restartable, NO_IMPLEMENT, BOARD_FOLDER, CARD_FILE, PROJECT_FOLDER, PLANNING_FOR, SPEC_SELECTOR_FOR, reflectedCards;
18323
- var init_prompts = __esm({
18324
- "src/lib/agent/prompts.ts"() {
18325
- "use strict";
18326
- init_cards();
18327
- init_memory();
18328
- init_memories();
18329
- init_paths();
18330
- init_agents();
18331
- init_command();
18332
- init_deliveries();
18333
- init_env();
18334
- init_facts();
18335
- init_outputs();
18336
- init_archive();
18337
- init_flows();
18338
- init_resolve();
18339
- init_runner();
18340
- init_workflows();
18341
- init_catalog2();
18342
- init_roles();
18343
- init_rules2();
18344
- init_settings2();
18345
- init_types3();
18346
- RESUME_PROMPT = [
18347
- `Continue. The previous run ended before it finished the task.`,
18348
- `Pick up where you left off and carry it through.`
18349
- ].join(" ");
18350
- DELIVERY_RESUME = [
18351
- `Continue delivery %s. The previous run ended before the delivery finished.`,
18352
- `Re-enter the flow from the top and check each step's precondition before you do it \u2014 work that is already done is done, so do not repeat it.`
18353
- ].join(" ");
18354
- DELIVERY_RESUME_CARD = `Build the card as the delivery holds it, not as the file reads now: \`%c\` prints the approved copy.`;
18355
- RESTARTABLE = /* @__PURE__ */ new Set([
18356
- "implement",
18357
- "clarify",
18358
- "resolve",
18359
- "approve",
18360
- "archive",
18361
- "spec",
18362
- "conflict",
18363
- "scheduled"
18364
- ]);
18365
- RESTART_LEAD = [
18366
- `The session you were continuing is gone, and this one holds nothing of it.`,
18367
- `Do the task below from the top, checking each step's precondition before you do it \u2014 work an earlier run already finished is done, so don't repeat it.`
18368
- ].join(" ");
18369
- restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
18370
- NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
18371
- BOARD_FOLDER = "<board folder>";
18372
- CARD_FILE = "<card file>";
18373
- PROJECT_FOLDER = "<project folder>";
18374
- PLANNING_FOR = /* @__PURE__ */ new Set(["create", "clarify", "resolve", "approve", "edit"]);
18375
- SPEC_SELECTOR_FOR = /* @__PURE__ */ new Set(["clarify", "resolve", "approve", "edit"]);
18376
- reflectedCards = (req) => req.cards ?? (req.id !== void 0 ? [req.id] : []);
18377
- }
18378
- });
18379
-
18380
- // src/lib/agent/stop.ts
18381
- import { spawnSync as spawnSync4 } from "node:child_process";
18382
- import { randomUUID as randomUUID5 } from "node:crypto";
18383
- import fs47 from "node:fs";
18384
- import os6 from "node:os";
18385
- function markedInProc(entry, strict = false) {
18386
- const pids = [];
18387
- for (const name of fs47.readdirSync("/proc")) {
18388
- if (!/^\d+$/.test(name)) continue;
18389
- try {
18390
- if (fs47.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
18391
- } catch (error) {
18392
- if (strict && !["ENOENT", "ESRCH"].includes(error.code ?? "")) {
18393
- const stat = fs47.statSync(`/proc/${name}`, { throwIfNoEntry: false });
18394
- if (stat?.uid === process.getuid?.()) throw error;
18395
- }
18396
- }
18397
- }
18398
- return pids;
18399
- }
18400
- function markedInPs(entry, roots) {
18401
- const ps = spawnSync4("ps", ["-A", "-E", "-ww", "-o", "pid=,ppid=,command="], {
18402
- encoding: "utf8",
18403
- maxBuffer: 64 * 1024 * 1024,
18404
- timeout: 5e3
18405
- });
18406
- if (ps.status !== 0 || !ps.stdout) throw new Error("\u65E0\u6CD5\u67E5\u8BE2\u8FDB\u7A0B\u6811\u3002");
18407
- const children = /* @__PURE__ */ new Map();
18408
- const listed2 = /* @__PURE__ */ new Set();
18409
- const found2 = /* @__PURE__ */ new Set();
18410
- for (const line of ps.stdout.split("\n")) {
18411
- const m = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
18412
- if (!m) continue;
18413
- const pid = Number(m[1]);
18414
- const ppid = Number(m[2]);
18415
- listed2.add(pid);
18416
- children.set(ppid, [...children.get(ppid) ?? [], pid]);
18417
- if (`${m[3]} `.includes(` ${entry} `)) found2.add(pid);
18418
- }
18419
- const queue = [...found2, ...roots.filter((pid) => listed2.has(pid))];
18420
- for (const pid of queue) {
18421
- found2.add(pid);
18422
- for (const child of children.get(pid) ?? []) if (!found2.has(child)) queue.push(child);
18423
- }
18424
- return [...found2];
18425
- }
18426
- function marked(mark, roots = []) {
18427
- if (WINDOWS3 || !mark.value) return [];
18428
- const entry = `${mark.name}=${mark.value}`;
18429
- try {
18430
- const pids = process.platform === "linux" ? markedInProc(entry) : markedInPs(entry, roots);
18431
- return pids.filter((pid) => pid !== process.pid);
18432
- } catch {
18433
- return [];
18434
- }
18435
- }
18436
- function signal(pids, sig) {
18437
- for (const pid of pids) {
18438
- try {
18439
- process.kill(pid, sig);
18440
- } catch {
18441
- }
18442
- }
18443
- }
18444
- function startedUnder(list, root, since) {
18445
- const self = list.procs.find((p) => p.pid === root);
18446
- const from = since ?? self?.startedAt;
18447
- if (from === void 0 || list.bootedAt > from) return [];
18448
- if (self && self.startedAt > from) return [];
18449
- const found2 = self ? [root] : [];
18450
- const seen = /* @__PURE__ */ new Set([root]);
18451
- const queue = [{ pid: root, startedAt: from }];
18452
- for (const parent of queue) {
18453
- for (const p of list.procs) {
18454
- if (p.ppid !== parent.pid || seen.has(p.pid) || p.startedAt < parent.startedAt) continue;
18455
- seen.add(p.pid);
18456
- found2.push(p.pid);
18457
- queue.push(p);
18458
- }
18459
- }
18460
- return found2.reverse();
18461
- }
18462
- function readProcList(out) {
18463
- const procs = [];
18464
- let bootedAt;
18465
- for (const line of out.split(/\r?\n/)) {
18466
- const boot = /^boot (\d+)$/.exec(line.trim());
18467
- if (boot) bootedAt = Number(boot[1]);
18468
- const m = /^(\d+) (\d+) (\d+)$/.exec(line.trim());
18469
- if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), startedAt: Number(m[3]) });
18470
- }
18471
- return bootedAt !== void 0 && procs.length ? { procs, bootedAt } : void 0;
18472
- }
18473
- function procsOnWindows() {
18474
- const ps = spawnSync4("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST_PROCS], {
18475
- encoding: "utf8",
18476
- maxBuffer: 64 * 1024 * 1024,
18477
- timeout: 5e3,
18478
- windowsHide: true
18479
- });
18480
- return ps.status === 0 && ps.stdout ? readProcList(ps.stdout) : void 0;
18481
- }
18482
- function killUnderOnWindows(pid, since) {
18483
- if (!WINDOWS3 || !pid) return;
18484
- const list = procsOnWindows();
18485
- if (!list) return;
18486
- const pids = startedUnder(list, pid, since).filter((p) => p !== process.pid);
18487
- if (!pids.length) return;
18488
- spawnSync4("taskkill", ["/F", ...pids.flatMap((p) => ["/PID", String(p)])], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
18489
- }
18490
- function killMarked(mark, agent) {
18491
- if (WINDOWS3) {
18492
- if (agent) killUnderOnWindows(agent.pid, agent.since);
18493
- return;
18494
- }
18495
- signal(marked(mark), "SIGKILL");
18496
- }
18497
- function killTreeOnWindows(pid) {
18498
- if (!WINDOWS3 || !pid) return false;
18499
- const out = spawnSync4("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
18500
- return out.status === 0;
18501
- }
18502
- function later(ms, fn) {
18503
- const t = setTimeout(fn, ms);
18504
- if (typeof t.unref === "function") t.unref();
18505
- }
18506
- function endAgent(child, mark, graceMs) {
18507
- const term = (sig) => {
18508
- try {
18509
- child.kill(sig);
18510
- } catch {
18511
- }
18512
- };
18513
- if (killTreeOnWindows(child.pid)) return;
18514
- killUnderOnWindows(child.pid);
18515
- const seen = new Set(marked(mark, child.pid ? [child.pid] : []));
18516
- term("SIGTERM");
18517
- signal([...seen].filter((pid) => pid !== child.pid), "SIGTERM");
18518
- const round = (left) => {
18519
- const pids = marked(mark, [...seen]);
18520
- signal(pids, "SIGKILL");
18521
- for (const pid of pids) seen.add(pid);
18522
- if (pids.length && left > 1) later(KILL_ROUND_MS, () => round(left - 1));
18523
- };
18524
- later(graceMs, () => {
18525
- term("SIGKILL");
18526
- round(KILL_ROUNDS);
18527
- });
18528
- }
18529
- function killRunning() {
18530
- for (const [child, mark] of running) {
18531
- if (killTreeOnWindows(child.pid)) continue;
18532
- killUnderOnWindows(child.pid);
18533
- signal(marked(mark, child.pid ? [child.pid] : []), "SIGKILL");
18534
- try {
18535
- child.kill("SIGKILL");
18536
- } catch {
18537
- }
18629
+ carriedNote(req),
18630
+ answeredNote(req.id, command),
18631
+ req.notes ? `Extra notes: ${req.notes}` : ""
18632
+ ].filter(Boolean).join(" ");
18538
18633
  }
18539
- running.clear();
18540
- }
18541
- function unlisten() {
18542
- for (const [sig, fn] of listening) process.removeListener(sig, fn);
18543
- listening.clear();
18544
- }
18545
- function onQuit(sig) {
18546
- killRunning();
18547
- unlisten();
18548
- if (process.listenerCount(sig) === 0) process.exit(128 + os6.constants.signals[sig]);
18549
18634
  }
18550
- function trackAgent(child, mark) {
18551
- if (!child.pid) return;
18552
- running.set(child, mark);
18553
- child.once("close", () => {
18554
- running.delete(child);
18555
- if (!running.size) unlisten();
18556
- });
18557
- for (const sig of QUIT_SIGNALS) {
18558
- if (listening.has(sig) || sig === "SIGINT" && interruptIsTheCallers) continue;
18559
- const fn = () => onQuit(sig);
18560
- listening.set(sig, fn);
18561
- process.on(sig, fn);
18562
- }
18635
+ function discardedCardsPrompt(cards = []) {
18636
+ if (!cards.length) return "";
18637
+ return "The user discarded the cards listed below. Their absence is intentional. Do not restore or recreate them, including under new IDs or filenames. Continue the remaining work from the current board, preserving the other cards.\n\n" + cards.map((c) => `- #${c.id}: ${c.path}`).join("\n");
18563
18638
  }
18564
- var runMark, stopMark, markEnv, WINDOWS3, KILL_ROUND_MS, KILL_ROUNDS, LIST_PROCS, running, QUIT_SIGNALS, listening, interruptIsTheCallers;
18565
- var init_stop = __esm({
18566
- "src/lib/agent/stop.ts"() {
18639
+ var RESUME_PROMPT, DELIVERY_RESUME, DELIVERY_RESUME_CARD, RESTARTABLE, RESTART_LEAD, restartable, NO_IMPLEMENT, BOARD_FOLDER, CARD_FILE, PROJECT_FOLDER, PLANNING_FOR, SPEC_SELECTOR_FOR, reflectedCards;
18640
+ var init_prompts = __esm({
18641
+ "src/lib/agent/prompts.ts"() {
18567
18642
  "use strict";
18643
+ init_cards();
18644
+ init_memory();
18645
+ init_memories();
18646
+ init_paths();
18647
+ init_agents();
18648
+ init_command();
18649
+ init_deliveries();
18568
18650
  init_env();
18569
- runMark = (sessionId) => ({ name: RUN_ENV, value: sessionId });
18570
- stopMark = () => ({ name: STOP_ENV, value: randomUUID5() });
18571
- markEnv = (env2, mark) => ({ ...env2, [mark.name]: mark.value });
18572
- WINDOWS3 = process.platform === "win32";
18573
- KILL_ROUND_MS = 300;
18574
- KILL_ROUNDS = 3;
18575
- LIST_PROCS = [
18576
- "$ErrorActionPreference = 'Stop'",
18577
- "Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() } }",
18578
- "'boot {0}' -f ([DateTimeOffset](Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToUnixTimeMilliseconds()"
18579
- ].join("; ");
18580
- running = /* @__PURE__ */ new Map();
18581
- QUIT_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
18582
- listening = /* @__PURE__ */ new Map();
18583
- interruptIsTheCallers = false;
18651
+ init_facts();
18652
+ init_outputs();
18653
+ init_archive();
18654
+ init_flows();
18655
+ init_resolve();
18656
+ init_runner();
18657
+ init_workflows();
18658
+ init_catalog2();
18659
+ init_roles();
18660
+ init_rules2();
18661
+ init_settings2();
18662
+ init_types3();
18663
+ RESUME_PROMPT = [
18664
+ `Continue. The previous run ended before it finished the task.`,
18665
+ `Pick up where you left off and carry it through.`
18666
+ ].join(" ");
18667
+ DELIVERY_RESUME = [
18668
+ `Continue delivery %s. The previous run ended before the delivery finished.`,
18669
+ `Re-enter the flow from the top and check each step's precondition before you do it \u2014 work that is already done is done, so do not repeat it.`
18670
+ ].join(" ");
18671
+ DELIVERY_RESUME_CARD = `Build the card as the delivery holds it, not as the file reads now: \`%c\` prints the approved copy.`;
18672
+ RESTARTABLE = /* @__PURE__ */ new Set([
18673
+ "implement",
18674
+ "clarify",
18675
+ "resolve",
18676
+ "approve",
18677
+ "archive",
18678
+ "spec",
18679
+ "conflict",
18680
+ "scheduled"
18681
+ ]);
18682
+ RESTART_LEAD = [
18683
+ `The session you were continuing is gone, and this one holds nothing of it.`,
18684
+ `Do the task below from the top, checking each step's precondition before you do it \u2014 work an earlier run already finished is done, so don't repeat it.`
18685
+ ].join(" ");
18686
+ restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
18687
+ NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
18688
+ BOARD_FOLDER = "<board folder>";
18689
+ CARD_FILE = "<card file>";
18690
+ PROJECT_FOLDER = "<project folder>";
18691
+ PLANNING_FOR = /* @__PURE__ */ new Set(["create", "clarify", "resolve", "approve", "edit"]);
18692
+ SPEC_SELECTOR_FOR = /* @__PURE__ */ new Set(["clarify", "resolve", "approve", "edit"]);
18693
+ reflectedCards = (req) => req.cards ?? (req.id !== void 0 ? [req.id] : []);
18584
18694
  }
18585
18695
  });
18586
18696
 
18587
18697
  // src/lib/agent/sessions.ts
18588
18698
  import { randomUUID as randomUUID6 } from "node:crypto";
18589
- import fs48 from "node:fs";
18590
- import path53 from "node:path";
18699
+ import fs49 from "node:fs";
18700
+ import path55 from "node:path";
18591
18701
  function reap(runs, reaped = [], restore = []) {
18592
18702
  let changed = false;
18593
18703
  const now = Date.now();
@@ -18607,7 +18717,7 @@ function reap(runs, reaped = [], restore = []) {
18607
18717
  }
18608
18718
  function stampDuration(run2, endedAt) {
18609
18719
  try {
18610
- fs48.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
18720
+ fs49.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
18611
18721
  } catch {
18612
18722
  }
18613
18723
  }
@@ -18621,7 +18731,7 @@ function cardNow(cardId2) {
18621
18731
  try {
18622
18732
  const file = cardFile(cardId2);
18623
18733
  if (!file) return null;
18624
- const { meta } = parseFrontmatter(fs48.readFileSync(file, "utf8"));
18734
+ const { meta } = parseFrontmatter(fs49.readFileSync(file, "utf8"));
18625
18735
  if (!meta) return null;
18626
18736
  return { status: meta.status || "todo", questions: openOf(meta.questions).length, title: meta.title };
18627
18737
  } catch {
@@ -18758,9 +18868,9 @@ function leftBoardOnLanding(id) {
18758
18868
  function archivedRejected(id) {
18759
18869
  const filed = locateArchived(id);
18760
18870
  if (!filed) return null;
18761
- const file = filed.kind === "group" ? path53.join(filed.target, "root.md") : filed.target;
18871
+ const file = filed.kind === "group" ? path55.join(filed.target, "root.md") : filed.target;
18762
18872
  try {
18763
- return !!parseFrontmatter(fs48.readFileSync(file, "utf8")).meta?.rejected;
18873
+ return !!parseFrontmatter(fs49.readFileSync(file, "utf8")).meta?.rejected;
18764
18874
  } catch {
18765
18875
  return false;
18766
18876
  }
@@ -19017,7 +19127,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said3) {
19017
19127
  return { run: record, spec };
19018
19128
  }
19019
19129
  function planningSession(cardId2, cwd = REPO_ROOT) {
19020
- const here = (dir) => !dir || path53.resolve(dir) === cwd;
19130
+ const here = (dir) => !dir || path55.resolve(dir) === cwd;
19021
19131
  const ended = readRuns().filter((r) => r.status === "done").sort((a, b) => b.startedAt - a.startedAt);
19022
19132
  const of = (run3, fork) => {
19023
19133
  if (!here(run3.cwd)) return { none: "elsewhere" };
@@ -19086,7 +19196,9 @@ function requestOf(record) {
19086
19196
  pictures: record.pictures
19087
19197
  };
19088
19198
  }
19089
- async function openResume(id, build) {
19199
+ async function openResume(id, options) {
19200
+ const build = typeof options === "object" ? options : void 0;
19201
+ const requireSession = options === true || !!build;
19090
19202
  const restore = [];
19091
19203
  const runs = withRuns((all2) => {
19092
19204
  reap(all2, [], restore);
@@ -19111,7 +19223,7 @@ async function openResume(id, build) {
19111
19223
  if (refused) return refused;
19112
19224
  }
19113
19225
  const retrying = lacksSession(prev);
19114
- if (build && (retrying || !resumesUnder(prev.harness))) {
19226
+ if (requireSession && (!resumeSessionId(prev) || !resumesUnder(prev.harness))) {
19115
19227
  return refusal("runNoSession", "\u539F\u6784\u5EFA\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4F1A\u8BDD\u6807\u8BC6\uFF0C\u6216\u539F Agent \u4E0D\u652F\u6301\u7EED\u8DD1\uFF1B\u672C\u6B21\u672A\u542F\u52A8\u65B0\u4F1A\u8BDD\u3002");
19116
19228
  }
19117
19229
  const ask2 = retrying && prev.status !== "stopped" ? retryAsk(prev) : void 0;
@@ -19250,8 +19362,8 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
19250
19362
  clearAsks(prev.sessionId);
19251
19363
  try {
19252
19364
  if (prev.action !== "create") {
19253
- fs48.unlinkSync(prev.logPath);
19254
- fs48.rmSync(eventsPathOf(prev.sessionId), { force: true });
19365
+ fs49.unlinkSync(prev.logPath);
19366
+ fs49.rmSync(eventsPathOf(prev.sessionId), { force: true });
19255
19367
  }
19256
19368
  } catch {
19257
19369
  }
@@ -19275,8 +19387,8 @@ function forgetRun(sessionId) {
19275
19387
  if (!gone) return;
19276
19388
  clearAsks(sessionId);
19277
19389
  try {
19278
- fs48.unlinkSync(gone.logPath);
19279
- fs48.rmSync(eventsPathOf(gone.sessionId), { force: true });
19390
+ fs49.unlinkSync(gone.logPath);
19391
+ fs49.rmSync(eventsPathOf(gone.sessionId), { force: true });
19280
19392
  } catch {
19281
19393
  }
19282
19394
  }
@@ -19305,14 +19417,14 @@ function noteSpecRefusals(sessionId, refused) {
19305
19417
  }
19306
19418
  function clearAsks(sessionId) {
19307
19419
  try {
19308
- fs48.unlinkSync(asksPathOf(sessionId));
19420
+ fs49.unlinkSync(asksPathOf(sessionId));
19309
19421
  } catch {
19310
19422
  }
19311
19423
  }
19312
19424
  function readAsks(sessionId) {
19313
19425
  let data;
19314
19426
  try {
19315
- data = JSON.parse(fs48.readFileSync(asksPathOf(sessionId), "utf8"));
19427
+ data = JSON.parse(fs49.readFileSync(asksPathOf(sessionId), "utf8"));
19316
19428
  } catch {
19317
19429
  return { asks: [], refines: [], refused: [] };
19318
19430
  }
@@ -19339,10 +19451,10 @@ function readAsks(sessionId) {
19339
19451
  return { asks: asks.filter((a) => !discarded.has(a.cardId)), refines: refines.filter((a) => !discarded.has(a.cardId)), refused };
19340
19452
  }
19341
19453
  function writeAsks(sessionId, file) {
19342
- fs48.mkdirSync(SESSIONS_DIR, { recursive: true });
19454
+ fs49.mkdirSync(SESSIONS_DIR, { recursive: true });
19343
19455
  const tmp = `${asksPathOf(sessionId)}.tmp`;
19344
- fs48.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
19345
- fs48.renameSync(tmp, asksPathOf(sessionId));
19456
+ fs49.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
19457
+ fs49.renameSync(tmp, asksPathOf(sessionId));
19346
19458
  }
19347
19459
  function markSpawned(sessionId, pid) {
19348
19460
  patch(sessionId, (r) => {
@@ -19430,7 +19542,10 @@ async function cancelDelivery(id) {
19430
19542
  if (!id.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to cancel", { action: "cancel" }) };
19431
19543
  const delivery = namedDelivery(id);
19432
19544
  if (!delivery) return { ok: false, ...unknownDelivery(id) };
19433
- if (delivery.status !== "active") return { ok: true, deliveryId: delivery.deliveryId };
19545
+ if (delivery.status !== "active") {
19546
+ tidyCheckout(delivery.deliveryId);
19547
+ return { ok: true, deliveryId: delivery.deliveryId };
19548
+ }
19434
19549
  endDelivery(delivery.deliveryId, "cancelled");
19435
19550
  const live = readRuns().find((r) => r.status === "running" && r.deliveryId === delivery.deliveryId && r.action !== "sub");
19436
19551
  if (live) await stopRun(live.sessionId);
@@ -19455,7 +19570,9 @@ async function runIsDown(sessionId) {
19455
19570
  }
19456
19571
  async function resumeDelivery(id) {
19457
19572
  if (!id.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to carry on", { action: "resume" }) };
19458
- const put = resumeRecord(id);
19573
+ const execution = executionOf();
19574
+ if (execution && !await executionHeld(execution)) return { ok: false, error: "\u65E0\u6CD5\u786E\u8BA4\u672C\u6B21\u7EED\u8DD1\u7684\u6267\u884C\u6743\uFF0C\u4EA4\u4ED8\u4FDD\u6301\u539F\u72B6\u3002" };
19575
+ const put = resumeRecord(id, execution);
19459
19576
  if (!put.ok) return put;
19460
19577
  const delivery = put.delivery;
19461
19578
  if (await settleAlreadyLanded(delivery)) {
@@ -19496,12 +19613,12 @@ async function discardDelivery(id) {
19496
19613
  return { ok: true, deliveryId: delivery.deliveryId };
19497
19614
  }
19498
19615
  function writeSpec(spec) {
19499
- fs48.mkdirSync(SESSIONS_DIR, { recursive: true });
19500
- fs48.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
19616
+ fs49.mkdirSync(SESSIONS_DIR, { recursive: true });
19617
+ fs49.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
19501
19618
  }
19502
19619
  function readSpec(sessionId) {
19503
19620
  try {
19504
- const spec = JSON.parse(fs48.readFileSync(specPathOf(sessionId), "utf8"));
19621
+ const spec = JSON.parse(fs49.readFileSync(specPathOf(sessionId), "utf8"));
19505
19622
  return spec && Array.isArray(spec.plan?.argv) ? spec : null;
19506
19623
  } catch {
19507
19624
  return null;
@@ -19509,28 +19626,28 @@ function readSpec(sessionId) {
19509
19626
  }
19510
19627
  function dropSpec(sessionId) {
19511
19628
  try {
19512
- fs48.unlinkSync(specPathOf(sessionId));
19629
+ fs49.unlinkSync(specPathOf(sessionId));
19513
19630
  } catch {
19514
19631
  }
19515
19632
  }
19516
19633
  async function acquireIndexLock(giveUp) {
19517
19634
  const until = Date.now() + INDEX_WAIT_MS;
19518
- const holder = path53.join(INDEX_LOCK2, "holder");
19635
+ const holder = path55.join(INDEX_LOCK2, "holder");
19519
19636
  for (; ; ) {
19520
19637
  if (giveUp()) return null;
19521
19638
  try {
19522
- fs48.mkdirSync(INDEX_LOCK2, { recursive: false });
19523
- fs48.writeFileSync(holder, String(process.pid));
19524
- return () => fs48.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19639
+ fs49.mkdirSync(INDEX_LOCK2, { recursive: false });
19640
+ fs49.writeFileSync(holder, String(process.pid));
19641
+ return () => fs49.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19525
19642
  } catch (err) {
19526
19643
  const code = err.code;
19527
19644
  if (code === "ENOENT") {
19528
- fs48.mkdirSync(path53.dirname(INDEX_LOCK2), { recursive: true });
19645
+ fs49.mkdirSync(path55.dirname(INDEX_LOCK2), { recursive: true });
19529
19646
  continue;
19530
19647
  }
19531
19648
  if (code !== "EEXIST") throw err;
19532
19649
  if (!pidAlive(Number(readHolder(holder)))) {
19533
- fs48.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19650
+ fs49.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19534
19651
  continue;
19535
19652
  }
19536
19653
  if (Date.now() > until) return null;
@@ -19540,7 +19657,7 @@ async function acquireIndexLock(giveUp) {
19540
19657
  }
19541
19658
  function readHolder(file) {
19542
19659
  try {
19543
- return fs48.readFileSync(file, "utf8").trim();
19660
+ return fs49.readFileSync(file, "utf8").trim();
19544
19661
  } catch {
19545
19662
  return String(process.pid);
19546
19663
  }
@@ -19549,6 +19666,7 @@ var INDEX_ACTIONS, SINGLETON_ACTIONS, VERB, SINGLETON_BUSY, RUN_STATUS, specPath
19549
19666
  var init_sessions = __esm({
19550
19667
  "src/lib/agent/sessions.ts"() {
19551
19668
  "use strict";
19669
+ init_execution();
19552
19670
  init_creation();
19553
19671
  init_cards();
19554
19672
  init_frontmatter();
@@ -19631,8 +19749,8 @@ var init_sessions = __esm({
19631
19749
  conflict: "implementing",
19632
19750
  hook: "implementing"
19633
19751
  };
19634
- specPathOf = (sessionId) => path53.join(SESSIONS_DIR, `${sessionId}.plan.json`);
19635
- asksPathOf = (sessionId) => path53.join(SESSIONS_DIR, `${sessionId}.asks.json`);
19752
+ specPathOf = (sessionId) => path55.join(SESSIONS_DIR, `${sessionId}.plan.json`);
19753
+ asksPathOf = (sessionId) => path55.join(SESSIONS_DIR, `${sessionId}.asks.json`);
19636
19754
  carriesSession = (r) => !!(r.resumedFrom || r.continues && !r.continues.fork);
19637
19755
  canPickUp = (r) => (r.status === "error" || r.status === "interrupted" || r.status === "stopped") && !(r.action === "create" && readRuns().some((next) => next.resumedFrom === r.sessionId));
19638
19756
  neverStarted = (r) => r.unspawned === true || !!r.errorWhy?.some((why) => why.kind === "notInstalled");
@@ -19766,8 +19884,8 @@ var init_questions = __esm({
19766
19884
  });
19767
19885
 
19768
19886
  // src/lib/agent/workflow-cards.ts
19769
- import fs49 from "node:fs";
19770
- import path54 from "node:path";
19887
+ import fs50 from "node:fs";
19888
+ import path56 from "node:path";
19771
19889
  function cardsOnWorkflow(id) {
19772
19890
  const wanted = id || DEFAULT_WORKFLOW;
19773
19891
  const ids = [];
@@ -19778,12 +19896,12 @@ function cardsOnWorkflow(id) {
19778
19896
  return [];
19779
19897
  }
19780
19898
  for (const file of files2) {
19781
- const base = path54.basename(file);
19782
- const card = base === "root.md" ? idPrefix(path54.basename(path54.dirname(file))) : idPrefix(base);
19899
+ const base = path56.basename(file);
19900
+ const card = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file))) : idPrefix(base);
19783
19901
  if (card === null) continue;
19784
19902
  let meta;
19785
19903
  try {
19786
- meta = parseFrontmatter(fs49.readFileSync(file, "utf8")).meta;
19904
+ meta = parseFrontmatter(fs50.readFileSync(file, "utf8")).meta;
19787
19905
  } catch {
19788
19906
  continue;
19789
19907
  }
@@ -19841,12 +19959,12 @@ var init_workflow_cards = __esm({
19841
19959
  });
19842
19960
 
19843
19961
  // src/lib/readme.ts
19844
- import fs50 from "node:fs";
19845
- import path55 from "node:path";
19962
+ import fs51 from "node:fs";
19963
+ import path57 from "node:path";
19846
19964
  function stripReadmeRefs(target) {
19847
- if (!fs50.existsSync(README)) return [];
19965
+ if (!fs51.existsSync(README)) return [];
19848
19966
  const needle = target.kind === "group" ? `](${target.rel}/` : `](${target.rel})`;
19849
- const lines = fs50.readFileSync(README, "utf8").split("\n");
19967
+ const lines = fs51.readFileSync(README, "utf8").split("\n");
19850
19968
  const out = [];
19851
19969
  const removed = [];
19852
19970
  let i = 0;
@@ -19868,20 +19986,20 @@ function stripReadmeRefs(target) {
19868
19986
  out.push(line);
19869
19987
  i++;
19870
19988
  }
19871
- if (removed.length) fs50.writeFileSync(README, out.join("\n"));
19989
+ if (removed.length) fs51.writeFileSync(README, out.join("\n"));
19872
19990
  return removed;
19873
19991
  }
19874
19992
  function addReadmeRef(id, title, relPath) {
19875
- if (!fs50.existsSync(README)) return false;
19876
- const link2 = relPath.split(path55.sep).join("/");
19993
+ if (!fs51.existsSync(README)) return false;
19994
+ const link2 = relPath.split(path57.sep).join("/");
19877
19995
  const bullet = `- [#${id} ${title}](${link2})`;
19878
19996
  const heading = `## ${TASKS_HEADING}`;
19879
- let lines = fs50.readFileSync(README, "utf8").split("\n");
19997
+ let lines = fs51.readFileSync(README, "utf8").split("\n");
19880
19998
  const hi = lines.findIndex((l) => l.trim().toLowerCase() === heading.toLowerCase());
19881
19999
  if (hi === -1) {
19882
20000
  while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
19883
20001
  lines.push("", heading, "", bullet);
19884
- fs50.writeFileSync(README, lines.join("\n") + "\n");
20002
+ fs51.writeFileSync(README, lines.join("\n") + "\n");
19885
20003
  return true;
19886
20004
  }
19887
20005
  let end2 = hi + 1;
@@ -19895,15 +20013,15 @@ function addReadmeRef(id, title, relPath) {
19895
20013
  const at = lastBullet !== -1 ? lastBullet + 1 : lines[hi + 1] === "" ? hi + 2 : hi + 1;
19896
20014
  lines.splice(at, 0, bullet);
19897
20015
  }
19898
- fs50.writeFileSync(README, lines.join("\n"));
20016
+ fs51.writeFileSync(README, lines.join("\n"));
19899
20017
  return true;
19900
20018
  }
19901
20019
  function repointReadmeLink(id, oldRel, newRel, title) {
19902
- if (!fs50.existsSync(README)) return false;
19903
- const oldLink = oldRel.split(path55.sep).join("/");
19904
- const newLink = newRel.split(path55.sep).join("/");
20020
+ if (!fs51.existsSync(README)) return false;
20021
+ const oldLink = oldRel.split(path57.sep).join("/");
20022
+ const newLink = newRel.split(path57.sep).join("/");
19905
20023
  const linkRe = new RegExp(`\\[#${id}\\b[^\\]]*\\]\\(${escapeRegex(oldLink)}\\)`);
19906
- const lines = fs50.readFileSync(README, "utf8").split("\n");
20024
+ const lines = fs51.readFileSync(README, "utf8").split("\n");
19907
20025
  let changed = false;
19908
20026
  for (let i = 0; i < lines.length; i++) {
19909
20027
  if (!lines[i].includes(`](${oldLink})`)) continue;
@@ -19913,7 +20031,7 @@ function repointReadmeLink(id, oldRel, newRel, title) {
19913
20031
  changed = true;
19914
20032
  }
19915
20033
  }
19916
- if (changed) fs50.writeFileSync(README, lines.join("\n"));
20034
+ if (changed) fs51.writeFileSync(README, lines.join("\n"));
19917
20035
  return changed;
19918
20036
  }
19919
20037
  var isTableRow, isBulletStart, bulletIndent, TASKS_HEADING, escapeRegex;
@@ -19930,14 +20048,14 @@ var init_readme = __esm({
19930
20048
  });
19931
20049
 
19932
20050
  // src/lib/reconcile.ts
19933
- import fs51 from "node:fs";
19934
- import path56 from "node:path";
20051
+ import fs52 from "node:fs";
20052
+ import path58 from "node:path";
19935
20053
  function liveIds() {
19936
20054
  const ids = /* @__PURE__ */ new Set();
19937
20055
  for (const file of walkMd(TODO)) {
19938
- const base = path56.basename(file);
20056
+ const base = path58.basename(file);
19939
20057
  if (base === "README.md") continue;
19940
- const id = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file))) : idPrefix(base);
20058
+ const id = base === "root.md" ? idPrefix(path58.basename(path58.dirname(file))) : idPrefix(base);
19941
20059
  if (id != null) ids.add(id);
19942
20060
  }
19943
20061
  return ids;
@@ -19945,16 +20063,16 @@ function liveIds() {
19945
20063
  function indexableCards() {
19946
20064
  const out = [];
19947
20065
  for (const dir of walkDirs(TODO)) {
19948
- const id = idPrefix(path56.basename(dir));
19949
- if (id != null && fs51.existsSync(path56.join(dir, "root.md"))) {
19950
- out.push({ id, rel: path56.join(path56.relative(TODO, dir), "root.md").split(path56.sep).join("/") });
20066
+ const id = idPrefix(path58.basename(dir));
20067
+ if (id != null && fs52.existsSync(path58.join(dir, "root.md"))) {
20068
+ out.push({ id, rel: path58.join(path58.relative(TODO, dir), "root.md").split(path58.sep).join("/") });
19951
20069
  }
19952
20070
  }
19953
20071
  for (const file of walkMd(TODO)) {
19954
- const base = path56.basename(file);
20072
+ const base = path58.basename(file);
19955
20073
  if (base === "README.md" || base === "root.md") continue;
19956
- const relTODO = path56.relative(TODO, file);
19957
- const segs = relTODO.split(path56.sep);
20074
+ const relTODO = path58.relative(TODO, file);
20075
+ const segs = relTODO.split(path58.sep);
19958
20076
  if (segs.length !== 1) continue;
19959
20077
  const id = idPrefix(base);
19960
20078
  if (id != null) out.push({ id, rel: segs.join("/") });
@@ -19963,7 +20081,7 @@ function indexableCards() {
19963
20081
  }
19964
20082
  function readmeComplaints(fix) {
19965
20083
  const said3 = [];
19966
- const lines = fs51.readFileSync(README, "utf8").split("\n");
20084
+ const lines = fs52.readFileSync(README, "utf8").split("\n");
19967
20085
  const indexed = /* @__PURE__ */ new Set();
19968
20086
  let fixed = 0;
19969
20087
  for (let i = 0; i < lines.length; i++) {
@@ -19972,13 +20090,13 @@ function readmeComplaints(fix) {
19972
20090
  const id = Number(m[1]);
19973
20091
  const linkPath = m[2];
19974
20092
  indexed.add(id);
19975
- if (fs51.existsSync(path56.join(TODO, linkPath))) continue;
20093
+ if (fs52.existsSync(path58.join(TODO, linkPath))) continue;
19976
20094
  const found2 = locate(id);
19977
20095
  if (!found2) {
19978
20096
  said3.push(`README links #${id} \u2192 ${linkPath}, but no card with that id exists (removed by hand?). Drop the entry or restore the file.`);
19979
20097
  continue;
19980
20098
  }
19981
- const want = (found2.kind === "group" ? path56.join(found2.rel, "root.md") : found2.rel).split(path56.sep).join("/");
20099
+ const want = (found2.kind === "group" ? path58.join(found2.rel, "root.md") : found2.rel).split(path58.sep).join("/");
19982
20100
  if (want === linkPath) continue;
19983
20101
  if (!fix) {
19984
20102
  said3.push(`README links #${id} \u2192 ${linkPath}, which isn't there any more; the card is at ${want}.`);
@@ -19988,7 +20106,7 @@ function readmeComplaints(fix) {
19988
20106
  said3.push(`README link #${id} pointed at missing ${linkPath} \u2192 repointed to ${want}.`);
19989
20107
  fixed++;
19990
20108
  }
19991
- if (fixed) fs51.writeFileSync(README, lines.join("\n"));
20109
+ if (fixed) fs52.writeFileSync(README, lines.join("\n"));
19992
20110
  for (const c of indexableCards()) {
19993
20111
  if (!indexed.has(c.id)) {
19994
20112
  said3.push(`card ${c.rel} (#${c.id}) is not in the README index. Add it under "## ${TASKS_HEADING}".`);
@@ -20000,11 +20118,11 @@ function crossRefComplaints() {
20000
20118
  const said3 = [];
20001
20119
  const live = liveIds();
20002
20120
  for (const file of walkMd(TODO)) {
20003
- const base = path56.basename(file);
20121
+ const base = path58.basename(file);
20004
20122
  if (base === "README.md") continue;
20005
- const ownerId = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file))) : idPrefix(base);
20123
+ const ownerId = base === "root.md" ? idPrefix(path58.basename(path58.dirname(file))) : idPrefix(base);
20006
20124
  if (ownerId == null) continue;
20007
- const { meta } = parseFrontmatter(fs51.readFileSync(file, "utf8"));
20125
+ const { meta } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
20008
20126
  if (!meta) continue;
20009
20127
  for (const field2 of ["blocked_by", "related"]) {
20010
20128
  for (const ref of meta[field2] || []) {
@@ -20017,11 +20135,11 @@ function crossRefComplaints() {
20017
20135
  return said3;
20018
20136
  }
20019
20137
  function reconcileBoard() {
20020
- if (!fs51.existsSync(README)) return;
20138
+ if (!fs52.existsSync(README)) return;
20021
20139
  for (const line of [...readmeComplaints(true), ...crossRefComplaints()]) warn2(line);
20022
20140
  }
20023
20141
  function boardComplaints() {
20024
- if (!fs51.existsSync(README)) return [];
20142
+ if (!fs52.existsSync(README)) return [];
20025
20143
  try {
20026
20144
  return [...readmeComplaints(false), ...crossRefComplaints()];
20027
20145
  } catch {
@@ -20041,8 +20159,8 @@ var init_reconcile = __esm({
20041
20159
  });
20042
20160
 
20043
20161
  // src/commands/card.ts
20044
- import fs52 from "node:fs";
20045
- import path57 from "node:path";
20162
+ import fs53 from "node:fs";
20163
+ import path59 from "node:path";
20046
20164
  function defaultBody() {
20047
20165
  return [
20048
20166
  "<\u7528\u4E00\u5C0F\u6BB5\u8BDD\u5148\u8BB2\u53D1\u751F\u4E86\u4EC0\u4E48\u3001\u7528\u6237\u9047\u5230\u4EC0\u4E48\uFF0C\u518D\u8BB2\u8FD9\u5F20\u5361\u8981\u8FBE\u5230\u7684\u7ED3\u679C\u3002>",
@@ -20068,7 +20186,7 @@ function bodyFromFile(opts) {
20068
20186
  if (opts.body === false) die("pass --body-file or --no-body, not both");
20069
20187
  let text5;
20070
20188
  try {
20071
- text5 = fs52.readFileSync(opts.bodyFile, "utf8");
20189
+ text5 = fs53.readFileSync(opts.bodyFile, "utf8");
20072
20190
  } catch {
20073
20191
  die(`can't read ${opts.bodyFile} \u2014 write the body to a file, then pass its path`, { kind: "needs-input" });
20074
20192
  }
@@ -20100,20 +20218,20 @@ function cmdCreate(opts) {
20100
20218
  const start = opts.id;
20101
20219
  const slug2 = slugify(opts.slug !== void 0 ? opts.slug : title);
20102
20220
  const fileRel = `${start}-${slug2}.md`;
20103
- const file = path57.join(TODO, fileRel);
20221
+ const file = path59.join(TODO, fileRel);
20104
20222
  const held4 = locate(start) ?? locateArchived(start);
20105
- if (held4 && path57.basename(held4.target) === `${start}-${slug2}.md`) {
20223
+ if (held4 && path59.basename(held4.target) === `${start}-${slug2}.md`) {
20106
20224
  say(start);
20107
20225
  say(` ${rel(held4.target)} was already written`);
20108
20226
  return { id: start, ids: [start], title, file: rel(held4.target), indexed: false };
20109
20227
  }
20110
20228
  if (held4) die(`#${start} is already a card here (${rel(held4.target)})`, { kind: "id-taken", id: start });
20111
- if (fs52.existsSync(file)) die(`${rel(file)} already exists \u2014 pick a different --slug`);
20229
+ if (fs53.existsSync(file)) die(`${rel(file)} already exists \u2014 pick a different --slug`);
20112
20230
  countBoardEvent(triage ? "cards_created_proposed" : "cards_created_asked");
20113
20231
  const meta = { title, priority, status: "todo", blocked_by, related, modules, workflow, triage, source, questions };
20114
20232
  const scaffolded = !written && opts.body !== false;
20115
20233
  const body = written ?? (scaffolded ? defaultBody() : "");
20116
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n\n" + body);
20234
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n\n" + body);
20117
20235
  const indexed = addReadmeRef(start, title, fileRel);
20118
20236
  say(start);
20119
20237
  say(
@@ -20151,8 +20269,8 @@ function cmdUpdate(id, flags) {
20151
20269
  if (creating) die(creating, { kind: "card-being-created", id });
20152
20270
  const found2 = locate(id);
20153
20271
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
20154
- const file = found2.kind === "group" ? path57.join(found2.target, "root.md") : found2.target;
20155
- const { meta, body } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
20272
+ const file = found2.kind === "group" ? path59.join(found2.target, "root.md") : found2.target;
20273
+ const { meta, body } = parseFrontmatter(fs53.readFileSync(file, "utf8"));
20156
20274
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
20157
20275
  if (flags.blockedBy !== void 0 && flags.addBlockedBy !== void 0) die("--blocked-by replaces the list and --add-blocked-by appends to it \u2014 pass one");
20158
20276
  if (flags.related !== void 0 && flags.addRelated !== void 0) die("--related replaces the list and --add-related appends to it \u2014 pass one");
@@ -20232,26 +20350,26 @@ function cmdUpdate(id, flags) {
20232
20350
  meta.status = "todo";
20233
20351
  changes.push("status\u2192todo (open questions)");
20234
20352
  }
20235
- const curRel = path57.relative(TODO, file);
20353
+ const curRel = path59.relative(TODO, file);
20236
20354
  const isSubtask = found2.kind === "file" && enclosingGroupRoot(file) !== null;
20237
- let base = path57.basename(file);
20355
+ let base = path59.basename(file);
20238
20356
  if (flags.slug !== void 0) {
20239
20357
  if (found2.kind === "group") die("renaming a group root by script is not supported");
20240
20358
  base = `${id}-${slugify(flags.slug)}.md`;
20241
20359
  }
20242
- const destRel = path57.join(path57.dirname(curRel), base);
20243
- const dest = path57.join(TODO, destRel);
20360
+ const destRel = path59.join(path59.dirname(curRel), base);
20361
+ const dest = path59.join(TODO, destRel);
20244
20362
  const moving = dest !== file;
20245
- if (moving && fs52.existsSync(dest)) die(`${rel(dest)} already exists`);
20246
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20247
- if (moving) fs52.renameSync(file, dest);
20363
+ if (moving && fs53.existsSync(dest)) die(`${rel(dest)} already exists`);
20364
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20365
+ if (moving) fs53.renameSync(file, dest);
20248
20366
  if (isSubtask) {
20249
20367
  if (moving || changes.includes("title")) repointReadmeLink(id, curRel, destRel, meta.title);
20250
- if (moving) changes.push(`renamed \u2192 ${destRel.split(path57.sep).join("/")}`);
20368
+ if (moving) changes.push(`renamed \u2192 ${destRel.split(path59.sep).join("/")}`);
20251
20369
  } else if (moving) {
20252
20370
  stripReadmeRefs({ kind: "file", rel: curRel });
20253
20371
  addReadmeRef(id, meta.title, destRel);
20254
- changes.push(`renamed \u2192 ${destRel.split(path57.sep).join("/")}`);
20372
+ changes.push(`renamed \u2192 ${destRel.split(path59.sep).join("/")}`);
20255
20373
  } else if (changes.includes("title")) {
20256
20374
  stripReadmeRefs({ kind: "file", rel: curRel });
20257
20375
  addReadmeRef(id, meta.title, curRel);
@@ -20263,8 +20381,8 @@ function cmdUpdateQuestions(id, input) {
20263
20381
  const ops = readQuestionOps(input.ops ?? []);
20264
20382
  const found2 = locate(id);
20265
20383
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
20266
- const file = found2.kind === "group" ? path57.join(found2.target, "root.md") : found2.target;
20267
- const { meta, body } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
20384
+ const file = found2.kind === "group" ? path59.join(found2.target, "root.md") : found2.target;
20385
+ const { meta, body } = parseFrontmatter(fs53.readFileSync(file, "utf8"));
20268
20386
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
20269
20387
  if (insideRun() && ops.some((op) => op.kind === "skip" || op.kind === "unskip")) {
20270
20388
  die("only the user skips or reopens a question \u2014 a run leaves questions for them to answer");
@@ -20337,7 +20455,7 @@ function cmdUpdateQuestions(id, input) {
20337
20455
  meta.status = "todo";
20338
20456
  changes.push("status\u2192todo (open questions)");
20339
20457
  }
20340
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20458
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20341
20459
  for (const kind of closed2) countBoardEvent(kind);
20342
20460
  settleDelivery2(id, skipped, unskipped);
20343
20461
  say(
@@ -20411,13 +20529,13 @@ var init_config_template = __esm({
20411
20529
  });
20412
20530
 
20413
20531
  // src/lib/agent/local.ts
20414
- import fs53 from "node:fs";
20415
- import path58 from "node:path";
20532
+ import fs54 from "node:fs";
20533
+ import path60 from "node:path";
20416
20534
  function takeLocalModels(board2) {
20417
- const file = path58.join(board2, ".local.json");
20535
+ const file = path60.join(board2, ".local.json");
20418
20536
  let held4;
20419
20537
  try {
20420
- held4 = configBlock(JSON.parse(fs53.readFileSync(file, "utf8")));
20538
+ held4 = configBlock(JSON.parse(fs54.readFileSync(file, "utf8")));
20421
20539
  } catch {
20422
20540
  return {};
20423
20541
  }
@@ -20435,7 +20553,7 @@ function takeLocalModels(board2) {
20435
20553
  }
20436
20554
  if (!Object.keys(agents).length) return out;
20437
20555
  delete held4.agents;
20438
- fs53.writeFileSync(file, JSON.stringify(held4, null, 2) + "\n");
20556
+ fs54.writeFileSync(file, JSON.stringify(held4, null, 2) + "\n");
20439
20557
  return out;
20440
20558
  }
20441
20559
  var LOCAL_IGNORE_LINE;
@@ -20496,12 +20614,12 @@ var init_identity2 = __esm({
20496
20614
  });
20497
20615
 
20498
20616
  // src/lib/signals/migrate.ts
20499
- import fs54 from "node:fs";
20500
- import path59 from "node:path";
20617
+ import fs55 from "node:fs";
20618
+ import path61 from "node:path";
20501
20619
  function readHandled() {
20502
20620
  let text5;
20503
20621
  try {
20504
- text5 = fs54.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
20622
+ text5 = fs55.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
20505
20623
  } catch {
20506
20624
  return [];
20507
20625
  }
@@ -20518,57 +20636,57 @@ function readHandled() {
20518
20636
  return held4;
20519
20637
  }
20520
20638
  function lift(from, into) {
20521
- fs54.mkdirSync(into, { recursive: true });
20522
- fs54.renameSync(from, path59.join(into, freeName(into, path59.basename(from))));
20639
+ fs55.mkdirSync(into, { recursive: true });
20640
+ fs55.renameSync(from, path61.join(into, freeName(into, path61.basename(from))));
20523
20641
  }
20524
20642
  function repoint(dir, from, into) {
20525
20643
  let entries;
20526
20644
  try {
20527
- entries = fs54.readdirSync(dir, { withFileTypes: true });
20645
+ entries = fs55.readdirSync(dir, { withFileTypes: true });
20528
20646
  } catch {
20529
20647
  return;
20530
20648
  }
20531
20649
  for (const entry of entries) {
20532
20650
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
20533
- const file = path59.join(dir, entry.name);
20534
- const text5 = fs54.readFileSync(file, "utf8");
20535
- if (text5.includes(from)) fs54.writeFileSync(file, text5.split(from).join(into));
20651
+ const file = path61.join(dir, entry.name);
20652
+ const text5 = fs55.readFileSync(file, "utf8");
20653
+ if (text5.includes(from)) fs55.writeFileSync(file, text5.split(from).join(into));
20536
20654
  }
20537
20655
  }
20538
20656
  function dropIfEmpty2(dir) {
20539
20657
  try {
20540
- fs54.rmdirSync(dir);
20658
+ fs55.rmdirSync(dir);
20541
20659
  } catch {
20542
20660
  }
20543
20661
  }
20544
20662
  function liftInbox() {
20545
- if (!fs54.existsSync(SIGNALS_OLD_INBOX)) return;
20546
- const oldFiles = path59.join(SIGNALS_OLD_INBOX, "files");
20547
- if (fs54.existsSync(oldFiles)) {
20548
- for (const entry of fs54.readdirSync(oldFiles, { withFileTypes: true })) {
20549
- if (entry.isFile()) lift(path59.join(oldFiles, entry.name), SIGNALS_FILES);
20663
+ if (!fs55.existsSync(SIGNALS_OLD_INBOX)) return;
20664
+ const oldFiles = path61.join(SIGNALS_OLD_INBOX, "files");
20665
+ if (fs55.existsSync(oldFiles)) {
20666
+ for (const entry of fs55.readdirSync(oldFiles, { withFileTypes: true })) {
20667
+ if (entry.isFile()) lift(path61.join(oldFiles, entry.name), SIGNALS_FILES);
20550
20668
  }
20551
20669
  dropIfEmpty2(oldFiles);
20552
20670
  }
20553
20671
  const held4 = new Set(readFolder(TRIAGE).map((signal2) => signal2.sourceId));
20554
- for (const entry of fs54.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
20672
+ for (const entry of fs55.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
20555
20673
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
20556
- const from = path59.join(SIGNALS_OLD_INBOX, entry.name);
20674
+ const from = path61.join(SIGNALS_OLD_INBOX, entry.name);
20557
20675
  const item = parse(from);
20558
20676
  if (item && held4.has(item.sourceId)) {
20559
- fs54.rmSync(from, { force: true });
20677
+ fs55.rmSync(from, { force: true });
20560
20678
  continue;
20561
20679
  }
20562
20680
  if (item) held4.add(item.sourceId);
20563
20681
  lift(from, TRIAGE);
20564
20682
  }
20565
- const wasAt = asWritten(path59.join(SIGNALS_OLD_INBOX, "files"));
20683
+ const wasAt = asWritten(path61.join(SIGNALS_OLD_INBOX, "files"));
20566
20684
  const nowAt = asWritten(SIGNALS_FILES);
20567
20685
  for (const dir of [TRIAGE, SIGNALS_ARCHIVED, SIGNALS_DISMISSED]) repoint(dir, wasAt, nowAt);
20568
20686
  dropIfEmpty2(SIGNALS_OLD_INBOX);
20569
20687
  }
20570
20688
  function liftHandled() {
20571
- if (!fs54.existsSync(SIGNALS_OLD_HANDLED)) return;
20689
+ if (!fs55.existsSync(SIGNALS_OLD_HANDLED)) return;
20572
20690
  const lines = readHandled();
20573
20691
  const held4 = /* @__PURE__ */ new Set([
20574
20692
  ...readFolder(TRIAGE).map((signal2) => signal2.sourceId),
@@ -20578,7 +20696,7 @@ function liftHandled() {
20578
20696
  for (const { sourceId, when } of lines) {
20579
20697
  if (held4.has(sourceId)) continue;
20580
20698
  held4.add(sourceId);
20581
- fs54.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
20699
+ fs55.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
20582
20700
  const name = freeName(SIGNALS_DISMISSED, fileName("", sourceId));
20583
20701
  const front = [
20584
20702
  "---",
@@ -20588,13 +20706,13 @@ function liftHandled() {
20588
20706
  "---",
20589
20707
  ""
20590
20708
  ];
20591
- fs54.writeFileSync(path59.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
20709
+ fs55.writeFileSync(path61.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
20592
20710
  `);
20593
20711
  }
20594
- fs54.rmSync(SIGNALS_OLD_HANDLED, { force: true });
20712
+ fs55.rmSync(SIGNALS_OLD_HANDLED, { force: true });
20595
20713
  }
20596
20714
  function migrateTriage() {
20597
- if (!fs54.existsSync(SIGNALS_OLD_INBOX) && !fs54.existsSync(SIGNALS_OLD_HANDLED)) return;
20715
+ if (!fs55.existsSync(SIGNALS_OLD_INBOX) && !fs55.existsSync(SIGNALS_OLD_HANDLED)) return;
20598
20716
  try {
20599
20717
  liftInbox();
20600
20718
  liftHandled();
@@ -20609,13 +20727,13 @@ var init_migrate = __esm({
20609
20727
  init_yaml();
20610
20728
  init_inbox();
20611
20729
  HANDLED_LINE = /^-\s+(.+?)\s+—\s+(.+)$/;
20612
- asWritten = (dir) => `${rel(dir).split(path59.sep).join("/")}/`;
20730
+ asWritten = (dir) => `${rel(dir).split(path61.sep).join("/")}/`;
20613
20731
  }
20614
20732
  });
20615
20733
 
20616
20734
  // src/lib/signals/add.ts
20617
- import fs55 from "node:fs";
20618
- import path60 from "node:path";
20735
+ import fs56 from "node:fs";
20736
+ import path62 from "node:path";
20619
20737
  import { createHash as createHash4 } from "node:crypto";
20620
20738
  function linkTitle(url) {
20621
20739
  let at;
@@ -20628,7 +20746,7 @@ function linkTitle(url) {
20628
20746
  return oneLine(where) || url.slice(0, TITLE_MAX);
20629
20747
  }
20630
20748
  function asText(file) {
20631
- const ext = path60.extname(file.name).toLowerCase();
20749
+ const ext = path62.extname(file.name).toLowerCase();
20632
20750
  if (!file.type.startsWith("text/") && file.type !== "application/json" && !TEXT_EXTENSIONS.has(ext)) return null;
20633
20751
  try {
20634
20752
  const text5 = new TextDecoder("utf-8", { fatal: true }).decode(file.data);
@@ -20638,9 +20756,9 @@ function asText(file) {
20638
20756
  }
20639
20757
  }
20640
20758
  function fileName2(name, data) {
20641
- const base = path60.basename(name);
20642
- const ext = path60.extname(base).toLowerCase().slice(0, 12);
20643
- const word = path60.basename(base, path60.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
20759
+ const base = path62.basename(name);
20760
+ const ext = path62.extname(base).toLowerCase().slice(0, 12);
20761
+ const word = path62.basename(base, path62.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
20644
20762
  const hash2 = createHash4("sha256").update(data).digest("hex").slice(0, 8);
20645
20763
  return `${word}-${hash2}${ext}`;
20646
20764
  }
@@ -20649,9 +20767,9 @@ function addToInbox(drop) {
20649
20767
  const typed = (drop.text ?? "").trim();
20650
20768
  const file = drop.file;
20651
20769
  if (!typed && !file) return { ok: false, error: "nothing to add \u2014 paste a link or some text, or drop a file." };
20652
- if (file && file.data.length === 0) return { ok: false, error: `${path60.basename(file.name)} is empty.` };
20770
+ if (file && file.data.length === 0) return { ok: false, error: `${path62.basename(file.name)} is empty.` };
20653
20771
  if (file && file.data.length > MAX_BYTES) {
20654
- return { ok: false, error: `${path60.basename(file.name)} is over ${MAX_BYTES / 1024 / 1024} MB \u2014 too big for the board.` };
20772
+ return { ok: false, error: `${path62.basename(file.name)} is over ${MAX_BYTES / 1024 / 1024} MB \u2014 too big for the board.` };
20655
20773
  }
20656
20774
  const read4 = describe(typed, file);
20657
20775
  const keep2 = read4.keep;
@@ -20673,8 +20791,8 @@ ${incoming.summary}`);
20673
20791
  if (seen.status === "pending" || seen.status === "archived") return { ok: false, error: `${sayHit(seen)}.` };
20674
20792
  try {
20675
20793
  if (keep2) {
20676
- fs55.mkdirSync(SIGNALS_FILES, { recursive: true });
20677
- fs55.writeFileSync(keep2.at, keep2.data);
20794
+ fs56.mkdirSync(SIGNALS_FILES, { recursive: true });
20795
+ fs56.writeFileSync(keep2.at, keep2.data);
20678
20796
  }
20679
20797
  return { ok: true, signal: writeSignal({ ...incoming, sourceId }, formatStamp(/* @__PURE__ */ new Date()), drop.slug) };
20680
20798
  } catch (e) {
@@ -20688,7 +20806,7 @@ function describe(typed, file) {
20688
20806
  return only ? [only] : [];
20689
20807
  };
20690
20808
  if (file) {
20691
- const name = path60.basename(file.name);
20809
+ const name = path62.basename(file.name);
20692
20810
  const text5 = asText(file);
20693
20811
  const note = typed ? `
20694
20812
 
@@ -20700,7 +20818,7 @@ ${typed}` : "";
20700
20818
  const at = keepAt(file);
20701
20819
  return {
20702
20820
  incoming: {
20703
- title: path60.basename(name, path60.extname(name)) || name,
20821
+ title: path62.basename(name, path62.extname(name)) || name,
20704
20822
  summary: `${name} \u2014 ${boardRel2(at)}${note}`,
20705
20823
  ...named2
20706
20824
  },
@@ -20738,73 +20856,73 @@ var init_add = __esm({
20738
20856
  MAX_BYTES = 25 * 1024 * 1024;
20739
20857
  TITLE_MAX = 120;
20740
20858
  TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".txt", ".text", ".csv", ".json", ".yml", ".yaml", ".log"]);
20741
- boardRel2 = (file) => rel(file).split(path60.sep).join("/");
20859
+ boardRel2 = (file) => rel(file).split(path62.sep).join("/");
20742
20860
  oneLine = (text5) => {
20743
20861
  const first = text5.split("\n").find((line) => line.trim()) ?? "";
20744
20862
  const clean = first.replace(/^#+\s*/, "").trim();
20745
20863
  return clean.length > TITLE_MAX ? `${clean.slice(0, TITLE_MAX - 1).trimEnd()}\u2026` : clean;
20746
20864
  };
20747
- keepAt = (file) => path60.join(SIGNALS_FILES, fileName2(file.name, file.data));
20865
+ keepAt = (file) => path62.join(SIGNALS_FILES, fileName2(file.name, file.data));
20748
20866
  }
20749
20867
  });
20750
20868
 
20751
20869
  // src/lib/recurring.ts
20752
- import fs56 from "node:fs";
20753
- import path61 from "node:path";
20870
+ import fs57 from "node:fs";
20871
+ import path63 from "node:path";
20754
20872
  function migratePruneMemoryCard() {
20755
20873
  const dir = recurringDir();
20756
20874
  let names4;
20757
20875
  try {
20758
- names4 = fs56.readdirSync(dir);
20876
+ names4 = fs57.readdirSync(dir);
20759
20877
  } catch {
20760
20878
  return null;
20761
20879
  }
20762
20880
  const name = names4.find((entry) => entry.endsWith(`-${PRUNE_SLUG}.md`));
20763
20881
  if (!name) return null;
20764
- const file = path61.join(dir, name);
20882
+ const file = path63.join(dir, name);
20765
20883
  try {
20766
- const { meta } = parseFrontmatter(fs56.readFileSync(file, "utf8"));
20884
+ const { meta } = parseFrontmatter(fs57.readFileSync(file, "utf8"));
20767
20885
  const cadence = meta?.cadence;
20768
20886
  if (typeof cadence === "string") adoptMemoryPruneCadence(cadence);
20769
20887
  } catch {
20770
20888
  }
20771
- fs56.rmSync(file, { force: true });
20889
+ fs57.rmSync(file, { force: true });
20772
20890
  return rel(file);
20773
20891
  }
20774
20892
  function legacyCards() {
20775
20893
  const dir = recurringDir();
20776
- if (!fs56.existsSync(dir)) return [];
20894
+ if (!fs57.existsSync(dir)) return [];
20777
20895
  const cards = [];
20778
- for (const entry of fs56.readdirSync(dir, { withFileTypes: true })) {
20896
+ for (const entry of fs57.readdirSync(dir, { withFileTypes: true })) {
20779
20897
  const id = idPrefix(entry.name);
20780
20898
  if (id === null) continue;
20781
- const full = path61.join(dir, entry.name);
20899
+ const full = path63.join(dir, entry.name);
20782
20900
  const slug2 = entry.name.replace(/\.md$/, "").replace(/^\d+-?/, "");
20783
20901
  if (entry.isFile() && entry.name.endsWith(".md")) cards.push({ id, slug: slug2, file: full });
20784
- else if (entry.isDirectory() && fs56.existsSync(path61.join(full, "root.md"))) {
20785
- cards.push({ id, slug: slug2, file: path61.join(full, "root.md"), folder: full });
20902
+ else if (entry.isDirectory() && fs57.existsSync(path63.join(full, "root.md"))) {
20903
+ cards.push({ id, slug: slug2, file: path63.join(full, "root.md"), folder: full });
20786
20904
  }
20787
20905
  }
20788
20906
  return cards.sort((a, b) => a.id - b.id);
20789
20907
  }
20790
20908
  function mergeInto2(from, to, skip = []) {
20791
- fs56.mkdirSync(to, { recursive: true });
20792
- for (const entry of fs56.readdirSync(from, { withFileTypes: true })) {
20909
+ fs57.mkdirSync(to, { recursive: true });
20910
+ for (const entry of fs57.readdirSync(from, { withFileTypes: true })) {
20793
20911
  if (skip.includes(entry.name)) continue;
20794
- const source = path61.join(from, entry.name);
20795
- const target = path61.join(to, entry.name);
20796
- if (!fs56.existsSync(target)) fs56.renameSync(source, target);
20797
- else if (entry.isDirectory() && fs56.statSync(target).isDirectory()) mergeInto2(source, target);
20912
+ const source = path63.join(from, entry.name);
20913
+ const target = path63.join(to, entry.name);
20914
+ if (!fs57.existsSync(target)) fs57.renameSync(source, target);
20915
+ else if (entry.isDirectory() && fs57.statSync(target).isDirectory()) mergeInto2(source, target);
20798
20916
  }
20799
- if (isEmpty(from)) fs56.rmSync(from, { recursive: true, force: true });
20917
+ if (isEmpty(from)) fs57.rmSync(from, { recursive: true, force: true });
20800
20918
  }
20801
20919
  function moveSideFolders() {
20802
20920
  const dir = recurringDir();
20803
- for (const entry of fs56.readdirSync(dir, { withFileTypes: true })) {
20921
+ for (const entry of fs57.readdirSync(dir, { withFileTypes: true })) {
20804
20922
  if (!entry.isDirectory() || idPrefix(entry.name) !== null) continue;
20805
- const from = path61.join(dir, entry.name);
20806
- if (isEmpty(from)) fs56.rmSync(from, { recursive: true, force: true });
20807
- else mergeInto2(from, path61.join(AGENTS, entry.name));
20923
+ const from = path63.join(dir, entry.name);
20924
+ if (isEmpty(from)) fs57.rmSync(from, { recursive: true, force: true });
20925
+ else mergeInto2(from, path63.join(AGENTS, entry.name));
20808
20926
  }
20809
20927
  }
20810
20928
  function sections(body) {
@@ -20854,8 +20972,8 @@ function agentName(card, text5) {
20854
20972
  const known2 = /* @__PURE__ */ new Set([...specAgentCatalog().agents.map((a) => a.name), ...ROLE_NAMES]);
20855
20973
  for (const name of [slug2, `${slug2}-${card.id}`]) {
20856
20974
  if (!AGENT_NAME.test(name)) continue;
20857
- const file = path61.join(AGENTS, name, AGENT_FILE3);
20858
- const written = fs56.existsSync(file) ? fs56.readFileSync(file, "utf8") : null;
20975
+ const file = path63.join(AGENTS, name, AGENT_FILE3);
20976
+ const written = fs57.existsSync(file) ? fs57.readFileSync(file, "utf8") : null;
20859
20977
  if (written === text5(name)) return name;
20860
20978
  if (written === null && !known2.has(name)) return name;
20861
20979
  }
@@ -20872,11 +20990,11 @@ ${q.options.map((o) => `- ${o}`).join("\n")}` : "";
20872
20990
  function removeCard(card) {
20873
20991
  dropCrossRefs(card.id);
20874
20992
  const target = card.folder ?? card.file;
20875
- stripReadmeRefs({ kind: card.folder ? "group" : "file", rel: path61.relative(TODO, target).split(path61.sep).join("/") });
20876
- fs56.rmSync(target, { recursive: true, force: true });
20993
+ stripReadmeRefs({ kind: card.folder ? "group" : "file", rel: path63.relative(TODO, target).split(path63.sep).join("/") });
20994
+ fs57.rmSync(target, { recursive: true, force: true });
20877
20995
  }
20878
20996
  function migrateCard(card) {
20879
- const { meta, body } = parseFrontmatter(fs56.readFileSync(card.file, "utf8"));
20997
+ const { meta, body } = parseFrontmatter(fs57.readFileSync(card.file, "utf8"));
20880
20998
  if (!meta) throw new Error("its frontmatter cannot be read");
20881
20999
  const raw = meta;
20882
21000
  const said3 = (key) => typeof raw[key] === "string" ? raw[key].trim() : "";
@@ -20886,19 +21004,19 @@ function migrateCard(card) {
20886
21004
  if (!flow) throw new Error("this board has no workflow to put it in");
20887
21005
  const text5 = (name2) => agentText(name2, meta.title || card.slug, body);
20888
21006
  const name = agentName(card, text5);
20889
- const dir = path61.join(AGENTS, name);
20890
- const file = path61.join(dir, AGENT_FILE3);
20891
- const madeDir = !fs56.existsSync(dir);
20892
- const wrote = !fs56.existsSync(file);
21007
+ const dir = path63.join(AGENTS, name);
21008
+ const file = path63.join(dir, AGENT_FILE3);
21009
+ const madeDir = !fs57.existsSync(dir);
21010
+ const wrote = !fs57.existsSync(file);
20893
21011
  try {
20894
- fs56.mkdirSync(dir, { recursive: true });
20895
- if (wrote) fs56.writeFileSync(file, text5(name));
21012
+ fs57.mkdirSync(dir, { recursive: true });
21013
+ if (wrote) fs57.writeFileSync(file, text5(name));
20896
21014
  const adopted = adoptWorkflowScheduled(flow.id, name, { cadence, lastRun });
20897
21015
  if (!adopted.ok) throw new Error(adopted.error);
20898
21016
  questionsToTriage(meta, name);
20899
21017
  } catch (e) {
20900
- if (madeDir) fs56.rmSync(dir, { recursive: true, force: true });
20901
- else if (wrote) fs56.rmSync(file, { force: true });
21018
+ if (madeDir) fs57.rmSync(dir, { recursive: true, force: true });
21019
+ else if (wrote) fs57.rmSync(file, { force: true });
20902
21020
  throw e;
20903
21021
  }
20904
21022
  if (card.folder) mergeInto2(card.folder, dir, ["root.md"]);
@@ -20908,7 +21026,7 @@ function migrateCard(card) {
20908
21026
  function migrateRecurringCards() {
20909
21027
  const done2 = { agents: [], removed: [], failed: [] };
20910
21028
  const dir = recurringDir();
20911
- if (!fs56.existsSync(dir)) return done2;
21029
+ if (!fs57.existsSync(dir)) return done2;
20912
21030
  migratePruneMemoryCard();
20913
21031
  moveSideFolders();
20914
21032
  for (const card of legacyCards()) {
@@ -20921,7 +21039,7 @@ function migrateRecurringCards() {
20921
21039
  done2.failed.push({ card: rel(card.file), why: e instanceof Error ? e.message : String(e) });
20922
21040
  }
20923
21041
  }
20924
- if (isEmpty(dir)) fs56.rmSync(dir, { recursive: true, force: true });
21042
+ if (isEmpty(dir)) fs57.rmSync(dir, { recursive: true, force: true });
20925
21043
  return done2;
20926
21044
  }
20927
21045
  function recurringMigrationLines(done2) {
@@ -20954,14 +21072,14 @@ var init_recurring = __esm({
20954
21072
  PRUNE_SLUG = "prune-the-memory";
20955
21073
  FETCH_SLUG = "fetch-triage-items";
20956
21074
  AGENT_FILE3 = "AGENT.md";
20957
- recurringDir = () => path61.join(TODO, LEGACY_RECURRING);
20958
- isEmpty = (dir) => fs56.readdirSync(dir).every((name) => name === ".DS_Store");
21075
+ recurringDir = () => path63.join(TODO, LEGACY_RECURRING);
21076
+ isEmpty = (dir) => fs57.readdirSync(dir).every((name) => name === ".DS_Store");
20959
21077
  SECTION = /^##\s+(.+?)\s*$/;
20960
21078
  }
20961
21079
  });
20962
21080
 
20963
21081
  // src/commands/init.ts
20964
- import fs57 from "node:fs";
21082
+ import fs58 from "node:fs";
20965
21083
  function boardReadme() {
20966
21084
  return `# Board
20967
21085
 
@@ -20974,20 +21092,20 @@ _(none)_
20974
21092
  `;
20975
21093
  }
20976
21094
  function writeConfigIfMissing() {
20977
- if (fs57.existsSync(CONFIG)) return false;
20978
- fs57.mkdirSync(KANBAN, { recursive: true });
20979
- fs57.writeFileSync(CONFIG, CONFIG_TEMPLATE);
21095
+ if (fs58.existsSync(CONFIG)) return false;
21096
+ fs58.mkdirSync(KANBAN, { recursive: true });
21097
+ fs58.writeFileSync(CONFIG, CONFIG_TEMPLATE);
20980
21098
  return true;
20981
21099
  }
20982
21100
  function writeModulesIfMissing() {
20983
- if (fs57.existsSync(MODULES_MD)) return false;
20984
- fs57.mkdirSync(KANBAN, { recursive: true });
20985
- fs57.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
21101
+ if (fs58.existsSync(MODULES_MD)) return false;
21102
+ fs58.mkdirSync(KANBAN, { recursive: true });
21103
+ fs58.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
20986
21104
  return true;
20987
21105
  }
20988
21106
  function writeGitignoreIfMissing() {
20989
- fs57.mkdirSync(KANBAN, { recursive: true });
20990
- const text5 = fs57.existsSync(KANBAN_GITIGNORE) ? fs57.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
21107
+ fs58.mkdirSync(KANBAN, { recursive: true });
21108
+ const text5 = fs58.existsSync(KANBAN_GITIGNORE) ? fs58.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
20991
21109
  const has = (rule) => text5.split("\n").some((line) => line.trim() === rule.line);
20992
21110
  const missing = IGNORE_RULES.filter((rule) => !has(rule));
20993
21111
  if (!missing.length) return false;
@@ -20995,37 +21113,37 @@ function writeGitignoreIfMissing() {
20995
21113
  ${rule.line}
20996
21114
  `).join("");
20997
21115
  const separator = !text5 || text5.endsWith("\n") ? "" : "\n";
20998
- fs57.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
21116
+ fs58.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
20999
21117
  return true;
21000
21118
  }
21001
21119
  function writeSkeletonIfMissing() {
21002
21120
  const added = [];
21003
- if (!fs57.existsSync(TODO)) {
21004
- fs57.mkdirSync(TODO, { recursive: true });
21121
+ if (!fs58.existsSync(TODO)) {
21122
+ fs58.mkdirSync(TODO, { recursive: true });
21005
21123
  added.push(`${rel(TODO)}/`);
21006
21124
  }
21007
- if (!fs57.existsSync(README)) {
21008
- fs57.writeFileSync(README, boardReadme());
21125
+ if (!fs58.existsSync(README)) {
21126
+ fs58.writeFileSync(README, boardReadme());
21009
21127
  added.push(rel(README));
21010
21128
  }
21011
21129
  return added;
21012
21130
  }
21013
21131
  function retireReleases() {
21014
21132
  const done2 = [];
21015
- if (fs57.existsSync(RELEASES)) {
21016
- fs57.rmSync(RELEASES);
21133
+ if (fs58.existsSync(RELEASES)) {
21134
+ fs58.rmSync(RELEASES);
21017
21135
  done2.push(`deleted ${rel(RELEASES)}`);
21018
21136
  }
21019
21137
  let cards = 0;
21020
21138
  for (const dir of [TODO, ARCHIVE]) {
21021
- if (!fs57.existsSync(dir)) continue;
21139
+ if (!fs58.existsSync(dir)) continue;
21022
21140
  for (const file of walkMd(dir)) {
21023
- const text5 = fs57.readFileSync(file, "utf8");
21141
+ const text5 = fs58.readFileSync(file, "utf8");
21024
21142
  const end2 = text5.startsWith("---\n") ? text5.indexOf("\n---", 3) : -1;
21025
21143
  if (end2 < 0) continue;
21026
21144
  const head = text5.slice(0, end2).replace(/\nrelease:[^\n]*/, "");
21027
21145
  if (head.length === end2) continue;
21028
- fs57.writeFileSync(file, head + text5.slice(end2));
21146
+ fs58.writeFileSync(file, head + text5.slice(end2));
21029
21147
  cards++;
21030
21148
  }
21031
21149
  }
@@ -21033,7 +21151,7 @@ function retireReleases() {
21033
21151
  return done2.join(", ");
21034
21152
  }
21035
21153
  function cmdInit() {
21036
- if (fs57.existsSync(KANBAN)) {
21154
+ if (fs58.existsSync(KANBAN)) {
21037
21155
  const added = [
21038
21156
  ...writeSkeletonIfMissing(),
21039
21157
  writeConfigIfMissing() && rel(CONFIG),
@@ -21068,8 +21186,8 @@ function cmdInit() {
21068
21186
  }
21069
21187
  return { board: rel(KANBAN), created: false, added, memory_paths: scaffolded.map((s) => rel(s.dir)) };
21070
21188
  }
21071
- fs57.mkdirSync(TODO, { recursive: true });
21072
- fs57.writeFileSync(README, boardReadme());
21189
+ fs58.mkdirSync(TODO, { recursive: true });
21190
+ fs58.writeFileSync(README, boardReadme());
21073
21191
  writeConfigIfMissing();
21074
21192
  scaffoldProjectMemory();
21075
21193
  writeModulesIfMissing();
@@ -21158,25 +21276,25 @@ var init_scheduled = __esm({
21158
21276
  });
21159
21277
 
21160
21278
  // src/lib/card-age.ts
21161
- import fs58 from "node:fs";
21162
- import path62 from "node:path";
21279
+ import fs59 from "node:fs";
21280
+ import path64 from "node:path";
21163
21281
  function staleAfterIn(config) {
21164
21282
  const days = Number(LINE.exec(config)?.[1]);
21165
21283
  return Number.isInteger(days) && days > 0 ? days : STALE_AFTER_DEFAULT;
21166
21284
  }
21167
21285
  function staleAfter() {
21168
- if (!fs58.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
21169
- return staleAfterIn(fs58.readFileSync(CONFIG, "utf8"));
21286
+ if (!fs59.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
21287
+ return staleAfterIn(fs59.readFileSync(CONFIG, "utf8"));
21170
21288
  }
21171
21289
  function todoPathspec(top) {
21172
- const from = path62.relative(real(top), real(TODO));
21173
- if (!from || from.startsWith("..") || path62.isAbsolute(from)) return null;
21174
- return from.split(path62.sep).join("/");
21290
+ const from = path64.relative(real(top), real(TODO));
21291
+ if (!from || from.startsWith("..") || path64.isAbsolute(from)) return null;
21292
+ return from.split(path64.sep).join("/");
21175
21293
  }
21176
21294
  function cardFile2(spec, printed) {
21177
21295
  const p = unquotePath(printed);
21178
21296
  if (!p.startsWith(`${spec}/`)) return null;
21179
- return path62.join(TODO, ...p.slice(spec.length + 1).split("/"));
21297
+ return path64.join(TODO, ...p.slice(spec.length + 1).split("/"));
21180
21298
  }
21181
21299
  function dirtyCards(top, spec) {
21182
21300
  const out = git(["status", "--porcelain", "--untracked-files=all", "--", spec], top);
@@ -21223,9 +21341,9 @@ var init_card_age = __esm({
21223
21341
  gitTop = () => git(["rev-parse", "--show-toplevel"])?.trim() || null;
21224
21342
  real = (p) => {
21225
21343
  try {
21226
- return fs58.realpathSync(p);
21344
+ return fs59.realpathSync(p);
21227
21345
  } catch {
21228
- return path62.resolve(p);
21346
+ return path64.resolve(p);
21229
21347
  }
21230
21348
  };
21231
21349
  unquotePath = (line) => {
@@ -21260,8 +21378,8 @@ var init_card_holds = __esm({
21260
21378
  });
21261
21379
 
21262
21380
  // src/commands/list.ts
21263
- import fs59 from "node:fs";
21264
- import path63 from "node:path";
21381
+ import fs60 from "node:fs";
21382
+ import path65 from "node:path";
21265
21383
  function summaryLine(body) {
21266
21384
  const lines = body.split("\n");
21267
21385
  let i = 0;
@@ -21277,13 +21395,13 @@ function summaryLine(body) {
21277
21395
  function openRows() {
21278
21396
  const rows = [];
21279
21397
  for (const file of walkMd(TODO)) {
21280
- const base = path63.basename(file);
21398
+ const base = path65.basename(file);
21281
21399
  if (base === "README.md") continue;
21282
21400
  const isRoot = base === "root.md";
21283
- const id = isRoot ? idPrefix(path63.basename(path63.dirname(file))) : idPrefix(base);
21401
+ const id = isRoot ? idPrefix(path65.basename(path65.dirname(file))) : idPrefix(base);
21284
21402
  if (id == null) continue;
21285
- if (isLegacyRecurring(path63.relative(TODO, file))) continue;
21286
- const { meta, body } = parseFrontmatter(fs59.readFileSync(file, "utf8"));
21403
+ if (isLegacyRecurring(path65.relative(TODO, file))) continue;
21404
+ const { meta, body } = parseFrontmatter(fs60.readFileSync(file, "utf8"));
21287
21405
  rows.push({
21288
21406
  id,
21289
21407
  file,
@@ -21325,15 +21443,15 @@ function cmdStale(rows, all2, scope, mod) {
21325
21443
  }
21326
21444
  function archivedFiles() {
21327
21445
  const files2 = /* @__PURE__ */ new Map();
21328
- if (!fs59.existsSync(ARCHIVE)) return files2;
21446
+ if (!fs60.existsSync(ARCHIVE)) return files2;
21329
21447
  for (const file of walkMd(ARCHIVE)) {
21330
- const id = idPrefix(path63.basename(file));
21448
+ const id = idPrefix(path65.basename(file));
21331
21449
  if (id !== null) files2.set(id, file);
21332
21450
  }
21333
21451
  for (const dir of walkDirs(ARCHIVE)) {
21334
- const id = idPrefix(path63.basename(dir));
21335
- const root = path63.join(dir, "root.md");
21336
- if (id !== null && fs59.existsSync(root)) files2.set(id, root);
21452
+ const id = idPrefix(path65.basename(dir));
21453
+ const root = path65.join(dir, "root.md");
21454
+ if (id !== null && fs60.existsSync(root)) files2.set(id, root);
21337
21455
  }
21338
21456
  return files2;
21339
21457
  }
@@ -21444,14 +21562,14 @@ var init_list = __esm({
21444
21562
  });
21445
21563
 
21446
21564
  // src/commands/misc.ts
21447
- import fs60 from "node:fs";
21448
- import path64 from "node:path";
21565
+ import fs61 from "node:fs";
21566
+ import path66 from "node:path";
21449
21567
  function extractOldMeta(text5, file) {
21450
21568
  const grab = (re) => {
21451
21569
  const m = text5.match(re);
21452
21570
  return m ? m[1].trim() : null;
21453
21571
  };
21454
- const title = grab(/^#\s+(.+)$/m) || slugify(path64.basename(file, ".md").replace(/^\d+-/, "")).replace(/-/g, " ");
21572
+ const title = grab(/^#\s+(.+)$/m) || slugify(path66.basename(file, ".md").replace(/^\d+-/, "")).replace(/-/g, " ");
21455
21573
  const norm = (raw) => {
21456
21574
  const v = (raw || "").toLowerCase();
21457
21575
  return LEVELS.includes(v) ? v : "med";
@@ -21478,11 +21596,11 @@ function stripOldHeader(text5) {
21478
21596
  }
21479
21597
  function cmdMigrate(opts) {
21480
21598
  const dry = opts.dryRun === true;
21481
- const files2 = walkMd(TODO).filter((f) => path64.basename(f) !== "README.md");
21599
+ const files2 = walkMd(TODO).filter((f) => path66.basename(f) !== "README.md");
21482
21600
  let changed = 0;
21483
21601
  let skipped = 0;
21484
21602
  for (const file of files2) {
21485
- const text5 = fs60.readFileSync(file, "utf8");
21603
+ const text5 = fs61.readFileSync(file, "utf8");
21486
21604
  if (text5.trimStart().startsWith("---")) {
21487
21605
  skipped++;
21488
21606
  continue;
@@ -21491,7 +21609,7 @@ function cmdMigrate(opts) {
21491
21609
  const out = serializeFrontmatter(meta) + "\n\n" + stripOldHeader(text5).replace(/^\n+/, "");
21492
21610
  if (dry) say(`would migrate ${rel(file)} (priority=${meta.priority})`);
21493
21611
  else {
21494
- fs60.writeFileSync(file, out.endsWith("\n") ? out : out + "\n");
21612
+ fs61.writeFileSync(file, out.endsWith("\n") ? out : out + "\n");
21495
21613
  say(`migrated ${rel(file)}`);
21496
21614
  }
21497
21615
  changed++;
@@ -21512,10 +21630,10 @@ var init_misc = __esm({
21512
21630
  });
21513
21631
 
21514
21632
  // src/lib/group-close.ts
21515
- import fs61 from "node:fs";
21633
+ import fs62 from "node:fs";
21516
21634
  function groupCloses(rootFile) {
21517
21635
  try {
21518
- return groupCloseOf(fs61.readFileSync(rootFile, "utf8"));
21636
+ return groupCloseOf(fs62.readFileSync(rootFile, "utf8"));
21519
21637
  } catch {
21520
21638
  return false;
21521
21639
  }
@@ -21528,12 +21646,12 @@ var init_group_close = __esm({
21528
21646
  });
21529
21647
 
21530
21648
  // src/commands/remove.ts
21531
- import fs62 from "node:fs";
21532
- import path65 from "node:path";
21649
+ import fs63 from "node:fs";
21650
+ import path67 from "node:path";
21533
21651
  function leavingIds(id, found2) {
21534
21652
  const ids = /* @__PURE__ */ new Set([id]);
21535
21653
  if (found2.kind === "group") {
21536
- const names4 = [...walkMd(found2.target), ...walkDirs(found2.target)].map((f) => path65.basename(f));
21654
+ const names4 = [...walkMd(found2.target), ...walkDirs(found2.target)].map((f) => path67.basename(f));
21537
21655
  for (const name of names4) {
21538
21656
  const n = idPrefix(name);
21539
21657
  if (n !== null) ids.add(n);
@@ -21545,10 +21663,10 @@ function findMentions(ids) {
21545
21663
  const hits = [];
21546
21664
  const re = new RegExp(ids.map((id) => `#${id}(?!\\d)`).join("|"));
21547
21665
  for (const dir of [TODO, MEMORY]) {
21548
- if (!fs62.existsSync(dir)) continue;
21666
+ if (!fs63.existsSync(dir)) continue;
21549
21667
  for (const file of walkMd(dir)) {
21550
- if (path65.basename(file) === "README.md") continue;
21551
- const lines = fs62.readFileSync(file, "utf8").split("\n");
21668
+ if (path67.basename(file) === "README.md") continue;
21669
+ const lines = fs63.readFileSync(file, "utf8").split("\n");
21552
21670
  const fmEnd = frontmatterEnd(lines);
21553
21671
  lines.forEach((line, i) => {
21554
21672
  if (!re.test(line)) return;
@@ -21564,12 +21682,12 @@ function findMentions(ids) {
21564
21682
  return hits;
21565
21683
  }
21566
21684
  function leavingCards(id, found2) {
21567
- const own = found2.kind === "group" ? path65.join(found2.target, "root.md") : found2.target;
21685
+ const own = found2.kind === "group" ? path67.join(found2.target, "root.md") : found2.target;
21568
21686
  const cards = [{ id, file: own }];
21569
21687
  if (found2.kind !== "group") return cards;
21570
21688
  for (const file of walkMd(found2.target)) {
21571
21689
  if (file === own) continue;
21572
- const n = idPrefix(path65.basename(file));
21690
+ const n = idPrefix(path67.basename(file));
21573
21691
  if (n !== null) cards.push({ id: n, file });
21574
21692
  }
21575
21693
  return cards;
@@ -21578,10 +21696,10 @@ function stampLeaving(cards, rejection) {
21578
21696
  const day = formatDay();
21579
21697
  const stamp4 = rejection && !rejection.discard ? { reason: rejection.reason, at: (/* @__PURE__ */ new Date()).toISOString(), by: insideRun() ? "agent" : "user" } : rejection && { reason: rejection.reason };
21580
21698
  for (const card of cards) {
21581
- if (!fs62.existsSync(card.file)) continue;
21582
- const text5 = fs62.readFileSync(card.file, "utf8");
21699
+ if (!fs63.existsSync(card.file)) continue;
21700
+ const text5 = fs63.readFileSync(card.file, "utf8");
21583
21701
  const stamped = stampLeavingIn(text5, day, stamp4);
21584
- if (stamped !== text5) fs62.writeFileSync(card.file, stamped);
21702
+ if (stamped !== text5) fs63.writeFileSync(card.file, stamped);
21585
21703
  }
21586
21704
  }
21587
21705
  function unfinishedDelivery(id) {
@@ -21597,7 +21715,7 @@ function unfinishedDelivery(id) {
21597
21715
  }[gap];
21598
21716
  return `#${id} is not finished: ${what}.`;
21599
21717
  }
21600
- const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs62.existsSync(path65.join(ASSETS, src.slice(".assets/".length))));
21718
+ const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs63.existsSync(path67.join(ASSETS, src.slice(".assets/".length))));
21601
21719
  return missing ? `#${id} is not finished: ${missing} is not on this machine.` : null;
21602
21720
  }
21603
21721
  function agentDecisions(text5) {
@@ -21624,8 +21742,8 @@ function removeCard2(id, metric, options) {
21624
21742
  const unfinished = metric === "completed" ? unfinishedDelivery(id) : null;
21625
21743
  if (unfinished) die(unfinished, { kind: "plan-delivery-unfinished" });
21626
21744
  const dest = options.cleanupDiscarded && locateArchived(id) ? null : archiveDest(found2);
21627
- const cardFile3 = found2.kind === "group" ? path65.join(found2.target, "root.md") : found2.target;
21628
- const cardText = fs62.existsSync(cardFile3) ? fs62.readFileSync(cardFile3, "utf8") : "";
21745
+ const cardFile3 = found2.kind === "group" ? path67.join(found2.target, "root.md") : found2.target;
21746
+ const cardText = fs63.existsSync(cardFile3) ? fs63.readFileSync(cardFile3, "utf8") : "";
21629
21747
  const { meta: cardMeta3 } = parseFrontmatter(cardText);
21630
21748
  const alsoRemoved = found2.kind === "group" ? walkMd(found2.target).filter((f) => f !== cardFile3).map((f) => rel(f)).sort() : [];
21631
21749
  const leftIds = leavingIds(id, found2);
@@ -21656,10 +21774,10 @@ function removeCard2(id, metric, options) {
21656
21774
  const groupRoot = found2.kind === "file" && !options.closing ? enclosingGroupRoot(found2.target) : null;
21657
21775
  if (dest) {
21658
21776
  stampLeaving(leaving, metric === "rejected" ? { reason: options.reason?.trim() ?? "", discard: options.discard === true } : null);
21659
- fs62.mkdirSync(ARCHIVE, { recursive: true });
21660
- fs62.renameSync(found2.target, dest);
21777
+ fs63.mkdirSync(ARCHIVE, { recursive: true });
21778
+ fs63.renameSync(found2.target, dest);
21661
21779
  } else {
21662
- fs62.rmSync(found2.target, { recursive: true, force: true });
21780
+ fs63.rmSync(found2.target, { recursive: true, force: true });
21663
21781
  }
21664
21782
  const removedRefs = stripReadmeRefs(found2);
21665
21783
  let marked2 = null;
@@ -21708,14 +21826,14 @@ function removeCard2(id, metric, options) {
21708
21826
  };
21709
21827
  }
21710
21828
  function closeGroup(rootFile) {
21711
- const rootId = idPrefix(path65.basename(path65.dirname(rootFile)));
21829
+ const rootId = idPrefix(path67.basename(path67.dirname(rootFile)));
21712
21830
  if (rootId === null) return null;
21713
21831
  if (runnerProject(KANBAN)) return null;
21714
21832
  if (!groupCloses(rootFile)) return null;
21715
21833
  say(`
21716
21834
  every subtask line on #${rootId} is resolved \u2014 closing the group:`);
21717
21835
  try {
21718
- const { meta, body } = parseFrontmatter(fs62.readFileSync(rootFile, "utf8"));
21836
+ const { meta, body } = parseFrontmatter(fs63.readFileSync(rootFile, "utf8"));
21719
21837
  const res = cmdRemove(rootId, "completed", { closing: true });
21720
21838
  return {
21721
21839
  id: rootId,
@@ -21772,7 +21890,7 @@ function cleanupDiscardedCards(sessionId) {
21772
21890
  if (card.pending) throw new Error(`Discarding #${card.id} did not finish. Retry the discard.`);
21773
21891
  while (locate(card.id)) cmdRemove(card.id, "rejected", { discard: true, cleanupDiscarded: true });
21774
21892
  dropCrossRefs(card.id);
21775
- stripReadmeRefs({ kind: "file", rel: path65.relative(TODO, path65.resolve(REPO_ROOT, card.path)).split(path65.sep).join("/") });
21893
+ stripReadmeRefs({ kind: "file", rel: path67.relative(TODO, path67.resolve(REPO_ROOT, card.path)).split(path67.sep).join("/") });
21776
21894
  }
21777
21895
  return discarded.map((c) => c.id);
21778
21896
  });
@@ -21858,8 +21976,8 @@ var init_memory_file = __esm({
21858
21976
  });
21859
21977
 
21860
21978
  // src/commands/rule.ts
21861
- import fs63 from "node:fs";
21862
- import path66 from "node:path";
21979
+ import fs64 from "node:fs";
21980
+ import path68 from "node:path";
21863
21981
  function cmdRule(askedName, flags) {
21864
21982
  const agent = askedName.trim();
21865
21983
  if (!agentRoster().some((a) => a.name === agent)) {
@@ -21868,7 +21986,7 @@ function cmdRule(askedName, flags) {
21868
21986
  const rule = readRuleText(flags.file, flags.text);
21869
21987
  const res = setAgentRule(agent, rule);
21870
21988
  if (!res.ok) die(res.error);
21871
- const file = rel(path66.join(RULES, `${agent}.md`));
21989
+ const file = rel(path68.join(RULES, `${agent}.md`));
21872
21990
  say(rule ? `wrote the \`${agent}\` rule (${file})` : `cleared the \`${agent}\` rule`);
21873
21991
  return { agent, file, cleared: !rule };
21874
21992
  }
@@ -21876,7 +21994,7 @@ function readRuleText(file, text5) {
21876
21994
  if (file !== void 0 && text5 !== void 0) die("pass --file or --text, not both");
21877
21995
  if (file !== void 0) {
21878
21996
  try {
21879
- return fs63.readFileSync(file, "utf8").trim();
21997
+ return fs64.readFileSync(file, "utf8").trim();
21880
21998
  } catch {
21881
21999
  die(`can't read ${file} \u2014 write the rule to a file, then pass its path`);
21882
22000
  }
@@ -22003,22 +22121,22 @@ var init_storyboard = __esm({
22003
22121
  });
22004
22122
 
22005
22123
  // src/lib/spec-contract.ts
22006
- import fs64 from "node:fs";
22007
- import path67 from "node:path";
22124
+ import fs65 from "node:fs";
22125
+ import path69 from "node:path";
22008
22126
  function snapshotSpecs() {
22009
22127
  const out = /* @__PURE__ */ new Map();
22010
- if (!fs64.existsSync(TODO)) return out;
22128
+ if (!fs65.existsSync(TODO)) return out;
22011
22129
  for (const file of walkMd(TODO)) {
22012
- if (isLegacyRecurring(path67.relative(TODO, file))) continue;
22013
- const id = idPrefix(path67.basename(file) === "root.md" ? path67.basename(path67.dirname(file)) : path67.basename(file));
22014
- if (id !== null) out.set(file, { id, text: fs64.readFileSync(file, "utf8") });
22130
+ if (isLegacyRecurring(path69.relative(TODO, file))) continue;
22131
+ const id = idPrefix(path69.basename(file) === "root.md" ? path69.basename(path69.dirname(file)) : path69.basename(file));
22132
+ if (id !== null) out.set(file, { id, text: fs65.readFileSync(file, "utf8") });
22015
22133
  }
22016
22134
  return out;
22017
22135
  }
22018
22136
  function enclosingGroups(file) {
22019
22137
  const ids = [];
22020
22138
  for (let root = enclosingGroupRoot(file); root; root = enclosingGroupRoot(root)) {
22021
- const id = idPrefix(path67.basename(path67.dirname(root)));
22139
+ const id = idPrefix(path69.basename(path69.dirname(root)));
22022
22140
  if (id !== null) ids.push(id);
22023
22141
  }
22024
22142
  return ids;
@@ -22187,9 +22305,9 @@ function validateSpec(file, text5, id) {
22187
22305
  }
22188
22306
  function inside(dir, name) {
22189
22307
  try {
22190
- const root = fs64.realpathSync(dir);
22191
- const real2 = fs64.realpathSync(path67.join(dir, name));
22192
- return real2.startsWith(root + path67.sep) && fs64.statSync(real2).isFile() ? real2 : null;
22308
+ const root = fs65.realpathSync(dir);
22309
+ const real2 = fs65.realpathSync(path69.join(dir, name));
22310
+ return real2.startsWith(root + path69.sep) && fs65.statSync(real2).isFile() ? real2 : null;
22193
22311
  } catch {
22194
22312
  return null;
22195
22313
  }
@@ -22207,7 +22325,7 @@ function variantsProblem(raw, src, id) {
22207
22325
  if (files2.length < 2 || !files2.every((f) => typeof f === "string" && f)) return `variants needs at least two labels, each naming a file. ${shape}`;
22208
22326
  if (!files2.includes(src)) return `src="${src}" is not one of the variants. Set src to the version shown first.`;
22209
22327
  if (id === void 0) return null;
22210
- const dir = path67.join(ASSETS, String(id));
22328
+ const dir = path69.join(ASSETS, String(id));
22211
22329
  for (const f of files2) {
22212
22330
  const parts = f.split("/");
22213
22331
  if (parts.length !== 3 || parts[0] !== ".assets" || parts[1] !== String(id) || !inside(dir, parts[2])) {
@@ -22217,7 +22335,7 @@ function variantsProblem(raw, src, id) {
22217
22335
  return null;
22218
22336
  }
22219
22337
  function compareProblem(attrs, id) {
22220
- const dir = path67.join(ASSETS, String(id));
22338
+ const dir = path69.join(ASSETS, String(id));
22221
22339
  const src = (message) => ({ rule: "compare-src", message });
22222
22340
  const shots = (message) => ({ rule: "compare-shots", message });
22223
22341
  for (const side of ["a", "b"]) {
@@ -22237,7 +22355,7 @@ function compareProblem(attrs, id) {
22237
22355
  const file = inside(dir, named2.name);
22238
22356
  if (!file) return { message: `Compare shots ${at} names no file in this card's asset folder. Write the JSON there or fix the path.` };
22239
22357
  try {
22240
- return { data: JSON.parse(fs64.readFileSync(file, "utf8")) };
22358
+ return { data: JSON.parse(fs65.readFileSync(file, "utf8")) };
22241
22359
  } catch {
22242
22360
  return { message: `${at} is not valid JSON.` };
22243
22361
  }
@@ -22257,7 +22375,7 @@ function compareProblem(attrs, id) {
22257
22375
  }
22258
22376
  function validateStoryboards(file, id, text5) {
22259
22377
  const errors = [];
22260
- const dir = path67.join(ASSETS, String(id));
22378
+ const dir = path69.join(ASSETS, String(id));
22261
22379
  for (const marker of storyboardMarkers(text5)) {
22262
22380
  const named2 = assetName(marker.src, id, ["json"]);
22263
22381
  const add = (message) => errors.push({ file: rel(file), line: marker.line, rule: "storyboard-src", message });
@@ -22406,8 +22524,8 @@ var init_mockups = __esm({
22406
22524
  });
22407
22525
 
22408
22526
  // src/commands/spec-write.ts
22409
- import fs65 from "node:fs";
22410
- import path68 from "node:path";
22527
+ import fs66 from "node:fs";
22528
+ import path70 from "node:path";
22411
22529
  function cmdSpecWrite(id, askedName, flags) {
22412
22530
  const agent = findSpecAgent(askedName);
22413
22531
  if (!agent) die(notAnAgent(askedName), { kind: "no-such-spec-agent", specAgent: askedName });
@@ -22415,11 +22533,11 @@ function cmdSpecWrite(id, askedName, flags) {
22415
22533
  const section = readSection(flags.file, flags.text);
22416
22534
  const found2 = locate(id);
22417
22535
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
22418
- const file = found2.kind === "group" ? path68.join(found2.target, "root.md") : found2.target;
22419
- const { meta, body } = parseFrontmatter(fs65.readFileSync(file, "utf8"));
22536
+ const file = found2.kind === "group" ? path70.join(found2.target, "root.md") : found2.target;
22537
+ const { meta, body } = parseFrontmatter(fs66.readFileSync(file, "utf8"));
22420
22538
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
22421
22539
  const { body: next, replaced } = splice(body, name, section);
22422
- fs65.writeFileSync(file, serializeFrontmatter(meta) + "\n" + next);
22540
+ fs66.writeFileSync(file, serializeFrontmatter(meta) + "\n" + next);
22423
22541
  say(`${replaced ? "rewrote" : "wrote"} the \`${name}\` section on #${id} (${rel(file)})`);
22424
22542
  return { id, specAgent: name, replaced, file: rel(file) };
22425
22543
  }
@@ -22428,7 +22546,7 @@ function readSection(file, text5) {
22428
22546
  let raw;
22429
22547
  if (file !== void 0) {
22430
22548
  try {
22431
- raw = fs65.readFileSync(file, "utf8");
22549
+ raw = fs66.readFileSync(file, "utf8");
22432
22550
  } catch {
22433
22551
  die(`can't read ${file} \u2014 write your section to a file, then pass its path`);
22434
22552
  }
@@ -22622,7 +22740,7 @@ function localBoard() {
22622
22740
  const no = checkWrite({ board: true }, env2, boardRevision());
22623
22741
  if (no) return no;
22624
22742
  const res = await resumeDelivery(deliveryId);
22625
- if (!res.ok) return opRefused(new Error(res.error || "the delivery could not be carried on"));
22743
+ if (!res.ok) return { ...opRefused(new Error(res.error || "the delivery could not be carried on")), reason: res.reason, args: res.args };
22626
22744
  return opOk(boardRevision(), { deliveryId: res.deliveryId, landed: res.landed, carryOn: res.carryOn });
22627
22745
  },
22628
22746
  async discardDelivery(deliveryId, env2) {
@@ -22894,11 +23012,11 @@ var init_shared = __esm({
22894
23012
  });
22895
23013
 
22896
23014
  // src/commands/goal.ts
22897
- import fs66 from "node:fs";
23015
+ import fs67 from "node:fs";
22898
23016
  function load() {
22899
23017
  const file = goalsFile();
22900
23018
  if (!file) die("Goals exist only inside a WildCrane goal discussion.");
22901
- const held4 = JSON.parse(fs66.readFileSync(file, "utf8"));
23019
+ const held4 = JSON.parse(fs67.readFileSync(file, "utf8"));
22902
23020
  if (held4.goals !== void 0 && held4.ideas !== void 0 && JSON.stringify(held4.goals) !== JSON.stringify(held4.ideas)) die("goals and ideas do not match.");
22903
23021
  const goals = held4.goals ?? held4.ideas;
22904
23022
  if (!Array.isArray(goals)) die("The goals array is missing or invalid.");
@@ -22923,7 +23041,7 @@ function splitBody2(text5) {
22923
23041
  }
22924
23042
  function readBody(bodyFile) {
22925
23043
  if (!bodyFile) die("--body-file is required; write the goal in a writable temporary file first.");
22926
- const text5 = fs66.readFileSync(bodyFile, "utf8");
23044
+ const text5 = fs67.readFileSync(bodyFile, "utf8");
22927
23045
  if (!text5.trim()) die("The goal must not be empty.");
22928
23046
  return splitBody2(text5);
22929
23047
  }
@@ -22935,7 +23053,7 @@ function named(held4, id) {
22935
23053
  function cmdGoal(args, opts) {
22936
23054
  const sub = args[0] ?? "";
22937
23055
  const { file, held: held4 } = load();
22938
- const write2 = () => fs66.writeFileSync(file, `${JSON.stringify({ workflows: held4.workflows, ideas: held4.goals }, null, 2)}
23056
+ const write2 = () => fs67.writeFileSync(file, `${JSON.stringify({ workflows: held4.workflows, ideas: held4.goals }, null, 2)}
22939
23057
  `);
22940
23058
  if (sub === "new") {
22941
23059
  const title = opts.title?.trim();
@@ -23005,8 +23123,8 @@ __export(board_exports, {
23005
23123
  buildBoardProgram: () => buildBoardProgram
23006
23124
  });
23007
23125
  import crypto4 from "node:crypto";
23008
- import fs67 from "node:fs";
23009
- import path69 from "node:path";
23126
+ import fs68 from "node:fs";
23127
+ import path71 from "node:path";
23010
23128
  async function dispatch(move2, cmd, args, opts, cli) {
23011
23129
  const ctx = ctxOf(cmd, cli.program);
23012
23130
  const data = await runAction(ctx, {}, async () => {
@@ -23045,7 +23163,7 @@ async function cloudCard(task, opts) {
23045
23163
  let request;
23046
23164
  if (typeof opts.bodyFile === "string") {
23047
23165
  try {
23048
- request = fs67.readFileSync(opts.bodyFile, "utf8");
23166
+ request = fs68.readFileSync(opts.bodyFile, "utf8");
23049
23167
  } catch {
23050
23168
  }
23051
23169
  }
@@ -23075,7 +23193,7 @@ async function cloudCard(task, opts) {
23075
23193
  const file = creationReceipt(`${checked.value}:${requestId}`, slot);
23076
23194
  const journal = readCreation(file, said3);
23077
23195
  if (!journal.made) {
23078
- const key = `akb-${path69.basename(file, ".json").slice(0, 40)}`;
23196
+ const key = `akb-${path71.basename(file, ".json").slice(0, 40)}`;
23079
23197
  const made = await createProjectTask(checked.value, journal.said, key);
23080
23198
  if (!made.ok) throw new BoardError(creationError(`Cloud did not make the task: ${made.error}`, triage), { kind: "refused" });
23081
23199
  journal.made = made.value;
@@ -23220,16 +23338,16 @@ var init_board2 = __esm({
23220
23338
  });
23221
23339
 
23222
23340
  // src/lib/board-cli.ts
23223
- import fs68 from "node:fs";
23224
- import path70 from "node:path";
23341
+ import fs69 from "node:fs";
23342
+ import path72 from "node:path";
23225
23343
  function useBoard(found2, dirNamed) {
23226
- if (!found2.named && found2.board === path70.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23344
+ if (!found2.named && found2.board === path72.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23227
23345
  else setBoardDir(found2.board, found2.root);
23228
23346
  useProjectState();
23229
23347
  }
23230
23348
  function whole(found2, move2) {
23231
23349
  if (move2 === MAKES_A_BOARD) return found2;
23232
- if (!fs68.existsSync(path70.join(found2.board, "todo"))) {
23350
+ if (!fs69.existsSync(path72.join(found2.board, "todo"))) {
23233
23351
  die(`the board in ${found2.board} has no todo/ \u2014 run \`init\` to add what is missing.`, {
23234
23352
  kind: "board-incomplete",
23235
23353
  dir: found2.root
@@ -23238,13 +23356,13 @@ function whole(found2, move2) {
23238
23356
  return found2;
23239
23357
  }
23240
23358
  function findBoardUpward(from, move2) {
23241
- let dir = path70.resolve(from);
23359
+ let dir = path72.resolve(from);
23242
23360
  for (; ; ) {
23243
- if (hasBoard(dir)) return { root: dir, board: path70.join(dir, "docs", "kanban") };
23361
+ if (hasBoard(dir)) return { root: dir, board: path72.join(dir, "docs", "kanban") };
23244
23362
  if (isBoardDir(dir)) return { root: projectRootOf(dir), board: dir };
23245
- const kept2 = path70.join(dir, ".akb", "kanban");
23246
- if (move2 !== MAKES_A_BOARD && fs68.existsSync(path70.join(kept2, "todo"))) return { root: dir, board: kept2 };
23247
- const up = path70.dirname(dir);
23363
+ const kept2 = path72.join(dir, ".akb", "kanban");
23364
+ if (move2 !== MAKES_A_BOARD && fs69.existsSync(path72.join(kept2, "todo"))) return { root: dir, board: kept2 };
23365
+ const up = path72.dirname(dir);
23248
23366
  if (up === dir) return null;
23249
23367
  dir = up;
23250
23368
  }
@@ -23252,11 +23370,11 @@ function findBoardUpward(from, move2) {
23252
23370
  function resolveBoard(move2, { board: board2, dir, cwd, installHint }) {
23253
23371
  const named2 = board2 ?? boardFromEnv();
23254
23372
  if (named2) {
23255
- const folder = path70.resolve(cwd, named2);
23256
- if (!fs68.existsSync(folder) && move2 !== MAKES_A_BOARD) {
23373
+ const folder = path72.resolve(cwd, named2);
23374
+ if (!fs69.existsSync(folder) && move2 !== MAKES_A_BOARD) {
23257
23375
  die(`no such folder: ${folder}`, { kind: "no-such-folder", dir: folder });
23258
23376
  }
23259
- if (fs68.existsSync(folder) && !isBoardDir(folder) && move2 !== MAKES_A_BOARD) {
23377
+ if (fs69.existsSync(folder) && !isBoardDir(folder) && move2 !== MAKES_A_BOARD) {
23260
23378
  die(`${folder} is not a board \u2014 it has no todo/ and config.md. ${installHint}\u3002`, {
23261
23379
  kind: "no-board",
23262
23380
  dir: folder
@@ -23265,24 +23383,24 @@ function resolveBoard(move2, { board: board2, dir, cwd, installHint }) {
23265
23383
  return { root: projectRootOf(folder), board: folder, named: true };
23266
23384
  }
23267
23385
  if (dir !== null) {
23268
- const root = path70.resolve(dir);
23269
- if (!fs68.existsSync(root)) die(`no such folder: ${root}`, { kind: "no-such-folder", dir: root });
23270
- const kept2 = path70.join(root, ".akb", "kanban");
23271
- if (!hasBoard(root) && move2 !== MAKES_A_BOARD && fs68.existsSync(path70.join(kept2, "todo"))) return whole({ root, board: kept2 }, move2);
23386
+ const root = path72.resolve(dir);
23387
+ if (!fs69.existsSync(root)) die(`no such folder: ${root}`, { kind: "no-such-folder", dir: root });
23388
+ const kept2 = path72.join(root, ".akb", "kanban");
23389
+ if (!hasBoard(root) && move2 !== MAKES_A_BOARD && fs69.existsSync(path72.join(kept2, "todo"))) return whole({ root, board: kept2 }, move2);
23272
23390
  if (!hasBoard(root) && move2 !== MAKES_A_BOARD) {
23273
23391
  die(`no board in ${root} \u2014 it has no docs/kanban/. ${installHint}\u3002`, {
23274
23392
  kind: "no-board",
23275
23393
  dir: root
23276
23394
  });
23277
23395
  }
23278
- return whole({ root, board: path70.join(root, "docs", "kanban") }, move2);
23396
+ return whole({ root, board: path72.join(root, "docs", "kanban") }, move2);
23279
23397
  }
23280
23398
  const found2 = findBoardUpward(cwd, move2);
23281
23399
  if (found2) return whole(found2, move2);
23282
- if (move2 === MAKES_A_BOARD) return { root: path70.resolve(cwd), board: path70.join(path70.resolve(cwd), "docs", "kanban") };
23400
+ if (move2 === MAKES_A_BOARD) return { root: path72.resolve(cwd), board: path72.join(path72.resolve(cwd), "docs", "kanban") };
23283
23401
  die(
23284
- `no board here. Looked in ${path70.resolve(cwd)} and every folder above it for docs/kanban/. ${installHint}\uFF0C\u6216\u7528 --board \u6307\u5B9A\u5DF2\u6709\u770B\u677F\u3002`,
23285
- { kind: "no-board", dir: path70.resolve(cwd) }
23402
+ `no board here. Looked in ${path72.resolve(cwd)} and every folder above it for docs/kanban/. ${installHint}\uFF0C\u6216\u7528 --board \u6307\u5B9A\u5DF2\u6709\u770B\u677F\u3002`,
23403
+ { kind: "no-board", dir: path72.resolve(cwd) }
23286
23404
  );
23287
23405
  }
23288
23406
  function editDistance(a, b) {
@@ -23364,8 +23482,8 @@ var init_board_cli = __esm({
23364
23482
  init_io();
23365
23483
  init_pointer();
23366
23484
  MAKES_A_BOARD = "init";
23367
- hasBoard = (dir) => fs68.existsSync(path70.join(dir, "docs", "kanban"));
23368
- isBoardDir = (dir) => fs68.existsSync(path70.join(dir, "todo")) && fs68.existsSync(path70.join(dir, "config.md"));
23485
+ hasBoard = (dir) => fs69.existsSync(path72.join(dir, "docs", "kanban"));
23486
+ isBoardDir = (dir) => fs69.existsSync(path72.join(dir, "todo")) && fs69.existsSync(path72.join(dir, "config.md"));
23369
23487
  boardFromEnv = () => {
23370
23488
  const named2 = process.env.AI4KANBAN_BOARD?.trim();
23371
23489
  return named2 ? named2 : null;
@@ -23409,7 +23527,7 @@ var init_card_chat = __esm({
23409
23527
  var conflict_default;
23410
23528
  var init_conflict = __esm({
23411
23529
  "src/guide/conflict.md"() {
23412
- conflict_default = "# Fit a delivery onto the moved target\n\nThe target branch moved while this delivery was being built, and the delivery has been\nrebased onto its new tip. Make the combined result work.\n\n- **Read both sides**: read the approved requirements, what the target brought in since the\n delivery's original base, and the delivery's own changes.\n- **Target wins**: keep the target's behavior unless the approved card requires changing it,\n replay only the delivery's intent on top of it, and never restore stale details.\n- **Resolve conflicts**: resolve every conflicted file the rebase stopped on.\n- **Find what git cannot see**: look for changes on one side that override, duplicate, or\n break the other side's work, including in files only one side touched.\n- **Fix by the project's conventions**: edit any file the fix needs, then run the project's\n own checks for the changed areas.\n- **Stage the result**: `git add` every file you changed; do not commit or finish the rebase.\n- **Stop when unsure**: if both intentions cannot be composed confidently or the checks still\n fail, stage nothing and run `akb delivery blocked <id> \"<what is in the way>\"`.\n- **Repair Git state**: fix Git failures in the worktree yourself, keeping its commits and\n staged work.\n- **Stay on this delivery**: do not change any card or create follow-up work.\n";
23530
+ conflict_default = "# Fit a delivery onto the moved target\n\nThe target branch moved while this delivery was being built, and the delivery has been\nrebased onto its new tip. Make the combined result work.\n\n- **Read both sides**: read the approved requirements, what the target brought in since the\n delivery's original base, and the delivery's own changes.\n- **Target wins**: keep the target's behavior unless the approved card requires changing it,\n replay only the delivery's intent on top of it, and never restore stale details.\n- **Resolve conflicts**: resolve every conflicted file the rebase stopped on.\n- **Find what git cannot see**: look for changes on one side that override, duplicate, or\n break the other side's work, including in files only one side touched.\n- **Fix by the project's conventions**: edit any file the fix needs, then run the project's\n own checks for the changed areas.\n- **Stage the result**: `git add` every file you changed; do not commit or finish the rebase.\n- **Check applicability**: use the working directory, project instructions, configuration\n sources and change history as evidence; missing configuration alone does not make a check\n inapplicable. Explain any inapplicable check and its alternative verification; never report\n an unrun or failing check as passed.\n- **Repair check failures**: fix directory, dependency, required configuration and implementation\n problems, then rerun applicable checks, including failures that predate this delivery. Do not\n create empty configuration, disable checks or lower standards to pass.\n- **User-action blockers**: only when composing both intentions or passing applicable checks\n needs a decision, permission or material only the user can supply, stage nothing and run\n `akb delivery blocked <id> \"<obstacle and required user action>\"`. Continue independent work;\n resume the rest once resolved.\n- **Repair Git state**: fix Git failures in the worktree yourself, keeping its commits and\n staged work.\n- **Stay on this delivery**: do not change any card or create follow-up work.\n";
23413
23531
  }
23414
23532
  });
23415
23533
 
@@ -23425,7 +23543,7 @@ var init_describe_project = __esm({
23425
23543
  var discuss_goal_default;
23426
23544
  var init_discuss_goal = __esm({
23427
23545
  "src/guide/discuss-goal.md"() {
23428
- discuss_goal_default = "# Discuss a goal\n\nTalk with the user as you would without extra context; any work before actual building is allowed.\n\n- **Build boundary**: when actual building is needed, save or update the goal with `akb raw goal` (see `akb raw goal --help`), then stop; an existing build continues in its current session under the project's build requirements.\n- **Missing information**: ask the user for information needed to form a goal.\n\n## Goals\n\n- **Goal format**: each goal has a title, an outcome of at most 150 words, and a `## Done when` section listing verifiable acceptance criteria, without technical design.\n- **Independent deliverables**: save separate deliverables as separate goals; remove a replaced goal with `akb raw goal drop --id <goal>`.\n- **Use judgment**: settle outcome decisions you can and explain them; ask only for decisions the user must make that change the result, with a recommendation.\n- **Plain words**: answer directly using everyday words.\n- **Hide machinery**: omit plans, files, paths, commands, tools, and connectors from replies; refer to actions by their button labels.\n";
23546
+ discuss_goal_default = "# Discuss a goal\n\nTalk with the user as you would without extra context; any work before actual building is allowed.\n\n- **Build boundary**: when actual building is needed, save or update the goal with `akb raw goal` (see `akb raw goal --help`), then stop; an existing build continues in its current session under the project's build requirements.\n- **Missing information**: ask the user for information needed to form a goal.\n- **Software failures**: read `akb guide troubleshoot` when root cause analysis is needed.\n\n## Goals\n\n- **Goal format**: each goal has a title, an outcome of at most 150 words, and a `## Done when` section listing verifiable acceptance criteria, without technical design.\n- **Independent deliverables**: save separate deliverables as separate goals; remove a replaced goal with `akb raw goal drop --id <goal>`.\n- **Use judgment**: settle outcome decisions you can and explain them; ask only for decisions the user must make that change the result, with a recommendation.\n- **Plain words**: answer directly using everyday words.\n- **Hide machinery**: omit plans, files, paths, commands, tools, and connectors from replies; refer to actions by their button labels.\n";
23429
23547
  }
23430
23548
  });
23431
23549
 
@@ -23449,7 +23567,7 @@ var init_follow_up = __esm({
23449
23567
  var implement_default;
23450
23568
  var init_implement = __esm({
23451
23569
  "src/guide/implement.md"() {
23452
- implement_default = '# Implement a settled card\n\nBuild the approved card. Preserve settled decisions and unrelated questions.\n\n- **Unchecked card**: a card with `triage:` set and an empty `## Scope` skipped planning; do\n what "Unchecked card" in `akb guide refine` says before building.\n- **User-action blockers**: follow `akb guide update-questions` and append a\n question describing the obstacle and action needed. Stop only dependent work; resume it\n after the user resolves the question. Settle routine technical choices yourself.\n- Do not replace or contradict what the card says.\n- **Defer what can wait**: queue as a follow-up any other work this card does not require;\n never hold the card with a question about it.\n- **Follow-ups**: follow `akb guide follow-up` for additional work.\n- **Decisions made while building**: record an answered material decision the user could\n reasonably reverse under `## Worth noting after implementation`.\n- A printed, interactive implementation may stay uncommitted in the target checkout only\n when the card already supplies a concrete outcome, boundaries, and build steps.\n Otherwise use the tracked implementation path. Background runs always keep their delivery\n path.\n\n## A build that writes its own card\n\n**Start now** sends a requirement with no card behind it \u2014 a typed sentence, the plan a\ndiscussion settled, or a triage item. Write the card first, in the same run, then build it. The board points\nthe run and its delivery at the card as the create lands, so from there it is an ordinary\nbuild.\n\n- **Read the plan first**: given a plan\'s path or a triage item\'s file, that file is the\n requirement \u2014 read it, and everything below reads "the plan" for "the sentence".\n- **Create it first**: `akb raw create --title ".."`. The title is one short line read off\n the sentence, or the plan\'s own title, in its own language \u2014 add\n `--slug <short-english-slug>` when that is not English, because filenames are ASCII. No `--modules`, no `--question` \u2014 nothing has evaluated this idea.\n- **The requirement is the summary**: replace the scaffold\'s opening paragraph with the\n sentence, or the plan\'s whole text, verbatim, in a fenced code block. Open the fence with\n more backticks than the longest run inside it, or the card fails validation on an unclosed\n fence.\n- **From a plan, name it**: pass `--source <plan path>` to the create.\n- **From a triage item, file it**: pass `--triage <source-id>` to the create, and run\n `akb triage archive <source-id> --card <id>` straight after, before any build work.\n- **Leave the rest of the scaffold**: `## Worth noting`, `## Scope`, `## Todo` and\n `## Decided by the agent` stay exactly as `raw create` wrote them.\n- **Then build that card**: the code block is the whole requirement \u2014 build exactly it and\n widen it no further. `akb card implement <id> --print` is the flow from here.\n';
23570
+ implement_default = "# Implement the approved requirements\n\nBuild the approved card or plan directly. Preserve settled decisions and unrelated questions;\ndo not replace or contradict the approved requirements. With no card, build only the given\nrequirement and create no card.\n\n- **Check applicability**: use the working directory, project instructions, configuration\n sources and change history as evidence; missing configuration alone does not make a check\n inapplicable. Explain any inapplicable check and its alternative verification; never report\n an unrun or failing check as passed. Do not bypass checks with empty configuration, disabled\n checks or lower standards.\n- **User-action blockers**: ask only when this build needs a decision, permission or material\n only the user can supply. On a card, follow `akb guide update-questions`; describe the obstacle\n and required action. Continue independent work and resume the rest once resolved.\n- **Defer what can wait**: follow `akb guide follow-up` for work this build does not require;\n never ask about it or let it block this build.\n- **Decisions made while building**: record an answered material decision the user could\n reasonably reverse under `## Worth noting after implementation` on the card.\n- **Delivery exception**: a printed, interactive implementation may stay uncommitted in the\n target checkout only when the card already supplies a concrete outcome, boundaries and\n build steps. Otherwise use the tracked implementation path. Background runs always keep\n their delivery path.\n";
23453
23571
  }
23454
23572
  });
23455
23573
 
@@ -23533,6 +23651,14 @@ var init_update_questions = __esm({
23533
23651
  }
23534
23652
  });
23535
23653
 
23654
+ // src/guide/troubleshoot.md
23655
+ var troubleshoot_default;
23656
+ var init_troubleshoot = __esm({
23657
+ "src/guide/troubleshoot.md"() {
23658
+ troubleshoot_default = "# Troubleshoot software failures\n\nTrace the causal chain from the observed failure, distinguishing its trigger from any system gap that lets it persist or spread.\nUse code, logs, or reproduction evidence to test candidate causes; when evidence is insufficient, state what remains uncertain and the next check that would distinguish them.\nFor example, if an external API outage leaves a job stuck retrying forever, check whether fault handling is missing or ineffective rather than assuming the outage alone explains the failure or that one mechanism is always the answer.\nIdentify the system behavior that needs to change and how reproducing the trigger would verify recovery or bounded failure, keeping investigation and any actual changes within the current session's operating boundaries.\n";
23659
+ }
23660
+ });
23661
+
23536
23662
  // src/guide/write-agent.md
23537
23663
  var write_agent_default;
23538
23664
  var init_write_agent = __esm({
@@ -23595,6 +23721,7 @@ var init_guide = __esm({
23595
23721
  init_revise();
23596
23722
  init_preview_agent();
23597
23723
  init_update_questions();
23724
+ init_troubleshoot();
23598
23725
  init_write_agent();
23599
23726
  init_writing();
23600
23727
  init_paths();
@@ -23605,6 +23732,7 @@ var init_guide = __esm({
23605
23732
  { name: "add-task", when: "turn one idea into a card", text: add_task_default },
23606
23733
  { name: "follow-up", when: "place additional work and prepare context for a follow-up card", text: follow_up_default },
23607
23734
  { name: "discuss-goal", when: "help decide what is worth building, and shape it into goals to start as tasks", text: discuss_goal_default },
23735
+ { name: "troubleshoot", when: "\u5B9A\u4F4D\u8F6F\u4EF6\u6545\u969C\u7684\u6839\u56E0\u4E0E\u4FEE\u590D\u65B9\u5411", text: troubleshoot_default },
23608
23736
  { name: "card-chat", when: "answer a card's conversation, and act on what each turn settles", text: card_chat_default },
23609
23737
  { name: "implement", when: "build a settled card and stop cleanly on an execution blocker", text: implement_default },
23610
23738
  { name: "archive", when: "finish a task \u2014 write its shipped line, then take it off the board", text: archive_default },
@@ -23632,8 +23760,8 @@ var init_guide = __esm({
23632
23760
  });
23633
23761
 
23634
23762
  // src/lib/agent/approve.ts
23635
- import fs74 from "node:fs";
23636
- import path76 from "node:path";
23763
+ import fs75 from "node:fs";
23764
+ import path78 from "node:path";
23637
23765
  function approvalRequest(req) {
23638
23766
  const id = req.id;
23639
23767
  const card = id === void 0 ? null : findCard(id);
@@ -23651,12 +23779,12 @@ function advancePhase(id) {
23651
23779
  const card = findCard(id);
23652
23780
  const found2 = locate(id);
23653
23781
  if (!card || !found2 || !awaitingApproval(card)) return { error: `#${id} is no longer waiting on approval.` };
23654
- const file = found2.kind === "group" ? path76.join(found2.target, "root.md") : found2.target;
23655
- const { meta, body } = parseFrontmatter(fs74.readFileSync(file, "utf8"));
23782
+ const file = found2.kind === "group" ? path78.join(found2.target, "root.md") : found2.target;
23783
+ const { meta, body } = parseFrontmatter(fs75.readFileSync(file, "utf8"));
23656
23784
  if (!meta) return { error: `#${id} has no frontmatter` };
23657
23785
  meta.phase = card.stage + 1;
23658
23786
  meta.status = "todo";
23659
- fs74.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
23787
+ fs75.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
23660
23788
  return null;
23661
23789
  }
23662
23790
  var init_approve = __esm({
@@ -23760,8 +23888,8 @@ function open2(req, sessionId) {
23760
23888
  markSpawned(run2.sessionId, pid);
23761
23889
  return { run: run2, spawned: pid !== void 0 };
23762
23890
  }
23763
- async function startResume(id, build) {
23764
- const opened = await openResume(id, build);
23891
+ async function startResume(id, options) {
23892
+ const opened = await openResume(id, options);
23765
23893
  if ("error" in opened) return opened;
23766
23894
  const pid = spawnWatcher(opened.run.sessionId);
23767
23895
  markSpawned(opened.run.sessionId, pid);
@@ -23787,16 +23915,16 @@ var init_start = __esm({
23787
23915
  });
23788
23916
 
23789
23917
  // src/lib/agent/task-chats.ts
23790
- import fs75 from "node:fs";
23791
- import path77 from "node:path";
23918
+ import fs76 from "node:fs";
23919
+ import path79 from "node:path";
23792
23920
  function taskChatFile(task, home3) {
23793
23921
  if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
23794
- return path77.join(taskChatsDir(home3), `${task}.jsonl`);
23922
+ return path79.join(taskChatsDir(home3), `${task}.jsonl`);
23795
23923
  }
23796
23924
  function readTaskChat(task, home3) {
23797
23925
  let text5;
23798
23926
  try {
23799
- text5 = fs75.readFileSync(taskChatFile(task, home3), "utf8");
23927
+ text5 = fs76.readFileSync(taskChatFile(task, home3), "utf8");
23800
23928
  } catch {
23801
23929
  return [];
23802
23930
  }
@@ -23817,13 +23945,13 @@ var init_task_chats = __esm({
23817
23945
  "use strict";
23818
23946
  init_home();
23819
23947
  TASK = /^[\w-]{1,100}$/;
23820
- taskChatsDir = (home3 = machineHome()) => path77.join(home3, "chats");
23948
+ taskChatsDir = (home3 = machineHome()) => path79.join(home3, "chats");
23821
23949
  }
23822
23950
  });
23823
23951
 
23824
23952
  // src/lib/agent/memory-review.ts
23825
- import fs76 from "node:fs";
23826
- import path78 from "node:path";
23953
+ import fs77 from "node:fs";
23954
+ import path80 from "node:path";
23827
23955
  function taskChatsToReview(tasks) {
23828
23956
  const out = [];
23829
23957
  for (const ref of [...new Set(tasks)]) {
@@ -23845,8 +23973,8 @@ function readArchived2(id) {
23845
23973
  const found2 = Number.isInteger(id) && id > 0 ? locateArchived(id) : null;
23846
23974
  if (!found2) return null;
23847
23975
  try {
23848
- const file = found2.kind === "group" ? path78.join(found2.target, "root.md") : found2.target;
23849
- const { meta, body } = parseFrontmatter(fs76.readFileSync(file, "utf8"));
23976
+ const file = found2.kind === "group" ? path80.join(found2.target, "root.md") : found2.target;
23977
+ const { meta, body } = parseFrontmatter(fs77.readFileSync(file, "utf8"));
23850
23978
  if (!meta) return null;
23851
23979
  return { id, title: meta.title, modules: meta.modules ?? [], rejected: meta.rejected, body };
23852
23980
  } catch {
@@ -23915,17 +24043,17 @@ var init_memory_review = __esm({
23915
24043
  });
23916
24044
 
23917
24045
  // src/lib/agent/dismissal-review.ts
23918
- import fs77 from "node:fs";
23919
- import path79 from "node:path";
24046
+ import fs78 from "node:fs";
24047
+ import path81 from "node:path";
23920
24048
  function rejectionsToReview() {
23921
- const dir = path79.join(ARCHIVE, REJECTIONS_TO_REVIEW);
23922
- if (!fs77.existsSync(dir)) return [];
24049
+ const dir = path81.join(ARCHIVE, REJECTIONS_TO_REVIEW);
24050
+ if (!fs78.existsSync(dir)) return [];
23923
24051
  const found2 = [];
23924
24052
  for (const file of walkMd(dir)) {
23925
24053
  const id = archivedId(file);
23926
24054
  if (id === null) continue;
23927
24055
  try {
23928
- const { meta } = parseFrontmatter(fs77.readFileSync(file, "utf8"));
24056
+ const { meta } = parseFrontmatter(fs78.readFileSync(file, "utf8"));
23929
24057
  if (!meta?.rejected || meta.rejected_by !== "user" || !meta.rejected_reason.trim()) continue;
23930
24058
  found2.push({ id, title: meta.title, file: rel(file), reason: meta.rejected_reason.trim(), rejectedAt: meta.rejected_at });
23931
24059
  } catch {
@@ -23955,7 +24083,7 @@ function citedSources(text5) {
23955
24083
  function withdrawnSources() {
23956
24084
  const cited = [...new Set(plannerCopies("rejected.md").flatMap((file) => {
23957
24085
  try {
23958
- return citedSources(fs77.readFileSync(file, "utf8"));
24086
+ return citedSources(fs78.readFileSync(file, "utf8"));
23959
24087
  } catch {
23960
24088
  return [];
23961
24089
  }
@@ -23980,8 +24108,8 @@ var init_dismissal_review = __esm({
23980
24108
  });
23981
24109
 
23982
24110
  // src/lib/agent/flow.ts
23983
- import fs78 from "node:fs";
23984
- import path80 from "node:path";
24111
+ import fs79 from "node:fs";
24112
+ import path82 from "node:path";
23985
24113
  function readCard2(id, home3 = "board") {
23986
24114
  const found2 = home3 === "archive" ? locateArchived(id) : locate(id);
23987
24115
  if (!found2) {
@@ -23990,10 +24118,10 @@ function readCard2(id, home3 = "board") {
23990
24118
  { kind: "card-not-found", id }
23991
24119
  );
23992
24120
  }
23993
- const file = found2.kind === "group" ? path80.join(found2.target, "root.md") : found2.target;
24121
+ const file = found2.kind === "group" ? path82.join(found2.target, "root.md") : found2.target;
23994
24122
  let text5;
23995
24123
  try {
23996
- text5 = fs78.readFileSync(file, "utf8");
24124
+ text5 = fs79.readFileSync(file, "utf8");
23997
24125
  } catch {
23998
24126
  die(`#${id} is on the board but ${rel(file)} can't be read.`, { kind: "card-unreadable", id });
23999
24127
  }
@@ -24117,7 +24245,7 @@ function workspaceField(delivery) {
24117
24245
  if (!delivery?.worktree) return [];
24118
24246
  return field("workspace", [
24119
24247
  `write code in ${delivery.worktree} \u2014 this delivery's own worktree, on branch ${delivery.branch}.`,
24120
- path80.resolve(process.cwd()).startsWith(worktreeDir(delivery.worktree)) ? `it is your working folder already; the board's own files are NOT in it and never go on that branch.` : `cd into it first \u2014 you are in the project checkout, and code written here is not part of this build. The board's own files are NOT in it and never go on that branch.`,
24248
+ path82.resolve(process.cwd()).startsWith(worktreeDir(delivery.worktree)) ? `it is your working folder already; the board's own files are NOT in it and never go on that branch.` : `cd into it first \u2014 you are in the project checkout, and code written here is not part of this build. The board's own files are NOT in it and never go on that branch.`,
24121
24249
  `every board command names the project's own copy: \`${boardCommandFor()} <command>\`.`,
24122
24250
  `${rel(REPO_ROOT)} is the project \u2014 the card, the memory files and the docs are changed there, not here.`
24123
24251
  ]);
@@ -24856,7 +24984,7 @@ __export(watch_exports, {
24856
24984
  watchRun: () => watchRun
24857
24985
  });
24858
24986
  import { spawn as spawn4 } from "node:child_process";
24859
- import fs79 from "node:fs";
24987
+ import fs80 from "node:fs";
24860
24988
  async function watchRun(sessionId, resume = startResume) {
24861
24989
  const spec = readSpec(sessionId);
24862
24990
  const run2 = peekRun(sessionId);
@@ -24892,11 +25020,11 @@ async function watchRun(sessionId, resume = startResume) {
24892
25020
  const record = claimed ?? run2;
24893
25021
  const sub = record.action === "sub";
24894
25022
  if (claim) await setCardStatus(claim.cardId, claim.status);
24895
- fs79.mkdirSync(SESSIONS_DIR, { recursive: true });
24896
- const logFile = fs79.createWriteStream(record.logPath, { flags: "a" });
25023
+ fs80.mkdirSync(SESSIONS_DIR, { recursive: true });
25024
+ const logFile = fs80.createWriteStream(record.logPath, { flags: "a" });
24897
25025
  logFile.on("error", () => {
24898
25026
  });
24899
- const eventsFile = fs79.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
25027
+ const eventsFile = fs80.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
24900
25028
  eventsFile.on("error", () => {
24901
25029
  });
24902
25030
  const event2 = (e) => eventsFile.write(`${JSON.stringify(e)}
@@ -25484,7 +25612,7 @@ var init_watch = __esm({
25484
25612
  });
25485
25613
 
25486
25614
  // src/kanban.ts
25487
- import fs85 from "node:fs";
25615
+ import fs86 from "node:fs";
25488
25616
  import { fileURLToPath as fileURLToPath3 } from "node:url";
25489
25617
 
25490
25618
  // src/lib/cli/agent.ts
@@ -25973,8 +26101,8 @@ async function testAgent(args) {
25973
26101
  }
25974
26102
 
25975
26103
  // src/commands/cloud.ts
25976
- import fs70 from "node:fs";
25977
- import path72 from "node:path";
26104
+ import fs71 from "node:fs";
26105
+ import path74 from "node:path";
25978
26106
 
25979
26107
  // src/lib/cloud/avatar.ts
25980
26108
  init_session();
@@ -26022,13 +26150,13 @@ init_config();
26022
26150
  init_home();
26023
26151
  init_config();
26024
26152
  init_session();
26025
- import fs69 from "node:fs";
26026
- import path71 from "node:path";
26153
+ import fs70 from "node:fs";
26154
+ import path73 from "node:path";
26027
26155
  var FRESH_MS = 10 * 6e4;
26028
26156
  var GRACE_MS = 7 * 24 * 60 * 6e4;
26029
- var heldFile = () => path71.join(machineHome(), "pro.json");
26157
+ var heldFile = () => path73.join(machineHome(), "pro.json");
26030
26158
  function forgetPro() {
26031
- fs69.rmSync(heldFile(), { force: true });
26159
+ fs70.rmSync(heldFile(), { force: true });
26032
26160
  }
26033
26161
 
26034
26162
  // src/lib/cloud/account.ts
@@ -26205,10 +26333,10 @@ async function cloudImage(opts, program2) {
26205
26333
  const prompt = opts.prompt.trim();
26206
26334
  if (!prompt) usage("Missing the prompt.", line);
26207
26335
  const references = opts.refs.map((file) => {
26208
- const type = REF_TYPES[path72.extname(file).toLowerCase()];
26336
+ const type = REF_TYPES[path74.extname(file).toLowerCase()];
26209
26337
  if (!type) usage(`--ref ${file}: use a PNG, JPEG or WebP file.`, line);
26210
26338
  try {
26211
- return `data:${type};base64,${fs70.readFileSync(file).toString("base64")}`;
26339
+ return `data:${type};base64,${fs71.readFileSync(file).toString("base64")}`;
26212
26340
  } catch (e) {
26213
26341
  usage(`--ref ${file}: ${e instanceof Error ? e.message : String(e)}`, line);
26214
26342
  }
@@ -26314,31 +26442,31 @@ async function generate(g) {
26314
26442
  refuse(g.failed, g.fallback);
26315
26443
  }
26316
26444
  const out = g.outFor?.(res, g.out) ?? g.out;
26317
- fs70.mkdirSync(path72.dirname(path72.resolve(out)), { recursive: true });
26318
- fs70.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
26445
+ fs71.mkdirSync(path74.dirname(path74.resolve(out)), { recursive: true });
26446
+ fs71.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
26319
26447
  say(`${out} (${g.label(res)})`);
26320
26448
  return { out };
26321
26449
  }
26322
26450
 
26323
26451
  // src/commands/cloud-import.ts
26324
26452
  import crypto5 from "node:crypto";
26325
- import fs72 from "node:fs";
26326
- import path74 from "node:path";
26453
+ import fs73 from "node:fs";
26454
+ import path76 from "node:path";
26327
26455
 
26328
26456
  // ../cloud/src/board-files.ts
26329
26457
  var ROOTS = ["todo/", ".archive/", "memory/", "workflows/", "triage/", "assets/", "rules/"];
26330
26458
  var SETTINGS = ["modules.md", "config.md"];
26331
- var isSettingsPath = (path86) => SETTINGS.includes(path86) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path86);
26459
+ var isSettingsPath = (path88) => SETTINGS.includes(path88) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path88);
26332
26460
  var BOARD_FILE_LIMIT = 256 * 1024;
26333
- function isBoardPath(path86) {
26334
- if (!path86 || path86.length > 500 || path86.startsWith("/") || path86.includes("\\") || path86.includes("\0")) return false;
26335
- if (path86.split("/").some((part) => !part || part === "." || part === "..")) return false;
26336
- if (path86 === "todo/README.md" || path86.split("/").includes(".sync")) return false;
26337
- if (path86.startsWith("workflows/")) return true;
26338
- if (SETTINGS.includes(path86)) return true;
26339
- if (path86.startsWith("rules/")) return isSettingsPath(path86);
26340
- if (path86.startsWith("assets/")) return path86.endsWith(".json");
26341
- return ROOTS.some((root) => path86.startsWith(root)) && path86.endsWith(".md");
26461
+ function isBoardPath(path88) {
26462
+ if (!path88 || path88.length > 500 || path88.startsWith("/") || path88.includes("\\") || path88.includes("\0")) return false;
26463
+ if (path88.split("/").some((part) => !part || part === "." || part === "..")) return false;
26464
+ if (path88 === "todo/README.md" || path88.split("/").includes(".sync")) return false;
26465
+ if (path88.startsWith("workflows/")) return true;
26466
+ if (SETTINGS.includes(path88)) return true;
26467
+ if (path88.startsWith("rules/")) return isSettingsPath(path88);
26468
+ if (path88.startsWith("assets/")) return path88.endsWith(".json");
26469
+ return ROOTS.some((root) => path88.startsWith(root)) && path88.endsWith(".md");
26342
26470
  }
26343
26471
  var workflowFolder = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
26344
26472
 
@@ -26442,8 +26570,8 @@ init_bundled();
26442
26570
  // src/lib/agents/shared-memory.ts
26443
26571
  init_bundled();
26444
26572
  init_parse();
26445
- import fs71 from "node:fs";
26446
- import path73 from "node:path";
26573
+ import fs72 from "node:fs";
26574
+ import path75 from "node:path";
26447
26575
  function sharedMemory(board2) {
26448
26576
  const declared = /* @__PURE__ */ new Map();
26449
26577
  const take = (folder, text5, builtIn) => {
@@ -26455,16 +26583,16 @@ function sharedMemory(board2) {
26455
26583
  const at = /^([^/]+)\/AGENT\.md$/.exec(key);
26456
26584
  if (at) take(at[1], text5, true);
26457
26585
  }
26458
- const root = path73.join(board2, "agents");
26586
+ const root = path75.join(board2, "agents");
26459
26587
  let folders2 = [];
26460
26588
  try {
26461
- folders2 = fs71.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
26589
+ folders2 = fs72.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
26462
26590
  } catch {
26463
26591
  }
26464
26592
  for (const folder of folders2.sort()) {
26465
26593
  let text5 = null;
26466
26594
  try {
26467
- text5 = fs71.readFileSync(path73.join(root, folder, "AGENT.md"), "utf8");
26595
+ text5 = fs72.readFileSync(path75.join(root, folder, "AGENT.md"), "utf8");
26468
26596
  } catch {
26469
26597
  }
26470
26598
  take(folder, text5, false);
@@ -26553,24 +26681,24 @@ async function findProject(asked) {
26553
26681
  }
26554
26682
  throw new Refused(`No project of yours has the id or prefix "${asked}".`, "not_found");
26555
26683
  }
26556
- var read = (file) => fs72.readFileSync(file, "utf8");
26684
+ var read = (file) => fs73.readFileSync(file, "utf8");
26557
26685
  var bytes2 = (text5) => Buffer.byteLength(text5, "utf8");
26558
26686
  function files(dir) {
26559
- if (!fs72.existsSync(dir)) return [];
26687
+ if (!fs73.existsSync(dir)) return [];
26560
26688
  const out = [];
26561
- for (const entry of fs72.readdirSync(dir, { withFileTypes: true })) {
26689
+ for (const entry of fs73.readdirSync(dir, { withFileTypes: true })) {
26562
26690
  if (entry.name.startsWith(".")) continue;
26563
- const full = path74.join(dir, entry.name);
26691
+ const full = path76.join(dir, entry.name);
26564
26692
  if (entry.isDirectory()) out.push(...files(full));
26565
26693
  else if (entry.isFile()) out.push(full);
26566
26694
  }
26567
26695
  return out;
26568
26696
  }
26569
- var posix2 = (p) => p.split(path74.sep).join("/");
26697
+ var posix2 = (p) => p.split(path76.sep).join("/");
26570
26698
  function openCards() {
26571
26699
  const out = [];
26572
26700
  for (const file of walkMd(TODO)) {
26573
- const rel2 = posix2(path74.relative(TODO, file));
26701
+ const rel2 = posix2(path76.relative(TODO, file));
26574
26702
  if (rel2 === "README.md") continue;
26575
26703
  const parts = rel2.split("/");
26576
26704
  const text5 = read(file);
@@ -26604,14 +26732,14 @@ function bodyProblems(text5) {
26604
26732
  return out;
26605
26733
  }
26606
26734
  function packWorkflow(flow) {
26607
- const own = path74.join(WORKFLOWS, flow.id);
26735
+ const own = path76.join(WORKFLOWS, flow.id);
26608
26736
  const out = {};
26609
- for (const file of files(own)) out[posix2(path74.relative(own, file))] = read(file);
26737
+ for (const file of files(own)) out[posix2(path76.relative(own, file))] = read(file);
26610
26738
  const named2 = [...flow.previews, ...flow.land, ...flow.scheduled].map((h) => h.agent).filter((a) => !LAND_ROLES.includes(a));
26611
26739
  for (const agent of new Set(named2)) {
26612
- const dir = path74.join(AGENTS, agent);
26613
- if (fs72.existsSync(path74.join(dir, "AGENT.md"))) {
26614
- for (const file of files(dir)) out[`agents/${agent}/${posix2(path74.relative(dir, file))}`] = read(file);
26740
+ const dir = path76.join(AGENTS, agent);
26741
+ if (fs73.existsSync(path76.join(dir, "AGENT.md"))) {
26742
+ for (const file of files(dir)) out[`agents/${agent}/${posix2(path76.relative(dir, file))}`] = read(file);
26615
26743
  continue;
26616
26744
  }
26617
26745
  for (const [key, text5] of Object.entries(BUNDLED_AGENT_FILES)) {
@@ -26663,8 +26791,8 @@ function draftsOf(text5) {
26663
26791
  const at = /^\.(assets|mockups)\/(.+)$/.exec(name);
26664
26792
  if (!at) continue;
26665
26793
  const base = at[1] === "assets" ? ASSETS : MOCKUPS;
26666
- const file = path74.resolve(base, at[2]);
26667
- if (file.startsWith(base + path74.sep) && fs72.statSync(file, { throwIfNoEntry: false })?.isFile()) out.set(name, file);
26794
+ const file = path76.resolve(base, at[2]);
26795
+ if (file.startsWith(base + path76.sep) && fs73.statSync(file, { throwIfNoEntry: false })?.isFile()) out.set(name, file);
26668
26796
  }
26669
26797
  return [...out].map(([name, file]) => ({ name, file }));
26670
26798
  }
@@ -26698,9 +26826,9 @@ async function uploadDrafts(task, drafts) {
26698
26826
  const assets = {};
26699
26827
  for (const { name, file } of drafts) {
26700
26828
  if (!card.body.includes(name)) continue;
26701
- const ext = path74.extname(file).toLowerCase();
26829
+ const ext = path76.extname(file).toLowerCase();
26702
26830
  const type = TYPES[ext] ?? "application/octet-stream";
26703
- const data = fs72.readFileSync(file);
26831
+ const data = fs73.readFileSync(file);
26704
26832
  const artifact = await api("POST", `/v1/tasks/${task}/artifacts`, { type: kindOf(ext), name: name.slice(0, 200) });
26705
26833
  const upload = await api("POST", `/v1/artifacts/${artifact.id}/uploads`, { content_type: type, size: Math.max(data.length, 1) });
26706
26834
  await api("PUT", `/v1/uploads/${upload.id}`, void 0, { bytes: data, type });
@@ -26743,10 +26871,10 @@ usage: ${program2} cloud import --project <id or prefix> [--dry-run]`, { kind: "
26743
26871
  async function run(asked, dryRun) {
26744
26872
  const project = await findProject(asked);
26745
26873
  const cloudFlows = await all(`/v1/workflows?workspace=${encodeURIComponent(project.workspace)}`);
26746
- const board2 = crypto5.createHash("sha256").update(fs72.realpathSync(KANBAN)).digest("hex").slice(0, 16);
26874
+ const board2 = crypto5.createHash("sha256").update(fs73.realpathSync(KANBAN)).digest("hex").slice(0, 16);
26747
26875
  const cards = openCards();
26748
26876
  const problems = [];
26749
- const where = (file) => posix2(path74.relative(KANBAN, file));
26877
+ const where = (file) => posix2(path76.relative(KANBAN, file));
26750
26878
  const own = workflows().filter((w) => !w.builtIn);
26751
26879
  const packed = /* @__PURE__ */ new Map();
26752
26880
  for (const flow of own) {
@@ -26773,7 +26901,7 @@ async function run(asked, dryRun) {
26773
26901
  const root = `projects/${project.id}/`;
26774
26902
  const boardFiles = [];
26775
26903
  for (const file of [...files(MEMORY), ...files(RULES), CONFIG, MODULES_MD]) {
26776
- if (!fs72.existsSync(file)) continue;
26904
+ if (!fs73.existsSync(file)) continue;
26777
26905
  const rel2 = where(file);
26778
26906
  if (!isBoardPath(rel2)) continue;
26779
26907
  const content = read(file);
@@ -26884,16 +27012,16 @@ async function run(asked, dryRun) {
26884
27012
  }
26885
27013
  function leftLocal(own) {
26886
27014
  const out = [];
26887
- const count4 = (dir) => fs72.existsSync(dir) ? walkMd(dir).length : 0;
27015
+ const count4 = (dir) => fs73.existsSync(dir) ? walkMd(dir).length : 0;
26888
27016
  const archived = count4(ARCHIVE);
26889
27017
  if (archived) out.push(`.archive/ (${archived})`);
26890
27018
  const triage = count4(TRIAGE);
26891
27019
  if (triage) out.push(`triage/ (${triage})`);
26892
- if (fs72.existsSync(DELIVERIES)) out.push("deliveries/");
26893
- if (fs72.existsSync(path74.join(KANBAN, "metrics.csv"))) out.push("metrics.csv");
27020
+ if (fs73.existsSync(DELIVERIES)) out.push("deliveries/");
27021
+ if (fs73.existsSync(path76.join(KANBAN, "metrics.csv"))) out.push("metrics.csv");
26894
27022
  const named2 = new Set(own.flatMap((w) => [...w.previews, ...w.land, ...w.scheduled].map((h) => h.agent)));
26895
- if (fs72.existsSync(AGENTS)) {
26896
- for (const e of fs72.readdirSync(AGENTS, { withFileTypes: true })) {
27023
+ if (fs73.existsSync(AGENTS)) {
27024
+ for (const e of fs73.readdirSync(AGENTS, { withFileTypes: true })) {
26897
27025
  if (e.isDirectory() && !e.name.startsWith(".") && !named2.has(e.name)) out.push(`agents/${e.name}/`);
26898
27026
  }
26899
27027
  }
@@ -26911,8 +27039,8 @@ init_session();
26911
27039
  init_io();
26912
27040
  init_paths();
26913
27041
  import { createHash as createHash5 } from "node:crypto";
26914
- import fs73 from "node:fs";
26915
- import path75 from "node:path";
27042
+ import fs74 from "node:fs";
27043
+ import path77 from "node:path";
26916
27044
  var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
26917
27045
  var CAPTURED = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;
26918
27046
  var MAX_BYTES3 = 50 * 1024 * 1024;
@@ -27011,10 +27139,10 @@ This template has no preview.`);
27011
27139
  const written = [];
27012
27140
  for (const p of previews) {
27013
27141
  const bytes3 = Buffer.from(await (await ask(`/${at}/previews/${route(p.path)}`, {}, WITHOUT)).arrayBuffer());
27014
- const file = path75.basename(p.path);
27015
- const out = path75.join(opts.to, file.startsWith(`${name}-`) ? file : `${name}-${file}`);
27016
- fs73.mkdirSync(opts.to, { recursive: true });
27017
- fs73.writeFileSync(out, bytes3);
27142
+ const file = path77.basename(p.path);
27143
+ const out = path77.join(opts.to, file.startsWith(`${name}-`) ? file : `${name}-${file}`);
27144
+ fs74.mkdirSync(opts.to, { recursive: true });
27145
+ fs74.writeFileSync(out, bytes3);
27018
27146
  written.push(out);
27019
27147
  say(out);
27020
27148
  }
@@ -27027,15 +27155,15 @@ async function templateGet(name, opts, program2) {
27027
27155
  const { template } = await asJson(await ask(`/${at}`, {}, WITHOUT));
27028
27156
  const fetched = [];
27029
27157
  for (const f of template.files) {
27030
- const out = path75.resolve(to, f.path);
27031
- if (!out.startsWith(path75.resolve(to) + path75.sep)) refuse2(T.corrupt, WITHOUT);
27158
+ const out = path77.resolve(to, f.path);
27159
+ if (!out.startsWith(path77.resolve(to) + path77.sep)) refuse2(T.corrupt, WITHOUT);
27032
27160
  const bytes3 = Buffer.from(await (await ask(`/${at}/files/${route(f.path)}`, {}, WITHOUT)).arrayBuffer());
27033
27161
  if (bytes3.byteLength !== f.size || createHash5("sha256").update(bytes3).digest("hex") !== f.sha256) {
27034
27162
  refuse2(T.corrupt, WITHOUT);
27035
27163
  }
27036
27164
  fetched.push({ out, bytes: bytes3 });
27037
27165
  }
27038
- const taken = fetched.filter((f) => fs73.existsSync(f.out)).map((f) => path75.relative(to, f.out));
27166
+ const taken = fetched.filter((f) => fs74.existsSync(f.out)).map((f) => path77.relative(to, f.out));
27039
27167
  if (taken.length > 0) {
27040
27168
  refuse2({
27041
27169
  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`,
@@ -27043,8 +27171,8 @@ async function templateGet(name, opts, program2) {
27043
27171
  });
27044
27172
  }
27045
27173
  for (const f of fetched) {
27046
- fs73.mkdirSync(path75.dirname(f.out), { recursive: true });
27047
- fs73.writeFileSync(f.out, f.bytes);
27174
+ fs74.mkdirSync(path77.dirname(f.out), { recursive: true });
27175
+ fs74.writeFileSync(f.out, f.bytes);
27048
27176
  }
27049
27177
  say(`\u5DF2\u53D6\u56DE ${name}\uFF1A${fetched.length} \u4E2A\u6587\u4EF6\uFF0C\u4F4D\u4E8E ${to}
27050
27178
  Fetched ${name}: ${fetched.length} files into ${to}`);
@@ -27062,25 +27190,25 @@ async function templateSource(name, opts) {
27062
27190
  say(`evidence: ${e.path}`);
27063
27191
  continue;
27064
27192
  }
27065
- const out = path75.join(opts.to, `${name}-${path75.basename(e.path)}`);
27066
- fs73.mkdirSync(opts.to, { recursive: true });
27067
- fs73.writeFileSync(out, Buffer.from(await (await ask(`/${at}/evidence/${route(e.path)}`)).arrayBuffer()));
27193
+ const out = path77.join(opts.to, `${name}-${path77.basename(e.path)}`);
27194
+ fs74.mkdirSync(opts.to, { recursive: true });
27195
+ fs74.writeFileSync(out, Buffer.from(await (await ask(`/${at}/evidence/${route(e.path)}`)).arrayBuffer()));
27068
27196
  written.push(out);
27069
27197
  say(out);
27070
27198
  }
27071
27199
  return { name, source, evidence: written.length > 0 ? written : evidence.map((e) => e.path) };
27072
27200
  }
27073
27201
  async function templatePublish(dir, opts) {
27074
- const root = path75.resolve(dir);
27075
- const manifest = path75.join(root, "template.md");
27076
- 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.");
27077
- const meta = readTemplateMeta(fs73.readFileSync(manifest, "utf8"));
27202
+ const root = path77.resolve(dir);
27203
+ const manifest = path77.join(root, "template.md");
27204
+ if (!fs74.existsSync(manifest)) invalid("\u6587\u4EF6\u5939\u9876\u5C42\u7F3A\u5C11 template.md\u3002", "template.md is missing from the folder\u2019s top level.");
27205
+ const meta = readTemplateMeta(fs74.readFileSync(manifest, "utf8"));
27078
27206
  const files2 = walk2(root);
27079
- const total = files2.reduce((sum, f) => sum + fs73.statSync(path75.join(root, f)).size, 0);
27207
+ const total = files2.reduce((sum, f) => sum + fs74.statSync(path77.join(root, f)).size, 0);
27080
27208
  if (total > MAX_BYTES3) invalid("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
27081
27209
  for (const extra of [...opts.preview, ...opts.evidence]) {
27082
- if (!fs73.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
27083
- if (path75.resolve(extra).startsWith(root + path75.sep)) {
27210
+ if (!fs74.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
27211
+ if (path77.resolve(extra).startsWith(root + path77.sep)) {
27084
27212
  invalid(
27085
27213
  `${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`,
27086
27214
  `${extra} is inside the template folder; keep previews and evidence outside it.`
@@ -27092,10 +27220,10 @@ async function templatePublish(dir, opts) {
27092
27220
  }
27093
27221
  const form = new FormData();
27094
27222
  form.set("meta", JSON.stringify({ ...meta, replace: !!opts.replace }));
27095
- const add = (kind, name, file) => form.append(`${kind}:${name}`, new Blob([fs73.readFileSync(file)]), path75.basename(name));
27096
- for (const f of files2) add("files", f, path75.join(root, f));
27097
- for (const f of opts.preview) add("previews", path75.basename(f), f);
27098
- for (const f of opts.evidence) add("evidence", path75.basename(f), f);
27223
+ const add = (kind, name, file) => form.append(`${kind}:${name}`, new Blob([fs74.readFileSync(file)]), path77.basename(name));
27224
+ for (const f of files2) add("files", f, path77.join(root, f));
27225
+ for (const f of opts.preview) add("previews", path77.basename(f), f);
27226
+ for (const f of opts.evidence) add("evidence", path77.basename(f), f);
27099
27227
  const done2 = await asJson(await ask("", { method: "POST", body: form }));
27100
27228
  say(
27101
27229
  done2.replaced ? `\u5DF2\u66FF\u6362 ${done2.name}\uFF1A${files2.length} \u4E2A\u6587\u4EF6\u3002
@@ -27111,11 +27239,11 @@ Deleted ${name} from the catalog.`);
27111
27239
  return { name, deleted: true };
27112
27240
  }
27113
27241
  async function templateShowcase(name, dir) {
27114
- const file = path75.join(dir, "showcase.json");
27115
- if (!fs73.existsSync(file)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
27242
+ const file = path77.join(dir, "showcase.json");
27243
+ if (!fs74.existsSync(file)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
27116
27244
  let meta;
27117
27245
  try {
27118
- meta = JSON.parse(fs73.readFileSync(file, "utf8"));
27246
+ meta = JSON.parse(fs74.readFileSync(file, "utf8"));
27119
27247
  } catch {
27120
27248
  return invalid("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
27121
27249
  }
@@ -27127,9 +27255,9 @@ async function templateShowcase(name, dir) {
27127
27255
  const form = new FormData();
27128
27256
  form.set("meta", JSON.stringify(meta));
27129
27257
  for (const p of new Set(named2)) {
27130
- const at = path75.join(dir, p);
27131
- if (!fs73.existsSync(at)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
27132
- form.append(`media:${p}`, new Blob([fs73.readFileSync(at)]), p);
27258
+ const at = path77.join(dir, p);
27259
+ if (!fs74.existsSync(at)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
27260
+ form.append(`media:${p}`, new Blob([fs74.readFileSync(at)]), p);
27133
27261
  }
27134
27262
  const done2 = await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form }));
27135
27263
  say(`\u5DF2\u66F4\u65B0 ${name} \u7684\u5C55\u793A\u8D44\u6599\uFF1A${done2.files} \u4E2A\u6587\u4EF6\u3002
@@ -27138,7 +27266,7 @@ Updated ${name}'s showcase: ${done2.files} files.`);
27138
27266
  }
27139
27267
  function walk2(root, sub = "") {
27140
27268
  const out = [];
27141
- for (const entry of fs73.readdirSync(path75.join(root, sub), { withFileTypes: true })) {
27269
+ for (const entry of fs74.readdirSync(path77.join(root, sub), { withFileTypes: true })) {
27142
27270
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
27143
27271
  const rel2 = sub ? `${sub}/${entry.name}` : entry.name;
27144
27272
  if (entry.isDirectory()) out.push(...walk2(root, rel2));
@@ -27423,7 +27551,7 @@ init_opencode();
27423
27551
  init_locate();
27424
27552
  init_store();
27425
27553
  import { spawnSync as spawnSync5 } from "node:child_process";
27426
- import path81 from "node:path";
27554
+ import path83 from "node:path";
27427
27555
  var AGENTS2 = {
27428
27556
  claude: "claude-code",
27429
27557
  codex: "codex",
@@ -27438,10 +27566,10 @@ var AGENTS2 = {
27438
27566
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun", "deno"]);
27439
27567
  function agentOf2(args) {
27440
27568
  const words = args.trim().split(/\s+/);
27441
- const first = path81.basename(words[0] ?? "");
27569
+ const first = path83.basename(words[0] ?? "");
27442
27570
  const script = RUNTIMES.has(first) ? words[1] ?? "" : words[0] ?? "";
27443
27571
  if (script.includes("/@anthropic-ai/claude-code/")) return "claude-code";
27444
- return AGENTS2[path81.basename(script).replace(/\.(m?js|cjs|exe)$/, "")];
27572
+ return AGENTS2[path83.basename(script).replace(/\.(m?js|cjs|exe)$/, "")];
27445
27573
  }
27446
27574
  function processChain() {
27447
27575
  if (process.platform === "win32") return [];
@@ -27505,8 +27633,8 @@ init_tasks();
27505
27633
  init_read();
27506
27634
  init_rules();
27507
27635
  init_board();
27508
- import fs80 from "node:fs";
27509
- import path82 from "node:path";
27636
+ import fs81 from "node:fs";
27637
+ import path84 from "node:path";
27510
27638
  var FOLLOW_MS = 400;
27511
27639
  async function cmdStartRun(action, args, opts, program2 = "akb") {
27512
27640
  const { req, follow: follow2, print } = readRequest(action, args, opts);
@@ -27706,13 +27834,13 @@ function readRequest(action, args, opts) {
27706
27834
  return { req, follow: follow2, print };
27707
27835
  }
27708
27836
  async function cmdResume(id, opts) {
27709
- const opened = await startResume(id ?? "last");
27837
+ const opened = await startResume(id ?? "last", opts.requireSession);
27710
27838
  if ("error" in opened) die(opened.error, { kind: "run-refused" });
27711
27839
  const { run: run2 } = opened;
27712
27840
  if (!opened.spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
27713
27841
  const within = run2.deliveryId ? ` in delivery ${run2.deliveryId}` : "";
27714
27842
  say(run2.resumedFrom ? `continuing ${short(run2.resumedFrom)} \u2014 run ${run2.sessionId}${within}` : `trying again \u2014 run ${run2.sessionId}${within}`);
27715
- if (opts.follow === true) return await followStarted(run2.sessionId, "akb");
27843
+ if (opts.follow === true) return await followStarted(run2.sessionId, "akb", opts.events === true);
27716
27844
  return { sessionId: run2.sessionId, resumedFrom: run2.resumedFrom };
27717
27845
  }
27718
27846
  async function cmdCancel(named2) {
@@ -27726,7 +27854,10 @@ async function cmdCancel(named2) {
27726
27854
  }
27727
27855
  async function cmdResumeDelivery(named2) {
27728
27856
  const res = await resumeBoardDelivery(named2);
27729
- if (!res.ok) die(res.error ?? "that delivery could not be carried on", { kind: "run-refused" });
27857
+ if (!res.ok) die(res.error ?? "that delivery could not be carried on", {
27858
+ kind: "run-refused",
27859
+ ...res.kind === "refused" ? { reason: res.reason, args: res.args } : {}
27860
+ });
27730
27861
  if (res.landed) {
27731
27862
  say(`delivery ${res.deliveryId} is done \u2014 its changes were already on the target branch.`);
27732
27863
  return { deliveryId: res.deliveryId, landed: true };
@@ -27803,7 +27934,7 @@ async function cmdSubStart(words, opts) {
27803
27934
  let prompt = words.join(" ");
27804
27935
  if (opts.file) {
27805
27936
  try {
27806
- prompt = fs80.readFileSync(path82.resolve(opts.file), "utf8");
27937
+ prompt = fs81.readFileSync(path84.resolve(opts.file), "utf8");
27807
27938
  } catch {
27808
27939
  die(`--file: cannot read ${opts.file}`, { kind: "run-refused" });
27809
27940
  }
@@ -27917,7 +28048,7 @@ async function followRun(sessionId, already = "", program2 = "akb", events = fal
27917
28048
  last = await followOne(current, printed, events);
27918
28049
  seen.add(current.sessionId);
27919
28050
  printed = 0;
27920
- const deliveryId2 = last.deliveryId ?? first.deliveryId;
28051
+ const deliveryId2 = first.deliveryId ?? last.deliveryId;
27921
28052
  const next = nextInFlow(first, current.sessionId, seen) ?? (deliveryId2 ? await moveDelivery(deliveryId2, idle) : void 0);
27922
28053
  if (next === void 0) break;
27923
28054
  if (next === null) {
@@ -27938,7 +28069,7 @@ async function followRun(sessionId, already = "", program2 = "akb", events = fal
27938
28069
  }
27939
28070
  say("");
27940
28071
  say(runLine(last, program2));
27941
- const deliveryId = last.deliveryId ?? first.deliveryId;
28072
+ const deliveryId = first.deliveryId ?? last.deliveryId;
27942
28073
  const delivery = deliveryId ? deliveryOutcome(deliveryId) : void 0;
27943
28074
  if (delivery) say(`delivery ${delivery.id}: ${delivery.line}`);
27944
28075
  const failed = last.status !== "done" ? `run ${short(last.sessionId)} ended ${last.status}${last.error ? `: ${last.error}` : ""}` : delivery && delivery.status !== "finished" ? `delivery ${delivery.id} did not land${idle.timedOut ? ` \u2014 nothing moved it for ${ago(follow.idleMs)}` : ""}: ${delivery.line}` : void 0;
@@ -28004,7 +28135,7 @@ async function followOne(view, already, events) {
28004
28135
  }
28005
28136
  function nextInFlow(first, after2, seen) {
28006
28137
  const runs = readRuns();
28007
- const next = runs.filter((r) => !seen.has(r.sessionId) && r.action !== "sub" && r.startedAt >= first.startedAt).filter((r) => r.resumedFrom === after2 || !!first.flowId && r.flowId === first.flowId).sort((a, b) => a.startedAt - b.startedAt)[0];
28138
+ const next = runs.filter((r) => !seen.has(r.sessionId) && r.action !== "sub" && r.startedAt >= first.startedAt).filter((r) => !first.deliveryId || !r.deliveryId || r.deliveryId === first.deliveryId).filter((r) => r.resumedFrom === after2 || !!first.flowId && r.flowId === first.flowId).sort((a, b) => a.startedAt - b.startedAt)[0];
28008
28139
  return next ? { ...next } : void 0;
28009
28140
  }
28010
28141
  async function moveDelivery(deliveryId, idle) {
@@ -28024,7 +28155,7 @@ async function moveDelivery(deliveryId, idle) {
28024
28155
  const ask2 = await advanceLanding();
28025
28156
  if (!ask2) return null;
28026
28157
  const started = await startRun(ask2);
28027
- return "error" in started ? null : { ...started.run };
28158
+ return "error" in started || started.run.deliveryId !== deliveryId ? null : { ...started.run };
28028
28159
  }
28029
28160
  function deliveryOutcome(deliveryId) {
28030
28161
  const delivery = findDelivery(deliveryId);
@@ -28094,7 +28225,7 @@ async function cmdWatch(sessionId) {
28094
28225
  // src/commands/triage.ts
28095
28226
  init_scheduled();
28096
28227
  init_workflows();
28097
- import fs82 from "node:fs";
28228
+ import fs83 from "node:fs";
28098
28229
 
28099
28230
  // src/lib/signals/index.ts
28100
28231
  init_cards();
@@ -28104,16 +28235,16 @@ init_yaml();
28104
28235
  // src/lib/signals/config.ts
28105
28236
  init_settings2();
28106
28237
  init_paths();
28107
- import fs81 from "node:fs";
28108
- import path83 from "node:path";
28238
+ import fs82 from "node:fs";
28239
+ import path85 from "node:path";
28109
28240
  var TOKEN_KEY = "TRIAGE_ENDPOINT_TOKEN";
28110
28241
  var ENDPOINT_SETTING = "Triage endpoint";
28111
28242
  var LINE2 = /^- \*\*Triage endpoint\*\*\s*[—-]\s*(.+)$/m;
28112
- var boardRel3 = (file) => rel(file).split(path83.sep).join("/");
28243
+ var boardRel3 = (file) => rel(file).split(path85.sep).join("/");
28113
28244
  function signalEndpoint() {
28114
28245
  let text5;
28115
28246
  try {
28116
- text5 = fs81.readFileSync(CONFIG, "utf8");
28247
+ text5 = fs82.readFileSync(CONFIG, "utf8");
28117
28248
  } catch {
28118
28249
  return "";
28119
28250
  }
@@ -28289,7 +28420,7 @@ async function cmdTriageAdd(opts) {
28289
28420
  let body = opts.text;
28290
28421
  if (opts.file !== void 0) {
28291
28422
  try {
28292
- body = fs82.readFileSync(opts.file, "utf8");
28423
+ body = fs83.readFileSync(opts.file, "utf8");
28293
28424
  } catch {
28294
28425
  die(`can't read ${opts.file} \u2014 write the item to a file, then pass its path`, { kind: "needs-input" });
28295
28426
  }
@@ -28721,7 +28852,7 @@ function declareRunning(run2, cli) {
28721
28852
  });
28722
28853
  verb("resume").argument("[id]", RUN_ID, String).summary("continue a run that failed, was cut off or was stopped").description(
28723
28854
  "The one command that reaches past the board: it picks the coding agent's own session back up \u2014 the conversation it was having, with everything it had already read \u2014 while the board counts the work as a fresh run. Before resuming a creation with no card, check sign-in, project access and connection. A refusal starts no run and leaves triage unchanged. Keep the triage source and request identity; reuse any task already created in Cloud. Repairing an existing card creates no other task. Example: akb run resume abc12345"
28724
- ).option("-f, --follow", "watch its log instead of returning").action(async function(...vals) {
28855
+ ).option("-f, --follow", "watch its log instead of returning").option("--events", "with --follow: print its structured events, one JSON object per line").option("--require-session", "refuse if the original conversation cannot be resumed").action(async function(...vals) {
28725
28856
  const [id] = positional(vals);
28726
28857
  await onBoard2(this, cli, () => cmdResume(id, this.opts()));
28727
28858
  });
@@ -28853,8 +28984,8 @@ function declareAgent(program2, cli) {
28853
28984
  }
28854
28985
 
28855
28986
  // src/lib/cli/setup.ts
28856
- import fs84 from "node:fs";
28857
- import path85 from "node:path";
28987
+ import fs85 from "node:fs";
28988
+ import path87 from "node:path";
28858
28989
  import { fileURLToPath as fileURLToPath2 } from "node:url";
28859
28990
 
28860
28991
  // src/commands/update.ts
@@ -28868,8 +28999,8 @@ init_paths();
28868
28999
  init_memory();
28869
29000
  init_yaml2();
28870
29001
  init_version();
28871
- import fs83 from "node:fs";
28872
- import path84 from "node:path";
29002
+ import fs84 from "node:fs";
29003
+ import path86 from "node:path";
28873
29004
  import { spawnSync as spawnSync6 } from "node:child_process";
28874
29005
  var NAME = "wildcrane";
28875
29006
  var REPO = "https://github.com/ai4kanban/ai4kanban";
@@ -28891,10 +29022,10 @@ var Report = class {
28891
29022
  for (const line of this.notes) say(` ! ${line}`);
28892
29023
  }
28893
29024
  };
28894
- var read3 = (file) => fs83.existsSync(file) ? fs83.readFileSync(file, "utf8") : null;
29025
+ var read3 = (file) => fs84.existsSync(file) ? fs84.readFileSync(file, "utf8") : null;
28895
29026
  function statOf(p) {
28896
29027
  try {
28897
- return fs83.lstatSync(p);
29028
+ return fs84.lstatSync(p);
28898
29029
  } catch {
28899
29030
  return null;
28900
29031
  }
@@ -28919,10 +29050,10 @@ async function cmdUpdate2(ctx) {
28919
29050
  return { updated: ctx.dir, from, to: SKILL_VERSION };
28920
29051
  }
28921
29052
  async function repairBoard(root, report3, named2) {
28922
- const legacy2 = path84.join(root, "docs", "kanban");
28923
- const kept2 = path84.join(root, ".akb", "kanban");
28924
- const board2 = named2 ?? (fs83.existsSync(legacy2) ? legacy2 : kept2);
28925
- if (!fs83.existsSync(board2)) {
29053
+ const legacy2 = path86.join(root, "docs", "kanban");
29054
+ const kept2 = path86.join(root, ".akb", "kanban");
29055
+ const board2 = named2 ?? (fs84.existsSync(legacy2) ? legacy2 : kept2);
29056
+ if (!fs84.existsSync(board2)) {
28926
29057
  report3.notes.push("\u672A\u627E\u5230\u770B\u677F\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002");
28927
29058
  return false;
28928
29059
  }
@@ -28953,20 +29084,20 @@ function moveRuntimes(root, board2, report3) {
28953
29084
  }
28954
29085
  }
28955
29086
  function moveLegacyMemory(board2, report3) {
28956
- const memory = path84.join(board2, "memory");
29087
+ const memory = path86.join(board2, "memory");
28957
29088
  const moved = [];
28958
29089
  for (const name of MEMORY_FILES) {
28959
- const from = path84.join(board2, name);
29090
+ const from = path86.join(board2, name);
28960
29091
  const st = statOf(from);
28961
29092
  if (!st || !st.isFile()) continue;
28962
- fs83.mkdirSync(memory, { recursive: true });
28963
- const to = path84.join(memory, name);
29093
+ fs84.mkdirSync(memory, { recursive: true });
29094
+ const to = path86.join(memory, name);
28964
29095
  const there = read3(to);
28965
29096
  if (there === null) {
28966
- fs83.renameSync(from, to);
29097
+ fs84.renameSync(from, to);
28967
29098
  moved.push(name);
28968
29099
  } else if (there === read3(from)) {
28969
- fs83.rmSync(from);
29100
+ fs84.rmSync(from);
28970
29101
  moved.push(name);
28971
29102
  } else {
28972
29103
  report3.notes.push(`both docs/kanban/${name} and docs/kanban/memory/${name} exist and differ \u2014 merge them by hand`);
@@ -28975,23 +29106,23 @@ function moveLegacyMemory(board2, report3) {
28975
29106
  if (moved.length) report3.did.push(`moved the memory set into docs/kanban/memory/: ${moved.join(", ")}`);
28976
29107
  }
28977
29108
  function dropRecordFile(board2) {
28978
- const file = path84.join(board2, "record.csv");
28979
- if (!fs83.existsSync(file)) return null;
28980
- fs83.rmSync(file);
29109
+ const file = path86.join(board2, "record.csv");
29110
+ if (!fs84.existsSync(file)) return null;
29111
+ fs84.rmSync(file);
28981
29112
  return "removed docs/kanban/record.csv (the planning scores it fed are gone)";
28982
29113
  }
28983
29114
  function dropModuleGoals(board2, report3) {
28984
- const memory = path84.join(board2, "memory");
28985
- if (!fs83.existsSync(memory)) return;
28986
- const root = read3(path84.join(memory, "goal.md"));
29115
+ const memory = path86.join(board2, "memory");
29116
+ if (!fs84.existsSync(memory)) return;
29117
+ const root = read3(path86.join(memory, "goal.md"));
28987
29118
  let dropped = 0;
28988
- for (const entry of fs83.readdirSync(memory, { withFileTypes: true })) {
29119
+ for (const entry of fs84.readdirSync(memory, { withFileTypes: true })) {
28989
29120
  if (!entry.isDirectory()) continue;
28990
- const file = path84.join(memory, entry.name, "goal.md");
29121
+ const file = path86.join(memory, entry.name, "goal.md");
28991
29122
  const text5 = read3(file);
28992
29123
  if (text5 === null) continue;
28993
29124
  if (text5 === root || text5.includes(UNFILLED) || !goalWords(text5)) {
28994
- fs83.rmSync(file);
29125
+ fs84.rmSync(file);
28995
29126
  dropped++;
28996
29127
  } else {
28997
29128
  report3.notes.push(
@@ -29013,10 +29144,10 @@ var PLAN_LEADS = {
29013
29144
  var GONE_LEADS = ["software-planner", "planner"];
29014
29145
  function planLeads(board2) {
29015
29146
  const leads = { ...PLAN_LEADS };
29016
- const root = path84.join(board2, "workflows");
29017
- for (const entry of fs83.existsSync(root) ? fs83.readdirSync(root, { withFileTypes: true }) : []) {
29147
+ const root = path86.join(board2, "workflows");
29148
+ for (const entry of fs84.existsSync(root) ? fs84.readdirSync(root, { withFileTypes: true }) : []) {
29018
29149
  if (!entry.isDirectory()) continue;
29019
- const meta = splitFrontmatter(read3(path84.join(root, entry.name, "WORKFLOW.md")) ?? "").meta;
29150
+ const meta = splitFrontmatter(read3(path86.join(root, entry.name, "WORKFLOW.md")) ?? "").meta;
29020
29151
  const stages = meta === null ? void 0 : parseYamlBlock(meta).stages;
29021
29152
  const plan = stages && typeof stages === "object" && !Array.isArray(stages) ? stages.plan : void 0;
29022
29153
  const lead = plan && typeof plan === "object" && !Array.isArray(plan) && typeof plan.lead === "string" ? plan.lead.trim() : "";
@@ -29025,30 +29156,30 @@ function planLeads(board2) {
29025
29156
  return leads;
29026
29157
  }
29027
29158
  function movePlanRules(board2, report3) {
29028
- const rules = path84.join(board2, "rules");
29159
+ const rules = path86.join(board2, "rules");
29029
29160
  const moved = [];
29030
29161
  for (const [id, leads] of Object.entries(planLeads(board2))) {
29031
29162
  for (const lead of leads) {
29032
- const from = path84.join(rules, `${lead}.md`);
29163
+ const from = path86.join(rules, `${lead}.md`);
29033
29164
  const rule = read3(from)?.trim();
29034
29165
  if (!rule) continue;
29035
- const to = path84.join(rules, "workflows", `${id}.md`);
29166
+ const to = path86.join(rules, "workflows", `${id}.md`);
29036
29167
  const there = read3(to)?.trim() ?? "";
29037
29168
  if (!there.includes(rule)) {
29038
- fs83.mkdirSync(path84.dirname(to), { recursive: true });
29039
- fs83.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
29169
+ fs84.mkdirSync(path86.dirname(to), { recursive: true });
29170
+ fs84.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
29040
29171
  `);
29041
29172
  moved.push(`${lead} \u2192 ${id}`);
29042
29173
  }
29043
29174
  }
29044
29175
  }
29045
- for (const lead of GONE_LEADS) fs83.rmSync(path84.join(rules, `${lead}.md`), { force: true });
29176
+ for (const lead of GONE_LEADS) fs84.rmSync(path86.join(rules, `${lead}.md`), { force: true });
29046
29177
  if (moved.length) report3.did.push(`made each plan agent's rule its workflow's card rule (docs/kanban/rules/workflows/): ${moved.join(", ")}`);
29047
29178
  }
29048
29179
  function noteOldWorkflows(board2, report3) {
29049
29180
  const old = (dir, file, keys) => {
29050
- const root = path84.join(board2, dir);
29051
- return (fs83.existsSync(root) ? fs83.readdirSync(root, { withFileTypes: true }) : []).filter((e) => e.isDirectory() && keys.test(splitFrontmatter(read3(path84.join(root, e.name, file)) ?? "").meta ?? "")).map((e) => `docs/kanban/${dir}/${e.name}/${file}`);
29181
+ const root = path86.join(board2, dir);
29182
+ return (fs84.existsSync(root) ? fs84.readdirSync(root, { withFileTypes: true }) : []).filter((e) => e.isDirectory() && keys.test(splitFrontmatter(read3(path86.join(root, e.name, file)) ?? "").meta ?? "")).map((e) => `docs/kanban/${dir}/${e.name}/${file}`);
29052
29183
  };
29053
29184
  const files2 = [...old("workflows", "WORKFLOW.md", /^(stages|delivers):/m), ...old("agents", "AGENT.md", /^\s+(hook|lead):/m)];
29054
29185
  if (files2.length) {
@@ -29058,7 +29189,7 @@ function noteOldWorkflows(board2, report3) {
29058
29189
  }
29059
29190
  }
29060
29191
  function checkConfig(board2, report3) {
29061
- const current = read3(path84.join(board2, "config.md"));
29192
+ const current = read3(path86.join(board2, "config.md"));
29062
29193
  if (!current) return;
29063
29194
  const added = missingConfigKeys(current);
29064
29195
  if (added.length) {
@@ -29068,7 +29199,7 @@ function checkConfig(board2, report3) {
29068
29199
  }
29069
29200
  }
29070
29201
  function checkModules(board2, report3) {
29071
- const map2 = read3(path84.join(board2, "modules.md"));
29202
+ const map2 = read3(path86.join(board2, "modules.md"));
29072
29203
  if (map2 && map2.includes(UNFILLED)) {
29073
29204
  report3.notes.push(
29074
29205
  "docs/kanban/modules.md is still blank \u2014 write it from the repo (`akb guide module-map`)"
@@ -29122,14 +29253,14 @@ function declareSetup(program2, cli) {
29122
29253
  program2.version(SKILL_VERSION, "-v, --version", "print this version").addHelpText("beforeAll", spelled(cli.program));
29123
29254
  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");
29124
29255
  const where = (cmd) => {
29125
- const dir = path85.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
29126
- if (!fs84.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
29256
+ const dir = path87.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
29257
+ if (!fs85.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
29127
29258
  return dir;
29128
29259
  };
29129
29260
  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() {
29130
29261
  const dir = where(this);
29131
29262
  const named2 = this.optsWithGlobals().board ?? process.env.AI4KANBAN_BOARD?.trim();
29132
- const board2 = named2 ? path85.resolve(cli.cwd, named2) : null;
29263
+ const board2 = named2 ? path87.resolve(cli.cwd, named2) : null;
29133
29264
  await runAction(ctxOf(this, cli.program), {}, () => cmdUpdate2({ dir, program: cli.program, board: board2 }));
29134
29265
  });
29135
29266
  program2.command("__rules", { hidden: true }).action(function() {
@@ -29173,7 +29304,7 @@ function invokedDirectly() {
29173
29304
  const entry = process.argv[1];
29174
29305
  if (!entry) return false;
29175
29306
  try {
29176
- return fs85.realpathSync(entry) === fs85.realpathSync(SELF2);
29307
+ return fs86.realpathSync(entry) === fs86.realpathSync(SELF2);
29177
29308
  } catch {
29178
29309
  return false;
29179
29310
  }