kaizen-agent 1.79.1 → 1.80.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.
Files changed (50) hide show
  1. package/cli/hermes.ts +20 -0
  2. package/cli/install.ts +20 -1
  3. package/cli/localsend.ts +61 -4
  4. package/cli/report.ts +7 -4
  5. package/cli/settings.ts +2 -8
  6. package/cli/state.ts +19 -3
  7. package/cli/task-results.ts +133 -0
  8. package/cli/task-service.ts +180 -0
  9. package/cli/tasks.ts +201 -0
  10. package/cli/ui-audit.allow.json +6 -0
  11. package/cli/ui-audit.ts +427 -0
  12. package/cli/web.ts +72 -1
  13. package/cli/whatsapp.ts +112 -0
  14. package/package.json +2 -1
  15. package/skills/kaizen/SKILL.md +4 -0
  16. package/skills/kaizen/adapters.md +4 -0
  17. package/skills/kaizen/spec-build.md +5 -1
  18. package/skills/kaizen/spec-main.md +4 -0
  19. package/skills/kaizen/spec-plan.md +4 -0
  20. package/skills/kaizen/spec-review.md +4 -0
  21. package/skills/kaizen/spec.md +52 -0
  22. package/web/board/add-project.ts +1 -1
  23. package/web/board/badge.ts +70 -8
  24. package/web/board/cards.ts +4 -2
  25. package/web/board/dom.ts +10 -0
  26. package/web/board/icebox.ts +2 -2
  27. package/web/board/keys.ts +1 -1
  28. package/web/board/live.ts +9 -5
  29. package/web/board/phone.ts +4 -3
  30. package/web/board/rich.ts +4 -2
  31. package/web/board/run-view.ts +16 -14
  32. package/web/board/settings-automations.ts +2 -2
  33. package/web/board/settings-skills.ts +2 -2
  34. package/web/board/settings.ts +12 -14
  35. package/web/board/task-page.ts +672 -0
  36. package/web/board/task-results.ts +235 -0
  37. package/web/board/tasks.ts +214 -200
  38. package/web/board/terms.ts +17 -2
  39. package/web/board/views.ts +35 -9
  40. package/web/board/whatsapp-setup.ts +137 -0
  41. package/web/board/workspace.ts +24 -2
  42. package/web/board.html +57 -35
  43. package/web/board.js +403 -142
  44. package/web/notebook.js +388 -153
  45. package/web/notes.html +16 -11
  46. package/web/term.js +1 -1
  47. package/web/video.html +22 -11
  48. package/web/video.js +415 -180
  49. package/web/video.ts +5 -5
  50. package/web/board/new-agent.ts +0 -20
package/cli/tasks.ts ADDED
@@ -0,0 +1,201 @@
1
+ // Durable task identity is independent of inbox text and run lifecycle. Mutations
2
+ // use an exclusive disk lock plus revision checks, including across board processes.
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync, rmSync } from "node:fs";
4
+ import { join, resolve, sep } from "node:path";
5
+ import { randomUUID, createHash } from "node:crypto";
6
+
7
+ export type InputState = "received" | "queued" | "dispatched" | "applied" | "failed";
8
+ export type TaskInput = { id: string; text: string; intent: "change" | "answer" | "status"; at: number; state: InputState; baseResult: string | null; baseRun: string | null; error?: string };
9
+ export type TaskEvent = { id: string; at: number; role: "user" | "assistant" | "system"; type: string; text: string; inputIds?: string[] };
10
+ export type TaskDecision = { id: string; kind: "question" | "proposal" | "rebase"; text: string; run: string | null; iteration: number; result: string | null; options?: string[]; summary?: string; details?: string; runRevision?: number };
11
+ export type TaskLaunch = { id: string; run: string | null; inputIds: string[]; phase: "intent" | "started" | "acknowledged" | "interrupted"; at: number; pty?: string };
12
+ export type Task = {
13
+ schema: 1; id: string; title: string; goal: string; project: string | null; revision: number; created: number; updated: number;
14
+ status: "draft" | "waiting" | "working" | "ready" | "accepted" | "stopping" | "interrupted" | "failed";
15
+ runIds: string[]; activeRun: string | null; currentResult: string | null; acceptedResult: string | null;
16
+ pendingDecision: TaskDecision | null; inputs: TaskInput[]; events: TaskEvent[]; operations: string[];
17
+ files: { name: string; path: string }[]; launch: TaskLaunch | null; safe: boolean; queuePaused: boolean;
18
+ initialConfirmed: boolean; writePhase: boolean; error?: string; legacyKey?: string; alias?: { state: string; id: string };
19
+ };
20
+ export type Mutation = { revision: number; opId: string };
21
+ export class TaskError extends Error { constructor(message: string, public status = 409) { super(message); } }
22
+ export const taskId = (id: unknown): id is string => typeof id === "string" && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(id);
23
+ export function taskDir(state: string, id: string) {
24
+ if (!taskId(id)) throw new TaskError("Unknown task", 404);
25
+ const dir = join(state, "tasks", id);
26
+ const tasks = join(state, "tasks");
27
+ if (existsSync(tasks) && existsSync(state) && !realpathSync(tasks).startsWith(realpathSync(state) + sep)) throw new TaskError("Task storage is outside this project", 404);
28
+ if (existsSync(dir) && existsSync(state) && !realpathSync(dir).startsWith(realpathSync(state) + sep)) throw new TaskError("Task storage is outside this project", 404);
29
+ return dir;
30
+ }
31
+ const fileOf = (state: string, id: string) => join(taskDir(state, id), "task.json");
32
+ const json = (file: string) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; } };
33
+ function atomic(file: string, value: unknown) { const tmp = `${file}.${process.pid}.${randomUUID()}.tmp`; try { writeFileSync(tmp, JSON.stringify(value, null, 2), { mode: 0o600 }); renameSync(tmp, file); } finally { rmSync(tmp, { force: true }); } }
34
+ // Dead disk locks may be reclaimed; this is storage recovery only and never a
35
+ // safe-work boundary or permission to replay an unacknowledged launch.
36
+ export function acquireTaskLock(lock: string): () => void {
37
+ try { mkdirSync(lock); }
38
+ catch {
39
+ // Serialize reclaimers separately, then reread ownership. Otherwise two
40
+ // reclaimers could both observe a dead PID and the second steal a fresh lock.
41
+ const recovery = lock + ".recovery";
42
+ try { mkdirSync(recovery); } catch { throw new TaskError("Task lock recovery is in progress. Refresh and try again."); }
43
+ try {
44
+ const owner = json(join(lock, "owner.json")); let dead = false;
45
+ if (Number.isSafeInteger(owner?.pid) && owner.pid > 0) {
46
+ try { process.kill(owner.pid, 0); } catch (error) { dead = (error as NodeJS.ErrnoException).code === "ESRCH"; }
47
+ } else { try { dead = Date.now() - statSync(lock).mtimeMs > 30_000; } catch { /* another process acquired it */ } }
48
+ if (!dead) throw new TaskError("Task is being updated. Refresh and try again.");
49
+ const stale = `${lock}.stale-${randomUUID()}`;
50
+ try { renameSync(lock, stale); mkdirSync(lock); }
51
+ catch { throw new TaskError("Task is being updated. Refresh and try again."); }
52
+ finally { rmSync(stale, { recursive: true, force: true }); }
53
+ } finally { rmSync(recovery, { recursive: true, force: true }); }
54
+ }
55
+ writeFileSync(join(lock, "owner.json"), JSON.stringify({ pid: process.pid }), { mode: 0o600 });
56
+ return () => rmSync(lock, { recursive: true, force: true });
57
+ }
58
+ function locked<T>(state: string, id: string, fn: () => T): T {
59
+ const dir = taskDir(state, id); mkdirSync(dir, { recursive: true, mode: 0o700 });
60
+ const release = acquireTaskLock(join(dir, "mutation.lock"));
61
+ try { return fn(); } finally { release(); }
62
+ }
63
+ export function readTask(state: string, id: string): Task | null {
64
+ if (!taskId(id)) return null;
65
+ try { const t = json(fileOf(state, id)); return t?.schema === 1 && t.id === id && Array.isArray(t.inputs) && Array.isArray(t.events) ? t : null; } catch { return null; }
66
+ }
67
+ export function resolveTask(state: string, id: string): { state: string; task: Task } | null {
68
+ const seen = new Set<string>();
69
+ for (let n = 0; n < 8; n++) {
70
+ const key = resolve(state) + "\0" + id; if (seen.has(key)) return null; seen.add(key);
71
+ const task = readTask(state, id); if (!task) return null;
72
+ if (!task.alias) return { state, task };
73
+ state = task.alias.state; id = task.alias.id;
74
+ }
75
+ return null;
76
+ }
77
+ export function listTasks(state: string): Task[] {
78
+ try { return readdirSync(join(state, "tasks")).filter(taskId).map((id) => readTask(state, id)).filter((t): t is Task => !!t && !t.alias).sort((a, b) => taskProjection(a).rank - taskProjection(b).rank || b.updated - a.updated); } catch { return []; }
79
+ }
80
+ export type NewTask = { goal: string; title?: string; project?: string | null; files?: Task["files"] };
81
+ export function createTask(state: string, input: NewTask, opId?: string): Task {
82
+ if (!input.goal?.trim()) throw new TaskError("Describe what you want to make", 400);
83
+ // The operation-derived UUID makes a retry safe even after process restart.
84
+ const hash = opId ? createHash("sha256").update(opId).digest("hex") : null;
85
+ const id = hash ? `${hash.slice(0, 8)}-${hash.slice(8, 12)}-4${hash.slice(13, 16)}-a${hash.slice(17, 20)}-${hash.slice(20, 32)}` : randomUUID();
86
+ return locked(state, id, () => {
87
+ const existing = readTask(state, id); if (existing) return existing;
88
+ const now = Date.now();
89
+ const task: Task = { schema: 1, id, title: (input.title?.trim() || input.goal.trim().split("\n")[0]).slice(0, 160), goal: input.goal.trim(), project: input.project ?? null, revision: 0, created: now, updated: now, status: "draft", runIds: [], activeRun: null, currentResult: null, acceptedResult: null, pendingDecision: null, inputs: [], events: [{ id: randomUUID(), at: now, role: "user", type: "goal", text: input.goal.trim() }], operations: opId ? [opId] : [], files: input.files ?? [], launch: null, safe: true, writePhase: false, queuePaused: false, initialConfirmed: false };
90
+ atomic(fileOf(state, id), task); return task;
91
+ });
92
+ }
93
+ export function mutateTask(state: string, id: string, mutation: Mutation, update: (task: Task) => void): Task {
94
+ if (!mutation.opId || mutation.opId.length > 200) throw new TaskError("A request id is required", 400);
95
+ return locked(state, id, () => {
96
+ const task = readTask(state, id); if (!task || task.alias) throw new TaskError("Task moved or is unavailable. Refresh.", 404);
97
+ if (task.operations.includes(mutation.opId)) return task;
98
+ if (task.revision !== mutation.revision) throw new TaskError("This task changed while you were reading (agent progress or another window). Refresh before sending.");
99
+ update(task); task.revision++; task.updated = Date.now(); task.operations.push(mutation.opId);
100
+ atomic(fileOf(state, id), task); return task;
101
+ });
102
+ }
103
+ export function adoptTask(state: string, legacyKey: string, input: NewTask): Task {
104
+ const task = createTask(state, input, `legacy:${legacyKey}`);
105
+ if (task.legacyKey === legacyKey) return task;
106
+ return mutateTask(state, task.id, { revision: task.revision, opId: `adopt:${legacyKey}` }, (t) => { t.legacyKey = legacyKey; });
107
+ }
108
+ // Destination is committed before the alias. A crash between those writes is safe:
109
+ // the same task UUID resumes transfer; the source remains readable until aliased.
110
+ export function transferDraft(state: string, id: string, destination: string, project: string): Task {
111
+ if (resolve(state) === resolve(destination)) {
112
+ const task = readTask(state, id); if (!task) throw new TaskError("Unknown draft", 404);
113
+ return mutateTask(state, id, { revision: task.revision, opId: `project:${project}` }, (t) => { t.project = project; });
114
+ }
115
+ return locked(state, id, () => {
116
+ const source = readTask(state, id); if (!source) throw new TaskError("Unknown draft", 404);
117
+ if (source.alias) { const resolved = resolveTask(state, id); if (!resolved) throw new TaskError("Project transfer is unavailable"); return resolved.task; }
118
+ const target = locked(destination, id, () => {
119
+ const existing = readTask(destination, id); if (existing) return existing;
120
+ const task = { ...source, project, revision: source.revision + 1, updated: Date.now() };
121
+ // Attachment bytes are owned by intake and copied before calling this method;
122
+ // preserving absolute file references prevents a draft transfer losing context.
123
+ task.files = source.files.map((f) => ({ ...f, path: resolve(state, f.path) }));
124
+ atomic(fileOf(destination, id), task); return task;
125
+ });
126
+ atomic(fileOf(state, id), { ...source, alias: { state: resolve(destination), id }, revision: source.revision + 1, updated: Date.now() });
127
+ return target;
128
+ });
129
+ }
130
+ export function addEvent(task: Task, role: TaskEvent["role"], type: string, text: string, inputIds?: string[]) {
131
+ task.events.push({ id: randomUUID(), at: Date.now(), role, type, text, ...(inputIds ? { inputIds } : {}) });
132
+ }
133
+ export function receiveInput(task: Task, input: { id: string; text: string; intent?: TaskInput["intent"]; baseResult: string | null; baseRun?: string | null }): TaskInput {
134
+ const existing = task.inputs.find((i) => i.id === input.id); if (existing) return existing;
135
+ if (input.baseResult !== task.currentResult || (input.baseRun !== undefined && input.baseRun !== task.activeRun)) throw new TaskError("The result changed. Refresh and review your request before sending.");
136
+ if (!input.text?.trim()) throw new TaskError("Write a message first", 400);
137
+ const intent = input.intent ?? "change";
138
+ const item: TaskInput = { id: input.id, text: input.text.trim(), intent, at: Date.now(), state: intent === "status" ? "applied" : "queued", baseResult: input.baseResult, baseRun: task.activeRun };
139
+ task.inputs.push(item); addEvent(task, "user", intent, item.text, [item.id]);
140
+ if (intent === "status") addEvent(task, "assistant", "status", taskProjection(task).reason, [item.id]);
141
+ else if (task.status === "accepted") { task.acceptedResult = null; task.status = "ready"; }
142
+ return item;
143
+ }
144
+ export function dispatchInputs(task: Task): TaskInput[] {
145
+ if (!task.safe || task.writePhase || task.queuePaused || task.pendingDecision || task.status === "stopping" || task.status === "interrupted" || (task.launch && task.launch.phase !== "acknowledged")) return [];
146
+ if (task.inputs.some((i) => i.state === "dispatched")) return [];
147
+ const batch = task.inputs.filter((i) => i.state === "queued" || i.state === "received");
148
+ if (!batch.length) return [];
149
+ for (const i of batch) i.state = "dispatched";
150
+ task.safe = false; task.status = "working"; return batch;
151
+ }
152
+ export function acknowledgeInputs(task: Task, ids: string[], outcome: "applied" | "failed", error?: string) {
153
+ for (const id of ids) {
154
+ const item = task.inputs.find((i) => i.id === id); if (!item || !["dispatched", outcome].includes(item.state)) throw new TaskError("Input acknowledgement does not match dispatched work");
155
+ }
156
+ for (const item of task.inputs.filter((i) => ids.includes(i.id))) { item.state = outcome; if (error) item.error = error; }
157
+ }
158
+ export function safeBoundary(task: Task, run: string, text = "Work paused at a safe boundary") {
159
+ if (task.activeRun !== run) throw new TaskError("This acknowledgement belongs to another run");
160
+ if (task.inputs.some((i) => i.state === "dispatched")) throw new TaskError("Acknowledge dispatched requests before the next pass");
161
+ task.safe = true; task.writePhase = false; if (task.launch) task.launch.phase = "acknowledged";
162
+ addEvent(task, "system", "boundary", text);
163
+ }
164
+ export function beginLaunch(task: Task, inputIds: string[] = []): TaskLaunch {
165
+ if (task.queuePaused || task.launch && ["intent", "started", "interrupted"].includes(task.launch.phase)) throw new TaskError("Previous launch needs acknowledgement or explicit recovery");
166
+ if (task.writePhase || task.pendingDecision || !task.safe && (!inputIds.length || !inputIds.every((id) => task.inputs.some((i) => i.id === id && i.state === "dispatched")))) throw new TaskError("Current work has not reached a safe boundary");
167
+ task.launch = { id: randomUUID(), run: null, inputIds, phase: "intent", at: Date.now() }; task.safe = false; task.status = "working"; return task.launch;
168
+ }
169
+ export function acknowledgeLaunch(task: Task, launchId: string, run: string, pty?: string) {
170
+ if (task.launch?.id !== launchId || task.launch.phase === "interrupted") throw new TaskError("Launch acknowledgement is stale");
171
+ if (task.launch.run && task.launch.run !== run) throw new TaskError("A different run owns this launch");
172
+ task.launch.run = run; task.launch.phase = "acknowledged"; if (pty) task.launch.pty = pty;
173
+ task.activeRun = run; if (!task.runIds.includes(run)) task.runIds.push(run);
174
+ }
175
+ export function recoverLaunch(task: Task) {
176
+ if (task.launch && ["intent", "started"].includes(task.launch.phase)) { task.launch.phase = "interrupted"; task.status = "interrupted"; task.queuePaused = true; task.safe = false; task.error = "The agent launch was interrupted before acknowledgement. Reconcile the session before resuming."; }
177
+ }
178
+ 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."); }
179
+ 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."); }
180
+ export function resumeTask(task: Task) {
181
+ if (!["interrupted", "failed"].includes(task.status)) throw new TaskError("This task does not need recovery");
182
+ task.queuePaused = false; task.safe = true; task.launch = null; task.error = undefined;
183
+ // Explicit recovery preserves ids and makes ambiguous work visible for reconciliation.
184
+ for (const i of task.inputs) if (i.state === "dispatched" || i.state === "failed") i.state = "queued";
185
+ task.status = task.currentResult ? "ready" : "draft";
186
+ addEvent(task, "system", "resume", "Resume requested. Reconcile existing edits before applying the saved requests.");
187
+ }
188
+ export function acceptTask(task: Task, result: string) {
189
+ if (!result || result !== task.currentResult) throw new TaskError("This result is no longer current");
190
+ 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");
191
+ task.acceptedResult = result; task.status = "accepted"; addEvent(task, "user", "accept", "Looks good. Result accepted; publishing is separate.");
192
+ }
193
+ export function taskProjection(task: Task): { filter: "needs-you" | "in-progress" | "completed"; label: string; reason: string; action: string; rank: number } {
194
+ if (task.pendingDecision) return { filter: "needs-you", label: task.pendingDecision.kind === "proposal" ? "Confirm proposal" : "Your answer needed", reason: task.pendingDecision.text, action: task.pendingDecision.kind === "proposal" ? "Review proposal" : "Reply", rank: 0 };
195
+ if (["failed", "interrupted"].includes(task.status)) return { filter: "needs-you", label: task.status === "failed" ? "Needs recovery" : "Work interrupted", reason: task.error || "The update stopped before finishing. Saved results and requests remain available.", action: "Review and resume", rank: 1 };
196
+ if (task.status === "accepted" && task.acceptedResult === task.currentResult) return { filter: "completed", label: "Completed", reason: "You accepted this result. Publishing is separate.", action: "View result", rank: 4 };
197
+ if (task.status === "ready" && !task.inputs.some((i) => ["queued", "received", "dispatched"].includes(i.state))) return { filter: "needs-you", label: "Your feedback needed", reason: "The latest result is ready to review.", action: "Review result", rank: 2 };
198
+ if (!task.project) return { filter: "needs-you", label: "Choose a project", reason: "Your goal is saved. Select or create a named project to continue.", action: "Choose project", rank: 0 };
199
+ const queued = task.inputs.filter((i) => i.state === "queued").length;
200
+ return { filter: "in-progress", label: task.status === "stopping" ? "Stopping" : queued ? "Changes queued" : task.status === "draft" ? "Ready to start" : "In progress", reason: task.status === "stopping" ? "Waiting for confirmed cancellation. Queued requests are paused." : queued ? `${queued} request${queued === 1 ? "" : "s"} saved for the next safe pass.` : task.events.filter((e) => e.role !== "user").at(-1)?.text || "Your goal is saved and ready to start.", action: task.status === "draft" ? "Start" : "Open task", rank: 3 };
201
+ }
@@ -0,0 +1,6 @@
1
+ [
2
+ {"screen": "*", "path": "div#phome>section.psec2", "rule": "column", "reason": "Phone Home's section headings are inset 4px from the cards under them (#phome h3 margin), as grouped lists on a phone are."},
3
+ {"variant": ".ice-cap-row :is(.ib,.sel,.btn), .ice-cap-row .ice-combo>.sel", "reason": "The Icebox capture row is a compact row: attach, mic, the project and board pickers and save are all 30px, below the page's 32px controls."},
4
+ {"screen": "*", "path": "button.ib.hgo", "rule": "size", "reason": "The composer's round send button is drawn 34px on purpose, a size step above the 32px icon buttons."},
5
+ {"screen": "notes", "path": "li>details>ul>li", "rule": "column", "reason": "A folder row starts with its chevron's box, 2px left of its sibling note names; the chevron drawn inside that box starts level with them."}
6
+ ]