@floydous/pi-agent-kernel 0.1.0

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 (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +108 -0
  3. package/config.toml +24 -0
  4. package/docs/README.md +22 -0
  5. package/docs/architecture.md +40 -0
  6. package/docs/configuration.md +43 -0
  7. package/docs/editing-and-verification.md +41 -0
  8. package/docs/lsp.md +31 -0
  9. package/docs/retrieval.md +42 -0
  10. package/docs/testing.md +32 -0
  11. package/package.json +48 -0
  12. package/src/config/index.ts +2 -0
  13. package/src/config/kernel_config.ts +218 -0
  14. package/src/config/toml.ts +237 -0
  15. package/src/context/session_repair.ts +99 -0
  16. package/src/dedup/content_store.ts +365 -0
  17. package/src/dedup/recall_tool.ts +157 -0
  18. package/src/editing/patch.ts +482 -0
  19. package/src/editing/post_edit_verification.ts +200 -0
  20. package/src/editing/syntax-verify.ts +353 -0
  21. package/src/index.ts +852 -0
  22. package/src/lsp/adapters/base.ts +42 -0
  23. package/src/lsp/adapters/index.ts +21 -0
  24. package/src/lsp/adapters/python.ts +37 -0
  25. package/src/lsp/adapters/rust.ts +35 -0
  26. package/src/lsp/adapters/typescript.ts +40 -0
  27. package/src/lsp/index.ts +13 -0
  28. package/src/lsp/lsp_client.ts +650 -0
  29. package/src/lsp/lsp_detector.ts +52 -0
  30. package/src/lsp/lsp_formatter.ts +284 -0
  31. package/src/lsp/lsp_installer.ts +604 -0
  32. package/src/lsp/lsp_manager.ts +202 -0
  33. package/src/lsp/lsp_modal.ts +675 -0
  34. package/src/lsp/lsp_registry.ts +539 -0
  35. package/src/lsp/lsp_types.ts +143 -0
  36. package/src/retrieval/ast_search.ts +926 -0
  37. package/src/retrieval/repomap.ts +779 -0
  38. package/src/retrieval/search_bm25.ts +190 -0
  39. package/src/retrieval/search_chunker.ts +251 -0
  40. package/src/retrieval/search_config.ts +162 -0
  41. package/src/retrieval/search_embedder.ts +362 -0
  42. package/src/retrieval/search_index.ts +753 -0
  43. package/src/retrieval/search_modal.ts +358 -0
  44. package/src/retrieval/symbol_reader.ts +200 -0
  45. package/src/safety/atomic_write.ts +26 -0
  46. package/src/safety/epistemic_guard.ts +733 -0
  47. package/src/safety/kernel_debug.ts +15 -0
  48. package/src/safety/output_clamper.ts +213 -0
  49. package/src/tools/ast_search_tool.ts +131 -0
  50. package/src/tools/code_search_tool.ts +147 -0
  51. package/src/tools/context.ts +20 -0
  52. package/src/tools/edit_tool.ts +288 -0
  53. package/src/tools/lsp_tool.ts +813 -0
  54. package/src/tools/read_tool.ts +348 -0
  55. package/src/tools/repo_map_tool.ts +57 -0
  56. package/src/ui/footer.ts +287 -0
  57. package/src/ui/tui_utils.ts +278 -0
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Lightweight, zero-dependency TOML parser and serializer
3
+ * Supports:
4
+ * - Table headers ([table], [table.sub])
5
+ * - Strings (single and double quoted, multiline)
6
+ * - Numbers (integers, floats)
7
+ * - Booleans (true, false)
8
+ * - Arrays (inline [1, 2, 3] and multi-line)
9
+ * - Comments (# comment)
10
+ */
11
+
12
+ export type TomlValue =
13
+ | string
14
+ | number
15
+ | boolean
16
+ | TomlValue[]
17
+ | { [key: string]: TomlValue };
18
+
19
+ export function parseToml(tomlStr: string): Record<string, TomlValue> {
20
+ const root: Record<string, TomlValue> = {};
21
+ let currentTable: Record<string, TomlValue> = root;
22
+
23
+ const lines = tomlStr.split(/\r?\n/);
24
+
25
+ for (let i = 0; i < lines.length; i++) {
26
+ let line = lines[i].trim();
27
+
28
+ // Skip empty lines and full comments
29
+ if (!line || line.startsWith("#")) {
30
+ continue;
31
+ }
32
+
33
+ // Table header: [table] or [table.sub]
34
+ if (line.startsWith("[") && line.endsWith("]") && !line.startsWith("[[")) {
35
+ const tableName = line.slice(1, -1).trim();
36
+ const parts = tableName.split(".").map((p) => p.trim());
37
+ let cursor = root;
38
+ for (const part of parts) {
39
+ const existing = cursor[part];
40
+ if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
41
+ cursor[part] = {};
42
+ }
43
+ cursor = cursor[part] as Record<string, TomlValue>;
44
+ }
45
+ currentTable = cursor;
46
+ continue;
47
+ }
48
+
49
+ // Key-value pair: key = value
50
+ const eqIndex = line.indexOf("=");
51
+ if (eqIndex === -1) continue;
52
+
53
+ const key = line.slice(0, eqIndex).trim();
54
+ let rawValue = line.slice(eqIndex + 1).trim();
55
+
56
+ // Handle multi-line arrays if open bracket without close bracket
57
+ if (rawValue.startsWith("[") && !rawValue.endsWith("]")) {
58
+ let combined = rawValue;
59
+ while (i + 1 < lines.length && !combined.includes("]")) {
60
+ i++;
61
+ combined += " " + lines[i].trim();
62
+ }
63
+ rawValue = combined;
64
+ }
65
+
66
+ // Strip inline comment if not inside quote
67
+ rawValue = stripInlineComment(rawValue);
68
+
69
+ currentTable[key] = parseTomlValue(rawValue);
70
+ }
71
+
72
+ return root;
73
+ }
74
+
75
+ function stripInlineComment(valStr: string): string {
76
+ let inQuote = false;
77
+ let quoteChar = "";
78
+ for (let i = 0; i < valStr.length; i++) {
79
+ const ch = valStr[i];
80
+ if ((ch === '"' || ch === "'") && (i === 0 || valStr[i - 1] !== "\\")) {
81
+ if (!inQuote) {
82
+ inQuote = true;
83
+ quoteChar = ch;
84
+ } else if (quoteChar === ch) {
85
+ inQuote = false;
86
+ }
87
+ } else if (ch === "#" && !inQuote) {
88
+ return valStr.slice(0, i).trim();
89
+ }
90
+ }
91
+ return valStr.trim();
92
+ }
93
+
94
+ function parseTomlValue(valStr: string): TomlValue {
95
+ const trimmed = valStr.trim();
96
+
97
+ // Boolean
98
+ if (trimmed === "true") return true;
99
+ if (trimmed === "false") return false;
100
+
101
+ // String (double quoted)
102
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') && trimmed.length >= 2) {
103
+ return trimmed
104
+ .slice(1, -1)
105
+ .replace(/\\"/g, '"')
106
+ .replace(/\\n/g, "\n")
107
+ .replace(/\\t/g, "\t")
108
+ .replace(/\\\\/g, "\\");
109
+ }
110
+
111
+ // String (single quoted)
112
+ if (trimmed.startsWith("'") && trimmed.endsWith("'") && trimmed.length >= 2) {
113
+ return trimmed.slice(1, -1);
114
+ }
115
+
116
+ // Array
117
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
118
+ const inner = trimmed.slice(1, -1).trim();
119
+ if (!inner) return [];
120
+ return splitTomlArray(inner).map(parseTomlValue);
121
+ }
122
+
123
+ // Number (Integer or Float)
124
+ if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
125
+ return trimmed.includes(".") ? parseFloat(trimmed) : parseInt(trimmed, 10);
126
+ }
127
+
128
+ // Fallback unquoted string
129
+ return trimmed;
130
+ }
131
+
132
+ function splitTomlArray(arrayContent: string): string[] {
133
+ const items: string[] = [];
134
+ let current = "";
135
+ let inQuote = false;
136
+ let quoteChar = "";
137
+ let depth = 0;
138
+
139
+ for (let i = 0; i < arrayContent.length; i++) {
140
+ const ch = arrayContent[i];
141
+
142
+ if ((ch === '"' || ch === "'") && (i === 0 || arrayContent[i - 1] !== "\\")) {
143
+ if (!inQuote) {
144
+ inQuote = true;
145
+ quoteChar = ch;
146
+ } else if (quoteChar === ch) {
147
+ inQuote = false;
148
+ }
149
+ current += ch;
150
+ } else if (ch === "[" && !inQuote) {
151
+ depth++;
152
+ current += ch;
153
+ } else if (ch === "]" && !inQuote) {
154
+ depth--;
155
+ current += ch;
156
+ } else if (ch === "," && !inQuote && depth === 0) {
157
+ if (current.trim()) {
158
+ items.push(current.trim());
159
+ }
160
+ current = "";
161
+ } else {
162
+ current += ch;
163
+ }
164
+ }
165
+
166
+ if (current.trim()) {
167
+ items.push(current.trim());
168
+ }
169
+
170
+ return items;
171
+ }
172
+
173
+ export function stringifyToml(
174
+ obj: Record<string, TomlValue>,
175
+ prefix = "",
176
+ ): string {
177
+ let out = "";
178
+ const topLevelKeys: string[] = [];
179
+ const tables: Array<{ key: string; val: Record<string, TomlValue> }> = [];
180
+
181
+ for (const [k, v] of Object.entries(obj)) {
182
+ if (v && typeof v === "object" && !Array.isArray(v)) {
183
+ tables.push({ key: k, val: v });
184
+ } else {
185
+ topLevelKeys.push(k);
186
+ }
187
+ }
188
+
189
+ // Top level keys first
190
+ for (const k of topLevelKeys) {
191
+ out += `${k} = ${formatTomlValue(obj[k])}\n`;
192
+ }
193
+
194
+ // Tables
195
+ for (const table of tables) {
196
+ const tableHeader = prefix ? `${prefix}.${table.key}` : table.key;
197
+ if (out.length > 0 && !out.endsWith("\n\n")) {
198
+ out += "\n";
199
+ }
200
+ out += `[${tableHeader}]\n`;
201
+
202
+ const subKeys: string[] = [];
203
+ const subTables: Array<{ key: string; val: Record<string, TomlValue> }> = [];
204
+
205
+ for (const [sk, sv] of Object.entries(table.val)) {
206
+ if (sv && typeof sv === "object" && !Array.isArray(sv)) {
207
+ subTables.push({ key: sk, val: sv });
208
+ } else {
209
+ subKeys.push(sk);
210
+ }
211
+ }
212
+
213
+ for (const sk of subKeys) {
214
+ out += `${sk} = ${formatTomlValue(table.val[sk])}\n`;
215
+ }
216
+
217
+ for (const subTable of subTables) {
218
+ out += "\n" + stringifyToml({ [subTable.key]: subTable.val }, tableHeader);
219
+ }
220
+ }
221
+
222
+ return out;
223
+ }
224
+
225
+ function formatTomlValue(val: TomlValue): string {
226
+ if (typeof val === "boolean") return val ? "true" : "false";
227
+ if (typeof val === "number") return String(val);
228
+ if (typeof val === "string") {
229
+ return `"${val.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
230
+ }
231
+ if (Array.isArray(val)) {
232
+ const formatted = val.map(formatTomlValue);
233
+ return `[${formatted.join(", ")}]`;
234
+ }
235
+ if (val === null || val === undefined) return '""';
236
+ return `"${String(val)}"`;
237
+ }
@@ -0,0 +1,99 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import * as os from "os";
4
+ import { getPiHomeDir } from "../config";
5
+
6
+ /**
7
+ * Sanitizes and repairs session JSONL files in ~/.pi/agent/sessions/
8
+ * Ensures that any compaction, branch_summary, or message entry with a partial
9
+ * usage object has a valid `cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }`
10
+ * to prevent uncaught TypeErrors in Pi's TUI footer renderer (usage-totals.js:15).
11
+ */
12
+ export function sanitizeSessionFiles(agentDir?: string): { repairedFiles: number; repairedEntries: number } {
13
+ let repairedFiles = 0;
14
+ let repairedEntries = 0;
15
+
16
+ try {
17
+ const baseAgentDir = agentDir || path.join(getPiHomeDir(), "agent");
18
+ const sessionsDir = path.join(baseAgentDir, "sessions");
19
+
20
+ if (!fs.existsSync(sessionsDir)) {
21
+ return { repairedFiles: 0, repairedEntries: 0 };
22
+ }
23
+
24
+ const sessionFolders = fs.readdirSync(sessionsDir);
25
+
26
+ for (const folder of sessionFolders) {
27
+ const folderPath = path.join(sessionsDir, folder);
28
+ if (!fs.statSync(folderPath).isDirectory()) continue;
29
+
30
+ const files = fs.readdirSync(folderPath);
31
+ for (const file of files) {
32
+ if (!file.endsWith(".jsonl")) continue;
33
+
34
+ const filePath = path.join(folderPath, file);
35
+ try {
36
+ const content = fs.readFileSync(filePath, "utf8");
37
+ const lines = content.split("\n");
38
+ let fileModified = false;
39
+
40
+ const repairedLines = lines.map((line) => {
41
+ if (!line.trim()) return line;
42
+ try {
43
+ const entry = JSON.parse(line);
44
+ let entryModified = false;
45
+
46
+ // Check compaction / branch_summary usage
47
+ if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
48
+ if (!entry.usage.cost || typeof entry.usage.cost.total !== "number") {
49
+ entry.usage.cost = {
50
+ input: 0,
51
+ output: 0,
52
+ cacheRead: 0,
53
+ cacheWrite: 0,
54
+ total: 0,
55
+ };
56
+ entryModified = true;
57
+ }
58
+ }
59
+
60
+ // Check message usage
61
+ if (entry.type === "message" && entry.message && entry.message.usage) {
62
+ if (!entry.message.usage.cost || typeof entry.message.usage.cost.total !== "number") {
63
+ entry.message.usage.cost = {
64
+ input: 0,
65
+ output: 0,
66
+ cacheRead: 0,
67
+ cacheWrite: 0,
68
+ total: 0,
69
+ };
70
+ entryModified = true;
71
+ }
72
+ }
73
+
74
+ if (entryModified) {
75
+ fileModified = true;
76
+ repairedEntries++;
77
+ return JSON.stringify(entry);
78
+ }
79
+ } catch (e) {
80
+ // Ignore unparseable lines
81
+ }
82
+ return line;
83
+ });
84
+
85
+ if (fileModified) {
86
+ fs.writeFileSync(filePath, repairedLines.join("\n"), "utf8");
87
+ repairedFiles++;
88
+ }
89
+ } catch (err) {
90
+ // Ignore individual file read errors
91
+ }
92
+ }
93
+ }
94
+ } catch (err) {
95
+ // Ignore top-level directory errors
96
+ }
97
+
98
+ return { repairedFiles, repairedEntries };
99
+ }
@@ -0,0 +1,365 @@
1
+ /**
2
+ * Per-session content-addressed dedup store.
3
+ *
4
+ * Trigger: SHA-256 of the rendered tool-result text combined with the tool
5
+ * name and a stable digest of the input parameters. Same content + same
6
+ * tool + same params = dedup. Same content + different tool or different
7
+ * params = new ref. This is a strict byte-equality rule with one extra
8
+ * dimension (input identity) so that `read(file, offset=1, limit=200)`
9
+ * and `read(file, offset=100, limit=100)` are not deduped against each
10
+ * other, even if the rendered bytes happen to overlap.
11
+ *
12
+ * Reference format: "r1", "r2", ... per-session monotonic counter.
13
+ * LRU-bounded: oldest entries are evicted when the per-session cap is
14
+ * exceeded, with a preference for evicting entries the LLM has already
15
+ * lost track of (entries whose `lastSeenInContext` is below the session's
16
+ * current compaction counter).
17
+ *
18
+ * Compaction safety: each entry records `lastSeenInContext` (the compaction
19
+ * counter value at the time the result was emitted). A duplicate is only
20
+ * deduped when the prior entry's `lastSeenInContext` matches the current
21
+ * compaction counter for the session — meaning the LLM still has the prior
22
+ * full text in its current context. After any compaction, the next duplicate
23
+ * is treated as a new first occurrence.
24
+ */
25
+
26
+ import * as crypto from "node:crypto";
27
+
28
+ export interface DedupEntry {
29
+ shortRef: string;
30
+ contentHash: string;
31
+ /** Tool name (e.g. "read", "code_search", "bash"). */
32
+ toolName: string;
33
+ /** Full SHA-256 digest of the stable input parameters; authoritative key. */
34
+ paramsHash: string;
35
+ /** Short hex digest of the input parameters for display; 4 hex chars. */
36
+ paramsKey: string;
37
+ callId: string;
38
+ fullText: string;
39
+ sizeBytes: number;
40
+ lastSeenInContext: number;
41
+ }
42
+
43
+ export interface RecordResult {
44
+ isDuplicate: boolean;
45
+ shortRef: string;
46
+ priorRef: string | null;
47
+ }
48
+
49
+ export interface DedupStoreOptions {
50
+ /** Don't record or dedup results whose text length is <= this many bytes. */
51
+ minBytes?: number;
52
+ /**
53
+ * LRU cap per session. Oldest entries are evicted first, with a
54
+ * preference for evicting entries the LLM has lost track of (post-
55
+ * compaction) before evicting still-live ones.
56
+ */
57
+ maxEntriesPerSession?: number;
58
+ }
59
+
60
+ const DEFAULT_MIN_BYTES = 80;
61
+ const DEFAULT_MAX_ENTRIES = 1024;
62
+
63
+ export class DedupStore {
64
+ private bySession = new Map<string, SessionState>();
65
+ private minBytes: number;
66
+ private maxEntries: number;
67
+
68
+ constructor(options: DedupStoreOptions = {}) {
69
+ this.minBytes = options.minBytes ?? DEFAULT_MIN_BYTES;
70
+ this.maxEntries = options.maxEntriesPerSession ?? DEFAULT_MAX_ENTRIES;
71
+ }
72
+
73
+ private getOrCreateSession(sessionId: string): SessionState {
74
+ let s = this.bySession.get(sessionId);
75
+ if (!s) {
76
+ s = {
77
+ entries: new Map<string, DedupEntry>(),
78
+ byDedupKey: new Map<string, string>(),
79
+ insertionOrder: [],
80
+ compactionCounter: 0,
81
+ nextRefNumber: 1,
82
+ };
83
+ this.bySession.set(sessionId, s);
84
+ }
85
+ return s;
86
+ }
87
+
88
+ /**
89
+ * Record a tool result and decide whether the caller should emit a dedup
90
+ * reference or the full text.
91
+ *
92
+ * @param toolName The name of the tool that produced the result. Used
93
+ * as part of the dedup key so `read` and `code_search` of the
94
+ * same file produce different refs.
95
+ * @param inputParams The tool's input parameters as a plain object
96
+ * (e.g. `event.input`). The store applies a stable key-sorted
97
+ * stringify so insertion order does not affect the dedup key.
98
+ * @param isError Pass-through if true. Errors are never deduped.
99
+ * @param currentCompactionCounter Pass the session's current compaction
100
+ * counter so the store can decide whether a prior entry is still
101
+ * "live" in the LLM's context.
102
+ */
103
+ record(
104
+ sessionId: string,
105
+ callId: string,
106
+ toolName: string,
107
+ inputParams: unknown,
108
+ fullText: string,
109
+ isError: boolean,
110
+ currentCompactionCounter: number,
111
+ ): RecordResult {
112
+ // Errors and short results are never deduped. Return a fresh ref
113
+ // (caller will not use it for a dedup notice; full text is emitted).
114
+ if (isError || Buffer.byteLength(fullText, "utf8") <= this.minBytes) {
115
+ const s = this.getOrCreateSession(sessionId);
116
+ const shortRef = this.allocateRef(s);
117
+ const paramsHash = hashParams(inputParams);
118
+ const paramsKey = paramsHash.slice(0, 4);
119
+ s.entries.set(shortRef, {
120
+ shortRef,
121
+ contentHash: hashOf(fullText),
122
+ toolName,
123
+ paramsHash,
124
+ paramsKey,
125
+ callId,
126
+ fullText,
127
+ sizeBytes: Buffer.byteLength(fullText, "utf8"),
128
+ lastSeenInContext: currentCompactionCounter,
129
+ });
130
+ // Don't index by dedup key — we don't want a future identical
131
+ // content to become a dedup reference to an error or short result.
132
+ s.insertionOrder.push(shortRef);
133
+ this.evictIfNeeded(s);
134
+ return { isDuplicate: false, shortRef, priorRef: null };
135
+ }
136
+
137
+ const s = this.getOrCreateSession(sessionId);
138
+ const contentHash = hashOf(fullText);
139
+ const paramsHash = hashParams(inputParams);
140
+ const paramsKey = paramsHash.slice(0, 4);
141
+ const dedupKey = contentHash + ":" + toolName + ":" + paramsHash;
142
+ const priorRef = s.byDedupKey.get(dedupKey);
143
+
144
+ if (
145
+ priorRef !== undefined &&
146
+ s.entries.has(priorRef) &&
147
+ s.entries.get(priorRef)!.lastSeenInContext === currentCompactionCounter
148
+ ) {
149
+ // Duplicate AND same tool + same params AND the LLM still has
150
+ // the prior full text. Promote the matched entry to MRU so an
151
+ // access-ordered LRU does not evict a hot reference.
152
+ this.touchInOrder(s, priorRef);
153
+ return { isDuplicate: true, shortRef: priorRef, priorRef };
154
+ }
155
+
156
+ // Not a duplicate (or a stale one — pre-compaction). Allocate a new
157
+ // ref and store. A different `toolName` or different `inputParams`
158
+ // naturally produces a different dedupKey, so it does not dedup
159
+ // against an existing entry even if `fullText` is byte-equal.
160
+ const shortRef = this.allocateRef(s);
161
+ s.entries.set(shortRef, {
162
+ shortRef,
163
+ contentHash,
164
+ toolName,
165
+ paramsHash,
166
+ paramsKey,
167
+ callId,
168
+ fullText,
169
+ sizeBytes: Buffer.byteLength(fullText, "utf8"),
170
+ lastSeenInContext: currentCompactionCounter,
171
+ });
172
+ s.byDedupKey.set(dedupKey, shortRef);
173
+ s.insertionOrder.push(shortRef);
174
+ this.evictIfNeeded(s);
175
+ return { isDuplicate: false, shortRef, priorRef: null };
176
+ }
177
+
178
+ /**
179
+ * Retrieve the full text and metadata for a previously-allocated ref.
180
+ * Returns null if the ref is unknown in this session.
181
+ */
182
+ get(
183
+ sessionId: string,
184
+ shortRef: string,
185
+ ): { fullText: string; sizeBytes: number; toolName: string; paramsKey: string } | null {
186
+ const s = this.bySession.get(sessionId);
187
+ if (!s) return null;
188
+ const entry = s.entries.get(shortRef);
189
+ if (!entry) return null;
190
+ return {
191
+ fullText: entry.fullText,
192
+ sizeBytes: entry.sizeBytes,
193
+ toolName: entry.toolName,
194
+ paramsKey: entry.paramsKey,
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Increment the per-session compaction counter. After this call, any
200
+ * prior entry that was recorded before the increment will fail the
201
+ * `lastSeenInContext === currentCompactionCounter` check on the next
202
+ * `record`, so the next duplicate will be treated as a new first
203
+ * occurrence.
204
+ */
205
+ onCompaction(sessionId: string): void {
206
+ const s = this.getOrCreateSession(sessionId);
207
+ s.compactionCounter += 1;
208
+ }
209
+
210
+ /**
211
+ * Diagnostic accessor. Returns the current compaction counter for the
212
+ * session (0 if no compaction has been recorded).
213
+ */
214
+ getCompactionCounter(sessionId: string): number {
215
+ const s = this.bySession.get(sessionId);
216
+ return s?.compactionCounter ?? 0;
217
+ }
218
+
219
+ /**
220
+ * Test-only / diagnostic. Number of entries currently held for the session.
221
+ */
222
+ size(sessionId: string): number {
223
+ return this.bySession.get(sessionId)?.entries.size ?? 0;
224
+ }
225
+
226
+ /**
227
+ * Test-only / cleanup. Drop all state for a session.
228
+ */
229
+ clearSession(sessionId: string): void {
230
+ this.bySession.delete(sessionId);
231
+ }
232
+
233
+ private allocateRef(s: SessionState): string {
234
+ const n = s.nextRefNumber++;
235
+ return `r${n}`;
236
+ }
237
+
238
+ /**
239
+ * Evict down to the cap. When choosing which entry to evict, prefer
240
+ * ones the LLM has already lost track of (post-compaction: their
241
+ * `lastSeenInContext` is below the current compaction counter). Only
242
+ * fall back to plain LRU (oldest in `insertionOrder`) when no such
243
+ * "dead" entries exist.
244
+ *
245
+ * This is the durability fix from the real-world test: previously, the
246
+ * LRU could evict a reference that was still visible in the LLM's
247
+ * context, making recall() return "no content stored". Now, anything
248
+ * the LLM can still see is preserved at the cost of evicting older
249
+ * already-summarized content.
250
+ */
251
+ private evictIfNeeded(s: SessionState): void {
252
+ while (s.insertionOrder.length > this.maxEntries) {
253
+ // Pass 1: try to evict an entry that is already dead to the LLM
254
+ // (lastSeenInContext is below the current compaction counter).
255
+ let evictedAny = false;
256
+ for (let i = 0; i < s.insertionOrder.length; i++) {
257
+ const candidateRef = s.insertionOrder[i];
258
+ const entry = s.entries.get(candidateRef);
259
+ if (entry && entry.lastSeenInContext < s.compactionCounter) {
260
+ this.evictOne(s, candidateRef);
261
+ evictedAny = true;
262
+ break;
263
+ }
264
+ }
265
+ if (evictedAny) continue;
266
+ // Pass 2: nothing dead to evict. Fall back to plain LRU
267
+ // (oldest at the head of insertionOrder). This is the case
268
+ // where the cap is too small for the current live context.
269
+ const oldestRef = s.insertionOrder.shift();
270
+ if (oldestRef === undefined) break;
271
+ this.evictOne(s, oldestRef);
272
+ }
273
+ }
274
+
275
+ private evictOne(s: SessionState, ref: string): void {
276
+ const entry = s.entries.get(ref);
277
+ if (!entry) return;
278
+ s.entries.delete(ref);
279
+ const dedupKey = entry.contentHash + ":" + entry.toolName + ":" + entry.paramsHash;
280
+ // Only delete from byDedupKey if the stored ref still points to
281
+ // this entry. (A different entry with the same dedup key may have
282
+ // overwritten it; in that case we should not delete the new ref.)
283
+ if (s.byDedupKey.get(dedupKey) === ref) {
284
+ s.byDedupKey.delete(dedupKey);
285
+ }
286
+ const idx = s.insertionOrder.indexOf(ref);
287
+ if (idx >= 0) s.insertionOrder.splice(idx, 1);
288
+ }
289
+
290
+ /** Move a ref to the most-recently-used end of the insertion order. */
291
+ private touchInOrder(s: SessionState, ref: string): void {
292
+ const idx = s.insertionOrder.indexOf(ref);
293
+ if (idx === -1) return;
294
+ s.insertionOrder.splice(idx, 1);
295
+ s.insertionOrder.push(ref);
296
+ }
297
+ }
298
+
299
+ interface SessionState {
300
+ entries: Map<string, DedupEntry>;
301
+ /** Map from `contentHash:toolName:paramsHash` to ref. */
302
+ byDedupKey: Map<string, string>;
303
+ /**
304
+ * MRU-ordered list of refs. New allocations and dedup hits push to the
305
+ * tail; eviction removes from the head. A hit on a prior entry promotes
306
+ * it to MRU so the LRU reflects actual access pattern, not just insertion.
307
+ */
308
+ insertionOrder: string[];
309
+ compactionCounter: number;
310
+ nextRefNumber: number;
311
+ }
312
+
313
+ function hashOf(text: string): string {
314
+ return crypto.createHash("sha256").update(text, "utf8").digest("hex");
315
+ }
316
+
317
+ /** Full SHA-256 digest of the stable input parameters. */
318
+ function hashParams(inputParams: unknown): string {
319
+ const s = typeof inputParams === "string" ? inputParams : stableStringify(inputParams);
320
+ return crypto.createHash("sha256").update(s, "utf8").digest("hex");
321
+ }
322
+
323
+ /**
324
+ * Stable JSON stringify with sorted keys. Two equivalent objects with
325
+ * different key insertion order produce the same string. This makes the
326
+ * paramsKey deterministic for a given semantic input, so
327
+ * `read({path: "a"})` and `read({path: "a"})` always match even if the
328
+ * harness builds the object in different orders.
329
+ */
330
+ export function stableStringify(value: unknown): string {
331
+ return stringifyStable(value, new Set<unknown>());
332
+ }
333
+
334
+ function stringifyStable(value: unknown, seen: Set<unknown>): string {
335
+ if (value === null) return "null";
336
+ if (value === undefined) return "undefined";
337
+ const t = typeof value;
338
+ if (t === "string") return JSON.stringify(value);
339
+ if (t === "number" || t === "boolean") return String(value);
340
+ if (t === "bigint") return value.toString();
341
+ if (Array.isArray(value)) {
342
+ if (seen.has(value)) return '"[circular]"';
343
+ seen.add(value);
344
+ const parts: string[] = [];
345
+ for (const v of value) parts.push(stringifyStable(v, seen));
346
+ seen.delete(value);
347
+ return "[" + parts.join(",") + "]";
348
+ }
349
+ if (t === "object") {
350
+ const obj = value as Record<string, unknown>;
351
+ if (seen.has(obj)) return '"[circular]"';
352
+ seen.add(obj);
353
+ const keys = Object.keys(obj).sort();
354
+ const parts: string[] = [];
355
+ for (const k of keys) {
356
+ const v = obj[k];
357
+ if (v === undefined) continue;
358
+ parts.push(JSON.stringify(k) + ":" + stringifyStable(v, seen));
359
+ }
360
+ seen.delete(obj);
361
+ return "{" + parts.join(",") + "}";
362
+ }
363
+ // Function, symbol, etc. — not a meaningful input parameter; skip.
364
+ return '"[unsupported]"';
365
+ }