@ian-pascoe/pi-todo 0.1.1 → 0.1.2

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 CHANGED
@@ -26,12 +26,18 @@ The `todo` tool supports five actions:
26
26
 
27
27
  Task status is `pending`, `active`, or `completed`; `add` defaults to `pending`. Tasks are flat, duplicate titles are allowed, and multiple Tasks may be active. Set `description` to `null` during `update` to remove it.
28
28
 
29
- The extension appends the current Todo List as hidden tail context before each model request. It does not modify the system prompt or tool description as the list changes, preserving the cacheable prompt prefix.
29
+ Each changed Todo List is projected from its immutable session state entry as a hidden full snapshot at a fixed conversation position. Mutations inside a tool group appear after all sibling results; later requests keep earlier snapshots in place. Clearing the list produces an explicit empty snapshot. The system prompt and tool description do not change.
30
+
31
+ After compaction, a fixed baseline immediately after the summary restores the state from before the retained Tail. Retained and newer mutations follow chronologically. This preserves previously written conversation cache prefixes between checkpoints; it does not guarantee provider cache hits.
30
32
 
31
33
  ## UI and persistence
32
34
 
33
35
  In interactive mode, a compact widget above the editor shows status counts and up to five Tasks. Tool calls and results use custom transcript rendering. `/todo clear` confirms before manually clearing the list.
34
36
 
35
- State is stored only in Pi session entries. It follows the active session branch and survives reloads, restarts, and compaction. The package has no settings or external state.
37
+ State is stored only in `pi-todo-state` session entries, without a second message journal. It follows the active session branch and survives reloads, restarts, and compaction. Legacy state entries use the same projection. The package has no settings or external state.
38
+
39
+ A failed journal write leaves acknowledged Todo state unchanged and disables Todo in that loaded session, including across `/reload`. Pi has an existing persistence limitation: subsequent entries can reference the unwritten entry, so reopening may omit earlier history from the selected branch even though it remains in the file. Todo does not repair session history; recovery is outside this cache-prefix change.
40
+
41
+ Missing or ambiguous conversation anchors abort the request instead of silently relocating snapshots. Extensions that rewrite those anchors are unsupported.
36
42
 
37
43
  This is privileged extension code: review it before installing it into an agent that can access local files, tools, or credentials.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ian-pascoe/pi-todo",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "private": false,
5
5
  "description": "Minimal session-native Todo List for Pi agents.",
6
6
  "keywords": [
@@ -2,15 +2,12 @@ import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import type { ExtensionAPI, ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
3
3
  import { type Component, Text, truncateToWidth } from "@earendil-works/pi-tui";
4
4
  import { Type } from "typebox";
5
- import { Value } from "typebox/value";
5
+ import { projectTodoContext, todoStateFromEntry } from "./todo-context.js";
6
6
  import {
7
7
  applyTodoAction,
8
8
  createEmptyTodoState,
9
- formatTodoList,
10
- parseTodoStateSnapshot,
11
9
  TODO_ACTIONS,
12
10
  TODO_STATUSES,
13
- TodoStateRecord,
14
11
  todoStatusMarker,
15
12
  type TodoActionInput,
16
13
  type TodoStateSnapshot,
@@ -20,6 +17,17 @@ import {
20
17
  } from "./todo-list.js";
21
18
 
22
19
  const TODO_STATE_ENTRY_TYPE = "pi-todo-state";
20
+ const JOURNAL_FAULT = Symbol.for("@ian-pascoe/pi-todo/journal-fault");
21
+
22
+ function assertTodoJournalReadable(context: ExtensionContext): void {
23
+ const manager = context.sessionManager;
24
+ const marker = Object.getOwnPropertyDescriptor(manager, JOURNAL_FAULT);
25
+ if (marker !== undefined && marker.value === manager.getHeader()) {
26
+ throw new Error(
27
+ "Todo journal write failed; Todo is disabled in this loaded session, including after /reload",
28
+ );
29
+ }
30
+ }
23
31
  const TODO_WIDGET_ID = "pi-todo";
24
32
  const TODO_WIDGET_STATUS_ORDER: readonly TodoStatus[] = ["active", "pending", "completed"];
25
33
  const TODO_COLLAPSED_TASK_LIMIT = 5;
@@ -44,14 +52,7 @@ const TodoParameters = Type.Object({
44
52
 
45
53
  function restoreTodoState(context: ExtensionContext): TodoStateSnapshot {
46
54
  for (const entry of context.sessionManager.getBranch().toReversed()) {
47
- if (
48
- entry.type !== "custom" ||
49
- entry.customType !== TODO_STATE_ENTRY_TYPE ||
50
- !Value.Check(TodoStateRecord, entry.data)
51
- ) {
52
- continue;
53
- }
54
- const snapshot = parseTodoStateSnapshot(entry.data);
55
+ const snapshot = todoStateFromEntry(entry);
55
56
  if (snapshot) return snapshot;
56
57
  }
57
58
  return createEmptyTodoState();
@@ -113,32 +114,43 @@ export default function piTodoExtension(pi: ExtensionAPI): void {
113
114
  );
114
115
  };
115
116
  const commitTodoState = (snapshot: TodoStateSnapshot, context: ExtensionContext): void => {
117
+ try {
118
+ pi.appendEntry(TODO_STATE_ENTRY_TYPE, snapshot);
119
+ } catch (cause) {
120
+ // Todo-owned metadata survives /reload; no Pi-owned journal or agent fields are changed.
121
+ Object.defineProperty(context.sessionManager, JOURNAL_FAULT, {
122
+ value: context.sessionManager.getHeader(),
123
+ configurable: true,
124
+ });
125
+ context.abort();
126
+ throw cause;
127
+ }
116
128
  state = snapshot;
117
- pi.appendEntry(TODO_STATE_ENTRY_TYPE, state);
118
129
  updateTodoWidget(context);
119
130
  };
120
131
  const runTodoAction = (input: TodoActionInput, context: ExtensionContext) => {
132
+ assertTodoJournalReadable(context);
121
133
  const result = applyTodoAction(state, input);
122
134
  if (!result.ok) throw result.error;
123
135
  if (result.state !== state) commitTodoState(result.state, context);
124
136
  return result;
125
137
  };
126
138
  const restoreState = (context: ExtensionContext): void => {
139
+ assertTodoJournalReadable(context);
127
140
  state = restoreTodoState(context);
128
141
  updateTodoWidget(context);
129
142
  };
130
143
  pi.on("session_start", (_event, context) => restoreState(context));
131
144
  pi.on("session_tree", (_event, context) => restoreState(context));
132
- pi.on("context", (event) => {
133
- if (state.tasks.length === 0) return;
134
- const todoListMessage = {
135
- role: "custom",
136
- customType: "pi-todo-context",
137
- content: `Todo List:\n${formatTodoList(state.tasks)}`,
138
- display: false,
139
- timestamp: 0,
140
- } as const;
141
- return { messages: [...event.messages, todoListMessage] };
145
+ pi.on("context", (event, context) => {
146
+ try {
147
+ assertTodoJournalReadable(context);
148
+ return { messages: projectTodoContext(context.sessionManager.getBranch(), event.messages) };
149
+ } catch (cause) {
150
+ // Pi logs context exceptions and continues; abort the active run as well.
151
+ context.abort();
152
+ throw cause;
153
+ }
142
154
  });
143
155
 
144
156
  pi.registerTool<typeof TodoParameters, TodoToolDetails | undefined>({
@@ -147,7 +159,8 @@ export default function piTodoExtension(pi: ExtensionAPI): void {
147
159
  description: "Manage the current session branch's Todo List.",
148
160
  parameters: TodoParameters,
149
161
  executionMode: "sequential",
150
- async execute(_toolCallId, params, _signal, _onUpdate, context) {
162
+ async execute(_toolCallId, params, signal, _onUpdate, context) {
163
+ signal?.throwIfAborted();
151
164
  const result = runTodoAction(params, context);
152
165
  return {
153
166
  content: [{ type: "text", text: result.message }],
@@ -0,0 +1,148 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import {
3
+ buildSessionContext,
4
+ type ContextEvent,
5
+ type SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+ import { Value } from "typebox/value";
9
+ import {
10
+ formatTodoList,
11
+ parseTodoStateSnapshot,
12
+ TodoStateRecord,
13
+ type TodoStateSnapshot,
14
+ } from "./todo-list.js";
15
+
16
+ type Message = ContextEvent["messages"][number];
17
+ const ProjectionDetails = Type.Object(
18
+ {
19
+ version: Type.Literal(1),
20
+ stateEntryId: Type.String(),
21
+ checkpointId: Type.Union([Type.String(), Type.Null()]),
22
+ },
23
+ { additionalProperties: false },
24
+ );
25
+
26
+ /** Validates both the serialized shape and Todo List invariants at the journal boundary. */
27
+ export function todoStateFromEntry(entry: SessionEntry): TodoStateSnapshot | undefined {
28
+ if (
29
+ entry.type !== "custom" ||
30
+ entry.customType !== "pi-todo-state" ||
31
+ !Value.Check(TodoStateRecord, entry.data)
32
+ )
33
+ return undefined;
34
+ return parseTodoStateSnapshot(entry.data);
35
+ }
36
+
37
+ function snapshotMessage(
38
+ entry: SessionEntry,
39
+ state: TodoStateSnapshot,
40
+ checkpointId: string | null,
41
+ ): Message {
42
+ return {
43
+ role: "custom",
44
+ customType: "pi-todo-context",
45
+ display: false,
46
+ content: `Todo List:\n${formatTodoList(state.tasks)}`,
47
+ timestamp: Date.parse(entry.timestamp),
48
+ details: { version: 1, stateEntryId: entry.id, checkpointId },
49
+ };
50
+ }
51
+
52
+ /** Reprojects only Todo-owned snapshots at immutable journal boundaries, never at the live tail. */
53
+ export function projectTodoContext(
54
+ branch: readonly SessionEntry[],
55
+ incoming: ContextEvent["messages"],
56
+ ): ContextEvent["messages"] {
57
+ const messages = incoming.filter(
58
+ (message) =>
59
+ !(
60
+ message.role === "custom" &&
61
+ message.customType === "pi-todo-context" &&
62
+ Value.Check(ProjectionDetails, message.details)
63
+ ),
64
+ );
65
+ if (!branch.some((entry) => todoStateFromEntry(entry))) return messages;
66
+ const checkpoint = branch.findLast((entry) => entry.type === "compaction");
67
+ let start = 0;
68
+ let anchor: Message | undefined;
69
+ let previousContent: string | undefined;
70
+ const insertions = new Map<number, Message[]>();
71
+ let previousIndex = -1;
72
+ const insert = (snapshot: Message): void => {
73
+ let index = -1;
74
+ if (anchor) {
75
+ // ponytail: linear exact matching per mutation; index fingerprints if large journals make this measurable.
76
+ const matches = messages.flatMap((message, i) =>
77
+ isDeepStrictEqual(message, anchor) ? [i] : [],
78
+ );
79
+ if (matches.length !== 1)
80
+ throw new Error(
81
+ "Todo context anchor is missing or ambiguous; cannot preserve snapshot order",
82
+ );
83
+ index = matches[0]!;
84
+ }
85
+ if (index < previousIndex) throw new Error("Todo context anchors are reordered");
86
+ previousIndex = index;
87
+ const group = insertions.get(index) ?? [];
88
+ group.push(snapshot);
89
+ insertions.set(index, group);
90
+ };
91
+ if (checkpoint) {
92
+ start = branch.findIndex((entry) => entry.id === checkpoint.firstKeptEntryId);
93
+ const checkpointIndex = branch.indexOf(checkpoint);
94
+ if (start < 0 || start > checkpointIndex)
95
+ throw new Error("Todo checkpoint cutoff is unavailable");
96
+ anchor = buildSessionContext([checkpoint], checkpoint.id).messages[0];
97
+ for (const entry of branch.slice(0, start).toReversed()) {
98
+ const state = todoStateFromEntry(entry);
99
+ if (!state) continue;
100
+ previousContent = formatTodoList(state.tasks);
101
+ insert(snapshotMessage(entry, state, checkpoint.id));
102
+ break;
103
+ }
104
+ }
105
+ const outstanding = new Map<string, number>();
106
+ let pending: Message[] = [];
107
+ for (const entry of branch.slice(start)) {
108
+ if (entry === checkpoint) continue;
109
+ const state = todoStateFromEntry(entry);
110
+ if (state) {
111
+ const content = formatTodoList(state.tasks);
112
+ if (
113
+ content !== previousContent &&
114
+ (previousContent !== undefined || state.tasks.length > 0)
115
+ ) {
116
+ const snapshot = snapshotMessage(entry, state, null);
117
+ if (outstanding.size > 0) pending.push(snapshot);
118
+ else insert(snapshot);
119
+ }
120
+ previousContent = content;
121
+ continue;
122
+ }
123
+ const message = buildSessionContext([entry], entry.id).messages[0];
124
+ if (!message) continue;
125
+ if (message.role === "assistant") {
126
+ if (outstanding.size > 0 && pending.length > 0)
127
+ throw new Error("Todo mutation has an incomplete tool group");
128
+ outstanding.clear();
129
+ for (const block of message.content)
130
+ if (block.type === "toolCall")
131
+ outstanding.set(block.id, (outstanding.get(block.id) ?? 0) + 1);
132
+ } else if (message.role === "toolResult") {
133
+ const remaining = (outstanding.get(message.toolCallId) ?? 0) - 1;
134
+ if (remaining > 0) outstanding.set(message.toolCallId, remaining);
135
+ else outstanding.delete(message.toolCallId);
136
+ }
137
+ anchor = message;
138
+ if (outstanding.size === 0 && pending.length > 0) {
139
+ for (const snapshot of pending) insert(snapshot);
140
+ pending = [];
141
+ }
142
+ }
143
+ if (pending.length > 0) throw new Error("Todo mutation has an incomplete tool group");
144
+ return [
145
+ ...(insertions.get(-1) ?? []),
146
+ ...messages.flatMap((message, index) => [message, ...(insertions.get(index) ?? [])]),
147
+ ];
148
+ }