acp-kernel 0.0.88 → 0.0.89-pr.315.262

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.
@@ -3,6 +3,7 @@ import type { Prompts } from "./prompts.js";
3
3
  export type NudgeVoice = "gentle" | "emergency";
4
4
  export interface NudgePromptSections {
5
5
  efficiencyNote?: string | null;
6
+ pressureHeader?: string | null;
6
7
  emergencyHeader?: string | null;
7
8
  t2Guidance?: string | null;
8
9
  t3Guidance?: string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"nudge-text.d.ts","sourceRoot":"","sources":["../src/nudge-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,cAAc,EAAiD,MAAM,YAAY,CAAC;AAElI,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEhD,MAAM,WAAW,mBAAmB;IAClC,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,UAAU,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AAwDD,wBAAgB,YAAY,CAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,MAAM,CAgFzG;AAiBD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,GAAE,OAAwB,EAAE,QAAQ,GAAE,mBAAwB,GAAG,aAAa,CAyE7I"}
1
+ {"version":3,"file":"nudge-text.d.ts","sourceRoot":"","sources":["../src/nudge-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,cAAc,EAAiD,MAAM,YAAY,CAAC;AAElI,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEhD,MAAM,WAAW,mBAAmB;IAClC,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,UAAU,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;CACd;AA6DD,wBAAgB,YAAY,CAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,eAAe,EAAE,cAAc,EAAE,GAAG,MAAM,CAgFzG;AAiBD,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,EAAE,OAAO,GAAE,OAAwB,EAAE,QAAQ,GAAE,mBAAwB,GAAG,aAAa,CAiF7I"}
@@ -3,7 +3,7 @@ import {
3
3
  defaultCountTokens,
4
4
  formatRanges,
5
5
  viableRanges
6
- } from "../chunk-NUQZKPQS.js";
6
+ } from "../chunk-OY6XYN4S.js";
7
7
 
8
8
  // src/panel/topic.ts
9
9
  function topicFallback(summary) {
@@ -25,6 +25,12 @@ var StateStore = class {
25
25
  writeChains = /* @__PURE__ */ new Map();
26
26
  /** id → absolute path, populated by writes and loadAll. */
27
27
  discovered = /* @__PURE__ */ new Map();
28
+ /** id → seq of the last COMMITTED write (sync or async). Async writers
29
+ * capture the seq at snapshot time and re-check it inside their
30
+ * synchronous commit block; a flushSync (or a newer committed write)
31
+ * bumping the seq makes the stale in-flight write abort its commit
32
+ * instead of clobbering the newer on-disk payload. */
33
+ commitSeq = /* @__PURE__ */ new Map();
28
34
  /** id → cumulative write-failure count, for rate-limited alerting. */
29
35
  failCounts = /* @__PURE__ */ new Map();
30
36
  /** Monotonic counter for unique temp filenames within a process. */
@@ -79,7 +85,9 @@ var StateStore = class {
79
85
  /** Synchronous flush for one id. Used where the caller cannot await
80
86
  * (memory eviction, sync shutdown paths). Cancels any pending debounce
81
87
  * timer. Returns true on success, false on failure — callers that use
82
- * the result to drop in-memory state must NOT drop it on failure. */
88
+ * the result to drop in-memory state must NOT drop it on failure.
89
+ * Committing bumps the per-id fence so a stale in-flight async write
90
+ * cannot land its older payload after this returns. */
83
91
  flushSync(id, build) {
84
92
  if (!this.enabled) return true;
85
93
  const timer = this.timers.get(id);
@@ -119,6 +127,7 @@ var StateStore = class {
119
127
  if (!lastErr) {
120
128
  this.discovered.set(id, file);
121
129
  this.clearFailure(id);
130
+ this.bumpCommit(id);
122
131
  this.removeSpillSync(file);
123
132
  return true;
124
133
  }
@@ -135,6 +144,7 @@ var StateStore = class {
135
144
  }
136
145
  }
137
146
  if (spillPath) this.discovered.set(id, spillPath);
147
+ if (spillPath) this.bumpCommit(id);
138
148
  this.recordFailure(id, lastErr, spillPath);
139
149
  return spillPath !== null;
140
150
  }
@@ -230,6 +240,7 @@ var StateStore = class {
230
240
  this.pending.clear();
231
241
  }
232
242
  async writeInner(id, build) {
243
+ const baseSeq = this.commitSeq.get(id) ?? 0;
233
244
  let payload;
234
245
  try {
235
246
  payload = build();
@@ -245,9 +256,26 @@ var StateStore = class {
245
256
  try {
246
257
  await fsp.mkdir(path.dirname(file), { recursive: true });
247
258
  await fsp.writeFile(tmp, data);
248
- await fsp.rename(tmp, file);
259
+ if ((this.commitSeq.get(id) ?? 0) !== baseSeq) {
260
+ await fsp.unlink(tmp).catch(() => {
261
+ });
262
+ return;
263
+ }
264
+ try {
265
+ fs.renameSync(tmp, file);
266
+ } catch (e) {
267
+ lastErr = e;
268
+ await fsp.unlink(tmp).catch(() => {
269
+ });
270
+ if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;
271
+ const { promise, resolve } = Promise.withResolvers();
272
+ setTimeout(resolve, this.backoffMs(attempt));
273
+ await promise;
274
+ continue;
275
+ }
249
276
  this.discovered.set(id, file);
250
277
  this.clearFailure(id);
278
+ this.commitSeq.set(id, baseSeq + 1);
251
279
  await this.removeSpill(file);
252
280
  return;
253
281
  } catch (e) {
@@ -260,12 +288,14 @@ var StateStore = class {
260
288
  await promise;
261
289
  }
262
290
  }
291
+ if ((this.commitSeq.get(id) ?? 0) !== baseSeq) return;
263
292
  const spill = this.spillPathFor(file);
264
293
  let spillPath = null;
265
294
  for (let attempt = 0; attempt < this.retryAttempts && spillPath === null; attempt++) {
266
295
  try {
267
296
  await fsp.mkdir(path.dirname(spill), { recursive: true });
268
- await fsp.writeFile(spill, data);
297
+ if ((this.commitSeq.get(id) ?? 0) !== baseSeq) return;
298
+ fs.writeFileSync(spill, data);
269
299
  spillPath = spill;
270
300
  } catch (e) {
271
301
  if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;
@@ -274,7 +304,10 @@ var StateStore = class {
274
304
  await promise;
275
305
  }
276
306
  }
277
- if (spillPath) this.discovered.set(id, spillPath);
307
+ if (spillPath) {
308
+ this.discovered.set(id, spillPath);
309
+ this.commitSeq.set(id, baseSeq + 1);
310
+ }
278
311
  this.recordFailure(id, lastErr, spillPath);
279
312
  throw lastErr;
280
313
  }
@@ -328,6 +361,12 @@ var StateStore = class {
328
361
  await fsp.unlink(this.spillPathFor(file)).catch(() => {
329
362
  });
330
363
  }
364
+ /** Advance the per-id commit fence after a successful synchronous
365
+ * commit, fencing off any in-flight async write holding an older
366
+ * snapshot. */
367
+ bumpCommit(id) {
368
+ this.commitSeq.set(id, (this.commitSeq.get(id) ?? 0) + 1);
369
+ }
331
370
  removeSpillSync(file) {
332
371
  try {
333
372
  fs.unlinkSync(this.spillPathFor(file));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/persist/store.ts","../../src/persist/state-merge.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** Logger callback. Downstream routes it wherever it wants (file, stderr). */\nexport type PersistLogger = (level: \"info\" | \"warn\" | \"error\", msg: string) => void;\n\n/**\n * On-disk record shape. The store owns the envelope (version stamp, save\n * time, id) so atomicity and discovery can rely on it; the payload schema\n * is entirely downstream-owned. `payload` must be JSON-serializable.\n */\nexport interface PersistedEnvelope<T> {\n version: number;\n savedAt: number;\n id: string;\n payload: T;\n}\n\n/** A legacy (pre-envelope) record adopted on load. `version`/`savedAt`\n * preserve the source record's own stamps when present. */\nexport interface LegacyAdoption<T> {\n id: string;\n payload: T;\n version?: number;\n savedAt?: number;\n}\n\n/**\n * Optional record codec: transforms serialized envelopes between the store\n * and disk (e.g. compress and/or encrypt at rest). The store is\n * codec-agnostic — it hands `encode` the exact JSON string it would have\n * written and passes raw file bytes to `decode`, which must return that same\n * JSON string or throw, in which case the file is treated as corrupt\n * (skipped + logged) like any unreadable record. Format detection (magic\n * bytes, plaintext fallback for unencoded legacy files) is the codec's job,\n * so mixed trees of legacy plaintext and encoded files load fine.\n */\nexport interface StateStoreCodec {\n encode(data: string): Buffer | string;\n decode(buf: Buffer): string;\n}\n\nexport interface StateStoreOptions<T> {\n /**\n * Storage root. The kernel deliberately has NO default location: the\n * downstream decides where state lives (CLI dir, XDG data dir, plugin\n * dir, temp dir in tests). All records live under this directory.\n */\n dir: string;\n /**\n * Schema version stamped into every envelope. Owned by the downstream;\n * bump it when the payload shape changes. The store itself never\n * rejects a record over its version — migration policy belongs to the\n * reader.\n */\n version: number;\n /** Debounce window for scheduleSave, ms. Default 500. */\n debounceMs?: number;\n /** Default true. When false, all writes are silent no-ops and loads\n * return empty results. */\n enabled?: boolean;\n log?: PersistLogger;\n /**\n * Relative path (under `dir`) for a record, possibly namespaced into\n * subdirectories (e.g. `openai/host-hash.json`). Default: flat\n * `<sha256(id)[:24]>.json`.\n *\n * Because the path may depend on payload fields the store only learns\n * at write time, single-record loads resolve namespaced files only\n * after loadAll() has discovered them (or the store itself wrote\n * them). The flat default name is always checked as a fallback, so\n * downstreams using a custom relPath should call loadAll() at boot.\n */\n relPath?: (id: string, payload: T) => string;\n /**\n * Adopt records written by an older, pre-envelope schema. Receives the\n * parsed JSON of any file that failed the envelope-shape check; return\n * an adoption to load it as an envelope, or null to skip it. Adopted\n * records are re-persisted in the current envelope format on the next\n * dirty write — files migrate organically, and old files keep loading\n * (same policy billion-context's proxy used for its v1→v3 migration).\n */\n legacy?: (parsed: unknown) => LegacyAdoption<T> | null;\n /**\n * Payload validation on load. Return false to skip a record (foreign\n * schema, corrupt content). Default: envelope-shape check only\n * (string id, non-null payload).\n */\n validate?: (envelope: PersistedEnvelope<T>) => boolean;\n /**\n * Optional codec applied around every write (canonical + spill) and\n * read. See StateStoreCodec. Default: none — files are plain UTF-8 JSON.\n */\n codec?: StateStoreCodec;\n /**\n * Transient-write retry policy (Windows + hostile temp environments).\n * The whole write cycle — mkdir, temp write, rename — is retried with\n * exponential backoff when it fails with a TRANSIENT code: EPERM/EBUSY/\n * EACCES (a lock held by AV scan, search indexer, SMB) or ENOENT/ENOTDIR\n * (the temp file or its directory vanished between create and rename —\n * observed on CI Windows runners where a sweeper deletes freshly\n * created files under %TEMP%). The delay after attempt i is\n * min(retryBaseMs * 2^i, retryMaxMs). Defaults (6 attempts, 50ms base,\n * 1600ms cap) give a ~1.5s window per write path — long enough for most\n * locks to release, short enough not to stall a sync flush. When the\n * window is exhausted the write spills to a side file (see spillPath)\n * instead of dropping the data.\n */\n retryAttempts?: number;\n retryBaseMs?: number;\n retryMaxMs?: number;\n}\n\n/**\n * Crash-safe, debounce-coalescing JSON state store. Mechanism only — lifted\n * from billion-context's proxy SessionStore and generalized:\n *\n * - atomic writes: temp file + rename, so a crash mid-write never leaves a\n * truncated record (readers see either the old or the new file)\n * - whole-cycle retries with exponential backoff on transient fs failures:\n * Windows locks (EPERM/EBUSY/EACCES from AV/indexer/SMB) and vanishing\n * files/dirs (ENOENT/ENOTDIR — a sweeper deleting fresh temp files, seen\n * on CI Windows runners); when the window is exhausted the record spills\n * to a side file (`<name>.fb.json`) instead of being dropped, so a lock\n * held by AV/indexer/SMB never silently loses session data\n * - per-id serialization so concurrent writeNow calls never interleave\n * temp-file names or reorders writes\n * - debounced scheduleSave coalesces bursts into one write; the record is\n * built at WRITE time from a builder, so late mutations are picked up\n * - optional record codec (compress/encrypt at rest): encode on every write,\n * decode on every read; a decode failure is corrupt-file semantics\n * - loadAll skips `.tmp-*` orphans, corrupt JSON, and records whose\n * filename does not match their id — one bad file never blocks boot; it\n * reconciles a canonical record against its spill by savedAt (freshest wins)\n *\n * The store never deletes a record's data. On a successful canonical write it\n * removes a now-stale spill of the SAME id (a duplicate, not distinct data).\n * Session cleanup is a downstream policy decision (kernel position: persisted\n * state should not be deleted opportunistically).\n */\nexport class StateStore<T> {\n readonly enabled: boolean;\n private readonly dir: string;\n private readonly version: number;\n private readonly debounceMs: number;\n private readonly log: PersistLogger;\n private readonly legacyFn?: (parsed: unknown) => LegacyAdoption<T> | null;\n private readonly relPathFn?: (id: string, payload: T) => string;\n private readonly validateFn: (envelope: PersistedEnvelope<T>) => boolean;\n private readonly codec?: StateStoreCodec;\n private readonly retryAttempts: number;\n private readonly retryBaseMs: number;\n private readonly retryMaxMs: number;\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly pending = new Map<string, () => T>();\n private readonly writeChains = new Map<string, Promise<void>>();\n /** id → absolute path, populated by writes and loadAll. */\n private readonly discovered = new Map<string, string>();\n /** id → cumulative write-failure count, for rate-limited alerting. */\n private readonly failCounts = new Map<string, number>();\n /** Monotonic counter for unique temp filenames within a process. */\n private tmpSeq = 0;\n\n constructor(opts: StateStoreOptions<T>) {\n this.dir = opts.dir;\n this.version = opts.version;\n this.debounceMs = opts.debounceMs ?? 500;\n this.enabled = opts.enabled ?? true;\n this.log = opts.log ?? ((_level, _msg) => {});\n this.relPathFn = opts.relPath;\n this.legacyFn = opts.legacy;\n this.validateFn = opts.validate ?? defaultValidate;\n this.codec = opts.codec;\n this.retryAttempts = Math.max(1, opts.retryAttempts ?? 6);\n this.retryBaseMs = Math.max(1, opts.retryBaseMs ?? 50);\n this.retryMaxMs = Math.max(this.retryBaseMs, opts.retryMaxMs ?? 1600);\n }\n\n /** Debounced save. Coalesces bursts; the builder runs at write time, so\n * the freshest state is always persisted. Never throws. */\n scheduleSave(id: string, build: () => T): void {\n if (!this.enabled) return;\n this.pending.set(id, build);\n const existing = this.timers.get(id);\n if (existing) return;\n const timer = setTimeout(() => {\n this.timers.delete(id);\n const builder = this.pending.get(id);\n this.pending.delete(id);\n if (!builder) return;\n // Errors are logged inside writeInner; swallowing here keeps a\n // failed timer write from becoming an unhandledRejection.\n void this.writeNow(id, builder).catch(() => {});\n }, this.debounceMs);\n timer.unref?.();\n this.timers.set(id, timer);\n }\n\n /** Immediate save, serialized per id. Rejects on write failure; a\n * failing write never breaks the chain for the next one. */\n async writeNow(id: string, build: () => T): Promise<void> {\n if (!this.enabled) return;\n // The previous promise may reject (disk full, EPERM) — catch so our\n // chain doesn't break, then run our own write.\n const prev = this.writeChains.get(id) ?? Promise.resolve();\n const next = prev.catch(() => {}).then(() => this.writeInner(id, build));\n this.writeChains.set(id, next);\n // Clean up the chain entry once settled so the Map doesn't grow. The\n // .catch() is load-bearing: .finally() returns a derived promise that\n // nobody else holds — when the chain rejects it would surface as an\n // unhandledRejection and crash the host on default Node settings.\n next\n .finally(() => {\n if (this.writeChains.get(id) === next) this.writeChains.delete(id);\n })\n .catch(() => {});\n return next;\n }\n\n /** Synchronous flush for one id. Used where the caller cannot await\n * (memory eviction, sync shutdown paths). Cancels any pending debounce\n * timer. Returns true on success, false on failure — callers that use\n * the result to drop in-memory state must NOT drop it on failure. */\n flushSync(id: string, build: () => T): boolean {\n if (!this.enabled) return true;\n const timer = this.timers.get(id);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(id);\n this.pending.delete(id);\n }\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n return false;\n }\n const file = this.resolvePath(id, payload);\n const data = this.serialize(id, payload);\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n // Fresh temp name + mkdir per attempt — same reasoning as the\n // async writeInner loop (delete-pending tombstones, swept dirs).\n const tmp = this.tempPath(file);\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(tmp, data);\n fs.renameSync(tmp, file);\n lastErr = undefined;\n break;\n } catch (e) {\n lastErr = e;\n try {\n fs.unlinkSync(tmp);\n } catch {\n // temp never created or already gone\n }\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n // sync sleep (Atomics.wait) — backoff grows per attempt\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));\n }\n }\n if (!lastErr) {\n this.discovered.set(id, file);\n this.clearFailure(id);\n this.removeSpillSync(file);\n return true;\n }\n // The canonical write outlived the retry window (Windows lock held by\n // AV/indexer/SMB). Spill to a side file so the data still lands on\n // disk instead of being dropped — loadAll picks the freshest of the\n // canonical and the spill, with its own transient retry window.\n const spill = this.spillPathFor(file);\n let spillPath: string | null = null;\n for (let attempt = 0; attempt < this.retryAttempts && spillPath === null; attempt++) {\n try {\n fs.mkdirSync(path.dirname(spill), { recursive: true });\n fs.writeFileSync(spill, data);\n spillPath = spill;\n } catch (e) {\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));\n }\n }\n if (spillPath) this.discovered.set(id, spillPath);\n this.recordFailure(id, lastErr, spillPath);\n return spillPath !== null;\n }\n\n /** Load one record. Checks the discovered path (from a prior\n * write/loadAll), an optional relative-path hint, and the flat default\n * name. Returns null when absent, disabled, corrupt, or rejected by\n * validate. The hint covers namespaced records the store has not\n * discovered (e.g. an evicted session re-requested with its meta,\n * where the path depends on data the store cannot reconstruct from\n * the id alone). */\n loadSync(id: string, hint?: string): PersistedEnvelope<T> | null {\n if (!this.enabled) return null;\n const candidates = [\n this.discovered.get(id),\n hint ? path.join(this.dir, hint) : undefined,\n path.join(this.dir, flatFileNameFor(id)),\n ];\n for (const file of candidates) {\n if (!file) continue;\n const envelope = this.readEnvelope(file);\n if (envelope && envelope.id === id) return envelope;\n }\n return null;\n }\n\n /** Load every record under dir. Populates the discovery map (enables\n * loadSync for namespaced relPaths). Skips corrupt files, `.tmp-*`\n * orphans, and records whose filename does not match their id — one\n * bad file never blocks boot. Never throws. */\n async loadAll(): Promise<Map<string, PersistedEnvelope<T>>> {\n const out = new Map<string, PersistedEnvelope<T>>();\n if (!this.enabled) return out;\n const files = await this.walkJsonFiles(this.dir);\n for (const file of files) {\n const envelope = this.readEnvelope(file);\n if (!envelope) continue;\n const base = path.basename(file);\n const relBase = path.basename(this.relPathOf(envelope.id, envelope.payload));\n const flatBase = flatFileNameFor(envelope.id);\n // A file is a valid record for its envelope id when its name is the\n // canonical name OR a spill (`.fb`) of the canonical name. This lets\n // a spilled record (written while the canonical was locked) be\n // discovered and reconciled against the canonical by savedAt.\n let owner: string | null = null;\n if (base === relBase || base === flatBase) {\n owner = envelope.id;\n } else if (base.endsWith(\".fb.json\")) {\n const canonicalBase = `${base.slice(0, -\".fb.json\".length)}.json`;\n if (canonicalBase === relBase || canonicalBase === flatBase) {\n owner = envelope.id;\n }\n }\n if (owner === null) {\n this.log(\"warn\", `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`);\n continue;\n }\n const existing = out.get(owner);\n if (!existing || envelope.savedAt >= existing.savedAt) {\n out.set(owner, envelope);\n this.discovered.set(owner, file);\n }\n }\n return out;\n }\n\n /** Whether a debounced write is pending for an id. */\n hasPending(id: string): boolean {\n return this.timers.has(id);\n }\n\n /** Ids with a pending debounced write. */\n pendingIds(): string[] {\n return [...this.timers.keys()];\n }\n\n /** Flush every pending debounced write immediately, then drain in-flight\n * writes. For graceful shutdown (SIGTERM/SIGINT). Never rejects. */\n async flushAll(): Promise<void> {\n const ids = this.pendingIds();\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n const builders = new Map<string, () => T>();\n for (const id of ids) {\n const build = this.pending.get(id);\n if (build) builders.set(id, build);\n this.pending.delete(id);\n }\n await Promise.all(\n [...builders.entries()].map(([id, build]) =>\n this.writeNow(id, build).catch((e) => {\n this.log(\"error\", `[persist] shutdown flush failed for ${id}: ${errText(e)}`);\n }),\n ),\n );\n // Drain writes whose timer fired earlier but are still mid-flight.\n await Promise.allSettled([...this.writeChains.values()]);\n }\n\n /** Cancel all pending debounced writes without flushing (tests). */\n cancelAll(): void {\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pending.clear();\n }\n\n private async writeInner(id: string, build: () => T): Promise<void> {\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n throw e;\n }\n const file = this.resolvePath(id, payload);\n const data = this.serialize(id, payload);\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n // Fresh temp name per attempt: on Windows a failed cleanup can\n // leave the previous name delete-pending, and creating over a\n // tombstoned name fails immediately — reusing it would burn every\n // remaining attempt before the write even happens. mkdir runs per\n // attempt too: a sweeper may have deleted the directory after the\n // previous cycle created it.\n const tmp = this.tempPath(file);\n try {\n await fsp.mkdir(path.dirname(file), { recursive: true });\n await fsp.writeFile(tmp, data);\n await fsp.rename(tmp, file);\n this.discovered.set(id, file);\n this.clearFailure(id);\n await this.removeSpill(file);\n return;\n } catch (e) {\n lastErr = e;\n // Clean up the .tmp orphan so the next write doesn't collide\n // with it.\n await fsp.unlink(tmp).catch(() => {});\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n }\n }\n // The canonical write outlived the retry window (Windows lock held\n // by AV/indexer/SMB, or a sweeper keeps deleting the fresh temp).\n // Spill to a side file so the data still lands on disk instead of\n // being dropped — loadAll picks the freshest of the canonical and\n // the spill. The spill write gets its own transient retry window for\n // the same reason (observed failing with ENOENT alongside the\n // canonical on CI Windows runners).\n const spill = this.spillPathFor(file);\n let spillPath: string | null = null;\n for (let attempt = 0; attempt < this.retryAttempts && spillPath === null; attempt++) {\n try {\n await fsp.mkdir(path.dirname(spill), { recursive: true });\n await fsp.writeFile(spill, data);\n spillPath = spill;\n } catch (e) {\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n }\n }\n if (spillPath) this.discovered.set(id, spillPath);\n this.recordFailure(id, lastErr, spillPath);\n throw lastErr;\n }\n\n private envelope(id: string, payload: T): PersistedEnvelope<T> {\n return { version: this.version, savedAt: Date.now(), id, payload };\n }\n\n /** Serialize an envelope for disk, applying the optional codec. Strings\n * are written as UTF-8 (the fs default); Buffer results pass through as\n * raw bytes. */\n private serialize(id: string, payload: T): Buffer | string {\n const json = JSON.stringify(this.envelope(id, payload));\n return this.codec ? this.codec.encode(json) : json;\n }\n\n /** Absolute path for a record: custom relPath (guarded against path\n * escape) or the flat hash default. */\n private resolvePath(id: string, payload: T): string {\n return path.join(this.dir, this.relPathOf(id, payload));\n }\n\n private relPathOf(id: string, payload: T): string {\n const custom = this.relPathFn?.(id, payload);\n if (!custom) return flatFileNameFor(id);\n const rel = path.normalize(custom);\n if (path.isAbsolute(rel) || rel.split(/[\\\\/]+/).includes(\"..\")) {\n this.log(\"warn\", `[persist] relPath for ${id} escapes dir; using flat name`);\n return flatFileNameFor(id);\n }\n return rel;\n }\n\n /** Unique temp file next to the destination (same dir ⇒ same volume ⇒\n * rename is atomic). Prefixed `.tmp-` so loadAll skips orphans. */\n private tempPath(dest: string): string {\n const seq = this.tmpSeq++;\n return path.join(path.dirname(dest), `.tmp-${path.basename(dest, \".json\")}-${process.pid}-${seq}`);\n }\n\n private backoffMs(attempt: number): number {\n return Math.min(this.retryBaseMs * 2 ** attempt, this.retryMaxMs);\n }\n\n /** Side file for a record whose canonical write keeps failing: the\n * canonical name with a `.fb` (fallback) infix, e.g. `a.json` →\n * `a.fb.json`. One slot per id, overwritten on each spill, so a stuck\n * lock never accumulates files. Ends in `.json` so loadAll discovers it. */\n private spillPathFor(file: string): string {\n const base = path.basename(file);\n const dot = base.lastIndexOf(\".\");\n const stem = dot > 0 ? base.slice(0, dot) : base;\n const ext = dot > 0 ? base.slice(dot) : \".json\";\n return path.join(path.dirname(file), `${stem}.fb${ext}`);\n }\n\n /** Remove a stale spill after a successful canonical write (best-effort). */\n private async removeSpill(file: string): Promise<void> {\n await fsp.unlink(this.spillPathFor(file)).catch(() => {});\n }\n\n private removeSpillSync(file: string): void {\n try {\n fs.unlinkSync(this.spillPathFor(file));\n } catch {\n // no spill or still locked — loadAll reconciles by savedAt\n }\n }\n\n /** Rate-limited failure alerting: log on the first failure and at each\n * power-of-two count (1,2,4,8,…), so a long lock yields ~log2(N) lines\n * instead of one per write. Includes the spill path so the operator can\n * see where the data landed. */\n private recordFailure(id: string, err: unknown, spillPath: string | null): void {\n const count = (this.failCounts.get(id) ?? 0) + 1;\n this.failCounts.set(id, count);\n const alertAt = count === 1 || (count >= 2 && (count & (count - 1)) === 0);\n if (!alertAt) return;\n const where = spillPath\n ? `; data spilled to ${rel(spillPath, this.dir)}`\n : \"; SPILLOVER ALSO FAILED — data at risk\";\n this.log(count === 1 ? \"error\" : \"warn\", `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`);\n }\n\n private clearFailure(id: string): void {\n this.failCounts.delete(id);\n }\n\n /** Parse + validate one file. Corrupt or invalid records return null\n * (logged) instead of throwing — load paths must never block boot. */\n private readEnvelope(file: string): PersistedEnvelope<T> | null {\n let parsed: unknown;\n try {\n const buf = fs.readFileSync(file);\n const text = this.codec ? this.codec.decode(buf) : buf.toString(\"utf8\");\n parsed = JSON.parse(text);\n } catch (e) {\n // A missing candidate path is an expected miss (loadSync probes);\n // only genuinely unreadable/corrupt files get logged.\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") {\n this.log(\"warn\", `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`);\n }\n return null;\n }\n if (isEnvelopeLike(parsed)) {\n if (!this.validateFn(parsed as PersistedEnvelope<T>)) {\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n return parsed as PersistedEnvelope<T>;\n }\n const adopted = this.adoptLegacy(parsed);\n if (adopted) return adopted;\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n\n /** Wrap a legacy (pre-envelope) record as an envelope via the `legacy`\n * hook, then validate the adopted payload like any other. */\n private adoptLegacy(parsed: unknown): PersistedEnvelope<T> | null {\n const adoption = this.legacyFn ? this.legacyFn(parsed) : null;\n if (!adoption || typeof adoption.id !== \"string\" || adoption.id.length === 0 || adoption.payload == null) {\n return null;\n }\n const source = parsed as Partial<PersistedEnvelope<T>>;\n const envelope: PersistedEnvelope<T> = {\n version: adoption.version ?? source.version ?? this.version,\n savedAt: adoption.savedAt ?? source.savedAt ?? 0,\n id: adoption.id,\n payload: adoption.payload,\n };\n if (!this.validateFn(envelope)) return null;\n return envelope;\n }\n\n /** Iterative recursive walk (no readdir-recursive dependency), skipping\n * `.tmp-*` names and non-.json files. */\n private async walkJsonFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n const queue: string[] = [root];\n while (queue.length > 0) {\n const dir = queue.pop()!;\n let dirents: fs.Dirent[];\n try {\n dirents = await fsp.readdir(dir, { withFileTypes: true });\n } catch {\n continue; // missing dir → no records yet\n }\n for (const d of dirents) {\n if (d.name.startsWith(\".tmp-\")) continue;\n const full = path.join(dir, d.name);\n if (d.isDirectory()) queue.push(full);\n else if (d.isFile() && d.name.endsWith(\".json\")) out.push(full);\n }\n }\n return out;\n }\n}\n\nfunction defaultValidate<T>(envelope: PersistedEnvelope<T>): boolean {\n return typeof envelope.id === \"string\" && envelope.id.length > 0 && envelope.payload != null;\n}\n\nfunction isEnvelopeLike(value: unknown): value is PersistedEnvelope<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const v = value as Partial<PersistedEnvelope<unknown>>;\n return typeof v.id === \"string\" && \"payload\" in v;\n}\n\n/** Deterministic flat filename: `<sha256(id)[:24]>.json`. Truncated hash —\n * 96 bits keeps collisions unreachable for realistic id counts, and short\n * names stay greppable. */\nexport function flatFileNameFor(id: string): string {\n return createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\").slice(0, 24) + \".json\";\n}\n\n/** Transient fs failure codes worth retrying the whole write cycle for:\n * - EPERM/EBUSY/EACCES — a lock held on the file/dir (AV scan, search\n * indexer, SMB); releases within the backoff window.\n * - ENOENT/ENOTDIR — the temp file or its directory VANISHED between\n * create and rename (a sweeper deleting fresh files under %TEMP%, seen\n * on CI Windows runners), or a delete-pending tombstone from the same\n * sweep. Recreating the dir + rewriting a fresh temp heals it. */\nfunction isTransientFsError(e: unknown): boolean {\n const code = (e as NodeJS.ErrnoException).code;\n return code === \"EPERM\" || code === \"EBUSY\" || code === \"EACCES\" || code === \"ENOENT\" || code === \"ENOTDIR\";\n}\n\nfunction errText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n\nfunction rel(p: string, base: string): string {\n const r = path.relative(base, p);\n return r && !r.startsWith(\"..\") ? r : p;\n}\n","import type { CompressionState } from \"../types.js\";\nimport { createInitialState } from \"../state.js\";\n\n/**\n * Forward-compat: merge a parsed state with a fresh one so fields added in\n * later kernel versions get sane defaults instead of `undefined`. Nested\n * groups (nudge, stats) are shallow-merged per field so older snapshots\n * keep their values while newer counters default in.\n *\n * Lifted verbatim in behavior from billion-context's proxy mergeState.\n */\nexport function mergeCompressionState(parsed: CompressionState): CompressionState {\n const fresh = createInitialState();\n return {\n blocks: parsed.blocks ?? fresh.blocks,\n messageRefs: parsed.messageRefs ?? fresh.messageRefs,\n nudge: { ...fresh.nudge, ...(parsed.nudge ?? {}) },\n stats: { ...fresh.stats, ...(parsed.stats ?? {}) },\n nextBlockId: parsed.nextBlockId ?? fresh.nextBlockId,\n nextRunId: parsed.nextRunId ?? fresh.nextRunId,\n tokenSnapshot: parsed.tokenSnapshot ?? fresh.tokenSnapshot,\n absorbed: parsed.absorbed ?? fresh.absorbed,\n rules: parsed.rules ?? fresh.rules,\n nextRuleId: parsed.nextRuleId ?? fresh.nextRuleId,\n terminalStreak: parsed.terminalStreak,\n imageFullRestored: parsed.imageFullRestored ?? fresh.imageFullRestored,\n imageShrinks: parsed.imageShrinks ?? fresh.imageShrinks,\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AA2IV,IAAM,aAAN,MAAoB;AAAA,EACd;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,oBAAI,IAA4B;AAAA,EACzC,UAAU,oBAAI,IAAqB;AAAA,EACnC,cAAc,oBAAI,IAA2B;AAAA;AAAA,EAE7C,aAAa,oBAAI,IAAoB;AAAA;AAAA,EAErC,aAAa,oBAAI,IAAoB;AAAA;AAAA,EAE9C,SAAS;AAAA,EAEjB,YAAY,MAA4B;AACpC,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AACpB,SAAK,aAAa,KAAK,cAAc;AACrC,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,MAAM,KAAK,QAAQ,CAAC,QAAQ,SAAS;AAAA,IAAC;AAC3C,SAAK,YAAY,KAAK;AACtB,SAAK,WAAW,KAAK;AACrB,SAAK,aAAa,KA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,WAAW,QAAQ,EAAE,OAAO,IAAI,MAAM,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE,IAAI;AAChF;AASA,SAAS,mBAAmB,GAAqB;AAC7C,QAAM,OAAQ,EAA4B;AAC1C,SAAO,SAAS,WAAW,SAAS,WAAW,SAAS,YAAY,SAAS,YAAY,SAAS;AACtG;AAEA,SAAS,QAAQ,GAAoB;AACjC,SAAO,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;AACpD;AAGA,SAAS,IAAI,GAAW,MAAsB;AAC1C,QAAM,IAAI,KAAK,SAAS,MAAM,CAAC;AAC/B,SAAO,KAAK,CAAC,EAAE,WAAW,IAAI,IAAI,IAAI;AAC1C;;;AC/nBO,SAAS,sBAAsB,QAA4C;AAChF,QAAM,QAAQ,mBAAmB;AACjC,SAAO;AAAA,IACL,QAAQ,OAAO,UAAU,MAAM;AAAA,IAC/B,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,WAAW,OAAO,aAAa,MAAM;AAAA,IACrC,eAAe,OAAO,iBAAiB,MAAM;AAAA,IAC7C,UAAU,OAAO,YAAY,MAAM;AAAA,IACnC,OAAO,OAAO,SAAS,MAAM;AAAA,IAC7B,YAAY,OAAO,cAAc,MAAM;AAAA,IACvC,gBAAgB,OAAO;AAAA,IACvB,mBAAmB,OAAO,qBAAqB,MAAM;AAAA,IACrD,cAAc,OAAO,gBAAgB,MAAM;AAAA,EAC7C;AACF;","names":["rel"]}
1
+ {"version":3,"sources":["../../src/persist/store.ts","../../src/persist/state-merge.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/** Logger callback. Downstream routes it wherever it wants (file, stderr). */\nexport type PersistLogger = (level: \"info\" | \"warn\" | \"error\", msg: string) => void;\n\n/**\n * On-disk record shape. The store owns the envelope (version stamp, save\n * time, id) so atomicity and discovery can rely on it; the payload schema\n * is entirely downstream-owned. `payload` must be JSON-serializable.\n */\nexport interface PersistedEnvelope<T> {\n version: number;\n savedAt: number;\n id: string;\n payload: T;\n}\n\n/** A legacy (pre-envelope) record adopted on load. `version`/`savedAt`\n * preserve the source record's own stamps when present. */\nexport interface LegacyAdoption<T> {\n id: string;\n payload: T;\n version?: number;\n savedAt?: number;\n}\n\n/**\n * Optional record codec: transforms serialized envelopes between the store\n * and disk (e.g. compress and/or encrypt at rest). The store is\n * codec-agnostic — it hands `encode` the exact JSON string it would have\n * written and passes raw file bytes to `decode`, which must return that same\n * JSON string or throw, in which case the file is treated as corrupt\n * (skipped + logged) like any unreadable record. Format detection (magic\n * bytes, plaintext fallback for unencoded legacy files) is the codec's job,\n * so mixed trees of legacy plaintext and encoded files load fine.\n */\nexport interface StateStoreCodec {\n encode(data: string): Buffer | string;\n decode(buf: Buffer): string;\n}\n\nexport interface StateStoreOptions<T> {\n /**\n * Storage root. The kernel deliberately has NO default location: the\n * downstream decides where state lives (CLI dir, XDG data dir, plugin\n * dir, temp dir in tests). All records live under this directory.\n */\n dir: string;\n /**\n * Schema version stamped into every envelope. Owned by the downstream;\n * bump it when the payload shape changes. The store itself never\n * rejects a record over its version — migration policy belongs to the\n * reader.\n */\n version: number;\n /** Debounce window for scheduleSave, ms. Default 500. */\n debounceMs?: number;\n /** Default true. When false, all writes are silent no-ops and loads\n * return empty results. */\n enabled?: boolean;\n log?: PersistLogger;\n /**\n * Relative path (under `dir`) for a record, possibly namespaced into\n * subdirectories (e.g. `openai/host-hash.json`). Default: flat\n * `<sha256(id)[:24]>.json`.\n *\n * Because the path may depend on payload fields the store only learns\n * at write time, single-record loads resolve namespaced files only\n * after loadAll() has discovered them (or the store itself wrote\n * them). The flat default name is always checked as a fallback, so\n * downstreams using a custom relPath should call loadAll() at boot.\n */\n relPath?: (id: string, payload: T) => string;\n /**\n * Adopt records written by an older, pre-envelope schema. Receives the\n * parsed JSON of any file that failed the envelope-shape check; return\n * an adoption to load it as an envelope, or null to skip it. Adopted\n * records are re-persisted in the current envelope format on the next\n * dirty write — files migrate organically, and old files keep loading\n * (same policy billion-context's proxy used for its v1→v3 migration).\n */\n legacy?: (parsed: unknown) => LegacyAdoption<T> | null;\n /**\n * Payload validation on load. Return false to skip a record (foreign\n * schema, corrupt content). Default: envelope-shape check only\n * (string id, non-null payload).\n */\n validate?: (envelope: PersistedEnvelope<T>) => boolean;\n /**\n * Optional codec applied around every write (canonical + spill) and\n * read. See StateStoreCodec. Default: none — files are plain UTF-8 JSON.\n */\n codec?: StateStoreCodec;\n /**\n * Transient-write retry policy (Windows + hostile temp environments).\n * The whole write cycle — mkdir, temp write, rename — is retried with\n * exponential backoff when it fails with a TRANSIENT code: EPERM/EBUSY/\n * EACCES (a lock held by AV scan, search indexer, SMB) or ENOENT/ENOTDIR\n * (the temp file or its directory vanished between create and rename —\n * observed on CI Windows runners where a sweeper deletes freshly\n * created files under %TEMP%). The delay after attempt i is\n * min(retryBaseMs * 2^i, retryMaxMs). Defaults (6 attempts, 50ms base,\n * 1600ms cap) give a ~1.5s window per write path — long enough for most\n * locks to release, short enough not to stall a sync flush. When the\n * window is exhausted the write spills to a side file (see spillPath)\n * instead of dropping the data.\n */\n retryAttempts?: number;\n retryBaseMs?: number;\n retryMaxMs?: number;\n}\n\n/**\n * Crash-safe, debounce-coalescing JSON state store. Mechanism only — lifted\n * from billion-context's proxy SessionStore and generalized:\n *\n * - atomic writes: temp file + rename, so a crash mid-write never leaves a\n * truncated record (readers see either the old or the new file)\n * - whole-cycle retries with exponential backoff on transient fs failures:\n * Windows locks (EPERM/EBUSY/EACCES from AV/indexer/SMB) and vanishing\n * files/dirs (ENOENT/ENOTDIR — a sweeper deleting fresh temp files, seen\n * on CI Windows runners); when the window is exhausted the record spills\n * to a side file (`<name>.fb.json`) instead of being dropped, so a lock\n * held by AV/indexer/SMB never silently loses session data\n * - per-id serialization so concurrent writeNow calls never interleave\n * temp-file names or reorders writes\n * - debounced scheduleSave coalesces bursts into one write; the record is\n * built at WRITE time from a builder, so late mutations are picked up\n * - optional record codec (compress/encrypt at rest): encode on every write,\n * decode on every read; a decode failure is corrupt-file semantics\n * - loadAll skips `.tmp-*` orphans, corrupt JSON, and records whose\n * filename does not match their id — one bad file never blocks boot; it\n * reconciles a canonical record against its spill by savedAt (freshest wins)\n *\n * The store never deletes a record's data. On a successful canonical write it\n * removes a now-stale spill of the SAME id (a duplicate, not distinct data).\n * Session cleanup is a downstream policy decision (kernel position: persisted\n * state should not be deleted opportunistically).\n */\nexport class StateStore<T> {\n readonly enabled: boolean;\n private readonly dir: string;\n private readonly version: number;\n private readonly debounceMs: number;\n private readonly log: PersistLogger;\n private readonly legacyFn?: (parsed: unknown) => LegacyAdoption<T> | null;\n private readonly relPathFn?: (id: string, payload: T) => string;\n private readonly validateFn: (envelope: PersistedEnvelope<T>) => boolean;\n private readonly codec?: StateStoreCodec;\n private readonly retryAttempts: number;\n private readonly retryBaseMs: number;\n private readonly retryMaxMs: number;\n private readonly timers = new Map<string, NodeJS.Timeout>();\n private readonly pending = new Map<string, () => T>();\n private readonly writeChains = new Map<string, Promise<void>>();\n /** id → absolute path, populated by writes and loadAll. */\n private readonly discovered = new Map<string, string>();\n /** id → seq of the last COMMITTED write (sync or async). Async writers\n * capture the seq at snapshot time and re-check it inside their\n * synchronous commit block; a flushSync (or a newer committed write)\n * bumping the seq makes the stale in-flight write abort its commit\n * instead of clobbering the newer on-disk payload. */\n private readonly commitSeq = new Map<string, number>();\n /** id → cumulative write-failure count, for rate-limited alerting. */\n private readonly failCounts = new Map<string, number>();\n /** Monotonic counter for unique temp filenames within a process. */\n private tmpSeq = 0;\n\n constructor(opts: StateStoreOptions<T>) {\n this.dir = opts.dir;\n this.version = opts.version;\n this.debounceMs = opts.debounceMs ?? 500;\n this.enabled = opts.enabled ?? true;\n this.log = opts.log ?? ((_level, _msg) => {});\n this.relPathFn = opts.relPath;\n this.legacyFn = opts.legacy;\n this.validateFn = opts.validate ?? defaultValidate;\n this.codec = opts.codec;\n this.retryAttempts = Math.max(1, opts.retryAttempts ?? 6);\n this.retryBaseMs = Math.max(1, opts.retryBaseMs ?? 50);\n this.retryMaxMs = Math.max(this.retryBaseMs, opts.retryMaxMs ?? 1600);\n }\n\n /** Debounced save. Coalesces bursts; the builder runs at write time, so\n * the freshest state is always persisted. Never throws. */\n scheduleSave(id: string, build: () => T): void {\n if (!this.enabled) return;\n this.pending.set(id, build);\n const existing = this.timers.get(id);\n if (existing) return;\n const timer = setTimeout(() => {\n this.timers.delete(id);\n const builder = this.pending.get(id);\n this.pending.delete(id);\n if (!builder) return;\n // Errors are logged inside writeInner; swallowing here keeps a\n // failed timer write from becoming an unhandledRejection.\n void this.writeNow(id, builder).catch(() => {});\n }, this.debounceMs);\n timer.unref?.();\n this.timers.set(id, timer);\n }\n\n /** Immediate save, serialized per id. Rejects on write failure; a\n * failing write never breaks the chain for the next one. */\n async writeNow(id: string, build: () => T): Promise<void> {\n if (!this.enabled) return;\n // The previous promise may reject (disk full, EPERM) — catch so our\n // chain doesn't break, then run our own write.\n const prev = this.writeChains.get(id) ?? Promise.resolve();\n const next = prev.catch(() => {}).then(() => this.writeInner(id, build));\n this.writeChains.set(id, next);\n // Clean up the chain entry once settled so the Map doesn't grow. The\n // .catch() is load-bearing: .finally() returns a derived promise that\n // nobody else holds — when the chain rejects it would surface as an\n // unhandledRejection and crash the host on default Node settings.\n next\n .finally(() => {\n if (this.writeChains.get(id) === next) this.writeChains.delete(id);\n })\n .catch(() => {});\n return next;\n }\n\n /** Synchronous flush for one id. Used where the caller cannot await\n * (memory eviction, sync shutdown paths). Cancels any pending debounce\n * timer. Returns true on success, false on failure — callers that use\n * the result to drop in-memory state must NOT drop it on failure.\n * Committing bumps the per-id fence so a stale in-flight async write\n * cannot land its older payload after this returns. */\n flushSync(id: string, build: () => T): boolean {\n if (!this.enabled) return true;\n const timer = this.timers.get(id);\n if (timer) {\n clearTimeout(timer);\n this.timers.delete(id);\n this.pending.delete(id);\n }\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n return false;\n }\n const file = this.resolvePath(id, payload);\n const data = this.serialize(id, payload);\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n // Fresh temp name + mkdir per attempt — same reasoning as the\n // async writeInner loop (delete-pending tombstones, swept dirs).\n const tmp = this.tempPath(file);\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n fs.writeFileSync(tmp, data);\n fs.renameSync(tmp, file);\n lastErr = undefined;\n break;\n } catch (e) {\n lastErr = e;\n try {\n fs.unlinkSync(tmp);\n } catch {\n // temp never created or already gone\n }\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n // sync sleep (Atomics.wait) — backoff grows per attempt\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));\n }\n }\n if (!lastErr) {\n this.discovered.set(id, file);\n this.clearFailure(id);\n this.bumpCommit(id);\n this.removeSpillSync(file);\n return true;\n }\n // The canonical write outlived the retry window (Windows lock held by\n // AV/indexer/SMB). Spill to a side file so the data still lands on\n // disk instead of being dropped — loadAll picks the freshest of the\n // canonical and the spill, with its own transient retry window.\n const spill = this.spillPathFor(file);\n let spillPath: string | null = null;\n for (let attempt = 0; attempt < this.retryAttempts && spillPath === null; attempt++) {\n try {\n fs.mkdirSync(path.dirname(spill), { recursive: true });\n fs.writeFileSync(spill, data);\n spillPath = spill;\n } catch (e) {\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));\n }\n }\n if (spillPath) this.discovered.set(id, spillPath);\n if (spillPath) this.bumpCommit(id);\n this.recordFailure(id, lastErr, spillPath);\n return spillPath !== null;\n }\n\n /** Load one record. Checks the discovered path (from a prior\n * write/loadAll), an optional relative-path hint, and the flat default\n * name. Returns null when absent, disabled, corrupt, or rejected by\n * validate. The hint covers namespaced records the store has not\n * discovered (e.g. an evicted session re-requested with its meta,\n * where the path depends on data the store cannot reconstruct from\n * the id alone). */\n loadSync(id: string, hint?: string): PersistedEnvelope<T> | null {\n if (!this.enabled) return null;\n const candidates = [\n this.discovered.get(id),\n hint ? path.join(this.dir, hint) : undefined,\n path.join(this.dir, flatFileNameFor(id)),\n ];\n for (const file of candidates) {\n if (!file) continue;\n const envelope = this.readEnvelope(file);\n if (envelope && envelope.id === id) return envelope;\n }\n return null;\n }\n\n /** Load every record under dir. Populates the discovery map (enables\n * loadSync for namespaced relPaths). Skips corrupt files, `.tmp-*`\n * orphans, and records whose filename does not match their id — one\n * bad file never blocks boot. Never throws. */\n async loadAll(): Promise<Map<string, PersistedEnvelope<T>>> {\n const out = new Map<string, PersistedEnvelope<T>>();\n if (!this.enabled) return out;\n const files = await this.walkJsonFiles(this.dir);\n for (const file of files) {\n const envelope = this.readEnvelope(file);\n if (!envelope) continue;\n const base = path.basename(file);\n const relBase = path.basename(this.relPathOf(envelope.id, envelope.payload));\n const flatBase = flatFileNameFor(envelope.id);\n // A file is a valid record for its envelope id when its name is the\n // canonical name OR a spill (`.fb`) of the canonical name. This lets\n // a spilled record (written while the canonical was locked) be\n // discovered and reconciled against the canonical by savedAt.\n let owner: string | null = null;\n if (base === relBase || base === flatBase) {\n owner = envelope.id;\n } else if (base.endsWith(\".fb.json\")) {\n const canonicalBase = `${base.slice(0, -\".fb.json\".length)}.json`;\n if (canonicalBase === relBase || canonicalBase === flatBase) {\n owner = envelope.id;\n }\n }\n if (owner === null) {\n this.log(\"warn\", `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`);\n continue;\n }\n const existing = out.get(owner);\n if (!existing || envelope.savedAt >= existing.savedAt) {\n out.set(owner, envelope);\n this.discovered.set(owner, file);\n }\n }\n return out;\n }\n\n /** Whether a debounced write is pending for an id. */\n hasPending(id: string): boolean {\n return this.timers.has(id);\n }\n\n /** Ids with a pending debounced write. */\n pendingIds(): string[] {\n return [...this.timers.keys()];\n }\n\n /** Flush every pending debounced write immediately, then drain in-flight\n * writes. For graceful shutdown (SIGTERM/SIGINT). Never rejects. */\n async flushAll(): Promise<void> {\n const ids = this.pendingIds();\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n const builders = new Map<string, () => T>();\n for (const id of ids) {\n const build = this.pending.get(id);\n if (build) builders.set(id, build);\n this.pending.delete(id);\n }\n await Promise.all(\n [...builders.entries()].map(([id, build]) =>\n this.writeNow(id, build).catch((e) => {\n this.log(\"error\", `[persist] shutdown flush failed for ${id}: ${errText(e)}`);\n }),\n ),\n );\n // Drain writes whose timer fired earlier but are still mid-flight.\n await Promise.allSettled([...this.writeChains.values()]);\n }\n\n /** Cancel all pending debounced writes without flushing (tests). */\n cancelAll(): void {\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pending.clear();\n }\n\n private async writeInner(id: string, build: () => T): Promise<void> {\n // Fence point, captured BEFORE build(): from here on, any write that\n // commits (a flushSync re-entering from inside build(), or a newer\n // chained write) bumps the seq and this snapshot is stale.\n const baseSeq = this.commitSeq.get(id) ?? 0;\n let payload: T;\n try {\n payload = build();\n } catch (e) {\n this.log(\"error\", `[persist] builder failed for ${id}: ${errText(e)}`);\n throw e;\n }\n const file = this.resolvePath(id, payload);\n const data = this.serialize(id, payload);\n let lastErr: unknown;\n for (let attempt = 0; attempt < this.retryAttempts; attempt++) {\n // Fresh temp name per attempt: on Windows a failed cleanup can\n // leave the previous name delete-pending, and creating over a\n // tombstoned name fails immediately — reusing it would burn every\n // remaining attempt before the write even happens. mkdir runs per\n // attempt too: a sweeper may have deleted the directory after the\n // previous cycle created it.\n const tmp = this.tempPath(file);\n try {\n await fsp.mkdir(path.dirname(file), { recursive: true });\n await fsp.writeFile(tmp, data);\n // Commit block: fence check + rename in one synchronous run\n // — the event loop cannot interleave a flushSync between the\n // check and the rename, so a stale payload can never land\n // after a newer committed write.\n if ((this.commitSeq.get(id) ?? 0) !== baseSeq) {\n await fsp.unlink(tmp).catch(() => {});\n return;\n }\n try {\n fs.renameSync(tmp, file);\n } catch (e) {\n lastErr = e;\n await fsp.unlink(tmp).catch(() => {});\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n continue;\n }\n this.discovered.set(id, file);\n this.clearFailure(id);\n this.commitSeq.set(id, baseSeq + 1);\n await this.removeSpill(file);\n return;\n } catch (e) {\n lastErr = e;\n // Clean up the .tmp orphan so the next write doesn't collide\n // with it.\n await fsp.unlink(tmp).catch(() => {});\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n }\n }\n // Fenced off before spilling: a newer committed write already owns\n // the disk record for this id — the stale payload is dropped, not\n // spilled (its spill would clobber the newer spill on the same slot).\n if ((this.commitSeq.get(id) ?? 0) !== baseSeq) return;\n // The canonical write outlived the retry window (Windows lock held\n // by AV/indexer/SMB, or a sweeper keeps deleting the fresh temp).\n // Spill to a side file so the data still lands on disk instead of\n // being dropped — loadAll picks the freshest of the canonical and\n // the spill. The spill write gets its own transient retry window for\n // the same reason (observed failing with ENOENT alongside the\n // canonical on CI Windows runners).\n const spill = this.spillPathFor(file);\n let spillPath: string | null = null;\n for (let attempt = 0; attempt < this.retryAttempts && spillPath === null; attempt++) {\n try {\n await fsp.mkdir(path.dirname(spill), { recursive: true });\n // Fence + write synchronously: the spill slot is shared per\n // id, so a late-landing stale spill would overwrite a newer\n // spill exactly like the canonical case above.\n if ((this.commitSeq.get(id) ?? 0) !== baseSeq) return;\n fs.writeFileSync(spill, data);\n spillPath = spill;\n } catch (e) {\n if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;\n const { promise, resolve } = Promise.withResolvers<void>();\n setTimeout(resolve, this.backoffMs(attempt));\n await promise;\n }\n }\n if (spillPath) {\n this.discovered.set(id, spillPath);\n this.commitSeq.set(id, baseSeq + 1);\n }\n this.recordFailure(id, lastErr, spillPath);\n throw lastErr;\n }\n\n private envelope(id: string, payload: T): PersistedEnvelope<T> {\n return { version: this.version, savedAt: Date.now(), id, payload };\n }\n\n /** Serialize an envelope for disk, applying the optional codec. Strings\n * are written as UTF-8 (the fs default); Buffer results pass through as\n * raw bytes. */\n private serialize(id: string, payload: T): Buffer | string {\n const json = JSON.stringify(this.envelope(id, payload));\n return this.codec ? this.codec.encode(json) : json;\n }\n\n /** Absolute path for a record: custom relPath (guarded against path\n * escape) or the flat hash default. */\n private resolvePath(id: string, payload: T): string {\n return path.join(this.dir, this.relPathOf(id, payload));\n }\n\n private relPathOf(id: string, payload: T): string {\n const custom = this.relPathFn?.(id, payload);\n if (!custom) return flatFileNameFor(id);\n const rel = path.normalize(custom);\n if (path.isAbsolute(rel) || rel.split(/[\\\\/]+/).includes(\"..\")) {\n this.log(\"warn\", `[persist] relPath for ${id} escapes dir; using flat name`);\n return flatFileNameFor(id);\n }\n return rel;\n }\n\n /** Unique temp file next to the destination (same dir ⇒ same volume ⇒\n * rename is atomic). Prefixed `.tmp-` so loadAll skips orphans. */\n private tempPath(dest: string): string {\n const seq = this.tmpSeq++;\n return path.join(path.dirname(dest), `.tmp-${path.basename(dest, \".json\")}-${process.pid}-${seq}`);\n }\n\n private backoffMs(attempt: number): number {\n return Math.min(this.retryBaseMs * 2 ** attempt, this.retryMaxMs);\n }\n\n /** Side file for a record whose canonical write keeps failing: the\n * canonical name with a `.fb` (fallback) infix, e.g. `a.json` →\n * `a.fb.json`. One slot per id, overwritten on each spill, so a stuck\n * lock never accumulates files. Ends in `.json` so loadAll discovers it. */\n private spillPathFor(file: string): string {\n const base = path.basename(file);\n const dot = base.lastIndexOf(\".\");\n const stem = dot > 0 ? base.slice(0, dot) : base;\n const ext = dot > 0 ? base.slice(dot) : \".json\";\n return path.join(path.dirname(file), `${stem}.fb${ext}`);\n }\n\n /** Remove a stale spill after a successful canonical write (best-effort). */\n private async removeSpill(file: string): Promise<void> {\n await fsp.unlink(this.spillPathFor(file)).catch(() => {});\n }\n\n /** Advance the per-id commit fence after a successful synchronous\n * commit, fencing off any in-flight async write holding an older\n * snapshot. */\n private bumpCommit(id: string): void {\n this.commitSeq.set(id, (this.commitSeq.get(id) ?? 0) + 1);\n }\n\n private removeSpillSync(file: string): void {\n try {\n fs.unlinkSync(this.spillPathFor(file));\n } catch {\n // no spill or still locked — loadAll reconciles by savedAt\n }\n }\n\n /** Rate-limited failure alerting: log on the first failure and at each\n * power-of-two count (1,2,4,8,…), so a long lock yields ~log2(N) lines\n * instead of one per write. Includes the spill path so the operator can\n * see where the data landed. */\n private recordFailure(id: string, err: unknown, spillPath: string | null): void {\n const count = (this.failCounts.get(id) ?? 0) + 1;\n this.failCounts.set(id, count);\n const alertAt = count === 1 || (count >= 2 && (count & (count - 1)) === 0);\n if (!alertAt) return;\n const where = spillPath\n ? `; data spilled to ${rel(spillPath, this.dir)}`\n : \"; SPILLOVER ALSO FAILED — data at risk\";\n this.log(count === 1 ? \"error\" : \"warn\", `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`);\n }\n\n private clearFailure(id: string): void {\n this.failCounts.delete(id);\n }\n\n /** Parse + validate one file. Corrupt or invalid records return null\n * (logged) instead of throwing — load paths must never block boot. */\n private readEnvelope(file: string): PersistedEnvelope<T> | null {\n let parsed: unknown;\n try {\n const buf = fs.readFileSync(file);\n const text = this.codec ? this.codec.decode(buf) : buf.toString(\"utf8\");\n parsed = JSON.parse(text);\n } catch (e) {\n // A missing candidate path is an expected miss (loadSync probes);\n // only genuinely unreadable/corrupt files get logged.\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") {\n this.log(\"warn\", `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`);\n }\n return null;\n }\n if (isEnvelopeLike(parsed)) {\n if (!this.validateFn(parsed as PersistedEnvelope<T>)) {\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n return parsed as PersistedEnvelope<T>;\n }\n const adopted = this.adoptLegacy(parsed);\n if (adopted) return adopted;\n this.log(\"warn\", `[persist] skipping invalid record ${rel(file, this.dir)}`);\n return null;\n }\n\n /** Wrap a legacy (pre-envelope) record as an envelope via the `legacy`\n * hook, then validate the adopted payload like any other. */\n private adoptLegacy(parsed: unknown): PersistedEnvelope<T> | null {\n const adoption = this.legacyFn ? this.legacyFn(parsed) : null;\n if (!adoption || typeof adoption.id !== \"string\" || adoption.id.length === 0 || adoption.payload == null) {\n return null;\n }\n const source = parsed as Partial<PersistedEnvelope<T>>;\n const envelope: PersistedEnvelope<T> = {\n version: adoption.version ?? source.version ?? this.version,\n savedAt: adoption.savedAt ?? source.savedAt ?? 0,\n id: adoption.id,\n payload: adoption.payload,\n };\n if (!this.validateFn(envelope)) return null;\n return envelope;\n }\n\n /** Iterative recursive walk (no readdir-recursive dependency), skipping\n * `.tmp-*` names and non-.json files. */\n private async walkJsonFiles(root: string): Promise<string[]> {\n const out: string[] = [];\n const queue: string[] = [root];\n while (queue.length > 0) {\n const dir = queue.pop()!;\n let dirents: fs.Dirent[];\n try {\n dirents = await fsp.readdir(dir, { withFileTypes: true });\n } catch {\n continue; // missing dir → no records yet\n }\n for (const d of dirents) {\n if (d.name.startsWith(\".tmp-\")) continue;\n const full = path.join(dir, d.name);\n if (d.isDirectory()) queue.push(full);\n else if (d.isFile() && d.name.endsWith(\".json\")) out.push(full);\n }\n }\n return out;\n }\n}\n\nfunction defaultValidate<T>(envelope: PersistedEnvelope<T>): boolean {\n return typeof envelope.id === \"string\" && envelope.id.length > 0 && envelope.payload != null;\n}\n\nfunction isEnvelopeLike(value: unknown): value is PersistedEnvelope<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const v = value as Partial<PersistedEnvelope<unknown>>;\n return typeof v.id === \"string\" && \"payload\" in v;\n}\n\n/** Deterministic flat filename: `<sha256(id)[:24]>.json`. Truncated hash —\n * 96 bits keeps collisions unreachable for realistic id counts, and short\n * names stay greppable. */\nexport function flatFileNameFor(id: string): string {\n return createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\").slice(0, 24) + \".json\";\n}\n\n/** Transient fs failure codes worth retrying the whole write cycle for:\n * - EPERM/EBUSY/EACCES — a lock held on the file/dir (AV scan, search\n * indexer, SMB); releases within the backoff window.\n * - ENOENT/ENOTDIR — the temp file or its directory VANISHED between\n * create and rename (a sweeper deleting fresh files under %TEMP%, seen\n * on CI Windows runners), or a delete-pending tombstone from the same\n * sweep. Recreating the dir + rewriting a fresh temp heals it. */\nfunction isTransientFsError(e: unknown): boolean {\n const code = (e as NodeJS.ErrnoException).code;\n return code === \"EPERM\" || code === \"EBUSY\" || code === \"EACCES\" || code === \"ENOENT\" || code === \"ENOTDIR\";\n}\n\nfunction errText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n\nfunction rel(p: string, base: string): string {\n const r = path.relative(base, p);\n return r && !r.startsWith(\"..\") ? r : p;\n}\n","import type { CompressionState } from \"../types.js\";\nimport { createInitialState } from \"../state.js\";\n\n/**\n * Forward-compat: merge a parsed state with a fresh one so fields added in\n * later kernel versions get sane defaults instead of `undefined`. Nested\n * groups (nudge, stats) are shallow-merged per field so older snapshots\n * keep their values while newer counters default in.\n *\n * Lifted verbatim in behavior from billion-context's proxy mergeState.\n */\nexport function mergeCompressionState(parsed: CompressionState): CompressionState {\n const fresh = createInitialState();\n return {\n blocks: parsed.blocks ?? fresh.blocks,\n messageRefs: parsed.messageRefs ?? fresh.messageRefs,\n nudge: { ...fresh.nudge, ...(parsed.nudge ?? {}) },\n stats: { ...fresh.stats, ...(parsed.stats ?? {}) },\n nextBlockId: parsed.nextBlockId ?? fresh.nextBlockId,\n nextRunId: parsed.nextRunId ?? fresh.nextRunId,\n tokenSnapshot: parsed.tokenSnapshot ?? fresh.tokenSnapshot,\n absorbed: parsed.absorbed ?? fresh.absorbed,\n rules: parsed.rules ?? fresh.rules,\n nextRuleId: parsed.nextRuleId ?? fresh.nextRuleId,\n terminalStreak: parsed.terminalStreak,\n imageFullRestored: parsed.imageFullRestored ?? fresh.imageFullRestored,\n imageShrinks: parsed.imageShrinks ?? fresh.imageShrinks,\n };\n}\n"],"mappings":";;;;;AAAA,SAAS,kBAAkB;AAC3B,OAAO,QAAQ;AACf,OAAO,SAAS;AAChB,OAAO,UAAU;AA2IV,IAAM,aAAN,MAAoB;AAAA,EACd;AAAA,EACQ;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAS,oBAAI,IAA4B;AAAA,EACzC,UAAU,oBAAI,IAAqB;AAAA,EACnC,cAAc,oBAAI,IAA2B;AAAA;AAAA,EAE7C,aAAa,oBAAI,IAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrC,YAAY,oBAAI,IAAoB;AAAA;AAAA,EAEpC,aAAa,oBAAI,IAAoB;AAAA;AAAA,EAE9C,SAAS;AAAA,EAEjB,YAAY,MAA4B;AACpC,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AACpB,SAAK,aAAa,KAAK,cAAc;AACrC,SAAK,UAAU,KAAK,WAAW;AAC/B,SAAK,MAAM,KAAK,QAAQ,CAAC,QAAQ,SAAS;AAAA,IAAC;AAC3C,SAAK,YAAY,KAAK;AACtB,SAAK,WAAW,KAAK;AACrB,SAAK,aAAa,KAAK,YAAY;AACnC,SAAK,QAAQ,KAAK;AAClB,SAAK,gBAAgB,KAAK,IAAI,GAAG,KAAK,iBAAiB,CAAC;AACxD,SAAK,cAAc,KAAK,IAAI,GAAG,KAAK,eAAe,EAAE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,QAAQ,mBAAmB;AACjC,SAAO;AAAA,IACL,QAAQ,OAAO,UAAU,MAAM;AAAA,IAC/B,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,OAAO,EAAE,GAAG,MAAM,OAAO,GAAI,OAAO,SAAS,CAAC,EAAG;AAAA,IACjD,aAAa,OAAO,eAAe,MAAM;AAAA,IACzC,WAAW,OAAO,aAAa,MAAM;AAAA,IACrC,eAAe,OAAO,iBAAiB,MAAM;AAAA,IAC7C,UAAU,OAAO,YAAY,MAAM;AAAA,IACnC,OAAO,OAAO,SAAS,MAAM;AAAA,IAC7B,YAAY,OAAO,cAAc,MAAM;AAAA,IACvC,gBAAgB,OAAO;AAAA,IACvB,mBAAmB,OAAO,qBAAqB,MAAM;AAAA,IACrD,cAAc,OAAO,gBAAgB,MAAM;AAAA,EAC7C;AACF;","names":["rel"]}
@@ -148,6 +148,12 @@ export declare class StateStore<T> {
148
148
  private readonly writeChains;
149
149
  /** id → absolute path, populated by writes and loadAll. */
150
150
  private readonly discovered;
151
+ /** id → seq of the last COMMITTED write (sync or async). Async writers
152
+ * capture the seq at snapshot time and re-check it inside their
153
+ * synchronous commit block; a flushSync (or a newer committed write)
154
+ * bumping the seq makes the stale in-flight write abort its commit
155
+ * instead of clobbering the newer on-disk payload. */
156
+ private readonly commitSeq;
151
157
  /** id → cumulative write-failure count, for rate-limited alerting. */
152
158
  private readonly failCounts;
153
159
  /** Monotonic counter for unique temp filenames within a process. */
@@ -162,7 +168,9 @@ export declare class StateStore<T> {
162
168
  /** Synchronous flush for one id. Used where the caller cannot await
163
169
  * (memory eviction, sync shutdown paths). Cancels any pending debounce
164
170
  * timer. Returns true on success, false on failure — callers that use
165
- * the result to drop in-memory state must NOT drop it on failure. */
171
+ * the result to drop in-memory state must NOT drop it on failure.
172
+ * Committing bumps the per-id fence so a stale in-flight async write
173
+ * cannot land its older payload after this returns. */
166
174
  flushSync(id: string, build: () => T): boolean;
167
175
  /** Load one record. Checks the discovered path (from a prior
168
176
  * write/loadAll), an optional relative-path hint, and the flat default
@@ -207,6 +215,10 @@ export declare class StateStore<T> {
207
215
  private spillPathFor;
208
216
  /** Remove a stale spill after a successful canonical write (best-effort). */
209
217
  private removeSpill;
218
+ /** Advance the per-id commit fence after a successful synchronous
219
+ * commit, fencing off any in-flight async write holding an older
220
+ * snapshot. */
221
+ private bumpCommit;
210
222
  private removeSpillSync;
211
223
  /** Rate-limited failure alerting: log on the first failure and at each
212
224
  * power-of-two count (1,2,4,8,…), so a long lock yields ~log2(N) lines
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/persist/store.ts"],"names":[],"mappings":"AAKA,8EAA8E;AAC9E,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;AAEpF;;;;GAIG;AACH,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,CAAC,CAAC;CACd;AAED;2DAC2D;AAC3D,MAAM,WAAW,cAAc,CAAC,CAAC;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,CAAC,CAAC;IACX,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,eAAe;IAC5B,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IACtC,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAChC;;;;OAIG;IACH,GAAG,EAAE,MAAM,C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
9
  export declare function summaryMessageId(blockId: string): string;
10
10
  export declare function isSummaryMessageId(id: string): boolean;
11
+ /**
12
+ * Base id of a message id: everything before the first `#`. Sub-id
13
+ * projections (`base#callId`, `base#r0`, …) are alternate renderings of the
14
+ * same original message, so coverage is decided per original message — id
15
+ * comparisons normalize to the base (issue #231).
16
+ */
17
+ export declare function baseIdOf(id: string): string;
18
+ /**
19
+ * True when `id` falls under any covered original message, regardless of
20
+ * which projection form the block recorded and which the current view emits.
21
+ * `coveredBases` must be the set of `baseIdOf(c)` over the covered ids,
22
+ * built once per pass (O(1) per message instead of a scan). The exact
23
+ * membership test is subsumed: a covered id's own base is in the set.
24
+ */
25
+ export declare function isCovered(id: string, coveredBases: Set<string>): boolean;
11
26
  /**
12
27
  * True when a message is a rendered block summary (the exact shape prune
13
28
  * emits). The id prefix alone is not sufficient — a host-authored message
@@ -1 +1 @@
1
- {"version":3,"file":"prune.d.ts","sourceRoot":"","sources":["../src/prune.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEhE,eAAO,MAAM,cAAc,sCAAsC,CAAC;AAOlE;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,GAAG,MAAM,GAAG,aAAa,CAAC,GACxD,OAAO,CAMT;AAED,MAAM,WAAW,YAAY;IAC3B,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,wBAAgB,KAAK,CACnB,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,YAAiB,GACzB,WAAW,EAAE,CA4Bf"}
1
+ {"version":3,"file":"prune.d.ts","sourceRoot":"","sources":["../src/prune.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEhE,eAAO,MAAM,cAAc,sCAAsC,CAAC;AAOlE;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAExD;AAED,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,CAG3C;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,OAAO,CAExE;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,IAAI,CAAC,WAAW,EAAE,IAAI,GAAG,MAAM,GAAG,aAAa,CAAC,GACxD,OAAO,CAMT;AAED,MAAM,WAAW,YAAY;IAC3B,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED,wBAAgB,KAAK,CACnB,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,YAAiB,GACzB,WAAW,EAAE,CAiCf"}
@@ -1 +1 @@
1
- {"version":3,"file":"report.d.ts","sourceRoot":"","sources":["../src/report.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAoB,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAsGlF;;2EAE2E;AAC3E,MAAM,WAAW,gBAAgB;IAC7B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,mBAAmB;IAChC,KAAK,CAAC,EAAE,YAAY,GAAG,cAAc,CAAC;IACtC,IAAI,CAAC,EAAE,QAAQ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ClC,OAAO,GAAE,mBAAwB,GAClC,MAAM,CAyBR;AAqOD,wBAAgB,UAAU,CACtB,KAAK,EAAE,gBAAgB,EACvB,OAAO,CAAC,EAAE,MAAM,GACjB,MAAM,CA6BR"}
@@ -1 +1 @@
1
- {"version":3,"file":"hybrid.d.ts","sourceRoot":"","sources":["../../../src/search/algorithms/hybrid.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAA0B,MAAM,aAAa,CAAC;AAwB3E,eAAO,MAAM,eAAe,EAAE,eAe7B,CAAC"}
1
+ {"version":3,"file":"hybrid.d.ts","sourceRoot":"","sources":["../../../src/search/algorithms/hybrid.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAA0B,MAAM,aAAa,CAAC;AAwB3E,eAAO,MAAM,eAAe,EAAE,eAgB7B,CAAC"}
@@ -4,16 +4,38 @@
4
4
  * A search over the compressed history re-scores the SAME immutable docs on
5
5
  * every call — compressed block summaries and folded message text never
6
6
  * change. Without this cache, every search_context call re-tokenized the
7
- * entire corpus (segmenter CJK pass ≈ 0.3s/MB cold) plus re-lowercased it
8
- * and rebuilt the bigram set for each channel: a 5MB session cost ~3s PER
9
- * CALL, growing linearly with session length. With the cache the corpus is
10
- * processed once; later searches are O(docs × query-terms).
7
+ * entire corpus (segmenter pass ≈ 0.1–0.6s/MB cold, content-dependent) plus
8
+ * re-lowercased it and rebuilt the bigram set for each channel: a 5MB session
9
+ * cost seconds PER CALL, growing linearly with session length. With the cache
10
+ * the corpus is processed once; later searches are O(docs × query-terms).
11
11
  *
12
- * Keyed by doc text (immutable). Bounded by total cached source chars —
13
- * oldest docs are evicted when the cap is exceeded, so a long-lived
14
- * process serving many sessions cannot grow unboundedly. Hosts that want to
15
- * release the memory eagerly on session shutdown/switch can call
16
- * clearDocFeatures() (optional: the cap already bounds it).
12
+ * Keyed by doc text (immutable), bounded by total cached SOURCE CHARS. Eviction
13
+ * is least-recently-used: a hit re-inserts the doc at the tail, so the docs a
14
+ * host keeps re-touching are retained. LRU helps when access is HETEROGENEOUS
15
+ * (a hot subset across many queries; a long-lived multi-session process). It
16
+ * does NOT help when every call re-scans the ENTIRE corpus below the cap — no
17
+ * hot subset exists, the window slides past every doc each call, and
18
+ * (corpus − cap) is re-tokenized every time.
19
+ *
20
+ * Sizing consequence: if your corpus exceeds the cap and each search rescans
21
+ * it whole, the ONLY setting that stops re-tokenization is
22
+ * setDocCacheCap(≥ corpus) (or Infinity). Do NOT lower the cap to save memory
23
+ * there — it trades bounded memory for a full re-tokenize of the excess on
24
+ * EVERY call. The default (8MB) suits hosts running many sessions that cannot
25
+ * afford to pin one corpus.
26
+ *
27
+ * The cap is in SOURCE CHARS, a loose proxy for retained heap: feature memory
28
+ * scales with DISTINCT token/bigram count, content-dependent (≈ 2×–49× per
29
+ * source char, latin prose → high-entropy CJK). The cap bounds billed chars,
30
+ * not a hard memory limit.
31
+ *
32
+ * The cap is MODULE-GLOBAL — setDocCacheCap() sets process-wide state shared
33
+ * by every acp-kernel consumer in the process. Fine while one consumer runs
34
+ * per process; a per-scope cache (keyed by doc ref) would let a host scope a
35
+ * cap to one session instead (see #227).
36
+ *
37
+ * Hosts that want to release the memory eagerly on session shutdown/switch
38
+ * can call clearDocFeatures() (optional: the cap already bounds it).
17
39
  */
18
40
  export interface DocFeatures {
19
41
  /** Stemmed term frequencies (BM25 channel). */
@@ -30,7 +52,9 @@ export declare function docFeatures(text: string): DocFeatures;
30
52
  export declare function clearDocFeatures(): void;
31
53
  /**
32
54
  * Set the cache cap in source chars. Docs larger than the cap are never
33
- * cached. Also used by tests to exercise eviction.
55
+ * cached. Pass a value ≥ the corpus size (or Infinity) to cache the whole
56
+ * corpus — a single-session host then avoids re-tokenizing on every call.
57
+ * Also used by tests to exercise eviction.
34
58
  */
35
59
  export declare function setDocCacheCap(chars: number): void;
36
60
  /** Cache occupancy — for diagnostics. */
@@ -1 +1 @@
1
- {"version":3,"file":"doc-cache.d.ts","sourceRoot":"","sources":["../../src/search/doc-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAIH,MAAM,WAAW,WAAW;IACxB,+CAA+C;IAC/C,EAAE,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxB,oDAAoD;IACpD,GAAG,EAAE,MAAM,CAAC;IACZ,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,sDAAsD;IACtD,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACtB;AAeD,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAcrD;AAED,kEAAkE;AAClE,wBAAgB,gBAAgB,IAAI,IAAI,CAGvC;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAOlD;AAED,yCAAyC;AACzC,wBAAgB,YAAY,IAAI;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAEjE"}
1
+ {"version":3,"file":"doc-cache.d.ts","sourceRoot":"","sources":["../../src/search/doc-cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAIH,MAAM,WAAW,WAAW;IACxB,+CAA+C;IAC/C,EAAE,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxB,oDAAoD;IACpD,GAAG,EAAE,MAAM,CAAC;IACZ,qDAAqD;IACrD,KAAK,EAAE,MAAM,CAAC;IACd,sDAAsD;IACtD,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACtB;AAeD,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,WAAW,CAmBrD;AAED,kEAAkE;AAClE,wBAAgB,gBAAgB,IAAI,IAAI,CAGvC;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAOlD;AAED,yCAAyC;AACzC,wBAAgB,YAAY,IAAI;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAEjE"}
@@ -1 +1 @@
1
- {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEhE,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,gBAAgB,CAAC;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,GACtB,UAAU,CAiFZ"}
1
+ {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../src/sync.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEhE,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,gBAAgB,CAAC;IACxB,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,GACtB,UAAU,CAmFZ"}
package/dist/types.d.ts CHANGED
@@ -239,6 +239,15 @@ export interface CompressionState {
239
239
  imageFullRestored?: string[];
240
240
  /** Arrival-time downsample records (#353). Optional: pre-feature persisted states lack it. */
241
241
  imageShrinks?: ImageShrinkRecord[];
242
+ /** Padded refs (mNNNNN) of HIDDEN orphan compress call/result messages — the
243
+ * orphans beyond the keep-last-N window that hide-consumed removed from the
244
+ * visible view this turn. Written every processTurn by the hide-compress-calls
245
+ * node so boundary resolution can snap a range endpoint that lands on such a
246
+ * hidden-but-intact artifact to its adjacent visible message instead of
247
+ * dead-ending the whole range (#396). A drifted/dangling ref (#387) is NOT in
248
+ * this set and keeps the clear "cannot be anchored" error. Optional for
249
+ * pre-feature persisted states. */
250
+ hiddenOrphanRefs?: string[];
242
251
  nextBlockId: number;
243
252
  nextRunId: number;
244
253
  }
@@ -267,7 +276,7 @@ export interface NudgeConfig {
267
276
  minGrowthFloor: number;
268
277
  /** Ratio for growth floor: max(minGrowthFloor, minGrowthRatio × growthTokens). Default 0.45. */
269
278
  minGrowthRatio: number;
270
- /** Emergency override: always nudge when usage ≥ this fraction. Default 0.98 (98%). */
279
+ /** Emergency override: always nudge when usage ≥ this fraction. Default 0.95 (95%). */
271
280
  emergencyThresholdPct: number;
272
281
  /** Growth multiplier for the tier-2 trigger: T2 distillation fires when T2
273
282
  * pending ≥ nudgeGrowthTokens × this multiplier AND T2 > T1 effective.
@@ -456,6 +465,11 @@ export interface ApplyCompressionResult {
456
465
  * The compression still succeeded; the host should surface these to the
457
466
  * model so it understands what was skipped. */
458
467
  warnings: string[];
468
+ /** Kernel-side rewrites of the model's input (e.g. reversed refs
469
+ * normalized to ascending order), for hosts to render into the tool
470
+ * result so the model knows its input was changed (#310). Omitted when
471
+ * empty. */
472
+ notes?: string[];
459
473
  };
460
474
  }
461
475
  export interface ProcessTurnResult {