@howaboua/pi-notes-compaction 0.0.9 → 0.0.11

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 (54) hide show
  1. package/CHANGELOG.md +28 -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 +258 -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 +204 -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 +155 -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/sqlite.mjs +33 -0
  46. package/src/store.ts +46 -13
  47. package/src/task-boundary.ts +6 -1
  48. package/src/tool-contracts.ts +279 -0
  49. package/src/tools.ts +19 -560
  50. package/src/tree-archive.ts +149 -0
  51. package/src/tree-checkpoint.ts +170 -0
  52. package/src/tree-handoff-read.ts +192 -0
  53. package/src/window-checkpoint.ts +105 -0
  54. package/src/windows.ts +25 -9
@@ -0,0 +1,149 @@
1
+ import type {
2
+ BranchSummaryEntry,
3
+ SessionEntry,
4
+ } from "@earendil-works/pi-coding-agent";
5
+ import { windowDetails } from "./windows.js";
6
+
7
+ export const TREE_ARCHIVE_ENTRY_TYPE = "codex-context-tree-archive";
8
+ const TREE_ARCHIVE_PROTOCOL = 1;
9
+ export const MAX_ARCHIVE_DEPTH = 50_000;
10
+
11
+ export interface TreeArchiveManifestData {
12
+ protocol: 1;
13
+ strategy: "codex-context-tree";
14
+ windowId: string;
15
+ boundaryEntryId: string;
16
+ summaryEntryId: string;
17
+ archivedLeafId: string;
18
+ branchBaseId: string | null;
19
+ compactionEntryId?: string;
20
+ }
21
+
22
+ interface TreeArchive {
23
+ manifest: TreeArchiveManifestData;
24
+ summary: BranchSummaryEntry;
25
+ // Pi forks copy the active branch, not the archived paths it references.
26
+ entries: SessionEntry[] | undefined;
27
+ }
28
+
29
+ export interface TreeArchiveIndex {
30
+ archives: TreeArchive[];
31
+ invalidManifest: boolean;
32
+ }
33
+
34
+ export function buildTreeArchiveIndex(
35
+ allEntries: readonly SessionEntry[],
36
+ activeBranch: readonly SessionEntry[],
37
+ ): TreeArchiveIndex {
38
+ const byId = new Map(allEntries.map((entry) => [entry.id, entry]));
39
+ const archives: TreeArchive[] = [];
40
+ const seenSummaries = new Set<string>();
41
+ const seenWindows = new Set<string>();
42
+ let invalidManifest = false;
43
+ for (const entry of activeBranch) {
44
+ if (entry.type !== "custom" || entry.customType !== TREE_ARCHIVE_ENTRY_TYPE)
45
+ continue;
46
+ if (!isTreeArchiveManifestData(entry.data)) {
47
+ invalidManifest = true;
48
+ continue;
49
+ }
50
+ const manifest = entry.data;
51
+ if (
52
+ seenSummaries.has(manifest.summaryEntryId) ||
53
+ seenWindows.has(manifest.windowId)
54
+ ) {
55
+ invalidManifest = true;
56
+ continue;
57
+ }
58
+ const summary = byId.get(manifest.summaryEntryId);
59
+ if (
60
+ !summary ||
61
+ summary.type !== "branch_summary" ||
62
+ entry.parentId !== summary.id ||
63
+ summary.fromId !== manifest.archivedLeafId ||
64
+ summary.parentId !== manifest.branchBaseId
65
+ ) {
66
+ invalidManifest = true;
67
+ continue;
68
+ }
69
+ const archivedEntries = archivedPath(manifest, byId);
70
+ if (
71
+ archivedEntries &&
72
+ manifest.compactionEntryId !== undefined &&
73
+ !archivedEntries.some(
74
+ (entry) =>
75
+ entry.id === manifest.compactionEntryId &&
76
+ entry.type === "compaction",
77
+ )
78
+ ) {
79
+ invalidManifest = true;
80
+ continue;
81
+ }
82
+ seenSummaries.add(summary.id);
83
+ seenWindows.add(manifest.windowId);
84
+ archives.push({ manifest, summary, entries: archivedEntries });
85
+ }
86
+ return { archives, invalidManifest };
87
+ }
88
+
89
+ function archivedPath(
90
+ manifest: TreeArchiveManifestData,
91
+ byId: ReadonlyMap<string, SessionEntry>,
92
+ ): SessionEntry[] | undefined {
93
+ const reverse: SessionEntry[] = [];
94
+ const visited = new Set<string>();
95
+ let currentId: string | null = manifest.archivedLeafId;
96
+ let foundBoundary = false;
97
+ while (currentId !== manifest.branchBaseId) {
98
+ if (
99
+ currentId === null ||
100
+ visited.has(currentId) ||
101
+ reverse.length >= MAX_ARCHIVE_DEPTH
102
+ )
103
+ return undefined;
104
+ visited.add(currentId);
105
+ const entry = byId.get(currentId);
106
+ if (!entry) return undefined;
107
+ reverse.push(entry);
108
+ if (entry.id === manifest.boundaryEntryId) foundBoundary = true;
109
+ currentId = entry.parentId;
110
+ }
111
+ if (!foundBoundary) return undefined;
112
+ return reverse.reverse();
113
+ }
114
+
115
+ export function isTreeArchiveManifestData(
116
+ value: unknown,
117
+ ): value is TreeArchiveManifestData {
118
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
119
+ const manifest = value as Record<string, unknown>;
120
+ return (
121
+ manifest["protocol"] === TREE_ARCHIVE_PROTOCOL &&
122
+ manifest["strategy"] === "codex-context-tree" &&
123
+ nonEmptyString(manifest["windowId"]) &&
124
+ nonEmptyString(manifest["boundaryEntryId"]) &&
125
+ nonEmptyString(manifest["summaryEntryId"]) &&
126
+ nonEmptyString(manifest["archivedLeafId"]) &&
127
+ (manifest["compactionEntryId"] === undefined ||
128
+ nonEmptyString(manifest["compactionEntryId"])) &&
129
+ (manifest["branchBaseId"] === null ||
130
+ nonEmptyString(manifest["branchBaseId"]))
131
+ );
132
+ }
133
+
134
+ function nonEmptyString(value: unknown): value is string {
135
+ return typeof value === "string" && value !== "";
136
+ }
137
+
138
+ export function hasTreeArchiveSuccessor(
139
+ entries: readonly SessionEntry[],
140
+ windowId: string,
141
+ ): boolean {
142
+ return entries.some((entry) => {
143
+ const details = windowDetails(entry);
144
+ return (
145
+ details?.kind === "window" &&
146
+ details.identity.previousWindowId === windowId
147
+ );
148
+ });
149
+ }
@@ -0,0 +1,170 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import {
3
+ buildSessionContext,
4
+ type SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ buildTreeArchiveIndex,
8
+ hasTreeArchiveSuccessor,
9
+ TREE_ARCHIVE_ENTRY_TYPE,
10
+ } from "./tree-archive.js";
11
+ import { windowDetails } from "./windows.js";
12
+
13
+ /** Restore the archived checkpoint's source path only in model/replay context. */
14
+ export function projectTreeCheckpointBranch(
15
+ active: readonly SessionEntry[],
16
+ all: readonly SessionEntry[],
17
+ ): readonly SessionEntry[] {
18
+ const index = buildTreeArchiveIndex(all, active);
19
+ const hiddenSummaries = new Set(
20
+ index.archives
21
+ .filter(
22
+ (item) =>
23
+ !item.manifest.compactionEntryId ||
24
+ hasTreeArchiveSuccessor(active, item.manifest.windowId),
25
+ )
26
+ .map((item) => item.summary.id),
27
+ );
28
+ const manifestIndex = active.findLastIndex(
29
+ (entry) =>
30
+ entry.type === "custom" && entry.customType === TREE_ARCHIVE_ENTRY_TYPE,
31
+ );
32
+ if (manifestIndex < 0) return hideArchiveSummaries(active, hiddenSummaries);
33
+ const tail = active.slice(manifestIndex + 1);
34
+ // Validate only the archive the live checkpoint still needs, not retired history.
35
+ if (
36
+ tail.some(
37
+ (entry) =>
38
+ entry.type === "compaction" ||
39
+ (entry.type === "custom_message" &&
40
+ windowDetails(entry)?.kind === "window" &&
41
+ windowDetails(entry)?.trim),
42
+ )
43
+ )
44
+ return hideArchiveSummaries(active, hiddenSummaries);
45
+ const archive = index.archives.find(
46
+ (item) => item.summary.id === active[manifestIndex]!.parentId,
47
+ );
48
+ if (!archive)
49
+ throw new Error("Invalid active Tree archive checkpoint metadata");
50
+ if (
51
+ !archive.manifest.compactionEntryId ||
52
+ !hasTreeArchiveSuccessor(active, archive.manifest.windowId)
53
+ )
54
+ return hideArchiveSummaries(active, hiddenSummaries);
55
+ if (!archive.entries)
56
+ throw new Error(
57
+ "The active Tree checkpoint is unavailable in this session copy; resume the source session",
58
+ );
59
+ const byId = new Map(all.map((entry) => [entry.id, entry]));
60
+ const source: SessionEntry[] = [];
61
+ const visited = new Set<string>();
62
+ let id: string | null = archive.manifest.archivedLeafId;
63
+ while (id !== null) {
64
+ if (visited.has(id) || source.length >= 50_000)
65
+ throw new Error("Invalid Tree checkpoint ancestry");
66
+ visited.add(id);
67
+ const entry = byId.get(id);
68
+ if (!entry) throw new Error("Tree checkpoint ancestry is missing");
69
+ source.push(entry);
70
+ id = entry.parentId;
71
+ }
72
+ source.reverse();
73
+ const checkpointIndex = source.findIndex(
74
+ (entry) => entry.id === archive.manifest.compactionEntryId,
75
+ );
76
+ const checkpoint = source[checkpointIndex];
77
+ if (
78
+ checkpoint?.type !== "compaction" ||
79
+ !source
80
+ .slice(0, checkpointIndex)
81
+ .some((entry) => entry.id === checkpoint.firstKeptEntryId)
82
+ )
83
+ throw new Error("Tree checkpoint kept history is missing");
84
+ return hideArchiveSummaries(
85
+ [...source, ...tail].map((entry, position, entries): SessionEntry => {
86
+ const parentId = position === 0 ? null : entries[position - 1]!.id;
87
+ return entry.parentId === parentId ? entry : { ...entry, parentId };
88
+ }),
89
+ hiddenSummaries,
90
+ );
91
+ }
92
+
93
+ function hideArchiveSummaries(
94
+ entries: readonly SessionEntry[],
95
+ hidden: ReadonlySet<string>,
96
+ ): readonly SessionEntry[] {
97
+ if (hidden.size === 0) return entries;
98
+ return entries.map(
99
+ (entry): SessionEntry =>
100
+ entry.type === "branch_summary" && hidden.has(entry.id)
101
+ ? // Keep entry IDs as replay cut points without sending archive summaries.
102
+ {
103
+ type: "custom",
104
+ id: entry.id,
105
+ parentId: entry.parentId,
106
+ timestamp: entry.timestamp,
107
+ customType: "codex-context-tree-summary",
108
+ data: {},
109
+ }
110
+ : entry,
111
+ );
112
+ }
113
+
114
+ /** Replace only persisted context displaced by the archive; retain extension edits/additions. */
115
+ export function projectTreeCheckpointMessages(
116
+ active: readonly SessionEntry[],
117
+ projected: readonly SessionEntry[],
118
+ messages: readonly AgentMessage[] | undefined,
119
+ ): readonly AgentMessage[] | undefined {
120
+ if (!messages || active === projected) return messages;
121
+ const original = new Set(
122
+ buildSessionContext([...active]).messages.map(messageKey),
123
+ );
124
+ const reconstructed = buildSessionContext([...projected]).messages;
125
+ const desired = new Set(reconstructed.map(messageKey));
126
+ const retained = messages.filter(
127
+ (message) =>
128
+ !original.has(messageKey(message)) || desired.has(messageKey(message)),
129
+ );
130
+ const positions = new Map<string, number[]>();
131
+ retained.forEach((message, index) => {
132
+ const key = messageKey(message);
133
+ positions.set(key, [...(positions.get(key) ?? []), index]);
134
+ });
135
+ const insertions = new Map<number, AgentMessage[]>();
136
+ let pending: AgentMessage[] = [];
137
+ let last = -1;
138
+ for (const message of reconstructed) {
139
+ const key = messageKey(message);
140
+ const position = positions.get(key)?.shift();
141
+ if (position !== undefined) {
142
+ if (pending.length)
143
+ insertions.set(position, [
144
+ ...(insertions.get(position) ?? []),
145
+ ...pending,
146
+ ]);
147
+ pending = [];
148
+ last = position;
149
+ } else if (!original.has(key)) pending.push(message);
150
+ }
151
+ if (pending.length)
152
+ insertions.set(last + 1, [...(insertions.get(last + 1) ?? []), ...pending]);
153
+ return retained
154
+ .flatMap((message, index) => [...(insertions.get(index) ?? []), message])
155
+ .concat(insertions.get(retained.length) ?? []);
156
+ }
157
+
158
+ function messageKey(message: AgentMessage): string {
159
+ return JSON.stringify([
160
+ message.role,
161
+ message.timestamp,
162
+ message.role === "custom"
163
+ ? message.customType
164
+ : message.role === "toolResult"
165
+ ? message.toolCallId
166
+ : message.role === "branchSummary"
167
+ ? message.fromId
168
+ : undefined,
169
+ ]);
170
+ }
@@ -0,0 +1,192 @@
1
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import type { JsonValue } from "@earendil-works/pi-ai";
3
+ import {
4
+ buildSessionProjection,
5
+ type SessionEntry,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import { Type } from "typebox";
8
+ import { Check } from "typebox/value";
9
+
10
+ const READ_KEY = "codexContextNoteRead";
11
+ const READ_SCHEMA = Type.Object(
12
+ {
13
+ protocol: Type.Literal(1),
14
+ origin: Type.Literal("host"),
15
+ id: Type.String({ pattern: "^[a-f0-9-]{36}$" }),
16
+ path: Type.String({ minLength: 1 }),
17
+ namespace: Type.Optional(Type.Literal("notes")),
18
+ api: Type.String({ minLength: 1 }),
19
+ provider: Type.String({ minLength: 1 }),
20
+ model: Type.String({ minLength: 1 }),
21
+ timestamp: Type.Number({ minimum: 0 }),
22
+ content: Type.Array(
23
+ Type.Union([
24
+ Type.Object({ type: Type.Literal("text"), text: Type.String() }),
25
+ Type.Object({
26
+ type: Type.Literal("image"),
27
+ data: Type.String(),
28
+ mimeType: Type.String(),
29
+ detail: Type.Optional(
30
+ Type.Union([
31
+ Type.Literal("auto"),
32
+ Type.Literal("high"),
33
+ Type.Literal("original"),
34
+ ]),
35
+ ),
36
+ }),
37
+ ]),
38
+ ),
39
+ details: Type.Object({
40
+ codexHistoryNotes: Type.Record(Type.String(), Type.Unknown()),
41
+ }),
42
+ },
43
+ { additionalProperties: false },
44
+ );
45
+
46
+ function callId(id: string): string {
47
+ const name = "tree_handoff_" + id.replaceAll("-", "");
48
+ return `${name}|fc_${name}`;
49
+ }
50
+
51
+ function isJson(value: unknown): value is JsonValue {
52
+ return (
53
+ value === null ||
54
+ typeof value === "string" ||
55
+ typeof value === "boolean" ||
56
+ (typeof value === "number" && Number.isFinite(value)) ||
57
+ (Array.isArray(value)
58
+ ? value.every(isJson)
59
+ : typeof value === "object" && Object.values(value).every(isJson))
60
+ );
61
+ }
62
+
63
+ /** Expand only surviving summaries, after Pi compaction and window retirement. */
64
+ export function projectTreeHandoffReads(
65
+ messages: readonly AgentMessage[],
66
+ entries: readonly SessionEntry[],
67
+ ): AgentMessage[] {
68
+ const summaries = new Map(
69
+ entries
70
+ .filter((entry) => entry.type === "branch_summary")
71
+ .map((entry) => [
72
+ JSON.stringify([entry.fromId, new Date(entry.timestamp).getTime()]),
73
+ entry,
74
+ ]),
75
+ );
76
+ const calls = new Set(
77
+ messages.flatMap((message) =>
78
+ message.role === "assistant"
79
+ ? message.content.flatMap((part) =>
80
+ part.type === "toolCall" ? [part.id] : [],
81
+ )
82
+ : [],
83
+ ),
84
+ );
85
+ const results = new Set(
86
+ messages.flatMap((message) =>
87
+ message.role === "toolResult" ? [message.toolCallId] : [],
88
+ ),
89
+ );
90
+ return messages.flatMap((message): AgentMessage[] => {
91
+ if (message.role !== "branchSummary") return [message];
92
+ const details = summaries.get(
93
+ JSON.stringify([message.fromId, message.timestamp]),
94
+ )?.details;
95
+ if (!details || typeof details !== "object" || !(READ_KEY in details))
96
+ return [message];
97
+ const read = details[READ_KEY];
98
+ if (!Check(READ_SCHEMA, read))
99
+ throw new Error("Invalid persisted tree handoff read");
100
+ const resultDetails = read.details;
101
+ if (!isJson(resultDetails))
102
+ throw new Error("Invalid persisted tree handoff result");
103
+ const id = callId(read.id);
104
+ if (calls.has(id) !== results.has(id))
105
+ throw new Error("Incomplete tree handoff read in context");
106
+ if (calls.has(id)) return [message];
107
+ const call = {
108
+ type: "toolCall" as const,
109
+ id,
110
+ name: "notes",
111
+ arguments: { action: "read_file", path: read.path },
112
+ ...(read.namespace
113
+ ? { namespace: read.namespace, responsesNamespace: read.namespace }
114
+ : {}),
115
+ };
116
+ return [
117
+ message,
118
+ {
119
+ role: "assistant",
120
+ api: read.api,
121
+ provider: read.provider,
122
+ model: read.model,
123
+ content: [call],
124
+ // This host operation has no generated tokens or provider response ID.
125
+ usage: {
126
+ input: 0,
127
+ output: 0,
128
+ cacheRead: 0,
129
+ cacheWrite: 0,
130
+ totalTokens: 0,
131
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
132
+ },
133
+ stopReason: "toolUse",
134
+ timestamp: read.timestamp,
135
+ },
136
+ {
137
+ role: "toolResult",
138
+ toolCallId: id,
139
+ toolName: "notes",
140
+ isError: false,
141
+ content: read.content,
142
+ details: resultDetails,
143
+ timestamp: read.timestamp,
144
+ },
145
+ ];
146
+ });
147
+ }
148
+
149
+ /** Compaction-only contributions: never append these entries to the session file.
150
+ * IDs belong to the original summary; Pi's persisted kept boundary stays physical.
151
+ */
152
+ export function projectTreeHandoffBranch(
153
+ entries: readonly SessionEntry[],
154
+ ): readonly SessionEntry[] {
155
+ const projection = buildSessionProjection([...entries]);
156
+ const expanded = projectTreeHandoffReads(projection.messages, entries);
157
+ if (expanded.length === projection.messages.length) return entries;
158
+ const additions = new Map<string, AgentMessage[]>();
159
+ for (const entry of projection.entries) {
160
+ if (entry.sourceEntry.type !== "branch_summary") continue;
161
+ const message = entry.messages.find(
162
+ (item) => item.role === "branchSummary",
163
+ );
164
+ if (!message) continue;
165
+ const offset = expanded.indexOf(message);
166
+ const next = projection.messages[projection.messages.indexOf(message) + 1];
167
+ const end = next ? expanded.indexOf(next) : expanded.length;
168
+ const inserted = expanded.slice(offset + 1, end);
169
+ if (inserted.length) additions.set(entry.sourceEntry.id, inserted);
170
+ }
171
+ const ids = new Set(entries.map((entry) => entry.id));
172
+ let parentId: string | null = null;
173
+ return entries.flatMap((entry): SessionEntry[] => {
174
+ const result: SessionEntry[] = [
175
+ entry.parentId === parentId ? entry : { ...entry, parentId },
176
+ ];
177
+ parentId = entry.id;
178
+ for (const [index, message] of (additions.get(entry.id) ?? []).entries()) {
179
+ const id = entry.id + ":notes-handoff:" + index;
180
+ if (ids.has(id)) throw new Error("Conflicting tree handoff contribution");
181
+ result.push({
182
+ type: "message",
183
+ id,
184
+ parentId,
185
+ timestamp: entry.timestamp,
186
+ message,
187
+ });
188
+ parentId = id;
189
+ }
190
+ return result;
191
+ });
192
+ }
@@ -0,0 +1,105 @@
1
+ import {
2
+ buildSessionProjection,
3
+ type CompactionEntryDraft,
4
+ calculateContextTokens,
5
+ type ExtensionContext,
6
+ estimateTokens,
7
+ getLastAssistantUsage,
8
+ type SessionBeforeCompactEvent,
9
+ type SessionBeforeCompactResult,
10
+ type SessionEntry,
11
+ } from "@earendil-works/pi-coding-agent";
12
+
13
+ const MARKER = "pi-notes-compaction/window-checkpoint";
14
+
15
+ export function isWindowCheckpoint(entry: SessionEntry): boolean {
16
+ return (
17
+ entry.type === "compaction" &&
18
+ entry.details !== null &&
19
+ typeof entry.details === "object" &&
20
+ MARKER in entry.details &&
21
+ entry.details[MARKER] === 1
22
+ );
23
+ }
24
+
25
+ /** Persist one complete native cut, never a partially edited conversation. */
26
+ export class WindowCheckpoints {
27
+ private pending: { session: string; firstKeptEntryId: string } | undefined;
28
+ private readonly project: (
29
+ entries: readonly SessionEntry[],
30
+ ) => SessionEntry[];
31
+
32
+ constructor(project: (entries: readonly SessionEntry[]) => SessionEntry[]) {
33
+ this.project = project;
34
+ }
35
+
36
+ draft(entries: readonly SessionEntry[]): CompactionEntryDraft | undefined {
37
+ const kept = this.project(entries);
38
+ const first = kept[0];
39
+ if (!first || first.id === entries[0]?.id) return;
40
+ const previous = entries.findLast((entry) => entry.type === "compaction");
41
+ if (previous?.firstKeptEntryId === first.id) return;
42
+ return {
43
+ type: "compaction",
44
+ summary: "",
45
+ firstKeptEntryId: first.id,
46
+ details: { [MARKER]: 1 },
47
+ };
48
+ }
49
+
50
+ prepare(
51
+ event: SessionBeforeCompactEvent,
52
+ ctx: ExtensionContext,
53
+ ): SessionBeforeCompactResult | undefined {
54
+ if (!this.pending) return;
55
+ const draft = this.draft(event.branchEntries);
56
+ if (
57
+ event.reason !== "manual" ||
58
+ ctx.sessionManager.getSessionId() !== this.pending.session ||
59
+ draft?.firstKeptEntryId !== this.pending.firstKeptEntryId
60
+ )
61
+ return { cancel: true };
62
+ const kept = this.project(event.branchEntries);
63
+ const messages = buildSessionProjection(kept).messages;
64
+ const usage = getLastAssistantUsage(kept);
65
+ return {
66
+ compaction: {
67
+ summary: draft.summary,
68
+ firstKeptEntryId: this.pending.firstKeptEntryId,
69
+ tokensBefore: usage
70
+ ? calculateContextTokens(usage)
71
+ : messages.reduce(
72
+ (tokens, message) => tokens + estimateTokens(message),
73
+ 0,
74
+ ),
75
+ details: draft.details,
76
+ },
77
+ };
78
+ }
79
+
80
+ /** Align restored sessions before Pi's first request-time structuredClone. */
81
+ async restore(ctx: ExtensionContext): Promise<void> {
82
+ const draft = this.draft(ctx.sessionManager.getBranch());
83
+ if (!draft?.firstKeptEntryId || !ctx.model) return;
84
+ this.pending = {
85
+ session: ctx.sessionManager.getSessionId(),
86
+ firstKeptEntryId: draft.firstKeptEntryId,
87
+ };
88
+ try {
89
+ await new Promise<void>((resolve, reject) => {
90
+ ctx.compact({
91
+ onComplete: () => resolve(),
92
+ onError: (error) => {
93
+ // Pi cannot cut a small conversation yet. The next completed
94
+ // turn can persist the same complete cut as a boundary draft.
95
+ if (error.message === "Nothing to compact (session too small)")
96
+ resolve();
97
+ else reject(error);
98
+ },
99
+ });
100
+ });
101
+ } finally {
102
+ this.pending = undefined;
103
+ }
104
+ }
105
+ }
package/src/windows.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  renderTaskBoundaryReminder,
15
15
  taskBoundaryEligible,
16
16
  } from "./task-boundary.js";
17
+ import { isWindowCheckpoint } from "./window-checkpoint.js";
17
18
 
18
19
  export const WINDOW_MESSAGE = "notes-compaction:window:v1";
19
20
  export const SETTLEMENT_ENTRY = "notes-compaction:settled:v1";
@@ -24,7 +25,7 @@ export interface WindowDetails {
24
25
  trim: boolean;
25
26
  }
26
27
  const GUIDANCE = `<context_window_guidance>
27
- Notes are recovery state, not a diary. Keep one concise, authoritative note per task or topic at a stable path. Task checkpoints cover request, constraints, decisions, status, next steps and history IDs. Use write_file to replace stale state and mark completion. Link to existing notes instead of copying or summarising their contents. Recording isn't permission to implement.
28
+ Notes are recovery state, not a diary. Write checkpoints and reports to relative paths in your own notes. Delegates do likewise and return their note paths. Keep one concise, authoritative note per task or topic at a stable path. Task checkpoints cover request, constraints, decisions, status, next steps and history IDs. Use write_file to replace stale state and mark completion. Link to existing notes instead of copying or summarising their contents. Recording isn't permission to implement.
28
29
 
29
30
  Batch saves at meaningful milestones, not every reply or intermediate step. Before new_context or handoff, save current state and wait for success; include the checkpoint path in handoffs. After rollover, read the checkpoint, then only needed links. Don't reread notes still in context unless they may have changed. Use history for missing details.
30
31
 
@@ -32,11 +33,11 @@ Previous skill reads don’t carry into this window. Read the skills needed for
32
33
  </context_window_guidance>`;
33
34
 
34
35
  const GPT_GUIDANCE = `<context_window_guidance>
35
- Notes=recoverystate≠diary. One concise authoritative note/task-or-topic, stablepath. Taskcheckpoint=request/constraints/decisions/status/nextsteps/historyIDs. write_file→replace stalestate; mark completion. Existingnotes→link≠copy/summarise. Recording≠implementationpermission.
36
+ Notes=recovery state≠diary. Checkpoints/reports→write relative paths in own notes. Delegates→same→return note paths. One concise authoritative note per task/topic, stable path. Task checkpoint=request/constraints/decisions/status/next steps/history IDs. write_file→replace stale state; mark completion. Existing notes→link≠copy/summarise. Recording≠implementation permission.
36
37
 
37
- Savebatch@meaningfulmilestones≠every reply/step. Before new_context/handoff: save currentstate→await success; handoff includes checkpointpath. Postrollover: read checkpoint→neededlinks only. In-context notes: reread only if possiblychanged. Missingdetails→history.
38
+ Batch saves@meaningful milestones≠every reply/step. Before new_context/handoff: save current state→await success; handoff includes checkpoint path. Post-rollover: read checkpoint→needed links only. In-context notes: reread only if possibly changed. Missing details→history.
38
39
 
39
- Prior skillreads≠currentcontext. Read task-relevant skills.
40
+ Prior skill reads≠current context. Read task-relevant skills.
40
41
  </context_window_guidance>`;
41
42
 
42
43
  export function registerWindowRenderer(pi: ExtensionAPI): void {
@@ -225,7 +226,7 @@ export class Windows {
225
226
  this.reminders.add(
226
227
  `${details.identity.currentWindowId}:${details.kind}`,
227
228
  );
228
- if (entry.type === "compaction") {
229
+ if (entry.type === "compaction" && !isWindowCheckpoint(entry)) {
229
230
  // Compaction frees capacity, but does not create a new window identity.
230
231
  this.reminders = new Set(
231
232
  [...this.reminders].filter((key) => key.endsWith(":task-boundary")),
@@ -271,6 +272,7 @@ export class Windows {
271
272
  ctx: ExtensionContext,
272
273
  taskBoundaryReminder = 0,
273
274
  checkpointReminder = true,
275
+ gpt = false,
274
276
  ): CustomMessageEntryDraft | undefined {
275
277
  const { remainingTokens, contextWindow, remainingPercent } =
276
278
  this.remaining(ctx);
@@ -306,8 +308,10 @@ export class Windows {
306
308
  customType: WINDOW_MESSAGE,
307
309
  content:
308
310
  kind === "task-boundary"
309
- ? renderTaskBoundaryReminder(remainingPercent)
310
- : `<context_window_reminder>\n${kind === "urgent" ? "Urgent: " : ""}${remainingPercent}% context remaining. Save the task state in notes, then call new_context ${kind === "urgent" ? "now, before other work" : "before continuing work"}.\n</context_window_reminder>`,
311
+ ? renderTaskBoundaryReminder(remainingPercent, gpt)
312
+ : gpt
313
+ ? `<context_window_reminder>\n${kind === "urgent" ? "Urgent: " : ""}${remainingPercent}% context left; save task state via notes→new_context ${kind === "urgent" ? "now, before other work" : "before continuing work"}.\n</context_window_reminder>`
314
+ : `<context_window_reminder>\n${kind === "urgent" ? "Urgent: " : ""}${remainingPercent}% context remaining. Save the task state in notes, then call new_context ${kind === "urgent" ? "now, before other work" : "before continuing work"}.\n</context_window_reminder>`,
311
315
  display: true,
312
316
  details: {
313
317
  protocol: 1,
@@ -408,8 +412,20 @@ export class Windows {
408
412
  const details = windowDetails(entries[i]!);
409
413
  if (details?.kind === "window" && details.trim) boundary = i;
410
414
  // Normal Pi/PCC compaction has already chosen its own checkpoint.
411
- if (entries[i]!.type === "compaction") boundary = -1;
415
+ if (entries[i]!.type === "compaction" && !isWindowCheckpoint(entries[i]!))
416
+ boundary = -1;
412
417
  }
413
- return entries.slice(Math.max(0, boundary));
418
+ return entries.slice(Math.max(0, boundary)).map(
419
+ (entry): SessionEntry =>
420
+ isWindowCheckpoint(entry)
421
+ ? {
422
+ type: "custom",
423
+ id: entry.id,
424
+ parentId: entry.parentId,
425
+ timestamp: entry.timestamp,
426
+ customType: "notes-compaction:window-checkpoint",
427
+ }
428
+ : entry,
429
+ );
414
430
  }
415
431
  }