@howaboua/pi-notes-compaction 0.0.12 → 0.0.14

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 (42) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/PCC-INTEGRATION.md +3 -1
  3. package/README.md +36 -22
  4. package/package.json +4 -6
  5. package/src/agent-identity.ts +112 -10
  6. package/src/attachment-sharing.ts +37 -6
  7. package/src/attachment-snapshot.ts +16 -6
  8. package/src/context-sharing.ts +15 -1
  9. package/src/extension-hooks.ts +15 -2
  10. package/src/extension-sharing.ts +25 -11
  11. package/src/fresh-checkpoint.ts +30 -4
  12. package/src/fresh-notes.ts +44 -33
  13. package/src/history-search.ts +1 -1
  14. package/src/history-windows.ts +12 -2
  15. package/src/history.ts +7 -1
  16. package/src/index.ts +5 -19
  17. package/src/integrations.ts +26 -26
  18. package/src/lifecycle.ts +26 -10
  19. package/src/model-role-config.ts +10 -30
  20. package/src/model-role-screen.ts +48 -32
  21. package/src/model-roles.ts +177 -315
  22. package/src/note-result.ts +70 -0
  23. package/src/note-save-marker.ts +23 -9
  24. package/src/notes-lookup.ts +5 -2
  25. package/src/notes.ts +8 -3
  26. package/src/query-executor.ts +34 -15
  27. package/src/query-input.ts +12 -1
  28. package/src/remote.ts +26 -7
  29. package/src/rollover.ts +17 -5
  30. package/src/saved-session.ts +1 -0
  31. package/src/saved-sharing-records.ts +18 -9
  32. package/src/settings-command.ts +1 -1
  33. package/src/shared-notes.ts +49 -20
  34. package/src/shared-session-reader.ts +8 -4
  35. package/src/sharing-service.ts +25 -8
  36. package/src/task-boundary.ts +1 -1
  37. package/src/tool-contracts.ts +50 -58
  38. package/src/tools.ts +34 -50
  39. package/src/window-message.ts +19 -8
  40. package/src/windows.ts +2 -2
  41. package/changelog.ts +0 -337
  42. package/src/model-role-editor.ts +0 -40
package/src/notes.ts CHANGED
@@ -3,6 +3,7 @@ import type {
3
3
  ExtensionContext,
4
4
  SessionEntry,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import { isContextAgentName } from "./agent-identity.js";
6
7
  import type { NoteSnapshotData } from "./bridge.js";
7
8
  import { canonicalPath, readNotes } from "./note-query.js";
8
9
  import { type NoteRevision, NotesStore, type SessionRef } from "./store.js";
@@ -77,7 +78,9 @@ function relativeLegacyPath(path: string): string {
77
78
  // Legacy canonical paths use the first notes component as the agent-root boundary.
78
79
  const components = path.split("/");
79
80
  const boundary = components.indexOf("notes");
80
- return components[0] === "" && components[1] === "root" && boundary > 1
81
+ return components[0] === "" &&
82
+ isContextAgentName(components.slice(0, boundary).join("/")) &&
83
+ boundary > 1
81
84
  ? components.slice(boundary + 1).join("/")
82
85
  : path;
83
86
  }
@@ -191,7 +194,7 @@ export function exportNotesSnapshot(
191
194
  entries: readonly SessionEntry[],
192
195
  agentName: string,
193
196
  ): NoteSnapshotData {
194
- if (!/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(agentName))
197
+ if (!isContextAgentName(agentName))
195
198
  throw new Error("Invalid notes agent identity");
196
199
  const notes = collectNotes({ read: () => undefined }, entries);
197
200
  const snapshot: NoteSnapshotData = {
@@ -231,7 +234,9 @@ export function noteHints(
231
234
  const paths = [
232
235
  ...new Set([...notes, ...store.cachedPaths(sourceSessionIds(ctx))]),
233
236
  ].slice(0, 5);
234
- return paths.length ? `Recent notes: ${paths.join(", ")}`.slice(0, 4000) : "";
237
+ return paths.length
238
+ ? `Recent notes in virtual filesystem: ${paths.join(", ")}`.slice(0, 4000)
239
+ : "";
235
240
  }
236
241
 
237
242
  export function useNotes(
@@ -3,9 +3,15 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ contextAgentIdentity,
8
+ contextAgentNames,
9
+ contextStorageAgentName,
10
+ } from "./agent-identity.js";
6
11
  import { useHistory } from "./history.js";
7
12
  import type { HistorySearch } from "./history-search.js";
8
13
  import type { NotesLifecycle } from "./lifecycle.js";
14
+ import { noteResult } from "./note-result.js";
9
15
  import { collectNotes, normalizeNoteParams, useNotes } from "./notes.js";
10
16
  import { lookupNotes } from "./notes-lookup.js";
11
17
  import {
@@ -41,8 +47,8 @@ export function createQueryExecutor(
41
47
  signal: AbortSignal | undefined,
42
48
  ctx: ExtensionContext,
43
49
  ): Promise<AgentToolResult<unknown>> {
44
- input = prepareNotesArguments(input, true);
45
- const help = queryHelp("notes", input, false, lifecycle.gptPromptMode());
50
+ input = prepareNotesArguments(input);
51
+ const help = queryHelp("notes", input, lifecycle.gptPromptMode());
46
52
  if (help) return help;
47
53
  assertActive();
48
54
  const raw = queryArguments("notes", input);
@@ -59,15 +65,28 @@ export function createQueryExecutor(
59
65
  signal?.throwIfAborted();
60
66
  if (!sharedNotesUnavailable(error)) throw error;
61
67
  const saved = await readSharedNotes(ctx, store, raw, signal);
62
- if (saved) return result(saved);
68
+ if (saved) return noteResult(saved);
63
69
  throw error;
64
70
  }
65
71
  const saved = await readSharedNotes(ctx, store, raw, signal);
66
- if (saved) return result(saved);
72
+ if (saved) return noteResult(saved);
73
+ }
74
+ const identity = contextAgentIdentity(ctx);
75
+ const storageAgent = contextStorageAgentName(identity);
76
+ const localRaw = { ...raw };
77
+ for (const key of ["path", "prefix", "path_prefix"]) {
78
+ const value = localRaw[key];
79
+ if (typeof value !== "string") continue;
80
+ const alias = contextAgentNames(identity).find(
81
+ (name) =>
82
+ value === `${name}/notes` || value.startsWith(`${name}/notes/`),
83
+ );
84
+ if (alias)
85
+ localRaw[key] = `${identity.agentName}${value.slice(alias.length)}`;
67
86
  }
68
87
  const params = queryArguments(
69
88
  "notes",
70
- normalizeNoteParams(raw, lifecycle.agent(ctx)),
89
+ normalizeNoteParams(localRaw, lifecycle.agent(ctx)),
71
90
  );
72
91
  if (signal?.aborted) throw new Error("Note operation cancelled");
73
92
  const local = useNotes(
@@ -85,7 +104,7 @@ export function createQueryExecutor(
85
104
  params["action"] === "append_to_file"
86
105
  )
87
106
  return {
88
- ...result(local),
107
+ ...noteResult(local),
89
108
  details: {
90
109
  ...(shared
91
110
  ? { codexHistoryNotes: {}, notesCompactionRouted: true }
@@ -103,7 +122,7 @@ export function createQueryExecutor(
103
122
  params["action"] === "read_file" &&
104
123
  notes.get(params["path"] as string)?.mode === "replace"
105
124
  )
106
- return result(local);
125
+ return noteResult(local);
107
126
  const prefix = String(params["prefix"] ?? params["path_prefix"] ?? "");
108
127
  const replacementsInScope =
109
128
  params["action"] !== "read_file" &&
@@ -114,7 +133,7 @@ export function createQueryExecutor(
114
133
  for (const field of ["path", "prefix", "path_prefix"])
115
134
  if (typeof remoteParams[field] === "string")
116
135
  remoteParams[field] =
117
- `${lifecycle.agent(ctx)}/notes${remoteParams[field] ? `/${remoteParams[field]}` : ""}`;
136
+ `${storageAgent}/notes${remoteParams[field] ? `/${remoteParams[field]}` : ""}`;
118
137
  return lookupNotes(
119
138
  pi,
120
139
  store,
@@ -135,12 +154,7 @@ export function createQueryExecutor(
135
154
  ctx: ExtensionContext,
136
155
  ): Promise<AgentToolResult<unknown>> {
137
156
  input = prepareHistoryArguments(input);
138
- const help = queryHelp(
139
- "history",
140
- input,
141
- search.isEnabled(ctx.sessionManager.getSessionId()),
142
- lifecycle.gptPromptMode(),
143
- );
157
+ const help = queryHelp("history", input, lifecycle.gptPromptMode());
144
158
  if (help) return help;
145
159
  assertActive();
146
160
  const params = queryArguments("history", input);
@@ -177,7 +191,12 @@ export function createQueryExecutor(
177
191
  const saved = await readSharedHistory(ctx, store, search, params, signal);
178
192
  if (saved) return result(saved);
179
193
  }
180
- if (params["agent_name"] && params["agent_name"] !== lifecycle.agent(ctx))
194
+ if (
195
+ params["agent_name"] &&
196
+ !contextAgentNames(contextAgentIdentity(ctx)).includes(
197
+ String(params["agent_name"]),
198
+ )
199
+ )
181
200
  throw new Error(
182
201
  "That agent's Pi session history is unavailable on this machine. Restore access to its saved JSONL session, or omit agent_name to search this session.",
183
202
  );
@@ -58,12 +58,21 @@ export function normalizeQueryInput(
58
58
  if (!input || typeof input !== "object" || Array.isArray(input))
59
59
  throw new Error("Supply an action object; use {} for help");
60
60
  const params = { ...input } as Record<string, unknown>;
61
+ if (
62
+ namespace === "history" &&
63
+ params["action"] === undefined &&
64
+ "query" in params
65
+ )
66
+ params["action"] = "search";
61
67
  const action =
62
68
  ACTIONS[namespace][String(params["action"])] ?? params["action"];
63
69
  if (action !== undefined) params["action"] = action;
64
70
  if (namespace === "notes") {
65
- if (action === "write" || action === "append")
71
+ alias(params, "address", "path");
72
+ if (action === "write" || action === "append") {
66
73
  alias(params, "content", "text");
74
+ alias(params, "body", "text");
75
+ }
67
76
  if (action === "list" || action === "search") {
68
77
  alias(params, "prefix", "path");
69
78
  alias(params, "path_prefix", "path");
@@ -76,6 +85,8 @@ export function normalizeQueryInput(
76
85
  alias(params, "max_results", "limit");
77
86
  }
78
87
  const used = PRESENTATION[`${namespace}:${String(action)}`] ?? [];
88
+ if (namespace === "history" && action !== "read")
89
+ delete params["offset_chars"];
79
90
  for (const hint of HINTS) if (!used.includes(hint)) delete params[hint];
80
91
  return params;
81
92
  }
package/src/remote.ts CHANGED
@@ -12,8 +12,11 @@ import {
12
12
  } from "@howaboua/pi-codex-conversion/code-mode";
13
13
  import {
14
14
  type ContextAgentIdentity,
15
+ canonicalContextIdentity,
15
16
  contextAgentIdentity,
17
+ contextStorageAgentName,
16
18
  contextTargetAgent,
19
+ isContextAgentName,
17
20
  } from "./agent-identity.js";
18
21
  import type { CachedResponse, LookupQuery } from "./bridge.js";
19
22
  import type {
@@ -21,6 +24,7 @@ import type {
21
24
  SharedContextRequest,
22
25
  SharedContextResult,
23
26
  } from "./context-sharing.js";
27
+ import { noteResult } from "./note-result.js";
24
28
 
25
29
  const ENDPOINTS = {
26
30
  list_files_by_prefix: [
@@ -97,7 +101,7 @@ function scope(
97
101
  return JSON.stringify({
98
102
  threadId: identity.threadId,
99
103
  sessionId: identity.sessionId,
100
- agentName: identity.agentName,
104
+ agentName: contextStorageAgentName(identity),
101
105
  accountScope: protectedAccountScope(accountId),
102
106
  baseUrl,
103
107
  });
@@ -154,6 +158,19 @@ async function lookup(
154
158
  target?: RemoteNoteReference,
155
159
  ): Promise<readonly CachedResponse[]> {
156
160
  const { action, args } = readQuery(query);
161
+ if (target) {
162
+ const identity = canonicalContextIdentity(target.identity);
163
+ for (const field of ["path", "prefix", "path_prefix"]) {
164
+ const value = args[field];
165
+ if (
166
+ typeof value === "string" &&
167
+ (value === `${identity.agentName}/notes` ||
168
+ value.startsWith(`${identity.agentName}/notes/`))
169
+ )
170
+ args[field] =
171
+ `${contextStorageAgentName(identity)}${value.slice(identity.agentName.length)}`;
172
+ }
173
+ }
157
174
  const auth = await authenticated(ctx);
158
175
  if (target) checkReference(target, auth.provider);
159
176
  const headers = auth.provider.headers;
@@ -173,8 +190,9 @@ async function lookup(
173
190
  ...args,
174
191
  context: {
175
192
  session_id: target?.identity.sessionId ?? auth.identity.sessionId,
176
- current_agent_name:
177
- target?.identity.agentName ?? auth.identity.agentName,
193
+ current_agent_name: contextStorageAgentName(
194
+ target?.identity ?? auth.identity,
195
+ ),
178
196
  },
179
197
  }),
180
198
  },
@@ -237,10 +255,11 @@ export async function executeRemoteAttachment(
237
255
  throw new Error(
238
256
  "History is unavailable from a saved remote notes attachment. Open its saved Pi JSONL session on this machine, then retry.",
239
257
  );
258
+ const identity = canonicalContextIdentity(reference.identity);
240
259
  if (
241
260
  request.sessionId !== reference.identity.sessionId ||
242
- (request.agentName !== reference.identity.agentName &&
243
- !request.agentName.startsWith(`${reference.identity.agentName}/`)) ||
261
+ (request.agentName !== identity.agentName &&
262
+ request.agentName !== contextStorageAgentName(identity)) ||
244
263
  contextTargetAgent(
245
264
  request.namespace,
246
265
  request.params,
@@ -259,7 +278,7 @@ export async function executeRemoteAttachment(
259
278
  reference,
260
279
  );
261
280
  return {
262
- content: [{ type: "text", text: "Saved remote read completed" }],
281
+ ...noteResult({ usage: "Saved remote read completed" }),
263
282
  details: {
264
283
  codexHistoryNotes: {},
265
284
  externalNotesResponses: responses.map(({ bytes, ...response }) => ({
@@ -303,7 +322,7 @@ async function projectNotesResponses(
303
322
  !provenance.sessionId ||
304
323
  !("agentName" in provenance) ||
305
324
  typeof provenance.agentName !== "string" ||
306
- !/^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(provenance.agentName)
325
+ !isContextAgentName(provenance.agentName)
307
326
  )
308
327
  throw new Error(
309
328
  "Shared protected contents belong to a different account or backend",
package/src/rollover.ts CHANGED
@@ -6,11 +6,13 @@ import type {
6
6
  } from "@earendil-works/pi-coding-agent";
7
7
  import { prepareCompactionProjection } from "./compaction-projection.js";
8
8
  import type { NotesLifecycle } from "./lifecycle.js";
9
+ import type { ModelRoleHandoff } from "./model-roles.js";
9
10
 
10
11
  type Rollover = {
11
12
  sessionId: string;
12
13
  windowId: string | undefined;
13
14
  triggerTurn: boolean;
15
+ handoff?: ModelRoleHandoff;
14
16
  } & (
15
17
  | { phase: "scheduled" | "compacting" }
16
18
  | { phase: "checking"; accepted?: AbortSignal }
@@ -34,6 +36,7 @@ export class RolloverRequests {
34
36
  ctx: ExtensionContext,
35
37
  triggerTurn: boolean,
36
38
  trim: boolean,
39
+ handoff?: ModelRoleHandoff,
37
40
  ) => Promise<void>;
38
41
  private readonly sendMessage: (
39
42
  message: Omit<CustomMessageEntryDraft, "type">,
@@ -64,12 +67,13 @@ export class RolloverRequests {
64
67
  clear(): void {
65
68
  this.rollover = undefined;
66
69
  }
67
- schedule(ctx: ExtensionContext): void {
70
+ schedule(ctx: ExtensionContext, handoff?: ModelRoleHandoff): void {
68
71
  this.rollover = {
69
72
  sessionId: ctx.sessionManager.getSessionId(),
70
73
  windowId: this.host.windows.current?.currentWindowId,
71
74
  phase: "scheduled",
72
75
  triggerTurn: true,
76
+ ...(handoff ? { handoff } : {}),
73
77
  };
74
78
  }
75
79
  settled(ctx: ExtensionContext): Promise<void> | undefined {
@@ -80,15 +84,19 @@ export class RolloverRequests {
80
84
  rollover.windowId === this.host.windows.current?.currentWindowId
81
85
  ) {
82
86
  this.rollover = undefined;
83
- return this.roll(ctx, rollover.triggerTurn);
87
+ return this.roll(ctx, rollover.triggerTurn, rollover.handoff);
84
88
  }
85
89
  }
86
90
 
87
- async roll(ctx: ExtensionContext, triggerTurn: boolean): Promise<void> {
91
+ async roll(
92
+ ctx: ExtensionContext,
93
+ triggerTurn: boolean,
94
+ handoff?: ModelRoleHandoff,
95
+ ): Promise<void> {
88
96
  const policy = triggerTurn ? this.host.newWindowRequests : undefined;
89
97
  const checkOnly = !this.host.normalCompaction && policy === "pi-limits";
90
98
  if (!this.host.normalCompaction && !checkOnly) {
91
- await this.openWindow(ctx, triggerTurn, true);
99
+ await this.openWindow(ctx, triggerTurn, true, handoff);
92
100
  return;
93
101
  }
94
102
  const pending: Rollover = {
@@ -96,6 +104,7 @@ export class RolloverRequests {
96
104
  windowId: this.host.windows.current?.currentWindowId,
97
105
  phase: checkOnly ? "checking" : "compacting",
98
106
  triggerTurn,
107
+ ...(handoff ? { handoff } : {}),
99
108
  };
100
109
  this.rollover = pending;
101
110
  await new Promise<void>((resolve, reject) => {
@@ -106,7 +115,10 @@ export class RolloverRequests {
106
115
  pending.windowId === this.host.windows.current?.currentWindowId;
107
116
  const finish = (trim: boolean) => {
108
117
  this.rollover = undefined;
109
- void this.openWindow(ctx, triggerTurn, trim).then(resolve, reject);
118
+ void this.openWindow(ctx, triggerTurn, trim, handoff).then(
119
+ resolve,
120
+ reject,
121
+ );
110
122
  };
111
123
  ctx.compact({
112
124
  onComplete: () => {
@@ -38,6 +38,7 @@ const NOTE_ENTRIES = new Set([
38
38
  ]);
39
39
  const SHARING_ENTRIES = new Set([
40
40
  "codex-context-agent",
41
+ "codex-context-backend",
41
42
  "herdr-context-child",
42
43
  "shepherdr-attachment-route",
43
44
  "shepherdr-attachment-owner",
@@ -1,13 +1,21 @@
1
1
  import { type Static, Type } from "typebox";
2
2
  import { Check } from "typebox/value";
3
+ import {
4
+ CONTEXT_AGENT_PATTERN,
5
+ canonicalAgentName,
6
+ canonicalContextIdentity,
7
+ contextStorageAgentName,
8
+ pinnedContextIdentity,
9
+ } from "./agent-identity.js";
3
10
  import type { SavedNotesSession } from "./saved-session.js";
4
11
 
5
- const Agent = Type.String({ pattern: "^/root(?:/[a-zA-Z0-9_-]+)*$" });
12
+ const Agent = Type.String({ pattern: CONTEXT_AGENT_PATTERN });
6
13
  export const Identity = Type.Object({
7
14
  protocol: Type.Literal(1),
8
15
  sessionId: Type.String(),
9
16
  threadId: Type.String(),
10
17
  agentName: Agent,
18
+ storageAgentName: Type.Optional(Agent),
11
19
  storage: Type.Optional(
12
20
  Type.Union([Type.Literal("session"), Type.Literal("remote")]),
13
21
  ),
@@ -84,13 +92,14 @@ export function savedNotesIdentity(
84
92
  if (found) throw new Error("Conflicting saved notes identities");
85
93
  found = entry.data;
86
94
  }
87
- return (
88
- found ?? {
89
- protocol: 1,
90
- threadId: session.threadId,
91
- sessionId: session.threadId,
92
- agentName: "/root",
93
- }
95
+ return canonicalContextIdentity(
96
+ found ??
97
+ pinnedContextIdentity(session.threadId, session.entries) ?? {
98
+ protocol: 1,
99
+ threadId: session.threadId,
100
+ sessionId: session.threadId,
101
+ agentName: canonicalAgentName(session.threadId),
102
+ },
94
103
  );
95
104
  }
96
105
 
@@ -98,6 +107,6 @@ export function sameOwner(a: Identity, b: Identity): boolean {
98
107
  return (
99
108
  a.threadId === b.threadId &&
100
109
  a.sessionId === b.sessionId &&
101
- a.agentName === b.agentName
110
+ contextStorageAgentName(a) === contextStorageAgentName(b)
102
111
  );
103
112
  }
@@ -96,7 +96,7 @@ export function registerNotesSettingsCommand(
96
96
  },
97
97
  });
98
98
  pi.registerCommand("roles", {
99
- description: "Configure model roles and in-conversation handoffs",
99
+ description: "View model roles and JSON configuration guidance",
100
100
  handler: async (args, ctx) => {
101
101
  if (args.trim()) {
102
102
  await roles.command(args, ctx);
@@ -2,6 +2,13 @@ import { isDeepStrictEqual } from "node:util";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import type { Static } from "typebox";
4
4
  import { Check } from "typebox/value";
5
+ import {
6
+ canonicalAgentName,
7
+ contextAgentNames,
8
+ contextStorageAgentName,
9
+ contextTargetAgent,
10
+ isContextAgentName,
11
+ } from "./agent-identity.js";
5
12
  import type { HistorySearch } from "./history-search.js";
6
13
  import {
7
14
  readSavedNotesSession,
@@ -106,10 +113,14 @@ async function readSharedSession(
106
113
  if (typeof path !== "string" || !path.startsWith("/")) return;
107
114
  const target =
108
115
  namespace === "history"
109
- ? /^\/root(?:\/[a-zA-Z0-9_-]+)*$/.test(path)
116
+ ? isContextAgentName(path)
110
117
  ? path
111
118
  : undefined
112
- : /^(\/root(?:\/[a-zA-Z0-9_-]+)*?)\/notes(?:\/|$)/.exec(path)?.[1];
119
+ : contextTargetAgent(
120
+ "notes",
121
+ { path },
122
+ canonicalAgentName(ctx.sessionManager.getSessionId()),
123
+ );
113
124
  if (!target) return;
114
125
  const outputAgent = target;
115
126
  const current: SavedNotesSession = {
@@ -117,7 +128,7 @@ async function readSharedSession(
117
128
  entries: ctx.sessionManager.getEntries(),
118
129
  branch: ctx.sessionManager.getBranch(),
119
130
  };
120
- if (savedNotesIdentity(current).agentName === target) return;
131
+ if (contextAgentNames(savedNotesIdentity(current)).includes(target)) return;
121
132
  const visited = new Set<string>();
122
133
 
123
134
  const { read, reference } = createSharedSessionReader(
@@ -136,7 +147,7 @@ async function readSharedSession(
136
147
  if (visited.has(session.threadId)) return;
137
148
  visited.add(session.threadId);
138
149
  const identity = savedNotesIdentity(session);
139
- if (identity.agentName === destination) {
150
+ if (contextAgentNames(identity).includes(destination)) {
140
151
  if (
141
152
  namespace === "notes" &&
142
153
  identity.storage === "remote" &&
@@ -147,7 +158,7 @@ async function readSharedSession(
147
158
  )
148
159
  )
149
160
  return;
150
- return read(session, query, identity.agentName);
161
+ return read(session, query, destination);
151
162
  }
152
163
  const routes = new Map<string, Static<typeof Route>>();
153
164
  for (const value of records(session, "shepherdr-attachment-route"))
@@ -158,14 +169,18 @@ async function readSharedSession(
158
169
  routes.set(`${value.machine}\0${value.sessionFile}`, value);
159
170
  for (const route of routes.values()) {
160
171
  const link = route.plan.context;
161
- if (route.phase !== "ready" || !link || !inside(destination, link.alias))
162
- continue;
172
+ if (route.phase !== "ready" || !link) continue;
173
+ const alias =
174
+ destination === canonicalAgentName(link.target.threadId)
175
+ ? destination
176
+ : link.alias;
177
+ if (!inside(destination, alias)) continue;
163
178
  if (!sameOwner(identity, link.controller))
164
179
  throw new Error("Saved shared notes identity changed");
165
180
  return reference(
166
181
  link.target,
167
- `${link.target.agentName}${destination.slice(link.alias.length)}`,
168
- remap(query, link.alias, link.target.agentName),
182
+ `${link.target.agentName}${destination.slice(alias.length)}`,
183
+ remap(query, alias, link.target.agentName),
169
184
  route.machine === "local" ? route.sessionFile : undefined,
170
185
  route.detached?.context ?? link.targetNotes,
171
186
  route.detached?.context !== undefined,
@@ -178,9 +193,14 @@ async function readSharedSession(
178
193
  if (
179
194
  Check(Plan, owner) &&
180
195
  owner.context &&
181
- inside(destination, owner.context.controllerAlias)
196
+ (inside(destination, owner.context.controllerAlias) ||
197
+ destination === canonicalAgentName(owner.context.controller.threadId))
182
198
  ) {
183
199
  const link = owner.context;
200
+ const alias =
201
+ destination === canonicalAgentName(link.controller.threadId)
202
+ ? destination
203
+ : link.controllerAlias;
184
204
  if (!sameOwner(identity, link.target))
185
205
  throw new Error("Saved shared notes identity changed");
186
206
  const detached = records(
@@ -195,22 +215,21 @@ async function readSharedSession(
195
215
  : undefined;
196
216
  return reference(
197
217
  link.controller,
198
- `${link.controller.agentName}${destination.slice(link.controllerAlias.length)}`,
199
- remap(query, link.controllerAlias, link.controller.agentName),
218
+ `${link.controller.agentName}${destination.slice(alias.length)}`,
219
+ remap(query, alias, link.controller.agentName),
200
220
  link.controllerFile,
201
221
  snapshot ?? link.controllerNotes,
202
222
  snapshot !== undefined,
203
223
  );
204
224
  }
205
- const member = records(session, "herdr-context-child").findLast(
225
+ const members = records(session, "herdr-context-child").filter(
206
226
  (value) =>
207
227
  Check(Member, value) &&
208
228
  value.threadId === identity.threadId &&
209
- value.sessionId === identity.sessionId &&
210
- inside(destination, value.agentName),
229
+ value.sessionId === identity.sessionId,
211
230
  );
212
- if (Check(Member, member)) {
213
- if (member.machine !== "local") return;
231
+ for (const member of members) {
232
+ if (!Check(Member, member) || member.machine !== "local") continue;
214
233
  const saved = await readSavedNotesSession(
215
234
  member.sessionFile,
216
235
  signal,
@@ -219,12 +238,14 @@ async function readSharedSession(
219
238
  const child = savedNotesIdentity(saved);
220
239
  if (
221
240
  child.sessionId !== identity.sessionId ||
222
- child.agentName !== member.agentName
241
+ (child.agentName !== member.agentName &&
242
+ contextStorageAgentName(child) !== member.agentName)
223
243
  )
224
244
  throw new Error(
225
245
  "Saved shared notes belong to a different agent family",
226
246
  );
227
- return resolve(saved, destination, query);
247
+ const result = await resolve(saved, destination, query);
248
+ if (result) return result;
228
249
  }
229
250
  const routing = identity.routing;
230
251
  const suffix = ".jsonl.shepherdr-context.json";
@@ -237,7 +258,15 @@ async function readSharedSession(
237
258
  const parent = savedNotesIdentity(saved);
238
259
  if (
239
260
  parent.sessionId !== identity.sessionId ||
240
- !identity.agentName.startsWith(`${parent.agentName}/`)
261
+ !records(saved, "herdr-context-child").some(
262
+ (value) =>
263
+ Check(Member, value) &&
264
+ value.threadId === parent.threadId &&
265
+ value.sessionId === parent.sessionId &&
266
+ [identity.agentName, contextStorageAgentName(identity)].includes(
267
+ value.agentName,
268
+ ),
269
+ )
241
270
  )
242
271
  throw new Error("Saved shared notes parent identity changed");
243
272
  return resolve(saved, destination, query);
@@ -1,5 +1,6 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
2
  import { Check } from "typebox/value";
3
+ import { contextStorageAgentName } from "./agent-identity.js";
3
4
  import { useHistory } from "./history.js";
4
5
  import type { HistorySearch } from "./history-search.js";
5
6
  import { normalizeNoteParams, readNotes } from "./note-query.js";
@@ -99,7 +100,8 @@ export function createSharedSessionReader(
99
100
  }
100
101
  if (
101
102
  namespace === "history" ||
102
- destination !== identity.agentName ||
103
+ (destination !== identity.agentName &&
104
+ destination !== contextStorageAgentName(identity)) ||
103
105
  !Check(Snapshot, retained)
104
106
  )
105
107
  return;
@@ -111,8 +113,10 @@ export function createSharedSessionReader(
111
113
  customType: "codex-context-note-snapshot",
112
114
  data: {
113
115
  ...retained,
114
- files: retained.files.filter((file) =>
115
- file.path.startsWith(`${identity.agentName}/notes/`),
116
+ files: retained.files.filter(
117
+ (file) =>
118
+ file.path.startsWith(`${identity.agentName}/notes/`) ||
119
+ file.path.startsWith(`${contextStorageAgentName(identity)}/notes/`),
116
120
  ),
117
121
  },
118
122
  };
@@ -120,7 +124,7 @@ export function createSharedSessionReader(
120
124
  ...(await read(
121
125
  { threadId: identity.threadId, entries: [], branch: [entry] },
122
126
  query,
123
- identity.agentName,
127
+ destination,
124
128
  )),
125
129
  captured_at: new Date(retained.timestamp).toISOString(),
126
130
  warning: detached