@abhishek944/pi-tasks 0.16.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.
package/dist/index.js CHANGED
@@ -1,6 +1,9 @@
1
+ /** Session-scoped work and todo tracking for Pi. */
2
+ import { basename } from "node:path";
1
3
  import { registerDelegationBridge } from "./agents/delegation.js";
2
4
  import { delegateLink, focusTerminal } from "./agents/links.js";
3
5
  import { registerTaskAutoContinue } from "./auto-continue.js";
6
+ import { blockedAuditPrompt } from "./blocked.js";
4
7
  import { registerWorksCommand } from "./command.js";
5
8
  import { registerDelegatedTimeTools } from "./delegated-time.js";
6
9
  import { GitStatusCache } from "./git-status.js";
@@ -21,6 +24,12 @@ export default function tasksExtension(pi) {
21
24
  const getOpenCommand = () => readOpenCommand(getSettings());
22
25
  let visibleMode = "floating";
23
26
  panel = new TasksPanelHost(state, git, getOpenCommand);
27
+ // A refreshed viewer is a package upgrade, not a failure; keep the replaced files findable.
28
+ const notifyModRefresh = (ctx, status) => {
29
+ if (!status?.backups.length)
30
+ return;
31
+ ctx.ui.notify(`Refreshed the installed Herdr Tasks mod for this pi-tasks version. Previous files: ${status.backups.map((path) => basename(path)).join(", ")}.`, "info");
32
+ };
24
33
  async function openHerdrTasksPaneOnStart(ctx) {
25
34
  if (!process.env.HC_TERMINAL_ID)
26
35
  return;
@@ -35,7 +44,8 @@ export default function tasksExtension(pi) {
35
44
  if (!enabled)
36
45
  return;
37
46
  try {
38
- await setHerdrTasksPaneVisible(ctx, true, state.snapshotPath, getOpenCommand(), { replaceStale: true });
47
+ const status = await setHerdrTasksPaneVisible(ctx, true, state.snapshotPath, getOpenCommand(), { replaceStale: true });
48
+ notifyModRefresh(ctx, status);
39
49
  }
40
50
  catch {
41
51
  // The native pane is an optional display; /works herdr-on reports the reason.
@@ -51,8 +61,9 @@ export default function tasksExtension(pi) {
51
61
  if (requested === "herdr-on" || requested === "herdr-off") {
52
62
  try {
53
63
  const visible = requested === "herdr-on";
54
- await setHerdrTasksPaneVisible(ctx, visible, visible ? state.snapshotPath : "", visible ? getOpenCommand() : undefined);
64
+ const status = await setHerdrTasksPaneVisible(ctx, visible, visible ? state.snapshotPath : "", visible ? getOpenCommand() : undefined);
55
65
  ctx.ui.notify(visible ? "Opened the Herdr Tasks pane." : "Closed this session’s Herdr Tasks pane.", "info");
66
+ notifyModRefresh(ctx, status);
56
67
  }
57
68
  catch (error) {
58
69
  ctx.ui.notify(error instanceof Error ? safeSingleLine(error.message) : "Could not change the Herdr Tasks pane visibility.", "error");
@@ -123,6 +134,24 @@ export default function tasksExtension(pi) {
123
134
  panel?.attach(ctx.ui, ctx.cwd, ctx.sessionManager.getSessionId());
124
135
  await openHerdrTasksPaneOnStart(ctx);
125
136
  }
137
+ // A reload/restart stops decision watchers and agent monitors. Surface every
138
+ // blocked record once for any restored start (startup, /reload, resume) so a
139
+ // stale blocker cannot survive silently. A fresh fork keeps its isolation; a
140
+ // new session has no inherited store. This audit changes nothing itself.
141
+ if (event.reason === "startup" || event.reason === "reload" || event.reason === "resume") {
142
+ const audit = blockedAuditPrompt(state.listTodos({ status: "blocked" }));
143
+ if (audit) {
144
+ pi.sendMessage({
145
+ customType: "pi-tasks-review",
146
+ content: [
147
+ "[pi-tasks] Session-start blocked-task audit after a resume. No task status was changed; reloads and session switches stop decision watchers and agent monitors, so a retained blocker may no longer have a live wake.",
148
+ audit,
149
+ "If a linked decision page is still needed, call WaitForAnswer once to re-arm its watcher. If it is superseded, withdraw it and update every linked task in the same turn. Do not clear a genuine blocker or change a task merely to end this audit.",
150
+ ].join("\n\n"),
151
+ display: true,
152
+ }, { triggerTurn: true, deliverAs: "followUp" });
153
+ }
154
+ }
126
155
  });
127
156
  pi.on("tool_result", (event) => {
128
157
  if (event.toolName === "write" || event.toolName === "edit" || event.toolName === "bash")
package/dist/progress.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export function taskCompletion(todo) {
2
- if (todo.status === "completed")
2
+ if (todo.status === "completed" || todo.status === "closed")
3
3
  return 100;
4
4
  const value = todo.completionPercent;
5
5
  return typeof value === "number" && Number.isInteger(value) && value >= 0 && value < 100 ? value : null;
package/dist/snapshot.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
- import { dirname, join } from "node:path";
3
+ import { dirname, isAbsolute, join } from "node:path";
4
4
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
5
  import { isTaskDependency } from "./dependency.js";
6
6
  import { taskOwner } from "./ownership.js";
@@ -40,23 +40,66 @@ export function validateSnapshot(value, sessionId) {
40
40
  for (const todo of value.todos) {
41
41
  if (!object(todo) || !id(todo.taskId, "T") || todos.has(todo.taskId) || !text(todo.workId) || !works.has(todo.workId)
42
42
  || !text(todo.taskName) || !text(todo.taskInfo) || !integer(todo.createdAt) || !integer(todo.updatedAt)
43
+ || (todo.revision !== undefined && (!integer(todo.revision) || todo.revision < 1))
44
+ || (todo.worktree !== undefined && (typeof todo.worktree !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(todo.worktree)))
43
45
  || (todo.finalThoughts !== undefined && !text(todo.finalThoughts))
44
- || !["active", "blocked", "completed", "cancelled"].includes(String(todo.status))
46
+ || !["active", "blocked", "completed", "closed", "cancelled"].includes(String(todo.status))
45
47
  || Number(todo.taskId.slice(1)) >= value.nextTaskId
46
48
  || (todo.blockedReason !== undefined && todo.blockedReason !== null && !text(todo.blockedReason))
47
49
  || (todo.status !== "blocked" && todo.blockedReason != null)
48
50
  || (todo.dependentOn !== undefined && (todo.status !== "blocked" || !isTaskDependency(todo.dependentOn)))
51
+ || (todo.blockedAt !== undefined && (todo.status !== "blocked" || !integer(todo.blockedAt)))
52
+ || (todo.decisionQuestionId !== undefined && (todo.status !== "blocked" || todo.dependentOn !== "user-decision" || typeof todo.decisionQuestionId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(todo.decisionQuestionId)))
49
53
  || (todo.completionPercent != null && (!integer(todo.completionPercent) || todo.completionPercent > 100))
50
- || (todo.status === "completed" && todo.completionPercent !== 100)
51
- || (todo.status !== "completed" && todo.completionPercent === 100)
54
+ || ((todo.status === "completed" || todo.status === "closed") && todo.completionPercent !== 100)
55
+ || (todo.status !== "completed" && todo.status !== "closed" && todo.completionPercent === 100)
52
56
  || (todo.elapsedMs != null && !integer(todo.elapsedMs)))
53
57
  return invalid();
58
+ if (todo.goal !== undefined) {
59
+ if (!object(todo.goal) || !text(todo.goal.goal) || !Array.isArray(todo.goal.criteria) || todo.goal.criteria.length === 0
60
+ || !todo.goal.criteria.every(text) || !integer(todo.goal.revision) || todo.goal.revision < 1)
61
+ return invalid();
62
+ if (todo.goal.confirmation !== undefined && (!object(todo.goal.confirmation) || todo.goal.confirmation.revision !== todo.goal.revision
63
+ || !text(todo.goal.confirmation.questionId) || !text(todo.goal.confirmation.answeredAt)))
64
+ return invalid();
65
+ }
66
+ if (todo.lifecycleDecisions !== undefined && (!Array.isArray(todo.lifecycleDecisions) || todo.lifecycleDecisions.some((decision) => !object(decision) || !["cancel", "reopen"].includes(String(decision.action)) || !text(decision.questionId) || !text(decision.answeredAt) || (decision.reason !== undefined && !text(decision.reason)))))
67
+ return invalid();
68
+ if (todo.workerClose !== undefined) {
69
+ const close = todo.workerClose;
70
+ if (!object(close) || (close.request === undefined && close.outcome === undefined))
71
+ return invalid();
72
+ const request = close.request;
73
+ if (request !== undefined && (!object(request) || typeof request.terminalId !== "string" || !TERMINAL_ID.test(request.terminalId) || !integer(request.turn) || !integer(request.requestedAt)))
74
+ return invalid();
75
+ if (close.outcome !== undefined && close.outcome !== "not-run-absent" && close.outcome !== "unverified-absent" && close.outcome !== "completed")
76
+ return invalid();
77
+ }
78
+ if (todo.closeoutAttempts !== undefined) {
79
+ if (!Array.isArray(todo.closeoutAttempts))
80
+ return invalid();
81
+ for (const attempt of todo.closeoutAttempts) {
82
+ if (!object(attempt) || !text(attempt.questionId) || !Array.isArray(attempt.batchTaskIds) || !attempt.batchTaskIds.length || !attempt.batchTaskIds.every((item) => id(item, "T")) || new Set(attempt.batchTaskIds).size !== attempt.batchTaskIds.length || !attempt.batchTaskIds.includes(todo.taskId) || !integer(attempt.taskRevision) || !text(attempt.taskName) || !text(attempt.limits)
83
+ || !object(attempt.goal) || !text(attempt.goal.goal) || !integer(attempt.goal.revision) || !Array.isArray(attempt.goal.criteria) || !attempt.goal.criteria.length || !attempt.goal.criteria.every(text)
84
+ || !object(attempt.goal.confirmation) || attempt.goal.confirmation.revision !== attempt.goal.revision || !text(attempt.goal.confirmation.questionId) || !text(attempt.goal.confirmation.answeredAt)
85
+ || !Array.isArray(attempt.results) || attempt.results.length !== attempt.goal.criteria.length
86
+ || attempt.results.some((result) => !object(result) || !text(result.criterion) || !text(result.result) || !text(result.evidence))
87
+ || (attempt.decision !== undefined && (!object(attempt.decision) || typeof attempt.decision.approved !== "boolean" || !text(attempt.decision.answeredAt) || typeof attempt.decision.feedback !== "string"))
88
+ || (attempt.workerClose !== undefined && attempt.workerClose !== "not-run-absent" && attempt.workerClose !== "unverified-absent" && attempt.workerClose !== "completed")
89
+ || (attempt.workerCloseRequest !== undefined && (!object(attempt.workerCloseRequest) || typeof attempt.workerCloseRequest.terminalId !== "string" || !TERMINAL_ID.test(attempt.workerCloseRequest.terminalId) || !integer(attempt.workerCloseRequest.turn) || !integer(attempt.workerCloseRequest.requestedAt))))
90
+ return invalid();
91
+ const criteria = attempt.goal.criteria;
92
+ if (attempt.results.some((result, index) => !object(result) || result.criterion !== criteria[index]))
93
+ return invalid();
94
+ }
95
+ }
54
96
  if (todo.delegatedTimes !== undefined) {
55
97
  if (!Array.isArray(todo.delegatedTimes))
56
98
  return invalid();
57
99
  const reports = new Set();
58
100
  for (const source of todo.delegatedTimes) {
59
101
  if (!object(source) || !text(source.reportPath) || reports.has(source.reportPath)
102
+ || (source.reportRoot !== undefined && (!text(source.reportRoot) || !isAbsolute(source.reportRoot)))
60
103
  || (source.elapsedMs !== null && !integer(source.elapsedMs))
61
104
  || (source.workerSessionId !== undefined && (typeof source.workerSessionId !== "string" || !SESSION_ID.test(source.workerSessionId))))
62
105
  return invalid();
package/dist/state.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { type TaskDependency } from "./dependency.js";
3
2
  import type { DelegatedTime, Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
4
3
  /** Legacy session entries are read once for migration, never written again. */
5
4
  export declare const TASK_ENTRY_TYPE = "pi-tasks-state";
@@ -9,6 +8,8 @@ export declare const MAX_TODOS = 500;
9
8
  export declare class TaskState {
10
9
  private readonly onChange;
11
10
  private binding;
11
+ /** An explicit working=false pause lasts until the next run boundary. */
12
+ private autoTimingPaused;
12
13
  constructor(_pi: ExtensionAPI, onChange: () => void);
13
14
  get snapshotPath(): string;
14
15
  restore(ctx: ExtensionContext, freshFork?: boolean): void;
@@ -28,6 +29,12 @@ export declare class TaskState {
28
29
  setAgentRunning(running: boolean): void;
29
30
  setWorking(taskId: string, working: boolean): void;
30
31
  clearWorking(): void;
32
+ /**
33
+ * Select the only eligible task when execution begins, so routine work needs
34
+ * no separate working=true call. Explicit choices and pauses always win, and
35
+ * timing starts only while the agent is actually running.
36
+ */
37
+ autoSelectWorking(): void;
31
38
  createWork(workName: string, workInfo: string): Work;
32
39
  updateWork(workId: string, patch: Partial<Pick<Work, "workName" | "workInfo">>): Work;
33
40
  deleteWork(workId: string): boolean;
@@ -35,15 +42,30 @@ export declare class TaskState {
35
42
  workId: string;
36
43
  taskName: string;
37
44
  taskInfo: string;
45
+ goal: {
46
+ goal: string;
47
+ criteria: string[];
48
+ };
38
49
  finalThoughts?: string;
39
- status?: TodoStatus;
40
50
  completionPercent?: number | null;
41
- blockedReason?: string | null;
42
- dependentOn?: TaskDependency | null;
43
51
  }): Todo;
44
- updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "finalThoughts" | "status" | "blockedReason" | "dependentOn" | "completionPercent">> & {
52
+ setGoal(taskId: string, input: {
53
+ goal: string;
54
+ criteria: string[];
55
+ }): Todo;
56
+ updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "finalThoughts" | "status" | "blockedReason" | "dependentOn" | "decisionQuestionId" | "completionPercent">> & {
45
57
  working?: boolean;
46
58
  }): Todo;
59
+ /** Record the one worker /close request for a completed delegated task. */
60
+ beginWorkerClose(taskId: string, terminalId: string, turn: number): Todo;
61
+ /** Close a completed task after its worker /close was verified. */
62
+ closeWorker(taskId: string, terminalId: string): Todo;
63
+ /** Close a completed task whose worker is confirmed absent. */
64
+ closeAbsent(taskId: string): Todo;
65
+ applyHumanLifecycleDecision(taskId: string, expectedRevision: number, action: "cancel" | "reopen", questionId: string, answeredAt: string, reason?: string): Todo;
66
+ /** Bind an assignment to one worktree; rebinding an existing task is forbidden. */
67
+ setWorktree(taskId: string, worktree: string): void;
68
+ removeUnstartedDelegatedTime(taskId: string, reportPath: string): void;
47
69
  setDelegatedTime(taskId: string, source: DelegatedTime): void;
48
70
  deleteTodo(taskId: string): boolean;
49
71
  }
package/dist/state.js CHANGED
@@ -12,6 +12,8 @@ export const MAX_TODOS = 500;
12
12
  export class TaskState {
13
13
  onChange;
14
14
  binding;
15
+ /** An explicit working=false pause lasts until the next run boundary. */
16
+ autoTimingPaused = false;
15
17
  constructor(_pi, onChange) {
16
18
  this.onChange = onChange;
17
19
  }
@@ -111,12 +113,30 @@ export class TaskState {
111
113
  this.change((snapshot) => selectWorking(snapshot, taskId, working));
112
114
  }
113
115
  clearWorking() {
116
+ // Every run boundary also ends an explicit pause.
117
+ this.autoTimingPaused = false;
114
118
  if (!this.binding)
115
119
  return;
116
120
  if (!this.read().focusedTaskId)
117
121
  return;
118
122
  this.change((snapshot) => { saveInterval(snapshot); delete snapshot.focusedTaskId; });
119
123
  }
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)
131
+ return;
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
+ });
139
+ }
120
140
  createWork(workName, workInfo) {
121
141
  return this.change((snapshot) => {
122
142
  if (snapshot.works.length >= MAX_WORKS)
@@ -143,6 +163,8 @@ export class TaskState {
143
163
  return this.change((snapshot) => {
144
164
  if (!snapshot.works.some((work) => work.workId === workId))
145
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.");
146
168
  if (snapshot.todos.some((todo) => todo.workId === workId && todo.taskId === snapshot.focusedTaskId)) {
147
169
  saveInterval(snapshot);
148
170
  delete snapshot.focusedTaskId;
@@ -153,32 +175,70 @@ export class TaskState {
153
175
  });
154
176
  }
155
177
  createTodo(input) {
156
- const { workId, taskName, taskInfo, finalThoughts, status = "active", completionPercent, blockedReason, dependentOn } = input;
178
+ const { workId, taskName, taskInfo, goal, finalThoughts, completionPercent } = input;
157
179
  return this.change((snapshot) => {
158
180
  if (!snapshot.works.some((work) => work.workId === workId))
159
181
  throw new Error(`Work ${workId} not found.`);
160
182
  if (snapshot.todos.length >= MAX_TODOS)
161
183
  throw new Error(`Maximum of ${MAX_TODOS} todos reached.`);
162
- validateCompletion(status, completionPercent);
184
+ validateCompletion("active", completionPercent);
163
185
  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 };
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 };
167
191
  snapshot.todos.push(todo);
168
192
  return todo;
169
193
  });
170
194
  }
171
- updateTodo(taskId, patch) {
195
+ setGoal(taskId, input) {
172
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
+ });
214
+ }
215
+ updateTodo(taskId, patch) {
216
+ if (patch.working === false)
217
+ this.autoTimingPaused = true;
218
+ const todo = this.change((snapshot) => {
173
219
  const current = snapshot.todos.find((todo) => todo.taskId === taskId);
174
220
  if (!current)
175
221
  throw new Error(`Todo ${taskId} not found.`);
176
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.");
177
231
  const transitioned = status !== current.status;
178
232
  validateCompletion(status, patch.completionPercent);
179
233
  const blockedReason = normalizeBlockedReason(status, patch.blockedReason, current);
180
234
  const dependency = normalizeDependency(status, patch.dependentOn, current);
181
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);
182
242
  const normalized = compactPatch({
183
243
  taskName: patch.taskName === undefined ? undefined : requiredName(patch.taskName, "taskName"),
184
244
  taskInfo: patch.taskInfo === undefined ? undefined : requiredText(patch.taskInfo, "taskInfo"),
@@ -186,6 +246,7 @@ export class TaskState {
186
246
  status: patch.status,
187
247
  blockedReason: patch.blockedReason !== undefined || transitioned ? blockedReason : undefined,
188
248
  dependentOn: patch.dependentOn !== undefined && dependency !== undefined ? dependency : undefined,
249
+ decisionQuestionId: decisionQuestionId === undefined ? undefined : decisionQuestionId,
189
250
  completionPercent: patch.completionPercent,
190
251
  });
191
252
  if (Object.keys(normalized).length === 0 && patch.working === undefined && patch.finalThoughts === undefined)
@@ -198,9 +259,27 @@ export class TaskState {
198
259
  saveInterval(snapshot);
199
260
  delete snapshot.focusedTaskId;
200
261
  }
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);
201
270
  Object.assign(current, normalized, { updatedAt: Date.now() });
271
+ if (changed)
272
+ current.revision = (current.revision ?? 0) + 1;
202
273
  if (dependencyCleared)
203
274
  delete current.dependentOn;
275
+ if (decisionQuestionCleared)
276
+ delete current.decisionQuestionId;
277
+ if (status === "blocked") {
278
+ if (blockedClassChanged)
279
+ current.blockedAt = Date.now();
280
+ }
281
+ else
282
+ delete current.blockedAt;
204
283
  // A new status is a new statement. Keep an explicitly supplied thought;
205
284
  // otherwise drop the old one so blocked, resumed, and completed rows never
206
285
  // show a stale message from the previous state. A completion without a
@@ -220,6 +299,114 @@ export class TaskState {
220
299
  selectWorking(snapshot, taskId, patch.working);
221
300
  return current;
222
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;
360
+ }
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
+ });
223
410
  }
224
411
  setDelegatedTime(taskId, source) {
225
412
  this.change((snapshot) => {
@@ -229,15 +416,23 @@ export class TaskState {
229
416
  if (!validDelegatedTime(source))
230
417
  throw new Error("Invalid delegated timing source.");
231
418
  const previous = todo.delegatedTimes?.find((entry) => entry.reportPath === source.reportPath);
232
- if (previous?.workerSessionId && previous.workerSessionId !== source.workerSessionId)
419
+ if (previous?.workerSessionId && source.workerSessionId && previous.workerSessionId !== source.workerSessionId)
233
420
  throw new Error("Timing report belongs to another worker session.");
234
- todo.delegatedTimes = [...(todo.delegatedTimes ?? []).filter((entry) => entry.reportPath !== source.reportPath), { ...source }];
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 }) }];
235
427
  });
236
428
  }
237
429
  deleteTodo(taskId) {
238
430
  return this.change((snapshot) => {
239
- if (!snapshot.todos.some((todo) => todo.taskId === taskId))
431
+ const todo = snapshot.todos.find((item) => item.taskId === taskId);
432
+ if (!todo)
240
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.");
241
436
  if (snapshot.focusedTaskId === taskId) {
242
437
  saveInterval(snapshot);
243
438
  delete snapshot.focusedTaskId;
@@ -247,6 +442,13 @@ export class TaskState {
247
442
  });
248
443
  }
249
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
+ }
250
452
  function saveInterval(snapshot) {
251
453
  const todo = snapshot.todos.find((todo) => todo.taskId === snapshot.focusedTaskId);
252
454
  if (!todo || todo.workingSince === undefined)
@@ -275,9 +477,6 @@ function selectWorking(snapshot, taskId, working) {
275
477
  if (snapshot.agentRunning)
276
478
  todo.workingSince = Date.now();
277
479
  }
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
480
  function legacyEntries(ctx) {
282
481
  const entries = ctx.sessionManager.getBranch();
283
482
  const tasks = entries.filter((entry) => entry.type === "custom" && entry.customType === TASK_ENTRY_TYPE);
@@ -414,8 +613,21 @@ function normalizeDependency(status, supplied, current) {
414
613
  throw new Error("Blocked tasks require dependentOn=\"user-decision\" or dependentOn=\"another-agent\".");
415
614
  return supplied;
416
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
+ }
417
628
  function validDelegatedTime(value) {
418
629
  return !!value && typeof value.reportPath === "string" && value.reportPath.length > 0
630
+ && (value.reportRoot === undefined || (typeof value.reportRoot === "string" && value.reportRoot.length > 0))
419
631
  && (value.elapsedMs === null || validElapsed(value.elapsedMs))
420
632
  && (value.workerSessionId === undefined || (typeof value.workerSessionId === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value.workerSessionId)));
421
633
  }
@@ -425,11 +637,20 @@ function validateCompletion(status, value) {
425
637
  return;
426
638
  if (!Number.isInteger(value) || value < 0 || value > 100)
427
639
  throw new Error("completionPercent must be an integer from 0 to 100, or null for unknown.");
428
- if (value === 100 && status !== "completed")
640
+ if (value === 100 && status !== "completed" && status !== "closed")
429
641
  throw new Error("100% requires verified completion. Set status to completed after verification.");
430
- if (status === "completed" && value !== 100)
642
+ if ((status === "completed" || status === "closed") && value !== 100)
431
643
  throw new Error("Completed tasks have 100% progress. Reopen the task before reporting partial progress.");
432
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
+ }
433
654
  function requiredText(value, field) {
434
655
  const text = value.trim();
435
656
  if (!text)
package/dist/timing.js CHANGED
@@ -4,7 +4,13 @@ export function registerTaskTiming(pi, state) {
4
4
  let running = false;
5
5
  let prompts = 0;
6
6
  let detachAbort;
7
- const sync = () => state.setAgentRunning(running && prompts === 0 && areTrackingToolsActive(pi));
7
+ const sync = () => {
8
+ state.setAgentRunning(running && prompts === 0 && areTrackingToolsActive(pi));
9
+ // Work begins when the agent actually executes. With exactly one eligible
10
+ // confirmed task, timing starts without a separate working=true call;
11
+ // explicit choices and pauses still win inside the state.
12
+ state.autoSelectWorking();
13
+ };
8
14
  const pause = () => {
9
15
  running = false;
10
16
  detachAbort?.();