wildcrane 0.11.10 → 0.11.12

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 +1256 -1135
  2. package/package.json +1 -1
package/dist/kanban.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // ai4kanban 0.11.10 — built from the CLI's TypeScript sources by cli/scripts/build.mjs.
2
+ // ai4kanban 0.11.12 — 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 path85 = __require("node:path");
1172
- var fs86 = __require("node:fs");
1171
+ var path87 = __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 = path85.resolve(baseDir, baseName);
2172
- if (fs86.existsSync(localBin)) return localBin;
2173
- if (sourceExt.includes(path85.extname(baseName))) return void 0;
2171
+ const localBin = path87.resolve(baseDir, baseName);
2172
+ if (fs87.existsSync(localBin)) return localBin;
2173
+ if (sourceExt.includes(path87.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 = path85.resolve(
2192
- path85.dirname(resolvedScriptPath),
2191
+ executableDir = path87.resolve(
2192
+ path87.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 = path85.basename(
2199
+ const legacyName = path87.basename(
2200
2200
  this._scriptPath,
2201
- path85.extname(this._scriptPath)
2201
+ path87.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(path85.extname(executableFile));
2212
+ launchWithNode = sourceExt.includes(path87.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 = path85.basename(filename, path85.extname(filename));
3059
+ this._name = path87.basename(filename, path87.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(path86) {
3074
- if (path86 === void 0) return this._executableDir;
3075
- this._executableDir = path86;
3073
+ executableDir(path88) {
3074
+ if (path88 === void 0) return this._executableDir;
3075
+ this._executableDir = path88;
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
  }
@@ -4058,42 +3872,42 @@ async function takeLock() {
4058
3872
  const until = Date.now() + LOCK_WAIT_MS;
4059
3873
  for (; ; ) {
4060
3874
  try {
4061
- fs5.mkdirSync(machineHome(), { recursive: true, mode: 448 });
4062
- fs5.mkdirSync(lockDir());
3875
+ fs4.mkdirSync(machineHome(), { recursive: true, mode: 448 });
3876
+ fs4.mkdirSync(lockDir());
4063
3877
  try {
4064
- fs5.writeFileSync(lockOwner(), `${process.pid}
3878
+ fs4.writeFileSync(lockOwner(), `${process.pid}
4065
3879
  `);
4066
3880
  } catch {
4067
3881
  }
4068
3882
  return () => {
4069
3883
  try {
4070
- fs5.rmSync(lockDir(), { recursive: true, force: true });
3884
+ fs4.rmSync(lockDir(), { recursive: true, force: true });
4071
3885
  } catch {
4072
3886
  }
4073
3887
  };
4074
3888
  } catch (err) {
4075
3889
  if (err.code !== "EEXIST") throw err;
4076
3890
  if (stale()) {
4077
- fs5.rmSync(lockDir(), { recursive: true, force: true });
3891
+ fs4.rmSync(lockDir(), { recursive: true, force: true });
4078
3892
  continue;
4079
3893
  }
4080
3894
  if (Date.now() > until) return () => {
4081
3895
  };
4082
- await sleep2(LOCK_RETRY_MS);
3896
+ await sleep(LOCK_RETRY_MS);
4083
3897
  }
4084
3898
  }
4085
3899
  }
4086
3900
  function stale() {
4087
3901
  let held4;
4088
3902
  try {
4089
- const pid = Number(fs5.readFileSync(lockOwner(), "utf8").trim());
3903
+ const pid = Number(fs4.readFileSync(lockOwner(), "utf8").trim());
4090
3904
  held4 = Number.isInteger(pid) && pid > 0 ? pid : void 0;
4091
3905
  } catch {
4092
3906
  held4 = void 0;
4093
3907
  }
4094
3908
  if (held4 !== void 0 && !alive(held4)) return true;
4095
3909
  try {
4096
- return Date.now() - fs5.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
3910
+ return Date.now() - fs4.statSync(lockDir()).mtimeMs > LOCK_STALE_MS;
4097
3911
  } catch {
4098
3912
  return false;
4099
3913
  }
@@ -4106,7 +3920,7 @@ function alive(pid) {
4106
3920
  return e.code === "EPERM";
4107
3921
  }
4108
3922
  }
4109
- var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep2;
3923
+ var REFRESH_MARGIN_MS, LOCK_STALE_MS, LOCK_WAIT_MS, LOCK_RETRY_MS, sessionFile, lockDir, lockOwner, expiringSoon, sleep;
4110
3924
  var init_session = __esm({
4111
3925
  "src/lib/cloud/session.ts"() {
4112
3926
  "use strict";
@@ -4116,11 +3930,234 @@ var init_session = __esm({
4116
3930
  LOCK_STALE_MS = 3e4;
4117
3931
  LOCK_WAIT_MS = 2e4;
4118
3932
  LOCK_RETRY_MS = 50;
4119
- sessionFile = () => path7.join(machineHome(), "session.json");
4120
- lockDir = () => path7.join(machineHome(), "session.lock");
4121
- lockOwner = () => path7.join(lockDir(), "owner");
3933
+ sessionFile = () => path5.join(machineHome(), "session.json");
3934
+ lockDir = () => path5.join(machineHome(), "session.lock");
3935
+ lockOwner = () => path5.join(lockDir(), "owner");
4122
3936
  expiringSoon = (session) => session.expiresAt - REFRESH_MARGIN_MS <= Date.now();
4123
- sleep2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
3937
+ sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
3938
+ }
3939
+ });
3940
+
3941
+ // src/lib/cloud/execution.ts
3942
+ function executionOf(value = process.env.AI4KANBAN_EXECUTION) {
3943
+ try {
3944
+ const held4 = typeof value === "string" ? JSON.parse(value) : value;
3945
+ if (held4 && UUID.test(held4.job) && UUID.test(held4.machine)) return { job: held4.job, machine: held4.machine };
3946
+ } catch {
3947
+ }
3948
+ return void 0;
3949
+ }
3950
+ async function executionHeld(execution) {
3951
+ if (!execution) return true;
3952
+ try {
3953
+ const auth = await accessToken();
3954
+ if (!auth.ok) return false;
3955
+ const response = await fetch(`${cloudEndpoints().api}/v1/runner/jobs/${execution.job}/renew`, {
3956
+ method: "POST",
3957
+ headers: { authorization: `Bearer ${auth.token}`, "content-type": "application/json" },
3958
+ body: JSON.stringify({ machineId: execution.machine }),
3959
+ signal: AbortSignal.timeout(2e4)
3960
+ });
3961
+ if (!response.ok) return false;
3962
+ const held4 = await response.json();
3963
+ return held4.renewed === true && held4.stop !== true;
3964
+ } catch {
3965
+ return false;
3966
+ }
3967
+ }
3968
+ var UUID;
3969
+ var init_execution = __esm({
3970
+ "src/lib/cloud/execution.ts"() {
3971
+ "use strict";
3972
+ init_config();
3973
+ init_session();
3974
+ UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3975
+ }
3976
+ });
3977
+
3978
+ // src/lib/lock.ts
3979
+ import { randomUUID } from "node:crypto";
3980
+ import fs5 from "node:fs";
3981
+ import path6 from "node:path";
3982
+ function sleep2(ms) {
3983
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
3984
+ }
3985
+ function ageOf(dir) {
3986
+ try {
3987
+ return Date.now() - fs5.statSync(dir).mtimeMs;
3988
+ } catch {
3989
+ return 0;
3990
+ }
3991
+ }
3992
+ function pidAlive(pid) {
3993
+ if (!pid) return false;
3994
+ try {
3995
+ process.kill(pid, 0);
3996
+ return true;
3997
+ } catch (e) {
3998
+ return e.code === "EPERM";
3999
+ }
4000
+ }
4001
+ function ownerOf(dir) {
4002
+ try {
4003
+ const pid = Number(fs5.readFileSync(path6.join(dir, OWNER), "utf8").trim());
4004
+ return Number.isInteger(pid) && pid > 0 ? pid : void 0;
4005
+ } catch {
4006
+ return void 0;
4007
+ }
4008
+ }
4009
+ function claimBreak(dir) {
4010
+ try {
4011
+ fs5.mkdirSync(path6.join(dir, BREAKING));
4012
+ return true;
4013
+ } catch {
4014
+ return false;
4015
+ }
4016
+ }
4017
+ function removeClaim(dir, token3) {
4018
+ if (token3) {
4019
+ try {
4020
+ fs5.unlinkSync(path6.join(dir, token3));
4021
+ } catch (err) {
4022
+ if (err.code !== "ENOENT") throw err;
4023
+ }
4024
+ }
4025
+ try {
4026
+ fs5.rmdirSync(dir);
4027
+ return true;
4028
+ } catch (err) {
4029
+ const code = err.code;
4030
+ if (code === "ENOENT") return true;
4031
+ if (code === "ENOTEMPTY" || code === "EEXIST") return false;
4032
+ throw err;
4033
+ }
4034
+ }
4035
+ function tryLock(dir) {
4036
+ fs5.mkdirSync(path6.dirname(dir), { recursive: true });
4037
+ const token3 = `${process.pid}-${randomUUID()}`;
4038
+ const candidate = fs5.mkdtempSync(`${dir}.`);
4039
+ try {
4040
+ fs5.writeFileSync(path6.join(candidate, token3), "");
4041
+ for (; ; ) {
4042
+ try {
4043
+ fs5.renameSync(candidate, dir);
4044
+ return () => {
4045
+ removeClaim(dir, token3);
4046
+ };
4047
+ } catch (err) {
4048
+ const code = err.code;
4049
+ if (code !== "ENOTEMPTY" && code !== "EEXIST") throw err;
4050
+ }
4051
+ let entries;
4052
+ try {
4053
+ entries = fs5.readdirSync(dir);
4054
+ } catch (err) {
4055
+ if (err.code === "ENOENT") continue;
4056
+ throw err;
4057
+ }
4058
+ if (entries.length) {
4059
+ if (entries.length !== 1 || !/^\d+-[a-f0-9-]{36}$/.test(entries[0])) return void 0;
4060
+ const owner = Number(entries[0].split("-")[0]);
4061
+ if (pidAlive(owner)) return void 0;
4062
+ }
4063
+ if (!removeClaim(dir, entries[0])) return void 0;
4064
+ }
4065
+ } finally {
4066
+ fs5.rmSync(candidate, { recursive: true, force: true });
4067
+ }
4068
+ }
4069
+ function withLock(dir, what, fn) {
4070
+ const until = Date.now() + WAIT_MS;
4071
+ let held4;
4072
+ for (; ; ) {
4073
+ try {
4074
+ fs5.mkdirSync(dir, { recursive: false });
4075
+ try {
4076
+ fs5.writeFileSync(path6.join(dir, OWNER), `${process.pid}
4077
+ `);
4078
+ } catch {
4079
+ }
4080
+ break;
4081
+ } catch (err) {
4082
+ const code = err.code;
4083
+ if (code === "ENOENT") {
4084
+ fs5.mkdirSync(path6.dirname(dir), { recursive: true });
4085
+ continue;
4086
+ }
4087
+ if (code !== "EEXIST") throw err;
4088
+ if (ageOf(dir) > STALE_MS) {
4089
+ fs5.rmSync(dir, { recursive: true, force: true });
4090
+ continue;
4091
+ }
4092
+ held4 = ownerOf(dir);
4093
+ if (held4 !== void 0 && !pidAlive(held4) && claimBreak(dir)) {
4094
+ fs5.rmSync(dir, { recursive: true, force: true });
4095
+ continue;
4096
+ }
4097
+ if (Date.now() > until) {
4098
+ die(
4099
+ `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.`,
4100
+ "board-busy"
4101
+ );
4102
+ }
4103
+ sleep2(RETRY_MS);
4104
+ }
4105
+ }
4106
+ try {
4107
+ return fn();
4108
+ } finally {
4109
+ const owner = ownerOf(dir);
4110
+ if (owner === void 0 || owner === process.pid) fs5.rmSync(dir, { recursive: true, force: true });
4111
+ }
4112
+ }
4113
+ function withBoardLock(fn) {
4114
+ if (!fs5.existsSync(KANBAN)) return fn();
4115
+ if (depth > 0) return fn();
4116
+ try {
4117
+ ensureAkbDir();
4118
+ } catch {
4119
+ }
4120
+ depth++;
4121
+ try {
4122
+ return withLock(LOCK, "writing this board", fn);
4123
+ } finally {
4124
+ depth--;
4125
+ }
4126
+ }
4127
+ var WAIT_MS, STALE_MS, RETRY_MS, OWNER, BREAKING, depth;
4128
+ var init_lock = __esm({
4129
+ "src/lib/lock.ts"() {
4130
+ "use strict";
4131
+ init_paths();
4132
+ WAIT_MS = 1e4;
4133
+ STALE_MS = 6e4;
4134
+ RETRY_MS = 25;
4135
+ OWNER = "owner";
4136
+ BREAKING = "breaking";
4137
+ depth = 0;
4138
+ }
4139
+ });
4140
+
4141
+ // src/lib/agent/creation-lock.ts
4142
+ import path7 from "node:path";
4143
+ function withCreationLock(fn) {
4144
+ if (depth2) return fn();
4145
+ return withLock(path7.join(SESSIONS_DIR, "creation.lock"), "changing card creation", () => {
4146
+ depth2++;
4147
+ try {
4148
+ return fn();
4149
+ } finally {
4150
+ depth2--;
4151
+ }
4152
+ });
4153
+ }
4154
+ var depth2;
4155
+ var init_creation_lock = __esm({
4156
+ "src/lib/agent/creation-lock.ts"() {
4157
+ "use strict";
4158
+ init_lock();
4159
+ init_paths();
4160
+ depth2 = 0;
4124
4161
  }
4125
4162
  });
4126
4163
 
@@ -5478,7 +5515,7 @@ var init_package = __esm({
5478
5515
  "package.json"() {
5479
5516
  package_default = {
5480
5517
  name: "wildcrane",
5481
- version: "0.11.10",
5518
+ version: "0.11.12",
5482
5519
  akbContract: 5,
5483
5520
  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.",
5484
5521
  keywords: [
@@ -8317,10 +8354,10 @@ function findRollout(threadId) {
8317
8354
  }
8318
8355
  for (const name of names4) {
8319
8356
  if (!name.startsWith("rollout-") || !name.endsWith(tail2)) continue;
8320
- const path85 = join(dir, name);
8357
+ const path87 = join(dir, name);
8321
8358
  try {
8322
- const at = statSync(path85).mtimeMs;
8323
- if (!newest2 || at > newest2.at) newest2 = { path: path85, at };
8359
+ const at = statSync(path87).mtimeMs;
8360
+ if (!newest2 || at > newest2.at) newest2 = { path: path87, at };
8324
8361
  } catch {
8325
8362
  }
8326
8363
  }
@@ -8328,11 +8365,11 @@ function findRollout(threadId) {
8328
8365
  return newest2?.path;
8329
8366
  }
8330
8367
  function readCodexRunFacts(threadId) {
8331
- const path85 = findRollout(threadId);
8332
- if (!path85) return void 0;
8368
+ const path87 = findRollout(threadId);
8369
+ if (!path87) return void 0;
8333
8370
  let raw;
8334
8371
  try {
8335
- raw = readFileSync(path85, "utf8");
8372
+ raw = readFileSync(path87, "utf8");
8336
8373
  } catch {
8337
8374
  return void 0;
8338
8375
  }
@@ -8460,8 +8497,8 @@ function renderCompleted(item) {
8460
8497
  const changes = Array.isArray(item.changes) ? item.changes : [];
8461
8498
  return changes.map((raw) => {
8462
8499
  const change2 = obj(raw);
8463
- const path85 = str2(change2.path);
8464
- return path85 ? `\u23FA ${str2(change2.kind) || "change"}(${path85})
8500
+ const path87 = str2(change2.path);
8501
+ return path87 ? `\u23FA ${str2(change2.kind) || "change"}(${path87})
8465
8502
  ` : "";
8466
8503
  }).join("");
8467
8504
  }
@@ -8720,10 +8757,10 @@ function readKimiRunFacts(sessionId) {
8720
8757
  const total = { input: 0, cacheCreation: 0, cacheRead: 0, output: 0 };
8721
8758
  let model;
8722
8759
  let holding = 0;
8723
- for (const { path: path85, main } of wireFiles(entry.sessionDir)) {
8760
+ for (const { path: path87, main } of wireFiles(entry.sessionDir)) {
8724
8761
  let raw;
8725
8762
  try {
8726
- raw = readFileSync2(path85, "utf8");
8763
+ raw = readFileSync2(path87, "utf8");
8727
8764
  } catch {
8728
8765
  continue;
8729
8766
  }
@@ -9004,8 +9041,8 @@ var init_tail = __esm({
9004
9041
  import fs24 from "node:fs";
9005
9042
  function whereHint(update2, title) {
9006
9043
  const locations = Array.isArray(update2.locations) ? update2.locations : [];
9007
- const path85 = str2(obj(locations[0]).path);
9008
- return path85 && !title.includes(path85) ? hint(path85) : "";
9044
+ const path87 = str2(obj(locations[0]).path);
9045
+ return path87 && !title.includes(path87) ? hint(path87) : "";
9009
9046
  }
9010
9047
  function saidBy(update2) {
9011
9048
  const content = Array.isArray(update2.content) ? update2.content : [];
@@ -9948,27 +9985,40 @@ import crypto3 from "node:crypto";
9948
9985
  import fs25 from "node:fs";
9949
9986
  import os4 from "node:os";
9950
9987
  import path28 from "node:path";
9988
+ function spawnGit(args, options) {
9989
+ const out = spawnSync3("git", args, {
9990
+ ...options,
9991
+ encoding: "utf8",
9992
+ stdio: ["ignore", "pipe", "pipe"],
9993
+ timeout: gitLimits.timeoutMs,
9994
+ killSignal: "SIGKILL"
9995
+ });
9996
+ if (out.error?.code === "ETIMEDOUT") throw new GitTimeoutError(`Git ${args[0]} timed out after ${gitLimits.timeoutMs / 1e3}s; the command was killed.`);
9997
+ return out;
9998
+ }
9951
9999
  function git(args, cwd = REPO_ROOT) {
9952
10000
  try {
9953
- const out = spawnSync3("git", args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
10001
+ const out = spawnGit(args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
9954
10002
  if (out.error || out.status !== 0) return null;
9955
10003
  return out.stdout;
9956
- } catch {
10004
+ } catch (error) {
10005
+ if (error instanceof GitTimeoutError) throw error;
9957
10006
  return null;
9958
10007
  }
9959
10008
  }
9960
10009
  function gitDiff(args, cwd = REPO_ROOT) {
9961
10010
  try {
9962
- const out = spawnSync3("git", args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
10011
+ const out = spawnGit(args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true });
9963
10012
  if (out.error || out.status !== 0 && out.status !== 1) return null;
9964
10013
  return out.stdout;
9965
- } catch {
10014
+ } catch (error) {
10015
+ if (error instanceof GitTimeoutError) throw error;
9966
10016
  return null;
9967
10017
  }
9968
10018
  }
9969
10019
  function tryGit(args, cwd = REPO_ROOT, env2) {
9970
10020
  try {
9971
- const out = spawnSync3("git", args, {
10021
+ const out = spawnGit(args, {
9972
10022
  cwd,
9973
10023
  encoding: "utf8",
9974
10024
  maxBuffer: MAX_OUTPUT,
@@ -9979,6 +10029,7 @@ function tryGit(args, cwd = REPO_ROOT, env2) {
9979
10029
  if (out.status !== 0) return { ok: false, why: (out.stderr || out.stdout || "").trim() };
9980
10030
  return { ok: true };
9981
10031
  } catch (e) {
10032
+ if (e instanceof GitTimeoutError) throw e;
9982
10033
  return { ok: false, why: e instanceof Error ? e.message : String(e) };
9983
10034
  }
9984
10035
  }
@@ -9987,7 +10038,7 @@ function boardManagedPaths() {
9987
10038
  }
9988
10039
  function outsideBoardForAdd(cwd = REPO_ROOT) {
9989
10040
  const kept2 = boardManagedPaths().filter(
9990
- (p) => spawnSync3("git", ["check-ignore", "-q", p], { cwd, windowsHide: true }).status !== 0
10041
+ (p) => spawnGit(["check-ignore", "-q", p], { cwd, windowsHide: true }).status !== 0
9991
10042
  );
9992
10043
  return ["--", ".", ...kept2.map((p) => `:(exclude)${p}`)];
9993
10044
  }
@@ -10107,10 +10158,10 @@ function treeMark(base, cwd = REPO_ROOT) {
10107
10158
  const index = path28.join(ensureAkbDir(), `index-${process.pid}-${Date.now()}`);
10108
10159
  try {
10109
10160
  const env2 = { ...process.env, GIT_INDEX_FILE: index };
10110
- const run2 = (args) => spawnSync3("git", args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true, env: env2 }).status === 0;
10161
+ const run2 = (args) => spawnGit(args, { cwd, encoding: "utf8", maxBuffer: MAX_OUTPUT, windowsHide: true, env: env2 }).status === 0;
10111
10162
  if (!run2(["read-tree", base])) return null;
10112
10163
  if (!run2(["add", "-A", ...outsideBoardForAdd(cwd)])) return null;
10113
- const tree = spawnSync3("git", ["write-tree"], {
10164
+ const tree = spawnGit(["write-tree"], {
10114
10165
  cwd,
10115
10166
  encoding: "utf8",
10116
10167
  maxBuffer: MAX_OUTPUT,
@@ -10118,7 +10169,8 @@ function treeMark(base, cwd = REPO_ROOT) {
10118
10169
  env: env2
10119
10170
  });
10120
10171
  return tree.status === 0 ? tree.stdout.trim() || null : null;
10121
- } catch {
10172
+ } catch (error) {
10173
+ if (error instanceof GitTimeoutError) throw error;
10122
10174
  return null;
10123
10175
  } finally {
10124
10176
  try {
@@ -10129,23 +10181,26 @@ function treeMark(base, cwd = REPO_ROOT) {
10129
10181
  }
10130
10182
  function reverseApplies(patch2, ref, cwd = REPO_ROOT) {
10131
10183
  if (!patch2.trim()) return false;
10132
- const index = path28.join(os4.tmpdir(), `akb-apply-${process.pid}-${Date.now()}.index`);
10184
+ const folder = fs25.mkdtempSync(path28.join(os4.tmpdir(), `akb-apply-${process.pid}-`));
10185
+ const index = path28.join(folder, "index");
10186
+ const patchFile = path28.join(folder, "patch");
10133
10187
  const env2 = { GIT_INDEX_FILE: index };
10134
10188
  try {
10189
+ fs25.writeFileSync(patchFile, patch2);
10135
10190
  if (!tryGit(["read-tree", ref], cwd, env2).ok) return false;
10136
- const out = spawnSync3("git", ["apply", "--cached", "--reverse", "--check", "-"], {
10191
+ const out = spawnGit(["apply", "--cached", "--reverse", "--check", patchFile], {
10137
10192
  cwd,
10138
- input: patch2,
10139
10193
  encoding: "utf8",
10140
10194
  maxBuffer: MAX_OUTPUT,
10141
10195
  windowsHide: true,
10142
10196
  env: { ...process.env, ...env2 }
10143
10197
  });
10144
10198
  return !out.error && out.status === 0;
10145
- } catch {
10199
+ } catch (error) {
10200
+ if (error instanceof GitTimeoutError) throw error;
10146
10201
  return false;
10147
10202
  } finally {
10148
- fs25.rmSync(index, { force: true });
10203
+ fs25.rmSync(folder, { recursive: true, force: true });
10149
10204
  }
10150
10205
  }
10151
10206
  function squashOnto(dir, base, message) {
@@ -10227,12 +10282,15 @@ function moveBranchRef(branch, commit, expect) {
10227
10282
  if (branchTip(branch) !== expect) return { moved: true };
10228
10283
  return { ok: false, error: `couldn't move ${branch} to ${commit.slice(0, 12)}: ${done2.why ?? "git refused"}` };
10229
10284
  }
10230
- var MAX_OUTPUT, scripted, posix, outsideBoard, deliveryBranch, deliveryWorktree, worktreeDir, inGitRepo, headCommit, worktreeExists, branchExists, pruneWorktreeMetadata, branchTip, isAncestor, changedPaths, branchPatch, lastCommitTouching, continueRebase, abortRebase, conflictedPaths, headingKind;
10285
+ 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;
10231
10286
  var init_worktree = __esm({
10232
10287
  "src/lib/agent/worktree.ts"() {
10233
10288
  "use strict";
10234
10289
  init_paths();
10235
10290
  MAX_OUTPUT = 64 * 1024 * 1024;
10291
+ gitLimits = { timeoutMs: 3e4 };
10292
+ GitTimeoutError = class extends Error {
10293
+ };
10236
10294
  scripted = (args, cwd) => tryGit(["-c", "core.hooksPath=/dev/null", ...args], cwd, { GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" });
10237
10295
  posix = (p) => p.split(path28.sep).join("/");
10238
10296
  outsideBoard = () => [
@@ -10249,7 +10307,7 @@ var init_worktree = __esm({
10249
10307
  branchExists = (branch) => !!branch && git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]) !== null;
10250
10308
  pruneWorktreeMetadata = () => void git(["worktree", "prune"]);
10251
10309
  branchTip = (branch) => git(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`])?.trim() || null;
10252
- isAncestor = (older, newer, cwd = REPO_ROOT) => spawnSync3("git", ["merge-base", "--is-ancestor", older, newer], { cwd, windowsHide: true }).status === 0;
10310
+ isAncestor = (older, newer, cwd = REPO_ROOT) => spawnGit(["merge-base", "--is-ancestor", older, newer], { cwd, windowsHide: true }).status === 0;
10253
10311
  changedPaths = (base, branch, cwd = REPO_ROOT) => {
10254
10312
  const out = git(["diff", "--name-only", base, branch, ...outsideBoard()], cwd);
10255
10313
  return out === null ? null : out.split("\n").filter(Boolean);
@@ -11557,49 +11615,12 @@ function withSystemLanguage(harness, argv, env2, line) {
11557
11615
  }
11558
11616
  var init_run_settings = __esm({
11559
11617
  "src/lib/agent/run-settings.ts"() {
11560
- "use strict";
11561
- init_argv();
11562
- init_env();
11563
- init_language();
11564
- init_types2();
11565
- init_providers();
11566
- }
11567
- });
11568
-
11569
- // src/lib/cloud/execution.ts
11570
- function executionOf(value = process.env.AI4KANBAN_EXECUTION) {
11571
- try {
11572
- const held4 = typeof value === "string" ? JSON.parse(value) : value;
11573
- if (held4 && UUID.test(held4.job) && UUID.test(held4.machine)) return { job: held4.job, machine: held4.machine };
11574
- } catch {
11575
- }
11576
- return void 0;
11577
- }
11578
- async function executionHeld(execution) {
11579
- if (!execution) return true;
11580
- try {
11581
- const auth = await accessToken();
11582
- if (!auth.ok) return false;
11583
- const response = await fetch(`${cloudEndpoints().api}/v1/runner/jobs/${execution.job}/renew`, {
11584
- method: "POST",
11585
- headers: { authorization: `Bearer ${auth.token}`, "content-type": "application/json" },
11586
- body: JSON.stringify({ machineId: execution.machine }),
11587
- signal: AbortSignal.timeout(2e4)
11588
- });
11589
- if (!response.ok) return false;
11590
- const held4 = await response.json();
11591
- return held4.renewed === true && held4.stop !== true;
11592
- } catch {
11593
- return false;
11594
- }
11595
- }
11596
- var UUID;
11597
- var init_execution = __esm({
11598
- "src/lib/cloud/execution.ts"() {
11599
- "use strict";
11600
- init_config();
11601
- init_session();
11602
- UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11618
+ "use strict";
11619
+ init_argv();
11620
+ init_env();
11621
+ init_language();
11622
+ init_types2();
11623
+ init_providers();
11603
11624
  }
11604
11625
  });
11605
11626
 
@@ -15547,6 +15568,252 @@ var init_complete = __esm({
15547
15568
  }
15548
15569
  });
15549
15570
 
15571
+ // src/lib/agent/stop.ts
15572
+ import { spawnSync as spawnSync4 } from "node:child_process";
15573
+ import { randomUUID as randomUUID5 } from "node:crypto";
15574
+ import fs39 from "node:fs";
15575
+ import os6 from "node:os";
15576
+ import path43 from "node:path";
15577
+ function markedInProc(entry, strict = false) {
15578
+ const pids = [];
15579
+ for (const name of fs39.readdirSync("/proc")) {
15580
+ if (!/^\d+$/.test(name)) continue;
15581
+ try {
15582
+ if (fs39.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
15583
+ } catch (error) {
15584
+ if (strict && !["ENOENT", "ESRCH"].includes(error.code ?? "")) {
15585
+ const stat = fs39.statSync(`/proc/${name}`, { throwIfNoEntry: false });
15586
+ if (stat?.uid === process.getuid?.()) throw error;
15587
+ }
15588
+ }
15589
+ }
15590
+ return pids;
15591
+ }
15592
+ function markedInPs(entry, roots) {
15593
+ const ps = spawnSync4("ps", ["-A", "-E", "-ww", "-o", "pid=,ppid=,command="], {
15594
+ encoding: "utf8",
15595
+ maxBuffer: 64 * 1024 * 1024,
15596
+ timeout: 5e3
15597
+ });
15598
+ if (ps.status !== 0 || !ps.stdout) throw new Error("\u65E0\u6CD5\u67E5\u8BE2\u8FDB\u7A0B\u6811\u3002");
15599
+ const children = /* @__PURE__ */ new Map();
15600
+ const listed2 = /* @__PURE__ */ new Set();
15601
+ const found2 = /* @__PURE__ */ new Set();
15602
+ for (const line of ps.stdout.split("\n")) {
15603
+ const m = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
15604
+ if (!m) continue;
15605
+ const pid = Number(m[1]);
15606
+ const ppid = Number(m[2]);
15607
+ listed2.add(pid);
15608
+ children.set(ppid, [...children.get(ppid) ?? [], pid]);
15609
+ if (`${m[3]} `.includes(` ${entry} `)) found2.add(pid);
15610
+ }
15611
+ const queue = [...found2, ...roots.filter((pid) => listed2.has(pid))];
15612
+ for (const pid of queue) {
15613
+ found2.add(pid);
15614
+ for (const child of children.get(pid) ?? []) if (!found2.has(child)) queue.push(child);
15615
+ }
15616
+ return [...found2];
15617
+ }
15618
+ function marked(mark, roots = []) {
15619
+ if (WINDOWS3 || !mark.value) return [];
15620
+ const entry = `${mark.name}=${mark.value}`;
15621
+ try {
15622
+ const pids = process.platform === "linux" ? markedInProc(entry) : markedInPs(entry, roots);
15623
+ return pids.filter((pid) => pid !== process.pid);
15624
+ } catch {
15625
+ return [];
15626
+ }
15627
+ }
15628
+ function signal(pids, sig) {
15629
+ for (const pid of pids) {
15630
+ try {
15631
+ process.kill(pid, sig);
15632
+ } catch {
15633
+ }
15634
+ }
15635
+ }
15636
+ function stopWatchers(sessions, onlyPid, stillOwns = () => true, startedBefore) {
15637
+ if (sessions ? !sessions.length : onlyPid === void 0) return [];
15638
+ const command = WINDOWS3 ? "powershell.exe" : "ps";
15639
+ 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="];
15640
+ const out = spawnSync4(command, args, { encoding: "utf8", timeout: 5e3, maxBuffer: 16 * 1024 * 1024, windowsHide: true, env: { ...process.env, LC_ALL: "C" } });
15641
+ if (out.status !== 0) return [];
15642
+ let procs;
15643
+ try {
15644
+ procs = WINDOWS3 ? [].concat(JSON.parse(out.stdout)).map((p) => ({ pid: p.ProcessId, command: p.CommandLine ?? "", startedAt: p.StartedAt })) : out.stdout.split("\n").flatMap((line) => {
15645
+ const m = /^\s*(\d+)\s+(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d{4})\s+(.*)$/.exec(line);
15646
+ return m ? [{ pid: Number(m[1]), command: m[3], startedAt: Date.parse(m[2]) }] : [];
15647
+ });
15648
+ } catch {
15649
+ return [];
15650
+ }
15651
+ const known2 = sessions && new Set(sessions);
15652
+ const stopped2 = [];
15653
+ for (const proc of procs) {
15654
+ if (proc.pid === process.pid || onlyPid !== void 0 && proc.pid !== onlyPid) continue;
15655
+ if (startedBefore !== void 0 && (!Number.isFinite(proc.startedAt) || proc.startedAt > startedBefore)) continue;
15656
+ const match = /^"?[^\n]*?\bnode(?:\.exe)?"?\s+(?:"[^\n"]+\.mjs"|\S+\.mjs)\s+__watch\s+(\S+)(?:\s|$)/.exec(proc.command);
15657
+ const args2 = `${proc.command} `;
15658
+ const names4 = (flag, value) => args2.includes(` ${flag} ${value} `) || args2.includes(` ${flag} "${value}" `);
15659
+ const board2 = names4("--board", KANBAN) || KANBAN === path43.join(REPO_ROOT, "docs", "kanban") && names4("--dir", REPO_ROOT);
15660
+ if (!match || known2 && !known2.has(match[1]) || !board2 || !stillOwns()) continue;
15661
+ if (WINDOWS3) {
15662
+ if (killTreeOnWindows(proc.pid)) stopped2.push(proc.pid);
15663
+ } else {
15664
+ try {
15665
+ process.kill(-proc.pid, "SIGKILL");
15666
+ stopped2.push(proc.pid);
15667
+ } catch {
15668
+ }
15669
+ }
15670
+ }
15671
+ return stopped2;
15672
+ }
15673
+ function startedUnder(list, root, since) {
15674
+ const self = list.procs.find((p) => p.pid === root);
15675
+ const from = since ?? self?.startedAt;
15676
+ if (from === void 0 || list.bootedAt > from) return [];
15677
+ if (self && self.startedAt > from) return [];
15678
+ const found2 = self ? [root] : [];
15679
+ const seen = /* @__PURE__ */ new Set([root]);
15680
+ const queue = [{ pid: root, startedAt: from }];
15681
+ for (const parent of queue) {
15682
+ for (const p of list.procs) {
15683
+ if (p.ppid !== parent.pid || seen.has(p.pid) || p.startedAt < parent.startedAt) continue;
15684
+ seen.add(p.pid);
15685
+ found2.push(p.pid);
15686
+ queue.push(p);
15687
+ }
15688
+ }
15689
+ return found2.reverse();
15690
+ }
15691
+ function readProcList(out) {
15692
+ const procs = [];
15693
+ let bootedAt;
15694
+ for (const line of out.split(/\r?\n/)) {
15695
+ const boot = /^boot (\d+)$/.exec(line.trim());
15696
+ if (boot) bootedAt = Number(boot[1]);
15697
+ const m = /^(\d+) (\d+) (\d+)$/.exec(line.trim());
15698
+ if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), startedAt: Number(m[3]) });
15699
+ }
15700
+ return bootedAt !== void 0 && procs.length ? { procs, bootedAt } : void 0;
15701
+ }
15702
+ function procsOnWindows() {
15703
+ const ps = spawnSync4("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST_PROCS], {
15704
+ encoding: "utf8",
15705
+ maxBuffer: 64 * 1024 * 1024,
15706
+ timeout: 5e3,
15707
+ windowsHide: true
15708
+ });
15709
+ return ps.status === 0 && ps.stdout ? readProcList(ps.stdout) : void 0;
15710
+ }
15711
+ function killUnderOnWindows(pid, since) {
15712
+ if (!WINDOWS3 || !pid) return;
15713
+ const list = procsOnWindows();
15714
+ if (!list) return;
15715
+ const pids = startedUnder(list, pid, since).filter((p) => p !== process.pid);
15716
+ if (!pids.length) return;
15717
+ spawnSync4("taskkill", ["/F", ...pids.flatMap((p) => ["/PID", String(p)])], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
15718
+ }
15719
+ function killMarked(mark, agent) {
15720
+ if (WINDOWS3) {
15721
+ if (agent) killUnderOnWindows(agent.pid, agent.since);
15722
+ return;
15723
+ }
15724
+ signal(marked(mark), "SIGKILL");
15725
+ }
15726
+ function killTreeOnWindows(pid) {
15727
+ if (!WINDOWS3 || !pid) return false;
15728
+ const out = spawnSync4("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
15729
+ return out.status === 0;
15730
+ }
15731
+ function later(ms, fn) {
15732
+ const t = setTimeout(fn, ms);
15733
+ if (typeof t.unref === "function") t.unref();
15734
+ }
15735
+ function endAgent(child, mark, graceMs) {
15736
+ const term = (sig) => {
15737
+ try {
15738
+ child.kill(sig);
15739
+ } catch {
15740
+ }
15741
+ };
15742
+ if (killTreeOnWindows(child.pid)) return;
15743
+ killUnderOnWindows(child.pid);
15744
+ const seen = new Set(marked(mark, child.pid ? [child.pid] : []));
15745
+ term("SIGTERM");
15746
+ signal([...seen].filter((pid) => pid !== child.pid), "SIGTERM");
15747
+ const round = (left) => {
15748
+ const pids = marked(mark, [...seen]);
15749
+ signal(pids, "SIGKILL");
15750
+ for (const pid of pids) seen.add(pid);
15751
+ if (pids.length && left > 1) later(KILL_ROUND_MS, () => round(left - 1));
15752
+ };
15753
+ later(graceMs, () => {
15754
+ term("SIGKILL");
15755
+ round(KILL_ROUNDS);
15756
+ });
15757
+ }
15758
+ function killRunning() {
15759
+ for (const [child, mark] of running) {
15760
+ if (killTreeOnWindows(child.pid)) continue;
15761
+ killUnderOnWindows(child.pid);
15762
+ signal(marked(mark, child.pid ? [child.pid] : []), "SIGKILL");
15763
+ try {
15764
+ child.kill("SIGKILL");
15765
+ } catch {
15766
+ }
15767
+ }
15768
+ running.clear();
15769
+ }
15770
+ function unlisten() {
15771
+ for (const [sig, fn] of listening) process.removeListener(sig, fn);
15772
+ listening.clear();
15773
+ }
15774
+ function onQuit(sig) {
15775
+ killRunning();
15776
+ unlisten();
15777
+ if (process.listenerCount(sig) === 0) process.exit(128 + os6.constants.signals[sig]);
15778
+ }
15779
+ function trackAgent(child, mark) {
15780
+ if (!child.pid) return;
15781
+ running.set(child, mark);
15782
+ child.once("close", () => {
15783
+ running.delete(child);
15784
+ if (!running.size) unlisten();
15785
+ });
15786
+ for (const sig of QUIT_SIGNALS) {
15787
+ if (listening.has(sig) || sig === "SIGINT" && interruptIsTheCallers) continue;
15788
+ const fn = () => onQuit(sig);
15789
+ listening.set(sig, fn);
15790
+ process.on(sig, fn);
15791
+ }
15792
+ }
15793
+ var runMark, stopMark, markEnv, WINDOWS3, KILL_ROUND_MS, KILL_ROUNDS, LIST_PROCS, running, QUIT_SIGNALS, listening, interruptIsTheCallers;
15794
+ var init_stop = __esm({
15795
+ "src/lib/agent/stop.ts"() {
15796
+ "use strict";
15797
+ init_env();
15798
+ init_paths();
15799
+ runMark = (sessionId) => ({ name: RUN_ENV, value: sessionId });
15800
+ stopMark = () => ({ name: STOP_ENV, value: randomUUID5() });
15801
+ markEnv = (env2, mark) => ({ ...env2, [mark.name]: mark.value });
15802
+ WINDOWS3 = process.platform === "win32";
15803
+ KILL_ROUND_MS = 300;
15804
+ KILL_ROUNDS = 3;
15805
+ LIST_PROCS = [
15806
+ "$ErrorActionPreference = 'Stop'",
15807
+ "Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() } }",
15808
+ "'boot {0}' -f ([DateTimeOffset](Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToUnixTimeMilliseconds()"
15809
+ ].join("; ");
15810
+ running = /* @__PURE__ */ new Map();
15811
+ QUIT_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
15812
+ listening = /* @__PURE__ */ new Map();
15813
+ interruptIsTheCallers = false;
15814
+ }
15815
+ });
15816
+
15550
15817
  // src/lib/agent/pause.ts
15551
15818
  function deliveryState(delivery, questions) {
15552
15819
  const landing = delivery.landing;
@@ -15735,12 +16002,12 @@ var init_runner = __esm({
15735
16002
  });
15736
16003
 
15737
16004
  // src/lib/agent/rules.ts
15738
- import fs39 from "node:fs";
15739
- import path43 from "node:path";
16005
+ import fs40 from "node:fs";
16006
+ import path44 from "node:path";
15740
16007
  function ruleFile(agent) {
15741
16008
  if (!agent || hiddenRole(agent)) return "";
15742
16009
  try {
15743
- return fs39.readFileSync(rulePath(agent), "utf8").trim();
16010
+ return fs40.readFileSync(rulePath(agent), "utf8").trim();
15744
16011
  } catch {
15745
16012
  return "";
15746
16013
  }
@@ -15755,11 +16022,11 @@ function setAgentRule(agent, text5) {
15755
16022
  const rule = String(text5 ?? "").trim();
15756
16023
  try {
15757
16024
  if (!rule) {
15758
- fs39.rmSync(rulePath(agent), { force: true });
16025
+ fs40.rmSync(rulePath(agent), { force: true });
15759
16026
  return { ok: true };
15760
16027
  }
15761
- fs39.mkdirSync(RULES, { recursive: true });
15762
- fs39.writeFileSync(rulePath(agent), `${rule}
16028
+ fs40.mkdirSync(RULES, { recursive: true });
16029
+ fs40.writeFileSync(rulePath(agent), `${rule}
15763
16030
  `);
15764
16031
  return { ok: true };
15765
16032
  } catch (err) {
@@ -15807,7 +16074,7 @@ function migrateFlowRules() {
15807
16074
  adoptRenamedRules();
15808
16075
  let here;
15809
16076
  try {
15810
- here = new Set(fs39.readdirSync(RULES));
16077
+ here = new Set(fs40.readdirSync(RULES));
15811
16078
  } catch {
15812
16079
  return [];
15813
16080
  }
@@ -15818,9 +16085,9 @@ function migrateFlowRules() {
15818
16085
  if (!from.length) continue;
15819
16086
  const parts = [ruleFile(owner.name), ...from.map(ruleFile)].filter(Boolean);
15820
16087
  try {
15821
- if (parts.length) fs39.writeFileSync(rulePath(owner.name), `${parts.join("\n\n")}
16088
+ if (parts.length) fs40.writeFileSync(rulePath(owner.name), `${parts.join("\n\n")}
15822
16089
  `);
15823
- for (const flow of from) fs39.rmSync(rulePath(flow), { force: true });
16090
+ for (const flow of from) fs40.rmSync(rulePath(flow), { force: true });
15824
16091
  } catch (err) {
15825
16092
  notes.push(`could not move the ${from.join(", ")} rule(s) onto \`${owner.name}\`: ${String(err)}`);
15826
16093
  continue;
@@ -15834,7 +16101,7 @@ function migrateFlowRules() {
15834
16101
  function adoptRenamedRules() {
15835
16102
  let here;
15836
16103
  try {
15837
- here = fs39.readdirSync(RULES);
16104
+ here = fs40.readdirSync(RULES);
15838
16105
  } catch {
15839
16106
  return;
15840
16107
  }
@@ -15844,13 +16111,13 @@ function adoptRenamedRules() {
15844
16111
  const now = RENAMED_ROLES[was] ?? canonicalSpecAgent(was);
15845
16112
  if (now === was) continue;
15846
16113
  try {
15847
- if (!fs39.existsSync(rulePath(now))) fs39.renameSync(rulePath(was), rulePath(now));
16114
+ if (!fs40.existsSync(rulePath(now))) fs40.renameSync(rulePath(was), rulePath(now));
15848
16115
  else if (FOLDED_SPEC_AGENTS.has(was)) {
15849
16116
  const kept2 = ruleFile(now);
15850
16117
  const carried = ruleFile(was);
15851
- if (carried && !kept2.includes(carried)) fs39.writeFileSync(rulePath(now), `${[kept2, carried].filter(Boolean).join("\n\n")}
16118
+ if (carried && !kept2.includes(carried)) fs40.writeFileSync(rulePath(now), `${[kept2, carried].filter(Boolean).join("\n\n")}
15852
16119
  `);
15853
- fs39.rmSync(rulePath(was), { force: true });
16120
+ fs40.rmSync(rulePath(was), { force: true });
15854
16121
  }
15855
16122
  } catch {
15856
16123
  }
@@ -15867,7 +16134,7 @@ var init_rules2 = __esm({
15867
16134
  init_runner();
15868
16135
  init_workflows();
15869
16136
  init_types3();
15870
- rulePath = (agent) => path43.join(RULES, `${agent}.md`);
16137
+ rulePath = (agent) => path44.join(RULES, `${agent}.md`);
15871
16138
  notOnTheRoster = (name) => `"${name}" is not an agent on this board. It has: ${agentNames().join(", ")}.`;
15872
16139
  flowForRequest = (req) => req.refineRound !== void 0 && REFINE_ACTIONS.has(req.action) ? flowByCommand("refine") : flowByAction(req.action);
15873
16140
  ruleOwnerSays = (owner) => `\`${owner.name}\` agent carries one rule of its own${owner.role ? ", on every flow it runs" : ""}`;
@@ -15952,8 +16219,8 @@ var init_source = __esm({
15952
16219
  });
15953
16220
 
15954
16221
  // src/lib/card-sources.ts
15955
- import fs40 from "node:fs";
15956
- import path44 from "node:path";
16222
+ import fs41 from "node:fs";
16223
+ import path45 from "node:path";
15957
16224
  function planById(id) {
15958
16225
  const found2 = readPlan(`plans/${id}-.md`);
15959
16226
  return found2?.text.trim() ? found2 : null;
@@ -15963,8 +16230,8 @@ function cardLink(id) {
15963
16230
  const found2 = open3 ?? locateArchived(id);
15964
16231
  if (!found2) return null;
15965
16232
  try {
15966
- const file = found2.kind === "group" ? path44.join(found2.target, "root.md") : found2.target;
15967
- const title = parseFrontmatter(fs40.readFileSync(file, "utf8")).meta?.title ?? "";
16233
+ const file = found2.kind === "group" ? path45.join(found2.target, "root.md") : found2.target;
16234
+ const title = parseFrontmatter(fs41.readFileSync(file, "utf8")).meta?.title ?? "";
15968
16235
  return { kind: "card", ref: String(id), title, ...open3 ? {} : { archived: true } };
15969
16236
  } catch {
15970
16237
  return null;
@@ -15989,7 +16256,7 @@ function link(ref, items) {
15989
16256
  if (ref.kind === "plan") return planLink(ref.id);
15990
16257
  if (ref.kind === "card") return cardLink(ref.id);
15991
16258
  if (ref.kind === "url") return urlLink(ref.url);
15992
- const item = items().find((signal2) => path44.basename(signal2.relPath) === ref.file);
16259
+ const item = items().find((signal2) => path45.basename(signal2.relPath) === ref.file);
15993
16260
  return item ? itemLink(item) : null;
15994
16261
  }
15995
16262
  function cardSources(meta, body) {
@@ -16030,12 +16297,12 @@ var init_card_sources = __esm({
16030
16297
  });
16031
16298
 
16032
16299
  // src/lib/view/read.ts
16033
- import fs41 from "node:fs";
16034
- import path45 from "node:path";
16300
+ import fs42 from "node:fs";
16301
+ import path46 from "node:path";
16035
16302
  function readCard(file, relFromTodo) {
16036
- const id = idPrefix(path45.basename(relFromTodo));
16303
+ const id = idPrefix(path46.basename(relFromTodo));
16037
16304
  if (id === null) {
16038
- const parts = relFromTodo.split(path45.sep);
16305
+ const parts = relFromTodo.split(path46.sep);
16039
16306
  const folderId = idPrefix(parts[parts.length - 2] || "");
16040
16307
  if (folderId === null) return null;
16041
16308
  return buildCard(folderId, file, relFromTodo);
@@ -16043,10 +16310,10 @@ function readCard(file, relFromTodo) {
16043
16310
  return buildCard(id, file, relFromTodo);
16044
16311
  }
16045
16312
  function buildCard(id, file, relFromTodo) {
16046
- const text5 = fs41.readFileSync(file, "utf8");
16313
+ const text5 = fs42.readFileSync(file, "utf8");
16047
16314
  const { meta, body } = parseFrontmatter(text5);
16048
16315
  if (!meta) return null;
16049
- const relPath = relFromTodo.split(path45.sep).join("/");
16316
+ const relPath = relFromTodo.split(path46.sep).join("/");
16050
16317
  const flow = workflowFor(meta.workflow);
16051
16318
  const plan = !!meta.workflow && archivesOnApproval(flow);
16052
16319
  const stages = cardStages(meta, flow).length;
@@ -16055,7 +16322,7 @@ function buildCard(id, file, relFromTodo) {
16055
16322
  // Derived from the file exactly as it is on disk (lib/board/revision.ts), so a card
16056
16323
  // read here and a card read by the contract agree on what version this is.
16057
16324
  revision: revisionOf(text5),
16058
- updatedAt: fs41.statSync(file).mtime.toISOString(),
16325
+ updatedAt: fs42.statSync(file).mtime.toISOString(),
16059
16326
  relPath,
16060
16327
  title: meta.title,
16061
16328
  priority: meta.priority,
@@ -16076,22 +16343,22 @@ function buildCard(id, file, relFromTodo) {
16076
16343
  };
16077
16344
  }
16078
16345
  function readGroup2(folderName) {
16079
- const groupDir = path45.join(TODO, folderName);
16080
- const rootFile = path45.join(groupDir, "root.md");
16081
- if (!fs41.existsSync(rootFile)) return null;
16082
- const root = readCard(rootFile, path45.join(folderName, "root.md"));
16346
+ const groupDir = path46.join(TODO, folderName);
16347
+ const rootFile = path46.join(groupDir, "root.md");
16348
+ if (!fs42.existsSync(rootFile)) return null;
16349
+ const root = readCard(rootFile, path46.join(folderName, "root.md"));
16083
16350
  if (!root) return null;
16084
16351
  root.isGroup = true;
16085
16352
  const { total, resolved: resolved2 } = subtaskLines(root.body);
16086
16353
  root.subtaskLines = { total, resolved: resolved2 };
16087
16354
  const subCards = [];
16088
16355
  const recurse = (dir, relDir) => {
16089
- for (const entry of fs41.readdirSync(dir, { withFileTypes: true })) {
16090
- const childRel = path45.join(relDir, entry.name);
16356
+ for (const entry of fs42.readdirSync(dir, { withFileTypes: true })) {
16357
+ const childRel = path46.join(relDir, entry.name);
16091
16358
  if (entry.isDirectory()) {
16092
- recurse(path45.join(dir, entry.name), childRel);
16359
+ recurse(path46.join(dir, entry.name), childRel);
16093
16360
  } else if (entry.name.endsWith(".md") && entry.name !== "README.md" && entry.name !== "root.md") {
16094
- const c = readCard(path45.join(dir, entry.name), childRel);
16361
+ const c = readCard(path46.join(dir, entry.name), childRel);
16095
16362
  if (c) {
16096
16363
  c.parent = { id: root.id, title: root.title };
16097
16364
  subCards.push(c);
@@ -16112,12 +16379,12 @@ function readGroup2(folderName) {
16112
16379
  return { root, subCards };
16113
16380
  }
16114
16381
  function standaloneCards(dirRel) {
16115
- const dir = dirRel ? path45.join(TODO, dirRel) : TODO;
16116
- if (!fs41.existsSync(dir)) return [];
16382
+ const dir = dirRel ? path46.join(TODO, dirRel) : TODO;
16383
+ if (!fs42.existsSync(dir)) return [];
16117
16384
  const cards = [];
16118
- for (const entry of fs41.readdirSync(dir, { withFileTypes: true })) {
16385
+ for (const entry of fs42.readdirSync(dir, { withFileTypes: true })) {
16119
16386
  if (entry.isFile() && entry.name.endsWith(".md") && entry.name !== "README.md") {
16120
- const c = readCard(path45.join(dir, entry.name), path45.join(dirRel, entry.name));
16387
+ const c = readCard(path46.join(dir, entry.name), path46.join(dirRel, entry.name));
16121
16388
  if (c) cards.push(c);
16122
16389
  }
16123
16390
  }
@@ -16129,7 +16396,7 @@ function collectCards() {
16129
16396
  const top = standaloneCards("");
16130
16397
  board2.push(...top);
16131
16398
  every.push(...top);
16132
- for (const entry of fs41.readdirSync(TODO, { withFileTypes: true })) {
16399
+ for (const entry of fs42.readdirSync(TODO, { withFileTypes: true })) {
16133
16400
  if (!entry.isDirectory()) continue;
16134
16401
  if (isGroupFolder(entry.name)) {
16135
16402
  const g = readGroup2(entry.name);
@@ -16161,7 +16428,7 @@ function findCard(id) {
16161
16428
  }
16162
16429
  function attachSources(card) {
16163
16430
  try {
16164
- const { meta, body } = parseFrontmatter(fs41.readFileSync(path45.join(TODO, card.relPath), "utf8"));
16431
+ const { meta, body } = parseFrontmatter(fs42.readFileSync(path46.join(TODO, card.relPath), "utf8"));
16165
16432
  const sources = meta ? cardSources(meta, body) : [];
16166
16433
  if (sources.length) card.sources = sources;
16167
16434
  } catch {
@@ -16349,8 +16616,8 @@ var init_review = __esm({
16349
16616
  });
16350
16617
 
16351
16618
  // src/lib/agent/deliveries.ts
16352
- import fs42 from "node:fs";
16353
- import path46 from "node:path";
16619
+ import fs43 from "node:fs";
16620
+ import path47 from "node:path";
16354
16621
  function writeAudit(delivery, runs) {
16355
16622
  const known2 = new Map(readAudit(delivery.deliveryId)?.sessions.map((s) => [s.sessionId, s]) ?? []);
16356
16623
  const sessions = delivery.sessions.flatMap((id) => {
@@ -16378,10 +16645,10 @@ function writeAudit(delivery, runs) {
16378
16645
  }
16379
16646
  function writeAuditFile(record) {
16380
16647
  try {
16381
- fs42.mkdirSync(DELIVERIES, { recursive: true });
16648
+ fs43.mkdirSync(DELIVERIES, { recursive: true });
16382
16649
  const tmp = `${auditPath(record.deliveryId)}.tmp`;
16383
- fs42.writeFileSync(tmp, JSON.stringify(record, null, 2) + "\n");
16384
- fs42.renameSync(tmp, auditPath(record.deliveryId));
16650
+ fs43.writeFileSync(tmp, JSON.stringify(record, null, 2) + "\n");
16651
+ fs43.renameSync(tmp, auditPath(record.deliveryId));
16385
16652
  return true;
16386
16653
  } catch {
16387
16654
  return false;
@@ -16389,7 +16656,7 @@ function writeAuditFile(record) {
16389
16656
  }
16390
16657
  function readAudit(deliveryId) {
16391
16658
  try {
16392
- const data = JSON.parse(fs42.readFileSync(auditPath(deliveryId), "utf8"));
16659
+ const data = JSON.parse(fs43.readFileSync(auditPath(deliveryId), "utf8"));
16393
16660
  return { sessions: Array.isArray(data?.sessions) ? data.sessions : [] };
16394
16661
  } catch {
16395
16662
  return null;
@@ -16404,7 +16671,7 @@ function syncAudit(deliveryId, just) {
16404
16671
  }
16405
16672
  function wholeAudit(file) {
16406
16673
  try {
16407
- const data = JSON.parse(fs42.readFileSync(file, "utf8"));
16674
+ const data = JSON.parse(fs43.readFileSync(file, "utf8"));
16408
16675
  return typeof data?.deliveryId === "string" && Array.isArray(data.sessions) ? data : null;
16409
16676
  } catch {
16410
16677
  return null;
@@ -16417,14 +16684,14 @@ function activeAudit(file) {
16417
16684
  function allAudits() {
16418
16685
  let names4;
16419
16686
  try {
16420
- names4 = fs42.readdirSync(DELIVERIES);
16687
+ names4 = fs43.readdirSync(DELIVERIES);
16421
16688
  } catch {
16422
16689
  return [];
16423
16690
  }
16424
16691
  const out = [];
16425
16692
  for (const name of names4) {
16426
16693
  if (!name.endsWith(".json")) continue;
16427
- const audit = wholeAudit(path46.join(DELIVERIES, name));
16694
+ const audit = wholeAudit(path47.join(DELIVERIES, name));
16428
16695
  if (audit) out.push(audit);
16429
16696
  }
16430
16697
  return out;
@@ -16535,11 +16802,11 @@ function resumeRefusal(delivery, store) {
16535
16802
  );
16536
16803
  }
16537
16804
  if (!worktreeExists(delivery.worktree)) {
16538
- const path85 = delivery.worktree ?? "";
16805
+ const path87 = delivery.worktree ?? "";
16539
16806
  return refusal(
16540
16807
  "deliveryWorktreeGone",
16541
- `delivery ${id}'s worktree ${path85} is gone, so there is nothing to carry on. ${rebuild}`,
16542
- { id, task, path: path85, command: discard }
16808
+ `delivery ${id}'s worktree ${path87} is gone, so there is nothing to carry on. ${rebuild}`,
16809
+ { id, task, path: path87, command: discard }
16543
16810
  );
16544
16811
  }
16545
16812
  if (!branchExists(delivery.branch)) {
@@ -16592,11 +16859,12 @@ function tidyCheckout(deliveryId) {
16592
16859
  const store = readStore();
16593
16860
  const row = store.deliveries.find((d) => d.deliveryId === deliveryId) ?? auditOnly(deliveryId);
16594
16861
  if (!row || row.status === "active") return NOTHING;
16595
- if (!row.worktree && !row.branch) return NOTHING;
16596
- if (isResumable(row)) return { removed: false, kept: true };
16597
16862
  if (store.runs.some((r) => r.deliveryId === deliveryId && runIsLive(r))) {
16598
16863
  return { removed: false, kept: false, error: `a run of delivery ${deliveryId} is still going`, reason: "deliveryRunGoing", args: { id: deliveryId } };
16599
16864
  }
16865
+ if (row.status !== "finished" || Date.now() - (row.endedAt ?? 0) > 3e4) stopWatchers(row.sessions);
16866
+ if (!row.worktree && !row.branch) return NOTHING;
16867
+ if (isResumable(row)) return { removed: false, kept: true };
16600
16868
  const removed = removeWorktree(row.worktree, row.branch, true);
16601
16869
  if (!removed.ok) return { removed: false, kept: false, error: removed.error };
16602
16870
  forgetCheckout(deliveryId);
@@ -16619,7 +16887,10 @@ function forgetCheckout(deliveryId) {
16619
16887
  function sweepCheckouts() {
16620
16888
  const seen = /* @__PURE__ */ new Set();
16621
16889
  const complaints = [];
16622
- const rows = [...readStore().deliveries, ...allAudits().flatMap((a) => auditRow(a) ?? [])];
16890
+ const store = readStore();
16891
+ const rows = [...store.deliveries, ...allAudits().flatMap((a) => auditRow(a) ?? [])];
16892
+ 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)));
16893
+ stopWatchers([...new Set(ended.flatMap((row) => row.sessions))]);
16623
16894
  for (const row of rows) {
16624
16895
  if (seen.has(row.deliveryId) || row.status === "active" || !row.worktree) continue;
16625
16896
  seen.add(row.deliveryId);
@@ -16629,21 +16900,27 @@ function sweepCheckouts() {
16629
16900
  dropEmptyWorktreeFolders();
16630
16901
  return complaints;
16631
16902
  }
16632
- function resumeRecord(id) {
16633
- const found2 = endedDelivery(id);
16903
+ function resumeRecord(id, execution) {
16904
+ const continueActive = !!execution;
16905
+ const found2 = (continueActive ? namedDelivery(id) : void 0) ?? endedDelivery(id);
16634
16906
  if (!found2) return { ok: false, ...unknownDelivery(id) };
16635
16907
  const refused = resumeRefusal(found2);
16636
- if (refused) return { ok: false, ...refused };
16908
+ if (refused && !(continueActive && found2.status === "active")) return { ok: false, ...refused };
16637
16909
  const out = withStore((store) => {
16638
16910
  const audit = wholeAudit(auditPath(found2.deliveryId));
16639
- const row = (audit && auditRow(audit)) ?? store.deliveries.find((d) => d.deliveryId === found2.deliveryId);
16911
+ const live = store.deliveries.find((d) => d.deliveryId === found2.deliveryId);
16912
+ const row = continueActive && live?.status === "active" ? live : (audit && auditRow(audit)) ?? live;
16640
16913
  if (!row) return { ok: false, ...unknownDelivery(id) };
16641
16914
  const again = resumeRefusal(row, store);
16642
- if (again) return { ok: false, ...again };
16915
+ if (continueActive && row.status === "active") {
16916
+ if (store.runs.some((r) => r.deliveryId === row.deliveryId && runIsLive(r))) {
16917
+ return { ok: false, ...refusal("deliveryRunGoing", "the delivery still has a running agent; stop it before continuing") };
16918
+ }
16919
+ } else if (again) return { ok: false, ...again };
16643
16920
  const at = Date.now();
16644
16921
  const resumed = {
16645
16922
  ...row,
16646
- cloudExecution: executionOf() ?? row.cloudExecution,
16923
+ cloudExecution: execution ?? executionOf() ?? row.cloudExecution,
16647
16924
  status: "active",
16648
16925
  endedAt: void 0,
16649
16926
  steps: [...row.steps, { step: "resume", at }],
@@ -16672,10 +16949,10 @@ function carryOnFrom(deliveryId) {
16672
16949
  function approvedRequirements(cardId2) {
16673
16950
  const found2 = locate(cardId2);
16674
16951
  if (!found2) return "";
16675
- const file = found2.kind === "group" ? path46.join(found2.target, "root.md") : found2.target;
16952
+ const file = found2.kind === "group" ? path47.join(found2.target, "root.md") : found2.target;
16676
16953
  let text5;
16677
16954
  try {
16678
- text5 = fs42.readFileSync(file, "utf8");
16955
+ text5 = fs43.readFileSync(file, "utf8");
16679
16956
  } catch {
16680
16957
  return "";
16681
16958
  }
@@ -16705,8 +16982,8 @@ function cardMeta2(cardId2) {
16705
16982
  try {
16706
16983
  const found2 = locate(cardId2);
16707
16984
  if (!found2) return null;
16708
- const file = found2.kind === "group" ? path46.join(found2.target, "root.md") : found2.target;
16709
- return parseFrontmatter(fs42.readFileSync(file, "utf8")).meta;
16985
+ const file = found2.kind === "group" ? path47.join(found2.target, "root.md") : found2.target;
16986
+ return parseFrontmatter(fs43.readFileSync(file, "utf8")).meta;
16710
16987
  } catch {
16711
16988
  return null;
16712
16989
  }
@@ -16955,6 +17232,7 @@ var init_deliveries = __esm({
16955
17232
  init_complete();
16956
17233
  init_outputs();
16957
17234
  init_env();
17235
+ init_stop();
16958
17236
  init_flows();
16959
17237
  init_pause();
16960
17238
  init_rules2();
@@ -16964,7 +17242,7 @@ var init_deliveries = __esm({
16964
17242
  init_store();
16965
17243
  init_types3();
16966
17244
  init_worktree();
16967
- auditPath = (deliveryId) => path46.join(DELIVERIES, `${deliveryId}.json`);
17245
+ auditPath = (deliveryId) => path47.join(DELIVERIES, `${deliveryId}.json`);
16968
17246
  activeAudits = () => allAudits().filter((a) => a.status === "active");
16969
17247
  auditRow = (audit) => readDeliveryRow({ ...audit, sessions: audit.sessions.map((s) => s.sessionId) });
16970
17248
  lastSessionRunning = (audit) => audit.sessions[audit.sessions.length - 1]?.status === "running";
@@ -16992,6 +17270,41 @@ var init_deliveries = __esm({
16992
17270
  }
16993
17271
  });
16994
17272
 
17273
+ // src/lib/agent/landing-lock.ts
17274
+ import fs44 from "node:fs";
17275
+ import path48 from "node:path";
17276
+ function lockLanding() {
17277
+ const dir = path48.join(SESSIONS_DIR, ".landing.lock");
17278
+ try {
17279
+ const entries = fs44.readdirSync(dir);
17280
+ const token3 = entries.length === 1 ? entries[0] : "";
17281
+ const match = /^(\d+)-[a-f0-9-]{36}$/.exec(token3);
17282
+ const stat = fs44.statSync(dir);
17283
+ if (match && Date.now() - stat.mtimeMs > landingLimits.staleMs) {
17284
+ stopWatchers(void 0, Number(match[1]), () => {
17285
+ const now = fs44.readdirSync(dir);
17286
+ return now.length === 1 && now[0] === token3 && Date.now() - fs44.statSync(dir).mtimeMs > landingLimits.staleMs;
17287
+ }, stat.birthtimeMs || stat.mtimeMs);
17288
+ }
17289
+ } catch {
17290
+ }
17291
+ return tryLock(dir);
17292
+ }
17293
+ function renewLandingLock() {
17294
+ const now = /* @__PURE__ */ new Date();
17295
+ fs44.utimesSync(path48.join(SESSIONS_DIR, ".landing.lock"), now, now);
17296
+ }
17297
+ var landingLimits;
17298
+ var init_landing_lock = __esm({
17299
+ "src/lib/agent/landing-lock.ts"() {
17300
+ "use strict";
17301
+ init_lock();
17302
+ init_paths();
17303
+ init_stop();
17304
+ landingLimits = { staleMs: 5 * 6e4 };
17305
+ }
17306
+ });
17307
+
16995
17308
  // src/lib/agent/answers.ts
16996
17309
  function answerOutcome(delivery) {
16997
17310
  return pendingAnswers(delivery).some((a) => a.outcome === "changed") ? "changed" : "unchanged";
@@ -17056,8 +17369,8 @@ var init_retry = __esm({
17056
17369
  });
17057
17370
 
17058
17371
  // src/lib/agent/landing.ts
17059
- import fs43 from "node:fs";
17060
- import path47 from "node:path";
17372
+ import fs45 from "node:fs";
17373
+ import path49 from "node:path";
17061
17374
  function waitingOut(delivery, now = Date.now()) {
17062
17375
  const landing = delivery.landing;
17063
17376
  if (!landing) return false;
@@ -17193,8 +17506,9 @@ function noteQueue(held4) {
17193
17506
  }
17194
17507
  async function advanceLanding() {
17195
17508
  let release;
17509
+ let current;
17196
17510
  try {
17197
- release = tryLock(path47.join(SESSIONS_DIR, ".landing.lock"));
17511
+ release = lockLanding();
17198
17512
  if (!release) return null;
17199
17513
  const owed = await owedRestart();
17200
17514
  if (owed) return owed;
@@ -17209,11 +17523,19 @@ async function advanceLanding() {
17209
17523
  return null;
17210
17524
  }
17211
17525
  tried.add(picked.deliveryId);
17526
+ current = picked;
17527
+ renewLandingLock();
17212
17528
  const step = await landStep(picked);
17213
17529
  if (step.start) return step.start;
17214
17530
  if (!step.done) return null;
17215
17531
  }
17216
- } catch {
17532
+ } catch (error) {
17533
+ if (current && error instanceof GitTimeoutError) {
17534
+ giveUpSlot(current, error.message);
17535
+ patchLanding(current.deliveryId, (landing) => {
17536
+ landing.retryAt = Date.now() + 3e4;
17537
+ });
17538
+ }
17217
17539
  return null;
17218
17540
  } finally {
17219
17541
  release?.();
@@ -17530,7 +17852,7 @@ async function settleAlreadyLanded(delivery) {
17530
17852
  return true;
17531
17853
  }
17532
17854
  function repairLanding() {
17533
- const release = tryLock(path47.join(SESSIONS_DIR, ".landing.lock"));
17855
+ const release = lockLanding();
17534
17856
  if (!release) return [];
17535
17857
  try {
17536
17858
  return repairIdleLanding();
@@ -17563,7 +17885,7 @@ var init_landing = __esm({
17563
17885
  init_execution();
17564
17886
  init_board();
17565
17887
  init_io();
17566
- init_lock();
17888
+ init_landing_lock();
17567
17889
  init_paths();
17568
17890
  init_answers();
17569
17891
  init_commit_mode();
@@ -17604,9 +17926,9 @@ var init_landing = __esm({
17604
17926
  sameDir = (a, b) => {
17605
17927
  const real2 = (dir) => {
17606
17928
  try {
17607
- return fs43.realpathSync(dir);
17929
+ return fs45.realpathSync(dir);
17608
17930
  } catch {
17609
- return path47.resolve(dir);
17931
+ return path49.resolve(dir);
17610
17932
  }
17611
17933
  };
17612
17934
  return real2(a) === real2(b);
@@ -17615,35 +17937,35 @@ var init_landing = __esm({
17615
17937
  });
17616
17938
 
17617
17939
  // src/lib/agent/pictures.ts
17618
- import fs44 from "node:fs";
17619
- import path48 from "node:path";
17940
+ import fs46 from "node:fs";
17941
+ import path50 from "node:path";
17620
17942
  function claimRunPictures(box2, sessionId, names4 = []) {
17621
17943
  if (!box2 || !freeBox(box2) || names4.length === 0) return [];
17622
17944
  const from = pictureBox(box2);
17623
17945
  const to = pictureBox(sessionId);
17624
17946
  try {
17625
- fs44.mkdirSync(SESSIONS_DIR, { recursive: true });
17626
- fs44.renameSync(from, to);
17947
+ fs46.mkdirSync(SESSIONS_DIR, { recursive: true });
17948
+ fs46.renameSync(from, to);
17627
17949
  } catch {
17628
17950
  return [];
17629
17951
  }
17630
- return names4.filter(pictureName).map((name) => path48.join(to, name)).filter((file) => fs44.existsSync(file));
17952
+ return names4.filter(pictureName).map((name) => path50.join(to, name)).filter((file) => fs46.existsSync(file));
17631
17953
  }
17632
17954
  function returnRunPictures(sessionId, box2) {
17633
17955
  if (!box2 || !boxId(box2)) return;
17634
17956
  try {
17635
- fs44.renameSync(pictureBox(sessionId), pictureBox(box2));
17957
+ fs46.renameSync(pictureBox(sessionId), pictureBox(box2));
17636
17958
  } catch {
17637
17959
  }
17638
17960
  }
17639
17961
  function moveRunPictures(from, to, files2 = []) {
17640
17962
  if (files2.length === 0) return [];
17641
17963
  try {
17642
- fs44.renameSync(pictureBox(from), pictureBox(to));
17964
+ fs46.renameSync(pictureBox(from), pictureBox(to));
17643
17965
  } catch {
17644
17966
  return files2;
17645
17967
  }
17646
- return files2.map((file) => path48.join(pictureBox(to), path48.basename(file)));
17968
+ return files2.map((file) => path50.join(pictureBox(to), path50.basename(file)));
17647
17969
  }
17648
17970
  var pictureName, boxId, freeBox, pictureBox;
17649
17971
  var init_pictures = __esm({
@@ -17652,14 +17974,14 @@ var init_pictures = __esm({
17652
17974
  init_paths();
17653
17975
  pictureName = (name) => /^[0-9a-f-]{36}\.[a-z0-9]{2,5}$/.test(name);
17654
17976
  boxId = (box2) => /^[0-9a-f-]{36}$/.test(box2);
17655
- freeBox = (box2) => boxId(box2) && !fs44.existsSync(path48.join(SESSIONS_DIR, `${box2}.log`));
17656
- pictureBox = (box2) => path48.join(SESSIONS_DIR, `${box2}.images`);
17977
+ freeBox = (box2) => boxId(box2) && !fs46.existsSync(path50.join(SESSIONS_DIR, `${box2}.log`));
17978
+ pictureBox = (box2) => path50.join(SESSIONS_DIR, `${box2}.images`);
17657
17979
  }
17658
17980
  });
17659
17981
 
17660
17982
  // src/lib/memories.ts
17661
- import fs45 from "node:fs";
17662
- import path49 from "node:path";
17983
+ import fs47 from "node:fs";
17984
+ import path51 from "node:path";
17663
17985
  function readMemory(text5, builtIn, folder) {
17664
17986
  const { meta, body } = splitFrontmatter(text5);
17665
17987
  if (meta === null) return null;
@@ -17679,7 +18001,7 @@ function readMemory(text5, builtIn, folder) {
17679
18001
  rules: body.trim(),
17680
18002
  text: text5,
17681
18003
  builtIn,
17682
- dir: path49.join(MEMORY, folder)
18004
+ dir: path51.join(MEMORY, folder)
17683
18005
  };
17684
18006
  }
17685
18007
  function globalMemories() {
@@ -17690,14 +18012,14 @@ function globalMemories() {
17690
18012
  }
17691
18013
  let folders2 = [];
17692
18014
  try {
17693
- folders2 = fs45.readdirSync(MEMORY, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
18015
+ folders2 = fs47.readdirSync(MEMORY, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).sort();
17694
18016
  } catch {
17695
18017
  }
17696
18018
  for (const name of folders2) {
17697
18019
  if (name in BUNDLED_MEMORY_FILES || name === RESERVED_MEMORY_DIR) continue;
17698
- const file = path49.join(MEMORY, name, GLOBAL_MEMORY_FILE);
17699
- if (!fs45.existsSync(file)) continue;
17700
- const memory = readMemory(fs45.readFileSync(file, "utf8"), false, name);
18020
+ const file = path51.join(MEMORY, name, GLOBAL_MEMORY_FILE);
18021
+ if (!fs47.existsSync(file)) continue;
18022
+ const memory = readMemory(fs47.readFileSync(file, "utf8"), false, name);
17701
18023
  if (memory) out.push(memory);
17702
18024
  }
17703
18025
  return out;
@@ -17753,16 +18075,16 @@ var init_facts = __esm({
17753
18075
  });
17754
18076
 
17755
18077
  // src/lib/view/archive.ts
17756
- import fs46 from "node:fs";
17757
- import path50 from "node:path";
18078
+ import fs48 from "node:fs";
18079
+ import path52 from "node:path";
17758
18080
  function archivedId(file) {
17759
- const own = idPrefix(path50.basename(file));
17760
- return own !== null ? own : idPrefix(path50.basename(path50.dirname(file)));
18081
+ const own = idPrefix(path52.basename(file));
18082
+ return own !== null ? own : idPrefix(path52.basename(path52.dirname(file)));
17761
18083
  }
17762
18084
  function readFile(file) {
17763
18085
  const id = archivedId(file);
17764
18086
  if (id === null) return null;
17765
- const { meta, body } = parseFrontmatter(fs46.readFileSync(file, "utf8"));
18087
+ const { meta, body } = parseFrontmatter(fs48.readFileSync(file, "utf8"));
17766
18088
  if (!meta) return null;
17767
18089
  return {
17768
18090
  row: {
@@ -17770,15 +18092,15 @@ function readFile(file) {
17770
18092
  title: meta.title,
17771
18093
  archived: meta.archived,
17772
18094
  rejected: meta.rejected,
17773
- relPath: rel(file).split(path50.sep).join("/")
18095
+ relPath: rel(file).split(path52.sep).join("/")
17774
18096
  },
17775
18097
  body: body.replace(/^\n+/, "").replace(/\s+$/, ""),
17776
18098
  meta
17777
18099
  };
17778
18100
  }
17779
18101
  function readArchive() {
17780
- const relPath = rel(ARCHIVE).split(path50.sep).join("/");
17781
- if (!fs46.existsSync(ARCHIVE)) return { relPath, cards: [] };
18102
+ const relPath = rel(ARCHIVE).split(path52.sep).join("/");
18103
+ if (!fs48.existsSync(ARCHIVE)) return { relPath, cards: [] };
17782
18104
  const cards = walkMd(ARCHIVE).map(readFile).filter((found2) => found2 !== null).map((found2) => found2.row);
17783
18105
  cards.sort((a, b) => b.id - a.id);
17784
18106
  return { relPath, cards };
@@ -17793,7 +18115,7 @@ var init_archive = __esm({
17793
18115
  });
17794
18116
 
17795
18117
  // src/lib/agent/prompts.ts
17796
- import path51 from "node:path";
18118
+ import path53 from "node:path";
17797
18119
  function resumePrompt(deliveryId, cardId2, action) {
17798
18120
  if (!deliveryId) return RESUME_PROMPT;
17799
18121
  if (action === "conflict") {
@@ -17837,7 +18159,7 @@ function buildAsk(rawReq, notes = []) {
17837
18159
  }
17838
18160
  function cardFileOf(id) {
17839
18161
  const found2 = id === void 0 ? null : locate(id);
17840
- return found2 ? found2.kind === "group" ? path51.join(found2.target, "root.md") : found2.target : "";
18162
+ return found2 ? found2.kind === "group" ? path53.join(found2.target, "root.md") : found2.target : "";
17841
18163
  }
17842
18164
  function realPaths(text5, req) {
17843
18165
  if (req.action !== "scheduled" && req.action !== "sub") return text5;
@@ -17930,7 +18252,7 @@ function frozenRules(req) {
17930
18252
  function archivedCardFile(id) {
17931
18253
  const found2 = locateArchived(id);
17932
18254
  if (!found2) return `${rel(ARCHIVE)}/`;
17933
- return rel(found2.kind === "group" ? path51.join(found2.target, "root.md") : found2.target);
18255
+ return rel(found2.kind === "group" ? path53.join(found2.target, "root.md") : found2.target);
17934
18256
  }
17935
18257
  function shippedLines(cardId2) {
17936
18258
  const delivery = endedDelivery(`${cardId2}`);
@@ -18101,7 +18423,7 @@ function actionPrompt(req, command, notes) {
18101
18423
  case "spec": {
18102
18424
  const agent = findSpecAgent(req.specAgent ?? "");
18103
18425
  const found2 = req.id === void 0 ? null : locate(req.id);
18104
- const cardFile3 = found2 ? rel(found2.kind === "group" ? path51.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
18426
+ const cardFile3 = found2 ? rel(found2.kind === "group" ? path53.join(found2.target, "root.md") : found2.target) : `task #${req.id}`;
18105
18427
  const own = agent ? specAgentInstructions(agent) : null;
18106
18428
  if (own) notes.push(...own.notes);
18107
18429
  const memory = agent ? agentMemoryBlock(agent) : "";
@@ -18213,289 +18535,82 @@ ${shared}` : ""
18213
18535
  `${kb}. Task ${req.id} ${named2} has been approved: write the previews that were waiting on that Approve from the card as it stands.`,
18214
18536
  req.notes ? `Extra notes: ${req.notes}` : "",
18215
18537
  `Don't ask me questions with human-in-the-loop. Leave any questions as open questions.`
18216
- ].filter(Boolean).join(" ");
18217
- case "resolve":
18218
- return [
18219
- `${kb}. Apply my answers to the open questions on task ${req.id} ${named2} following \`akb guide resolve\`.`,
18220
- carriedNote(req),
18221
- answeredNote(req.id, command),
18222
- req.notes ? `Extra notes: ${req.notes}` : ""
18223
- ].filter(Boolean).join(" ");
18224
- }
18225
- }
18226
- function discardedCardsPrompt(cards = []) {
18227
- if (!cards.length) return "";
18228
- 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");
18229
- }
18230
- 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;
18231
- var init_prompts = __esm({
18232
- "src/lib/agent/prompts.ts"() {
18233
- "use strict";
18234
- init_cards();
18235
- init_memory();
18236
- init_memories();
18237
- init_paths();
18238
- init_agents();
18239
- init_command();
18240
- init_deliveries();
18241
- init_env();
18242
- init_facts();
18243
- init_outputs();
18244
- init_archive();
18245
- init_flows();
18246
- init_resolve();
18247
- init_runner();
18248
- init_workflows();
18249
- init_catalog2();
18250
- init_roles();
18251
- init_rules2();
18252
- init_settings2();
18253
- init_types3();
18254
- RESUME_PROMPT = [
18255
- `Continue. The previous run ended before it finished the task.`,
18256
- `Pick up where you left off and carry it through.`
18257
- ].join(" ");
18258
- DELIVERY_RESUME = [
18259
- `Continue delivery %s. The previous run ended before the delivery finished.`,
18260
- `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.`
18261
- ].join(" ");
18262
- DELIVERY_RESUME_CARD = `Build the card as the delivery holds it, not as the file reads now: \`%c\` prints the approved copy.`;
18263
- RESTARTABLE = /* @__PURE__ */ new Set([
18264
- "implement",
18265
- "clarify",
18266
- "resolve",
18267
- "approve",
18268
- "archive",
18269
- "spec",
18270
- "conflict",
18271
- "scheduled"
18272
- ]);
18273
- RESTART_LEAD = [
18274
- `The session you were continuing is gone, and this one holds nothing of it.`,
18275
- `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.`
18276
- ].join(" ");
18277
- restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
18278
- NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
18279
- BOARD_FOLDER = "<board folder>";
18280
- CARD_FILE = "<card file>";
18281
- PROJECT_FOLDER = "<project folder>";
18282
- PLANNING_FOR = /* @__PURE__ */ new Set(["create", "clarify", "resolve", "approve", "edit"]);
18283
- SPEC_SELECTOR_FOR = /* @__PURE__ */ new Set(["clarify", "resolve", "approve", "edit"]);
18284
- reflectedCards = (req) => req.cards ?? (req.id !== void 0 ? [req.id] : []);
18285
- }
18286
- });
18287
-
18288
- // src/lib/agent/stop.ts
18289
- import { spawnSync as spawnSync4 } from "node:child_process";
18290
- import { randomUUID as randomUUID5 } from "node:crypto";
18291
- import fs47 from "node:fs";
18292
- import os6 from "node:os";
18293
- function markedInProc(entry, strict = false) {
18294
- const pids = [];
18295
- for (const name of fs47.readdirSync("/proc")) {
18296
- if (!/^\d+$/.test(name)) continue;
18297
- try {
18298
- if (fs47.readFileSync(`/proc/${name}/environ`, "utf8").split("\0").includes(entry)) pids.push(Number(name));
18299
- } catch (error) {
18300
- if (strict && !["ENOENT", "ESRCH"].includes(error.code ?? "")) {
18301
- const stat = fs47.statSync(`/proc/${name}`, { throwIfNoEntry: false });
18302
- if (stat?.uid === process.getuid?.()) throw error;
18303
- }
18304
- }
18305
- }
18306
- return pids;
18307
- }
18308
- function markedInPs(entry, roots) {
18309
- const ps = spawnSync4("ps", ["-A", "-E", "-ww", "-o", "pid=,ppid=,command="], {
18310
- encoding: "utf8",
18311
- maxBuffer: 64 * 1024 * 1024,
18312
- timeout: 5e3
18313
- });
18314
- if (ps.status !== 0 || !ps.stdout) throw new Error("\u65E0\u6CD5\u67E5\u8BE2\u8FDB\u7A0B\u6811\u3002");
18315
- const children = /* @__PURE__ */ new Map();
18316
- const listed2 = /* @__PURE__ */ new Set();
18317
- const found2 = /* @__PURE__ */ new Set();
18318
- for (const line of ps.stdout.split("\n")) {
18319
- const m = /^\s*(\d+)\s+(\d+)\s(.*)$/.exec(line);
18320
- if (!m) continue;
18321
- const pid = Number(m[1]);
18322
- const ppid = Number(m[2]);
18323
- listed2.add(pid);
18324
- children.set(ppid, [...children.get(ppid) ?? [], pid]);
18325
- if (`${m[3]} `.includes(` ${entry} `)) found2.add(pid);
18326
- }
18327
- const queue = [...found2, ...roots.filter((pid) => listed2.has(pid))];
18328
- for (const pid of queue) {
18329
- found2.add(pid);
18330
- for (const child of children.get(pid) ?? []) if (!found2.has(child)) queue.push(child);
18331
- }
18332
- return [...found2];
18333
- }
18334
- function marked(mark, roots = []) {
18335
- if (WINDOWS3 || !mark.value) return [];
18336
- const entry = `${mark.name}=${mark.value}`;
18337
- try {
18338
- const pids = process.platform === "linux" ? markedInProc(entry) : markedInPs(entry, roots);
18339
- return pids.filter((pid) => pid !== process.pid);
18340
- } catch {
18341
- return [];
18342
- }
18343
- }
18344
- function signal(pids, sig) {
18345
- for (const pid of pids) {
18346
- try {
18347
- process.kill(pid, sig);
18348
- } catch {
18349
- }
18350
- }
18351
- }
18352
- function startedUnder(list, root, since) {
18353
- const self = list.procs.find((p) => p.pid === root);
18354
- const from = since ?? self?.startedAt;
18355
- if (from === void 0 || list.bootedAt > from) return [];
18356
- if (self && self.startedAt > from) return [];
18357
- const found2 = self ? [root] : [];
18358
- const seen = /* @__PURE__ */ new Set([root]);
18359
- const queue = [{ pid: root, startedAt: from }];
18360
- for (const parent of queue) {
18361
- for (const p of list.procs) {
18362
- if (p.ppid !== parent.pid || seen.has(p.pid) || p.startedAt < parent.startedAt) continue;
18363
- seen.add(p.pid);
18364
- found2.push(p.pid);
18365
- queue.push(p);
18366
- }
18367
- }
18368
- return found2.reverse();
18369
- }
18370
- function readProcList(out) {
18371
- const procs = [];
18372
- let bootedAt;
18373
- for (const line of out.split(/\r?\n/)) {
18374
- const boot = /^boot (\d+)$/.exec(line.trim());
18375
- if (boot) bootedAt = Number(boot[1]);
18376
- const m = /^(\d+) (\d+) (\d+)$/.exec(line.trim());
18377
- if (m) procs.push({ pid: Number(m[1]), ppid: Number(m[2]), startedAt: Number(m[3]) });
18378
- }
18379
- return bootedAt !== void 0 && procs.length ? { procs, bootedAt } : void 0;
18380
- }
18381
- function procsOnWindows() {
18382
- const ps = spawnSync4("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", LIST_PROCS], {
18383
- encoding: "utf8",
18384
- maxBuffer: 64 * 1024 * 1024,
18385
- timeout: 5e3,
18386
- windowsHide: true
18387
- });
18388
- return ps.status === 0 && ps.stdout ? readProcList(ps.stdout) : void 0;
18389
- }
18390
- function killUnderOnWindows(pid, since) {
18391
- if (!WINDOWS3 || !pid) return;
18392
- const list = procsOnWindows();
18393
- if (!list) return;
18394
- const pids = startedUnder(list, pid, since).filter((p) => p !== process.pid);
18395
- if (!pids.length) return;
18396
- spawnSync4("taskkill", ["/F", ...pids.flatMap((p) => ["/PID", String(p)])], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
18397
- }
18398
- function killMarked(mark, agent) {
18399
- if (WINDOWS3) {
18400
- if (agent) killUnderOnWindows(agent.pid, agent.since);
18401
- return;
18402
- }
18403
- signal(marked(mark), "SIGKILL");
18404
- }
18405
- function killTreeOnWindows(pid) {
18406
- if (!WINDOWS3 || !pid) return false;
18407
- const out = spawnSync4("taskkill", ["/PID", String(pid), "/T", "/F"], { stdio: "ignore", windowsHide: true, timeout: 1e4 });
18408
- return out.status === 0;
18409
- }
18410
- function later(ms, fn) {
18411
- const t = setTimeout(fn, ms);
18412
- if (typeof t.unref === "function") t.unref();
18413
- }
18414
- function endAgent(child, mark, graceMs) {
18415
- const term = (sig) => {
18416
- try {
18417
- child.kill(sig);
18418
- } catch {
18419
- }
18420
- };
18421
- if (killTreeOnWindows(child.pid)) return;
18422
- killUnderOnWindows(child.pid);
18423
- const seen = new Set(marked(mark, child.pid ? [child.pid] : []));
18424
- term("SIGTERM");
18425
- signal([...seen].filter((pid) => pid !== child.pid), "SIGTERM");
18426
- const round = (left) => {
18427
- const pids = marked(mark, [...seen]);
18428
- signal(pids, "SIGKILL");
18429
- for (const pid of pids) seen.add(pid);
18430
- if (pids.length && left > 1) later(KILL_ROUND_MS, () => round(left - 1));
18431
- };
18432
- later(graceMs, () => {
18433
- term("SIGKILL");
18434
- round(KILL_ROUNDS);
18435
- });
18436
- }
18437
- function killRunning() {
18438
- for (const [child, mark] of running) {
18439
- if (killTreeOnWindows(child.pid)) continue;
18440
- killUnderOnWindows(child.pid);
18441
- signal(marked(mark, child.pid ? [child.pid] : []), "SIGKILL");
18442
- try {
18443
- child.kill("SIGKILL");
18444
- } catch {
18445
- }
18538
+ ].filter(Boolean).join(" ");
18539
+ case "resolve":
18540
+ return [
18541
+ `${kb}. Apply my answers to the open questions on task ${req.id} ${named2} following \`akb guide resolve\`.`,
18542
+ carriedNote(req),
18543
+ answeredNote(req.id, command),
18544
+ req.notes ? `Extra notes: ${req.notes}` : ""
18545
+ ].filter(Boolean).join(" ");
18446
18546
  }
18447
- running.clear();
18448
- }
18449
- function unlisten() {
18450
- for (const [sig, fn] of listening) process.removeListener(sig, fn);
18451
- listening.clear();
18452
- }
18453
- function onQuit(sig) {
18454
- killRunning();
18455
- unlisten();
18456
- if (process.listenerCount(sig) === 0) process.exit(128 + os6.constants.signals[sig]);
18457
18547
  }
18458
- function trackAgent(child, mark) {
18459
- if (!child.pid) return;
18460
- running.set(child, mark);
18461
- child.once("close", () => {
18462
- running.delete(child);
18463
- if (!running.size) unlisten();
18464
- });
18465
- for (const sig of QUIT_SIGNALS) {
18466
- if (listening.has(sig) || sig === "SIGINT" && interruptIsTheCallers) continue;
18467
- const fn = () => onQuit(sig);
18468
- listening.set(sig, fn);
18469
- process.on(sig, fn);
18470
- }
18548
+ function discardedCardsPrompt(cards = []) {
18549
+ if (!cards.length) return "";
18550
+ 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");
18471
18551
  }
18472
- var runMark, stopMark, markEnv, WINDOWS3, KILL_ROUND_MS, KILL_ROUNDS, LIST_PROCS, running, QUIT_SIGNALS, listening, interruptIsTheCallers;
18473
- var init_stop = __esm({
18474
- "src/lib/agent/stop.ts"() {
18552
+ 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;
18553
+ var init_prompts = __esm({
18554
+ "src/lib/agent/prompts.ts"() {
18475
18555
  "use strict";
18556
+ init_cards();
18557
+ init_memory();
18558
+ init_memories();
18559
+ init_paths();
18560
+ init_agents();
18561
+ init_command();
18562
+ init_deliveries();
18476
18563
  init_env();
18477
- runMark = (sessionId) => ({ name: RUN_ENV, value: sessionId });
18478
- stopMark = () => ({ name: STOP_ENV, value: randomUUID5() });
18479
- markEnv = (env2, mark) => ({ ...env2, [mark.name]: mark.value });
18480
- WINDOWS3 = process.platform === "win32";
18481
- KILL_ROUND_MS = 300;
18482
- KILL_ROUNDS = 3;
18483
- LIST_PROCS = [
18484
- "$ErrorActionPreference = 'Stop'",
18485
- "Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { '{0} {1} {2}' -f $_.ProcessId, $_.ParentProcessId, ([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds() } }",
18486
- "'boot {0}' -f ([DateTimeOffset](Get-CimInstance Win32_OperatingSystem).LastBootUpTime).ToUnixTimeMilliseconds()"
18487
- ].join("; ");
18488
- running = /* @__PURE__ */ new Map();
18489
- QUIT_SIGNALS = ["SIGTERM", "SIGINT", "SIGHUP"];
18490
- listening = /* @__PURE__ */ new Map();
18491
- interruptIsTheCallers = false;
18564
+ init_facts();
18565
+ init_outputs();
18566
+ init_archive();
18567
+ init_flows();
18568
+ init_resolve();
18569
+ init_runner();
18570
+ init_workflows();
18571
+ init_catalog2();
18572
+ init_roles();
18573
+ init_rules2();
18574
+ init_settings2();
18575
+ init_types3();
18576
+ RESUME_PROMPT = [
18577
+ `Continue. The previous run ended before it finished the task.`,
18578
+ `Pick up where you left off and carry it through.`
18579
+ ].join(" ");
18580
+ DELIVERY_RESUME = [
18581
+ `Continue delivery %s. The previous run ended before the delivery finished.`,
18582
+ `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.`
18583
+ ].join(" ");
18584
+ DELIVERY_RESUME_CARD = `Build the card as the delivery holds it, not as the file reads now: \`%c\` prints the approved copy.`;
18585
+ RESTARTABLE = /* @__PURE__ */ new Set([
18586
+ "implement",
18587
+ "clarify",
18588
+ "resolve",
18589
+ "approve",
18590
+ "archive",
18591
+ "spec",
18592
+ "conflict",
18593
+ "scheduled"
18594
+ ]);
18595
+ RESTART_LEAD = [
18596
+ `The session you were continuing is gone, and this one holds nothing of it.`,
18597
+ `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.`
18598
+ ].join(" ");
18599
+ restartable = (run2) => (run2.cardId !== null || !!run2.deliveryId) && RESTARTABLE.has(run2.action);
18600
+ NO_IMPLEMENT = `(Unless the request explicitly asks for implementation, don't implement it; revising the card's drafts is not implementing.)`;
18601
+ BOARD_FOLDER = "<board folder>";
18602
+ CARD_FILE = "<card file>";
18603
+ PROJECT_FOLDER = "<project folder>";
18604
+ PLANNING_FOR = /* @__PURE__ */ new Set(["create", "clarify", "resolve", "approve", "edit"]);
18605
+ SPEC_SELECTOR_FOR = /* @__PURE__ */ new Set(["clarify", "resolve", "approve", "edit"]);
18606
+ reflectedCards = (req) => req.cards ?? (req.id !== void 0 ? [req.id] : []);
18492
18607
  }
18493
18608
  });
18494
18609
 
18495
18610
  // src/lib/agent/sessions.ts
18496
18611
  import { randomUUID as randomUUID6 } from "node:crypto";
18497
- import fs48 from "node:fs";
18498
- import path52 from "node:path";
18612
+ import fs49 from "node:fs";
18613
+ import path54 from "node:path";
18499
18614
  function reap(runs, reaped = [], restore = []) {
18500
18615
  let changed = false;
18501
18616
  const now = Date.now();
@@ -18515,7 +18630,7 @@ function reap(runs, reaped = [], restore = []) {
18515
18630
  }
18516
18631
  function stampDuration(run2, endedAt) {
18517
18632
  try {
18518
- fs48.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
18633
+ fs49.appendFileSync(run2.logPath, durationLine(endedAt - run2.startedAt));
18519
18634
  } catch {
18520
18635
  }
18521
18636
  }
@@ -18529,7 +18644,7 @@ function cardNow(cardId2) {
18529
18644
  try {
18530
18645
  const file = cardFile(cardId2);
18531
18646
  if (!file) return null;
18532
- const { meta } = parseFrontmatter(fs48.readFileSync(file, "utf8"));
18647
+ const { meta } = parseFrontmatter(fs49.readFileSync(file, "utf8"));
18533
18648
  if (!meta) return null;
18534
18649
  return { status: meta.status || "todo", questions: openOf(meta.questions).length, title: meta.title };
18535
18650
  } catch {
@@ -18666,9 +18781,9 @@ function leftBoardOnLanding(id) {
18666
18781
  function archivedRejected(id) {
18667
18782
  const filed = locateArchived(id);
18668
18783
  if (!filed) return null;
18669
- const file = filed.kind === "group" ? path52.join(filed.target, "root.md") : filed.target;
18784
+ const file = filed.kind === "group" ? path54.join(filed.target, "root.md") : filed.target;
18670
18785
  try {
18671
- return !!parseFrontmatter(fs48.readFileSync(file, "utf8")).meta?.rejected;
18786
+ return !!parseFrontmatter(fs49.readFileSync(file, "utf8")).meta?.rejected;
18672
18787
  } catch {
18673
18788
  return false;
18674
18789
  }
@@ -18925,7 +19040,7 @@ function openRun(req, prompt, notes = [], sessionId = randomUUID6(), said3) {
18925
19040
  return { run: record, spec };
18926
19041
  }
18927
19042
  function planningSession(cardId2, cwd = REPO_ROOT) {
18928
- const here = (dir) => !dir || path52.resolve(dir) === cwd;
19043
+ const here = (dir) => !dir || path54.resolve(dir) === cwd;
18929
19044
  const ended = readRuns().filter((r) => r.status === "done").sort((a, b) => b.startedAt - a.startedAt);
18930
19045
  const of = (run3, fork) => {
18931
19046
  if (!here(run3.cwd)) return { none: "elsewhere" };
@@ -19147,8 +19262,8 @@ async function resumeHeld(prev, plan, sessionId, resuming, fresh) {
19147
19262
  clearAsks(prev.sessionId);
19148
19263
  try {
19149
19264
  if (prev.action !== "create") {
19150
- fs48.unlinkSync(prev.logPath);
19151
- fs48.rmSync(eventsPathOf(prev.sessionId), { force: true });
19265
+ fs49.unlinkSync(prev.logPath);
19266
+ fs49.rmSync(eventsPathOf(prev.sessionId), { force: true });
19152
19267
  }
19153
19268
  } catch {
19154
19269
  }
@@ -19172,8 +19287,8 @@ function forgetRun(sessionId) {
19172
19287
  if (!gone) return;
19173
19288
  clearAsks(sessionId);
19174
19289
  try {
19175
- fs48.unlinkSync(gone.logPath);
19176
- fs48.rmSync(eventsPathOf(gone.sessionId), { force: true });
19290
+ fs49.unlinkSync(gone.logPath);
19291
+ fs49.rmSync(eventsPathOf(gone.sessionId), { force: true });
19177
19292
  } catch {
19178
19293
  }
19179
19294
  }
@@ -19202,14 +19317,14 @@ function noteSpecRefusals(sessionId, refused) {
19202
19317
  }
19203
19318
  function clearAsks(sessionId) {
19204
19319
  try {
19205
- fs48.unlinkSync(asksPathOf(sessionId));
19320
+ fs49.unlinkSync(asksPathOf(sessionId));
19206
19321
  } catch {
19207
19322
  }
19208
19323
  }
19209
19324
  function readAsks(sessionId) {
19210
19325
  let data;
19211
19326
  try {
19212
- data = JSON.parse(fs48.readFileSync(asksPathOf(sessionId), "utf8"));
19327
+ data = JSON.parse(fs49.readFileSync(asksPathOf(sessionId), "utf8"));
19213
19328
  } catch {
19214
19329
  return { asks: [], refines: [], refused: [] };
19215
19330
  }
@@ -19236,10 +19351,10 @@ function readAsks(sessionId) {
19236
19351
  return { asks: asks.filter((a) => !discarded.has(a.cardId)), refines: refines.filter((a) => !discarded.has(a.cardId)), refused };
19237
19352
  }
19238
19353
  function writeAsks(sessionId, file) {
19239
- fs48.mkdirSync(SESSIONS_DIR, { recursive: true });
19354
+ fs49.mkdirSync(SESSIONS_DIR, { recursive: true });
19240
19355
  const tmp = `${asksPathOf(sessionId)}.tmp`;
19241
- fs48.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
19242
- fs48.renameSync(tmp, asksPathOf(sessionId));
19356
+ fs49.writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n");
19357
+ fs49.renameSync(tmp, asksPathOf(sessionId));
19243
19358
  }
19244
19359
  function markSpawned(sessionId, pid) {
19245
19360
  patch(sessionId, (r) => {
@@ -19327,7 +19442,10 @@ async function cancelDelivery(id) {
19327
19442
  if (!id.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to cancel", { action: "cancel" }) };
19328
19443
  const delivery = namedDelivery(id);
19329
19444
  if (!delivery) return { ok: false, ...unknownDelivery(id) };
19330
- if (delivery.status !== "active") return { ok: true, deliveryId: delivery.deliveryId };
19445
+ if (delivery.status !== "active") {
19446
+ tidyCheckout(delivery.deliveryId);
19447
+ return { ok: true, deliveryId: delivery.deliveryId };
19448
+ }
19331
19449
  endDelivery(delivery.deliveryId, "cancelled");
19332
19450
  const live = readRuns().find((r) => r.status === "running" && r.deliveryId === delivery.deliveryId && r.action !== "sub");
19333
19451
  if (live) await stopRun(live.sessionId);
@@ -19352,7 +19470,9 @@ async function runIsDown(sessionId) {
19352
19470
  }
19353
19471
  async function resumeDelivery(id) {
19354
19472
  if (!id.trim()) return { ok: false, ...refusal("deliveryUnnamed", "name the delivery to carry on", { action: "resume" }) };
19355
- const put = resumeRecord(id);
19473
+ const execution = executionOf();
19474
+ 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" };
19475
+ const put = resumeRecord(id, execution);
19356
19476
  if (!put.ok) return put;
19357
19477
  const delivery = put.delivery;
19358
19478
  if (await settleAlreadyLanded(delivery)) {
@@ -19393,12 +19513,12 @@ async function discardDelivery(id) {
19393
19513
  return { ok: true, deliveryId: delivery.deliveryId };
19394
19514
  }
19395
19515
  function writeSpec(spec) {
19396
- fs48.mkdirSync(SESSIONS_DIR, { recursive: true });
19397
- fs48.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
19516
+ fs49.mkdirSync(SESSIONS_DIR, { recursive: true });
19517
+ fs49.writeFileSync(specPathOf(spec.sessionId), JSON.stringify(spec, null, 2) + "\n");
19398
19518
  }
19399
19519
  function readSpec(sessionId) {
19400
19520
  try {
19401
- const spec = JSON.parse(fs48.readFileSync(specPathOf(sessionId), "utf8"));
19521
+ const spec = JSON.parse(fs49.readFileSync(specPathOf(sessionId), "utf8"));
19402
19522
  return spec && Array.isArray(spec.plan?.argv) ? spec : null;
19403
19523
  } catch {
19404
19524
  return null;
@@ -19406,28 +19526,28 @@ function readSpec(sessionId) {
19406
19526
  }
19407
19527
  function dropSpec(sessionId) {
19408
19528
  try {
19409
- fs48.unlinkSync(specPathOf(sessionId));
19529
+ fs49.unlinkSync(specPathOf(sessionId));
19410
19530
  } catch {
19411
19531
  }
19412
19532
  }
19413
19533
  async function acquireIndexLock(giveUp) {
19414
19534
  const until = Date.now() + INDEX_WAIT_MS;
19415
- const holder = path52.join(INDEX_LOCK2, "holder");
19535
+ const holder = path54.join(INDEX_LOCK2, "holder");
19416
19536
  for (; ; ) {
19417
19537
  if (giveUp()) return null;
19418
19538
  try {
19419
- fs48.mkdirSync(INDEX_LOCK2, { recursive: false });
19420
- fs48.writeFileSync(holder, String(process.pid));
19421
- return () => fs48.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19539
+ fs49.mkdirSync(INDEX_LOCK2, { recursive: false });
19540
+ fs49.writeFileSync(holder, String(process.pid));
19541
+ return () => fs49.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19422
19542
  } catch (err) {
19423
19543
  const code = err.code;
19424
19544
  if (code === "ENOENT") {
19425
- fs48.mkdirSync(path52.dirname(INDEX_LOCK2), { recursive: true });
19545
+ fs49.mkdirSync(path54.dirname(INDEX_LOCK2), { recursive: true });
19426
19546
  continue;
19427
19547
  }
19428
19548
  if (code !== "EEXIST") throw err;
19429
19549
  if (!pidAlive(Number(readHolder(holder)))) {
19430
- fs48.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19550
+ fs49.rmSync(INDEX_LOCK2, { recursive: true, force: true });
19431
19551
  continue;
19432
19552
  }
19433
19553
  if (Date.now() > until) return null;
@@ -19437,7 +19557,7 @@ async function acquireIndexLock(giveUp) {
19437
19557
  }
19438
19558
  function readHolder(file) {
19439
19559
  try {
19440
- return fs48.readFileSync(file, "utf8").trim();
19560
+ return fs49.readFileSync(file, "utf8").trim();
19441
19561
  } catch {
19442
19562
  return String(process.pid);
19443
19563
  }
@@ -19446,6 +19566,7 @@ var INDEX_ACTIONS, SINGLETON_ACTIONS, VERB, SINGLETON_BUSY, RUN_STATUS, specPath
19446
19566
  var init_sessions = __esm({
19447
19567
  "src/lib/agent/sessions.ts"() {
19448
19568
  "use strict";
19569
+ init_execution();
19449
19570
  init_creation();
19450
19571
  init_cards();
19451
19572
  init_frontmatter();
@@ -19528,8 +19649,8 @@ var init_sessions = __esm({
19528
19649
  conflict: "implementing",
19529
19650
  hook: "implementing"
19530
19651
  };
19531
- specPathOf = (sessionId) => path52.join(SESSIONS_DIR, `${sessionId}.plan.json`);
19532
- asksPathOf = (sessionId) => path52.join(SESSIONS_DIR, `${sessionId}.asks.json`);
19652
+ specPathOf = (sessionId) => path54.join(SESSIONS_DIR, `${sessionId}.plan.json`);
19653
+ asksPathOf = (sessionId) => path54.join(SESSIONS_DIR, `${sessionId}.asks.json`);
19533
19654
  carriesSession = (r) => !!(r.resumedFrom || r.continues && !r.continues.fork);
19534
19655
  canPickUp = (r) => (r.status === "error" || r.status === "interrupted" || r.status === "stopped") && !(r.action === "create" && readRuns().some((next) => next.resumedFrom === r.sessionId));
19535
19656
  neverStarted = (r) => r.unspawned === true || !!r.errorWhy?.some((why) => why.kind === "notInstalled");
@@ -19663,8 +19784,8 @@ var init_questions = __esm({
19663
19784
  });
19664
19785
 
19665
19786
  // src/lib/agent/workflow-cards.ts
19666
- import fs49 from "node:fs";
19667
- import path53 from "node:path";
19787
+ import fs50 from "node:fs";
19788
+ import path55 from "node:path";
19668
19789
  function cardsOnWorkflow(id) {
19669
19790
  const wanted = id || DEFAULT_WORKFLOW;
19670
19791
  const ids = [];
@@ -19675,12 +19796,12 @@ function cardsOnWorkflow(id) {
19675
19796
  return [];
19676
19797
  }
19677
19798
  for (const file of files2) {
19678
- const base = path53.basename(file);
19679
- const card = base === "root.md" ? idPrefix(path53.basename(path53.dirname(file))) : idPrefix(base);
19799
+ const base = path55.basename(file);
19800
+ const card = base === "root.md" ? idPrefix(path55.basename(path55.dirname(file))) : idPrefix(base);
19680
19801
  if (card === null) continue;
19681
19802
  let meta;
19682
19803
  try {
19683
- meta = parseFrontmatter(fs49.readFileSync(file, "utf8")).meta;
19804
+ meta = parseFrontmatter(fs50.readFileSync(file, "utf8")).meta;
19684
19805
  } catch {
19685
19806
  continue;
19686
19807
  }
@@ -19738,12 +19859,12 @@ var init_workflow_cards = __esm({
19738
19859
  });
19739
19860
 
19740
19861
  // src/lib/readme.ts
19741
- import fs50 from "node:fs";
19742
- import path54 from "node:path";
19862
+ import fs51 from "node:fs";
19863
+ import path56 from "node:path";
19743
19864
  function stripReadmeRefs(target) {
19744
- if (!fs50.existsSync(README)) return [];
19865
+ if (!fs51.existsSync(README)) return [];
19745
19866
  const needle = target.kind === "group" ? `](${target.rel}/` : `](${target.rel})`;
19746
- const lines = fs50.readFileSync(README, "utf8").split("\n");
19867
+ const lines = fs51.readFileSync(README, "utf8").split("\n");
19747
19868
  const out = [];
19748
19869
  const removed = [];
19749
19870
  let i = 0;
@@ -19765,20 +19886,20 @@ function stripReadmeRefs(target) {
19765
19886
  out.push(line);
19766
19887
  i++;
19767
19888
  }
19768
- if (removed.length) fs50.writeFileSync(README, out.join("\n"));
19889
+ if (removed.length) fs51.writeFileSync(README, out.join("\n"));
19769
19890
  return removed;
19770
19891
  }
19771
19892
  function addReadmeRef(id, title, relPath) {
19772
- if (!fs50.existsSync(README)) return false;
19773
- const link2 = relPath.split(path54.sep).join("/");
19893
+ if (!fs51.existsSync(README)) return false;
19894
+ const link2 = relPath.split(path56.sep).join("/");
19774
19895
  const bullet = `- [#${id} ${title}](${link2})`;
19775
19896
  const heading = `## ${TASKS_HEADING}`;
19776
- let lines = fs50.readFileSync(README, "utf8").split("\n");
19897
+ let lines = fs51.readFileSync(README, "utf8").split("\n");
19777
19898
  const hi = lines.findIndex((l) => l.trim().toLowerCase() === heading.toLowerCase());
19778
19899
  if (hi === -1) {
19779
19900
  while (lines.length && lines[lines.length - 1].trim() === "") lines.pop();
19780
19901
  lines.push("", heading, "", bullet);
19781
- fs50.writeFileSync(README, lines.join("\n") + "\n");
19902
+ fs51.writeFileSync(README, lines.join("\n") + "\n");
19782
19903
  return true;
19783
19904
  }
19784
19905
  let end2 = hi + 1;
@@ -19792,15 +19913,15 @@ function addReadmeRef(id, title, relPath) {
19792
19913
  const at = lastBullet !== -1 ? lastBullet + 1 : lines[hi + 1] === "" ? hi + 2 : hi + 1;
19793
19914
  lines.splice(at, 0, bullet);
19794
19915
  }
19795
- fs50.writeFileSync(README, lines.join("\n"));
19916
+ fs51.writeFileSync(README, lines.join("\n"));
19796
19917
  return true;
19797
19918
  }
19798
19919
  function repointReadmeLink(id, oldRel, newRel, title) {
19799
- if (!fs50.existsSync(README)) return false;
19800
- const oldLink = oldRel.split(path54.sep).join("/");
19801
- const newLink = newRel.split(path54.sep).join("/");
19920
+ if (!fs51.existsSync(README)) return false;
19921
+ const oldLink = oldRel.split(path56.sep).join("/");
19922
+ const newLink = newRel.split(path56.sep).join("/");
19802
19923
  const linkRe = new RegExp(`\\[#${id}\\b[^\\]]*\\]\\(${escapeRegex(oldLink)}\\)`);
19803
- const lines = fs50.readFileSync(README, "utf8").split("\n");
19924
+ const lines = fs51.readFileSync(README, "utf8").split("\n");
19804
19925
  let changed = false;
19805
19926
  for (let i = 0; i < lines.length; i++) {
19806
19927
  if (!lines[i].includes(`](${oldLink})`)) continue;
@@ -19810,7 +19931,7 @@ function repointReadmeLink(id, oldRel, newRel, title) {
19810
19931
  changed = true;
19811
19932
  }
19812
19933
  }
19813
- if (changed) fs50.writeFileSync(README, lines.join("\n"));
19934
+ if (changed) fs51.writeFileSync(README, lines.join("\n"));
19814
19935
  return changed;
19815
19936
  }
19816
19937
  var isTableRow, isBulletStart, bulletIndent, TASKS_HEADING, escapeRegex;
@@ -19827,14 +19948,14 @@ var init_readme = __esm({
19827
19948
  });
19828
19949
 
19829
19950
  // src/lib/reconcile.ts
19830
- import fs51 from "node:fs";
19831
- import path55 from "node:path";
19951
+ import fs52 from "node:fs";
19952
+ import path57 from "node:path";
19832
19953
  function liveIds() {
19833
19954
  const ids = /* @__PURE__ */ new Set();
19834
19955
  for (const file of walkMd(TODO)) {
19835
- const base = path55.basename(file);
19956
+ const base = path57.basename(file);
19836
19957
  if (base === "README.md") continue;
19837
- const id = base === "root.md" ? idPrefix(path55.basename(path55.dirname(file))) : idPrefix(base);
19958
+ const id = base === "root.md" ? idPrefix(path57.basename(path57.dirname(file))) : idPrefix(base);
19838
19959
  if (id != null) ids.add(id);
19839
19960
  }
19840
19961
  return ids;
@@ -19842,16 +19963,16 @@ function liveIds() {
19842
19963
  function indexableCards() {
19843
19964
  const out = [];
19844
19965
  for (const dir of walkDirs(TODO)) {
19845
- const id = idPrefix(path55.basename(dir));
19846
- if (id != null && fs51.existsSync(path55.join(dir, "root.md"))) {
19847
- out.push({ id, rel: path55.join(path55.relative(TODO, dir), "root.md").split(path55.sep).join("/") });
19966
+ const id = idPrefix(path57.basename(dir));
19967
+ if (id != null && fs52.existsSync(path57.join(dir, "root.md"))) {
19968
+ out.push({ id, rel: path57.join(path57.relative(TODO, dir), "root.md").split(path57.sep).join("/") });
19848
19969
  }
19849
19970
  }
19850
19971
  for (const file of walkMd(TODO)) {
19851
- const base = path55.basename(file);
19972
+ const base = path57.basename(file);
19852
19973
  if (base === "README.md" || base === "root.md") continue;
19853
- const relTODO = path55.relative(TODO, file);
19854
- const segs = relTODO.split(path55.sep);
19974
+ const relTODO = path57.relative(TODO, file);
19975
+ const segs = relTODO.split(path57.sep);
19855
19976
  if (segs.length !== 1) continue;
19856
19977
  const id = idPrefix(base);
19857
19978
  if (id != null) out.push({ id, rel: segs.join("/") });
@@ -19860,7 +19981,7 @@ function indexableCards() {
19860
19981
  }
19861
19982
  function readmeComplaints(fix) {
19862
19983
  const said3 = [];
19863
- const lines = fs51.readFileSync(README, "utf8").split("\n");
19984
+ const lines = fs52.readFileSync(README, "utf8").split("\n");
19864
19985
  const indexed = /* @__PURE__ */ new Set();
19865
19986
  let fixed = 0;
19866
19987
  for (let i = 0; i < lines.length; i++) {
@@ -19869,13 +19990,13 @@ function readmeComplaints(fix) {
19869
19990
  const id = Number(m[1]);
19870
19991
  const linkPath = m[2];
19871
19992
  indexed.add(id);
19872
- if (fs51.existsSync(path55.join(TODO, linkPath))) continue;
19993
+ if (fs52.existsSync(path57.join(TODO, linkPath))) continue;
19873
19994
  const found2 = locate(id);
19874
19995
  if (!found2) {
19875
19996
  said3.push(`README links #${id} \u2192 ${linkPath}, but no card with that id exists (removed by hand?). Drop the entry or restore the file.`);
19876
19997
  continue;
19877
19998
  }
19878
- const want = (found2.kind === "group" ? path55.join(found2.rel, "root.md") : found2.rel).split(path55.sep).join("/");
19999
+ const want = (found2.kind === "group" ? path57.join(found2.rel, "root.md") : found2.rel).split(path57.sep).join("/");
19879
20000
  if (want === linkPath) continue;
19880
20001
  if (!fix) {
19881
20002
  said3.push(`README links #${id} \u2192 ${linkPath}, which isn't there any more; the card is at ${want}.`);
@@ -19885,7 +20006,7 @@ function readmeComplaints(fix) {
19885
20006
  said3.push(`README link #${id} pointed at missing ${linkPath} \u2192 repointed to ${want}.`);
19886
20007
  fixed++;
19887
20008
  }
19888
- if (fixed) fs51.writeFileSync(README, lines.join("\n"));
20009
+ if (fixed) fs52.writeFileSync(README, lines.join("\n"));
19889
20010
  for (const c of indexableCards()) {
19890
20011
  if (!indexed.has(c.id)) {
19891
20012
  said3.push(`card ${c.rel} (#${c.id}) is not in the README index. Add it under "## ${TASKS_HEADING}".`);
@@ -19897,11 +20018,11 @@ function crossRefComplaints() {
19897
20018
  const said3 = [];
19898
20019
  const live = liveIds();
19899
20020
  for (const file of walkMd(TODO)) {
19900
- const base = path55.basename(file);
20021
+ const base = path57.basename(file);
19901
20022
  if (base === "README.md") continue;
19902
- const ownerId = base === "root.md" ? idPrefix(path55.basename(path55.dirname(file))) : idPrefix(base);
20023
+ const ownerId = base === "root.md" ? idPrefix(path57.basename(path57.dirname(file))) : idPrefix(base);
19903
20024
  if (ownerId == null) continue;
19904
- const { meta } = parseFrontmatter(fs51.readFileSync(file, "utf8"));
20025
+ const { meta } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
19905
20026
  if (!meta) continue;
19906
20027
  for (const field2 of ["blocked_by", "related"]) {
19907
20028
  for (const ref of meta[field2] || []) {
@@ -19914,11 +20035,11 @@ function crossRefComplaints() {
19914
20035
  return said3;
19915
20036
  }
19916
20037
  function reconcileBoard() {
19917
- if (!fs51.existsSync(README)) return;
20038
+ if (!fs52.existsSync(README)) return;
19918
20039
  for (const line of [...readmeComplaints(true), ...crossRefComplaints()]) warn2(line);
19919
20040
  }
19920
20041
  function boardComplaints() {
19921
- if (!fs51.existsSync(README)) return [];
20042
+ if (!fs52.existsSync(README)) return [];
19922
20043
  try {
19923
20044
  return [...readmeComplaints(false), ...crossRefComplaints()];
19924
20045
  } catch {
@@ -19938,8 +20059,8 @@ var init_reconcile = __esm({
19938
20059
  });
19939
20060
 
19940
20061
  // src/commands/card.ts
19941
- import fs52 from "node:fs";
19942
- import path56 from "node:path";
20062
+ import fs53 from "node:fs";
20063
+ import path58 from "node:path";
19943
20064
  function defaultBody() {
19944
20065
  return [
19945
20066
  "<\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>",
@@ -19965,7 +20086,7 @@ function bodyFromFile(opts) {
19965
20086
  if (opts.body === false) die("pass --body-file or --no-body, not both");
19966
20087
  let text5;
19967
20088
  try {
19968
- text5 = fs52.readFileSync(opts.bodyFile, "utf8");
20089
+ text5 = fs53.readFileSync(opts.bodyFile, "utf8");
19969
20090
  } catch {
19970
20091
  die(`can't read ${opts.bodyFile} \u2014 write the body to a file, then pass its path`, { kind: "needs-input" });
19971
20092
  }
@@ -19997,20 +20118,20 @@ function cmdCreate(opts) {
19997
20118
  const start = opts.id;
19998
20119
  const slug2 = slugify(opts.slug !== void 0 ? opts.slug : title);
19999
20120
  const fileRel = `${start}-${slug2}.md`;
20000
- const file = path56.join(TODO, fileRel);
20121
+ const file = path58.join(TODO, fileRel);
20001
20122
  const held4 = locate(start) ?? locateArchived(start);
20002
- if (held4 && path56.basename(held4.target) === `${start}-${slug2}.md`) {
20123
+ if (held4 && path58.basename(held4.target) === `${start}-${slug2}.md`) {
20003
20124
  say(start);
20004
20125
  say(` ${rel(held4.target)} was already written`);
20005
20126
  return { id: start, ids: [start], title, file: rel(held4.target), indexed: false };
20006
20127
  }
20007
20128
  if (held4) die(`#${start} is already a card here (${rel(held4.target)})`, { kind: "id-taken", id: start });
20008
- if (fs52.existsSync(file)) die(`${rel(file)} already exists \u2014 pick a different --slug`);
20129
+ if (fs53.existsSync(file)) die(`${rel(file)} already exists \u2014 pick a different --slug`);
20009
20130
  countBoardEvent(triage ? "cards_created_proposed" : "cards_created_asked");
20010
20131
  const meta = { title, priority, status: "todo", blocked_by, related, modules, workflow, triage, source, questions };
20011
20132
  const scaffolded = !written && opts.body !== false;
20012
20133
  const body = written ?? (scaffolded ? defaultBody() : "");
20013
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n\n" + body);
20134
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n\n" + body);
20014
20135
  const indexed = addReadmeRef(start, title, fileRel);
20015
20136
  say(start);
20016
20137
  say(
@@ -20048,8 +20169,8 @@ function cmdUpdate(id, flags) {
20048
20169
  if (creating) die(creating, { kind: "card-being-created", id });
20049
20170
  const found2 = locate(id);
20050
20171
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
20051
- const file = found2.kind === "group" ? path56.join(found2.target, "root.md") : found2.target;
20052
- const { meta, body } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
20172
+ const file = found2.kind === "group" ? path58.join(found2.target, "root.md") : found2.target;
20173
+ const { meta, body } = parseFrontmatter(fs53.readFileSync(file, "utf8"));
20053
20174
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
20054
20175
  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");
20055
20176
  if (flags.related !== void 0 && flags.addRelated !== void 0) die("--related replaces the list and --add-related appends to it \u2014 pass one");
@@ -20129,26 +20250,26 @@ function cmdUpdate(id, flags) {
20129
20250
  meta.status = "todo";
20130
20251
  changes.push("status\u2192todo (open questions)");
20131
20252
  }
20132
- const curRel = path56.relative(TODO, file);
20253
+ const curRel = path58.relative(TODO, file);
20133
20254
  const isSubtask = found2.kind === "file" && enclosingGroupRoot(file) !== null;
20134
- let base = path56.basename(file);
20255
+ let base = path58.basename(file);
20135
20256
  if (flags.slug !== void 0) {
20136
20257
  if (found2.kind === "group") die("renaming a group root by script is not supported");
20137
20258
  base = `${id}-${slugify(flags.slug)}.md`;
20138
20259
  }
20139
- const destRel = path56.join(path56.dirname(curRel), base);
20140
- const dest = path56.join(TODO, destRel);
20260
+ const destRel = path58.join(path58.dirname(curRel), base);
20261
+ const dest = path58.join(TODO, destRel);
20141
20262
  const moving = dest !== file;
20142
- if (moving && fs52.existsSync(dest)) die(`${rel(dest)} already exists`);
20143
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20144
- if (moving) fs52.renameSync(file, dest);
20263
+ if (moving && fs53.existsSync(dest)) die(`${rel(dest)} already exists`);
20264
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20265
+ if (moving) fs53.renameSync(file, dest);
20145
20266
  if (isSubtask) {
20146
20267
  if (moving || changes.includes("title")) repointReadmeLink(id, curRel, destRel, meta.title);
20147
- if (moving) changes.push(`renamed \u2192 ${destRel.split(path56.sep).join("/")}`);
20268
+ if (moving) changes.push(`renamed \u2192 ${destRel.split(path58.sep).join("/")}`);
20148
20269
  } else if (moving) {
20149
20270
  stripReadmeRefs({ kind: "file", rel: curRel });
20150
20271
  addReadmeRef(id, meta.title, destRel);
20151
- changes.push(`renamed \u2192 ${destRel.split(path56.sep).join("/")}`);
20272
+ changes.push(`renamed \u2192 ${destRel.split(path58.sep).join("/")}`);
20152
20273
  } else if (changes.includes("title")) {
20153
20274
  stripReadmeRefs({ kind: "file", rel: curRel });
20154
20275
  addReadmeRef(id, meta.title, curRel);
@@ -20160,8 +20281,8 @@ function cmdUpdateQuestions(id, input) {
20160
20281
  const ops = readQuestionOps(input.ops ?? []);
20161
20282
  const found2 = locate(id);
20162
20283
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
20163
- const file = found2.kind === "group" ? path56.join(found2.target, "root.md") : found2.target;
20164
- const { meta, body } = parseFrontmatter(fs52.readFileSync(file, "utf8"));
20284
+ const file = found2.kind === "group" ? path58.join(found2.target, "root.md") : found2.target;
20285
+ const { meta, body } = parseFrontmatter(fs53.readFileSync(file, "utf8"));
20165
20286
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
20166
20287
  if (insideRun() && ops.some((op) => op.kind === "skip" || op.kind === "unskip")) {
20167
20288
  die("only the user skips or reopens a question \u2014 a run leaves questions for them to answer");
@@ -20234,7 +20355,7 @@ function cmdUpdateQuestions(id, input) {
20234
20355
  meta.status = "todo";
20235
20356
  changes.push("status\u2192todo (open questions)");
20236
20357
  }
20237
- fs52.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20358
+ fs53.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
20238
20359
  for (const kind of closed2) countBoardEvent(kind);
20239
20360
  settleDelivery2(id, skipped, unskipped);
20240
20361
  say(
@@ -20308,13 +20429,13 @@ var init_config_template = __esm({
20308
20429
  });
20309
20430
 
20310
20431
  // src/lib/agent/local.ts
20311
- import fs53 from "node:fs";
20312
- import path57 from "node:path";
20432
+ import fs54 from "node:fs";
20433
+ import path59 from "node:path";
20313
20434
  function takeLocalModels(board2) {
20314
- const file = path57.join(board2, ".local.json");
20435
+ const file = path59.join(board2, ".local.json");
20315
20436
  let held4;
20316
20437
  try {
20317
- held4 = configBlock(JSON.parse(fs53.readFileSync(file, "utf8")));
20438
+ held4 = configBlock(JSON.parse(fs54.readFileSync(file, "utf8")));
20318
20439
  } catch {
20319
20440
  return {};
20320
20441
  }
@@ -20332,7 +20453,7 @@ function takeLocalModels(board2) {
20332
20453
  }
20333
20454
  if (!Object.keys(agents).length) return out;
20334
20455
  delete held4.agents;
20335
- fs53.writeFileSync(file, JSON.stringify(held4, null, 2) + "\n");
20456
+ fs54.writeFileSync(file, JSON.stringify(held4, null, 2) + "\n");
20336
20457
  return out;
20337
20458
  }
20338
20459
  var LOCAL_IGNORE_LINE;
@@ -20393,12 +20514,12 @@ var init_identity2 = __esm({
20393
20514
  });
20394
20515
 
20395
20516
  // src/lib/signals/migrate.ts
20396
- import fs54 from "node:fs";
20397
- import path58 from "node:path";
20517
+ import fs55 from "node:fs";
20518
+ import path60 from "node:path";
20398
20519
  function readHandled() {
20399
20520
  let text5;
20400
20521
  try {
20401
- text5 = fs54.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
20522
+ text5 = fs55.readFileSync(SIGNALS_OLD_HANDLED, "utf8");
20402
20523
  } catch {
20403
20524
  return [];
20404
20525
  }
@@ -20415,57 +20536,57 @@ function readHandled() {
20415
20536
  return held4;
20416
20537
  }
20417
20538
  function lift(from, into) {
20418
- fs54.mkdirSync(into, { recursive: true });
20419
- fs54.renameSync(from, path58.join(into, freeName(into, path58.basename(from))));
20539
+ fs55.mkdirSync(into, { recursive: true });
20540
+ fs55.renameSync(from, path60.join(into, freeName(into, path60.basename(from))));
20420
20541
  }
20421
20542
  function repoint(dir, from, into) {
20422
20543
  let entries;
20423
20544
  try {
20424
- entries = fs54.readdirSync(dir, { withFileTypes: true });
20545
+ entries = fs55.readdirSync(dir, { withFileTypes: true });
20425
20546
  } catch {
20426
20547
  return;
20427
20548
  }
20428
20549
  for (const entry of entries) {
20429
20550
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
20430
- const file = path58.join(dir, entry.name);
20431
- const text5 = fs54.readFileSync(file, "utf8");
20432
- if (text5.includes(from)) fs54.writeFileSync(file, text5.split(from).join(into));
20551
+ const file = path60.join(dir, entry.name);
20552
+ const text5 = fs55.readFileSync(file, "utf8");
20553
+ if (text5.includes(from)) fs55.writeFileSync(file, text5.split(from).join(into));
20433
20554
  }
20434
20555
  }
20435
20556
  function dropIfEmpty2(dir) {
20436
20557
  try {
20437
- fs54.rmdirSync(dir);
20558
+ fs55.rmdirSync(dir);
20438
20559
  } catch {
20439
20560
  }
20440
20561
  }
20441
20562
  function liftInbox() {
20442
- if (!fs54.existsSync(SIGNALS_OLD_INBOX)) return;
20443
- const oldFiles = path58.join(SIGNALS_OLD_INBOX, "files");
20444
- if (fs54.existsSync(oldFiles)) {
20445
- for (const entry of fs54.readdirSync(oldFiles, { withFileTypes: true })) {
20446
- if (entry.isFile()) lift(path58.join(oldFiles, entry.name), SIGNALS_FILES);
20563
+ if (!fs55.existsSync(SIGNALS_OLD_INBOX)) return;
20564
+ const oldFiles = path60.join(SIGNALS_OLD_INBOX, "files");
20565
+ if (fs55.existsSync(oldFiles)) {
20566
+ for (const entry of fs55.readdirSync(oldFiles, { withFileTypes: true })) {
20567
+ if (entry.isFile()) lift(path60.join(oldFiles, entry.name), SIGNALS_FILES);
20447
20568
  }
20448
20569
  dropIfEmpty2(oldFiles);
20449
20570
  }
20450
20571
  const held4 = new Set(readFolder(TRIAGE).map((signal2) => signal2.sourceId));
20451
- for (const entry of fs54.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
20572
+ for (const entry of fs55.readdirSync(SIGNALS_OLD_INBOX, { withFileTypes: true })) {
20452
20573
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
20453
- const from = path58.join(SIGNALS_OLD_INBOX, entry.name);
20574
+ const from = path60.join(SIGNALS_OLD_INBOX, entry.name);
20454
20575
  const item = parse(from);
20455
20576
  if (item && held4.has(item.sourceId)) {
20456
- fs54.rmSync(from, { force: true });
20577
+ fs55.rmSync(from, { force: true });
20457
20578
  continue;
20458
20579
  }
20459
20580
  if (item) held4.add(item.sourceId);
20460
20581
  lift(from, TRIAGE);
20461
20582
  }
20462
- const wasAt = asWritten(path58.join(SIGNALS_OLD_INBOX, "files"));
20583
+ const wasAt = asWritten(path60.join(SIGNALS_OLD_INBOX, "files"));
20463
20584
  const nowAt = asWritten(SIGNALS_FILES);
20464
20585
  for (const dir of [TRIAGE, SIGNALS_ARCHIVED, SIGNALS_DISMISSED]) repoint(dir, wasAt, nowAt);
20465
20586
  dropIfEmpty2(SIGNALS_OLD_INBOX);
20466
20587
  }
20467
20588
  function liftHandled() {
20468
- if (!fs54.existsSync(SIGNALS_OLD_HANDLED)) return;
20589
+ if (!fs55.existsSync(SIGNALS_OLD_HANDLED)) return;
20469
20590
  const lines = readHandled();
20470
20591
  const held4 = /* @__PURE__ */ new Set([
20471
20592
  ...readFolder(TRIAGE).map((signal2) => signal2.sourceId),
@@ -20475,7 +20596,7 @@ function liftHandled() {
20475
20596
  for (const { sourceId, when } of lines) {
20476
20597
  if (held4.has(sourceId)) continue;
20477
20598
  held4.add(sourceId);
20478
- fs54.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
20599
+ fs55.mkdirSync(SIGNALS_DISMISSED, { recursive: true });
20479
20600
  const name = freeName(SIGNALS_DISMISSED, fileName("", sourceId));
20480
20601
  const front = [
20481
20602
  "---",
@@ -20485,13 +20606,13 @@ function liftHandled() {
20485
20606
  "---",
20486
20607
  ""
20487
20608
  ];
20488
- fs54.writeFileSync(path58.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
20609
+ fs55.writeFileSync(path60.join(SIGNALS_DISMISSED, name), `${front.join("\n")}
20489
20610
  `);
20490
20611
  }
20491
- fs54.rmSync(SIGNALS_OLD_HANDLED, { force: true });
20612
+ fs55.rmSync(SIGNALS_OLD_HANDLED, { force: true });
20492
20613
  }
20493
20614
  function migrateTriage() {
20494
- if (!fs54.existsSync(SIGNALS_OLD_INBOX) && !fs54.existsSync(SIGNALS_OLD_HANDLED)) return;
20615
+ if (!fs55.existsSync(SIGNALS_OLD_INBOX) && !fs55.existsSync(SIGNALS_OLD_HANDLED)) return;
20495
20616
  try {
20496
20617
  liftInbox();
20497
20618
  liftHandled();
@@ -20506,13 +20627,13 @@ var init_migrate = __esm({
20506
20627
  init_yaml();
20507
20628
  init_inbox();
20508
20629
  HANDLED_LINE = /^-\s+(.+?)\s+—\s+(.+)$/;
20509
- asWritten = (dir) => `${rel(dir).split(path58.sep).join("/")}/`;
20630
+ asWritten = (dir) => `${rel(dir).split(path60.sep).join("/")}/`;
20510
20631
  }
20511
20632
  });
20512
20633
 
20513
20634
  // src/lib/signals/add.ts
20514
- import fs55 from "node:fs";
20515
- import path59 from "node:path";
20635
+ import fs56 from "node:fs";
20636
+ import path61 from "node:path";
20516
20637
  import { createHash as createHash3 } from "node:crypto";
20517
20638
  function linkTitle(url) {
20518
20639
  let at;
@@ -20525,7 +20646,7 @@ function linkTitle(url) {
20525
20646
  return oneLine(where) || url.slice(0, TITLE_MAX);
20526
20647
  }
20527
20648
  function asText(file) {
20528
- const ext = path59.extname(file.name).toLowerCase();
20649
+ const ext = path61.extname(file.name).toLowerCase();
20529
20650
  if (!file.type.startsWith("text/") && file.type !== "application/json" && !TEXT_EXTENSIONS.has(ext)) return null;
20530
20651
  try {
20531
20652
  const text5 = new TextDecoder("utf-8", { fatal: true }).decode(file.data);
@@ -20535,9 +20656,9 @@ function asText(file) {
20535
20656
  }
20536
20657
  }
20537
20658
  function fileName2(name, data) {
20538
- const base = path59.basename(name);
20539
- const ext = path59.extname(base).toLowerCase().slice(0, 12);
20540
- const word = path59.basename(base, path59.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
20659
+ const base = path61.basename(name);
20660
+ const ext = path61.extname(base).toLowerCase().slice(0, 12);
20661
+ const word = path61.basename(base, path61.extname(base)).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "file";
20541
20662
  const hash2 = createHash3("sha256").update(data).digest("hex").slice(0, 8);
20542
20663
  return `${word}-${hash2}${ext}`;
20543
20664
  }
@@ -20546,9 +20667,9 @@ function addToInbox(drop) {
20546
20667
  const typed = (drop.text ?? "").trim();
20547
20668
  const file = drop.file;
20548
20669
  if (!typed && !file) return { ok: false, error: "nothing to add \u2014 paste a link or some text, or drop a file." };
20549
- if (file && file.data.length === 0) return { ok: false, error: `${path59.basename(file.name)} is empty.` };
20670
+ if (file && file.data.length === 0) return { ok: false, error: `${path61.basename(file.name)} is empty.` };
20550
20671
  if (file && file.data.length > MAX_BYTES) {
20551
- return { ok: false, error: `${path59.basename(file.name)} is over ${MAX_BYTES / 1024 / 1024} MB \u2014 too big for the board.` };
20672
+ return { ok: false, error: `${path61.basename(file.name)} is over ${MAX_BYTES / 1024 / 1024} MB \u2014 too big for the board.` };
20552
20673
  }
20553
20674
  const read4 = describe(typed, file);
20554
20675
  const keep2 = read4.keep;
@@ -20570,8 +20691,8 @@ ${incoming.summary}`);
20570
20691
  if (seen.status === "pending" || seen.status === "archived") return { ok: false, error: `${sayHit(seen)}.` };
20571
20692
  try {
20572
20693
  if (keep2) {
20573
- fs55.mkdirSync(SIGNALS_FILES, { recursive: true });
20574
- fs55.writeFileSync(keep2.at, keep2.data);
20694
+ fs56.mkdirSync(SIGNALS_FILES, { recursive: true });
20695
+ fs56.writeFileSync(keep2.at, keep2.data);
20575
20696
  }
20576
20697
  return { ok: true, signal: writeSignal({ ...incoming, sourceId }, formatStamp(/* @__PURE__ */ new Date()), drop.slug) };
20577
20698
  } catch (e) {
@@ -20585,7 +20706,7 @@ function describe(typed, file) {
20585
20706
  return only ? [only] : [];
20586
20707
  };
20587
20708
  if (file) {
20588
- const name = path59.basename(file.name);
20709
+ const name = path61.basename(file.name);
20589
20710
  const text5 = asText(file);
20590
20711
  const note = typed ? `
20591
20712
 
@@ -20597,7 +20718,7 @@ ${typed}` : "";
20597
20718
  const at = keepAt(file);
20598
20719
  return {
20599
20720
  incoming: {
20600
- title: path59.basename(name, path59.extname(name)) || name,
20721
+ title: path61.basename(name, path61.extname(name)) || name,
20601
20722
  summary: `${name} \u2014 ${boardRel2(at)}${note}`,
20602
20723
  ...named2
20603
20724
  },
@@ -20635,73 +20756,73 @@ var init_add = __esm({
20635
20756
  MAX_BYTES = 25 * 1024 * 1024;
20636
20757
  TITLE_MAX = 120;
20637
20758
  TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".txt", ".text", ".csv", ".json", ".yml", ".yaml", ".log"]);
20638
- boardRel2 = (file) => rel(file).split(path59.sep).join("/");
20759
+ boardRel2 = (file) => rel(file).split(path61.sep).join("/");
20639
20760
  oneLine = (text5) => {
20640
20761
  const first = text5.split("\n").find((line) => line.trim()) ?? "";
20641
20762
  const clean = first.replace(/^#+\s*/, "").trim();
20642
20763
  return clean.length > TITLE_MAX ? `${clean.slice(0, TITLE_MAX - 1).trimEnd()}\u2026` : clean;
20643
20764
  };
20644
- keepAt = (file) => path59.join(SIGNALS_FILES, fileName2(file.name, file.data));
20765
+ keepAt = (file) => path61.join(SIGNALS_FILES, fileName2(file.name, file.data));
20645
20766
  }
20646
20767
  });
20647
20768
 
20648
20769
  // src/lib/recurring.ts
20649
- import fs56 from "node:fs";
20650
- import path60 from "node:path";
20770
+ import fs57 from "node:fs";
20771
+ import path62 from "node:path";
20651
20772
  function migratePruneMemoryCard() {
20652
20773
  const dir = recurringDir();
20653
20774
  let names4;
20654
20775
  try {
20655
- names4 = fs56.readdirSync(dir);
20776
+ names4 = fs57.readdirSync(dir);
20656
20777
  } catch {
20657
20778
  return null;
20658
20779
  }
20659
20780
  const name = names4.find((entry) => entry.endsWith(`-${PRUNE_SLUG}.md`));
20660
20781
  if (!name) return null;
20661
- const file = path60.join(dir, name);
20782
+ const file = path62.join(dir, name);
20662
20783
  try {
20663
- const { meta } = parseFrontmatter(fs56.readFileSync(file, "utf8"));
20784
+ const { meta } = parseFrontmatter(fs57.readFileSync(file, "utf8"));
20664
20785
  const cadence = meta?.cadence;
20665
20786
  if (typeof cadence === "string") adoptMemoryPruneCadence(cadence);
20666
20787
  } catch {
20667
20788
  }
20668
- fs56.rmSync(file, { force: true });
20789
+ fs57.rmSync(file, { force: true });
20669
20790
  return rel(file);
20670
20791
  }
20671
20792
  function legacyCards() {
20672
20793
  const dir = recurringDir();
20673
- if (!fs56.existsSync(dir)) return [];
20794
+ if (!fs57.existsSync(dir)) return [];
20674
20795
  const cards = [];
20675
- for (const entry of fs56.readdirSync(dir, { withFileTypes: true })) {
20796
+ for (const entry of fs57.readdirSync(dir, { withFileTypes: true })) {
20676
20797
  const id = idPrefix(entry.name);
20677
20798
  if (id === null) continue;
20678
- const full = path60.join(dir, entry.name);
20799
+ const full = path62.join(dir, entry.name);
20679
20800
  const slug2 = entry.name.replace(/\.md$/, "").replace(/^\d+-?/, "");
20680
20801
  if (entry.isFile() && entry.name.endsWith(".md")) cards.push({ id, slug: slug2, file: full });
20681
- else if (entry.isDirectory() && fs56.existsSync(path60.join(full, "root.md"))) {
20682
- cards.push({ id, slug: slug2, file: path60.join(full, "root.md"), folder: full });
20802
+ else if (entry.isDirectory() && fs57.existsSync(path62.join(full, "root.md"))) {
20803
+ cards.push({ id, slug: slug2, file: path62.join(full, "root.md"), folder: full });
20683
20804
  }
20684
20805
  }
20685
20806
  return cards.sort((a, b) => a.id - b.id);
20686
20807
  }
20687
20808
  function mergeInto2(from, to, skip = []) {
20688
- fs56.mkdirSync(to, { recursive: true });
20689
- for (const entry of fs56.readdirSync(from, { withFileTypes: true })) {
20809
+ fs57.mkdirSync(to, { recursive: true });
20810
+ for (const entry of fs57.readdirSync(from, { withFileTypes: true })) {
20690
20811
  if (skip.includes(entry.name)) continue;
20691
- const source = path60.join(from, entry.name);
20692
- const target = path60.join(to, entry.name);
20693
- if (!fs56.existsSync(target)) fs56.renameSync(source, target);
20694
- else if (entry.isDirectory() && fs56.statSync(target).isDirectory()) mergeInto2(source, target);
20812
+ const source = path62.join(from, entry.name);
20813
+ const target = path62.join(to, entry.name);
20814
+ if (!fs57.existsSync(target)) fs57.renameSync(source, target);
20815
+ else if (entry.isDirectory() && fs57.statSync(target).isDirectory()) mergeInto2(source, target);
20695
20816
  }
20696
- if (isEmpty(from)) fs56.rmSync(from, { recursive: true, force: true });
20817
+ if (isEmpty(from)) fs57.rmSync(from, { recursive: true, force: true });
20697
20818
  }
20698
20819
  function moveSideFolders() {
20699
20820
  const dir = recurringDir();
20700
- for (const entry of fs56.readdirSync(dir, { withFileTypes: true })) {
20821
+ for (const entry of fs57.readdirSync(dir, { withFileTypes: true })) {
20701
20822
  if (!entry.isDirectory() || idPrefix(entry.name) !== null) continue;
20702
- const from = path60.join(dir, entry.name);
20703
- if (isEmpty(from)) fs56.rmSync(from, { recursive: true, force: true });
20704
- else mergeInto2(from, path60.join(AGENTS, entry.name));
20823
+ const from = path62.join(dir, entry.name);
20824
+ if (isEmpty(from)) fs57.rmSync(from, { recursive: true, force: true });
20825
+ else mergeInto2(from, path62.join(AGENTS, entry.name));
20705
20826
  }
20706
20827
  }
20707
20828
  function sections(body) {
@@ -20751,8 +20872,8 @@ function agentName(card, text5) {
20751
20872
  const known2 = /* @__PURE__ */ new Set([...specAgentCatalog().agents.map((a) => a.name), ...ROLE_NAMES]);
20752
20873
  for (const name of [slug2, `${slug2}-${card.id}`]) {
20753
20874
  if (!AGENT_NAME.test(name)) continue;
20754
- const file = path60.join(AGENTS, name, AGENT_FILE3);
20755
- const written = fs56.existsSync(file) ? fs56.readFileSync(file, "utf8") : null;
20875
+ const file = path62.join(AGENTS, name, AGENT_FILE3);
20876
+ const written = fs57.existsSync(file) ? fs57.readFileSync(file, "utf8") : null;
20756
20877
  if (written === text5(name)) return name;
20757
20878
  if (written === null && !known2.has(name)) return name;
20758
20879
  }
@@ -20769,11 +20890,11 @@ ${q.options.map((o) => `- ${o}`).join("\n")}` : "";
20769
20890
  function removeCard(card) {
20770
20891
  dropCrossRefs(card.id);
20771
20892
  const target = card.folder ?? card.file;
20772
- stripReadmeRefs({ kind: card.folder ? "group" : "file", rel: path60.relative(TODO, target).split(path60.sep).join("/") });
20773
- fs56.rmSync(target, { recursive: true, force: true });
20893
+ stripReadmeRefs({ kind: card.folder ? "group" : "file", rel: path62.relative(TODO, target).split(path62.sep).join("/") });
20894
+ fs57.rmSync(target, { recursive: true, force: true });
20774
20895
  }
20775
20896
  function migrateCard(card) {
20776
- const { meta, body } = parseFrontmatter(fs56.readFileSync(card.file, "utf8"));
20897
+ const { meta, body } = parseFrontmatter(fs57.readFileSync(card.file, "utf8"));
20777
20898
  if (!meta) throw new Error("its frontmatter cannot be read");
20778
20899
  const raw = meta;
20779
20900
  const said3 = (key) => typeof raw[key] === "string" ? raw[key].trim() : "";
@@ -20783,19 +20904,19 @@ function migrateCard(card) {
20783
20904
  if (!flow) throw new Error("this board has no workflow to put it in");
20784
20905
  const text5 = (name2) => agentText(name2, meta.title || card.slug, body);
20785
20906
  const name = agentName(card, text5);
20786
- const dir = path60.join(AGENTS, name);
20787
- const file = path60.join(dir, AGENT_FILE3);
20788
- const madeDir = !fs56.existsSync(dir);
20789
- const wrote = !fs56.existsSync(file);
20907
+ const dir = path62.join(AGENTS, name);
20908
+ const file = path62.join(dir, AGENT_FILE3);
20909
+ const madeDir = !fs57.existsSync(dir);
20910
+ const wrote = !fs57.existsSync(file);
20790
20911
  try {
20791
- fs56.mkdirSync(dir, { recursive: true });
20792
- if (wrote) fs56.writeFileSync(file, text5(name));
20912
+ fs57.mkdirSync(dir, { recursive: true });
20913
+ if (wrote) fs57.writeFileSync(file, text5(name));
20793
20914
  const adopted = adoptWorkflowScheduled(flow.id, name, { cadence, lastRun });
20794
20915
  if (!adopted.ok) throw new Error(adopted.error);
20795
20916
  questionsToTriage(meta, name);
20796
20917
  } catch (e) {
20797
- if (madeDir) fs56.rmSync(dir, { recursive: true, force: true });
20798
- else if (wrote) fs56.rmSync(file, { force: true });
20918
+ if (madeDir) fs57.rmSync(dir, { recursive: true, force: true });
20919
+ else if (wrote) fs57.rmSync(file, { force: true });
20799
20920
  throw e;
20800
20921
  }
20801
20922
  if (card.folder) mergeInto2(card.folder, dir, ["root.md"]);
@@ -20805,7 +20926,7 @@ function migrateCard(card) {
20805
20926
  function migrateRecurringCards() {
20806
20927
  const done2 = { agents: [], removed: [], failed: [] };
20807
20928
  const dir = recurringDir();
20808
- if (!fs56.existsSync(dir)) return done2;
20929
+ if (!fs57.existsSync(dir)) return done2;
20809
20930
  migratePruneMemoryCard();
20810
20931
  moveSideFolders();
20811
20932
  for (const card of legacyCards()) {
@@ -20818,7 +20939,7 @@ function migrateRecurringCards() {
20818
20939
  done2.failed.push({ card: rel(card.file), why: e instanceof Error ? e.message : String(e) });
20819
20940
  }
20820
20941
  }
20821
- if (isEmpty(dir)) fs56.rmSync(dir, { recursive: true, force: true });
20942
+ if (isEmpty(dir)) fs57.rmSync(dir, { recursive: true, force: true });
20822
20943
  return done2;
20823
20944
  }
20824
20945
  function recurringMigrationLines(done2) {
@@ -20851,14 +20972,14 @@ var init_recurring = __esm({
20851
20972
  PRUNE_SLUG = "prune-the-memory";
20852
20973
  FETCH_SLUG = "fetch-triage-items";
20853
20974
  AGENT_FILE3 = "AGENT.md";
20854
- recurringDir = () => path60.join(TODO, LEGACY_RECURRING);
20855
- isEmpty = (dir) => fs56.readdirSync(dir).every((name) => name === ".DS_Store");
20975
+ recurringDir = () => path62.join(TODO, LEGACY_RECURRING);
20976
+ isEmpty = (dir) => fs57.readdirSync(dir).every((name) => name === ".DS_Store");
20856
20977
  SECTION = /^##\s+(.+?)\s*$/;
20857
20978
  }
20858
20979
  });
20859
20980
 
20860
20981
  // src/commands/init.ts
20861
- import fs57 from "node:fs";
20982
+ import fs58 from "node:fs";
20862
20983
  function boardReadme() {
20863
20984
  return `# Board
20864
20985
 
@@ -20871,20 +20992,20 @@ _(none)_
20871
20992
  `;
20872
20993
  }
20873
20994
  function writeConfigIfMissing() {
20874
- if (fs57.existsSync(CONFIG)) return false;
20875
- fs57.mkdirSync(KANBAN, { recursive: true });
20876
- fs57.writeFileSync(CONFIG, CONFIG_TEMPLATE);
20995
+ if (fs58.existsSync(CONFIG)) return false;
20996
+ fs58.mkdirSync(KANBAN, { recursive: true });
20997
+ fs58.writeFileSync(CONFIG, CONFIG_TEMPLATE);
20877
20998
  return true;
20878
20999
  }
20879
21000
  function writeModulesIfMissing() {
20880
- if (fs57.existsSync(MODULES_MD)) return false;
20881
- fs57.mkdirSync(KANBAN, { recursive: true });
20882
- fs57.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
21001
+ if (fs58.existsSync(MODULES_MD)) return false;
21002
+ fs58.mkdirSync(KANBAN, { recursive: true });
21003
+ fs58.writeFileSync(MODULES_MD, MODULES_TEMPLATE);
20883
21004
  return true;
20884
21005
  }
20885
21006
  function writeGitignoreIfMissing() {
20886
- fs57.mkdirSync(KANBAN, { recursive: true });
20887
- const text5 = fs57.existsSync(KANBAN_GITIGNORE) ? fs57.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
21007
+ fs58.mkdirSync(KANBAN, { recursive: true });
21008
+ const text5 = fs58.existsSync(KANBAN_GITIGNORE) ? fs58.readFileSync(KANBAN_GITIGNORE, "utf8") : "";
20888
21009
  const has = (rule) => text5.split("\n").some((line) => line.trim() === rule.line);
20889
21010
  const missing = IGNORE_RULES.filter((rule) => !has(rule));
20890
21011
  if (!missing.length) return false;
@@ -20892,37 +21013,37 @@ function writeGitignoreIfMissing() {
20892
21013
  ${rule.line}
20893
21014
  `).join("");
20894
21015
  const separator = !text5 || text5.endsWith("\n") ? "" : "\n";
20895
- fs57.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
21016
+ fs58.writeFileSync(KANBAN_GITIGNORE, `${text5}${separator}${block}`);
20896
21017
  return true;
20897
21018
  }
20898
21019
  function writeSkeletonIfMissing() {
20899
21020
  const added = [];
20900
- if (!fs57.existsSync(TODO)) {
20901
- fs57.mkdirSync(TODO, { recursive: true });
21021
+ if (!fs58.existsSync(TODO)) {
21022
+ fs58.mkdirSync(TODO, { recursive: true });
20902
21023
  added.push(`${rel(TODO)}/`);
20903
21024
  }
20904
- if (!fs57.existsSync(README)) {
20905
- fs57.writeFileSync(README, boardReadme());
21025
+ if (!fs58.existsSync(README)) {
21026
+ fs58.writeFileSync(README, boardReadme());
20906
21027
  added.push(rel(README));
20907
21028
  }
20908
21029
  return added;
20909
21030
  }
20910
21031
  function retireReleases() {
20911
21032
  const done2 = [];
20912
- if (fs57.existsSync(RELEASES)) {
20913
- fs57.rmSync(RELEASES);
21033
+ if (fs58.existsSync(RELEASES)) {
21034
+ fs58.rmSync(RELEASES);
20914
21035
  done2.push(`deleted ${rel(RELEASES)}`);
20915
21036
  }
20916
21037
  let cards = 0;
20917
21038
  for (const dir of [TODO, ARCHIVE]) {
20918
- if (!fs57.existsSync(dir)) continue;
21039
+ if (!fs58.existsSync(dir)) continue;
20919
21040
  for (const file of walkMd(dir)) {
20920
- const text5 = fs57.readFileSync(file, "utf8");
21041
+ const text5 = fs58.readFileSync(file, "utf8");
20921
21042
  const end2 = text5.startsWith("---\n") ? text5.indexOf("\n---", 3) : -1;
20922
21043
  if (end2 < 0) continue;
20923
21044
  const head = text5.slice(0, end2).replace(/\nrelease:[^\n]*/, "");
20924
21045
  if (head.length === end2) continue;
20925
- fs57.writeFileSync(file, head + text5.slice(end2));
21046
+ fs58.writeFileSync(file, head + text5.slice(end2));
20926
21047
  cards++;
20927
21048
  }
20928
21049
  }
@@ -20930,7 +21051,7 @@ function retireReleases() {
20930
21051
  return done2.join(", ");
20931
21052
  }
20932
21053
  function cmdInit() {
20933
- if (fs57.existsSync(KANBAN)) {
21054
+ if (fs58.existsSync(KANBAN)) {
20934
21055
  const added = [
20935
21056
  ...writeSkeletonIfMissing(),
20936
21057
  writeConfigIfMissing() && rel(CONFIG),
@@ -20965,8 +21086,8 @@ function cmdInit() {
20965
21086
  }
20966
21087
  return { board: rel(KANBAN), created: false, added, memory_paths: scaffolded.map((s) => rel(s.dir)) };
20967
21088
  }
20968
- fs57.mkdirSync(TODO, { recursive: true });
20969
- fs57.writeFileSync(README, boardReadme());
21089
+ fs58.mkdirSync(TODO, { recursive: true });
21090
+ fs58.writeFileSync(README, boardReadme());
20970
21091
  writeConfigIfMissing();
20971
21092
  scaffoldProjectMemory();
20972
21093
  writeModulesIfMissing();
@@ -21055,25 +21176,25 @@ var init_scheduled = __esm({
21055
21176
  });
21056
21177
 
21057
21178
  // src/lib/card-age.ts
21058
- import fs58 from "node:fs";
21059
- import path61 from "node:path";
21179
+ import fs59 from "node:fs";
21180
+ import path63 from "node:path";
21060
21181
  function staleAfterIn(config) {
21061
21182
  const days = Number(LINE.exec(config)?.[1]);
21062
21183
  return Number.isInteger(days) && days > 0 ? days : STALE_AFTER_DEFAULT;
21063
21184
  }
21064
21185
  function staleAfter() {
21065
- if (!fs58.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
21066
- return staleAfterIn(fs58.readFileSync(CONFIG, "utf8"));
21186
+ if (!fs59.existsSync(CONFIG)) return STALE_AFTER_DEFAULT;
21187
+ return staleAfterIn(fs59.readFileSync(CONFIG, "utf8"));
21067
21188
  }
21068
21189
  function todoPathspec(top) {
21069
- const from = path61.relative(real(top), real(TODO));
21070
- if (!from || from.startsWith("..") || path61.isAbsolute(from)) return null;
21071
- return from.split(path61.sep).join("/");
21190
+ const from = path63.relative(real(top), real(TODO));
21191
+ if (!from || from.startsWith("..") || path63.isAbsolute(from)) return null;
21192
+ return from.split(path63.sep).join("/");
21072
21193
  }
21073
21194
  function cardFile2(spec, printed) {
21074
21195
  const p = unquotePath(printed);
21075
21196
  if (!p.startsWith(`${spec}/`)) return null;
21076
- return path61.join(TODO, ...p.slice(spec.length + 1).split("/"));
21197
+ return path63.join(TODO, ...p.slice(spec.length + 1).split("/"));
21077
21198
  }
21078
21199
  function dirtyCards(top, spec) {
21079
21200
  const out = git(["status", "--porcelain", "--untracked-files=all", "--", spec], top);
@@ -21120,9 +21241,9 @@ var init_card_age = __esm({
21120
21241
  gitTop = () => git(["rev-parse", "--show-toplevel"])?.trim() || null;
21121
21242
  real = (p) => {
21122
21243
  try {
21123
- return fs58.realpathSync(p);
21244
+ return fs59.realpathSync(p);
21124
21245
  } catch {
21125
- return path61.resolve(p);
21246
+ return path63.resolve(p);
21126
21247
  }
21127
21248
  };
21128
21249
  unquotePath = (line) => {
@@ -21157,8 +21278,8 @@ var init_card_holds = __esm({
21157
21278
  });
21158
21279
 
21159
21280
  // src/commands/list.ts
21160
- import fs59 from "node:fs";
21161
- import path62 from "node:path";
21281
+ import fs60 from "node:fs";
21282
+ import path64 from "node:path";
21162
21283
  function summaryLine(body) {
21163
21284
  const lines = body.split("\n");
21164
21285
  let i = 0;
@@ -21174,13 +21295,13 @@ function summaryLine(body) {
21174
21295
  function openRows() {
21175
21296
  const rows = [];
21176
21297
  for (const file of walkMd(TODO)) {
21177
- const base = path62.basename(file);
21298
+ const base = path64.basename(file);
21178
21299
  if (base === "README.md") continue;
21179
21300
  const isRoot = base === "root.md";
21180
- const id = isRoot ? idPrefix(path62.basename(path62.dirname(file))) : idPrefix(base);
21301
+ const id = isRoot ? idPrefix(path64.basename(path64.dirname(file))) : idPrefix(base);
21181
21302
  if (id == null) continue;
21182
- if (isLegacyRecurring(path62.relative(TODO, file))) continue;
21183
- const { meta, body } = parseFrontmatter(fs59.readFileSync(file, "utf8"));
21303
+ if (isLegacyRecurring(path64.relative(TODO, file))) continue;
21304
+ const { meta, body } = parseFrontmatter(fs60.readFileSync(file, "utf8"));
21184
21305
  rows.push({
21185
21306
  id,
21186
21307
  file,
@@ -21222,15 +21343,15 @@ function cmdStale(rows, all2, scope, mod) {
21222
21343
  }
21223
21344
  function archivedFiles() {
21224
21345
  const files2 = /* @__PURE__ */ new Map();
21225
- if (!fs59.existsSync(ARCHIVE)) return files2;
21346
+ if (!fs60.existsSync(ARCHIVE)) return files2;
21226
21347
  for (const file of walkMd(ARCHIVE)) {
21227
- const id = idPrefix(path62.basename(file));
21348
+ const id = idPrefix(path64.basename(file));
21228
21349
  if (id !== null) files2.set(id, file);
21229
21350
  }
21230
21351
  for (const dir of walkDirs(ARCHIVE)) {
21231
- const id = idPrefix(path62.basename(dir));
21232
- const root = path62.join(dir, "root.md");
21233
- if (id !== null && fs59.existsSync(root)) files2.set(id, root);
21352
+ const id = idPrefix(path64.basename(dir));
21353
+ const root = path64.join(dir, "root.md");
21354
+ if (id !== null && fs60.existsSync(root)) files2.set(id, root);
21234
21355
  }
21235
21356
  return files2;
21236
21357
  }
@@ -21341,14 +21462,14 @@ var init_list = __esm({
21341
21462
  });
21342
21463
 
21343
21464
  // src/commands/misc.ts
21344
- import fs60 from "node:fs";
21345
- import path63 from "node:path";
21465
+ import fs61 from "node:fs";
21466
+ import path65 from "node:path";
21346
21467
  function extractOldMeta(text5, file) {
21347
21468
  const grab = (re) => {
21348
21469
  const m = text5.match(re);
21349
21470
  return m ? m[1].trim() : null;
21350
21471
  };
21351
- const title = grab(/^#\s+(.+)$/m) || slugify(path63.basename(file, ".md").replace(/^\d+-/, "")).replace(/-/g, " ");
21472
+ const title = grab(/^#\s+(.+)$/m) || slugify(path65.basename(file, ".md").replace(/^\d+-/, "")).replace(/-/g, " ");
21352
21473
  const norm = (raw) => {
21353
21474
  const v = (raw || "").toLowerCase();
21354
21475
  return LEVELS.includes(v) ? v : "med";
@@ -21375,11 +21496,11 @@ function stripOldHeader(text5) {
21375
21496
  }
21376
21497
  function cmdMigrate(opts) {
21377
21498
  const dry = opts.dryRun === true;
21378
- const files2 = walkMd(TODO).filter((f) => path63.basename(f) !== "README.md");
21499
+ const files2 = walkMd(TODO).filter((f) => path65.basename(f) !== "README.md");
21379
21500
  let changed = 0;
21380
21501
  let skipped = 0;
21381
21502
  for (const file of files2) {
21382
- const text5 = fs60.readFileSync(file, "utf8");
21503
+ const text5 = fs61.readFileSync(file, "utf8");
21383
21504
  if (text5.trimStart().startsWith("---")) {
21384
21505
  skipped++;
21385
21506
  continue;
@@ -21388,7 +21509,7 @@ function cmdMigrate(opts) {
21388
21509
  const out = serializeFrontmatter(meta) + "\n\n" + stripOldHeader(text5).replace(/^\n+/, "");
21389
21510
  if (dry) say(`would migrate ${rel(file)} (priority=${meta.priority})`);
21390
21511
  else {
21391
- fs60.writeFileSync(file, out.endsWith("\n") ? out : out + "\n");
21512
+ fs61.writeFileSync(file, out.endsWith("\n") ? out : out + "\n");
21392
21513
  say(`migrated ${rel(file)}`);
21393
21514
  }
21394
21515
  changed++;
@@ -21409,10 +21530,10 @@ var init_misc = __esm({
21409
21530
  });
21410
21531
 
21411
21532
  // src/lib/group-close.ts
21412
- import fs61 from "node:fs";
21533
+ import fs62 from "node:fs";
21413
21534
  function groupCloses(rootFile) {
21414
21535
  try {
21415
- return groupCloseOf(fs61.readFileSync(rootFile, "utf8"));
21536
+ return groupCloseOf(fs62.readFileSync(rootFile, "utf8"));
21416
21537
  } catch {
21417
21538
  return false;
21418
21539
  }
@@ -21425,12 +21546,12 @@ var init_group_close = __esm({
21425
21546
  });
21426
21547
 
21427
21548
  // src/commands/remove.ts
21428
- import fs62 from "node:fs";
21429
- import path64 from "node:path";
21549
+ import fs63 from "node:fs";
21550
+ import path66 from "node:path";
21430
21551
  function leavingIds(id, found2) {
21431
21552
  const ids = /* @__PURE__ */ new Set([id]);
21432
21553
  if (found2.kind === "group") {
21433
- const names4 = [...walkMd(found2.target), ...walkDirs(found2.target)].map((f) => path64.basename(f));
21554
+ const names4 = [...walkMd(found2.target), ...walkDirs(found2.target)].map((f) => path66.basename(f));
21434
21555
  for (const name of names4) {
21435
21556
  const n = idPrefix(name);
21436
21557
  if (n !== null) ids.add(n);
@@ -21442,10 +21563,10 @@ function findMentions(ids) {
21442
21563
  const hits = [];
21443
21564
  const re = new RegExp(ids.map((id) => `#${id}(?!\\d)`).join("|"));
21444
21565
  for (const dir of [TODO, MEMORY]) {
21445
- if (!fs62.existsSync(dir)) continue;
21566
+ if (!fs63.existsSync(dir)) continue;
21446
21567
  for (const file of walkMd(dir)) {
21447
- if (path64.basename(file) === "README.md") continue;
21448
- const lines = fs62.readFileSync(file, "utf8").split("\n");
21568
+ if (path66.basename(file) === "README.md") continue;
21569
+ const lines = fs63.readFileSync(file, "utf8").split("\n");
21449
21570
  const fmEnd = frontmatterEnd(lines);
21450
21571
  lines.forEach((line, i) => {
21451
21572
  if (!re.test(line)) return;
@@ -21461,12 +21582,12 @@ function findMentions(ids) {
21461
21582
  return hits;
21462
21583
  }
21463
21584
  function leavingCards(id, found2) {
21464
- const own = found2.kind === "group" ? path64.join(found2.target, "root.md") : found2.target;
21585
+ const own = found2.kind === "group" ? path66.join(found2.target, "root.md") : found2.target;
21465
21586
  const cards = [{ id, file: own }];
21466
21587
  if (found2.kind !== "group") return cards;
21467
21588
  for (const file of walkMd(found2.target)) {
21468
21589
  if (file === own) continue;
21469
- const n = idPrefix(path64.basename(file));
21590
+ const n = idPrefix(path66.basename(file));
21470
21591
  if (n !== null) cards.push({ id: n, file });
21471
21592
  }
21472
21593
  return cards;
@@ -21475,10 +21596,10 @@ function stampLeaving(cards, rejection) {
21475
21596
  const day = formatDay();
21476
21597
  const stamp4 = rejection && !rejection.discard ? { reason: rejection.reason, at: (/* @__PURE__ */ new Date()).toISOString(), by: insideRun() ? "agent" : "user" } : rejection && { reason: rejection.reason };
21477
21598
  for (const card of cards) {
21478
- if (!fs62.existsSync(card.file)) continue;
21479
- const text5 = fs62.readFileSync(card.file, "utf8");
21599
+ if (!fs63.existsSync(card.file)) continue;
21600
+ const text5 = fs63.readFileSync(card.file, "utf8");
21480
21601
  const stamped = stampLeavingIn(text5, day, stamp4);
21481
- if (stamped !== text5) fs62.writeFileSync(card.file, stamped);
21602
+ if (stamped !== text5) fs63.writeFileSync(card.file, stamped);
21482
21603
  }
21483
21604
  }
21484
21605
  function unfinishedDelivery(id) {
@@ -21494,7 +21615,7 @@ function unfinishedDelivery(id) {
21494
21615
  }[gap];
21495
21616
  return `#${id} is not finished: ${what}.`;
21496
21617
  }
21497
- const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs62.existsSync(path64.join(ASSETS, src.slice(".assets/".length))));
21618
+ const missing = planDeliverables(card.body).filter((src) => src.startsWith(".assets/")).find((src) => !fs63.existsSync(path66.join(ASSETS, src.slice(".assets/".length))));
21498
21619
  return missing ? `#${id} is not finished: ${missing} is not on this machine.` : null;
21499
21620
  }
21500
21621
  function agentDecisions(text5) {
@@ -21521,8 +21642,8 @@ function removeCard2(id, metric, options) {
21521
21642
  const unfinished = metric === "completed" ? unfinishedDelivery(id) : null;
21522
21643
  if (unfinished) die(unfinished, { kind: "plan-delivery-unfinished" });
21523
21644
  const dest = options.cleanupDiscarded && locateArchived(id) ? null : archiveDest(found2);
21524
- const cardFile3 = found2.kind === "group" ? path64.join(found2.target, "root.md") : found2.target;
21525
- const cardText = fs62.existsSync(cardFile3) ? fs62.readFileSync(cardFile3, "utf8") : "";
21645
+ const cardFile3 = found2.kind === "group" ? path66.join(found2.target, "root.md") : found2.target;
21646
+ const cardText = fs63.existsSync(cardFile3) ? fs63.readFileSync(cardFile3, "utf8") : "";
21526
21647
  const { meta: cardMeta3 } = parseFrontmatter(cardText);
21527
21648
  const alsoRemoved = found2.kind === "group" ? walkMd(found2.target).filter((f) => f !== cardFile3).map((f) => rel(f)).sort() : [];
21528
21649
  const leftIds = leavingIds(id, found2);
@@ -21553,10 +21674,10 @@ function removeCard2(id, metric, options) {
21553
21674
  const groupRoot = found2.kind === "file" && !options.closing ? enclosingGroupRoot(found2.target) : null;
21554
21675
  if (dest) {
21555
21676
  stampLeaving(leaving, metric === "rejected" ? { reason: options.reason?.trim() ?? "", discard: options.discard === true } : null);
21556
- fs62.mkdirSync(ARCHIVE, { recursive: true });
21557
- fs62.renameSync(found2.target, dest);
21677
+ fs63.mkdirSync(ARCHIVE, { recursive: true });
21678
+ fs63.renameSync(found2.target, dest);
21558
21679
  } else {
21559
- fs62.rmSync(found2.target, { recursive: true, force: true });
21680
+ fs63.rmSync(found2.target, { recursive: true, force: true });
21560
21681
  }
21561
21682
  const removedRefs = stripReadmeRefs(found2);
21562
21683
  let marked2 = null;
@@ -21605,14 +21726,14 @@ function removeCard2(id, metric, options) {
21605
21726
  };
21606
21727
  }
21607
21728
  function closeGroup(rootFile) {
21608
- const rootId = idPrefix(path64.basename(path64.dirname(rootFile)));
21729
+ const rootId = idPrefix(path66.basename(path66.dirname(rootFile)));
21609
21730
  if (rootId === null) return null;
21610
21731
  if (runnerProject(KANBAN)) return null;
21611
21732
  if (!groupCloses(rootFile)) return null;
21612
21733
  say(`
21613
21734
  every subtask line on #${rootId} is resolved \u2014 closing the group:`);
21614
21735
  try {
21615
- const { meta, body } = parseFrontmatter(fs62.readFileSync(rootFile, "utf8"));
21736
+ const { meta, body } = parseFrontmatter(fs63.readFileSync(rootFile, "utf8"));
21616
21737
  const res = cmdRemove(rootId, "completed", { closing: true });
21617
21738
  return {
21618
21739
  id: rootId,
@@ -21669,7 +21790,7 @@ function cleanupDiscardedCards(sessionId) {
21669
21790
  if (card.pending) throw new Error(`Discarding #${card.id} did not finish. Retry the discard.`);
21670
21791
  while (locate(card.id)) cmdRemove(card.id, "rejected", { discard: true, cleanupDiscarded: true });
21671
21792
  dropCrossRefs(card.id);
21672
- stripReadmeRefs({ kind: "file", rel: path64.relative(TODO, path64.resolve(REPO_ROOT, card.path)).split(path64.sep).join("/") });
21793
+ stripReadmeRefs({ kind: "file", rel: path66.relative(TODO, path66.resolve(REPO_ROOT, card.path)).split(path66.sep).join("/") });
21673
21794
  }
21674
21795
  return discarded.map((c) => c.id);
21675
21796
  });
@@ -21755,8 +21876,8 @@ var init_memory_file = __esm({
21755
21876
  });
21756
21877
 
21757
21878
  // src/commands/rule.ts
21758
- import fs63 from "node:fs";
21759
- import path65 from "node:path";
21879
+ import fs64 from "node:fs";
21880
+ import path67 from "node:path";
21760
21881
  function cmdRule(askedName, flags) {
21761
21882
  const agent = askedName.trim();
21762
21883
  if (!agentRoster().some((a) => a.name === agent)) {
@@ -21765,7 +21886,7 @@ function cmdRule(askedName, flags) {
21765
21886
  const rule = readRuleText(flags.file, flags.text);
21766
21887
  const res = setAgentRule(agent, rule);
21767
21888
  if (!res.ok) die(res.error);
21768
- const file = rel(path65.join(RULES, `${agent}.md`));
21889
+ const file = rel(path67.join(RULES, `${agent}.md`));
21769
21890
  say(rule ? `wrote the \`${agent}\` rule (${file})` : `cleared the \`${agent}\` rule`);
21770
21891
  return { agent, file, cleared: !rule };
21771
21892
  }
@@ -21773,7 +21894,7 @@ function readRuleText(file, text5) {
21773
21894
  if (file !== void 0 && text5 !== void 0) die("pass --file or --text, not both");
21774
21895
  if (file !== void 0) {
21775
21896
  try {
21776
- return fs63.readFileSync(file, "utf8").trim();
21897
+ return fs64.readFileSync(file, "utf8").trim();
21777
21898
  } catch {
21778
21899
  die(`can't read ${file} \u2014 write the rule to a file, then pass its path`);
21779
21900
  }
@@ -21900,22 +22021,22 @@ var init_storyboard = __esm({
21900
22021
  });
21901
22022
 
21902
22023
  // src/lib/spec-contract.ts
21903
- import fs64 from "node:fs";
21904
- import path66 from "node:path";
22024
+ import fs65 from "node:fs";
22025
+ import path68 from "node:path";
21905
22026
  function snapshotSpecs() {
21906
22027
  const out = /* @__PURE__ */ new Map();
21907
- if (!fs64.existsSync(TODO)) return out;
22028
+ if (!fs65.existsSync(TODO)) return out;
21908
22029
  for (const file of walkMd(TODO)) {
21909
- if (isLegacyRecurring(path66.relative(TODO, file))) continue;
21910
- const id = idPrefix(path66.basename(file) === "root.md" ? path66.basename(path66.dirname(file)) : path66.basename(file));
21911
- if (id !== null) out.set(file, { id, text: fs64.readFileSync(file, "utf8") });
22030
+ if (isLegacyRecurring(path68.relative(TODO, file))) continue;
22031
+ const id = idPrefix(path68.basename(file) === "root.md" ? path68.basename(path68.dirname(file)) : path68.basename(file));
22032
+ if (id !== null) out.set(file, { id, text: fs65.readFileSync(file, "utf8") });
21912
22033
  }
21913
22034
  return out;
21914
22035
  }
21915
22036
  function enclosingGroups(file) {
21916
22037
  const ids = [];
21917
22038
  for (let root = enclosingGroupRoot(file); root; root = enclosingGroupRoot(root)) {
21918
- const id = idPrefix(path66.basename(path66.dirname(root)));
22039
+ const id = idPrefix(path68.basename(path68.dirname(root)));
21919
22040
  if (id !== null) ids.push(id);
21920
22041
  }
21921
22042
  return ids;
@@ -22084,9 +22205,9 @@ function validateSpec(file, text5, id) {
22084
22205
  }
22085
22206
  function inside(dir, name) {
22086
22207
  try {
22087
- const root = fs64.realpathSync(dir);
22088
- const real2 = fs64.realpathSync(path66.join(dir, name));
22089
- return real2.startsWith(root + path66.sep) && fs64.statSync(real2).isFile() ? real2 : null;
22208
+ const root = fs65.realpathSync(dir);
22209
+ const real2 = fs65.realpathSync(path68.join(dir, name));
22210
+ return real2.startsWith(root + path68.sep) && fs65.statSync(real2).isFile() ? real2 : null;
22090
22211
  } catch {
22091
22212
  return null;
22092
22213
  }
@@ -22104,7 +22225,7 @@ function variantsProblem(raw, src, id) {
22104
22225
  if (files2.length < 2 || !files2.every((f) => typeof f === "string" && f)) return `variants needs at least two labels, each naming a file. ${shape}`;
22105
22226
  if (!files2.includes(src)) return `src="${src}" is not one of the variants. Set src to the version shown first.`;
22106
22227
  if (id === void 0) return null;
22107
- const dir = path66.join(ASSETS, String(id));
22228
+ const dir = path68.join(ASSETS, String(id));
22108
22229
  for (const f of files2) {
22109
22230
  const parts = f.split("/");
22110
22231
  if (parts.length !== 3 || parts[0] !== ".assets" || parts[1] !== String(id) || !inside(dir, parts[2])) {
@@ -22114,7 +22235,7 @@ function variantsProblem(raw, src, id) {
22114
22235
  return null;
22115
22236
  }
22116
22237
  function compareProblem(attrs, id) {
22117
- const dir = path66.join(ASSETS, String(id));
22238
+ const dir = path68.join(ASSETS, String(id));
22118
22239
  const src = (message) => ({ rule: "compare-src", message });
22119
22240
  const shots = (message) => ({ rule: "compare-shots", message });
22120
22241
  for (const side of ["a", "b"]) {
@@ -22134,7 +22255,7 @@ function compareProblem(attrs, id) {
22134
22255
  const file = inside(dir, named2.name);
22135
22256
  if (!file) return { message: `Compare shots ${at} names no file in this card's asset folder. Write the JSON there or fix the path.` };
22136
22257
  try {
22137
- return { data: JSON.parse(fs64.readFileSync(file, "utf8")) };
22258
+ return { data: JSON.parse(fs65.readFileSync(file, "utf8")) };
22138
22259
  } catch {
22139
22260
  return { message: `${at} is not valid JSON.` };
22140
22261
  }
@@ -22154,7 +22275,7 @@ function compareProblem(attrs, id) {
22154
22275
  }
22155
22276
  function validateStoryboards(file, id, text5) {
22156
22277
  const errors = [];
22157
- const dir = path66.join(ASSETS, String(id));
22278
+ const dir = path68.join(ASSETS, String(id));
22158
22279
  for (const marker of storyboardMarkers(text5)) {
22159
22280
  const named2 = assetName(marker.src, id, ["json"]);
22160
22281
  const add = (message) => errors.push({ file: rel(file), line: marker.line, rule: "storyboard-src", message });
@@ -22303,8 +22424,8 @@ var init_mockups = __esm({
22303
22424
  });
22304
22425
 
22305
22426
  // src/commands/spec-write.ts
22306
- import fs65 from "node:fs";
22307
- import path67 from "node:path";
22427
+ import fs66 from "node:fs";
22428
+ import path69 from "node:path";
22308
22429
  function cmdSpecWrite(id, askedName, flags) {
22309
22430
  const agent = findSpecAgent(askedName);
22310
22431
  if (!agent) die(notAnAgent(askedName), { kind: "no-such-spec-agent", specAgent: askedName });
@@ -22312,11 +22433,11 @@ function cmdSpecWrite(id, askedName, flags) {
22312
22433
  const section = readSection(flags.file, flags.text);
22313
22434
  const found2 = locate(id);
22314
22435
  if (!found2) die(`no task with id ${id} under ${rel(TODO)}`, { kind: "card-not-found", id });
22315
- const file = found2.kind === "group" ? path67.join(found2.target, "root.md") : found2.target;
22316
- const { meta, body } = parseFrontmatter(fs65.readFileSync(file, "utf8"));
22436
+ const file = found2.kind === "group" ? path69.join(found2.target, "root.md") : found2.target;
22437
+ const { meta, body } = parseFrontmatter(fs66.readFileSync(file, "utf8"));
22317
22438
  if (!meta) die(`${rel(file)} has no frontmatter \u2014 run \`migrate\` first`);
22318
22439
  const { body: next, replaced } = splice(body, name, section);
22319
- fs65.writeFileSync(file, serializeFrontmatter(meta) + "\n" + next);
22440
+ fs66.writeFileSync(file, serializeFrontmatter(meta) + "\n" + next);
22320
22441
  say(`${replaced ? "rewrote" : "wrote"} the \`${name}\` section on #${id} (${rel(file)})`);
22321
22442
  return { id, specAgent: name, replaced, file: rel(file) };
22322
22443
  }
@@ -22325,7 +22446,7 @@ function readSection(file, text5) {
22325
22446
  let raw;
22326
22447
  if (file !== void 0) {
22327
22448
  try {
22328
- raw = fs65.readFileSync(file, "utf8");
22449
+ raw = fs66.readFileSync(file, "utf8");
22329
22450
  } catch {
22330
22451
  die(`can't read ${file} \u2014 write your section to a file, then pass its path`);
22331
22452
  }
@@ -22791,11 +22912,11 @@ var init_shared = __esm({
22791
22912
  });
22792
22913
 
22793
22914
  // src/commands/goal.ts
22794
- import fs66 from "node:fs";
22915
+ import fs67 from "node:fs";
22795
22916
  function load() {
22796
22917
  const file = goalsFile();
22797
22918
  if (!file) die("Goals exist only inside a WildCrane goal discussion.");
22798
- const held4 = JSON.parse(fs66.readFileSync(file, "utf8"));
22919
+ const held4 = JSON.parse(fs67.readFileSync(file, "utf8"));
22799
22920
  if (held4.goals !== void 0 && held4.ideas !== void 0 && JSON.stringify(held4.goals) !== JSON.stringify(held4.ideas)) die("goals and ideas do not match.");
22800
22921
  const goals = held4.goals ?? held4.ideas;
22801
22922
  if (!Array.isArray(goals)) die("The goals array is missing or invalid.");
@@ -22820,7 +22941,7 @@ function splitBody2(text5) {
22820
22941
  }
22821
22942
  function readBody(bodyFile) {
22822
22943
  if (!bodyFile) die("--body-file is required; write the goal in a writable temporary file first.");
22823
- const text5 = fs66.readFileSync(bodyFile, "utf8");
22944
+ const text5 = fs67.readFileSync(bodyFile, "utf8");
22824
22945
  if (!text5.trim()) die("The goal must not be empty.");
22825
22946
  return splitBody2(text5);
22826
22947
  }
@@ -22832,7 +22953,7 @@ function named(held4, id) {
22832
22953
  function cmdGoal(args, opts) {
22833
22954
  const sub = args[0] ?? "";
22834
22955
  const { file, held: held4 } = load();
22835
- const write2 = () => fs66.writeFileSync(file, `${JSON.stringify({ workflows: held4.workflows, ideas: held4.goals }, null, 2)}
22956
+ const write2 = () => fs67.writeFileSync(file, `${JSON.stringify({ workflows: held4.workflows, ideas: held4.goals }, null, 2)}
22836
22957
  `);
22837
22958
  if (sub === "new") {
22838
22959
  const title = opts.title?.trim();
@@ -22902,8 +23023,8 @@ __export(board_exports, {
22902
23023
  buildBoardProgram: () => buildBoardProgram
22903
23024
  });
22904
23025
  import crypto4 from "node:crypto";
22905
- import fs67 from "node:fs";
22906
- import path68 from "node:path";
23026
+ import fs68 from "node:fs";
23027
+ import path70 from "node:path";
22907
23028
  async function dispatch(move2, cmd, args, opts, cli) {
22908
23029
  const ctx = ctxOf(cmd, cli.program);
22909
23030
  const data = await runAction(ctx, {}, async () => {
@@ -22942,7 +23063,7 @@ async function cloudCard(task, opts) {
22942
23063
  let request;
22943
23064
  if (typeof opts.bodyFile === "string") {
22944
23065
  try {
22945
- request = fs67.readFileSync(opts.bodyFile, "utf8");
23066
+ request = fs68.readFileSync(opts.bodyFile, "utf8");
22946
23067
  } catch {
22947
23068
  }
22948
23069
  }
@@ -22972,7 +23093,7 @@ async function cloudCard(task, opts) {
22972
23093
  const file = creationReceipt(`${checked.value}:${requestId}`, slot);
22973
23094
  const journal = readCreation(file, said3);
22974
23095
  if (!journal.made) {
22975
- const key = `akb-${path68.basename(file, ".json").slice(0, 40)}`;
23096
+ const key = `akb-${path70.basename(file, ".json").slice(0, 40)}`;
22976
23097
  const made = await createProjectTask(checked.value, journal.said, key);
22977
23098
  if (!made.ok) throw new BoardError(creationError(`Cloud did not make the task: ${made.error}`, triage), { kind: "refused" });
22978
23099
  journal.made = made.value;
@@ -23117,16 +23238,16 @@ var init_board2 = __esm({
23117
23238
  });
23118
23239
 
23119
23240
  // src/lib/board-cli.ts
23120
- import fs68 from "node:fs";
23121
- import path69 from "node:path";
23241
+ import fs69 from "node:fs";
23242
+ import path71 from "node:path";
23122
23243
  function useBoard(found2, dirNamed) {
23123
- if (!found2.named && found2.board === path69.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23244
+ if (!found2.named && found2.board === path71.join(found2.root, "docs", "kanban")) setBoardRoot(found2.root, dirNamed);
23124
23245
  else setBoardDir(found2.board, found2.root);
23125
23246
  useProjectState();
23126
23247
  }
23127
23248
  function whole(found2, move2) {
23128
23249
  if (move2 === MAKES_A_BOARD) return found2;
23129
- if (!fs68.existsSync(path69.join(found2.board, "todo"))) {
23250
+ if (!fs69.existsSync(path71.join(found2.board, "todo"))) {
23130
23251
  die(`the board in ${found2.board} has no todo/ \u2014 run \`init\` to add what is missing.`, {
23131
23252
  kind: "board-incomplete",
23132
23253
  dir: found2.root
@@ -23135,13 +23256,13 @@ function whole(found2, move2) {
23135
23256
  return found2;
23136
23257
  }
23137
23258
  function findBoardUpward(from, move2) {
23138
- let dir = path69.resolve(from);
23259
+ let dir = path71.resolve(from);
23139
23260
  for (; ; ) {
23140
- if (hasBoard(dir)) return { root: dir, board: path69.join(dir, "docs", "kanban") };
23261
+ if (hasBoard(dir)) return { root: dir, board: path71.join(dir, "docs", "kanban") };
23141
23262
  if (isBoardDir(dir)) return { root: projectRootOf(dir), board: dir };
23142
- const kept2 = path69.join(dir, ".akb", "kanban");
23143
- if (move2 !== MAKES_A_BOARD && fs68.existsSync(path69.join(kept2, "todo"))) return { root: dir, board: kept2 };
23144
- const up = path69.dirname(dir);
23263
+ const kept2 = path71.join(dir, ".akb", "kanban");
23264
+ if (move2 !== MAKES_A_BOARD && fs69.existsSync(path71.join(kept2, "todo"))) return { root: dir, board: kept2 };
23265
+ const up = path71.dirname(dir);
23145
23266
  if (up === dir) return null;
23146
23267
  dir = up;
23147
23268
  }
@@ -23149,11 +23270,11 @@ function findBoardUpward(from, move2) {
23149
23270
  function resolveBoard(move2, { board: board2, dir, cwd, installHint }) {
23150
23271
  const named2 = board2 ?? boardFromEnv();
23151
23272
  if (named2) {
23152
- const folder = path69.resolve(cwd, named2);
23153
- if (!fs68.existsSync(folder) && move2 !== MAKES_A_BOARD) {
23273
+ const folder = path71.resolve(cwd, named2);
23274
+ if (!fs69.existsSync(folder) && move2 !== MAKES_A_BOARD) {
23154
23275
  die(`no such folder: ${folder}`, { kind: "no-such-folder", dir: folder });
23155
23276
  }
23156
- if (fs68.existsSync(folder) && !isBoardDir(folder) && move2 !== MAKES_A_BOARD) {
23277
+ if (fs69.existsSync(folder) && !isBoardDir(folder) && move2 !== MAKES_A_BOARD) {
23157
23278
  die(`${folder} is not a board \u2014 it has no todo/ and config.md. ${installHint}\u3002`, {
23158
23279
  kind: "no-board",
23159
23280
  dir: folder
@@ -23162,24 +23283,24 @@ function resolveBoard(move2, { board: board2, dir, cwd, installHint }) {
23162
23283
  return { root: projectRootOf(folder), board: folder, named: true };
23163
23284
  }
23164
23285
  if (dir !== null) {
23165
- const root = path69.resolve(dir);
23166
- if (!fs68.existsSync(root)) die(`no such folder: ${root}`, { kind: "no-such-folder", dir: root });
23167
- const kept2 = path69.join(root, ".akb", "kanban");
23168
- if (!hasBoard(root) && move2 !== MAKES_A_BOARD && fs68.existsSync(path69.join(kept2, "todo"))) return whole({ root, board: kept2 }, move2);
23286
+ const root = path71.resolve(dir);
23287
+ if (!fs69.existsSync(root)) die(`no such folder: ${root}`, { kind: "no-such-folder", dir: root });
23288
+ const kept2 = path71.join(root, ".akb", "kanban");
23289
+ if (!hasBoard(root) && move2 !== MAKES_A_BOARD && fs69.existsSync(path71.join(kept2, "todo"))) return whole({ root, board: kept2 }, move2);
23169
23290
  if (!hasBoard(root) && move2 !== MAKES_A_BOARD) {
23170
23291
  die(`no board in ${root} \u2014 it has no docs/kanban/. ${installHint}\u3002`, {
23171
23292
  kind: "no-board",
23172
23293
  dir: root
23173
23294
  });
23174
23295
  }
23175
- return whole({ root, board: path69.join(root, "docs", "kanban") }, move2);
23296
+ return whole({ root, board: path71.join(root, "docs", "kanban") }, move2);
23176
23297
  }
23177
23298
  const found2 = findBoardUpward(cwd, move2);
23178
23299
  if (found2) return whole(found2, move2);
23179
- if (move2 === MAKES_A_BOARD) return { root: path69.resolve(cwd), board: path69.join(path69.resolve(cwd), "docs", "kanban") };
23300
+ if (move2 === MAKES_A_BOARD) return { root: path71.resolve(cwd), board: path71.join(path71.resolve(cwd), "docs", "kanban") };
23180
23301
  die(
23181
- `no board here. Looked in ${path69.resolve(cwd)} and every folder above it for docs/kanban/. ${installHint}\uFF0C\u6216\u7528 --board \u6307\u5B9A\u5DF2\u6709\u770B\u677F\u3002`,
23182
- { kind: "no-board", dir: path69.resolve(cwd) }
23302
+ `no board here. Looked in ${path71.resolve(cwd)} and every folder above it for docs/kanban/. ${installHint}\uFF0C\u6216\u7528 --board \u6307\u5B9A\u5DF2\u6709\u770B\u677F\u3002`,
23303
+ { kind: "no-board", dir: path71.resolve(cwd) }
23183
23304
  );
23184
23305
  }
23185
23306
  function editDistance(a, b) {
@@ -23261,8 +23382,8 @@ var init_board_cli = __esm({
23261
23382
  init_io();
23262
23383
  init_pointer();
23263
23384
  MAKES_A_BOARD = "init";
23264
- hasBoard = (dir) => fs68.existsSync(path69.join(dir, "docs", "kanban"));
23265
- isBoardDir = (dir) => fs68.existsSync(path69.join(dir, "todo")) && fs68.existsSync(path69.join(dir, "config.md"));
23385
+ hasBoard = (dir) => fs69.existsSync(path71.join(dir, "docs", "kanban"));
23386
+ isBoardDir = (dir) => fs69.existsSync(path71.join(dir, "todo")) && fs69.existsSync(path71.join(dir, "config.md"));
23266
23387
  boardFromEnv = () => {
23267
23388
  const named2 = process.env.AI4KANBAN_BOARD?.trim();
23268
23389
  return named2 ? named2 : null;
@@ -23529,8 +23650,8 @@ var init_guide = __esm({
23529
23650
  });
23530
23651
 
23531
23652
  // src/lib/agent/approve.ts
23532
- import fs74 from "node:fs";
23533
- import path75 from "node:path";
23653
+ import fs75 from "node:fs";
23654
+ import path77 from "node:path";
23534
23655
  function approvalRequest(req) {
23535
23656
  const id = req.id;
23536
23657
  const card = id === void 0 ? null : findCard(id);
@@ -23548,12 +23669,12 @@ function advancePhase(id) {
23548
23669
  const card = findCard(id);
23549
23670
  const found2 = locate(id);
23550
23671
  if (!card || !found2 || !awaitingApproval(card)) return { error: `#${id} is no longer waiting on approval.` };
23551
- const file = found2.kind === "group" ? path75.join(found2.target, "root.md") : found2.target;
23552
- const { meta, body } = parseFrontmatter(fs74.readFileSync(file, "utf8"));
23672
+ const file = found2.kind === "group" ? path77.join(found2.target, "root.md") : found2.target;
23673
+ const { meta, body } = parseFrontmatter(fs75.readFileSync(file, "utf8"));
23553
23674
  if (!meta) return { error: `#${id} has no frontmatter` };
23554
23675
  meta.phase = card.stage + 1;
23555
23676
  meta.status = "todo";
23556
- fs74.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
23677
+ fs75.writeFileSync(file, serializeFrontmatter(meta) + "\n" + body);
23557
23678
  return null;
23558
23679
  }
23559
23680
  var init_approve = __esm({
@@ -23677,16 +23798,16 @@ var init_start = __esm({
23677
23798
  });
23678
23799
 
23679
23800
  // src/lib/agent/task-chats.ts
23680
- import fs75 from "node:fs";
23681
- import path76 from "node:path";
23801
+ import fs76 from "node:fs";
23802
+ import path78 from "node:path";
23682
23803
  function taskChatFile(task, home3) {
23683
23804
  if (!TASK.test(task)) throw new Error(`${task} is not a task id.`);
23684
- return path76.join(taskChatsDir(home3), `${task}.jsonl`);
23805
+ return path78.join(taskChatsDir(home3), `${task}.jsonl`);
23685
23806
  }
23686
23807
  function readTaskChat(task, home3) {
23687
23808
  let text5;
23688
23809
  try {
23689
- text5 = fs75.readFileSync(taskChatFile(task, home3), "utf8");
23810
+ text5 = fs76.readFileSync(taskChatFile(task, home3), "utf8");
23690
23811
  } catch {
23691
23812
  return [];
23692
23813
  }
@@ -23707,13 +23828,13 @@ var init_task_chats = __esm({
23707
23828
  "use strict";
23708
23829
  init_home();
23709
23830
  TASK = /^[\w-]{1,100}$/;
23710
- taskChatsDir = (home3 = machineHome()) => path76.join(home3, "chats");
23831
+ taskChatsDir = (home3 = machineHome()) => path78.join(home3, "chats");
23711
23832
  }
23712
23833
  });
23713
23834
 
23714
23835
  // src/lib/agent/memory-review.ts
23715
- import fs76 from "node:fs";
23716
- import path77 from "node:path";
23836
+ import fs77 from "node:fs";
23837
+ import path79 from "node:path";
23717
23838
  function taskChatsToReview(tasks) {
23718
23839
  const out = [];
23719
23840
  for (const ref of [...new Set(tasks)]) {
@@ -23735,8 +23856,8 @@ function readArchived2(id) {
23735
23856
  const found2 = Number.isInteger(id) && id > 0 ? locateArchived(id) : null;
23736
23857
  if (!found2) return null;
23737
23858
  try {
23738
- const file = found2.kind === "group" ? path77.join(found2.target, "root.md") : found2.target;
23739
- const { meta, body } = parseFrontmatter(fs76.readFileSync(file, "utf8"));
23859
+ const file = found2.kind === "group" ? path79.join(found2.target, "root.md") : found2.target;
23860
+ const { meta, body } = parseFrontmatter(fs77.readFileSync(file, "utf8"));
23740
23861
  if (!meta) return null;
23741
23862
  return { id, title: meta.title, modules: meta.modules ?? [], rejected: meta.rejected, body };
23742
23863
  } catch {
@@ -23805,17 +23926,17 @@ var init_memory_review = __esm({
23805
23926
  });
23806
23927
 
23807
23928
  // src/lib/agent/dismissal-review.ts
23808
- import fs77 from "node:fs";
23809
- import path78 from "node:path";
23929
+ import fs78 from "node:fs";
23930
+ import path80 from "node:path";
23810
23931
  function rejectionsToReview() {
23811
- const dir = path78.join(ARCHIVE, REJECTIONS_TO_REVIEW);
23812
- if (!fs77.existsSync(dir)) return [];
23932
+ const dir = path80.join(ARCHIVE, REJECTIONS_TO_REVIEW);
23933
+ if (!fs78.existsSync(dir)) return [];
23813
23934
  const found2 = [];
23814
23935
  for (const file of walkMd(dir)) {
23815
23936
  const id = archivedId(file);
23816
23937
  if (id === null) continue;
23817
23938
  try {
23818
- const { meta } = parseFrontmatter(fs77.readFileSync(file, "utf8"));
23939
+ const { meta } = parseFrontmatter(fs78.readFileSync(file, "utf8"));
23819
23940
  if (!meta?.rejected || meta.rejected_by !== "user" || !meta.rejected_reason.trim()) continue;
23820
23941
  found2.push({ id, title: meta.title, file: rel(file), reason: meta.rejected_reason.trim(), rejectedAt: meta.rejected_at });
23821
23942
  } catch {
@@ -23845,7 +23966,7 @@ function citedSources(text5) {
23845
23966
  function withdrawnSources() {
23846
23967
  const cited = [...new Set(plannerCopies("rejected.md").flatMap((file) => {
23847
23968
  try {
23848
- return citedSources(fs77.readFileSync(file, "utf8"));
23969
+ return citedSources(fs78.readFileSync(file, "utf8"));
23849
23970
  } catch {
23850
23971
  return [];
23851
23972
  }
@@ -23870,8 +23991,8 @@ var init_dismissal_review = __esm({
23870
23991
  });
23871
23992
 
23872
23993
  // src/lib/agent/flow.ts
23873
- import fs78 from "node:fs";
23874
- import path79 from "node:path";
23994
+ import fs79 from "node:fs";
23995
+ import path81 from "node:path";
23875
23996
  function readCard2(id, home3 = "board") {
23876
23997
  const found2 = home3 === "archive" ? locateArchived(id) : locate(id);
23877
23998
  if (!found2) {
@@ -23880,10 +24001,10 @@ function readCard2(id, home3 = "board") {
23880
24001
  { kind: "card-not-found", id }
23881
24002
  );
23882
24003
  }
23883
- const file = found2.kind === "group" ? path79.join(found2.target, "root.md") : found2.target;
24004
+ const file = found2.kind === "group" ? path81.join(found2.target, "root.md") : found2.target;
23884
24005
  let text5;
23885
24006
  try {
23886
- text5 = fs78.readFileSync(file, "utf8");
24007
+ text5 = fs79.readFileSync(file, "utf8");
23887
24008
  } catch {
23888
24009
  die(`#${id} is on the board but ${rel(file)} can't be read.`, { kind: "card-unreadable", id });
23889
24010
  }
@@ -24007,7 +24128,7 @@ function workspaceField(delivery) {
24007
24128
  if (!delivery?.worktree) return [];
24008
24129
  return field("workspace", [
24009
24130
  `write code in ${delivery.worktree} \u2014 this delivery's own worktree, on branch ${delivery.branch}.`,
24010
- path79.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.`,
24131
+ path81.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.`,
24011
24132
  `every board command names the project's own copy: \`${boardCommandFor()} <command>\`.`,
24012
24133
  `${rel(REPO_ROOT)} is the project \u2014 the card, the memory files and the docs are changed there, not here.`
24013
24134
  ]);
@@ -24751,7 +24872,7 @@ __export(watch_exports, {
24751
24872
  watchRun: () => watchRun
24752
24873
  });
24753
24874
  import { spawn as spawn4 } from "node:child_process";
24754
- import fs79 from "node:fs";
24875
+ import fs80 from "node:fs";
24755
24876
  async function watchRun(sessionId, resume = startResume) {
24756
24877
  const spec = readSpec(sessionId);
24757
24878
  const run2 = peekRun(sessionId);
@@ -24787,11 +24908,11 @@ async function watchRun(sessionId, resume = startResume) {
24787
24908
  const record = claimed ?? run2;
24788
24909
  const sub = record.action === "sub";
24789
24910
  if (claim) await setCardStatus(claim.cardId, claim.status);
24790
- fs79.mkdirSync(SESSIONS_DIR, { recursive: true });
24791
- const logFile = fs79.createWriteStream(record.logPath, { flags: "a" });
24911
+ fs80.mkdirSync(SESSIONS_DIR, { recursive: true });
24912
+ const logFile = fs80.createWriteStream(record.logPath, { flags: "a" });
24792
24913
  logFile.on("error", () => {
24793
24914
  });
24794
- const eventsFile = fs79.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
24915
+ const eventsFile = fs80.createWriteStream(eventsPathOf(sessionId), { flags: "a" });
24795
24916
  eventsFile.on("error", () => {
24796
24917
  });
24797
24918
  const event2 = (e) => eventsFile.write(`${JSON.stringify(e)}
@@ -25380,7 +25501,7 @@ var init_watch = __esm({
25380
25501
  });
25381
25502
 
25382
25503
  // src/kanban.ts
25383
- import fs85 from "node:fs";
25504
+ import fs86 from "node:fs";
25384
25505
  import { fileURLToPath as fileURLToPath3 } from "node:url";
25385
25506
 
25386
25507
  // src/lib/cli/agent.ts
@@ -25869,8 +25990,8 @@ async function testAgent(args) {
25869
25990
  }
25870
25991
 
25871
25992
  // src/commands/cloud.ts
25872
- import fs70 from "node:fs";
25873
- import path71 from "node:path";
25993
+ import fs71 from "node:fs";
25994
+ import path73 from "node:path";
25874
25995
 
25875
25996
  // src/lib/cloud/avatar.ts
25876
25997
  init_session();
@@ -25918,13 +26039,13 @@ init_config();
25918
26039
  init_home();
25919
26040
  init_config();
25920
26041
  init_session();
25921
- import fs69 from "node:fs";
25922
- import path70 from "node:path";
26042
+ import fs70 from "node:fs";
26043
+ import path72 from "node:path";
25923
26044
  var FRESH_MS = 10 * 6e4;
25924
26045
  var GRACE_MS = 7 * 24 * 60 * 6e4;
25925
- var heldFile = () => path70.join(machineHome(), "pro.json");
26046
+ var heldFile = () => path72.join(machineHome(), "pro.json");
25926
26047
  function forgetPro() {
25927
- fs69.rmSync(heldFile(), { force: true });
26048
+ fs70.rmSync(heldFile(), { force: true });
25928
26049
  }
25929
26050
 
25930
26051
  // src/lib/cloud/account.ts
@@ -26101,10 +26222,10 @@ async function cloudImage(opts, program2) {
26101
26222
  const prompt = opts.prompt.trim();
26102
26223
  if (!prompt) usage("Missing the prompt.", line);
26103
26224
  const references = opts.refs.map((file) => {
26104
- const type = REF_TYPES[path71.extname(file).toLowerCase()];
26225
+ const type = REF_TYPES[path73.extname(file).toLowerCase()];
26105
26226
  if (!type) usage(`--ref ${file}: use a PNG, JPEG or WebP file.`, line);
26106
26227
  try {
26107
- return `data:${type};base64,${fs70.readFileSync(file).toString("base64")}`;
26228
+ return `data:${type};base64,${fs71.readFileSync(file).toString("base64")}`;
26108
26229
  } catch (e) {
26109
26230
  usage(`--ref ${file}: ${e instanceof Error ? e.message : String(e)}`, line);
26110
26231
  }
@@ -26210,31 +26331,31 @@ async function generate(g) {
26210
26331
  refuse(g.failed, g.fallback);
26211
26332
  }
26212
26333
  const out = g.outFor?.(res, g.out) ?? g.out;
26213
- fs70.mkdirSync(path71.dirname(path71.resolve(out)), { recursive: true });
26214
- fs70.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
26334
+ fs71.mkdirSync(path73.dirname(path73.resolve(out)), { recursive: true });
26335
+ fs71.writeFileSync(out, Buffer.from(await res.arrayBuffer()));
26215
26336
  say(`${out} (${g.label(res)})`);
26216
26337
  return { out };
26217
26338
  }
26218
26339
 
26219
26340
  // src/commands/cloud-import.ts
26220
26341
  import crypto5 from "node:crypto";
26221
- import fs72 from "node:fs";
26222
- import path73 from "node:path";
26342
+ import fs73 from "node:fs";
26343
+ import path75 from "node:path";
26223
26344
 
26224
26345
  // ../cloud/src/board-files.ts
26225
26346
  var ROOTS = ["todo/", ".archive/", "memory/", "workflows/", "triage/", "assets/", "rules/"];
26226
26347
  var SETTINGS = ["modules.md", "config.md"];
26227
- var isSettingsPath = (path85) => SETTINGS.includes(path85) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path85);
26348
+ var isSettingsPath = (path87) => SETTINGS.includes(path87) || /^rules\/(?:workflows\/)?[^/]+\.md$/.test(path87);
26228
26349
  var BOARD_FILE_LIMIT = 256 * 1024;
26229
- function isBoardPath(path85) {
26230
- if (!path85 || path85.length > 500 || path85.startsWith("/") || path85.includes("\\") || path85.includes("\0")) return false;
26231
- if (path85.split("/").some((part) => !part || part === "." || part === "..")) return false;
26232
- if (path85 === "todo/README.md" || path85.split("/").includes(".sync")) return false;
26233
- if (path85.startsWith("workflows/")) return true;
26234
- if (SETTINGS.includes(path85)) return true;
26235
- if (path85.startsWith("rules/")) return isSettingsPath(path85);
26236
- if (path85.startsWith("assets/")) return path85.endsWith(".json");
26237
- return ROOTS.some((root) => path85.startsWith(root)) && path85.endsWith(".md");
26350
+ function isBoardPath(path87) {
26351
+ if (!path87 || path87.length > 500 || path87.startsWith("/") || path87.includes("\\") || path87.includes("\0")) return false;
26352
+ if (path87.split("/").some((part) => !part || part === "." || part === "..")) return false;
26353
+ if (path87 === "todo/README.md" || path87.split("/").includes(".sync")) return false;
26354
+ if (path87.startsWith("workflows/")) return true;
26355
+ if (SETTINGS.includes(path87)) return true;
26356
+ if (path87.startsWith("rules/")) return isSettingsPath(path87);
26357
+ if (path87.startsWith("assets/")) return path87.endsWith(".json");
26358
+ return ROOTS.some((root) => path87.startsWith(root)) && path87.endsWith(".md");
26238
26359
  }
26239
26360
  var workflowFolder = (id) => id.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
26240
26361
 
@@ -26338,8 +26459,8 @@ init_bundled();
26338
26459
  // src/lib/agents/shared-memory.ts
26339
26460
  init_bundled();
26340
26461
  init_parse();
26341
- import fs71 from "node:fs";
26342
- import path72 from "node:path";
26462
+ import fs72 from "node:fs";
26463
+ import path74 from "node:path";
26343
26464
  function sharedMemory(board2) {
26344
26465
  const declared = /* @__PURE__ */ new Map();
26345
26466
  const take = (folder, text5, builtIn) => {
@@ -26351,16 +26472,16 @@ function sharedMemory(board2) {
26351
26472
  const at = /^([^/]+)\/AGENT\.md$/.exec(key);
26352
26473
  if (at) take(at[1], text5, true);
26353
26474
  }
26354
- const root = path72.join(board2, "agents");
26475
+ const root = path74.join(board2, "agents");
26355
26476
  let folders2 = [];
26356
26477
  try {
26357
- folders2 = fs71.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
26478
+ folders2 = fs72.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
26358
26479
  } catch {
26359
26480
  }
26360
26481
  for (const folder of folders2.sort()) {
26361
26482
  let text5 = null;
26362
26483
  try {
26363
- text5 = fs71.readFileSync(path72.join(root, folder, "AGENT.md"), "utf8");
26484
+ text5 = fs72.readFileSync(path74.join(root, folder, "AGENT.md"), "utf8");
26364
26485
  } catch {
26365
26486
  }
26366
26487
  take(folder, text5, false);
@@ -26449,24 +26570,24 @@ async function findProject(asked) {
26449
26570
  }
26450
26571
  throw new Refused(`No project of yours has the id or prefix "${asked}".`, "not_found");
26451
26572
  }
26452
- var read = (file) => fs72.readFileSync(file, "utf8");
26573
+ var read = (file) => fs73.readFileSync(file, "utf8");
26453
26574
  var bytes2 = (text5) => Buffer.byteLength(text5, "utf8");
26454
26575
  function files(dir) {
26455
- if (!fs72.existsSync(dir)) return [];
26576
+ if (!fs73.existsSync(dir)) return [];
26456
26577
  const out = [];
26457
- for (const entry of fs72.readdirSync(dir, { withFileTypes: true })) {
26578
+ for (const entry of fs73.readdirSync(dir, { withFileTypes: true })) {
26458
26579
  if (entry.name.startsWith(".")) continue;
26459
- const full = path73.join(dir, entry.name);
26580
+ const full = path75.join(dir, entry.name);
26460
26581
  if (entry.isDirectory()) out.push(...files(full));
26461
26582
  else if (entry.isFile()) out.push(full);
26462
26583
  }
26463
26584
  return out;
26464
26585
  }
26465
- var posix2 = (p) => p.split(path73.sep).join("/");
26586
+ var posix2 = (p) => p.split(path75.sep).join("/");
26466
26587
  function openCards() {
26467
26588
  const out = [];
26468
26589
  for (const file of walkMd(TODO)) {
26469
- const rel2 = posix2(path73.relative(TODO, file));
26590
+ const rel2 = posix2(path75.relative(TODO, file));
26470
26591
  if (rel2 === "README.md") continue;
26471
26592
  const parts = rel2.split("/");
26472
26593
  const text5 = read(file);
@@ -26500,14 +26621,14 @@ function bodyProblems(text5) {
26500
26621
  return out;
26501
26622
  }
26502
26623
  function packWorkflow(flow) {
26503
- const own = path73.join(WORKFLOWS, flow.id);
26624
+ const own = path75.join(WORKFLOWS, flow.id);
26504
26625
  const out = {};
26505
- for (const file of files(own)) out[posix2(path73.relative(own, file))] = read(file);
26626
+ for (const file of files(own)) out[posix2(path75.relative(own, file))] = read(file);
26506
26627
  const named2 = [...flow.previews, ...flow.land, ...flow.scheduled].map((h) => h.agent).filter((a) => !LAND_ROLES.includes(a));
26507
26628
  for (const agent of new Set(named2)) {
26508
- const dir = path73.join(AGENTS, agent);
26509
- if (fs72.existsSync(path73.join(dir, "AGENT.md"))) {
26510
- for (const file of files(dir)) out[`agents/${agent}/${posix2(path73.relative(dir, file))}`] = read(file);
26629
+ const dir = path75.join(AGENTS, agent);
26630
+ if (fs73.existsSync(path75.join(dir, "AGENT.md"))) {
26631
+ for (const file of files(dir)) out[`agents/${agent}/${posix2(path75.relative(dir, file))}`] = read(file);
26511
26632
  continue;
26512
26633
  }
26513
26634
  for (const [key, text5] of Object.entries(BUNDLED_AGENT_FILES)) {
@@ -26559,8 +26680,8 @@ function draftsOf(text5) {
26559
26680
  const at = /^\.(assets|mockups)\/(.+)$/.exec(name);
26560
26681
  if (!at) continue;
26561
26682
  const base = at[1] === "assets" ? ASSETS : MOCKUPS;
26562
- const file = path73.resolve(base, at[2]);
26563
- if (file.startsWith(base + path73.sep) && fs72.statSync(file, { throwIfNoEntry: false })?.isFile()) out.set(name, file);
26683
+ const file = path75.resolve(base, at[2]);
26684
+ if (file.startsWith(base + path75.sep) && fs73.statSync(file, { throwIfNoEntry: false })?.isFile()) out.set(name, file);
26564
26685
  }
26565
26686
  return [...out].map(([name, file]) => ({ name, file }));
26566
26687
  }
@@ -26594,9 +26715,9 @@ async function uploadDrafts(task, drafts) {
26594
26715
  const assets = {};
26595
26716
  for (const { name, file } of drafts) {
26596
26717
  if (!card.body.includes(name)) continue;
26597
- const ext = path73.extname(file).toLowerCase();
26718
+ const ext = path75.extname(file).toLowerCase();
26598
26719
  const type = TYPES[ext] ?? "application/octet-stream";
26599
- const data = fs72.readFileSync(file);
26720
+ const data = fs73.readFileSync(file);
26600
26721
  const artifact = await api("POST", `/v1/tasks/${task}/artifacts`, { type: kindOf(ext), name: name.slice(0, 200) });
26601
26722
  const upload = await api("POST", `/v1/artifacts/${artifact.id}/uploads`, { content_type: type, size: Math.max(data.length, 1) });
26602
26723
  await api("PUT", `/v1/uploads/${upload.id}`, void 0, { bytes: data, type });
@@ -26639,10 +26760,10 @@ usage: ${program2} cloud import --project <id or prefix> [--dry-run]`, { kind: "
26639
26760
  async function run(asked, dryRun) {
26640
26761
  const project = await findProject(asked);
26641
26762
  const cloudFlows = await all(`/v1/workflows?workspace=${encodeURIComponent(project.workspace)}`);
26642
- const board2 = crypto5.createHash("sha256").update(fs72.realpathSync(KANBAN)).digest("hex").slice(0, 16);
26763
+ const board2 = crypto5.createHash("sha256").update(fs73.realpathSync(KANBAN)).digest("hex").slice(0, 16);
26643
26764
  const cards = openCards();
26644
26765
  const problems = [];
26645
- const where = (file) => posix2(path73.relative(KANBAN, file));
26766
+ const where = (file) => posix2(path75.relative(KANBAN, file));
26646
26767
  const own = workflows().filter((w) => !w.builtIn);
26647
26768
  const packed = /* @__PURE__ */ new Map();
26648
26769
  for (const flow of own) {
@@ -26669,7 +26790,7 @@ async function run(asked, dryRun) {
26669
26790
  const root = `projects/${project.id}/`;
26670
26791
  const boardFiles = [];
26671
26792
  for (const file of [...files(MEMORY), ...files(RULES), CONFIG, MODULES_MD]) {
26672
- if (!fs72.existsSync(file)) continue;
26793
+ if (!fs73.existsSync(file)) continue;
26673
26794
  const rel2 = where(file);
26674
26795
  if (!isBoardPath(rel2)) continue;
26675
26796
  const content = read(file);
@@ -26780,16 +26901,16 @@ async function run(asked, dryRun) {
26780
26901
  }
26781
26902
  function leftLocal(own) {
26782
26903
  const out = [];
26783
- const count4 = (dir) => fs72.existsSync(dir) ? walkMd(dir).length : 0;
26904
+ const count4 = (dir) => fs73.existsSync(dir) ? walkMd(dir).length : 0;
26784
26905
  const archived = count4(ARCHIVE);
26785
26906
  if (archived) out.push(`.archive/ (${archived})`);
26786
26907
  const triage = count4(TRIAGE);
26787
26908
  if (triage) out.push(`triage/ (${triage})`);
26788
- if (fs72.existsSync(DELIVERIES)) out.push("deliveries/");
26789
- if (fs72.existsSync(path73.join(KANBAN, "metrics.csv"))) out.push("metrics.csv");
26909
+ if (fs73.existsSync(DELIVERIES)) out.push("deliveries/");
26910
+ if (fs73.existsSync(path75.join(KANBAN, "metrics.csv"))) out.push("metrics.csv");
26790
26911
  const named2 = new Set(own.flatMap((w) => [...w.previews, ...w.land, ...w.scheduled].map((h) => h.agent)));
26791
- if (fs72.existsSync(AGENTS)) {
26792
- for (const e of fs72.readdirSync(AGENTS, { withFileTypes: true })) {
26912
+ if (fs73.existsSync(AGENTS)) {
26913
+ for (const e of fs73.readdirSync(AGENTS, { withFileTypes: true })) {
26793
26914
  if (e.isDirectory() && !e.name.startsWith(".") && !named2.has(e.name)) out.push(`agents/${e.name}/`);
26794
26915
  }
26795
26916
  }
@@ -26807,8 +26928,8 @@ init_session();
26807
26928
  init_io();
26808
26929
  init_paths();
26809
26930
  import { createHash as createHash4 } from "node:crypto";
26810
- import fs73 from "node:fs";
26811
- import path74 from "node:path";
26931
+ import fs74 from "node:fs";
26932
+ import path76 from "node:path";
26812
26933
  var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
26813
26934
  var CAPTURED = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;
26814
26935
  var MAX_BYTES3 = 50 * 1024 * 1024;
@@ -26907,10 +27028,10 @@ This template has no preview.`);
26907
27028
  const written = [];
26908
27029
  for (const p of previews) {
26909
27030
  const bytes3 = Buffer.from(await (await ask(`/${at}/previews/${route(p.path)}`, {}, WITHOUT)).arrayBuffer());
26910
- const file = path74.basename(p.path);
26911
- const out = path74.join(opts.to, file.startsWith(`${name}-`) ? file : `${name}-${file}`);
26912
- fs73.mkdirSync(opts.to, { recursive: true });
26913
- fs73.writeFileSync(out, bytes3);
27031
+ const file = path76.basename(p.path);
27032
+ const out = path76.join(opts.to, file.startsWith(`${name}-`) ? file : `${name}-${file}`);
27033
+ fs74.mkdirSync(opts.to, { recursive: true });
27034
+ fs74.writeFileSync(out, bytes3);
26914
27035
  written.push(out);
26915
27036
  say(out);
26916
27037
  }
@@ -26923,15 +27044,15 @@ async function templateGet(name, opts, program2) {
26923
27044
  const { template } = await asJson(await ask(`/${at}`, {}, WITHOUT));
26924
27045
  const fetched = [];
26925
27046
  for (const f of template.files) {
26926
- const out = path74.resolve(to, f.path);
26927
- if (!out.startsWith(path74.resolve(to) + path74.sep)) refuse2(T.corrupt, WITHOUT);
27047
+ const out = path76.resolve(to, f.path);
27048
+ if (!out.startsWith(path76.resolve(to) + path76.sep)) refuse2(T.corrupt, WITHOUT);
26928
27049
  const bytes3 = Buffer.from(await (await ask(`/${at}/files/${route(f.path)}`, {}, WITHOUT)).arrayBuffer());
26929
27050
  if (bytes3.byteLength !== f.size || createHash4("sha256").update(bytes3).digest("hex") !== f.sha256) {
26930
27051
  refuse2(T.corrupt, WITHOUT);
26931
27052
  }
26932
27053
  fetched.push({ out, bytes: bytes3 });
26933
27054
  }
26934
- const taken = fetched.filter((f) => fs73.existsSync(f.out)).map((f) => path74.relative(to, f.out));
27055
+ const taken = fetched.filter((f) => fs74.existsSync(f.out)).map((f) => path76.relative(to, f.out));
26935
27056
  if (taken.length > 0) {
26936
27057
  refuse2({
26937
27058
  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`,
@@ -26939,8 +27060,8 @@ async function templateGet(name, opts, program2) {
26939
27060
  });
26940
27061
  }
26941
27062
  for (const f of fetched) {
26942
- fs73.mkdirSync(path74.dirname(f.out), { recursive: true });
26943
- fs73.writeFileSync(f.out, f.bytes);
27063
+ fs74.mkdirSync(path76.dirname(f.out), { recursive: true });
27064
+ fs74.writeFileSync(f.out, f.bytes);
26944
27065
  }
26945
27066
  say(`\u5DF2\u53D6\u56DE ${name}\uFF1A${fetched.length} \u4E2A\u6587\u4EF6\uFF0C\u4F4D\u4E8E ${to}
26946
27067
  Fetched ${name}: ${fetched.length} files into ${to}`);
@@ -26958,25 +27079,25 @@ async function templateSource(name, opts) {
26958
27079
  say(`evidence: ${e.path}`);
26959
27080
  continue;
26960
27081
  }
26961
- const out = path74.join(opts.to, `${name}-${path74.basename(e.path)}`);
26962
- fs73.mkdirSync(opts.to, { recursive: true });
26963
- fs73.writeFileSync(out, Buffer.from(await (await ask(`/${at}/evidence/${route(e.path)}`)).arrayBuffer()));
27082
+ const out = path76.join(opts.to, `${name}-${path76.basename(e.path)}`);
27083
+ fs74.mkdirSync(opts.to, { recursive: true });
27084
+ fs74.writeFileSync(out, Buffer.from(await (await ask(`/${at}/evidence/${route(e.path)}`)).arrayBuffer()));
26964
27085
  written.push(out);
26965
27086
  say(out);
26966
27087
  }
26967
27088
  return { name, source, evidence: written.length > 0 ? written : evidence.map((e) => e.path) };
26968
27089
  }
26969
27090
  async function templatePublish(dir, opts) {
26970
- const root = path74.resolve(dir);
26971
- const manifest = path74.join(root, "template.md");
26972
- 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.");
26973
- const meta = readTemplateMeta(fs73.readFileSync(manifest, "utf8"));
27091
+ const root = path76.resolve(dir);
27092
+ const manifest = path76.join(root, "template.md");
27093
+ 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.");
27094
+ const meta = readTemplateMeta(fs74.readFileSync(manifest, "utf8"));
26974
27095
  const files2 = walk2(root);
26975
- const total = files2.reduce((sum, f) => sum + fs73.statSync(path74.join(root, f)).size, 0);
27096
+ const total = files2.reduce((sum, f) => sum + fs74.statSync(path76.join(root, f)).size, 0);
26976
27097
  if (total > MAX_BYTES3) invalid("\u6A21\u677F\u6587\u4EF6\u5408\u8BA1\u8D85\u8FC7 50 MB\u3002", "the template\u2019s files exceed 50 MB.");
26977
27098
  for (const extra of [...opts.preview, ...opts.evidence]) {
26978
- if (!fs73.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
26979
- if (path74.resolve(extra).startsWith(root + path74.sep)) {
27099
+ if (!fs74.existsSync(extra)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${extra}\u3002`, `${extra} does not exist.`);
27100
+ if (path76.resolve(extra).startsWith(root + path76.sep)) {
26980
27101
  invalid(
26981
27102
  `${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`,
26982
27103
  `${extra} is inside the template folder; keep previews and evidence outside it.`
@@ -26988,10 +27109,10 @@ async function templatePublish(dir, opts) {
26988
27109
  }
26989
27110
  const form = new FormData();
26990
27111
  form.set("meta", JSON.stringify({ ...meta, replace: !!opts.replace }));
26991
- const add = (kind, name, file) => form.append(`${kind}:${name}`, new Blob([fs73.readFileSync(file)]), path74.basename(name));
26992
- for (const f of files2) add("files", f, path74.join(root, f));
26993
- for (const f of opts.preview) add("previews", path74.basename(f), f);
26994
- for (const f of opts.evidence) add("evidence", path74.basename(f), f);
27112
+ const add = (kind, name, file) => form.append(`${kind}:${name}`, new Blob([fs74.readFileSync(file)]), path76.basename(name));
27113
+ for (const f of files2) add("files", f, path76.join(root, f));
27114
+ for (const f of opts.preview) add("previews", path76.basename(f), f);
27115
+ for (const f of opts.evidence) add("evidence", path76.basename(f), f);
26995
27116
  const done2 = await asJson(await ask("", { method: "POST", body: form }));
26996
27117
  say(
26997
27118
  done2.replaced ? `\u5DF2\u66FF\u6362 ${done2.name}\uFF1A${files2.length} \u4E2A\u6587\u4EF6\u3002
@@ -27007,11 +27128,11 @@ Deleted ${name} from the catalog.`);
27007
27128
  return { name, deleted: true };
27008
27129
  }
27009
27130
  async function templateShowcase(name, dir) {
27010
- const file = path74.join(dir, "showcase.json");
27011
- if (!fs73.existsSync(file)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
27131
+ const file = path76.join(dir, "showcase.json");
27132
+ if (!fs74.existsSync(file)) invalid(`${dir} \u4E2D\u7F3A\u5C11 showcase.json\u3002`, `showcase.json is missing from ${dir}.`);
27012
27133
  let meta;
27013
27134
  try {
27014
- meta = JSON.parse(fs73.readFileSync(file, "utf8"));
27135
+ meta = JSON.parse(fs74.readFileSync(file, "utf8"));
27015
27136
  } catch {
27016
27137
  return invalid("showcase.json \u4E0D\u662F\u6709\u6548\u7684 JSON\u3002", "showcase.json is not valid JSON.");
27017
27138
  }
@@ -27023,9 +27144,9 @@ async function templateShowcase(name, dir) {
27023
27144
  const form = new FormData();
27024
27145
  form.set("meta", JSON.stringify(meta));
27025
27146
  for (const p of new Set(named2)) {
27026
- const at = path74.join(dir, p);
27027
- if (!fs73.existsSync(at)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
27028
- form.append(`media:${p}`, new Blob([fs73.readFileSync(at)]), p);
27147
+ const at = path76.join(dir, p);
27148
+ if (!fs74.existsSync(at)) invalid(`\u627E\u4E0D\u5230\u6587\u4EF6 ${at}\u3002`, `${at} does not exist.`);
27149
+ form.append(`media:${p}`, new Blob([fs74.readFileSync(at)]), p);
27029
27150
  }
27030
27151
  const done2 = await asJson(await ask(`/${encodeURIComponent(name)}/showcase`, { method: "PUT", body: form }));
27031
27152
  say(`\u5DF2\u66F4\u65B0 ${name} \u7684\u5C55\u793A\u8D44\u6599\uFF1A${done2.files} \u4E2A\u6587\u4EF6\u3002
@@ -27034,7 +27155,7 @@ Updated ${name}'s showcase: ${done2.files} files.`);
27034
27155
  }
27035
27156
  function walk2(root, sub = "") {
27036
27157
  const out = [];
27037
- for (const entry of fs73.readdirSync(path74.join(root, sub), { withFileTypes: true })) {
27158
+ for (const entry of fs74.readdirSync(path76.join(root, sub), { withFileTypes: true })) {
27038
27159
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
27039
27160
  const rel2 = sub ? `${sub}/${entry.name}` : entry.name;
27040
27161
  if (entry.isDirectory()) out.push(...walk2(root, rel2));
@@ -27319,7 +27440,7 @@ init_opencode();
27319
27440
  init_locate();
27320
27441
  init_store();
27321
27442
  import { spawnSync as spawnSync5 } from "node:child_process";
27322
- import path80 from "node:path";
27443
+ import path82 from "node:path";
27323
27444
  var AGENTS2 = {
27324
27445
  claude: "claude-code",
27325
27446
  codex: "codex",
@@ -27334,10 +27455,10 @@ var AGENTS2 = {
27334
27455
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun", "deno"]);
27335
27456
  function agentOf2(args) {
27336
27457
  const words = args.trim().split(/\s+/);
27337
- const first = path80.basename(words[0] ?? "");
27458
+ const first = path82.basename(words[0] ?? "");
27338
27459
  const script = RUNTIMES.has(first) ? words[1] ?? "" : words[0] ?? "";
27339
27460
  if (script.includes("/@anthropic-ai/claude-code/")) return "claude-code";
27340
- return AGENTS2[path80.basename(script).replace(/\.(m?js|cjs|exe)$/, "")];
27461
+ return AGENTS2[path82.basename(script).replace(/\.(m?js|cjs|exe)$/, "")];
27341
27462
  }
27342
27463
  function processChain() {
27343
27464
  if (process.platform === "win32") return [];
@@ -27401,8 +27522,8 @@ init_tasks();
27401
27522
  init_read();
27402
27523
  init_rules();
27403
27524
  init_board();
27404
- import fs80 from "node:fs";
27405
- import path81 from "node:path";
27525
+ import fs81 from "node:fs";
27526
+ import path83 from "node:path";
27406
27527
  var FOLLOW_MS = 400;
27407
27528
  async function cmdStartRun(action, args, opts, program2 = "akb") {
27408
27529
  const { req, follow: follow2, print } = readRequest(action, args, opts);
@@ -27692,7 +27813,7 @@ async function cmdSubStart(words, opts) {
27692
27813
  let prompt = words.join(" ");
27693
27814
  if (opts.file) {
27694
27815
  try {
27695
- prompt = fs80.readFileSync(path81.resolve(opts.file), "utf8");
27816
+ prompt = fs81.readFileSync(path83.resolve(opts.file), "utf8");
27696
27817
  } catch {
27697
27818
  die(`--file: cannot read ${opts.file}`, { kind: "run-refused" });
27698
27819
  }
@@ -27983,7 +28104,7 @@ async function cmdWatch(sessionId) {
27983
28104
  // src/commands/triage.ts
27984
28105
  init_scheduled();
27985
28106
  init_workflows();
27986
- import fs82 from "node:fs";
28107
+ import fs83 from "node:fs";
27987
28108
 
27988
28109
  // src/lib/signals/index.ts
27989
28110
  init_cards();
@@ -27993,16 +28114,16 @@ init_yaml();
27993
28114
  // src/lib/signals/config.ts
27994
28115
  init_settings2();
27995
28116
  init_paths();
27996
- import fs81 from "node:fs";
27997
- import path82 from "node:path";
28117
+ import fs82 from "node:fs";
28118
+ import path84 from "node:path";
27998
28119
  var TOKEN_KEY = "TRIAGE_ENDPOINT_TOKEN";
27999
28120
  var ENDPOINT_SETTING = "Triage endpoint";
28000
28121
  var LINE2 = /^- \*\*Triage endpoint\*\*\s*[—-]\s*(.+)$/m;
28001
- var boardRel3 = (file) => rel(file).split(path82.sep).join("/");
28122
+ var boardRel3 = (file) => rel(file).split(path84.sep).join("/");
28002
28123
  function signalEndpoint() {
28003
28124
  let text5;
28004
28125
  try {
28005
- text5 = fs81.readFileSync(CONFIG, "utf8");
28126
+ text5 = fs82.readFileSync(CONFIG, "utf8");
28006
28127
  } catch {
28007
28128
  return "";
28008
28129
  }
@@ -28178,7 +28299,7 @@ async function cmdTriageAdd(opts) {
28178
28299
  let body = opts.text;
28179
28300
  if (opts.file !== void 0) {
28180
28301
  try {
28181
- body = fs82.readFileSync(opts.file, "utf8");
28302
+ body = fs83.readFileSync(opts.file, "utf8");
28182
28303
  } catch {
28183
28304
  die(`can't read ${opts.file} \u2014 write the item to a file, then pass its path`, { kind: "needs-input" });
28184
28305
  }
@@ -28742,8 +28863,8 @@ function declareAgent(program2, cli) {
28742
28863
  }
28743
28864
 
28744
28865
  // src/lib/cli/setup.ts
28745
- import fs84 from "node:fs";
28746
- import path84 from "node:path";
28866
+ import fs85 from "node:fs";
28867
+ import path86 from "node:path";
28747
28868
  import { fileURLToPath as fileURLToPath2 } from "node:url";
28748
28869
 
28749
28870
  // src/commands/update.ts
@@ -28757,8 +28878,8 @@ init_paths();
28757
28878
  init_memory();
28758
28879
  init_yaml2();
28759
28880
  init_version();
28760
- import fs83 from "node:fs";
28761
- import path83 from "node:path";
28881
+ import fs84 from "node:fs";
28882
+ import path85 from "node:path";
28762
28883
  import { spawnSync as spawnSync6 } from "node:child_process";
28763
28884
  var NAME = "wildcrane";
28764
28885
  var REPO = "https://github.com/ai4kanban/ai4kanban";
@@ -28780,10 +28901,10 @@ var Report = class {
28780
28901
  for (const line of this.notes) say(` ! ${line}`);
28781
28902
  }
28782
28903
  };
28783
- var read3 = (file) => fs83.existsSync(file) ? fs83.readFileSync(file, "utf8") : null;
28904
+ var read3 = (file) => fs84.existsSync(file) ? fs84.readFileSync(file, "utf8") : null;
28784
28905
  function statOf(p) {
28785
28906
  try {
28786
- return fs83.lstatSync(p);
28907
+ return fs84.lstatSync(p);
28787
28908
  } catch {
28788
28909
  return null;
28789
28910
  }
@@ -28808,10 +28929,10 @@ async function cmdUpdate2(ctx) {
28808
28929
  return { updated: ctx.dir, from, to: SKILL_VERSION };
28809
28930
  }
28810
28931
  async function repairBoard(root, report3, named2) {
28811
- const legacy = path83.join(root, "docs", "kanban");
28812
- const kept2 = path83.join(root, ".akb", "kanban");
28813
- const board2 = named2 ?? (fs83.existsSync(legacy) ? legacy : kept2);
28814
- if (!fs83.existsSync(board2)) {
28932
+ const legacy = path85.join(root, "docs", "kanban");
28933
+ const kept2 = path85.join(root, ".akb", "kanban");
28934
+ const board2 = named2 ?? (fs84.existsSync(legacy) ? legacy : kept2);
28935
+ if (!fs84.existsSync(board2)) {
28815
28936
  report3.notes.push("\u672A\u627E\u5230\u770B\u677F\uFF0C\u8BF7\u901A\u8FC7\u63D2\u4EF6\u8FDE\u63A5\u4E91\u7AEF\u9879\u76EE\u3002");
28816
28937
  return false;
28817
28938
  }
@@ -28842,20 +28963,20 @@ function moveRuntimes(root, board2, report3) {
28842
28963
  }
28843
28964
  }
28844
28965
  function moveLegacyMemory(board2, report3) {
28845
- const memory = path83.join(board2, "memory");
28966
+ const memory = path85.join(board2, "memory");
28846
28967
  const moved = [];
28847
28968
  for (const name of MEMORY_FILES) {
28848
- const from = path83.join(board2, name);
28969
+ const from = path85.join(board2, name);
28849
28970
  const st = statOf(from);
28850
28971
  if (!st || !st.isFile()) continue;
28851
- fs83.mkdirSync(memory, { recursive: true });
28852
- const to = path83.join(memory, name);
28972
+ fs84.mkdirSync(memory, { recursive: true });
28973
+ const to = path85.join(memory, name);
28853
28974
  const there = read3(to);
28854
28975
  if (there === null) {
28855
- fs83.renameSync(from, to);
28976
+ fs84.renameSync(from, to);
28856
28977
  moved.push(name);
28857
28978
  } else if (there === read3(from)) {
28858
- fs83.rmSync(from);
28979
+ fs84.rmSync(from);
28859
28980
  moved.push(name);
28860
28981
  } else {
28861
28982
  report3.notes.push(`both docs/kanban/${name} and docs/kanban/memory/${name} exist and differ \u2014 merge them by hand`);
@@ -28864,23 +28985,23 @@ function moveLegacyMemory(board2, report3) {
28864
28985
  if (moved.length) report3.did.push(`moved the memory set into docs/kanban/memory/: ${moved.join(", ")}`);
28865
28986
  }
28866
28987
  function dropRecordFile(board2) {
28867
- const file = path83.join(board2, "record.csv");
28868
- if (!fs83.existsSync(file)) return null;
28869
- fs83.rmSync(file);
28988
+ const file = path85.join(board2, "record.csv");
28989
+ if (!fs84.existsSync(file)) return null;
28990
+ fs84.rmSync(file);
28870
28991
  return "removed docs/kanban/record.csv (the planning scores it fed are gone)";
28871
28992
  }
28872
28993
  function dropModuleGoals(board2, report3) {
28873
- const memory = path83.join(board2, "memory");
28874
- if (!fs83.existsSync(memory)) return;
28875
- const root = read3(path83.join(memory, "goal.md"));
28994
+ const memory = path85.join(board2, "memory");
28995
+ if (!fs84.existsSync(memory)) return;
28996
+ const root = read3(path85.join(memory, "goal.md"));
28876
28997
  let dropped = 0;
28877
- for (const entry of fs83.readdirSync(memory, { withFileTypes: true })) {
28998
+ for (const entry of fs84.readdirSync(memory, { withFileTypes: true })) {
28878
28999
  if (!entry.isDirectory()) continue;
28879
- const file = path83.join(memory, entry.name, "goal.md");
29000
+ const file = path85.join(memory, entry.name, "goal.md");
28880
29001
  const text5 = read3(file);
28881
29002
  if (text5 === null) continue;
28882
29003
  if (text5 === root || text5.includes(UNFILLED) || !goalWords(text5)) {
28883
- fs83.rmSync(file);
29004
+ fs84.rmSync(file);
28884
29005
  dropped++;
28885
29006
  } else {
28886
29007
  report3.notes.push(
@@ -28902,10 +29023,10 @@ var PLAN_LEADS = {
28902
29023
  var GONE_LEADS = ["software-planner", "planner"];
28903
29024
  function planLeads(board2) {
28904
29025
  const leads = { ...PLAN_LEADS };
28905
- const root = path83.join(board2, "workflows");
28906
- for (const entry of fs83.existsSync(root) ? fs83.readdirSync(root, { withFileTypes: true }) : []) {
29026
+ const root = path85.join(board2, "workflows");
29027
+ for (const entry of fs84.existsSync(root) ? fs84.readdirSync(root, { withFileTypes: true }) : []) {
28907
29028
  if (!entry.isDirectory()) continue;
28908
- const meta = splitFrontmatter(read3(path83.join(root, entry.name, "WORKFLOW.md")) ?? "").meta;
29029
+ const meta = splitFrontmatter(read3(path85.join(root, entry.name, "WORKFLOW.md")) ?? "").meta;
28909
29030
  const stages = meta === null ? void 0 : parseYamlBlock(meta).stages;
28910
29031
  const plan = stages && typeof stages === "object" && !Array.isArray(stages) ? stages.plan : void 0;
28911
29032
  const lead = plan && typeof plan === "object" && !Array.isArray(plan) && typeof plan.lead === "string" ? plan.lead.trim() : "";
@@ -28914,30 +29035,30 @@ function planLeads(board2) {
28914
29035
  return leads;
28915
29036
  }
28916
29037
  function movePlanRules(board2, report3) {
28917
- const rules = path83.join(board2, "rules");
29038
+ const rules = path85.join(board2, "rules");
28918
29039
  const moved = [];
28919
29040
  for (const [id, leads] of Object.entries(planLeads(board2))) {
28920
29041
  for (const lead of leads) {
28921
- const from = path83.join(rules, `${lead}.md`);
29042
+ const from = path85.join(rules, `${lead}.md`);
28922
29043
  const rule = read3(from)?.trim();
28923
29044
  if (!rule) continue;
28924
- const to = path83.join(rules, "workflows", `${id}.md`);
29045
+ const to = path85.join(rules, "workflows", `${id}.md`);
28925
29046
  const there = read3(to)?.trim() ?? "";
28926
29047
  if (!there.includes(rule)) {
28927
- fs83.mkdirSync(path83.dirname(to), { recursive: true });
28928
- fs83.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
29048
+ fs84.mkdirSync(path85.dirname(to), { recursive: true });
29049
+ fs84.writeFileSync(to, `${[there, rule].filter(Boolean).join("\n\n")}
28929
29050
  `);
28930
29051
  moved.push(`${lead} \u2192 ${id}`);
28931
29052
  }
28932
29053
  }
28933
29054
  }
28934
- for (const lead of GONE_LEADS) fs83.rmSync(path83.join(rules, `${lead}.md`), { force: true });
29055
+ for (const lead of GONE_LEADS) fs84.rmSync(path85.join(rules, `${lead}.md`), { force: true });
28935
29056
  if (moved.length) report3.did.push(`made each plan agent's rule its workflow's card rule (docs/kanban/rules/workflows/): ${moved.join(", ")}`);
28936
29057
  }
28937
29058
  function noteOldWorkflows(board2, report3) {
28938
29059
  const old = (dir, file, keys) => {
28939
- const root = path83.join(board2, dir);
28940
- return (fs83.existsSync(root) ? fs83.readdirSync(root, { withFileTypes: true }) : []).filter((e) => e.isDirectory() && keys.test(splitFrontmatter(read3(path83.join(root, e.name, file)) ?? "").meta ?? "")).map((e) => `docs/kanban/${dir}/${e.name}/${file}`);
29060
+ const root = path85.join(board2, dir);
29061
+ return (fs84.existsSync(root) ? fs84.readdirSync(root, { withFileTypes: true }) : []).filter((e) => e.isDirectory() && keys.test(splitFrontmatter(read3(path85.join(root, e.name, file)) ?? "").meta ?? "")).map((e) => `docs/kanban/${dir}/${e.name}/${file}`);
28941
29062
  };
28942
29063
  const files2 = [...old("workflows", "WORKFLOW.md", /^(stages|delivers):/m), ...old("agents", "AGENT.md", /^\s+(hook|lead):/m)];
28943
29064
  if (files2.length) {
@@ -28947,7 +29068,7 @@ function noteOldWorkflows(board2, report3) {
28947
29068
  }
28948
29069
  }
28949
29070
  function checkConfig(board2, report3) {
28950
- const current = read3(path83.join(board2, "config.md"));
29071
+ const current = read3(path85.join(board2, "config.md"));
28951
29072
  if (!current) return;
28952
29073
  const added = missingConfigKeys(current);
28953
29074
  if (added.length) {
@@ -28957,7 +29078,7 @@ function checkConfig(board2, report3) {
28957
29078
  }
28958
29079
  }
28959
29080
  function checkModules(board2, report3) {
28960
- const map2 = read3(path83.join(board2, "modules.md"));
29081
+ const map2 = read3(path85.join(board2, "modules.md"));
28961
29082
  if (map2 && map2.includes(UNFILLED)) {
28962
29083
  report3.notes.push(
28963
29084
  "docs/kanban/modules.md is still blank \u2014 write it from the repo (`akb guide module-map`)"
@@ -29011,14 +29132,14 @@ function declareSetup(program2, cli) {
29011
29132
  program2.version(SKILL_VERSION, "-v, --version", "print this version").addHelpText("beforeAll", spelled(cli.program));
29012
29133
  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");
29013
29134
  const where = (cmd) => {
29014
- const dir = path84.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
29015
- if (!fs84.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
29135
+ const dir = path86.resolve(String(cmd.optsWithGlobals().dir ?? cli.cwd));
29136
+ if (!fs85.existsSync(dir)) throw new BoardError(`no such folder: ${dir}`, { kind: "no-such-folder", dir });
29016
29137
  return dir;
29017
29138
  };
29018
29139
  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() {
29019
29140
  const dir = where(this);
29020
29141
  const named2 = this.optsWithGlobals().board ?? process.env.AI4KANBAN_BOARD?.trim();
29021
- const board2 = named2 ? path84.resolve(cli.cwd, named2) : null;
29142
+ const board2 = named2 ? path86.resolve(cli.cwd, named2) : null;
29022
29143
  await runAction(ctxOf(this, cli.program), {}, () => cmdUpdate2({ dir, program: cli.program, board: board2 }));
29023
29144
  });
29024
29145
  program2.command("__rules", { hidden: true }).action(function() {
@@ -29062,7 +29183,7 @@ function invokedDirectly() {
29062
29183
  const entry = process.argv[1];
29063
29184
  if (!entry) return false;
29064
29185
  try {
29065
- return fs85.realpathSync(entry) === fs85.realpathSync(SELF2);
29186
+ return fs86.realpathSync(entry) === fs86.realpathSync(SELF2);
29066
29187
  } catch {
29067
29188
  return false;
29068
29189
  }