kaizen-agent 1.63.0 → 1.64.1

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 (77) hide show
  1. package/README.md +10 -10
  2. package/agents/kaizen-planner.md +2 -2
  3. package/cli/backlog.test.ts +1 -1
  4. package/cli/board.test.ts +24 -24
  5. package/cli/dashboard.ts +15 -15
  6. package/cli/handoff.test.ts +133 -0
  7. package/cli/handoff.ts +122 -0
  8. package/cli/install.ts +31 -5
  9. package/cli/notes.test.ts +3 -3
  10. package/cli/notes.ts +1 -1
  11. package/cli/pty.ts +16 -2
  12. package/cli/resources.test.ts +50 -0
  13. package/cli/resources.ts +113 -0
  14. package/cli/restart.test.ts +28 -1
  15. package/cli/settings.ts +8 -5
  16. package/cli/sources.test.ts +32 -32
  17. package/cli/sources.ts +15 -15
  18. package/cli/state.test.ts +74 -51
  19. package/cli/state.ts +77 -49
  20. package/cli/usage.test.ts +11 -0
  21. package/cli/web.ts +139 -38
  22. package/cli/workers.ts +11 -4
  23. package/cli/worktree.test.ts +174 -1
  24. package/cli/worktree.ts +190 -35
  25. package/commands/kaizen-discover.md +1 -1
  26. package/package.json +1 -1
  27. package/skills/kaizen/README.md +2 -2
  28. package/skills/kaizen/SKILL.md +2 -2
  29. package/skills/kaizen/config.default.yml +32 -22
  30. package/skills/kaizen/discover.md +8 -8
  31. package/skills/kaizen/gather.md +2 -2
  32. package/skills/kaizen/settings.md +3 -0
  33. package/skills/kaizen/spec-build.md +13 -0
  34. package/skills/kaizen/spec-main.md +13 -0
  35. package/skills/kaizen/spec-plan.md +1 -1
  36. package/skills/kaizen/spec.md +1 -1
  37. package/skills/kaizen-help/SKILL.md +2 -2
  38. package/web/board/api.ts +10 -10
  39. package/web/board/cards.ts +47 -46
  40. package/web/board/git.ts +4 -4
  41. package/web/board/icebox.ts +14 -14
  42. package/web/board/keys.ts +3 -3
  43. package/web/board/labels.ts +2 -2
  44. package/web/board/live.ts +3 -3
  45. package/web/board/main.ts +1 -1
  46. package/web/board/markdown.ts +1 -1
  47. package/web/board/panel.ts +17 -17
  48. package/web/board/phone.ts +10 -12
  49. package/web/board/projects.ts +6 -6
  50. package/web/board/resources.ts +152 -0
  51. package/web/board/run-view.ts +5 -5
  52. package/web/board/search.ts +11 -11
  53. package/web/board/settings-cleanup.ts +42 -0
  54. package/web/board/settings-pages.ts +1 -1
  55. package/web/board/settings.ts +13 -0
  56. package/web/board/store.ts +1 -1
  57. package/web/board/{ideas.ts → tasks.ts} +22 -22
  58. package/web/board/terms.ts +3 -3
  59. package/web/board/views.ts +23 -12
  60. package/web/board/workspace.ts +9 -7
  61. package/web/board/ws-board-ui.ts +1 -1
  62. package/web/board/ws-board.test.ts +1 -1
  63. package/web/board/ws-board.ts +1 -1
  64. package/web/board/ws-tabs.test.ts +10 -2
  65. package/web/board/ws-tabs.ts +10 -9
  66. package/web/board.html +46 -34
  67. package/web/board.js +107 -97
  68. package/web/notebook.js +22 -22
  69. package/web/notebook.ts +5 -5
  70. package/web/notes-lib.ts +2 -2
  71. package/web/notes.html +12 -11
  72. package/web/term-font.test.ts +22 -0
  73. package/web/term-font.ts +30 -0
  74. package/web/term.js +38 -38
  75. package/web/term.ts +13 -2
  76. package/web/video.html +12 -11
  77. package/web/video.js +48 -48
package/cli/state.ts CHANGED
@@ -628,7 +628,7 @@ export function parseItem(raw: string): Item {
628
628
  // and a severity tag in brackets ("Finding 1 (medium) — …", "(review 2, low)",
629
629
  // "[low] …"). A severity loose in prose ("too low") is not one.
630
630
  const at = /^(.{1,160}?)\s*[:—-]\s*(critical|high|medium|low)\s*[:—-]\s*(.+)$/i.exec(raw);
631
- // Only a real place counts as one (a path, or a line number): an idea's own words
631
+ // Only a real place counts as one (a path, or a line number): a task's own words
632
632
  // before a severity stay its words.
633
633
  if (at && /\/|:\d/.test(at[1]!)) return { severity: at[2]!.toLowerCase(), where: at[1]!.replace(/`/g, "").trim().split("/").pop()!, text: tidy(at[3]!), raw };
634
634
  const num = /^\d+\.\s*(critical|high|medium|low)\s*[:—-]\s*(.+)$/i.exec(raw);
@@ -720,7 +720,7 @@ export type BacklogCard = { state: string; where: string; source: string; n: num
720
720
  const SEVERITY_RANK: Record<string, number> = { critical: 0, high: 1, medium: 2, low: 3 };
721
721
 
722
722
  // The open backlog items of every non-abandoned run and the orphanage, as cards for the
723
- // board's Ideas column: most severe first, then newest run first, then file order. An
723
+ // board's Tasks column: most severe first, then newest run first, then file order. An
724
724
  // item a live run was started from is not shown; an abandoned one gives it back.
725
725
  export function backlogCards(states: string[]): BacklogCard[] {
726
726
  const out: BacklogCard[] = [];
@@ -776,9 +776,15 @@ export function markBacklogDone(state: string) {
776
776
 
777
777
  // ---------------------------------------------------------------- board data
778
778
 
779
+ export type Land = { kind: "conflict" | "check" | "merge"; why: string; paths?: string[]; term?: string; at?: number };
780
+ const readLand = (st: string, id: string): Land | undefined => {
781
+ try { const l = JSON.parse(readFileSync(join(st, "runs", id, "land.json"), "utf8")); return typeof l?.kind === "string" ? l : undefined; } catch { return undefined; }
782
+ };
779
783
  export type Card = {
780
784
  kind: "idea" | "run";
781
785
  id?: string; // runs only: the directory name
786
+ handoff?: string; // runs only: how a handoff ended, when its first agent is gone
787
+ land?: Land; // runs only: what stopped the last land (land.json)
782
788
  stage?: string; // runs only: the stage word
783
789
  iteration?: number; // runs only: the fix round
784
790
  status: string; // what the legend calls this card
@@ -789,8 +795,8 @@ export type Card = {
789
795
  awaiting: string | null;
790
796
  dim: boolean;
791
797
  moved?: number; // runs only: state.json mtime
792
- added?: number; // ideas only: when the inbox line first appeared (ms)
793
- inboxIndex?: number; // ideas only: line in the project's inbox
798
+ added?: number; // tasks only: when the inbox line first appeared (ms)
799
+ inboxIndex?: number; // tasks only: line in the project's inbox
794
800
  title?: string; // runs only: first line of the request
795
801
  archived: boolean; // hidden from the board unless asked for
796
802
  branch?: string; // runs only: the run's own branch while it has a worktree
@@ -804,7 +810,7 @@ export type Card = {
804
810
  };
805
811
 
806
812
  // A `Parent: <run id>` line (or the older `Follow-up of: <run id>`) in a request or
807
- // an idea's notes is what links a card to the run it came from.
813
+ // a task's notes is what links a card to the run it came from.
808
814
  export function parentOf(text?: string) {
809
815
  return /^\s*(?:\[[^\]]*\]\s*)?(?:Parent|Follow-up of):\s*(\S+)/im.exec(text ?? "")?.[1]?.replace(/[.,]$/, "");
810
816
  }
@@ -813,7 +819,7 @@ export function parentOf(text?: string) {
813
819
  // to ask. Anything in flight and older than this is stalled, not running -- the
814
820
  // difference the board exists to show.
815
821
 
816
- // The verbatim request of every run, normalised, so an idea that has become a run
822
+ // The verbatim request of every run, normalised, so a task that has become a run
817
823
  // can be retired from the board.
818
824
  // ponytail: reads each run's 00-request.md on every refresh; fine at tens of runs,
819
825
  // cache by mtime if a project ever has hundreds.
@@ -863,7 +869,7 @@ export function columnOf(stage: string, awaiting: string | null = null) {
863
869
  // `added` is when the line first appeared (ms), kept as a hidden comment on its bullet.
864
870
  export type InboxLine = { status: string; text: string; notes?: string; added?: number };
865
871
 
866
- // Ideas with no run yet. Deliberately not backlog.md, which the spec defines as
872
+ // Tasks with no run yet. Deliberately not backlog.md, which the spec defines as
867
873
  // an orphanage for items rescued from pruned runs, and not a run stub each.
868
874
  export function readInbox(state: string): InboxLine[] {
869
875
  const f = join(state, "inbox.md");
@@ -876,7 +882,7 @@ export function readInbox(state: string): InboxLine[] {
876
882
  out.push(a ? { status: m[1]!, text: m[2]!.slice(0, a.index).trim(), added: +a[1]! } : { status: m[1]!, text: m[2]!.trim() });
877
883
  continue;
878
884
  }
879
- // A bullet typed by hand, without a status, is an open idea.
885
+ // A bullet typed by hand, without a status, is an open task.
880
886
  const b = /^[-*]\s+(?:\[ \]\s+)?(.+)$/.exec(raw);
881
887
  if (b) {
882
888
  out.push({ status: "open", text: b[1]!.trim() });
@@ -897,7 +903,7 @@ export function writeInbox(state: string, lines: InboxLine[]) {
897
903
  // A line already in the file keeps its stamp; a text the file never had is new now.
898
904
  // Lines from before stamps existed stay unstamped rather than looking new.
899
905
  // Stamps queue per text and each is used once: re-adding words the file already
900
- // holds (a done or rejected line, or an open duplicate) is a new idea, not the old
906
+ // holds (a done or rejected line, or an open duplicate) is a new task, not the old
901
907
  // one's stamp, which an older run with those words would retire.
902
908
  const had = new Map<string, (number | undefined)[]>();
903
909
  for (const l of readInbox(state)) had.set(l.text, [...(had.get(l.text) ?? []), l.added]);
@@ -928,7 +934,7 @@ export function requestOf(text: string, notes?: string, state?: string) {
928
934
  return n ? `${text}\n\n${n}` : text;
929
935
  }
930
936
 
931
- // Free text beside a run -- what the user learned after the idea became a run.
937
+ // Free text beside a run -- what the user learned after the task became a run.
932
938
  // Its own file, never state.json: that shape is the resume contract.
933
939
  export function readNotes(state: string, id: string) {
934
940
  try { return readText(join(state, "runs", id, "notes.md")); } catch { return ""; }
@@ -967,7 +973,7 @@ export function formatNote(text: string, at = stamp()) {
967
973
  return `[${at}] ${text.trim().replace(/\n/g, "\n ")}`;
968
974
  }
969
975
 
970
- // Append one entry: to runs/<id>/notes.md for a run, or under the idea's inbox
976
+ // Append one entry: to runs/<id>/notes.md for a run, or under the task's inbox
971
977
  // bullet. Attachments arrive as markdown links already written into text.
972
978
  export function appendNote(state: string, target: { id: string } | { text: string; index?: number }, text: string): string | null {
973
979
  if (!text.trim()) return "empty note";
@@ -978,16 +984,16 @@ export function appendNote(state: string, target: { id: string } | { text: strin
978
984
  }
979
985
  const lines = readInbox(state);
980
986
  const at = target.index === undefined ? lines.findIndex((l) => l.status === "open" && l.text === target.text) : target.index;
981
- if (lines[at]?.status !== "open" || lines[at]?.text !== target.text) return "no such idea";
987
+ if (lines[at]?.status !== "open" || lines[at]?.text !== target.text) return "no such task";
982
988
  const prev = lines[at]!.notes;
983
989
  lines[at] = { ...lines[at]!, notes: (prev ? prev + "\n" : "") + formatNote(text) };
984
990
  writeInbox(state, lines);
985
991
  return null;
986
992
  }
987
993
 
988
- // A card filed by a run: an open idea whose note names the run as its parent. The
994
+ // A card filed by a run: an open task whose note names the run as its parent. The
989
995
  // parent is the one named, else the newest run still in flight. `details` go in the
990
- // idea's notes below the Parent line, so the title stays a title.
996
+ // task's notes below the Parent line, so the title stays a title.
991
997
  export function addCard(state: string, text: string, parent?: string, details?: string): { parent: string } | string {
992
998
  text = text.trim().replace(/\s+/g, " ");
993
999
  if (!text) return "empty card";
@@ -1001,7 +1007,7 @@ export function addCard(state: string, text: string, parent?: string, details?:
1001
1007
  }
1002
1008
 
1003
1009
  // A file beside the notes it belongs to: runs/<id>/attachments/ for a run,
1004
- // <state>/attachments/ for an idea. Returns the path relative to the state dir,
1010
+ // <state>/attachments/ for a task. Returns the path relative to the state dir,
1005
1011
  // which is what the note links and what /file serves.
1006
1012
  // ponytail: no dedupe, no size accounting beyond the request cap in web.ts.
1007
1013
  export function saveAttachment(state: string, id: string | null, name: string, bytes: Uint8Array) {
@@ -1025,7 +1031,7 @@ const NEED: Record<string, string> = {
1025
1031
  };
1026
1032
  export function notice(c: Card): string | null {
1027
1033
  if (c.kind !== "run") return null;
1028
- const what = c.awaiting ? NEED[c.awaiting] ?? `waiting on ${c.awaiting}` : c.status === "done" ? (c.accept === "needs" ? "done, not approved" : "done") : null;
1034
+ const what = c.land ? (c.land.kind === "conflict" ? `conflict: ${c.land.paths?.join(", ") || c.land.why}` : `land failed: ${c.land.why}`) : c.handoff ? `the worktree agent ended (${c.handoff}): tell the first agent, or review it here` : c.awaiting ? NEED[c.awaiting] ?? `waiting on ${c.awaiting}` : c.status === "done" ? (c.accept === "needs" ? "done, not approved" : "done") : null;
1029
1035
  return what && `${c.text} — ${what}\n${c.where}`;
1030
1036
  }
1031
1037
 
@@ -1100,33 +1106,33 @@ export function abandonRun(st: string, id: string, why: string): string | null {
1100
1106
  }
1101
1107
  }
1102
1108
 
1103
- // A run still planning, back to the idea it came from: abandoned and archived (the
1104
- // record stays), and the idea open again. Its fresh stamp is newer than the run's
1109
+ // A run still planning, back to the task it came from: abandoned and archived (the
1110
+ // record stays), and the task open again. Its fresh stamp is newer than the run's
1105
1111
  // request, so the old run no longer retires it.
1106
- export function runToIdea(st: string, id: string): string | null {
1112
+ export function runToTask(st: string, id: string): string | null {
1107
1113
  let stage = "";
1108
1114
  try { stage = JSON.parse(readText(join(st, "runs", id, "state.json"))).stage; } catch {}
1109
- if (stage !== "plan") return "Only a run still in planning goes back to an idea.";
1115
+ if (stage !== "plan") return "Only a run still in planning goes back to a task.";
1110
1116
  let req = "";
1111
1117
  try { req = readText(join(st, "runs", id, "00-request.md")).trim(); } catch {}
1112
1118
  const lines = readInbox(st);
1113
- // The longest started idea the request holds: "test" must not stand in for "test login".
1119
+ // The longest started task the request holds: "test" must not stand in for "test login".
1114
1120
  let at = -1;
1115
1121
  lines.forEach((l, i) => { if (l.status === "started" && normalise(req).includes(normalise(l.text)) && (at < 0 || l.text.length > lines[at]!.text.length)) at = i; });
1116
1122
  const [first = "", ...rest] = req.split("\n");
1117
- const idea: InboxLine = at >= 0
1123
+ const task: InboxLine = at >= 0
1118
1124
  ? { ...lines[at]!, status: "open", added: Date.now() }
1119
1125
  : { status: "open", text: first.replace(/^\/kaizen(?:-\w+)?\s+(?:(?:lite|full|auto|plan)\s+)?/i, "").trim(), notes: rest.join("\n").trim() || undefined, added: Date.now() };
1120
- if (!idea.text) return "That run has no request to make an idea of.";
1121
- const failed = abandonRun(st, id, "Sent back to ideas from the board.");
1126
+ if (!task.text) return "That run has no request to make a task of.";
1127
+ const failed = abandonRun(st, id, "Sent back to tasks from the board.");
1122
1128
  if (failed) return failed;
1123
1129
  setArchived(st, id, true);
1124
1130
  if (at >= 0) lines.splice(at, 1);
1125
- writeInbox(st, [...lines, idea]);
1131
+ writeInbox(st, [...lines, task]);
1126
1132
  return null;
1127
1133
  }
1128
1134
 
1129
- export function replaceIdea(state: string, text: string, next: InboxLine | null, index?: number) {
1135
+ export function replaceTask(state: string, text: string, next: InboxLine | null, index?: number) {
1130
1136
  const lines = readInbox(state);
1131
1137
  const at = index === undefined ? lines.findIndex((l) => (l.status === "open" || l.status === "started") && l.text === text) : index;
1132
1138
  if (!lines[at] || !["open", "started"].includes(lines[at]!.status) || lines[at]!.text !== text) return false;
@@ -1135,24 +1141,24 @@ export function replaceIdea(state: string, text: string, next: InboxLine | null,
1135
1141
  return true;
1136
1142
  }
1137
1143
 
1138
- // An open idea, notes and all, from one project's inbox to another's. Files its notes
1144
+ // An open task, notes and all, from one project's inbox to another's. Files its notes
1139
1145
  // link (attachments/...) are copied along, so the links resolve from the new state dir.
1140
1146
  // Written to the new project first and taken back out if the old one cannot be
1141
1147
  // written, like moveSource: a crash between the two leaves it listed twice, never lost.
1142
- export function moveIdea(from: string, to: string, text: string): string | null {
1148
+ export function moveTask(from: string, to: string, text: string): string | null {
1143
1149
  if (from === to) return "already in that project";
1144
1150
  const src = readInbox(from);
1145
1151
  const at = src.findIndex((l) => l.status === "open" && l.text === text);
1146
- if (at < 0) return "no such idea";
1152
+ if (at < 0) return "no such task";
1147
1153
  const dest = readInbox(to);
1148
- if (dest.some((l) => l.status === "open" && l.text === text)) return "that project already has this idea";
1149
- const idea = src[at]!;
1150
- for (const m of (idea.notes ?? "").matchAll(/\]\((attachments\/[^)\/]+)\)/g)) {
1154
+ if (dest.some((l) => l.status === "open" && l.text === text)) return "that project already has this task";
1155
+ const task = src[at]!;
1156
+ for (const m of (task.notes ?? "").matchAll(/\]\((attachments\/[^)\/]+)\)/g)) {
1151
1157
  if (!existsSync(join(from, m[1]!)) || !statSync(join(from, m[1]!)).isFile()) continue;
1152
1158
  mkdirSync(join(to, "attachments"), { recursive: true });
1153
1159
  copyFileSync(join(from, m[1]!), join(to, m[1]!));
1154
1160
  }
1155
- writeInbox(to, [...dest, idea]);
1161
+ writeInbox(to, [...dest, task]);
1156
1162
  try { writeInbox(from, src.filter((_, i) => i !== at)); }
1157
1163
  catch (e) { writeInbox(to, dest); throw e; }
1158
1164
  return null;
@@ -1201,8 +1207,8 @@ export function requestTitle(text: string) {
1201
1207
  return first.length > 90 ? first.slice(0, 89).trimEnd() + "…" : first;
1202
1208
  }
1203
1209
 
1204
- // Every card on the board, for the state dirs asked for. Retirement of an idea is
1205
- // checked against every known project's runs, not just these: an idea in the global
1210
+ // Every card on the board, for the state dirs asked for. Retirement of a task is
1211
+ // checked against every known project's runs, not just these: a task in the global
1206
1212
  // inbox becomes a run in whichever project the agent was started in.
1207
1213
  // The gate reads a done run's reports on every refresh: kept per run until one of the
1208
1214
  // files it reads changes (stat only), so a project of many done runs costs no reads.
@@ -1234,14 +1240,14 @@ export function boardCards(states: string[], now: number): Card[] {
1234
1240
  if (!bodies.has(f)) { try { bodies.set(f, readText(f)); } catch { bodies.set(f, ""); } }
1235
1241
  return bodies.get(f)!;
1236
1242
  };
1237
- // Each request with when it was written, so a run older than an idea cannot retire it.
1243
+ // Each request with when it was written, so a run older than a task cannot retire it.
1238
1244
  const requests: { at: number; text: string }[] = [];
1239
- // Each request line on its own, quote and list markers stripped: what an idea
1245
+ // Each request line on its own, quote and list markers stripped: what a task
1240
1246
  // nobody launched from the board is matched against.
1241
1247
  const lines: { at: number; text: string }[] = [];
1242
1248
  for (const st of [...states, ...knownProjects().map((d) => join(d, ".kaizen")), join(home, ".kaizen")]
1243
1249
  .filter((d, i, all) => all.indexOf(d) === i && existsSync(join(d, "runs")))) {
1244
- // A run with no state.json yet has no card either: retiring the idea against it
1250
+ // A run with no state.json yet has no card either: retiring the task against it
1245
1251
  // leaves the board showing neither until the agent writes one.
1246
1252
  for (const id of readdirSync(join(st, "runs"))) { const b = body(st, id); if (!b || !existsSync(join(st, "runs", id, "state.json"))) continue;
1247
1253
  let at = 0;
@@ -1250,7 +1256,7 @@ export function boardCards(states: string[], now: number): Card[] {
1250
1256
  for (const l of b.split("\n")) lines.push({ at, text: normalise(l.replace(/^[\s>*"'`-]+|[\s"'`.]+$/g, "")) });
1251
1257
  }
1252
1258
  }
1253
- // A launched idea whose run reworded the request: the board's own launch record,
1259
+ // A launched task whose run reworded the request: the board's own launch record,
1254
1260
  // owned by a run (session id in its state.json, see ownerOf), retires it all the same.
1255
1261
  const indexes = new Map<string, RunIndex>(), indexOf = (st: string) => indexes.get(st) ?? indexes.set(st, runIndex(st)).get(st)!;
1256
1262
  const launchedInto = (st: string, t: string) => readSessions(st).some((s) => !s.run && normalise(s.text.replace(/^(lite|full|auto|plan)\s+/i, "")) === t.replace(/^(lite|full|auto|plan)\s+/i, "") && ownerOf(st, s, indexOf(st)) !== null);
@@ -1260,16 +1266,16 @@ export function boardCards(states: string[], now: number): Card[] {
1260
1266
  for (const [inboxIndex, it] of readInbox(st).entries()) {
1261
1267
  if (it.status !== "open" && it.status !== "started" && it.status !== "archived") continue;
1262
1268
  // Retired once any run's request contains this text -- whoever started it.
1263
- // Checking `started` items only would leave every idea acted on outside the
1269
+ // Checking `started` items only would leave every task acted on outside the
1264
1270
  // board sitting in IDEA forever, and typing `/kaizen ...` in a terminal is
1265
1271
  // the common way a run begins.
1266
- // An idea that was launched only has to appear somewhere in a request. One
1272
+ // A task that was launched only has to appear somewhere in a request. One
1267
1273
  // that was not must be what a request line says (after any `/kaizen lite`
1268
- // prefix): a short idea like "test" is a substring of half the requests
1274
+ // prefix): a short task like "test" is a substring of half the requests
1269
1275
  // ever written, and would vanish the moment it was added.
1270
1276
  const t = normalise(it.text);
1271
- // A run written before the idea existed is not this idea's run: an old request
1272
- // titled "fix this bugs" must not swallow a new idea with the same words.
1277
+ // A run written before the task existed is not this task's run: an old request
1278
+ // titled "fix this bugs" must not swallow a new task with the same words.
1273
1279
  // ponytail: 2s slack for coarse filesystem clocks.
1274
1280
  const after = (r: { at: number }) => !it.added || r.at >= it.added - 2000;
1275
1281
  if (it.status === "started" ? requests.some((r) => after(r) && r.text.includes(t)) || launchedInto(st, t) : lines.some((l) => after(l) && (l.text === t || l.text.endsWith(" " + t)))) continue;
@@ -1295,6 +1301,7 @@ export function boardCards(states: string[], now: number): Card[] {
1295
1301
  notes: readNotes(st, r.id) || undefined,
1296
1302
  parent: parentOf(body(st, r.id)),
1297
1303
  ...(r.healed ? { healed: true } : {}),
1304
+ ...((land) => land ? { land } : {})(readLand(st, r.id)),
1298
1305
  ...(r.stage === "done" ? accepted(st, r.id) : {}),
1299
1306
  });
1300
1307
  }
@@ -1490,9 +1497,9 @@ export function runIndex(st: string): RunIndex {
1490
1497
  return { bySession, requests };
1491
1498
  }
1492
1499
 
1493
- // Whose session a record is. A decision's launch names its run. An idea's launch came
1500
+ // Whose session a record is. A decision's launch names its run. A task's launch came
1494
1501
  // before its run existed, so it belongs to the first run created after it whose
1495
- // request holds the idea's text: one run per record, never every run that mentions it.
1502
+ // request holds the task's text: one run per record, never every run that mentions it.
1496
1503
  // A caller asking about many sessions passes runIndex(st) once: built per call, it
1497
1504
  // reads every run's state.json and request each time.
1498
1505
  export function ownerOf(st: string, s: Session, idx?: RunIndex): string | null {
@@ -1630,6 +1637,27 @@ const openSessions = (st: string) => readSessions(st).filter((s) => {
1630
1637
  return true;
1631
1638
  });
1632
1639
 
1640
+ // Launch records nothing can use again, oldest first; with `apply`, deleted with their
1641
+ // PID and link files. Past a week and with no live agent, a record goes when no run
1642
+ // owns it, its run is abandoned, or its run no longer exists. A done run's records stay:
1643
+ // a follow-up resumes its conversation from them. An unreadable state.json keeps them too.
1644
+ const SESSION_KEEP_MS = 7 * 24 * 3600_000;
1645
+ export function pruneSessions(state: string, apply = false, now = Date.now()): { key: string; reason: "abandoned" | "unowned" | "gone" }[] {
1646
+ const idx = runIndex(state), live = new Set(openSessions(state).map((s) => s.key));
1647
+ const why = (run: string | null) => {
1648
+ if (!run) return "unowned" as const;
1649
+ const dir = join(state, "runs", run);
1650
+ if (!existsSync(dir)) return "gone" as const;
1651
+ try { return JSON.parse(readText(join(dir, "state.json"))).stage === "abandoned" ? "abandoned" as const : null; } catch { return null; }
1652
+ };
1653
+ const gone = readSessions(state).filter((s) => now - s.started > SESSION_KEEP_MS && !live.has(s.key)).flatMap((s) => {
1654
+ const reason = why(ownerOf(state, s, idx));
1655
+ return reason ? [{ key: s.key, reason }] : [];
1656
+ });
1657
+ if (apply) for (const { key } of gone) for (const ext of [".json", ".pid", ".run"]) rmSync(join(sessionsDir(state), key + ext), { force: true });
1658
+ return gone;
1659
+ }
1660
+
1633
1661
  // Close every session kaizen opened for a run, those launched before `before` only,
1634
1662
  // so a decision's own successor is never caught. The record stays: it holds the
1635
1663
  // conversation id the next decision resumes. Never throws.
@@ -1738,7 +1766,7 @@ export function trustFolder(dir: string, cfg = join(process.env.CLAUDE_CONFIG_DI
1738
1766
  } catch { /* Claude asks as before */ }
1739
1767
  }
1740
1768
 
1741
- // run: the run a decision is for. Without it, an idea starting a new run.
1769
+ // run: the run a decision is for. Without it, a task starting a new run.
1742
1770
  // pick: the tool, model and yolo chosen for a new run; a decision takes the run's own
1743
1771
  // tool and model, and stays in Yolo when the run was started in it. card: run it inside the board (agent.launch: card),
1744
1772
  // where a pseudo-terminal exists; onChange is told when that agent ends.
@@ -1749,7 +1777,7 @@ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_
1749
1777
  // written only where that folder has a .kaizen (a project place does; the library usually not).
1750
1778
  export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; account?: string; model?: string; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
1751
1779
  const projectDir = pick.cwd ?? projectOf(from);
1752
- // The run will be born here; the board must know the dir or the idea never retires.
1780
+ // The run will be born here; the board must know the dir or the task never retires.
1753
1781
  if (!pick.cwd) remember(projectDir);
1754
1782
  const own = run && !pick.agent ? runAgent(join(projectDir, ".kaizen"), run) : null;
1755
1783
  const agent = detectDefaultAgent(projectDir, pick.agent ?? own?.cmd);
@@ -1780,7 +1808,7 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
1780
1808
  // Settings' bypass takes the same road, so the session record and the card's mark follow.
1781
1809
  const yolo = (wasYolo || (!!pick.yolo && agent.cmd === pick.agent) || prefersBypass(agent.cmd, prefs)) && !!YOLO_FLAGS[agent.cmd];
1782
1810
  const flags = [...agentFlags(projectDir, agent.cmd, undefined, model), ...(yolo ? YOLO_FLAGS[agent.cmd] : []), ...argsOf(agent.cmd, prefs)];
1783
- // The idea as its run's request will hold it: without the runner word in front.
1811
+ // The task as its run's request will hold it: without the runner word in front.
1784
1812
  // Session lookups read the tool's folder from the environment; for this launch it's the account's.
1785
1813
  const prior = acct.envVar ? process.env[acct.envVar] : undefined;
1786
1814
  if (acct.envVar) process.env[acct.envVar] = acct.dir;
package/cli/usage.test.ts CHANGED
@@ -82,6 +82,17 @@ test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown proje
82
82
  expect((await post({ dir: st }, "http://localhost:3000")).status).toBe(403);
83
83
  // A simple (no-preflight) POST body type.
84
84
  expect((await post({ dir: st }, at, "text/plain")).status).toBe(415);
85
+ const kill = (body: object, origin?: string, type = "application/json") => fetch(at + "/pty/kill", { method: "POST", headers: { "content-type": type, ...(origin ? { origin } : {}) }, body: JSON.stringify(body) });
86
+ expect((await kill({ key: "x" }, "https://evil.example")).status).toBe(403);
87
+ expect((await kill({ key: "x" }, at, "text/plain")).status).toBe(415);
88
+ expect((await kill({ key: "no-such" }, at)).status).toBe(404);
89
+ expect((await kill({ key: "../x" }, at)).status).toBe(404);
90
+ const res = await (await fetch(at + "/resources")).json();
91
+ expect(res.system.total).toBeGreaterThan(0);
92
+ expect(res.kaizen).toBeGreaterThan(0);
93
+ const disk = await fetch(at + "/resources/storage");
94
+ expect(disk.status).toBe(200);
95
+ expect(typeof (await disk.json()).scanning).toBe("boolean");
85
96
  expect((await post({ dir: join(root, "elsewhere", ".kaizen") })).status).toBe(404);
86
97
  expect((await post({ dir: join(homeDir, ".kaizen") })).status).toBe(404);
87
98
  expect((await post({ dir: st, agent: "rm -rf /" })).status).toBe(400);