@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.
@@ -0,0 +1,100 @@
1
+ /** Count blocked tasks by the dependency class the record actually stores. */
2
+ export function blockedDependencyCounts(todos) {
3
+ const counts = { user: 0, agent: 0, unclassified: 0 };
4
+ for (const todo of todos) {
5
+ if (todo.status !== "blocked")
6
+ continue;
7
+ if (todo.dependentOn === "user-decision")
8
+ counts.user++;
9
+ else if (todo.dependentOn === "another-agent")
10
+ counts.agent++;
11
+ else
12
+ counts.unclassified++;
13
+ }
14
+ return counts;
15
+ }
16
+ /** Null for legacy records that never stored the transition time. */
17
+ export function blockedAgeMs(todo, now = Date.now()) {
18
+ if (todo.status !== "blocked" || todo.blockedAt === undefined)
19
+ return null;
20
+ return Math.max(0, now - todo.blockedAt);
21
+ }
22
+ /** Compact age such as `18h`; absent when the record stores no transition time. */
23
+ export function formatBlockedAge(ageMs) {
24
+ if (ageMs === null)
25
+ return undefined;
26
+ const minutes = Math.floor(ageMs / 60_000);
27
+ if (minutes < 60)
28
+ return `${minutes}m`;
29
+ const hours = Math.floor(minutes / 60);
30
+ if (hours < 48)
31
+ return `${hours}h`;
32
+ return `${Math.floor(hours / 24)}d`;
33
+ }
34
+ export function blockedDependencyLabel(todo) {
35
+ if (todo.status !== "blocked")
36
+ return undefined;
37
+ if (todo.dependentOn === "user-decision")
38
+ return "blocked on you";
39
+ if (todo.dependentOn === "another-agent")
40
+ return "waiting on agents";
41
+ return "blocked";
42
+ }
43
+ /** Compact header summary; the two dependency classes stay visibly separate. */
44
+ export function compactBlockedSummary(counts) {
45
+ const parts = [];
46
+ if (counts.user)
47
+ parts.push(`${counts.user} on you`);
48
+ if (counts.agent)
49
+ parts.push(`${counts.agent} on agents`);
50
+ if (counts.unclassified)
51
+ parts.push(`${counts.unclassified} blocked`);
52
+ return parts.length ? `${parts.join(" · ")}` : undefined;
53
+ }
54
+ /** Row suffix such as `blocked on you · 18h`; active rows and a record with no stored age have none. */
55
+ export function blockedRowLabel(todo, now = Date.now()) {
56
+ const label = blockedDependencyLabel(todo);
57
+ if (label === undefined)
58
+ return undefined;
59
+ const age = formatBlockedAge(blockedAgeMs(todo, now));
60
+ return age === undefined ? label : `${label} · ${age}`;
61
+ }
62
+ function quoted(value, max = 180) {
63
+ const single = value.replace(/\s+/gu, " ").trim();
64
+ return single.length > max ? `${single.slice(0, max - 1)}…` : single;
65
+ }
66
+ /**
67
+ * Read-only reconciliation block attached to a review that is already being
68
+ * delivered. It never changes a record and never creates a wake of its own.
69
+ * Linked decision questions are grouped so one answer can reconcile every task
70
+ * that references it.
71
+ */
72
+ export function blockedAuditPrompt(todos, now = Date.now()) {
73
+ const blocked = todos.filter((todo) => todo.status === "blocked");
74
+ if (blocked.length === 0)
75
+ return undefined;
76
+ const byQuestion = new Map();
77
+ for (const todo of blocked) {
78
+ if (todo.dependentOn !== "user-decision" || todo.decisionQuestionId === undefined)
79
+ continue;
80
+ byQuestion.set(todo.decisionQuestionId, [...(byQuestion.get(todo.decisionQuestionId) ?? []), todo.taskId]);
81
+ }
82
+ const rows = blocked.map((todo) => {
83
+ const dependency = blockedDependencyLabel(todo) ?? "blocked";
84
+ const age = formatBlockedAge(blockedAgeMs(todo, now));
85
+ const since = age === undefined ? "" : ` · ${age}`;
86
+ const question = todo.decisionQuestionId === undefined ? ""
87
+ : ` · question ${todo.decisionQuestionId}${(byQuestion.get(todo.decisionQuestionId)?.length ?? 0) > 1
88
+ ? ` (shared by ${byQuestion.get(todo.decisionQuestionId)?.join(", ")})` : ""}`;
89
+ const reason = todo.blockedReason ?? todo.finalThoughts ?? "no reason recorded";
90
+ return `- ${todo.taskId} “${quoted(todo.taskName)}” — ${dependency}${since}${question} — ${quoted(reason)}`;
91
+ });
92
+ const shared = [...byQuestion].filter(([, ids]) => ids.length > 1)
93
+ .map(([questionId, ids]) => `${ids.join(", ")} all reference question ${questionId}; one answer must reconcile every linked task`);
94
+ return [
95
+ `Blocked task audit (${blocked.length}):`,
96
+ ...rows,
97
+ ...(shared.length ? [`Shared decisions: ${shared.join(". ")}.`] : []),
98
+ "For each row, confirm in this turn that the dependency still exists and the record is accurate. If it no longer exists, update the task in this same turn: return it to active with the next concrete step, complete it with evidence, or take an obsolete task through the human cancellation decision with the superseding reason. If it still exists, keep the task blocked with the exact unblock condition and make sure the question or monitor that will resume it is live. Saying in conversation that no input is needed without changing the record is a lifecycle defect. Never clear a genuine blocker, invent an answer, or change status merely to finish this review.",
99
+ ].join("\n");
100
+ }
@@ -6,10 +6,10 @@ export interface TimingInspection {
6
6
  workerSessionId: string | null;
7
7
  }
8
8
  /**
9
- * Validate an existing timing descriptor for a delegated assignment before registration.
10
- * A fresh descriptor has no worker session or tasks yet; that is a placeholder, not a
11
- * measurement. Callers must report it as unknown until the worker exports real effort.
9
+ * Validate an existing timing report for a delegated assignment. Legacy reports may
10
+ * contain a placeholder; new assignments register the expected path in task state
11
+ * and create no report until the worker exports measured effort.
12
12
  */
13
- export declare function inspectTimingReport(ctx: ExtensionContext, taskDir: string, workId: string, taskId: string, reportPath: string): Promise<TimingInspection>;
14
- export declare function createTimingReport(ctx: ExtensionContext, taskDir: string, workId: string, taskId: string): Promise<string>;
13
+ export declare function inspectTimingReport(ctx: ExtensionContext, taskDir: string, workId: string, taskId: string, reportPath: string, reportRoot?: string): Promise<TimingInspection>;
14
+ export declare function createTimingReport(ctx: ExtensionContext, taskDir: string, workId: string, taskId: string, reportRoot?: string): Promise<string>;
15
15
  export declare function registerDelegatedTimeTools(pi: ExtensionAPI, state: TaskState): void;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { lstat, mkdir, readFile, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
2
+ import { link, lstat, mkdir, readFile, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
3
3
  import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
4
4
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
5
  import { Type } from "typebox";
@@ -93,14 +93,14 @@ async function readReport(path) {
93
93
  return data;
94
94
  }
95
95
  /**
96
- * Validate an existing timing descriptor for a delegated assignment before registration.
97
- * A fresh descriptor has no worker session or tasks yet; that is a placeholder, not a
98
- * measurement. Callers must report it as unknown until the worker exports real effort.
96
+ * Validate an existing timing report for a delegated assignment. Legacy reports may
97
+ * contain a placeholder; new assignments register the expected path in task state
98
+ * and create no report until the worker exports measured effort.
99
99
  */
100
- export async function inspectTimingReport(ctx, taskDir, workId, taskId, reportPath) {
100
+ export async function inspectTimingReport(ctx, taskDir, workId, taskId, reportPath, reportRoot = ctx.cwd) {
101
101
  const sessionId = ctx.sessionManager.getSessionId();
102
- const directory = await reportDirectory(ctx.cwd, resolve(ctx.cwd, taskDir));
103
- const actual = await reportFile(ctx.cwd, reportPath);
102
+ const directory = await reportDirectory(reportRoot, resolve(reportRoot, taskDir));
103
+ const actual = await reportFile(reportRoot, reportPath);
104
104
  if (dirname(actual) !== directory)
105
105
  throw new Error("Timing report is not in the delegated task directory.");
106
106
  const report = await readReport(actual);
@@ -109,15 +109,14 @@ export async function inspectTimingReport(ctx, taskDir, workId, taskId, reportPa
109
109
  }
110
110
  return { reportPath: actual, timing: report.workerSessionId === null ? "placeholder" : "measured", workerSessionId: report.workerSessionId };
111
111
  }
112
- export async function createTimingReport(ctx, taskDir, workId, taskId) {
112
+ export async function createTimingReport(ctx, taskDir, workId, taskId, reportRoot = ctx.cwd) {
113
113
  const sessionId = ctx.sessionManager.getSessionId();
114
- if (!SESSION_ID.test(sessionId))
115
- throw new Error("Invalid parent session ID for timing handoff.");
116
- const directory = await ensureReportDirectory(ctx.cwd, resolve(ctx.cwd, taskDir));
117
- const path = resolve(directory, `delegated-time-${randomUUID()}.json`);
118
- const report = { version: 1, parentSessionId: sessionId, parentWorkId: workId, parentTaskId: taskId, workerSessionId: null, tasks: [] };
119
- await withFileMutationQueue(path, () => writeFile(path, `${JSON.stringify(report, null, 2)}\n`, { flag: "wx", mode: 0o600 }));
120
- return path;
114
+ if (!SESSION_ID.test(sessionId) || !WORK_ID.test(workId) || !TASK_ID.test(taskId))
115
+ throw new Error("Invalid parent identity for timing handoff.");
116
+ const directory = await ensureReportDirectory(reportRoot, resolve(reportRoot, taskDir));
117
+ if (basename(directory) !== taskId || basename(dirname(directory)) !== workId || basename(dirname(dirname(directory))) !== sessionId)
118
+ throw new Error("Timing directory does not match the parent assignment.");
119
+ return resolve(directory, `delegated-time-${randomUUID()}.json`);
121
120
  }
122
121
  function measuredTotal(report) {
123
122
  if (!report.tasks.length || report.tasks.some((task) => task.elapsedMs === null))
@@ -143,9 +142,28 @@ export function registerDelegatedTimeTools(pi, state) {
143
142
  ...execution,
144
143
  async execute(_id, params, _signal, _update, ctx) {
145
144
  requireMainWork();
146
- const path = await reportFile(ctx.cwd, params.reportPath);
147
- return withFileMutationQueue(path, async () => {
148
- const previous = await readReport(path);
145
+ const requested = resolve(ctx.cwd, params.reportPath);
146
+ const directory = await reportDirectory(ctx.cwd, dirname(requested));
147
+ if (!/^delegated-time-[0-9a-f-]{36}\.json$/i.test(basename(requested)) || requested !== resolve(directory, basename(requested)))
148
+ throw new Error("Invalid timing report path.");
149
+ return withFileMutationQueue(requested, async () => {
150
+ let previous;
151
+ let exists = true;
152
+ try {
153
+ previous = await readReport(await reportFile(ctx.cwd, requested));
154
+ }
155
+ catch (error) {
156
+ if (error.code !== "ENOENT")
157
+ throw error;
158
+ exists = false;
159
+ const parentTaskId = basename(directory);
160
+ const parentWorkId = basename(dirname(directory));
161
+ const parentSessionId = basename(dirname(dirname(directory)));
162
+ if (!TASK_ID.test(parentTaskId) || !WORK_ID.test(parentWorkId) || !SESSION_ID.test(parentSessionId))
163
+ throw new Error("Timing report directory does not identify a parent assignment.");
164
+ previous = { version: 1, parentSessionId, parentWorkId, parentTaskId, workerSessionId: null, tasks: [] };
165
+ }
166
+ const path = requested;
149
167
  const workerSessionId = ctx.sessionManager.getSessionId();
150
168
  if (!SESSION_ID.test(workerSessionId) || workerSessionId === previous.parentSessionId)
151
169
  throw new Error("Timing export requires a distinct worker session.");
@@ -168,7 +186,10 @@ export function registerDelegatedTimeTools(pi, state) {
168
186
  const temporary = `${path}.${randomUUID()}.tmp`;
169
187
  try {
170
188
  await writeFile(temporary, `${JSON.stringify(report, null, 2)}\n`, { flag: "wx", mode: 0o600 });
171
- await rename(temporary, path);
189
+ if (exists)
190
+ await rename(temporary, path);
191
+ else
192
+ await link(temporary, path);
172
193
  }
173
194
  finally {
174
195
  await unlink(temporary).catch((error) => { if (error.code !== "ENOENT")
@@ -193,14 +214,25 @@ export function registerDelegatedTimeTools(pi, state) {
193
214
  throw new Error("This task has no timing handoff registered by AgentCreate.");
194
215
  const updates = [];
195
216
  for (const source of todo.delegatedTimes) {
196
- const path = await reportFile(ctx.cwd, source.reportPath);
217
+ const root = source.reportRoot ?? ctx.cwd;
218
+ let path;
219
+ try {
220
+ path = await reportFile(root, source.reportPath);
221
+ }
222
+ catch (error) {
223
+ if (error.code !== "ENOENT")
224
+ throw error;
225
+ await reportDirectory(root, dirname(source.reportPath));
226
+ updates.push({ reportPath: source.reportPath, reportRoot: source.reportRoot, workerSessionId: source.workerSessionId, elapsedMs: null });
227
+ continue;
228
+ }
197
229
  const report = await readReport(path);
198
230
  if (report.parentSessionId !== ctx.sessionManager.getSessionId() || report.parentWorkId !== todo.workId || report.parentTaskId !== todo.taskId) {
199
231
  throw new Error("Timing report belongs to another parent assignment.");
200
232
  }
201
233
  if (source.workerSessionId && source.workerSessionId !== report.workerSessionId)
202
234
  throw new Error("Timing report belongs to another worker session.");
203
- updates.push({ reportPath: source.reportPath, workerSessionId: report.workerSessionId ?? undefined, elapsedMs: measuredTotal(report) });
235
+ updates.push({ reportPath: source.reportPath, reportRoot: source.reportRoot, workerSessionId: report.workerSessionId ?? undefined, elapsedMs: measuredTotal(report) });
204
236
  }
205
237
  for (const source of updates)
206
238
  state.setDelegatedTime(todo.taskId, source);
@@ -2,6 +2,6 @@
2
2
  export declare const TASK_DEPENDENCIES: readonly ["user-decision", "another-agent"];
3
3
  export type TaskDependency = (typeof TASK_DEPENDENCIES)[number];
4
4
  export declare const DEPENDENCY_LABELS: Record<TaskDependency, string>;
5
- export declare const DEPENDENCY_GUIDANCE = "Only a blocked task has dependentOn. When entering blocked, supply exactly one of \"user-decision\" for a user response, decision, or permission, or \"another-agent\" for another agent's output or review. Nonblocked tasks omit it and leaving blocked clears it. Do not mark a task blocked for external services, tool failures, or other obstacles that fit neither category; keep the task active, preserve safety, and report the unavailable dependency truthfully.";
5
+ export declare const DEPENDENCY_GUIDANCE = "Only a blocked task has dependentOn. When entering blocked, supply exactly one of \"user-decision\" for a user response, decision, or permission, or \"another-agent\" for another agent's output or review. Nonblocked tasks omit it and leaving blocked clears it. Do not mark a task blocked when a service, tool or access failed and nobody can act on it yet; keep the task active, preserve safety, and report the unavailable dependency truthfully. Do mark it blocked with \"user-decision\" when only the user can clear that obstacle, for example by signing in or reconnecting a browser profile, granting access, supplying a missing identifier, or choosing between options. When the blocker is a pi-decisions page, record its questionId in decisionQuestionId so a pending page can be re-armed or withdrawn and every task waiting on that question is reconciled together. If you conclude in conversation that a blocked dependency no longer exists, update the task record in that same turn; saying no input is needed without clearing or re-recording the blocker is a lifecycle defect, and a task that is proved obsolete must go through the human cancellation decision with the superseding reason rather than staying active.";
6
6
  export declare function isTaskDependency(value: unknown): value is TaskDependency;
7
7
  export declare function dependentOnLabel(value: TaskDependency | null | undefined): string | undefined;
@@ -4,7 +4,7 @@ export const DEPENDENCY_LABELS = {
4
4
  "user-decision": "User decision",
5
5
  "another-agent": "Another agent",
6
6
  };
7
- export const DEPENDENCY_GUIDANCE = "Only a blocked task has dependentOn. When entering blocked, supply exactly one of \"user-decision\" for a user response, decision, or permission, or \"another-agent\" for another agent's output or review. Nonblocked tasks omit it and leaving blocked clears it. Do not mark a task blocked for external services, tool failures, or other obstacles that fit neither category; keep the task active, preserve safety, and report the unavailable dependency truthfully.";
7
+ export const DEPENDENCY_GUIDANCE = "Only a blocked task has dependentOn. When entering blocked, supply exactly one of \"user-decision\" for a user response, decision, or permission, or \"another-agent\" for another agent's output or review. Nonblocked tasks omit it and leaving blocked clears it. Do not mark a task blocked when a service, tool or access failed and nobody can act on it yet; keep the task active, preserve safety, and report the unavailable dependency truthfully. Do mark it blocked with \"user-decision\" when only the user can clear that obstacle, for example by signing in or reconnecting a browser profile, granting access, supplying a missing identifier, or choosing between options. When the blocker is a pi-decisions page, record its questionId in decisionQuestionId so a pending page can be re-armed or withdrawn and every task waiting on that question is reconciled together. If you conclude in conversation that a blocked dependency no longer exists, update the task record in that same turn; saying no input is needed without clearing or re-recording the blocker is a lifecycle defect, and a task that is proved obsolete must go through the human cancellation decision with the superseding reason rather than staying active.";
8
8
  export function isTaskDependency(value) {
9
9
  return typeof value === "string" && TASK_DEPENDENCIES.includes(value);
10
10
  }
package/dist/durable.d.ts CHANGED
@@ -7,7 +7,7 @@ export interface TasksDurableSettings {
7
7
  /** Maximum todos per conversation. Default 500. Must be an integer from 1 to 10000. */
8
8
  readonly maxTodos?: number;
9
9
  }
10
- export type DurableTaskStatus = "active" | "blocked" | "completed" | "cancelled";
10
+ export type DurableTaskStatus = "active" | "blocked" | "completed" | "closed" | "cancelled";
11
11
  export type DurableWork = {
12
12
  workId: string;
13
13
  workName: string;
@@ -26,6 +26,10 @@ export type DurableTodo = {
26
26
  status: DurableTaskStatus;
27
27
  blockedReason: string | null;
28
28
  dependentOn: TaskDependency | null;
29
+ /** When the current blocked state began; absent on legacy records. */
30
+ blockedAt?: number;
31
+ /** Linked pi-decisions question for a user-decision blocker. */
32
+ decisionQuestionId?: string;
29
33
  completionPercent: number | null;
30
34
  createdAt: number;
31
35
  updatedAt: number;
package/dist/durable.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * - AgentCreate/Resume/List/Status/Output/Send/Interrupt/Close/Focus need the Herdr CLI
13
13
  * plus Pi nested `executeTool`, which Durable 1.1 `ToolExecutionApi` does not expose.
14
14
  * - TaskTimeExport/Import need repository `var/` timing files plus a parent Pi session.
15
- * - Auto-continuation needs Pi's `agent_before_settle` boundary; the `/works`
15
+ * - Auto-continuation and TodoUpdate transition review need Pi's `agent_before_settle`/`turn_end` boundaries; the `/works`
16
16
  * command and the TUI panel/overlay are desktop Pi surfaces.
17
17
  * - Effort timing (`working` selection, elapsed measurement) needs the Pi agent
18
18
  * lifecycle that pauses timers at loop boundaries; no native equivalent exists, so
@@ -24,10 +24,12 @@
24
24
  import { StringEnum } from "@earendil-works/pi-ai";
25
25
  import { defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
26
26
  import { Type } from "typebox";
27
+ import { blockedAgeMs, formatBlockedAge } from "./blocked.js";
27
28
  import { DEPENDENCY_GUIDANCE, dependentOnLabel, isTaskDependency, TASK_DEPENDENCIES } from "./dependency.js";
28
29
  import { taskOwner } from "./ownership.js";
29
30
  import { safeSingleLine } from "./text.js";
30
31
  import { finalThoughtsFor } from "./thoughts.js";
32
+ import { todoTransition } from "./transition.js";
31
33
  const STATE_KIND = "pi-tasks.state";
32
34
  const STATE_VERSION = 1;
33
35
  const tasksDoc = defineDoc({
@@ -38,7 +40,7 @@ const tasksDoc = defineDoc({
38
40
  fork: "initial",
39
41
  initial: () => ({ works: [], todos: [], nextWorkId: 1, nextTaskId: 1 }),
40
42
  });
41
- const StatusSchema = StringEnum(["active", "blocked", "completed", "cancelled"]);
43
+ const StatusSchema = StringEnum(["active", "blocked", "completed", "closed", "cancelled"]);
42
44
  const InfoSchema = Type.String({ minLength: 1, maxLength: 10_000 });
43
45
  const TaskInfoSchema = Type.String({ minLength: 1, maxLength: 10_000, description: "Hidden coordination metadata for resumption: owner declaration, canonical artifact paths, parent IDs, and necessary execution constraints. Never shown as task text; do not narrate goals or progress here." });
44
46
  const FinalThoughtsSchema = Type.String({ description: "The only user-visible task text. One concise update, not a goal, history, list, or section. Completed tasks state the actual result, verification, and remaining limits; active tasks update only for significant changes with no filler; blocked tasks use blockedReason as the authoritative dependency. Never include owner declarations, links, paths, or parent IDs." });
@@ -46,6 +48,7 @@ const NameSchema = Type.String({ minLength: 1, maxLength: 240 });
46
48
  const CompletionSchema = Type.Union([Type.Integer({ minimum: 0, maximum: 100 }), Type.Null()]);
47
49
  const BlockedReasonSchema = Type.Union([Type.String({ minLength: 1, maxLength: 10_000 }), Type.Null()]);
48
50
  const DependencySchema = Type.Union([StringEnum(TASK_DEPENDENCIES), Type.Null()], { description: DEPENDENCY_GUIDANCE });
51
+ const DecisionQuestionSchema = Type.String({ minLength: 1, description: "The pi-decisions questionId this user-decision blocker waits on. Set it when the blocker was presented with SubmitQuestion so a pending page can be re-armed or withdrawn and every linked task reconciled together. Only valid while blocked on user-decision." });
49
52
  const MAX_TEXT_BYTES = 50_000;
50
53
  const MAX_TEXT_LINES = 2_000;
51
54
  function bounded(text) {
@@ -86,16 +89,16 @@ function checkCompletion(status, value) {
86
89
  if (!Number.isInteger(value) || value < 0 || value > 100) {
87
90
  throw new Error("completionPercent must be an integer from 0 to 100, or null for unknown.");
88
91
  }
89
- if (value === 100 && status !== "completed") {
92
+ if (value === 100 && status !== "completed" && status !== "closed") {
90
93
  throw new Error("100% requires verified completion. Set status to completed after verification.");
91
94
  }
92
- if (status === "completed" && value !== 100) {
95
+ if ((status === "completed" || status === "closed") && value !== 100) {
93
96
  throw new Error("Completed tasks have 100% progress. Reopen the task before reporting partial progress.");
94
97
  }
95
98
  }
96
99
  /** Mirrors the desktop completion policy: completed is 100, missing estimates stay unknown. */
97
100
  function taskCompletion(status, completionPercent) {
98
- if (status === "completed")
101
+ if (status === "completed" || status === "closed")
99
102
  return 100;
100
103
  return typeof completionPercent === "number" && Number.isInteger(completionPercent)
101
104
  && completionPercent >= 0 && completionPercent < 100 ? completionPercent : null;
@@ -144,10 +147,29 @@ function normalizeDependency(status, supplied, current) {
144
147
  }
145
148
  return supplied;
146
149
  }
150
+ function normalizeDecisionQuestionId(status, dependency, supplied, current) {
151
+ if (status !== "blocked" || dependency !== "user-decision") {
152
+ if (supplied !== undefined) {
153
+ throw new Error("decisionQuestionId is only valid for a task blocked on user-decision.");
154
+ }
155
+ return undefined;
156
+ }
157
+ if (supplied === undefined) {
158
+ return current?.status === "blocked" && current.dependentOn === "user-decision" ? current.decisionQuestionId : undefined;
159
+ }
160
+ if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/u.test(supplied)) {
161
+ throw new Error("decisionQuestionId must be a pi-decisions question ID.");
162
+ }
163
+ return supplied;
164
+ }
147
165
  function formatTodo(todo) {
148
166
  const owner = taskOwner(todo.taskInfo);
149
167
  const dependency = dependentOnLabel(todo.dependentOn);
150
- return `${todo.taskId} [${todo.status}] [${owner === "self" || owner === "delegate" ? owner : "unassigned"}] ${todo.taskName} · ${formatCompletion(taskCompletion(todo.status, todo.completionPercent))}\nWork: ${todo.workId}\nFinal thoughts:\n${finalThoughtsFor(todo) ?? "None recorded."}\n${dependency === undefined ? "" : `Dependent on: ${dependency}\n`}Task info (hidden coordination metadata):\n${todo.taskInfo}`;
168
+ const blockedAge = todo.status === "blocked" ? formatBlockedAge(blockedAgeMs(todo)) : undefined;
169
+ const blockedSince = blockedAge === undefined ? "" : ` · ${blockedAge}`;
170
+ const question = todo.status === "blocked" && todo.decisionQuestionId !== undefined
171
+ ? `Decision question: ${todo.decisionQuestionId}\n` : "";
172
+ return `${todo.taskId} [${todo.status}] [${owner === "self" || owner === "delegate" ? owner : "unassigned"}] ${todo.taskName} · ${formatCompletion(taskCompletion(todo.status, todo.completionPercent))}\nWork: ${todo.workId}\nFinal thoughts:\n${finalThoughtsFor(todo) ?? "None recorded."}\n${dependency === undefined ? "" : `Dependent on: ${dependency}${blockedSince}\n`}${question}Task info (hidden coordination metadata):\n${todo.taskInfo}`;
151
173
  }
152
174
  function formatWork(doc, work, filter) {
153
175
  const todos = doc.todos
@@ -306,6 +328,7 @@ export function createTasksDurableExtension(settings = {}) {
306
328
  completionPercent: Type.Optional(CompletionSchema),
307
329
  blockedReason: Type.Optional(BlockedReasonSchema),
308
330
  dependentOn: Type.Optional(DependencySchema),
331
+ decisionQuestionId: Type.Optional(DecisionQuestionSchema),
309
332
  }, { additionalProperties: false }),
310
333
  replay: "unsafe",
311
334
  executionMode: "sequential",
@@ -320,11 +343,15 @@ export function createTasksDurableExtension(settings = {}) {
320
343
  if (doc.todos.length >= maxTodos)
321
344
  throw new Error(`Maximum of ${maxTodos} todos reached.`);
322
345
  const status = (args.status ?? "active");
346
+ if (status === "closed")
347
+ throw new Error("Create the task first; close it after its verified completion.");
323
348
  checkCompletion(status, args.completionPercent ?? null);
324
349
  const now = Date.now();
325
350
  // Chord rejects an own undefined property as non-JSON. Normalize once and
326
351
  // omit the field entirely when the caller supplied nothing or blank text.
327
352
  const finalThoughts = optionalThoughts(args.finalThoughts);
353
+ const dependency = normalizeDependency(status, args.dependentOn, undefined);
354
+ const decisionQuestionId = normalizeDecisionQuestionId(status, dependency, args.decisionQuestionId, undefined);
328
355
  const todo = {
329
356
  taskId: `T${doc.nextTaskId}`,
330
357
  workId: args.workId,
@@ -333,7 +360,9 @@ export function createTasksDurableExtension(settings = {}) {
333
360
  ...(finalThoughts === undefined ? {} : { finalThoughts }),
334
361
  status,
335
362
  blockedReason: normalizeBlockedReason(status, args.blockedReason ?? undefined, undefined),
336
- dependentOn: normalizeDependency(status, args.dependentOn, undefined),
363
+ dependentOn: dependency,
364
+ ...(status === "blocked" ? { blockedAt: now } : {}),
365
+ ...(decisionQuestionId === undefined ? {} : { decisionQuestionId }),
337
366
  completionPercent: status === "completed" ? 100 : (args.completionPercent ?? null),
338
367
  createdAt: now,
339
368
  updatedAt: now,
@@ -388,6 +417,7 @@ export function createTasksDurableExtension(settings = {}) {
388
417
  completionPercent: Type.Optional(CompletionSchema),
389
418
  blockedReason: Type.Optional(BlockedReasonSchema),
390
419
  dependentOn: Type.Optional(DependencySchema),
420
+ decisionQuestionId: Type.Optional(DecisionQuestionSchema),
391
421
  }, { additionalProperties: false }),
392
422
  replay: "unsafe",
393
423
  executionMode: "sequential",
@@ -400,7 +430,15 @@ export function createTasksDurableExtension(settings = {}) {
400
430
  if (!todo)
401
431
  throw new Error(`Todo ${args.taskId} not found in this conversation.`);
402
432
  const oldStatus = todo.status;
433
+ const oldDependency = todo.dependentOn;
434
+ const oldQuestion = todo.decisionQuestionId;
403
435
  const status = (args.status ?? oldStatus);
436
+ if (status === "closed" && oldStatus !== "completed")
437
+ throw new Error("Close a task after its verified completion.");
438
+ if (oldStatus === "closed" && status !== "closed")
439
+ throw new Error("Reopen a closed task through an explicit human decision.");
440
+ if (oldStatus === "closed")
441
+ throw new Error("Reopen this closed task through an explicit human decision before editing it.");
404
442
  checkCompletion(status, args.completionPercent);
405
443
  // Validate the reason transition before mutating anything: entering blocked
406
444
  // without a reason is rejected, and leaving blocked always clears the reason.
@@ -411,6 +449,8 @@ export function createTasksDurableExtension(settings = {}) {
411
449
  const dependency = (args.dependentOn !== undefined || transitioned)
412
450
  ? normalizeDependency(status, args.dependentOn, transitioned ? undefined : todo)
413
451
  : todo.dependentOn;
452
+ const decisionQuestionId = normalizeDecisionQuestionId(status, dependency, args.decisionQuestionId, todo);
453
+ const blockedClassChanged = status === "blocked" && (oldStatus !== "blocked" || oldDependency !== dependency);
414
454
  let changed = false;
415
455
  if (args.taskName !== undefined) {
416
456
  const name = requiredName(args.taskName);
@@ -453,6 +493,23 @@ export function createTasksDurableExtension(settings = {}) {
453
493
  todo.dependentOn = dependency;
454
494
  changed = true;
455
495
  }
496
+ if (decisionQuestionId !== oldQuestion) {
497
+ if (decisionQuestionId === undefined)
498
+ delete todo.decisionQuestionId;
499
+ else
500
+ todo.decisionQuestionId = decisionQuestionId;
501
+ changed = true;
502
+ }
503
+ if (status === "blocked") {
504
+ if (blockedClassChanged) {
505
+ todo.blockedAt = Date.now();
506
+ changed = true;
507
+ }
508
+ }
509
+ else if (todo.blockedAt !== undefined) {
510
+ delete todo.blockedAt;
511
+ changed = true;
512
+ }
456
513
  if (args.completionPercent !== undefined && args.completionPercent !== todo.completionPercent) {
457
514
  todo.completionPercent = args.completionPercent;
458
515
  changed = true;
@@ -470,16 +527,21 @@ export function createTasksDurableExtension(settings = {}) {
470
527
  throw new Error("TodoUpdate requires at least one changed field.");
471
528
  }
472
529
  todo.updatedAt = Date.now();
530
+ const transition = todoTransition({ status: oldStatus, dependentOn: oldDependency ?? undefined }, { status, dependentOn: dependency ?? undefined });
473
531
  return {
474
532
  taskId: todo.taskId,
475
533
  workId: todo.workId,
476
534
  status: todo.status,
477
535
  completionPercent: taskCompletion(todo.status, todo.completionPercent),
536
+ transition: transition ?? null,
478
537
  };
479
538
  }, context);
480
539
  return {
481
540
  content: [{ type: "text", text: `Updated todo ${updated.taskId}: [${updated.status}] · ${formatCompletion(updated.completionPercent)}` }],
482
- details: { ...updated },
541
+ details: {
542
+ ...updated,
543
+ data: updated.transition === null ? null : { transition: updated.transition },
544
+ },
483
545
  };
484
546
  },
485
547
  });
@@ -1,7 +1,15 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ export interface HerdrTasksModStatus {
3
+ /** Assets written because the mods folder had none. */
4
+ installed: string[];
5
+ /** Assets replaced because the installed copy differed from this package's version. */
6
+ refreshed: string[];
7
+ /** Timestamped copies of the replaced files, kept beside them. */
8
+ backups: string[];
9
+ }
2
10
  export interface HerdrTasksPaneOptions {
3
11
  /** Close this terminal's Tasks pane from an earlier session before opening the current one. */
4
12
  replaceStale?: boolean;
5
13
  }
6
14
  /** Show beside this terminal, or hide only its same-session Tasks mod panes. */
7
- export declare function setHerdrTasksPaneVisible(ctx: ExtensionContext, visible: boolean, snapshot: string, openCommand?: string[], options?: HerdrTasksPaneOptions): Promise<void>;
15
+ export declare function setHerdrTasksPaneVisible(ctx: ExtensionContext, visible: boolean, snapshot: string, openCommand?: string[], options?: HerdrTasksPaneOptions): Promise<HerdrTasksModStatus | null>;
@@ -1,27 +1,60 @@
1
1
  import { spawn } from "node:child_process";
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, isAbsolute, join } from "node:path";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
6
  import { app, hc, object, TERMINAL_ID } from "./agents/herdr.js";
7
7
  import { ensureHerdrTasksHeader } from "./herdr-header.js";
8
8
  import { readSnapshot } from "./snapshot.js";
9
- /** Install missing shipped assets only. Never overwrite a personal/customized mod. */
9
+ /** Replace a watched file in one step, so a concurrent mod read cannot see a half-written viewer. */
10
+ async function writeAtomic(destination, contents) {
11
+ const temporary = `${destination}.tmp-${process.pid}-${Date.now()}`;
12
+ await writeFile(temporary, contents, { flag: "wx" });
13
+ try {
14
+ await rename(temporary, destination);
15
+ }
16
+ catch (error) {
17
+ await unlink(temporary).catch(() => { });
18
+ throw error;
19
+ }
20
+ }
21
+ /**
22
+ * Keep the shipped viewer in step with this package's snapshot contract. The pane is a read-only
23
+ * viewer of records this package writes, so a viewer from another package version can reject
24
+ * records it does not know: a differing copy is kept as a timestamped backup and replaced, while
25
+ * an identical copy is never rewritten. The personal header mod is a separate, cloned mod.
26
+ */
10
27
  async function installBundledMod(appHome) {
11
28
  const assets = await Promise.all(["README.md", "main.js", "mod.json", "spinner.svg"].map(async (name) => ({
12
29
  name, contents: await readFile(new URL(`../herdr/pi-tasks/${name}`, import.meta.url)),
13
30
  })));
14
31
  const directory = join(appHome, "mods", "pi-tasks");
15
32
  await mkdir(directory, { recursive: true });
33
+ const status = { installed: [], refreshed: [], backups: [] };
16
34
  for (const asset of assets) {
35
+ const destination = join(directory, asset.name);
36
+ let current = null;
17
37
  try {
18
- await writeFile(join(directory, asset.name), asset.contents, { flag: "wx" });
38
+ current = await readFile(destination);
19
39
  }
20
40
  catch (error) {
21
- if (error.code !== "EEXIST")
41
+ if (error.code !== "ENOENT")
22
42
  throw error;
23
43
  }
44
+ if (current === null) {
45
+ await writeFile(destination, asset.contents, { flag: "wx" });
46
+ status.installed.push(asset.name);
47
+ continue;
48
+ }
49
+ if (current.equals(asset.contents))
50
+ continue;
51
+ const backup = `${destination}.bak-${new Date().toISOString().replace(/[:.]/g, "-")}`;
52
+ await writeFile(backup, current, { flag: "wx" });
53
+ status.backups.push(backup);
54
+ await writeAtomic(destination, asset.contents);
55
+ status.refreshed.push(asset.name);
24
56
  }
57
+ return status;
25
58
  }
26
59
  /** Public Core document read only. One connection per deliberate opener, no service. */
27
60
  async function readAppDocument(ctx) {
@@ -133,16 +166,21 @@ export async function setHerdrTasksPaneVisible(ctx, visible, snapshot, openComma
133
166
  if (!visible) {
134
167
  for (const pane of existing)
135
168
  await app(["do", "pane.close", JSON.stringify({ pane: pane.id })], ctx.cwd, ctx.signal);
136
- return;
169
+ return null;
137
170
  }
138
- if (existing.length) {
171
+ const status = await installBundledMod(appHome);
172
+ // A fresh pane loads the mod code it finds, so a viewer this call refreshed needs a new
173
+ // pane; focusing the old one would keep rendering the replaced contract.
174
+ if (existing.length && !status.refreshed.length) {
139
175
  const pane = existing[0];
140
176
  if (typeof pane.id !== "string")
141
177
  throw new Error("The existing Tasks pane has no pane ID.");
142
178
  await app(["do", "pane.focus", JSON.stringify({ pane: pane.id })], ctx.cwd, ctx.signal);
143
179
  await publishTasksPane(snapshot, pane.id);
144
- return;
180
+ return status;
145
181
  }
182
+ for (const pane of existing)
183
+ await app(["do", "pane.close", JSON.stringify({ pane: pane.id })], ctx.cwd, ctx.signal);
146
184
  if (options.replaceStale) {
147
185
  for (const pane of panes) {
148
186
  const content = object(pane.content);
@@ -154,7 +192,6 @@ export async function setHerdrTasksPaneVisible(ctx, visible, snapshot, openComma
154
192
  }
155
193
  }
156
194
  const activity = panes.find((pane) => matches(pane, "pi-loop-monitor"));
157
- await installBundledMod(appHome);
158
195
  await ensureHerdrTasksHeader(ctx, appHome);
159
196
  const args = ["do", "pane.split", JSON.stringify({ pane: activity?.id ?? item.pane, direction: activity ? "down" : "right", mod: "pi-tasks", props: { sessionId: ctx.sessionManager.getSessionId(), snapshot, terminal, openCommand, paneFile: tasksPaneFile(snapshot) } })];
160
197
  let result;
@@ -174,7 +211,7 @@ export async function setHerdrTasksPaneVisible(ctx, visible, snapshot, openComma
174
211
  if (typeof result.pane !== "string")
175
212
  throw new Error("Herdr did not return a Tasks pane ID.");
176
213
  await publishTasksPane(snapshot, result.pane);
177
- return;
214
+ return status;
178
215
  }
179
216
  }
180
217
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  /** Session-scoped work and todo tracking for Pi. */
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  export default function tasksExtension(pi: ExtensionAPI): void;
4
- export type { DelegatedTime, Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";
4
+ export type { CloseoutAttempt, DelegatedTime, TaskGoal, Todo, TodoStatus, Work, WorkWithTodos } from "./types.js";