pi-context-kit 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "pi-context-kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Context maintenance for Pi: stale read replacement, pruning, handoff compaction with background notes, and recall.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "HugoLopes45 (https://github.com/HugoLopes45)",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/HugoLopes45/pi-context-kit.git"
11
+ },
12
+ "homepage": "https://github.com/HugoLopes45/pi-context-kit#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/HugoLopes45/pi-context-kit/issues"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "pi-extension",
19
+ "pi",
20
+ "compaction",
21
+ "context",
22
+ "handoff"
23
+ ],
24
+ "files": [
25
+ "extensions",
26
+ "src",
27
+ "CHANGELOG.md"
28
+ ],
29
+ "pi": {
30
+ "extensions": [
31
+ "./extensions/index.ts"
32
+ ]
33
+ },
34
+ "scripts": {
35
+ "check": "node scripts/release.ts check && tsc --noEmit && vitest --run",
36
+ "test": "vitest --run",
37
+ "release": "node scripts/release.ts prepare",
38
+ "prepublishOnly": "test -n \"$GITHUB_ACTIONS\" || test \"$(npm whoami)\" = hugolopes45 || { echo 'Publish only as the npm user hugolopes45.' >&2; exit 1; }; npm run check"
39
+ },
40
+ "peerDependencies": {
41
+ "@earendil-works/pi-ai": "*",
42
+ "@earendil-works/pi-coding-agent": "*"
43
+ },
44
+ "devDependencies": {
45
+ "@earendil-works/pi-ai": "^1.0.3",
46
+ "@earendil-works/pi-coding-agent": "^1.0.3",
47
+ "@types/node": "^26.6.4",
48
+ "typescript": "^7.0.2",
49
+ "vitest": "^5.0.3"
50
+ }
51
+ }
@@ -0,0 +1,104 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+
4
+ export interface Note {
5
+ note: string;
6
+ usage?: Usage;
7
+ }
8
+
9
+ export interface BackgroundNote extends Note {
10
+ /** The last entry the note covers. */
11
+ leafId: string;
12
+ }
13
+
14
+ interface Job {
15
+ /** ID of the latest compaction when the job started, or null before the first one. */
16
+ epoch: string | null;
17
+ leafId: string;
18
+ controller: AbortController;
19
+ note: Promise<Note | undefined>;
20
+ settled: boolean;
21
+ }
22
+
23
+ /** One speculative handoff note per compaction epoch, written while the agent keeps working. */
24
+ export class BackgroundHandoff {
25
+ #job: Job | undefined;
26
+
27
+ /** Starts a job unless one already ran in this epoch. */
28
+ start(
29
+ epoch: string | null,
30
+ leafId: string,
31
+ run: (signal: AbortSignal) => Promise<Note | undefined>,
32
+ onError: (error: unknown) => void,
33
+ ): boolean {
34
+ if (this.#job?.epoch === epoch) return false;
35
+ this.cancel();
36
+ const controller = new AbortController();
37
+ const note = run(controller.signal)
38
+ .catch((error: unknown) => {
39
+ if (!controller.signal.aborted) onError(error);
40
+ return undefined;
41
+ })
42
+ .finally(() => {
43
+ job.settled = true;
44
+ });
45
+ const job: Job = { epoch, leafId, controller, note, settled: false };
46
+ this.#job = job;
47
+ return true;
48
+ }
49
+
50
+ /** Whether the note of this epoch is still being written. */
51
+ writing(epoch: string | null): boolean {
52
+ return this.#job?.epoch === epoch && !this.#job.settled;
53
+ }
54
+
55
+ /** Returns a finished note only when it still covers a prefix of the branch. */
56
+ async takeReady(
57
+ epoch: string | null,
58
+ branch: readonly SessionEntry[],
59
+ ): Promise<BackgroundNote | undefined> {
60
+ const job = this.#job;
61
+ if (
62
+ !job ||
63
+ !job.settled ||
64
+ job.epoch !== epoch ||
65
+ !branch.some((entry) => entry.id === job.leafId)
66
+ ) {
67
+ return undefined;
68
+ }
69
+ const note = await job.note;
70
+ return note && { ...note, leafId: job.leafId };
71
+ }
72
+
73
+ /** Cancels work tied to a branch that is no longer active. */
74
+ invalidate(epoch: string | null, branch: readonly SessionEntry[]): void {
75
+ if (
76
+ this.#job &&
77
+ (this.#job.epoch !== epoch ||
78
+ !branch.some((entry) => entry.id === this.#job?.leafId))
79
+ ) {
80
+ this.cancel();
81
+ }
82
+ }
83
+
84
+ cancel(): void {
85
+ this.#job?.controller.abort();
86
+ this.#job = undefined;
87
+ }
88
+ }
89
+
90
+ /** The first entry after `leafId` that may start the kept part of a context. */
91
+ export function firstEntryAfter(
92
+ branch: readonly SessionEntry[],
93
+ leafId: string,
94
+ ): string | undefined {
95
+ const index = branch.findIndex((entry) => entry.id === leafId);
96
+ if (index < 0) return undefined;
97
+ return branch
98
+ .slice(index + 1)
99
+ .find(
100
+ (entry) =>
101
+ entry.type === "custom_message" ||
102
+ (entry.type === "message" && entry.message.role !== "toolResult"),
103
+ )?.id;
104
+ }
package/src/config.ts ADDED
@@ -0,0 +1,228 @@
1
+ import type { PruneOptions } from "./prune.ts";
2
+ import type { ShakeOptions } from "./shake.ts";
3
+
4
+ export interface ContextKitConfig {
5
+ /** Turns off maintenance and handoff compaction. `recall` stays available. */
6
+ enabled: boolean;
7
+ /** Compact above this many tokens. -1 uses `thresholdPercent`. Overrides `thresholdPercent`. */
8
+ thresholdTokens: number;
9
+ /** Compact above this percentage of the context window. -1 uses Pi's threshold only. */
10
+ thresholdPercent: number;
11
+ /** What to try, in order, when the context stays above the threshold after pruning. */
12
+ methodOrder: Method[];
13
+ /** Replace older reads of a file that was read again. */
14
+ supersedeReads: boolean;
15
+ /** Superseded reads are replaced only within this many newest tokens, to keep the prompt cache. */
16
+ staleSuffixTokens: number;
17
+ prune: PruneOptions & { enabled: boolean };
18
+ shake: ShakeOptions;
19
+ /** Pruning and shaking must reach this fraction of the threshold, or compaction runs instead. */
20
+ progressRatio: number;
21
+ /** Write the handoff note in the background before the threshold. */
22
+ asyncEnabled: boolean;
23
+ }
24
+
25
+ /**
26
+ * `handoff`: compact with a note written by the session model.
27
+ * `shake`: elide large blocks and images from older messages, without a model call.
28
+ * `soft`: leave compaction to Pi's own summary.
29
+ */
30
+ export type Method = "handoff" | "shake" | "soft";
31
+
32
+ const METHODS: readonly Method[] = ["handoff", "shake", "soft"];
33
+ /** Methods that oh-my-pi offers and Pi lacks. They are skipped like methods that are unavailable. */
34
+ const UNAVAILABLE: readonly unknown[] = ["remote", "snapcompact"];
35
+
36
+ export const DEFAULT_CONFIG: ContextKitConfig = {
37
+ enabled: true,
38
+ thresholdTokens: -1,
39
+ thresholdPercent: -1,
40
+ methodOrder: [...METHODS],
41
+ supersedeReads: true,
42
+ staleSuffixTokens: 8_000,
43
+ prune: {
44
+ enabled: true,
45
+ protectTokens: 40_000,
46
+ minSavings: 20_000,
47
+ minTokens: 50,
48
+ },
49
+ shake: {
50
+ protectTokens: 16_000,
51
+ minSavings: 4_000,
52
+ blockMinTokens: 400,
53
+ },
54
+ progressRatio: 0.8,
55
+ asyncEnabled: true,
56
+ };
57
+
58
+ export interface ConfigResult {
59
+ config: ContextKitConfig;
60
+ /** One message per invalid value. Each invalid value keeps its default. */
61
+ problems: string[];
62
+ }
63
+
64
+ type Check<T> = { test: (value: unknown) => value is T; must: string };
65
+
66
+ const boolean: Check<boolean> = {
67
+ test: (value) => typeof value === "boolean",
68
+ must: "a boolean",
69
+ };
70
+ const count: Check<number> = {
71
+ test: (value): value is number =>
72
+ Number.isSafeInteger(value) && Number(value) >= 0,
73
+ must: "a non-negative integer",
74
+ };
75
+ const tokens: Check<number> = {
76
+ test: (value): value is number =>
77
+ value === -1 || (Number.isSafeInteger(value) && Number(value) > 0),
78
+ must: "-1 or a positive integer",
79
+ };
80
+ const percent: Check<number> = {
81
+ test: (value): value is number =>
82
+ value === -1 || (typeof value === "number" && value > 0 && value <= 100),
83
+ must: "-1 or a number in (0, 100]",
84
+ };
85
+ const ratio: Check<number> = {
86
+ test: (value): value is number =>
87
+ typeof value === "number" && value > 0 && value <= 1,
88
+ must: "a number in (0, 1]",
89
+ };
90
+
91
+ const isMethod = (value: unknown): value is Method =>
92
+ METHODS.some((method) => method === value);
93
+ const methodOrder: Check<unknown[]> = {
94
+ test: (value): value is unknown[] =>
95
+ Array.isArray(value) &&
96
+ value.every((method) => isMethod(method) || UNAVAILABLE.includes(method)),
97
+ must: 'an array of "handoff", "shake", "soft", "remote" or "snapcompact"',
98
+ };
99
+
100
+ /** Reads the keys of one settings object and reports invalid or unknown keys. */
101
+ class Section {
102
+ readonly #raw: Record<string, unknown>;
103
+ readonly #path: string;
104
+ readonly #problems: string[];
105
+ readonly #known = new Set<string>();
106
+
107
+ constructor(raw: unknown, path: string, problems: string[]) {
108
+ this.#path = path;
109
+ this.#problems = problems;
110
+ if (raw === undefined || isRecord(raw)) this.#raw = raw ?? {};
111
+ else {
112
+ problems.push(`${path} must be an object`);
113
+ this.#raw = {};
114
+ }
115
+ }
116
+
117
+ get<T>(key: string, check: Check<T>, fallback: T): T {
118
+ this.#known.add(key);
119
+ const value = this.#raw[key];
120
+ if (value === undefined) return fallback;
121
+ if (check.test(value)) return value;
122
+ this.#problems.push(`${this.#path}.${key} must be ${check.must}`);
123
+ return fallback;
124
+ }
125
+
126
+ section(key: string): Section {
127
+ this.#known.add(key);
128
+ return new Section(this.#raw[key], `${this.#path}.${key}`, this.#problems);
129
+ }
130
+
131
+ /** Reports keys that no `get` or `section` call read. Call it last. */
132
+ done(): void {
133
+ for (const key of Object.keys(this.#raw))
134
+ if (!this.#known.has(key))
135
+ this.#problems.push(`${this.#path}.${key} is not a setting`);
136
+ }
137
+ }
138
+
139
+ /** Validates the `contextKit` value of Pi's settings. */
140
+ export function readConfig(raw: unknown): ConfigResult {
141
+ const problems: string[] = [];
142
+ const d = DEFAULT_CONFIG;
143
+ const root = new Section(raw, "contextKit", problems);
144
+ const enabled = root.get("enabled", boolean, d.enabled);
145
+ const thresholdTokens = root.get(
146
+ "thresholdTokens",
147
+ tokens,
148
+ d.thresholdTokens,
149
+ );
150
+ const thresholdPercent = root.get(
151
+ "thresholdPercent",
152
+ percent,
153
+ d.thresholdPercent,
154
+ );
155
+ const methods = root.get("methodOrder", methodOrder, d.methodOrder);
156
+ const supersedeReads = root.get("supersedeReads", boolean, d.supersedeReads);
157
+ const staleSuffixTokens = root.get(
158
+ "staleSuffixTokens",
159
+ count,
160
+ d.staleSuffixTokens,
161
+ );
162
+ const progressRatio = root.get("progressRatio", ratio, d.progressRatio);
163
+
164
+ const p = root.section("prune");
165
+ const prune = {
166
+ enabled: p.get("enabled", boolean, d.prune.enabled),
167
+ protectTokens: p.get("protectTokens", count, d.prune.protectTokens),
168
+ minSavings: p.get("minSavings", count, d.prune.minSavings),
169
+ minTokens: p.get("minTokens", count, d.prune.minTokens),
170
+ };
171
+ p.done();
172
+
173
+ const s = root.section("shake");
174
+ const shake = {
175
+ protectTokens: s.get("protectTokens", count, d.shake.protectTokens),
176
+ minSavings: s.get("minSavings", count, d.shake.minSavings),
177
+ blockMinTokens: s.get("blockMinTokens", count, d.shake.blockMinTokens),
178
+ };
179
+ s.done();
180
+
181
+ const asyncEnabled = root.get("asyncEnabled", boolean, d.asyncEnabled);
182
+ root.done();
183
+
184
+ return {
185
+ config: {
186
+ enabled,
187
+ thresholdTokens,
188
+ thresholdPercent,
189
+ methodOrder: [...new Set(methods.filter(isMethod))],
190
+ supersedeReads,
191
+ staleSuffixTokens,
192
+ prune,
193
+ shake,
194
+ progressRatio,
195
+ asyncEnabled,
196
+ },
197
+ problems,
198
+ };
199
+ }
200
+
201
+ export function isRecord(value: unknown): value is Record<string, unknown> {
202
+ return typeof value === "object" && value !== null && !Array.isArray(value);
203
+ }
204
+
205
+ /** The configured threshold for this context window, or +Infinity when only Pi's threshold applies. */
206
+ export function ownThreshold(
207
+ config: ContextKitConfig,
208
+ contextWindow: number,
209
+ ): number {
210
+ if (config.thresholdTokens > 0)
211
+ return Math.min(contextWindow - 1, config.thresholdTokens);
212
+ if (config.thresholdPercent > 0)
213
+ return Math.floor(
214
+ (contextWindow * Math.min(99, config.thresholdPercent)) / 100,
215
+ );
216
+ return Number.POSITIVE_INFINITY;
217
+ }
218
+
219
+ /**
220
+ * How many tokens before the threshold the background note starts: an eighth of the threshold,
221
+ * so the band scales with the window, bounded so small windows do not start a note every turn
222
+ * and large ones do not miss too much history.
223
+ */
224
+ export function speculationLead(threshold: number): number {
225
+ return Number.isFinite(threshold) && threshold > 0
226
+ ? Math.min(32_000, Math.floor(threshold / 8))
227
+ : 0;
228
+ }
package/src/context.ts ADDED
@@ -0,0 +1,108 @@
1
+ import {
2
+ type ContextEditableContent,
3
+ type ContextEditEntryDraft,
4
+ estimateTokens,
5
+ type ProjectedSessionEntry,
6
+ type SessionEntry,
7
+ } from "@earendil-works/pi-coding-agent";
8
+
9
+ export type AgentMessage = ProjectedSessionEntry["messages"][number];
10
+ export type EditableMessage = Extract<
11
+ AgentMessage,
12
+ { role: "user" | "assistant" | "toolResult" | "custom" }
13
+ >;
14
+
15
+ /** A replacement of one entry's model-visible content. */
16
+ export interface Edit {
17
+ targetId: string;
18
+ content: ContextEditableContent;
19
+ }
20
+
21
+ const EDITABLE_ROLES = new Set(["user", "assistant", "toolResult", "custom"]);
22
+
23
+ /** The single editable message an entry contributes, if any. */
24
+ export function editableMessage(
25
+ entry: ProjectedSessionEntry,
26
+ ): EditableMessage | undefined {
27
+ if (entry.messages.length !== 1) return undefined;
28
+ const [message] = entry.messages;
29
+ return message && EDITABLE_ROLES.has(message.role)
30
+ ? (message as EditableMessage)
31
+ : undefined;
32
+ }
33
+
34
+ /** Same rule as Pi's projected estimate: the current system message plus every other message. */
35
+ export function contextTokens(messages: readonly AgentMessage[]): number {
36
+ let system: AgentMessage | undefined;
37
+ let tokens = 0;
38
+ for (const message of messages) {
39
+ if (message.role === "system") system = message;
40
+ else tokens += estimateTokens(message);
41
+ }
42
+ return tokens + (system ? estimateTokens(system) : 0);
43
+ }
44
+
45
+ export function messageTokens(message: AgentMessage): number {
46
+ return estimateTokens(message);
47
+ }
48
+
49
+ /** Tokens from each entry through the end of the projected context. */
50
+ export function suffixTokens(
51
+ entries: readonly ProjectedSessionEntry[],
52
+ ): number[] {
53
+ const suffix = new Array<number>(entries.length).fill(0);
54
+ let total = 0;
55
+ for (let i = entries.length - 1; i >= 0; i--) {
56
+ for (const message of entries[i]?.messages ?? []) {
57
+ if (message.role !== "system") total += estimateTokens(message);
58
+ }
59
+ suffix[i] = total;
60
+ }
61
+ return suffix;
62
+ }
63
+
64
+ export function withContent(
65
+ message: EditableMessage,
66
+ content: ContextEditableContent,
67
+ ): EditableMessage {
68
+ return { ...message, content } as EditableMessage;
69
+ }
70
+
71
+ /** Applies edits to projected entries without mutating them. */
72
+ export function applyEdits(
73
+ entries: readonly ProjectedSessionEntry[],
74
+ edits: readonly Edit[],
75
+ ): ProjectedSessionEntry[] {
76
+ if (edits.length === 0) return [...entries];
77
+ const byId = new Map(edits.map((edit) => [edit.targetId, edit.content]));
78
+ return entries.map((entry) => {
79
+ const content = byId.get(entry.sourceEntry.id);
80
+ const message = editableMessage(entry);
81
+ return content !== undefined && message
82
+ ? { ...entry, messages: [withContent(message, content)] }
83
+ : entry;
84
+ });
85
+ }
86
+
87
+ export function projectedMessages(
88
+ entries: readonly ProjectedSessionEntry[],
89
+ ): AgentMessage[] {
90
+ return entries.flatMap((entry) => entry.messages);
91
+ }
92
+
93
+ /** Entry IDs that already have a context edit on the branch. */
94
+ export function editedEntryIds(branch: readonly SessionEntry[]): Set<string> {
95
+ const ids = new Set<string>();
96
+ for (const entry of branch) {
97
+ if (entry.type === "context_edit") ids.add(entry.targetId);
98
+ }
99
+ return ids;
100
+ }
101
+
102
+ export function toDrafts(edits: readonly Edit[]): ContextEditEntryDraft[] {
103
+ return edits.map((edit) => ({
104
+ type: "context_edit",
105
+ targetId: edit.targetId,
106
+ replacement: { content: edit.content },
107
+ }));
108
+ }
package/src/files.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+
3
+ /** Same shape as the details of Pi's default compaction. */
4
+ export interface FileLists {
5
+ readFiles: string[];
6
+ modifiedFiles: string[];
7
+ }
8
+
9
+ /**
10
+ * Files read, written or edited on the whole branch, including calls made from codemode scripts.
11
+ * The raw branch keeps compacted entries, so the lists stay cumulative across every compaction.
12
+ */
13
+ export function fileLists(branch: readonly SessionEntry[]): FileLists {
14
+ const read = new Set<string>();
15
+ const modified = new Set<string>();
16
+ const add = (name: string, args: Record<string, unknown> | undefined) => {
17
+ const path = args?.path;
18
+ if (typeof path !== "string" || path.length === 0) return;
19
+ if (name === "read") read.add(path);
20
+ else if (name === "write" || name === "edit") modified.add(path);
21
+ };
22
+ for (const entry of branch) {
23
+ if (entry.type !== "message") continue;
24
+ const { message } = entry;
25
+ if (message.role === "assistant") {
26
+ for (const block of message.content) {
27
+ if (block.type === "toolCall") add(block.name, block.arguments);
28
+ }
29
+ } else if (message.role === "toolResult") {
30
+ for (const call of message.nestedCalls?.calls ?? [])
31
+ add(call.name, call.arguments);
32
+ }
33
+ }
34
+ return {
35
+ readFiles: [...read].filter((path) => !modified.has(path)).sort(),
36
+ modifiedFiles: [...modified].sort(),
37
+ };
38
+ }
39
+
40
+ /** The file sections Pi appends to its own compaction summaries. */
41
+ export function formatFileLists({
42
+ readFiles,
43
+ modifiedFiles,
44
+ }: FileLists): string {
45
+ const sections: string[] = [];
46
+ if (readFiles.length > 0)
47
+ sections.push(`<read-files>\n${readFiles.join("\n")}\n</read-files>`);
48
+ if (modifiedFiles.length > 0) {
49
+ sections.push(
50
+ `<modified-files>\n${modifiedFiles.join("\n")}\n</modified-files>`,
51
+ );
52
+ }
53
+ return sections.join("\n\n");
54
+ }
package/src/handoff.ts ADDED
@@ -0,0 +1,83 @@
1
+ import type { AssistantMessage, Context, Message } from "@earendil-works/pi-ai";
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import { type FileLists, fileLists, formatFileLists } from "./files.ts";
4
+
5
+ /** Asks for the sections of Pi's own compaction summary, written from the live context. */
6
+ const HANDOFF_PROMPT = `Your context is about to be replaced by a handoff note. Write that note now so you can continue this work without any other memory of the conversation. Do not call tools. Reply with the note only, in markdown, using exactly these sections:
7
+
8
+ ## Goal
9
+ What the user is trying to accomplish.
10
+
11
+ ## Constraints & Preferences
12
+ - Every requirement and preference the user stated.
13
+
14
+ ## Progress
15
+ ### Done
16
+ - [x] Finished work, with its evidence (commands, results).
17
+ ### In Progress
18
+ - [ ] Current work and its exact state.
19
+ ### Blocked
20
+ - Open issues, if any.
21
+
22
+ ## Key Decisions
23
+ - **Decision**: why it was made, and approaches rejected.
24
+
25
+ ## Next Steps
26
+ 1. The remaining actions, in order.
27
+
28
+ ## Critical Context
29
+ - Paths, identifiers, commands, values and error messages needed to continue, quoted exactly.
30
+
31
+ The most recent messages stay visible after the note, but cover them too. Be dense and specific.`;
32
+
33
+ /** The live conversation plus a final request for a handoff note, so the cached prefix is reused. */
34
+ export function handoffContext(
35
+ messages: readonly Message[],
36
+ focus?: string,
37
+ ): Context {
38
+ const text = focus?.trim()
39
+ ? `${HANDOFF_PROMPT}\n\nGive extra attention to: ${focus.trim()}`
40
+ : HANDOFF_PROMPT;
41
+ return {
42
+ messages: [
43
+ ...messages,
44
+ {
45
+ role: "user",
46
+ content: [{ type: "text", text }],
47
+ timestamp: Date.now(),
48
+ },
49
+ ],
50
+ };
51
+ }
52
+
53
+ /** The note in a handoff response. Throws when the request failed. */
54
+ export function handoffNote(response: AssistantMessage): string | undefined {
55
+ if (
56
+ response.stopReason === "error" ||
57
+ response.stopReason === "aborted" ||
58
+ response.stopReason === "length"
59
+ ) {
60
+ throw new Error(
61
+ response.errorMessage ?? `Handoff request ${response.stopReason}`,
62
+ );
63
+ }
64
+ // Text next to a tool call is a preamble to more work, not a note.
65
+ if (response.content.some((block) => block.type === "toolCall")) {
66
+ throw new Error("Handoff request called a tool");
67
+ }
68
+ const note = response.content
69
+ .flatMap((block) => (block.type === "text" ? [block.text] : []))
70
+ .join("\n")
71
+ .trim();
72
+ return note || undefined;
73
+ }
74
+
75
+ /** The compaction summary and details for a note, with Pi's cumulative file sections. */
76
+ export function handoffSummary(
77
+ note: string,
78
+ branch: readonly SessionEntry[],
79
+ ): { summary: string; details: FileLists } {
80
+ const details = fileLists(branch);
81
+ const files = formatFileLists(details);
82
+ return { summary: files ? `${note}\n\n${files}` : note, details };
83
+ }