@howaboua/pi-notes-compaction 0.0.15 → 0.0.17

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 (86) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +17 -2
  4. package/index.ts +8 -0
  5. package/package.json +16 -13
  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/{context-sharing.ts → notes/context-sharing.ts} +7 -2
  14. package/src/{extension-hooks.ts → notes/extension-hooks.ts} +1 -12
  15. package/src/{extension-sharing.ts → notes/extension-sharing.ts} +1 -1
  16. package/src/notes/feature.ts +234 -0
  17. package/src/notes/history-search-pruning.mjs +154 -0
  18. package/src/{history-search-worker.mjs → notes/history-search-worker.mjs} +1 -1
  19. package/src/{history-windows.ts → notes/history-windows.ts} +10 -22
  20. package/src/{history.ts → notes/history.ts} +6 -5
  21. package/src/{index.ts → notes/index.ts} +20 -11
  22. package/src/{integrations.ts → notes/integrations.ts} +19 -3
  23. package/src/{lifecycle.ts → notes/lifecycle.ts} +0 -2
  24. package/src/{note-query.ts → notes/note-query.ts} +3 -5
  25. package/src/notes/note-result.ts +119 -0
  26. package/src/{note-save-marker.ts → notes/note-save-marker.ts} +3 -1
  27. package/src/{notes-lookup.ts → notes/notes-lookup.ts} +1 -1
  28. package/src/{query-executor.ts → notes/query-executor.ts} +7 -2
  29. package/src/{query-input.ts → notes/query-input.ts} +1 -0
  30. package/src/{remote.ts → notes/remote.ts} +1 -1
  31. package/src/{saved-session-access.ts → notes/saved-session-access.ts} +14 -10
  32. package/src/{saved-session.ts → notes/saved-session.ts} +31 -15
  33. package/src/notes/saved-sharing-records.ts +170 -0
  34. package/src/notes/session-pruning-cleanup.mjs +163 -0
  35. package/src/notes/session-pruning-exit.mjs +312 -0
  36. package/src/{session-pruning-screen.ts → notes/session-pruning-screen.ts} +1 -1
  37. package/src/notes/session-pruning-sparse.mjs +133 -0
  38. package/src/notes/session-pruning-state.mjs +123 -0
  39. package/src/{session-pruning.ts → notes/session-pruning.ts} +39 -6
  40. package/src/{settings-command.ts → notes/settings-command.ts} +29 -42
  41. package/src/{settings-controls.ts → notes/settings-controls.ts} +61 -75
  42. package/src/{settings-screen.ts → notes/settings-screen.ts} +25 -11
  43. package/src/{settings.ts → notes/settings.ts} +37 -6
  44. package/src/{shared-notes.ts → notes/shared-notes.ts} +21 -13
  45. package/src/{shared-session-reader.ts → notes/shared-session-reader.ts} +8 -11
  46. package/src/{sharing-service.ts → notes/sharing-service.ts} +1 -1
  47. package/src/{tool-contracts.ts → notes/tool-contracts.ts} +71 -44
  48. package/src/{tools.ts → notes/tools.ts} +2 -2
  49. package/src/{tree-handoff-read.ts → notes/tree-handoff-read.ts} +47 -32
  50. package/src/{window-message.ts → notes/window-message.ts} +8 -25
  51. package/src/settings-navigation.ts +11 -0
  52. package/src/timestamps.ts +3 -0
  53. package/tsconfig.json +9 -0
  54. package/src/history-search-pruning.mjs +0 -120
  55. package/src/note-result.ts +0 -70
  56. package/src/saved-sharing-records.ts +0 -135
  57. /package/src/{agent-identity.ts → notes/agent-identity.ts} +0 -0
  58. /package/src/{binding-startup.ts → notes/binding-startup.ts} +0 -0
  59. /package/src/{bridge.ts → notes/bridge.ts} +0 -0
  60. /package/src/{compaction-projection.ts → notes/compaction-projection.ts} +0 -0
  61. /package/src/{context-owner.ts → notes/context-owner.ts} +0 -0
  62. /package/src/{fresh-checkpoint.ts → notes/fresh-checkpoint.ts} +0 -0
  63. /package/src/{fresh-notes.ts → notes/fresh-notes.ts} +0 -0
  64. /package/src/{history-search-protocol.ts → notes/history-search-protocol.ts} +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.ts → notes/notes.ts} +0 -0
  71. /package/src/{rollover.ts → notes/rollover.ts} +0 -0
  72. /package/src/{saved-session-index.mjs → notes/saved-session-index.mjs} +0 -0
  73. /package/src/{saved-session.mjs → notes/saved-session.mjs} +0 -0
  74. /package/src/{session-pruning-content.ts → notes/session-pruning-content.ts} +0 -0
  75. /package/src/{session-pruning-plan.ts → notes/session-pruning-plan.ts} +0 -0
  76. /package/src/{session-pruning-policy.ts → notes/session-pruning-policy.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/{store.ts → notes/store.ts} +0 -0
  81. /package/src/{task-boundary.ts → notes/task-boundary.ts} +0 -0
  82. /package/src/{tree-archive-manifest.mjs → notes/tree-archive-manifest.mjs} +0 -0
  83. /package/src/{tree-archive.ts → notes/tree-archive.ts} +0 -0
  84. /package/src/{tree-checkpoint.ts → notes/tree-checkpoint.ts} +0 -0
  85. /package/src/{window-checkpoint.ts → notes/window-checkpoint.ts} +0 -0
  86. /package/src/{windows.ts → notes/windows.ts} +0 -0
@@ -1,6 +1,7 @@
1
1
  import { join } from "node:path";
2
2
  import {
3
3
  type ExtensionAPI,
4
+ type ExtensionContext,
4
5
  getAgentDir,
5
6
  } from "@earendil-works/pi-coding-agent";
6
7
  import { createNotesActivation } from "./activation.js";
@@ -14,18 +15,17 @@ import { NotesLifecycle } from "./lifecycle.js";
14
15
  import { createModelRoles } from "./model-roles.js";
15
16
  import { registerNoteSaveMarkers } from "./note-save-marker.js";
16
17
  import { SessionPruning } from "./session-pruning.js";
17
- import { registerNotesSettingsCommand } from "./settings-command.js";
18
- import { NotesStore } from "./store.js";
18
+ import type { NotesSettings } from "./settings.js";
19
+ import type { NotesStore } from "./store.js";
19
20
  import { createTools } from "./tools.js";
20
21
  import { WindowCheckpoints } from "./window-checkpoint.js";
21
22
  import { registerWindowRenderer } from "./windows.js";
22
23
 
23
- export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
24
+ export async function createNotesRuntime(pi: ExtensionAPI, store: NotesStore) {
24
25
  registerWindowRenderer(pi);
25
26
  registerCheckpointRenderer(pi);
26
27
  const dir = join(getAgentDir(), "notes-compaction");
27
28
  const settingsPath = join(dir, "settings.json");
28
- const store = new NotesStore(join(dir, "notes.sqlite"));
29
29
  const search = new HistorySearch(join(dir, "history-search.sqlite"));
30
30
  const lifecycle = new NotesLifecycle(pi, store);
31
31
  const checkpoints = new WindowCheckpoints((entries) =>
@@ -86,7 +86,6 @@ export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
86
86
  owner,
87
87
  checkpoints,
88
88
  markers,
89
- family,
90
89
  );
91
90
  const sessionPruning = new SessionPruning(
92
91
  pi,
@@ -98,19 +97,29 @@ export default async function notesCompaction(pi: ExtensionAPI): Promise<void> {
98
97
  pi.on("session_shutdown", () => {
99
98
  lifecycle.reset();
100
99
  lifecycle.active = false;
101
- store.close();
102
100
  search.close();
103
101
  stopOwner();
104
102
  stopAdmission();
105
103
  });
106
- registerNotesSettingsCommand(
107
- pi,
104
+ return {
108
105
  activation,
109
106
  lifecycle,
110
- store,
111
107
  search,
112
- settingsPath,
113
108
  sessionPruning,
114
109
  roles,
115
- );
110
+ async start(ctx: ExtensionContext, settings?: NotesSettings) {
111
+ markers.start(ctx);
112
+ activation.start(ctx, family, settings);
113
+ if (activation.available) {
114
+ try {
115
+ await checkpoints.restore(ctx);
116
+ } catch (error) {
117
+ ctx.ui.notify(`Context checkpoint failed: ${String(error)}`, "error");
118
+ }
119
+ }
120
+ sessionPruning.start(ctx);
121
+ },
122
+ };
116
123
  }
124
+
125
+ export type NotesRuntime = Awaited<ReturnType<typeof createNotesRuntime>>;
@@ -3,12 +3,14 @@ import type {
3
3
  ExtensionAPI,
4
4
  ExtensionContext,
5
5
  } from "@earendil-works/pi-coding-agent";
6
+ import type { Schema } from "@earendil-works/pi-schema";
6
7
  import type { NotesActivation } from "./activation.js";
7
8
  import type { NotesLifecycle } from "./lifecycle.js";
8
9
  import {
9
10
  GPT_NEW_CONTEXT_DESCRIPTION,
10
11
  HISTORY_USAGE,
11
12
  NEW_CONTEXT_DESCRIPTION,
13
+ NOTES_SCHEMA,
12
14
  NOTES_USAGE,
13
15
  } from "./tool-contracts.js";
14
16
  import type { createTools } from "./tools.js";
@@ -53,6 +55,7 @@ export async function registerNotesToolIntegrations(
53
55
  throw error;
54
56
  }
55
57
  let refreshNested = () => {};
58
+ const noteProperties = NOTES_SCHEMA["properties"] as Record<string, Schema>;
56
59
  try {
57
60
  const { adaptToolForCodeMode, registerCodeModeExtensionTools } =
58
61
  await import("@howaboua/pi-codex-conversion/code-mode");
@@ -61,8 +64,8 @@ export async function registerNotesToolIntegrations(
61
64
  () =>
62
65
  tools
63
66
  .filter((tool) => tool.name === "notes" || tool.name === "history")
64
- .map((tool) =>
65
- adaptToolForCodeMode(tool, {
67
+ .map((tool) => ({
68
+ ...adaptToolForCodeMode(tool, {
66
69
  discovery: "help",
67
70
  usage: tool.name === "notes" ? NOTES_USAGE : HISTORY_USAGE,
68
71
  deferLoading: tool.name !== "notes",
@@ -71,7 +74,20 @@ export async function registerNotesToolIntegrations(
71
74
  ? { resultValue: historyResultValue }
72
75
  : {}),
73
76
  }),
74
- ),
77
+ // Code checks inputs before Pi can normalise these aliases.
78
+ ...(tool.name === "notes"
79
+ ? {
80
+ inputSchema: {
81
+ ...NOTES_SCHEMA,
82
+ properties: {
83
+ ...noteProperties,
84
+ content: noteProperties["text"],
85
+ end_line: noteProperties["stop_line"],
86
+ },
87
+ },
88
+ }
89
+ : {}),
90
+ })),
75
91
  { isActive: () => lifecycle.active },
76
92
  );
77
93
  refreshNested = registration.refresh;
@@ -229,8 +229,6 @@ export class NotesLifecycle {
229
229
  );
230
230
  this.windows.current = ids;
231
231
  if (handoff) message.content = `${message.content}\n\nRole: ${handoff.id}`;
232
- if (triggerTurn)
233
- message.content = `${message.content}\n\n${this.gptPromptMode() ? "Saved notes→notes tool→resume task" : "Read your saved notes with the notes tool and resume the task."}`;
234
232
  this.sendMessage(message, { triggerTurn });
235
233
  }
236
234
 
@@ -1,3 +1,4 @@
1
+ import { minuteTimestamp } from "../timestamps.js";
1
2
  import type { NoteRevision } from "./store.js";
2
3
 
3
4
  export function canonicalPath(
@@ -66,9 +67,6 @@ export function readNotes(
66
67
  file: {
67
68
  path: `${root}${note.path}`,
68
69
  content: start <= stop ? lines.slice(start, stop + 1).join("\n") : "",
69
- start_line: start + 1,
70
- stop_line: Math.max(start, stop) + 1,
71
- total_lines: lines.length,
72
70
  ...(note.mode === "append" ? { append_only: true } : {}),
73
71
  },
74
72
  };
@@ -88,9 +86,9 @@ export function readNotes(
88
86
  )
89
87
  .map((note) => ({
90
88
  path: `${root}${note.path}`,
91
- updated_at: new Date(note.updatedAt).toISOString(),
89
+ updated_at: minuteTimestamp(note.updatedAt),
92
90
  ...(by === "created_at"
93
- ? { created_at: new Date(note.createdAt).toISOString() }
91
+ ? { created_at: minuteTimestamp(note.createdAt) }
94
92
  : {}),
95
93
  }));
96
94
  const limit = integer(params["max_results"], 20, 100);
@@ -0,0 +1,119 @@
1
+ import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ arr,
4
+ bool,
5
+ compile,
6
+ int,
7
+ nul,
8
+ obj,
9
+ opt,
10
+ str,
11
+ union,
12
+ unsafe,
13
+ } from "@earendil-works/pi-schema";
14
+
15
+ const OPTIONAL_STRING = opt(str());
16
+ const OPTIONAL_BOOLEAN = opt(bool());
17
+ const MATCH = obj({ line_number: int(), line: str() }, { open: true });
18
+
19
+ // Pi codemode needs this declaration to return structuredContent rather than text.
20
+ export const NOTES_OUTPUT_SCHEMA = {
21
+ ...obj({}, { open: true }),
22
+ additionalProperties: true,
23
+ };
24
+
25
+ const NOTES_RESULT_SCHEMA = obj(
26
+ {
27
+ file: opt(
28
+ union([
29
+ obj(
30
+ {
31
+ path: str(),
32
+ content: OPTIONAL_STRING,
33
+ append_only: OPTIONAL_BOOLEAN,
34
+ },
35
+ { open: true },
36
+ ),
37
+ nul(),
38
+ ]),
39
+ ),
40
+ files: opt(
41
+ arr(
42
+ obj(
43
+ {
44
+ path: str(),
45
+ updated_at: OPTIONAL_STRING,
46
+ created_at: OPTIONAL_STRING,
47
+ matches: opt(arr(MATCH)),
48
+ truncated: OPTIONAL_BOOLEAN,
49
+ append_only: OPTIONAL_BOOLEAN,
50
+ },
51
+ { open: true },
52
+ ),
53
+ ),
54
+ ),
55
+ usage: OPTIONAL_STRING,
56
+ warnings: opt(arr(str())),
57
+ warning: OPTIONAL_STRING,
58
+ truncated: OPTIONAL_BOOLEAN,
59
+ read_only: OPTIONAL_BOOLEAN,
60
+ saved_at: OPTIONAL_STRING,
61
+ captured_at: OPTIONAL_STRING,
62
+ results: OPTIONAL_STRING,
63
+ actions: opt(
64
+ unsafe<Record<string, string>>({
65
+ type: "object",
66
+ patternProperties: { "^.*$": str() },
67
+ }),
68
+ ),
69
+ writes: OPTIONAL_STRING,
70
+ paths: OPTIONAL_STRING,
71
+ ranges: OPTIONAL_STRING,
72
+ defaults: OPTIONAL_STRING,
73
+ },
74
+ { open: false },
75
+ );
76
+
77
+ const notesResultSchemaValidator = compile(NOTES_RESULT_SCHEMA);
78
+
79
+ /** One canonical payload for native text and every programmatic caller. */
80
+ export function noteResult(payload: unknown): AgentToolResult<unknown> {
81
+ if (!notesResultSchemaValidator.check(payload))
82
+ throw new Error(
83
+ "Notes returned invalid data. Read the note before retrying a write.",
84
+ );
85
+ // Keep recovery warnings, but omit sharing and storage bookkeeping.
86
+ const {
87
+ read_only: _readOnly,
88
+ warning,
89
+ saved_at: _savedAt,
90
+ captured_at: _capturedAt,
91
+ ...visible
92
+ } = payload;
93
+ if (warning !== undefined)
94
+ visible.warnings = [...(visible.warnings ?? []), warning];
95
+ if (visible.file)
96
+ visible.file = {
97
+ path: visible.file.path,
98
+ ...(visible.file.content === undefined
99
+ ? {}
100
+ : { content: visible.file.content }),
101
+ ...(visible.file.append_only === undefined
102
+ ? {}
103
+ : { append_only: visible.file.append_only }),
104
+ };
105
+ if (visible.files)
106
+ visible.files = visible.files.map(
107
+ ({ path, matches, truncated, append_only }) => ({
108
+ path,
109
+ ...(matches === undefined ? {} : { matches }),
110
+ ...(truncated === undefined ? {} : { truncated }),
111
+ ...(append_only === undefined ? {} : { append_only }),
112
+ }),
113
+ );
114
+ return {
115
+ content: [{ type: "text", text: JSON.stringify(visible) }],
116
+ structuredContent: visible,
117
+ details: {},
118
+ };
119
+ }
@@ -25,7 +25,6 @@ export function registerNoteSaveMarkers(
25
25
  manager = ctx.sessionManager;
26
26
  cached = undefined;
27
27
  };
28
- pi.on("session_start", restore);
29
28
  pi.on("session_tree", restore);
30
29
  pi.on("session_compact", restore);
31
30
  pi.on("session_shutdown", () => {
@@ -63,6 +62,9 @@ export function registerNoteSaveMarkers(
63
62
  })("", 0, 0);
64
63
  });
65
64
  return {
65
+ start(ctx: ExtensionContext) {
66
+ restore(undefined, ctx);
67
+ },
66
68
  record(
67
69
  ctx: ExtensionContext,
68
70
  windowId: string | undefined,
@@ -79,7 +79,7 @@ export async function lookupNotes(
79
79
  );
80
80
  else if (lookupFailed)
81
81
  warnings.push(
82
- "Some notes could not be retrieved. Available notes are shown; retry the lookup to check for missing results.",
82
+ "Remote notes could not be checked. Local results are shown; retry to check for remote-only notes.",
83
83
  );
84
84
  if (responses.length && canProject && replacementsInScope)
85
85
  warnings.push(
@@ -75,7 +75,12 @@ export function createQueryExecutor(
75
75
  ctx,
76
76
  signal,
77
77
  );
78
- if (routed) return routed;
78
+ if (routed)
79
+ return {
80
+ ...routed,
81
+ ...noteResult(routed.structuredContent),
82
+ details: routed.details,
83
+ };
79
84
  } catch (error) {
80
85
  signal?.throwIfAborted();
81
86
  if (!unavailable || !sharedNotesUnavailable(error)) throw error;
@@ -218,7 +223,7 @@ export function createQueryExecutor(
218
223
  )
219
224
  )
220
225
  throw new Error(
221
- "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.",
226
+ "That agent's history is unavailable here. Omit agent_name to search this session, or request an accessible handoff from its owner.",
222
227
  );
223
228
  signal?.throwIfAborted();
224
229
  return result(
@@ -69,6 +69,7 @@ export function normalizeQueryInput(
69
69
  if (action !== undefined) params["action"] = action;
70
70
  if (namespace === "notes") {
71
71
  alias(params, "address", "path");
72
+ if (action === "read") alias(params, "end_line", "stop_line");
72
73
  if (action === "write" || action === "append") {
73
74
  alias(params, "content", "text");
74
75
  alias(params, "body", "text");
@@ -278,7 +278,7 @@ export async function executeRemoteAttachment(
278
278
  reference,
279
279
  );
280
280
  return {
281
- ...noteResult({ usage: "Saved remote read completed" }),
281
+ ...noteResult({}),
282
282
  details: {
283
283
  codexHistoryNotes: {},
284
284
  externalNotesResponses: responses.map(({ bytes, ...response }) => ({
@@ -1,5 +1,4 @@
1
- import { Type } from "typebox";
2
- import { Check } from "typebox/value";
1
+ import { arr, compile, obj, str } from "@earendil-works/pi-schema";
3
2
  import type {
4
3
  SavedSessionLoader,
5
4
  SavedSessionLocator,
@@ -12,13 +11,18 @@ import {
12
11
  import { savedFamilyIdentity } from "./saved-sharing-records.js";
13
12
  import type { NotesStore } from "./store.js";
14
13
 
15
- const Locations = Type.Array(
16
- Type.Object({
17
- machine: Type.String({ minLength: 1 }),
18
- sessionFile: Type.String({ minLength: 1 }),
19
- }),
14
+ const Locations = arr(
15
+ obj(
16
+ {
17
+ machine: str({ minLength: 1 }),
18
+ sessionFile: str({ minLength: 1 }),
19
+ },
20
+ { open: true },
21
+ ),
20
22
  );
21
23
 
24
+ const locationsValidator = compile(Locations);
25
+
22
26
  /** Local is relative to the session carrying the edge, not the machine running this reader. */
23
27
  export function createSavedSessionAccess(
24
28
  store: Pick<NotesStore, "sessionFile">,
@@ -57,7 +61,7 @@ export function createSavedSessionAccess(
57
61
  : (() => {
58
62
  throw Object.assign(
59
63
  new Error(
60
- "Saved shared sessions on that machine are unavailable. Resume the shared agent and reconnect its machine, or make its saved Pi JSONL session available locally.",
64
+ "Saved context on that machine is unavailable. Request a handoff from its owner, or ask the user to reconnect the machine before retrying.",
61
65
  ),
62
66
  { code: "SAVED_SESSION_UNAVAILABLE" },
63
67
  );
@@ -86,7 +90,7 @@ export function createSavedSessionAccess(
86
90
  member.agentName !== target
87
91
  )
88
92
  throw new Error(
89
- "Saved shared notes belong to a different agent family",
93
+ "This session cannot access the requested saved context. Request an accessible handoff or note path from its owner.",
90
94
  );
91
95
  return saved;
92
96
  }
@@ -100,7 +104,7 @@ export function createSavedSessionAccess(
100
104
  signal?.throwIfAborted();
101
105
  const value = await loader.find(threadId, signal);
102
106
  signal?.throwIfAborted();
103
- if (!Check(Locations, value))
107
+ if (!locationsValidator.check(value))
104
108
  throw new Error(
105
109
  "Saved session discovery response is invalid. Update Notes on the other machine and retry.",
106
110
  );
@@ -1,6 +1,14 @@
1
1
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- import { Check } from "typebox/value";
2
+ import {
3
+ arr,
4
+ compile,
5
+ nul,
6
+ num,
7
+ obj,
8
+ opt,
9
+ str,
10
+ union,
11
+ } from "@earendil-works/pi-schema";
4
12
 
5
13
  export { readSavedNotesSession } from "./saved-session.mjs";
6
14
  export interface SavedNotesSession {
@@ -10,22 +18,30 @@ export interface SavedNotesSession {
10
18
  savedAt?: number;
11
19
  }
12
20
 
13
- const SavedEntry = Type.Object({
14
- type: Type.String(),
15
- id: Type.String(),
16
- parentId: Type.Union([Type.String(), Type.Null()]),
17
- timestamp: Type.String(),
18
- });
19
- const SavedSession = Type.Object({
20
- threadId: Type.String({ minLength: 1 }),
21
- entries: Type.Array(SavedEntry),
22
- branch: Type.Array(SavedEntry),
23
- savedAt: Type.Optional(Type.Number()),
24
- });
21
+ const SavedEntry = obj(
22
+ {
23
+ type: str(),
24
+ id: str(),
25
+ parentId: union([str(), nul()]),
26
+ timestamp: str(),
27
+ },
28
+ { open: true },
29
+ );
30
+ const SavedSession = obj(
31
+ {
32
+ threadId: str({ minLength: 1 }),
33
+ entries: arr(SavedEntry),
34
+ branch: arr(SavedEntry),
35
+ savedAt: opt(num()),
36
+ },
37
+ { open: true },
38
+ );
39
+
40
+ const savedSessionValidator = compile(SavedSession);
25
41
 
26
42
  /** Remote loaders carry data, not authority. Native identity is checked by the graph reader. */
27
43
  export function validateSavedNotesSession(value: unknown): SavedNotesSession {
28
- if (!Check(SavedSession, value))
44
+ if (!savedSessionValidator.check(value))
29
45
  throw new Error(
30
46
  "Saved session response is invalid. Update Notes on the other machine and retry.",
31
47
  );
@@ -0,0 +1,170 @@
1
+ import {
2
+ arr,
3
+ compile,
4
+ lit,
5
+ num,
6
+ obj,
7
+ opt,
8
+ type Static,
9
+ str,
10
+ union,
11
+ unknown,
12
+ } from "@earendil-works/pi-schema";
13
+ import {
14
+ CONTEXT_AGENT_PATTERN,
15
+ canonicalAgentName,
16
+ canonicalContextIdentity,
17
+ contextStorageAgentName,
18
+ pinnedContextIdentity,
19
+ } from "./agent-identity.js";
20
+ import type { SavedNotesSession } from "./saved-session.js";
21
+
22
+ const Agent = str({ pattern: CONTEXT_AGENT_PATTERN });
23
+ export const Identity = obj(
24
+ {
25
+ protocol: lit(1),
26
+ sessionId: str(),
27
+ threadId: str(),
28
+ agentName: Agent,
29
+ storageAgentName: opt(Agent),
30
+ storage: opt(union([lit("session"), lit("remote")])),
31
+ routing: opt(unknown()),
32
+ },
33
+ { open: true },
34
+ );
35
+ export const Member = obj(
36
+ {
37
+ threadId: str(),
38
+ sessionId: str(),
39
+ agentName: Agent,
40
+ machine: str(),
41
+ sessionFile: str(),
42
+ },
43
+ { open: true },
44
+ );
45
+ export const Plan = obj(
46
+ {
47
+ controllerSessionId: str(),
48
+ targetSessionId: str(),
49
+ context: opt(
50
+ obj(
51
+ {
52
+ controller: Identity,
53
+ target: Identity,
54
+ alias: Agent,
55
+ controllerAlias: Agent,
56
+ controllerFile: opt(str()),
57
+ controllerMachine: opt(str()),
58
+ controllerNotes: unknown(),
59
+ targetNotes: unknown(),
60
+ },
61
+ { open: true },
62
+ ),
63
+ ),
64
+ },
65
+ { open: true },
66
+ );
67
+ export const Route = obj(
68
+ {
69
+ plan: Plan,
70
+ machine: str(),
71
+ sessionFile: str(),
72
+ phase: union([lit("pending"), lit("ready")]),
73
+ detached: opt(obj({ context: opt(unknown()) }, { open: true })),
74
+ },
75
+ { open: true },
76
+ );
77
+ export const Detachment = obj(
78
+ {
79
+ plan: Plan,
80
+ context: opt(unknown()),
81
+ },
82
+ { open: true },
83
+ );
84
+ export const Snapshot = obj(
85
+ {
86
+ protocol: lit(1),
87
+ timestamp: num(),
88
+ files: arr(
89
+ obj(
90
+ {
91
+ path: str(),
92
+ text: str(),
93
+ createdAt: num(),
94
+ updatedAt: num(),
95
+ operation: union([
96
+ lit("local_append_overlay"),
97
+ lit("local_replacement"),
98
+ ]),
99
+ },
100
+ { open: true },
101
+ ),
102
+ ),
103
+ },
104
+ { open: true },
105
+ );
106
+ export const Parent = obj(
107
+ {
108
+ transport: lit("shepherdr"),
109
+ parent: str(),
110
+ savedParent: opt(
111
+ obj({ machine: str(), sessionFile: str() }, { open: true }),
112
+ ),
113
+ },
114
+ { open: true },
115
+ );
116
+ export type Identity = Static<typeof Identity>;
117
+
118
+ const identityValidator = compile(Identity);
119
+
120
+ /** Ordinary family membership is immutable, explicit and native-session owned. */
121
+ export function savedFamilyIdentity(
122
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
123
+ ): Identity | undefined {
124
+ const identity = savedNotesIdentity(session);
125
+ if (
126
+ identity.storage === undefined ||
127
+ !session.entries.some(
128
+ (entry) =>
129
+ entry.type === "custom" &&
130
+ entry.customType === "codex-context-agent" &&
131
+ identityValidator.check(entry.data) &&
132
+ entry.data.threadId === session.threadId,
133
+ )
134
+ )
135
+ return;
136
+ return identity;
137
+ }
138
+
139
+ /** Persisted sharing is session-scoped. Forks never inherit the source agent's address. */
140
+ export function savedNotesIdentity(
141
+ session: Pick<SavedNotesSession, "threadId" | "entries">,
142
+ ): Identity {
143
+ let found: Identity | undefined;
144
+ for (const entry of session.entries) {
145
+ if (entry.type !== "custom" || entry.customType !== "codex-context-agent")
146
+ continue;
147
+ if (!identityValidator.check(entry.data))
148
+ throw new Error("Invalid saved notes identity");
149
+ if (entry.data.threadId !== session.threadId) continue;
150
+ if (found) throw new Error("Conflicting saved notes identities");
151
+ found = entry.data;
152
+ }
153
+ return canonicalContextIdentity(
154
+ found ??
155
+ pinnedContextIdentity(session.threadId, session.entries) ?? {
156
+ protocol: 1,
157
+ threadId: session.threadId,
158
+ sessionId: session.threadId,
159
+ agentName: canonicalAgentName(session.threadId),
160
+ },
161
+ );
162
+ }
163
+
164
+ export function sameOwner(a: Identity, b: Identity): boolean {
165
+ return (
166
+ a.threadId === b.threadId &&
167
+ a.sessionId === b.sessionId &&
168
+ contextStorageAgentName(a) === contextStorageAgentName(b)
169
+ );
170
+ }