kaizen-agent 1.85.2 → 1.86.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/rea.ts CHANGED
@@ -3,10 +3,10 @@
3
3
  // `setup`, `uninstall` and `doctor` do, through `npx` pinned to an exact version. Kaizen keeps
4
4
  // only its switch in ~/.kaizen/rea.json and reads agent configs to see what is registered.
5
5
  import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
- import { join } from "node:path";
6
+ import { delimiter, join, posix, win32 } from "node:path";
7
7
  import { SKILL_HOMES } from "./skills.ts";
8
8
 
9
- export type Run = (argv: string[]) => Promise<{ ok: boolean; out: string }>;
9
+ export type Run = (argv: string[], ms?: number) => Promise<{ ok: boolean; out: string; err?: string }>;
10
10
  export type Reg = { client: string; version: string | null };
11
11
  export type Saved = { on: boolean; version: string; clients: string[] };
12
12
 
@@ -21,14 +21,16 @@ const npx = process.platform === "win32" ? "npx.cmd" : "npx";
21
21
  const npm = process.platform === "win32" ? "npm.cmd" : "npm";
22
22
  const pkg = (version: string) => `rea-agents@${version}`;
23
23
 
24
- // Up to 5 minutes: a first npx run downloads REA (about 50 MB). A missing npx is a failure, not a throw.
25
- export const run: Run = async (argv) => {
24
+ // Up to 5 minutes by default: a first npx run downloads REA (about 50 MB). A missing npx is a failure, not a throw.
25
+ export const run: Run = async (argv, ms = 5 * 60_000) => {
26
26
  try {
27
27
  const p = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe", stdin: "ignore", windowsHide: true });
28
- const timer = setTimeout(() => p.kill(), 5 * 60_000);
28
+ const timer = setTimeout(() => p.kill(), ms);
29
29
  const [out, err, code] = await Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]);
30
30
  clearTimeout(timer);
31
- return { ok: code === 0, out: out || err };
31
+ // `out` stays one stream, as REA's JSON parsing expects; `err` is there for callers that
32
+ // want the reason a package manager put on stderr after its progress on stdout.
33
+ return { ok: code === 0, out: out || err, err };
32
34
  } catch (e: any) { return { ok: false, out: `${argv[0]} not found: ${e?.message ?? e}` }; }
33
35
  };
34
36
 
@@ -57,7 +59,10 @@ export function doctorMissing(j: any): string[] {
57
59
  if (Array.isArray(v)) return v.forEach(walk);
58
60
  if (!v || typeof v !== "object") return;
59
61
  const bad = v.ok === false || v.passed === false || /^(fail|failed|error|missing)$/i.test(String(v.status ?? ""));
60
- if (bad && (v.name || v.id || v.message)) out.add(String(v.name ?? v.id ?? v.message).slice(0, 80));
62
+ // A failed `node` check is the PC's Node.js being too old: name what it needs, like oldNode.
63
+ const need = v.name === "node" && /^Install (Node\.js .+?)\.?$/.exec(String(v.remediation ?? ""))?.[1]?.replace(/, or /, ", ");
64
+ if (bad && need) out.add(`${need} (this PC has ${v.detail ?? "an older one"})`);
65
+ else if (bad && (v.name || v.id || v.message)) out.add(String(v.name ?? v.id ?? v.message).slice(0, 80));
61
66
  for (const x of Object.values(v)) if (x && typeof x === "object") walk(x);
62
67
  };
63
68
  if (j) for (const k of ["scope_checks", "informational_checks", "providerInspections", "checks"]) walk(j[k]);
@@ -107,8 +112,82 @@ const validClients = (home: string, clients: string[]) => {
107
112
  return clients.length > 0 && clients.every((c) => known.has(c));
108
113
  };
109
114
  const clientArgs = (clients: string[]) => clients.flatMap((c) => ["--client", c]);
115
+ // REA refuses a Node.js older than it supports with one plain line, no JSON. On Windows npx
116
+ // runs the PC's own Node.js, which kaizen cannot update, so say what is needed and how.
117
+ export function oldNode(out: string): { need: string; have: string } | null {
118
+ const m = /REA requires (Node\.js .+?); this process runs Node\.js v?(\d+(?:\.\d+)*)/.exec(out);
119
+ return m ? { need: m[1]!.replace(/, or /, ", "), have: m[2]! } : null;
120
+ }
121
+ const NODE_FIX = "Use Update Node.js on the REA row in Settings → Skills, or install the current Node.js LTS from nodejs.org, then try again.";
122
+
123
+ // ---- Node.js for REA: missing (no node on PATH) or old (REA said so). Installed only on the
124
+ // user's click and yes, through the platform's own package manager; otherwise a download link.
125
+ let nodeOld: { need: string; have: string } | null = null;
126
+ export const forgetNodeOld = () => { nodeOld = null; };
127
+ export const NODE_URL = "https://nodejs.org/en/download";
128
+ export type NodeFix = { how: "winget" | "brew"; argv: string[]; command: string; bin: string } | { how: "link"; url: string };
129
+
130
+ // Where a package manager lives when a desktop app's PATH does not list it (macOS GUI apps).
131
+ const BREWS = ["/opt/homebrew/bin/brew", "/usr/local/bin/brew"];
132
+ export function nodeFix(platform = process.platform, which: (b: string) => string | null = (b) => Bun.which(b, { PATH: process.env.PATH }), exists = existsSync, env = process.env): NodeFix {
133
+ if (platform === "win32") {
134
+ const winget = which("winget");
135
+ // `install` upgrades a package winget already knows, so one command covers both cases.
136
+ const argv = ["winget", "install", "--id", "OpenJS.NodeJS.LTS", "--exact", "--source", "winget", "--accept-package-agreements", "--accept-source-agreements", "--disable-interactivity"];
137
+ if (winget) return { how: "winget", argv: [winget, ...argv.slice(1)], command: argv.join(" "), bin: win32.join(env.ProgramFiles ?? "C:\\Program Files", "nodejs") };
138
+ }
139
+ if (platform === "darwin") {
140
+ const brew = which("brew") ?? BREWS.find((b) => exists(b)) ?? null;
141
+ // `brew install` of an outdated formula upgrades it.
142
+ if (brew) return { how: "brew", argv: [brew, "install", "node"], command: "brew install node", bin: posix.dirname(brew) }; // Homebrew paths are POSIX
143
+ }
144
+ return { how: "link", url: NODE_URL };
145
+ }
146
+
147
+ // What the row shows: null when Node.js is there and REA has not called it too old.
148
+ export function nodeState(which: (b: string) => string | null = (b) => Bun.which(b, { PATH: process.env.PATH })) {
149
+ const state = !which("node") ? "missing" as const : nodeOld ? "old" as const : null;
150
+ if (!state) return null;
151
+ const fix = nodeFix();
152
+ return { state, ...(state === "old" ? { need: nodeOld!.need, have: nodeOld!.have } : {}), ...(fix.how === "link" ? { how: fix.how, url: fix.url } : { how: fix.how, command: fix.command }) };
153
+ }
154
+
155
+ // Runs the fix nodeFix built here, never a command from the page. Up to 10 minutes: winget
156
+ // downloads and runs Node's installer, and Windows shows its own admin prompt. On success the
157
+ // new Node.js folder goes first on this process's PATH, so REA's npx finds it without a restart.
158
+ let nodeBusy = false;
159
+ export async function installNode(sh: Run = run, fix: NodeFix = nodeFix(), env: Record<string, string | undefined> = process.env) {
160
+ if (fix.how === "link") return { ok: false as const, why: `Download Node.js from ${fix.url}`, url: fix.url };
161
+ if (nodeBusy) return { ok: false as const, why: "Node.js is already being installed" };
162
+ nodeBusy = true;
163
+ try {
164
+ const r = await sh(fix.argv, 10 * 60_000);
165
+ // Already the newest: winget exits non-zero. The old Node.js REA sees then comes from
166
+ // somewhere else on PATH (nvm, Volta, another installer), which kaizen does not touch.
167
+ const said = [r.out, r.err ?? ""].join("\n");
168
+ if (!r.ok && /No (available upgrade|newer package versions) (found|are available)/i.test(said)) {
169
+ return { ok: false as const, why: `Node.js from ${fix.how} is already the newest, but an older Node.js comes first on PATH (nvm, Volta or another installer?). Update or remove that one, then restart kaizen.` };
170
+ }
171
+ // The last real line: winget redraws its spinner with \r, so split on both.
172
+ if (!r.ok) return { ok: false as const, why: (said.split(/[\r\n]+/).map((l) => l.trim()).filter((l) => l && !/^[-\\|/\s█▒░]+$/.test(l)).pop() ?? `${fix.command} failed`).slice(0, 300) };
173
+ // Windows keeps both PATH and Path here (adoptLoginEnv sets both): update every spelling.
174
+ const keys = Object.keys(env).filter((k) => k.toUpperCase() === "PATH");
175
+ for (const key of keys.length ? keys : ["PATH"]) {
176
+ const parts = (env[key] ?? "").split(delimiter).filter((d) => d && d.toLowerCase() !== fix.bin.toLowerCase());
177
+ env[key] = [fix.bin, ...parts].join(delimiter);
178
+ }
179
+ nodeOld = null;
180
+ forgetDoctor();
181
+ return { ok: true as const };
182
+ } finally { nodeBusy = false; }
183
+ }
110
184
  // REA's own words when a step did not go through: its message, else the first line it printed.
111
- const reason = (j: any, out: string) => String(j?.message ?? j?.error ?? j?.reason ?? (out.trim().split("\n")[0] || "REA did not answer")).slice(0, 300);
185
+ const reason = (j: any, out: string) => {
186
+ const n = oldNode(out);
187
+ if (n) nodeOld = n;
188
+ if (n) return `REA needs ${n.need}; this PC has Node.js ${n.have}. ${NODE_FIX}`;
189
+ return String(j?.message ?? j?.error ?? j?.reason ?? (out.trim().split("\n")[0] || "REA did not answer")).slice(0, 300);
190
+ };
112
191
 
113
192
  export async function reaLatest(sh: Run = run): Promise<string | null> {
114
193
  const r = await sh([npm, "view", "rea-agents", "version"]);
@@ -143,6 +222,7 @@ export async function reaRemove(home: string, sh: Run = run) {
143
222
  const r = await sh([npx, "-y", pkg(version), "uninstall", "--json"]);
144
223
  if (!r.ok) return { ok: false as const, why: reason(parse(r.out), r.out) };
145
224
  save(home, null);
225
+ nodeOld = null;
146
226
  const left = reaRegistered(home).map((x) => x.client);
147
227
  return { ok: true as const, left, ...(left.includes("claude_code") ? { hint: "claude mcp remove --scope user rea" } : {}) };
148
228
  }
@@ -155,7 +235,14 @@ export function reaDoctor(version: string, sh: Run = run, now = Date.now()) {
155
235
  const entry: { at: number; p: Promise<any>; v?: any } = { at: now, p: Promise.resolve(null) };
156
236
  entry.p = sh([npx, "-y", pkg(version), "doctor", "--json"]).then((r) => {
157
237
  const j = parse(r.out);
158
- entry.v = j ? { healthy: j.healthy === true, missing: doctorMissing(j) } : null;
238
+ const n = j ? null : oldNode(r.out);
239
+ if (n) nodeOld = n;
240
+ else if (j) {
241
+ // Doctor ran, so it settles the question either way: a failed node check is old, else fine.
242
+ const check = (Array.isArray(j.scope_checks) ? j.scope_checks : []).find((c: any) => c?.name === "node");
243
+ nodeOld = check?.ok === false ? { need: "a newer Node.js", have: String(check.detail ?? "") } : null;
244
+ }
245
+ entry.v = n ? { healthy: false, missing: [`${n.need} (this PC has ${n.have})`] } : j ? { healthy: j.healthy === true, missing: doctorMissing(j) } : null;
159
246
  return entry.v;
160
247
  });
161
248
  doctorCache.set(version, entry);
@@ -186,14 +273,15 @@ export function reaRow(home: string, sh: Run = run, now = Date.now()) {
186
273
  const latest = on ? cachedLatest(sh, now) : null;
187
274
  const doc = on && installed ? reaDoctor(installed, sh, now) : null;
188
275
  const regd = new Set(reg.map((r) => r.client));
276
+ const node = nodeState();
189
277
  const note = !on ? undefined
190
278
  : `REA ${installed ?? "(version unknown)"}${!saved ? " · set up outside kaizen" : ""}${latest && installed && newer(latest, installed) ? ` · ${latest} available` : ""}${doc === undefined ? " · checking what it needs…" : ""}`;
191
279
  return {
192
280
  id: "rea", title: "Reverse engineering (REA)", group: "optional", offByDefault: true, status: "beta",
193
281
  description: "Lets agents study apps, binaries, packages and file formats whose source isn't here, through REA's MCP tools.",
194
- off: !on, needs: (doc?.missing ?? []).map((name) => ({ name, found: false })),
282
+ off: !on, needs: [...(node?.state === "missing" ? ["Node.js"] : []), ...(doc?.missing ?? [])].map((name) => ({ name, found: false })),
195
283
  agents: reaClients(home).map((c) => ({ agent: c.agent, state: regd.has(c.client) ? "installed" : "missing" })),
196
284
  ...(note ? { note } : {}),
197
- rea: { installed, latest, update: !!(latest && installed && newer(latest, installed)), outside: on && !saved, clients: reaClients(home).map((c) => c.client) },
285
+ rea: { installed, latest, update: !!(latest && installed && newer(latest, installed)), outside: on && !saved, clients: reaClients(home).map((c) => c.client), node },
198
286
  };
199
287
  }
@@ -8,7 +8,7 @@ import * as R from './task-results.ts';
8
8
  import { read as scalar } from './config-values.ts';
9
9
  import { detectDefaultAgent, home, readInbox, writeInbox, replaceTask, abandonRun, setArchived, readRuns, readText, saveAttachment, acceptance, gateOf } from './state.ts';
10
10
 
11
- type Hooks = { launch: (state:string, run:string, text:string, task:T.Task, pick?:any) => {ok:boolean; pty?:string; why?:string}; alive:(pty:string)=>boolean; stop:(pty:string)=>boolean };
11
+ type Hooks = { launch: (state:string, run:string, text:string, task:T.Task, pick?:any) => {ok:boolean; pty?:string; why?:string}; alive:(pty:string)=>boolean; stop:(pty:string)=>boolean; find?:(state:string,run:string)=>string|undefined };
12
12
  const runtimeLaunches = new Set<string>();
13
13
  const parse = (file:string) => { try { return JSON.parse(readFileSync(file,'utf8')); } catch { return null; } };
14
14
  const put = (file:string,value:unknown) => { const temp = file + `.${process.pid}.${randomUUID()}.tmp`; writeFileSync(temp,JSON.stringify(value,null,2)+'\n'); renameSync(temp,file); };
@@ -18,13 +18,29 @@ export const taskDefaults = (state:string) => ({ agent: detectDefaultAgent(dirna
18
18
  export function resultViews(state:string,id:string) {
19
19
  return R.listResults(state,id).map((r:any)=>({...r,createdAt:r.createdAt??r.created,summary:r.summary??'',checks:r.checks??r.validation??[],artifacts:r.artifacts.map((a:any)=>({...a,url:a.url??`/task-artifact?dir=${encodeURIComponent(state)}&task=${id}&result=${r.id}&artifact=${a.id}`,preview:a.preview??'download'}))}));
20
20
  }
21
- export function taskView(state:string,task:T.Task) {
21
+ // The one place that says which buttons a task may use; the page only draws this list and taskAction refuses the rest.
22
+ const agentKey=(state:string,t:T.Task,hooks?:Hooks)=>t.launch?.pty??(t.activeRun?hooks?.find?.(state,t.activeRun):undefined);
23
+ export function allowedActions(state:string,task:T.Task,hooks?:Hooks) {
24
+ const run=runState(state,task),finished=!!run&&(['done','abandoned'].includes(run.stage)||!!run.healed),live=!!task.activeRun&&!!run&&!finished;
25
+ const key=agentKey(state,task,hooks),alive=!!(key&&hooks?.alive(key));
26
+ let accept=false,acceptWhy:string|undefined;
27
+ try{T.acceptTask(structuredClone(task),task.currentResult??'');accept=true;}catch{/* not acceptable now */}
28
+ if(accept&&run&&!finished){accept=false;acceptWhy='The workflow is still reviewing this result';}
29
+ else if(accept&&run?.awaiting&&!run.healed){accept=false;acceptWhy='Resolve the blocking workflow decision first.';}
30
+ return {accept,...(acceptWhy?{acceptWhy}:{}),
31
+ stop:(live&&['draft','waiting','working','ready'].includes(task.status))||(['failed','interrupted','working'].includes(task.status)&&alive),
32
+ // A ready task whose run is still in review but whose agent is gone can only finish by relaunching it.
33
+ resume:(['interrupted','failed','stopping'].includes(task.status)||(task.status==='ready'&&live))&&!alive,
34
+ abandon:live||task.status==='stopping',archive:true,delete:!task.runIds.length&&!task.activeRun,
35
+ start:task.status==='draft'&&!task.activeRun&&!task.currentResult&&!!task.project};
36
+ }
37
+ export function taskView(state:string,task:T.Task,hooks?:Hooks) {
22
38
  const p=T.taskProjection(task);
23
39
  const run=runState(state,task), finished=run&&(['done','abandoned'].includes(run.stage)||run.healed);
24
- return {...task,activeRun:finished&&['ready','accepted'].includes(task.status)?null:task.activeRun,projectName:task.project?.split(/[\\/]/).pop()??'Choose a project',dir:state,updatedAt:task.updated,attention:{category:p.filter,reason:p.reason,action:p.action},statusLabel:p.label,decision:!task.project?{id:'project',kind:'project',text:'Choose a named project for your saved goal.'}:task.pendingDecision,messages:task.events,runs:task.runIds,currentResultId:task.currentResult,acceptedResultId:task.acceptedResult};
40
+ return {...task,actions:allowedActions(state,task,hooks),...(hooks?{agentAlive:!!(agentKey(state,task,hooks)&&hooks.alive(agentKey(state,task,hooks)!))}:{}),activeRun:finished&&['ready','accepted'].includes(task.status)?null:task.activeRun,projectName:task.project?.split(/[\\/]/).pop()??'Choose a project',dir:state,updatedAt:task.updated,attention:{category:p.filter,reason:p.reason,action:p.action},statusLabel:p.label,decision:!task.project?{id:'project',kind:'project',text:'Choose a named project for your saved goal.'}:task.pendingDecision,messages:task.events,runs:task.runIds,currentResultId:task.currentResult,acceptedResultId:task.acceptedResult};
25
41
  }
26
42
  export function taskList(states:string[],hooks?:Hooks) {
27
- const tasks=states.flatMap(state=>T.listTasks(state).filter(t=>!t.archived).map(t=>taskView(state,reconcile(state,t,hooks))));
43
+ const tasks=states.flatMap(state=>T.listTasks(state).filter(t=>!t.archived).map(t=>taskView(state,reconcile(state,t,hooks),hooks)));
28
44
  // Legacy rows become durable only when opened. Stable keys include stamps/index,
29
45
  // never a title-based merge; existing inbox and run files are left intact.
30
46
  for(const state of states) {
@@ -42,12 +58,28 @@ export function taskList(states:string[],hooks?:Hooks) {
42
58
  const readTextSafe=(f:string)=>{try{return readText(f);}catch{return null;}};
43
59
  export function reconcile(state:string,task:T.Task,hooks?:Hooks):T.Task {
44
60
  let reason='';
45
- if(task.status==='stopping'&&task.launch?.pty&&hooks&&!hooks.alive(task.launch.pty))return T.mutateTask(state,task.id,{revision:task.revision,opId:`stopped:${task.launch.id}`},T.confirmStopped);
61
+ if(T.normalizePause(structuredClone(task)))task=T.mutateTask(state,task.id,{revision:task.revision,opId:`heal:${task.revision}`},t=>{T.normalizePause(t);});
62
+ // The run finished with a saved result and nothing left to apply: the task is ready, whatever became of the agent.
63
+ // Not while its agent is still alive: clearing launch would stop tracking it; the heal runs once it ends.
64
+ if(['working','interrupted'].includes(task.status)&&task.currentResult&&!task.pendingDecision&&task.inputs.every(i=>['applied','failed'].includes(i.state))&&!(hooks&&task.launch?.pty&&hooks.alive(task.launch.pty))){
65
+ const run=runState(state,task);
66
+ if(run&&(run.stage==='done'||run.healed))return T.mutateTask(state,task.id,{revision:task.revision,opId:`finished:${task.revision}`},t=>{t.status='ready';t.safe=true;t.writePhase=false;t.queuePaused=false;t.error=undefined;t.launch=null;T.addEvent(t,'system','finished','The run finished and the saved result is ready to review.');});
67
+ }
68
+ if(task.status==='stopping'&&hooks){
69
+ // Stop is finished when the terminal is gone, or when there is none to wait for. A live one is asked again.
70
+ const key=agentKey(state,task,hooks);
71
+ if(key&&hooks.alive(key)){hooks.stop(key);return task;}
72
+ return T.mutateTask(state,task.id,{revision:task.revision,opId:`stopped:${task.revision}`},t=>stopped(t,key));
73
+ }
46
74
  if(task.launch && ['intent','started'].includes(task.launch.phase) && !runtimeLaunches.has(task.launch.id) && hooks && !(task.launch.pty&&hooks.alive(task.launch.pty))) reason='The launch was interrupted before the agent acknowledged it. Review the existing session before resuming.';
47
75
  else if(task.status==='working'&&task.launch?.pty&&hooks&&!hooks.alive(task.launch.pty)&&!task.safe)reason='The agent ended before reporting a safe handback. Your requests and previous results are saved.';
48
76
  if(reason) return T.mutateTask(state,task.id,{revision:task.revision,opId:`interrupted:${task.launch?.id}`},t=>{T.recoverLaunch(t);t.status='interrupted';t.error=reason;t.queuePaused=true;});
49
77
  return task;
50
78
  }
79
+ function stopped(t:T.Task,key?:string) {
80
+ T.confirmStopped(t);
81
+ if(!key)T.addEvent(t,'system','stop-unverified','No agent terminal was found on this board. If the agent runs somewhere else it may still be working. Resume starts a new session.');
82
+ }
51
83
  function runState(state:string,task:T.Task) { return task.activeRun?parse(join(state,'runs',task.activeRun,'state.json')):null; }
52
84
  export function dispatchReady(state:string,id:string,hooks:Hooks,initial=false,pick?:any):T.Task {
53
85
  let task=T.readTask(state,id)!;
@@ -115,23 +147,30 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
115
147
  return {state,task};
116
148
  }
117
149
  const found=T.resolveTask(state,String(body.id??''));if(!found)throw new T.TaskError('Unknown task',404);state=found.state;let task=reconcile(state,found.task,hooks);
118
- const mutation={revision:Number(body.revision),opId:operationId};
150
+ // Reconcile may bump the revision between the page's read and this call; a page that held the revision read just before it is not stale.
151
+ const mutation={revision:Number(body.revision)===found.task.revision&&['stop','abandon','archive'].includes(op)?task.revision:Number(body.revision),opId:operationId};
119
152
  if(task.operations.includes(operationId))return {state,task};
153
+ const allowed=allowedActions(state,task,hooks);
120
154
  if(op==='start'){task=T.mutateTask(state,task.id,mutation,t=>{if(t.status!=='draft')throw new T.TaskError('Task already started');});return {state,task:dispatchReady(state,task.id,hooks,true,body.pick&&typeof body.pick==='object'?body.pick:undefined)};}
121
155
  if(op==='delete'||op==='archive'||op==='abandon'){
122
156
  // Closing a task: Delete only before any run exists; Archive hides it; Abandon ends its run.
123
157
  if(op==='delete'){
124
- if(task.runIds.length||task.activeRun)throw new T.TaskError('A run already started. Archive or abandon it instead.');
158
+ if(!allowed.delete)throw new T.TaskError('A run already started. Archive or abandon it instead.');
125
159
  replaceTask(state,task.goal,null);T.deleteTask(state,task.id);return {state,task};
126
160
  }
127
- if(op==='abandon'){
128
- if(!task.activeRun)throw new T.TaskError('No run to abandon');
129
- const key=task.launch?.pty;if(key&&hooks.alive(key))hooks.stop(key);
130
- const bad=abandonRun(state,task.activeRun,String(body.why??'').trim()||'abandoned from the task page');if(bad)throw new T.TaskError(bad);
131
- }else if(task.activeRun)setArchived(state,task.activeRun,true);
132
- else{const lines=readInbox(state),at=lines.findIndex(l=>l.status==='open'&&l.text===task.goal);if(at>=0){lines[at]={...lines[at]!,status:'archived'};writeInbox(state,lines);}}
133
- return {state,task:T.mutateTask(state,task.id,mutation,t=>{t.archived=true;})};
161
+ if(op==='abandon'&&!task.activeRun)throw new T.TaskError('No run to abandon');
162
+ // Side effects run inside the mutation, after the revision check and under the task lock, so a stale page changes nothing.
163
+ // A run that is already done, already abandoned or gone counts as success: the task is archived either way.
164
+ return {state,task:T.mutateTask(state,task.id,mutation,t=>{
165
+ if(op==='abandon'){
166
+ const run=runState(state,t);
167
+ if(run&&!['done','abandoned'].includes(run.stage)){const key=agentKey(state,t,hooks);if(key&&hooks.alive(key))hooks.stop(key);const bad=abandonRun(state,t.activeRun!,String(body.why??'').trim()||'abandoned from the task page');if(bad)throw new T.TaskError(bad);}
168
+ }else if(t.activeRun)setArchived(state,t.activeRun,true);
169
+ else{const lines=readInbox(state),at=lines.findIndex(l=>l.status==='open'&&l.text===t.goal);if(at>=0){lines[at]={...lines[at]!,status:'archived'};writeInbox(state,lines);}}
170
+ t.archived=true;
171
+ })};
134
172
  }
173
+ if(op==='stop'&&!allowed.stop)return {state,task};
135
174
  task=T.mutateTask(state,task.id,mutation,t=>{
136
175
  if(op==='message'){
137
176
  const text=String(body.text??'').trim();const status=body.intent==='question'||/^\s*(status\??|what(?:'s| is) (?:the )?(?:status|progress)\??|how (?:is|are) (?:it|things|the task) (?:going|doing)\??)\s*$/i.test(text);
@@ -140,10 +179,9 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
140
179
  T.receiveInput(t,{id:operationId,text,intent:answer?'answer':'change',baseResult:body.baseResultId??null});
141
180
  if(answer||t.pendingDecision?.kind==='proposal'){t.pendingDecision=null;t.safe=true;t.status='draft';}
142
181
  }else if(op==='stop'){T.requestStop(t);}
143
- else if(op==='resume'){if(t.launch?.pty&&hooks.alive(t.launch.pty))throw new T.TaskError('The existing agent is still alive. Stop it or reconcile it in Technical details before resuming.');T.resumeTask(t);}
182
+ else if(op==='resume'){const key=agentKey(state,t,hooks);if(key&&hooks.alive(key))throw new T.TaskError('The existing agent is still alive. Stop it or reconcile it in Technical details before resuming.');if(!allowed.resume)throw new T.TaskError('This task does not need recovery');T.resumeTask(t);}
144
183
  else if(op==='accept'){
145
- const run=runState(state,t);if(run&&!['done','abandoned'].includes(run.stage)&&!run.healed)throw new T.TaskError('Workflow checks are still running. Wait for completed work before accepting.');
146
- if(run?.awaiting&&!run.healed)throw new T.TaskError('Resolve the blocking workflow decision first.');
184
+ if(!allowed.accept)throw new T.TaskError(allowed.acceptWhy??'Finish the active work and pending decisions before accepting this result');
147
185
  T.acceptTask(t,String(body.resultId??''));
148
186
  }else if(op==='confirm'){
149
187
  const d=t.pendingDecision;if(!d||d.kind!=='proposal'||d.id!==body.decisionId||d.run!==t.activeRun||d.result!==t.currentResult)throw new T.TaskError('This proposal changed. Refresh and review it again.');
@@ -156,9 +194,10 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
156
194
  }else throw new T.TaskError('Unknown task action',400);
157
195
  });
158
196
  if(op==='stop'){
159
- const key=task.launch?.pty;if(key&&hooks.alive(key))hooks.stop(key);
160
- else if(key)task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':stopped'},T.confirmStopped);
161
- else task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':unsupported'},t=>{t.error='This agent is outside the board. Stop it in Technical details and confirm its session has ended before resuming.';});
197
+ const key=agentKey(state,task,hooks);
198
+ if(key&&hooks.alive(key))hooks.stop(key);
199
+ else try{task=T.mutateTask(state,task.id,{revision:task.revision,opId:operationId+':stopped'},t=>stopped(t,key));}
200
+ catch{task=T.readTask(state,task.id)!;/* the pump confirmed the stop first: same outcome */}
162
201
  }else if(['message','confirm','resume'].includes(op))task=dispatchReady(state,task.id,hooks,op==='resume'&&!task.inputs.some(i=>['queued','received'].includes(i.state)));
163
202
  return {state,task};
164
203
  }
@@ -166,6 +205,7 @@ export function taskAction(state:string,body:any,hooks:Hooks):{state:string;task
166
205
  // CLI-only structured events. Raw terminal text is never an acknowledgement.
167
206
  export function taskEvent(state:string,id:string,runId:string,event:any,operationId:string):T.Task {
168
207
  const task=T.readTask(state,id);if(!task||task.activeRun!==runId)throw new T.TaskError('This run does not own the task');
208
+ let preserving=false;
169
209
  try { return T.mutateTask(state,id,{revision:task.revision,opId:operationId},t=>{
170
210
  const run=runState(state,t);if(!run||run.task_id!==id)throw new T.TaskError('Run task identity does not match');
171
211
  if(event.type==='ack'){T.acknowledgeLaunch(t,String(event.launchId),runId,t.launch?.pty);}
@@ -183,11 +223,21 @@ export function taskEvent(state:string,id:string,runId:string,event:any,operatio
183
223
  else if(event.type==='result'){
184
224
  if(run.task_policy?.requirePlanConfirmation&&!run.task_confirmed)throw new T.TaskError('Proposal confirmation is required');
185
225
  if(t.inputs.some(i=>i.state==='dispatched'))throw new T.TaskError('Acknowledge the dispatched requests before publishing a result');
186
- const result=R.publishResult(state,id,{...event,runId,iteration:run.iteration??0,roots:[dirname(state),...(typeof run.worktree==='string'?[run.worktree]:[])],id:stableUuid(`${id}:${runId}:${operationId}`)});
187
- t.currentResult=result.id;t.acceptedResult=null;t.status='ready';t.safe=true;t.pendingDecision=null;if(t.launch)t.launch.phase='acknowledged';T.addEvent(t,'assistant','result',String(event.summary??event.title??'Result ready'));
226
+ preserving=true;const result=R.publishResult(state,id,{...event,runId,iteration:run.iteration??0,roots:[dirname(state),...(typeof run.worktree==='string'?[run.worktree]:[])],id:stableUuid(`${id}:${runId}:${operationId}`)});
227
+ preserving=false;
228
+ // A result that lands while the task is stopping is saved, but the stop stands.
229
+ if(['stopping','interrupted'].includes(t.status)){t.currentResult=result.id;t.acceptedResult=null;T.addEvent(t,'assistant','result',String(event.summary??event.title??'Result ready'));return;}
230
+ t.currentResult=result.id;t.acceptedResult=null;t.status='ready';t.safe=true;t.pendingDecision=null;t.queuePaused=false;t.error=undefined;if(t.launch)t.launch.phase='acknowledged';T.addEvent(t,'assistant','result',String(event.summary??event.title??'Result ready'));
188
231
  }else throw new T.TaskError('Unknown task event',400);
189
232
  }); } catch (error) {
190
- if(event.type==='result'){const current=T.readTask(state,id)!;T.mutateTask(state,id,{revision:current.revision,opId:operationId+':preservation-failed'},t=>{t.error=(error as Error).message;t.status='failed';t.queuePaused=true;T.addEvent(t,'system','preservation-failed',`This result could not be preserved. ${t.error} Earlier saved results remain available.`);});}
233
+ if(event.type==='result'){
234
+ const current=T.readTask(state,id)!,disk=preserving&&((error as T.TaskError).status===507||!(error instanceof T.TaskError));
235
+ // Only a failed copy to disk pauses the task. A refused result (unreceipted input, unconfirmed proposal, bad output) is fixed and published again.
236
+ T.mutateTask(state,id,{revision:current.revision,opId:operationId+':preservation-failed'},t=>{
237
+ if(disk){t.error=(error as Error).message;t.status='failed';t.queuePaused=true;T.addEvent(t,'system','preservation-failed',`This result could not be preserved. ${t.error} Earlier saved results remain available.`);}
238
+ else T.addEvent(t,'system','result-refused',`The result was not accepted yet: ${(error as Error).message}. The agent can fix this and publish again.`);
239
+ });
240
+ }
191
241
  throw error;
192
242
  }
193
243
  }
package/cli/tasks.ts CHANGED
@@ -179,13 +179,19 @@ export function recoverLaunch(task: Task) {
179
179
  export function requestStop(task: Task) { task.queuePaused = true; task.status = "stopping"; task.safe = false; addEvent(task, "system", "stop", "Stop requested. Waiting for the agent to stop; existing edits are retained."); }
180
180
  export function confirmStopped(task: Task) { if (task.status !== "stopping") throw new TaskError("Stop was not requested"); task.status = "interrupted"; if (task.launch) task.launch.phase = "interrupted"; addEvent(task, "system", "stopped", "The agent stopped. Queued requests are saved. This does not undo edits."); }
181
181
  export function resumeTask(task: Task) {
182
- if (!["interrupted", "failed"].includes(task.status)) throw new TaskError("This task does not need recovery");
182
+ if (!["interrupted", "failed", "stopping", "ready"].includes(task.status)) throw new TaskError("This task does not need recovery");
183
183
  task.queuePaused = false; task.safe = true; task.launch = null; task.error = undefined;
184
184
  // Explicit recovery preserves ids and makes ambiguous work visible for reconciliation.
185
185
  for (const i of task.inputs) if (i.state === "dispatched" || i.state === "failed") i.state = "queued";
186
186
  task.status = task.currentResult ? "ready" : "draft";
187
187
  addEvent(task, "system", "resume", "Resume requested. Reconcile existing edits before applying the saved requests.");
188
188
  }
189
+ // A pause only means something while the task is stopping, interrupted or failed. Anywhere else it
190
+ // is a leftover that blocks Looks good, so it is cleared. Returns whether anything changed.
191
+ export function normalizePause(task: Task): boolean {
192
+ if (["stopping", "interrupted", "failed"].includes(task.status) || !(task.queuePaused || task.error)) return false;
193
+ task.queuePaused = false; task.error = undefined; return true;
194
+ }
189
195
  export function acceptTask(task: Task, result: string) {
190
196
  if (!result || result !== task.currentResult) throw new TaskError("This result is no longer current");
191
197
  if (task.status !== "ready" || !task.safe || task.writePhase || task.pendingDecision || task.queuePaused || task.inputs.some((i) => !["applied", "failed"].includes(i.state))) throw new TaskError("Finish the active work and pending decisions before accepting this result");
package/cli/web.ts CHANGED
@@ -290,9 +290,12 @@ export async function web(repoDir: string, opts: Opts = {}) {
290
290
  },
291
291
  alive: (key: string) => ptyState(key)?.alive === true,
292
292
  stop: (key: string) => killPty(key),
293
+ find: (dir: string, run: string) => liveAgent(dir, run)?.key,
293
294
  };
294
295
  const taskPump = setInterval(() => {
295
296
  for (const dir of states(true)) for (const task of tasks.listTasks(dir)) {
297
+ // A stopping task is asked to stop again until its terminal is gone, not only when someone opens it.
298
+ if (task.status === "stopping" && !task.archived) { try { if (taskService.reconcile(dir, task, taskHooks).revision !== task.revision) changed(); } catch { /* next pass */ } continue; }
296
299
  if (!task.safe || task.queuePaused || task.pendingDecision || !task.inputs.some(i => i.state === "queued")) continue;
297
300
  try { taskService.dispatchReady(dir, task.id, taskHooks); changed(); } catch { /* CAS conflict: next pass reads the new state */ }
298
301
  }
@@ -1509,7 +1512,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
1509
1512
  if (path === "/task-artifact") return taskArtifactResponse(found.state, found.task.id, url.searchParams.get("result") ?? "", url.searchParams.get("artifact") ?? "", req, url.searchParams.get("download") === "1");
1510
1513
  let task = taskService.reconcile(found.state, found.task, taskHooks);
1511
1514
  if (task.safe && !task.queuePaused && !task.pendingDecision && task.inputs.some(i => i.state === "queued")) task = taskService.dispatchReady(found.state, task.id, taskHooks);
1512
- return json({ task: taskService.taskView(found.state, task), results: taskService.resultViews(found.state, task.id), projects: taskProjects(), defaults: taskService.taskDefaults(found.state) });
1515
+ return json({ task: taskService.taskView(found.state, task, taskHooks), results: taskService.resultViews(found.state, task.id), projects: taskProjects(), defaults: taskService.taskDefaults(found.state) });
1513
1516
  } catch (e) { return bad((e as Error).message, e instanceof tasks.TaskError ? e.status : 400); }
1514
1517
  }
1515
1518
 
@@ -1830,7 +1833,16 @@ export async function web(repoDir: string, opts: Opts = {}) {
1830
1833
  rea.forgetDoctor(); rea.forgetLatest();
1831
1834
  return r.ok ? json(r) : bad(r.why);
1832
1835
  }
1833
- return bad("step: plan, apply or off");
1836
+ // Node.js for REA: runs only the command nodeFix builds here, after the page's confirm
1837
+ // and with the one-time token the Skills page got; never a command from the request.
1838
+ if (body?.step === "node") {
1839
+ const tokenOk = !!skillToken && body?.token === skillToken;
1840
+ skillToken = "";
1841
+ if (body?.confirm !== true || !tokenOk) return bad("confirm required");
1842
+ const r = await rea.installNode();
1843
+ return r.ok ? json({ ok: true }) : bad(r.why);
1844
+ }
1845
+ return bad("step: plan, apply, off or node");
1834
1846
  }
1835
1847
 
1836
1848
  // Per user, so no scope. A saved environment value is never in either answer.
@@ -2270,14 +2282,14 @@ export async function web(repoDir: string, opts: Opts = {}) {
2270
2282
  if (!destination || !states(true).includes(destination) || destination === join(home, ".kaizen")) return bad("Choose a named project", 400);
2271
2283
  const task = tasks.transferDraft(found.state, found.task.id, destination, dirname(destination));
2272
2284
  const result = taskService.taskAction(destination, { op: "start", id: task.id, revision: task.revision, operationId: String(body.operationId) + ":start" }, taskHooks);
2273
- changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task) });
2285
+ changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task, taskHooks) });
2274
2286
  }
2275
2287
  if (!["create", "adopt"].includes(body.op)) {
2276
2288
  const found = tasks.resolveTask(dir, String(body.id ?? ""));
2277
2289
  if (!found || !states(true).includes(found.state)) return bad("unknown task", 404);
2278
2290
  }
2279
2291
  const result = taskService.taskAction(dir, body, taskHooks);
2280
- changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task) });
2292
+ changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task, taskHooks) });
2281
2293
  } catch (e) { return bad((e as Error).message, e instanceof tasks.TaskError ? e.status : 400); }
2282
2294
  }
2283
2295
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.85.2",
3
+ "version": "1.86.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": {
@@ -239,7 +239,8 @@ input ids; acknowledge the launch before doing anything else:
239
239
  publishes a typed version. Paths must be regular files inside the project/worktree.
240
240
  Do not snapshot source trees or databases. HTML/SVG files download only. Include
241
241
  specialized Video identity as `video:{name,letter,revision}` when relevant, without
242
- changing its recipes. A copy/disk failure retains earlier versions and needs recovery.
242
+ changing its recipes. A refused result does not pause the task; fix the cause and publish again.
243
+ Only a failed copy to disk pauses it, retains earlier versions and needs recovery.
243
244
 
244
245
  A question/status reply never authorizes production. Queued change requests are not
245
246
  already applied: keep their ids and report receipts. Stop requests cancellation and
@@ -0,0 +1,60 @@
1
+ ---
2
+ name: disk-cleanup
3
+ description: Audit disk usage on this PC and clean it up safely. Shows terminal box charts of what is fat (home dirs, Steam games, caches, rebuildable build output), then a verdict panel and a pick-what-to-delete question. Use when the user asks to tidy files and dirs, free disk space, find what is safe to delete, prune caches, or "what is eating my disk".
4
+ ---
5
+
6
+ # Disk cleanup
7
+
8
+ Audit first, delete only what the user picks. Never delete without an explicit pick.
9
+
10
+ ## Rules learned the hard way
11
+
12
+ - **Verify before saying "safe".** Look inside (`ls`, `du`, `diff -rq`, read `project.json`) before calling anything cache or a copy. A dir named `.cache` can hold a venv, a backup, or project history.
13
+ - **Never total unlike things.** A sum of cache dirs is not "reclaimable". Report each group on its own and state what is regenerable and what is not.
14
+ - **Use real numbers.** Say what a number is (apparent vs on-disk). The disk is btrfs with zstd, so use `du -x` and `df -h /home`.
15
+ - Delete only on a pick. Prefer move-to-Archive for anything not obviously regenerable.
16
+ - Report outcomes faithfully: freed space comes from `df` before/after, not from the plan.
17
+
18
+ ## Procedure
19
+
20
+ 1. **Overview.** `df -h /home`, then `du -xsh ~/.[!.]* ~/* | sort -rh | head -25`. Expect `~/.local/share/Steam` to dominate; drill into it separately.
21
+ 2. **Drill the fat ones** with `du -xh --max-depth=1 <dir> | sort -rh | head`:
22
+ - Steam: `steamapps/common`, `shadercache`, `compatdata`. Game name, size and last played come from `steamapps/appmanifest_*.acf` (`name`, `SizeOnDisk`, `LastPlayed`; missing or 0 = never played).
23
+ - Projects: rebuildable output = `node_modules`, `target`, `.next`, `dist` (`find Projects -name node_modules -type d -prune`).
24
+ - `~/.cache`, `~/.config` browser profiles, `~/.hermes`, `~/.local/share/mise/installs` (old tool versions).
25
+ 3. **Round 1: show charts, then ask where to go.** Print the box charts as chat text (see Format), then `AskUserQuestion` with: explore outside Steam / explore Steam / continue to cleanup. Do the exploration the user picks, show new boxes, ask again.
26
+ 4. **Round 2: verdict, then ask what to run.** Print the verdict panel as chat text, then `AskUserQuestion` (multiSelect, max 4 options; overflow items go via "Other") whose options are the verdict rows.
27
+ 5. **Run only the picks.** Close Steam before touching `steamapps`. Re-run `df -h /home` and report freed space.
28
+
29
+ ## Verdict tiers
30
+
31
+ | Tier | Meaning | Examples |
32
+ |---|---|---|
33
+ | ✓ SAFE NOW | regenerates, no work lost | Steam `shadercache`, `node_modules`/`target`/`.next`, `.zcompdump`, empty dirs, stale `.claude.json.tmp.*` |
34
+ | ✓ RE-DOWNLOAD | recoverable, costs time | never-played Steam games, model caches under `~/.cache/huggingface` |
35
+ | ? YOUR CALL | depends on use | idle games (2+ months), old `mise` versions, VMs, headless browser profiles |
36
+ | ✗ KEEP | never offer | `Projects` source, `Documents`, `.ssh`, `.gnupg`, `.kaizen`, `Games/roms` |
37
+
38
+ Watch for: `whisperx-venv` is a venv, not cache; `kaizen-video` needs it. Desktop shortcuts in `~` for a "never played" game mean the user may be about to play it.
39
+
40
+ ## Format
41
+
42
+ Boxes are 38 wide, two per row. No scale text in the title: the title is bold, the top-right shows the box's used total and a 5-cell gauge. Sizes show as TB, GB, MB or KB (never bare `G`); a blank line separates the title from the rows. Row bars fill the width up to the right-aligned size column and scale to the box's biggest row (`▌` half, `▏` under one half-cell). Mark never-played games `✗`.
43
+
44
+ Gauge = box total ÷ the limit (the disk size for HOME and STEAM boxes; the biggest dir's parent for others). Each filled cell is an emoji square coloured by that ratio: 🟩 <50%, 🟨 <75%, 🟧 <90%, 🟥 ≥90%; empty cells are ⬜. Both are 2 cells wide, so `box` counts them double. Bold titles use Unicode bold letters (`𝗛𝗢𝗠𝗘`) because markdown bold does not work inside a code block. Never hand-draw boxes: import the shared component `tui.py` (same dir as this file) for every report that uses a box.
45
+
46
+ ```python
47
+ import sys, os; sys.path.insert(0, os.path.expanduser("~/.claude/skills/disk-cleanup"))
48
+ from tui import box, panel, render, storage, GB, MB, KB
49
+ render(box("HOME", [("Steam", GB(1500)), ("Projects", GB(52))], GB(1552), GB(1900)), box("CACHE", [("huggingface", GB(12)), ("tmp", MB(300), "✗")], GB(12), GB(1900)))
50
+ ```
51
+
52
+ `box(title, [(name, bytes, flag?)], used, limit)` makes a bold-title box: sizes in bytes (`GB()`, `MB()`, `KB()` build them; shown as GB, MB, KB), bars fill the row up to the size column and scale to the box's biggest row, the top-right gauge is box total vs `limit`; `panel(title, [(line, note)], foot)` the verdict panel; `render` prints two per row. `storage([(label, bytes)], total, free)` returns the full-width DISK box: one bar split by pattern (█ ▓ ▒, then ░ other, blank free; chat text cannot colour per section), real disk size top-right, and a one-line legend underneath (short lowercase labels, sizes without a space, so it fits one line). Print it above every chart set, using disjoint sections (e.g. steam games, steam other, home rest) and the real `df` total and free. A box total must be the real `du` figure, not the sum of the rows shown.
53
+
54
+ Every box line must be 40 cells wide by `w()` (emoji = 2); check before printing.
55
+
56
+ Verdict panel: `panel()`, one numbered row per option (`[1] ✓ SAFE NOW <what> <size>` with a `└` note line), a `✗ KEEP` footer.
57
+
58
+ The user sees chat text and the question dialog, but a question dialog shows only its own text, so charts go in chat before the call, never inside the question.
59
+
60
+ **Bash output is collapsed in the user's terminal ("Ran 2 shell commands"), so a chart printed by `render` is invisible.** After running `tui.py`, copy its output verbatim into your own reply inside a ``` code block, before the `AskUserQuestion` call. Never ask "next step?" until the chart is in reply text. Same for the verdict panel.
@@ -0,0 +1 @@
1
+ {"title": "Disk cleanup", "group": "optional", "status": "beta", "needs": ["python3"]}
@@ -0,0 +1,90 @@
1
+ """Shared box/panel component for disk-cleanup reports.
2
+ Use: sys.path.insert(0, os.path.expanduser("~/.claude/skills/disk-cleanup")); from tui import *
3
+ Sizes are bytes everywhere. Helpers: GB(n), MB(n), KB(n) build bytes."""
4
+ W = 38 # box inner width
5
+ KB = lambda n: int(n * 1024)
6
+ MB = lambda n: int(n * 1024**2)
7
+ GB = lambda n: int(n * 1024**3)
8
+
9
+ def size(b):
10
+ """Bytes -> '1.5 TB' / '1500 GB' / '52 MB' / '4 KB' / '0 B' (TB from 1024 GB)."""
11
+ for u, d in (("TB", 1024**4), ("GB", 1024**3), ("MB", 1024**2), ("KB", 1024)):
12
+ if b >= d:
13
+ v = b / d
14
+ return f"{v:.0f} {u}" if v >= 10 else f"{v:.1f} {u}"
15
+ return f"{b} B"
16
+
17
+ def bold(s):
18
+ return "".join(chr(0x1D5D4+ord(c)-65) if "A"<=c<="Z" else chr(0x1D5EE+ord(c)-97) if "a"<=c<="z" else chr(0x1D7EC+ord(c)-48) if c.isdigit() else c for c in s)
19
+
20
+ def w(s):
21
+ """Display width: emoji squares = 2 cells."""
22
+ return sum(2 if ord(c) >= 0x1F000 or c == "⬜" else 1 for c in s)
23
+
24
+ def gauge(used, limit, n=5):
25
+ r = used / limit; f = min(n, round(r * n))
26
+ c = "🟩" if r < .5 else "🟨" if r < .75 else "🟧" if r < .9 else "🟥"
27
+ return c * f + "⬜" * (n - f)
28
+
29
+ def bar(b, top, bw):
30
+ h = round(b / top * bw * 2) # half-cells, scaled to the box's biggest row
31
+ return ("▏" if h == 0 else "█" * (h // 2) + ("▌" if h % 2 else "")).ljust(bw)
32
+
33
+ def box(title, rows, used, limit):
34
+ """rows = [(name, bytes, flag)]; flag optional ('✗'). Bars scale to the box's biggest row; gauge shows box total vs limit."""
35
+ rows = [(r + ("",))[:3] for r in rows]
36
+ top = max(b for _, b, _ in rows)
37
+ lw = max(len(n) for n, _, _ in rows)
38
+ sw = max(len(size(b)) for _, b, _ in rows)
39
+ fw = max(len(f) for _, _, f in rows)
40
+ bw = W - 2 - lw - sw - 2 - (fw + 1 if fw else 0) # bar fills the gap
41
+ body = ["│ " + (f"{n:<{lw}} {bar(b, top, bw)} {size(b):>{sw}}" + (f" {f}" if fw else "")).ljust(W - 1) + "│"
42
+ for n, b, f in rows]
43
+ tag = f"{size(used)} {gauge(used, limit)}"
44
+ head = "┌─ " + bold(title) + " " + "─" * (W - len(title) - w(tag) - 5) + " " + tag + " ┐"
45
+ return [head, "│" + " " * W + "│"] + body + ["└" + "─" * W + "┘"]
46
+
47
+ def side_by_side(a, b):
48
+ n = max(len(a), len(b)); a += [" " * 40] * (n - len(a)); b += [" " * 40] * (n - len(b))
49
+ return [x + " " * (41 - w(x)) + y for x, y in zip(a, b)]
50
+
51
+ def panel(title, rows, foot, pw=62):
52
+ """Verdict panel: rows = [(line, note)], double-line box."""
53
+ out = ["╔═ " + bold(title) + " " + "═" * (pw - len(title) - 3) + "╗"]
54
+ for i, (line, note) in enumerate(rows, 1):
55
+ out += ["║ " + f"[{i}] {line}".ljust(pw - 1) + "║", "║ " + f" └ {note}".ljust(pw - 1) + "║"]
56
+ return out + ["╠" + "═" * pw + "╣", "║ " + foot.ljust(pw - 1) + "║", "╚" + "═" * pw + "╝"]
57
+
58
+ FILL = "█▓▒" # block-element glyphs only (▤ ▚ fell back to another font and broke widths)
59
+
60
+ def storage(segments, total, free, title="DISK", width=79):
61
+ """Full-width disk bar in one box (Apple-storage style). segments = [(label, bytes)], disjoint,
62
+ drawn in order with patterns █ ▤ ▚ ░; rest of used = other (░ if free), unused = FREE (blank).
63
+ Top-right of the box = real disk size. Returns lines, same width as two boxes side by side."""
64
+ other = max(0, total - free - sum(b for _, b in segments))
65
+ parts = [(l, b, FILL[i % 3]) for i, (l, b) in enumerate(segments)] + [("other", other, "░"), ("free", free, " ")]
66
+ n = width - 2
67
+ raw = [b / total * n for _, b, _ in parts]
68
+ cells = [int(r) for r in raw]
69
+ for i in sorted(range(len(parts)), key=lambda i: raw[i] - cells[i], reverse=True)[: n - sum(cells)]:
70
+ cells[i] += 1
71
+ for i, (_, b, _) in enumerate(parts): # never hide a non-empty part
72
+ if b and not cells[i]:
73
+ cells[cells.index(max(cells))] -= 1; cells[i] = 1
74
+ legend, cur = [], ""
75
+ for l, b, c in parts:
76
+ item = f"{c} {l.lower()} {size(b).replace(' ', '')}".strip()
77
+ if cur and len(cur) + 2 + len(item) > n:
78
+ legend.append(cur); cur = item
79
+ else:
80
+ cur = f"{cur} {item}" if cur else item
81
+ legend.append(cur)
82
+ tag = size(total)
83
+ head = "┌─ " + bold(title) + " " + "─" * (width - len(title) - len(tag) - 5) + " " + tag + " ┐"
84
+ row = lambda t: "│ " + t.ljust(n) + " │"
85
+ return [head, row(""), row("".join(c * k for (_, _, c), k in zip(parts, cells)))] + [row(x) for x in legend] + ["└" + "─" * width + "┘"]
86
+
87
+ def render(*boxes):
88
+ """Print boxes two per row."""
89
+ for i in range(0, len(boxes), 2):
90
+ print("\n".join(side_by_side(boxes[i], boxes[i+1]) if i+1 < len(boxes) else boxes[i]))