@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/README.md +10 -8
- package/dist/agents/delegation.js +77 -6
- package/dist/auto-continue.js +262 -19
- package/dist/blocked.d.ts +29 -0
- package/dist/blocked.js +100 -0
- package/dist/delegated-time.d.ts +5 -5
- package/dist/delegated-time.js +53 -21
- package/dist/dependency.d.ts +1 -1
- package/dist/dependency.js +1 -1
- package/dist/durable.d.ts +5 -1
- package/dist/durable.js +70 -8
- package/dist/herdr-panel.d.ts +9 -1
- package/dist/herdr-panel.js +46 -9
- package/dist/index.d.ts +1 -1
- package/dist/index.js +31 -2
- package/dist/progress.js +1 -1
- package/dist/snapshot.js +47 -4
- package/dist/state.d.ts +27 -5
- package/dist/state.js +235 -14
- package/dist/timing.js +7 -1
- package/dist/tools.js +258 -16
- package/dist/tracking.js +14 -9
- package/dist/transition.d.ts +9 -0
- package/dist/transition.js +26 -0
- package/dist/types.d.ts +67 -1
- package/dist/ui/panel.js +22 -10
- package/dist/ui/works-dashboard.js +16 -5
- package/docs/REFERENCE.md +40 -14
- package/docs/USAGE_GUIDE.md +29 -17
- package/herdr/pi-tasks/README.md +7 -6
- package/herdr/pi-tasks/header.js +61 -41
- package/herdr/pi-tasks/main.js +88 -13
- package/package.json +1 -1
package/dist/tools.js
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readFile, realpath, stat } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, isAbsolute, relative, sep } from "node:path";
|
|
1
4
|
import { StringEnum } from "@earendil-works/pi-ai";
|
|
2
5
|
import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
|
|
3
6
|
import { Type } from "typebox";
|
|
4
7
|
import { delegateLink, preservePaneLink } from "./agents/links.js";
|
|
8
|
+
import { blockedAgeMs, formatBlockedAge } from "./blocked.js";
|
|
5
9
|
import { DEPENDENCY_GUIDANCE, dependentOnLabel, TASK_DEPENDENCIES } from "./dependency.js";
|
|
6
10
|
import { formatCompletion, taskCompletion, workCompletion } from "./progress.js";
|
|
7
11
|
import { finalThoughtsFor } from "./thoughts.js";
|
|
8
12
|
import { formatTime, taskTime, workTime } from "./time.js";
|
|
9
13
|
import { renderTaskCall, renderTaskResult, taskResult } from "./tool-result.js";
|
|
10
14
|
import { areTrackingToolsActive } from "./tracking.js";
|
|
11
|
-
|
|
12
|
-
const
|
|
15
|
+
import { todoTransition } from "./transition.js";
|
|
16
|
+
const StatusSchema = StringEnum(["active", "blocked", "completed", "closed", "cancelled"]);
|
|
17
|
+
const STATUS_GUIDANCE = "A new task starts active with its visible goal. Use blocked only when the next step must wait for a user decision (a response, approval, or permission) or for another agent's output or review. Supply both blockedReason and dependentOn when moving a task to blocked; dependentOn accepts only \"user-decision\" or \"another-agent\". Unrelated blocked edits preserve both; leaving blocked clears both. Retain progress. Return blocked tasks to active when the dependency resolves and work resumes. 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. A task whose premise no longer holds must go through the human cancellation decision with the superseding reason rather than staying active or being marked completed. Classify an obstacle by who can clear it: when the next step needs the user to sign in or reconnect a browser profile, grant access, supply a missing identifier, or choose between options, blocked with user-decision is the correct status. When nobody can act on it yet, such as a provider outage or an internal tool defect, keep the task active, preserve safety, and report the unavailable dependency truthfully. Works are collections and have no status. A closed task is finished; close it only after verified completion, and cancel or reopen a closed or cancelled task only through an explicit human decision.";
|
|
13
18
|
const CompletionSchema = Type.Union([Type.Integer({ minimum: 0, maximum: 100 }), Type.Null()], {
|
|
14
19
|
description: "AI-reported approximate task completion, not elapsed time or a status-to-percentage mapping. Use null for unknown; reserve 100 for verified completed status. Work progress is the equal average of non-cancelled tasks. Keep visible evidence in finalThoughts only for a significant change; never narrate progress in taskInfo.",
|
|
15
20
|
});
|
|
@@ -17,10 +22,14 @@ const BlockedReasonSchema = Type.Union([Type.String({ minLength: 1, maxLength: 1
|
|
|
17
22
|
description: "Required with dependentOn when creating a blocked task or entering blocked status. Explain the current dependency and what will unblock it. This is the visible Final thoughts for a blocked task, so do not duplicate it in finalThoughts. Omission preserves the current reason while blocked; leaving blocked clears it automatically.",
|
|
18
23
|
});
|
|
19
24
|
const DependencySchema = StringEnum(TASK_DEPENDENCIES, { description: DEPENDENCY_GUIDANCE });
|
|
25
|
+
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; cleared automatically when the task leaves blocked or changes dependency class." });
|
|
26
|
+
const decisionTools = { reachesTools: () => ["SubmitQuestion", "WaitForAnswer"] };
|
|
27
|
+
const workerCloseTools = { reachesTools: () => ["AgentStatus", "MonitorList", "AgentSend", "AgentOutput"] };
|
|
28
|
+
const workerPresenceTools = { reachesTools: () => ["AgentList", "AgentStatus"] };
|
|
20
29
|
const NameSchema = Type.String({ minLength: 1, maxLength: 240 });
|
|
21
30
|
const WORK_INFO_GUIDANCE = "Write workInfo in normal prose with full sentences and spaces between words. Conversational brevity modes must not compress stored records or concatenate words.";
|
|
22
31
|
const TASK_INFO_GUIDANCE = "taskInfo is hidden coordination metadata for resumption: keep the owner declaration, canonical artifact paths, parent IDs, and necessary execution constraints. Do not restate the goal, narrate progress, or put visible updates there.";
|
|
23
|
-
const FINAL_THOUGHTS_GUIDANCE = "The
|
|
32
|
+
const FINAL_THOUGHTS_GUIDANCE = "The user-visible result update, separate from any stored goal and criteria. Write one concise update, not a goal, history, list, or section. For a completed task, state the short actual result, the verification performed, and any remaining limits; do not omit it by habit. For an active task, update only when something significant changed; otherwise leave it unchanged with no filler. For a blocked task, blockedReason is the authoritative visible dependency; do not duplicate it. Never put owner declarations, terminal or monitor links, artifact paths, or parent IDs here.";
|
|
24
33
|
const WorkInfoSchema = Type.String({ minLength: 1, maxLength: 10_000, description: WORK_INFO_GUIDANCE });
|
|
25
34
|
const TaskInfoSchema = Type.String({ minLength: 1, maxLength: 10_000, description: TASK_INFO_GUIDANCE });
|
|
26
35
|
const FinalThoughtsSchema = Type.String({ description: FINAL_THOUGHTS_GUIDANCE });
|
|
@@ -84,7 +93,7 @@ export function registerTaskTools(pi, state) {
|
|
|
84
93
|
pi.registerTool({
|
|
85
94
|
name: "WorkDelete",
|
|
86
95
|
label: "WorkDelete",
|
|
87
|
-
description: "Delete a work
|
|
96
|
+
description: "Delete a work together with its tasks that have no recorded work. A work holding any retained task is rejected; cancel its tasks through the explicit human decision path instead. Use only for mistaken records.",
|
|
88
97
|
parameters: Type.Object({ workId: Type.String() }, { additionalProperties: false }),
|
|
89
98
|
execute(_id, params) {
|
|
90
99
|
const work = state.getWork(params.workId);
|
|
@@ -100,11 +109,12 @@ export function registerTaskTools(pi, state) {
|
|
|
100
109
|
pi.registerTool({
|
|
101
110
|
name: "TodoCreate",
|
|
102
111
|
label: "TodoCreate",
|
|
103
|
-
description: `Create a todo under an existing work, optionally reporting approximate completionPercent (0 for known unstarted work, null for unknown). For longer tasks, use TodoUpdate for interim estimates after roughly 5–10 meaningful working steps or a milestone; do not wait until completion. taskInfo must contain the required hidden coordination metadata and is never shown;
|
|
112
|
+
description: `Create a todo under an existing work, optionally reporting approximate completionPercent (0 for known unstarted work, null for unknown). For longer tasks, use TodoUpdate for interim estimates after roughly 5–10 meaningful working steps or a milestone; do not wait until completion. taskInfo must contain the required hidden coordination metadata and is never shown; the goal, criteria, and finalThoughts are visible. ${STATUS_GUIDANCE} ${TASK_INFO_GUIDANCE} ${FINAL_THOUGHTS_GUIDANCE}`,
|
|
104
113
|
promptSnippet: "Create a todo for each distinct new actionable request before work",
|
|
105
114
|
promptGuidelines: [
|
|
106
115
|
"Use TodoCreate only under an existing work and only for actionable main-conversation work; never use it during /ask or /btw.",
|
|
107
116
|
"Create a Todo for each distinct new actionable user request, including one added to an existing Work; reuse an existing Todo only when it owns the same outcome. Do not create one for each sentence, clarification, check, or tool call.",
|
|
117
|
+
"For each new task, record its visible goal and acceptance criteria. The task starts active, and changing the goal later through TaskGoalUpdate needs no separate approval.",
|
|
108
118
|
"Keep taskInfo to hidden coordination metadata and finalThoughts to the visible update. completionPercent is optional; estimate from actual progress, use null when unknown, and do not infer partial completion just from status. For longer tasks, report interim estimates through TodoUpdate after roughly 5–10 meaningful working steps or a milestone.",
|
|
109
119
|
TASK_INFO_GUIDANCE,
|
|
110
120
|
FINAL_THOUGHTS_GUIDANCE,
|
|
@@ -113,14 +123,12 @@ export function registerTaskTools(pi, state) {
|
|
|
113
123
|
workId: Type.String(),
|
|
114
124
|
taskName: NameSchema,
|
|
115
125
|
taskInfo: TaskInfoSchema,
|
|
126
|
+
goal: Type.Object({ goal: Type.String({ minLength: 1 }), criteria: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }) }, { additionalProperties: false, description: "Visible task-specific goal and acceptance criteria. The task starts active; no separate goal approval is required." }),
|
|
116
127
|
finalThoughts: Type.Optional(FinalThoughtsSchema),
|
|
117
|
-
blockedReason: Type.Optional(BlockedReasonSchema),
|
|
118
|
-
dependentOn: Type.Optional(DependencySchema),
|
|
119
|
-
status: Type.Optional(StatusSchema),
|
|
120
128
|
completionPercent: Type.Optional(CompletionSchema),
|
|
121
129
|
}, { additionalProperties: false }),
|
|
122
130
|
execute(_id, params) {
|
|
123
|
-
const todo = state.createTodo({ workId: params.workId, taskName: params.taskName, taskInfo: params.taskInfo,
|
|
131
|
+
const todo = state.createTodo({ workId: params.workId, taskName: params.taskName, taskInfo: params.taskInfo, goal: params.goal, finalThoughts: params.finalThoughts, completionPercent: params.completionPercent });
|
|
124
132
|
return Promise.resolve(taskResult(`Created todo ${todo.taskId} under ${todo.workId}: ${todo.taskName} · ${formatCompletion(taskCompletion(todo))} [${todo.status}]`, "todo-create", { taskId: todo.taskId, workId: todo.workId, completionPercent: taskCompletion(todo) }));
|
|
125
133
|
},
|
|
126
134
|
renderCall: renderTaskCall("TodoCreate"),
|
|
@@ -148,9 +156,9 @@ export function registerTaskTools(pi, state) {
|
|
|
148
156
|
pi.registerTool({
|
|
149
157
|
name: "TodoUpdate",
|
|
150
158
|
label: "TodoUpdate",
|
|
151
|
-
description: `Update a todo's name, hidden coordination metadata, visible final thoughts, status, completionPercent, or working selection.
|
|
159
|
+
description: `Update a todo's name, hidden coordination metadata, visible final thoughts, status, completionPercent, or working selection. Timing starts automatically for the only eligible active owner: self task when execution begins or when it becomes eligible, so routine work needs no working=true call. Set working=true only to switch between eligible tasks; it pauses any previously selected task. Set working=false to pause without changing status for the rest of the run. Timing is calculated automatically, never estimated. Delegated agents time their own local tasks; never select a parent delegate task. For longer tasks, include an optional completionPercent estimate after roughly 5–10 meaningful working steps or a milestone, not just at completion or in status-only updates. Use finalThoughts for significant visible evidence; use null when unknown and never increase a percentage without evidence. A status change clears an unsupplied thought, so state the new dependency through blockedReason or the completed verified result. Blocking retains progress. Reserve completed/100 for verified completion. ${STATUS_GUIDANCE} ${TASK_INFO_GUIDANCE} ${FINAL_THOUGHTS_GUIDANCE} Completing a delegate task with a still-linked Core worker returns a cleanup advisory only; it never sends commands or changes worker state.`,
|
|
152
160
|
promptSnippet: "Keep todo status and visible final thoughts synchronized with active work",
|
|
153
|
-
promptGuidelines: ["
|
|
161
|
+
promptGuidelines: ["Mark the todo you are attempting active. An active owner: self task starts timing automatically when execution begins, so use working=true only to switch between eligible tasks, including when several are eligible; use working=false to pause for the rest of the run without a status change. Only one local task is timed; runtime idle and user waits pause automatically. Never update tracking during /ask or /btw.", "A completion cleanup advisory is informational only. Decide whether a real follow-up dependency remains; never treat it as permission to send /close, interrupt, or close a worker.", "Do not rename or broaden an existing Todo to absorb a distinct new user request; create a new Todo for it.", "During longer tasks, include an evidence-based completionPercent estimate after roughly 5–10 meaningful working steps or a milestone; do not wait until completion or only update status. Estimates remain optional: use null when unknown, and leave a percentage unchanged if there is no new evidence. Explain evidence in finalThoughts only when it is significant; only verified completed tasks may reach 100. Work completion is calculated automatically from tasks.", TASK_INFO_GUIDANCE, FINAL_THOUGHTS_GUIDANCE],
|
|
154
162
|
parameters: Type.Object({
|
|
155
163
|
taskId: Type.String(),
|
|
156
164
|
taskName: Type.Optional(NameSchema),
|
|
@@ -158,27 +166,256 @@ export function registerTaskTools(pi, state) {
|
|
|
158
166
|
finalThoughts: Type.Optional(FinalThoughtsSchema),
|
|
159
167
|
blockedReason: Type.Optional(BlockedReasonSchema),
|
|
160
168
|
dependentOn: Type.Optional(DependencySchema),
|
|
169
|
+
decisionQuestionId: Type.Optional(DecisionQuestionSchema),
|
|
161
170
|
status: Type.Optional(StatusSchema),
|
|
162
171
|
completionPercent: Type.Optional(CompletionSchema),
|
|
163
|
-
working: Type.Optional(Type.Boolean({ description: "
|
|
172
|
+
working: Type.Optional(Type.Boolean({ description: "Switch timing to this active owner: self task, or pause it for the rest of the run. Automatic timing already selects the only eligible task when a run begins, so use true only to switch between several eligible tasks. Selection switches away from the previously timed task. No timestamps or duration estimates are accepted." })),
|
|
164
173
|
}, { additionalProperties: false, minProperties: 2 }),
|
|
165
174
|
execute(_id, params) {
|
|
166
175
|
if (params.working !== undefined && !areTrackingToolsActive(pi))
|
|
167
176
|
throw new Error("Task timing is available only in tracked main-conversation work, not /ask or /btw.");
|
|
168
177
|
const previous = state.getTodo(params.taskId);
|
|
169
178
|
const taskInfo = params.taskInfo === undefined ? undefined : preservePaneLink(previous?.taskInfo ?? "", params.taskInfo);
|
|
170
|
-
const todo = state.updateTodo(params.taskId, { taskName: params.taskName, taskInfo, finalThoughts: params.finalThoughts, status: params.status, blockedReason: params.blockedReason, dependentOn: params.dependentOn, completionPercent: params.completionPercent, working: params.working });
|
|
179
|
+
const todo = state.updateTodo(params.taskId, { taskName: params.taskName, taskInfo, finalThoughts: params.finalThoughts, status: params.status, blockedReason: params.blockedReason, dependentOn: params.dependentOn, decisionQuestionId: params.decisionQuestionId, completionPercent: params.completionPercent, working: params.working });
|
|
171
180
|
const completedTransition = previous?.status !== "completed" && todo.status === "completed";
|
|
172
181
|
const cleanupTerminalId = completedTransition ? delegateLink(todo.taskInfo)?.terminalId : undefined;
|
|
173
|
-
|
|
182
|
+
const transition = todoTransition(previous, todo);
|
|
183
|
+
const sharedDecisionTaskIds = state.listTodos({ status: "blocked" })
|
|
184
|
+
.filter((other) => other.taskId !== todo.taskId && other.dependentOn === "user-decision"
|
|
185
|
+
&& todo.decisionQuestionId !== undefined && other.decisionQuestionId === todo.decisionQuestionId)
|
|
186
|
+
.map((other) => other.taskId);
|
|
187
|
+
const sharedDecision = sharedDecisionTaskIds.length
|
|
188
|
+
? ` Tasks ${sharedDecisionTaskIds.join(", ")} already wait on decision ${todo.decisionQuestionId}; one answer must reconcile every linked task.`
|
|
189
|
+
: "";
|
|
190
|
+
return Promise.resolve(taskResult(`Updated todo ${todo.taskId}: ${todo.taskName} · ${formatCompletion(taskCompletion(todo))} · ${formatTime(taskTime(todo))}${todo.workingSince === undefined ? "" : " running"} [${todo.status}]${sharedDecision}`, "todo-update", { taskId: todo.taskId, workId: todo.workId, status: todo.status, completionPercent: taskCompletion(todo), elapsedMs: taskTime(todo), working: todo.workingSince !== undefined, completedTransition, ...(todo.decisionQuestionId === undefined ? {} : { decisionQuestionId: todo.decisionQuestionId, sharedDecisionTaskIds }), ...(transition === undefined ? {} : { transition }), ...(cleanupTerminalId === undefined ? {} : { cleanupTerminalId }) }));
|
|
174
191
|
},
|
|
175
192
|
renderCall: renderTaskCall("TodoUpdate"),
|
|
176
193
|
renderResult: renderTaskResult,
|
|
177
194
|
});
|
|
195
|
+
pi.registerTool({
|
|
196
|
+
name: "TaskGoalUpdate",
|
|
197
|
+
label: "TaskGoalUpdate",
|
|
198
|
+
description: "Change a task's visible goal and acceptance criteria. The goal revision increases; no separate approval is required.",
|
|
199
|
+
parameters: Type.Object({ taskId: Type.String(), goal: Type.String({ minLength: 1 }), criteria: Type.Array(Type.String({ minLength: 1 }), { minItems: 1 }) }, { additionalProperties: false }),
|
|
200
|
+
execute(_id, params) {
|
|
201
|
+
if (!areTrackingToolsActive(pi))
|
|
202
|
+
throw new Error("Task lifecycle tools are available only in tracked main-conversation work.");
|
|
203
|
+
const todo = state.setGoal(params.taskId, params);
|
|
204
|
+
return Promise.resolve(taskResult("Task goal updated.", "goal-update", { taskId: todo.taskId, revision: todo.goal?.revision }));
|
|
205
|
+
},
|
|
206
|
+
renderCall: renderTaskCall("TaskGoalUpdate"),
|
|
207
|
+
renderResult: renderTaskResult,
|
|
208
|
+
});
|
|
209
|
+
pi.registerTool({
|
|
210
|
+
name: "TaskWorkerClose",
|
|
211
|
+
label: "TaskWorkerClose",
|
|
212
|
+
...workerCloseTools,
|
|
213
|
+
description: "For a completed task, start the live worker's /close once, then verify its completed retrospective after the existing Core monitor wakes. Never replay an uncertain request.",
|
|
214
|
+
parameters: Type.Object({ taskId: Type.String(), terminalId: Type.String(), action: StringEnum(["start", "verify"]), retrospectivePath: Type.Optional(Type.String()) }, { additionalProperties: false }),
|
|
215
|
+
executionMode: "sequential",
|
|
216
|
+
async execute(_id, params, _signal, _update, ctx) {
|
|
217
|
+
if (!areTrackingToolsActive(pi))
|
|
218
|
+
throw new Error("Task lifecycle tools are available only in tracked main-conversation work.");
|
|
219
|
+
const todo = state.getTodo(params.taskId);
|
|
220
|
+
if (todo?.status !== "completed")
|
|
221
|
+
throw new Error("Worker closeout requires a completed task.");
|
|
222
|
+
const context = ctx;
|
|
223
|
+
if (typeof context.executeTool !== "function" || !process.env.HC_TERMINAL_ID)
|
|
224
|
+
throw new Error("Worker closeout requires the Core parent and agent tools.");
|
|
225
|
+
const inspected = await context.executeTool("AgentStatus", { terminalId: params.terminalId });
|
|
226
|
+
const worker = inspected.result.details?.data;
|
|
227
|
+
if (inspected.isError || !worker || worker.address !== params.terminalId || worker.parent !== process.env.HC_TERMINAL_ID || worker.state !== "live" || worker.labels?.["pi.session"] !== ctx.sessionManager.getSessionId() || worker.labels?.["pi.task"] !== todo.taskId || !Number.isSafeInteger(worker.turn))
|
|
228
|
+
throw new Error("Cannot verify the live worker's task and parent identity.");
|
|
229
|
+
if (params.action === "start") {
|
|
230
|
+
if (todo.workerClose?.request)
|
|
231
|
+
throw new Error("The worker close request was already recorded; inspect its outcome instead of replaying it.");
|
|
232
|
+
if (worker.status?.state !== "done" && worker.status?.state !== "idle")
|
|
233
|
+
throw new Error("The task worker is not idle for /close.");
|
|
234
|
+
const monitors = await context.executeTool("MonitorList", {});
|
|
235
|
+
const entries = monitors.result.details?.monitors;
|
|
236
|
+
if (monitors.isError || !Array.isArray(entries) || !entries.some((entry) => entry && typeof entry === "object" && entry.hcTerminalId === params.terminalId && entry.status === "running" && entry.subscriptionReady === true))
|
|
237
|
+
throw new Error("The worker's continuous Core monitor is not ready.");
|
|
238
|
+
state.beginWorkerClose(todo.taskId, params.terminalId, Number(worker.turn));
|
|
239
|
+
const sent = await context.executeTool("AgentSend", { terminalId: params.terminalId, message: "/close" });
|
|
240
|
+
const receipt = sent.result.details?.data;
|
|
241
|
+
if (sent.isError || receipt?.started !== true)
|
|
242
|
+
throw new Error("The /close request outcome is uncertain. Inspect the same worker and monitor; do not send it again blindly.");
|
|
243
|
+
return taskResult("Worker /close requested. Wait for its existing monitor before verifying the retrospective.", "worker-close", { taskId: todo.taskId, status: "waiting" });
|
|
244
|
+
}
|
|
245
|
+
const request = todo.workerClose?.request;
|
|
246
|
+
if (!request || request.terminalId !== params.terminalId)
|
|
247
|
+
throw new Error("No matching worker /close request is recorded.");
|
|
248
|
+
if (worker.status?.state !== "done" && worker.status?.state !== "idle" || Number(worker.turn) <= request.turn)
|
|
249
|
+
throw new Error("The worker has not completed a new turn after /close.");
|
|
250
|
+
if (!params.retrospectivePath || !isAbsolute(params.retrospectivePath) || basename(params.retrospectivePath) !== "improvements.md")
|
|
251
|
+
throw new Error("Supply the worker's absolute improvements.md path.");
|
|
252
|
+
const file = await realpath(params.retrospectivePath);
|
|
253
|
+
let owned = false;
|
|
254
|
+
for (const source of todo.delegatedTimes ?? []) {
|
|
255
|
+
const root = await realpath(dirname(source.reportPath));
|
|
256
|
+
const components = relative(root, file).split(sep);
|
|
257
|
+
if (components.length === 4 && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(components[0]) && /^W[1-9][0-9]*$/.test(components[1]) && /^T[1-9][0-9]*$/.test(components[2]) && components[3] === "improvements.md" && (!source.workerSessionId || source.workerSessionId === components[0]))
|
|
258
|
+
owned = true;
|
|
259
|
+
}
|
|
260
|
+
if (!owned)
|
|
261
|
+
throw new Error("The retrospective is not in this task's canonical delegated directory.");
|
|
262
|
+
const info = await stat(file);
|
|
263
|
+
const text = await readFile(file, "utf8");
|
|
264
|
+
if (!info.isFile() || info.mtimeMs < request.requestedAt || !text.trim())
|
|
265
|
+
throw new Error("The worker retrospective is missing, empty, or older than the close request.");
|
|
266
|
+
if (!/\b(?:Completed|Blocked|Interrupted)\b/u.test(text) || !["Skill improvements", "Codebase improvements", "Documentation improvements", "Speed opportunities"].every((section) => text.toLowerCase().includes(section.toLowerCase())))
|
|
267
|
+
throw new Error("The worker retrospective does not contain the required outcome and sections.");
|
|
268
|
+
const output = await context.executeTool("AgentOutput", { terminalId: params.terminalId, lines: 200 });
|
|
269
|
+
const workerOutput = output.result.details?.data?.output;
|
|
270
|
+
const relativePath = relative(ctx.cwd, file);
|
|
271
|
+
if (output.isError || typeof workerOutput !== "string" || (!workerOutput.includes(params.retrospectivePath) && !workerOutput.includes(relativePath)))
|
|
272
|
+
throw new Error("The worker's completed output does not confirm this retrospective path.");
|
|
273
|
+
const closed = state.closeWorker(todo.taskId, params.terminalId);
|
|
274
|
+
return taskResult("Worker retrospective verified and task closed.", "worker-close", { taskId: closed.taskId, status: closed.status, workerClose: "completed" });
|
|
275
|
+
},
|
|
276
|
+
renderCall: renderTaskCall("TaskWorkerClose"),
|
|
277
|
+
renderResult: renderTaskResult,
|
|
278
|
+
});
|
|
279
|
+
pi.registerTool({
|
|
280
|
+
name: "TaskCloseoutFinalize",
|
|
281
|
+
label: "TaskCloseoutFinalize",
|
|
282
|
+
...workerPresenceTools,
|
|
283
|
+
description: "For a completed task, verify whether its worker is absent. If confirmed absent, close the task and record that /close was not run. A live worker must complete /close before closure; an unavailable presence check is not absence.",
|
|
284
|
+
parameters: Type.Object({ taskId: Type.String() }, { additionalProperties: false }),
|
|
285
|
+
executionMode: "sequential",
|
|
286
|
+
async execute(_id, params, _signal, _update, ctx) {
|
|
287
|
+
if (!areTrackingToolsActive(pi))
|
|
288
|
+
throw new Error("Task lifecycle tools are available only in tracked main-conversation work.");
|
|
289
|
+
const todo = state.getTodo(params.taskId);
|
|
290
|
+
if (todo?.status !== "completed")
|
|
291
|
+
throw new Error("Worker absence can be verified only for a completed task.");
|
|
292
|
+
const context = ctx;
|
|
293
|
+
if (typeof context.executeTool !== "function" || !process.env.HC_TERMINAL_ID)
|
|
294
|
+
throw new Error("Cannot verify worker presence without the Core parent and AgentList tools.");
|
|
295
|
+
const listed = await context.executeTool("AgentList", {});
|
|
296
|
+
const list = listed.result.details;
|
|
297
|
+
if (listed.isError || !Array.isArray(list?.data?.terminals))
|
|
298
|
+
throw new Error("Worker presence is unknown; AgentList did not return a verified live-terminal list.");
|
|
299
|
+
const terminals = list.data.terminals;
|
|
300
|
+
const linked = delegateLink(todo.taskInfo)?.terminalId;
|
|
301
|
+
for (const candidate of terminals) {
|
|
302
|
+
if (!candidate || typeof candidate !== "object")
|
|
303
|
+
throw new Error("Worker presence is unknown; the Core terminal list was invalid.");
|
|
304
|
+
const item = candidate;
|
|
305
|
+
if (typeof item.address !== "string" || typeof item.state !== "string")
|
|
306
|
+
throw new Error("Worker presence is unknown; a Core terminal record was incomplete.");
|
|
307
|
+
if (item.state !== "live")
|
|
308
|
+
continue;
|
|
309
|
+
if (linked === item.address)
|
|
310
|
+
throw new Error("The linked worker is present and must complete /close before this task can close.");
|
|
311
|
+
if (item.agent !== "pi" || item.parent !== process.env.HC_TERMINAL_ID)
|
|
312
|
+
continue;
|
|
313
|
+
const inspected = await context.executeTool("AgentStatus", { terminalId: item.address });
|
|
314
|
+
const data = inspected.result.details?.data;
|
|
315
|
+
if (inspected.isError || !data?.labels || typeof data.labels !== "object")
|
|
316
|
+
throw new Error("Worker presence is unknown; a live Pi terminal could not be inspected.");
|
|
317
|
+
const labels = data.labels;
|
|
318
|
+
if (labels["pi.session"] === ctx.sessionManager.getSessionId() && labels["pi.task"] === todo.taskId)
|
|
319
|
+
throw new Error("The task's worker is present and must complete /close before this task can close.");
|
|
320
|
+
}
|
|
321
|
+
const closed = state.closeAbsent(todo.taskId);
|
|
322
|
+
const workerClose = closed.workerClose?.outcome;
|
|
323
|
+
return taskResult(workerClose === "unverified-absent" ? "Task closed; the worker is absent and the requested /close outcome is unverified." : "Task closed; the worker was absent and /close was not run.", "closeout-finalize", { taskId: closed.taskId, status: closed.status, workerClose });
|
|
324
|
+
},
|
|
325
|
+
renderCall: renderTaskCall("TaskCloseoutFinalize"),
|
|
326
|
+
renderResult: renderTaskResult,
|
|
327
|
+
});
|
|
328
|
+
pi.registerTool({
|
|
329
|
+
name: "TaskLifecycleDecision",
|
|
330
|
+
label: "TaskLifecycleDecision",
|
|
331
|
+
...decisionTools,
|
|
332
|
+
description: "Ask a human to explicitly cancel a task or reopen a closed or cancelled one. Supply reason when cancelling an obsolete or superseded task so the page and the recorded decision state why its premise no longer holds; this is the truthful human-authorized retirement, never a completion. Share the URL and yield while waiting. A cancellation requested from an active task is recorded as blocked on user-decision with this decisionQuestionId once the page is pending; rejecting it restores the task to active, and confirming cancels it. Resume with the same questionId and the same reason so the page identity stays valid. The task is unchanged until the human confirms.",
|
|
333
|
+
parameters: Type.Object({ taskId: Type.String(), action: StringEnum(["cancel", "reopen"]), questionId: Type.Optional(Type.String()), reason: Type.Optional(Type.String({ minLength: 1, description: "Why the task should be retired or reopened. Recorded with the human decision and shown on the page; required in substance when cancelling because the task's premise no longer holds." })) }, { additionalProperties: false }),
|
|
334
|
+
executionMode: "sequential",
|
|
335
|
+
async execute(_id, params, _signal, _update, ctx) {
|
|
336
|
+
if (!areTrackingToolsActive(pi))
|
|
337
|
+
throw new Error("Task lifecycle tools are available only in tracked main-conversation work.");
|
|
338
|
+
const todo = state.getTodo(params.taskId);
|
|
339
|
+
if (!todo)
|
|
340
|
+
throw new Error("An existing task is required.");
|
|
341
|
+
if (params.action === "cancel" && (todo.status === "cancelled" || todo.status === "closed"))
|
|
342
|
+
throw new Error("Task is already closed or cancelled.");
|
|
343
|
+
if (params.action === "reopen" && todo.status !== "cancelled" && todo.status !== "closed")
|
|
344
|
+
throw new Error("Only a closed or cancelled task can be reopened here.");
|
|
345
|
+
if (params.reason !== undefined && params.action !== "cancel")
|
|
346
|
+
throw new Error("A reason is accepted only for a cancellation decision.");
|
|
347
|
+
const reason = params.reason?.trim();
|
|
348
|
+
if (params.reason !== undefined && !reason)
|
|
349
|
+
throw new Error("A cancellation reason must not be blank.");
|
|
350
|
+
const settings = pi.getSettings?.();
|
|
351
|
+
const config = settings && typeof settings === "object" ? settings["pi-decisions"] : undefined;
|
|
352
|
+
if (config && typeof config === "object" && config.backend === "here.now")
|
|
353
|
+
throw new Error("Task details are not authorized for public hosted delivery. Use a local decision backend.");
|
|
354
|
+
const context = ctx;
|
|
355
|
+
if (typeof context.executeTool !== "function")
|
|
356
|
+
throw new Error("Human task decisions require Pi tool delegation support.");
|
|
357
|
+
const currentRevision = todo.revision ?? 0;
|
|
358
|
+
const presentedRevision = currentRevision;
|
|
359
|
+
const decisionPattern = /^task-(cancel|reopen)-(T[1-9]\d*)-(\d+|undefined)-([a-f0-9-]{36})$/u;
|
|
360
|
+
const questionId = params.questionId ?? `task-${params.action}-${todo.taskId}-${presentedRevision}-${randomUUID()}`;
|
|
361
|
+
const parsed = decisionPattern.exec(questionId);
|
|
362
|
+
if (!parsed || parsed[1] !== params.action || parsed[2] !== todo.taskId)
|
|
363
|
+
throw new Error("This decision does not belong to this task and action.");
|
|
364
|
+
const parsedRevision = parsed[3] === "undefined" ? 0 : Number(parsed[3]);
|
|
365
|
+
// An active task is recorded blocked only after its page is confirmed
|
|
366
|
+
// pending; rejection restores it. That block is the one accepted change
|
|
367
|
+
// beyond the presented revision.
|
|
368
|
+
const pendingBlock = currentRevision === parsedRevision + 1 && todo.status === "blocked"
|
|
369
|
+
&& todo.decisionQuestionId === questionId;
|
|
370
|
+
if (currentRevision !== parsedRevision && !pendingBlock)
|
|
371
|
+
throw new Error("The task changed since this decision was presented; request a new decision.");
|
|
372
|
+
const presentedStatus = pendingBlock ? "active" : todo.status;
|
|
373
|
+
const question = params.action === "cancel" ? `Cancel ${todo.taskId}?` : `Reopen ${todo.taskId}?`;
|
|
374
|
+
const pageContent = [todo.taskName, `Current status: ${presentedStatus}`, ...(reason ? [`Reason: ${reason}`] : [])].join("\n");
|
|
375
|
+
const submitted = await context.executeTool("SubmitQuestion", { questionId, mode: "single", question, content: [{ type: "text", text: pageContent }], options: [{ id: "confirm", label: params.action === "cancel" ? "Cancel task" : "Reopen task" }, { id: "reject", label: "Leave unchanged" }] });
|
|
376
|
+
if (submitted.isError)
|
|
377
|
+
throw new Error(`Could not present the task decision. Resume question ${questionId} after checking SubmitQuestion and its local backend.`);
|
|
378
|
+
const checked = await context.executeTool("WaitForAnswer", { questionId });
|
|
379
|
+
if (checked.isError)
|
|
380
|
+
throw new Error(`Could not check the task decision. Resume question ${questionId} after checking WaitForAnswer and its watcher.`);
|
|
381
|
+
const details = checked.result.details;
|
|
382
|
+
if (details?.status === "waiting") {
|
|
383
|
+
if (params.action === "cancel" && todo.status === "active") {
|
|
384
|
+
// blockedReason has an existing 10k record bound; keep the page reason
|
|
385
|
+
// intact while fitting the stored explanation to that boundary.
|
|
386
|
+
const pendingReason = reason === undefined ? "" : ` ${reason.length > 9000 ? `${reason.slice(0, 8999)}…` : reason}`;
|
|
387
|
+
state.updateTodo(todo.taskId, {
|
|
388
|
+
status: "blocked",
|
|
389
|
+
blockedReason: `Awaiting a human cancellation decision for ${todo.taskId} (question ${questionId}).${pendingReason}`,
|
|
390
|
+
dependentOn: "user-decision",
|
|
391
|
+
decisionQuestionId: questionId,
|
|
392
|
+
...(todo.finalThoughts === undefined ? {} : { finalThoughts: todo.finalThoughts }),
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
return taskResult(`Waiting for a human decision: ${String(details.url ?? "URL unavailable")}. The task is recorded as waiting on this decision with dependentOn="user-decision". Resume with the same questionId${reason ? " and reason" : ""} once the human answers.`, "lifecycle-decision", { taskId: todo.taskId, questionId, reason, status: "waiting", url: details.url });
|
|
396
|
+
}
|
|
397
|
+
const answer = details?.answer;
|
|
398
|
+
if (details?.status !== "answered" || answer?.questionId !== questionId || answer.sessionId !== ctx.sessionManager.getSessionId() || !Array.isArray(answer.selectedIds) || typeof answer.timestamp !== "string")
|
|
399
|
+
throw new Error("The task decision was not a valid answer for this session.");
|
|
400
|
+
if (answer.selectedIds.length !== 1 || answer.selectedIds[0] !== "confirm") {
|
|
401
|
+
if (pendingBlock)
|
|
402
|
+
state.updateTodo(todo.taskId, { status: "active", ...(todo.finalThoughts === undefined ? {} : { finalThoughts: todo.finalThoughts }) });
|
|
403
|
+
return taskResult("Task unchanged.", "lifecycle-decision", { taskId: todo.taskId, status: "rejected" });
|
|
404
|
+
}
|
|
405
|
+
const current = state.getTodo(todo.taskId);
|
|
406
|
+
const currentRevisionNow = current?.revision ?? 0;
|
|
407
|
+
if (!current || (currentRevisionNow !== parsedRevision && !pendingBlock))
|
|
408
|
+
throw new Error("The task changed while the decision was waiting; request a new decision.");
|
|
409
|
+
const updated = state.applyHumanLifecycleDecision(todo.taskId, currentRevisionNow, params.action, questionId, answer.timestamp, reason);
|
|
410
|
+
return taskResult(`Task ${updated.taskId} is ${updated.status}.`, "lifecycle-decision", { taskId: updated.taskId, status: updated.status });
|
|
411
|
+
},
|
|
412
|
+
renderCall: renderTaskCall("TaskLifecycleDecision"),
|
|
413
|
+
renderResult: renderTaskResult,
|
|
414
|
+
});
|
|
178
415
|
pi.registerTool({
|
|
179
416
|
name: "TodoDelete",
|
|
180
417
|
label: "TodoDelete",
|
|
181
|
-
description: "Delete a
|
|
418
|
+
description: "Delete a task with no recorded work. A retained task cannot be deleted; cancel it through the explicit human decision instead.",
|
|
182
419
|
parameters: Type.Object({ taskId: Type.String() }, { additionalProperties: false }),
|
|
183
420
|
execute(_id, params) {
|
|
184
421
|
const todo = state.getTodo(params.taskId);
|
|
@@ -205,7 +442,12 @@ function formatTodos(todos) {
|
|
|
205
442
|
return "No todos found.";
|
|
206
443
|
return todos.map((todo) => {
|
|
207
444
|
const dependency = dependentOnLabel(todo.dependentOn);
|
|
208
|
-
|
|
445
|
+
const blockedAge = todo.status === "blocked" ? formatBlockedAge(blockedAgeMs(todo)) : undefined;
|
|
446
|
+
const blockedSince = blockedAge === undefined ? "" : ` · ${blockedAge}`;
|
|
447
|
+
const question = todo.status === "blocked" && todo.decisionQuestionId !== undefined ? `\nDecision question: ${todo.decisionQuestionId}` : "";
|
|
448
|
+
const goal = todo.goal ? `\nGoal${todo.goal.confirmation?.revision === todo.goal.revision ? " (confirmed)" : ""}:\n${todo.goal.goal}\nAcceptance criteria:\n${todo.goal.criteria.map((criterion) => `- ${criterion}`).join("\n")}` : "";
|
|
449
|
+
const closeouts = todo.closeoutAttempts?.map((attempt) => `\nCloseout ${attempt.questionId} (${attempt.decision ? attempt.decision.approved ? "approved" : "rejected" : "pending"}):\nGoal: ${attempt.goal.goal}\n${attempt.results.map((result) => `- ${result.criterion}\n Result: ${result.result}\n Evidence: ${result.evidence}`).join("\n")}\nLimits: ${attempt.limits}${attempt.decision?.feedback ? `\nFeedback: ${attempt.decision.feedback}` : ""}${attempt.workerClose ? `\nWorker close: ${attempt.workerClose}` : ""}`).join("") ?? "";
|
|
450
|
+
return `${todo.taskId} [${todo.status}] ${todo.taskName} · ${formatCompletion(taskCompletion(todo))} · Time: ${formatTime(taskTime(todo))}${todo.workingSince === undefined ? "" : " (running)"}${goal}${closeouts}\nWork: ${todo.workId}${todo.worktree === undefined ? "" : `\nWorktree: ${todo.worktree}`}\nFinal thoughts:\n${finalThoughtsFor(todo) ?? "None recorded."}\n${dependency === undefined ? "" : `Dependent on: ${dependency}${blockedSince}\n`}${question}Task info (hidden coordination metadata):\n${todo.taskInfo}`;
|
|
209
451
|
}).join("\n\n");
|
|
210
452
|
}
|
|
211
453
|
function bounded(text) {
|
package/dist/tracking.js
CHANGED
|
@@ -4,9 +4,9 @@ Work is a collection of tasks with shared context and no status of its own. A to
|
|
|
4
4
|
|
|
5
5
|
Tasks belong only to the Pi session ID. Conversation branch navigation never rolls back task records; a new session ID starts a separate store.
|
|
6
6
|
For every normal user request that starts or continues work, keep the session's work and todo records synchronized. Treat each distinct new actionable request as its own outcome: before starting or delegating it, create its own Todo under the relevant Work, or a new Work when the outcome is separate, even when the request extends an existing Work. Do not record a new request only by broadening workInfo, renaming an existing Todo, or blocking a previous Todo. Reuse an active Todo only when it genuinely owns the same outcome; do not create a Todo for each sentence, clarification, check, or tool call. Do not skip tracking because the work looks small. Plain conversation and clarification need no Todo, and /ask and /btw remain outside tracking.
|
|
7
|
-
Write workInfo in normal prose with full sentences and spaces between words. Conversational brevity modes must not compress stored records or concatenate words. taskInfo is hidden coordination metadata; finalThoughts is the
|
|
7
|
+
Write workInfo in normal prose with full sentences and spaces between words. Conversational brevity modes must not compress stored records or concatenate words. taskInfo is hidden coordination metadata; finalThoughts is the user-visible result update, separate from stored goals and criteria where available.
|
|
8
8
|
|
|
9
|
-
Each task's finalThoughts is
|
|
9
|
+
Each task's finalThoughts is its concise result update. Write one concise update, never a goal restatement, ownership rationale, history, list, or section. For a blocked task, blockedReason is the authoritative visible dependency and what will unblock it; do not duplicate it in finalThoughts. A blocked task also requires dependentOn="user-decision" for a user response, decision, or permission, or dependentOn="another-agent" for another agent's output or review; task details show it beside Final thoughts. For a completed task, state the short actual result, the verification performed, and any remaining limits; do not omit it by habit. For an active task, update only when something significant changed; otherwise leave the thought unchanged rather than adding filler. Keep owner declarations, terminal/monitor links, artifact paths, and parent IDs in taskInfo, never in finalThoughts.
|
|
10
10
|
|
|
11
11
|
Every delegated subagent, at every delegation depth, must use these tools to create or resume its own session-local Work and Todos before assigned work. Do not begin assigned work without a real workId and an active taskId for the current step. Keep these records current and return the IDs with results, checks, and blockers. Parent assignment IDs are context, not shared records: IDs are session-scoped. Record the parent assignment in the worker's details; do not mutate the parent's session records. Include this requirement in every subagent prompt. If tracking tools or IDs are unavailable, report the blocker and do not begin delegated work; a parent-owned Todo or Markdown checklist is not a substitute. Do not invent IDs or backdate tracking. This is an instruction, not a runtime enforcement hook, and does not change the /ask or /btw exceptions.
|
|
12
12
|
|
|
@@ -22,20 +22,24 @@ Shared workflow contract:
|
|
|
22
22
|
Before implementation, investigation, or any other requested work:
|
|
23
23
|
1. Use WorkList and TodoList to find the relevant existing records and avoid duplicates.
|
|
24
24
|
2. If no suitable work exists, create one with WorkCreate. Otherwise use WorkUpdate when its scope or shared context needs refreshing.
|
|
25
|
-
3. Create a Todo for each distinct new actionable request, or update an existing Todo that already owns the same outcome; adding a request to an existing Work never makes it part of an existing Todo. Works have no status.
|
|
26
|
-
4. Mark the todo being attempted active with TodoUpdate before doing that work.
|
|
25
|
+
3. Create a Todo for each distinct new actionable request, or update an existing Todo that already owns the same outcome; adding a request to an existing Work never makes it part of an existing Todo. Works have no status. Each task carries its own visible goal and acceptance criteria and starts active with no separate goal approval; only an explicit human decision cancels or reopens a closed or cancelled task. Keep taskInfo to hidden coordination metadata and set concise finalThoughts for visible updates.
|
|
26
|
+
4. Mark the todo being attempted active with TodoUpdate before doing that work. An active owner: self task starts timing automatically when execution begins or when it becomes the only eligible task; use working=true only to switch between several eligible tasks, and working=false to pause for the rest of the run. Only one local task can be timed; selecting another pauses the previous one. Idle, blocking user prompts, and terminal statuses pause automatically. Delegated agents time their own local tasks; a parent delegate record is not a running local task. AgentCreate provides a timing reportPath: workers pause or complete assignment tasks and call TaskTimeExport with that path and all assignment-local taskIds before returning. The parent calls TaskTimeImport for its delegated task after worker output is available, before closing the agent. Follow-ups re-export the cumulative assignment task set and re-import. Import nested delegate time before exporting to your own caller. These tools read measured values; never hand-write timing reports or estimate or submit durations.
|
|
27
27
|
5. completionPercent on TodoCreate/TodoUpdate is optional. When estimating, use an approximate integer from 0 to 100 based on actual work and verification, not elapsed time or a fixed mapping from status. Use 0 for genuinely unstarted tasks and null when unknown. Never invent progress to make a work look further along.
|
|
28
28
|
|
|
29
29
|
During and after the attempt:
|
|
30
30
|
- When available, use MonitorCreate only when a command should continue in the background; inspect it with MonitorList and do not poll it with shell sleep loops.
|
|
31
31
|
- When available, use LoopCreate only when work needs a future or repeated wake. Do not create a loop for ordinary synchronous work.
|
|
32
|
-
- Waiting has an owner and a wake. A real delegated agent keeps its parent task blocked with dependentOn="another-agent" and one continuous Core monitor (hcTerminalId); a state change is a cue to inspect fresh output, and done or idle is not completion proof. A long command keeps its task active with owner: self and uses a monitor onDone wake; it is not blocked merely because a process is running. An external service, failed tool, or missing access keeps the task active
|
|
33
|
-
- A loop or monitor does not replace task status. Mark a task blocked only when its next step waits for a user decision or another agent's output or review. Supply both blockedReason and dependentOn when creating a blocked task or entering blocked status; dependentOn must be exactly "user-decision" or "another-agent". Explain the current dependency and what will unblock it; preserve progress. blockedReason is the visible Final thoughts for a blocked task, so do not duplicate it in finalThoughts. Unrelated blocked edits preserve both fields; leaving blocked clears both. Do not mark a task blocked
|
|
32
|
+
- Waiting has an owner and a wake. A real delegated agent keeps its parent task blocked with dependentOn="another-agent" and one continuous Core monitor (hcTerminalId); a state change is a cue to inspect fresh output, and done or idle is not completion proof. A long command keeps its task active with owner: self and uses a monitor onDone wake; it is not blocked merely because a process is running. An external service, failed tool, or missing access keeps the task active only when nobody can act on it yet; classify by who can clear it. When only the user can unblock the next step, such as a browser profile they must sign in or reconnect, access they must grant, or an identifier only they hold, that is a user-decision blocker for the browser decision workflow, never a plain external obstacle. Never mislabel an external obstacle a user decision or agent output merely because a tool failed. Do not poll on a timer, add one-shot waits, retry unchanged work, or write repeat updates that only restate waiting. A stopped or unchanged loop iteration is normal: for a dynamic loop, update it once; fixed cron/event loops persist normally and need no update. Continue only with remaining work and finish cleanly when the stop condition is met.
|
|
33
|
+
- A loop or monitor does not replace task status. Mark a task blocked only when its next step waits for a user decision or another agent's output or review. Supply both blockedReason and dependentOn when creating a blocked task or entering blocked status; dependentOn must be exactly "user-decision" or "another-agent". Explain the current dependency and what will unblock it; preserve progress. blockedReason is the visible Final thoughts for a blocked task, so do not duplicate it in finalThoughts. Unrelated blocked edits preserve both fields; leaving blocked clears both. Do not mark a task blocked when a service, tool or access failed and nobody can act on it yet: continue safe work and report the unavailable dependency truthfully instead of misclassifying it. Do not leave an obstacle that only the user can clear as an active task with no request to them either; that is a user-decision blocker. When the blocker is a pi-decisions page, set decisionQuestionId to its questionId and pass the same task IDs to SubmitQuestion; if several tasks share one decision, one answer must reconcile all of them, and a superseded page is withdrawn with WithdrawQuestion in the same turn that its linked tasks are updated. If you conclude 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. A task whose premise no longer holds is retired through the human cancellation decision with the reason, never by staying active or marking completion. Parent delegated tasks stay blocked while awaiting worker output; the worker's own local tasks may be active. AgentCreate marks the parent task blocked automatically with dependentOn="another-agent". For manual delegation, mark the parent task blocked explicitly. When the dependency resolves and work resumes, mark the affected tasks active and state the new significant update if there is one; a status change clears an unsupplied stale thought.
|
|
34
34
|
- During longer tasks, include an evidence-based completionPercent estimate in TodoUpdate after roughly 5–10 meaningful working steps or a milestone. Do not wait until completion or only update status when an estimate is possible. When a change is significant, explain the visible evidence and remaining work in finalThoughts; never narrate progress in taskInfo and do not add filler on every estimate. Estimates remain optional: use null when unknown, and leave a percentage unchanged if there is no new evidence. Keep estimates current, including after scope changes. Work completion is derived as the equal average of non-cancelled task percentages; any unknown child makes it unknown. Do not set an independent work percentage.
|
|
35
35
|
- Mark the todo completed, blocked, or cancelled as appropriate. Only use completed/100 after verification. On completion, set finalThoughts to the short actual result, checks performed, and remaining limits. Blocking retains the last percentage; it does not erase completed effort. Reopening a completed task needs a fresh estimate (otherwise it becomes unknown). Update taskInfo only when coordination metadata changes.
|
|
36
36
|
- Percentages are approximate completion, not ETA or proof. Never change task statuses merely because a percentage looks complete.
|
|
37
37
|
- Work is only a collection: never assign it active, blocked, completed, or cancelled status. Track every executable step as a todo; empty works do not trigger continuation. Automatic continuation checks active todos across all works in the current Pi session; blocked, completed, and cancelled tasks do not trigger it. Update workInfo only when shared scope, context, or decisions change.
|
|
38
|
-
- Never create or update works, todos, loops, or monitors during /ask, /btw, or any BTW side thread
|
|
38
|
+
- Never create or update works, todos, loops, or monitors during /ask, /btw, or any BTW side thread.
|
|
39
|
+
|
|
40
|
+
Task lifecycle: every task carries its own visible goal and acceptance criteria and starts active; no separate approval is required to begin, delegate, complete, or close it. Use TaskGoalUpdate when scope materially changes the goal. completed means verified work at 100%; close a completed task when no further work belongs to it. For a delegated worker, request and verify its /close with TaskWorkerClose, or use TaskCloseoutFinalize to verify absence before closing; closure itself needs no approval. Use TaskLifecycleDecision for explicit human cancellation or reopening of closed or cancelled tasks; never autonomously cancel or reopen them. Genuine user decisions still use the browser decision workflow.
|
|
41
|
+
|
|
42
|
+
When enabled, pi-tasks may deliver one combined task review at a safe settlement after tracked transitions or for eligible active work; record-correctness reviews for completed/blocked transitions are delivered even when progress auto-continuation is disabled or its budget is spent. Every delivered review and the first turn after a session resume includes a read-only blocked-task audit with dependency class, blocked age, linked question and reason. Use it to reconcile each record, not to clear blockers that still exist. Treat it as part of the same authorized run: sweep in-scope work and verification before handing back, and do not expand completion into unrelated optional work. A genuine human decision goes to the browser workflow (SubmitQuestion, then WaitForAnswer once) rather than a chat question; share the URL and yield for the watcher wake. If those tools are unavailable or headless, say so and keep the exact dependency in blockedReason. An other-agent wait is not a human decision: keep dependentOn="another-agent" and one continuous monitor.`;
|
|
39
43
|
export function areTrackingToolsActive(pi) {
|
|
40
44
|
const active = new Set(pi.getActiveTools());
|
|
41
45
|
return REQUIRED_TRACKING_TOOLS.every((name) => active.has(name));
|
|
@@ -45,8 +49,9 @@ export function registerTrackingGuidance(pi) {
|
|
|
45
49
|
if (!areTrackingToolsActive(pi))
|
|
46
50
|
return;
|
|
47
51
|
const options = event.systemPromptOptions;
|
|
52
|
+
const guidance = TRACKING_GUIDANCE;
|
|
48
53
|
options.appendSystemPrompt = options.appendSystemPrompt
|
|
49
|
-
? `${options.appendSystemPrompt}\n\n${
|
|
50
|
-
:
|
|
54
|
+
? `${options.appendSystemPrompt}\n\n${guidance}`
|
|
55
|
+
: guidance;
|
|
51
56
|
});
|
|
52
57
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Todo } from "./types.js";
|
|
2
|
+
/** The tracked status changes that deserve an in-run review. */
|
|
3
|
+
export type TodoTransitionKind = "completed" | "blocked-user" | "blocked-agent";
|
|
4
|
+
/**
|
|
5
|
+
* Map one TodoUpdate state change to its review kind. Ordinary same-status
|
|
6
|
+
* edits emit nothing, except a blocked task whose dependency changes class:
|
|
7
|
+
* that is a genuinely new wait and needs its own review.
|
|
8
|
+
*/
|
|
9
|
+
export declare function todoTransition(previous: Pick<Todo, "status" | "dependentOn"> | undefined, todo: Pick<Todo, "status" | "dependentOn">): TodoTransitionKind | undefined;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
function blockedKind(dependentOn) {
|
|
2
|
+
if (dependentOn === "user-decision")
|
|
3
|
+
return "blocked-user";
|
|
4
|
+
if (dependentOn === "another-agent")
|
|
5
|
+
return "blocked-agent";
|
|
6
|
+
return undefined;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Map one TodoUpdate state change to its review kind. Ordinary same-status
|
|
10
|
+
* edits emit nothing, except a blocked task whose dependency changes class:
|
|
11
|
+
* that is a genuinely new wait and needs its own review.
|
|
12
|
+
*/
|
|
13
|
+
export function todoTransition(previous, todo) {
|
|
14
|
+
if (previous?.status === todo.status) {
|
|
15
|
+
if (todo.status !== "blocked" || previous.dependentOn === todo.dependentOn)
|
|
16
|
+
return undefined;
|
|
17
|
+
const from = blockedKind(previous.dependentOn);
|
|
18
|
+
const to = blockedKind(todo.dependentOn);
|
|
19
|
+
return from === to ? undefined : to;
|
|
20
|
+
}
|
|
21
|
+
if (todo.status === "completed")
|
|
22
|
+
return "completed";
|
|
23
|
+
if (todo.status === "blocked")
|
|
24
|
+
return blockedKind(todo.dependentOn);
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { TaskDependency } from "./dependency.js";
|
|
2
2
|
export type { TaskDependency } from "./dependency.js";
|
|
3
|
-
export type TodoStatus = "active" | "blocked" | "completed" | "cancelled";
|
|
3
|
+
export type TodoStatus = "active" | "blocked" | "completed" | "closed" | "cancelled";
|
|
4
4
|
export interface Work {
|
|
5
5
|
workId: string;
|
|
6
6
|
workName: string;
|
|
@@ -11,13 +11,75 @@ export interface Work {
|
|
|
11
11
|
/** One assignment's cumulative imported effort; absent measurement stays unknown. */
|
|
12
12
|
export interface DelegatedTime {
|
|
13
13
|
reportPath: string;
|
|
14
|
+
/** Worker checkout root used to validate cross-worktree reports. */
|
|
15
|
+
reportRoot?: string;
|
|
14
16
|
elapsedMs: number | null;
|
|
15
17
|
workerSessionId?: string;
|
|
16
18
|
}
|
|
19
|
+
export interface TaskGoal {
|
|
20
|
+
goal: string;
|
|
21
|
+
criteria: string[];
|
|
22
|
+
revision: number;
|
|
23
|
+
/** Legacy stored human confirmation; no longer required or written. */
|
|
24
|
+
confirmation?: {
|
|
25
|
+
revision: number;
|
|
26
|
+
questionId: string;
|
|
27
|
+
answeredAt: string;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/** Legacy stored closeout review evidence; no longer created or required. */
|
|
31
|
+
export interface CloseoutAttempt {
|
|
32
|
+
questionId: string;
|
|
33
|
+
batchTaskIds: string[];
|
|
34
|
+
taskRevision: number;
|
|
35
|
+
taskName: string;
|
|
36
|
+
goal: TaskGoal;
|
|
37
|
+
results: Array<{
|
|
38
|
+
criterion: string;
|
|
39
|
+
result: string;
|
|
40
|
+
evidence: string;
|
|
41
|
+
}>;
|
|
42
|
+
limits: string;
|
|
43
|
+
decision?: {
|
|
44
|
+
approved: boolean;
|
|
45
|
+
answeredAt: string;
|
|
46
|
+
feedback: string;
|
|
47
|
+
};
|
|
48
|
+
workerClose?: "not-run-absent" | "unverified-absent" | "completed";
|
|
49
|
+
workerCloseRequest?: {
|
|
50
|
+
terminalId: string;
|
|
51
|
+
turn: number;
|
|
52
|
+
requestedAt: number;
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export interface WorkerClose {
|
|
56
|
+
request?: {
|
|
57
|
+
terminalId: string;
|
|
58
|
+
turn: number;
|
|
59
|
+
requestedAt: number;
|
|
60
|
+
};
|
|
61
|
+
outcome?: "not-run-absent" | "unverified-absent" | "completed";
|
|
62
|
+
}
|
|
17
63
|
export interface Todo {
|
|
18
64
|
taskId: string;
|
|
19
65
|
workId: string;
|
|
20
66
|
taskName: string;
|
|
67
|
+
/** Monotonic mutation identity for binding human decisions. */
|
|
68
|
+
revision?: number;
|
|
69
|
+
/** User-visible outcome and criteria. */
|
|
70
|
+
goal?: TaskGoal;
|
|
71
|
+
lifecycleDecisions?: Array<{
|
|
72
|
+
action: "cancel" | "reopen";
|
|
73
|
+
questionId: string;
|
|
74
|
+
answeredAt: string;
|
|
75
|
+
reason?: string;
|
|
76
|
+
}>;
|
|
77
|
+
/** Legacy closeout review history; retained for existing records only. */
|
|
78
|
+
closeoutAttempts?: CloseoutAttempt[];
|
|
79
|
+
/** Delegated worker `/close` request and outcome; the task may close without it. */
|
|
80
|
+
workerClose?: WorkerClose;
|
|
81
|
+
/** Name of the worktree assigned to this task, when applicable. */
|
|
82
|
+
worktree?: string;
|
|
21
83
|
/** Hidden coordination metadata: owner declaration, artifact paths, parent IDs, identifiers. Never shown as task text. */
|
|
22
84
|
taskInfo: string;
|
|
23
85
|
/** The only visible task text. Concise status update, not a goal or narrative. */
|
|
@@ -27,6 +89,10 @@ export interface Todo {
|
|
|
27
89
|
blockedReason?: string | null;
|
|
28
90
|
/** The only two valid blocked dependencies; absent on nonblocked and legacy tasks. */
|
|
29
91
|
dependentOn?: TaskDependency;
|
|
92
|
+
/** When the current blocked state began; absent on legacy records, so age stays unknown. */
|
|
93
|
+
blockedAt?: number;
|
|
94
|
+
/** Linked browser decision for a user-decision blocker; shared questions are reconciled together. */
|
|
95
|
+
decisionQuestionId?: string;
|
|
30
96
|
completionPercent?: number | null;
|
|
31
97
|
/** Accumulated measured time; missing/null means historical time is unknown. */
|
|
32
98
|
elapsedMs?: number | null;
|