@maxiaochao/pi-toolkit 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +1 -1
  3. package/package.json +2 -2
  4. package/packages/herdr-subagents/CHANGELOG.md +15 -0
  5. package/packages/herdr-subagents/README.md +9 -6
  6. package/packages/herdr-subagents/TESTING.md +6 -4
  7. package/packages/herdr-subagents/docs/demo.webm +0 -0
  8. package/packages/herdr-subagents/docs/screenshot.png +0 -0
  9. package/packages/herdr-subagents/extensions/herdr-subagents.ts +40 -6
  10. package/packages/herdr-subagents/package.json +1 -1
  11. package/packages/herdr-subagents/src/batch-runner.ts +7 -7
  12. package/packages/herdr-subagents/src/blocking.ts +4 -4
  13. package/packages/herdr-subagents/src/dispatcher.ts +8 -0
  14. package/packages/herdr-subagents/src/fleet-controller.ts +167 -16
  15. package/packages/herdr-subagents/src/fleet.ts +119 -8
  16. package/packages/herdr-subagents/src/history.ts +11 -5
  17. package/packages/herdr-subagents/src/parameters.ts +2 -2
  18. package/packages/herdr-subagents/src/reconcile.ts +2 -1
  19. package/packages/herdr-subagents/src/records.ts +53 -1
  20. package/packages/herdr-subagents/src/tab-cleanup.ts +18 -2
  21. package/packages/herdr-subagents/src/tool.ts +30 -3
  22. package/packages/herdr-subagents/src/validation.ts +2 -1
  23. package/packages/herdr-subagents/tests/extension-contract.ts +16 -2
  24. package/packages/herdr-subagents/tests/run-tests.mjs +169 -8
  25. package/packages/todo/CHANGELOG.md +4 -0
  26. package/packages/todo/README.md +19 -9
  27. package/packages/todo/TESTING.md +9 -7
  28. package/packages/todo/docs/demo.gif +0 -0
  29. package/packages/todo/docs/screenshot.png +0 -0
  30. package/packages/todo/extensions/todo.ts +120 -90
  31. package/packages/todo/package.json +2 -2
  32. package/packages/todo/src/todo-state.ts +48 -49
  33. package/packages/todo/tests/todo-extension.mjs +134 -0
  34. package/packages/todo/tests/todo-state.mjs +80 -70
@@ -2,6 +2,7 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSyn
2
2
  import { join } from "node:path";
3
3
  import { tmpdir } from "node:os";
4
4
  import { getEventListeners } from "node:events";
5
+ import { visibleWidth } from "@earendil-works/pi-tui";
5
6
  import { discoverPackageAgents, parseAgentMarkdown } from "../src/personas.ts";
6
7
  import { loadSubagentConfiguration } from "../src/config.ts";
7
8
  import { runHerdrSubagents } from "../src/runner.ts";
@@ -14,10 +15,11 @@ import { cancelQueuedRuns, loadQueuedRuns, persistQueuedRun } from "../src/queue
14
15
  import { cancelActiveSubagentRuns, reconcileSubagentRuns } from "../src/reconcile.ts";
15
16
  import { continueQueuedRun } from "../src/continue-run.ts";
16
17
  import { CliHerdrAutomation } from "../src/herdr.ts";
17
- import { fleetEditorHasFocus, FleetSelection, fleetLines } from "../src/fleet.ts";
18
+ import { aggregateSessionTokens, fleetEditorHasFocus, FleetSelection, fleetLines, formatFleetDuration, formatFleetTokens } from "../src/fleet.ts";
19
+ import { FleetController, FleetWidget } from "../src/fleet-controller.ts";
18
20
  import { HERDR_ACTIONS, validateControlParams, validateRunParams } from "../src/validation.ts";
19
21
  import { resultPathForAttempt } from "../src/result-path.ts";
20
- import { isSettledRunStatus, readTaskRecord } from "../src/records.ts";
22
+ import { applyTaskStatus, isSettledRunStatus, projectTaskActivity, readTaskRecord } from "../src/records.ts";
21
23
  import { RunPaneAllocator } from "../src/run-pane-allocator.ts";
22
24
  import { aggregateTaskStatus } from "../src/run-status.ts";
23
25
  import { isAbortError } from "../src/errors.ts";
@@ -138,17 +140,20 @@ function latestRunDirectory() {
138
140
  try {
139
141
  check("run validation accepts one or more tasks", validateRunParams({ tasks: [{ name: "one", prompt: "do it" }], concurrency: 2, background: true }) === undefined);
140
142
  check("control validation accepts supported calls", [
141
- { action: "list" }, { action: "history" }, { action: "cleanup", runId: "run" },
143
+ { action: "list" }, { action: "history" }, { action: "cancel", runId: "run" }, { action: "cleanup", runId: "run" },
142
144
  { action: "respond", runId: "run", answer: "yes", task: 1 },
143
145
  { action: "resume", runId: "run", task: 1, prompt: "continue" },
144
146
  ].every((params) => validateControlParams(params) === undefined));
145
- check("all supported actions have shared validation and rendering metadata", ["list", "history", "cleanup", "respond", "resume"].every((action) => action in HERDR_ACTIONS));
147
+ check("all supported actions have shared validation and rendering metadata", ["list", "history", "cancel", "cleanup", "respond", "resume"].every((action) => action in HERDR_ACTIONS));
146
148
  check("split validation rejects missing tasks and invalid control fields", [
147
149
  validateRunParams({ tasks: [] }),
148
150
  validateControlParams({ action: "list", prompt: "not allowed" }),
149
151
  validateControlParams({ action: "respond", runId: "run" }),
150
152
  validateControlParams({ action: "resume", runId: "run", task: 1 }),
151
153
  ].every((message) => typeof message === "string" && message.length > 0));
154
+ let cancelledRunId;
155
+ const cancelControl = await executeHerdrSubagents({ action: "cancel", runId: "active-run" }, undefined, undefined, { cwd: root }, { agentsDirectory: join(process.cwd(), "agents"), cancelRun: async (runId) => { cancelledRunId = runId; return { cancelled: true }; } });
156
+ check("cancel control targets the selected active or queued run", !cancelControl.isError && cancelledRunId === "active-run" && cancelControl.details.cancelled === true);
152
157
  const fleet = new FleetSelection();
153
158
  const fleetBatch = { label: "reviews", activity: [
154
159
  { index: 0, name: "one", status: "completed", paneId: "p1" },
@@ -160,7 +165,143 @@ try {
160
165
  check("Fleet Escape exits selection", fleet.handle("\u001b[B", "", 2).consume && fleet.handle("\u001b", "", 2).consume && !fleet.isSelecting());
161
166
  const enhancedFleet = new FleetSelection((data, key) => data === `enhanced-${key}`);
162
167
  check("Fleet delegates enhanced keyboard decoding to Pi key matching", enhancedFleet.handle("enhanced-down", "", 2).consume && enhancedFleet.handle("enhanced-up", "", 2).consume && enhancedFleet.handle("enhanced-enter", "", 2).focusTask === 2);
168
+ const shrinkingFleet = new FleetSelection();
169
+ shrinkingFleet.handle("\u001b[B", "", 3);
170
+ shrinkingFleet.handle("\u001b[A", "", 3);
171
+ check("Fleet Enter focuses the row displayed after activity shrinks", shrinkingFleet.selectedIndex(2) === 1 && shrinkingFleet.handle("\r", "", 2).focusTask === 2);
163
172
  check("Fleet ignores unknown focus, dialogs, and overlays", fleetEditorHasFocus(undefined, () => false) === false && fleetEditorHasFocus({ kind: "dialog" }, () => false) === false && fleetEditorHasFocus({ kind: "editor" }, () => true) === true);
173
+ const usage = (input, output, cacheRead, cacheWrite) => ({ input, output, cacheRead, cacheWrite, totalTokens: input + output + cacheRead + cacheWrite, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } });
174
+ const usageJsonl = [
175
+ { type: "message", message: { role: "assistant", usage: usage(1, 2, 3, 4) } },
176
+ { type: "usage", usage: usage(5, 6, 7, 8) },
177
+ { type: "message", message: { role: "toolResult", usage: usage(9, 10, 11, 12) } },
178
+ { type: "compaction", usage: usage(1, 1, 1, 1) },
179
+ { type: "branch_summary", usage: usage(2, 2, 2, 2) },
180
+ { type: "message", message: { role: "user", usage: usage(99, 99, 99, 99) } },
181
+ ].map(JSON.stringify).join("\n");
182
+ check("Fleet aggregates every authoritative Pi usage-bearing entry", aggregateSessionTokens(usageJsonl) === 90);
183
+ check("Fleet ignores malformed and truncated JSONL while preserving valid usage", aggregateSessionTokens(`${usageJsonl.split("\n")[0]}\nnot-json\n{\"type\":\"message\",\"message\":`) === 10);
184
+ const elapsedStart = "2026-10-08T07:00:00.000Z";
185
+ check("Fleet elapsed formatting is live and blocked duration freezes", formatFleetDuration({ index: 0, name: "live", agent: "explorer", status: "running", startedAt: elapsedStart }, Date.parse(elapsedStart) + 65_000) === "1m 5s" && formatFleetDuration({ index: 0, name: "blocked", agent: "explorer", status: "blocked", startedAt: elapsedStart, updatedAt: "2026-10-08T07:00:05.000Z" }, Date.parse(elapsedStart) + 99_000) === "5s");
186
+ const timedTask = { id: "timed", runId: "run", order: 1, name: "timed", agent: "worker", status: "queued" };
187
+ applyTaskStatus(timedTask, "running", { at: elapsedStart });
188
+ applyTaskStatus(timedTask, "blocked", { at: "2026-10-08T07:00:05.000Z" });
189
+ applyTaskStatus(timedTask, "running", { at: "2026-10-08T07:01:00.000Z" });
190
+ check("Fleet duration accumulates active work without counting blocked wait", formatFleetDuration(projectTaskActivity(timedTask), Date.parse("2026-10-08T07:01:07.000Z")) === "12s");
191
+ const legacyTimedTask = { id: "legacy", runId: "run", order: 1, name: "legacy", agent: "worker", status: "blocked", startedAt: elapsedStart, updatedAt: "2026-10-08T07:00:05.000Z" };
192
+ applyTaskStatus(legacyTimedTask, "running", { at: "2026-10-08T07:01:00.000Z" });
193
+ check("Fleet timing migrates legacy blocked records without losing prior work", formatFleetDuration(projectTaskActivity(legacyTimedTask), Date.parse("2026-10-08T07:01:07.000Z")) === "12s");
194
+ const recoveredTimedTask = { id: "recovered", runId: "run", order: 1, name: "recovered", agent: "worker", status: "running", startedAt: elapsedStart };
195
+ applyTaskStatus(recoveredTimedTask, "cancelled", { at: "2026-10-08T07:00:09.000Z" });
196
+ check("Fleet timing settles legacy recovered-running records", formatFleetDuration(projectTaskActivity(recoveredTimedTask), Date.parse("2026-10-08T08:00:00.000Z")) === "9s");
197
+ check("Fleet formats true token totals without estimates", formatFleetTokens(999) === "999 tok" && formatFleetTokens(1_250) === "1.3k tok" && formatFleetTokens(12_400) === "12k tok");
198
+ const metricFleet = new FleetSelection();
199
+ const metricBatch = { label: "audit", activity: [
200
+ { index: 0, name: "inspect auth", agent: "explorer", status: "running", startedAt: elapsedStart, sessionFile: "/tmp/live.jsonl" },
201
+ { index: 1, name: "review patch", agent: "reviewer", status: "queued", sessionFile: "/tmp/queued.jsonl" },
202
+ ] };
203
+ const metricLines = fleetLines(metricBatch, metricFleet, { width: 80, now: Date.parse(elapsedStart) + 65_000, metrics: new Map([[0, { tokens: 1_250 }], [1, { tokens: 999 }]]) });
204
+ check("Fleet rows show persona task status elapsed and right-aligned true usage", metricLines[1].includes("explorer") && metricLines[1].includes("inspect auth") && metricLines[1].includes("running") && metricLines[1].endsWith("1m 5s 1.3k tok"));
205
+ const compactLines = fleetLines({ label: "compact", activity: [
206
+ { index: 0, name: "API", agent: "explorer", status: "running", startedAt: elapsedStart },
207
+ { index: 1, name: "Recovery", agent: "explorer", status: "completed", startedAt: elapsedStart, completedAt: "2026-10-08T07:00:09.000Z" },
208
+ ] }, new FleetSelection(), { width: 160, now: Date.parse(elapsedStart) + 21_000, metrics: new Map([[0, { tokens: 4_800 }], [1, { tokens: 900 }]]) });
209
+ check("wide Fleet rows align metrics without terminal-width whitespace", visibleWidth(compactLines[1]) < 80 && compactLines[1].indexOf("tok") === compactLines[2].indexOf("tok"));
210
+ const semanticColors = [];
211
+ fleetLines({ label: "colors", activity: [
212
+ { index: 0, name: "doing", agent: "worker", status: "running" },
213
+ { index: 1, name: "done", agent: "worker", status: "completed" },
214
+ ] }, new FleetSelection(), { theme: { fg: (color, text) => { semanticColors.push([color, text]); return text; }, bold: (text) => text } });
215
+ check("Fleet uses warning yellow for running work and success green for completed work", semanticColors.some(([color, text]) => color === "warning" && text === "●") && semanticColors.some(([color, text]) => color === "success" && text === "●"));
216
+ check("queued Fleet rows fabricate neither duration nor usage", metricLines[2].includes("reviewer") && metricLines[2].includes("queued") && !metricLines[2].includes("tok") && !metricLines[2].match(/\d+[smh]/));
217
+ check("Fleet rendering fits narrow terminal widths", [1, 8, 16, 24].every((width) => fleetLines(metricBatch, metricFleet, { width, metrics: new Map([[0, { tokens: 1_250 }]]) }).every((line) => visibleWidth(line) <= width)));
218
+ let liveTokens = 42;
219
+ let nextRuntimeId = 1;
220
+ const runtimeIntervals = new Map();
221
+ const runtimeTimeouts = new Map();
222
+ const runtimeWatchers = [];
223
+ let clearedIntervals = 0;
224
+ const fleetRuntime = {
225
+ watchSession(path, onChange, onError) { const entry = { path, onChange, onError, closed: false }; runtimeWatchers.push(entry); return { close() { entry.closed = true; } }; },
226
+ setInterval(callback) { const id = nextRuntimeId++; runtimeIntervals.set(id, callback); return id; },
227
+ clearInterval(id) { if (runtimeIntervals.delete(id)) clearedIntervals += 1; },
228
+ setTimeout(callback) { const id = nextRuntimeId++; runtimeTimeouts.set(id, callback); return id; },
229
+ clearTimeout(id) { runtimeTimeouts.delete(id); },
230
+ async readTokens() { return liveTokens; },
231
+ };
232
+ let requestedFleetRenders = 0;
233
+ const liveWidgetBatch = { runId: "live", label: "live", status: "running", activity: [{ index: 0, name: "inspect", agent: "explorer", status: "running", startedAt: elapsedStart, activeStartedAt: elapsedStart, sessionFile: "/tmp/fleet-live/session.jsonl", paneId: "p1" }], prompts: [], tasks: [], documents: [], summary: "", ok: false, requestedConcurrency: 1, effectiveConcurrency: 1, recordDirectory: "/tmp/fleet-live" };
234
+ const liveWidget = new FleetWidget({ requestRender() { requestedFleetRenders += 1; } }, { fg: (_color, text) => text, bold: (text) => text }, liveWidgetBatch, new FleetSelection(), fleetRuntime);
235
+ for (const callback of [...runtimeTimeouts.values()]) callback();
236
+ runtimeTimeouts.clear();
237
+ await new Promise((resolve) => setTimeout(resolve, 0));
238
+ check("Fleet widget reads usage on demand and uses one running repaint timer", liveWidget.render(80)[1].includes("42 tok") && runtimeWatchers.length === 1 && runtimeIntervals.size === 1 && requestedFleetRenders > 0);
239
+ liveTokens = 84;
240
+ runtimeWatchers[0].onChange();
241
+ for (const callback of [...runtimeTimeouts.values()]) callback();
242
+ runtimeTimeouts.clear();
243
+ await new Promise((resolve) => setTimeout(resolve, 0));
244
+ check("Fleet widget refreshes token usage from file events", liveWidget.render(80)[1].includes("84 tok"));
245
+ liveTokens = 126;
246
+ for (const callback of [...runtimeIntervals.values()]) callback();
247
+ for (const callback of [...runtimeTimeouts.values()]) callback();
248
+ runtimeTimeouts.clear();
249
+ await new Promise((resolve) => setTimeout(resolve, 0));
250
+ check("Fleet widget refreshes token usage on every running one-second tick", liveWidget.render(80)[1].includes("126 tok"));
251
+ liveWidget.update({ ...liveWidgetBatch, status: "blocked", activity: [{ ...liveWidgetBatch.activity[0], status: "blocked", updatedAt: "2026-10-08T07:00:05.000Z", activeStartedAt: undefined, elapsedMs: 5_000 }] });
252
+ check("Fleet widget stops elapsed repainting when work blocks", runtimeIntervals.size === 0 && clearedIntervals === 1);
253
+ liveWidget.dispose();
254
+ const watcherClosed = runtimeWatchers.every((watcher) => watcher.closed);
255
+ liveWidget.update(liveWidgetBatch);
256
+ check("Fleet widget disposal closes watchers and prevents timer restart", watcherClosed && runtimeIntervals.size === 0 && runtimeTimeouts.size === 0);
257
+ const makeFleetUi = () => {
258
+ let component;
259
+ let factoryInstalls = 0;
260
+ return {
261
+ ui: {
262
+ setWidget(_key, content) { component?.dispose?.(); component = undefined; if (typeof content === "function") { factoryInstalls += 1; component = content({ requestRender() {}, focusedComponent: undefined }, { fg: (_color, text) => text, bold: (text) => text }); } },
263
+ onTerminalInput() { return () => {}; },
264
+ getEditorText() { return ""; },
265
+ },
266
+ get component() { return component; },
267
+ get factoryInstalls() { return factoryInstalls; },
268
+ };
269
+ };
270
+ const firstFleetUi = makeFleetUi();
271
+ const secondFleetUi = makeFleetUi();
272
+ const fleetController = new FleetController({}, () => false, undefined, fleetRuntime);
273
+ fleetController.bind(firstFleetUi.ui, true);
274
+ fleetController.setActive(liveWidgetBatch);
275
+ const firstUiWidget = firstFleetUi.component;
276
+ fleetController.bind(secondFleetUi.ui, true);
277
+ fleetController.sync(liveWidgetBatch);
278
+ check("Fleet UI rebinding replaces the disposed widget in the new context", firstUiWidget !== secondFleetUi.component && secondFleetUi.factoryInstalls === 1);
279
+ fleetController.sync({ ...liveWidgetBatch, runId: "foreign", label: "foreign" });
280
+ check("foreign run updates do not replace the active Fleet owner", fleetController.active?.runId === "live" && secondFleetUi.factoryInstalls === 1);
281
+ const installsBeforeShutdown = secondFleetUi.factoryInstalls;
282
+ fleetController.shutdown();
283
+ fleetController.sync(liveWidgetBatch);
284
+ check("late updates after shutdown cannot recreate Fleet resources", secondFleetUi.factoryInstalls === installsBeforeShutdown && runtimeIntervals.size === 0 && !fleetController.active);
285
+ let resolveStaleTokens;
286
+ const staleTimeouts = new Map();
287
+ const staleWatchers = [];
288
+ let staleId = 1;
289
+ const staleRuntime = {
290
+ watchSession(path, onChange) { const watcher = { path, onChange, closed: false }; staleWatchers.push(watcher); return { close() { watcher.closed = true; } }; },
291
+ setInterval() { return staleId++; },
292
+ clearInterval() {},
293
+ setTimeout(callback) { const id = staleId++; staleTimeouts.set(id, callback); return id; },
294
+ clearTimeout(id) { staleTimeouts.delete(id); },
295
+ readTokens() { return new Promise((resolve) => { resolveStaleTokens = resolve; }); },
296
+ };
297
+ const staleWidget = new FleetWidget({ requestRender() {} }, { fg: (_color, text) => text, bold: (text) => text }, liveWidgetBatch, new FleetSelection(), staleRuntime);
298
+ for (const callback of [...staleTimeouts.values()]) callback();
299
+ staleTimeouts.clear();
300
+ staleWidget.update({ ...liveWidgetBatch, runId: "replacement", activity: [{ ...liveWidgetBatch.activity[0], sessionFile: "/tmp/fleet-replacement/session.jsonl" }] });
301
+ resolveStaleTokens(999);
302
+ await new Promise((resolve) => setTimeout(resolve, 0));
303
+ check("Fleet ignores stale token reads after session sources change", !staleWidget.render(80)[1].includes("999 tok"));
304
+ staleWidget.dispose();
164
305
  let unknownStatusRejected = false;
165
306
  try { aggregateTaskStatus(["unknown"]); } catch { unknownStatusRejected = true; }
166
307
  check("task status aggregation rejects unknown states", unknownStatusRejected);
@@ -188,6 +329,7 @@ try {
188
329
  const createRequest = herdr.calls.find(([name]) => name === "createTab")[1];
189
330
  const startRequest = herdr.calls.find(([name]) => name === "startAgent")[1];
190
331
  check("named unfocused tab in parent workspace", createRequest.workspaceId === "w1" && createRequest.cwd === root && createRequest.label === "SA · auth-review" && createRequest.focus === false);
332
+ check("ordinary execution never steals pane focus", !herdr.calls.some(([name]) => name === "focusPane"));
191
333
  check("child environment points at durable task", createRequest.env.PI_HERDR_SUBAGENTS_CHILD === "1" && createRequest.env.PI_HERDR_SUBAGENTS_TASK_DIR.includes(join(".pi", "herdr-subagents", "runs")));
192
334
  check("persistent isolated child Pi", startRequest.kind === "pi" && startRequest.paneId === "w1:p2" && startRequest.args.includes("--session") && startRequest.args.includes("--no-extensions") && startRequest.args.includes("--extension") && startRequest.args.includes("--no-skills") && startRequest.args.includes("--model") && startRequest.args.includes("fake/model") && startRequest.args.includes("--tools") && startRequest.args.includes("read,grep,subagent_report"));
193
335
  const promptRequest = herdr.calls.find(([name]) => name === "promptAgent")[1];
@@ -297,18 +439,25 @@ try {
297
439
  check("batch is FIFO with a dedicated pane per task", batchPrompts.join(",") === "one slow,two,three FAIL,four" && new Set(batchStarts.map((request) => request.paneId)).size === 4);
298
440
  check("failed sibling does not cancel batch", batch.isError && batchDetails.status === "partial" && batchDetails.tasks.map((task) => task.name).join(",") === "one,two,three,four" && batchDetails.tasks[2].status === "failed" && batchDetails.tasks[3].status === "completed");
299
441
  const batchCleanupHerdr = fakeHerdr("close-failed");
300
- const batchCleanup = await executeHerdrSubagents({ tasks: [{ name: "cleanup", prompt: "cleanup", agent: "explorer" }] }, undefined, undefined, { cwd: root, model: { provider: "fake", id: "model" } }, { agentsDirectory: join(process.cwd(), "agents"), herdr: batchCleanupHerdr });
442
+ const batchCleanupUpdates = [];
443
+ const batchCleanup = await executeHerdrSubagents({ tasks: [{ name: "cleanup", prompt: "cleanup", agent: "explorer" }] }, undefined, (update) => batchCleanupUpdates.push(update), { cwd: root, model: { provider: "fake", id: "model" } }, { agentsDirectory: join(process.cwd(), "agents"), herdr: batchCleanupHerdr });
301
444
  const batchCleanupRecord = JSON.parse(readFileSync(join(batchCleanup.details.recordDirectory, "run.json"), "utf8"));
302
- check("batch cleanup failure is persisted and surfaced", batchCleanup.isError && batchCleanup.content[0].text.includes("cleanup failed") && batchCleanupRecord.status === "failed" && batchCleanupRecord.cleanupError.includes("tab still busy"));
445
+ check("batch cleanup failure is persisted and surfaced once", batchCleanup.isError && batchCleanup.content[0].text.includes("cleanup failed") && batchCleanupRecord.status === "failed" && batchCleanupRecord.cleanupError.includes("tab still busy") && batchCleanupUpdates.filter((update) => update.content[0]?.text.includes("cleanup failed")).length === 1);
303
446
  const cleanupProbeHerdr = fakeHerdr();
304
447
  cleanupProbeHerdr.isTabFocused = async () => { throw new Error("tab lookup failed"); };
305
448
  const cleanupProbe = await executeHerdrSubagents({ tasks: [{ name: "cleanup-probe", prompt: "cleanup probe", agent: "explorer" }] }, undefined, undefined, { cwd: root, model: { provider: "fake", id: "model" } }, { agentsDirectory: join(process.cwd(), "agents"), herdr: cleanupProbeHerdr });
306
449
  const cleanupProbeRecord = JSON.parse(readFileSync(join(cleanupProbe.details.recordDirectory, "run.json"), "utf8"));
307
450
  check("cleanup focus-probe failure is persisted and surfaced", cleanupProbe.isError && cleanupProbe.content[0].text.includes("tab lookup failed") && cleanupProbeRecord.status === "failed" && cleanupProbeRecord.cleanupError === "tab lookup failed");
451
+ const missingTabHerdr = fakeHerdr();
452
+ missingTabHerdr.isTabFocused = async () => { throw new Error('{"error":{"code":"tab_not_found","message":"tab w1:t2 not found"}}'); };
453
+ const missingTabCleanup = await executeHerdrSubagents({ tasks: [{ name: "already-closed", prompt: "already closed", agent: "explorer" }] }, undefined, undefined, { cwd: root, model: { provider: "fake", id: "model" } }, { agentsDirectory: join(process.cwd(), "agents"), herdr: missingTabHerdr });
454
+ const missingTabRecord = JSON.parse(readFileSync(join(missingTabCleanup.details.recordDirectory, "run.json"), "utf8"));
455
+ check("already-missing tab is successful idempotent cleanup", !missingTabCleanup.isError && missingTabRecord.status === "completed" && !missingTabRecord.cleanupPendingTabIds && !missingTabRecord.cleanupError);
308
456
  const activeUpdate = batchUpdates.find((update) => update.activity?.some((task) => task.status === "running"));
309
457
  const counts = activityCounts(activeUpdate);
310
458
  const focusHerdr = fakeHerdr();
311
459
  const runningTask = activeUpdate.activity.find((task) => task.status === "running");
460
+ check("activity projections expose true persona task timing and session sources", runningTask.agent === "explorer" && runningTask.name === "one" && runningTask.prompt === "one slow" && typeof runningTask.startedAt === "string" && runningTask.sessionFile.endsWith("session.jsonl"));
312
461
  const focused = await focusActiveTask(activeUpdate, runningTask.index + 1, focusHerdr);
313
462
  check("active progress exposes widget counts and exact pane navigation", counts.running > 0 && counts.queued > 0 && focused && focusHerdr.calls.at(-1)[0] === "focusPane" && focusHerdr.calls.at(-1)[1].paneId === runningTask.paneId);
314
463
  const settledFocused = await focusActiveTask({ activity: [{ index: 0, name: "settled", status: "completed", paneId: "w1:p-settled" }] }, 1, focusHerdr);
@@ -417,6 +566,13 @@ try {
417
566
  check("dispatcher starts next queued run automatically", starts.join(",") === "run-one,run-two" && dispatcher.snapshot().activeRunId === "run-two");
418
567
  releaseSecond();
419
568
  check("dispatcher settles queued run", await second === "two");
569
+ const cancellingDispatcher = new RunDispatcher();
570
+ cancellingDispatcher.pause();
571
+ const removedQueued = cancellingDispatcher.submit("remove-me", async () => "unexpected").catch((error) => error.message);
572
+ const keptQueued = cancellingDispatcher.submit("keep-me", async () => "kept");
573
+ check("dispatcher cancels only the selected queued run", cancellingDispatcher.cancelQueuedRun("remove-me", new Error("cancelled by user")) && await removedQueued === "cancelled by user" && cancellingDispatcher.snapshot().queuedRunIds.join(",") === "keep-me");
574
+ cancellingDispatcher.resume();
575
+ check("dispatcher still executes uncancelled queued siblings", await keptQueued === "kept");
420
576
  const retainedDispatcher = new RunDispatcher();
421
577
  const retainedStarts = [];
422
578
  const retainedFirst = retainedDispatcher.submit("blocked-run", async () => { retainedStarts.push("blocked-run"); retainedDispatcher.retain("blocked-run"); return "blocked"; });
@@ -548,9 +704,11 @@ try {
548
704
  const stableHistory = history.find((run) => run.id === backgroundId);
549
705
  check("history lists compact project-local runs and tasks", Boolean(stableHistory?.tasks.length) && historyText(history).includes("stable") && !historyText(history).includes("FULL stable"));
550
706
  const historyHerdr = fakeHerdr();
551
- const historicalResume = await executeHerdrSubagents({ action: "resume", runId: backgroundId, task: 1, prompt: "follow up" }, undefined, undefined, { cwd: root, model: { provider: "fake", id: "model" } }, { agentsDirectory: join(process.cwd(), "agents"), herdr: historyHerdr });
707
+ const historicalUpdates = [];
708
+ const historicalResume = await executeHerdrSubagents({ action: "resume", runId: backgroundId, task: 1, prompt: "follow up" }, undefined, (update) => historicalUpdates.push(update.details), { cwd: root, model: { provider: "fake", id: "model" } }, { agentsDirectory: join(process.cwd(), "agents"), herdr: historyHerdr });
552
709
  const historyStartRequest = historyHerdr.calls.find(([name]) => name === "startAgent")[1];
553
710
  check("historical resume preserves the saved Pi session and persona prompt", !historicalResume.isError && historyHerdr.calls[0][0] === "createTab" && historyStartRequest.args.includes(stableHistory.tasks[0].sessionFile) && historyStartRequest.args.includes(stableHistory.tasks[0].model) && historyStartRequest.args.some((value) => String(value).includes("subagent_report")) && existsSync(join(stableHistory.tasks[0].recordDirectory, "turns", "02.json")) && readFileSync(join(stableHistory.tasks[0].recordDirectory, "followup-system-prompt.md"), "utf8").includes("Investigate the assigned question without modifying files"));
711
+ check("historical resume streams authoritative Fleet activity", historicalUpdates.some((update) => update.status === "running" && update.activity?.[0]?.agent === "explorer" && update.activity[0].sessionFile === stableHistory.tasks[0].sessionFile));
554
712
  const historicalTaskRecord = JSON.parse(readFileSync(join(stableHistory.tasks[0].recordDirectory, "task.json"), "utf8"));
555
713
  const historicalTurnRecord = JSON.parse(readFileSync(join(stableHistory.tasks[0].recordDirectory, "turns", "02.json"), "utf8"));
556
714
  check("historical task and turn retain their tab identity", historicalTaskRecord.tabId === historicalResume.details.tabId && historicalTurnRecord.tabId === historicalResume.details.tabId);
@@ -618,9 +776,11 @@ try {
618
776
  check("historical pre-prompt failure replaces stale state and report", prePromptFailure.isError && prePromptFailedTask.status === "failed" && !("question" in prePromptFailedTask) && prePromptFailedTask.error.includes("historical startup failed") && prePromptFailedTask.completedAt !== "2000-01-01T00:00:00.000Z" && prePromptFailureReport.status === "failed" && prePromptFailureReport.error.includes("historical startup failed"));
619
777
  check("historical resume releases the run lock after failure", !existsSync(join(stableHistory.recordDirectory, ".resume.lock")));
620
778
  const postPromptFailureHerdr = fakeHerdr("post-fail");
621
- const postPromptFailure = await executeHerdrSubagents({ action: "resume", runId: backgroundId, task: 1, prompt: "fails after submit" }, undefined, undefined, { cwd: root }, { agentsDirectory: join(process.cwd(), "agents"), herdr: postPromptFailureHerdr });
779
+ const postPromptFailureUpdates = [];
780
+ const postPromptFailure = await executeHerdrSubagents({ action: "resume", runId: backgroundId, task: 1, prompt: "fails after submit" }, undefined, (update) => postPromptFailureUpdates.push(update.details), { cwd: root }, { agentsDirectory: join(process.cwd(), "agents"), herdr: postPromptFailureHerdr });
622
781
  const postPromptFailureReport = JSON.parse(readFileSync(join(stableHistory.tasks[0].recordDirectory, "report.json"), "utf8"));
623
782
  check("historical post-prompt failure persists its authoritative report", postPromptFailure.isError && postPromptFailureReport.status === "failed" && postPromptFailureReport.error.includes("connection lost after prompt submission"));
783
+ check("historical resume failure emits terminal Fleet activity", postPromptFailureUpdates.some((update) => update.status === "running") && postPromptFailureUpdates.at(-1).status === "failed" && postPromptFailureUpdates.at(-1).activity.every((task) => task.status !== "running"));
624
784
  const shutdownBlockedHerdr = fakeHerdr("blocked");
625
785
  const shutdownBlocked = await executeHerdrSubagents({ tasks: [{ name: "blocked-at-shutdown", prompt: "need input", agent: "explorer" }] }, undefined, undefined, { cwd: root }, { agentsDirectory: join(process.cwd(), "agents"), herdr: shutdownBlockedHerdr });
626
786
  await cancelActiveSubagentRuns(root, shutdownBlockedHerdr);
@@ -674,6 +834,7 @@ try {
674
834
  const authoritativeReport = JSON.parse(readFileSync(join(authoritativeTaskDirectory, "report.json"), "utf8"));
675
835
  check("valid persisted report remains authoritative after Herdr prompt transport failure", !authoritativeAfterPromptFailure.isError && authoritativeTask.status === "completed" && authoritativeReport.status === "completed" && authoritativeAfterPromptFailure.details.tasks[0].summary === authoritativeReport.summary);
676
836
  check("production batch path never passes print mode", batchStarts.every((request) => !request.args.includes("--print")));
837
+ check("production batch path never steals pane focus", !batchHerdr.calls.some(([name]) => name === "focusPane"));
677
838
 
678
839
  const atomicFile = join(root, "atomic.json");
679
840
  await Promise.all(Array.from({ length: 12 }, (_, index) => writeJsonAtomic(atomicFile, { index, payload: "x".repeat(1000) })));
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ - replace generic Todo CRUD with serialized execution-plan lifecycle commands, guarded single-step advancement, preserved replan history, canonical current-plan results, branch reconstruction tests, and a live rerendering current-plan widget
6
+
3
7
  ## 2026-09-30 - v0.1.0
4
8
 
5
9
  - 从 `@maxiaochao/pi-toolkit` 提取 todo 权威源码,支持主包捆绑和独立安装。
@@ -1,24 +1,24 @@
1
1
  # @maxiaochao/pi-todo
2
2
 
3
- Pi 的会话清单扩展,提供 `todo` 工具、自动推进的生命周期、活跃任务 widget 和 `/todos` 历史视图。
3
+ Pi 的分支本地执行计划扩展,提供 `todo` 生命周期工具、只显示当前计划的 widget 和 `/todos` 完整历史视图。
4
4
 
5
5
  ![Todo 真实状态机运行截图](docs/screenshot.png)
6
6
 
7
7
  ## 为什么有这个包
8
8
 
9
- 这是 pi-toolkit 自研的计划执行模块,用明确状态替代只存在于对话文本里的计划。它解决计划替换后旧任务残留、多个任务同时 doing、完成后不自动推进,以及 UI 序号与持久 ID 混用的问题。
9
+ 这是 pi-toolkit 自研的计划执行模块,用明确状态替代只存在于对话文本里的计划。Todo 是用户可见的后续工作顺序,不是隐藏推理、完成报告或通用任务管理器。它解决改向后历史丢失、并发调用误完成、多个步骤同时 doing、完成后不推进,以及 UI 序号与持久 ID 混用的问题。
10
10
 
11
11
  ## 演示
12
12
 
13
13
  ![Todo 生命周期演示](docs/demo.gif)
14
14
 
15
15
  ```text
16
- todo({ action: "replace", items: ["Inspect callers", "Implement", "Verify"] })
17
- todo({ action: "update", id: 1, status: "done" })
16
+ todo({ action: "plan", items: ["Inspect callers", "Implement", "Verify"] })
17
+ todo({ action: "complete_current", expected_current_id: 1 })
18
18
  /todos
19
19
  ```
20
20
 
21
- 第一项完成后下一项自动进入 `doing`;`/todos` 同时展示活跃队列和关闭历史。
21
+ 第一项实际完成后,下一项自动进入 `doing`。工具结果和 widget 只展示 `CURRENT plan`;`/todos` 展示当前分支的全部完成、取消和未完成历史。
22
22
 
23
23
  ## 安装
24
24
 
@@ -47,10 +47,20 @@ pi update npm:@maxiaochao/pi-todo # 更新独立子包
47
47
 
48
48
  ## 行为
49
49
 
50
- - `replace` 用新计划替换旧计划,并将未完成旧任务标记为取消。
51
- - `add`、`update`、`remove`、`clear` 管理任务。
52
- - 同一时间最多一个任务为 `doing`,完成后自动推进下一项。
53
- - widget 使用连续队列位置;持久记录保留稳定内部 ID。
50
+ - `plan(items)` 创建或重新规划。非空计划取消并保留全部旧 `doing`/`todo` 历史,保留已关闭历史,使用新的单调递增 ID,并启动第一步。
51
+ - `plan([])` 取消全部未完成工作,不留下当前计划;ID 不重置。
52
+ - `add_step(text)` 只追加一步。`complete_current` 和 `cancel_current` 必须携带匹配唯一 `doing` 步骤的 `expected_current_id`,否则原子失败;每次调用只推进一步。
53
+ - 调用共享可变状态并串行执行。同轮多个 sibling completion 不是支持的顺序机制。
54
+ - `list` 与每个变更都向模型返回简洁、规范的 `CURRENT plan`,包含稳定内部 ID 和状态;只有 `/todos` 显示完整历史。
55
+ - widget 从实时状态读取当前计划,使用连续显示位置、隐藏内部 ID 和关闭历史,并在计划结束时消失。
56
+
57
+ ## 使用准则
58
+
59
+ - 只为明确的多步工作、确实分阶段的工作或跨模型交接创建计划;不要为简单单步任务创建计划。
60
+ - 仅在工作实际完成后调用 `complete_current`。仍然需要但被阻塞的步骤保持当前状态。
61
+ - `cancel_current` 表示当前步骤不再需要且后续计划仍有效;方向改变时使用 `plan`。
62
+ - 保留用户给出的步骤意图和顺序,只在可执行性要求下拆分步骤。
63
+ - 协议不提供任意更新、删除、清空、撤销、批量完成或 marker 文本解析。
54
64
 
55
65
  ## 开发与测试
56
66
 
@@ -2,19 +2,21 @@
2
2
 
3
3
  ## 流程
4
4
 
5
- 1. `npm --prefix packages/todo test`:运行纯状态机确定性测试。
5
+ 1. `npm --prefix packages/todo test`:运行状态机确定性测试和扩展/widget 集成测试。
6
6
  2. `npm --prefix packages/todo run load-test`:让 Pi 加载真实扩展入口。
7
7
  3. `npm pack ./packages/todo --dry-run`:确认发布文件完整。
8
8
  4. 确认由真实状态机输出生成的 `docs/screenshot.png` 和 `docs/demo.gif` 可打开且进入 tarball。
9
9
 
10
10
  ## 用例数据
11
11
 
12
- - 恢复旧格式记录并修复非法生命周期。
13
- - `replace` 取消旧的活跃任务并建立新队列。
14
- - 完成当前任务后自动推进下一项。
15
- - 删除、清空、非法 ID 和非法状态处理。
16
- - widget 队列位置连续,内部 ID 保持稳定。
12
+ - 恢复旧格式记录、修复非法生命周期,并只从当前分支快照重建。
13
+ - 非空 `plan` 保留关闭历史、取消旧未完成步骤并使用单调新 ID;`plan([])` 留下空当前计划。
14
+ - `expected_current_id` 的 stale、重复和缺失调用原子失败;顺序完成与取消每次只推进一步。
15
+ - `add_step` 只追加,步骤文本不作为 marker 或唯一键解释。
16
+ - 并发发起的调用按提交顺序串行化,同轮重复 completion 不会跨越两个步骤。
17
+ - 已挂载 widget 从实时状态重渲染、主动请求 TUI render、隐藏内部 ID 和关闭历史,并在计划结束时消失。
18
+ - `/todos` 展示完整当前分支历史,而所有工具结果只返回规范 `CURRENT plan`。
17
19
 
18
20
  ## 最近验证结果
19
21
 
20
- 迁移基线:状态机测试全部通过,扩展可由 Pi 独立加载。发布前必须重新运行上述三步;跳过的检查不算通过。
22
+ 迁移基线:状态机和扩展集成测试全部通过,扩展可由 Pi 独立加载。发布前必须重新运行上述三步;跳过的检查不算通过。
Binary file
Binary file