@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,18 +1,16 @@
1
- import { join } from "node:path";
2
1
  import type {
3
2
  ExtensionAPI,
4
3
  ExtensionContext,
5
4
  } from "@earendil-works/pi-coding-agent";
6
- import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
7
5
  import { type NotesBridge, TOOL_NAMES } from "./bridge.js";
8
6
  import { indexHistory } from "./history.js";
9
7
  import type { HistorySearch } from "./history-search.js";
10
8
  import type { NotesLifecycle } from "./lifecycle.js";
11
9
  import { sessionRef } from "./notes.js";
12
10
  import {
11
+ loadNotesSettings,
13
12
  modelIsActive,
14
13
  type NotesSettings,
15
- readSettings,
16
14
  writeSettings,
17
15
  } from "./settings.js";
18
16
  import type { NotesStore } from "./store.js";
@@ -35,6 +33,7 @@ export function createNotesActivation(
35
33
  if (lifecycle.active) lifecycle.reset(ctx);
36
34
  lifecycle.active = false;
37
35
  search.setSession(undefined);
36
+ store.close();
38
37
  pi.setActiveTools(
39
38
  pi
40
39
  .getActiveTools()
@@ -99,19 +98,18 @@ export function createNotesActivation(
99
98
  lifecycle.idleMinutes = value.idleMinutes;
100
99
  lifecycle.taskBoundaryReminder = value.taskBoundaryReminder;
101
100
  }
102
- function start(ctx: ExtensionContext, family: NotesBridge): void {
101
+ function start(
102
+ ctx: ExtensionContext,
103
+ family: NotesBridge,
104
+ initial?: NotesSettings,
105
+ ): void {
103
106
  search.setSession(undefined);
104
107
  lifecycle.reset(ctx);
105
108
  lifecycle.active = false;
106
109
  ready = false;
107
110
  unavailable = undefined;
108
111
  try {
109
- settings = readSettings(settingsPath, [
110
- join(getAgentDir(), "pi-codex-conversion.json"),
111
- ...(ctx.isProjectTrusted()
112
- ? [join(ctx.cwd, CONFIG_DIR_NAME, "pi-codex-conversion.json")]
113
- : []),
114
- ]);
112
+ settings = initial ?? loadNotesSettings(ctx);
115
113
  writeSettings(settingsPath, settings);
116
114
  applySettings(settings);
117
115
  lifecycle.bridge = family;
@@ -150,7 +150,7 @@ export function createAttachmentSharing(
150
150
  const details = readAttachmentSnapshot(snapshot, params);
151
151
  return {
152
152
  ...noteResult({ ...details, ...annotation }),
153
- details: { codexHistoryNotes: details },
153
+ details: { codexHistoryNotes: { ...details, ...annotation } },
154
154
  };
155
155
  },
156
156
  } satisfies Pick<
@@ -1,35 +1,48 @@
1
- import { Type } from "typebox";
2
- import { Check } from "typebox/value";
1
+ import {
2
+ arr,
3
+ compile,
4
+ lit,
5
+ num,
6
+ obj,
7
+ opt,
8
+ str,
9
+ union,
10
+ } from "@earendil-works/pi-schema";
3
11
  import { contextTargetAgent, isContextAgentName } from "./agent-identity.js";
4
12
  import type { RemoteNoteReference } from "./context-sharing.js";
5
13
  import { normalizeNoteParams, readNotes } from "./notes.js";
6
14
  import type { NoteRevision } from "./store.js";
7
15
 
8
- const Snapshot = Type.Object({
9
- protocol: Type.Literal(1),
10
- timestamp: Type.Number({ minimum: 0 }),
11
- files: Type.Array(
12
- Type.Object({
13
- path: Type.String(),
14
- text: Type.String(),
15
- createdAt: Type.Number(),
16
- updatedAt: Type.Number(),
17
- operation: Type.Optional(
18
- Type.Union([
19
- Type.Literal("local_append_overlay"),
20
- Type.Literal("local_replacement"),
21
- ]),
16
+ const Snapshot = obj(
17
+ {
18
+ protocol: lit(1),
19
+ timestamp: num({ minimum: 0 }),
20
+ files: arr(
21
+ obj(
22
+ {
23
+ path: str(),
24
+ text: str(),
25
+ createdAt: num(),
26
+ updatedAt: num(),
27
+ operation: opt(
28
+ union([lit("local_append_overlay"), lit("local_replacement")]),
29
+ ),
30
+ },
31
+ { open: true },
22
32
  ),
23
- }),
24
- ),
25
- });
33
+ ),
34
+ },
35
+ { open: true },
36
+ );
37
+
38
+ const snapshotValidator = compile(Snapshot);
26
39
 
27
40
  /** Retained checkpoints remain readable without a running owner or database. */
28
41
  export function readAttachmentSnapshot(
29
42
  snapshot: unknown,
30
43
  params: Record<string, unknown>,
31
44
  ): Record<string, unknown> {
32
- if (!Check(Snapshot, snapshot))
45
+ if (!snapshotValidator.check(snapshot))
33
46
  throw new Error("Invalid retained note snapshot");
34
47
  if (
35
48
  !["list_files_by_prefix", "read_file", "search_contents"].includes(
@@ -85,6 +85,7 @@ export interface NotesOwner {
85
85
 
86
86
  export interface NotesBridge {
87
87
  protocol: 1;
88
+ loadSavedSession?: import("./context-sharing.js").SavedSessionLoader;
88
89
  /** Preserve the owner's chronological entry while enabling developer-role delivery. */
89
90
  prepareReminder?(entry: CustomMessageEntryDraft): CustomMessageEntryDraft;
90
91
  lookup?(
@@ -46,6 +46,20 @@ export type ContextRouter = ((
46
46
  requiresRemoteScope?(ctx: ExtensionContext): boolean;
47
47
  };
48
48
 
49
+ export interface SavedSessionLocator {
50
+ machine: string;
51
+ sessionFile: string;
52
+ }
53
+
54
+ export type SavedSessionLoader = ((
55
+ locator: SavedSessionLocator,
56
+ history: boolean,
57
+ signal?: AbortSignal,
58
+ ) => Promise<unknown>) & {
59
+ /** Exact native-thread discovery only; returned locators are untrusted hints. */
60
+ find?(threadId: string, signal?: AbortSignal): Promise<unknown>;
61
+ };
62
+
49
63
  /** Remote checkpoints retain an authenticated address, never decrypted note contents. */
50
64
  export interface RemoteNoteReference {
51
65
  protocol: 1;
@@ -118,6 +132,7 @@ export interface ContextSharingService {
118
132
  signal?: AbortSignal,
119
133
  ): Promise<SharedContextResult>;
120
134
  registerRouter(router: ContextRouter): () => void;
135
+ registerSavedSessionLoader?(loader: SavedSessionLoader): () => void;
121
136
  }
122
137
 
123
138
  export const CONTEXT_SHARING_AVAILABLE =
@@ -126,7 +141,10 @@ export const CONTEXT_SHARING_REQUEST =
126
141
  "pi-notes-compaction:context-sharing:request";
127
142
 
128
143
  /** Optional, load-order-independent integration. No provider or tool schema changes. */
129
- export function connectNotesContextSharing(pi: ExtensionAPI): {
144
+ export function connectNotesContextSharing(
145
+ pi: ExtensionAPI,
146
+ onAvailable?: () => void,
147
+ ): {
130
148
  readonly service: ContextSharingService | undefined;
131
149
  dispose(): void;
132
150
  } {
@@ -142,8 +160,10 @@ export function connectNotesContextSharing(pi: ExtensionAPI): {
142
160
  typeof candidate.bind === "function" &&
143
161
  typeof candidate.execute === "function" &&
144
162
  typeof candidate.registerRouter === "function"
145
- )
163
+ ) {
146
164
  service = candidate as ContextSharingService;
165
+ onAvailable?.();
166
+ }
147
167
  });
148
168
  pi.events.emit(CONTEXT_SHARING_REQUEST, { protocol: 1 });
149
169
  return {
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import type { NotesActivation } from "./activation.js";
3
- import type { NotesBridge, NotesOwner } from "./bridge.js";
3
+ import type { NotesOwner } from "./bridge.js";
4
4
  import { NESTED_NOTE_OUTCOME, type NestedNoteOutcome } from "./fresh-notes.js";
5
5
  import { registerNotesCompactionIntegration } from "./integrations.js";
6
6
  import type { NotesLifecycle } from "./lifecycle.js";
@@ -20,18 +20,7 @@ export async function registerNotesHooks(
20
20
  owner: NotesOwner,
21
21
  checkpoints: WindowCheckpoints,
22
22
  markers: ReturnType<typeof registerNoteSaveMarkers>,
23
- family: NotesBridge,
24
23
  ) {
25
- pi.on("session_start", async (_event, ctx) => {
26
- activation.start(ctx, family);
27
- if (activation.available) {
28
- try {
29
- await checkpoints.restore(ctx);
30
- } catch (error) {
31
- ctx.ui.notify(`Context checkpoint failed: ${String(error)}`, "error");
32
- }
33
- }
34
- });
35
24
  pi.on("before_agent_start", (event, ctx) => {
36
25
  activation.refreshActivation(ctx);
37
26
  if (lifecycle.active) return lifecycle.beforeStart(ctx, event);
@@ -48,6 +48,7 @@ export async function registerNotesSharing(
48
48
  const family = {
49
49
  ...remote,
50
50
  protocol: 1 as const,
51
+ loadSavedSession: route.loadSavedSession,
51
52
  agentName: (ctx: ExtensionContext) => contextAgentIdentity(ctx).agentName,
52
53
  route: async (
53
54
  query: import("./bridge.js").LookupQuery,
@@ -80,7 +81,7 @@ export async function registerNotesSharing(
80
81
  const { externalNotesResponses, ...details } = result.details;
81
82
  if (!remote.projectResult || remote.canProject?.(ctx) === false) {
82
83
  const warning =
83
- "Shared encrypted contents are unavailable on this model. Local results remain available. Use a compatible Codex model with PCC for remote contents.";
84
+ "Some notes cannot be read with this model. Available notes are shown; select a compatible Codex model to read the rest.";
84
85
  const data = result.structuredContent;
85
86
  if (!data || typeof data !== "object" || Array.isArray(data))
86
87
  throw new Error(
@@ -0,0 +1,168 @@
1
+ import { dirname, join } from "node:path";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionCommandContext,
5
+ ExtensionContext,
6
+ } from "@earendil-works/pi-coding-agent";
7
+ import type { CommsFeature } from "../guidance.js";
8
+ import type { OpenSettings } from "../settings-navigation.js";
9
+ import type { NotesRuntime } from "./index.js";
10
+ import {
11
+ legacyNotesConfigured,
12
+ loadNotesSettings,
13
+ modelIsActive,
14
+ type NotesSettings,
15
+ notesSettingsPath,
16
+ writeSettings,
17
+ } from "./settings.js";
18
+ import type { NotesSettingsOwner } from "./settings-command.js";
19
+ import type { NotesStore } from "./store.js";
20
+
21
+ /** Dormant sessions need only settings; saved continuity still owns its history cuts. */
22
+ function hasSavedContinuity(ctx: ExtensionContext): boolean {
23
+ return ctx.sessionManager.getEntries().some((entry) => {
24
+ if (entry.type === "custom" || entry.type === "custom_message")
25
+ return (
26
+ entry.customType.startsWith("notes-compaction:") ||
27
+ [
28
+ "codex-context-agent",
29
+ "codex-context-backend",
30
+ "codex-context-note",
31
+ "codex-context-note-snapshot",
32
+ "codex-context-window",
33
+ "codex-context-tree-archive",
34
+ "codex-note-save-marker",
35
+ ].includes(entry.customType)
36
+ );
37
+ return (
38
+ entry.type === "compaction" &&
39
+ entry.details !== null &&
40
+ typeof entry.details === "object" &&
41
+ "pi-notes-compaction/window-checkpoint" in entry.details
42
+ );
43
+ });
44
+ }
45
+
46
+ export function createNotesFeature(
47
+ pi: ExtensionAPI,
48
+ openSettings?: OpenSettings,
49
+ ): CommsFeature {
50
+ let settings: NotesSettings | undefined;
51
+ let runtime: NotesRuntime | undefined;
52
+ let loading: Promise<NotesRuntime> | undefined;
53
+ let store: NotesStore | undefined;
54
+ let storage: Promise<NotesStore> | undefined;
55
+ let closed = false;
56
+ const ensureStore = () =>
57
+ (storage ??= (async () => {
58
+ const { NotesStore } = await import("./store.js");
59
+ if (closed) throw new Error("Session changed; reopen Notes settings");
60
+ return (store = new NotesStore(
61
+ join(dirname(notesSettingsPath()), "notes.sqlite"),
62
+ ));
63
+ })());
64
+ const ensure = (ctx: ExtensionContext): Promise<NotesRuntime> => {
65
+ if (loading) return loading;
66
+ loading = (async () => {
67
+ const { createNotesRuntime } = await import("./index.js");
68
+ if (closed) throw new Error("Session changed; reopen Notes settings");
69
+ runtime = await createNotesRuntime(pi, await ensureStore());
70
+ if (closed) throw new Error("Session changed; reopen Notes settings");
71
+ await runtime.start(ctx, settings);
72
+ return runtime;
73
+ })();
74
+ return loading;
75
+ };
76
+ const owner: NotesSettingsOwner = {
77
+ get settings() {
78
+ if (!settings)
79
+ throw new Error(
80
+ "Notes settings are unavailable; fix the settings file and reload Pi",
81
+ );
82
+ return settings;
83
+ },
84
+ get runtime() {
85
+ return runtime;
86
+ },
87
+ async save(value, ctx) {
88
+ if (runtime) runtime.activation.save(value, ctx);
89
+ else writeSettings(notesSettingsPath(), value);
90
+ settings = value;
91
+ if (!runtime && modelIsActive(value, ctx.model)) await ensure(ctx);
92
+ },
93
+ start: ensure,
94
+ };
95
+ const open = async (
96
+ ctx: ExtensionCommandContext,
97
+ initial: "notes" | "roles" = "notes",
98
+ ) => {
99
+ const { createNotesSettings } = await import("./settings-command.js");
100
+ return createNotesSettings(
101
+ owner,
102
+ await ensureStore(),
103
+ notesSettingsPath(),
104
+ Boolean(openSettings),
105
+ )(ctx, initial);
106
+ };
107
+ const routeSettings: OpenSettings =
108
+ openSettings ??
109
+ (async (ctx) => {
110
+ await open(ctx);
111
+ });
112
+ pi.on("session_start", async (_event, ctx) => {
113
+ try {
114
+ settings = loadNotesSettings(ctx);
115
+ writeSettings(notesSettingsPath(), settings);
116
+ if (
117
+ modelIsActive(settings, ctx.model) ||
118
+ hasSavedContinuity(ctx) ||
119
+ legacyNotesConfigured(ctx)
120
+ )
121
+ await ensure(ctx);
122
+ } catch (error) {
123
+ ctx.ui.notify(
124
+ `Notes continuity inactive: ${error instanceof Error ? error.message : String(error)}`,
125
+ "warning",
126
+ );
127
+ }
128
+ });
129
+ pi.on("model_select", async (_event, ctx) => {
130
+ if (!runtime && settings && modelIsActive(settings, ctx.model))
131
+ await ensure(ctx);
132
+ });
133
+ pi.on("session_shutdown", () => {
134
+ closed = true;
135
+ store?.close();
136
+ });
137
+ pi.registerCommand("notes", {
138
+ description: "Manage local notes and context rollover",
139
+ handler: async (args, ctx) => {
140
+ if (args.trim()) {
141
+ ctx.ui.notify("Use /notes to open settings.", "info");
142
+ return;
143
+ }
144
+ await routeSettings(ctx, "notes");
145
+ },
146
+ });
147
+ pi.registerCommand("roles", {
148
+ description: "View model roles and JSON configuration guidance",
149
+ handler: async (args, ctx) => {
150
+ if (args.trim()) {
151
+ ctx.ui.notify(
152
+ "Use /roles to view roles and JSON configuration guidance.",
153
+ "info",
154
+ );
155
+ return;
156
+ }
157
+ const next = await open(ctx, "roles");
158
+ if (next) await routeSettings(ctx, next);
159
+ },
160
+ });
161
+ return {
162
+ enabled: () => runtime?.lifecycle.active ?? false,
163
+ gptPromptMode: () => runtime?.lifecycle.gptPromptMode() ?? false,
164
+ async openSettings(ctx) {
165
+ return open(ctx);
166
+ },
167
+ };
168
+ }
@@ -12,23 +12,13 @@ interface HistoryItem {
12
12
  content: string;
13
13
  }
14
14
 
15
- // Pi entries are immutable once persisted. Rendering is lazy so indexing never
16
- // serializes the ongoing context, and repeated lookups reuse unchanged text.
17
- const rendered = new WeakMap<SessionEntry, string>();
15
+ // Cache lazy metadata, not rendered content: Pi retains persisted entries, so
16
+ // caching serialized tool arguments would duplicate them for the session lifetime.
18
17
  const cachedItems = new WeakMap<SessionEntry, HistoryItem>();
19
18
  const indexItems = new WeakMap<
20
19
  HistoryItem,
21
20
  Pick<HistoryItem, "item_id" | "content">
22
21
  >();
23
- function content(entry: SessionEntry, render: () => string): string {
24
- let value = rendered.get(entry);
25
- if (value === undefined) {
26
- value = render();
27
- rendered.set(entry, value);
28
- }
29
- return value;
30
- }
31
-
32
22
  function customHistoryRole(
33
23
  entry: Extract<SessionEntry, { type: "custom_message" }>,
34
24
  ): string {
@@ -180,7 +170,7 @@ export async function historyWindows(
180
170
  }
181
171
  : {}),
182
172
  get content() {
183
- return content(entry, render);
173
+ return render();
184
174
  },
185
175
  };
186
176
  if (message.role === "user" || message.role === "assistant") {
@@ -212,15 +202,13 @@ export async function historyWindows(
212
202
  item_id: entry.id,
213
203
  role: customHistoryRole(entry),
214
204
  get content() {
215
- return content(entry, () =>
216
- typeof entry.content === "string"
217
- ? entry.content
218
- : entry.content
219
- .map((block) =>
220
- block.type === "text" ? block.text : "[image]",
221
- )
222
- .join("\n"),
223
- );
205
+ return typeof entry.content === "string"
206
+ ? entry.content
207
+ : entry.content
208
+ .map((block) =>
209
+ block.type === "text" ? block.text : "[image]",
210
+ )
211
+ .join("\n");
224
212
  },
225
213
  };
226
214
  }
@@ -70,15 +70,16 @@ export async function useHistory(
70
70
  : undefined);
71
71
  const item = items?.find((item) => item.item_id === itemId);
72
72
  if (!item) return { item: null };
73
- const offset = integer(params["offset_chars"], 0, item.content.length);
73
+ const { content: fullContent, ...metadata } = item;
74
+ const offset = integer(params["offset_chars"], 0, fullContent.length);
74
75
  const limit = integer(params["limit_chars"], 8000, 8000);
75
- const content = item.content.slice(offset, offset + limit);
76
+ const content = fullContent.slice(offset, offset + limit);
76
77
  return {
77
78
  item: {
78
- ...item,
79
+ ...metadata,
79
80
  content,
80
- total_chars: item.content.length,
81
- ...(offset + content.length < item.content.length
81
+ total_chars: fullContent.length,
82
+ ...(offset + content.length < fullContent.length
82
83
  ? { next_offset_chars: offset + content.length }
83
84
  : {}),
84
85
  },
@@ -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);