@howaboua/pi-notes-compaction 0.0.14 → 0.0.16

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 (83) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/LICENSE +21 -0
  3. package/README.md +8 -3
  4. package/index.ts +8 -0
  5. package/package.json +16 -11
  6. package/src/board/context-briefing.ts +245 -0
  7. package/src/board/delivery.ts +85 -0
  8. package/src/guidance.ts +121 -0
  9. package/src/notes/AGENTS.md +27 -0
  10. package/src/{activation.ts → notes/activation.ts} +8 -10
  11. package/src/{attachment-sharing.ts → notes/attachment-sharing.ts} +1 -1
  12. package/src/{attachment-snapshot.ts → notes/attachment-snapshot.ts} +33 -20
  13. package/src/{bridge.ts → notes/bridge.ts} +1 -0
  14. package/src/{context-sharing.ts → notes/context-sharing.ts} +22 -2
  15. package/src/{extension-hooks.ts → notes/extension-hooks.ts} +1 -12
  16. package/src/{extension-sharing.ts → notes/extension-sharing.ts} +2 -1
  17. package/src/notes/feature.ts +168 -0
  18. package/src/{history-windows.ts → notes/history-windows.ts} +10 -22
  19. package/src/{history.ts → notes/history.ts} +6 -5
  20. package/src/{index.ts → notes/index.ts} +20 -11
  21. package/src/{integrations.ts → notes/integrations.ts} +19 -3
  22. package/src/{lifecycle.ts → notes/lifecycle.ts} +0 -2
  23. package/src/{note-query.ts → notes/note-query.ts} +3 -5
  24. package/src/notes/note-result.ts +119 -0
  25. package/src/{note-save-marker.ts → notes/note-save-marker.ts} +3 -1
  26. package/src/{query-executor.ts → notes/query-executor.ts} +34 -9
  27. package/src/{query-input.ts → notes/query-input.ts} +1 -0
  28. package/src/{remote.ts → notes/remote.ts} +1 -1
  29. package/src/notes/saved-session-access.ts +121 -0
  30. package/src/notes/saved-session-index.mjs +83 -0
  31. package/src/notes/saved-session.mjs +241 -0
  32. package/src/notes/saved-session.ts +67 -0
  33. package/src/notes/saved-sharing-records.ts +170 -0
  34. package/src/{session-pruning.ts → notes/session-pruning.ts} +5 -5
  35. package/src/{settings-command.ts → notes/settings-command.ts} +29 -42
  36. package/src/{settings-controls.ts → notes/settings-controls.ts} +62 -72
  37. package/src/{settings-screen.ts → notes/settings-screen.ts} +25 -7
  38. package/src/{settings.ts → notes/settings.ts} +37 -6
  39. package/src/notes/shared-notes.ts +419 -0
  40. package/src/{shared-session-reader.ts → notes/shared-session-reader.ts} +35 -26
  41. package/src/{sharing-service.ts → notes/sharing-service.ts} +32 -1
  42. package/src/{store.ts → notes/store.ts} +10 -0
  43. package/src/{tool-contracts.ts → notes/tool-contracts.ts} +71 -44
  44. package/src/{tools.ts → notes/tools.ts} +2 -2
  45. package/src/notes/tree-archive-manifest.mjs +27 -0
  46. package/src/{tree-archive.ts → notes/tree-archive.ts} +6 -26
  47. package/src/{tree-handoff-read.ts → notes/tree-handoff-read.ts} +47 -32
  48. package/src/{window-message.ts → notes/window-message.ts} +15 -20
  49. package/src/settings-navigation.ts +11 -0
  50. package/src/timestamps.ts +3 -0
  51. package/tsconfig.json +9 -0
  52. package/src/note-result.ts +0 -70
  53. package/src/saved-session.ts +0 -169
  54. package/src/saved-sharing-records.ts +0 -112
  55. package/src/shared-notes.ts +0 -290
  56. /package/src/{agent-identity.ts → notes/agent-identity.ts} +0 -0
  57. /package/src/{binding-startup.ts → notes/binding-startup.ts} +0 -0
  58. /package/src/{compaction-projection.ts → notes/compaction-projection.ts} +0 -0
  59. /package/src/{context-owner.ts → notes/context-owner.ts} +0 -0
  60. /package/src/{fresh-checkpoint.ts → notes/fresh-checkpoint.ts} +0 -0
  61. /package/src/{fresh-notes.ts → notes/fresh-notes.ts} +0 -0
  62. /package/src/{history-search-protocol.ts → notes/history-search-protocol.ts} +0 -0
  63. /package/src/{history-search-pruning.mjs → notes/history-search-pruning.mjs} +0 -0
  64. /package/src/{history-search-worker.mjs → notes/history-search-worker.mjs} +0 -0
  65. /package/src/{history-search.ts → notes/history-search.ts} +0 -0
  66. /package/src/{idle-admission.ts → notes/idle-admission.ts} +0 -0
  67. /package/src/{model-role-config.ts → notes/model-role-config.ts} +0 -0
  68. /package/src/{model-role-screen.ts → notes/model-role-screen.ts} +0 -0
  69. /package/src/{model-roles.ts → notes/model-roles.ts} +0 -0
  70. /package/src/{notes-lookup.ts → notes/notes-lookup.ts} +0 -0
  71. /package/src/{notes.ts → notes/notes.ts} +0 -0
  72. /package/src/{rollover.ts → notes/rollover.ts} +0 -0
  73. /package/src/{session-pruning-content.ts → notes/session-pruning-content.ts} +0 -0
  74. /package/src/{session-pruning-plan.ts → notes/session-pruning-plan.ts} +0 -0
  75. /package/src/{session-pruning-policy.ts → notes/session-pruning-policy.ts} +0 -0
  76. /package/src/{session-pruning-screen.ts → notes/session-pruning-screen.ts} +0 -0
  77. /package/src/{session-pruning-source.ts → notes/session-pruning-source.ts} +0 -0
  78. /package/src/{session-pruning-transaction.ts → notes/session-pruning-transaction.ts} +0 -0
  79. /package/src/{sqlite.mjs → notes/sqlite.mjs} +0 -0
  80. /package/src/{task-boundary.ts → notes/task-boundary.ts} +0 -0
  81. /package/src/{tree-checkpoint.ts → notes/tree-checkpoint.ts} +0 -0
  82. /package/src/{window-checkpoint.ts → notes/window-checkpoint.ts} +0 -0
  83. /package/src/{windows.ts → notes/windows.ts} +0 -0
@@ -1,5 +1,10 @@
1
1
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
- import { dirname } from "node:path";
2
+ import { dirname, join } from "node:path";
3
+ import {
4
+ CONFIG_DIR_NAME,
5
+ type ExtensionContext,
6
+ getAgentDir,
7
+ } from "@earendil-works/pi-coding-agent";
3
8
 
4
9
  // Hour presets store their effective duration, with five minutes of headroom.
5
10
  export const IDLE_MINUTES = [0, 25, 55, 115, 355, 715] as const;
@@ -17,7 +22,7 @@ const DEFAULT_MODEL_WHITELIST = [
17
22
  "gpt-6.1-sol",
18
23
  ];
19
24
  export interface NotesSettings {
20
- active: "all" | "whitelist";
25
+ active: "all" | "whitelist" | "off";
21
26
  modelWhitelist: string[];
22
27
  normalCompaction: boolean;
23
28
  noteSaveMarkers: boolean;
@@ -28,7 +33,32 @@ export interface NotesSettings {
28
33
  taskBoundaryReminder: number;
29
34
  }
30
35
 
31
- export function readSettings(
36
+ export function notesSettingsPath(): string {
37
+ return join(getAgentDir(), "notes-compaction", "settings.json");
38
+ }
39
+
40
+ function legacySettingsPaths(ctx: ExtensionContext): string[] {
41
+ return [
42
+ join(getAgentDir(), "pi-codex-conversion.json"),
43
+ ...(ctx.isProjectTrusted()
44
+ ? [join(ctx.cwd, CONFIG_DIR_NAME, "pi-codex-conversion.json")]
45
+ : []),
46
+ ];
47
+ }
48
+
49
+ export function loadNotesSettings(ctx: ExtensionContext): NotesSettings {
50
+ return readSettings(notesSettingsPath(), legacySettingsPaths(ctx));
51
+ }
52
+
53
+ export function legacyNotesConfigured(ctx: ExtensionContext): boolean {
54
+ const { compaction } = readLegacyPreferences(legacySettingsPaths(ctx));
55
+ return (
56
+ compaction["continuity"] === "notes" ||
57
+ compaction["continuity"] === "notes-and-compaction"
58
+ );
59
+ }
60
+
61
+ function readSettings(
32
62
  path: string,
33
63
  legacyPaths: readonly string[] = [],
34
64
  ): NotesSettings {
@@ -67,9 +97,9 @@ export function readSettings(
67
97
  "Invalid notes settings. Save a setting in /notes, then reload Pi.",
68
98
  );
69
99
  const active = "active" in settings ? settings.active : "all";
70
- if (active !== "all" && active !== "whitelist")
100
+ if (active !== "all" && active !== "whitelist" && active !== "off")
71
101
  throw new Error(
72
- `Invalid active setting in ${path}. Use "all" or "whitelist", then reload Pi.`,
102
+ `Invalid active setting in ${path}. Use "all", "whitelist" or "off", then reload Pi.`,
73
103
  );
74
104
  const modelWhitelist =
75
105
  "modelWhitelist" in settings
@@ -140,7 +170,8 @@ export function modelIsActive(
140
170
  ): boolean {
141
171
  return (
142
172
  settings.active === "all" ||
143
- Boolean(model && settings.modelWhitelist.includes(model.id))
173
+ (settings.active === "whitelist" &&
174
+ Boolean(model && settings.modelWhitelist.includes(model.id)))
144
175
  );
145
176
  }
146
177
 
@@ -0,0 +1,419 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { compile, type Static } from "@earendil-works/pi-schema";
4
+ import {
5
+ canonicalAgentName,
6
+ contextAgentNames,
7
+ contextStorageAgentName,
8
+ contextTargetAgent,
9
+ isContextAgentName,
10
+ } from "./agent-identity.js";
11
+ import type { SavedSessionLoader } from "./context-sharing.js";
12
+ import type { HistorySearch } from "./history-search.js";
13
+ import type { SavedNotesSession } from "./saved-session.js";
14
+ import { createSavedSessionAccess } from "./saved-session-access.js";
15
+ import {
16
+ Detachment,
17
+ Member,
18
+ Parent,
19
+ Plan,
20
+ Route,
21
+ sameOwner,
22
+ savedFamilyIdentity,
23
+ savedNotesIdentity,
24
+ } from "./saved-sharing-records.js";
25
+ import { createSharedSessionReader } from "./shared-session-reader.js";
26
+ import type { NotesStore } from "./store.js";
27
+
28
+ export { savedNotesIdentity } from "./saved-sharing-records.js";
29
+
30
+ const detachmentValidator = compile(Detachment);
31
+ const memberValidator = compile(Member);
32
+ const parentValidator = compile(Parent);
33
+ const planValidator = compile(Plan);
34
+ const routeValidator = compile(Route);
35
+
36
+ function records(session: SavedNotesSession, kind: string): unknown[] {
37
+ return session.entries.flatMap((entry) =>
38
+ entry.type === "custom" && entry.customType === kind ? [entry.data] : [],
39
+ );
40
+ }
41
+
42
+ function inside(path: string, root: string): boolean {
43
+ return path === root || path.startsWith(`${root}/`);
44
+ }
45
+ function remap(
46
+ params: Record<string, unknown>,
47
+ from: string,
48
+ to: string,
49
+ ): Record<string, unknown> {
50
+ return Object.fromEntries(
51
+ Object.entries(params).map(([key, value]) => [
52
+ key,
53
+ ["path", "prefix", "path_prefix"].includes(key) &&
54
+ typeof value === "string" &&
55
+ inside(value, from)
56
+ ? `${to}${value.slice(from.length)}`
57
+ : value,
58
+ ]),
59
+ );
60
+ }
61
+
62
+ export function sharedNotesUnavailable(error: unknown): boolean {
63
+ return (
64
+ error instanceof Error &&
65
+ (("code" in error &&
66
+ [
67
+ "ENOENT",
68
+ "EACCES",
69
+ "EPERM",
70
+ "SAVED_SESSION_UNAVAILABLE",
71
+ "ECONNREFUSED",
72
+ "ECONNRESET",
73
+ "EPIPE",
74
+ "ETIMEDOUT",
75
+ ].includes(String(error.code))) ||
76
+ /^(No shared context agent\b|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|Unknown Core machine |Core machine .* is (?:unavailable|connecting)\b|Core is unavailable\b|Remote connection (?:closed|is not ready)\b|Remote request timed out\b)/.test(
77
+ error.message,
78
+ ))
79
+ );
80
+ }
81
+
82
+ /** Saved local notes do not need PCC, a router, or a running owner. Writes still belong to the live session. */
83
+ export async function readSharedNotes(
84
+ ctx: ExtensionContext,
85
+ store: Pick<NotesStore, "read" | "sessionFile">,
86
+ params: Record<string, unknown>,
87
+ signal?: AbortSignal,
88
+ loader?: SavedSessionLoader,
89
+ ): Promise<Record<string, unknown> | undefined> {
90
+ return readSharedSession(
91
+ ctx,
92
+ store,
93
+ params,
94
+ { namespace: "notes" },
95
+ signal,
96
+ loader,
97
+ );
98
+ }
99
+
100
+ export async function readSharedHistory(
101
+ ctx: ExtensionContext,
102
+ store: Pick<NotesStore, "read" | "sessionFile">,
103
+ search: HistorySearch,
104
+ params: Record<string, unknown>,
105
+ signal?: AbortSignal,
106
+ loader?: SavedSessionLoader,
107
+ ): Promise<Record<string, unknown> | undefined> {
108
+ return readSharedSession(
109
+ ctx,
110
+ store,
111
+ params,
112
+ { namespace: "history", search },
113
+ signal,
114
+ loader,
115
+ );
116
+ }
117
+
118
+ async function readSharedSession(
119
+ ctx: ExtensionContext,
120
+ store: Pick<NotesStore, "read" | "sessionFile">,
121
+ params: Record<string, unknown>,
122
+ access:
123
+ | { namespace: "notes" }
124
+ | { namespace: "history"; search: HistorySearch },
125
+ signal?: AbortSignal,
126
+ loader?: SavedSessionLoader,
127
+ ): Promise<Record<string, unknown> | undefined> {
128
+ const { namespace } = access;
129
+ if (
130
+ namespace === "notes" &&
131
+ !["read_file", "list_files_by_prefix", "search_contents"].includes(
132
+ String(params["action"]),
133
+ )
134
+ )
135
+ return;
136
+ const path =
137
+ namespace === "history"
138
+ ? params["agent_name"]
139
+ : (params["path"] ?? params["prefix"] ?? params["path_prefix"]);
140
+ if (typeof path !== "string" || !path.startsWith("/")) return;
141
+ const target =
142
+ namespace === "history"
143
+ ? isContextAgentName(path)
144
+ ? path
145
+ : undefined
146
+ : contextTargetAgent(
147
+ "notes",
148
+ { path },
149
+ canonicalAgentName(ctx.sessionManager.getSessionId()),
150
+ );
151
+ if (!target) return;
152
+ const outputAgent = target;
153
+ const current: SavedNotesSession = {
154
+ threadId: ctx.sessionManager.getSessionId(),
155
+ entries: ctx.sessionManager.getEntries(),
156
+ branch: ctx.sessionManager.getBranch(),
157
+ };
158
+ if (contextAgentNames(savedNotesIdentity(current)).includes(target)) return;
159
+ const visited = new Set<string>();
160
+ const { containingMachine, locator, load, indexed, find } =
161
+ createSavedSessionAccess(store, namespace, loader, signal);
162
+ let unavailable: unknown;
163
+ let targetReached = false;
164
+ async function exploratoryLoad(location: Parameters<typeof load>[0]) {
165
+ try {
166
+ return await load(location);
167
+ } catch (error) {
168
+ signal?.throwIfAborted();
169
+ if (!sharedNotesUnavailable(error)) throw error;
170
+ unavailable ??= error;
171
+ return undefined;
172
+ }
173
+ }
174
+
175
+ const { read, reference } = createSharedSessionReader(
176
+ store,
177
+ access,
178
+ outputAgent,
179
+ signal,
180
+ load,
181
+ resolve,
182
+ sharedNotesUnavailable,
183
+ );
184
+ async function resolve(
185
+ session: SavedNotesSession,
186
+ destination: string,
187
+ query: Record<string, unknown>,
188
+ ): Promise<Record<string, unknown> | undefined> {
189
+ signal?.throwIfAborted();
190
+ const key = `${containingMachine(session)}\0${session.threadId}`;
191
+ if (visited.has(key)) return;
192
+ visited.add(key);
193
+ const identity = savedNotesIdentity(session);
194
+ if (contextAgentNames(identity).includes(destination)) {
195
+ targetReached = true;
196
+ return read(session, query, destination);
197
+ }
198
+ const routes = new Map<string, Static<typeof Route>>();
199
+ for (const value of records(session, "shepherdr-attachment-route"))
200
+ if (
201
+ routeValidator.check(value) &&
202
+ value.plan.controllerSessionId === identity.threadId
203
+ )
204
+ routes.set(`${value.machine}\0${value.sessionFile}`, value);
205
+ const matching = [...routes.values()].filter((route) => {
206
+ const link = route.plan.context;
207
+ return (
208
+ route.phase === "ready" &&
209
+ link &&
210
+ (destination === canonicalAgentName(link.target.threadId) ||
211
+ inside(destination, link.alias))
212
+ );
213
+ });
214
+ if (matching.length > 1)
215
+ throw new Error(
216
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
217
+ );
218
+ for (const route of matching) {
219
+ targetReached = true;
220
+ const link = route.plan.context;
221
+ if (route.phase !== "ready" || !link) continue;
222
+ const alias =
223
+ destination === canonicalAgentName(link.target.threadId)
224
+ ? destination
225
+ : link.alias;
226
+ if (!inside(destination, alias)) continue;
227
+ if (!sameOwner(identity, link.controller))
228
+ throw new Error("Saved shared notes identity changed");
229
+ return reference(
230
+ link.target,
231
+ `${link.target.agentName}${destination.slice(alias.length)}`,
232
+ remap(query, alias, link.target.agentName),
233
+ locator(session, route.machine, route.sessionFile),
234
+ route.detached?.context ?? link.targetNotes,
235
+ route.detached?.context !== undefined,
236
+ );
237
+ }
238
+ const owner = records(session, "shepherdr-attachment-owner").findLast(
239
+ (value) =>
240
+ planValidator.check(value) &&
241
+ value.targetSessionId === identity.threadId,
242
+ );
243
+ if (
244
+ planValidator.check(owner) &&
245
+ owner.context &&
246
+ (inside(destination, owner.context.controllerAlias) ||
247
+ destination === canonicalAgentName(owner.context.controller.threadId))
248
+ ) {
249
+ targetReached = true;
250
+ const link = owner.context;
251
+ const alias =
252
+ destination === canonicalAgentName(link.controller.threadId)
253
+ ? destination
254
+ : link.controllerAlias;
255
+ if (!sameOwner(identity, link.target))
256
+ throw new Error("Saved shared notes identity changed");
257
+ const detached = records(
258
+ session,
259
+ "shepherdr-attachment-detached",
260
+ ).findLast(
261
+ (value) =>
262
+ detachmentValidator.check(value) &&
263
+ isDeepStrictEqual(value.plan, owner),
264
+ );
265
+ const snapshot = detachmentValidator.check(detached)
266
+ ? detached.context
267
+ : undefined;
268
+ return reference(
269
+ link.controller,
270
+ `${link.controller.agentName}${destination.slice(alias.length)}`,
271
+ remap(query, alias, link.controller.agentName),
272
+ link.controllerFile
273
+ ? locator(
274
+ session,
275
+ link.controllerMachine ?? "local",
276
+ link.controllerFile,
277
+ )
278
+ : undefined,
279
+ snapshot ?? link.controllerNotes,
280
+ snapshot !== undefined,
281
+ );
282
+ }
283
+ // Explicit attachment routes (including detach snapshots) own their addresses.
284
+ if (session === current) {
285
+ let saved: SavedNotesSession | undefined;
286
+ try {
287
+ saved = await indexed(current, destination);
288
+ } catch (error) {
289
+ signal?.throwIfAborted();
290
+ if (!sharedNotesUnavailable(error)) throw error;
291
+ unavailable ??= error;
292
+ }
293
+ if (saved) return resolve(saved, destination, query);
294
+ }
295
+ if (!savedFamilyIdentity(session)) return;
296
+ let result: Record<string, unknown> | undefined;
297
+ const members = records(session, "herdr-context-child").filter(
298
+ (value) =>
299
+ memberValidator.check(value) &&
300
+ value.threadId === identity.threadId &&
301
+ value.sessionId === identity.sessionId,
302
+ );
303
+ const direct = members.filter(
304
+ (member) =>
305
+ memberValidator.check(member) && member.agentName === destination,
306
+ );
307
+ for (const member of direct.length ? direct : members) {
308
+ if (!memberValidator.check(member)) continue;
309
+ const location = locator(session, member.machine, member.sessionFile);
310
+ // Only exploratory edges may be skipped. A recorded target must report its failure.
311
+ const saved = await (direct.length
312
+ ? load(location)
313
+ : exploratoryLoad(location));
314
+ if (!saved) continue;
315
+ const child = savedFamilyIdentity(saved);
316
+ if (
317
+ !child ||
318
+ child.sessionId !== identity.sessionId ||
319
+ (child.agentName !== member.agentName &&
320
+ contextStorageAgentName(child) !== member.agentName)
321
+ )
322
+ throw new Error(
323
+ "This session cannot access the requested saved context. Request an accessible handoff or note path from its owner.",
324
+ );
325
+ const candidate = await resolve(saved, destination, query);
326
+ if (candidate) {
327
+ if (result)
328
+ throw new Error(
329
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
330
+ );
331
+ result = candidate;
332
+ }
333
+ }
334
+ if (direct.length) return result;
335
+ const routing = identity.routing;
336
+ const suffix = ".jsonl.shepherdr-context.json";
337
+ if (parentValidator.check(routing)) {
338
+ const parentLocator = routing.savedParent
339
+ ? locator(
340
+ session,
341
+ routing.savedParent.machine,
342
+ routing.savedParent.sessionFile,
343
+ )
344
+ : routing.parent.endsWith(suffix)
345
+ ? locator(
346
+ session,
347
+ "local",
348
+ routing.parent.slice(0, -".shepherdr-context.json".length),
349
+ )
350
+ : undefined;
351
+ if (parentLocator) {
352
+ const saved = await exploratoryLoad(parentLocator);
353
+ if (!saved) return result;
354
+ const parent = savedFamilyIdentity(saved);
355
+ if (!parent || parent.sessionId !== identity.sessionId)
356
+ throw new Error("Saved shared notes parent identity changed");
357
+ const candidate = await resolve(saved, destination, query);
358
+ if (candidate && result)
359
+ throw new Error(
360
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
361
+ );
362
+ result = candidate ?? result;
363
+ }
364
+ }
365
+ return result;
366
+ }
367
+ try {
368
+ let result: Record<string, unknown> | undefined;
369
+ try {
370
+ result = await resolve(current, target, params);
371
+ } catch (error) {
372
+ signal?.throwIfAborted();
373
+ if (!sharedNotesUnavailable(error)) throw error;
374
+ unavailable ??= error;
375
+ }
376
+ // Legacy remote children may record only a now-dead relay parent. Find the
377
+ // requested native thread once, never aliases or intermediate graph nodes.
378
+ const family = savedFamilyIdentity(current);
379
+ if (!result && !targetReached && family) {
380
+ const candidates: SavedNotesSession[] = [];
381
+ for (const location of await find(target)) {
382
+ const saved = await exploratoryLoad(location);
383
+ if (!saved) continue;
384
+ if (saved.threadId !== target.slice(1))
385
+ throw new Error(
386
+ "Saved session discovery returned a different thread",
387
+ );
388
+ const member = savedFamilyIdentity(saved);
389
+ if (
390
+ member?.storage === "session" &&
391
+ member.sessionId === family.sessionId &&
392
+ member.agentName === target
393
+ )
394
+ candidates.push(saved);
395
+ }
396
+ if (candidates.length > 1)
397
+ throw new Error(
398
+ "Saved shared address is ambiguous across machines. Use a unique attached alias, then retry.",
399
+ );
400
+ if (candidates[0]) result = await read(candidates[0], params, target);
401
+ }
402
+ if (!result && unavailable) throw unavailable;
403
+ return result;
404
+ } catch (error) {
405
+ if (
406
+ error instanceof Error &&
407
+ "code" in error &&
408
+ ["ENOENT", "EACCES", "EPERM"].includes(String(error.code))
409
+ )
410
+ throw Object.assign(
411
+ new Error(
412
+ `Saved ${namespace} could not be read on this machine. Request a handoff from the owner, or ask the user to restore access before retrying.`,
413
+ { cause: error },
414
+ ),
415
+ { code: "SAVED_SESSION_UNAVAILABLE" },
416
+ );
417
+ throw error;
418
+ }
419
+ }
@@ -1,14 +1,13 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { Check } from "typebox/value";
2
+ import { compile } from "@earendil-works/pi-schema";
3
+ import { minuteTimestamp } from "../timestamps.js";
3
4
  import { contextStorageAgentName } from "./agent-identity.js";
5
+ import type { SavedSessionLocator } from "./context-sharing.js";
4
6
  import { useHistory } from "./history.js";
5
7
  import type { HistorySearch } from "./history-search.js";
6
8
  import { normalizeNoteParams, readNotes } from "./note-query.js";
7
9
  import { collectNotes } from "./notes.js";
8
- import {
9
- readSavedNotesSession,
10
- type SavedNotesSession,
11
- } from "./saved-session.js";
10
+ import { type SavedNotesSession } from "./saved-session.js";
12
11
  import {
13
12
  type Identity,
14
13
  Snapshot,
@@ -17,6 +16,8 @@ import {
17
16
  } from "./saved-sharing-records.js";
18
17
  import type { NotesStore } from "./store.js";
19
18
 
19
+ const snapshotValidator = compile(Snapshot);
20
+
20
21
  export function createSharedSessionReader(
21
22
  store: Pick<NotesStore, "read">,
22
23
  access:
@@ -24,18 +25,38 @@ export function createSharedSessionReader(
24
25
  | { namespace: "history"; search: HistorySearch },
25
26
  outputAgent: string,
26
27
  signal: AbortSignal | undefined,
28
+ load: (locator: SavedSessionLocator) => Promise<SavedNotesSession>,
27
29
  resolve: (
28
30
  session: SavedNotesSession,
29
31
  destination: string,
30
32
  query: Record<string, unknown>,
31
33
  ) => Promise<Record<string, unknown> | undefined>,
34
+ unavailable: (error: unknown) => boolean,
32
35
  ) {
33
36
  const { namespace } = access;
34
37
  async function read(
35
38
  session: SavedNotesSession,
36
39
  query: Record<string, unknown>,
37
40
  native: string,
38
- ) {
41
+ ): Promise<Record<string, unknown> | undefined> {
42
+ if (namespace === "notes") {
43
+ const normalized = normalizeNoteParams(query, native);
44
+ const replacement =
45
+ normalized["action"] === "read_file" &&
46
+ collectNotes(store, session.branch).get(String(normalized["path"]))
47
+ ?.mode === "replace";
48
+ // Never replace a merged hybrid read with a local-only saved branch.
49
+ if (
50
+ !replacement &&
51
+ (savedNotesIdentity(session).storage === "remote" ||
52
+ session.branch.some(
53
+ (entry) =>
54
+ entry.type === "custom" &&
55
+ entry.customType === "notes-compaction:cache:v1",
56
+ ))
57
+ )
58
+ return;
59
+ }
39
60
  return {
40
61
  ...(access.namespace === "history"
41
62
  ? await useHistory(
@@ -51,41 +72,28 @@ export function createSharedSessionReader(
51
72
  normalizeNoteParams(query, native),
52
73
  outputAgent,
53
74
  )),
54
- ...(namespace === "notes"
55
- ? {
56
- read_only: true,
57
- warning:
58
- "Only saved notes are included; other notes may be missing",
59
- }
60
- : {}),
61
75
  ...(session.savedAt === undefined
62
76
  ? {}
63
- : { saved_at: new Date(session.savedAt).toISOString() }),
77
+ : { saved_at: minuteTimestamp(session.savedAt) }),
64
78
  };
65
79
  }
66
80
  async function reference(
67
81
  identity: Identity,
68
82
  destination: string,
69
83
  query: Record<string, unknown>,
70
- file: string | undefined,
84
+ locator: SavedSessionLocator | undefined,
71
85
  retained?: unknown,
72
86
  detached = false,
73
87
  ): Promise<Record<string, unknown> | undefined> {
74
- if (file && (!detached || namespace === "history")) {
88
+ if (locator && (!detached || namespace === "history")) {
75
89
  let saved: SavedNotesSession | undefined;
76
90
  try {
77
- saved = await readSavedNotesSession(
78
- file,
79
- signal,
80
- namespace === "history",
81
- );
91
+ saved = await load(locator);
82
92
  } catch (error) {
83
93
  signal?.throwIfAborted();
84
94
  if (
85
95
  !(
86
- error instanceof Error &&
87
- "code" in error &&
88
- error.code === "ENOENT" &&
96
+ unavailable(error) &&
89
97
  retained !== undefined &&
90
98
  namespace === "notes"
91
99
  )
@@ -102,7 +110,7 @@ export function createSharedSessionReader(
102
110
  namespace === "history" ||
103
111
  (destination !== identity.agentName &&
104
112
  destination !== contextStorageAgentName(identity)) ||
105
- !Check(Snapshot, retained)
113
+ !snapshotValidator.check(retained)
106
114
  )
107
115
  return;
108
116
  const entry: SessionEntry = {
@@ -126,7 +134,8 @@ export function createSharedSessionReader(
126
134
  query,
127
135
  destination,
128
136
  )),
129
- captured_at: new Date(retained.timestamp).toISOString(),
137
+ read_only: true,
138
+ captured_at: minuteTimestamp(retained.timestamp),
130
139
  warning: detached
131
140
  ? "Read-only notes captured when sharing ended; later changes are not included"
132
141
  : "The latest notes are unavailable; this read-only copy may be outdated",
@@ -19,6 +19,7 @@ import {
19
19
  CONTEXT_SHARING_REQUEST,
20
20
  type ContextRouter,
21
21
  type ContextSharingService,
22
+ type SavedSessionLoader,
22
23
  type SharedContextRequest,
23
24
  type SharedContextResult,
24
25
  } from "./context-sharing.js";
@@ -35,8 +36,9 @@ export function registerContextSharingService(
35
36
  ): Promise<SharedContextResult>;
36
37
  owner(): NotesOwner;
37
38
  },
38
- ): ContextRouter {
39
+ ): ContextRouter & { loadSavedSession: SavedSessionLoader } {
39
40
  let router: ContextRouter | undefined;
41
+ let savedSessionLoader: SavedSessionLoader | undefined;
40
42
  const describe: ContextSharingService["describe"] = (ctx) => {
41
43
  const storageMode = config.enabled(ctx);
42
44
  if (!storageMode) return undefined;
@@ -212,6 +214,14 @@ export function registerContextSharingService(
212
214
  return config.execute(ctx, request, signal);
213
215
  },
214
216
  ...createAttachmentSharing(describe),
217
+ registerSavedSessionLoader(next) {
218
+ if (savedSessionLoader && savedSessionLoader !== next)
219
+ throw new Error("A saved session loader is already registered");
220
+ savedSessionLoader = next;
221
+ return () => {
222
+ if (savedSessionLoader === next) savedSessionLoader = undefined;
223
+ };
224
+ },
215
225
  registerRouter(next) {
216
226
  if (router && router !== next)
217
227
  throw new Error("A context router is already registered");
@@ -228,6 +238,7 @@ export function registerContextSharingService(
228
238
  pi.on("session_shutdown", () => {
229
239
  off();
230
240
  router = undefined;
241
+ savedSessionLoader = undefined;
231
242
  });
232
243
  return Object.assign(
233
244
  async (
@@ -244,6 +255,26 @@ export function registerContextSharingService(
244
255
  return router(ctx, request, signal);
245
256
  },
246
257
  {
258
+ loadSavedSession: Object.defineProperty(
259
+ (
260
+ locator: import("./context-sharing.js").SavedSessionLocator,
261
+ history: boolean,
262
+ signal?: AbortSignal,
263
+ ) => {
264
+ if (!savedSessionLoader)
265
+ throw Object.assign(
266
+ new Error(
267
+ "Saved context on that machine is unavailable. Request a handoff from its owner, or ask the user to reconnect the machine before retrying.",
268
+ ),
269
+ { code: "SAVED_SESSION_UNAVAILABLE" },
270
+ );
271
+ return savedSessionLoader(locator, history, signal);
272
+ },
273
+ "find",
274
+ {
275
+ get: () => savedSessionLoader?.find?.bind(savedSessionLoader),
276
+ },
277
+ ),
247
278
  requiresRemoteScope: (ctx: ExtensionContext) =>
248
279
  router?.requiresRemoteScope?.(ctx) ?? false,
249
280
  },