@howaboua/pi-agent-comms 0.0.0-stage → 0.0.1-dev.14.1.g7d1d3da173aa

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 (141) hide show
  1. package/INTEGRATION.md +31 -0
  2. package/LICENSE +21 -0
  3. package/PCC-INTEGRATION.md +17 -0
  4. package/README.md +53 -2
  5. package/dist/viewer/archive.js +249 -0
  6. package/dist/viewer/config.js +85 -0
  7. package/dist/viewer/contracts.js +1 -0
  8. package/dist/viewer/server.js +177 -0
  9. package/dist/viewer/source.js +29 -0
  10. package/dist/viewer/web/app.js +88 -0
  11. package/dist/viewer/web/index.html +41 -0
  12. package/dist/viewer/web/navigation.js +72 -0
  13. package/dist/viewer/web/posts.js +105 -0
  14. package/dist/viewer/web/render.js +147 -0
  15. package/dist/viewer/web/session.js +86 -0
  16. package/dist/viewer/web/style.css +517 -0
  17. package/dist/viewer/web/updates.js +106 -0
  18. package/docs/BOARD-CHANGELOG.md +49 -0
  19. package/docs/BOARD.md +124 -0
  20. package/docs/NOTES-CHANGELOG.md +127 -0
  21. package/docs/NOTES.md +122 -0
  22. package/index.ts +21 -0
  23. package/package.json +75 -5
  24. package/src/board/AGENTS.md +12 -0
  25. package/src/board/activity.ts +274 -0
  26. package/src/board/archive.ts +118 -0
  27. package/src/board/awareness.ts +179 -0
  28. package/src/board/briefing.ts +25 -0
  29. package/src/board/config.ts +192 -0
  30. package/src/board/consolidation.ts +32 -0
  31. package/src/board/context-briefing.ts +245 -0
  32. package/src/board/contract.ts +254 -0
  33. package/src/board/delivery.ts +85 -0
  34. package/src/board/feature.ts +91 -0
  35. package/src/board/identity.ts +238 -0
  36. package/src/board/integration.ts +55 -0
  37. package/src/board/paging.ts +54 -0
  38. package/src/board/protocol.ts +78 -0
  39. package/src/board/queries.ts +168 -0
  40. package/src/board/response.ts +82 -0
  41. package/src/board/runtime/activation.ts +50 -0
  42. package/src/board/runtime/catchup.ts +96 -0
  43. package/src/board/runtime/coordinator.ts +311 -0
  44. package/src/board/runtime/engine.ts +40 -0
  45. package/src/board/runtime/index.ts +63 -0
  46. package/src/board/runtime/owner.ts +168 -0
  47. package/src/board/runtime/routing.ts +152 -0
  48. package/src/board/runtime/turns.ts +109 -0
  49. package/src/board/search.ts +95 -0
  50. package/src/board/settings/panel.ts +193 -0
  51. package/src/board/store.ts +427 -0
  52. package/src/board/summaries.ts +124 -0
  53. package/src/board/summarizer.ts +201 -0
  54. package/src/board/tool.ts +27 -0
  55. package/src/board/viewer/AGENTS.md +1 -0
  56. package/src/board/viewer/archive.ts +308 -0
  57. package/src/board/viewer/config.ts +111 -0
  58. package/src/board/viewer/contracts.ts +98 -0
  59. package/src/board/viewer/index.ts +162 -0
  60. package/src/board/viewer/server.ts +204 -0
  61. package/src/board/viewer/source.ts +33 -0
  62. package/src/board/viewer/web/app.js +88 -0
  63. package/src/board/viewer/web/index.html +41 -0
  64. package/src/board/viewer/web/navigation.js +72 -0
  65. package/src/board/viewer/web/posts.js +105 -0
  66. package/src/board/viewer/web/render.js +147 -0
  67. package/src/board/viewer/web/session.js +86 -0
  68. package/src/board/viewer/web/style.css +517 -0
  69. package/src/board/viewer/web/updates.js +106 -0
  70. package/src/guidance.ts +121 -0
  71. package/src/notes/AGENTS.md +27 -0
  72. package/src/notes/activation.ts +150 -0
  73. package/src/notes/agent-identity.ts +221 -0
  74. package/src/notes/attachment-sharing.ts +165 -0
  75. package/src/notes/attachment-snapshot.ts +113 -0
  76. package/src/notes/binding-startup.ts +30 -0
  77. package/src/notes/bridge.ts +130 -0
  78. package/src/notes/compaction-projection.ts +88 -0
  79. package/src/notes/context-owner.ts +99 -0
  80. package/src/notes/context-sharing.ts +178 -0
  81. package/src/notes/extension-hooks.ts +200 -0
  82. package/src/notes/extension-sharing.ts +133 -0
  83. package/src/notes/feature.ts +168 -0
  84. package/src/notes/fresh-checkpoint.ts +143 -0
  85. package/src/notes/fresh-notes.ts +323 -0
  86. package/src/notes/history-search-protocol.ts +39 -0
  87. package/src/notes/history-search-pruning.mjs +120 -0
  88. package/src/notes/history-search-worker.mjs +258 -0
  89. package/src/notes/history-search.ts +269 -0
  90. package/src/notes/history-windows.ts +221 -0
  91. package/src/notes/history.ts +158 -0
  92. package/src/notes/idle-admission.ts +201 -0
  93. package/src/notes/index.ts +125 -0
  94. package/src/notes/integrations.ts +174 -0
  95. package/src/notes/lifecycle.ts +308 -0
  96. package/src/notes/model-role-config.ts +79 -0
  97. package/src/notes/model-role-screen.ts +74 -0
  98. package/src/notes/model-roles.ts +225 -0
  99. package/src/notes/note-query.ts +148 -0
  100. package/src/notes/note-result.ts +88 -0
  101. package/src/notes/note-save-marker.ts +128 -0
  102. package/src/notes/notes-lookup.ts +115 -0
  103. package/src/notes/notes.ts +302 -0
  104. package/src/notes/query-executor.ts +242 -0
  105. package/src/notes/query-input.ts +126 -0
  106. package/src/notes/remote.ts +376 -0
  107. package/src/notes/rollover.ts +224 -0
  108. package/src/notes/saved-session-access.ts +117 -0
  109. package/src/notes/saved-session-index.mjs +83 -0
  110. package/src/notes/saved-session.mjs +241 -0
  111. package/src/notes/saved-session.ts +51 -0
  112. package/src/notes/saved-sharing-records.ts +135 -0
  113. package/src/notes/session-pruning-content.ts +237 -0
  114. package/src/notes/session-pruning-plan.ts +243 -0
  115. package/src/notes/session-pruning-policy.ts +20 -0
  116. package/src/notes/session-pruning-screen.ts +204 -0
  117. package/src/notes/session-pruning-source.ts +44 -0
  118. package/src/notes/session-pruning-transaction.ts +141 -0
  119. package/src/notes/session-pruning.ts +155 -0
  120. package/src/notes/settings-command.ts +95 -0
  121. package/src/notes/settings-controls.ts +199 -0
  122. package/src/notes/settings-screen.ts +113 -0
  123. package/src/notes/settings.ts +287 -0
  124. package/src/notes/shared-notes.ts +411 -0
  125. package/src/notes/shared-session-reader.ts +143 -0
  126. package/src/notes/sharing-service.ts +282 -0
  127. package/src/notes/sqlite.mjs +33 -0
  128. package/src/notes/store.ts +283 -0
  129. package/src/notes/task-boundary.ts +37 -0
  130. package/src/notes/tool-contracts.ts +312 -0
  131. package/src/notes/tools.ts +148 -0
  132. package/src/notes/tree-archive-manifest.mjs +27 -0
  133. package/src/notes/tree-archive.ts +129 -0
  134. package/src/notes/tree-checkpoint.ts +170 -0
  135. package/src/notes/tree-handoff-read.ts +192 -0
  136. package/src/notes/window-checkpoint.ts +105 -0
  137. package/src/notes/window-message.ts +185 -0
  138. package/src/notes/windows.ts +272 -0
  139. package/src/settings-navigation.ts +11 -0
  140. package/src/timestamps.ts +3 -0
  141. package/tsconfig.json +9 -0
@@ -0,0 +1,282 @@
1
+ import { isDeepStrictEqual } from "node:util";
2
+ import type {
3
+ ExtensionAPI,
4
+ ExtensionContext,
5
+ } from "@earendil-works/pi-coding-agent";
6
+ import {
7
+ CONTEXT_AGENT_ENTRY,
8
+ canonicalAgentName,
9
+ contextAgentIdentity,
10
+ contextAgentNames,
11
+ contextTargetAgent,
12
+ parseContextAgentBinding,
13
+ } from "./agent-identity.js";
14
+ import { createAttachmentSharing } from "./attachment-sharing.js";
15
+ import { bindingStartupEntries } from "./binding-startup.js";
16
+ import type { NotesOwner } from "./bridge.js";
17
+ import {
18
+ CONTEXT_SHARING_AVAILABLE,
19
+ CONTEXT_SHARING_REQUEST,
20
+ type ContextRouter,
21
+ type ContextSharingService,
22
+ type SavedSessionLoader,
23
+ type SharedContextRequest,
24
+ type SharedContextResult,
25
+ } from "./context-sharing.js";
26
+
27
+ export function registerContextSharingService(
28
+ pi: ExtensionAPI,
29
+ config: {
30
+ enabled(ctx: ExtensionContext): boolean;
31
+ shareSubagentContext(ctx: ExtensionContext): boolean;
32
+ execute(
33
+ ctx: ExtensionContext,
34
+ request: SharedContextRequest,
35
+ signal?: AbortSignal,
36
+ ): Promise<SharedContextResult>;
37
+ owner(): NotesOwner;
38
+ },
39
+ ): ContextRouter & { loadSavedSession: SavedSessionLoader } {
40
+ let router: ContextRouter | undefined;
41
+ let savedSessionLoader: SavedSessionLoader | undefined;
42
+ const describe: ContextSharingService["describe"] = (ctx) => {
43
+ const storageMode = config.enabled(ctx);
44
+ if (!storageMode) return undefined;
45
+ const identity = contextAgentIdentity(ctx);
46
+ // Saved attachment identities are immutable even after their writer retires.
47
+ const storage = identity.storage ?? "session";
48
+ return { ...identity, storage };
49
+ };
50
+ const inspectAttachment: NonNullable<
51
+ ContextSharingService["inspectAttachment"]
52
+ > = (ctx, standalone = true) => {
53
+ const check = () => {
54
+ const identity = describe(ctx);
55
+ if (!identity)
56
+ throw new Error("Context attachment requires notes-based continuity");
57
+ if (standalone && !ctx.isIdle())
58
+ throw new Error("Attach context only after the target settles");
59
+ if (!ctx.sessionManager.getSessionFile())
60
+ throw new Error("Context attachment requires a saved Pi session");
61
+ if (standalone && contextAgentIdentity(ctx).storage)
62
+ throw new Error("Target already belongs to a shared context family");
63
+ if (!router)
64
+ throw new Error(
65
+ "Context attachment requires an available context router",
66
+ );
67
+ return identity;
68
+ };
69
+ const identity = check();
70
+ return identity;
71
+ };
72
+ const service: ContextSharingService = {
73
+ protocol: 1,
74
+ canCreateChild: (ctx) => config.shareSubagentContext(ctx),
75
+ describe,
76
+ async verify() {},
77
+ async createChild(ctx, options) {
78
+ if (!service.canCreateChild(ctx))
79
+ throw new Error(
80
+ "Shared subagent context is disabled; enable it in /notes",
81
+ );
82
+ const parent = describe(ctx);
83
+ if (!parent)
84
+ throw new Error("Shared context requires notes-based continuity");
85
+ if (
86
+ options.threadId === parent.threadId ||
87
+ options.threadId === parent.sessionId
88
+ )
89
+ throw new Error(
90
+ "Child Pi session ID conflicts with its controller or family root; start a session with another ID",
91
+ );
92
+ const agentName = canonicalAgentName(options.threadId);
93
+ if (!router || options.routing === undefined)
94
+ throw new Error("Local sharing requires a registered context router");
95
+
96
+ if (ctx.sessionManager.getSessionId() !== parent.threadId)
97
+ throw new Error(
98
+ "Controller session changed while preparing shared context",
99
+ );
100
+ const binding = {
101
+ protocol: 1 as const,
102
+ sessionId: parent.sessionId,
103
+ agentName,
104
+ storage: "session" as const,
105
+ ...(parent.accountScope ? { accountScope: parent.accountScope } : {}),
106
+ ...(parent.backendUrl ? { backendUrl: parent.backendUrl } : {}),
107
+ ...(options.routing === undefined ? {} : { routing: options.routing }),
108
+ };
109
+ return {
110
+ binding,
111
+ async adopt() {
112
+ const current = describe(ctx);
113
+ if (
114
+ !current ||
115
+ current.threadId !== parent.threadId ||
116
+ current.sessionId !== parent.sessionId ||
117
+ current.agentName !== parent.agentName ||
118
+ current.storage !== parent.storage ||
119
+ (current.accountScope !== undefined &&
120
+ current.accountScope !== parent.accountScope)
121
+ )
122
+ throw new Error(
123
+ "Controller context changed while binding shared context",
124
+ );
125
+ if (!contextAgentIdentity(ctx).storage)
126
+ pi.appendEntry(CONTEXT_AGENT_ENTRY, parent);
127
+ },
128
+ };
129
+ },
130
+ async bind(ctx, input, options) {
131
+ const binding = parseContextAgentBinding(input);
132
+ if (ctx.sessionManager.getSessionId() === binding.sessionId)
133
+ throw new Error(
134
+ "Child Pi session ID conflicts with its family root; start a session with another ID",
135
+ );
136
+ if (
137
+ binding.agentName !==
138
+ canonicalAgentName(ctx.sessionManager.getSessionId()) ||
139
+ binding.storageAgentName !== undefined
140
+ )
141
+ throw new Error(
142
+ "Shared context binding must use this Pi session identity",
143
+ );
144
+ const identity = {
145
+ ...binding,
146
+ threadId: ctx.sessionManager.getSessionId(),
147
+ };
148
+ const check = () => {
149
+ if (ctx.sessionManager.getSessionId() !== identity.threadId)
150
+ throw new Error(
151
+ "Worker session changed while binding shared context",
152
+ );
153
+ const current = describe(ctx);
154
+ if (!current || current.storage !== binding.storage)
155
+ throw new Error(
156
+ "Shared context binding requires matching history storage",
157
+ );
158
+ if (contextAgentIdentity(ctx).storage) {
159
+ if (!isDeepStrictEqual(current, identity))
160
+ throw new Error("An existing context identity cannot be rebound");
161
+ return true;
162
+ }
163
+ const owner = config.owner();
164
+ const entries = bindingStartupEntries(ctx, options);
165
+ if (!ctx.isIdle() || !owner.canBind?.(ctx, entries))
166
+ throw new Error(
167
+ "Shared context requires an idle child before its first turn; inherited fork history needs an explicit boundary",
168
+ );
169
+ if (binding.storage === "session" && !router)
170
+ throw new Error("Local sharing requires a registered context router");
171
+ return false;
172
+ };
173
+ check();
174
+ if (binding.storage === "remote")
175
+ throw new Error("New shared agents require local Notes storage");
176
+ // Auth can yield to input or a session switch; the live owner commits only while still fresh.
177
+ if (!check()) pi.appendEntry(CONTEXT_AGENT_ENTRY, identity);
178
+ return identity;
179
+ },
180
+ inspectAttachment,
181
+ retainAttachmentIdentity(ctx) {
182
+ const native = describe(ctx);
183
+ if (!native || !router || !ctx.sessionManager.getSessionFile())
184
+ throw new Error(
185
+ "Context attachment requires a saved owner and live router",
186
+ );
187
+ const identity = native;
188
+ if (!contextAgentIdentity(ctx).storage)
189
+ pi.appendEntry(CONTEXT_AGENT_ENTRY, identity);
190
+ return identity;
191
+ },
192
+ async execute(ctx, request, signal) {
193
+ signal?.throwIfAborted();
194
+ const identity = describe(ctx);
195
+ if (
196
+ !identity ||
197
+ identity.sessionId !== request.sessionId ||
198
+ !contextAgentNames(identity).includes(request.agentName) ||
199
+ (request.namespace !== "notes" && request.namespace !== "history") ||
200
+ !request.params ||
201
+ typeof request.params !== "object" ||
202
+ Array.isArray(request.params) ||
203
+ contextTargetAgent(
204
+ request.namespace,
205
+ request.params,
206
+ identity.agentName,
207
+ ) !== request.agentName
208
+ )
209
+ throw new Error("Shared context request does not belong to this agent");
210
+ if (request.encryptedArguments)
211
+ throw new Error(
212
+ "Encrypted Remote arguments cannot execute against Local storage; use Code or Notebook history/notes with ordinary query/text",
213
+ );
214
+ return config.execute(ctx, request, signal);
215
+ },
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
+ },
225
+ registerRouter(next) {
226
+ if (router && router !== next)
227
+ throw new Error("A context router is already registered");
228
+ router = next;
229
+ return () => {
230
+ if (router === next) router = undefined;
231
+ };
232
+ },
233
+ };
234
+ const off = pi.events.on(CONTEXT_SHARING_REQUEST, () =>
235
+ pi.events.emit(CONTEXT_SHARING_AVAILABLE, service),
236
+ );
237
+ pi.events.emit(CONTEXT_SHARING_AVAILABLE, service);
238
+ pi.on("session_shutdown", () => {
239
+ off();
240
+ router = undefined;
241
+ savedSessionLoader = undefined;
242
+ });
243
+ return Object.assign(
244
+ async (
245
+ ctx: ExtensionContext,
246
+ request: SharedContextRequest,
247
+ signal?: AbortSignal,
248
+ ) => {
249
+ describe(ctx);
250
+ if (!router) {
251
+ throw new Error(
252
+ "Cross-agent context requires an available context router",
253
+ );
254
+ }
255
+ return router(ctx, request, signal);
256
+ },
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
+ ),
278
+ requiresRemoteScope: (ctx: ExtensionContext) =>
279
+ router?.requiresRemoteScope?.(ctx) ?? false,
280
+ },
281
+ );
282
+ }
@@ -0,0 +1,33 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ // Only the shared SQLite surface used by Notes. Bun returns null for a missing
4
+ // row (better-sqlite3 returns undefined); blobs may be Uint8Array, not Buffer.
5
+ /** @template {unknown[]} P
6
+ * @template R
7
+ * @typedef {{get(...params:P): R | null | undefined; all(...params:P): R[]; run(...params:P): {changes:number; lastInsertRowid:number|bigint}}} Statement
8
+ */
9
+ /** @template {unknown[]} P
10
+ * @template R
11
+ * @typedef {((...params:P) => R) & {immediate(...params:P):R}} Transaction
12
+ */
13
+ /** @typedef {{
14
+ * prepare<P extends unknown[] = unknown[], R = unknown>(sql:string): Statement<P,R>;
15
+ * transaction<P extends unknown[], R>(fn:(...params:P) => R): Transaction<P,R>;
16
+ * exec(sql:string):void;
17
+ * close():void;
18
+ * }} Database
19
+ */
20
+
21
+ const require = createRequire(import.meta.url);
22
+
23
+ /** Avoid loading the native addon at all in Bun, including compiled Pi builds.
24
+ * @param {string} path
25
+ * @returns {Database}
26
+ */
27
+ export function openDatabase(path) {
28
+ /** @type {new(path:string) => Database} */
29
+ const Database = process.versions["bun"]
30
+ ? require("bun:sqlite").Database
31
+ : require("better-sqlite3");
32
+ return new Database(path);
33
+ }
@@ -0,0 +1,283 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, statSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import type { CachedResponse, LookupQuery } from "./bridge.js";
5
+ import { queryKey } from "./bridge.js";
6
+ import {
7
+ PRUNING_OFF,
8
+ pruningPolicy,
9
+ type SessionPruningPolicy,
10
+ } from "./session-pruning-policy.js";
11
+ import { type Database, openDatabase } from "./sqlite.mjs";
12
+
13
+ export interface SessionRef {
14
+ id: string;
15
+ file: string | undefined;
16
+ }
17
+ export interface NoteRevision {
18
+ id: string;
19
+ path: string;
20
+ text: string;
21
+ mode: "replace" | "append";
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ }
25
+ interface CacheRow {
26
+ query_json: string;
27
+ bytes: Uint8Array;
28
+ source: string;
29
+ encoding: string;
30
+ fetched_at: number;
31
+ coverage: CachedResponse["coverage"];
32
+ }
33
+
34
+ /** One connection per extension process. Read-only access never creates a database or session. */
35
+ export class NotesStore {
36
+ private db: Database | undefined;
37
+ readonly path: string;
38
+ constructor(path: string) {
39
+ this.path = path;
40
+ }
41
+ private open(write = false): Database | undefined {
42
+ if (this.db) return this.db;
43
+ if (!write && !existsSync(this.path)) return undefined;
44
+ if (write) mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 });
45
+ const db = openDatabase(this.path);
46
+ try {
47
+ db.exec("PRAGMA busy_timeout = 5000");
48
+ db.exec("PRAGMA journal_mode = WAL");
49
+ db.exec("PRAGMA foreign_keys = ON");
50
+ const version = db
51
+ .prepare<[], { user_version: number }>("PRAGMA user_version")
52
+ .get()?.user_version;
53
+ if (version !== 0 && version !== 1) {
54
+ throw new Error("Notes database version is not supported");
55
+ }
56
+ db.exec(`
57
+ CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, file_path TEXT, updated_at INTEGER NOT NULL);
58
+ CREATE TABLE IF NOT EXISTS session_pruning (session_id TEXT PRIMARY KEY, windows INTEGER NOT NULL, days INTEGER NOT NULL);
59
+ CREATE TABLE IF NOT EXISTS notes (
60
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
61
+ path TEXT NOT NULL, text TEXT NOT NULL, mode TEXT NOT NULL,
62
+ created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
63
+ );
64
+ CREATE INDEX IF NOT EXISTS notes_session ON notes(session_id);
65
+ CREATE TABLE IF NOT EXISTS remote_cache (
66
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
67
+ query_key TEXT NOT NULL, query_json TEXT NOT NULL, source TEXT NOT NULL,
68
+ encoding TEXT NOT NULL, bytes BLOB NOT NULL, fetched_at INTEGER NOT NULL, coverage TEXT NOT NULL,
69
+ PRIMARY KEY(session_id, query_key, source)
70
+ );
71
+ PRAGMA user_version = 1;
72
+ `);
73
+ this.db = db;
74
+ return db;
75
+ } catch {
76
+ db.close();
77
+ throw new Error(
78
+ "Local notes storage is unavailable. History remains available. Retry when local storage is restored.",
79
+ );
80
+ }
81
+ }
82
+ private record(db: Database, session: SessionRef): void {
83
+ db.prepare(
84
+ "INSERT INTO sessions VALUES (?, ?, ?) ON CONFLICT(id) DO UPDATE SET file_path = COALESCE(excluded.file_path, sessions.file_path), updated_at = excluded.updated_at",
85
+ ).run(session.id, session.file ?? null, Date.now());
86
+ }
87
+ pruningPolicy(sessionId: string): SessionPruningPolicy {
88
+ const row = this.open()
89
+ ?.prepare(
90
+ "SELECT windows, days FROM session_pruning WHERE session_id = ?",
91
+ )
92
+ .get(sessionId);
93
+ return row ? pruningPolicy(row) : { ...PRUNING_OFF };
94
+ }
95
+ setPruningPolicy(sessionId: string, value: SessionPruningPolicy): void {
96
+ const policy = pruningPolicy(value);
97
+ this.open(true)!
98
+ .prepare(
99
+ "INSERT INTO session_pruning VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET windows = excluded.windows, days = excluded.days",
100
+ )
101
+ .run(sessionId, policy.windows, policy.days);
102
+ }
103
+ /** Persist only after a real mutation. Snapshot revisions remain immutable for branch navigation. */
104
+ write(session: SessionRef, note: Omit<NoteRevision, "id">): NoteRevision {
105
+ const db = this.open(true)!;
106
+ const revision = { ...note, id: randomUUID() };
107
+ db.transaction(() => {
108
+ this.record(db, session);
109
+ db.prepare("INSERT INTO notes VALUES (?, ?, ?, ?, ?, ?, ?)").run(
110
+ revision.id,
111
+ session.id,
112
+ revision.path,
113
+ revision.text,
114
+ revision.mode,
115
+ revision.createdAt,
116
+ revision.updatedAt,
117
+ );
118
+ })();
119
+ return revision;
120
+ }
121
+ read(id: string): NoteRevision | undefined {
122
+ const row = this.open()
123
+ ?.prepare<[string], NoteRevision>(
124
+ "SELECT id, path, text, mode, created_at AS createdAt, updated_at AS updatedAt FROM notes WHERE id = ?",
125
+ )
126
+ .get(id);
127
+ return row ?? undefined;
128
+ }
129
+ updateFile(session: SessionRef): void {
130
+ if (!session.file) return;
131
+ this.open()
132
+ ?.prepare("UPDATE sessions SET file_path = ? WHERE id = ?")
133
+ .run(session.file, session.id);
134
+ }
135
+ /** Exact native thread lookup only. The JSONL header and binding remain authoritative. */
136
+ sessionFile(threadId: string): string | undefined {
137
+ return (
138
+ this.open()
139
+ ?.prepare<[string], { file_path: string | null }>(
140
+ "SELECT file_path FROM sessions WHERE id = ?",
141
+ )
142
+ .get(threadId)?.file_path ?? undefined
143
+ );
144
+ }
145
+ cache(session: SessionRef, responses: readonly CachedResponse[]): void {
146
+ if (!responses.length) return;
147
+ for (const response of responses) {
148
+ if (
149
+ !(response.bytes instanceof Uint8Array) ||
150
+ !response.bytes.length ||
151
+ !response.source ||
152
+ !response.encoding ||
153
+ !Number.isFinite(response.fetchedAt) ||
154
+ !["complete", "partial", "unknown"].includes(response.coverage)
155
+ )
156
+ throw new Error("Remote lookup returned an invalid cache response");
157
+ }
158
+ const db = this.open(true)!;
159
+ db.transaction(() => {
160
+ this.record(db, session);
161
+ const insert = db.prepare(
162
+ "INSERT INTO remote_cache VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(session_id, query_key, source) DO UPDATE SET query_json = excluded.query_json, encoding = excluded.encoding, bytes = excluded.bytes, fetched_at = excluded.fetched_at, coverage = excluded.coverage",
163
+ );
164
+ for (const response of responses)
165
+ insert.run(
166
+ session.id,
167
+ queryKey(response.query),
168
+ JSON.stringify(response.query),
169
+ response.source,
170
+ response.encoding,
171
+ Buffer.from(response.bytes),
172
+ response.fetchedAt,
173
+ response.coverage,
174
+ );
175
+ })();
176
+ }
177
+ cached(sessionIds: readonly string[], query: LookupQuery): CachedResponse[] {
178
+ const db = this.open();
179
+ if (!db) return [];
180
+ const rows = sessionIds.flatMap(
181
+ (id) =>
182
+ db
183
+ .prepare(
184
+ "SELECT * FROM remote_cache WHERE session_id = ? AND query_key = ?",
185
+ )
186
+ .all(id, queryKey(query)) as CacheRow[],
187
+ );
188
+ const latest = new Map<string, CachedResponse>();
189
+ for (const row of rows)
190
+ if (
191
+ !latest.has(row.source) ||
192
+ latest.get(row.source)!.fetchedAt < row.fetched_at
193
+ )
194
+ latest.set(row.source, {
195
+ query: JSON.parse(row.query_json) as LookupQuery,
196
+ bytes: new Uint8Array(row.bytes),
197
+ source: row.source,
198
+ encoding: row.encoding,
199
+ fetchedAt: row.fetched_at,
200
+ coverage: row.coverage,
201
+ });
202
+ return [...latest.values()];
203
+ }
204
+ cachedPaths(sessionIds: readonly string[]): string[] {
205
+ const db = this.open();
206
+ if (!db) return [];
207
+ const rows = sessionIds
208
+ .flatMap(
209
+ (id) =>
210
+ db
211
+ .prepare(
212
+ "SELECT query_json, fetched_at FROM remote_cache WHERE session_id = ? ORDER BY fetched_at DESC LIMIT 20",
213
+ )
214
+ .all(id) as { query_json: string; fetched_at: number }[],
215
+ )
216
+ .sort((a, b) => b.fetched_at - a.fetched_at);
217
+ return rows.flatMap((row) => {
218
+ const query = JSON.parse(row.query_json) as LookupQuery;
219
+ return query.namespace === "notes" &&
220
+ query.params["action"] === "read_file" &&
221
+ typeof query.params["path"] === "string"
222
+ ? [query.params["path"]]
223
+ : [];
224
+ });
225
+ }
226
+ status(): { sessions: number; revisions: number; cachedResponses: number } {
227
+ const db = this.open();
228
+ const count = (table: string) =>
229
+ (
230
+ db?.prepare(`SELECT count(*) AS n FROM ${table}`).get() as
231
+ | { n: number }
232
+ | undefined
233
+ )?.n ?? 0;
234
+ return {
235
+ sessions: count("sessions"),
236
+ revisions: count("notes"),
237
+ cachedResponses: count("remote_cache"),
238
+ };
239
+ }
240
+ sessionFiles(): Record<string, string | null> {
241
+ const rows =
242
+ this.open()
243
+ ?.prepare<[], { id: string; file_path: string | null }>(
244
+ "SELECT id, file_path FROM sessions",
245
+ )
246
+ .all() ?? [];
247
+ return Object.fromEntries(rows.map((row) => [row.id, row.file_path]));
248
+ }
249
+ prune(activeSessionId: string): {
250
+ removed: number;
251
+ unknownPaths: number;
252
+ inaccessible: number;
253
+ } {
254
+ const db = this.open();
255
+ const result = { removed: 0, unknownPaths: 0, inaccessible: 0 };
256
+ if (!db) return result;
257
+ const sessions = db.prepare("SELECT id, file_path FROM sessions").all() as {
258
+ id: string;
259
+ file_path: string | null;
260
+ }[];
261
+ for (const session of sessions) {
262
+ if (session.id === activeSessionId) continue;
263
+ if (!session.file_path) {
264
+ result.unknownPaths++;
265
+ continue;
266
+ }
267
+ try {
268
+ statSync(session.file_path);
269
+ } catch (error) {
270
+ // Only missing paths prove deletion. Permission failures and malformed paths do not.
271
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
272
+ db.prepare("DELETE FROM sessions WHERE id = ?").run(session.id);
273
+ result.removed++;
274
+ } else result.inaccessible++;
275
+ }
276
+ }
277
+ return result;
278
+ }
279
+ close(): void {
280
+ this.db?.close();
281
+ this.db = undefined;
282
+ }
283
+ }
@@ -0,0 +1,37 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ export function renderTaskBoundaryReminder(
4
+ remainingPercent: number,
5
+ gpt = false,
6
+ ): string {
7
+ if (gpt)
8
+ return `<context_window_reminder>\nSuggested budget reached; ${remainingPercent}% left. Task sequence→finish current task→save notes→new_context before next; otherwise continue here.\n</context_window_reminder>`;
9
+ return `<context_window_reminder>\nSuggested context budget reached; ${remainingPercent}% remains. For task sequences, finish current task, save notes and call new_context before next task. Otherwise continue here.\n</context_window_reminder>`;
10
+ }
11
+
12
+ export const TASK_BOUNDARY_PRESETS = [
13
+ 0, 250_000, 300_000, 400_000, 450_000,
14
+ ] as const;
15
+ export function taskBoundaryLabel(tokens: number): string {
16
+ return tokens === 0
17
+ ? "off"
18
+ : TASK_BOUNDARY_PRESETS.some((value) => value === tokens)
19
+ ? `${tokens / 1000}k`
20
+ : "custom (edit JSON)";
21
+ }
22
+ export function taskBoundaryEligible(
23
+ ctx: ExtensionContext,
24
+ threshold: number,
25
+ tokens = ctx.getContextUsage()?.tokens,
26
+ ): boolean {
27
+ const capacity =
28
+ ctx.getContextUsage()?.contextWindow ?? ctx.model?.contextWindow ?? 0;
29
+ return (
30
+ threshold > 0 &&
31
+ Number.isFinite(capacity) &&
32
+ capacity > 272_000 &&
33
+ typeof tokens === "number" &&
34
+ Number.isFinite(tokens) &&
35
+ tokens >= threshold
36
+ );
37
+ }