acp-kernel 0.0.79 → 0.0.80-pr.334.200

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  createInitialState
3
- } from "../chunk-UX4LINT7.js";
3
+ } from "../chunk-5TQA7ZQM.js";
4
4
 
5
5
  // src/persist/store.ts
6
6
  import { createHash } from "crypto";
@@ -450,6 +450,8 @@ function mergeCompressionState(parsed) {
450
450
  nextRunId: parsed.nextRunId ?? fresh.nextRunId,
451
451
  tokenSnapshot: parsed.tokenSnapshot ?? fresh.tokenSnapshot,
452
452
  absorbed: parsed.absorbed ?? fresh.absorbed,
453
+ rules: parsed.rules ?? fresh.rules,
454
+ nextRuleId: parsed.nextRuleId ?? fresh.nextRuleId,
453
455
  terminalStreak: parsed.terminalStreak
454
456
  };
455
457
  }
@@ -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 terminalStreak: parsed.terminalStreak,\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,IAA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Aa,MAAM;AAAA,IACrC,eAAe,OAAO,iBAAiB,MAAM;AAAA,IAC7C,UAAU,OAAO,YAAY,MAAM;AAAA,IACnC,gBAAgB,OAAO;AAAA,EACzB;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 → 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 };\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,SAA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AAC;AAGpD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAahF"}
1
+ {"version":3,"file":"state-merge.d.ts","sourceRoot":"","sources":["../../src/persist/state-merge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGpD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,gBAAgB,GAAG,gBAAgB,CAehF"}
@@ -2,9 +2,11 @@ import type { Config, CoreMessage } from "./types.js";
2
2
  /** Tools that are ALWAYS protected, regardless of user config. These are ACP's
3
3
  * own metadata tools whose records must remain in context: compress calls
4
4
  * carry the summaries that decompress/search rely on, and the system prompt
5
- * treats past compress calls as load-bearing metadata. Letting them be
5
+ * treats past compress calls as load-bearing metadata. acp_rule calls record
6
+ * persistent user rules that are re-injected every turn — compressing them
7
+ * away would silently lose what the rules state. Letting any of these be
6
8
  * compressed away breaks decompress and the "summary is historical" contract. */
7
- export declare const ALWAYS_PROTECTED_TOOLS: readonly ["compress"];
9
+ export declare const ALWAYS_PROTECTED_TOOLS: readonly ["compress", "acp_rule"];
8
10
  /** Tool results that must NEVER participate in the soft-protected recent zone
9
11
  * (preserveRecentMessages / preserveRecentTokens / last user message).
10
12
  *
@@ -39,4 +41,21 @@ export declare function collectProtectedToolCallIds(messages: CoreMessage[], con
39
41
  /** Like isMessageProtected, but also matches tool-results by toolCallId against
40
42
  * the protected call set. Use when you have the full message list available. */
41
43
  export declare function isMessageProtectedWithPairing(msg: CoreMessage, config: Pick<Config, "protectedTools" | "isToolProtected">, protectedCallIds: Set<string>): boolean;
44
+ /** "Latest only" protection set: for each protectedLatestTools pattern, the
45
+ * LAST tool-call matching it (in message order) plus its paired result. Older
46
+ * instances of the same tool stay compressible. Use for cumulative-snapshot
47
+ * tools (e.g. todo_list) where only the newest result is the source of truth
48
+ * and every older result is strictly redundant.
49
+ *
50
+ * `callIds` holds the latest calls' toolCallIds (pairing covers the result
51
+ * half, including results projected without a toolName); `msgIds` holds
52
+ * latest calls that lack a toolCallId (pairing impossible — protect by id). */
53
+ export interface LatestProtected {
54
+ callIds: Set<string>;
55
+ msgIds: Set<string>;
56
+ }
57
+ export declare function collectLatestProtected(messages: CoreMessage[], config: Pick<Config, "protectedLatestTools">): LatestProtected;
58
+ /** True when msg is a latest-protected tool-call, or the tool-result paired to
59
+ * one (by toolCallId). */
60
+ export declare function isMessageLatestProtected(msg: CoreMessage, latest: LatestProtected): boolean;
42
61
  //# sourceMappingURL=protected.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"protected.d.ts","sourceRoot":"","sources":["../src/protected.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEtD;;;;kFAIkF;AAClF,eAAO,MAAM,sBAAsB,uBAAwB,CAAC;AAE5D;;;;;;;;;;;;;;;;;;gEAkBgE;AAChE,eAAO,MAAM,2BAA2B,2DAK9B,CAAC;AAEX;;mEAEmE;AACnE,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAM/D;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAK3E;AAED,wBAAgB,kBAAkB,CAChC,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,gBAAgB,GAAG,iBAAiB,CAAC,GACzD,OAAO,CAsBT;AAED;;;8DAG8D;AAC9D,wBAAgB,2BAA2B,CACzC,QAAQ,EAAE,WAAW,EAAE,EACvB,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,gBAAgB,GAAG,iBAAiB,CAAC,GACzD,GAAG,CAAC,MAAM,CAAC,CAQb;AAED;iFACiF;AACjF,wBAAgB,6BAA6B,CAC3C,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,IAAI,CAAC,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B,CACpC,QAAQ,EAAE,WAAW,EAAE,EACvB,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,sBAAsB,CAAC,GAC3C,eAAe,CAqBjB;AAED;2BAC2B;AAC3B,wBAAgB,wBAAwB,CACtC,GAAG,EAAE,WAAW,EAChB,MAAM,EAAE,eAAe,GACtB,OAAO,CAUT"}
@@ -1 +1 @@
1
- {"version":3,"file":"recommend.d.ts","sourceRoot":"","sources":["../src/recommend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,iBAAiB,EACjB,MAAM,EACN,aAAa,EACb,WAAW,EAEZ,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAiBnD,wBAAgB,aAAa,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAE3D;AAgBD;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,EACvB,MAAM,EAAE,MAAM,EACd,WAAW,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAA2B,GACzD,GAAG,CAAC,MAAM,CAAC,CAwDb;AAID;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,EACvB,MAAM,EAAE,MAAM,EACd,iBAAiB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAC/B,WAAW,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAA2B,GACzD,aAAa,CAqLf;AAsCD;;;;;;;;;;gFAUgF;AAChF,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,iBAAiB,EAAE,EAC3B,QAAQ,EAAE,MAAM,GACf,iBAAiB,EAAE,CAmBrB"}
1
+ {"version":3,"file":"recommend.d.ts","sourceRoot":"","sources":["../src/recommend.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EACV,iBAAiB,EACjB,MAAM,EACN,aAAa,EACb,WAAW,EAEZ,MAAM,YAAY,CAAC;AACpB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAmBnD,wBAAgB,aAAa,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAE3D;AAgBD;;;;;;;;;GASG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,EACvB,MAAM,EAAE,MAAM,EACd,WAAW,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAA2B,GACzD,GAAG,CAAC,MAAM,CAAC,CAwDb;AAID;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,QAAQ,EAAE,WAAW,EAAE,EACvB,KAAK,EAAE,gBAAgB,EACvB,MAAM,EAAE,MAAM,EACd,iBAAiB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,EAC/B,WAAW,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,MAA2B,GACzD,aAAa,CA6Lf;AAsCD;;;;;;;;;;gFAUgF;AAChF,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,iBAAiB,EAAE,EAC3B,QAAQ,EAAE,MAAM,GACf,iBAAiB,EAAE,CAmBrB"}
@@ -0,0 +1,59 @@
1
+ import type { CompressionState, Config, RuleRecord } from "./types.js";
2
+ /**
3
+ * Persistent rules ("acp_rule") — durable reminders recorded for future turns
4
+ * (kernel #282, from billion-context-pi#433). The adapter injects
5
+ * formatRulesForPrompt(state) into the system prompt every turn, and acp_rule
6
+ * tool calls/results are hard-protected from compression
7
+ * (ALWAYS_PROTECTED_TOOLS), so a recorded rule survives context compaction.
8
+ *
9
+ * State-mutating helpers: hosts hold live CompressionState objects (a session's
10
+ * single state instance) and discard returned states — these helpers update
11
+ * `state` in place and return only an ok/error result. All mutations stay
12
+ * shallow-copy-free: the rules array is replaced (not spliced) so hosts that
13
+ * captured listRules() output keep a stable snapshot.
14
+ */
15
+ export declare const RULE_TOOL_NAME = "acp_rule";
16
+ export interface RuleLimits {
17
+ maxRules: number;
18
+ maxRuleChars: number;
19
+ }
20
+ export declare const DEFAULT_RULE_LIMITS: Readonly<RuleLimits>;
21
+ export declare const RULES_USAGE_PROMPT: string;
22
+ export declare function listRules(state: CompressionState): RuleRecord[];
23
+ /** Effective limits: `config.rules` overrides on top of the defaults. Hosts
24
+ * resolving per-request configs pass the resolved Config here (billion-context
25
+ * three-level merge / pi acp.json both land in Config.rules). */
26
+ export declare function resolveRuleLimits(config?: Pick<Config, "rules">): RuleLimits;
27
+ /** Pure (unlike the mutating addRule/removeRule/clearRules): returns the id
28
+ * the next addRule call would issue, without touching state. Never re-issues
29
+ * an issued id, even after removal: the counter is monotonic and the
30
+ * hand-crafted-state guard backfills it from the highest surviving id. */
31
+ export declare function allocateRuleId(state: CompressionState): string;
32
+ export type AddRuleResult = {
33
+ ok: true;
34
+ rule: RuleRecord;
35
+ } | {
36
+ ok: false;
37
+ error: string;
38
+ };
39
+ export declare function addRule(state: CompressionState, text: string, limits?: Partial<RuleLimits>): AddRuleResult;
40
+ export type RemoveRuleResult = {
41
+ ok: true;
42
+ rule: RuleRecord;
43
+ } | {
44
+ ok: false;
45
+ error: string;
46
+ };
47
+ export declare function removeRule(state: CompressionState, id: string): RemoveRuleResult;
48
+ export interface ClearRulesResult {
49
+ ok: true;
50
+ count: number;
51
+ }
52
+ export declare function clearRules(state: CompressionState): ClearRulesResult;
53
+ /** System-prompt section for adapters with rules enabled. Returns "" when no
54
+ * rules exist so empty sessions pay zero tokens. */
55
+ export declare function formatRulesForPrompt(state: CompressionState): string;
56
+ /** Plain numbered rendering for the acp_rule tool result when the model lists
57
+ * rules (billion-context#750 executeRule returns this verbatim). */
58
+ export declare function formatRulesList(rules: RuleRecord[]): string;
59
+ //# sourceMappingURL=rules.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.d.ts","s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ED,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,IAAI,CAAC;IACT,KAAK,EAAE,MAAM,CAAC;CACf;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,gBAAgB,GAAG,gBAAgB,CAIpE;AAED;qDACqD;AACrD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAOpE;AAED;qEACqE;AACrE,wBAAgB,eAAe,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,MAAM,CAI3D"}
@@ -1 +1 @@
1
- {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAErE,wBAAgB,kBAAkB,IAAI,gBAAgB,CAiBrD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAI/D;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAI7D;AAED,wBAAgB,SAAS,CACvB,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE,MAAM,GACd,gBAAgB,GAAG,SAAS,CAE9B;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG,gBAAgB,EAAE,CAExE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,gBAAgB,GAAG,GAAG,CAAC,MAAM,CAAC,CAOtE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,gBAAgB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAMxE;AAED,wBAAgB,eAAe,CAC7B,KAAK,EAAE,gBAAgB,EACvB,kBAAkB,EAAE,MAAM,GACzB,IAAI,CAQN"}
1
+ {"version":3,"file":"state.d.ts","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAErE,wBAAgB,kBAAkB,IAAI,gBAAgB,CAmBrD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAI/D;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAI7D;AAED,wBAAgB,SAAS,CACvB,KAAK,EAAE,gBAAgB,EACvB,OAAO,EAAE,MAAM,GACd,gBAAgB,GAAG,SAAS,CAE9B;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG,gBAAgB,EAAE,CAExE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,gBAAgB,GAAG,GAAG,CAAC,MAAM,CAAC,CAOtE;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,gBAAgB,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAMxE;AAED,wBAAgB,eAAe,CAC7B,KAAK,EAAE,gBAAgB,EACvB,kBAAkB,EAAE,MAAM,GACzB,IAAI,CAQN"}
@@ -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,CA+EZ"}
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"}
package/dist/types.d.ts CHANGED
@@ -113,6 +113,24 @@ export interface TerminalEscapeSignal {
113
113
  /** Consecutive events the terminal condition has held. */
114
114
  stuckEvents: number;
115
115
  }
116
+ /** A persistent reminder recorded via the acp_rule tool (see rules.ts).
117
+ * Injected into the system prompt every turn by the adapter and hard-protected
118
+ * from compression. Ids are never re-issued (see nextRuleId). */
119
+ export interface RuleRecord {
120
+ id: string;
121
+ text: string;
122
+ }
123
+ /** Persistent-rule ("acp_rule") feature settings (see rules.ts). Absent or
124
+ * enabled !== true = feature off — the adapter never injects the tool; kernel
125
+ * protection is unconditional but side-effect-free without acp_rule messages.
126
+ * Deviates from kernel#282's original "no Config field" stance: hosts gate the
127
+ * feature and carry their limit overrides through the resolved Config
128
+ * (billion-context#750 reads config.rules.enabled + resolveRuleLimits). */
129
+ export interface RulesConfig {
130
+ enabled?: boolean;
131
+ maxRules?: number;
132
+ maxRuleChars?: number;
133
+ }
116
134
  export interface CompressionState {
117
135
  blocks: CompressionBlock[];
118
136
  messageRefs: MessageRefMap;
@@ -132,6 +150,13 @@ export interface CompressionState {
132
150
  * threshold, viable compression appearing, truncation savings, or a
133
151
  * successful applyCompression. Optional for pre-existing persisted states. */
134
152
  terminalStreak?: number;
153
+ /** Persistent reminders recorded via acp_rule (see rules.ts). Optional:
154
+ * pre-rules persisted states lack it. */
155
+ rules?: RuleRecord[];
156
+ /** Monotonic rule-id counter (`rule${n}`). Never reset by remove/clear so an
157
+ * issued id is never re-issued with different content. Optional: defaults
158
+ * to 1 when absent on older persisted states. */
159
+ nextRuleId?: number;
135
160
  nextBlockId: number;
136
161
  nextRunId: number;
137
162
  }
@@ -197,11 +222,19 @@ export interface Config {
197
222
  compress: CompressValidationConfig;
198
223
  protectedTools: string[];
199
224
  isToolProtected?: (toolName: string, toolInputText?: string) => boolean;
225
+ /** Tool-name patterns (glob suffix allowed) protected in their LATEST
226
+ * instance only: the newest matching tool-call and its paired tool-result
227
+ * are protected from compression; older instances remain compressible. For
228
+ * cumulative-snapshot tools (e.g. todo_list) where only the newest result
229
+ * is the source of truth. */
230
+ protectedLatestTools?: string[];
200
231
  preserveRecentMessages: number;
201
232
  preserveRecentTokens: number;
202
233
  modelContextLimit: number;
203
234
  /** Instant tool-result absorption (see absorb.ts). Absent/disabled = feature off. */
204
235
  absorb?: AbsorbConfig;
236
+ /** Persistent acp_rule reminders (see rules.ts). Absent/disabled = feature off. */
237
+ rules?: RulesConfig;
205
238
  messageFilters?: import("./filter/types.js").MessageFiltersConfig;
206
239
  }
207
240
  export type CompressMode = "range" | "message";
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,WAAW,GAAG,QAAQ,GAAG,MAAM,CAAC;AAEnE,MAAM,MAAM,kBAAkB,GAC5B,MAAM,GAAG,WAAW,GAAG,aAAa,GAAG,WAAW,CAAC;AAErD,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,WAAW,CAAC;IAClB,WAAW,EAAE,kBAAkB,CAAC;IAChC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;;uDAMmD;IACnD,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;AAExC,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,KAAK,CAAC;AAE9C,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,eAAe,CAAC;IACtB,KAAK,CAAC,EAAE,MAAM,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EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB,EAAE,MAAM,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACnC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "acp-kernel",
3
- "version": "0.0.79",
3
+ "version": "0.0.80-pr.334.200",
4
4
  "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.",
5
5
  "license": "MIT",
6
6
  "author": "ranxianglei",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/state.ts"],"sourcesContent":["import type { CompressionBlock, CompressionState } from \"./types.js\";\n\nexport function createInitialState(): CompressionState {\n return {\n blocks: [],\n messageRefs: { byRaw: {}, byRef: {} },\n tokenSnapshot: {},\n nudge: {\n lastPerMessageNudgeTokens: 0,\n lastNudgeShownTokens: 0,\n baselineTokens: 0,\n anchors: {},\n lastShownByTier: {},\n },\n stats: { tokensCompressed: 0, compressionCount: 0, absorbedTokens: 0 },\n absorbed: [],\n nextBlockId: 1,\n nextRunId: 1,\n };\n}\n\nexport function allocateBlockId(state: CompressionState): string {\n const id = state.nextBlockId;\n state.nextBlockId = Math.max(1, id) + 1;\n return `b${id}`;\n}\n\nexport function allocateRunId(state: CompressionState): string {\n const id = state.nextRunId;\n state.nextRunId = Math.max(1, id) + 1;\n return `r${id}`;\n}\n\nexport function blockById(\n state: CompressionState,\n blockId: string,\n): CompressionBlock | undefined {\n return state.blocks.find((block) => block.blockId === blockId);\n}\n\nexport function activeBlocks(state: CompressionState): CompressionBlock[] {\n return state.blocks.filter((block) => block.active);\n}\n\nexport function coveredMessageIds(state: CompressionState): Set<string> {\n const covered = new Set<string>();\n for (const block of state.blocks) {\n if (!block.active) continue;\n for (const id of block.effectiveMessageIds) covered.add(id);\n }\n return covered;\n}\n\nexport function highestActiveTier(state: CompressionState): 0 | 1 | 2 | 3 {\n let highest: 0 | 1 | 2 | 3 = 0;\n for (const block of state.blocks) {\n if (block.active && block.tier > highest) highest = block.tier;\n }\n return highest;\n}\n\nexport function advanceSurvival(\n state: CompressionState,\n promotionThreshold: number,\n): void {\n for (const block of state.blocks) {\n if (!block.active) continue;\n block.survivedCount += 1;\n if (block.survivedCount >= promotionThreshold) {\n block.generation = \"old\";\n }\n }\n}\n"],"mappings":";AAEO,SAAS,qBAAuC;AACrD,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT,aAAa,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,EAAE;AAAA,IACpC,eAAe,CAAC;AAAA,IAChB,OAAO;AAAA,MACL,2BAA2B;AAAA,MAC3B,sBAAsB;AAAA,MACtB,gBAAgB;AAAA,MAChB,SAAS,CAAC;AAAA,MACV,iBAAiB,CAAC;AAAA,IACpB;AAAA,IACA,OAAO,EAAE,kBAAkB,GAAG,kBAAkB,GAAG,gBAAgB,EAAE;AAAA,IACrE,UAAU,CAAC;AAAA,IACX,aAAa;AAAA,IACb,WAAW;AAAA,EACb;AACF;AAEO,SAAS,gBAAgB,OAAiC;AAC/D,QAAM,KAAK,MAAM;AACjB,QAAM,cAAc,KAAK,IAAI,GAAG,EAAE,IAAI;AACtC,SAAO,IAAI,EAAE;AACf;AAEO,SAAS,cAAc,OAAiC;AAC7D,QAAM,KAAK,MAAM;AACjB,QAAM,YAAY,KAAK,IAAI,GAAG,EAAE,IAAI;AACpC,SAAO,IAAI,EAAE;AACf;AAEO,SAAS,UACd,OACA,SAC8B;AAC9B,SAAO,MAAM,OAAO,KAAK,CAAC,UAAU,MAAM,YAAY,OAAO;AAC/D;AAEO,SAAS,aAAa,OAA6C;AACxE,SAAO,MAAM,OAAO,OAAO,CAAC,UAAU,MAAM,MAAM;AACpD;AAEO,SAAS,kBAAkB,OAAsC;AACtE,QAAM,UAAU,oBAAI,IAAY;AAChC,aAAW,SAAS,MAAM,QAAQ;AAChC,QAAI,CAAC,MAAM,OAAQ;AACnB,eAAW,MAAM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