@abhishek944/pi-tasks 0.15.0 → 0.16.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 (48) hide show
  1. package/README.md +59 -12
  2. package/dist/agents/delegation.d.ts +4 -0
  3. package/dist/agents/delegation.js +59 -0
  4. package/dist/agents/herdr.d.ts +10 -3
  5. package/dist/agents/herdr.js +39 -12
  6. package/dist/agents/links.d.ts +3 -3
  7. package/dist/agents/links.js +42 -19
  8. package/dist/auto-continue.js +160 -27
  9. package/dist/command.d.ts +2 -2
  10. package/dist/command.js +7 -3
  11. package/dist/delegated-time.d.ts +11 -0
  12. package/dist/delegated-time.js +51 -2
  13. package/dist/dependency.d.ts +7 -0
  14. package/dist/dependency.js +13 -0
  15. package/dist/durable.d.ts +38 -0
  16. package/dist/durable.js +515 -0
  17. package/dist/herdr-header.d.ts +3 -0
  18. package/dist/herdr-header.js +100 -0
  19. package/dist/herdr-panel.d.ts +7 -0
  20. package/dist/herdr-panel.js +182 -0
  21. package/dist/index.js +96 -56
  22. package/dist/markdown.js +3 -1
  23. package/dist/panel-settings.d.ts +11 -0
  24. package/dist/panel-settings.js +30 -0
  25. package/dist/snapshot.d.ts +23 -0
  26. package/dist/snapshot.js +123 -0
  27. package/dist/state.d.ts +21 -18
  28. package/dist/state.js +357 -286
  29. package/dist/thoughts.d.ts +11 -0
  30. package/dist/thoughts.js +14 -0
  31. package/dist/timing.js +2 -1
  32. package/dist/tools.js +48 -29
  33. package/dist/tracking.js +18 -11
  34. package/dist/types.d.ts +9 -2
  35. package/dist/ui/panel.js +17 -10
  36. package/dist/ui/task-view.d.ts +7 -0
  37. package/dist/ui/task-view.js +10 -0
  38. package/dist/ui/works-dashboard.js +22 -15
  39. package/docs/REFERENCE.md +56 -28
  40. package/docs/USAGE_GUIDE.md +112 -50
  41. package/herdr/pi-tasks/README.md +45 -0
  42. package/herdr/pi-tasks/header.js +192 -0
  43. package/herdr/pi-tasks/main.js +413 -0
  44. package/herdr/pi-tasks/mod.json +3 -0
  45. package/herdr/pi-tasks/spinner.svg +1 -0
  46. package/package.json +26 -1
  47. package/dist/agents/tools.d.ts +0 -3
  48. package/dist/agents/tools.js +0 -143
package/dist/state.js CHANGED
@@ -1,330 +1,392 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isTaskDependency } from "./dependency.js";
1
3
  import { taskOwner } from "./ownership.js";
2
4
  import { taskCompletion } from "./progress.js";
5
+ import { emptySnapshot, readSnapshot, taskSnapshotPath, writeSnapshot } from "./snapshot.js";
3
6
  import { safeSingleLine } from "./text.js";
7
+ /** Legacy session entries are read once for migration, never written again. */
4
8
  export const TASK_ENTRY_TYPE = "pi-tasks-state";
5
9
  export const MAX_WORKS = 100;
6
10
  export const MAX_TODOS = 500;
11
+ /** File-backed session state. Only the binding lives here, never an authoritative record cache. */
7
12
  export class TaskState {
8
- pi;
9
13
  onChange;
10
- works = new Map();
11
- todos = new Map();
12
- nextWorkId = 1;
13
- nextTaskId = 1;
14
- focusedTaskId;
15
- workingSince;
16
- agentRunning = false;
17
- constructor(pi, onChange) {
18
- this.pi = pi;
14
+ binding;
15
+ constructor(_pi, onChange) {
19
16
  this.onChange = onChange;
20
17
  }
21
- restore(ctx) {
22
- // The branch has already changed. Never append the old interval to it.
23
- this.focusedTaskId = undefined;
24
- this.workingSince = undefined;
25
- this.agentRunning = false;
26
- this.works.clear();
27
- this.todos.clear();
28
- this.nextWorkId = 1;
29
- this.nextTaskId = 1;
30
- for (const entry of ctx.sessionManager.getBranch()) {
31
- if (entry.type !== "custom" || entry.customType !== TASK_ENTRY_TYPE)
32
- continue;
33
- const event = parseEvent(entry.data);
34
- if (!event)
35
- continue;
36
- try {
37
- this.apply(event);
18
+ get snapshotPath() {
19
+ if (!this.binding)
20
+ throw new Error("Task storage is not initialized for a Pi session.");
21
+ return this.binding.path;
22
+ }
23
+ restore(ctx, freshFork = false) {
24
+ const previous = this.binding;
25
+ this.binding = undefined;
26
+ const sessionId = ctx.sessionManager.getSessionId();
27
+ const path = taskSnapshotPath(sessionId);
28
+ const existing = readSnapshot(path, sessionId);
29
+ if (!existing && previous?.sessionId === sessionId)
30
+ throw new Error("The session task snapshot disappeared. Restore it before continuing; it will not be recreated from conversation history.");
31
+ const snapshot = existing ?? emptySnapshot(sessionId, ctx.cwd);
32
+ if (!existing && !freshFork) {
33
+ // Import the old selected view exactly once. From now on tree navigation
34
+ // never replays history. New fork identities never inherit parent tasks.
35
+ for (const entry of legacyEntries(ctx)) {
36
+ if (entry.type !== "custom" || entry.customType !== TASK_ENTRY_TYPE)
37
+ continue;
38
+ const event = parseEvent(entry.data);
39
+ if (!event)
40
+ continue;
41
+ try {
42
+ applyEvent(snapshot, event);
43
+ }
44
+ catch { /* Keep malformed legacy entries out of the migrated view. */ }
38
45
  }
39
- catch { /* Ignore malformed extension entries and continue replay. */ }
40
46
  }
47
+ snapshot.cwd = ctx.cwd;
48
+ const terminalId = process.env.HC_TERMINAL_ID;
49
+ snapshot.terminalId = terminalId && /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/.test(terminalId) ? terminalId : undefined;
50
+ // A resumed process cannot measure the previous process's unfinished interval.
51
+ snapshot.agentRunning = false;
52
+ snapshot.focusedTaskId = undefined;
53
+ for (const todo of snapshot.todos)
54
+ delete todo.workingSince;
55
+ snapshot.updatedAt = Date.now();
56
+ writeSnapshot(path, snapshot);
57
+ this.binding = { sessionId, path };
58
+ this.onChange();
59
+ }
60
+ read() {
61
+ if (!this.binding)
62
+ throw new Error("Task storage is not initialized for a Pi session.");
63
+ const snapshot = readSnapshot(this.binding.path, this.binding.sessionId);
64
+ if (!snapshot)
65
+ throw new Error("The session task snapshot is missing. Restore the file before continuing.");
66
+ return snapshot;
67
+ }
68
+ change(update) {
69
+ const snapshot = this.read();
70
+ const result = update(snapshot);
71
+ snapshot.updatedAt = Date.now();
72
+ writeSnapshot(this.snapshotPath, snapshot);
41
73
  this.onChange();
74
+ return result;
42
75
  }
43
76
  listWorks(filter) {
44
- return [...this.works.values()]
45
- .filter((work) => !filter?.workId || work.workId === filter.workId)
77
+ const snapshot = this.read();
78
+ return snapshot.works.filter((work) => !filter?.workId || work.workId === filter.workId)
46
79
  .sort((left, right) => left.createdAt - right.createdAt)
47
- .map((work) => ({ ...work, tasks: this.listTodos({ workId: work.workId }) }));
80
+ .map((work) => ({ ...work, tasks: snapshot.todos.filter((todo) => todo.workId === work.workId).sort((left, right) => left.createdAt - right.createdAt) }));
48
81
  }
49
82
  listTodos(filter) {
50
- return [...this.todos.values()]
83
+ return this.read().todos
51
84
  .filter((todo) => !filter?.taskId || todo.taskId === filter.taskId)
52
85
  .filter((todo) => !filter?.workId || todo.workId === filter.workId)
53
86
  .filter((todo) => !filter?.status || todo.status === filter.status)
54
- .sort((left, right) => left.createdAt - right.createdAt)
55
- .map((todo) => this.snapshot(todo));
56
- }
57
- getWork(workId) {
58
- const work = this.works.get(workId);
59
- return work ? { ...work } : undefined;
60
- }
61
- getTodo(taskId) {
62
- const todo = this.todos.get(taskId);
63
- return todo ? this.snapshot(todo) : undefined;
87
+ .sort((left, right) => left.createdAt - right.createdAt);
64
88
  }
65
- snapshot(todo) {
66
- return { ...todo, delegatedTimes: todo.delegatedTimes?.map((source) => ({ ...source })), workingSince: todo.taskId === this.focusedTaskId ? this.workingSince : undefined };
89
+ getWork(workId) { return this.read().works.find((work) => work.workId === workId); }
90
+ getTodo(taskId) { return this.read().todos.find((todo) => todo.taskId === taskId); }
91
+ getFocusedTodo() {
92
+ const snapshot = this.read();
93
+ return snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
67
94
  }
68
- /** Gate the selected task on actual agent execution, not task status. */
69
95
  setAgentRunning(running) {
70
- if (this.agentRunning === running)
96
+ // Timing hooks run before storage initialization and after failed startup too.
97
+ if (!this.binding)
71
98
  return;
72
- if (!running)
73
- this.saveInterval();
74
- this.agentRunning = running;
75
- if (running && this.focusedTaskId)
76
- this.workingSince = Date.now();
77
- this.onChange();
99
+ if (this.read().agentRunning === running)
100
+ return;
101
+ this.change((snapshot) => {
102
+ if (!running)
103
+ saveInterval(snapshot);
104
+ snapshot.agentRunning = running;
105
+ const todo = snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
106
+ if (running && todo)
107
+ todo.workingSince = Date.now();
108
+ });
78
109
  }
79
110
  setWorking(taskId, working) {
80
- const todo = this.todos.get(taskId);
81
- if (!todo)
82
- throw new Error(`Todo ${taskId} not found.`);
83
- if (!working) {
84
- if (this.focusedTaskId === taskId)
85
- this.clearWorking();
86
- return;
87
- }
88
- if (todo.status !== "active" || taskOwner(todo.taskInfo) !== "self") {
89
- throw new Error("working=true requires an active task with owner: self in this session.");
90
- }
91
- if (this.focusedTaskId === taskId)
92
- return;
93
- this.clearWorking();
94
- if (todo.elapsedMs === undefined || todo.elapsedMs === null) {
95
- this.record({ version: 1, type: "todo-time", at: Date.now(), taskId, elapsedMs: 0 });
96
- }
97
- this.focusedTaskId = taskId;
98
- if (this.agentRunning)
99
- this.workingSince = Date.now();
100
- this.onChange();
111
+ this.change((snapshot) => selectWorking(snapshot, taskId, working));
101
112
  }
102
113
  clearWorking() {
103
- this.saveInterval();
104
- this.focusedTaskId = undefined;
105
- this.onChange();
106
- }
107
- saveInterval() {
108
- if (!this.focusedTaskId || this.workingSince === undefined)
114
+ if (!this.binding)
109
115
  return;
110
- const todo = this.todos.get(this.focusedTaskId);
111
- const now = Date.now();
112
- if (todo) {
113
- this.record({ version: 1, type: "todo-time", at: now, taskId: todo.taskId,
114
- elapsedMs: (todo.elapsedMs ?? 0) + Math.max(0, now - this.workingSince) });
115
- }
116
- this.workingSince = undefined;
116
+ if (!this.read().focusedTaskId)
117
+ return;
118
+ this.change((snapshot) => { saveInterval(snapshot); delete snapshot.focusedTaskId; });
117
119
  }
118
120
  createWork(workName, workInfo) {
119
- if (this.works.size >= MAX_WORKS)
120
- throw new Error(`Maximum of ${MAX_WORKS} works reached.`);
121
- const now = Date.now();
122
- const work = {
123
- workId: `W${this.nextWorkId}`,
124
- workName: requiredName(workName, "workName"),
125
- workInfo: requiredText(workInfo, "workInfo"),
126
- createdAt: now,
127
- updatedAt: now,
128
- };
129
- this.record({ version: 1, type: "work-created", at: now, work });
130
- return { ...work };
121
+ return this.change((snapshot) => {
122
+ if (snapshot.works.length >= MAX_WORKS)
123
+ throw new Error(`Maximum of ${MAX_WORKS} works reached.`);
124
+ const now = Date.now();
125
+ const work = { workId: `W${snapshot.nextWorkId++}`, workName: requiredName(workName, "workName"), workInfo: requiredText(workInfo, "workInfo"), createdAt: now, updatedAt: now };
126
+ snapshot.works.push(work);
127
+ return work;
128
+ });
131
129
  }
132
130
  updateWork(workId, patch) {
133
- if (!this.works.has(workId))
134
- throw new Error(`Work ${workId} not found.`);
135
- const normalized = compactPatch({
136
- workName: patch.workName === undefined ? undefined : requiredName(patch.workName, "workName"),
137
- workInfo: patch.workInfo === undefined ? undefined : requiredText(patch.workInfo, "workInfo"),
131
+ return this.change((snapshot) => {
132
+ const work = snapshot.works.find((work) => work.workId === workId);
133
+ if (!work)
134
+ throw new Error(`Work ${workId} not found.`);
135
+ const normalized = compactPatch({ workName: patch.workName === undefined ? undefined : requiredName(patch.workName, "workName"), workInfo: patch.workInfo === undefined ? undefined : requiredText(patch.workInfo, "workInfo") });
136
+ if (Object.keys(normalized).length === 0)
137
+ throw new Error("WorkUpdate requires at least one changed field.");
138
+ Object.assign(work, normalized, { updatedAt: Date.now() });
139
+ return work;
138
140
  });
139
- if (Object.keys(normalized).length === 0)
140
- throw new Error("WorkUpdate requires at least one changed field.");
141
- this.record({ version: 1, type: "work-updated", at: Date.now(), workId, patch: normalized });
142
- return this.getWork(workId);
143
141
  }
144
142
  deleteWork(workId) {
145
- if (!this.works.has(workId))
146
- return false;
147
- if (this.focusedTaskId && this.todos.get(this.focusedTaskId)?.workId === workId)
148
- this.clearWorking();
149
- this.record({ version: 1, type: "work-deleted", at: Date.now(), workId });
150
- return true;
143
+ return this.change((snapshot) => {
144
+ if (!snapshot.works.some((work) => work.workId === workId))
145
+ return false;
146
+ if (snapshot.todos.some((todo) => todo.workId === workId && todo.taskId === snapshot.focusedTaskId)) {
147
+ saveInterval(snapshot);
148
+ delete snapshot.focusedTaskId;
149
+ }
150
+ snapshot.works = snapshot.works.filter((work) => work.workId !== workId);
151
+ snapshot.todos = snapshot.todos.filter((todo) => todo.workId !== workId);
152
+ return true;
153
+ });
151
154
  }
152
- createTodo(workId, taskName, taskInfo, status = "active", completionPercent, blockedReason) {
153
- if (!this.works.has(workId))
154
- throw new Error(`Work ${workId} not found.`);
155
- if (this.todos.size >= MAX_TODOS)
156
- throw new Error(`Maximum of ${MAX_TODOS} todos reached.`);
157
- validateCompletion(status, completionPercent);
158
- const reason = normalizeBlockedReason(status, blockedReason, undefined);
159
- const now = Date.now();
160
- const todo = {
161
- taskId: `T${this.nextTaskId}`,
162
- workId,
163
- taskName: requiredName(taskName, "taskName"),
164
- taskInfo: requiredText(taskInfo, "taskInfo"),
165
- status,
166
- blockedReason: reason,
167
- completionPercent: status === "completed" ? 100 : completionPercent ?? null,
168
- elapsedMs: 0,
169
- createdAt: now,
170
- updatedAt: now,
171
- };
172
- this.record({ version: 1, type: "todo-created", at: now, todo });
173
- return { ...todo };
155
+ createTodo(input) {
156
+ const { workId, taskName, taskInfo, finalThoughts, status = "active", completionPercent, blockedReason, dependentOn } = input;
157
+ return this.change((snapshot) => {
158
+ if (!snapshot.works.some((work) => work.workId === workId))
159
+ throw new Error(`Work ${workId} not found.`);
160
+ if (snapshot.todos.length >= MAX_TODOS)
161
+ throw new Error(`Maximum of ${MAX_TODOS} todos reached.`);
162
+ validateCompletion(status, completionPercent);
163
+ const now = Date.now();
164
+ const dependency = normalizeDependency(status, dependentOn, undefined);
165
+ const todo = { taskId: `T${snapshot.nextTaskId++}`, workId, taskName: requiredName(taskName, "taskName"), taskInfo: requiredText(taskInfo, "taskInfo"), finalThoughts: optionalThoughts(finalThoughts), status,
166
+ blockedReason: normalizeBlockedReason(status, blockedReason, undefined), ...(dependency === undefined ? {} : { dependentOn: dependency }), completionPercent: status === "completed" ? 100 : completionPercent ?? null, elapsedMs: 0, createdAt: now, updatedAt: now };
167
+ snapshot.todos.push(todo);
168
+ return todo;
169
+ });
174
170
  }
175
171
  updateTodo(taskId, patch) {
176
- const current = this.todos.get(taskId);
177
- if (!current)
178
- throw new Error(`Todo ${taskId} not found.`);
179
- const status = patch.status ?? current.status;
180
- validateCompletion(status, patch.completionPercent);
181
- const blockedReason = normalizeBlockedReason(status, patch.blockedReason, current);
182
- const normalized = compactPatch({
183
- taskName: patch.taskName === undefined ? undefined : requiredName(patch.taskName, "taskName"),
184
- taskInfo: patch.taskInfo === undefined ? undefined : requiredText(patch.taskInfo, "taskInfo"),
185
- status: patch.status,
186
- blockedReason: patch.blockedReason !== undefined || status !== current.status ? blockedReason : undefined,
187
- completionPercent: patch.completionPercent,
172
+ return this.change((snapshot) => {
173
+ const current = snapshot.todos.find((todo) => todo.taskId === taskId);
174
+ if (!current)
175
+ throw new Error(`Todo ${taskId} not found.`);
176
+ const status = patch.status ?? current.status;
177
+ const transitioned = status !== current.status;
178
+ validateCompletion(status, patch.completionPercent);
179
+ const blockedReason = normalizeBlockedReason(status, patch.blockedReason, current);
180
+ const dependency = normalizeDependency(status, patch.dependentOn, current);
181
+ const dependencyCleared = (patch.dependentOn !== undefined || transitioned) && dependency === undefined;
182
+ const normalized = compactPatch({
183
+ taskName: patch.taskName === undefined ? undefined : requiredName(patch.taskName, "taskName"),
184
+ taskInfo: patch.taskInfo === undefined ? undefined : requiredText(patch.taskInfo, "taskInfo"),
185
+ finalThoughts: optionalThoughts(patch.finalThoughts),
186
+ status: patch.status,
187
+ blockedReason: patch.blockedReason !== undefined || transitioned ? blockedReason : undefined,
188
+ dependentOn: patch.dependentOn !== undefined && dependency !== undefined ? dependency : undefined,
189
+ completionPercent: patch.completionPercent,
190
+ });
191
+ if (Object.keys(normalized).length === 0 && patch.working === undefined && patch.finalThoughts === undefined)
192
+ throw new Error("TodoUpdate requires at least one changed field.");
193
+ const effective = { ...current, ...normalized };
194
+ const canWork = effective.status === "active" && taskOwner(effective.taskInfo) === "self";
195
+ if (patch.working === true && !canWork)
196
+ throw new Error("working=true requires an active task with owner: self in this session.");
197
+ if (snapshot.focusedTaskId === taskId && (!canWork || patch.working === false)) {
198
+ saveInterval(snapshot);
199
+ delete snapshot.focusedTaskId;
200
+ }
201
+ Object.assign(current, normalized, { updatedAt: Date.now() });
202
+ if (dependencyCleared)
203
+ delete current.dependentOn;
204
+ // A new status is a new statement. Keep an explicitly supplied thought;
205
+ // otherwise drop the old one so blocked, resumed, and completed rows never
206
+ // show a stale message from the previous state. A completion without a
207
+ // thought stays honestly empty for historical callers.
208
+ if (patch.finalThoughts !== undefined) {
209
+ const thoughts = optionalThoughts(patch.finalThoughts);
210
+ if (thoughts === undefined)
211
+ delete current.finalThoughts;
212
+ else
213
+ current.finalThoughts = thoughts;
214
+ }
215
+ else if (transitioned) {
216
+ delete current.finalThoughts;
217
+ }
218
+ current.completionPercent = taskCompletion(current);
219
+ if (patch.working !== undefined)
220
+ selectWorking(snapshot, taskId, patch.working);
221
+ return current;
188
222
  });
189
- if (Object.keys(normalized).length === 0 && patch.working === undefined)
190
- throw new Error("TodoUpdate requires at least one changed field.");
191
- const effective = { ...current, ...normalized };
192
- const canWork = effective.status === "active" && taskOwner(effective.taskInfo) === "self";
193
- if (patch.working === true && !canWork)
194
- throw new Error("working=true requires an active task with owner: self in this session.");
195
- if (this.focusedTaskId === taskId && (!canWork || patch.working === false))
196
- this.clearWorking();
197
- if (Object.keys(normalized).length > 0)
198
- this.record({ version: 1, type: "todo-updated", at: Date.now(), taskId, patch: normalized });
199
- if (patch.working !== undefined)
200
- this.setWorking(taskId, patch.working);
201
- return this.getTodo(taskId);
202
223
  }
203
- /** Replace a cumulative assignment snapshot, never add it again on retry. */
204
224
  setDelegatedTime(taskId, source) {
205
- const todo = this.todos.get(taskId);
206
- if (!todo || taskOwner(todo.taskInfo) !== "delegate")
207
- throw new Error("Delegated timing requires an existing owner: delegate task.");
208
- if (!validDelegatedTime(source))
209
- throw new Error("Invalid delegated timing source.");
210
- const previous = todo.delegatedTimes?.find((entry) => entry.reportPath === source.reportPath);
211
- if (previous?.workerSessionId && previous.workerSessionId !== source.workerSessionId)
212
- throw new Error("Timing report belongs to another worker session.");
213
- if (previous?.elapsedMs === source.elapsedMs && previous?.workerSessionId === source.workerSessionId)
214
- return;
215
- this.record({ version: 1, type: "todo-delegated-time", at: Date.now(), taskId, source });
225
+ this.change((snapshot) => {
226
+ const todo = snapshot.todos.find((todo) => todo.taskId === taskId);
227
+ if (!todo || taskOwner(todo.taskInfo) !== "delegate")
228
+ throw new Error("Delegated timing requires an existing owner: delegate task.");
229
+ if (!validDelegatedTime(source))
230
+ throw new Error("Invalid delegated timing source.");
231
+ const previous = todo.delegatedTimes?.find((entry) => entry.reportPath === source.reportPath);
232
+ if (previous?.workerSessionId && previous.workerSessionId !== source.workerSessionId)
233
+ throw new Error("Timing report belongs to another worker session.");
234
+ todo.delegatedTimes = [...(todo.delegatedTimes ?? []).filter((entry) => entry.reportPath !== source.reportPath), { ...source }];
235
+ });
216
236
  }
217
237
  deleteTodo(taskId) {
218
- if (!this.todos.has(taskId))
219
- return false;
220
- if (this.focusedTaskId === taskId)
221
- this.clearWorking();
222
- this.record({ version: 1, type: "todo-deleted", at: Date.now(), taskId });
223
- return true;
238
+ return this.change((snapshot) => {
239
+ if (!snapshot.todos.some((todo) => todo.taskId === taskId))
240
+ return false;
241
+ if (snapshot.focusedTaskId === taskId) {
242
+ saveInterval(snapshot);
243
+ delete snapshot.focusedTaskId;
244
+ }
245
+ snapshot.todos = snapshot.todos.filter((todo) => todo.taskId !== taskId);
246
+ return true;
247
+ });
224
248
  }
225
- record(event) {
226
- this.pi.appendEntry(TASK_ENTRY_TYPE, event);
227
- this.apply(event);
228
- this.onChange();
249
+ }
250
+ function saveInterval(snapshot) {
251
+ const todo = snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
252
+ if (!todo || todo.workingSince === undefined)
253
+ return;
254
+ todo.elapsedMs = (todo.elapsedMs ?? 0) + Math.max(0, Date.now() - todo.workingSince);
255
+ delete todo.workingSince;
256
+ }
257
+ function selectWorking(snapshot, taskId, working) {
258
+ const todo = snapshot.todos.find((todo) => todo.taskId === taskId);
259
+ if (!todo)
260
+ throw new Error(`Todo ${taskId} not found.`);
261
+ if (!working) {
262
+ if (snapshot.focusedTaskId === taskId) {
263
+ saveInterval(snapshot);
264
+ delete snapshot.focusedTaskId;
265
+ }
266
+ return;
229
267
  }
230
- apply(event) {
231
- switch (event.type) {
232
- case "work-created": {
233
- assertId(event.work.workId, "W");
234
- if (typeof event.work.workName !== "string" || typeof event.work.workInfo !== "string")
235
- throw new Error("Malformed work entry.");
236
- // Explicit fields keep retired Work status out of restored records.
237
- this.works.set(event.work.workId, {
238
- workId: event.work.workId,
239
- workName: safeSingleLine(event.work.workName),
240
- workInfo: event.work.workInfo,
241
- createdAt: event.work.createdAt,
242
- updatedAt: event.work.updatedAt,
243
- });
244
- this.nextWorkId = Math.max(this.nextWorkId, numericId(event.work.workId) + 1);
245
- break;
246
- }
247
- case "work-updated": {
248
- const work = this.works.get(event.workId);
249
- if (work)
250
- this.works.set(event.workId, {
251
- ...work,
252
- ...(typeof event.patch.workName === "string" ? { workName: safeSingleLine(event.patch.workName) } : {}),
253
- ...(typeof event.patch.workInfo === "string" ? { workInfo: event.patch.workInfo } : {}),
254
- updatedAt: event.at,
255
- });
256
- break;
257
- }
258
- case "work-deleted":
259
- this.works.delete(event.workId);
260
- for (const [taskId, todo] of this.todos)
261
- if (todo.workId === event.workId)
262
- this.todos.delete(taskId);
263
- break;
264
- case "todo-created": {
265
- const status = restoredStatus(event.todo.status);
266
- assertId(event.todo.taskId, "T");
267
- if (typeof event.todo.workId !== "string" || typeof event.todo.taskName !== "string" || typeof event.todo.taskInfo !== "string" || !status)
268
- throw new Error("Malformed todo entry.");
269
- if (this.works.has(event.todo.workId))
270
- this.todos.set(event.todo.taskId, {
271
- ...event.todo,
272
- status,
273
- blockedReason: status === "blocked" ? restoredReason(event.todo.blockedReason) : null,
274
- taskName: safeSingleLine(event.todo.taskName),
275
- completionPercent: taskCompletion(event.todo),
276
- elapsedMs: validElapsed(event.todo.elapsedMs) ? event.todo.elapsedMs : null,
277
- delegatedTimes: undefined,
278
- workingSince: undefined,
279
- });
280
- this.nextTaskId = Math.max(this.nextTaskId, numericId(event.todo.taskId) + 1);
281
- break;
282
- }
283
- case "todo-updated": {
284
- const status = restoredStatus(event.patch.status);
285
- const todo = this.todos.get(event.taskId);
286
- if (todo) {
287
- const updated = {
288
- ...todo,
289
- ...(typeof event.patch.taskName === "string" ? { taskName: safeSingleLine(event.patch.taskName) } : {}),
290
- ...(typeof event.patch.taskInfo === "string" ? { taskInfo: event.patch.taskInfo } : {}),
291
- ...(status ? { status } : {}),
292
- ...(event.patch.completionPercent !== undefined ? { completionPercent: event.patch.completionPercent } : {}),
293
- updatedAt: event.at,
294
- };
295
- this.todos.set(event.taskId, {
296
- ...updated,
297
- blockedReason: updated.status === "blocked"
298
- ? event.patch.blockedReason !== undefined ? restoredReason(event.patch.blockedReason) : todo.status === "blocked" ? todo.blockedReason : null
299
- : null,
300
- completionPercent: taskCompletion(updated),
301
- });
302
- }
303
- break;
304
- }
305
- case "todo-time": {
306
- const todo = this.todos.get(event.taskId);
307
- if (todo && validElapsed(event.elapsedMs))
308
- this.todos.set(event.taskId, { ...todo, elapsedMs: event.elapsedMs });
268
+ if (todo.status !== "active" || taskOwner(todo.taskInfo) !== "self")
269
+ throw new Error("working=true requires an active task with owner: self in this session.");
270
+ if (snapshot.focusedTaskId === taskId)
271
+ return;
272
+ saveInterval(snapshot);
273
+ snapshot.focusedTaskId = taskId;
274
+ todo.elapsedMs ??= 0;
275
+ if (snapshot.agentRunning)
276
+ todo.workingSince = Date.now();
277
+ }
278
+ /** CLI --fork starts with reason startup too. Copied legacy entries alone are
279
+ * not this new session's tasks. A pre-upgrade fork with its own task edits still
280
+ * imports its old view, including the ancestors those edits depended on. */
281
+ function legacyEntries(ctx) {
282
+ const entries = ctx.sessionManager.getBranch();
283
+ const tasks = entries.filter((entry) => entry.type === "custom" && entry.customType === TASK_ENTRY_TYPE);
284
+ const parent = ctx.sessionManager.getHeader()?.parentSession;
285
+ if (!parent || tasks.length === 0)
286
+ return entries;
287
+ const inherited = new Set();
288
+ let contents;
289
+ try {
290
+ contents = readFileSync(parent, "utf8");
291
+ }
292
+ catch {
293
+ throw new Error("Cannot distinguish inherited legacy tasks in this fork: restore its parent session file before migrating. Existing task history has not been changed.");
294
+ }
295
+ for (const line of contents.split("\n")) {
296
+ if (!line.includes(TASK_ENTRY_TYPE))
297
+ continue;
298
+ try {
299
+ const entry = JSON.parse(line);
300
+ if (entry?.type === "custom" && entry.customType === TASK_ENTRY_TYPE)
301
+ inherited.add(`${entry.id}:${entry.timestamp}`);
302
+ }
303
+ catch { /* A malformed parent line cannot be a valid inherited task event. */ }
304
+ }
305
+ return tasks.some((entry) => !inherited.has(`${entry.id}:${entry.timestamp}`)) ? entries : [];
306
+ }
307
+ /** Compatibility reducer used only when a session has no JSON task store yet. */
308
+ function applyEvent(snapshot, event) {
309
+ switch (event.type) {
310
+ case "work-created": {
311
+ assertId(event.work.workId, "W");
312
+ const work = { workId: event.work.workId, workName: requiredName(event.work.workName, "workName"), workInfo: requiredText(event.work.workInfo, "workInfo"), createdAt: event.work.createdAt, updatedAt: event.work.updatedAt };
313
+ snapshot.works = [...snapshot.works.filter((item) => item.workId !== work.workId), work];
314
+ snapshot.nextWorkId = Math.max(snapshot.nextWorkId, Number(work.workId.slice(1)) + 1);
315
+ break;
316
+ }
317
+ case "work-updated": {
318
+ const work = snapshot.works.find((work) => work.workId === event.workId);
319
+ if (work)
320
+ Object.assign(work, compactPatch({ workName: typeof event.patch.workName === "string" ? requiredName(event.patch.workName, "workName") : undefined, workInfo: event.patch.workInfo }), { updatedAt: event.at });
321
+ break;
322
+ }
323
+ case "work-deleted":
324
+ snapshot.works = snapshot.works.filter((work) => work.workId !== event.workId);
325
+ snapshot.todos = snapshot.todos.filter((todo) => todo.workId !== event.workId);
326
+ break;
327
+ case "todo-created": {
328
+ assertId(event.todo.taskId, "T");
329
+ const status = restoredStatus(event.todo.status);
330
+ if (!status)
331
+ throw new Error("Malformed legacy task status.");
332
+ const todo = { ...event.todo, taskName: requiredName(event.todo.taskName, "taskName"), taskInfo: requiredText(event.todo.taskInfo, "taskInfo"),
333
+ finalThoughts: optionalThoughts(typeof event.todo.finalThoughts === "string" ? event.todo.finalThoughts : undefined), status,
334
+ blockedReason: status === "blocked" ? restoredReason(event.todo.blockedReason) : null,
335
+ ...(status === "blocked" && isTaskDependency(event.todo.dependentOn) ? { dependentOn: event.todo.dependentOn } : {}),
336
+ completionPercent: taskCompletion({ ...event.todo, status }), elapsedMs: validElapsed(event.todo.elapsedMs) ? event.todo.elapsedMs : null, delegatedTimes: undefined, workingSince: undefined };
337
+ if (snapshot.works.some((work) => work.workId === todo.workId))
338
+ snapshot.todos = [...snapshot.todos.filter((item) => item.taskId !== todo.taskId), todo];
339
+ snapshot.nextTaskId = Math.max(snapshot.nextTaskId, Number(todo.taskId.slice(1)) + 1);
340
+ break;
341
+ }
342
+ case "todo-updated": {
343
+ const todo = snapshot.todos.find((todo) => todo.taskId === event.taskId);
344
+ if (!todo)
309
345
  break;
346
+ const patch = event.patch;
347
+ const status = restoredStatus(patch.status) ?? todo.status;
348
+ const transitioned = status !== todo.status;
349
+ const dependency = status === "blocked"
350
+ ? patch.dependentOn !== undefined ? (isTaskDependency(patch.dependentOn) ? patch.dependentOn : todo.dependentOn) : todo.dependentOn
351
+ : undefined;
352
+ Object.assign(todo, compactPatch({ taskName: typeof patch.taskName === "string" ? requiredName(patch.taskName, "taskName") : undefined, taskInfo: patch.taskInfo, completionPercent: patch.completionPercent }), {
353
+ status, blockedReason: status === "blocked" ? patch.blockedReason !== undefined ? restoredReason(patch.blockedReason) : todo.blockedReason : null, updatedAt: event.at,
354
+ });
355
+ if (dependency === undefined)
356
+ delete todo.dependentOn;
357
+ else
358
+ todo.dependentOn = dependency;
359
+ if (typeof patch.finalThoughts === "string") {
360
+ const thoughts = optionalThoughts(patch.finalThoughts);
361
+ if (thoughts === undefined)
362
+ delete todo.finalThoughts;
363
+ else
364
+ todo.finalThoughts = thoughts;
310
365
  }
311
- case "todo-delegated-time": {
312
- const todo = this.todos.get(event.taskId);
313
- if (todo && validDelegatedTime(event.source)) {
314
- const sources = (todo.delegatedTimes ?? []).filter((source) => source.reportPath !== event.source.reportPath);
315
- this.todos.set(event.taskId, { ...todo, delegatedTimes: [...sources, { ...event.source }] });
316
- }
317
- break;
366
+ else if (transitioned) {
367
+ delete todo.finalThoughts;
318
368
  }
319
- case "todo-deleted":
320
- this.todos.delete(event.taskId);
321
- break;
369
+ todo.completionPercent = taskCompletion(todo);
370
+ break;
371
+ }
372
+ case "todo-time": {
373
+ const todo = snapshot.todos.find((todo) => todo.taskId === event.taskId);
374
+ if (todo && validElapsed(event.elapsedMs))
375
+ todo.elapsedMs = event.elapsedMs;
376
+ break;
322
377
  }
378
+ case "todo-delegated-time": {
379
+ const todo = snapshot.todos.find((todo) => todo.taskId === event.taskId);
380
+ if (todo && validDelegatedTime(event.source))
381
+ todo.delegatedTimes = [...(todo.delegatedTimes ?? []).filter((source) => source.reportPath !== event.source.reportPath), { ...event.source }];
382
+ break;
383
+ }
384
+ case "todo-deleted":
385
+ snapshot.todos = snapshot.todos.filter((todo) => todo.taskId !== event.taskId);
386
+ break;
323
387
  }
324
388
  }
325
- function restoredReason(value) {
326
- return typeof value === "string" && value.trim() ? value.trim() : null;
327
- }
389
+ function restoredReason(value) { return typeof value === "string" && value.trim() ? value.trim() : null; }
328
390
  function normalizeBlockedReason(status, supplied, current) {
329
391
  if (status !== "blocked") {
330
392
  if (supplied !== undefined && supplied !== null)
@@ -340,14 +402,24 @@ function normalizeBlockedReason(status, supplied, current) {
340
402
  throw new Error("blockedReason must not exceed 10000 characters.");
341
403
  return reason;
342
404
  }
405
+ function normalizeDependency(status, supplied, current) {
406
+ if (status !== "blocked") {
407
+ if (supplied !== undefined && supplied !== null)
408
+ throw new Error("dependentOn is only valid for blocked tasks.");
409
+ return undefined;
410
+ }
411
+ if (supplied === undefined && current?.status === "blocked")
412
+ return current.dependentOn;
413
+ if (!isTaskDependency(supplied))
414
+ throw new Error("Blocked tasks require dependentOn=\"user-decision\" or dependentOn=\"another-agent\".");
415
+ return supplied;
416
+ }
343
417
  function validDelegatedTime(value) {
344
418
  return !!value && typeof value.reportPath === "string" && value.reportPath.length > 0
345
419
  && (value.elapsedMs === null || validElapsed(value.elapsedMs))
346
420
  && (value.workerSessionId === undefined || (typeof value.workerSessionId === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value.workerSessionId)));
347
421
  }
348
- function validElapsed(value) {
349
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
350
- }
422
+ function validElapsed(value) { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; }
351
423
  function validateCompletion(status, value) {
352
424
  if (value === undefined || value === null)
353
425
  return;
@@ -370,20 +442,19 @@ function requiredName(value, field) {
370
442
  throw new Error(`${field} must not be empty.`);
371
443
  return text;
372
444
  }
373
- function compactPatch(patch) {
374
- return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined));
375
- }
376
- function numericId(id) {
377
- const value = Number.parseInt(id.slice(1), 10);
378
- return Number.isSafeInteger(value) ? value : 0;
445
+ /** Visible thoughts are one optional concise string; empty input clears it. */
446
+ function optionalThoughts(value) {
447
+ if (value === undefined || value === null)
448
+ return undefined;
449
+ const text = value.trim();
450
+ return text || undefined;
379
451
  }
452
+ function compactPatch(patch) { return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)); }
380
453
  function assertId(id, prefix) {
381
- if (typeof id !== "string" || !new RegExp(`^${prefix}[1-9]\\d*$`).test(id) || !Number.isSafeInteger(Number(id.slice(1)))) {
454
+ if (typeof id !== "string" || !new RegExp(`^${prefix}[1-9]\\d*$`).test(id) || !Number.isSafeInteger(Number(id.slice(1))))
382
455
  throw new Error(`Malformed ${prefix === "W" ? "work" : "todo"} ID.`);
383
- }
384
456
  }
385
457
  function restoredStatus(value) {
386
- // Keep legacy branch events readable without exposing retired statuses in tools.
387
458
  if (value === "planned" || value === "pending")
388
459
  return "active";
389
460
  if (value === "active" || value === "blocked" || value === "completed" || value === "cancelled")