@howaboua/pi-notes-compaction 0.0.5 → 0.0.6

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.
@@ -0,0 +1,377 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type {
3
+ ExtensionContext,
4
+ SessionEntry,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import { type Static, Type } from "typebox";
7
+ import { Check } from "typebox/value";
8
+ import { collectNotes, normalizeNoteParams, readNotes } from "./notes.js";
9
+ import {
10
+ readSavedNotesSession,
11
+ type SavedNotesSession,
12
+ } from "./saved-session.js";
13
+ import type { NotesStore } from "./store.js";
14
+
15
+ const Agent = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
16
+ const Identity = Type.Object({
17
+ protocol: Type.Literal(1),
18
+ sessionId: Type.String(),
19
+ threadId: Type.String(),
20
+ agentName: Agent,
21
+ storage: Type.Optional(
22
+ Type.Union([Type.Literal("session"), Type.Literal("remote")]),
23
+ ),
24
+ routing: Type.Optional(Type.Unknown()),
25
+ });
26
+ const Member = Type.Object({
27
+ threadId: Type.String(),
28
+ sessionId: Type.String(),
29
+ agentName: Agent,
30
+ machine: Type.String(),
31
+ sessionFile: Type.String(),
32
+ });
33
+ const Plan = Type.Object({
34
+ controllerSessionId: Type.String(),
35
+ targetSessionId: Type.String(),
36
+ context: Type.Optional(
37
+ Type.Object({
38
+ controller: Identity,
39
+ target: Identity,
40
+ alias: Agent,
41
+ controllerAlias: Agent,
42
+ controllerFile: Type.Optional(Type.String()),
43
+ controllerNotes: Type.Unknown(),
44
+ targetNotes: Type.Unknown(),
45
+ }),
46
+ ),
47
+ });
48
+ const Route = Type.Object({
49
+ plan: Plan,
50
+ machine: Type.String(),
51
+ sessionFile: Type.String(),
52
+ phase: Type.Union([Type.Literal("pending"), Type.Literal("ready")]),
53
+ detached: Type.Optional(
54
+ Type.Object({ context: Type.Optional(Type.Unknown()) }),
55
+ ),
56
+ });
57
+ const Detachment = Type.Object({
58
+ plan: Plan,
59
+ context: Type.Optional(Type.Unknown()),
60
+ });
61
+ const Snapshot = Type.Object({
62
+ protocol: Type.Literal(1),
63
+ timestamp: Type.Number(),
64
+ files: Type.Array(
65
+ Type.Object({
66
+ path: Type.String(),
67
+ text: Type.String(),
68
+ createdAt: Type.Number(),
69
+ updatedAt: Type.Number(),
70
+ operation: Type.Union([
71
+ Type.Literal("local_append_overlay"),
72
+ Type.Literal("local_replacement"),
73
+ ]),
74
+ }),
75
+ ),
76
+ });
77
+ const Parent = Type.Object({
78
+ transport: Type.Literal("shepherdr"),
79
+ parent: Type.String(),
80
+ });
81
+ type Identity = Static<typeof Identity>;
82
+
83
+ function records(session: SavedNotesSession, kind: string): unknown[] {
84
+ return session.entries.flatMap((entry) =>
85
+ entry.type === "custom" && entry.customType === kind ? [entry.data] : [],
86
+ );
87
+ }
88
+
89
+ /** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
90
+ export function savedNotesIdentity(
91
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
92
+ ): Identity {
93
+ let found: Identity | undefined;
94
+ for (const entry of session.entries) {
95
+ if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
96
+ continue;
97
+ if (!Check(Identity, entry.data))
98
+ throw new Error("Invalid saved notes identity");
99
+ if (entry.data.threadId !== session.threadId) continue;
100
+ if (found) throw new Error("Conflicting saved notes identities");
101
+ found = entry.data;
102
+ }
103
+ return (
104
+ found ?? {
105
+ protocol: 1,
106
+ threadId: session.threadId,
107
+ sessionId: session.threadId,
108
+ agentName: "/root",
109
+ }
110
+ );
111
+ }
112
+
113
+ function sameOwner(a: Identity, b: Identity): boolean {
114
+ return (
115
+ a.threadId === b.threadId &&
116
+ a.sessionId === b.sessionId &&
117
+ a.agentName === b.agentName
118
+ );
119
+ }
120
+ function inside(path: string, root: string): boolean {
121
+ return path === root || path.startsWith(`${root}/`);
122
+ }
123
+ function remap(
124
+ params: Record<string, unknown>,
125
+ from: string,
126
+ to: string,
127
+ ): Record<string, unknown> {
128
+ return Object.fromEntries(
129
+ Object.entries(params).map(([key, value]) => [
130
+ key,
131
+ ["path", "prefix", "path_prefix"].includes(key) &&
132
+ typeof value === "string" &&
133
+ inside(value, from)
134
+ ? `${to}${value.slice(from.length)}`
135
+ : value,
136
+ ]),
137
+ );
138
+ }
139
+
140
+ export function sharedNotesUnavailable(error: unknown): boolean {
141
+ return (
142
+ error instanceof Error &&
143
+ /^(Cross-agent (?:context requires an available context router|notes (?:are unavailable here|owner is unavailable))|Shared context (?:owner|controller) is unavailable|Shared context response was lost|Herdr machine .* is (?:unavailable|disconnected)|remote Shepherdr bridge (?:is unavailable|closed|exited\b)|remote Shepherdr context timed out)/.test(
144
+ error.message,
145
+ )
146
+ );
147
+ }
148
+
149
+ /** Saved local notes do not need PCC, a router, or a running owner. Writes still belong to the live session. */
150
+ export async function readSharedNotes(
151
+ ctx: ExtensionContext,
152
+ store: Pick<NotesStore, "read">,
153
+ params: Record<string, unknown>,
154
+ signal?: AbortSignal,
155
+ ): Promise<Record<string, unknown> | undefined> {
156
+ if (
157
+ !["read_file", "list_files_by_prefix", "search_contents"].includes(
158
+ String(params["action"]),
159
+ )
160
+ )
161
+ return;
162
+ const path = params["path"] ?? params["prefix"] ?? params["path_prefix"];
163
+ if (typeof path !== "string" || !path.startsWith("/")) return;
164
+ const target = /^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(
165
+ path,
166
+ )?.[1];
167
+ if (!target) return;
168
+ const outputAgent = target;
169
+ const current: SavedNotesSession = {
170
+ threadId: ctx.sessionManager.getSessionId(),
171
+ entries: ctx.sessionManager.getEntries(),
172
+ branch: ctx.sessionManager.getBranch(),
173
+ };
174
+ if (savedNotesIdentity(current).agentName === target) return;
175
+ const visited = new Set<string>();
176
+
177
+ function read(
178
+ session: SavedNotesSession,
179
+ query: Record<string, unknown>,
180
+ native: string,
181
+ ) {
182
+ return {
183
+ ...readNotes(
184
+ collectNotes(store, session.branch),
185
+ normalizeNoteParams(query, native),
186
+ outputAgent,
187
+ ),
188
+ source: "saved-session",
189
+ read_only: true,
190
+ remote: { state: "not_fetched" },
191
+ ...(session.savedAt === undefined
192
+ ? {}
193
+ : { saved_at: new Date(session.savedAt).toISOString() }),
194
+ };
195
+ }
196
+ async function reference(
197
+ identity: Identity,
198
+ destination: string,
199
+ query: Record<string, unknown>,
200
+ file: string | undefined,
201
+ retained?: unknown,
202
+ detached = false,
203
+ ): Promise<Record<string, unknown> | undefined> {
204
+ if (file && !detached) {
205
+ let saved: SavedNotesSession | undefined;
206
+ try {
207
+ saved = await readSavedNotesSession(file, signal);
208
+ } catch (error) {
209
+ signal?.throwIfAborted();
210
+ if (
211
+ !(
212
+ error instanceof Error &&
213
+ "code" in error &&
214
+ error.code === "ENOENT" &&
215
+ retained !== undefined
216
+ )
217
+ )
218
+ throw error;
219
+ }
220
+ if (saved) {
221
+ if (!sameOwner(savedNotesIdentity(saved), identity))
222
+ throw new Error("Saved shared notes belong to a different session");
223
+ return resolve(saved, destination, query);
224
+ }
225
+ }
226
+ if (destination !== identity.agentName || !Check(Snapshot, retained))
227
+ return;
228
+ const entry: SessionEntry = {
229
+ type: "custom",
230
+ id: "retained",
231
+ parentId: null,
232
+ timestamp: new Date(retained.timestamp).toISOString(),
233
+ customType: "codex-context-note-snapshot",
234
+ data: {
235
+ ...retained,
236
+ files: retained.files.filter((file) =>
237
+ file.path.startsWith(`${identity.agentName}/notes/`),
238
+ ),
239
+ },
240
+ };
241
+ return {
242
+ ...read(
243
+ { threadId: identity.threadId, entries: [], branch: [entry] },
244
+ query,
245
+ identity.agentName,
246
+ ),
247
+ source: "retained-checkpoints",
248
+ captured_at: new Date(retained.timestamp).toISOString(),
249
+ ...(detached ? { detached: true } : { stale: true }),
250
+ };
251
+ }
252
+ async function resolve(
253
+ session: SavedNotesSession,
254
+ destination: string,
255
+ query: Record<string, unknown>,
256
+ ): Promise<Record<string, unknown> | undefined> {
257
+ signal?.throwIfAborted();
258
+ if (visited.has(session.threadId)) return;
259
+ visited.add(session.threadId);
260
+ const identity = savedNotesIdentity(session);
261
+ if (identity.agentName === destination) {
262
+ if (
263
+ identity.storage === "remote" &&
264
+ !session.branch.some(
265
+ (entry) =>
266
+ entry.type === "custom" &&
267
+ entry.customType === "notes-compaction:note:v1",
268
+ )
269
+ )
270
+ return;
271
+ return read(session, query, identity.agentName);
272
+ }
273
+ const routes = new Map<string, Static<typeof Route>>();
274
+ for (const value of records(session, "shepherdr-attachment-route"))
275
+ if (
276
+ Check(Route, value) &&
277
+ value.plan.controllerSessionId === identity.threadId
278
+ )
279
+ routes.set(`${value.machine}\0${value.sessionFile}`, value);
280
+ for (const route of routes.values()) {
281
+ const link = route.plan.context;
282
+ if (route.phase !== "ready" || !link || !inside(destination, link.alias))
283
+ continue;
284
+ if (!sameOwner(identity, link.controller))
285
+ throw new Error("Saved shared notes identity changed");
286
+ return reference(
287
+ link.target,
288
+ `${link.target.agentName}${destination.slice(link.alias.length)}`,
289
+ remap(query, link.alias, link.target.agentName),
290
+ route.machine === "local" ? route.sessionFile : undefined,
291
+ route.detached?.context ?? link.targetNotes,
292
+ route.detached?.context !== undefined,
293
+ );
294
+ }
295
+ const owner = records(session, "shepherdr-attachment-owner").findLast(
296
+ (value) =>
297
+ Check(Plan, value) && value.targetSessionId === identity.threadId,
298
+ );
299
+ if (
300
+ Check(Plan, owner) &&
301
+ owner.context &&
302
+ inside(destination, owner.context.controllerAlias)
303
+ ) {
304
+ const link = owner.context;
305
+ if (!sameOwner(identity, link.target))
306
+ throw new Error("Saved shared notes identity changed");
307
+ const detached = records(
308
+ session,
309
+ "shepherdr-attachment-detached",
310
+ ).findLast(
311
+ (value) =>
312
+ Check(Detachment, value) && isDeepStrictEqual(value.plan, owner),
313
+ );
314
+ const snapshot = Check(Detachment, detached)
315
+ ? detached.context
316
+ : undefined;
317
+ return reference(
318
+ link.controller,
319
+ `${link.controller.agentName}${destination.slice(link.controllerAlias.length)}`,
320
+ remap(query, link.controllerAlias, link.controller.agentName),
321
+ link.controllerFile,
322
+ snapshot ?? link.controllerNotes,
323
+ snapshot !== undefined,
324
+ );
325
+ }
326
+ const member = records(session, "herdr-context-child").findLast(
327
+ (value) =>
328
+ Check(Member, value) &&
329
+ value.threadId === identity.threadId &&
330
+ value.sessionId === identity.sessionId &&
331
+ inside(destination, value.agentName),
332
+ );
333
+ if (Check(Member, member)) {
334
+ if (member.machine !== "local") return;
335
+ const saved = await readSavedNotesSession(member.sessionFile, signal);
336
+ const child = savedNotesIdentity(saved);
337
+ if (
338
+ child.sessionId !== identity.sessionId ||
339
+ child.agentName !== member.agentName
340
+ )
341
+ throw new Error(
342
+ "Saved shared notes belong to a different agent family",
343
+ );
344
+ return resolve(saved, destination, query);
345
+ }
346
+ const routing = identity.routing;
347
+ const suffix = ".jsonl.shepherdr-context.json";
348
+ if (Check(Parent, routing) && routing.parent.endsWith(suffix)) {
349
+ const saved = await readSavedNotesSession(
350
+ routing.parent.slice(0, -".shepherdr-context.json".length),
351
+ signal,
352
+ );
353
+ const parent = savedNotesIdentity(saved);
354
+ if (
355
+ parent.sessionId !== identity.sessionId ||
356
+ !identity.agentName.startsWith(`${parent.agentName}/`)
357
+ )
358
+ throw new Error("Saved shared notes parent identity changed");
359
+ return resolve(saved, destination, query);
360
+ }
361
+ return undefined;
362
+ }
363
+ try {
364
+ return await resolve(current, target, params);
365
+ } catch (error) {
366
+ if (
367
+ error instanceof Error &&
368
+ "code" in error &&
369
+ ["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
370
+ )
371
+ throw new Error(
372
+ "Saved shared notes are unavailable on this machine. Restore access to the saved session, then retry.",
373
+ { cause: error },
374
+ );
375
+ throw error;
376
+ }
377
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  export function renderTaskBoundaryReminder(remainingPercent: number): string {
4
- return `<context_window_reminder>\nThis window is approaching the recommended token budget. You still have ${remainingPercent}% of your context window remaining, so there is no need to start a new window immediately. If you are working through a sequence of tasks toward a larger goal, finish the current task, save a checkpoint, and start a new window before continuing with the next task. Otherwise, continue here.\n</context_window_reminder>`;
4
+ return `<context_window_reminder>\nSuggested context budget reached; ${remainingPercent}% remains. For a sequence of tasks, finish the current task, save notes and call new_context before the next. Otherwise, continue here.\n</context_window_reminder>`;
5
5
  }
6
6
 
7
7
  export const TASK_BOUNDARY_PRESETS = [
package/src/tools.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  sourceSessionIds,
25
25
  useNotes,
26
26
  } from "./notes.js";
27
+ import { readSharedNotes, sharedNotesUnavailable } from "./shared-notes.js";
27
28
  import type { NotesStore } from "./store.js";
28
29
 
29
30
  const NOTES_ACTIONS = [
@@ -223,8 +224,7 @@ function discovery(
223
224
  ),
224
225
  ...(namespace === "notes"
225
226
  ? {
226
- usage:
227
- 'await tools.notes({ action: "read_file", path: "checkpoint" })',
227
+ usage: '{ "action": "read_file", "path": "checkpoint" }',
228
228
  ranges:
229
229
  "start_line/stop_line inclusive, 1-based; negative counts from end; 0/null/omitted uses first/last line; out-of-range clamps; reversed range returns empty content",
230
230
  defaults:
@@ -348,7 +348,9 @@ function createQueryExecutor(
348
348
  ) {
349
349
  const assertActive = () => {
350
350
  if (!lifecycle.active)
351
- throw new Error("Notes continuity is unavailable in this session");
351
+ throw new Error(
352
+ "Notes tools are inactive. Ask the user to check /notes.",
353
+ );
352
354
  };
353
355
  async function notes(
354
356
  callId: string,
@@ -360,15 +362,25 @@ function createQueryExecutor(
360
362
  if (help) return help;
361
363
  assertActive();
362
364
  const raw = relevant("notes", input);
363
- const routed =
364
- !shared &&
365
- (await lifecycle.bridge?.route?.(
366
- { namespace: "notes", params: raw },
367
- callId,
368
- ctx,
369
- signal,
370
- ));
371
- if (routed) return routed;
365
+ if (!shared) {
366
+ try {
367
+ const routed = await lifecycle.bridge?.route?.(
368
+ { namespace: "notes", params: raw },
369
+ callId,
370
+ ctx,
371
+ signal,
372
+ );
373
+ if (routed) return routed;
374
+ } catch (error) {
375
+ signal?.throwIfAborted();
376
+ if (!sharedNotesUnavailable(error)) throw error;
377
+ const saved = await readSharedNotes(ctx, store, raw, signal);
378
+ if (saved) return result(saved);
379
+ throw error;
380
+ }
381
+ const saved = await readSharedNotes(ctx, store, raw, signal);
382
+ if (saved) return result(saved);
383
+ }
372
384
  const params = relevant(
373
385
  "notes",
374
386
  normalizeNoteParams(raw, lifecycle.agent(ctx)),
@@ -509,7 +521,9 @@ export function createTools(
509
521
  ): ToolDefinition[] {
510
522
  const assertActive = () => {
511
523
  if (!lifecycle.active)
512
- throw new Error("Notes continuity is unavailable in this session");
524
+ throw new Error(
525
+ "Notes tools are inactive. Ask the user to check /notes.",
526
+ );
513
527
  };
514
528
  const queries = createQueryExecutor(pi, store, lifecycle);
515
529
  return [
@@ -517,14 +531,14 @@ export function createTools(
517
531
  name: "notes",
518
532
  label: "notes",
519
533
  description:
520
- "Cross-window notes. write_file replaces; append_to_file adds. Virtual paths: relative uses current agent; cross-agent uses <agent>/notes[/path].",
534
+ "Persistent notes. write_file replaces; append_to_file adds. Virtual paths: relative uses current agent; cross-agent uses <agent>/notes[/path].",
521
535
  parameters: NOTES_SCHEMA,
522
536
  executionMode: "sequential",
523
537
  prepareArguments(args) {
524
538
  if (args === undefined) return {};
525
539
  if (!args || typeof args !== "object" || Array.isArray(args))
526
540
  throw new Error(
527
- 'Supply an action object: await tools.notes({ action: "read_file", path: "checkpoint" }); tools.notes() returns help',
541
+ 'Supply an action object, e.g. { "action": "read_file", "path": "checkpoint" }. Use {} for help',
528
542
  );
529
543
  const params = { ...args } as Record<string, unknown>;
530
544
  if (
@@ -551,7 +565,7 @@ export function createTools(
551
565
  ];
552
566
  if (!schema || !Check(schema, value))
553
567
  throw new Error(
554
- `Invalid notes ${field}; call tools.notes() for exact arguments`,
568
+ `Invalid notes ${field}; use {} for exact arguments`,
555
569
  );
556
570
  }
557
571
  return params;
@@ -563,7 +577,7 @@ export function createTools(
563
577
  name: "history",
564
578
  label: "history",
565
579
  description:
566
- "Prior-window detail. Pass IDs unchanged. Search, never browse",
580
+ "Search earlier conversation, don't browse it. Pass returned IDs unchanged",
567
581
  parameters: HISTORY_SCHEMA,
568
582
  prepareArguments(args) {
569
583
  return args === undefined ? {} : args;
@@ -574,22 +588,23 @@ export function createTools(
574
588
  {
575
589
  name: "new_context",
576
590
  label: "new_context",
577
- description: "Start a new context window",
591
+ description:
592
+ "Start fresh from saved notes; recover earlier conversation through history",
578
593
  parameters: Type.Object({}, { additionalProperties: false }),
579
594
  exposure: "model-only",
580
595
  executionMode: "sequential",
581
- async execute(_id, _input, signal, _update, ctx) {
596
+ async execute(id, _input, signal, _update, ctx) {
582
597
  assertActive();
583
598
  if (signal?.aborted) throw new Error("Rollover cancelled");
584
- const started = lifecycle.requestRollover(ctx);
599
+ const started = lifecycle.requestRollover(ctx, id);
585
600
  if (started) ctx.abort();
586
601
  return {
587
602
  ...result({
588
603
  started,
589
604
  message: started
590
- ? lifecycle.normalCompaction
591
- ? "Normal compaction will run before the new window opens"
592
- : "A new window will continue from your notes after this run settles"
605
+ ? lifecycle.newWindowRequests === "pi-limits"
606
+ ? "Window request queued. Pi will check whether enough history can be compacted"
607
+ : "A new window will open after this run settles"
593
608
  : "A checkpoint or rollover is already pending. Save notes and finish your response",
594
609
  }),
595
610
  ...(started ? { terminate: true } : {}),
package/src/windows.ts CHANGED
@@ -9,7 +9,7 @@ import type {
9
9
  } from "@earendil-works/pi-coding-agent";
10
10
  import { keyHint } from "@earendil-works/pi-coding-agent";
11
11
  import { Box, Text, TruncatedText } from "@earendil-works/pi-tui";
12
- import type { WindowIdentity } from "./bridge.js";
12
+ import type { NotesBridge, WindowIdentity } from "./bridge.js";
13
13
  import {
14
14
  renderTaskBoundaryReminder,
15
15
  taskBoundaryEligible,
@@ -24,9 +24,9 @@ export interface WindowDetails {
24
24
  trim: boolean;
25
25
  }
26
26
  const GUIDANCE = `<context_window_guidance>
27
- Keep one checkpoint per task at a stable path: request, constraints, decisions, progress, next steps, history IDs. Replace stale state; mark completion in place. Keep reusable findings and deferred ideas in separate topic notes; link, don't copy. Recording isn't permission to implement.
27
+ Notes persist across windows. Keep one checkpoint per task at a stable path, covering the request, constraints, decisions, progress, next steps and history IDs so you can resume without rereading the conversation. Replace stale state; mark completion in place. Keep reusable findings and deferred ideas in separate topic notes; link, don't copy. Recording isn't permission to implement.
28
28
 
29
- Save changed state after substantial work, before replying, and before new_context or handoff. Skip routine or unchanged state. Include checkpoint paths in handoffs. After rollover, read the checkpoint, then linked notes as needed; history only for missing details.
29
+ Save changed state after substantial work, before replying, and before new_context or handoff. Skip routine or unchanged state. Include checkpoint paths in handoffs. After rollover, read the checkpoint, then linked notes as needed. History retrieves earlier conversation; use it only for missing details.
30
30
  </context_window_guidance>`;
31
31
 
32
32
  export function registerWindowRenderer(pi: ExtensionAPI): void {
@@ -177,17 +177,34 @@ export function windowMessage(
177
177
 
178
178
  export class Windows {
179
179
  current: WindowIdentity | undefined;
180
+ private identityEntry:
181
+ | Extract<SessionEntry, { type: "custom_message" }>
182
+ | undefined;
183
+ private restoredIdentity:
184
+ | {
185
+ entryId: string;
186
+ timestamp: number;
187
+ prepare: NotesBridge["prepareReminder"];
188
+ message: AgentMessage;
189
+ }
190
+ | undefined;
180
191
  private compactedSinceBoundary = false;
181
192
  private reminders = new Set<string>();
182
193
  restore(entries: readonly SessionEntry[]): void {
183
194
  this.current = undefined;
195
+ this.identityEntry = undefined;
184
196
  this.compactedSinceBoundary = false;
185
197
  this.reminders.clear();
186
198
  for (const entry of entries) {
187
199
  const details = windowDetails(entry);
200
+ if (
201
+ entry.type === "custom_message" &&
202
+ (details?.kind === "window" || details?.kind === "identity")
203
+ )
204
+ this.identityEntry = entry;
188
205
  if (details?.kind === "window") {
189
206
  this.current = details.identity;
190
- this.compactedSinceBoundary = false;
207
+ if (details.trim) this.compactedSinceBoundary = false;
191
208
  } else if (
192
209
  details &&
193
210
  (details.kind === "reminder" ||
@@ -279,7 +296,7 @@ export class Windows {
279
296
  content:
280
297
  kind === "task-boundary"
281
298
  ? renderTaskBoundaryReminder(remainingPercent)
282
- : `<context_window_reminder>\n${kind === "urgent" ? "Urgent: " : ""}${remainingPercent}% remaining. Checkpoint the active request, state and known history IDs in notes, then call new_context ${kind === "urgent" ? "now, before other work" : "before continuing work"}.\n</context_window_reminder>`,
299
+ : `<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>`,
283
300
  display: true,
284
301
  details: {
285
302
  protocol: 1,
@@ -289,8 +306,74 @@ export class Windows {
289
306
  } satisfies WindowDetails,
290
307
  };
291
308
  }
292
- projectMessages(messages: readonly AgentMessage[]): AgentMessage[] {
293
- if (this.compactedSinceBoundary) return [...messages];
309
+ projectMessages(
310
+ messages: readonly AgentMessage[],
311
+ prepareIdentity?: NotesBridge["prepareReminder"],
312
+ ): AgentMessage[] {
313
+ if (this.compactedSinceBoundary) {
314
+ const summary = messages.findIndex(
315
+ (message) => message.role === "compactionSummary",
316
+ );
317
+ const entry = this.identityEntry;
318
+ const details = entry && windowDetails(entry);
319
+ const hasIdentity = messages.some((message) => {
320
+ const current =
321
+ message.role === "custom" &&
322
+ messageWindowDetails(message.customType, message.details);
323
+ return (
324
+ current &&
325
+ (current.kind === "window" || current.kind === "identity") &&
326
+ current.identity.currentWindowId === this.current?.currentWindowId
327
+ );
328
+ });
329
+ if (
330
+ summary < 0 ||
331
+ messages[0]?.role !== "system" ||
332
+ !entry ||
333
+ !details ||
334
+ typeof entry.content !== "string" ||
335
+ hasIdentity
336
+ )
337
+ return [...messages];
338
+ const timestamp = messages[summary]!.timestamp;
339
+ if (
340
+ this.restoredIdentity?.entryId !== entry.id ||
341
+ this.restoredIdentity.timestamp !== timestamp ||
342
+ this.restoredIdentity.prepare !== prepareIdentity
343
+ ) {
344
+ const draft: CustomMessageEntryDraft = {
345
+ type: "custom_message",
346
+ customType: WINDOW_MESSAGE,
347
+ content: `${entry.content}\n\nIf no checkpoint is available, use history to recover missing context.`,
348
+ display: false,
349
+ details: {
350
+ ...details,
351
+ kind: "identity",
352
+ trim: false,
353
+ } satisfies WindowDetails,
354
+ };
355
+ const prepared = prepareIdentity?.(draft) ?? draft;
356
+ this.restoredIdentity = {
357
+ entryId: entry.id,
358
+ timestamp,
359
+ prepare: prepareIdentity,
360
+ message: {
361
+ role: "custom",
362
+ customType: prepared.customType,
363
+ content: prepared.content,
364
+ display: prepared.display,
365
+ details: prepared.details,
366
+ timestamp,
367
+ },
368
+ };
369
+ }
370
+ // Carry the older identity ahead of its summary, outside opaque native replay.
371
+ return [
372
+ ...messages.slice(0, summary),
373
+ this.restoredIdentity.message,
374
+ ...messages.slice(summary),
375
+ ];
376
+ }
294
377
  let boundary = -1;
295
378
  for (let i = 0; i < messages.length; i++) {
296
379
  const message = messages[i]!;
@@ -300,7 +383,7 @@ export class Windows {
300
383
  throw new Error(
301
384
  "Invalid saved context window. Open an intact session branch to continue.",
302
385
  );
303
- if (details?.kind === "window") boundary = details.trim ? i : -1;
386
+ if (details?.kind === "window" && details.trim) boundary = i;
304
387
  }
305
388
  if (boundary < 0) return [...messages];
306
389
  const system = getCurrentSystemMessage(messages.slice(0, boundary));
@@ -312,7 +395,7 @@ export class Windows {
312
395
  let boundary = -1;
313
396
  for (let i = 0; i < entries.length; i++) {
314
397
  const details = windowDetails(entries[i]!);
315
- if (details?.kind === "window") boundary = details.trim ? i : -1;
398
+ if (details?.kind === "window" && details.trim) boundary = i;
316
399
  // Normal Pi/PCC compaction has already chosen its own checkpoint.
317
400
  if (entries[i]!.type === "compaction") boundary = -1;
318
401
  }