kaizen-agent 1.75.0 → 1.76.0

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.
package/cli/chat.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { randomUUID } from "node:crypto";
7
7
  import { basename, dirname, join } from "node:path";
8
+ import { hostname, platform, release, arch } from "node:os";
8
9
  import { CHILD_ENV, readRuns, readText } from "./state.ts";
9
10
 
10
11
  export type Step = { kind: "cmd" | "edit" | "tool" | "project"; text: string; ok?: boolean };
@@ -70,6 +71,10 @@ export function brief(c: Chat, board: Board) {
70
71
  .map((r) => `- ${p.label}: ${r.id} (${r.stage}, waiting on ${r.awaiting})`)).join("\n");
71
72
  return `[kaizen board context, not written by the user]
72
73
  You are kaizen's main agent, talking with the user from the kaizen board's Home page.
74
+ Board server machine: hostname ${hostname()}, OS ${platform()} ${release()}, architecture ${arch()}. This is the machine hosting the board, not necessarily the user's phone or browser. A scratch folder is only your working directory, not a separate machine.
75
+ Use your available tools to investigate and finish the user's request: shell commands, file reads and edits, web search, and any configured MCP tools. Inspect the tools actually available in this session; do not assume every integration is connected. Use installed skills when relevant, reading their SKILL.md before following them.
76
+ For questions about this machine, run appropriate read-only checks (for example hostname and uname on Unix, or PowerShell equivalents on Windows). Do not claim you cannot inspect the machine without trying an appropriate available tool. If a check fails, report the actual limitation and what you could verify. Do not infer the hosting provider or physical host from a hostname alone.
77
+ Read-only investigation does not need a project selection or the development choice below. Use web search for current information and cite sources. Tool access does not authorize unrelated changes or sending messages to others.
73
78
  Project of this chat: ${here ? `${here.label} (${dirname(here.dir)})` : "none — you are in a scratch folder"}.
74
79
  Projects on the board:
75
80
  ${list || "(none)"}
@@ -223,7 +228,9 @@ export function sendChat(base: string, id: string | null, text: string, project:
223
228
  // Every listed project is writable, so the agent works on any of them without a switch.
224
229
  const dirs = roots(board).filter((d) => d !== cwd).flatMap((d) => ["--add-dir", d]);
225
230
  const argv = [bin, "exec", "--json", "--skip-git-repo-check", "-s", "workspace-write", ...dirs,
226
- "-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium", ...(chat.thread ? ["resume", chat.thread] : []), ...images, "-"];
231
+ "-m", "gpt-6-luna", "-c", "model_reasoning_effort=medium",
232
+ "-c", 'web_search="live"', "-c", "sandbox_workspace_write.network_access=true",
233
+ ...(chat.thread ? ["resume", chat.thread] : []), ...images, "-"];
227
234
  let p;
228
235
  try { p = Bun.spawn(argv, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }); }
229
236
  catch (err: any) {
@@ -0,0 +1,27 @@
1
+ // Shared scalar lookup for comment-preserving Kaizen config files.
2
+ // Read and write a dotted key by walking indentation, so the comment above every
3
+ // key survives. Parsing to an object and dumping it back would delete all of them.
4
+ export function lineOf(text: string, key: string) {
5
+ const parts = key.split(".");
6
+ const lines = text.split("\n");
7
+ let depth = 0, from = 0;
8
+ for (const [pi, part] of parts.entries()) {
9
+ const want = new RegExp(`^ {${depth}}${part}:`);
10
+ let found = -1;
11
+ for (let i = from; i < lines.length; i++) {
12
+ if (want.test(lines[i]!)) { found = i; break; }
13
+ if (pi > 0 && /^\S/.test(lines[i]!) && i > from) break; // left the parent block
14
+ }
15
+ if (found < 0) return { lines, index: -1, indent: depth };
16
+ from = found + 1; depth += 2;
17
+ }
18
+ return { lines, index: from - 1, indent: depth - 2 };
19
+ }
20
+
21
+ export function read(text: string, key: string) {
22
+ const { lines, index } = lineOf(text, key);
23
+ if (index < 0) return null;
24
+ const v = lines[index]!.split(":").slice(1).join(":").split("#")[0]!.trim();
25
+ return v.replace(/^["']|["']$/g, "");
26
+ }
27
+
package/cli/settings.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  // Full-screen settings browser for .kaizen/config.yml.
2
2
  // Arrow keys move and change; every change is written straight to the file.
3
+ import { lineOf, read } from "./config-values.ts";
4
+ export { read } from "./config-values.ts";
3
5
  import { existsSync, writeFileSync, copyFileSync, mkdirSync } from "node:fs";
4
6
  import { join, dirname, basename } from "node:path";
5
7
  import { homedir } from "node:os";
@@ -107,6 +109,7 @@ const SETTINGS: Setting[] = [
107
109
  { key: "approvals.review", label: "Approve after review", group: "Approvals", values: ["true", "false"], help: "In auto mode too: a run that changed files waits for your approval unless auto_accept is on" },
108
110
  { key: "auto_accept", label: "Auto runs skip final approval", group: "Approvals", values: ["false", "true"], help: "true: an auto run that changed files finishes without waiting, marked auto-accepted", when: ["mode", "auto"] },
109
111
  { key: "approvals.each_file", label: "Confirm every file edit", group: "Approvals", values: ["true", "false"], help: "", when: ["mode", "approve"] },
112
+ { key: "explore.enabled", label: "Explore before planning", group: "Agents", values: ["false", "true"], help: "Question the idea and research uncertainties before Plan. Clear fixes skip it; each run can skip Explore." },
110
113
  { key: "runner", label: "Stage isolation", group: "Agents", values: ["full", "lite"], help: "full: separate agent per stage. lite: one session" },
111
114
  { key: "build.executor", label: "Who builds", group: "Agents", values: ["subagent", "inline", "ask"], help: "subagent: its own agent · inline: this session · ask: pick at plan approval", when: ["runner", "full"] },
112
115
  { key: "review.executor", label: "Reviewer", group: "Agents", values: ["inline", "subagent", "ask"], help: "subagent: its own cold agent · inline: this session · ask: pick before review", when: ["runner", "lite"] },
@@ -483,32 +486,6 @@ function scopeFile(project?: string | null) {
483
486
  return project === undefined ? locate() : project === null ? globalFile() : join(project, ".kaizen", "config.yml");
484
487
  }
485
488
 
486
- // Read and write a dotted key by walking indentation, so the comment above every
487
- // key survives. Parsing to an object and dumping it back would delete all of them.
488
- function lineOf(text: string, key: string) {
489
- const parts = key.split(".");
490
- const lines = text.split("\n");
491
- let depth = 0, from = 0;
492
- for (const [pi, part] of parts.entries()) {
493
- const want = new RegExp(`^ {${depth}}${part}:`);
494
- let found = -1;
495
- for (let i = from; i < lines.length; i++) {
496
- if (want.test(lines[i]!)) { found = i; break; }
497
- if (pi > 0 && /^\S/.test(lines[i]!) && i > from) break; // left the parent block
498
- }
499
- if (found < 0) return { lines, index: -1, indent: depth };
500
- from = found + 1; depth += 2;
501
- }
502
- return { lines, index: from - 1, indent: depth - 2 };
503
- }
504
-
505
- export function read(text: string, key: string) {
506
- const { lines, index } = lineOf(text, key);
507
- if (index < 0) return null;
508
- const v = lines[index]!.split(":").slice(1).join(":").split("#")[0]!.trim();
509
- return v.replace(/^["']|["']$/g, "");
510
- }
511
-
512
489
  function write(text: string, key: string, value: string, defaults: string) {
513
490
  const name = key.split(".").pop()!;
514
491
  const shown = value === "" ? '""' : value;
package/cli/skills.ts CHANGED
@@ -12,7 +12,7 @@ export const SKILL_HOMES = [
12
12
  ];
13
13
 
14
14
  // Core by name, so a lost manifest or an edited off-list can never remove the workflow.
15
- const CORE = ["kaizen", "kaizen-concept", "kaizen-help"];
15
+ const CORE = ["kaizen", "kaizen-concept", "kaizen-explore", "kaizen-help"];
16
16
 
17
17
  function frontMatter(text: string) {
18
18
  const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? "";
package/cli/state.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Everything kaizen knows about a project's state, read from and written to the
2
2
  // `.kaizen/` directory. No terminal, no HTTP: the TUI (`dashboard.ts`) and the web
3
3
  // board (`web.ts`) both import this and draw it their own way.
4
+ import { read as readSetting } from "./config-values.ts";
4
5
  import { readAccounts, resolveAccount, type Resolved } from "./accounts.ts";
5
6
  import { agentEnabled, argsOf, commandOf, prefersBypass, readPrefs, withEnv } from "./agent-prefs.ts";
6
7
  import { existsSync, readFileSync, readdirSync, appendFileSync, writeFileSync, mkdirSync, statSync, realpathSync, rmSync, renameSync, copyFileSync, openSync, readSync, closeSync } from "node:fs";
@@ -167,6 +168,7 @@ export function subagentEnv(projectDir: string, cmd: string): string[] {
167
168
  export function agentChoices(projectDir: string) {
168
169
  return {
169
170
  default: detectDefaultAgent(projectDir).cmd,
171
+ explore: configTexts(projectDir).map((t) => readSetting(t, "explore.enabled")).find((v) => v !== null) === "true",
170
172
  agents: KNOWN_AGENTS.filter((a) => agentUsable(a.cmd)).map((a) => ({
171
173
  ...accountChoices(a.cmd), name: a.name, cmd: a.cmd, model: agentConfig(projectDir, a.cmd).model ?? "", models: !!MODEL_FLAGS[a.cmd], yolo: !!YOLO_FLAGS[a.cmd], bypassDefault: prefersBypass(a.cmd) && !!YOLO_FLAGS[a.cmd],
172
174
  })),
@@ -615,8 +617,8 @@ export function resumePrompt(id: string) {
615
617
  return `run ${id}: continue it from its state.json; its last agent session ended before the stage finished.`;
616
618
  }
617
619
 
618
- export function canApproveAwaiting(awaiting: unknown): awaiting is "approvals.plan" | "approvals.review" | "findings" {
619
- return awaiting === "approvals.plan" || awaiting === "approvals.review" || awaiting === "findings";
620
+ export function canApproveAwaiting(awaiting: unknown): awaiting is "explore" | "approvals.plan" | "approvals.review" | "findings" {
621
+ return awaiting === "explore" || awaiting === "approvals.plan" || awaiting === "approvals.review" || awaiting === "findings";
620
622
  }
621
623
 
622
624
  // The board's answer to an approval the run is waiting on. The comment is collapsed to
@@ -629,6 +631,9 @@ const COMMIT_PUSH = " Then commit and push this run's changed files only, with t
629
631
  + " If state.json names a `worktree`, commit there instead and then run `kaizen worktree land` with this run's id from the project folder in place of the push; report its result as it prints it.";
630
632
 
631
633
  export function approvalPrompt(id: string, awaiting: string, why?: string, answers?: string[]) {
634
+ if (awaiting === "explore") return `run ${id}: ` + (why === undefined
635
+ ? "the user confirmed the Explore brief. Record the decision in 00-explore.md, preserve its evidence and open questions, unblock its report, set explore_status=completed stage=plan awaiting=null with kaizen state, and prepare 01-plan.md from that brief. This approves exploration only; keep the normal plan approval before building."
636
+ : `continue Explore with the user feedback: ${why.replace(/\s+/g, " ").trim()}. Update 00-explore.md; do not begin building.`);
632
637
  const plan = awaiting === "approvals.plan";
633
638
  const one = (t: string) => t.replace(/\s+/g, " ").trim();
634
639
  const note = why === undefined ? undefined : one(why);
@@ -1057,6 +1062,7 @@ export function saveAttachment(state: string, id: string | null, name: string, b
1057
1062
  // that wants a decision, or one that finished. Null for everything else. The second
1058
1063
  // line is the project, since a notification outlives the board that raised it.
1059
1064
  const NEED: Record<string, string> = {
1065
+ explore: "exploration needs your decision",
1060
1066
  "approvals.plan": "plan needs your approval",
1061
1067
  "approvals.review": "review needs your approval",
1062
1068
  "approvals.each_file": "an edit needs your approval",
@@ -1811,7 +1817,7 @@ export const CHILD_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(SESSION_ID|CHILD_
1811
1817
  // skill: start that skill instead of /kaizen (the Video page starts kaizen-video), in cwd:
1812
1818
  // a work folder that may not be a project, so it is not remembered as one. A session record is
1813
1819
  // written only where that folder has a .kaizen (a project place does; the library usually not).
1814
- 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 {
1820
+ export function launchRun(it: Item, from: string, run?: string, pick: { agent?: string; account?: string; model?: string; explore?: boolean; yolo?: boolean; card?: boolean; onChange?: () => void; skill?: "kaizen-video"; cwd?: string; seed?: string } = {}): Launch {
1815
1821
  const projectDir = pick.cwd ?? projectOf(from);
1816
1822
  // The run will be born here; the board must know the dir or the task never retires.
1817
1823
  if (!pick.cwd) remember(projectDir);
@@ -1832,7 +1838,8 @@ export function launchRun(it: Item, from: string, run?: string, pick: { agent?:
1832
1838
  // No text: a run's conversation reopened as it was, with nothing sent to it.
1833
1839
  // A skill other than kaizen: Claude Code takes it as a slash command; other agents are told to use it.
1834
1840
  const lead = !pick.skill ? "/kaizen" : agent.cmd === "claude" ? `/${pick.skill}` : `Use the ${pick.skill} skill.`;
1835
- const prompt = !it.text ? "" : requestOf(it.where ? `${lead} ${it.text} (${it.where})` : `${lead} ${it.text}`, it.notes, from);
1841
+ const exploreChoice = !run && !pick.skill && typeof pick.explore === "boolean" ? `\n\n[Kaizen launch option: explore=${pick.explore ? "on" : "off"}. Freeze this per-run override at intake; it does not change the saved setting.]` : "";
1842
+ const prompt = !it.text ? "" : requestOf(it.where ? `${lead} ${it.text} (${it.where})` : `${lead} ${it.text}`, it.notes, from) + exploreChoice;
1836
1843
  const wanted = pick.model ?? (own?.cmd === agent.cmd ? own.model : null) ?? undefined;
1837
1844
  const model = wanted && plainModel(wanted) ? wanted : undefined;
1838
1845
  // Yolo was picked for one tool; a fallback to another opens in its normal mode.
@@ -2076,8 +2083,8 @@ function setStage(file: string, change: (s: any) => boolean): boolean {
2076
2083
  // `kaizen state <id> key=value ...`: the one writer agents use for a run's state.json,
2077
2084
  // so stage and awaiting can only take the words every reader knows (spec.md, Stage 0).
2078
2085
  // `done` is refused: finishing goes through finishRun, which checks the review gate.
2079
- const STAGES = ["plan", "build", "review", "abandoned"];
2080
- const AWAITING = [null, "approvals.plan", "approvals.review", "approvals.each_file", "findings"];
2086
+ const STAGES = ["explore", "plan", "build", "review", "abandoned"];
2087
+ const AWAITING = [null, "explore", "approvals.plan", "approvals.review", "approvals.each_file", "findings"];
2081
2088
  export function setRunState(state: string, id: string, pairs: string[]): string | null {
2082
2089
  const file = join(state, "runs", id, "state.json");
2083
2090
  if (!existsSync(file)) return `no run ${id} under ${state}`;
@@ -2092,6 +2099,7 @@ export function setRunState(state: string, id: string, pairs: string[]): string
2092
2099
  if (k === "stage" && v === "done") return "stage done: use kaizen done <id>, which checks the final approval";
2093
2100
  if (k === "stage" && !STAGES.includes(String(v))) return `stage must be one of ${STAGES.join(", ")} (done: kaizen done)`;
2094
2101
  if (k === "awaiting" && !AWAITING.includes(v as any)) return `awaiting must be null or one of ${AWAITING.slice(1).join(", ")}`;
2102
+ if (k === "explore_status" && !["active", "completed", "skipped"].includes(raw)) return "explore_status must be active, completed or skipped";
2095
2103
  if (k === "iteration") { if (!/^\d+$/.test(raw)) return "iteration must be a whole number"; set[k] = Number(raw); continue; }
2096
2104
  set[k] = v;
2097
2105
  }
package/cli/stats.ts CHANGED
@@ -15,7 +15,7 @@ const mtime = (f: string) => { try { return statSync(f).mtimeMs; } catch { retur
15
15
  export type RunStat = {
16
16
  id: string; stage: string; track: string; runner: string; mode: string;
17
17
  reviewed: boolean; fixed: boolean; unverified: boolean;
18
- plan: number | null; wait: number | null; build: number | null; review: number | null;
18
+ explore: number | null; plan: number | null; wait: number | null; build: number | null; review: number | null;
19
19
  };
20
20
 
21
21
  export function runStat(state: string, id: string): RunStat | null {
@@ -39,7 +39,7 @@ export function runStat(state: string, id: string): RunStat | null {
39
39
  // awaiting is set, else the stage. The interval before the first line is planning,
40
40
  // from the request's write (00-request.md is written once, at intake).
41
41
  export function stageTimes(log: string, start: number) {
42
- const out = { plan: null as number | null, wait: null as number | null, build: null as number | null, review: null as number | null };
42
+ const out = { explore: null as number | null, plan: null as number | null, wait: null as number | null, build: null as number | null, review: null as number | null };
43
43
  const rows = log.split("\n").map((l) => l.trim().split(/\s+/)).filter((r) => r.length >= 3 && !isNaN(Date.parse(r[0]!)))
44
44
  .map(([at, stage, awaiting]) => ({ at: Date.parse(at!), stage: stage!, waiting: awaiting !== "-" }));
45
45
  if (!rows.length) return out;
@@ -71,15 +71,15 @@ const count = (rs: RunStat[], k: keyof RunStat) => rs.reduce((o, r) => { const v
71
71
 
72
72
  export function summary(rs: RunStat[]) {
73
73
  const reviewed = rs.filter((r) => r.reviewed);
74
- const med = (k: "plan" | "wait" | "build" | "review") => median(rs.map((r) => r[k]).filter((v): v is number => v !== null));
74
+ const med = (k: "explore" | "plan" | "wait" | "build" | "review") => median(rs.map((r) => r[k]).filter((v): v is number => v !== null));
75
75
  return {
76
76
  runs: rs.length,
77
77
  stage: count(rs, "stage"), track: count(rs, "track"), runner: count(rs, "runner"), mode: count(rs, "mode"),
78
78
  reviewed: reviewed.length,
79
79
  fixed: rs.filter((r) => r.fixed).length,
80
80
  unverified: rs.filter((r) => r.unverified).length,
81
- timed: rs.filter((r) => r.plan !== null || r.build !== null).length,
82
- median: { plan: med("plan"), wait: med("wait"), build: med("build"), review: med("review") },
81
+ timed: rs.filter((r) => r.explore !== null || r.plan !== null || r.build !== null).length,
82
+ median: { explore: med("explore"), plan: med("plan"), wait: med("wait"), build: med("build"), review: med("review") },
83
83
  };
84
84
  }
85
85
 
@@ -159,7 +159,7 @@ export function statsText(state: string, id?: string, json = false): string {
159
159
  if (json) return JSON.stringify({ ...r, tokens: t }, null, 2);
160
160
  const tok = t ? `${t.input + t.cacheWrite + t.cacheRead} in (${t.cacheRead} from cache), ${t.output} out, ${t.turns} turns` : "n/a";
161
161
  return [`${r.id} ${r.stage} · ${r.track} · ${r.runner} · ${r.mode}`,
162
- `plan ${dur(r.plan)} · waiting for approval ${dur(r.wait)} · build ${dur(r.build)} · review ${dur(r.review)} (from stages.log)`,
162
+ `explore ${dur(r.explore)} · plan ${dur(r.plan)} · waiting for approval ${dur(r.wait)} · build ${dur(r.build)} · review ${dur(r.review)} (from stages.log)`,
163
163
  `fix round: ${r.fixed ? "yes" : "no"} · CANNOT VERIFY: ${r.unverified ? "yes" : "no"}`,
164
164
  `tokens: ${tok}`].join("\n");
165
165
  }
@@ -168,5 +168,5 @@ export function statsText(state: string, id?: string, json = false): string {
168
168
  return [`${s.runs} runs — ${kv(s.stage)}`,
169
169
  `track: ${kv(s.track)}`, `runner: ${kv(s.runner)} · mode: ${kv(s.mode)}`,
170
170
  `fix round: ${s.fixed} of ${s.reviewed} reviewed (${pct(s.fixed, s.reviewed)}) · CANNOT VERIFY in ${s.unverified} reviews (${pct(s.unverified, s.reviewed)})`,
171
- `median: plan ${dur(s.median.plan)} · waiting for approval ${dur(s.median.wait)} · build ${dur(s.median.build)} · review ${dur(s.median.review)} (runs with a stages.log: ${s.timed})`].join("\n");
171
+ `median: explore ${dur(s.median.explore)} · plan ${dur(s.median.plan)} · waiting for approval ${dur(s.median.wait)} · build ${dur(s.median.build)} · review ${dur(s.median.review)} (runs with a stages.log: ${s.timed})`].join("\n");
172
172
  }
@@ -0,0 +1,49 @@
1
+ import { open } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, basename } from "node:path";
4
+
5
+ // Read saved history without starting a shell or executing its startup files.
6
+ export function parseHistory(text: string, kind: string): string[] {
7
+ if (kind === "fish") return text.split(/\r?\n/).filter((s) => s.startsWith("- cmd: ")).map((s) => s.slice(7).replace(/\\(\\|n)/g, (_, c) => c === "n" ? "\n" : "\\"));
8
+ const commands: string[] = [];
9
+ let pending = "";
10
+ for (const line of text.split(/\r?\n/)) {
11
+ if (kind === "bash" && /^#\d+$/.test(line)) continue;
12
+ const value = kind === "zsh" ? line.replace(/^: \d+:\d+;/, "") : line;
13
+ if (kind === "zsh" && value.endsWith("\\")) { pending += value.slice(0, -1) + "\n"; continue; }
14
+ if (value || pending) commands.push(pending + value);
15
+ pending = "";
16
+ }
17
+ if (pending) commands.push(pending.trimEnd());
18
+ return commands;
19
+ }
20
+
21
+ export async function shellHistory(env: NodeJS.ProcessEnv = process.env, root = homedir()): Promise<string[]> {
22
+ const preferred = basename(env.SHELL || "bash").replace(/\.exe$/i, "");
23
+ const files: [string, string][] = [
24
+ [join(root, ".bash_history"), "bash"],
25
+ [join(env.ZDOTDIR || root, ".zsh_history"), "zsh"],
26
+ [join(env.XDG_DATA_HOME || join(root, ".local", "share"), "fish", "fish_history"), "fish"],
27
+ [join(env.APPDATA || join(root, "AppData", "Roaming"), "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"), "powershell"],
28
+ [join(env.XDG_DATA_HOME || join(root, ".local", "share"), "powershell", "PSReadLine", "ConsoleHost_history.txt"), "powershell"],
29
+ ];
30
+ files.sort((a, b) => Number(a[1] === preferred) - Number(b[1] === preferred));
31
+ if (env.HISTFILE) files.push([env.HISTFILE.replace(/^~\//, root + "/"), preferred]);
32
+ const commands: string[] = [];
33
+ for (const [path, kind] of files) {
34
+ let file;
35
+ try {
36
+ file = await open(path, "r");
37
+ const stat = await file.stat();
38
+ if (!stat.isFile()) continue;
39
+ const start = Math.max(0, stat.size - 512 * 1024);
40
+ const buffer = Buffer.alloc(Math.min(stat.size, 512 * 1024));
41
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
42
+ let text = buffer.subarray(0, bytesRead).toString("utf8");
43
+ if (start) text = text.slice(text.indexOf("\n") + 1);
44
+ commands.push(...parseHistory(text, kind));
45
+ } catch { /* A shell may have no saved history or disable it. */ }
46
+ finally { await file?.close(); }
47
+ }
48
+ return [...new Set(commands.reverse().filter((s) => s.trim()))].slice(0, 500);
49
+ }
package/cli/web.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  import { ACCOUNT_VAR, accountDir, addAccount, readAccounts, renameAccount, signedIn, removeAccount, resolveAccount, setDefaultAccount } from "./accounts.ts";
15
15
  import { readReport, signalOf } from "./report.ts";
16
16
  import { MAX_IMAGE, saveImage } from "./term-image.ts";
17
+ import { shellHistory } from "./term-history.ts";
17
18
  import { bundledSkills, repairSkill, setSkill, skillsHeld, skillsOff, skillStatus } from "./skills.ts";
18
19
  import * as rea from "./rea.ts";
19
20
  import { accountEnv, accountForRun, agentUsable, CHILD_ENV, heartbeatMinutes, keepAwake, launchPreview, trustFolder, YOLO_FLAGS } from "./state.ts";
@@ -913,6 +914,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
913
914
  return bad("websocket expected", 426);
914
915
  }
915
916
 
917
+ if (req.method === "POST" && path === "/pty/history") {
918
+ const refused = strict(req);
919
+ if (refused) return refused;
920
+ let body: any;
921
+ try { body = await req.json(); } catch { return bad("json body expected"); }
922
+ const key = String(body.key ?? "");
923
+ if (!/^[\w-]+$/.test(key) || !ptyState(key)) return bad("no such terminal", 404);
924
+ return new Response(JSON.stringify({ history: await shellHistory() }), { headers: { "content-type": "application/json", "cache-control": "no-store" } });
925
+ }
926
+
916
927
  // The Terminal page's ×: the agent is asked to /exit, and ended if it will not.
917
928
  if (req.method === "POST" && path === "/pty/exit") {
918
929
  if (!local(req)) return bad("cross-origin write refused", 403);
@@ -1481,7 +1492,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1481
1492
  const read = (f: string) => existsSync(join(base, f)) ? readText(join(base, f)) : null;
1482
1493
  return json({
1483
1494
  id, short: short(id), state: read("state.json"),
1484
- request: read("00-request.md"), plan: read("01-plan.md"), approval: read("02-approval.md"),
1495
+ request: read("00-request.md"), explore: read("00-explore.md"), plan: read("01-plan.md"), approval: read("02-approval.md"),
1485
1496
  impl: read("03-impl.md"), review: read("04-review.md"), backlog: read("06-backlog.md"),
1486
1497
  notes: read("notes.md"), progress: read("progress.md"),
1487
1498
  // Notebook notes whose [[run:…]] links name this run.
@@ -2264,7 +2275,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2264
2275
  const p = parseItem(line.text);
2265
2276
  const it: Item = { ...p, text: kind ? `${kind} ${p.text}` : p.text };
2266
2277
  it.notes = [source !== "orphan" ? `Parent: ${source}` : "", `Backlog: ${source}#${n}`, p.text !== line.text ? `Backlog item: ${line.text}` : ""].filter(Boolean).join("\n");
2267
- const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
2278
+ const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, explore: typeof body.explore === "boolean" ? body.explore : undefined, yolo: body.yolo === true, ...inCard(dir) });
2268
2279
  if (r.ok) backlogLaunched.add(`${dir}\0${source}#${n}`);
2269
2280
  changed();
2270
2281
  return json(r.ok
@@ -2275,7 +2286,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
2275
2286
  // A `started` task may be run again: the terminal the first launch opened
2276
2287
  // can come up empty, and nothing else tells the board a run never began.
2277
2288
  it.notes = readInbox(dir).find((l) => (l.status === "open" || l.status === "started") && l.text === text)?.notes;
2278
- const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, yolo: body.yolo === true, ...inCard(dir) });
2289
+ const r = launchRun(it, dir, undefined, { agent, account: typeof body.account === "string" ? body.account : undefined, model: model || undefined, explore: typeof body.explore === "boolean" ? body.explore : undefined, yolo: body.yolo === true, ...inCard(dir) });
2279
2290
  if (r.ok) replaceTask(dir, text, { status: "started", text });
2280
2291
  if (r.ok && r.pty) {
2281
2292
  for (const [k, v] of taskPty) if (!ptyState(v)) taskPty.delete(k); // sessions already dropped
@@ -2462,6 +2473,26 @@ export async function web(repoDir: string, opts: Opts = {}) {
2462
2473
  : { ok: false, why: r.why, manual: r.manual, agent: r.agent }, r.ok ? 200 : 500);
2463
2474
  }
2464
2475
 
2476
+ // Skipping changes only this run. The agent records the partial brief and
2477
+ // transition, so an in-flight research write cannot race a server-side edit.
2478
+ if (path === "/explore/skip") {
2479
+ const id = String(body.id ?? "");
2480
+ if (!/^(?!\.+$)[\w.-]+$/.test(id)) return bad("bad run id");
2481
+ if (dir === join(home, ".kaizen")) return bad("no project to run in", 409);
2482
+ let run: any;
2483
+ try { run = JSON.parse(readText(join(dir, "runs", id, "state.json"))); } catch { return bad("no such run", 404); }
2484
+ if (run.stage !== "explore") return bad("this run is not exploring", 409);
2485
+ const text = `run ${id}: the user chose Skip Explore for this run only. Stop exploration, preserve partial findings and unanswered questions in 00-explore.md, record that the user skipped it, run kaizen report unblock --run ${id}, set explore_status=skipped stage=plan awaiting=null with kaizen state, and prepare the plan. Do not change explore.enabled or skip the plan approval.`;
2486
+ const live = liveAgent(dir, id), before = Date.now();
2487
+ const r = live ? { ok: true as const, agent: live.agent, pty: live.key }
2488
+ : launchRun({ severity: null, where: null, text, raw: text }, dir, id, inCard(dir));
2489
+ if (live) submitPty(live.key, text);
2490
+ else if (r.ok) closeSessions(dir, id, { before });
2491
+ changed();
2492
+ return json(r.ok ? { ok: true, agent: r.agent, pty: r.pty }
2493
+ : { ok: false, why: r.why, manual: r.manual }, r.ok ? 200 : 500);
2494
+ }
2495
+
2465
2496
  // Approve or send back what a run is waiting on, from its panel. The page names
2466
2497
  // the approval it saw: one already answered elsewhere is not answered twice.
2467
2498
  if (path === "/decide") {
@@ -0,0 +1,6 @@
1
+ ---
2
+ description: Question an idea and research uncertainties before planning
3
+ argument-hint: "<request>"
4
+ ---
5
+
6
+ Follow the kaizen skill for `/kaizen explore $ARGUMENTS`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.75.0",
3
+ "version": "1.76.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -44,6 +44,8 @@ Porting the workflow to Codex or Antigravity is covered in [`adapters.md`](adapt
44
44
  | `/kaizen auto <request>` | Start a run in `auto` mode: every stage back to back, no approval stops |
45
45
  | `/kaizen lite <request>` | Run every stage in this session — cheap, and the reviewer has seen the work unless `review.executor` is `subagent` |
46
46
  | `/kaizen full <request>` | Dispatch every stage as its own agent — the reviewer starts cold |
47
+ | `/kaizen explore <request>` | Explore an idea before Plan for this run, even when Explore is off |
48
+ | `/kaizen skip-explore [request]` | Skip Explore in the current run, or start the request directly at Plan |
47
49
  | `/kaizen run` | Resume the current run and execute the approved plan |
48
50
  | `/kaizen review [target]` | Review-only: audit existing code, no plan, no implementation (`review-only`) |
49
51
  | `/kaizen status` | List every run grouped waiting-on-you / in flight / done / abandoned, plus the open backlog count |
@@ -119,6 +121,35 @@ run starts.
119
121
 
120
122
  **Follow-ups are runs too.** Both runners record the same artifacts: `01-plan.md`, `03-impl.md`, `04-review.md`, and a final `state.json` — `lite` and `full` differ only in who executes the stages. A message the user sends later in the same session is judged by what it asks: a question, explanation or chat is answered, no run; a request to change or produce something is building, so it goes through the flow. While the previous run has not reached `done` (including awaiting its final approval), a change to that run's own work is a revise of it, recorded in `02-approval.md` ("make the new panel narrower" while that panel is being built). A request for something else while a run is in flight (a bug in another area found mid-feature, an unrelated fix) asks first, AskUserQuestion: *Side run: new worktree off the default branch, built by a second agent* (recommended), *Side run: new worktree off the default branch, built in this session* (in the side run's own worktree, never the other run's folder), *Revise the current run*, *Answer without a run*; create nothing under `runs/` until a side run is picked. **A side run** is a new run, started like any other with its own fresh `state.json`: never copy another run's `state.json`, and never carry over its `worktree`, `branch`, `workspace`, `session`, `base_branch` or `base_sha`. Its `00-request.md` ends with `Follow-up of: <the run in flight>`. Plan it and take its plan approval as usual, then run `kaizen worktree start <id> --default` from the project folder or any worktree: it cuts `kaizen/<id>` from the remote default branch and never places the run in the folder you are in. For the second agent, run `kaizen handoff start <id>` as `spec-build.md` says. This works under `lite` and `full` alike. Either way, go back to the run in flight; the side run never changes it. After `done` or `abandoned`, ask the user before opening a new run — AskUserQuestion with *open a follow-up run*, *answer without a run*, *cancel* — and create nothing under `runs/` until they pick the first. An explicit `/kaizen <request>` is that answer already. The new run's `00-request.md` is the user's words verbatim, then a line `Follow-up of: <previous run id>`; where those words only answer a question ("Plan 2b next"), put one line naming the work first — the board titles the card from it. Never reopen a finished run. When unsure whether a message asks for a change, ask once.
121
123
 
124
+ ## Optional Explore before Plan
125
+
126
+ `explore.enabled` defaults to `false`: Plan → Build → Review → Done stays the
127
+ normal workflow. When enabled, new or unclear directions can take Explore → Plan
128
+ → Build → Review → Done. Offer Skip Explore when entering it. Clear bug fixes,
129
+ small edits, dependency updates and already agreed work go straight to Plan;
130
+ finding an unknown bug cause is ordinary debugging, not a reason to require Explore.
131
+
132
+ `/kaizen explore <request>` explicitly includes Explore for one run; a launch
133
+ option `explore=on` has the same effect. `/kaizen skip-explore <request>` or
134
+ `explore=off` explicitly skips it. These override the setting for this run only.
135
+ A bare `/kaizen skip-explore`, or a clear request to skip during Explore, preserves
136
+ partial notes and moves the current run to Plan. Never change the global toggle.
137
+
138
+ At intake record `explore_status` as `active` or `skipped`, and the reason in
139
+ `00-request.md`. Enter `stage: "explore"` only when included; otherwise `plan`.
140
+ `review-only` always starts at Review. Freeze this choice: resume by the saved stage
141
+ and status, not today's configuration. Legacy runs with no Explore fields continue
142
+ normally. For an active Explore use the **kaizen-explore** skill before dispatching
143
+ the planner. The main thread handles its user dialogue under both runners; delegated
144
+ research, where supported, does not take the user's decisions. Its saved artifact is
145
+ `00-explore.md`, and `awaiting: "explore"` means the brief needs confirmation.
146
+
147
+ Explore can end by confirming the brief, skipping it, or abandoning the run. Both
148
+ confirmation and skip enter Plan; neither approves the plan or authorizes Build.
149
+ Read `00-explore.md` during planning, preserving confirmed choices and evidence
150
+ limits instead of repeating the interview. A `plan-only` run may explore first,
151
+ then stops after its plan as usual. `auto` never supplies invented human decisions.
152
+
122
153
  ## Modes
123
154
 
124
155
  Set by `mode` in config, overridable per invocation.
@@ -275,6 +306,7 @@ file, never the whole set.
275
306
 
276
307
  | Stage | Agent type | Writes |
277
308
  |---|---|---|
309
+ | Explore (optional) | Main thread using `kaizen-explore` | `00-explore.md` |
278
310
  | Plan | `kaizen-planner` | `01-plan.md` |
279
311
  | Implement (`stage: "build"`) | `kaizen-builder`, or the main thread when `build.executor` is `inline` | `03-impl.md` + the actual changes |
280
312
  | Review | `kaizen-reviewer` | `04-review.md` |
@@ -336,6 +368,7 @@ shown automatically.
336
368
  runs/
337
369
  2026-09-02-add-oauth/
338
370
  00-request.md # the original request, verbatim
371
+ 00-explore.md # optional: evidence, decisions, open questions
339
372
  01-plan.md
340
373
  02-approval.md # decisions, with reasons and timestamps
341
374
  03-impl.md # what changed, which files, what was skipped
@@ -38,6 +38,11 @@ approvals:
38
38
  # Override for one run with `/kaizen lite <request>` or `/kaizen full <request>`.
39
39
  runner: full
40
40
 
41
+ explore:
42
+ # Optional questioning and evidence gathering before Plan. Clear fixes skip it.
43
+ # A run may override this with /kaizen explore or /kaizen skip-explore.
44
+ enabled: false
45
+
41
46
  build:
42
47
  # Who carries out the approved plan.
43
48
  # subagent - dispatch the builder as its own agent. The main thread keeps its
@@ -74,3 +74,10 @@ picker with thirty options.
74
74
  `kaizen settings` in a terminal opens the same settings as a full-screen browser, for
75
75
  someone who would rather see the whole file at once. Mention it when the user is
76
76
  changing several at a time.
77
+
78
+ ## Explore
79
+
80
+ `explore.enabled` is a project/global boolean, default false. It offers an optional
81
+ Explore phase before Plan for new or unclear work. Routine fixes skip it. A per-run
82
+ Explore checkbox or `/kaizen explore` includes it; `/kaizen skip-explore` skips it.
83
+ Choices are frozen per run, and changing this setting does not move existing runs.
@@ -327,3 +327,15 @@ write what it found to the run's `notes.md`, and dispatch the planner with it. W
327
327
  REA has to be installed first, the install in *Offer REA* (`spec-plan.md`) is the main
328
328
  thread's too: doctor, the dry-run shown to the user, setup only on their approval,
329
329
  then the restart, after which the run resumes at `stage: "plan"` from `state.json`.
330
+
331
+ ## Explore before planning
332
+
333
+ Before dispatching the planner, honor the run's saved Explore choice and phase.
334
+ Read the kaizen-explore skill for `stage: explore`. The main thread conducts its
335
+ interview and confirmation under both runners. It saves `00-explore.md`, keeps
336
+ interview questions in the blocked report, and uses `awaiting: explore` only for a
337
+ ready brief. Confirming or skipping enters Plan, never Build. Skip is per-run and
338
+ preserves partial evidence. A resumed run never restarts Explore from a changed
339
+ setting. On a board confirmation record the decision, unblock and prepare the plan;
340
+ normal plan approval remains required. An Explore revise returns to questioning,
341
+ not implementation. Stop abandons the run.
@@ -23,6 +23,12 @@ and open backlog may bear on this one; the Framing adds `Related: <ids it used>`
23
23
  the codebase, the manuscript, the current campaign, whatever this run builds on.
24
24
  **Output:** `01-plan.md`.
25
25
 
26
+ Before framing, read `00-explore.md` when present. Carry confirmed decisions,
27
+ supporting sources and uncertainty into the plan; do not repeat settled interview
28
+ questions. A skipped Explore may contain partial evidence, not approved conclusions.
29
+ If state.json still says `stage: "explore"`, return control to the main thread for
30
+ Explore completion or skip before planning. Build remains behind its normal approval.
31
+
26
32
  The request is usually one sentence. The planner's first job is to expand it — but by
27
33
  proposing, not by interrogating. It restates the problem, brings the nearest good
28
34
  solution, and names the assumptions it took, so the user reacts to something concrete
@@ -111,14 +111,14 @@ categorize their own request up front.
111
111
 
112
112
  Write into `00-request.md`: the verbatim request, the deliverable, what done means,
113
113
  and what wrong means. Record in `state.json`: `id`, `mode`, `runner`, `agent`, `track`,
114
- `stage: "plan"`, `awaiting: null`, `iteration: 0`, and `updated` — the time of this
114
+ `stage: "explore"` when included (otherwise `"plan"`; `review-only` starts at `"review"`), `explore_status` (`active` or `skipped`), `awaiting: null`, `iteration: 0`, and `updated` — the time of this
115
115
  write, refreshed on every later one.
116
116
  A `lite` run also records `review_executor` (`inline` or `subagent`, from `review.executor`, `ask` resolved) once it is known, and a resumed run keeps it.
117
117
  Where the environment has `CLAUDE_CODE_SESSION_ID`, also record it as `session`: the
118
118
  board keeps the run on the card it was launched from by that id.
119
119
 
120
- `stage` takes exactly one of five words, and boards key their columns on them:
121
- `plan`, `build`, `review`, `done`, `abandoned`. Set it when the stage starts —
120
+ `stage` takes exactly one of six words, and boards key their columns on them:
121
+ `explore`, `plan`, `build`, `review`, `done`, `abandoned`. Set it when the stage starts —
122
122
  `build` before the builder touches anything, `review` before the reviewer reads — as
123
123
  its own write, not tacked onto a longer command that may not finish. Fixing findings
124
124
  is building and a recheck is reviewing, whoever runs them and whether the loop or the
@@ -134,7 +134,7 @@ installed, edit `state.json` by hand in its two-space JSON layout. Finish with
134
134
 
135
135
  `awaiting` is `null` or the config key of the approval being waited on —
136
136
  `approvals.plan`, `approvals.review`, `approvals.each_file` — or `findings` when the
137
- run has stopped for the user to pick which review findings to fix. Boards read it to
137
+ run has stopped for the user to pick which review findings to fix. `explore` means the Explore brief is ready for the user to confirm; interview rounds use `kaizen report blocked` with `awaiting: null`. Boards read it to
138
138
  say what a run is waiting for and where it sits; a word outside this list is shown but
139
139
  not understood.
140
140
 
@@ -158,6 +158,16 @@ round of questions here is cheaper than a rejected plan.
158
158
 
159
159
  ---
160
160
 
161
+ ## Before Plan — optional Explore
162
+
163
+ Read the intake rules in the kaizen skill. `explore.enabled: false` is the default;
164
+ explicit per-run choices take precedence. Clear fixes skip this phase. If included,
165
+ run the kaizen-explore skill in the main thread and save `00-explore.md` before Plan.
166
+ On confirmation set `explore_status=completed stage=plan awaiting=null`; on skip
167
+ preserve partial work and set `explore_status=skipped stage=plan awaiting=null`.
168
+ Unblock any interview report. A stop abandons the run. Neither exit bypasses normal
169
+ plan approval. Legacy runs and resumed runs never gain Explore automatically.
170
+
161
171
  ## Reporting to the board
162
172
 
163
173
  Every stage reports with `kaizen report`, under every runner. From the moment the run
@@ -168,7 +178,7 @@ the work. Windows has no `KAIZEN_RUN_ID`, and a new run gets one only once resum
168
178
  Work list step. These are the run's heartbeat.
169
179
  - `kaizen report blocked "<question>" --options a,b` when only the user can answer,
170
180
  instead of stalling or guessing. Then stop and ask; `kaizen report unblock` once answered.
171
- - `kaizen report done --stage <plan|build|review> --outcome succeeded|failed --summary "<3 sentences>" --files a,b`
181
+ - `kaizen report done --stage <explore|plan|build|review> --outcome succeeded|failed --summary "<3 sentences>" --files a,b`
172
182
  as the stage's last act. A build or review that ends without it shows as unverified.
173
183
 
174
184
  ---
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matt Pocock
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.