pi-tuck 1.1.2 → 1.2.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 (77) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +7 -3
  3. package/dist/index.d.ts +2 -6
  4. package/dist/index.js +16 -111
  5. package/dist/src/build-id.d.ts +1 -1
  6. package/dist/src/build-id.js +1 -1
  7. package/dist/src/compaction.d.ts +2 -103
  8. package/dist/src/compaction.js +29 -146
  9. package/dist/src/diagnostic-replay.js +2 -2
  10. package/dist/src/diagnostics.d.ts +3 -2
  11. package/dist/src/diagnostics.js +30 -9
  12. package/dist/src/history-tools.js +3 -3
  13. package/dist/src/kept-reads.d.ts +2 -2
  14. package/dist/src/kept-reads.js +144 -8
  15. package/dist/src/ledger.d.ts +1 -1
  16. package/dist/src/ledger.js +5 -3
  17. package/dist/src/legacy-cleanup.d.ts +3 -0
  18. package/dist/src/legacy-cleanup.js +190 -0
  19. package/dist/src/notify.d.ts +3 -0
  20. package/dist/src/notify.js +13 -0
  21. package/dist/src/omissions.d.ts +1 -1
  22. package/dist/src/omissions.js +3 -3
  23. package/dist/src/path-key.d.ts +3 -0
  24. package/dist/src/path-key.js +8 -0
  25. package/dist/src/request-capacity.js +1 -1
  26. package/dist/src/run.d.ts +1 -3
  27. package/dist/src/run.js +3 -5
  28. package/dist/src/source-export.d.ts +1 -1
  29. package/dist/src/source-export.js +1 -1
  30. package/dist/src/status.d.ts +0 -6
  31. package/dist/src/status.js +1 -6
  32. package/dist/src/tuck/core/content.js +6 -9
  33. package/dist/src/tuck/core/keyword-query.d.ts +2 -2
  34. package/dist/src/tuck/core/keyword-query.js +1 -1
  35. package/dist/src/tuck/core/search-entries.js +5 -5
  36. package/dist/src/tuck/core/transcript.js +2 -1
  37. package/dist/src/tuck.js +390 -394
  38. package/dist/src/windows-private-storage.d.ts +9 -0
  39. package/dist/src/windows-private-storage.js +90 -0
  40. package/index.ts +18 -82
  41. package/package.json +5 -8
  42. package/src/build-id.ts +1 -1
  43. package/src/compaction.ts +28 -113
  44. package/src/diagnostic-replay.ts +2 -2
  45. package/src/diagnostics.ts +24 -9
  46. package/src/history-tools.ts +3 -3
  47. package/src/kept-reads.ts +78 -10
  48. package/src/ledger.ts +5 -3
  49. package/src/legacy-cleanup.ts +134 -0
  50. package/src/notify.ts +10 -0
  51. package/src/omissions.ts +3 -3
  52. package/src/path-key.ts +9 -0
  53. package/src/request-capacity.ts +1 -1
  54. package/src/run.ts +4 -6
  55. package/src/source-export.ts +1 -1
  56. package/src/status.ts +1 -10
  57. package/src/tuck/core/content.ts +5 -10
  58. package/src/tuck/core/keyword-query.ts +2 -2
  59. package/src/tuck/core/search-entries.ts +5 -5
  60. package/src/tuck/core/transcript.ts +2 -1
  61. package/src/tuck.ts +329 -335
  62. package/src/windows-private-storage.ts +94 -0
  63. package/dist/src/assets.d.ts +0 -58
  64. package/dist/src/assets.js +0 -80
  65. package/dist/src/eligibility-cache.d.ts +0 -19
  66. package/dist/src/eligibility-cache.js +0 -33
  67. package/dist/src/semantic-recall.d.ts +0 -422
  68. package/dist/src/semantic-recall.js +0 -1386
  69. package/dist/src/setup.d.ts +0 -3
  70. package/dist/src/setup.js +0 -191
  71. package/scripts/eg2-runtime.py +0 -307
  72. package/scripts/provision-eg2.py +0 -139
  73. package/scripts/semantic-worker.py +0 -234
  74. package/src/assets.ts +0 -92
  75. package/src/eligibility-cache.ts +0 -43
  76. package/src/semantic-recall.ts +0 -592
  77. package/src/setup.ts +0 -163
@@ -1,1386 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { readFile, rm, mkdtemp, mkdir, writeFile } from 'node:fs/promises';
4
- import { lstatSync, realpathSync } from 'node:fs';
5
- import { resolve, relative, join, dirname, basename, isAbsolute, sep } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
- import { LLAMA, defaultRoot, runtimeConfigPath } from './assets.js';
8
- import { createRecall } from './recall.js';
9
- import { buildGlobalIndexById } from './tuck/core/global-indices.js';
10
- // Session-owned mutable scratch is outside verified software and caller projects.
11
- const hash = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
12
- const abort = () => Object.assign(new Error('Semantic recall cancelled'), { name: 'AbortError' });
13
- const yieldWork = () => new Promise(done => setTimeout(done, 5));
14
- // Resolve existing ancestors without creating an index or accepting a dangling link.
15
- function physicalPath(path) {
16
- const parts = [];
17
- let parent = resolve(path);
18
- for (;;) {
19
- try {
20
- return join(realpathSync(parent), ...parts);
21
- }
22
- catch (error) {
23
- if (error.code !== 'ENOENT')
24
- throw error;
25
- try {
26
- lstatSync(parent);
27
- throw error;
28
- }
29
- catch (statError) {
30
- if (statError === error || statError.code !== 'ENOENT')
31
- throw statError;
32
- }
33
- const next = dirname(parent);
34
- if (next === parent)
35
- throw error;
36
- parts.unshift(basename(parent));
37
- parent = next;
38
- }
39
- }
40
- }
41
- const inside = (base, target) => { const rel = relative(base, target); return rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel); };
42
- function outsideProject(project, path, kind) {
43
- if (inside(resolve(project), resolve(path)) || inside(physicalPath(project), physicalPath(path)))
44
- throw new Error('Semantic ' + kind + ' must be outside project');
45
- }
46
- function outsideRuntime(runtime, path, kind) {
47
- if (inside(resolve(runtime), resolve(path)) || inside(physicalPath(runtime), physicalPath(path)))
48
- throw new Error('Semantic ' + kind + ' must be outside immutable runtime');
49
- }
50
- function scratchParent(config) { return config.scratchDirectory ?? dirname(config.indexDirectory); }
51
- const sourceCharacters = (source) => source.ranges.reduce((n, r) => n + r.end - r.start, 0);
52
- const expandedGroups = Symbol('expanded semantic groups');
53
- const nativeBase64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
54
- function nativeObject(text) {
55
- const value = JSON.parse(text), tokens = text.match(/"(?:\\.|[^"\\])*"|[{}:\[\],]/g) ?? [], objects = [];
56
- for (let i = 0; i < tokens.length; i++) {
57
- const token = tokens[i];
58
- if (token === '{')
59
- objects.push(new Set());
60
- else if (token === '}')
61
- objects.pop();
62
- else if (token?.startsWith('"') && tokens[i + 1] === ':') {
63
- const key = JSON.parse(token), keys = objects.at(-1);
64
- if (keys.has(key))
65
- throw new Error('Duplicate native frame key');
66
- keys.add(key);
67
- }
68
- }
69
- return value;
70
- }
71
- function nativeSafeError(frame) {
72
- if (Object.keys(frame).sort().join(',') !== 'error,ok,version' || frame.version !== 1 || frame.ok !== false || !frame.error || typeof frame.error !== 'object' || Array.isArray(frame.error))
73
- return false;
74
- const error = frame.error;
75
- return Object.keys(error).sort().join(',') === 'code,message' && ['INVALID_REQUEST', 'RUN_START', 'RUN_SETTLEMENT'].includes(error.code) && typeof error.message === 'string' && error.message.length > 0 && error.message.length <= 1024;
76
- }
77
- function observeNativeFrames(stream, stderr, invalid, diagnostic = invalid) {
78
- let pending = Buffer.alloc(0), receipt, broken = false;
79
- const bad = () => { if (!broken) {
80
- broken = true;
81
- receipt = undefined;
82
- pending = Buffer.alloc(0);
83
- invalid();
84
- } };
85
- stream.on('data', (chunk) => {
86
- if (broken)
87
- return;
88
- let start = 0;
89
- while (start < chunk.length) {
90
- const lf = chunk.indexOf(10, start), end = lf < 0 ? chunk.length : lf;
91
- if (pending.length + end - start > 65536) {
92
- bad();
93
- return;
94
- }
95
- pending = Buffer.concat([pending, chunk.subarray(start, end)]);
96
- if (lf < 0)
97
- break;
98
- try {
99
- const text = pending.toString('utf8');
100
- if (!Buffer.from(text).equals(pending) || text.includes('\r'))
101
- throw new Error();
102
- const frame = nativeObject(text);
103
- if (!frame || typeof frame !== 'object' || Array.isArray(frame))
104
- throw new Error();
105
- const keys = Object.keys(frame).sort().join(',');
106
- // A strict diagnostic can accompany an operation failure before or after
107
- // its one zero receipt. It cannot erase observed cleanup or become success.
108
- if (nativeSafeError(frame))
109
- diagnostic();
110
- else if (receipt)
111
- throw new Error('Native output followed settlement');
112
- else if (keys === 'data,op' && frame.op === 'stderr' && typeof frame.data === 'string' && nativeBase64.test(frame.data)) {
113
- const data = Buffer.from(frame.data, 'base64');
114
- if (data.length > 32768 || data.toString('base64') !== frame.data)
115
- throw new Error();
116
- stderr(data);
117
- }
118
- else if (keys === 'activeProcesses,exitCode,op' && frame.op === 'settled' && frame.activeProcesses === 0 && (frame.exitCode === null || typeof frame.exitCode === 'number' && Number.isSafeInteger(frame.exitCode) && frame.exitCode >= 0 && frame.exitCode <= 4294967295))
119
- receipt = frame;
120
- else
121
- throw new Error();
122
- }
123
- catch {
124
- bad();
125
- return;
126
- }
127
- pending = Buffer.alloc(0);
128
- start = end + 1;
129
- }
130
- });
131
- stream.on('error', bad);
132
- return () => { if (pending.length)
133
- bad(); return broken ? undefined : receipt; };
134
- }
135
- async function joinExactNativeJob(helper, jobId) {
136
- for (;;) {
137
- const empty = await new Promise(done => {
138
- const child = spawn(helper, ['--join-job'], { stdio: 'pipe', windowsHide: true, env: { SYSTEMROOT: process.env.SYSTEMROOT ?? '' } });
139
- let invalid = false;
140
- const bad = () => { invalid = true; child.kill(); }, timer = setTimeout(bad, 5000);
141
- const receipt = observeNativeFrames(child.stderr, () => bad(), bad, () => { });
142
- child.stdout.on('data', bad);
143
- child.stdout.on('error', bad);
144
- child.stdin.on('error', bad);
145
- child.once('error', () => { invalid = true; });
146
- child.once('close', (code, signal) => { clearTimeout(timer); done(!invalid && code === 0 && !signal && !!receipt()); });
147
- child.stdin.end(JSON.stringify({ jobId }) + '\n');
148
- }).catch(() => false);
149
- if (empty)
150
- return;
151
- await new Promise(done => setTimeout(done, 250));
152
- }
153
- }
154
- /** A refusal, death or timeout of the worker (not a caller's cancel or a bound). `code` is the worker's reason code when it sent one. */
155
- class WorkerFailure extends Error {
156
- code;
157
- constructor(message, code = null) {
158
- super(message);
159
- this.code = code;
160
- this.name = 'SemanticWorkerFailure';
161
- }
162
- }
163
- /** Reasons the worker gives for a native encoder that failed to start or answer: time can mend these. Every other worker code is a verification refusal (membership, integrity, origin, pins, profile) that needs repair. */
164
- const TRANSIENT_CODES = new Set(['native_start_failure', 'native_start_timeout', 'native_request_failure', 'native_response_bound', 'native_transport_unavailable', 'local_runtime_failure']);
165
- const integrityRefusal = (error) => error.code !== null && !TRANSIENT_CODES.has(error.code);
166
- /** Automatic recovery after a failed start or a lost worker: bounded exponential backoff, then a steady slow cadence. Integrity refusals use the slow cadence only. */
167
- export const HEAL_DELAYS_MS = [5000, 30000, 120000];
168
- export const HEAL_STEADY_MS = 600000;
169
- /** A session that has not searched for this long gives its worker back (the index stays on disk). Enabling starts nothing; a search starts the worker again. */
170
- export const IDLE_STOP_MS = 600000;
171
- /** Background indexing (a session that has not searched, indexing what a cut moved out of view) holds this lock in the index directory, so
172
- * several Pi sessions on one machine embed one at a time: one encoder's memory at a time instead of one per session. A search never waits for it. */
173
- export const INDEXER_LOCK = 'background-indexer.lock';
174
- /** How long background indexing waits before trying the lock again when another process holds it. */
175
- export const INDEXER_RETRY_MS = 15000;
176
- const alive = (pid) => { try {
177
- process.kill(pid, 0);
178
- return true;
179
- }
180
- catch (error) {
181
- return error.code === 'EPERM';
182
- } };
183
- /** Take the machine's background-indexer lock, or null when another live holder has it. A holder that has died leaves a stale lock, which is taken over. */
184
- async function tryIndexerLock(directory) {
185
- const path = join(directory, INDEXER_LOCK), take = async () => { try {
186
- await mkdir(path);
187
- return true;
188
- }
189
- catch (error) {
190
- if (error.code === 'EEXIST')
191
- return false;
192
- throw error;
193
- } };
194
- if (!await take()) {
195
- const holder = Number(await readFile(join(path, 'pid'), 'utf8').catch(() => ''));
196
- if (holder && alive(holder))
197
- return null;
198
- await rm(path, { recursive: true, force: true });
199
- if (!await take())
200
- return null;
201
- }
202
- await writeFile(join(path, 'pid'), String(process.pid));
203
- return () => rm(path, { recursive: true, force: true });
204
- }
205
- /** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
206
- export const CALL_DEADLINE_MS = 60000;
207
- /** Why semantic recall is off where the embedding server cannot start on Metal (a VM, a Mac without a GPU): it runs on Metal only. */
208
- export const METAL_UNAVAILABLE = 'Semantic recall needs Metal; word recall still works';
209
- /** What an `embed` call adds to its deadline for each text it carries. A batch of 8 passages on a starved CPU took longer than the per-call
210
- * deadline, and the worker failed when it should have slowed down; a query (one text) still fails fast when the server hangs. The worker
211
- * scales its native request timeout by the same amount (semantic-worker.py), so that limit is not reached first. */
212
- export const EMBED_TEXT_MS = 30000;
213
- /** The deadline for a worker's start: Python start, `ready` (which verifies every runtime file) and the first call after it, which loads the
214
- * model and starts its native server. On a busy machine that takes minutes; held to the per-call deadline, the worker never started and
215
- * semantic recall went unavailable. It stays above the worker's own native start limit (540 s, in semantic-worker.py). */
216
- export const START_DEADLINE_MS = 600000;
217
- /** The most units one index window holds. The worker's SQLite store stops at 8,008 rows (`PRAGMA max_page_count=8192` in scripts/semantic-worker.py), so a cap below that keeps a window of short units from filling the store and sticking in `unavailable`. Raise it only together with the store. */
218
- export const MAX_INDEX_UNITS = 8000;
219
- /** Keys per worker `score` request: a multiple of the worker's 128-key sub-batches, aligned from the start of the covered prefix. A key is a SHA-256 hex digest (64 characters, see `hash`), so 1024 keys and the 768-float query make a request of about 90 KiB, far under both the 512 KiB design bound and the worker's 1 MiB line limit. */
220
- const SCORE_CHUNK = 1024;
221
- /** The wait before the next automatic attempt, given how many were already armed since the last success. */
222
- export function healDelayMs(attempts, integrity, delays = HEAL_DELAYS_MS, steady = HEAL_STEADY_MS) { return integrity ? steady : delays[attempts] ?? steady; }
223
- /** Errors that mean "the history moved or a slice ended; try again", not that the runtime failed. They do not make the state `unavailable`. */
224
- const CHURN = /indexing incomplete|history changed|source changed before|branch or source changed|cancelled/i;
225
- const OFF_SETUP = ['off-settings', 'off-user', 'off-platform', 'off-project'];
226
- /** Host policy is re-evaluated at session start; only a start may publish ready. */
227
- export const SEMANTIC_SETUP_TRANSITIONS = {
228
- 'off-settings': OFF_SETUP,
229
- 'off-user': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
230
- 'off-platform': [...OFF_SETUP, 'not-installed', 'starting'],
231
- 'off-project': [...OFF_SETUP, 'not-installed', 'starting'],
232
- 'not-installed': [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
233
- starting: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
234
- failed: [...OFF_SETUP, 'not-installed', 'starting', 'failed'],
235
- ready: [...OFF_SETUP, 'not-installed', 'starting', 'failed', 'ready'],
236
- };
237
- /** Setup and operator wording have one owner; runtime indexing state remains separate. */
238
- export function semanticSetupMessage(setup, detail = {}) {
239
- switch (setup) {
240
- case 'not-installed': return 'Semantic recall is not set up yet; start Pi once in an interactive session to set it up. Word recall works meanwhile';
241
- case 'starting': return detail.installed ? 'Semantic recall is starting; word recall works meanwhile' : 'Semantic recall is being set up; word recall works meanwhile';
242
- case 'failed': return detail.stage === 'start' ? detail.reason ?? 'Semantic recall could not start' : `Semantic recall setup failed: ${detail.reason}`;
243
- default: return null;
244
- }
245
- }
246
- export function semanticSetupNotice(setup, detail = {}) {
247
- let message, level = 'info';
248
- switch (setup) {
249
- case 'off-platform':
250
- message = 'pi-tuck: semantic recall needs macOS on Apple silicon; compaction and word recall work.';
251
- break;
252
- case 'off-project':
253
- message = "pi-tuck: semantic recall is off here because Pi's agent folder is inside this folder; open Pi in a project folder to use it.";
254
- break;
255
- case 'not-installed':
256
- message = 'pi-tuck: semantic recall is not set up yet; start Pi once in an interactive session to set it up. Word recall works.';
257
- level = 'warning';
258
- break;
259
- case 'starting':
260
- message = detail.notice;
261
- break;
262
- case 'ready':
263
- if (detail.announced)
264
- message = 'pi-tuck: semantic recall is set up. Search by meaning works from the first cut on.';
265
- break;
266
- case 'failed':
267
- message = detail.stage === 'start'
268
- ? `pi-tuck: semantic recall could not start (${detail.reason}); it tries again when a session starts.`
269
- : `pi-tuck: semantic recall setup failed (${detail.reason}). Word recall works; setup retries when a session starts.`;
270
- level = 'warning';
271
- break;
272
- }
273
- return message ? { message, level } : undefined;
274
- }
275
- const PROBE_TEXT = 'pi-tuck semantic recall status probe';
276
- class LocalWorker {
277
- config;
278
- project;
279
- cleanupFailure;
280
- onLoss;
281
- deadlines;
282
- nativeHelper = false;
283
- jobId;
284
- helperReceipt;
285
- nativeExit;
286
- // Serialize native RPC delivery by child reply, not host pipe acceptance.
287
- // This leaves room for the previous native write to finish plus one queued
288
- // control, even when the child replies before that writer goroutine retires.
289
- nativeInputs = [];
290
- nativeInputId;
291
- child;
292
- scratch;
293
- starting;
294
- exited;
295
- buffer = '';
296
- next = 0;
297
- pending = new Map();
298
- stopped = false;
299
- lost = false;
300
- closing;
301
- loaded = false;
302
- constructor(config, project, cleanupFailure, onLoss = () => { }, deadlines = { startMs: START_DEADLINE_MS, callMs: CALL_DEADLINE_MS, embedTextMs: EMBED_TEXT_MS }) {
303
- this.config = config;
304
- this.project = project;
305
- this.cleanupFailure = cleanupFailure;
306
- this.onLoss = onLoss;
307
- this.deadlines = deadlines;
308
- }
309
- closeInBackground() { void this.close().catch(error => this.cleanupFailure(error)); }
310
- // The worker stopped without the controller asking: report it once, then join it like any other background close.
311
- lose(reason) { if (!this.stopped && !this.lost) {
312
- this.lost = true;
313
- this.onLoss(reason);
314
- } this.closeInBackground(); }
315
- async start() {
316
- if (this.child)
317
- return;
318
- if (this.starting)
319
- return this.starting;
320
- this.starting = (async () => {
321
- this.nativeHelper = process.platform === 'win32';
322
- if (this.nativeHelper) {
323
- if (!this.config.nativeOwnerHelperPath)
324
- throw new Error('Windows semantic recall requires an explicit verified nativeOwnerHelperPath with streaming input and Job settlement');
325
- outsideProject(this.project, this.config.nativeOwnerHelperPath, 'runtime');
326
- }
327
- outsideProject(this.project, this.config.runtimeRoot, 'runtime');
328
- const scratchRoot = scratchParent(this.config);
329
- outsideProject(this.project, scratchRoot, 'scratch');
330
- outsideRuntime(this.config.runtimeRoot, scratchRoot, 'scratch');
331
- await mkdir(scratchRoot, { recursive: true, mode: 0o700 });
332
- outsideProject(this.project, scratchRoot, 'scratch');
333
- outsideRuntime(this.config.runtimeRoot, scratchRoot, 'scratch');
334
- this.scratch = await mkdtemp(join(scratchRoot, '.pi-semantic-'));
335
- outsideProject(this.project, this.scratch, 'scratch');
336
- outsideRuntime(this.config.runtimeRoot, this.scratch, 'scratch');
337
- if (this.stopped)
338
- throw new Error('Local worker closed');
339
- const worker = this.config.workerPath ?? fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../scripts/semantic-worker.py' : '../../scripts/semantic-worker.py', import.meta.url));
340
- const osNames = this.nativeHelper ? ['SYSTEMROOT', 'WINDIR', 'LANG', 'LC_ALL'] : ['SystemRoot', 'SYSTEMROOT', 'WINDIR', 'LANG', 'LC_ALL'];
341
- const osEnvironment = Object.fromEntries(osNames.flatMap(name => typeof process.env[name] === 'string' ? [[name, process.env[name]]] : []));
342
- const args = ['-I', '-B', '-u', worker], env = { ...osEnvironment, TMPDIR: this.scratch, TMP: this.scratch, TEMP: this.scratch, PI_SEMANTIC_RUNTIME_ROOT: this.config.runtimeRoot, PI_SEMANTIC_OWN_SERVER_SHA256: LLAMA.files['llama-server'] };
343
- this.jobId = randomUUID();
344
- const launch = { executable: this.config.pythonPath, args, cwd: this.scratch, env, jobId: this.jobId, stdinMode: 'stream' };
345
- const launchLine = JSON.stringify(launch) + '\n';
346
- if (this.nativeHelper && Buffer.byteLength(launchLine) > 2 * 1048576)
347
- throw new Error('Native owner launch bound');
348
- const child = spawn(this.nativeHelper ? this.config.nativeOwnerHelperPath : this.config.pythonPath, this.nativeHelper ? ['--run'] : args, { cwd: this.scratch, env: this.nativeHelper ? osEnvironment : env, stdio: 'pipe', detached: !this.nativeHelper });
349
- this.child = child;
350
- this.exited = new Promise(done => child.once('close', (code, signal) => { this.nativeExit = { code, signal }; this.rejectAll(new WorkerFailure('Local worker stopped')); done(); this.lose('Local worker stopped'); }));
351
- child.stdout.on('data', data => { this.buffer += data.toString(); if (this.buffer.length > 16 * 1024 * 1024) {
352
- this.lose('Local worker output bound');
353
- return;
354
- } let end; while ((end = this.buffer.indexOf('\n')) >= 0) {
355
- const line = this.buffer.slice(0, end);
356
- this.buffer = this.buffer.slice(end + 1);
357
- try {
358
- const reply = JSON.parse(line), pending = this.pending.get(reply.id);
359
- if (pending) {
360
- clearTimeout(pending.timer);
361
- this.pending.delete(reply.id);
362
- reply.ok ? pending.resolve(reply.result) : pending.reject(new WorkerFailure(reply.error?.code === 'metal_unavailable' ? METAL_UNAVAILABLE : 'Local semantic runtime: ' + reply.error?.code, reply.error?.code ?? null));
363
- if (this.nativeHelper && this.nativeInputId === reply.id) {
364
- this.nativeInputId = undefined;
365
- this.pumpNativeInput();
366
- }
367
- }
368
- }
369
- catch {
370
- this.lose('Local worker framing');
371
- }
372
- } });
373
- child.stdout.on('error', () => this.lose('Local worker output'));
374
- if (this.nativeHelper)
375
- this.helperReceipt = observeNativeFrames(child.stderr, () => { }, () => this.closeInBackground());
376
- else
377
- child.stderr.resume();
378
- child.stdin.on('error', () => this.lose('Local worker input'));
379
- child.on('error', () => { this.rejectAll(new WorkerFailure('Local runtime unavailable')); this.lose('Local runtime unavailable'); });
380
- if (this.nativeHelper)
381
- child.stdin.write(launchLine);
382
- })();
383
- try {
384
- await this.starting;
385
- }
386
- catch (error) {
387
- await this.close();
388
- throw error;
389
- }
390
- }
391
- async call(op, input = {}, signal) {
392
- if (signal?.aborted)
393
- throw abort();
394
- if (this.stopped)
395
- throw new WorkerFailure('Local worker closed');
396
- await this.start();
397
- if (this.stopped || signal?.aborted)
398
- throw this.lost && !signal?.aborted ? new WorkerFailure('Local worker stopped') : abort();
399
- if (this.pending.size >= 2)
400
- throw new Error('Local semantic concurrency bound');
401
- const id = ++this.next, body = JSON.stringify({ id, op, ...input }) + '\n';
402
- if (Buffer.byteLength(body) > 1048576)
403
- throw new Error('Local worker input bound');
404
- return new Promise((resolveReply, reject) => { const onAbort = () => { this.closeInBackground(); reject(abort()); }; signal?.addEventListener('abort', onAbort, { once: true }); const finish = (callback, value) => { signal?.removeEventListener('abort', onAbort); callback(value); }; const timer = setTimeout(() => { this.lose('Local runtime deadline'); finish(reject, new WorkerFailure('Local runtime deadline')); }, this.loaded ? this.deadlines.callMs + (op === 'embed' ? this.deadlines.embedTextMs * (input.texts?.length ?? 0) : 0) : this.deadlines.startMs); this.pending.set(id, { resolve: value => { if (op !== 'ready')
405
- this.loaded = true; finish(resolveReply, value); }, reject: error => finish(reject, error), timer }); if (this.nativeHelper) {
406
- const control = { op: 'input', input: Buffer.from(body).toString('base64') };
407
- this.nativeInputs.push({ id, control: JSON.stringify(control) + '\n' });
408
- this.pumpNativeInput();
409
- }
410
- else
411
- this.child.stdin.write(body); });
412
- }
413
- pumpNativeInput() { if (this.stopped || this.nativeInputId !== undefined)
414
- return; const next = this.nativeInputs.shift(); if (next) {
415
- this.nativeInputId = next.id;
416
- this.child.stdin.write(next.control);
417
- } }
418
- rejectAll(error) { for (const p of this.pending.values()) {
419
- clearTimeout(p.timer);
420
- p.reject(error);
421
- } this.pending.clear(); this.nativeInputs = []; this.nativeInputId = undefined; }
422
- async close() { if (this.closing)
423
- return this.closing; this.stopped = true; const closing = this.stopNative(); this.closing = closing; try {
424
- await closing;
425
- }
426
- finally {
427
- if (this.closing === closing)
428
- this.closing = undefined;
429
- } }
430
- async stopNative() {
431
- await this.starting?.catch(() => { });
432
- this.rejectAll(new WorkerFailure('Local worker closed'));
433
- const child = this.child;
434
- if (child) {
435
- if (this.nativeHelper) {
436
- // Never taskkill or kill the helper leader as a substitute for Job absence.
437
- if (!this.nativeExit) {
438
- const cancel = { op: 'cancel' };
439
- child.stdin.end(JSON.stringify(cancel) + '\n');
440
- }
441
- // Deadline can force kill-on-close, never claim settlement. Failed starts,
442
- // crashes and invalid frames still require exact named observation. Native
443
- // named absence cannot supply a receipt; retries retain scratch/index custody.
444
- const timer = setTimeout(() => child.kill(), 5000);
445
- try {
446
- await this.exited;
447
- }
448
- finally {
449
- clearTimeout(timer);
450
- }
451
- if (child.pid !== undefined && (!this.helperReceipt?.() || this.nativeExit?.signal || typeof this.nativeExit?.code !== 'number'))
452
- await joinExactNativeJob(this.config.nativeOwnerHelperPath, this.jobId);
453
- this.child = undefined;
454
- }
455
- else {
456
- // The worker and its native encoder share one owned process group. HTTP abort is not cancellation.
457
- // macOS answers EPERM for a group whose remaining member has exited but is not yet reaped: the group is still present, so keep polling to the bound below; only a group still present after it fails the close.
458
- const signal = (value) => { try {
459
- if (child.pid)
460
- process.kill(-child.pid, value);
461
- }
462
- catch (error) {
463
- const code = error.code;
464
- if (code !== 'ESRCH' && code !== 'EPERM')
465
- throw error;
466
- } };
467
- const alive = () => { if (!child.pid)
468
- return false; try {
469
- process.kill(-child.pid, 0);
470
- return true;
471
- }
472
- catch (error) {
473
- const code = error.code;
474
- if (code === 'ESRCH')
475
- return false;
476
- if (code === 'EPERM')
477
- return true;
478
- throw error;
479
- } };
480
- const timer = setTimeout(() => signal('SIGKILL'), 1000);
481
- signal('SIGTERM');
482
- try {
483
- await this.exited;
484
- if (alive())
485
- signal('SIGKILL');
486
- const until = Date.now() + 1000;
487
- while (alive() && Date.now() < until)
488
- await new Promise(done => setTimeout(done, 10));
489
- if (alive())
490
- throw new Error('Owned native encoder group did not close');
491
- this.child = undefined;
492
- }
493
- finally {
494
- clearTimeout(timer);
495
- }
496
- }
497
- }
498
- if (this.scratch) {
499
- await rm(this.scratch, { recursive: true, force: true });
500
- this.scratch = undefined;
501
- }
502
- }
503
- }
504
- /** Where the current view starts, as a branch position: the latest compaction entry's first kept entry. Earlier entries were compacted away. With no compaction, nothing is out of view. */
505
- export function viewStart(branch) {
506
- const at = branch.findLastIndex(entry => entry.type === 'compaction');
507
- if (at < 0)
508
- return 0;
509
- const entry = branch[at], kept = entry.type === 'compaction' ? branch.findIndex(candidate => candidate.id === entry.firstKeptEntryId) : -1;
510
- return kept >= 0 && kept <= at ? kept : at;
511
- }
512
- const TOOL_OUTPUT = new Set(['toolResult', 'bashExecution']);
513
- const isToolOutput = (source) => TOOL_OUTPUT.has(source.row.role);
514
- /** Whether `now` only grew from `plan`: the same session and project, and every source the plan ranks still eligible with the same hash. */
515
- function grownFrom(now, plan) {
516
- if (now.session !== plan.session || now.project !== plan.project)
517
- return false;
518
- if (now.id === plan.id)
519
- return true;
520
- const shas = new Map(now.sources.map(source => [source.entry.id, source.sha]));
521
- return plan.sources.every(source => shas.get(source.entry.id) === source.sha);
522
- }
523
- /** Sources in the order they are covered: out-of-view conversation (user messages, assistant text, tool-call names and arguments), then out-of-view tool output, then what is in view.
524
- * Each part is newest first, extending backward. */
525
- function windowOrder(snapshot) {
526
- const before = snapshot.sources.filter(source => source.order < snapshot.viewStart), kept = snapshot.sources.filter(source => source.order >= snapshot.viewStart);
527
- return [...before.filter(source => !isToolOutput(source)).reverse(), ...before.filter(isToolOutput).reverse(), ...kept.reverse()];
528
- }
529
- /** How many leading units of the window are indexed. Indexing runs in window order, so this is what the coverage statement covers and the only part a search ranks. */
530
- function indexedPrefix(snapshot) { let prefix = 0; while (prefix < snapshot.units.length && snapshot.indexed.has(snapshot.units[prefix].key))
531
- prefix++; return prefix; }
532
- /** The coverage statement of a snapshot for its first `prefix` units (the indexed prefix unless the caller froze another): back to the oldest source named. */
533
- function windowCoverage(snapshot, prefix = indexedPrefix(snapshot)) {
534
- const window = snapshot.window;
535
- if (!window)
536
- return null;
537
- const time = (source) => { const at = source?.row.sourceTime; return at && at.basis !== 'unknown' ? at.utc : null; };
538
- let indexedCharacters = 0, conversation = 0, tools = 0, units = 0, oldest, oldestTool;
539
- for (const [index, source] of window.order.entries()) {
540
- units += window.counts[index];
541
- if (units > prefix)
542
- break;
543
- const size = sourceCharacters(source);
544
- indexedCharacters += size;
545
- if (!oldest || source.order < oldest.order)
546
- oldest = source;
547
- if (source.order < snapshot.viewStart) {
548
- if (isToolOutput(source)) {
549
- tools += size;
550
- if (!oldestTool || source.order < oldestTool.order)
551
- oldestTool = source;
552
- }
553
- else
554
- conversation += size;
555
- }
556
- }
557
- return { indexedCharacters, windowCharacters: window.windowCharacters, outOfViewCharacters: window.conversationOutOfView + window.toolOutOfView, eligibleCharacters: window.eligibleCharacters, oldestCoveredEntryId: oldest?.entry.id ?? null, oldestCoveredTime: time(oldest),
558
- conversation: { indexedCharacters: conversation, outOfViewCharacters: window.conversationOutOfView }, toolResults: { indexedCharacters: tools, outOfViewCharacters: window.toolOutOfView, oldestCoveredTime: time(oldestTool) } };
559
- }
560
- /** `pendingKeptId`: the first kept entry of a cut pi-tuck has applied to the requests but Pi has not yet saved (a prompt's cut is saved at the end of
561
- * the first turn). Tools in that turn see the history as the model does: everything before that entry is out of view. */
562
- export function semanticEligibleSources(ctx, policy, access, pendingKeptId) {
563
- try {
564
- access();
565
- }
566
- catch (error) {
567
- throw Object.assign(new Error(error instanceof Error ? error.message : 'Source access denied'), { name: 'SemanticAccessError' });
568
- }
569
- const branch = ctx.sessionManager.getBranch(), all = ctx.sessionManager.getEntries();
570
- if (branch.some(e => e.type === 'context_edit' && e.replacement !== null))
571
- throw new Error('Unsupported replacement context edit');
572
- const omitted = new Set(branch.flatMap(e => e.type === 'context_edit' ? [e.targetId] : []));
573
- const projection = ctx.sessionManager.buildSessionProjection();
574
- for (const p of projection.entries)
575
- if (!p.messages.length && p.sourceEntry.type !== 'compaction')
576
- omitted.add(p.sourceEntry.id);
577
- const ids = new Map();
578
- for (const e of all)
579
- ids.set(e.id, (ids.get(e.id) ?? 0) + 1);
580
- const eligible = branch.filter(e => !omitted.has(e.id) && ids.get(e.id) === 1), recall = createRecall(policy), attempts = recall.recallAttempts(eligible), links = recall.producerReads(eligible), indices = buildGlobalIndexById(all);
581
- const orders = new Map(branch.map((entry, order) => [entry.id, order]));
582
- const sources = eligible.flatMap(entry => { const order = orders.get(entry.id); const row = recall.discoveryEntry(entry, attempts, links); if (!row)
583
- return []; const { sourceText: unusedText, ranges: unusedRanges, ...readable } = row; return [{ entry, row: readable, sourceText: row.sourceText, ranges: row.ranges, order, sha: hash({ entry, order, row: readable, ranges: row.ranges, index: indices.get(entry.id) }) }]; });
584
- const pending = pendingKeptId === undefined ? -1 : pendingKeptId === '' ? branch.length : branch.findIndex(e => e.id === pendingKeptId), start = Math.max(viewStart(branch), pending);
585
- const session = ctx.sessionManager.getSessionId(), id = hash({ session, project: resolve(ctx.cwd), branch: branch.map(e => [e.id, e.parentId]), sources: sources.map(s => [s.entry.id, s.sha]), ...(pending >= 0 ? { pendingKeptId } : {}) });
586
- return { id, session, project: ctx.cwd, sources, units: [], complete: false, throughEntryId: sources.at(-1)?.entry.id ?? null, viewStart: start, indexed: new Set() };
587
- }
588
- export class SemanticRecallController {
589
- timing;
590
- ownerId = randomUUID();
591
- indexFiles = new Set();
592
- closing;
593
- joiningSearches = 0;
594
- activeSearches = new Set();
595
- config;
596
- worker;
597
- identity = '';
598
- provider;
599
- generation = 0;
600
- cleanupError = null;
601
- dirty = false;
602
- operations = { preparationEmbeddings: 0, queryEmbeddings: 0 };
603
- // The fields below decide `status().state`; their setters announce a change to `onStateChange` listeners.
604
- setup = 'off-user';
605
- setupDetail = {};
606
- _enabled = false;
607
- _current;
608
- _task;
609
- _timer;
610
- _error = null;
611
- get enabled() { return this._enabled; }
612
- set enabled(value) {
613
- this._enabled = value;
614
- if (!value && this.setup === 'ready') {
615
- const reason = this.error ?? this.cleanupError;
616
- this.setSetup(reason ? 'failed' : 'off-user', reason ? { stage: 'start', reason } : {});
617
- }
618
- this.touch();
619
- }
620
- get current() { return this._current; }
621
- set current(value) { this._current = value; this.touch(); }
622
- get task() { return this._task; }
623
- set task(value) { this._task = value; this.touch(); }
624
- get timer() { return this._timer; }
625
- set timer(value) { this._timer = value; this.touch(); }
626
- get error() { return this._error; }
627
- set error(value) { this._error = value; this.touch(); }
628
- // Automatic recovery: why the last start failed or the worker was lost (null while healthy), the attempts armed since the last success, and the pending retry.
629
- // Tokenized units by source sha, kept across attempts: an attempt that a history change aborts loses nothing it finished, and the next one tokenizes only the rest.
630
- // Pruned to the eligible sources when an attempt starts and to the window when one publishes.
631
- tokenized = new Map();
632
- healReason = null;
633
- healIntegrity = false;
634
- healAttempts = 0;
635
- healTimer;
636
- healRetryAt = null;
637
- recycle = false;
638
- // Lazy start: background work runs only for a session that searched within the idle limit, or that searched at some point and has just been cut (`indexAtCut`).
639
- active = false;
640
- fullIndexing = false; /** Work a cut started with no search or wait behind it: it takes the machine's indexer lock, and its worker stops once the window is indexed. */
641
- backgroundOnly = false; /** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */
642
- releaseLock;
643
- idleTimer;
644
- idling;
645
- quietStop = false;
646
- // Whether this session ran a search since the controller was created or last closed; it survives idle stops, so a cut after a long quiet spell still indexes.
647
- searched = false;
648
- listeners = new Set();
649
- announced = 'disabled\0';
650
- announcing = false;
651
- constructor(config, timing = {}) {
652
- this.timing = timing;
653
- if (config)
654
- this.configure(config);
655
- }
656
- /** Be told when `status().state` or `lastError` changes: once per change, after the synchronous work that caused it. Returns the unsubscribe. A listener that throws is ignored. */
657
- onStateChange(listener) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
658
- touch() { if (this.announcing)
659
- return; this.announcing = true; queueMicrotask(() => { this.announcing = false; const { state, lastError } = this.status(), key = state + '\0' + (lastError ?? ''); if (key === this.announced)
660
- return; this.announced = key; for (const listener of [...this.listeners])
661
- try {
662
- listener(state, lastError);
663
- }
664
- catch { } }); }
665
- /** A host that could not configure the runtime records why a requested start failed. The controller stays disabled and `lastError` carries the reason until the next `enable`. */
666
- setSetup(setup, detail = {}) {
667
- if (!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes(setup))
668
- return;
669
- const announced = setup === 'ready' && this.setupDetail.announced;
670
- this.setup = setup;
671
- this.setupDetail = announced ? { ...detail, announced: true } : detail;
672
- this.touch();
673
- }
674
- /** Compatibility for hosts that already record an external start failure. */
675
- refuse(reason) { this.setSetup('failed', { stage: 'start', reason }); }
676
- setupNotice() { return semanticSetupNotice(this.setup, this.setupDetail); }
677
- configure(config) { if (this.enabled || this.worker || this.task)
678
- throw new Error('Disable before changing semantic configuration'); for (const [key, max] of [['queryWaitMs', 120000], ['prepareWorkMs', 120000], ['maxUnits', MAX_INDEX_UNITS], ['maxSourceCharacters', 2000000]]) {
679
- const value = config[key];
680
- if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > max))
681
- throw new Error('Invalid bounded semantic configuration: ' + key);
682
- } if ('rerank' in config)
683
- throw new Error('Obsolete rerank configuration: this release supports embeddings only'); for (const key of ['pythonPath', 'runtimeRoot', 'indexDirectory'])
684
- if (typeof config[key] !== 'string' || !config[key])
685
- throw new Error('Invalid semantic runtime configuration'); if (config.scratchDirectory !== undefined && (typeof config.scratchDirectory !== 'string' || !config.scratchDirectory || !isAbsolute(config.scratchDirectory)))
686
- throw new Error('Invalid semantic scratchDirectory; absolute directory required'); if (config.nativeOwnerHelperPath !== undefined && (typeof config.nativeOwnerHelperPath !== 'string' || !config.nativeOwnerHelperPath || !isAbsolute(config.nativeOwnerHelperPath)))
687
- throw new Error('Invalid semantic nativeOwnerHelperPath; absolute verified helper required'); const normalized = { ...config, pythonPath: resolve(config.pythonPath), runtimeRoot: resolve(config.runtimeRoot), indexDirectory: resolve(config.indexDirectory), ...(config.scratchDirectory === undefined ? {} : { scratchDirectory: resolve(config.scratchDirectory) }) }; outsideRuntime(normalized.runtimeRoot, normalized.indexDirectory, 'index'); outsideRuntime(normalized.runtimeRoot, scratchParent(normalized), 'scratch'); this.config = normalized; }
688
- /** Ordinary external settings remain caller-selected/outside-project. The
689
- * optional override is a current-process verified dependency, not Task data. */
690
- async configureExternal(project, selectedPath = runtimeConfigPath(defaultRoot()), runtime) {
691
- const path = resolve(selectedPath);
692
- outsideProject(project, path, 'configuration');
693
- if (runtime?.nativeOwnerHelperPath !== undefined)
694
- outsideProject(project, runtime.nativeOwnerHelperPath, 'runtime');
695
- const text = await readFile(path, 'utf8').catch((error) => { throw error.code === 'ENOENT' ? new Error('Semantic recall is not set up yet: pi-tuck sets it up when a session starts, unless pi-tuck.json turns it off') : error; });
696
- this.configure({ ...JSON.parse(text), ...(runtime?.nativeOwnerHelperPath === undefined ? {} : { nativeOwnerHelperPath: runtime.nativeOwnerHelperPath }) });
697
- }
698
- enable() {
699
- // Explicit opt-in can end off-user; project, platform and settings policy belongs to the host.
700
- if (['off-user', 'not-installed', 'failed'].includes(this.setup))
701
- this.setSetup('starting');
702
- if (!SEMANTIC_SETUP_TRANSITIONS[this.setup].includes('ready'))
703
- return;
704
- try {
705
- if (this.closing || this.joiningSearches || this.cleanupError)
706
- throw new Error('Semantic cleanup is unresolved; retry close before enable');
707
- if (!this.config)
708
- throw new Error('Optional local semantic runtime is not configured');
709
- this.setSetup('ready');
710
- this.enabled = true;
711
- this.error = null;
712
- this.healReason = null;
713
- this.healAttempts = 0;
714
- this.cancelHeal();
715
- if (this.provider && this.active)
716
- this.schedule(this.provider);
717
- }
718
- catch (error) {
719
- this.setSetup('failed', { stage: 'start', reason: error instanceof Error ? error.message : String(error) });
720
- throw error;
721
- }
722
- }
723
- status() { return { setup: this.setup, setupMessage: semanticSetupMessage(this.setup, this.setupDetail), enabled: this.enabled, configured: Boolean(this.config), cleanupError: this.cleanupError, state: (!this.enabled ? 'disabled' : this.healReason !== null || (this.error !== null && !CHURN.test(this.error)) ? 'unavailable' : this.task || this.timer ? 'preparing' : this.current?.complete ? 'ready' : 'waiting'), snapshotId: this.current?.id ?? null, throughEntryId: this.current?.throughEntryId ?? null, eligibleSources: this.current?.sources.length ?? 0, totalUnits: this.current?.units.length ?? 0, coveredUnits: this.current?.indexed.size ?? 0, indexingComplete: Boolean(this.current?.complete), lastError: this.error ?? this.healReason ?? semanticSetupMessage(this.setup, this.setupDetail), window: this.current ? windowCoverage(this.current) : null, recovery: this.healReason === null ? null : { attempts: this.healAttempts, integrity: this.healIntegrity, retryAt: this.healRetryAt === null ? null : new Date(this.healRetryAt).toISOString() }, operations: { ...this.operations }, limits: { keyword: 16000, broad: 20000 } }; }
724
- /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
725
- requestCoverage() { const { setup, setupMessage, ...coverage } = this.status(); return coverage; }
726
- schedule(provider) { this.provider = provider; if (!this.enabled || this.timer || !this.active || this.healTimer)
727
- return; this.timer = setTimeout(() => { this.timer = undefined; if (this.task) {
728
- this.dirty = true;
729
- return;
730
- } this.task = this.prepare(provider, this.fullIndexing).catch(async (error) => { if (this.quietStop || !this.enabled)
731
- return; this.error = error instanceof Error ? error.message : 'local failure'; if (error instanceof Error && error.name === 'SemanticAccessError') {
732
- this.enabled = false;
733
- this.generation++;
734
- this.dirty = false;
735
- try {
736
- await this.closeResources();
737
- }
738
- catch (cleanup) {
739
- this.cleanupError = cleanup instanceof Error ? cleanup.message : 'Semantic cleanup failed';
740
- this.error = this.cleanupError;
741
- }
742
- }
743
- else
744
- this.heal(error); }).finally(() => { this.task = undefined; if (this.enabled && this.dirty) {
745
- this.dirty = false;
746
- this.error = null;
747
- this.schedule(this.provider);
748
- } }); }, 5); }
749
- /** A saved cut has moved entries out of view: start indexing the whole window now, whether or not this session has searched. Awaits nothing; a failure goes to `heal` like any preparation.
750
- * Every session indexes at its cuts, but only one background indexer runs per machine (the lock in the index folder), so several sessions never run several encoders at once on a 16 GB machine;
751
- * its worker is given back once the window is indexed. A heal backoff in progress is not bypassed. Callers: Pi's own compactions (session_compact) and every cut pi-tuck saves at a boundary. */
752
- indexAtCut(provider) { if (this.enabled && !this.healTimer && !this.active) {
753
- this.active = true;
754
- this.fullIndexing = true;
755
- this.backgroundOnly = true;
756
- this.armIdle();
757
- } this.schedule(provider); }
758
- async runtime(project) {
759
- if (this.idling)
760
- await this.idling;
761
- if (!this.enabled)
762
- throw abort();
763
- outsideProject(project, this.config.runtimeRoot, 'runtime');
764
- outsideProject(project, scratchParent(this.config), 'scratch');
765
- outsideRuntime(this.config.runtimeRoot, scratchParent(this.config), 'scratch');
766
- if (this.worker && this.recycle) {
767
- const old = this.worker;
768
- await old.close();
769
- if (this.worker === old) {
770
- this.worker = undefined;
771
- this.identity = '';
772
- this.recycle = false;
773
- }
774
- if (!this.enabled)
775
- throw abort();
776
- }
777
- if (!this.worker) {
778
- const worker = new LocalWorker(this.config, project, error => { if (this.worker !== worker)
779
- return; this.cleanupError = error instanceof Error ? error.message : 'Semantic cleanup failed'; this.error = this.cleanupError; this.enabled = false; this.generation++; }, reason => { if (this.worker === worker)
780
- this.heal(new WorkerFailure(reason)); }, { startMs: this.timing.startDeadlineMs ?? START_DEADLINE_MS, callMs: this.timing.callDeadlineMs ?? CALL_DEADLINE_MS, embedTextMs: this.timing.embedTextMs ?? EMBED_TEXT_MS });
781
- this.worker = worker;
782
- }
783
- if (!this.identity) {
784
- const ready = await this.worker.call('ready');
785
- if (ready.dimensions !== 768 || ready.maxTokens !== 8192 || !ready.offline)
786
- throw new Error('Incompatible semantic model; EG2 768/8192 offline required');
787
- this.identity = hash({ worker: ready.identity, chunk: 'eg2-passage256-focused-disjoint-direct-v3' });
788
- }
789
- return this.worker;
790
- }
791
- path(snapshot) { const directory = this.config.indexDirectory; outsideProject(snapshot.project, directory, 'index'); return join(directory, hash({ owner: this.ownerId, session: snapshot.session, project: resolve(snapshot.project) }) + '.sqlite'); }
792
- async index(action, snapshot, extra = {}, boundId) { const path = this.path(snapshot), generation = this.generation, worker = await this.runtime(snapshot.project); if (!this.enabled || generation !== this.generation)
793
- throw abort(); if (this.provider) {
794
- if (boundId !== undefined)
795
- this.recheckGrown(this.provider, snapshot, boundId);
796
- else
797
- this.recheck(this.provider, snapshot);
798
- } /* a search's scoring may read a plan its snapshot grew from */ /* a search's scoring may read a plan its snapshot grew from */ this.indexFiles.add(path); const result = await worker.call('index', { path, identity: this.identity, action, projectDirectory: snapshot.project, ...extra }); if (!this.enabled || generation !== this.generation)
799
- throw abort(); if (this.provider) {
800
- if (boundId !== undefined)
801
- this.recheckGrown(this.provider, snapshot, boundId);
802
- else
803
- this.recheck(this.provider, snapshot);
804
- } return result; }
805
- async prepare(provider, full = true) {
806
- if (!this.enabled)
807
- return;
808
- const generation = this.generation, started = performance.now();
809
- let snapshot = provider();
810
- const prior = this.current;
811
- if (prior?.complete && prior.id === snapshot.id)
812
- return;
813
- let release = null;
814
- if (this.backgroundOnly) {
815
- await mkdir(this.config.indexDirectory, { recursive: true });
816
- release = await tryIndexerLock(this.config.indexDirectory);
817
- if (!release) {
818
- const retry = setTimeout(() => { if (this.enabled && generation === this.generation)
819
- this.schedule(provider); }, INDEXER_RETRY_MS);
820
- retry.unref();
821
- return;
822
- }
823
- }
824
- try {
825
- await this.prepareLocked(provider, full, generation, started, snapshot, prior);
826
- }
827
- finally {
828
- if (release) {
829
- if (this.backgroundOnly && this.current?.complete)
830
- this.releaseLock = release;
831
- else
832
- await release();
833
- }
834
- }
835
- }
836
- async prepareLocked(provider, full, generation, started, snapshot, prior) {
837
- // Both caps bound the window instead of failing above them. The unit cap (MAX_INDEX_UNITS) stays below the worker's 8,008-row store; the character cap, 2,000,000, usually binds first, at about 2.2 thousand units.
838
- const maxChars = this.config.maxSourceCharacters ?? 2000000, maxUnits = this.config.maxUnits ?? MAX_INDEX_UNITS;
839
- const check = () => { if (generation !== this.generation || !this.enabled)
840
- throw abort(); this.recheck(provider, snapshot); };
841
- this.path(snapshot); // Reject project-local/aliased index storage before starting inference.
842
- const worker = await this.runtime(snapshot.project);
843
- check();
844
- // A retry after a failure proves the native encoder too, not only the worker: nothing may need embedding, and recovery must not be declared on a worker that cannot embed.
845
- if (this.healReason !== null) {
846
- await worker.call('embed', { texts: [PROBE_TEXT], kind: 'query' });
847
- check();
848
- this.recovered();
849
- }
850
- const stillEligible = new Map(snapshot.sources.map(source => [source.entry.id, source.sha]));
851
- await this.index('reconcile', snapshot, { keys: (prior?.units ?? []).filter(unit => stillEligible.get(unit.source.entry.id) === unit.source.sha).map(unit => unit.key) });
852
- check();
853
- if (prior?.id === snapshot.id)
854
- snapshot = prior;
855
- else {
856
- // The window covers what the agent can no longer see, kind first and then recency (see windowOrder), within both caps, newest first. A source too large to fit even alone is skipped;
857
- // the first source that does not fit the rest of the budget ends the window. What the window drops is not ranked (tuck_recall still reads it) and loses its stored vectors.
858
- const built = new Map(), order = [];
859
- let chars = 0, units = 0;
860
- const eligibleShas = new Set(stillEligible.values());
861
- for (const sha of [...this.tokenized.keys()])
862
- if (!eligibleShas.has(sha))
863
- this.tokenized.delete(sha);
864
- for (const source of windowOrder(snapshot)) {
865
- const size = sourceCharacters(source);
866
- if (size > maxChars)
867
- continue;
868
- if (chars + size > maxChars)
869
- break;
870
- let list;
871
- const reused = this.tokenized.get(source.sha);
872
- if (reused)
873
- list = reused.map(unit => ({ ...unit, source }));
874
- else {
875
- list = [];
876
- for (const range of source.ranges) {
877
- if (generation !== this.generation || !this.enabled)
878
- throw abort();
879
- if (provider().id !== snapshot.id)
880
- throw new Error('Eligible history changed before tokenization');
881
- const text = source.sourceText.slice(range.start, range.end);
882
- const pieces = (await worker.call('tokenize', { texts: [text], kind: 'passage', split: true, maxTokens: 256 })).ranges[0];
883
- check();
884
- for (const part of pieces) {
885
- const start = range.start + part.start, end = range.start + part.end, encoded = `Source role: ${source.row.role}\nOriginal passage: ${source.sourceText.slice(start, end)}`, inputSha = hash(encoded), key = hash({ identity: this.identity, source: source.sha, start, end, inputSha });
886
- list.push({ key, entryId: source.entry.id, start, end, inputSha, encoded, source });
887
- }
888
- if (units + list.length > maxUnits)
889
- break;
890
- if (generation !== this.generation || !this.enabled)
891
- throw abort();
892
- await yieldWork();
893
- }
894
- }
895
- if (units + list.length > maxUnits)
896
- break;
897
- this.tokenized.set(source.sha, list);
898
- built.set(source.sha, list);
899
- order.push(source);
900
- chars += size;
901
- units += list.length;
902
- }
903
- for (const sha of [...this.tokenized.keys()])
904
- if (!built.has(sha))
905
- this.tokenized.delete(sha);
906
- snapshot.units = order.flatMap(source => built.get(source.sha));
907
- const outside = snapshot.sources.filter(source => source.order < snapshot.viewStart), total = (sources) => sources.reduce((n, source) => n + sourceCharacters(source), 0);
908
- snapshot.window = { order, counts: order.map(source => built.get(source.sha).length), searchUnits: order.filter(source => source.order < snapshot.viewStart && !isToolOutput(source)).reduce((n, source) => n + built.get(source.sha).length, 0),
909
- windowCharacters: chars, eligibleCharacters: total(snapshot.sources), conversationOutOfView: total(outside.filter(source => !isToolOutput(source))), toolOutOfView: total(outside.filter(isToolOutput)) };
910
- }
911
- check();
912
- this.current = snapshot;
913
- const keys = snapshot.units.map(u => u.key);
914
- await this.index('reconcile', snapshot, { keys });
915
- check();
916
- const present = await this.index('status', snapshot, { keys });
917
- check();
918
- snapshot.indexed = new Set(present.coveredKeys);
919
- let progressed = false;
920
- // Embedding runs in window order, so what is indexed is a growing prefix. Out-of-view conversation is small and never evicted: it is indexed whenever the worker is alive, right after a cut.
921
- // Tool output and the in-view tail wait for a search (`full`), newest first: embedding tool output the window drops a few cuts later would waste hours of work.
922
- const wanted = snapshot.units.filter(unit => full || (unit.source.order < snapshot.viewStart && !isToolOutput(unit.source)));
923
- for (let offset = 0; offset < wanted.length; offset += 8) {
924
- if (generation !== this.generation || !this.enabled)
925
- throw abort();
926
- const now = provider();
927
- if (now.id !== snapshot.id)
928
- throw new Error('Eligible history changed; indexing incomplete');
929
- const units = wanted.slice(offset, offset + 8).filter(u => !snapshot.indexed.has(u.key));
930
- if (units.length) {
931
- const result = await worker.call('embed', { texts: units.map(u => u.encoded), kind: 'passage' });
932
- this.operations.preparationEmbeddings += units.length;
933
- check();
934
- await this.index('upsert', snapshot, { rows: units.map((u, i) => ({ key: u.key, entryId: u.entryId, start: u.start, end: u.end, inputSha: u.inputSha, vector: result.vectors[i] })) });
935
- check();
936
- for (const unit of units)
937
- snapshot.indexed.add(unit.key);
938
- progressed = true;
939
- }
940
- await yieldWork();
941
- if (progressed && performance.now() - started > (this.config.prepareWorkMs ?? 30000)) {
942
- this.error = 'Preparation work slice exhausted; indexing incomplete';
943
- this.dirty = true;
944
- return;
945
- }
946
- }
947
- check();
948
- if (snapshot.units.every(unit => snapshot.indexed.has(unit.key))) {
949
- snapshot.complete = true;
950
- if (full)
951
- this.fullIndexing = false;
952
- if (this.backgroundOnly)
953
- setTimeout(() => { void (this.backgroundOnly ? this.idleStop() : Promise.resolve()).finally(() => this.freeLock()); }, 0).unref();
954
- }
955
- this.error = null;
956
- this.recovered();
957
- }
958
- async waitForReady(timeoutMs = this.config?.queryWaitMs ?? 30000, signal, expectedSnapshotId, forSearch = false) { if (this.enabled)
959
- this.demand(); let targetId = expectedSnapshotId; try {
960
- targetId ??= this.provider?.().id;
961
- }
962
- catch (error) {
963
- await this.revoked(error);
964
- throw error;
965
- } if (this.enabled && this.provider && this.current?.id !== targetId) {
966
- this.error = null;
967
- this.schedule(this.provider);
968
- } const started = performance.now(); while (this.enabled && !this.readyFor(targetId, forSearch) && !this.error && !this.healTimer && performance.now() - started < timeoutMs) {
969
- if (signal?.aborted) {
970
- await this.cancelled();
971
- throw abort();
972
- }
973
- if (this.provider && !this.timer && !this.task)
974
- this.schedule(this.provider);
975
- await new Promise(done => setTimeout(done, 10));
976
- } this.armIdle(); return this.status(); }
977
- /** A plan for this snapshot that is fully indexed or, for a search, has all its out-of-view conversation indexed. The tool output behind it and the in-view tail are not worth waiting for: they keep indexing in the background and the coverage statement says how far they got.
978
- * With no out-of-view conversation (no cut) nothing waits: the search returns at once. Only a window whose out-of-view part is tool output alone still waits for the whole window. */
979
- readyFor(id, forSearch) { const plan = this.current; return Boolean(plan && plan.id === id && (plan.complete || (forSearch && plan.window !== undefined && plan.window.searchUnits > 0 && plan.units.slice(0, plan.window.searchUnits).every(unit => plan.indexed.has(unit.key))))); }
980
- /** A search may rank a plan its own snapshot has grown from (every source in the plan still eligible, unchanged), as long as the session has not
981
- * moved since the search took that snapshot; a move during the search still fails it. Indexing keeps the exact `recheck`. */
982
- recheckGrown(provider, snapshot, boundId) { const now = provider(); if (now.id !== boundId || !grownFrom(now, snapshot))
983
- throw new Error('Eligible branch or source changed before semantic admission'); }
984
- recheck(provider, snapshot) { const now = provider(); if (now.id !== snapshot.id || now.session !== snapshot.session || now.project !== snapshot.project)
985
- throw new Error('Eligible branch or source changed before semantic admission'); }
986
- async joinPreparation(deadline, signal) {
987
- const task = this.task;
988
- if (!task)
989
- return true;
990
- let timer, onAbort;
991
- try {
992
- const waiting = [task.then(() => true), new Promise(done => { timer = setTimeout(() => done(false), Math.max(0, deadline - performance.now())); })];
993
- if (signal)
994
- waiting.push(new Promise((_resolve, reject) => { onAbort = () => reject(abort()); signal.addEventListener('abort', onAbort, { once: true }); if (signal.aborted)
995
- onAbort(); }));
996
- return await Promise.race(waiting);
997
- }
998
- catch (error) {
999
- if (signal?.aborted) {
1000
- await this.cancelled();
1001
- throw abort();
1002
- }
1003
- throw error;
1004
- }
1005
- finally {
1006
- if (timer)
1007
- clearTimeout(timer);
1008
- if (onAbort)
1009
- signal?.removeEventListener('abort', onAbort);
1010
- }
1011
- }
1012
- search(query, provider, signal, prior = [], words) { const task = this.searchOwned(query, provider, signal, prior, words); this.activeSearches.add(task); const settled = () => { this.activeSearches.delete(task); this.armIdle(); }; void task.then(settled, settled); return task; }
1013
- async searchOwned(query, provider, signal, prior = [], words) {
1014
- if (signal?.aborted)
1015
- throw abort();
1016
- if (!this.enabled)
1017
- return { status: 'disabled', notice: 'Optional semantic recall is disabled; ordinary word recall remains available.', coverage: this.requestCoverage(), groups: [] };
1018
- this.demand();
1019
- this.searched = true;
1020
- const deadline = performance.now() + (this.config.queryWaitMs ?? 30000), incomplete = () => ({ status: 'indexing_incomplete', notice: 'No semantic ranking performed: nothing of the requested eligible snapshot is indexed yet.', coverage: this.requestCoverage(), groups: [] }), unavailable = () => ({ status: 'unavailable', notice: 'Local semantic preparation unavailable; permitted ordinary recall remains available.', coverage: this.requestCoverage(), groups: [] });
1021
- const queryGeneration = this.generation;
1022
- let bound;
1023
- try {
1024
- bound = provider();
1025
- }
1026
- catch (error) {
1027
- await this.revoked(error);
1028
- throw error;
1029
- }
1030
- this.provider = provider;
1031
- if (this.healTimer)
1032
- return unavailable(); // a retry is waiting: it owns the next attempt, a search does not bypass the backoff
1033
- // Nothing out of view (no cut yet, or the cut kept everything): the whole history is in the agent's context, so a search never waits for indexing, and the query never starts a worker itself (background preparation may). It ranks what an already running worker has indexed, else it says so at once; a recorded failure is still reported as unavailable, as on the waiting path.
1034
- if (bound.sources.every(source => source.order >= bound.viewStart)) {
1035
- const failure = this.error ?? this.healReason, failed = failure !== null && !CHURN.test(failure), planned = this.current?.id === bound.id && this.current.complete, page = failed ? unavailable() : null; // built before the retry clears the error, so the page's coverage reports it
1036
- if (!planned) {
1037
- this.error = null;
1038
- this.schedule(provider);
1039
- }
1040
- if (!(this.current?.id === bound.id && ((this.current.complete && !this.current.units.length) || (indexedPrefix(this.current) > 0 && this.worker !== undefined && !this.recycle && !this.idling)))) {
1041
- if (page)
1042
- return page;
1043
- return { status: 'indexing_incomplete', notice: 'No semantic ranking performed: nothing is out of view, so the whole history is in your context.', coverage: this.requestCoverage(), groups: [] };
1044
- }
1045
- }
1046
- else {
1047
- if (this.current?.id !== bound.id) {
1048
- const prepared = !this.task || await this.joinPreparation(deadline, signal);
1049
- if (signal?.aborted || queryGeneration !== this.generation)
1050
- throw abort();
1051
- if (prepared && performance.now() < deadline) {
1052
- this.error = null;
1053
- this.schedule(provider);
1054
- await this.waitForReady(Math.max(0, deadline - performance.now()), signal, bound.id, true);
1055
- }
1056
- }
1057
- else {
1058
- if (!this.current.complete) {
1059
- this.error = null;
1060
- this.schedule(provider);
1061
- }
1062
- await this.waitForReady(Math.max(0, deadline - performance.now()), signal, bound.id, true);
1063
- }
1064
- if (signal?.aborted || queryGeneration !== this.generation)
1065
- throw abort();
1066
- }
1067
- // Ranking needs a plan for the bound snapshot and an indexed prefix; the coverage statement describes exactly that prefix and nothing else is ranked, so a search that reaches its wait limit with part of the window indexed ranks that part. Only an empty prefix is `indexing_incomplete`.
1068
- const snapshot = this.current, older = snapshot !== undefined && snapshot.id !== bound.id && grownFrom(bound, snapshot);
1069
- if (!snapshot || (snapshot.id !== bound.id && !older) || (snapshot.units.length ? indexedPrefix(snapshot) === 0 : !snapshot.complete)) {
1070
- const failure = this.error ?? this.healReason;
1071
- return failure && !CHURN.test(failure) ? unavailable() : incomplete();
1072
- }
1073
- if (!snapshot.units.length)
1074
- return { status: 'no_matches', notice: 'No eligible original source units in this snapshot.', coverage: this.requestCoverage(), method: 'embedding', groups: [] };
1075
- try {
1076
- const worker = await this.runtime(snapshot.project);
1077
- this.recheckGrown(provider, snapshot, bound.id);
1078
- const encoded = await worker.call('embed', { texts: [query], kind: 'query' }, signal);
1079
- this.operations.queryEmbeddings++;
1080
- this.recheckGrown(provider, snapshot, bound.id);
1081
- const prefix = indexedPrefix(snapshot), stored = snapshot.units.slice(0, prefix), byKey = new Map(stored.map(u => [u.key, u])), covered = windowCoverage(snapshot, prefix);
1082
- let ranked = [], observed = 0;
1083
- for (let offset = 0; offset < stored.length; offset += SCORE_CHUNK) {
1084
- this.recheckGrown(provider, snapshot, bound.id);
1085
- const scored = await this.index('score', snapshot, { keys: stored.slice(offset, offset + SCORE_CHUNK).map(u => u.key), query: encoded.vectors[0] }, bound.id);
1086
- observed += scored.observed;
1087
- ranked.push(...scored.ranked.map(row => ({ unit: byKey.get(row.key), score: row.score })));
1088
- ranked.sort((a, b) => b.score - a.score);
1089
- ranked = ranked.slice(0, 24);
1090
- if (signal?.aborted)
1091
- throw abort();
1092
- await yieldWork();
1093
- }
1094
- if (observed !== stored.length)
1095
- throw new Error('Snapshot index coverage changed');
1096
- if (signal?.aborted || queryGeneration !== this.generation || !this.enabled)
1097
- throw abort();
1098
- this.recheckGrown(provider, snapshot, bound.id);
1099
- const final = provider();
1100
- const finalSources = new Map(final.sources.map(source => [source.entry.id, source.sha]));
1101
- if (snapshot.sources.some(source => finalSources.get(source.entry.id) !== source.sha))
1102
- throw new Error('Eligible source changed or access revoked before return');
1103
- // What the caller already read only spares it a repeat. A reference that does not match this history spares nothing, and it must not fail the search.
1104
- const usable = prior.filter(reference => { const source = snapshot.sources.find(s => s.entry.id === reference.entryId); return Number.isSafeInteger(reference.start) && Number.isSafeInteger(reference.end) && reference.start <= reference.end && source !== undefined && reference.sourceSha === source.sha && reference.end <= source.sourceText.length; }), ignored = prior.length - usable.length;
1105
- const previous = [...usable, ...(words?.hits ?? []).map((hit) => ({ entryId: hit.entryId, start: hit.read.offset, end: hit.read.offset + hit.read.limit, sourceSha: snapshot.sources.find(s => s.entry.id === hit.entryId)?.sha }))];
1106
- return { status: 'ok', notice: 'Related original evidence, not current truth or proof that every qualification was found. Scores do not establish authority, event time or supersession. Sources preserve recorded time and original order.' + (ignored ? ` ${ignored} of the priorResults did not match this history and were ignored, so their text may appear again.` : '') + ` Semantic ranking covers ${covered.conversation.indexedCharacters} of ${covered.conversation.outOfViewCharacters} characters of earlier conversation and ${covered.toolResults.indexedCharacters} of ${covered.toolResults.outOfViewCharacters} characters of earlier tool output (newest first, back to ${covered.toolResults.oldestCoveredTime ?? covered.oldestCoveredTime ?? 'an unknown time'}); use tuck_recall for the rest.` + (older ? ` This ranking covers the history through entry ${snapshot.throughEntryId}: later entries are still being indexed, so search them by keyword.` : ''), coverage: { ...this.requestCoverage(), window: covered }, method: 'embedding', groups: this.assemble(ranked.map(hit => hit.unit), snapshot, previous) };
1107
- }
1108
- catch (error) {
1109
- if (error instanceof Error && error.name === 'SemanticAccessError') {
1110
- await this.revoked(error);
1111
- throw error;
1112
- }
1113
- if (signal?.aborted || queryGeneration !== this.generation || error instanceof Error && error.name === 'AbortError') {
1114
- await this.cancelled();
1115
- throw abort();
1116
- }
1117
- this.heal(error);
1118
- return { status: 'unavailable', notice: 'Local semantic search failed; ordinary recall remains available. ' + (error instanceof Error ? error.message : 'failure'), coverage: this.requestCoverage(), groups: [] };
1119
- }
1120
- }
1121
- assemble(units, snapshot, previous) {
1122
- // Collapse coordinate overlap only; disjoint evidence in one entry remains independent.
1123
- const groups = [], selected = [];
1124
- for (const unit of units) {
1125
- if (groups.length >= 8)
1126
- break;
1127
- const inputs = [{ source: unit.source, start: unit.start, end: unit.end }];
1128
- const producer = unit.source.row.producerRead;
1129
- for (const source of snapshot.sources) {
1130
- if (source === unit.source)
1131
- continue;
1132
- if (producer && source.entry.id === producer.entryId) {
1133
- for (const r of source.ranges) {
1134
- const start = Math.max(r.start, producer.offset), end = Math.min(r.end, producer.offset + producer.limit);
1135
- if (start < end)
1136
- inputs.push({ source, start, end });
1137
- }
1138
- }
1139
- else if (!producer && Math.abs(source.order - unit.source.order) === 1 && ['user', 'assistant'].includes(source.row.role) && source.ranges[0]) {
1140
- const r = source.ranges[0];
1141
- let end = Math.min(r.end, r.start + 1000);
1142
- if (/[\uD800-\uDBFF]/u.test(source.sourceText[end - 1] ?? ''))
1143
- end--;
1144
- inputs.push({ source, start: r.start, end });
1145
- }
1146
- }
1147
- const spans = inputs.map(input => this.focus(input)).sort((a, b) => a.source.order - b.source.order || a.start - b.start);
1148
- if (spans.every(p => [...selected, ...previous.filter(r => r.entryId === p.source.entry.id && r.sourceSha === p.source.sha).map(r => ({ source: p.source, start: r.start, end: r.end }))].some(old => old.source.sha === p.source.sha && old.start <= p.start && old.end >= p.end)))
1149
- continue;
1150
- const sources = spans.map(p => this.evidence(p.source, p.start, p.end));
1151
- groups.push({ sources, notice: 'Bounded original passage; omitted text may qualify it. Not current authority or exhaustive qualifications.' });
1152
- selected.push(...spans);
1153
- }
1154
- const consolidated = consolidateEvidence(groups, previous);
1155
- Object.defineProperty(consolidated, expandedGroups, { value: { groups, previous } });
1156
- return consolidated;
1157
- }
1158
- focus(input) {
1159
- const { source } = input, range = source.ranges.find(r => r.start <= input.start && r.end >= input.end);
1160
- if (!range)
1161
- throw new Error('Evidence outside eligible original range');
1162
- if (range.end - range.start <= 1600)
1163
- return { source, ...range };
1164
- let start = source.sourceText.lastIndexOf('\n\n', input.start);
1165
- start = start < range.start ? range.start : start + 2;
1166
- let end = source.sourceText.indexOf('\n\n', input.end);
1167
- end = end < 0 || end > range.end ? range.end : end;
1168
- if (end - start > 2000) {
1169
- start = input.start;
1170
- end = input.end;
1171
- }
1172
- return { source, start, end };
1173
- }
1174
- evidence(source, start, end) { return { ...source.row, sourceOrder: source.order, sourceSha: source.sha, text: source.sourceText.slice(start, end), textOffset: start, totalCharacters: source.sourceText.length, read: { entryId: source.entry.id, offset: start, limit: end - start }, complete: start === 0 && end === source.sourceText.length }; }
1175
- async disable(joinSearches = true, userOff = true) { if (userOff)
1176
- this.setSetup('off-user'); if (joinSearches)
1177
- this.joiningSearches++; try {
1178
- if (!this.closing) {
1179
- const stop = this.stopOwner();
1180
- this.closing = stop;
1181
- void stop.finally(() => { if (this.closing === stop)
1182
- this.closing = undefined; }).catch(() => { });
1183
- }
1184
- await this.closing;
1185
- if (joinSearches)
1186
- await Promise.allSettled([...this.activeSearches]);
1187
- }
1188
- finally {
1189
- if (joinSearches)
1190
- this.joiningSearches--;
1191
- } }
1192
- async closeResources() { this.fullIndexing = false; this.cancelHeal(); this.cancelIdle(); this.active = false; this.healReason = null; this.healAttempts = 0; this.recycle = false; const worker = this.worker; await worker?.close(); await Promise.all([...this.indexFiles].flatMap(path => [path, path + '-wal', path + '-shm']).map(path => rm(path, { force: true }))); this.indexFiles.clear(); if (this.worker === worker)
1193
- this.worker = undefined; this.identity = ''; this.current = undefined; this.tokenized.clear(); this.cleanupError = null; }
1194
- async stopOwner() { this.dirty = false; this.enabled = false; this.generation++; if (this.timer) {
1195
- clearTimeout(this.timer);
1196
- this.timer = undefined;
1197
- } try {
1198
- await this.closeResources();
1199
- await this.task;
1200
- this.task = undefined;
1201
- }
1202
- catch (error) {
1203
- this.cleanupError = error instanceof Error ? error.message : 'Semantic cleanup failed';
1204
- throw error;
1205
- } }
1206
- /** A search, or a wait for readiness, is demand: it lets background work start and keeps it alive for IDLE_STOP_MS after the last one. */
1207
- demand() { this.active = true; this.fullIndexing = true; this.backgroundOnly = false; this.cancelIdle(); }
1208
- cancelIdle() { if (this.idleTimer)
1209
- clearTimeout(this.idleTimer); this.idleTimer = undefined; }
1210
- armIdle() { this.cancelIdle(); if (!this.enabled || !this.active)
1211
- return; this.idleTimer = setTimeout(() => { this.idleTimer = undefined; void this.idleStop(); }, this.timing.idleStopMs ?? IDLE_STOP_MS); this.idleTimer.unref(); }
1212
- async freeLock() { const release = this.releaseLock; this.releaseLock = undefined; await release?.().catch(() => { }); }
1213
- idleStop() {
1214
- if (this.idling || !this.enabled || !this.active || this.joiningSearches || this.activeSearches.size)
1215
- return Promise.resolve();
1216
- return this.stopWorker();
1217
- }
1218
- /** A search or wait the caller cancelled (Esc) or that a stop overtook ends, and the worker with it, but recall stays enabled: the next search starts a worker again. Only access loss disables (see `searchOwned`). */
1219
- async cancelled() { if (this.enabled)
1220
- await this.stopWorker();
1221
- else
1222
- await this.disable(false); }
1223
- /** Stop the worker and any preparation under way, quietly (no error, no recovery). The vectors stay in the on-disk index and the in-memory plan,
1224
- * so the next search starts a worker and finds them. Enabled stays enabled; a recorded start failure stays recorded, but its retry timer ends. Used after the idle limit and after a cancelled search. */
1225
- stopWorker() {
1226
- if (this.idling)
1227
- return this.idling;
1228
- const running = this.task; // a preparation a search starts during the stop waits for it in runtime(), so the stop must not wait for that one
1229
- const stop = (async () => {
1230
- this.active = false;
1231
- this.fullIndexing = false;
1232
- this.backgroundOnly = false;
1233
- this.quietStop = true;
1234
- this.generation++;
1235
- this.dirty = false;
1236
- if (this._timer) {
1237
- clearTimeout(this._timer);
1238
- this.timer = undefined;
1239
- }
1240
- this.cancelHeal();
1241
- const worker = this.worker;
1242
- try {
1243
- await worker?.close();
1244
- await running;
1245
- if (this.worker === worker) {
1246
- this.worker = undefined;
1247
- this.identity = '';
1248
- this.recycle = false;
1249
- }
1250
- }
1251
- catch (error) {
1252
- this.cleanupError = error instanceof Error ? error.message : 'Semantic cleanup failed';
1253
- this.error = this.cleanupError;
1254
- this.enabled = false;
1255
- this.generation++;
1256
- }
1257
- finally {
1258
- this.quietStop = false;
1259
- }
1260
- })();
1261
- this.idling = stop;
1262
- void stop.finally(() => { if (this.idling === stop)
1263
- this.idling = undefined; });
1264
- return stop;
1265
- }
1266
- cancelHeal() { if (this.healTimer)
1267
- clearTimeout(this.healTimer); this.healTimer = undefined; this.healRetryAt = null; }
1268
- /** A worker failure puts the controller into recovery: `unavailable` with the reason, the worker replaced at the next attempt, a retry armed. Other failures only re-arm a retry already under way. */
1269
- heal(error) {
1270
- if (!this.enabled)
1271
- return;
1272
- if (error instanceof WorkerFailure) {
1273
- this.healReason = error.message;
1274
- this.healIntegrity = integrityRefusal(error);
1275
- this.recycle = true;
1276
- if (this.current)
1277
- this.current.complete = false;
1278
- }
1279
- this.touch();
1280
- if (this.healReason === null || this.healTimer || !this.provider)
1281
- return;
1282
- if (!(error instanceof WorkerFailure) && error instanceof Error && CHURN.test(error.message))
1283
- return; // the history moved: not a failed attempt; the next turn end or search retries
1284
- const delay = healDelayMs(this.healAttempts++, this.healIntegrity, this.timing.healDelaysMs, this.timing.healSteadyMs);
1285
- this.healRetryAt = Date.now() + delay;
1286
- this.healTimer = setTimeout(() => { this.healTimer = undefined; this.healRetryAt = null; if (this.enabled && this.provider && this.healReason !== null)
1287
- this.schedule(this.provider); }, delay);
1288
- this.healTimer.unref();
1289
- }
1290
- recovered() { this.cancelHeal(); this.healReason = null; this.healAttempts = 0; this.touch(); }
1291
- /** One-shot health check for a status tool: start the worker (it verifies every file), embed a fixed string, and report. Enable first; close afterwards. */
1292
- async probe(project) {
1293
- const started = performance.now();
1294
- await this.runtime(project);
1295
- const ready = performance.now();
1296
- const vector = (await this.worker.call('embed', { texts: [PROBE_TEXT], kind: 'query' })).vectors?.[0];
1297
- if (!Array.isArray(vector))
1298
- throw new WorkerFailure('Local semantic runtime: invalid_vector', 'invalid_vector');
1299
- return { dimension: vector.length, startMs: Math.round(ready - started), embedMs: Math.round(performance.now() - ready) };
1300
- }
1301
- // A source that can no longer be read stops recall; the reason stays readable until the next enable, so this never looks like recall that was never on.
1302
- async revoked(error) { await this.disable(false); this.error = error instanceof Error ? error.message : 'Source access denied'; }
1303
- async invalidate() { await this.disable(); this.error = 'Caller invalidated semantic source access; explicit enable required'; }
1304
- async close() { await this.disable(true, false); await this.freeLock(); this.provider = undefined; this.searched = false; } // a closed controller serves a new session, which has not searched; a disable and enable keeps it
1305
- }
1306
- export const createSemanticRecall = (config) => new SemanticRecallController(config);
1307
- /** Consolidate only source-bound coordinate overlap; equal text in distinct events is retained.
1308
- * Reference rows preserve each original association without repeating its evidence text.
1309
- */
1310
- function consolidateEvidence(groups, previous = []) {
1311
- const delivered = [];
1312
- return groups.map(group => {
1313
- const consolidated = { ...group, sources: group.sources.flatMap(source => {
1314
- const start = source.textOffset, end = start + source.text.length;
1315
- const prior = previous.find(p => p.entryId === source.entryId && p.sourceSha === source.sourceSha && p.start <= start && p.end >= end);
1316
- const covered = prior ? [{ start, end, prior: true }] : delivered.filter(p => p.entryId === source.entryId && p.sourceSha === source.sourceSha && p.start < end && p.end > start).map(p => ({ start: Math.max(start, p.start), end: Math.min(end, p.end), prior: false })).sort((a, b) => a.start - b.start);
1317
- const merged = [];
1318
- for (const range of covered) {
1319
- const last = merged.at(-1);
1320
- if (last && range.start <= last.end)
1321
- last.end = Math.max(last.end, range.end);
1322
- else
1323
- merged.push({ ...range });
1324
- }
1325
- const parts = [];
1326
- let cursor = start;
1327
- const piece = (left, right, reference, prior) => { if (left >= right)
1328
- return; parts.push({ ...source, text: reference ? '' : source.text.slice(left - start, right - start), textOffset: left, read: { entryId: source.entryId, offset: left, limit: right - left }, complete: !reference && left === 0 && right === source.totalCharacters, ...(reference ? { evidenceReference: { entryId: source.entryId, sourceSha: source.sourceSha, start: left, end: right, basis: prior ? 'explicit prior or word result' : 'earlier source text in this response' }, notice: 'Original association retained; evidence text is referenced, not repeated.' } : {}) }); };
1329
- for (const range of merged) {
1330
- piece(cursor, range.start);
1331
- piece(range.start, range.end, true, range.prior);
1332
- cursor = range.end;
1333
- }
1334
- piece(cursor, end);
1335
- if (!source.text.length)
1336
- return [source];
1337
- if (!prior)
1338
- delivered.push({ entryId: source.entryId, sourceSha: source.sourceSha, start, end });
1339
- return parts;
1340
- }) };
1341
- // References must not displace evidence merely because their metadata is larger.
1342
- return JSON.stringify(consolidated).length <= JSON.stringify(group).length ? consolidated : group;
1343
- });
1344
- }
1345
- /** Price complete evidence groups before delivery; ordinary section is never changed.
1346
- * Consolidate each admitted prefix, so capacity omissions never back references.
1347
- */
1348
- export function budgetSemantic(value, allowance) {
1349
- const plan = value.groups?.[expandedGroups], groups = plan?.groups ?? value.groups ?? [], previous = plan?.previous ?? [];
1350
- const page = { ...value, groups: [], omittedGroups: groups.length };
1351
- if (JSON.stringify(page).length > allowance)
1352
- throw new Error('Semantic status cannot fit declared complete allowance');
1353
- const accepted = [], omitted = [];
1354
- for (const group of groups) {
1355
- const candidate = consolidateEvidence([...accepted, group], previous);
1356
- page.groups = candidate;
1357
- page.omittedGroups--;
1358
- if (JSON.stringify(page).length <= allowance) {
1359
- accepted.push(group);
1360
- continue;
1361
- }
1362
- page.groups = consolidateEvidence(accepted, previous);
1363
- page.omittedGroups++;
1364
- omitted.push(group);
1365
- }
1366
- // Coherent bodies have first use of capacity. One locator group cannot block a later body,
1367
- // enter the evidence-reference ledger, or point back to text from an omitted group.
1368
- const firstOmitted = omitted[0];
1369
- if (firstOmitted) {
1370
- const partial = { ...firstOmitted, sources: firstOmitted.sources.map((source) => {
1371
- const { evidenceReference: _reference, ...original } = source;
1372
- return { ...original, text: '', complete: false, notice: 'Original evidence omitted for response capacity; use exact expansion locator.', read: { entryId: source.entryId, offset: source.textOffset, limit: Math.min(8000, source.totalCharacters - source.textOffset) } };
1373
- }) };
1374
- page.groups.push(partial);
1375
- page.omittedGroups--;
1376
- if (JSON.stringify(page).length > allowance) {
1377
- page.groups.pop();
1378
- page.omittedGroups++;
1379
- }
1380
- }
1381
- if (groups.length && !page.groups.length)
1382
- page.status = 'no_room';
1383
- if (JSON.stringify(page).length > allowance)
1384
- throw new Error('Semantic status cannot fit declared complete allowance');
1385
- return page;
1386
- }