wildcrane 0.11.15 → 0.11.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/kanban.mjs +1275 -1149
  2. package/package.json +2 -2
package/dist/kanban.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.15 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
2
+ // ai4kanban 0.11.17 — 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,8 +5518,8 @@ var init_package = __esm({
5481
5518
  "package.json"() {
5482
5519
  package_default = {
5483
5520
  name: "wildcrane",
5484
- version: "0.11.15",
5485
- akbContract: 4,
5521
+ version: "0.11.17",
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: [
5488
5525
  "kanban",
@@ -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);
@@ -11648,50 +11706,13 @@ function withSystemLanguage(harness, argv, env2, language) {
11648
11706
  }
11649
11707
  var init_run_settings = __esm({
11650
11708
  "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"() {
11691
- "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;
11709
+ "use strict";
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") {
@@ -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}`);
@@ -18193,7 +18515,7 @@ function actionPrompt(req, command, notes) {
18193
18515
  case "spec": {
18194
18516
  const agent = findSpecAgent(req.specAgent ?? "");
18195
18517
  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}`;
18518
+ const cardFile3 = found2 ? rel(found2.kind === "group" ? path54.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
18197
18519
  const own = agent ? specAgentInstructions(agent) : null;
18198
18520
  if (own) notes.push(...own.notes);
18199
18521
  const memory = agent ? agentMemoryBlock(agent) : "";
@@ -18306,288 +18628,81 @@ ${shared}` : ""
18306
18628
  req.notes ? `Extra notes: ${req.notes}` : "",
18307
18629
  `Don't ask me questions with human-in-the-loop. Leave any questions as open questions.`
18308
18630
  ].filter(Boolean).join(" ");
18309
- case "resolve":
18310
- return [
18311
- `${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
- }
18631
+ case "resolve":
18632
+ return [
18633
+ `${kb}. Apply my answers to the open questions on task ${req.id} ${named2} following \`akb guide resolve\`.`,
18634
+ carriedNote(req),
18635
+ answeredNote(req.id, command),
18636
+ req.notes ? `Extra notes: ${req.notes}` : ""
18637
+ ].filter(Boolean).join(" ");
18538
18638
  }
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
18639
  }
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
- }
18640
+ function discardedCardsPrompt(cards = []) {
18641
+ if (!cards.length) return "";
18642
+ 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
18643
  }
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"() {
18644
+ 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;
18645
+ var init_prompts = __esm({
18646
+ "src/lib/agent/prompts.ts"() {
18567
18647
  "use strict";
18648
+ init_cards();
18649
+ init_memory();
18650
+ init_memories();
18651
+ init_paths();
18652
+ init_agents();
18653
+ init_command();
18654
+ init_deliveries();
18568
18655
  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;
18656
+ init_facts();
18657
+ init_outputs();
18658
+ init_archive();
18659
+ init_flows();
18660
+ init_resolve();
18661
+ init_runner();
18662
+ init_workflows();
18663
+ init_catalog2();
18664
+ init_roles();
18665
+ init_rules2();
18666
+ init_settings2();
18667
+ init_types3();
18668
+ RESUME_PROMPT = [
18669
+ `Continue. The previous run ended before it finished the task.`,
18670
+ `Pick up where you left off and carry it through.`
18671
+ ].join(" ");
18672
+ DELIVERY_RESUME = [
18673
+ `Continue delivery %s. The previous run ended before the delivery finished.`,
18674
+ `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.`
18675
+ ].join(" ");
18676
+ DELIVERY_RESUME_CARD = `Build the card as the delivery holds it, not as the file reads now: \`%c\` prints the approved copy.`;
18677
+ RESTARTABLE = /* @__PURE__ */ new Set([
18678
+ "implement",
18679
+ "clarify",
18680
+ "resolve",
18681
+ "approve",
18682
+ "archive",
18683
+ "spec",
18684
+ "conflict",
18685
+ "scheduled"
18686
+ ]);
18687
+ RESTART_LEAD = [
18688
+ `The session you were continuing is gone, and this one holds nothing of it.`,
18689
+ `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.`
18690
+ ].join(" ");
18691
+ restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
18692
+ NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
18693
+ BOARD_FOLDER = "<board folder>";
18694
+ CARD_FILE = "<card file>";
18695
+ PROJECT_FOLDER = "<project folder>";
18696
+ PLANNING_FOR = /* @__PURE__ */ new Set(["create", "clarify", "resolve", "approve", "edit"]);
18697
+ SPEC_SELECTOR_FOR = /* @__PURE__ */ new Set(["clarify", "resolve", "approve", "edit"]);
18698
+ reflectedCards = (req) => req.cards ?? (req.id !== void 0 ? [req.id] : []);
18584
18699
  }
18585
18700
  });
18586
18701
 
18587
18702
  // src/lib/agent/sessions.ts
18588
18703
  import { randomUUID as randomUUID6 } from "node:crypto";
18589
- import fs48 from "node:fs";
18590
- import path53 from "node:path";
18704
+ import fs49 from "node:fs";
18705
+ import path55 from "node:path";
18591
18706
  function reap(runs, reaped = [], restore = []) {
18592
18707
  let changed = false;
18593
18708
  const now = Date.now();
@@ -18607,7 +18722,7 @@ function reap(runs, reaped = [], restore = []) {
18607
18722
  }
18608
18723
  function stampDuration(run2, endedAt) {
18609
18724
  try {
18610
- fs48.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
18725
+ fs49.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
18611
18726
  } catch {
18612
18727
  }
18613
18728
  }
@@ -18621,7 +18736,7 @@ function cardNow(cardId2) {
18621
18736
  try {
18622
18737
  const file = cardFile(cardId2);
18623
18738
  if (!file) return null;
18624
- const { meta } = parseFrontmatter(fs48.readFileSync(file, "utf8"));
18739
+ const { meta } = parseFrontmatter(fs49.readFileSync(file, "utf8"));
18625
18740
  if (!meta) return null;
18626
18741
  return { status: meta.status || "todo", questions: openOf(meta.questions).length, title: meta.title };
18627
18742
  } catch {
@@ -18758,9 +18873,9 @@ function leftBoardOnLanding(id) {
18758
18873
  function archivedRejected(id) {
18759
18874
  const filed = locateArchived(id);
18760
18875
  if (!filed) return null;
18761
- const file = filed.kind === "group" ? path53.join(filed.target, "root.md") : filed.target;
18876
+ const file = filed.kind === "group" ? path55.join(filed.target, "root.md") : filed.target;
18762
18877
  try {
18763
- return !!parseFrontmatter(fs48.readFileSync(file, "utf8")).meta?.rejected;
18878
+ return !!parseFrontmatter(fs49.readFileSync(file, "utf8")).meta?.rejected;
18764
18879
  } catch {
18765
18880
  return false;
18766
18881
  }
@@ -19017,7 +19132,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said3) {
19017
19132
  return { run: record, spec };
19018
19133
  }
19019
19134
  function planningSession(cardId2, cwd = REPO_ROOT) {
19020
- const here = (dir) => !dir || path53.resolve(dir) === cwd;
19135
+ const here = (dir) => !dir || path55.resolve(dir) === cwd;
19021
19136
  const ended = readRuns().filter((r) => r.status === "done").sort((a, b) => b.startedAt - a.startedAt);
19022
19137
  const of = (run3, fork) => {
19023
19138
  if (!here(run3.cwd)) return { none: "elsewhere" };
@@ -19086,7 +19201,9 @@ function requestOf(record) {
19086
19201
  pictures: record.pictures
19087
19202
  };
19088
19203
  }
19089
- async function openResume(id, build) {
19204
+ async function openResume(id, options) {
19205
+ const build = typeof options === "object" ? options : void 0;
19206
+ const requireSession = options === true || !!build;
19090
19207
  const restore = [];
19091
19208
  const runs = withRuns((all2) => {
19092
19209
  reap(all2, [], restore);
@@ -19111,7 +19228,7 @@ async function openResume(id, build) {
19111
19228
  if (refused) return refused;
19112
19229
  }
19113
19230
  const retrying = lacksSession(prev);
19114
- if (build && (retrying || !resumesUnder(prev.harness))) {
19231
+ if (requireSession && (!resumeSessionId(prev) || !resumesUnder(prev.harness))) {
19115
19232
  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
19233
  }
19117
19234
  const ask2 = retrying && prev.status !== "stopped" ? retryAsk(prev) : void 0;
@@ -19250,8 +19367,8 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
19250
19367
  clearAsks(prev.sessionId);
19251
19368
  try {
19252
19369
  if (prev.action !== "create") {
19253
- fs48.unlinkSync(prev.logPath);
19254
- fs48.rmSync(eventsPathOf(prev.sessionId), { force: true });
19370
+ fs49.unlinkSync(prev.logPath);
19371
+ fs49.rmSync(eventsPathOf(prev.sessionId), { force: true });
19255
19372
  }
19256
19373
  } catch {
19257
19374
  }
@@ -19275,8 +19392,8 @@ function forgetRun(sessionId) {
19275
19392
  if (!gone) return;
19276
19393
  clearAsks(sessionId);
19277
19394
  try {
19278
- fs48.unlinkSync(gone.logPath);
19279
- fs48.rmSync(eventsPathOf(gone.sessionId), { force: true });
19395
+ fs49.unlinkSync(gone.logPath);
19396
+ fs49.rmSync(eventsPathOf(gone.sessionId), { force: true });
19280
19397
  } catch {
19281
19398
  }
19282
19399
  }
@@ -19305,14 +19422,14 @@ function noteSpecRefusals(sessionId, refused) {
19305
19422
  }
19306
19423
  function clearAsks(sessionId) {
19307
19424
  try {
19308
- fs48.unlinkSync(asksPathOf(sessionId));
19425
+ fs49.unlinkSync(asksPathOf(sessionId));
19309
19426
  } catch {
19310
19427
  }
19311
19428
  }
19312
19429
  function readAsks(sessionId) {
19313
19430
  let data;
19314
19431
  try {
19315
- data = JSON.parse(fs48.readFileSync(asksPathOf(sessionId), "utf8"));
19432
+ data = JSON.parse(fs49.readFileSync(asksPathOf(sessionId), "utf8"));
19316
19433
  } catch {
19317
19434
  return { asks: [], refines: [], refused: [] };
19318
19435
  }
@@ -19339,10 +19456,10 @@ function readAsks(sessionId) {
19339
19456
  return { asks: asks.filter((a) => !discarded.has(a.cardId)), refines: refines.filter((a) => !discarded.has(a.cardId)), refused };
19340
19457
  }
19341
19458
  function writeAsks(sessionId, file) {
19342
- fs48.mkdirSync(SESSIONS_DIR, { recursive: true });
19459
+ fs49.mkdirSync(SESSIONS_DIR, { recursive: true });
19343
19460
  const tmp = `${asksPathOf(sessionId)}.tmp`;
19344
- fs48.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
19345
- fs48.renameSync(tmp, asksPathOf(sessionId));
19461
+ fs49.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
19462
+ fs49.renameSync(tmp, asksPathOf(sessionId));
19346
19463
  }
19347
19464
  function markSpawned(sessionId, pid) {
19348
19465
  patch(sessionId, (r) => {
@@ -19430,7 +19547,10 @@ async function cancelDelivery(id) {
19430
19547
  if (!id.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to cancel", { action: "cancel" }) };
19431
19548
  const delivery = namedDelivery(id);
19432
19549
  if (!delivery) return { ok: false, ...unknownDelivery(id) };
19433
- if (delivery.status !== "active") return { ok: true, deliveryId: delivery.deliveryId };
19550
+ if (delivery.status !== "active") {
19551
+ tidyCheckout(delivery.deliveryId);
19552
+ return { ok: true, deliveryId: delivery.deliveryId };
19553
+ }
19434
19554
  endDelivery(delivery.deliveryId, "cancelled");
19435
19555
  const live = readRuns().find((r) => r.status === "running" && r.deliveryId === delivery.deliveryId && r.action !== "sub");
19436
19556
  if (live) await stopRun(live.sessionId);
@@ -19455,7 +19575,9 @@ async function runIsDown(sessionId) {
19455
19575
  }
19456
19576
  async function resumeDelivery(id) {
19457
19577
  if (!id.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to carry on", { action: "resume" }) };
19458
- const put = resumeRecord(id);
19578
+ const execution = executionOf();
19579
+ 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" };
19580
+ const put = resumeRecord(id, execution);
19459
19581
  if (!put.ok) return put;
19460
19582
  const delivery = put.delivery;
19461
19583
  if (await settleAlreadyLanded(delivery)) {
@@ -19496,12 +19618,12 @@ async function discardDelivery(id) {
19496
19618
  return { ok: true, deliveryId: delivery.deliveryId };
19497
19619
  }
19498
19620
  function writeSpec(spec) {
19499
- fs48.mkdirSync(SESSIONS_DIR, { recursive: true });
19500
- fs48.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
19621
+ fs49.mkdirSync(SESSIONS_DIR, { recursive: true });
19622
+ fs49.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
19501
19623
  }
19502
19624
  function readSpec(sessionId) {
19503
19625
  try {
19504
- const spec = JSON.parse(fs48.readFileSync(specPathOf(sessionId), "utf8"));
19626
+ const spec = JSON.parse(fs49.readFileSync(specPathOf(sessionId), "utf8"));
19505
19627
  return spec && Array.isArray(spec.plan?.argv) ? spec : null;
19506
19628
  } catch {
19507
19629
  return null;
@@ -19509,28 +19631,28 @@ function readSpec(sessionId) {
19509
19631
  }
19510
19632
  function dropSpec(sessionId) {
19511
19633
  try {
19512
- fs48.unlinkSync(specPathOf(sessionId));
19634
+ fs49.unlinkSync(specPathOf(sessionId));
19513
19635
  } catch {
19514
19636
  }
19515
19637
  }
19516
19638
  async function acquireIndexLock(giveUp) {
19517
19639
  const until = Date.now() + INDEX_WAIT_MS;
19518
- const holder = path53.join(INDEX_LOCK2, "holder");
19640
+ const holder = path55.join(INDEX_LOCK2, "holder");
19519
19641
  for (; ; ) {
19520
19642
  if (giveUp()) return null;
19521
19643
  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 });
19644
+ fs49.mkdirSync(INDEX_LOCK2, { recursive: false });
19645
+ fs49.writeFileSync(holder, String(process.pid));
19646
+ return () => fs49.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19525
19647
  } catch (err) {
19526
19648
  const code = err.code;
19527
19649
  if (code === "ENOENT") {
19528
- fs48.mkdirSync(path53.dirname(INDEX_LOCK2), { recursive: true });
19650
+ fs49.mkdirSync(path55.dirname(INDEX_LOCK2), { recursive: true });
19529
19651
  continue;
19530
19652
  }
19531
19653
  if (code !== "EEXIST") throw err;
19532
19654
  if (!pidAlive(Number(readHolder(holder)))) {
19533
- fs48.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19655
+ fs49.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19534
19656
  continue;
19535
19657
  }
19536
19658
  if (Date.now() > until) return null;
@@ -19540,7 +19662,7 @@ async function acquireIndexLock(giveUp) {
19540
19662
  }
19541
19663
  function readHolder(file) {
19542
19664
  try {
19543
- return fs48.readFileSync(file, "utf8").trim();
19665
+ return fs49.readFileSync(file, "utf8").trim();
19544
19666
  } catch {
19545
19667
  return String(process.pid);
19546
19668
  }
@@ -19549,6 +19671,7 @@ var INDEX_ACTIONS, SINGLETON_ACTIONS, VERB, SINGLETON_BUSY, RUN_STATUS, specPath
19549
19671
  var init_sessions = __esm({
19550
19672
  "src/lib/agent/sessions.ts"() {
19551
19673
  "use strict";
19674
+ init_execution();
19552
19675
  init_creation();
19553
19676
  init_cards();
19554
19677
  init_frontmatter();
@@ -19631,8 +19754,8 @@ var init_sessions = __esm({
19631
19754
  conflict: "implementing",
19632
19755
  hook: "implementing"
19633
19756
  };
19634
- specPathOf = (sessionId) => path53.join(SESSIONS_DIR, `${sessionId}.plan.json`);
19635
- asksPathOf = (sessionId) => path53.join(SESSIONS_DIR, `${sessionId}.asks.json`);
19757
+ specPathOf = (sessionId) => path55.join(SESSIONS_DIR, `${sessionId}.plan.json`);
19758
+ asksPathOf = (sessionId) => path55.join(SESSIONS_DIR, `${sessionId}.asks.json`);
19636
19759
  carriesSession = (r) => !!(r.resumedFrom || r.continues && !r.continues.fork);
19637
19760
  canPickUp = (r) => (r.status === "error" || r.status === "interrupted" || r.status === "stopped") && !(r.action === "create" && readRuns().some((next) => next.resumedFrom === r.sessionId));
19638
19761
  neverStarted = (r) => r.unspawned === true || !!r.errorWhy?.some((why) => why.kind === "notInstalled");
@@ -19766,8 +19889,8 @@ var init_questions = __esm({
19766
19889
  });
19767
19890
 
19768
19891
  // src/lib/agent/workflow-cards.ts
19769
- import fs49 from "node:fs";
19770
- import path54 from "node:path";
19892
+ import fs50 from "node:fs";
19893
+ import path56 from "node:path";
19771
19894
  function cardsOnWorkflow(id) {
19772
19895
  const wanted = id || DEFAULT_WORKFLOW;
19773
19896
  const ids = [];
@@ -19778,12 +19901,12 @@ function cardsOnWorkflow(id) {
19778
19901
  return [];
19779
19902
  }
19780
19903
  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);
19904
+ const base = path56.basename(file);
19905
+ const card = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file))) : idPrefix(base);
19783
19906
  if (card === null) continue;
19784
19907
  let meta;
19785
19908
  try {
19786
- meta = parseFrontmatter(fs49.readFileSync(file, "utf8")).meta;
19909
+ meta = parseFrontmatter(fs50.readFileSync(file, "utf8")).meta;
19787
19910
  } catch {
19788
19911
  continue;
19789
19912
  }
@@ -19841,12 +19964,12 @@ var init_workflow_cards = __esm({
19841
19964
  });
19842
19965
 
19843
19966
  // src/lib/readme.ts
19844
- import fs50 from "node:fs";
19845
- import path55 from "node:path";
19967
+ import fs51 from "node:fs";
19968
+ import path57 from "node:path";
19846
19969
  function stripReadmeRefs(target) {
19847
- if (!fs50.existsSync(README)) return [];
19970
+ if (!fs51.existsSync(README)) return [];
19848
19971
  const needle = target.kind === "group" ? `](${target.rel}/` : `](${target.rel})`;
19849
- const lines = fs50.readFileSync(README, "utf8").split("\n");
19972
+ const lines = fs51.readFileSync(README, "utf8").split("\n");
19850
19973
  const out = [];
19851
19974
  const removed = [];
19852
19975
  let i = 0;
@@ -19868,20 +19991,20 @@ function stripReadmeRefs(target) {
19868
19991
  out.push(line);
19869
19992
  i++;
19870
19993
  }
19871
- if (removed.length) fs50.writeFileSync(README, out.join("\n"));
19994
+ if (removed.length) fs51.writeFileSync(README, out.join("\n"));
19872
19995
  return removed;
19873
19996
  }
19874
19997
  function addReadmeRef(id, title, relPath) {
19875
- if (!fs50.existsSync(README)) return false;
19876
- const link2 = relPath.split(path55.sep).join("/");
19998
+ if (!fs51.existsSync(README)) return false;
19999
+ const link2 = relPath.split(path57.sep).join("/");
19877
20000
  const bullet = `- [#${id} ${title}](${link2})`;
19878
20001
  const heading = `## ${TASKS_HEADING}`;
19879
- let lines = fs50.readFileSync(README, "utf8").split("\n");
20002
+ let lines = fs51.readFileSync(README, "utf8").split("\n");
19880
20003
  const hi = lines.findIndex((l) => l.trim().toLowerCase() === heading.toLowerCase());
19881
20004
  if (hi === -1) {
19882
20005
  while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
19883
20006
  lines.push("", heading, "", bullet);
19884
- fs50.writeFileSync(README, lines.join("\n") + "\n");
20007
+ fs51.writeFileSync(README, lines.join("\n") + "\n");
19885
20008
  return true;
19886
20009
  }
19887
20010
  let end2 = hi + 1;
@@ -19895,15 +20018,15 @@ function addReadmeRef(id, title, relPath) {
19895
20018
  const at = lastBullet !== -1 ? lastBullet + 1 : lines[hi + 1] === "" ? hi + 2 : hi + 1;
19896
20019
  lines.splice(at, 0, bullet);
19897
20020
  }
19898
- fs50.writeFileSync(README, lines.join("\n"));
20021
+ fs51.writeFileSync(README, lines.join("\n"));
19899
20022
  return true;
19900
20023
  }
19901
20024
  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("/");
20025
+ if (!fs51.existsSync(README)) return false;
20026
+ const oldLink = oldRel.split(path57.sep).join("/");
20027
+ const newLink = newRel.split(path57.sep).join("/");
19905
20028
  const linkRe = new RegExp(`\\[#${id}\\b[^\\]]*\\]\\(${escapeRegex(oldLink)}\\)`);
19906
- const lines = fs50.readFileSync(README, "utf8").split("\n");
20029
+ const lines = fs51.readFileSync(README, "utf8").split("\n");
19907
20030
  let changed = false;
19908
20031
  for (let i = 0; i < lines.length; i++) {
19909
20032
  if (!lines[i].includes(`](${oldLink})`)) continue;
@@ -19913,7 +20036,7 @@ function repointReadmeLink(id, oldRel, newRel, title) {
19913
20036
  changed = true;
19914
20037
  }
19915
20038
  }
19916
- if (changed) fs50.writeFileSync(README, lines.join("\n"));
20039
+ if (changed) fs51.writeFileSync(README, lines.join("\n"));
19917
20040
  return changed;
19918
20041
  }
19919
20042
  var isTableRow, isBulletStart, bulletIndent, TASKS_HEADING, escapeRegex;
@@ -19930,14 +20053,14 @@ var init_readme = __esm({
19930
20053
  });
19931
20054
 
19932
20055
  // src/lib/reconcile.ts
19933
- import fs51 from "node:fs";
19934
- import path56 from "node:path";
20056
+ import fs52 from "node:fs";
20057
+ import path58 from "node:path";
19935
20058
  function liveIds() {
19936
20059
  const ids = /* @__PURE__ */ new Set();
19937
20060
  for (const file of walkMd(TODO)) {
19938
- const base = path56.basename(file);
20061
+ const base = path58.basename(file);
19939
20062
  if (base === "README.md") continue;
19940
- const id = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file))) : idPrefix(base);
20063
+ const id = base === "root.md" ? idPrefix(path58.basename(path58.dirname(file))) : idPrefix(base);
19941
20064
  if (id != null) ids.add(id);
19942
20065
  }
19943
20066
  return ids;
@@ -19945,16 +20068,16 @@ function liveIds() {
19945
20068
  function indexableCards() {
19946
20069
  const out = [];
19947
20070
  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("/") });
20071
+ const id = idPrefix(path58.basename(dir));
20072
+ if (id != null && fs52.existsSync(path58.join(dir, "root.md"))) {
20073
+ out.push({ id, rel: path58.join(path58.relative(TODO, dir), "root.md").split(path58.sep).join("/") });
19951
20074
  }
19952
20075
  }
19953
20076
  for (const file of walkMd(TODO)) {
19954
- const base = path56.basename(file);
20077
+ const base = path58.basename(file);
19955
20078
  if (base === "README.md" || base === "root.md") continue;
19956
- const relTODO = path56.relative(TODO, file);
19957
- const segs = relTODO.split(path56.sep);
20079
+ const relTODO = path58.relative(TODO, file);
20080
+ const segs = relTODO.split(path58.sep);
19958
20081
  if (segs.length !== 1) continue;
19959
20082
  const id = idPrefix(base);
19960
20083
  if (id != null) out.push({ id, rel: segs.join("/") });
@@ -19963,7 +20086,7 @@ function indexableCards() {
19963
20086
  }
19964
20087
  function readmeComplaints(fix) {
19965
20088
  const said3 = [];
19966
- const lines = fs51.readFileSync(README, "utf8").split("\n");
20089
+ const lines = fs52.readFileSync(README, "utf8").split("\n");
19967
20090
  const indexed = /* @__PURE__ */ new Set();
19968
20091
  let fixed = 0;
19969
20092
  for (let i = 0; i < lines.length; i++) {
@@ -19972,13 +20095,13 @@ function readmeComplaints(fix) {
19972
20095
  const id = Number(m[1]);
19973
20096
  const linkPath = m[2];
19974
20097
  indexed.add(id);
19975
- if (fs51.existsSync(path56.join(TODO, linkPath))) continue;
20098
+ if (fs52.existsSync(path58.join(TODO, linkPath))) continue;
19976
20099
  const found2 = locate(id);
19977
20100
  if (!found2) {
19978
20101
  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
20102
  continue;
19980
20103
  }
19981
- const want = (found2.kind === "group" ? path56.join(found2.rel, "root.md") : found2.rel).split(path56.sep).join("/");
20104
+ const want = (found2.kind === "group" ? path58.join(found2.rel, "root.md") : found2.rel).split(path58.sep).join("/");
19982
20105
  if (want === linkPath) continue;
19983
20106
  if (!fix) {
19984
20107
  said3.push(`README links #${id} \u2192 ${linkPath}, which isn't there any more; the card is at ${want}.`);
@@ -19988,7 +20111,7 @@ function readmeComplaints(fix) {
19988
20111
  said3.push(`README link #${id} pointed at missing ${linkPath} \u2192 repointed to ${want}.`);
19989
20112
  fixed++;
19990
20113
  }
19991
- if (fixed) fs51.writeFileSync(README, lines.join("\n"));
20114
+ if (fixed) fs52.writeFileSync(README, lines.join("\n"));
19992
20115
  for (const c of indexableCards()) {
19993
20116
  if (!indexed.has(c.id)) {
19994
20117
  said3.push(`card ${c.rel} (#${c.id}) is not in the README index. Add it under "## ${TASKS_HEADING}".`);
@@ -20000,11 +20123,11 @@ function crossRefComplaints() {
20000
20123
  const said3 = [];
20001
20124
  const live = liveIds();
20002
20125
  for (const file of walkMd(TODO)) {
20003
- const base = path56.basename(file);
20126
+ const base = path58.basename(file);
20004
20127
  if (base === "README.md") continue;
20005
- const ownerId = base === "root.md" ? idPrefix(path56.basename(path56.dirname(file))) : idPrefix(base);
20128
+ const ownerId = base === "root.md" ? idPrefix(path58.basename(path58.dirname(file))) : idPrefix(base);
20006
20129
  if (ownerId == null) continue;
20007
- const { meta } = parseFrontmatter(fs51.readFileSync(file, "utf8"));
20130
+ const { meta } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
20008
20131
  if (!meta) continue;
20009
20132
  for (const field2 of ["blocked_by", "related"]) {
20010
20133
  for (const ref of meta[field2] || []) {
@@ -20017,11 +20140,11 @@ function crossRefComplaints() {
20017
20140
  return said3;
20018
20141
  }
20019
20142
  function reconcileBoard() {
20020
- if (!fs51.existsSync(README)) return;
20143
+ if (!fs52.existsSync(README)) return;
20021
20144
  for (const line of [...readmeComplaints(true), ...crossRefComplaints()]) warn2(line);
20022
20145
  }
20023
20146
  function boardComplaints() {
20024
- if (!fs51.existsSync(README)) return [];
20147
+ if (!fs52.existsSync(README)) return [];
20025
20148
  try {
20026
20149
  return [...readmeComplaints(false), ...crossRefComplaints()];
20027
20150
  } catch {
@@ -20041,8 +20164,8 @@ var init_reconcile = __esm({
20041
20164
  });
20042
20165
 
20043
20166
  // src/commands/card.ts
20044
- import fs52 from "node:fs";
20045
- import path57 from "node:path";
20167
+ import fs53 from "node:fs";
20168
+ import path59 from "node:path";
20046
20169
  function defaultBody() {
20047
20170
  return [
20048
20171
  "<\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 +20191,7 @@ function bodyFromFile(opts) {
20068
20191
  if (opts.body === false) die("pass --body-file or --no-body, not both");
20069
20192
  let text5;
20070
20193
  try {
20071
- text5 = fs52.readFileSync(opts.bodyFile, "utf8");
20194
+ text5 = fs53.readFileSync(opts.bodyFile, "utf8");
20072
20195
  } catch {
20073
20196
  die(`can't read ${opts.bodyFile} \u2014 write the body to a file, then pass its path`, { kind: "needs-input" });
20074
20197
  }
@@ -20100,20 +20223,20 @@ function cmdCreate(opts) {
20100
20223
  const start = opts.id;
20101
20224
  const slug2 = slugify(opts.slug !== void 0 ? opts.slug : title);
20102
20225
  const fileRel = `${start}-${slug2}.md`;
20103
- const file = path57.join(TODO, fileRel);
20226
+ const file = path59.join(TODO, fileRel);
20104
20227
  const held4 = locate(start) ?? locateArchived(start);
20105
- if (held4 && path57.basename(held4.target) === `${start}-${slug2}.md`) {
20228
+ if (held4 && path59.basename(held4.target) === `${start}-${slug2}.md`) {
20106
20229
  say(start);
20107
20230
  say(` ${rel(held4.target)} was already written`);
20108
20231
  return { id: start, ids: [start], title, file: rel(held4.target), indexed: false };
20109
20232
  }
20110
20233
  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`);
20234
+ if (fs53.existsSync(file)) die(`${rel(file)} already exists \u2014 pick a different --slug`);
20112
20235
  countBoardEvent(triage ? "cards_created_proposed" : "cards_created_asked");
20113
20236
  const meta = { title, priority, status: "todo", blocked_by, related, modules, workflow, triage, source, questions };
20114
20237
  const scaffolded = !written && opts.body !== false;
20115
20238
  const body = written ?? (scaffolded ? defaultBody() : "");
20116
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n\n" + body);
20239
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n\n" + body);
20117
20240
  const indexed = addReadmeRef(start, title, fileRel);
20118
20241
  say(start);
20119
20242
  say(
@@ -20151,8 +20274,8 @@ function cmdUpdate(id, flags) {
20151
20274
  if (creating) die(creating, { kind: "card-being-created", id });
20152
20275
  const found2 = locate(id);
20153
20276
  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"));
20277
+ const file = found2.kind === "group" ? path59.join(found2.target, "root.md") : found2.target;
20278
+ const { meta, body } = parseFrontmatter(fs53.readFileSync(file, "utf8"));
20156
20279
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
20157
20280
  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
20281
  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 +20355,26 @@ function cmdUpdate(id, flags) {
20232
20355
  meta.status = "todo";
20233
20356
  changes.push("status\u2192todo (open questions)");
20234
20357
  }
20235
- const curRel = path57.relative(TODO, file);
20358
+ const curRel = path59.relative(TODO, file);
20236
20359
  const isSubtask = found2.kind === "file" && enclosingGroupRoot(file) !== null;
20237
- let base = path57.basename(file);
20360
+ let base = path59.basename(file);
20238
20361
  if (flags.slug !== void 0) {
20239
20362
  if (found2.kind === "group") die("renaming a group root by script is not supported");
20240
20363
  base = `${id}-${slugify(flags.slug)}.md`;
20241
20364
  }
20242
- const destRel = path57.join(path57.dirname(curRel), base);
20243
- const dest = path57.join(TODO, destRel);
20365
+ const destRel = path59.join(path59.dirname(curRel), base);
20366
+ const dest = path59.join(TODO, destRel);
20244
20367
  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);
20368
+ if (moving && fs53.existsSync(dest)) die(`${rel(dest)} already exists`);
20369
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20370
+ if (moving) fs53.renameSync(file, dest);
20248
20371
  if (isSubtask) {
20249
20372
  if (moving || changes.includes("title")) repointReadmeLink(id, curRel, destRel, meta.title);
20250
- if (moving) changes.push(`renamed \u2192 ${destRel.split(path57.sep).join("/")}`);
20373
+ if (moving) changes.push(`renamed \u2192 ${destRel.split(path59.sep).join("/")}`);
20251
20374
  } else if (moving) {
20252
20375
  stripReadmeRefs({ kind: "file", rel: curRel });
20253
20376
  addReadmeRef(id, meta.title, destRel);
20254
- changes.push(`renamed \u2192 ${destRel.split(path57.sep).join("/")}`);
20377
+ changes.push(`renamed \u2192 ${destRel.split(path59.sep).join("/")}`);
20255
20378
  } else if (changes.includes("title")) {
20256
20379
  stripReadmeRefs({ kind: "file", rel: curRel });
20257
20380
  addReadmeRef(id, meta.title, curRel);
@@ -20263,8 +20386,8 @@ function cmdUpdateQuestions(id, input) {
20263
20386
  const ops = readQuestionOps(input.ops ?? []);
20264
20387
  const found2 = locate(id);
20265
20388
  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"));
20389
+ const file = found2.kind === "group" ? path59.join(found2.target, "root.md") : found2.target;
20390
+ const { meta, body } = parseFrontmatter(fs53.readFileSync(file, "utf8"));
20268
20391
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
20269
20392
  if (insideRun() && ops.some((op) => op.kind === "skip" || op.kind === "unskip")) {
20270
20393
  die("only the user skips or reopens a question \u2014 a run leaves questions for them to answer");
@@ -20337,7 +20460,7 @@ function cmdUpdateQuestions(id, input) {
20337
20460
  meta.status = "todo";
20338
20461
  changes.push("status\u2192todo (open questions)");
20339
20462
  }
20340
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20463
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20341
20464
  for (const kind of closed2) countBoardEvent(kind);
20342
20465
  settleDelivery2(id, skipped, unskipped);
20343
20466
  say(
@@ -20411,13 +20534,13 @@ var init_config_template = __esm({
20411
20534
  });
20412
20535
 
20413
20536
  // src/lib/agent/local.ts
20414
- import fs53 from "node:fs";
20415
- import path58 from "node:path";
20537
+ import fs54 from "node:fs";
20538
+ import path60 from "node:path";
20416
20539
  function takeLocalModels(board2) {
20417
- const file = path58.join(board2, ".local.json");
20540
+ const file = path60.join(board2, ".local.json");
20418
20541
  let held4;
20419
20542
  try {
20420
- held4 = configBlock(JSON.parse(fs53.readFileSync(file, "utf8")));
20543
+ held4 = configBlock(JSON.parse(fs54.readFileSync(file, "utf8")));
20421
20544
  } catch {
20422
20545
  return {};
20423
20546
  }
@@ -20435,7 +20558,7 @@ function takeLocalModels(board2) {
20435
20558
  }
20436
20559
  if (!Object.keys(agents).length) return out;
20437
20560
  delete held4.agents;
20438
- fs53.writeFileSync(file, JSON.stringify(held4, null, 2) + "\n");
20561
+ fs54.writeFileSync(file, JSON.stringify(held4, null, 2) + "\n");
20439
20562
  return out;
20440
20563
  }
20441
20564
  var LOCAL_IGNORE_LINE;
@@ -20496,12 +20619,12 @@ var init_identity2 = __esm({
20496
20619
  });
20497
20620
 
20498
20621
  // src/lib/signals/migrate.ts
20499
- import fs54 from "node:fs";
20500
- import path59 from "node:path";
20622
+ import fs55 from "node:fs";
20623
+ import path61 from "node:path";
20501
20624
  function readHandled() {
20502
20625
  let text5;
20503
20626
  try {
20504
- text5 = fs54.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
20627
+ text5 = fs55.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
20505
20628
  } catch {
20506
20629
  return [];
20507
20630
  }
@@ -20518,57 +20641,57 @@ function readHandled() {
20518
20641
  return held4;
20519
20642
  }
20520
20643
  function lift(from, into) {
20521
- fs54.mkdirSync(into, { recursive: true });
20522
- fs54.renameSync(from, path59.join(into, freeName(into, path59.basename(from))));
20644
+ fs55.mkdirSync(into, { recursive: true });
20645
+ fs55.renameSync(from, path61.join(into, freeName(into, path61.basename(from))));
20523
20646
  }
20524
20647
  function repoint(dir, from, into) {
20525
20648
  let entries;
20526
20649
  try {
20527
- entries = fs54.readdirSync(dir, { withFileTypes: true });
20650
+ entries = fs55.readdirSync(dir, { withFileTypes: true });
20528
20651
  } catch {
20529
20652
  return;
20530
20653
  }
20531
20654
  for (const entry of entries) {
20532
20655
  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));
20656
+ const file = path61.join(dir, entry.name);
20657
+ const text5 = fs55.readFileSync(file, "utf8");
20658
+ if (text5.includes(from)) fs55.writeFileSync(file, text5.split(from).join(into));
20536
20659
  }
20537
20660
  }
20538
20661
  function dropIfEmpty2(dir) {
20539
20662
  try {
20540
- fs54.rmdirSync(dir);
20663
+ fs55.rmdirSync(dir);
20541
20664
  } catch {
20542
20665
  }
20543
20666
  }
20544
20667
  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);
20668
+ if (!fs55.existsSync(SIGNALS_OLD_INBOX)) return;
20669
+ const oldFiles = path61.join(SIGNALS_OLD_INBOX, "files");
20670
+ if (fs55.existsSync(oldFiles)) {
20671
+ for (const entry of fs55.readdirSync(oldFiles, { withFileTypes: true })) {
20672
+ if (entry.isFile()) lift(path61.join(oldFiles, entry.name), SIGNALS_FILES);
20550
20673
  }
20551
20674
  dropIfEmpty2(oldFiles);
20552
20675
  }
20553
20676
  const held4 = new Set(readFolder(TRIAGE).map((signal2) => signal2.sourceId));
20554
- for (const entry of fs54.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
20677
+ for (const entry of fs55.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
20555
20678
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
20556
- const from = path59.join(SIGNALS_OLD_INBOX, entry.name);
20679
+ const from = path61.join(SIGNALS_OLD_INBOX, entry.name);
20557
20680
  const item = parse(from);
20558
20681
  if (item && held4.has(item.sourceId)) {
20559
- fs54.rmSync(from, { force: true });
20682
+ fs55.rmSync(from, { force: true });
20560
20683
  continue;
20561
20684
  }
20562
20685
  if (item) held4.add(item.sourceId);
20563
20686
  lift(from, TRIAGE);
20564
20687
  }
20565
- const wasAt = asWritten(path59.join(SIGNALS_OLD_INBOX, "files"));
20688
+ const wasAt = asWritten(path61.join(SIGNALS_OLD_INBOX, "files"));
20566
20689
  const nowAt = asWritten(SIGNALS_FILES);
20567
20690
  for (const dir of [TRIAGE, SIGNALS_ARCHIVED, SIGNALS_DISMISSED]) repoint(dir, wasAt, nowAt);
20568
20691
  dropIfEmpty2(SIGNALS_OLD_INBOX);
20569
20692
  }
20570
20693
  function liftHandled() {
20571
- if (!fs54.existsSync(SIGNALS_OLD_HANDLED)) return;
20694
+ if (!fs55.existsSync(SIGNALS_OLD_HANDLED)) return;
20572
20695
  const lines = readHandled();
20573
20696
  const held4 = /* @__PURE__ */ new Set([
20574
20697
  ...readFolder(TRIAGE).map((signal2) => signal2.sourceId),
@@ -20578,7 +20701,7 @@ function liftHandled() {
20578
20701
  for (const { sourceId, when } of lines) {
20579
20702
  if (held4.has(sourceId)) continue;
20580
20703
  held4.add(sourceId);
20581
- fs54.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
20704
+ fs55.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
20582
20705
  const name = freeName(SIGNALS_DISMISSED, fileName("", sourceId));
20583
20706
  const front = [
20584
20707
  "---",
@@ -20588,13 +20711,13 @@ function liftHandled() {
20588
20711
  "---",
20589
20712
  ""
20590
20713
  ];
20591
- fs54.writeFileSync(path59.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
20714
+ fs55.writeFileSync(path61.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
20592
20715
  `);
20593
20716
  }
20594
- fs54.rmSync(SIGNALS_OLD_HANDLED, { force: true });
20717
+ fs55.rmSync(SIGNALS_OLD_HANDLED, { force: true });
20595
20718
  }
20596
20719
  function migrateTriage() {
20597
- if (!fs54.existsSync(SIGNALS_OLD_INBOX) && !fs54.existsSync(SIGNALS_OLD_HANDLED)) return;
20720
+ if (!fs55.existsSync(SIGNALS_OLD_INBOX) && !fs55.existsSync(SIGNALS_OLD_HANDLED)) return;
20598
20721
  try {
20599
20722
  liftInbox();
20600
20723
  liftHandled();
@@ -20609,13 +20732,13 @@ var init_migrate = __esm({
20609
20732
  init_yaml();
20610
20733
  init_inbox();
20611
20734
  HANDLED_LINE = /^-\s+(.+?)\s+—\s+(.+)$/;
20612
- asWritten = (dir) => `${rel(dir).split(path59.sep).join("/")}/`;
20735
+ asWritten = (dir) => `${rel(dir).split(path61.sep).join("/")}/`;
20613
20736
  }
20614
20737
  });
20615
20738
 
20616
20739
  // src/lib/signals/add.ts
20617
- import fs55 from "node:fs";
20618
- import path60 from "node:path";
20740
+ import fs56 from "node:fs";
20741
+ import path62 from "node:path";
20619
20742
  import { createHash as createHash4 } from "node:crypto";
20620
20743
  function linkTitle(url) {
20621
20744
  let at;
@@ -20628,7 +20751,7 @@ function linkTitle(url) {
20628
20751
  return oneLine(where) || url.slice(0, TITLE_MAX);
20629
20752
  }
20630
20753
  function asText(file) {
20631
- const ext = path60.extname(file.name).toLowerCase();
20754
+ const ext = path62.extname(file.name).toLowerCase();
20632
20755
  if (!file.type.startsWith("text/") && file.type !== "application/json" && !TEXT_EXTENSIONS.has(ext)) return null;
20633
20756
  try {
20634
20757
  const text5 = new TextDecoder("utf-8", { fatal: true }).decode(file.data);
@@ -20638,9 +20761,9 @@ function asText(file) {
20638
20761
  }
20639
20762
  }
20640
20763
  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";
20764
+ const base = path62.basename(name);
20765
+ const ext = path62.extname(base).toLowerCase().slice(0, 12);
20766
+ const word = path62.basename(base, path62.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
20644
20767
  const hash2 = createHash4("sha256").update(data).digest("hex").slice(0, 8);
20645
20768
  return `${word}-${hash2}${ext}`;
20646
20769
  }
@@ -20649,9 +20772,9 @@ function addToInbox(drop) {
20649
20772
  const typed = (drop.text ?? "").trim();
20650
20773
  const file = drop.file;
20651
20774
  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.` };
20775
+ if (file && file.data.length === 0) return { ok: false, error: `${path62.basename(file.name)} is empty.` };
20653
20776
  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.` };
20777
+ return { ok: false, error: `${path62.basename(file.name)} is over ${MAX_BYTES / 1024 / 1024} MB \u2014 too big for the board.` };
20655
20778
  }
20656
20779
  const read4 = describe(typed, file);
20657
20780
  const keep2 = read4.keep;
@@ -20673,8 +20796,8 @@ ${incoming.summary}`);
20673
20796
  if (seen.status === "pending" || seen.status === "archived") return { ok: false, error: `${sayHit(seen)}.` };
20674
20797
  try {
20675
20798
  if (keep2) {
20676
- fs55.mkdirSync(SIGNALS_FILES, { recursive: true });
20677
- fs55.writeFileSync(keep2.at, keep2.data);
20799
+ fs56.mkdirSync(SIGNALS_FILES, { recursive: true });
20800
+ fs56.writeFileSync(keep2.at, keep2.data);
20678
20801
  }
20679
20802
  return { ok: true, signal: writeSignal({ ...incoming, sourceId }, formatStamp(/* @__PURE__ */ new Date()), drop.slug) };
20680
20803
  } catch (e) {
@@ -20688,7 +20811,7 @@ function describe(typed, file) {
20688
20811
  return only ? [only] : [];
20689
20812
  };
20690
20813
  if (file) {
20691
- const name = path60.basename(file.name);
20814
+ const name = path62.basename(file.name);
20692
20815
  const text5 = asText(file);
20693
20816
  const note = typed ? `
20694
20817
 
@@ -20700,7 +20823,7 @@ ${typed}` : "";
20700
20823
  const at = keepAt(file);
20701
20824
  return {
20702
20825
  incoming: {
20703
- title: path60.basename(name, path60.extname(name)) || name,
20826
+ title: path62.basename(name, path62.extname(name)) || name,
20704
20827
  summary: `${name} \u2014 ${boardRel2(at)}${note}`,
20705
20828
  ...named2
20706
20829
  },
@@ -20738,73 +20861,73 @@ var init_add = __esm({
20738
20861
  MAX_BYTES = 25 * 1024 * 1024;
20739
20862
  TITLE_MAX = 120;
20740
20863
  TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".txt", ".text", ".csv", ".json", ".yml", ".yaml", ".log"]);
20741
- boardRel2 = (file) => rel(file).split(path60.sep).join("/");
20864
+ boardRel2 = (file) => rel(file).split(path62.sep).join("/");
20742
20865
  oneLine = (text5) => {
20743
20866
  const first = text5.split("\n").find((line) => line.trim()) ?? "";
20744
20867
  const clean = first.replace(/^#+\s*/, "").trim();
20745
20868
  return clean.length > TITLE_MAX ? `${clean.slice(0, TITLE_MAX - 1).trimEnd()}\u2026` : clean;
20746
20869
  };
20747
- keepAt = (file) => path60.join(SIGNALS_FILES, fileName2(file.name, file.data));
20870
+ keepAt = (file) => path62.join(SIGNALS_FILES, fileName2(file.name, file.data));
20748
20871
  }
20749
20872
  });
20750
20873
 
20751
20874
  // src/lib/recurring.ts
20752
- import fs56 from "node:fs";
20753
- import path61 from "node:path";
20875
+ import fs57 from "node:fs";
20876
+ import path63 from "node:path";
20754
20877
  function migratePruneMemoryCard() {
20755
20878
  const dir = recurringDir();
20756
20879
  let names4;
20757
20880
  try {
20758
- names4 = fs56.readdirSync(dir);
20881
+ names4 = fs57.readdirSync(dir);
20759
20882
  } catch {
20760
20883
  return null;
20761
20884
  }
20762
20885
  const name = names4.find((entry) => entry.endsWith(`-${PRUNE_SLUG}.md`));
20763
20886
  if (!name) return null;
20764
- const file = path61.join(dir, name);
20887
+ const file = path63.join(dir, name);
20765
20888
  try {
20766
- const { meta } = parseFrontmatter(fs56.readFileSync(file, "utf8"));
20889
+ const { meta } = parseFrontmatter(fs57.readFileSync(file, "utf8"));
20767
20890
  const cadence = meta?.cadence;
20768
20891
  if (typeof cadence === "string") adoptMemoryPruneCadence(cadence);
20769
20892
  } catch {
20770
20893
  }
20771
- fs56.rmSync(file, { force: true });
20894
+ fs57.rmSync(file, { force: true });
20772
20895
  return rel(file);
20773
20896
  }
20774
20897
  function legacyCards() {
20775
20898
  const dir = recurringDir();
20776
- if (!fs56.existsSync(dir)) return [];
20899
+ if (!fs57.existsSync(dir)) return [];
20777
20900
  const cards = [];
20778
- for (const entry of fs56.readdirSync(dir, { withFileTypes: true })) {
20901
+ for (const entry of fs57.readdirSync(dir, { withFileTypes: true })) {
20779
20902
  const id = idPrefix(entry.name);
20780
20903
  if (id === null) continue;
20781
- const full = path61.join(dir, entry.name);
20904
+ const full = path63.join(dir, entry.name);
20782
20905
  const slug2 = entry.name.replace(/\.md$/, "").replace(/^\d+-?/, "");
20783
20906
  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 });
20907
+ else if (entry.isDirectory() && fs57.existsSync(path63.join(full, "root.md"))) {
20908
+ cards.push({ id, slug: slug2, file: path63.join(full, "root.md"), folder: full });
20786
20909
  }
20787
20910
  }
20788
20911
  return cards.sort((a, b) => a.id - b.id);
20789
20912
  }
20790
20913
  function mergeInto2(from, to, skip = []) {
20791
- fs56.mkdirSync(to, { recursive: true });
20792
- for (const entry of fs56.readdirSync(from, { withFileTypes: true })) {
20914
+ fs57.mkdirSync(to, { recursive: true });
20915
+ for (const entry of fs57.readdirSync(from, { withFileTypes: true })) {
20793
20916
  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);
20917
+ const source = path63.join(from, entry.name);
20918
+ const target = path63.join(to, entry.name);
20919
+ if (!fs57.existsSync(target)) fs57.renameSync(source, target);
20920
+ else if (entry.isDirectory() && fs57.statSync(target).isDirectory()) mergeInto2(source, target);
20798
20921
  }
20799
- if (isEmpty(from)) fs56.rmSync(from, { recursive: true, force: true });
20922
+ if (isEmpty(from)) fs57.rmSync(from, { recursive: true, force: true });
20800
20923
  }
20801
20924
  function moveSideFolders() {
20802
20925
  const dir = recurringDir();
20803
- for (const entry of fs56.readdirSync(dir, { withFileTypes: true })) {
20926
+ for (const entry of fs57.readdirSync(dir, { withFileTypes: true })) {
20804
20927
  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));
20928
+ const from = path63.join(dir, entry.name);
20929
+ if (isEmpty(from)) fs57.rmSync(from, { recursive: true, force: true });
20930
+ else mergeInto2(from, path63.join(AGENTS, entry.name));
20808
20931
  }
20809
20932
  }
20810
20933
  function sections(body) {
@@ -20854,8 +20977,8 @@ function agentName(card, text5) {
20854
20977
  const known2 = /* @__PURE__ */ new Set([...specAgentCatalog().agents.map((a) => a.name), ...ROLE_NAMES]);
20855
20978
  for (const name of [slug2, `${slug2}-${card.id}`]) {
20856
20979
  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;
20980
+ const file = path63.join(AGENTS, name, AGENT_FILE3);
20981
+ const written = fs57.existsSync(file) ? fs57.readFileSync(file, "utf8") : null;
20859
20982
  if (written === text5(name)) return name;
20860
20983
  if (written === null && !known2.has(name)) return name;
20861
20984
  }
@@ -20872,11 +20995,11 @@ ${q.options.map((o) => `- ${o}`).join("\n")}` : "";
20872
20995
  function removeCard(card) {
20873
20996
  dropCrossRefs(card.id);
20874
20997
  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 });
20998
+ stripReadmeRefs({ kind: card.folder ? "group" : "file", rel: path63.relative(TODO, target).split(path63.sep).join("/") });
20999
+ fs57.rmSync(target, { recursive: true, force: true });
20877
21000
  }
20878
21001
  function migrateCard(card) {
20879
- const { meta, body } = parseFrontmatter(fs56.readFileSync(card.file, "utf8"));
21002
+ const { meta, body } = parseFrontmatter(fs57.readFileSync(card.file, "utf8"));
20880
21003
  if (!meta) throw new Error("its frontmatter cannot be read");
20881
21004
  const raw = meta;
20882
21005
  const said3 = (key) => typeof raw[key] === "string" ? raw[key].trim() : "";
@@ -20886,19 +21009,19 @@ function migrateCard(card) {
20886
21009
  if (!flow) throw new Error("this board has no workflow to put it in");
20887
21010
  const text5 = (name2) => agentText(name2, meta.title || card.slug, body);
20888
21011
  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);
21012
+ const dir = path63.join(AGENTS, name);
21013
+ const file = path63.join(dir, AGENT_FILE3);
21014
+ const madeDir = !fs57.existsSync(dir);
21015
+ const wrote = !fs57.existsSync(file);
20893
21016
  try {
20894
- fs56.mkdirSync(dir, { recursive: true });
20895
- if (wrote) fs56.writeFileSync(file, text5(name));
21017
+ fs57.mkdirSync(dir, { recursive: true });
21018
+ if (wrote) fs57.writeFileSync(file, text5(name));
20896
21019
  const adopted = adoptWorkflowScheduled(flow.id, name, { cadence, lastRun });
20897
21020
  if (!adopted.ok) throw new Error(adopted.error);
20898
21021
  questionsToTriage(meta, name);
20899
21022
  } catch (e) {
20900
- if (madeDir) fs56.rmSync(dir, { recursive: true, force: true });
20901
- else if (wrote) fs56.rmSync(file, { force: true });
21023
+ if (madeDir) fs57.rmSync(dir, { recursive: true, force: true });
21024
+ else if (wrote) fs57.rmSync(file, { force: true });
20902
21025
  throw e;
20903
21026
  }
20904
21027
  if (card.folder) mergeInto2(card.folder, dir, ["root.md"]);
@@ -20908,7 +21031,7 @@ function migrateCard(card) {
20908
21031
  function migrateRecurringCards() {
20909
21032
  const done2 = { agents: [], removed: [], failed: [] };
20910
21033
  const dir = recurringDir();
20911
- if (!fs56.existsSync(dir)) return done2;
21034
+ if (!fs57.existsSync(dir)) return done2;
20912
21035
  migratePruneMemoryCard();
20913
21036
  moveSideFolders();
20914
21037
  for (const card of legacyCards()) {
@@ -20921,7 +21044,7 @@ function migrateRecurringCards() {
20921
21044
  done2.failed.push({ card: rel(card.file), why: e instanceof Error ? e.message : String(e) });
20922
21045
  }
20923
21046
  }
20924
- if (isEmpty(dir)) fs56.rmSync(dir, { recursive: true, force: true });
21047
+ if (isEmpty(dir)) fs57.rmSync(dir, { recursive: true, force: true });
20925
21048
  return done2;
20926
21049
  }
20927
21050
  function recurringMigrationLines(done2) {
@@ -20954,14 +21077,14 @@ var init_recurring = __esm({
20954
21077
  PRUNE_SLUG = "prune-the-memory";
20955
21078
  FETCH_SLUG = "fetch-triage-items";
20956
21079
  AGENT_FILE3 = "AGENT.md";
20957
- recurringDir = () => path61.join(TODO, LEGACY_RECURRING);
20958
- isEmpty = (dir) => fs56.readdirSync(dir).every((name) => name === ".DS_Store");
21080
+ recurringDir = () => path63.join(TODO, LEGACY_RECURRING);
21081
+ isEmpty = (dir) => fs57.readdirSync(dir).every((name) => name === ".DS_Store");
20959
21082
  SECTION = /^##\s+(.+?)\s*$/;
20960
21083
  }
20961
21084
  });
20962
21085
 
20963
21086
  // src/commands/init.ts
20964
- import fs57 from "node:fs";
21087
+ import fs58 from "node:fs";
20965
21088
  function boardReadme() {
20966
21089
  return `# Board
20967
21090
 
@@ -20974,20 +21097,20 @@ _(none)_
20974
21097
  `;
20975
21098
  }
20976
21099
  function writeConfigIfMissing() {
20977
- if (fs57.existsSync(CONFIG)) return false;
20978
- fs57.mkdirSync(KANBAN, { recursive: true });
20979
- fs57.writeFileSync(CONFIG, CONFIG_TEMPLATE);
21100
+ if (fs58.existsSync(CONFIG)) return false;
21101
+ fs58.mkdirSync(KANBAN, { recursive: true });
21102
+ fs58.writeFileSync(CONFIG, CONFIG_TEMPLATE);
20980
21103
  return true;
20981
21104
  }
20982
21105
  function writeModulesIfMissing() {
20983
- if (fs57.existsSync(MODULES_MD)) return false;
20984
- fs57.mkdirSync(KANBAN, { recursive: true });
20985
- fs57.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
21106
+ if (fs58.existsSync(MODULES_MD)) return false;
21107
+ fs58.mkdirSync(KANBAN, { recursive: true });
21108
+ fs58.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
20986
21109
  return true;
20987
21110
  }
20988
21111
  function writeGitignoreIfMissing() {
20989
- fs57.mkdirSync(KANBAN, { recursive: true });
20990
- const text5 = fs57.existsSync(KANBAN_GITIGNORE) ? fs57.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
21112
+ fs58.mkdirSync(KANBAN, { recursive: true });
21113
+ const text5 = fs58.existsSync(KANBAN_GITIGNORE) ? fs58.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
20991
21114
  const has = (rule) => text5.split("\n").some((line) => line.trim() === rule.line);
20992
21115
  const missing = IGNORE_RULES.filter((rule) => !has(rule));
20993
21116
  if (!missing.length) return false;
@@ -20995,37 +21118,37 @@ function writeGitignoreIfMissing() {
20995
21118
  ${rule.line}
20996
21119
  `).join("");
20997
21120
  const separator = !text5 || text5.endsWith("\n") ? "" : "\n";
20998
- fs57.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
21121
+ fs58.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
20999
21122
  return true;
21000
21123
  }
21001
21124
  function writeSkeletonIfMissing() {
21002
21125
  const added = [];
21003
- if (!fs57.existsSync(TODO)) {
21004
- fs57.mkdirSync(TODO, { recursive: true });
21126
+ if (!fs58.existsSync(TODO)) {
21127
+ fs58.mkdirSync(TODO, { recursive: true });
21005
21128
  added.push(`${rel(TODO)}/`);
21006
21129
  }
21007
- if (!fs57.existsSync(README)) {
21008
- fs57.writeFileSync(README, boardReadme());
21130
+ if (!fs58.existsSync(README)) {
21131
+ fs58.writeFileSync(README, boardReadme());
21009
21132
  added.push(rel(README));
21010
21133
  }
21011
21134
  return added;
21012
21135
  }
21013
21136
  function retireReleases() {
21014
21137
  const done2 = [];
21015
- if (fs57.existsSync(RELEASES)) {
21016
- fs57.rmSync(RELEASES);
21138
+ if (fs58.existsSync(RELEASES)) {
21139
+ fs58.rmSync(RELEASES);
21017
21140
  done2.push(`deleted ${rel(RELEASES)}`);
21018
21141
  }
21019
21142
  let cards = 0;
21020
21143
  for (const dir of [TODO, ARCHIVE]) {
21021
- if (!fs57.existsSync(dir)) continue;
21144
+ if (!fs58.existsSync(dir)) continue;
21022
21145
  for (const file of walkMd(dir)) {
21023
- const text5 = fs57.readFileSync(file, "utf8");
21146
+ const text5 = fs58.readFileSync(file, "utf8");
21024
21147
  const end2 = text5.startsWith("---\n") ? text5.indexOf("\n---", 3) : -1;
21025
21148
  if (end2 < 0) continue;
21026
21149
  const head = text5.slice(0, end2).replace(/\nrelease:[^\n]*/, "");
21027
21150
  if (head.length === end2) continue;
21028
- fs57.writeFileSync(file, head + text5.slice(end2));
21151
+ fs58.writeFileSync(file, head + text5.slice(end2));
21029
21152
  cards++;
21030
21153
  }
21031
21154
  }
@@ -21033,7 +21156,7 @@ function retireReleases() {
21033
21156
  return done2.join(", ");
21034
21157
  }
21035
21158
  function cmdInit() {
21036
- if (fs57.existsSync(KANBAN)) {
21159
+ if (fs58.existsSync(KANBAN)) {
21037
21160
  const added = [
21038
21161
  ...writeSkeletonIfMissing(),
21039
21162
  writeConfigIfMissing() && rel(CONFIG),
@@ -21068,8 +21191,8 @@ function cmdInit() {
21068
21191
  }
21069
21192
  return { board: rel(KANBAN), created: false, added, memory_paths: scaffolded.map((s) => rel(s.dir)) };
21070
21193
  }
21071
- fs57.mkdirSync(TODO, { recursive: true });
21072
- fs57.writeFileSync(README, boardReadme());
21194
+ fs58.mkdirSync(TODO, { recursive: true });
21195
+ fs58.writeFileSync(README, boardReadme());
21073
21196
  writeConfigIfMissing();
21074
21197
  scaffoldProjectMemory();
21075
21198
  writeModulesIfMissing();
@@ -21158,25 +21281,25 @@ var init_scheduled = __esm({
21158
21281
  });
21159
21282
 
21160
21283
  // src/lib/card-age.ts
21161
- import fs58 from "node:fs";
21162
- import path62 from "node:path";
21284
+ import fs59 from "node:fs";
21285
+ import path64 from "node:path";
21163
21286
  function staleAfterIn(config) {
21164
21287
  const days = Number(LINE.exec(config)?.[1]);
21165
21288
  return Number.isInteger(days) && days > 0 ? days : STALE_AFTER_DEFAULT;
21166
21289
  }
21167
21290
  function staleAfter() {
21168
- if (!fs58.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
21169
- return staleAfterIn(fs58.readFileSync(CONFIG, "utf8"));
21291
+ if (!fs59.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
21292
+ return staleAfterIn(fs59.readFileSync(CONFIG, "utf8"));
21170
21293
  }
21171
21294
  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("/");
21295
+ const from = path64.relative(real(top), real(TODO));
21296
+ if (!from || from.startsWith("..") || path64.isAbsolute(from)) return null;
21297
+ return from.split(path64.sep).join("/");
21175
21298
  }
21176
21299
  function cardFile2(spec, printed) {
21177
21300
  const p = unquotePath(printed);
21178
21301
  if (!p.startsWith(`${spec}/`)) return null;
21179
- return path62.join(TODO, ...p.slice(spec.length + 1).split("/"));
21302
+ return path64.join(TODO, ...p.slice(spec.length + 1).split("/"));
21180
21303
  }
21181
21304
  function dirtyCards(top, spec) {
21182
21305
  const out = git(["status", "--porcelain", "--untracked-files=all", "--", spec], top);
@@ -21223,9 +21346,9 @@ var init_card_age = __esm({
21223
21346
  gitTop = () => git(["rev-parse", "--show-toplevel"])?.trim() || null;
21224
21347
  real = (p) => {
21225
21348
  try {
21226
- return fs58.realpathSync(p);
21349
+ return fs59.realpathSync(p);
21227
21350
  } catch {
21228
- return path62.resolve(p);
21351
+ return path64.resolve(p);
21229
21352
  }
21230
21353
  };
21231
21354
  unquotePath = (line) => {
@@ -21260,8 +21383,8 @@ var init_card_holds = __esm({
21260
21383
  });
21261
21384
 
21262
21385
  // src/commands/list.ts
21263
- import fs59 from "node:fs";
21264
- import path63 from "node:path";
21386
+ import fs60 from "node:fs";
21387
+ import path65 from "node:path";
21265
21388
  function summaryLine(body) {
21266
21389
  const lines = body.split("\n");
21267
21390
  let i = 0;
@@ -21277,13 +21400,13 @@ function summaryLine(body) {
21277
21400
  function openRows() {
21278
21401
  const rows = [];
21279
21402
  for (const file of walkMd(TODO)) {
21280
- const base = path63.basename(file);
21403
+ const base = path65.basename(file);
21281
21404
  if (base === "README.md") continue;
21282
21405
  const isRoot = base === "root.md";
21283
- const id = isRoot ? idPrefix(path63.basename(path63.dirname(file))) : idPrefix(base);
21406
+ const id = isRoot ? idPrefix(path65.basename(path65.dirname(file))) : idPrefix(base);
21284
21407
  if (id == null) continue;
21285
- if (isLegacyRecurring(path63.relative(TODO, file))) continue;
21286
- const { meta, body } = parseFrontmatter(fs59.readFileSync(file, "utf8"));
21408
+ if (isLegacyRecurring(path65.relative(TODO, file))) continue;
21409
+ const { meta, body } = parseFrontmatter(fs60.readFileSync(file, "utf8"));
21287
21410
  rows.push({
21288
21411
  id,
21289
21412
  file,
@@ -21325,15 +21448,15 @@ function cmdStale(rows, all2, scope, mod) {
21325
21448
  }
21326
21449
  function archivedFiles() {
21327
21450
  const files2 = /* @__PURE__ */ new Map();
21328
- if (!fs59.existsSync(ARCHIVE)) return files2;
21451
+ if (!fs60.existsSync(ARCHIVE)) return files2;
21329
21452
  for (const file of walkMd(ARCHIVE)) {
21330
- const id = idPrefix(path63.basename(file));
21453
+ const id = idPrefix(path65.basename(file));
21331
21454
  if (id !== null) files2.set(id, file);
21332
21455
  }
21333
21456
  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);
21457
+ const id = idPrefix(path65.basename(dir));
21458
+ const root = path65.join(dir, "root.md");
21459
+ if (id !== null && fs60.existsSync(root)) files2.set(id, root);
21337
21460
  }
21338
21461
  return files2;
21339
21462
  }
@@ -21444,14 +21567,14 @@ var init_list = __esm({
21444
21567
  });
21445
21568
 
21446
21569
  // src/commands/misc.ts
21447
- import fs60 from "node:fs";
21448
- import path64 from "node:path";
21570
+ import fs61 from "node:fs";
21571
+ import path66 from "node:path";
21449
21572
  function extractOldMeta(text5, file) {
21450
21573
  const grab = (re) => {
21451
21574
  const m = text5.match(re);
21452
21575
  return m ? m[1].trim() : null;
21453
21576
  };
21454
- const title = grab(/^#\s+(.+)$/m) || slugify(path64.basename(file, ".md").replace(/^\d+-/, "")).replace(/-/g, " ");
21577
+ const title = grab(/^#\s+(.+)$/m) || slugify(path66.basename(file, ".md").replace(/^\d+-/, "")).replace(/-/g, " ");
21455
21578
  const norm = (raw) => {
21456
21579
  const v = (raw || "").toLowerCase();
21457
21580
  return LEVELS.includes(v) ? v : "med";
@@ -21478,11 +21601,11 @@ function stripOldHeader(text5) {
21478
21601
  }
21479
21602
  function cmdMigrate(opts) {
21480
21603
  const dry = opts.dryRun === true;
21481
- const files2 = walkMd(TODO).filter((f) => path64.basename(f) !== "README.md");
21604
+ const files2 = walkMd(TODO).filter((f) => path66.basename(f) !== "README.md");
21482
21605
  let changed = 0;
21483
21606
  let skipped = 0;
21484
21607
  for (const file of files2) {
21485
- const text5 = fs60.readFileSync(file, "utf8");
21608
+ const text5 = fs61.readFileSync(file, "utf8");
21486
21609
  if (text5.trimStart().startsWith("---")) {
21487
21610
  skipped++;
21488
21611
  continue;
@@ -21491,7 +21614,7 @@ function cmdMigrate(opts) {
21491
21614
  const out = serializeFrontmatter(meta) + "\n\n" + stripOldHeader(text5).replace(/^\n+/, "");
21492
21615
  if (dry) say(`would migrate ${rel(file)} (priority=${meta.priority})`);
21493
21616
  else {
21494
- fs60.writeFileSync(file, out.endsWith("\n") ? out : out + "\n");
21617
+ fs61.writeFileSync(file, out.endsWith("\n") ? out : out + "\n");
21495
21618
  say(`migrated ${rel(file)}`);
21496
21619
  }
21497
21620
  changed++;
@@ -21512,10 +21635,10 @@ var init_misc = __esm({
21512
21635
  });
21513
21636
 
21514
21637
  // src/lib/group-close.ts
21515
- import fs61 from "node:fs";
21638
+ import fs62 from "node:fs";
21516
21639
  function groupCloses(rootFile) {
21517
21640
  try {
21518
- return groupCloseOf(fs61.readFileSync(rootFile, "utf8"));
21641
+ return groupCloseOf(fs62.readFileSync(rootFile, "utf8"));
21519
21642
  } catch {
21520
21643
  return false;
21521
21644
  }
@@ -21528,12 +21651,12 @@ var init_group_close = __esm({
21528
21651
  });
21529
21652
 
21530
21653
  // src/commands/remove.ts
21531
- import fs62 from "node:fs";
21532
- import path65 from "node:path";
21654
+ import fs63 from "node:fs";
21655
+ import path67 from "node:path";
21533
21656
  function leavingIds(id, found2) {
21534
21657
  const ids = /* @__PURE__ */ new Set([id]);
21535
21658
  if (found2.kind === "group") {
21536
- const names4 = [...walkMd(found2.target), ...walkDirs(found2.target)].map((f) => path65.basename(f));
21659
+ const names4 = [...walkMd(found2.target), ...walkDirs(found2.target)].map((f) => path67.basename(f));
21537
21660
  for (const name of names4) {
21538
21661
  const n = idPrefix(name);
21539
21662
  if (n !== null) ids.add(n);
@@ -21545,10 +21668,10 @@ function findMentions(ids) {
21545
21668
  const hits = [];
21546
21669
  const re = new RegExp(ids.map((id) => `#${id}(?!\\d)`).join("|"));
21547
21670
  for (const dir of [TODO, MEMORY]) {
21548
- if (!fs62.existsSync(dir)) continue;
21671
+ if (!fs63.existsSync(dir)) continue;
21549
21672
  for (const file of walkMd(dir)) {
21550
- if (path65.basename(file) === "README.md") continue;
21551
- const lines = fs62.readFileSync(file, "utf8").split("\n");
21673
+ if (path67.basename(file) === "README.md") continue;
21674
+ const lines = fs63.readFileSync(file, "utf8").split("\n");
21552
21675
  const fmEnd = frontmatterEnd(lines);
21553
21676
  lines.forEach((line, i) => {
21554
21677
  if (!re.test(line)) return;
@@ -21564,12 +21687,12 @@ function findMentions(ids) {
21564
21687
  return hits;
21565
21688
  }
21566
21689
  function leavingCards(id, found2) {
21567
- const own = found2.kind === "group" ? path65.join(found2.target, "root.md") : found2.target;
21690
+ const own = found2.kind === "group" ? path67.join(found2.target, "root.md") : found2.target;
21568
21691
  const cards = [{ id, file: own }];
21569
21692
  if (found2.kind !== "group") return cards;
21570
21693
  for (const file of walkMd(found2.target)) {
21571
21694
  if (file === own) continue;
21572
- const n = idPrefix(path65.basename(file));
21695
+ const n = idPrefix(path67.basename(file));
21573
21696
  if (n !== null) cards.push({ id: n, file });
21574
21697
  }
21575
21698
  return cards;
@@ -21578,10 +21701,10 @@ function stampLeaving(cards, rejection) {
21578
21701
  const day = formatDay();
21579
21702
  const stamp4 = rejection && !rejection.discard ? { reason: rejection.reason, at: (/* @__PURE__ */ new Date()).toISOString(), by: insideRun() ? "agent" : "user" } : rejection && { reason: rejection.reason };
21580
21703
  for (const card of cards) {
21581
- if (!fs62.existsSync(card.file)) continue;
21582
- const text5 = fs62.readFileSync(card.file, "utf8");
21704
+ if (!fs63.existsSync(card.file)) continue;
21705
+ const text5 = fs63.readFileSync(card.file, "utf8");
21583
21706
  const stamped = stampLeavingIn(text5, day, stamp4);
21584
- if (stamped !== text5) fs62.writeFileSync(card.file, stamped);
21707
+ if (stamped !== text5) fs63.writeFileSync(card.file, stamped);
21585
21708
  }
21586
21709
  }
21587
21710
  function unfinishedDelivery(id) {
@@ -21597,7 +21720,7 @@ function unfinishedDelivery(id) {
21597
21720
  }[gap];
21598
21721
  return `#${id} is not finished: ${what}.`;
21599
21722
  }
21600
- const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs62.existsSync(path65.join(ASSETS, src.slice(".assets/".length))));
21723
+ const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs63.existsSync(path67.join(ASSETS, src.slice(".assets/".length))));
21601
21724
  return missing ? `#${id} is not finished: ${missing} is not on this machine.` : null;
21602
21725
  }
21603
21726
  function agentDecisions(text5) {
@@ -21624,8 +21747,8 @@ function removeCard2(id, metric, options) {
21624
21747
  const unfinished = metric === "completed" ? unfinishedDelivery(id) : null;
21625
21748
  if (unfinished) die(unfinished, { kind: "plan-delivery-unfinished" });
21626
21749
  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") : "";
21750
+ const cardFile3 = found2.kind === "group" ? path67.join(found2.target, "root.md") : found2.target;
21751
+ const cardText = fs63.existsSync(cardFile3) ? fs63.readFileSync(cardFile3, "utf8") : "";
21629
21752
  const { meta: cardMeta3 } = parseFrontmatter(cardText);
21630
21753
  const alsoRemoved = found2.kind === "group" ? walkMd(found2.target).filter((f) => f !== cardFile3).map((f) => rel(f)).sort() : [];
21631
21754
  const leftIds = leavingIds(id, found2);
@@ -21656,10 +21779,10 @@ function removeCard2(id, metric, options) {
21656
21779
  const groupRoot = found2.kind === "file" && !options.closing ? enclosingGroupRoot(found2.target) : null;
21657
21780
  if (dest) {
21658
21781
  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);
21782
+ fs63.mkdirSync(ARCHIVE, { recursive: true });
21783
+ fs63.renameSync(found2.target, dest);
21661
21784
  } else {
21662
- fs62.rmSync(found2.target, { recursive: true, force: true });
21785
+ fs63.rmSync(found2.target, { recursive: true, force: true });
21663
21786
  }
21664
21787
  const removedRefs = stripReadmeRefs(found2);
21665
21788
  let marked2 = null;
@@ -21708,14 +21831,14 @@ function removeCard2(id, metric, options) {
21708
21831
  };
21709
21832
  }
21710
21833
  function closeGroup(rootFile) {
21711
- const rootId = idPrefix(path65.basename(path65.dirname(rootFile)));
21834
+ const rootId = idPrefix(path67.basename(path67.dirname(rootFile)));
21712
21835
  if (rootId === null) return null;
21713
21836
  if (runnerProject(KANBAN)) return null;
21714
21837
  if (!groupCloses(rootFile)) return null;
21715
21838
  say(`
21716
21839
  every subtask line on #${rootId} is resolved \u2014 closing the group:`);
21717
21840
  try {
21718
- const { meta, body } = parseFrontmatter(fs62.readFileSync(rootFile, "utf8"));
21841
+ const { meta, body } = parseFrontmatter(fs63.readFileSync(rootFile, "utf8"));
21719
21842
  const res = cmdRemove(rootId, "completed", { closing: true });
21720
21843
  return {
21721
21844
  id: rootId,
@@ -21772,7 +21895,7 @@ function cleanupDiscardedCards(sessionId) {
21772
21895
  if (card.pending) throw new Error(`Discarding #${card.id} did not finish. Retry the discard.`);
21773
21896
  while (locate(card.id)) cmdRemove(card.id, "rejected", { discard: true, cleanupDiscarded: true });
21774
21897
  dropCrossRefs(card.id);
21775
- stripReadmeRefs({ kind: "file", rel: path65.relative(TODO, path65.resolve(REPO_ROOT, card.path)).split(path65.sep).join("/") });
21898
+ stripReadmeRefs({ kind: "file", rel: path67.relative(TODO, path67.resolve(REPO_ROOT, card.path)).split(path67.sep).join("/") });
21776
21899
  }
21777
21900
  return discarded.map((c) => c.id);
21778
21901
  });
@@ -21858,8 +21981,8 @@ var init_memory_file = __esm({
21858
21981
  });
21859
21982
 
21860
21983
  // src/commands/rule.ts
21861
- import fs63 from "node:fs";
21862
- import path66 from "node:path";
21984
+ import fs64 from "node:fs";
21985
+ import path68 from "node:path";
21863
21986
  function cmdRule(askedName, flags) {
21864
21987
  const agent = askedName.trim();
21865
21988
  if (!agentRoster().some((a) => a.name === agent)) {
@@ -21868,7 +21991,7 @@ function cmdRule(askedName, flags) {
21868
21991
  const rule = readRuleText(flags.file, flags.text);
21869
21992
  const res = setAgentRule(agent, rule);
21870
21993
  if (!res.ok) die(res.error);
21871
- const file = rel(path66.join(RULES, `${agent}.md`));
21994
+ const file = rel(path68.join(RULES, `${agent}.md`));
21872
21995
  say(rule ? `wrote the \`${agent}\` rule (${file})` : `cleared the \`${agent}\` rule`);
21873
21996
  return { agent, file, cleared: !rule };
21874
21997
  }
@@ -21876,7 +21999,7 @@ function readRuleText(file, text5) {
21876
21999
  if (file !== void 0 && text5 !== void 0) die("pass --file or --text, not both");
21877
22000
  if (file !== void 0) {
21878
22001
  try {
21879
- return fs63.readFileSync(file, "utf8").trim();
22002
+ return fs64.readFileSync(file, "utf8").trim();
21880
22003
  } catch {
21881
22004
  die(`can't read ${file} \u2014 write the rule to a file, then pass its path`);
21882
22005
  }
@@ -22003,22 +22126,22 @@ var init_storyboard = __esm({
22003
22126
  });
22004
22127
 
22005
22128
  // src/lib/spec-contract.ts
22006
- import fs64 from "node:fs";
22007
- import path67 from "node:path";
22129
+ import fs65 from "node:fs";
22130
+ import path69 from "node:path";
22008
22131
  function snapshotSpecs() {
22009
22132
  const out = /* @__PURE__ */ new Map();
22010
- if (!fs64.existsSync(TODO)) return out;
22133
+ if (!fs65.existsSync(TODO)) return out;
22011
22134
  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") });
22135
+ if (isLegacyRecurring(path69.relative(TODO, file))) continue;
22136
+ const id = idPrefix(path69.basename(file) === "root.md" ? path69.basename(path69.dirname(file)) : path69.basename(file));
22137
+ if (id !== null) out.set(file, { id, text: fs65.readFileSync(file, "utf8") });
22015
22138
  }
22016
22139
  return out;
22017
22140
  }
22018
22141
  function enclosingGroups(file) {
22019
22142
  const ids = [];
22020
22143
  for (let root = enclosingGroupRoot(file); root; root = enclosingGroupRoot(root)) {
22021
- const id = idPrefix(path67.basename(path67.dirname(root)));
22144
+ const id = idPrefix(path69.basename(path69.dirname(root)));
22022
22145
  if (id !== null) ids.push(id);
22023
22146
  }
22024
22147
  return ids;
@@ -22187,9 +22310,9 @@ function validateSpec(file, text5, id) {
22187
22310
  }
22188
22311
  function inside(dir, name) {
22189
22312
  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;
22313
+ const root = fs65.realpathSync(dir);
22314
+ const real2 = fs65.realpathSync(path69.join(dir, name));
22315
+ return real2.startsWith(root + path69.sep) && fs65.statSync(real2).isFile() ? real2 : null;
22193
22316
  } catch {
22194
22317
  return null;
22195
22318
  }
@@ -22207,7 +22330,7 @@ function variantsProblem(raw, src, id) {
22207
22330
  if (files2.length < 2 || !files2.every((f) => typeof f === "string" && f)) return `variants needs at least two labels, each naming a file. ${shape}`;
22208
22331
  if (!files2.includes(src)) return `src="${src}" is not one of the variants. Set src to the version shown first.`;
22209
22332
  if (id === void 0) return null;
22210
- const dir = path67.join(ASSETS, String(id));
22333
+ const dir = path69.join(ASSETS, String(id));
22211
22334
  for (const f of files2) {
22212
22335
  const parts = f.split("/");
22213
22336
  if (parts.length !== 3 || parts[0] !== ".assets" || parts[1] !== String(id) || !inside(dir, parts[2])) {
@@ -22217,7 +22340,7 @@ function variantsProblem(raw, src, id) {
22217
22340
  return null;
22218
22341
  }
22219
22342
  function compareProblem(attrs, id) {
22220
- const dir = path67.join(ASSETS, String(id));
22343
+ const dir = path69.join(ASSETS, String(id));
22221
22344
  const src = (message) => ({ rule: "compare-src", message });
22222
22345
  const shots = (message) => ({ rule: "compare-shots", message });
22223
22346
  for (const side of ["a", "b"]) {
@@ -22237,7 +22360,7 @@ function compareProblem(attrs, id) {
22237
22360
  const file = inside(dir, named2.name);
22238
22361
  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
22362
  try {
22240
- return { data: JSON.parse(fs64.readFileSync(file, "utf8")) };
22363
+ return { data: JSON.parse(fs65.readFileSync(file, "utf8")) };
22241
22364
  } catch {
22242
22365
  return { message: `${at} is not valid JSON.` };
22243
22366
  }
@@ -22257,7 +22380,7 @@ function compareProblem(attrs, id) {
22257
22380
  }
22258
22381
  function validateStoryboards(file, id, text5) {
22259
22382
  const errors = [];
22260
- const dir = path67.join(ASSETS, String(id));
22383
+ const dir = path69.join(ASSETS, String(id));
22261
22384
  for (const marker of storyboardMarkers(text5)) {
22262
22385
  const named2 = assetName(marker.src, id, ["json"]);
22263
22386
  const add = (message) => errors.push({ file: rel(file), line: marker.line, rule: "storyboard-src", message });
@@ -22406,8 +22529,8 @@ var init_mockups = __esm({
22406
22529
  });
22407
22530
 
22408
22531
  // src/commands/spec-write.ts
22409
- import fs65 from "node:fs";
22410
- import path68 from "node:path";
22532
+ import fs66 from "node:fs";
22533
+ import path70 from "node:path";
22411
22534
  function cmdSpecWrite(id, askedName, flags) {
22412
22535
  const agent = findSpecAgent(askedName);
22413
22536
  if (!agent) die(notAnAgent(askedName), { kind: "no-such-spec-agent", specAgent: askedName });
@@ -22415,11 +22538,11 @@ function cmdSpecWrite(id, askedName, flags) {
22415
22538
  const section = readSection(flags.file, flags.text);
22416
22539
  const found2 = locate(id);
22417
22540
  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"));
22541
+ const file = found2.kind === "group" ? path70.join(found2.target, "root.md") : found2.target;
22542
+ const { meta, body } = parseFrontmatter(fs66.readFileSync(file, "utf8"));
22420
22543
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
22421
22544
  const { body: next, replaced } = splice(body, name, section);
22422
- fs65.writeFileSync(file, serializeFrontmatter(meta) + "\n" + next);
22545
+ fs66.writeFileSync(file, serializeFrontmatter(meta) + "\n" + next);
22423
22546
  say(`${replaced ? "rewrote" : "wrote"} the \`${name}\` section on #${id} (${rel(file)})`);
22424
22547
  return { id, specAgent: name, replaced, file: rel(file) };
22425
22548
  }
@@ -22428,7 +22551,7 @@ function readSection(file, text5) {
22428
22551
  let raw;
22429
22552
  if (file !== void 0) {
22430
22553
  try {
22431
- raw = fs65.readFileSync(file, "utf8");
22554
+ raw = fs66.readFileSync(file, "utf8");
22432
22555
  } catch {
22433
22556
  die(`can't read ${file} \u2014 write your section to a file, then pass its path`);
22434
22557
  }
@@ -22622,7 +22745,7 @@ function localBoard() {
22622
22745
  const no = checkWrite({ board: true }, env2, boardRevision());
22623
22746
  if (no) return no;
22624
22747
  const res = await resumeDelivery(deliveryId);
22625
- if (!res.ok) return opRefused(new Error(res.error || "the delivery could not be carried on"));
22748
+ if (!res.ok) return { ...opRefused(new Error(res.error || "the delivery could not be carried on")), reason: res.reason, args: res.args };
22626
22749
  return opOk(boardRevision(), { deliveryId: res.deliveryId, landed: res.landed, carryOn: res.carryOn });
22627
22750
  },
22628
22751
  async discardDelivery(deliveryId, env2) {
@@ -22894,11 +23017,11 @@ var init_shared = __esm({
22894
23017
  });
22895
23018
 
22896
23019
  // src/commands/goal.ts
22897
- import fs66 from "node:fs";
23020
+ import fs67 from "node:fs";
22898
23021
  function load() {
22899
23022
  const file = goalsFile();
22900
23023
  if (!file) die("Goals exist only inside a WildCrane goal discussion.");
22901
- const held4 = JSON.parse(fs66.readFileSync(file, "utf8"));
23024
+ const held4 = JSON.parse(fs67.readFileSync(file, "utf8"));
22902
23025
  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
23026
  const goals = held4.goals ?? held4.ideas;
22904
23027
  if (!Array.isArray(goals)) die("The goals array is missing or invalid.");
@@ -22923,7 +23046,7 @@ function splitBody2(text5) {
22923
23046
  }
22924
23047
  function readBody(bodyFile) {
22925
23048
  if (!bodyFile) die("--body-file is required; write the goal in a writable temporary file first.");
22926
- const text5 = fs66.readFileSync(bodyFile, "utf8");
23049
+ const text5 = fs67.readFileSync(bodyFile, "utf8");
22927
23050
  if (!text5.trim()) die("The goal must not be empty.");
22928
23051
  return splitBody2(text5);
22929
23052
  }
@@ -22935,7 +23058,7 @@ function named(held4, id) {
22935
23058
  function cmdGoal(args, opts) {
22936
23059
  const sub = args[0] ?? "";
22937
23060
  const { file, held: held4 } = load();
22938
- const write2 = () => fs66.writeFileSync(file, `${JSON.stringify({ workflows: held4.workflows, ideas: held4.goals }, null, 2)}
23061
+ const write2 = () => fs67.writeFileSync(file, `${JSON.stringify({ workflows: held4.workflows, ideas: held4.goals }, null, 2)}
22939
23062
  `);
22940
23063
  if (sub === "new") {
22941
23064
  const title = opts.title?.trim();
@@ -23005,8 +23128,8 @@ __export(board_exports, {
23005
23128
  buildBoardProgram: () => buildBoardProgram
23006
23129
  });
23007
23130
  import crypto4 from "node:crypto";
23008
- import fs67 from "node:fs";
23009
- import path69 from "node:path";
23131
+ import fs68 from "node:fs";
23132
+ import path71 from "node:path";
23010
23133
  async function dispatch(move2, cmd, args, opts, cli) {
23011
23134
  const ctx = ctxOf(cmd, cli.program);
23012
23135
  const data = await runAction(ctx, {}, async () => {
@@ -23045,7 +23168,7 @@ async function cloudCard(task, opts) {
23045
23168
  let request;
23046
23169
  if (typeof opts.bodyFile === "string") {
23047
23170
  try {
23048
- request = fs67.readFileSync(opts.bodyFile, "utf8");
23171
+ request = fs68.readFileSync(opts.bodyFile, "utf8");
23049
23172
  } catch {
23050
23173
  }
23051
23174
  }
@@ -23075,7 +23198,7 @@ async function cloudCard(task, opts) {
23075
23198
  const file = creationReceipt(`${checked.value}:${requestId}`, slot);
23076
23199
  const journal = readCreation(file, said3);
23077
23200
  if (!journal.made) {
23078
- const key = `akb-${path69.basename(file, ".json").slice(0, 40)}`;
23201
+ const key = `akb-${path71.basename(file, ".json").slice(0, 40)}`;
23079
23202
  const made = await createProjectTask(checked.value, journal.said, key);
23080
23203
  if (!made.ok) throw new BoardError(creationError(`Cloud did not make the task: ${made.error}`, triage), { kind: "refused" });
23081
23204
  journal.made = made.value;
@@ -23220,16 +23343,16 @@ var init_board2 = __esm({
23220
23343
  });
23221
23344
 
23222
23345
  // src/lib/board-cli.ts
23223
- import fs68 from "node:fs";
23224
- import path70 from "node:path";
23346
+ import fs69 from "node:fs";
23347
+ import path72 from "node:path";
23225
23348
  function useBoard(found2, dirNamed) {
23226
- if (!found2.named && found2.board === path70.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23349
+ if (!found2.named && found2.board === path72.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23227
23350
  else setBoardDir(found2.board, found2.root);
23228
23351
  useProjectState();
23229
23352
  }
23230
23353
  function whole(found2, move2) {
23231
23354
  if (move2 === MAKES_A_BOARD) return found2;
23232
- if (!fs68.existsSync(path70.join(found2.board, "todo"))) {
23355
+ if (!fs69.existsSync(path72.join(found2.board, "todo"))) {
23233
23356
  die(`the board in ${found2.board} has no todo/ \u2014 run \`init\` to add what is missing.`, {
23234
23357
  kind: "board-incomplete",
23235
23358
  dir: found2.root
@@ -23238,13 +23361,13 @@ function whole(found2, move2) {
23238
23361
  return found2;
23239
23362
  }
23240
23363
  function findBoardUpward(from, move2) {
23241
- let dir = path70.resolve(from);
23364
+ let dir = path72.resolve(from);
23242
23365
  for (; ; ) {
23243
- if (hasBoard(dir)) return { root: dir, board: path70.join(dir, "docs", "kanban") };
23366
+ if (hasBoard(dir)) return { root: dir, board: path72.join(dir, "docs", "kanban") };
23244
23367
  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);
23368
+ const kept2 = path72.join(dir, ".akb", "kanban");
23369
+ if (move2 !== MAKES_A_BOARD && fs69.existsSync(path72.join(kept2, "todo"))) return { root: dir, board: kept2 };
23370
+ const up = path72.dirname(dir);
23248
23371
  if (up === dir) return null;
23249
23372
  dir = up;
23250
23373
  }
@@ -23252,11 +23375,11 @@ function findBoardUpward(from, move2) {
23252
23375
  function resolveBoard(move2, { board: board2, dir, cwd, installHint }) {
23253
23376
  const named2 = board2 ?? boardFromEnv();
23254
23377
  if (named2) {
23255
- const folder = path70.resolve(cwd, named2);
23256
- if (!fs68.existsSync(folder) && move2 !== MAKES_A_BOARD) {
23378
+ const folder = path72.resolve(cwd, named2);
23379
+ if (!fs69.existsSync(folder) && move2 !== MAKES_A_BOARD) {
23257
23380
  die(`no such folder: ${folder}`, { kind: "no-such-folder", dir: folder });
23258
23381
  }
23259
- if (fs68.existsSync(folder) && !isBoardDir(folder) && move2 !== MAKES_A_BOARD) {
23382
+ if (fs69.existsSync(folder) && !isBoardDir(folder) && move2 !== MAKES_A_BOARD) {
23260
23383
  die(`${folder} is not a board \u2014 it has no todo/ and config.md. ${installHint}\u3002`, {
23261
23384
  kind: "no-board",
23262
23385
  dir: folder
@@ -23265,24 +23388,24 @@ function resolveBoard(move2, { board: board2, dir, cwd, installHint }) {
23265
23388
  return { root: projectRootOf(folder), board: folder, named: true };
23266
23389
  }
23267
23390
  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);
23391
+ const root = path72.resolve(dir);
23392
+ if (!fs69.existsSync(root)) die(`no such folder: ${root}`, { kind: "no-such-folder", dir: root });
23393
+ const kept2 = path72.join(root, ".akb", "kanban");
23394
+ if (!hasBoard(root) && move2 !== MAKES_A_BOARD && fs69.existsSync(path72.join(kept2, "todo"))) return whole({ root, board: kept2 }, move2);
23272
23395
  if (!hasBoard(root) && move2 !== MAKES_A_BOARD) {
23273
23396
  die(`no board in ${root} \u2014 it has no docs/kanban/. ${installHint}\u3002`, {
23274
23397
  kind: "no-board",
23275
23398
  dir: root
23276
23399
  });
23277
23400
  }
23278
- return whole({ root, board: path70.join(root, "docs", "kanban") }, move2);
23401
+ return whole({ root, board: path72.join(root, "docs", "kanban") }, move2);
23279
23402
  }
23280
23403
  const found2 = findBoardUpward(cwd, move2);
23281
23404
  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") };
23405
+ if (move2 === MAKES_A_BOARD) return { root: path72.resolve(cwd), board: path72.join(path72.resolve(cwd), "docs", "kanban") };
23283
23406
  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) }
23407
+ `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`,
23408
+ { kind: "no-board", dir: path72.resolve(cwd) }
23286
23409
  );
23287
23410
  }
23288
23411
  function editDistance(a, b) {
@@ -23364,8 +23487,8 @@ var init_board_cli = __esm({
23364
23487
  init_io();
23365
23488
  init_pointer();
23366
23489
  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"));
23490
+ hasBoard = (dir) => fs69.existsSync(path72.join(dir, "docs", "kanban"));
23491
+ isBoardDir = (dir) => fs69.existsSync(path72.join(dir, "todo")) && fs69.existsSync(path72.join(dir, "config.md"));
23369
23492
  boardFromEnv = () => {
23370
23493
  const named2 = process.env.AI4KANBAN_BOARD?.trim();
23371
23494
  return named2 ? named2 : null;
@@ -23632,8 +23755,8 @@ var init_guide = __esm({
23632
23755
  });
23633
23756
 
23634
23757
  // src/lib/agent/approve.ts
23635
- import fs74 from "node:fs";
23636
- import path76 from "node:path";
23758
+ import fs75 from "node:fs";
23759
+ import path78 from "node:path";
23637
23760
  function approvalRequest(req) {
23638
23761
  const id = req.id;
23639
23762
  const card = id === void 0 ? null : findCard(id);
@@ -23651,12 +23774,12 @@ function advancePhase(id) {
23651
23774
  const card = findCard(id);
23652
23775
  const found2 = locate(id);
23653
23776
  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"));
23777
+ const file = found2.kind === "group" ? path78.join(found2.target, "root.md") : found2.target;
23778
+ const { meta, body } = parseFrontmatter(fs75.readFileSync(file, "utf8"));
23656
23779
  if (!meta) return { error: `#${id} has no frontmatter` };
23657
23780
  meta.phase = card.stage + 1;
23658
23781
  meta.status = "todo";
23659
- fs74.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
23782
+ fs75.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
23660
23783
  return null;
23661
23784
  }
23662
23785
  var init_approve = __esm({
@@ -23760,8 +23883,8 @@ function open2(req, sessionId) {
23760
23883
  markSpawned(run2.sessionId, pid);
23761
23884
  return { run: run2, spawned: pid !== void 0 };
23762
23885
  }
23763
- async function startResume(id, build) {
23764
- const opened = await openResume(id, build);
23886
+ async function startResume(id, options) {
23887
+ const opened = await openResume(id, options);
23765
23888
  if ("error" in opened) return opened;
23766
23889
  const pid = spawnWatcher(opened.run.sessionId);
23767
23890
  markSpawned(opened.run.sessionId, pid);
@@ -23787,16 +23910,16 @@ var init_start = __esm({
23787
23910
  });
23788
23911
 
23789
23912
  // src/lib/agent/task-chats.ts
23790
- import fs75 from "node:fs";
23791
- import path77 from "node:path";
23913
+ import fs76 from "node:fs";
23914
+ import path79 from "node:path";
23792
23915
  function taskChatFile(task, home3) {
23793
23916
  if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
23794
- return path77.join(taskChatsDir(home3), `${task}.jsonl`);
23917
+ return path79.join(taskChatsDir(home3), `${task}.jsonl`);
23795
23918
  }
23796
23919
  function readTaskChat(task, home3) {
23797
23920
  let text5;
23798
23921
  try {
23799
- text5 = fs75.readFileSync(taskChatFile(task, home3), "utf8");
23922
+ text5 = fs76.readFileSync(taskChatFile(task, home3), "utf8");
23800
23923
  } catch {
23801
23924
  return [];
23802
23925
  }
@@ -23817,13 +23940,13 @@ var init_task_chats = __esm({
23817
23940
  "use strict";
23818
23941
  init_home();
23819
23942
  TASK = /^[\w-]{1,100}$/;
23820
- taskChatsDir = (home3 = machineHome()) => path77.join(home3, "chats");
23943
+ taskChatsDir = (home3 = machineHome()) => path79.join(home3, "chats");
23821
23944
  }
23822
23945
  });
23823
23946
 
23824
23947
  // src/lib/agent/memory-review.ts
23825
- import fs76 from "node:fs";
23826
- import path78 from "node:path";
23948
+ import fs77 from "node:fs";
23949
+ import path80 from "node:path";
23827
23950
  function taskChatsToReview(tasks) {
23828
23951
  const out = [];
23829
23952
  for (const ref of [...new Set(tasks)]) {
@@ -23845,8 +23968,8 @@ function readArchived2(id) {
23845
23968
  const found2 = Number.isInteger(id) && id > 0 ? locateArchived(id) : null;
23846
23969
  if (!found2) return null;
23847
23970
  try {
23848
- const file = found2.kind === "group" ? path78.join(found2.target, "root.md") : found2.target;
23849
- const { meta, body } = parseFrontmatter(fs76.readFileSync(file, "utf8"));
23971
+ const file = found2.kind === "group" ? path80.join(found2.target, "root.md") : found2.target;
23972
+ const { meta, body } = parseFrontmatter(fs77.readFileSync(file, "utf8"));
23850
23973
  if (!meta) return null;
23851
23974
  return { id, title: meta.title, modules: meta.modules ?? [], rejected: meta.rejected, body };
23852
23975
  } catch {
@@ -23915,17 +24038,17 @@ var init_memory_review = __esm({
23915
24038
  });
23916
24039
 
23917
24040
  // src/lib/agent/dismissal-review.ts
23918
- import fs77 from "node:fs";
23919
- import path79 from "node:path";
24041
+ import fs78 from "node:fs";
24042
+ import path81 from "node:path";
23920
24043
  function rejectionsToReview() {
23921
- const dir = path79.join(ARCHIVE, REJECTIONS_TO_REVIEW);
23922
- if (!fs77.existsSync(dir)) return [];
24044
+ const dir = path81.join(ARCHIVE, REJECTIONS_TO_REVIEW);
24045
+ if (!fs78.existsSync(dir)) return [];
23923
24046
  const found2 = [];
23924
24047
  for (const file of walkMd(dir)) {
23925
24048
  const id = archivedId(file);
23926
24049
  if (id === null) continue;
23927
24050
  try {
23928
- const { meta } = parseFrontmatter(fs77.readFileSync(file, "utf8"));
24051
+ const { meta } = parseFrontmatter(fs78.readFileSync(file, "utf8"));
23929
24052
  if (!meta?.rejected || meta.rejected_by !== "user" || !meta.rejected_reason.trim()) continue;
23930
24053
  found2.push({ id, title: meta.title, file: rel(file), reason: meta.rejected_reason.trim(), rejectedAt: meta.rejected_at });
23931
24054
  } catch {
@@ -23955,7 +24078,7 @@ function citedSources(text5) {
23955
24078
  function withdrawnSources() {
23956
24079
  const cited = [...new Set(plannerCopies("rejected.md").flatMap((file) => {
23957
24080
  try {
23958
- return citedSources(fs77.readFileSync(file, "utf8"));
24081
+ return citedSources(fs78.readFileSync(file, "utf8"));
23959
24082
  } catch {
23960
24083
  return [];
23961
24084
  }
@@ -23980,8 +24103,8 @@ var init_dismissal_review = __esm({
23980
24103
  });
23981
24104
 
23982
24105
  // src/lib/agent/flow.ts
23983
- import fs78 from "node:fs";
23984
- import path80 from "node:path";
24106
+ import fs79 from "node:fs";
24107
+ import path82 from "node:path";
23985
24108
  function readCard2(id, home3 = "board") {
23986
24109
  const found2 = home3 === "archive" ? locateArchived(id) : locate(id);
23987
24110
  if (!found2) {
@@ -23990,10 +24113,10 @@ function readCard2(id, home3 = "board") {
23990
24113
  { kind: "card-not-found", id }
23991
24114
  );
23992
24115
  }
23993
- const file = found2.kind === "group" ? path80.join(found2.target, "root.md") : found2.target;
24116
+ const file = found2.kind === "group" ? path82.join(found2.target, "root.md") : found2.target;
23994
24117
  let text5;
23995
24118
  try {
23996
- text5 = fs78.readFileSync(file, "utf8");
24119
+ text5 = fs79.readFileSync(file, "utf8");
23997
24120
  } catch {
23998
24121
  die(`#${id} is on the board but ${rel(file)} can't be read.`, { kind: "card-unreadable", id });
23999
24122
  }
@@ -24117,7 +24240,7 @@ function workspaceField(delivery) {
24117
24240
  if (!delivery?.worktree) return [];
24118
24241
  return field("workspace", [
24119
24242
  `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.`,
24243
+ 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
24244
  `every board command names the project's own copy: \`${boardCommandFor()} <command>\`.`,
24122
24245
  `${rel(REPO_ROOT)} is the project \u2014 the card, the memory files and the docs are changed there, not here.`
24123
24246
  ]);
@@ -24856,7 +24979,7 @@ __export(watch_exports, {
24856
24979
  watchRun: () => watchRun
24857
24980
  });
24858
24981
  import { spawn as spawn4 } from "node:child_process";
24859
- import fs79 from "node:fs";
24982
+ import fs80 from "node:fs";
24860
24983
  async function watchRun(sessionId, resume = startResume) {
24861
24984
  const spec = readSpec(sessionId);
24862
24985
  const run2 = peekRun(sessionId);
@@ -24892,11 +25015,11 @@ async function watchRun(sessionId, resume = startResume) {
24892
25015
  const record = claimed ?? run2;
24893
25016
  const sub = record.action === "sub";
24894
25017
  if (claim) await setCardStatus(claim.cardId, claim.status);
24895
- fs79.mkdirSync(SESSIONS_DIR, { recursive: true });
24896
- const logFile = fs79.createWriteStream(record.logPath, { flags: "a" });
25018
+ fs80.mkdirSync(SESSIONS_DIR, { recursive: true });
25019
+ const logFile = fs80.createWriteStream(record.logPath, { flags: "a" });
24897
25020
  logFile.on("error", () => {
24898
25021
  });
24899
- const eventsFile = fs79.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
25022
+ const eventsFile = fs80.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
24900
25023
  eventsFile.on("error", () => {
24901
25024
  });
24902
25025
  const event2 = (e) => eventsFile.write(`${JSON.stringify(e)}
@@ -25484,7 +25607,7 @@ var init_watch = __esm({
25484
25607
  });
25485
25608
 
25486
25609
  // src/kanban.ts
25487
- import fs85 from "node:fs";
25610
+ import fs86 from "node:fs";
25488
25611
  import { fileURLToPath as fileURLToPath3 } from "node:url";
25489
25612
 
25490
25613
  // src/lib/cli/agent.ts
@@ -25973,8 +26096,8 @@ async function testAgent(args) {
25973
26096
  }
25974
26097
 
25975
26098
  // src/commands/cloud.ts
25976
- import fs70 from "node:fs";
25977
- import path72 from "node:path";
26099
+ import fs71 from "node:fs";
26100
+ import path74 from "node:path";
25978
26101
 
25979
26102
  // src/lib/cloud/avatar.ts
25980
26103
  init_session();
@@ -26022,13 +26145,13 @@ init_config();
26022
26145
  init_home();
26023
26146
  init_config();
26024
26147
  init_session();
26025
- import fs69 from "node:fs";
26026
- import path71 from "node:path";
26148
+ import fs70 from "node:fs";
26149
+ import path73 from "node:path";
26027
26150
  var FRESH_MS = 10 * 6e4;
26028
26151
  var GRACE_MS = 7 * 24 * 60 * 6e4;
26029
- var heldFile = () => path71.join(machineHome(), "pro.json");
26152
+ var heldFile = () => path73.join(machineHome(), "pro.json");
26030
26153
  function forgetPro() {
26031
- fs69.rmSync(heldFile(), { force: true });
26154
+ fs70.rmSync(heldFile(), { force: true });
26032
26155
  }
26033
26156
 
26034
26157
  // src/lib/cloud/account.ts
@@ -26205,10 +26328,10 @@ async function cloudImage(opts, program2) {
26205
26328
  const prompt = opts.prompt.trim();
26206
26329
  if (!prompt) usage("Missing the prompt.", line);
26207
26330
  const references = opts.refs.map((file) => {
26208
- const type = REF_TYPES[path72.extname(file).toLowerCase()];
26331
+ const type = REF_TYPES[path74.extname(file).toLowerCase()];
26209
26332
  if (!type) usage(`--ref ${file}: use a PNG, JPEG or WebP file.`, line);
26210
26333
  try {
26211
- return `data:${type};base64,${fs70.readFileSync(file).toString("base64")}`;
26334
+ return `data:${type};base64,${fs71.readFileSync(file).toString("base64")}`;
26212
26335
  } catch (e) {
26213
26336
  usage(`--ref ${file}: ${e instanceof Error ? e.message : String(e)}`, line);
26214
26337
  }
@@ -26314,31 +26437,31 @@ async function generate(g) {
26314
26437
  refuse(g.failed, g.fallback);
26315
26438
  }
26316
26439
  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()));
26440
+ fs71.mkdirSync(path74.dirname(path74.resolve(out)), { recursive: true });
26441
+ fs71.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
26319
26442
  say(`${out} (${g.label(res)})`);
26320
26443
  return { out };
26321
26444
  }
26322
26445
 
26323
26446
  // src/commands/cloud-import.ts
26324
26447
  import crypto5 from "node:crypto";
26325
- import fs72 from "node:fs";
26326
- import path74 from "node:path";
26448
+ import fs73 from "node:fs";
26449
+ import path76 from "node:path";
26327
26450
 
26328
26451
  // ../cloud/src/board-files.ts
26329
26452
  var ROOTS = ["todo/", ".archive/", "memory/", "workflows/", "triage/", "assets/", "rules/"];
26330
26453
  var SETTINGS = ["modules.md", "config.md"];
26331
- var isSettingsPath = (path86) => SETTINGS.includes(path86) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path86);
26454
+ var isSettingsPath = (path88) => SETTINGS.includes(path88) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path88);
26332
26455
  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");
26456
+ function isBoardPath(path88) {
26457
+ if (!path88 || path88.length > 500 || path88.startsWith("/") || path88.includes("\\") || path88.includes("\0")) return false;
26458
+ if (path88.split("/").some((part) => !part || part === "." || part === "..")) return false;
26459
+ if (path88 === "todo/README.md" || path88.split("/").includes(".sync")) return false;
26460
+ if (path88.startsWith("workflows/")) return true;
26461
+ if (SETTINGS.includes(path88)) return true;
26462
+ if (path88.startsWith("rules/")) return isSettingsPath(path88);
26463
+ if (path88.startsWith("assets/")) return path88.endsWith(".json");
26464
+ return ROOTS.some((root) => path88.startsWith(root)) && path88.endsWith(".md");
26342
26465
  }
26343
26466
  var workflowFolder = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
26344
26467
 
@@ -26442,8 +26565,8 @@ init_bundled();
26442
26565
  // src/lib/agents/shared-memory.ts
26443
26566
  init_bundled();
26444
26567
  init_parse();
26445
- import fs71 from "node:fs";
26446
- import path73 from "node:path";
26568
+ import fs72 from "node:fs";
26569
+ import path75 from "node:path";
26447
26570
  function sharedMemory(board2) {
26448
26571
  const declared = /* @__PURE__ */ new Map();
26449
26572
  const take = (folder, text5, builtIn) => {
@@ -26455,16 +26578,16 @@ function sharedMemory(board2) {
26455
26578
  const at = /^([^/]+)\/AGENT\.md$/.exec(key);
26456
26579
  if (at) take(at[1], text5, true);
26457
26580
  }
26458
- const root = path73.join(board2, "agents");
26581
+ const root = path75.join(board2, "agents");
26459
26582
  let folders2 = [];
26460
26583
  try {
26461
- folders2 = fs71.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
26584
+ folders2 = fs72.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
26462
26585
  } catch {
26463
26586
  }
26464
26587
  for (const folder of folders2.sort()) {
26465
26588
  let text5 = null;
26466
26589
  try {
26467
- text5 = fs71.readFileSync(path73.join(root, folder, "AGENT.md"), "utf8");
26590
+ text5 = fs72.readFileSync(path75.join(root, folder, "AGENT.md"), "utf8");
26468
26591
  } catch {
26469
26592
  }
26470
26593
  take(folder, text5, false);
@@ -26553,24 +26676,24 @@ async function findProject(asked) {
26553
26676
  }
26554
26677
  throw new Refused(`No project of yours has the id or prefix "${asked}".`, "not_found");
26555
26678
  }
26556
- var read = (file) => fs72.readFileSync(file, "utf8");
26679
+ var read = (file) => fs73.readFileSync(file, "utf8");
26557
26680
  var bytes2 = (text5) => Buffer.byteLength(text5, "utf8");
26558
26681
  function files(dir) {
26559
- if (!fs72.existsSync(dir)) return [];
26682
+ if (!fs73.existsSync(dir)) return [];
26560
26683
  const out = [];
26561
- for (const entry of fs72.readdirSync(dir, { withFileTypes: true })) {
26684
+ for (const entry of fs73.readdirSync(dir, { withFileTypes: true })) {
26562
26685
  if (entry.name.startsWith(".")) continue;
26563
- const full = path74.join(dir, entry.name);
26686
+ const full = path76.join(dir, entry.name);
26564
26687
  if (entry.isDirectory()) out.push(...files(full));
26565
26688
  else if (entry.isFile()) out.push(full);
26566
26689
  }
26567
26690
  return out;
26568
26691
  }
26569
- var posix2 = (p) => p.split(path74.sep).join("/");
26692
+ var posix2 = (p) => p.split(path76.sep).join("/");
26570
26693
  function openCards() {
26571
26694
  const out = [];
26572
26695
  for (const file of walkMd(TODO)) {
26573
- const rel2 = posix2(path74.relative(TODO, file));
26696
+ const rel2 = posix2(path76.relative(TODO, file));
26574
26697
  if (rel2 === "README.md") continue;
26575
26698
  const parts = rel2.split("/");
26576
26699
  const text5 = read(file);
@@ -26604,14 +26727,14 @@ function bodyProblems(text5) {
26604
26727
  return out;
26605
26728
  }
26606
26729
  function packWorkflow(flow) {
26607
- const own = path74.join(WORKFLOWS, flow.id);
26730
+ const own = path76.join(WORKFLOWS, flow.id);
26608
26731
  const out = {};
26609
- for (const file of files(own)) out[posix2(path74.relative(own, file))] = read(file);
26732
+ for (const file of files(own)) out[posix2(path76.relative(own, file))] = read(file);
26610
26733
  const named2 = [...flow.previews, ...flow.land, ...flow.scheduled].map((h) => h.agent).filter((a) => !LAND_ROLES.includes(a));
26611
26734
  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);
26735
+ const dir = path76.join(AGENTS, agent);
26736
+ if (fs73.existsSync(path76.join(dir, "AGENT.md"))) {
26737
+ for (const file of files(dir)) out[`agents/${agent}/${posix2(path76.relative(dir, file))}`] = read(file);
26615
26738
  continue;
26616
26739
  }
26617
26740
  for (const [key, text5] of Object.entries(BUNDLED_AGENT_FILES)) {
@@ -26663,8 +26786,8 @@ function draftsOf(text5) {
26663
26786
  const at = /^\.(assets|mockups)\/(.+)$/.exec(name);
26664
26787
  if (!at) continue;
26665
26788
  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);
26789
+ const file = path76.resolve(base, at[2]);
26790
+ if (file.startsWith(base + path76.sep) && fs73.statSync(file, { throwIfNoEntry: false })?.isFile()) out.set(name, file);
26668
26791
  }
26669
26792
  return [...out].map(([name, file]) => ({ name, file }));
26670
26793
  }
@@ -26698,9 +26821,9 @@ async function uploadDrafts(task, drafts) {
26698
26821
  const assets = {};
26699
26822
  for (const { name, file } of drafts) {
26700
26823
  if (!card.body.includes(name)) continue;
26701
- const ext = path74.extname(file).toLowerCase();
26824
+ const ext = path76.extname(file).toLowerCase();
26702
26825
  const type = TYPES[ext] ?? "application/octet-stream";
26703
- const data = fs72.readFileSync(file);
26826
+ const data = fs73.readFileSync(file);
26704
26827
  const artifact = await api("POST", `/v1/tasks/${task}/artifacts`, { type: kindOf(ext), name: name.slice(0, 200) });
26705
26828
  const upload = await api("POST", `/v1/artifacts/${artifact.id}/uploads`, { content_type: type, size: Math.max(data.length, 1) });
26706
26829
  await api("PUT", `/v1/uploads/${upload.id}`, void 0, { bytes: data, type });
@@ -26743,10 +26866,10 @@ usage: ${program2} cloud import --project <id or prefix> [--dry-run]`, { kind: "
26743
26866
  async function run(asked, dryRun) {
26744
26867
  const project = await findProject(asked);
26745
26868
  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);
26869
+ const board2 = crypto5.createHash("sha256").update(fs73.realpathSync(KANBAN)).digest("hex").slice(0, 16);
26747
26870
  const cards = openCards();
26748
26871
  const problems = [];
26749
- const where = (file) => posix2(path74.relative(KANBAN, file));
26872
+ const where = (file) => posix2(path76.relative(KANBAN, file));
26750
26873
  const own = workflows().filter((w) => !w.builtIn);
26751
26874
  const packed = /* @__PURE__ */ new Map();
26752
26875
  for (const flow of own) {
@@ -26773,7 +26896,7 @@ async function run(asked, dryRun) {
26773
26896
  const root = `projects/${project.id}/`;
26774
26897
  const boardFiles = [];
26775
26898
  for (const file of [...files(MEMORY), ...files(RULES), CONFIG, MODULES_MD]) {
26776
- if (!fs72.existsSync(file)) continue;
26899
+ if (!fs73.existsSync(file)) continue;
26777
26900
  const rel2 = where(file);
26778
26901
  if (!isBoardPath(rel2)) continue;
26779
26902
  const content = read(file);
@@ -26884,16 +27007,16 @@ async function run(asked, dryRun) {
26884
27007
  }
26885
27008
  function leftLocal(own) {
26886
27009
  const out = [];
26887
- const count4 = (dir) => fs72.existsSync(dir) ? walkMd(dir).length : 0;
27010
+ const count4 = (dir) => fs73.existsSync(dir) ? walkMd(dir).length : 0;
26888
27011
  const archived = count4(ARCHIVE);
26889
27012
  if (archived) out.push(`.archive/ (${archived})`);
26890
27013
  const triage = count4(TRIAGE);
26891
27014
  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");
27015
+ if (fs73.existsSync(DELIVERIES)) out.push("deliveries/");
27016
+ if (fs73.existsSync(path76.join(KANBAN, "metrics.csv"))) out.push("metrics.csv");
26894
27017
  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 })) {
27018
+ if (fs73.existsSync(AGENTS)) {
27019
+ for (const e of fs73.readdirSync(AGENTS, { withFileTypes: true })) {
26897
27020
  if (e.isDirectory() && !e.name.startsWith(".") && !named2.has(e.name)) out.push(`agents/${e.name}/`);
26898
27021
  }
26899
27022
  }
@@ -26911,8 +27034,8 @@ init_session();
26911
27034
  init_io();
26912
27035
  init_paths();
26913
27036
  import { createHash as createHash5 } from "node:crypto";
26914
- import fs73 from "node:fs";
26915
- import path75 from "node:path";
27037
+ import fs74 from "node:fs";
27038
+ import path77 from "node:path";
26916
27039
  var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
26917
27040
  var CAPTURED = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;
26918
27041
  var MAX_BYTES3 = 50 * 1024 * 1024;
@@ -27011,10 +27134,10 @@ This template has no preview.`);
27011
27134
  const written = [];
27012
27135
  for (const p of previews) {
27013
27136
  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);
27137
+ const file = path77.basename(p.path);
27138
+ const out = path77.join(opts.to, file.startsWith(`${name}-`) ? file : `${name}-${file}`);
27139
+ fs74.mkdirSync(opts.to, { recursive: true });
27140
+ fs74.writeFileSync(out, bytes3);
27018
27141
  written.push(out);
27019
27142
  say(out);
27020
27143
  }
@@ -27027,15 +27150,15 @@ async function templateGet(name, opts, program2) {
27027
27150
  const { template } = await asJson(await ask(`/${at}`, {}, WITHOUT));
27028
27151
  const fetched = [];
27029
27152
  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);
27153
+ const out = path77.resolve(to, f.path);
27154
+ if (!out.startsWith(path77.resolve(to) + path77.sep)) refuse2(T.corrupt, WITHOUT);
27032
27155
  const bytes3 = Buffer.from(await (await ask(`/${at}/files/${route(f.path)}`, {}, WITHOUT)).arrayBuffer());
27033
27156
  if (bytes3.byteLength !== f.size || createHash5("sha256").update(bytes3).digest("hex") !== f.sha256) {
27034
27157
  refuse2(T.corrupt, WITHOUT);
27035
27158
  }
27036
27159
  fetched.push({ out, bytes: bytes3 });
27037
27160
  }
27038
- const taken = fetched.filter((f) => fs73.existsSync(f.out)).map((f) => path75.relative(to, f.out));
27161
+ const taken = fetched.filter((f) => fs74.existsSync(f.out)).map((f) => path77.relative(to, f.out));
27039
27162
  if (taken.length > 0) {
27040
27163
  refuse2({
27041
27164
  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 +27166,8 @@ async function templateGet(name, opts, program2) {
27043
27166
  });
27044
27167
  }
27045
27168
  for (const f of fetched) {
27046
- fs73.mkdirSync(path75.dirname(f.out), { recursive: true });
27047
- fs73.writeFileSync(f.out, f.bytes);
27169
+ fs74.mkdirSync(path77.dirname(f.out), { recursive: true });
27170
+ fs74.writeFileSync(f.out, f.bytes);
27048
27171
  }
27049
27172
  say(`\u5DF2\u53D6\u56DE ${name}\uFF1A${fetched.length} \u4E2A\u6587\u4EF6\uFF0C\u4F4D\u4E8E ${to}
27050
27173
  Fetched ${name}: ${fetched.length} files into ${to}`);
@@ -27062,25 +27185,25 @@ async function templateSource(name, opts) {
27062
27185
  say(`evidence: ${e.path}`);
27063
27186
  continue;
27064
27187
  }
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()));
27188
+ const out = path77.join(opts.to, `${name}-${path77.basename(e.path)}`);
27189
+ fs74.mkdirSync(opts.to, { recursive: true });
27190
+ fs74.writeFileSync(out, Buffer.from(await (await ask(`/${at}/evidence/${route(e.path)}`)).arrayBuffer()));
27068
27191
  written.push(out);
27069
27192
  say(out);
27070
27193
  }
27071
27194
  return { name, source, evidence: written.length > 0 ? written : evidence.map((e) => e.path) };
27072
27195
  }
27073
27196
  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"));
27197
+ const root = path77.resolve(dir);
27198
+ const manifest = path77.join(root, "template.md");
27199
+ 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.");
27200
+ const meta = readTemplateMeta(fs74.readFileSync(manifest, "utf8"));
27078
27201
  const files2 = walk2(root);
27079
- const total = files2.reduce((sum, f) => sum + fs73.statSync(path75.join(root, f)).size, 0);
27202
+ const total = files2.reduce((sum, f) => sum + fs74.statSync(path77.join(root, f)).size, 0);
27080
27203
  if (total > MAX_BYTES3) invalid("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
27081
27204
  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)) {
27205
+ if (!fs74.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
27206
+ if (path77.resolve(extra).startsWith(root + path77.sep)) {
27084
27207
  invalid(
27085
27208
  `${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
27209
  `${extra} is inside the template folder; keep previews and evidence outside it.`
@@ -27092,10 +27215,10 @@ async function templatePublish(dir, opts) {
27092
27215
  }
27093
27216
  const form = new FormData();
27094
27217
  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);
27218
+ const add = (kind, name, file) => form.append(`${kind}:${name}`, new Blob([fs74.readFileSync(file)]), path77.basename(name));
27219
+ for (const f of files2) add("files", f, path77.join(root, f));
27220
+ for (const f of opts.preview) add("previews", path77.basename(f), f);
27221
+ for (const f of opts.evidence) add("evidence", path77.basename(f), f);
27099
27222
  const done2 = await asJson(await ask("", { method: "POST", body: form }));
27100
27223
  say(
27101
27224
  done2.replaced ? `\u5DF2\u66FF\u6362 ${done2.name}\uFF1A${files2.length} \u4E2A\u6587\u4EF6\u3002
@@ -27111,11 +27234,11 @@ Deleted ${name} from the catalog.`);
27111
27234
  return { name, deleted: true };
27112
27235
  }
27113
27236
  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}.`);
27237
+ const file = path77.join(dir, "showcase.json");
27238
+ if (!fs74.existsSync(file)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
27116
27239
  let meta;
27117
27240
  try {
27118
- meta = JSON.parse(fs73.readFileSync(file, "utf8"));
27241
+ meta = JSON.parse(fs74.readFileSync(file, "utf8"));
27119
27242
  } catch {
27120
27243
  return invalid("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
27121
27244
  }
@@ -27127,9 +27250,9 @@ async function templateShowcase(name, dir) {
27127
27250
  const form = new FormData();
27128
27251
  form.set("meta", JSON.stringify(meta));
27129
27252
  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);
27253
+ const at = path77.join(dir, p);
27254
+ if (!fs74.existsSync(at)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
27255
+ form.append(`media:${p}`, new Blob([fs74.readFileSync(at)]), p);
27133
27256
  }
27134
27257
  const done2 = await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form }));
27135
27258
  say(`\u5DF2\u66F4\u65B0 ${name} \u7684\u5C55\u793A\u8D44\u6599\uFF1A${done2.files} \u4E2A\u6587\u4EF6\u3002
@@ -27138,7 +27261,7 @@ Updated ${name}'s showcase: ${done2.files} files.`);
27138
27261
  }
27139
27262
  function walk2(root, sub = "") {
27140
27263
  const out = [];
27141
- for (const entry of fs73.readdirSync(path75.join(root, sub), { withFileTypes: true })) {
27264
+ for (const entry of fs74.readdirSync(path77.join(root, sub), { withFileTypes: true })) {
27142
27265
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
27143
27266
  const rel2 = sub ? `${sub}/${entry.name}` : entry.name;
27144
27267
  if (entry.isDirectory()) out.push(...walk2(root, rel2));
@@ -27423,7 +27546,7 @@ init_opencode();
27423
27546
  init_locate();
27424
27547
  init_store();
27425
27548
  import { spawnSync as spawnSync5 } from "node:child_process";
27426
- import path81 from "node:path";
27549
+ import path83 from "node:path";
27427
27550
  var AGENTS2 = {
27428
27551
  claude: "claude-code",
27429
27552
  codex: "codex",
@@ -27438,10 +27561,10 @@ var AGENTS2 = {
27438
27561
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun", "deno"]);
27439
27562
  function agentOf2(args) {
27440
27563
  const words = args.trim().split(/\s+/);
27441
- const first = path81.basename(words[0] ?? "");
27564
+ const first = path83.basename(words[0] ?? "");
27442
27565
  const script = RUNTIMES.has(first) ? words[1] ?? "" : words[0] ?? "";
27443
27566
  if (script.includes("/@anthropic-ai/claude-code/")) return "claude-code";
27444
- return AGENTS2[path81.basename(script).replace(/\.(m?js|cjs|exe)$/, "")];
27567
+ return AGENTS2[path83.basename(script).replace(/\.(m?js|cjs|exe)$/, "")];
27445
27568
  }
27446
27569
  function processChain() {
27447
27570
  if (process.platform === "win32") return [];
@@ -27505,8 +27628,8 @@ init_tasks();
27505
27628
  init_read();
27506
27629
  init_rules();
27507
27630
  init_board();
27508
- import fs80 from "node:fs";
27509
- import path82 from "node:path";
27631
+ import fs81 from "node:fs";
27632
+ import path84 from "node:path";
27510
27633
  var FOLLOW_MS = 400;
27511
27634
  async function cmdStartRun(action, args, opts, program2 = "akb") {
27512
27635
  const { req, follow: follow2, print } = readRequest(action, args, opts);
@@ -27706,13 +27829,13 @@ function readRequest(action, args, opts) {
27706
27829
  return { req, follow: follow2, print };
27707
27830
  }
27708
27831
  async function cmdResume(id, opts) {
27709
- const opened = await startResume(id ?? "last");
27832
+ const opened = await startResume(id ?? "last", opts.requireSession);
27710
27833
  if ("error" in opened) die(opened.error, { kind: "run-refused" });
27711
27834
  const { run: run2 } = opened;
27712
27835
  if (!opened.spawned) die(`couldn't start a process for run ${run2.sessionId}`, { kind: "spawn-failed" });
27713
27836
  const within = run2.deliveryId ? ` in delivery ${run2.deliveryId}` : "";
27714
27837
  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");
27838
+ if (opts.follow === true) return await followStarted(run2.sessionId, "akb", opts.events === true);
27716
27839
  return { sessionId: run2.sessionId, resumedFrom: run2.resumedFrom };
27717
27840
  }
27718
27841
  async function cmdCancel(named2) {
@@ -27726,7 +27849,10 @@ async function cmdCancel(named2) {
27726
27849
  }
27727
27850
  async function cmdResumeDelivery(named2) {
27728
27851
  const res = await resumeBoardDelivery(named2);
27729
- if (!res.ok) die(res.error ?? "that delivery could not be carried on", { kind: "run-refused" });
27852
+ if (!res.ok) die(res.error ?? "that delivery could not be carried on", {
27853
+ kind: "run-refused",
27854
+ ...res.kind === "refused" ? { reason: res.reason, args: res.args } : {}
27855
+ });
27730
27856
  if (res.landed) {
27731
27857
  say(`delivery ${res.deliveryId} is done \u2014 its changes were already on the target branch.`);
27732
27858
  return { deliveryId: res.deliveryId, landed: true };
@@ -27803,7 +27929,7 @@ async function cmdSubStart(words, opts) {
27803
27929
  let prompt = words.join(" ");
27804
27930
  if (opts.file) {
27805
27931
  try {
27806
- prompt = fs80.readFileSync(path82.resolve(opts.file), "utf8");
27932
+ prompt = fs81.readFileSync(path84.resolve(opts.file), "utf8");
27807
27933
  } catch {
27808
27934
  die(`--file: cannot read ${opts.file}`, { kind: "run-refused" });
27809
27935
  }
@@ -27917,7 +28043,7 @@ async function followRun(sessionId, already = "", program2 = "akb", events = fal
27917
28043
  last = await followOne(current, printed, events);
27918
28044
  seen.add(current.sessionId);
27919
28045
  printed = 0;
27920
- const deliveryId2 = last.deliveryId ?? first.deliveryId;
28046
+ const deliveryId2 = first.deliveryId ?? last.deliveryId;
27921
28047
  const next = nextInFlow(first, current.sessionId, seen) ?? (deliveryId2 ? await moveDelivery(deliveryId2, idle) : void 0);
27922
28048
  if (next === void 0) break;
27923
28049
  if (next === null) {
@@ -27938,7 +28064,7 @@ async function followRun(sessionId, already = "", program2 = "akb", events = fal
27938
28064
  }
27939
28065
  say("");
27940
28066
  say(runLine(last, program2));
27941
- const deliveryId = last.deliveryId ?? first.deliveryId;
28067
+ const deliveryId = first.deliveryId ?? last.deliveryId;
27942
28068
  const delivery = deliveryId ? deliveryOutcome(deliveryId) : void 0;
27943
28069
  if (delivery) say(`delivery ${delivery.id}: ${delivery.line}`);
27944
28070
  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 +28130,7 @@ async function followOne(view, already, events) {
28004
28130
  }
28005
28131
  function nextInFlow(first, after2, seen) {
28006
28132
  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];
28133
+ 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
28134
  return next ? { ...next } : void 0;
28009
28135
  }
28010
28136
  async function moveDelivery(deliveryId, idle) {
@@ -28024,7 +28150,7 @@ async function moveDelivery(deliveryId, idle) {
28024
28150
  const ask2 = await advanceLanding();
28025
28151
  if (!ask2) return null;
28026
28152
  const started = await startRun(ask2);
28027
- return "error" in started ? null : { ...started.run };
28153
+ return "error" in started || started.run.deliveryId !== deliveryId ? null : { ...started.run };
28028
28154
  }
28029
28155
  function deliveryOutcome(deliveryId) {
28030
28156
  const delivery = findDelivery(deliveryId);
@@ -28094,7 +28220,7 @@ async function cmdWatch(sessionId) {
28094
28220
  // src/commands/triage.ts
28095
28221
  init_scheduled();
28096
28222
  init_workflows();
28097
- import fs82 from "node:fs";
28223
+ import fs83 from "node:fs";
28098
28224
 
28099
28225
  // src/lib/signals/index.ts
28100
28226
  init_cards();
@@ -28104,16 +28230,16 @@ init_yaml();
28104
28230
  // src/lib/signals/config.ts
28105
28231
  init_settings2();
28106
28232
  init_paths();
28107
- import fs81 from "node:fs";
28108
- import path83 from "node:path";
28233
+ import fs82 from "node:fs";
28234
+ import path85 from "node:path";
28109
28235
  var TOKEN_KEY = "TRIAGE_ENDPOINT_TOKEN";
28110
28236
  var ENDPOINT_SETTING = "Triage endpoint";
28111
28237
  var LINE2 = /^- \*\*Triage endpoint\*\*\s*[—-]\s*(.+)$/m;
28112
- var boardRel3 = (file) => rel(file).split(path83.sep).join("/");
28238
+ var boardRel3 = (file) => rel(file).split(path85.sep).join("/");
28113
28239
  function signalEndpoint() {
28114
28240
  let text5;
28115
28241
  try {
28116
- text5 = fs81.readFileSync(CONFIG, "utf8");
28242
+ text5 = fs82.readFileSync(CONFIG, "utf8");
28117
28243
  } catch {
28118
28244
  return "";
28119
28245
  }
@@ -28289,7 +28415,7 @@ async function cmdTriageAdd(opts) {
28289
28415
  let body = opts.text;
28290
28416
  if (opts.file !== void 0) {
28291
28417
  try {
28292
- body = fs82.readFileSync(opts.file, "utf8");
28418
+ body = fs83.readFileSync(opts.file, "utf8");
28293
28419
  } catch {
28294
28420
  die(`can't read ${opts.file} \u2014 write the item to a file, then pass its path`, { kind: "needs-input" });
28295
28421
  }
@@ -28721,7 +28847,7 @@ function declareRunning(run2, cli) {
28721
28847
  });
28722
28848
  verb("resume").argument("[id]", RUN_ID, String).summary("continue a run that failed, was cut off or was stopped").description(
28723
28849
  "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) {
28850
+ ).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
28851
  const [id] = positional(vals);
28726
28852
  await onBoard2(this, cli, () => cmdResume(id, this.opts()));
28727
28853
  });
@@ -28853,8 +28979,8 @@ function declareAgent(program2, cli) {
28853
28979
  }
28854
28980
 
28855
28981
  // src/lib/cli/setup.ts
28856
- import fs84 from "node:fs";
28857
- import path85 from "node:path";
28982
+ import fs85 from "node:fs";
28983
+ import path87 from "node:path";
28858
28984
  import { fileURLToPath as fileURLToPath2 } from "node:url";
28859
28985
 
28860
28986
  // src/commands/update.ts
@@ -28868,8 +28994,8 @@ init_paths();
28868
28994
  init_memory();
28869
28995
  init_yaml2();
28870
28996
  init_version();
28871
- import fs83 from "node:fs";
28872
- import path84 from "node:path";
28997
+ import fs84 from "node:fs";
28998
+ import path86 from "node:path";
28873
28999
  import { spawnSync as spawnSync6 } from "node:child_process";
28874
29000
  var NAME = "wildcrane";
28875
29001
  var REPO = "https://github.com/ai4kanban/ai4kanban";
@@ -28891,10 +29017,10 @@ var Report = class {
28891
29017
  for (const line of this.notes) say(` ! ${line}`);
28892
29018
  }
28893
29019
  };
28894
- var read3 = (file) => fs83.existsSync(file) ? fs83.readFileSync(file, "utf8") : null;
29020
+ var read3 = (file) => fs84.existsSync(file) ? fs84.readFileSync(file, "utf8") : null;
28895
29021
  function statOf(p) {
28896
29022
  try {
28897
- return fs83.lstatSync(p);
29023
+ return fs84.lstatSync(p);
28898
29024
  } catch {
28899
29025
  return null;
28900
29026
  }
@@ -28919,10 +29045,10 @@ async function cmdUpdate2(ctx) {
28919
29045
  return { updated: ctx.dir, from, to: SKILL_VERSION };
28920
29046
  }
28921
29047
  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)) {
29048
+ const legacy2 = path86.join(root, "docs", "kanban");
29049
+ const kept2 = path86.join(root, ".akb", "kanban");
29050
+ const board2 = named2 ?? (fs84.existsSync(legacy2) ? legacy2 : kept2);
29051
+ if (!fs84.existsSync(board2)) {
28926
29052
  report3.notes.push("\u672A\u627E\u5230\u770B\u677F\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002");
28927
29053
  return false;
28928
29054
  }
@@ -28953,20 +29079,20 @@ function moveRuntimes(root, board2, report3) {
28953
29079
  }
28954
29080
  }
28955
29081
  function moveLegacyMemory(board2, report3) {
28956
- const memory = path84.join(board2, "memory");
29082
+ const memory = path86.join(board2, "memory");
28957
29083
  const moved = [];
28958
29084
  for (const name of MEMORY_FILES) {
28959
- const from = path84.join(board2, name);
29085
+ const from = path86.join(board2, name);
28960
29086
  const st = statOf(from);
28961
29087
  if (!st || !st.isFile()) continue;
28962
- fs83.mkdirSync(memory, { recursive: true });
28963
- const to = path84.join(memory, name);
29088
+ fs84.mkdirSync(memory, { recursive: true });
29089
+ const to = path86.join(memory, name);
28964
29090
  const there = read3(to);
28965
29091
  if (there === null) {
28966
- fs83.renameSync(from, to);
29092
+ fs84.renameSync(from, to);
28967
29093
  moved.push(name);
28968
29094
  } else if (there === read3(from)) {
28969
- fs83.rmSync(from);
29095
+ fs84.rmSync(from);
28970
29096
  moved.push(name);
28971
29097
  } else {
28972
29098
  report3.notes.push(`both docs/kanban/${name} and docs/kanban/memory/${name} exist and differ \u2014 merge them by hand`);
@@ -28975,23 +29101,23 @@ function moveLegacyMemory(board2, report3) {
28975
29101
  if (moved.length) report3.did.push(`moved the memory set into docs/kanban/memory/: ${moved.join(", ")}`);
28976
29102
  }
28977
29103
  function dropRecordFile(board2) {
28978
- const file = path84.join(board2, "record.csv");
28979
- if (!fs83.existsSync(file)) return null;
28980
- fs83.rmSync(file);
29104
+ const file = path86.join(board2, "record.csv");
29105
+ if (!fs84.existsSync(file)) return null;
29106
+ fs84.rmSync(file);
28981
29107
  return "removed docs/kanban/record.csv (the planning scores it fed are gone)";
28982
29108
  }
28983
29109
  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"));
29110
+ const memory = path86.join(board2, "memory");
29111
+ if (!fs84.existsSync(memory)) return;
29112
+ const root = read3(path86.join(memory, "goal.md"));
28987
29113
  let dropped = 0;
28988
- for (const entry of fs83.readdirSync(memory, { withFileTypes: true })) {
29114
+ for (const entry of fs84.readdirSync(memory, { withFileTypes: true })) {
28989
29115
  if (!entry.isDirectory()) continue;
28990
- const file = path84.join(memory, entry.name, "goal.md");
29116
+ const file = path86.join(memory, entry.name, "goal.md");
28991
29117
  const text5 = read3(file);
28992
29118
  if (text5 === null) continue;
28993
29119
  if (text5 === root || text5.includes(UNFILLED) || !goalWords(text5)) {
28994
- fs83.rmSync(file);
29120
+ fs84.rmSync(file);
28995
29121
  dropped++;
28996
29122
  } else {
28997
29123
  report3.notes.push(
@@ -29013,10 +29139,10 @@ var PLAN_LEADS = {
29013
29139
  var GONE_LEADS = ["software-planner", "planner"];
29014
29140
  function planLeads(board2) {
29015
29141
  const leads = { ...PLAN_LEADS };
29016
- const root = path84.join(board2, "workflows");
29017
- for (const entry of fs83.existsSync(root) ? fs83.readdirSync(root, { withFileTypes: true }) : []) {
29142
+ const root = path86.join(board2, "workflows");
29143
+ for (const entry of fs84.existsSync(root) ? fs84.readdirSync(root, { withFileTypes: true }) : []) {
29018
29144
  if (!entry.isDirectory()) continue;
29019
- const meta = splitFrontmatter(read3(path84.join(root, entry.name, "WORKFLOW.md")) ?? "").meta;
29145
+ const meta = splitFrontmatter(read3(path86.join(root, entry.name, "WORKFLOW.md")) ?? "").meta;
29020
29146
  const stages = meta === null ? void 0 : parseYamlBlock(meta).stages;
29021
29147
  const plan = stages && typeof stages === "object" && !Array.isArray(stages) ? stages.plan : void 0;
29022
29148
  const lead = plan && typeof plan === "object" && !Array.isArray(plan) && typeof plan.lead === "string" ? plan.lead.trim() : "";
@@ -29025,30 +29151,30 @@ function planLeads(board2) {
29025
29151
  return leads;
29026
29152
  }
29027
29153
  function movePlanRules(board2, report3) {
29028
- const rules = path84.join(board2, "rules");
29154
+ const rules = path86.join(board2, "rules");
29029
29155
  const moved = [];
29030
29156
  for (const [id, leads] of Object.entries(planLeads(board2))) {
29031
29157
  for (const lead of leads) {
29032
- const from = path84.join(rules, `${lead}.md`);
29158
+ const from = path86.join(rules, `${lead}.md`);
29033
29159
  const rule = read3(from)?.trim();
29034
29160
  if (!rule) continue;
29035
- const to = path84.join(rules, "workflows", `${id}.md`);
29161
+ const to = path86.join(rules, "workflows", `${id}.md`);
29036
29162
  const there = read3(to)?.trim() ?? "";
29037
29163
  if (!there.includes(rule)) {
29038
- fs83.mkdirSync(path84.dirname(to), { recursive: true });
29039
- fs83.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
29164
+ fs84.mkdirSync(path86.dirname(to), { recursive: true });
29165
+ fs84.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
29040
29166
  `);
29041
29167
  moved.push(`${lead} \u2192 ${id}`);
29042
29168
  }
29043
29169
  }
29044
29170
  }
29045
- for (const lead of GONE_LEADS) fs83.rmSync(path84.join(rules, `${lead}.md`), { force: true });
29171
+ for (const lead of GONE_LEADS) fs84.rmSync(path86.join(rules, `${lead}.md`), { force: true });
29046
29172
  if (moved.length) report3.did.push(`made each plan agent's rule its workflow's card rule (docs/kanban/rules/workflows/): ${moved.join(", ")}`);
29047
29173
  }
29048
29174
  function noteOldWorkflows(board2, report3) {
29049
29175
  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}`);
29176
+ const root = path86.join(board2, dir);
29177
+ 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
29178
  };
29053
29179
  const files2 = [...old("workflows", "WORKFLOW.md", /^(stages|delivers):/m), ...old("agents", "AGENT.md", /^\s+(hook|lead):/m)];
29054
29180
  if (files2.length) {
@@ -29058,7 +29184,7 @@ function noteOldWorkflows(board2, report3) {
29058
29184
  }
29059
29185
  }
29060
29186
  function checkConfig(board2, report3) {
29061
- const current = read3(path84.join(board2, "config.md"));
29187
+ const current = read3(path86.join(board2, "config.md"));
29062
29188
  if (!current) return;
29063
29189
  const added = missingConfigKeys(current);
29064
29190
  if (added.length) {
@@ -29068,7 +29194,7 @@ function checkConfig(board2, report3) {
29068
29194
  }
29069
29195
  }
29070
29196
  function checkModules(board2, report3) {
29071
- const map2 = read3(path84.join(board2, "modules.md"));
29197
+ const map2 = read3(path86.join(board2, "modules.md"));
29072
29198
  if (map2 && map2.includes(UNFILLED)) {
29073
29199
  report3.notes.push(
29074
29200
  "docs/kanban/modules.md is still blank \u2014 write it from the repo (`akb guide module-map`)"
@@ -29122,14 +29248,14 @@ function declareSetup(program2, cli) {
29122
29248
  program2.version(SKILL_VERSION, "-v, --version", "print this version").addHelpText("beforeAll", spelled(cli.program));
29123
29249
  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
29250
  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 });
29251
+ const dir = path87.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
29252
+ if (!fs85.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
29127
29253
  return dir;
29128
29254
  };
29129
29255
  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
29256
  const dir = where(this);
29131
29257
  const named2 = this.optsWithGlobals().board ?? process.env.AI4KANBAN_BOARD?.trim();
29132
- const board2 = named2 ? path85.resolve(cli.cwd, named2) : null;
29258
+ const board2 = named2 ? path87.resolve(cli.cwd, named2) : null;
29133
29259
  await runAction(ctxOf(this, cli.program), {}, () => cmdUpdate2({ dir, program: cli.program, board: board2 }));
29134
29260
  });
29135
29261
  program2.command("__rules", { hidden: true }).action(function() {
@@ -29173,7 +29299,7 @@ function invokedDirectly() {
29173
29299
  const entry = process.argv[1];
29174
29300
  if (!entry) return false;
29175
29301
  try {
29176
- return fs85.realpathSync(entry) === fs85.realpathSync(SELF2);
29302
+ return fs86.realpathSync(entry) === fs86.realpathSync(SELF2);
29177
29303
  } catch {
29178
29304
  return false;
29179
29305
  }