@howaboua/pi-notes-compaction 0.0.9 → 0.0.10

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 (53) hide show
  1. package/CHANGELOG.md +23 -5
  2. package/PCC-INTEGRATION.md +7 -98
  3. package/README.md +21 -13
  4. package/package.json +7 -3
  5. package/src/activation.ts +152 -0
  6. package/src/agent-identity.ts +119 -0
  7. package/src/attachment-snapshot.ts +103 -0
  8. package/src/binding-startup.ts +30 -0
  9. package/src/bridge.ts +1 -43
  10. package/src/compaction-projection.ts +88 -0
  11. package/src/context-owner.ts +103 -0
  12. package/src/context-sharing.ts +144 -0
  13. package/src/extension-hooks.ts +198 -0
  14. package/src/extension-sharing.ts +118 -0
  15. package/src/fresh-checkpoint.ts +117 -0
  16. package/src/fresh-notes.ts +141 -26
  17. package/src/history-search-protocol.ts +39 -0
  18. package/src/history-search-pruning.mjs +120 -0
  19. package/src/history-search-worker.mjs +256 -0
  20. package/src/history-search.ts +269 -0
  21. package/src/history.ts +212 -40
  22. package/src/idle-admission.ts +201 -0
  23. package/src/index.ts +71 -401
  24. package/src/integrations.ts +159 -0
  25. package/src/lifecycle.ts +63 -448
  26. package/src/note-save-marker.ts +112 -0
  27. package/src/notes-lookup.ts +112 -0
  28. package/src/notes.ts +24 -28
  29. package/src/query-executor.ts +190 -0
  30. package/src/remote.ts +357 -0
  31. package/src/rollover.ts +212 -0
  32. package/src/saved-session.ts +44 -7
  33. package/src/session-pruning-content.ts +237 -0
  34. package/src/session-pruning-plan.ts +243 -0
  35. package/src/session-pruning-policy.ts +20 -0
  36. package/src/session-pruning-screen.ts +130 -0
  37. package/src/session-pruning-source.ts +44 -0
  38. package/src/session-pruning-transaction.ts +141 -0
  39. package/src/session-pruning.ts +142 -0
  40. package/src/settings-command.ts +77 -0
  41. package/src/settings-screen.ts +84 -19
  42. package/src/settings.ts +143 -11
  43. package/src/shared-notes.ts +37 -14
  44. package/src/sharing-service.ts +348 -0
  45. package/src/store.ts +31 -0
  46. package/src/task-boundary.ts +6 -1
  47. package/src/tool-contracts.ts +279 -0
  48. package/src/tools.ts +19 -560
  49. package/src/tree-archive.ts +149 -0
  50. package/src/tree-checkpoint.ts +170 -0
  51. package/src/tree-handoff-read.ts +192 -0
  52. package/src/window-checkpoint.ts +105 -0
  53. package/src/windows.ts +25 -9
@@ -0,0 +1,198 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import type { NotesActivation } from "./activation.js";
3
+ import type { NotesBridge, NotesOwner } from "./bridge.js";
4
+ import { NESTED_NOTE_OUTCOME, type NestedNoteOutcome } from "./fresh-notes.js";
5
+ import { registerNotesCompactionIntegration } from "./integrations.js";
6
+ import type { NotesLifecycle } from "./lifecycle.js";
7
+ import type { registerNoteSaveMarkers } from "./note-save-marker.js";
8
+ import {
9
+ projectTreeCheckpointBranch,
10
+ projectTreeCheckpointMessages,
11
+ } from "./tree-checkpoint.js";
12
+ import { projectTreeHandoffReads } from "./tree-handoff-read.js";
13
+ import type { WindowCheckpoints } from "./window-checkpoint.js";
14
+
15
+ export async function registerNotesHooks(
16
+ pi: ExtensionAPI,
17
+ activation: NotesActivation,
18
+ lifecycle: NotesLifecycle,
19
+ owner: NotesOwner,
20
+ checkpoints: WindowCheckpoints,
21
+ markers: ReturnType<typeof registerNoteSaveMarkers>,
22
+ family: NotesBridge,
23
+ ) {
24
+ pi.on("session_start", async (_event, ctx) => {
25
+ activation.start(ctx, family);
26
+ if (activation.available) {
27
+ try {
28
+ await checkpoints.restore(ctx);
29
+ } catch (error) {
30
+ ctx.ui.notify(`Context checkpoint failed: ${String(error)}`, "error");
31
+ }
32
+ }
33
+ });
34
+ pi.on("before_agent_start", (event, ctx) => {
35
+ activation.refreshActivation(ctx);
36
+ if (lifecycle.active) return lifecycle.beforeStart(ctx, event);
37
+ });
38
+ pi.on("input", async (event, ctx) => {
39
+ activation.refreshActivation(ctx);
40
+ if (activation.available && ctx.isIdle()) {
41
+ try {
42
+ await checkpoints.restore(ctx);
43
+ } catch (error) {
44
+ ctx.ui.notify(`Context checkpoint failed: ${String(error)}`, "error");
45
+ return { action: "handled" };
46
+ }
47
+ }
48
+ return lifecycle.active ? lifecycle.input(event, ctx) : undefined;
49
+ });
50
+ const nestedWrites = new Map<
51
+ string,
52
+ { runId: string; windowId: string; parentCallId: string; sessionId: string }
53
+ >();
54
+ pi.on("tool_execution_start", (event, ctx) => {
55
+ if (
56
+ !lifecycle.active ||
57
+ event.toolName !== "notes" ||
58
+ !event.parentToolCallId ||
59
+ !lifecycle.runId ||
60
+ !lifecycle.windows.current
61
+ )
62
+ return;
63
+ const input = event.args as { action?: unknown } | undefined;
64
+ if (input?.action !== "write_file" && input?.action !== "append_to_file")
65
+ return;
66
+ nestedWrites.set(event.toolCallId, {
67
+ runId: lifecycle.runId,
68
+ windowId: lifecycle.windows.current.currentWindowId,
69
+ parentCallId: event.parentToolCallId,
70
+ sessionId: ctx.sessionManager.getSessionId(),
71
+ });
72
+ });
73
+ pi.on("tool_execution_end", (event, ctx) => {
74
+ const write = nestedWrites.get(event.toolCallId);
75
+ nestedWrites.delete(event.toolCallId);
76
+ if (!write || write.sessionId !== ctx.sessionManager.getSessionId()) return;
77
+ const details = event.result?.details;
78
+ pi.appendEntry(NESTED_NOTE_OUTCOME, {
79
+ protocol: 1,
80
+ runId: write.runId,
81
+ windowId: write.windowId,
82
+ callId: event.toolCallId,
83
+ parentCallId: write.parentCallId,
84
+ ...(details?.notesCompactionRouted === true
85
+ ? { origin: "routed" as const }
86
+ : {}),
87
+ saved:
88
+ !event.isError &&
89
+ details?.notesCompaction?.saved === true &&
90
+ details.notesCompaction.runId === write.runId,
91
+ } satisfies NestedNoteOutcome);
92
+ });
93
+ pi.on("agent_before_settle", (event) => {
94
+ if (lifecycle.active) lifecycle.outcome(event.outcome);
95
+ });
96
+ pi.on("agent_settled", async (event, ctx) => {
97
+ if (!lifecycle.active) return;
98
+ try {
99
+ markers.record(
100
+ ctx,
101
+ lifecycle.windows.current?.currentWindowId,
102
+ lifecycle.runId,
103
+ event.aborted,
104
+ );
105
+ await lifecycle.settled(event, ctx);
106
+ } catch (error) {
107
+ ctx.ui.notify(
108
+ `Context rollover failed: ${error instanceof Error ? error.message : String(error)}`,
109
+ "error",
110
+ );
111
+ }
112
+ });
113
+ pi.on("turn_end", (event, ctx) => {
114
+ const checkpoint = event.entries.some(
115
+ (entry) => entry.type === "compaction",
116
+ )
117
+ ? undefined
118
+ : checkpoints.draft(ctx.sessionManager.getBranch());
119
+ const entries = checkpoint ? [...event.entries, checkpoint] : event.entries;
120
+ if (!lifecycle.active || lifecycle.newWindowRequests === "off")
121
+ return checkpoint ? { entries } : undefined;
122
+ const reminder = lifecycle.windows.reminder(
123
+ ctx,
124
+ event.message.role === "assistant" &&
125
+ !ctx.signal?.aborted &&
126
+ !["error", "length", "aborted"].includes(event.message.stopReason) &&
127
+ event.toolResults.length > 0 &&
128
+ pi.getActiveTools().includes("new_context")
129
+ ? lifecycle.taskBoundaryReminder
130
+ : 0,
131
+ !lifecycle.fresh(ctx, lifecycle.runId),
132
+ lifecycle.gptPromptMode(),
133
+ );
134
+ return reminder || checkpoint
135
+ ? {
136
+ entries: [
137
+ ...entries,
138
+ ...(reminder
139
+ ? [lifecycle.prepareReminder?.(reminder) ?? reminder]
140
+ : []),
141
+ ],
142
+ }
143
+ : undefined;
144
+ });
145
+ pi.on("context", (event, ctx) => {
146
+ try {
147
+ if (lifecycle.active)
148
+ markers.bookmark(ctx, lifecycle.windows.current?.currentWindowId);
149
+ const branch = ctx.sessionManager.getBranch();
150
+ const projected = projectTreeCheckpointBranch(
151
+ branch,
152
+ ctx.sessionManager.getEntries(),
153
+ );
154
+ return {
155
+ messages: owner.projectMessages(
156
+ projectTreeHandoffReads(
157
+ projectTreeCheckpointMessages(branch, projected, event.messages) ??
158
+ event.messages,
159
+ projected,
160
+ ),
161
+ projected,
162
+ ),
163
+ };
164
+ } catch (error) {
165
+ ctx.abort();
166
+ throw error;
167
+ }
168
+ });
169
+ const prepareProviderWindow = await registerNotesCompactionIntegration(
170
+ pi,
171
+ activation,
172
+ lifecycle,
173
+ checkpoints,
174
+ );
175
+ lifecycle.prepareWindow = async (ctx) => {
176
+ activation.refreshHistorySearch(ctx, true);
177
+ await prepareProviderWindow?.(ctx);
178
+ };
179
+ pi.on("session_compact_failed", async (event, ctx) => {
180
+ if (lifecycle.active) await lifecycle.compactFailed(event, ctx);
181
+ });
182
+ pi.on("session_compact", (_event, ctx) => {
183
+ if (lifecycle.active) {
184
+ lifecycle.windows.restore(ctx.sessionManager.getBranch());
185
+ activation.refreshHistorySearch(ctx, true);
186
+ }
187
+ });
188
+ pi.on("session_tree", (_event, ctx) => {
189
+ lifecycle.reset(ctx);
190
+ activation.refreshHistorySearch(ctx, true);
191
+ });
192
+ pi.on("agent_start", (_event, ctx) =>
193
+ activation.refreshHistorySearch(ctx, true),
194
+ );
195
+ pi.on("model_select", (_event, ctx) => {
196
+ activation.refreshActivation(ctx);
197
+ });
198
+ }
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import type { NotesActivation } from "./activation.js";
7
+ import { contextAgentIdentity, contextTargetAgent } from "./agent-identity.js";
8
+ import { type NotesOwner, OWNER_CHANNEL, type OwnerRequest } from "./bridge.js";
9
+ import { optionalPccMissing } from "./integrations.js";
10
+ import type { NotesLifecycle } from "./lifecycle.js";
11
+ import { modelIsActive } from "./settings.js";
12
+ import { registerContextSharingService } from "./sharing-service.js";
13
+
14
+ export async function registerNotesSharing(
15
+ pi: ExtensionAPI,
16
+ owner: NotesOwner,
17
+ activation: NotesActivation,
18
+ lifecycle: NotesLifecycle,
19
+ ) {
20
+ const route = registerContextSharingService(pi, {
21
+ enabled: () => activation.available,
22
+ shareSubagentContext: () =>
23
+ lifecycle.active && activation.settings.shareSubagentContext,
24
+ owner: () => owner,
25
+ execute: (ctx, request, signal) =>
26
+ owner.executeShared!(
27
+ { namespace: request.namespace, params: request.params },
28
+ randomUUID(),
29
+ ctx,
30
+ signal,
31
+ ),
32
+ });
33
+ let remote: Pick<
34
+ import("./bridge.js").NotesBridge,
35
+ "lookup" | "canProject" | "projectResult"
36
+ > = {};
37
+ try {
38
+ const { createNotesRemoteService } = await import("./remote.js");
39
+ remote = createNotesRemoteService(pi);
40
+ } catch (error) {
41
+ if (!optionalPccMissing(error)) throw error;
42
+ }
43
+ const family = {
44
+ ...remote,
45
+ protocol: 1 as const,
46
+ agentName: (ctx: ExtensionContext) => contextAgentIdentity(ctx).agentName,
47
+ route: async (
48
+ query: import("./bridge.js").LookupQuery,
49
+ callId: string,
50
+ ctx: ExtensionContext,
51
+ signal?: AbortSignal,
52
+ ) => {
53
+ const identity = contextAgentIdentity(ctx);
54
+ const target = contextTargetAgent(
55
+ query.namespace,
56
+ query.params,
57
+ identity.agentName,
58
+ );
59
+ if (target === identity.agentName) return undefined;
60
+ const result = await route(
61
+ ctx,
62
+ { ...query, sessionId: identity.sessionId, agentName: target },
63
+ signal,
64
+ );
65
+ if (
66
+ query.namespace === "history" &&
67
+ result &&
68
+ (result.details.externalNotesResponses?.length ||
69
+ "protectedOutputs" in result.details)
70
+ )
71
+ throw new Error(
72
+ "That agent returned encrypted history instead of Pi session history. Update and reload Notes on the other agent, or open its saved Pi JSONL session locally.",
73
+ );
74
+ if (!result?.details.externalNotesResponses?.length) return result;
75
+ const { externalNotesResponses, ...details } = result.details;
76
+ if (!remote.projectResult || remote.canProject?.(ctx) === false)
77
+ return {
78
+ ...result,
79
+ details,
80
+ content: [
81
+ ...result.content,
82
+ {
83
+ type: "text" as const,
84
+ text: "Shared encrypted contents are unavailable on this model. Local results remain available. Use a compatible Codex model with PCC for remote contents.",
85
+ },
86
+ ],
87
+ };
88
+ return remote.projectResult(
89
+ { ...result, details },
90
+ externalNotesResponses.map(({ bytesBase64, ...response }) => ({
91
+ ...response,
92
+ bytes: Uint8Array.from(Buffer.from(bytesBase64, "base64")),
93
+ })),
94
+ callId,
95
+ ctx,
96
+ signal,
97
+ true,
98
+ );
99
+ },
100
+ };
101
+ const stopOwner = pi.events.on(OWNER_CHANNEL, (data) => {
102
+ if (!data || typeof data !== "object") return;
103
+ const request = data as Partial<OwnerRequest>;
104
+ if (request.protocol === 1 && activation.available)
105
+ request.projection?.(owner);
106
+ if (
107
+ request.protocol === 1 &&
108
+ typeof request.reply === "function" &&
109
+ activation.available &&
110
+ (request.ctx
111
+ ? modelIsActive(activation.settings, request.ctx.model)
112
+ : lifecycle.active)
113
+ )
114
+ request.reply(owner);
115
+ });
116
+
117
+ return { family, stopOwner };
118
+ }
@@ -0,0 +1,117 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type {
3
+ AgentSettledEvent,
4
+ BeforeAgentStartEvent,
5
+ CustomMessageEntryDraft,
6
+ ExtensionContext,
7
+ } from "@earendil-works/pi-coding-agent";
8
+ import type { NotesLifecycle } from "./lifecycle.js";
9
+
10
+ interface Checkpoint {
11
+ sessionId: string;
12
+ windowId: string;
13
+ requestId: string;
14
+ runId: string | undefined;
15
+ outcome: "completed" | "aborted" | "error" | undefined;
16
+ }
17
+
18
+ // Owns checkpoint request/run association and completed-write eligibility.
19
+ export class FreshCheckpoint {
20
+ private checkpoint: Checkpoint | undefined;
21
+ private readonly host: Pick<NotesLifecycle, "windows" | "fresh">;
22
+ private readonly sendMessage: (
23
+ message: Omit<CustomMessageEntryDraft, "type">,
24
+ options: { triggerTurn: boolean },
25
+ ) => void;
26
+ constructor(
27
+ host: FreshCheckpoint["host"],
28
+ sendMessage: FreshCheckpoint["sendMessage"],
29
+ ) {
30
+ this.host = host;
31
+ this.sendMessage = sendMessage;
32
+ }
33
+ get pending(): boolean {
34
+ return Boolean(this.checkpoint);
35
+ }
36
+ reset(): void {
37
+ this.checkpoint = undefined;
38
+ }
39
+ take(): Checkpoint | undefined {
40
+ const checkpoint = this.checkpoint;
41
+ this.checkpoint = undefined;
42
+ return checkpoint;
43
+ }
44
+ bind(event: BeforeAgentStartEvent, runId: string): void {
45
+ if (
46
+ this.checkpoint &&
47
+ event.messageType === "custom" &&
48
+ event.message.customType === "notes-compaction:checkpoint:v1" &&
49
+ (event.message.details as { requestId?: string } | undefined)
50
+ ?.requestId === this.checkpoint.requestId
51
+ )
52
+ this.checkpoint.runId = runId;
53
+ }
54
+
55
+ outcome(outcome: "completed" | "aborted" | "error"): void {
56
+ if (this.checkpoint) this.checkpoint.outcome = outcome;
57
+ }
58
+ start(ctx: ExtensionContext, instructions?: string): void {
59
+ if (!ctx.isIdle() || !this.host.windows.current || this.checkpoint)
60
+ throw new Error("A checkpoint cannot start until the session settles");
61
+ const requestId = randomUUID();
62
+ this.checkpoint = {
63
+ sessionId: ctx.sessionManager.getSessionId(),
64
+ windowId: this.host.windows.current.currentWindowId,
65
+ requestId,
66
+ runId: undefined,
67
+ outcome: undefined,
68
+ };
69
+ try {
70
+ this.sendMessage(
71
+ {
72
+ customType: "notes-compaction:checkpoint:v1",
73
+ details: { requestId },
74
+ content: `<context_window_reminder>\nSave the task state in notes, then finish your reply. A new window opens automatically after your reply; do not call new_context. If saving fails, report the error.\n</context_window_reminder>${instructions?.trim() ? `\n\nCheckpoint guidance:\n${instructions}` : ""}`,
75
+ display: true,
76
+ },
77
+ { triggerTurn: true },
78
+ );
79
+ } catch (error) {
80
+ this.checkpoint = undefined;
81
+ throw error;
82
+ }
83
+ }
84
+
85
+ permitsRollover(
86
+ checkpoint: Checkpoint,
87
+ event: AgentSettledEvent,
88
+ ctx: ExtensionContext,
89
+ ): boolean {
90
+ const valid =
91
+ checkpoint.sessionId === ctx.sessionManager.getSessionId() &&
92
+ checkpoint.windowId === this.host.windows.current?.currentWindowId;
93
+ const aborted =
94
+ event.aborted ||
95
+ checkpoint.outcome === "aborted" ||
96
+ checkpoint.outcome === undefined;
97
+ if (!valid || aborted) {
98
+ ctx.ui.notify(
99
+ "Checkpoint cancelled. The old context remains.",
100
+ "warning",
101
+ );
102
+ return false;
103
+ }
104
+ if (
105
+ checkpoint.outcome !== "completed" ||
106
+ !checkpoint.runId ||
107
+ !this.host.fresh(ctx, checkpoint.runId)
108
+ ) {
109
+ ctx.ui.notify(
110
+ "Rollover did not start. No fresh note was saved in the completed checkpoint. The old context remains.",
111
+ "warning",
112
+ );
113
+ return false;
114
+ }
115
+ return true;
116
+ }
117
+ }
@@ -5,6 +5,16 @@ import {
5
5
  } from "@earendil-works/pi-coding-agent";
6
6
  import { NOTE_RECEIPT, type NoteReceipt, noteReceipt } from "./notes.js";
7
7
 
8
+ export const NESTED_NOTE_OUTCOME = "notes-compaction:nested-write:v1";
9
+ export interface NestedNoteOutcome {
10
+ protocol: 1;
11
+ runId: string;
12
+ windowId: string;
13
+ callId: string;
14
+ parentCallId: string;
15
+ saved: boolean;
16
+ origin?: "routed";
17
+ }
8
18
  export const NOTES_RUN_ENTRY = "notes-compaction:run:v1";
9
19
 
10
20
  /** A receipt proves persistence. Current-run tool outcomes prove the checkpoint actually completed. */
@@ -13,7 +23,11 @@ export function hasFreshNotes(
13
23
  windowId: string | undefined,
14
24
  runId?: string,
15
25
  ): boolean {
16
- const { messages, receipts } = noteEvidence(branch, windowId, runId);
26
+ const { messages, receipts, outcomes } = noteEvidence(
27
+ branch,
28
+ windowId,
29
+ runId,
30
+ );
17
31
  const final = messages.findLast((message) => message.role === "assistant");
18
32
  if (
19
33
  final?.role !== "assistant" ||
@@ -31,6 +45,10 @@ export function hasFreshNotes(
31
45
  message.role === "toolResult" ? [message] : [],
32
46
  ),
33
47
  receipts,
48
+ outcomes,
49
+ messages.flatMap((message) =>
50
+ message.role === "toolResult" ? [message] : [],
51
+ ),
34
52
  );
35
53
  }
36
54
 
@@ -41,7 +59,11 @@ export function hasPrecedingNoteWrite(
41
59
  runId: string,
42
60
  requestCallId: string,
43
61
  ): boolean {
44
- const { messages, receipts } = noteEvidence(branch, windowId, runId);
62
+ const { messages, receipts, outcomes } = noteEvidence(
63
+ branch,
64
+ windowId,
65
+ runId,
66
+ );
45
67
  const request = messages.findLastIndex(
46
68
  (message) =>
47
69
  message.role === "assistant" &&
@@ -68,7 +90,15 @@ export function hasPrecedingNoteWrite(
68
90
  );
69
91
  return (
70
92
  previous?.role === "toolResult" &&
71
- completedWrites([call], [previous], receipts)
93
+ completedWrites(
94
+ [call],
95
+ [previous],
96
+ receipts,
97
+ outcomes,
98
+ messages.flatMap((message) =>
99
+ message.role === "toolResult" ? [message] : [],
100
+ ),
101
+ )
72
102
  );
73
103
  }
74
104
 
@@ -80,16 +110,23 @@ function noteEvidence(
80
110
  const lastUser = branch.findLastIndex(
81
111
  (entry) => entry.type === "message" && entry.message.role === "user",
82
112
  );
113
+ const lastMessage = branch.findLastIndex(
114
+ (entry) =>
115
+ entry.type === "custom_message" ||
116
+ (entry.type === "message" && entry.message.role !== "system"),
117
+ );
83
118
  // Custom kickoffs have no user message. Scope both receipts and tool outcomes
84
119
  // to their native preparation boundary, not an earlier custom-only run.
120
+ // /tree returns to a prompt's parent, which can include its preparation marker
121
+ // without the prompt. Only a delivered message starts a new historical run.
85
122
  const runStart = branch.findLastIndex(
86
- (entry) =>
123
+ (entry, index) =>
87
124
  entry.type === "custom" &&
88
125
  entry.customType === NOTES_RUN_ENTRY &&
89
126
  entry.data &&
90
127
  typeof entry.data === "object" &&
91
128
  "runId" in entry.data &&
92
- (!runId || entry.data.runId === runId),
129
+ (runId ? entry.data.runId === runId : index < lastMessage),
93
130
  );
94
131
  const run = branch.slice(Math.max(lastUser, runStart) + 1);
95
132
  const receipts = run
@@ -108,13 +145,29 @@ function noteEvidence(
108
145
  ),
109
146
  );
110
147
  const messages = buildSessionProjection(run).messages;
111
- return { messages, receipts };
148
+ const outcomes = run.flatMap((entry) => {
149
+ if (entry.type !== "custom" || entry.customType !== NESTED_NOTE_OUTCOME)
150
+ return [];
151
+ const value = entry.data as Partial<NestedNoteOutcome> | undefined;
152
+ return value?.protocol === 1 &&
153
+ value.windowId === windowId &&
154
+ (!runId || value.runId === runId) &&
155
+ typeof value.callId === "string" &&
156
+ typeof value.parentCallId === "string" &&
157
+ (value.origin === undefined || value.origin === "routed") &&
158
+ typeof value.saved === "boolean"
159
+ ? [value as NestedNoteOutcome]
160
+ : [];
161
+ });
162
+ return { messages, receipts, outcomes };
112
163
  }
113
164
 
114
165
  function completedWrites(
115
166
  calls: readonly ToolCall[],
116
167
  results: readonly ToolResultMessage[],
117
168
  receipts: readonly NoteReceipt[],
169
+ outcomes: readonly NestedNoteOutcome[],
170
+ allResults: readonly ToolResultMessage[],
118
171
  ): boolean {
119
172
  if (!receipts.length) return false;
120
173
  const writes = calls.filter(
@@ -159,39 +212,80 @@ function completedWrites(
159
212
  completedWrite = true;
160
213
  }
161
214
  for (const result of results) {
162
- const details = result.details;
163
- const saved =
164
- details && typeof details === "object" && "contextNotesSaved" in details
165
- ? details["contextNotesSaved"]
166
- : undefined;
167
- // PCC's protected exec/wait host records cover nested calls outside Pi's executeTool path.
168
- if (saved === false || (saved === true && result.isError)) return false;
169
- if (
170
- saved === true &&
171
- (result.toolName === "exec" || result.toolName === "wait")
172
- )
215
+ const cell = codeCell(result);
216
+ const terminal = cell
217
+ ? allResults.findLast(
218
+ (item) =>
219
+ codeCell(item)?.id === cell.id &&
220
+ codeCell(item)?.status !== "yielded",
221
+ )
222
+ : undefined;
223
+ const parents = new Set(
224
+ allResults
225
+ .filter((item) => cell && codeCell(item)?.id === cell.id)
226
+ .map((item) => item.toolCallId),
227
+ );
228
+ parents.add(result.toolCallId);
229
+ const completed = outcomes.filter((item) => parents.has(item.parentCallId));
230
+ const local = completed.filter((item) => item.origin !== "routed");
231
+ if (local.length) {
232
+ if (local.some((item) => !item.saved)) return false;
233
+ if (
234
+ result.isError ||
235
+ (cell &&
236
+ (!terminal ||
237
+ terminal.isError ||
238
+ codeCell(terminal)?.status !== "result" ||
239
+ codeCell(terminal)?.failed))
240
+ )
241
+ return false;
173
242
  completedWrite = true;
243
+ }
244
+ // Older saved PCC runs used a note-specific completion field. Read it,
245
+ // but new executions rely on Notes-owned outcomes and public Pi events.
246
+ const legacy =
247
+ result.details &&
248
+ typeof result.details === "object" &&
249
+ "contextNotesSaved" in result.details
250
+ ? result.details["contextNotesSaved"]
251
+ : undefined;
252
+ if (!completed.length && legacy !== undefined) {
253
+ if (
254
+ legacy === false ||
255
+ result.isError ||
256
+ (cell &&
257
+ (!terminal ||
258
+ codeCell(terminal)?.status !== "result" ||
259
+ codeCell(terminal)?.failed))
260
+ )
261
+ return false;
262
+ if (legacy === true) completedWrite = true;
263
+ }
174
264
  const nested = result.nestedCalls;
175
265
  const noteCalls =
176
266
  nested?.calls.filter((call) => call.name === "notes") ?? [];
267
+ const uncovered =
268
+ legacy === true && !completed.length
269
+ ? []
270
+ : noteCalls.filter(
271
+ (call) => !outcomes.some((item) => item.callId === call.id),
272
+ );
177
273
  if (
178
- noteCalls.some(
274
+ uncovered.some(
179
275
  (call) =>
180
276
  call.status !== "ok" &&
181
277
  (!call.arguments ||
182
278
  call.arguments["action"] === "write_file" ||
183
279
  call.arguments["action"] === "append_to_file"),
184
280
  ) ||
185
- (noteCalls.length && !nested?.complete)
281
+ (uncovered.length && !nested?.complete)
186
282
  )
187
283
  return false;
188
- const nestedWrites =
189
- nested?.calls.filter(
190
- (call) =>
191
- call.name === "notes" &&
192
- (call.arguments?.["action"] === "write_file" ||
193
- call.arguments?.["action"] === "append_to_file"),
194
- ) ?? [];
284
+ const nestedWrites = uncovered.filter(
285
+ (call) =>
286
+ call.arguments?.["action"] === "write_file" ||
287
+ call.arguments?.["action"] === "append_to_file",
288
+ );
195
289
  if (
196
290
  nestedWrites.some((call) => call.status !== "ok") ||
197
291
  (nestedWrites.length && (result.isError || !nested?.complete))
@@ -201,3 +295,24 @@ function completedWrites(
201
295
  }
202
296
  return completedWrite;
203
297
  }
298
+
299
+ function codeCell(
300
+ result: ToolResultMessage,
301
+ ): { id: string; status: unknown; failed: boolean } | undefined {
302
+ const details = result.details;
303
+ if (
304
+ !details ||
305
+ typeof details !== "object" ||
306
+ !("codeMode" in details) ||
307
+ details["codeMode"] !== true ||
308
+ !("cellId" in details) ||
309
+ typeof details["cellId"] !== "string" ||
310
+ !("status" in details)
311
+ )
312
+ return;
313
+ return {
314
+ id: details["cellId"],
315
+ status: details["status"],
316
+ failed: "scriptError" in details && Boolean(details["scriptError"]),
317
+ };
318
+ }