@abhishek944/pi-tasks 0.15.0 → 0.17.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 (54) hide show
  1. package/README.md +63 -14
  2. package/dist/agents/delegation.d.ts +4 -0
  3. package/dist/agents/delegation.js +130 -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 +409 -33
  9. package/dist/blocked.d.ts +29 -0
  10. package/dist/blocked.js +100 -0
  11. package/dist/command.d.ts +2 -2
  12. package/dist/command.js +7 -3
  13. package/dist/delegated-time.d.ts +12 -1
  14. package/dist/delegated-time.js +96 -15
  15. package/dist/dependency.d.ts +7 -0
  16. package/dist/dependency.js +13 -0
  17. package/dist/durable.d.ts +42 -0
  18. package/dist/durable.js +577 -0
  19. package/dist/herdr-header.d.ts +3 -0
  20. package/dist/herdr-header.js +100 -0
  21. package/dist/herdr-panel.d.ts +15 -0
  22. package/dist/herdr-panel.js +219 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +125 -56
  25. package/dist/markdown.js +3 -1
  26. package/dist/panel-settings.d.ts +11 -0
  27. package/dist/panel-settings.js +30 -0
  28. package/dist/progress.js +1 -1
  29. package/dist/snapshot.d.ts +23 -0
  30. package/dist/snapshot.js +166 -0
  31. package/dist/state.d.ts +43 -18
  32. package/dist/state.js +581 -289
  33. package/dist/thoughts.d.ts +11 -0
  34. package/dist/thoughts.js +14 -0
  35. package/dist/timing.js +9 -2
  36. package/dist/tools.js +295 -34
  37. package/dist/tracking.js +25 -13
  38. package/dist/transition.d.ts +9 -0
  39. package/dist/transition.js +26 -0
  40. package/dist/types.d.ts +76 -3
  41. package/dist/ui/panel.js +38 -19
  42. package/dist/ui/task-view.d.ts +7 -0
  43. package/dist/ui/task-view.js +10 -0
  44. package/dist/ui/works-dashboard.js +37 -19
  45. package/docs/REFERENCE.md +85 -31
  46. package/docs/USAGE_GUIDE.md +129 -55
  47. package/herdr/pi-tasks/README.md +46 -0
  48. package/herdr/pi-tasks/header.js +212 -0
  49. package/herdr/pi-tasks/main.js +488 -0
  50. package/herdr/pi-tasks/mod.json +3 -0
  51. package/herdr/pi-tasks/spinner.svg +1 -0
  52. package/package.json +26 -1
  53. package/dist/agents/tools.d.ts +0 -3
  54. package/dist/agents/tools.js +0 -143
package/dist/state.js CHANGED
@@ -1,330 +1,591 @@
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
+ /** An explicit working=false pause lasts until the next run boundary. */
16
+ autoTimingPaused = false;
17
+ constructor(_pi, onChange) {
19
18
  this.onChange = onChange;
20
19
  }
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);
20
+ get snapshotPath() {
21
+ if (!this.binding)
22
+ throw new Error("Task storage is not initialized for a Pi session.");
23
+ return this.binding.path;
24
+ }
25
+ restore(ctx, freshFork = false) {
26
+ const previous = this.binding;
27
+ this.binding = undefined;
28
+ const sessionId = ctx.sessionManager.getSessionId();
29
+ const path = taskSnapshotPath(sessionId);
30
+ const existing = readSnapshot(path, sessionId);
31
+ if (!existing && previous?.sessionId === sessionId)
32
+ throw new Error("The session task snapshot disappeared. Restore it before continuing; it will not be recreated from conversation history.");
33
+ const snapshot = existing ?? emptySnapshot(sessionId, ctx.cwd);
34
+ if (!existing && !freshFork) {
35
+ // Import the old selected view exactly once. From now on tree navigation
36
+ // never replays history. New fork identities never inherit parent tasks.
37
+ for (const entry of legacyEntries(ctx)) {
38
+ if (entry.type !== "custom" || entry.customType !== TASK_ENTRY_TYPE)
39
+ continue;
40
+ const event = parseEvent(entry.data);
41
+ if (!event)
42
+ continue;
43
+ try {
44
+ applyEvent(snapshot, event);
45
+ }
46
+ catch { /* Keep malformed legacy entries out of the migrated view. */ }
38
47
  }
39
- catch { /* Ignore malformed extension entries and continue replay. */ }
40
48
  }
49
+ snapshot.cwd = ctx.cwd;
50
+ const terminalId = process.env.HC_TERMINAL_ID;
51
+ snapshot.terminalId = terminalId && /^(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)?t[0-9a-z]+$/.test(terminalId) ? terminalId : undefined;
52
+ // A resumed process cannot measure the previous process's unfinished interval.
53
+ snapshot.agentRunning = false;
54
+ snapshot.focusedTaskId = undefined;
55
+ for (const todo of snapshot.todos)
56
+ delete todo.workingSince;
57
+ snapshot.updatedAt = Date.now();
58
+ writeSnapshot(path, snapshot);
59
+ this.binding = { sessionId, path };
41
60
  this.onChange();
42
61
  }
62
+ read() {
63
+ if (!this.binding)
64
+ throw new Error("Task storage is not initialized for a Pi session.");
65
+ const snapshot = readSnapshot(this.binding.path, this.binding.sessionId);
66
+ if (!snapshot)
67
+ throw new Error("The session task snapshot is missing. Restore the file before continuing.");
68
+ return snapshot;
69
+ }
70
+ change(update) {
71
+ const snapshot = this.read();
72
+ const result = update(snapshot);
73
+ snapshot.updatedAt = Date.now();
74
+ writeSnapshot(this.snapshotPath, snapshot);
75
+ this.onChange();
76
+ return result;
77
+ }
43
78
  listWorks(filter) {
44
- return [...this.works.values()]
45
- .filter((work) => !filter?.workId || work.workId === filter.workId)
79
+ const snapshot = this.read();
80
+ return snapshot.works.filter((work) => !filter?.workId || work.workId === filter.workId)
46
81
  .sort((left, right) => left.createdAt - right.createdAt)
47
- .map((work) => ({ ...work, tasks: this.listTodos({ workId: work.workId }) }));
82
+ .map((work) => ({ ...work, tasks: snapshot.todos.filter((todo) => todo.workId === work.workId).sort((left, right) => left.createdAt - right.createdAt) }));
48
83
  }
49
84
  listTodos(filter) {
50
- return [...this.todos.values()]
85
+ return this.read().todos
51
86
  .filter((todo) => !filter?.taskId || todo.taskId === filter.taskId)
52
87
  .filter((todo) => !filter?.workId || todo.workId === filter.workId)
53
88
  .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;
89
+ .sort((left, right) => left.createdAt - right.createdAt);
60
90
  }
61
- getTodo(taskId) {
62
- const todo = this.todos.get(taskId);
63
- return todo ? this.snapshot(todo) : undefined;
91
+ getWork(workId) { return this.read().works.find((work) => work.workId === workId); }
92
+ getTodo(taskId) { return this.read().todos.find((todo) => todo.taskId === taskId); }
93
+ getFocusedTodo() {
94
+ const snapshot = this.read();
95
+ return snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
64
96
  }
65
- snapshot(todo) {
66
- return { ...todo, delegatedTimes: todo.delegatedTimes?.map((source) => ({ ...source })), workingSince: todo.taskId === this.focusedTaskId ? this.workingSince : undefined };
67
- }
68
- /** Gate the selected task on actual agent execution, not task status. */
69
97
  setAgentRunning(running) {
70
- if (this.agentRunning === running)
98
+ // Timing hooks run before storage initialization and after failed startup too.
99
+ if (!this.binding)
71
100
  return;
72
- if (!running)
73
- this.saveInterval();
74
- this.agentRunning = running;
75
- if (running && this.focusedTaskId)
76
- this.workingSince = Date.now();
77
- this.onChange();
101
+ if (this.read().agentRunning === running)
102
+ return;
103
+ this.change((snapshot) => {
104
+ if (!running)
105
+ saveInterval(snapshot);
106
+ snapshot.agentRunning = running;
107
+ const todo = snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
108
+ if (running && todo)
109
+ todo.workingSince = Date.now();
110
+ });
78
111
  }
79
112
  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();
113
+ this.change((snapshot) => selectWorking(snapshot, taskId, working));
101
114
  }
102
115
  clearWorking() {
103
- this.saveInterval();
104
- this.focusedTaskId = undefined;
105
- this.onChange();
116
+ // Every run boundary also ends an explicit pause.
117
+ this.autoTimingPaused = false;
118
+ if (!this.binding)
119
+ return;
120
+ if (!this.read().focusedTaskId)
121
+ return;
122
+ this.change((snapshot) => { saveInterval(snapshot); delete snapshot.focusedTaskId; });
106
123
  }
107
- saveInterval() {
108
- if (!this.focusedTaskId || this.workingSince === undefined)
124
+ /**
125
+ * Select the only eligible task when execution begins, so routine work needs
126
+ * no separate working=true call. Explicit choices and pauses always win, and
127
+ * timing starts only while the agent is actually running.
128
+ */
129
+ autoSelectWorking() {
130
+ if (!this.binding || this.autoTimingPaused)
109
131
  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;
132
+ if (!soleEligibleTask(this.read()))
133
+ return;
134
+ this.change((snapshot) => {
135
+ const taskId = soleEligibleTask(snapshot);
136
+ if (taskId !== undefined)
137
+ selectWorking(snapshot, taskId, true);
138
+ });
117
139
  }
118
140
  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 };
141
+ return this.change((snapshot) => {
142
+ if (snapshot.works.length >= MAX_WORKS)
143
+ throw new Error(`Maximum of ${MAX_WORKS} works reached.`);
144
+ const now = Date.now();
145
+ const work = { workId: `W${snapshot.nextWorkId++}`, workName: requiredName(workName, "workName"), workInfo: requiredText(workInfo, "workInfo"), createdAt: now, updatedAt: now };
146
+ snapshot.works.push(work);
147
+ return work;
148
+ });
131
149
  }
132
150
  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"),
151
+ return this.change((snapshot) => {
152
+ const work = snapshot.works.find((work) => work.workId === workId);
153
+ if (!work)
154
+ throw new Error(`Work ${workId} not found.`);
155
+ const normalized = compactPatch({ workName: patch.workName === undefined ? undefined : requiredName(patch.workName, "workName"), workInfo: patch.workInfo === undefined ? undefined : requiredText(patch.workInfo, "workInfo") });
156
+ if (Object.keys(normalized).length === 0)
157
+ throw new Error("WorkUpdate requires at least one changed field.");
158
+ Object.assign(work, normalized, { updatedAt: Date.now() });
159
+ return work;
138
160
  });
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
161
  }
144
162
  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;
151
- }
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 };
163
+ return this.change((snapshot) => {
164
+ if (!snapshot.works.some((work) => work.workId === workId))
165
+ return false;
166
+ if (snapshot.todos.some((todo) => todo.workId === workId && !isUnstartedTask(todo)))
167
+ throw new Error("A Work holding retained tasks cannot be deleted; only a task with no recorded work may be removed.");
168
+ if (snapshot.todos.some((todo) => todo.workId === workId && todo.taskId === snapshot.focusedTaskId)) {
169
+ saveInterval(snapshot);
170
+ delete snapshot.focusedTaskId;
171
+ }
172
+ snapshot.works = snapshot.works.filter((work) => work.workId !== workId);
173
+ snapshot.todos = snapshot.todos.filter((todo) => todo.workId !== workId);
174
+ return true;
175
+ });
174
176
  }
175
- 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,
177
+ createTodo(input) {
178
+ const { workId, taskName, taskInfo, goal, finalThoughts, completionPercent } = input;
179
+ return this.change((snapshot) => {
180
+ if (!snapshot.works.some((work) => work.workId === workId))
181
+ throw new Error(`Work ${workId} not found.`);
182
+ if (snapshot.todos.length >= MAX_TODOS)
183
+ throw new Error(`Maximum of ${MAX_TODOS} todos reached.`);
184
+ validateCompletion("active", completionPercent);
185
+ const now = Date.now();
186
+ const worktree = process.env.PI_WORKTREE_NAME;
187
+ if (worktree !== undefined && !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(worktree))
188
+ throw new Error("Invalid inherited worktree name.");
189
+ const todo = { taskId: `T${snapshot.nextTaskId++}`, workId, taskName: requiredName(taskName, "taskName"), revision: 1, goal: normalizeGoal(goal, 1), ...(worktree === undefined ? {} : { worktree }), taskInfo: requiredText(taskInfo, "taskInfo"), finalThoughts: optionalThoughts(finalThoughts), status: "active",
190
+ completionPercent: completionPercent ?? null, elapsedMs: 0, createdAt: now, updatedAt: now };
191
+ snapshot.todos.push(todo);
192
+ return todo;
188
193
  });
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
- }
203
- /** Replace a cumulative assignment snapshot, never add it again on retry. */
204
- 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 });
216
194
  }
217
- 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;
224
- }
225
- record(event) {
226
- this.pi.appendEntry(TASK_ENTRY_TYPE, event);
227
- this.apply(event);
228
- this.onChange();
195
+ setGoal(taskId, input) {
196
+ return this.change((snapshot) => {
197
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
198
+ if (!todo)
199
+ throw new Error("Goal updates require an existing task.");
200
+ const next = normalizeGoal(input, (todo.goal?.revision ?? 0) + 1);
201
+ if (todo.goal && todo.goal.goal === next.goal && JSON.stringify(todo.goal.criteria) === JSON.stringify(next.criteria))
202
+ return todo;
203
+ if (todo.status !== "active" && todo.status !== "blocked")
204
+ throw new Error("Return the task to active before changing its goal.");
205
+ if (snapshot.focusedTaskId === taskId) {
206
+ saveInterval(snapshot);
207
+ delete snapshot.focusedTaskId;
208
+ }
209
+ todo.goal = next;
210
+ todo.revision = (todo.revision ?? 0) + 1;
211
+ todo.updatedAt = Date.now();
212
+ return todo;
213
+ });
229
214
  }
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;
215
+ updateTodo(taskId, patch) {
216
+ if (patch.working === false)
217
+ this.autoTimingPaused = true;
218
+ const todo = this.change((snapshot) => {
219
+ const current = snapshot.todos.find((todo) => todo.taskId === taskId);
220
+ if (!current)
221
+ throw new Error(`Todo ${taskId} not found.`);
222
+ const status = patch.status ?? current.status;
223
+ if (current.status === "closed" && (status !== "closed" || patch.taskInfo === undefined || patch.taskName !== undefined || patch.finalThoughts !== undefined || patch.blockedReason !== undefined || patch.dependentOn !== undefined || patch.decisionQuestionId !== undefined || patch.completionPercent !== undefined || patch.working !== undefined))
224
+ throw new Error("Reopen this closed task through an explicit human decision before editing it.");
225
+ if (status === "closed" && current.status !== "completed" && current.status !== "closed")
226
+ throw new Error("Close a task after its verified completion.");
227
+ if (status === "cancelled" && current.status !== "cancelled")
228
+ throw new Error("Cancellation requires explicit human authorization.");
229
+ if (current.status === "cancelled" && status !== "cancelled")
230
+ throw new Error("Reopening a cancelled task requires explicit human authorization.");
231
+ const transitioned = status !== current.status;
232
+ validateCompletion(status, patch.completionPercent);
233
+ const blockedReason = normalizeBlockedReason(status, patch.blockedReason, current);
234
+ const dependency = normalizeDependency(status, patch.dependentOn, current);
235
+ const dependencyCleared = (patch.dependentOn !== undefined || transitioned) && dependency === undefined;
236
+ const decisionQuestionId = normalizeDecisionQuestionId(status, dependency, patch.decisionQuestionId, current);
237
+ const decisionQuestionCleared = status !== "blocked" || dependency !== "user-decision";
238
+ // A different blocked class is a new wait, so its age starts now; an
239
+ // unrelated edit to a blocked record preserves the recorded start.
240
+ const blockedClassChanged = status === "blocked"
241
+ && (current.status !== "blocked" || current.dependentOn !== dependency);
242
+ const normalized = compactPatch({
243
+ taskName: patch.taskName === undefined ? undefined : requiredName(patch.taskName, "taskName"),
244
+ taskInfo: patch.taskInfo === undefined ? undefined : requiredText(patch.taskInfo, "taskInfo"),
245
+ finalThoughts: optionalThoughts(patch.finalThoughts),
246
+ status: patch.status,
247
+ blockedReason: patch.blockedReason !== undefined || transitioned ? blockedReason : undefined,
248
+ dependentOn: patch.dependentOn !== undefined && dependency !== undefined ? dependency : undefined,
249
+ decisionQuestionId: decisionQuestionId === undefined ? undefined : decisionQuestionId,
250
+ completionPercent: patch.completionPercent,
251
+ });
252
+ if (Object.keys(normalized).length === 0 && patch.working === undefined && patch.finalThoughts === undefined)
253
+ throw new Error("TodoUpdate requires at least one changed field.");
254
+ const effective = { ...current, ...normalized };
255
+ const canWork = effective.status === "active" && taskOwner(effective.taskInfo) === "self";
256
+ if (patch.working === true && !canWork)
257
+ throw new Error("working=true requires an active task with owner: self in this session.");
258
+ if (snapshot.focusedTaskId === taskId && (!canWork || patch.working === false)) {
259
+ saveInterval(snapshot);
260
+ delete snapshot.focusedTaskId;
246
261
  }
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;
262
+ const changed = (patch.taskName !== undefined && normalized.taskName !== current.taskName)
263
+ || (patch.taskInfo !== undefined && normalized.taskInfo !== current.taskInfo)
264
+ || (patch.finalThoughts !== undefined && optionalThoughts(patch.finalThoughts) !== current.finalThoughts)
265
+ || transitioned
266
+ || (patch.blockedReason !== undefined && blockedReason !== current.blockedReason)
267
+ || (patch.dependentOn !== undefined && dependency !== current.dependentOn)
268
+ || (patch.decisionQuestionId !== undefined && decisionQuestionId !== current.decisionQuestionId)
269
+ || (patch.completionPercent !== undefined && patch.completionPercent !== current.completionPercent);
270
+ Object.assign(current, normalized, { updatedAt: Date.now() });
271
+ if (changed)
272
+ current.revision = (current.revision ?? 0) + 1;
273
+ if (dependencyCleared)
274
+ delete current.dependentOn;
275
+ if (decisionQuestionCleared)
276
+ delete current.decisionQuestionId;
277
+ if (status === "blocked") {
278
+ if (blockedClassChanged)
279
+ current.blockedAt = Date.now();
257
280
  }
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;
281
+ else
282
+ delete current.blockedAt;
283
+ // A new status is a new statement. Keep an explicitly supplied thought;
284
+ // otherwise drop the old one so blocked, resumed, and completed rows never
285
+ // show a stale message from the previous state. A completion without a
286
+ // thought stays honestly empty for historical callers.
287
+ if (patch.finalThoughts !== undefined) {
288
+ const thoughts = optionalThoughts(patch.finalThoughts);
289
+ if (thoughts === undefined)
290
+ delete current.finalThoughts;
291
+ else
292
+ current.finalThoughts = thoughts;
282
293
  }
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;
294
+ else if (transitioned) {
295
+ delete current.finalThoughts;
304
296
  }
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 });
309
- break;
297
+ current.completionPercent = taskCompletion(current);
298
+ if (patch.working !== undefined)
299
+ selectWorking(snapshot, taskId, patch.working);
300
+ return current;
301
+ });
302
+ // Becoming the only eligible task during a run is the moment its work begins.
303
+ this.autoSelectWorking();
304
+ return todo;
305
+ }
306
+ /** Record the one worker /close request for a completed delegated task. */
307
+ beginWorkerClose(taskId, terminalId, turn) {
308
+ return this.change((snapshot) => {
309
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
310
+ if (todo?.status !== "completed")
311
+ throw new Error("Worker /close requires a completed task.");
312
+ if (todo.workerClose?.request)
313
+ throw new Error("A worker close request was already recorded; inspect its outcome rather than sending it again.");
314
+ todo.workerClose = { ...todo.workerClose, request: { terminalId, turn, requestedAt: Date.now() } };
315
+ todo.revision = (todo.revision ?? 0) + 1;
316
+ todo.updatedAt = Date.now();
317
+ return todo;
318
+ });
319
+ }
320
+ /** Close a completed task after its worker /close was verified. */
321
+ closeWorker(taskId, terminalId) {
322
+ return this.change((snapshot) => {
323
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
324
+ if (todo?.status !== "completed" || todo.workerClose?.request?.terminalId !== terminalId)
325
+ throw new Error("A verified worker /close is required before this task can close.");
326
+ todo.workerClose = { ...todo.workerClose, outcome: "completed" };
327
+ todo.status = "closed";
328
+ todo.completionPercent = 100;
329
+ todo.revision = (todo.revision ?? 0) + 1;
330
+ todo.updatedAt = Date.now();
331
+ return todo;
332
+ });
333
+ }
334
+ /** Close a completed task whose worker is confirmed absent. */
335
+ closeAbsent(taskId) {
336
+ return this.change((snapshot) => {
337
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
338
+ if (todo?.status !== "completed")
339
+ throw new Error("Worker absence can be verified only for a completed task.");
340
+ todo.workerClose = { ...todo.workerClose, outcome: todo.workerClose?.request ? "unverified-absent" : "not-run-absent" };
341
+ todo.status = "closed";
342
+ todo.completionPercent = 100;
343
+ todo.revision = (todo.revision ?? 0) + 1;
344
+ todo.updatedAt = Date.now();
345
+ return todo;
346
+ });
347
+ }
348
+ applyHumanLifecycleDecision(taskId, expectedRevision, action, questionId, answeredAt, reason) {
349
+ const decided = this.change((snapshot) => {
350
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
351
+ if (!todo || (todo.revision ?? 0) !== expectedRevision)
352
+ throw new Error("Task changed since the decision was presented; request a new decision.");
353
+ if (action === "cancel" && (todo.status === "cancelled" || todo.status === "closed"))
354
+ throw new Error("Task is already closed or cancelled.");
355
+ if (action === "reopen" && todo.status !== "cancelled" && todo.status !== "closed")
356
+ throw new Error("Only a closed or cancelled task can be reopened here.");
357
+ if (snapshot.focusedTaskId === taskId) {
358
+ saveInterval(snapshot);
359
+ delete snapshot.focusedTaskId;
310
360
  }
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;
361
+ const recordedReason = reason?.trim();
362
+ todo.status = action === "cancel" ? "cancelled" : "active";
363
+ todo.lifecycleDecisions = [...(todo.lifecycleDecisions ?? []), { action, questionId, answeredAt, ...(recordedReason ? { reason: recordedReason } : {}) }];
364
+ todo.blockedReason = null;
365
+ delete todo.dependentOn;
366
+ delete todo.blockedAt;
367
+ delete todo.decisionQuestionId;
368
+ delete todo.finalThoughts;
369
+ if (todo.completionPercent === 100)
370
+ todo.completionPercent = null;
371
+ todo.revision = (todo.revision ?? 0) + 1;
372
+ todo.updatedAt = Date.now();
373
+ return todo;
374
+ });
375
+ // Reopened work resumes timing when it is the only eligible task.
376
+ if (action === "reopen")
377
+ this.autoSelectWorking();
378
+ return decided;
379
+ }
380
+ /** Bind an assignment to one worktree; rebinding an existing task is forbidden. */
381
+ setWorktree(taskId, worktree) {
382
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(worktree))
383
+ throw new Error("Invalid worktree name.");
384
+ const inherited = process.env.PI_WORKTREE_NAME;
385
+ if (inherited !== undefined && inherited !== worktree)
386
+ throw new Error("A worker cannot bind a task to a different worktree.");
387
+ this.change((snapshot) => {
388
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
389
+ if (!todo)
390
+ throw new Error(`Todo ${taskId} not found.`);
391
+ if (todo.worktree !== undefined && todo.worktree !== worktree)
392
+ throw new Error("Task is already bound to a different worktree.");
393
+ todo.worktree = worktree;
394
+ todo.revision = (todo.revision ?? 0) + 1;
395
+ todo.updatedAt = Date.now();
396
+ });
397
+ }
398
+ removeUnstartedDelegatedTime(taskId, reportPath) {
399
+ this.change((snapshot) => {
400
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
401
+ const source = todo?.delegatedTimes?.find((item) => item.reportPath === reportPath);
402
+ if (!todo || taskOwner(todo.taskInfo) !== "delegate" || !source)
403
+ throw new Error("Timing registration not found for this delegated task.");
404
+ if (source.workerSessionId !== undefined || source.elapsedMs !== null)
405
+ throw new Error("Cannot remove measured delegated timing.");
406
+ todo.delegatedTimes = todo.delegatedTimes?.filter((item) => item.reportPath !== reportPath);
407
+ if (!todo.delegatedTimes?.length)
408
+ delete todo.delegatedTimes;
409
+ });
410
+ }
411
+ setDelegatedTime(taskId, source) {
412
+ this.change((snapshot) => {
413
+ const todo = snapshot.todos.find((todo) => todo.taskId === taskId);
414
+ if (!todo || taskOwner(todo.taskInfo) !== "delegate")
415
+ throw new Error("Delegated timing requires an existing owner: delegate task.");
416
+ if (!validDelegatedTime(source))
417
+ throw new Error("Invalid delegated timing source.");
418
+ const previous = todo.delegatedTimes?.find((entry) => entry.reportPath === source.reportPath);
419
+ if (previous?.workerSessionId && source.workerSessionId && previous.workerSessionId !== source.workerSessionId)
420
+ throw new Error("Timing report belongs to another worker session.");
421
+ if (previous?.reportRoot && source.reportRoot && previous.reportRoot !== source.reportRoot)
422
+ throw new Error("Timing report root cannot change.");
423
+ const workerSessionId = source.workerSessionId ?? previous?.workerSessionId;
424
+ const reportRoot = source.reportRoot ?? previous?.reportRoot;
425
+ const elapsedMs = source.workerSessionId === undefined && previous?.workerSessionId ? previous.elapsedMs : source.elapsedMs;
426
+ todo.delegatedTimes = [...(todo.delegatedTimes ?? []).filter((entry) => entry.reportPath !== source.reportPath), { ...source, elapsedMs, ...(reportRoot === undefined ? {} : { reportRoot }), ...(workerSessionId === undefined ? {} : { workerSessionId }) }];
427
+ });
428
+ }
429
+ deleteTodo(taskId) {
430
+ return this.change((snapshot) => {
431
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
432
+ if (!todo)
433
+ return false;
434
+ if (!isUnstartedTask(todo))
435
+ throw new Error("Retained tasks cannot be deleted; only a task with no recorded work may be removed.");
436
+ if (snapshot.focusedTaskId === taskId) {
437
+ saveInterval(snapshot);
438
+ delete snapshot.focusedTaskId;
318
439
  }
319
- case "todo-deleted":
320
- this.todos.delete(event.taskId);
321
- break;
440
+ snapshot.todos = snapshot.todos.filter((todo) => todo.taskId !== taskId);
441
+ return true;
442
+ });
443
+ }
444
+ }
445
+ /** An active, self-owned task is the only timing candidate. */
446
+ function soleEligibleTask(snapshot) {
447
+ if (!snapshot.agentRunning || snapshot.focusedTaskId !== undefined)
448
+ return undefined;
449
+ const eligible = snapshot.todos.filter((todo) => todo.status === "active" && taskOwner(todo.taskInfo) === "self" && !todo.delegatedTimes?.length);
450
+ return eligible.length === 1 ? eligible[0].taskId : undefined;
451
+ }
452
+ function saveInterval(snapshot) {
453
+ const todo = snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
454
+ if (!todo || todo.workingSince === undefined)
455
+ return;
456
+ todo.elapsedMs = (todo.elapsedMs ?? 0) + Math.max(0, Date.now() - todo.workingSince);
457
+ delete todo.workingSince;
458
+ }
459
+ function selectWorking(snapshot, taskId, working) {
460
+ const todo = snapshot.todos.find((todo) => todo.taskId === taskId);
461
+ if (!todo)
462
+ throw new Error(`Todo ${taskId} not found.`);
463
+ if (!working) {
464
+ if (snapshot.focusedTaskId === taskId) {
465
+ saveInterval(snapshot);
466
+ delete snapshot.focusedTaskId;
322
467
  }
468
+ return;
323
469
  }
470
+ if (todo.status !== "active" || taskOwner(todo.taskInfo) !== "self")
471
+ throw new Error("working=true requires an active task with owner: self in this session.");
472
+ if (snapshot.focusedTaskId === taskId)
473
+ return;
474
+ saveInterval(snapshot);
475
+ snapshot.focusedTaskId = taskId;
476
+ todo.elapsedMs ??= 0;
477
+ if (snapshot.agentRunning)
478
+ todo.workingSince = Date.now();
324
479
  }
325
- function restoredReason(value) {
326
- return typeof value === "string" && value.trim() ? value.trim() : null;
480
+ function legacyEntries(ctx) {
481
+ const entries = ctx.sessionManager.getBranch();
482
+ const tasks = entries.filter((entry) => entry.type === "custom" && entry.customType === TASK_ENTRY_TYPE);
483
+ const parent = ctx.sessionManager.getHeader()?.parentSession;
484
+ if (!parent || tasks.length === 0)
485
+ return entries;
486
+ const inherited = new Set();
487
+ let contents;
488
+ try {
489
+ contents = readFileSync(parent, "utf8");
490
+ }
491
+ catch {
492
+ 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.");
493
+ }
494
+ for (const line of contents.split("\n")) {
495
+ if (!line.includes(TASK_ENTRY_TYPE))
496
+ continue;
497
+ try {
498
+ const entry = JSON.parse(line);
499
+ if (entry?.type === "custom" && entry.customType === TASK_ENTRY_TYPE)
500
+ inherited.add(`${entry.id}:${entry.timestamp}`);
501
+ }
502
+ catch { /* A malformed parent line cannot be a valid inherited task event. */ }
503
+ }
504
+ return tasks.some((entry) => !inherited.has(`${entry.id}:${entry.timestamp}`)) ? entries : [];
327
505
  }
506
+ /** Compatibility reducer used only when a session has no JSON task store yet. */
507
+ function applyEvent(snapshot, event) {
508
+ switch (event.type) {
509
+ case "work-created": {
510
+ assertId(event.work.workId, "W");
511
+ 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 };
512
+ snapshot.works = [...snapshot.works.filter((item) => item.workId !== work.workId), work];
513
+ snapshot.nextWorkId = Math.max(snapshot.nextWorkId, Number(work.workId.slice(1)) + 1);
514
+ break;
515
+ }
516
+ case "work-updated": {
517
+ const work = snapshot.works.find((work) => work.workId === event.workId);
518
+ if (work)
519
+ Object.assign(work, compactPatch({ workName: typeof event.patch.workName === "string" ? requiredName(event.patch.workName, "workName") : undefined, workInfo: event.patch.workInfo }), { updatedAt: event.at });
520
+ break;
521
+ }
522
+ case "work-deleted":
523
+ snapshot.works = snapshot.works.filter((work) => work.workId !== event.workId);
524
+ snapshot.todos = snapshot.todos.filter((todo) => todo.workId !== event.workId);
525
+ break;
526
+ case "todo-created": {
527
+ assertId(event.todo.taskId, "T");
528
+ const status = restoredStatus(event.todo.status);
529
+ if (!status)
530
+ throw new Error("Malformed legacy task status.");
531
+ const todo = { ...event.todo, taskName: requiredName(event.todo.taskName, "taskName"), taskInfo: requiredText(event.todo.taskInfo, "taskInfo"),
532
+ finalThoughts: optionalThoughts(typeof event.todo.finalThoughts === "string" ? event.todo.finalThoughts : undefined), status,
533
+ blockedReason: status === "blocked" ? restoredReason(event.todo.blockedReason) : null,
534
+ ...(status === "blocked" && isTaskDependency(event.todo.dependentOn) ? { dependentOn: event.todo.dependentOn } : {}),
535
+ completionPercent: taskCompletion({ ...event.todo, status }), elapsedMs: validElapsed(event.todo.elapsedMs) ? event.todo.elapsedMs : null, delegatedTimes: undefined, workingSince: undefined };
536
+ if (snapshot.works.some((work) => work.workId === todo.workId))
537
+ snapshot.todos = [...snapshot.todos.filter((item) => item.taskId !== todo.taskId), todo];
538
+ snapshot.nextTaskId = Math.max(snapshot.nextTaskId, Number(todo.taskId.slice(1)) + 1);
539
+ break;
540
+ }
541
+ case "todo-updated": {
542
+ const todo = snapshot.todos.find((todo) => todo.taskId === event.taskId);
543
+ if (!todo)
544
+ break;
545
+ const patch = event.patch;
546
+ const status = restoredStatus(patch.status) ?? todo.status;
547
+ const transitioned = status !== todo.status;
548
+ const dependency = status === "blocked"
549
+ ? patch.dependentOn !== undefined ? (isTaskDependency(patch.dependentOn) ? patch.dependentOn : todo.dependentOn) : todo.dependentOn
550
+ : undefined;
551
+ Object.assign(todo, compactPatch({ taskName: typeof patch.taskName === "string" ? requiredName(patch.taskName, "taskName") : undefined, taskInfo: patch.taskInfo, completionPercent: patch.completionPercent }), {
552
+ status, blockedReason: status === "blocked" ? patch.blockedReason !== undefined ? restoredReason(patch.blockedReason) : todo.blockedReason : null, updatedAt: event.at,
553
+ });
554
+ if (dependency === undefined)
555
+ delete todo.dependentOn;
556
+ else
557
+ todo.dependentOn = dependency;
558
+ if (typeof patch.finalThoughts === "string") {
559
+ const thoughts = optionalThoughts(patch.finalThoughts);
560
+ if (thoughts === undefined)
561
+ delete todo.finalThoughts;
562
+ else
563
+ todo.finalThoughts = thoughts;
564
+ }
565
+ else if (transitioned) {
566
+ delete todo.finalThoughts;
567
+ }
568
+ todo.completionPercent = taskCompletion(todo);
569
+ break;
570
+ }
571
+ case "todo-time": {
572
+ const todo = snapshot.todos.find((todo) => todo.taskId === event.taskId);
573
+ if (todo && validElapsed(event.elapsedMs))
574
+ todo.elapsedMs = event.elapsedMs;
575
+ break;
576
+ }
577
+ case "todo-delegated-time": {
578
+ const todo = snapshot.todos.find((todo) => todo.taskId === event.taskId);
579
+ if (todo && validDelegatedTime(event.source))
580
+ todo.delegatedTimes = [...(todo.delegatedTimes ?? []).filter((source) => source.reportPath !== event.source.reportPath), { ...event.source }];
581
+ break;
582
+ }
583
+ case "todo-deleted":
584
+ snapshot.todos = snapshot.todos.filter((todo) => todo.taskId !== event.taskId);
585
+ break;
586
+ }
587
+ }
588
+ function restoredReason(value) { return typeof value === "string" && value.trim() ? value.trim() : null; }
328
589
  function normalizeBlockedReason(status, supplied, current) {
329
590
  if (status !== "blocked") {
330
591
  if (supplied !== undefined && supplied !== null)
@@ -340,24 +601,56 @@ function normalizeBlockedReason(status, supplied, current) {
340
601
  throw new Error("blockedReason must not exceed 10000 characters.");
341
602
  return reason;
342
603
  }
604
+ function normalizeDependency(status, supplied, current) {
605
+ if (status !== "blocked") {
606
+ if (supplied !== undefined && supplied !== null)
607
+ throw new Error("dependentOn is only valid for blocked tasks.");
608
+ return undefined;
609
+ }
610
+ if (supplied === undefined && current?.status === "blocked")
611
+ return current.dependentOn;
612
+ if (!isTaskDependency(supplied))
613
+ throw new Error("Blocked tasks require dependentOn=\"user-decision\" or dependentOn=\"another-agent\".");
614
+ return supplied;
615
+ }
616
+ function normalizeDecisionQuestionId(status, dependency, supplied, current) {
617
+ if (status !== "blocked" || dependency !== "user-decision") {
618
+ if (supplied !== undefined)
619
+ throw new Error("decisionQuestionId is only valid for a task blocked on user-decision.");
620
+ return undefined;
621
+ }
622
+ if (supplied === undefined)
623
+ return current.status === "blocked" && current.dependentOn === "user-decision" ? current.decisionQuestionId : undefined;
624
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(supplied))
625
+ throw new Error("decisionQuestionId must be a pi-decisions question ID.");
626
+ return supplied;
627
+ }
343
628
  function validDelegatedTime(value) {
344
629
  return !!value && typeof value.reportPath === "string" && value.reportPath.length > 0
630
+ && (value.reportRoot === undefined || (typeof value.reportRoot === "string" && value.reportRoot.length > 0))
345
631
  && (value.elapsedMs === null || validElapsed(value.elapsedMs))
346
632
  && (value.workerSessionId === undefined || (typeof value.workerSessionId === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value.workerSessionId)));
347
633
  }
348
- function validElapsed(value) {
349
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
350
- }
634
+ function validElapsed(value) { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; }
351
635
  function validateCompletion(status, value) {
352
636
  if (value === undefined || value === null)
353
637
  return;
354
638
  if (!Number.isInteger(value) || value < 0 || value > 100)
355
639
  throw new Error("completionPercent must be an integer from 0 to 100, or null for unknown.");
356
- if (value === 100 && status !== "completed")
640
+ if (value === 100 && status !== "completed" && status !== "closed")
357
641
  throw new Error("100% requires verified completion. Set status to completed after verification.");
358
- if (status === "completed" && value !== 100)
642
+ if ((status === "completed" || status === "closed") && value !== 100)
359
643
  throw new Error("Completed tasks have 100% progress. Reopen the task before reporting partial progress.");
360
644
  }
645
+ function isUnstartedTask(todo) {
646
+ return (todo.status === "active" || todo.status === "blocked") && (todo.elapsedMs ?? 0) === 0
647
+ && !todo.delegatedTimes?.length && !todo.lifecycleDecisions?.length && !todo.closeoutAttempts?.length && !todo.workerClose;
648
+ }
649
+ function normalizeGoal(input, revision) {
650
+ if (!Array.isArray(input.criteria) || input.criteria.length === 0)
651
+ throw new Error("At least one acceptance criterion is required.");
652
+ return { goal: requiredText(input.goal, "goal"), criteria: input.criteria.map((criterion) => requiredText(criterion, "criterion")), revision };
653
+ }
361
654
  function requiredText(value, field) {
362
655
  const text = value.trim();
363
656
  if (!text)
@@ -370,20 +663,19 @@ function requiredName(value, field) {
370
663
  throw new Error(`${field} must not be empty.`);
371
664
  return text;
372
665
  }
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;
666
+ /** Visible thoughts are one optional concise string; empty input clears it. */
667
+ function optionalThoughts(value) {
668
+ if (value === undefined || value === null)
669
+ return undefined;
670
+ const text = value.trim();
671
+ return text || undefined;
379
672
  }
673
+ function compactPatch(patch) { return Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)); }
380
674
  function assertId(id, prefix) {
381
- if (typeof id !== "string" || !new RegExp(`^${prefix}[1-9]\\d*$`).test(id) || !Number.isSafeInteger(Number(id.slice(1)))) {
675
+ if (typeof id !== "string" || !new RegExp(`^${prefix}[1-9]\\d*$`).test(id) || !Number.isSafeInteger(Number(id.slice(1))))
382
676
  throw new Error(`Malformed ${prefix === "W" ? "work" : "todo"} ID.`);
383
- }
384
677
  }
385
678
  function restoredStatus(value) {
386
- // Keep legacy branch events readable without exposing retired statuses in tools.
387
679
  if (value === "planned" || value === "pending")
388
680
  return "active";
389
681
  if (value === "active" || value === "blocked" || value === "completed" || value === "cancelled")