pi-tuck 1.0.31 → 1.0.32

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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,28 @@
3
3
  All notable changes to pi-tuck. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [1.0.32] - 2026-11-13
7
+
8
+ ### Changed
9
+
10
+ - **Search by meaning is ready sooner in sessions that have not searched yet.** At every cut, pi-tuck now indexes in the background what the
11
+ cut moved out of view, so a first tuck_search finds it without embedding it then. One background indexer runs per machine at a time,
12
+ holding a lock in the index folder, so several Pi sessions do not each load the encoder; a search never waits for that lock. The worker
13
+ is given back once the window is indexed, and the cut itself never waits for indexing.
14
+
15
+ ### Fixed
16
+
17
+ - **Background indexing never started at the cuts pi-tuck makes itself.** Pi announces only its own compactions, so cuts pi-tuck saved
18
+ after a tool round, at the end of a run, or before retrying a reply that hit the output limit started no indexing. Each of these cuts now
19
+ starts it.
20
+
21
+ ### Release gates
22
+
23
+ - **Replay matches 1.0.31:** 13,946 requests, 0 different, 0 lost or dead tasks, clips 17 → 17. Indexing changes nothing the model sees.
24
+ - **Live check, 5 tasks:** no breakage; the indexer ran at all 13 cuts, using 1-2 seconds of worker CPU per cut.
25
+ - **Strict stress, 313 cells:** 0 findings on Pi 1.2.0 and the newest Pi, including the 85 MB large-session test. Tests and CI. The
26
+ packed tarball loaded in the real installed Pi 1.5.2.
27
+
6
28
  ## [1.0.31] - 2026-11-12
7
29
 
8
30
  ### Fixed
@@ -1 +1 @@
1
- export declare const BUILD_ID = "5bf3e8c3b38641652836a07684de20f6e5b17aec8e3ad4051e4fd85a250b9a2d";
1
+ export declare const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
@@ -1 +1 @@
1
- export const BUILD_ID = "5bf3e8c3b38641652836a07684de20f6e5b17aec8e3ad4051e4fd85a250b9a2d";
1
+ export const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
@@ -1029,8 +1029,13 @@ export async function installCompaction(pi, options = {}) {
1029
1029
  };
1030
1030
  const atBoundary = (event, ctx, reason, decide) => {
1031
1031
  const current = view(ctx);
1032
- if (!current.pending)
1033
- return decide ? boundaryCut(event, ctx, reason) : undefined;
1032
+ if (!current.pending) {
1033
+ const result = decide ? boundaryCut(event, ctx, reason) : undefined;
1034
+ // Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
1035
+ if (result?.entries.some(entry => entry.type === "compaction"))
1036
+ setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
1037
+ return result;
1038
+ }
1034
1039
  const entry = run.cut.take();
1035
1040
  const preview = current.session, context = Object.create(ctx, { sessionManager: { value: preview } });
1036
1041
  const more = decide && !event.entries.length
@@ -1088,6 +1093,8 @@ export async function installCompaction(pi, options = {}) {
1088
1093
  stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
1089
1094
  estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
1090
1095
  markBoundary(drafts);
1096
+ // As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
1097
+ setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
1091
1098
  return { entries: drafts, continue: true };
1092
1099
  };
1093
1100
  pi.on("turn_end", (event, ctx) => {
@@ -1,6 +1,6 @@
1
1
  import { type RecallPolicy } from './recall.js';
2
2
  import type { SessionEntry } from '@earendil-works/pi-coding-agent';
3
- export declare const DIAGNOSTIC_BUILD = "5bf3e8c3b38641652836a07684de20f6e5b17aec8e3ad4051e4fd85a250b9a2d";
3
+ export declare const DIAGNOSTIC_BUILD = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
4
4
  export interface Receipt {
5
5
  id: string;
6
6
  build: string;
@@ -110,6 +110,11 @@ export declare const HEAL_DELAYS_MS: readonly number[];
110
110
  export declare const HEAL_STEADY_MS = 600000;
111
111
  /** 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. */
112
112
  export declare const IDLE_STOP_MS = 600000;
113
+ /** Background indexing (a session that has not searched, indexing what a cut moved out of view) holds this lock in the index directory, so
114
+ * 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. */
115
+ export declare const INDEXER_LOCK = "background-indexer.lock";
116
+ /** How long background indexing waits before trying the lock again when another process holds it. */
117
+ export declare const INDEXER_RETRY_MS = 15000;
113
118
  /** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
114
119
  export declare const CALL_DEADLINE_MS = 60000;
115
120
  /** 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. */
@@ -186,7 +191,9 @@ export declare class SemanticRecallController {
186
191
  private healRetryAt;
187
192
  private recycle;
188
193
  private active;
189
- private fullIndexing;
194
+ private fullIndexing; /** 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. */
195
+ private backgroundOnly; /** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */
196
+ private releaseLock?;
190
197
  private idleTimer?;
191
198
  private idling?;
192
199
  private quietStop;
@@ -310,14 +317,15 @@ export declare class SemanticRecallController {
310
317
  };
311
318
  };
312
319
  schedule(provider: () => Snapshot): void;
313
- /** A saved cut has moved entries out of view: start indexing them now, for a session that has searched before but is not searching now, or whose worker the idle limit stopped. Awaits nothing; a failure goes to `heal` like any preparation.
314
- * Only a session that ran a search earlier (`searched`) indexes at a cut: a host may give every session its own controller and worker, so indexing at every node's cut could run several encoders at once on a 16 GB machine.
315
- * It is the conversation that left the view only (kind first, no full pass), a heal backoff in progress is not bypassed, and the idle limit applies afterwards. */
320
+ /** 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.
321
+ * 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;
322
+ * 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. */
316
323
  indexAtCut(provider: () => Snapshot): void;
317
324
  private runtime;
318
325
  private path;
319
326
  private index;
320
327
  private prepare;
328
+ private prepareLocked;
321
329
  waitForReady(timeoutMs?: number, signal?: AbortSignal, expectedSnapshotId?: string, forSearch?: boolean): Promise<{
322
330
  setup: SemanticSetup;
323
331
  setupMessage: string | null;
@@ -383,6 +391,7 @@ export declare class SemanticRecallController {
383
391
  private demand;
384
392
  private cancelIdle;
385
393
  private armIdle;
394
+ private freeLock;
386
395
  private idleStop;
387
396
  /** 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`). */
388
397
  private cancelled;
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
- import { readFile, rm, mkdtemp, mkdir } from 'node:fs/promises';
3
+ import { readFile, rm, mkdtemp, mkdir, writeFile } from 'node:fs/promises';
4
4
  import { lstatSync, realpathSync } from 'node:fs';
5
5
  import { resolve, relative, join, dirname, basename, isAbsolute, sep } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
@@ -168,6 +168,40 @@ export const HEAL_DELAYS_MS = [5000, 30000, 120000];
168
168
  export const HEAL_STEADY_MS = 600000;
169
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
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
+ }
171
205
  /** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
172
206
  export const CALL_DEADLINE_MS = 60000;
173
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. */
@@ -584,7 +618,9 @@ export class SemanticRecallController {
584
618
  recycle = false;
585
619
  // 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`).
586
620
  active = false;
587
- fullIndexing = false;
621
+ 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. */
622
+ backgroundOnly = false; /** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */
623
+ releaseLock;
588
624
  idleTimer;
589
625
  idling;
590
626
  quietStop = false;
@@ -663,11 +699,13 @@ export class SemanticRecallController {
663
699
  this.error = null;
664
700
  this.schedule(this.provider);
665
701
  } }); }, 5); }
666
- /** A saved cut has moved entries out of view: start indexing them now, for a session that has searched before but is not searching now, or whose worker the idle limit stopped. Awaits nothing; a failure goes to `heal` like any preparation.
667
- * Only a session that ran a search earlier (`searched`) indexes at a cut: a host may give every session its own controller and worker, so indexing at every node's cut could run several encoders at once on a 16 GB machine.
668
- * It is the conversation that left the view only (kind first, no full pass), a heal backoff in progress is not bypassed, and the idle limit applies afterwards. */
669
- indexAtCut(provider) { if (this.enabled && !this.healTimer && this.searched && !this.active) {
702
+ /** 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.
703
+ * 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;
704
+ * 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. */
705
+ indexAtCut(provider) { if (this.enabled && !this.healTimer && !this.active) {
670
706
  this.active = true;
707
+ this.fullIndexing = true;
708
+ this.backgroundOnly = true;
671
709
  this.armIdle();
672
710
  } this.schedule(provider); }
673
711
  async runtime(project) {
@@ -725,6 +763,30 @@ export class SemanticRecallController {
725
763
  const prior = this.current;
726
764
  if (prior?.complete && prior.id === snapshot.id)
727
765
  return;
766
+ let release = null;
767
+ if (this.backgroundOnly) {
768
+ await mkdir(this.config.indexDirectory, { recursive: true });
769
+ release = await tryIndexerLock(this.config.indexDirectory);
770
+ if (!release) {
771
+ const retry = setTimeout(() => { if (this.enabled && generation === this.generation)
772
+ this.schedule(provider); }, INDEXER_RETRY_MS);
773
+ retry.unref();
774
+ return;
775
+ }
776
+ }
777
+ try {
778
+ await this.prepareLocked(provider, full, generation, started, snapshot, prior);
779
+ }
780
+ finally {
781
+ if (release) {
782
+ if (this.backgroundOnly && this.current?.complete)
783
+ this.releaseLock = release;
784
+ else
785
+ await release();
786
+ }
787
+ }
788
+ }
789
+ async prepareLocked(provider, full, generation, started, snapshot, prior) {
728
790
  // 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.
729
791
  const maxChars = this.config.maxSourceCharacters ?? 2000000, maxUnits = this.config.maxUnits ?? MAX_INDEX_UNITS;
730
792
  const check = () => { if (generation !== this.generation || !this.enabled)
@@ -840,6 +902,8 @@ export class SemanticRecallController {
840
902
  snapshot.complete = true;
841
903
  if (full)
842
904
  this.fullIndexing = false;
905
+ if (this.backgroundOnly)
906
+ setTimeout(() => { void (this.backgroundOnly ? this.idleStop() : Promise.resolve()).finally(() => this.freeLock()); }, 0).unref();
843
907
  }
844
908
  this.error = null;
845
909
  this.recovered();
@@ -1093,11 +1157,12 @@ export class SemanticRecallController {
1093
1157
  throw error;
1094
1158
  } }
1095
1159
  /** 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. */
1096
- demand() { this.active = true; this.fullIndexing = true; this.cancelIdle(); }
1160
+ demand() { this.active = true; this.fullIndexing = true; this.backgroundOnly = false; this.cancelIdle(); }
1097
1161
  cancelIdle() { if (this.idleTimer)
1098
1162
  clearTimeout(this.idleTimer); this.idleTimer = undefined; }
1099
1163
  armIdle() { this.cancelIdle(); if (!this.enabled || !this.active)
1100
1164
  return; this.idleTimer = setTimeout(() => { this.idleTimer = undefined; void this.idleStop(); }, this.timing.idleStopMs ?? IDLE_STOP_MS); this.idleTimer.unref(); }
1165
+ async freeLock() { const release = this.releaseLock; this.releaseLock = undefined; await release?.().catch(() => { }); }
1101
1166
  idleStop() {
1102
1167
  if (this.idling || !this.enabled || !this.active || this.joiningSearches || this.activeSearches.size)
1103
1168
  return Promise.resolve();
@@ -1117,6 +1182,7 @@ export class SemanticRecallController {
1117
1182
  const stop = (async () => {
1118
1183
  this.active = false;
1119
1184
  this.fullIndexing = false;
1185
+ this.backgroundOnly = false;
1120
1186
  this.quietStop = true;
1121
1187
  this.generation++;
1122
1188
  this.dirty = false;
@@ -1188,7 +1254,7 @@ export class SemanticRecallController {
1188
1254
  // 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.
1189
1255
  async revoked(error) { await this.disable(false); this.error = error instanceof Error ? error.message : 'Source access denied'; }
1190
1256
  async invalidate() { await this.disable(); this.error = 'Caller invalidated semantic source access; explicit enable required'; }
1191
- async close() { await this.disable(true, false); this.provider = undefined; this.searched = false; } // a closed controller serves a new session, which has not searched; a disable and enable keeps it
1257
+ 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
1192
1258
  }
1193
1259
  export const createSemanticRecall = (config) => new SemanticRecallController(config);
1194
1260
  /** Consolidate only source-bound coordinate overlap; equal text in distinct events is retained.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-tuck",
3
- "version": "1.0.31",
3
+ "version": "1.0.32",
4
4
  "description": "Deterministic compaction for Pi with no model call, plus exact recall of earlier history. Search by meaning on Apple silicon.",
5
5
  "keywords": [
6
6
  "pi-package",
package/src/build-id.ts CHANGED
@@ -1 +1 @@
1
- export const BUILD_ID = "5bf3e8c3b38641652836a07684de20f6e5b17aec8e3ad4051e4fd85a250b9a2d";
1
+ export const BUILD_ID = "e221c8f3d2154596f83256c799882e6ff8ac9c954aa63709379a993518932a25";
package/src/compaction.ts CHANGED
@@ -907,7 +907,12 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
907
907
  };
908
908
  const atBoundary = (event: Boundary, ctx: ExtensionContext, reason: "tool-loop" | "run-end", decide: boolean) => {
909
909
  const current = view(ctx);
910
- if (!current.pending) return decide ? boundaryCut(event, ctx, reason) : undefined;
910
+ if (!current.pending) {
911
+ const result = decide ? boundaryCut(event, ctx, reason) : undefined;
912
+ // Pi announces only its own compactions (session_compact); a cut saved here gets no event, so it starts the indexing itself.
913
+ if (result?.entries.some(entry => entry.type === "compaction")) setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
914
+ return result;
915
+ }
911
916
  const entry = run!.cut.take()!;
912
917
  const preview = current.session, context: ExtensionContext = Object.create(ctx, { sessionManager: { value: preview } });
913
918
  const more = decide && !event.entries.length
@@ -960,6 +965,8 @@ export async function installCompaction(pi: ExtensionAPI, options: CompactionOpt
960
965
  stoppedOutputTokens: event.message.role === "assistant" ? event.message.usage?.output ?? 0 : 0, cut: true,
961
966
  estimatedTokens: corrected(tokens, view), piEstimateTokens: check.estimate, piCap: check.cap, room, hardLine, buildId: BUILD_ID } }];
962
967
  markBoundary(drafts);
968
+ // As at a boundary: Pi announces only its own compactions, so the cut saved for the retry starts the indexing itself.
969
+ setImmediate(() => { semantic.indexAtCut(semanticProvider(ctx)); });
963
970
  return { entries: drafts, continue: true };
964
971
  };
965
972
  pi.on("turn_end", (event, ctx) => {
@@ -1,6 +1,6 @@
1
1
  import {spawn,type ChildProcessWithoutNullStreams} from 'node:child_process';
2
2
  import {createHash,randomUUID} from 'node:crypto';
3
- import {readFile,rm,mkdtemp,mkdir} from 'node:fs/promises';
3
+ import {readFile,rm,mkdtemp,mkdir,writeFile} from 'node:fs/promises';
4
4
  import {lstatSync,realpathSync} from 'node:fs';
5
5
  import {resolve,relative,join,dirname,basename,isAbsolute,sep} from 'node:path';
6
6
  import {fileURLToPath} from 'node:url';
@@ -101,6 +101,23 @@ export const HEAL_DELAYS_MS:readonly number[]=[5000,30000,120000];
101
101
  export const HEAL_STEADY_MS=600000;
102
102
  /** 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. */
103
103
  export const IDLE_STOP_MS=600000;
104
+ /** Background indexing (a session that has not searched, indexing what a cut moved out of view) holds this lock in the index directory, so
105
+ * 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. */
106
+ export const INDEXER_LOCK='background-indexer.lock';
107
+ /** How long background indexing waits before trying the lock again when another process holds it. */
108
+ export const INDEXER_RETRY_MS=15000;
109
+ const alive=(pid:number)=>{try{process.kill(pid,0);return true;}catch(error){return (error as NodeJS.ErrnoException).code==='EPERM';}};
110
+ /** 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. */
111
+ async function tryIndexerLock(directory:string):Promise<(()=>Promise<void>)|null>{
112
+ const path=join(directory,INDEXER_LOCK),take=async()=>{try{await mkdir(path);return true;}catch(error){if((error as NodeJS.ErrnoException).code==='EEXIST')return false;throw error;}};
113
+ if(!await take()){
114
+ const holder=Number(await readFile(join(path,'pid'),'utf8').catch(()=>''));
115
+ if(holder&&alive(holder))return null;
116
+ await rm(path,{recursive:true,force:true});if(!await take())return null;
117
+ }
118
+ await writeFile(join(path,'pid'),String(process.pid));
119
+ return ()=>rm(path,{recursive:true,force:true});
120
+ }
104
121
  /** A worker call's deadline once the worker has answered a call after `ready`: index, embed and tokenize on a loaded model. */
105
122
  export const CALL_DEADLINE_MS=60000;
106
123
  /** 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. */
@@ -277,7 +294,7 @@ export class SemanticRecallController {
277
294
  private tokenized=new Map<string,Unit[]>();
278
295
  private healReason:string|null=null;private healIntegrity=false;private healAttempts=0;private healTimer?:ReturnType<typeof setTimeout>;private healRetryAt:number|null=null;private recycle=false;
279
296
  // 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`).
280
- private active=false;private fullIndexing=false;private idleTimer?:ReturnType<typeof setTimeout>;private idling?:Promise<void>;private quietStop=false;
297
+ private active=false;private 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. */private backgroundOnly=false;/** The machine indexer lock while this controller holds it: released once its worker has stopped, not when embedding ends. */private releaseLock?:()=>Promise<void>;private idleTimer?:ReturnType<typeof setTimeout>;private idling?:Promise<void>;private quietStop=false;
281
298
  // 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.
282
299
  private searched=false;
283
300
  private readonly listeners=new Set<(state:SemanticState,reason:string|null)=>void>();private announced='disabled\0';private announcing=false;
@@ -300,10 +317,10 @@ export class SemanticRecallController {
300
317
  /** The existing model-facing coverage contract: setup metadata belongs to operator status, not the request. */
301
318
  requestCoverage(){const {setup,setupMessage,...coverage}=this.status();return coverage;}
302
319
  schedule(provider:()=>Snapshot){this.provider=provider;if(!this.enabled||this.timer||!this.active||this.healTimer)return;this.timer=setTimeout(()=>{this.timer=undefined;if(this.task){this.dirty=true;return;}this.task=this.prepare(provider,this.fullIndexing).catch(async error=>{if(this.quietStop||!this.enabled)return;this.error=error instanceof Error?error.message:'local failure';if(error instanceof Error&&error.name==='SemanticAccessError'){this.enabled=false;this.generation++;this.dirty=false;try{await this.closeResources();}catch(cleanup){this.cleanupError=cleanup instanceof Error?cleanup.message:'Semantic cleanup failed';this.error=this.cleanupError;}}else this.heal(error);}).finally(()=>{this.task=undefined;if(this.enabled&&this.dirty){this.dirty=false;this.error=null;this.schedule(this.provider!);}});},5);}
303
- /** A saved cut has moved entries out of view: start indexing them now, for a session that has searched before but is not searching now, or whose worker the idle limit stopped. Awaits nothing; a failure goes to `heal` like any preparation.
304
- * Only a session that ran a search earlier (`searched`) indexes at a cut: a host may give every session its own controller and worker, so indexing at every node's cut could run several encoders at once on a 16 GB machine.
305
- * It is the conversation that left the view only (kind first, no full pass), a heal backoff in progress is not bypassed, and the idle limit applies afterwards. */
306
- indexAtCut(provider:()=>Snapshot){if(this.enabled&&!this.healTimer&&this.searched&&!this.active){this.active=true;this.armIdle();}this.schedule(provider);}
320
+ /** 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.
321
+ * 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;
322
+ * 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. */
323
+ indexAtCut(provider:()=>Snapshot){if(this.enabled&&!this.healTimer&&!this.active){this.active=true;this.fullIndexing=true;this.backgroundOnly=true;this.armIdle();}this.schedule(provider);}
307
324
  private async runtime(project:string){if(this.idling)await this.idling;if(!this.enabled)throw abort();outsideProject(project,this.config!.runtimeRoot,'runtime');outsideProject(project,scratchParent(this.config!),'scratch');outsideRuntime(this.config!.runtimeRoot,scratchParent(this.config!),'scratch');if(this.worker&&this.recycle){const old=this.worker;await old.close();if(this.worker===old){this.worker=undefined;this.identity='';this.recycle=false;}if(!this.enabled)throw abort();}
308
325
  if(!this.worker){const worker=new LocalWorker(this.config!,project,error=>{if(this.worker!==worker)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)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});this.worker=worker;}if(!this.identity){const ready=await this.worker.call('ready');if(ready.dimensions!==768||ready.maxTokens!==8192||!ready.offline)throw new Error('Incompatible semantic model; EG2 768/8192 offline required');this.identity=hash({worker:ready.identity,chunk:'eg2-passage256-focused-disjoint-direct-v3'});}return this.worker;}
309
326
  private path(snapshot: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');}
@@ -312,6 +329,15 @@ export class SemanticRecallController {
312
329
  if(!this.enabled)return;
313
330
  const generation=this.generation,started=performance.now();let snapshot=provider();const prior=this.current;
314
331
  if(prior?.complete&&prior.id===snapshot.id)return;
332
+ let release:(()=>Promise<void>)|null=null;
333
+ if(this.backgroundOnly){
334
+ await mkdir(this.config!.indexDirectory,{recursive:true});release=await tryIndexerLock(this.config!.indexDirectory);
335
+ if(!release){const retry=setTimeout(()=>{if(this.enabled&&generation===this.generation)this.schedule(provider);},INDEXER_RETRY_MS);retry.unref();return;}
336
+ }
337
+ try{await this.prepareLocked(provider,full,generation,started,snapshot,prior);}
338
+ finally{if(release){if(this.backgroundOnly&&this.current?.complete)this.releaseLock=release;else await release();}}
339
+ }
340
+ private async prepareLocked(provider:()=>Snapshot,full:boolean,generation:number,started:number,snapshot:Snapshot,prior:Snapshot|undefined){
315
341
  // 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.
316
342
  const maxChars=this.config!.maxSourceCharacters??2000000,maxUnits=this.config!.maxUnits??MAX_INDEX_UNITS;
317
343
  const check=()=>{if(generation!==this.generation||!this.enabled)throw abort();this.recheck(provider,snapshot);};
@@ -366,7 +392,7 @@ export class SemanticRecallController {
366
392
  await yieldWork();if(progressed&&performance.now()-started>(this.config!.prepareWorkMs??30000)){this.error='Preparation work slice exhausted; indexing incomplete';this.dirty=true;return;}
367
393
  }
368
394
  check();
369
- if(snapshot.units.every(unit=>snapshot.indexed.has(unit.key))){snapshot.complete=true;if(full)this.fullIndexing=false;}
395
+ if(snapshot.units.every(unit=>snapshot.indexed.has(unit.key))){snapshot.complete=true;if(full)this.fullIndexing=false;if(this.backgroundOnly)setTimeout(()=>{void (this.backgroundOnly?this.idleStop():Promise.resolve()).finally(()=>this.freeLock());},0).unref();}
370
396
  this.error=null;this.recovered();
371
397
  }
372
398
  async waitForReady(timeoutMs=this.config?.queryWaitMs??30000,signal?:AbortSignal,expectedSnapshotId?:string,forSearch=false){if(this.enabled)this.demand();let targetId=expectedSnapshotId;try{targetId??=this.provider?.().id;}catch(error){await this.revoked(error);throw error;}if(this.enabled&&this.provider&&this.current?.id!==targetId){this.error=null;this.schedule(this.provider);}const started=performance.now();while(this.enabled&&!this.readyFor(targetId,forSearch)&&!this.error&&!this.healTimer&&performance.now()-started<timeoutMs){if(signal?.aborted){await this.cancelled();throw abort();}if(this.provider&&!this.timer&&!this.task)this.schedule(this.provider);await new Promise(done=>setTimeout(done,10));}this.armIdle();return this.status();}
@@ -442,9 +468,10 @@ export class SemanticRecallController {
442
468
  private async stopOwner(){this.dirty=false;this.enabled=false;this.generation++;if(this.timer){clearTimeout(this.timer);this.timer=undefined;}try{await this.closeResources();await this.task;this.task=undefined;}catch(error){this.cleanupError=error instanceof Error?error.message:'Semantic cleanup failed';throw error;}}
443
469
 
444
470
  /** 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. */
445
- private demand(){this.active=true;this.fullIndexing=true;this.cancelIdle();}
471
+ private demand(){this.active=true;this.fullIndexing=true;this.backgroundOnly=false;this.cancelIdle();}
446
472
  private cancelIdle(){if(this.idleTimer)clearTimeout(this.idleTimer);this.idleTimer=undefined;}
447
473
  private armIdle(){this.cancelIdle();if(!this.enabled||!this.active)return;this.idleTimer=setTimeout(()=>{this.idleTimer=undefined;void this.idleStop();},this.timing.idleStopMs??IDLE_STOP_MS);this.idleTimer.unref();}
474
+ private async freeLock(){const release=this.releaseLock;this.releaseLock=undefined;await release?.().catch(()=>{});}
448
475
  private idleStop(){
449
476
  if(this.idling||!this.enabled||!this.active||this.joiningSearches||this.activeSearches.size)return Promise.resolve();
450
477
  return this.stopWorker();
@@ -457,7 +484,7 @@ export class SemanticRecallController {
457
484
  if(this.idling)return this.idling;
458
485
  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
459
486
  const stop=(async()=>{
460
- this.active=false;this.fullIndexing=false;this.quietStop=true;this.generation++;this.dirty=false;
487
+ this.active=false;this.fullIndexing=false;this.backgroundOnly=false;this.quietStop=true;this.generation++;this.dirty=false;
461
488
  if(this._timer){clearTimeout(this._timer);this.timer=undefined;}
462
489
  this.cancelHeal();
463
490
  const worker=this.worker;
@@ -490,7 +517,7 @@ export class SemanticRecallController {
490
517
  // 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.
491
518
  private async revoked(error:unknown){await this.disable(false);this.error=error instanceof Error?error.message:'Source access denied';}
492
519
  async invalidate(){await this.disable();this.error='Caller invalidated semantic source access; explicit enable required';}
493
- async close(){await this.disable(true,false);this.provider=undefined;this.searched=false;} // a closed controller serves a new session, which has not searched; a disable and enable keeps it
520
+ 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
494
521
  }
495
522
  export const createSemanticRecall=(config?:SemanticRecallConfig)=>new SemanticRecallController(config);
496
523
  /** Consolidate only source-bound coordinate overlap; equal text in distinct events is retained.