acp-kernel 0.0.94-pr.438.290 → 0.0.94

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/DESIGN.md +137 -158
  2. package/PROVENANCE.md +40 -44
  3. package/README.md +30 -43
  4. package/dist/cache-report.d.ts.map +1 -1
  5. package/dist/{chunk-WR7OPWNT.js → chunk-NUQZKPQS.js} +3 -7
  6. package/dist/chunk-NUQZKPQS.js.map +1 -0
  7. package/dist/compress-tools.d.ts.map +1 -1
  8. package/dist/config.d.ts.map +1 -1
  9. package/dist/decompress.d.ts.map +1 -1
  10. package/dist/filter/apply.d.ts.map +1 -1
  11. package/dist/filter/index.d.ts +1 -1
  12. package/dist/filter/index.d.ts.map +1 -1
  13. package/dist/filter/types.d.ts.map +1 -1
  14. package/dist/handoff.d.ts.map +1 -1
  15. package/dist/hide-consumed.d.ts.map +1 -1
  16. package/dist/image-compress.d.ts.map +1 -1
  17. package/dist/index.js +75 -254
  18. package/dist/index.js.map +1 -1
  19. package/dist/message-kind.d.ts.map +1 -1
  20. package/dist/nudge-text.d.ts.map +1 -1
  21. package/dist/packs.d.ts.map +1 -1
  22. package/dist/panel/cache.d.ts.map +1 -1
  23. package/dist/panel/index.js +10 -29
  24. package/dist/panel/index.js.map +1 -1
  25. package/dist/panel/panel.d.ts.map +1 -1
  26. package/dist/panel/topic.d.ts.map +1 -1
  27. package/dist/parse-compress-input.d.ts.map +1 -1
  28. package/dist/persist/index.d.ts +1 -1
  29. package/dist/persist/index.d.ts.map +1 -1
  30. package/dist/persist/index.js +12 -49
  31. package/dist/persist/index.js.map +1 -1
  32. package/dist/persist/state-merge.d.ts.map +1 -1
  33. package/dist/persist/store.d.ts.map +1 -1
  34. package/dist/protected.d.ts.map +1 -1
  35. package/dist/rebuild.d.ts.map +1 -1
  36. package/dist/recommend.d.ts.map +1 -1
  37. package/dist/render-refs.d.ts.map +1 -1
  38. package/dist/report.d.ts.map +1 -1
  39. package/dist/search/algorithms/bm25.d.ts.map +1 -1
  40. package/dist/search/algorithms/fuzzy.d.ts.map +1 -1
  41. package/dist/search/algorithms/hybrid.d.ts.map +1 -1
  42. package/dist/search/algorithms/semantic.d.ts.map +1 -1
  43. package/dist/search/algorithms/substring.d.ts.map +1 -1
  44. package/dist/search/doc-cache.d.ts.map +1 -1
  45. package/dist/search/index.d.ts +1 -1
  46. package/dist/search/index.d.ts.map +1 -1
  47. package/dist/search/registry.d.ts.map +1 -1
  48. package/dist/search/stemmer.d.ts.map +1 -1
  49. package/dist/search/tokenizer.d.ts.map +1 -1
  50. package/dist/search/types.d.ts.map +1 -1
  51. package/dist/search.d.ts +3 -3
  52. package/dist/search.d.ts.map +1 -1
  53. package/dist/surface-config.d.ts.map +1 -1
  54. package/dist/tool-pairs.d.ts.map +1 -1
  55. package/dist/truncate-tools.d.ts.map +1 -1
  56. package/dist/truncate.d.ts.map +1 -1
  57. package/dist/turn-integrity.d.ts.map +1 -1
  58. package/dist/wire/anthropic.d.ts.map +1 -1
  59. package/dist/wire/bili-message.d.ts.map +1 -1
  60. package/dist/wire/compress-detect.d.ts.map +1 -1
  61. package/dist/wire/demoted-thinking.d.ts.map +1 -1
  62. package/dist/wire/formats.d.ts.map +1 -1
  63. package/dist/wire/index.js +97 -403
  64. package/dist/wire/index.js.map +1 -1
  65. package/dist/wire/message-id.d.ts.map +1 -1
  66. package/dist/wire/mirror.d.ts.map +1 -1
  67. package/dist/wire/openai.d.ts.map +1 -1
  68. package/dist/wire/responses.d.ts.map +1 -1
  69. package/dist/wire/strip-images.d.ts.map +1 -1
  70. package/dist/wire/util.d.ts.map +1 -1
  71. package/package.json +66 -66
  72. package/dist/chunk-WR7OPWNT.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"message-kind.d.ts","sourceRoot":"","sources":["../src/message-kind.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAI3D"}
1
+ {"version":3,"file":"message-kind.d.ts","sourceRoot":"","sources":["../src/message-kind.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,WAAW,GAAG,OAAO,CAE3D"}
@@ -1 +1 @@
1
- {"version":3,"file":"nudge-text.d.ts","sourceRoot":"","sources":["../src/nudge-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,iBAAiB,EACjB,cAAc,EAIf,MAAM,YAAY,CAAC;AAEpB,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;AA8DD,wBAAgB,YAAY,CAC1B,YAAY,EAAE,iBAAiB,EAAE,EACjC,eAAe,EAAE,cAAc,EAAE,GAChC,MAAM,CAsHR;AAoBD,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,aAAa,EACvB,OAAO,GAAE,OAAwB,EACjC,QAAQ,GAAE,mBAAwB,GACjC,aAAa,CA6Ef"}
1
+ {"version":3,"file":"nudge-text.d.ts","sourceRoot":"","sources":["../src/nudge-text.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAA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G,EAAE,MAAM,GAAG,UAAU,CAoCvE;AAED,0EAA0E;AAC1E,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,GAAG,YAAY,CAyB/E;AAED;;0BAE0B;AAC1B,wBAAgB,kBAAkB,CAAC,IAAI,EAAE;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,GAAG,UAAU,EAAE,CAK3G"}
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/panel/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;kCAOkC;AAElC,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,KAAK,EAAE,MAAM,CAAC;IACd,wDAAwD;IACxD,SAAS,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B;6DACyD;IACzD,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B;4DACwD;IACxD,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;IACjB,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,YAAY,EAAE,MAAM,CAAC;CACtB;AAMD,oEAAoE;AACpE,wBAAgB,aAAa,CAC3B,MAAM,EAAE,SAAS,gBAAgB,EAAE,GAClC,eAAe,CAyBjB;AAED,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD"}
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/panel/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;kCAOkC;AAElC,MAAM,WAAW,gBAAgB;IAC/B,mEAAmE;IACnE,KAAK,EAAE,MAAM,CAAC;IACd,wDAAwD;IACxD,SAAS,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B;6DACyD;IACzD,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B;4DACwD;IACxD,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,2DAA2D;IAC3D,QAAQ,EAAE,MAAM,CAAC;IACjB,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,wEAAwE;IACxE,YAAY,EAAE,MAAM,CAAC;CACtB;AAMD,oEAAoE;AACpE,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,gBAAgB,EAAE,GAAG,eAAe,CAyBlF;AAED,qEAAqE;AACrE,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD"}
@@ -3,7 +3,7 @@ import {
3
3
  defaultCountTokens,
4
4
  formatRanges,
5
5
  viableRanges
6
- } from "../chunk-WR7OPWNT.js";
6
+ } from "../chunk-NUQZKPQS.js";
7
7
 
8
8
  // src/panel/topic.ts
9
9
  function topicFallback(summary) {
@@ -57,10 +57,7 @@ function formatHitRate(rate) {
57
57
  // src/panel/panel.ts
58
58
  function bar(value, total, width = 20) {
59
59
  if (total === 0) return "";
60
- const filled = Math.max(
61
- 0,
62
- Math.min(width, Math.round(value / total * width))
63
- );
60
+ const filled = Math.max(0, Math.min(width, Math.round(value / total * width)));
64
61
  return "\u2588".repeat(filled) + "\u2591".repeat(width - filled);
65
62
  }
66
63
  function buildStatusPanel(input) {
@@ -83,22 +80,16 @@ function buildStatusPanel(input) {
83
80
  lines.push("\u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F");
84
81
  if (input.version) lines.push(input.version);
85
82
  lines.push("");
86
- lines.push(
87
- `Context (session accounting, host footer scale): ${displayPct}% (${fmt(displayTotal)} / ${fmt(limit)}) \u2014 includes compressed originals; shrinks slower than the sent view`
88
- );
83
+ lines.push(`Context (session accounting, host footer scale): ${displayPct}% (${fmt(displayTotal)} / ${fmt(limit)}) \u2014 includes compressed originals; shrinks slower than the sent view`);
89
84
  if (nudge && bd) {
90
85
  const growth = bd.growth;
91
86
  if (growth > 0 && displayTotal > 0) {
92
87
  lines.push(`Growth: +${fmt(growth)} since last nudge`);
93
88
  }
94
89
  lines.push("");
95
- lines.push(
96
- `Sent to LLM (after compression, est.): ${fmt(sentTotal)}${limit > 0 ? ` (${sentPct}% of limit)` : ""}`
97
- );
90
+ lines.push(`Sent to LLM (after compression, est.): ${fmt(sentTotal)}${limit > 0 ? ` (${sentPct}% of limit)` : ""}`);
98
91
  if (input.unprunedTokens !== void 0 && sessionOnly > 0) {
99
- lines.push(
100
- `Session-only (compressed originals, est.): ${fmt(sessionOnly)} \u2014 pruned from every request; the footer/nudge still count them`
101
- );
92
+ lines.push(`Session-only (compressed originals, est.): ${fmt(sessionOnly)} \u2014 pruned from every request; the footer/nudge still count them`);
102
93
  }
103
94
  lines.push("");
104
95
  lines.push("Token Breakdown (sent view):");
@@ -113,9 +104,7 @@ function buildStatusPanel(input) {
113
104
  if (cat.value <= 0) continue;
114
105
  const pct = sentTotal > 0 ? Math.round(cat.value / sentTotal * 100) : 0;
115
106
  const b = bar(cat.value, sentTotal);
116
- lines.push(
117
- ` ${cat.label.padEnd(10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`
118
- );
107
+ lines.push(` ${cat.label.padEnd(10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`);
119
108
  }
120
109
  }
121
110
  if (input.cacheUsages) {
@@ -144,30 +133,22 @@ function buildStatusPanel(input) {
144
133
  }
145
134
  if (activeBlocksList.length > 0) {
146
135
  lines.push("");
147
- lines.push(
148
- `Blocks: ${activeBlocksList.length} active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`
149
- );
136
+ lines.push(`Blocks: ${activeBlocksList.length} active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`);
150
137
  for (const b of activeBlocksList) {
151
138
  const topic = b.topic ? `: ${b.topic}` : `: ${topicFallback(b.summary || "")}`;
152
139
  const summaryTok = defaultCountTokens(b.summary || "");
153
140
  const origTok = b.compressedTokens > 0 ? b.compressedTokens : summaryTok;
154
- lines.push(
155
- ` [${b.blockId}] T${b.tier} ${fmt(origTok)}\u2192${fmt(summaryTok)}${topic}`
156
- );
141
+ lines.push(` [${b.blockId}] T${b.tier} ${fmt(origTok)}\u2192${fmt(summaryTok)}${topic}`);
157
142
  }
158
143
  } else if (totalBlocksList.length > 0) {
159
144
  lines.push("");
160
- lines.push(
161
- `Blocks: 0 active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`
162
- );
145
+ lines.push(`Blocks: 0 active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`);
163
146
  } else {
164
147
  lines.push("");
165
148
  lines.push("Blocks: none (nothing compressed yet)");
166
149
  }
167
150
  lines.push("");
168
- lines.push(
169
- "Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal."
170
- );
151
+ lines.push("Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.");
171
152
  return lines.join("\n");
172
153
  }
173
154
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/panel/topic.ts","../../src/panel/format.ts","../../src/panel/cache.ts","../../src/panel/panel.ts"],"sourcesContent":["/** Short topic for a block when the model did not provide one: first sentence\n * segment, leading quotes stripped, truncated to 30 chars with an ellipsis.\n * Used wherever block lists are rendered (panels, search results). */\nimport { clampPrefix } from \"../truncate.js\";\n\nexport function topicFallback(summary: string): string {\n const first = summary.split(/[.\\n]/)[0] ?? \"\";\n const t = first\n .trim()\n .replace(/^[\"'`]+/, \"\")\n .trim();\n return t.length <= 30 ? t : `${clampPrefix(t, 30).trimEnd()}…`;\n}\n","/** Compact token formatting for user-facing panels: lowercase k/M with the\n * same thresholds as the hosts' footers (<1000 → raw, <10000 → one decimal\n * k, <1e6 → rounded k, <1e7 → one decimal M). */\nexport function formatCompactTokens(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n return `${Math.round(count / 1000000)}M`;\n}\n","/** Cache hit-rate math for the /acp status panel.\n *\n * Hosts feed per-request prompt-cache usage samples (from assistant\n * messages' provider-reported `usage`); the kernel derives the display\n * numbers. A request COUNTS only when the provider reported cache\n * activity for it (`cacheRead + cacheWrite > 0`): providers without\n * prompt-cache reporting (0/0 with plain `input`) must not drag the\n * average to a fabricated 0%. */\n\nexport interface CacheUsageSample {\n /** Non-cached conversation input tokens billed for the request. */\n input: number;\n /** Conversation tokens served from the prompt cache. */\n cacheRead: number;\n /** Conversation tokens written to the prompt cache (cache creation). */\n cacheWrite: number;\n}\n\nexport interface CacheHitSummary {\n /** Session hit rate (0..1), weighted by billed prompt tokens.\n * Undefined when no request reported cache activity. */\n session: number | undefined;\n /** Hit rate (0..1) of the most recent request that reported cache\n * activity. Undefined when no request reported any. */\n last: number | undefined;\n /** Counted requests (provider reported cache activity). */\n requests: number;\n /** Cumulative tokens served from cache. */\n cacheRead: number;\n /** Cumulative billed prompt tokens (input + cacheRead + cacheWrite). */\n billedPrompt: number;\n}\n\nfunction num(v: unknown): number {\n return typeof v === \"number\" && Number.isFinite(v) && v > 0 ? v : 0;\n}\n\n/** Aggregate per-request cache usage into panel display numbers. */\nexport function cacheHitStats(\n usages: readonly CacheUsageSample[],\n): CacheHitSummary {\n let cacheRead = 0;\n let billedPrompt = 0;\n let requests = 0;\n let last: number | undefined;\n for (const u of usages) {\n const read = num(u?.cacheRead);\n const write = num(u?.cacheWrite);\n const input = num(u?.input);\n // No cache signal on this request → excluded entirely (see header).\n if (read + write <= 0) continue;\n const total = read + write + input;\n if (total <= 0) continue;\n cacheRead += read;\n billedPrompt += total;\n requests += 1;\n last = read / total;\n }\n return {\n session: requests > 0 ? cacheRead / billedPrompt : undefined,\n last,\n requests,\n cacheRead,\n billedPrompt,\n };\n}\n\n/** Format a 0..1 rate as a percentage with one decimal (\"92.3%\"). */\nexport function formatHitRate(rate: number): string {\n return `${(Math.max(0, Math.min(1, rate)) * 100).toFixed(1)}%`;\n}\n","import { defaultCountTokens } from \"../tokenize.js\";\nimport { formatRanges } from \"../nudge-text.js\";\nimport type { CompressionState, NudgeDecision } from \"../types.js\";\nimport { formatCompactTokens } from \"./format.js\";\nimport { topicFallback } from \"./topic.js\";\nimport { viableRanges } from \"../viable.js\";\nimport {\n cacheHitStats,\n formatHitRate,\n type CacheUsageSample,\n} from \"./cache.js\";\n\nexport interface StatusPanelInput {\n /** Adapter identifier for the header, e.g. \"billion-context-omp@0.1.6\".\n * Omit to hide the version line. */\n version?: string;\n /** Host session accounting — the SAME number the host footer displays.\n * It includes compressed originals (summaries stay in the window), so it\n * shrinks slower than the sent view when compression prunes the\n * per-request projection. */\n tokenCount: number;\n /** Measured token count of the host system prompt (host-specific to\n * obtain; the kernel breakdown does not see it). */\n systemPromptTokens: number;\n /** Kernel state (blocks drive the Blocks section). */\n state: CompressionState;\n /** The nudge decision from core.processTurn for this turn, if any. The\n * panel applies the viability filter to compressibleRanges itself. */\n nudge: NudgeDecision | undefined;\n /** Configured model context window, in tokens. */\n modelContextLimit: number;\n /** Estimate of the FULL (unpruned) core-message projection, computed\n * with the SAME countTokens the core uses (kernel default = CJK-aware\n * defaultCountTokens) — the same estimation scale as the kernel\n * breakdown. When provided, the panel derives `Session-only` on that\n * scale (unpruned − sent). Without it the line is omitted: subtracting\n * the host's provider-scale number from an estimate-scale number\n * invents a third, meaningless scale (issue #18 \"看板统计的和拆分的有差异\"). */\n unprunedTokens?: number;\n /** Per-request prompt-cache usage (from assistant messages' provider-\n * reported `usage`). Requests without cache reporting are excluded by\n * cacheHitStats; when no counted request remains, the section is\n * omitted entirely. Omit the field to hide the section. */\n cacheUsages?: ReadonlyArray<CacheUsageSample>;\n /** Token formatter override (defaults to formatCompactTokens). */\n fmtTokens?: (n: number) => string;\n}\n\nfunction bar(value: number, total: number, width: number = 20): string {\n if (total === 0) return \"\";\n const filled = Math.max(\n 0,\n Math.min(width, Math.round((value / total) * width)),\n );\n return \"█\".repeat(filled) + \"░\".repeat(width - filled);\n}\n\n/** Render the /acp status panel. Three token numbers, each labeled with\n * its own scale, never mixed in arithmetic:\n * - Session accounting (host footer scale): the host's reported context\n * size INCLUDING compressed originals (summaries stay in the window), so\n * it shrinks slower than the sent view when compression prunes the\n * per-request projection.\n * - Sent view (estimated, kernel countTokens scale): what actually\n * reaches the LLM after compression (kernel's classification over the\n * pruned projection + measured system prompt). This is the number\n * compression controls.\n * - Session-only (estimated, kernel countTokens scale): unpruned\n * projection − sent view; the compressed originals pruned from every\n * request.\n * Subtracting the host number from an estimate produced numbers that\n * reconciled with neither scale (\"Framework 390K\", \"session-only 29k vs\n * 112k compressed\") — that is what issue #18 reported. */\nexport function buildStatusPanel(input: StatusPanelInput): string {\n const { tokenCount, state, nudge, modelContextLimit } = input;\n const fmt = input.fmtTokens ?? formatCompactTokens;\n const bd = nudge?.contextBreakdown;\n const limit = modelContextLimit;\n const classified = bd\n ? bd.system + bd.tool + bd.summaries + bd.code + bd.text\n : 0;\n const systemPromptTokens = input.systemPromptTokens;\n const sentTotal = classified + systemPromptTokens;\n // Same-scale derivation only: both sides use the core's countTokens\n // estimate (kernel default = CJK-aware defaultCountTokens). The host\n // footer's tokenCount (provider-anchored, session-tree) is displayed as\n // its own line and never fed into an arithmetic difference with these.\n const sessionOnly =\n input.unprunedTokens !== undefined\n ? Math.max(0, input.unprunedTokens - sentTotal)\n : 0;\n const displayTotal = tokenCount;\n const displayPct = limit > 0 ? Math.round((displayTotal / limit) * 100) : 0;\n const sentPct = limit > 0 ? Math.round((sentTotal / limit) * 100) : 0;\n const activeBlocksList = state.blocks.filter((b) => b.active);\n const totalBlocksList = state.blocks;\n\n const lines: string[] = [];\n\n lines.push(\"╭─────────────────────────────────────────────╮\");\n lines.push(\"│ ACP Context Analysis │\");\n lines.push(\"╰─────────────────────────────────────────────╯\");\n if (input.version) lines.push(input.version);\n lines.push(\"\");\n lines.push(\n `Context (session accounting, host footer scale): ${displayPct}% (${fmt(displayTotal)} / ${fmt(limit)}) — includes compressed originals; shrinks slower than the sent view`,\n );\n\n if (nudge && bd) {\n const growth = bd.growth;\n if (growth > 0 && displayTotal > 0) {\n lines.push(`Growth: +${fmt(growth)} since last nudge`);\n }\n lines.push(\"\");\n lines.push(\n `Sent to LLM (after compression, est.): ${fmt(sentTotal)}${limit > 0 ? ` (${sentPct}% of limit)` : \"\"}`,\n );\n if (input.unprunedTokens !== undefined && sessionOnly > 0) {\n lines.push(\n `Session-only (compressed originals, est.): ${fmt(sessionOnly)} — pruned from every request; the footer/nudge still count them`,\n );\n }\n lines.push(\"\");\n lines.push(\"Token Breakdown (sent view):\");\n\n const categories: Array<{ label: string; value: number }> = [\n { label: \"Tool\", value: bd.tool },\n { label: \"SysPrompt\", value: systemPromptTokens },\n { label: \"Text\", value: bd.text },\n { label: \"Code\", value: bd.code },\n { label: \"Summaries\", value: bd.summaries },\n ];\n\n for (const cat of categories) {\n if (cat.value <= 0) continue;\n const pct = sentTotal > 0 ? Math.round((cat.value / sentTotal) * 100) : 0;\n const b = bar(cat.value, sentTotal);\n lines.push(\n ` ${cat.label.padEnd(10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`,\n );\n }\n }\n\n if (input.cacheUsages) {\n const cache = cacheHitStats(input.cacheUsages);\n if (\n cache.requests > 0 &&\n cache.session !== undefined &&\n cache.last !== undefined\n ) {\n lines.push(\"\");\n lines.push(\n `Prompt cache (provider-reported): ${formatHitRate(cache.last)} last · ${formatHitRate(cache.session)} session avg — ${fmt(cache.cacheRead)} of ${fmt(cache.billedPrompt)} billed prompt tokens served from cache (${cache.requests} req)`,\n );\n }\n }\n\n lines.push(\"\");\n\n if (nudge) {\n if (nudge.shouldInject) {\n const tierInfo = nudge.tier ? ` [T${nudge.tier} distillation]` : \"\";\n lines.push(`Nudge: ACTIVE${tierInfo} — ${nudge.reason}`);\n } else {\n lines.push(`Nudge: idle — ${nudge.reason}`);\n }\n }\n\n const ranges = viableRanges(nudge?.compressibleRanges ?? []);\n const protectedRanges = nudge?.protectedRanges ?? [];\n if (ranges.length > 0 || protectedRanges.length > 0) {\n lines.push(\"\");\n lines.push(formatRanges(ranges, protectedRanges));\n }\n\n if (activeBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(\n `Blocks: ${activeBlocksList.length} active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`,\n );\n for (const b of activeBlocksList) {\n const topic = b.topic\n ? `: ${b.topic}`\n : `: ${topicFallback(b.summary || \"\")}`;\n const summaryTok = defaultCountTokens(b.summary || \"\");\n const origTok = b.compressedTokens > 0 ? b.compressedTokens : summaryTok;\n lines.push(\n ` [${b.blockId}] T${b.tier} ${fmt(origTok)}→${fmt(summaryTok)}${topic}`,\n );\n }\n } else if (totalBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(\n `Blocks: 0 active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`,\n );\n } else {\n lines.push(\"\");\n lines.push(\"Blocks: none (nothing compressed yet)\");\n }\n\n lines.push(\"\");\n lines.push(\n \"Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.\",\n );\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;AAKO,SAAS,cAAc,SAAyB;AACrD,QAAM,QAAQ,QAAQ,MAAM,OAAO,EAAE,CAAC,KAAK;A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AI,MAAM,MAAM,gBAAgB,CAAC;AAAA,IAC1F;AAAA,EACF,OAAO;AACL,UAAM,KAAK,EAAE;AACb,UAAM,KAAK,uCAAuC;AAAA,EACpD;AAEA,QAAM,KAAK,EAAE;AACb,QAAM;AAAA,IACJ;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
1
+ {"version":3,"sources":["../../src/panel/topic.ts","../../src/panel/format.ts","../../src/panel/cache.ts","../../src/panel/panel.ts"],"sourcesContent":["/** Short topic for a block when the model did not provide one: first sentence\n * segment, leading quotes stripped, truncated to 30 chars with an ellipsis.\n * Used wherever block lists are rendered (panels, search results). */\nimport { clampPrefix } from \"../truncate.js\";\n\nexport function topicFallback(summary: string): string {\n const first = summary.split(/[.\\n]/)[0] ?? \"\";\n const t = first.trim().replace(/^[\"'`]+/, \"\").trim();\n return t.length <= 30 ? t : `${clampPrefix(t, 30).trimEnd()}…`;\n}\n","/** Compact token formatting for user-facing panels: lowercase k/M with the\n * same thresholds as the hosts' footers (<1000 → raw, <10000 → one decimal\n * k, <1e6 → rounded k, <1e7 → one decimal M). */\nexport function formatCompactTokens(count: number): string {\n if (count < 1000) return count.toString();\n if (count < 10000) return `${(count / 1000).toFixed(1)}k`;\n if (count < 1000000) return `${Math.round(count / 1000)}k`;\n if (count < 10000000) return `${(count / 1000000).toFixed(1)}M`;\n return `${Math.round(count / 1000000)}M`;\n}\n","/** Cache hit-rate math for the /acp status panel.\n *\n * Hosts feed per-request prompt-cache usage samples (from assistant\n * messages' provider-reported `usage`); the kernel derives the display\n * numbers. A request COUNTS only when the provider reported cache\n * activity for it (`cacheRead + cacheWrite > 0`): providers without\n * prompt-cache reporting (0/0 with plain `input`) must not drag the\n * average to a fabricated 0%. */\n\nexport interface CacheUsageSample {\n /** Non-cached conversation input tokens billed for the request. */\n input: number;\n /** Conversation tokens served from the prompt cache. */\n cacheRead: number;\n /** Conversation tokens written to the prompt cache (cache creation). */\n cacheWrite: number;\n}\n\nexport interface CacheHitSummary {\n /** Session hit rate (0..1), weighted by billed prompt tokens.\n * Undefined when no request reported cache activity. */\n session: number | undefined;\n /** Hit rate (0..1) of the most recent request that reported cache\n * activity. Undefined when no request reported any. */\n last: number | undefined;\n /** Counted requests (provider reported cache activity). */\n requests: number;\n /** Cumulative tokens served from cache. */\n cacheRead: number;\n /** Cumulative billed prompt tokens (input + cacheRead + cacheWrite). */\n billedPrompt: number;\n}\n\nfunction num(v: unknown): number {\n return typeof v === \"number\" && Number.isFinite(v) && v > 0 ? v : 0;\n}\n\n/** Aggregate per-request cache usage into panel display numbers. */\nexport function cacheHitStats(usages: readonly CacheUsageSample[]): CacheHitSummary {\n let cacheRead = 0;\n let billedPrompt = 0;\n let requests = 0;\n let last: number | undefined;\n for (const u of usages) {\n const read = num(u?.cacheRead);\n const write = num(u?.cacheWrite);\n const input = num(u?.input);\n // No cache signal on this request → excluded entirely (see header).\n if (read + write <= 0) continue;\n const total = read + write + input;\n if (total <= 0) continue;\n cacheRead += read;\n billedPrompt += total;\n requests += 1;\n last = read / total;\n }\n return {\n session: requests > 0 ? cacheRead / billedPrompt : undefined,\n last,\n requests,\n cacheRead,\n billedPrompt,\n };\n}\n\n/** Format a 0..1 rate as a percentage with one decimal (\"92.3%\"). */\nexport function formatHitRate(rate: number): string {\n return `${(Math.max(0, Math.min(1, rate)) * 100).toFixed(1)}%`;\n}\n","import { defaultCountTokens } from \"../tokenize.js\";\nimport { formatRanges } from \"../nudge-text.js\";\nimport type { CompressionState, NudgeDecision } from \"../types.js\";\nimport { formatCompactTokens } from \"./format.js\";\nimport { topicFallback } from \"./topic.js\";\nimport { viableRanges } from \"../viable.js\";\nimport { cacheHitStats, formatHitRate, type CacheUsageSample } from \"./cache.js\";\n\nexport interface StatusPanelInput {\n /** Adapter identifier for the header, e.g. \"billion-context-omp@0.1.6\".\n * Omit to hide the version line. */\n version?: string;\n /** Host session accounting — the SAME number the host footer displays.\n * It includes compressed originals (summaries stay in the window), so it\n * shrinks slower than the sent view when compression prunes the\n * per-request projection. */\n tokenCount: number;\n /** Measured token count of the host system prompt (host-specific to\n * obtain; the kernel breakdown does not see it). */\n systemPromptTokens: number;\n /** Kernel state (blocks drive the Blocks section). */\n state: CompressionState;\n /** The nudge decision from core.processTurn for this turn, if any. The\n * panel applies the viability filter to compressibleRanges itself. */\n nudge: NudgeDecision | undefined;\n /** Configured model context window, in tokens. */\n modelContextLimit: number;\n /** Estimate of the FULL (unpruned) core-message projection, computed\n * with the SAME countTokens the core uses (kernel default = CJK-aware\n * defaultCountTokens) — the same estimation scale as the kernel\n * breakdown. When provided, the panel derives `Session-only` on that\n * scale (unpruned − sent). Without it the line is omitted: subtracting\n * the host's provider-scale number from an estimate-scale number\n * invents a third, meaningless scale (issue #18 \"看板统计的和拆分的有差异\"). */\n unprunedTokens?: number;\n /** Per-request prompt-cache usage (from assistant messages' provider-\n * reported `usage`). Requests without cache reporting are excluded by\n * cacheHitStats; when no counted request remains, the section is\n * omitted entirely. Omit the field to hide the section. */\n cacheUsages?: ReadonlyArray<CacheUsageSample>;\n /** Token formatter override (defaults to formatCompactTokens). */\n fmtTokens?: (n: number) => string;\n}\n\nfunction bar(value: number, total: number, width: number = 20): string {\n if (total === 0) return \"\";\n const filled = Math.max(0, Math.min(width, Math.round((value / total) * width)));\n return \"█\".repeat(filled) + \"░\".repeat(width - filled);\n}\n\n/** Render the /acp status panel. Three token numbers, each labeled with\n * its own scale, never mixed in arithmetic:\n * - Session accounting (host footer scale): the host's reported context\n * size INCLUDING compressed originals (summaries stay in the window), so\n * it shrinks slower than the sent view when compression prunes the\n * per-request projection.\n * - Sent view (estimated, kernel countTokens scale): what actually\n * reaches the LLM after compression (kernel's classification over the\n * pruned projection + measured system prompt). This is the number\n * compression controls.\n * - Session-only (estimated, kernel countTokens scale): unpruned\n * projection − sent view; the compressed originals pruned from every\n * request.\n * Subtracting the host number from an estimate produced numbers that\n * reconciled with neither scale (\"Framework 390K\", \"session-only 29k vs\n * 112k compressed\") — that is what issue #18 reported. */\nexport function buildStatusPanel(input: StatusPanelInput): string {\n const { tokenCount, state, nudge, modelContextLimit } = input;\n const fmt = input.fmtTokens ?? formatCompactTokens;\n const bd = nudge?.contextBreakdown;\n const limit = modelContextLimit;\n const classified = bd ? bd.system + bd.tool + bd.summaries + bd.code + bd.text : 0;\n const systemPromptTokens = input.systemPromptTokens;\n const sentTotal = classified + systemPromptTokens;\n // Same-scale derivation only: both sides use the core's countTokens\n // estimate (kernel default = CJK-aware defaultCountTokens). The host\n // footer's tokenCount (provider-anchored, session-tree) is displayed as\n // its own line and never fed into an arithmetic difference with these.\n const sessionOnly = input.unprunedTokens !== undefined ? Math.max(0, input.unprunedTokens - sentTotal) : 0;\n const displayTotal = tokenCount;\n const displayPct = limit > 0 ? Math.round((displayTotal / limit) * 100) : 0;\n const sentPct = limit > 0 ? Math.round((sentTotal / limit) * 100) : 0;\n const activeBlocksList = state.blocks.filter((b) => b.active);\n const totalBlocksList = state.blocks;\n\n const lines: string[] = [];\n\n lines.push(\"╭─────────────────────────────────────────────╮\");\n lines.push(\"│ ACP Context Analysis │\");\n lines.push(\"╰─────────────────────────────────────────────╯\");\n if (input.version) lines.push(input.version);\n lines.push(\"\");\n lines.push(`Context (session accounting, host footer scale): ${displayPct}% (${fmt(displayTotal)} / ${fmt(limit)}) — includes compressed originals; shrinks slower than the sent view`);\n\n if (nudge && bd) {\n const growth = bd.growth;\n if (growth > 0 && displayTotal > 0) {\n lines.push(`Growth: +${fmt(growth)} since last nudge`);\n }\n lines.push(\"\");\n lines.push(`Sent to LLM (after compression, est.): ${fmt(sentTotal)}${limit > 0 ? ` (${sentPct}% of limit)` : \"\"}`);\n if (input.unprunedTokens !== undefined && sessionOnly > 0) {\n lines.push(`Session-only (compressed originals, est.): ${fmt(sessionOnly)} — pruned from every request; the footer/nudge still count them`);\n }\n lines.push(\"\");\n lines.push(\"Token Breakdown (sent view):\");\n\n const categories: Array<{ label: string; value: number }> = [\n { label: \"Tool\", value: bd.tool },\n { label: \"SysPrompt\", value: systemPromptTokens },\n { label: \"Text\", value: bd.text },\n { label: \"Code\", value: bd.code },\n { label: \"Summaries\", value: bd.summaries },\n ];\n\n for (const cat of categories) {\n if (cat.value <= 0) continue;\n const pct = sentTotal > 0 ? Math.round((cat.value / sentTotal) * 100) : 0;\n const b = bar(cat.value, sentTotal);\n lines.push(` ${cat.label.padEnd(10)} ${b} ${String(pct).padStart(3)}% ${fmt(cat.value)}`);\n }\n }\n\n if (input.cacheUsages) {\n const cache = cacheHitStats(input.cacheUsages);\n if (cache.requests > 0 && cache.session !== undefined && cache.last !== undefined) {\n lines.push(\"\");\n lines.push(\n `Prompt cache (provider-reported): ${formatHitRate(cache.last)} last · ${formatHitRate(cache.session)} session avg — ${fmt(cache.cacheRead)} of ${fmt(cache.billedPrompt)} billed prompt tokens served from cache (${cache.requests} req)`,\n );\n }\n }\n\n lines.push(\"\");\n\n if (nudge) {\n if (nudge.shouldInject) {\n const tierInfo = nudge.tier ? ` [T${nudge.tier} distillation]` : \"\";\n lines.push(`Nudge: ACTIVE${tierInfo} — ${nudge.reason}`);\n } else {\n lines.push(`Nudge: idle — ${nudge.reason}`);\n }\n }\n\n const ranges = viableRanges(nudge?.compressibleRanges ?? []);\n const protectedRanges = nudge?.protectedRanges ?? [];\n if (ranges.length > 0 || protectedRanges.length > 0) {\n lines.push(\"\");\n lines.push(formatRanges(ranges, protectedRanges));\n }\n\n if (activeBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(`Blocks: ${activeBlocksList.length} active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`);\n for (const b of activeBlocksList) {\n const topic = b.topic ? `: ${b.topic}` : `: ${topicFallback(b.summary || \"\")}`;\n const summaryTok = defaultCountTokens(b.summary || \"\");\n const origTok = b.compressedTokens > 0 ? b.compressedTokens : summaryTok;\n lines.push(` [${b.blockId}] T${b.tier} ${fmt(origTok)}→${fmt(summaryTok)}${topic}`);\n }\n } else if (totalBlocksList.length > 0) {\n lines.push(\"\");\n lines.push(`Blocks: 0 active / ${totalBlocksList.length} total (${fmt(state.stats.tokensCompressed)} tokens compressed, cumulative)`);\n } else {\n lines.push(\"\");\n lines.push(\"Blocks: none (nothing compressed yet)\");\n }\n\n lines.push(\"\");\n lines.push(\"Tag visibility: tags injected to LLM only (deep copy), not persisted in session, not shown in terminal.\");\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;AAKO,SAAS,cAAc,SAAyB;AACrD,QAAM,QAAQ,QAAQ,MAAM,OAAO,EAAE,CAAC,KAAK;AAC3C,QAAM,IAAI,MAAM,KAAK,EAAE,QAAQ,WAAW,EAAE,EAAE,KAAK;AACnD,SAAO,EAAE,UAAU,KAAK,IAAI,GAAG,YAAY,GAAG,EAAE,EAAE,QAAQ,CAAC;AAC7D;;;ACNO,SAAS,oBAAoB,OAAuB;AACzD,MAAI,QAAQ,IAAM,QAAO,MAAM,SAAS;AACxC,MAAI,QAAQ,IAAO,QAAO,IAAI,QAAQ,KAAM,QAAQ,CAAC,CAAC;AACtD,MAAI,QAAQ,IAAS,QAAO,GAAG,KAAK,MAAM,QAAQ,GAAI,CAAC;AACvD,MAAI,QAAQ,IAAU,QAAO,IAAI,QAAQ,KAAS,QAAQ,CAAC,CAAC;AAC5D,SAAO,GAAG,KAAK,MAAM,QAAQ,GAAO,CAAC;AACvC;;;ACwBA,SAAS,IAAI,GAAoB;AAC/B,SAAO,OAAO,MAAM,YAAY,OAAO,SAAS,CAAC,KAAK,IAAI,IAAI,IAAI;AACpE;AAGO,SAAS,cAAc,QAAsD;AAClF,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,WAAW;AACf,MAAI;AACJ,aAAW,KAAK,QAAQ;AACtB,UAAM,OAAO,IAAI,GAAG,SAAS;AAC7B,UAAM,QAAQ,IAAI,GAAG,UAAU;AAC/B,UAAM,QAAQ,IAAI,GAAG,KAAK;AAE1B,QAAI,OAAO,SAAS,EAAG;AACvB,UAAM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,MAAM,KAAK,MAAM,CAAC;CACnC;AAWD;;;;;;;;;;;;;;;2DAe2D;AAC3D,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAqIhE"}
1
+ {"version":3,"file":"panel.d.ts","sourceRoot":"","sources":["../../src/panel/panel.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAInE,OAAO,EAAgC,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEjF,MAAM,WAAW,gBAAgB;IAC/B;yCACqC;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;kCAG8B;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB;yDACqD;IACrD,kBAAkB,EAAE,MAAM,CAAC;IAC3B,sDAAsD;IACtD,KAAK,EAAE,gBAAgB,CAAC;IACxB;2EACuE;IACvE,KAAK,EAAE,aAAa,GAAG,SAAS,CAAC;IACjC,kDAAkD;IAClD,iBAAiB,EAAE,MAAM,CAAC;IAC1B;;;;;;yEAMqE;IACrE,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;gEAG4D;IAC5D,WAAW,CAAC,EAAE,aAAa,CAAC,gBAAgB,CAAC,CAAC;IAC9C,kEAAkE;IAClE,SAAS,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;CACnC;AAQD;;;;;;;;;;;;;;;2DAe2D;AAC3D,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CA0GhE"}
@@ -1 +1 @@
1
- {"version":3,"file":"topic.d.ts","sourceRoot":"","sources":["../../src/panel/topic.ts"],"names":[],"mappings":"AAKA,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAOrD"}
1
+ {"version":3,"file":"topic.d.ts","sourceRoot":"","sources":["../../src/panel/topic.ts"],"names":[],"mappings":"AAKA,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAIrD"}
@@ -1 +1 @@
1
- {"version":3,"file":"parse-compress-input.d.ts","sourceRoot":"","sources":["../src/parse-compress-input.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,MAAM,iBAAiB,GACzB,IAAI,GACJ,aAAa,GACb,YAAY,GACZ,iBAAiB,GACjB,mBAAmB,GACnB,gBAAgB,GAChB,WAAW,GACX,iBAAiB,CAAC;AAEtB,MAAM,WAAW,wBAAwB;IACvC,uDAAuD;IACvD,EAAE,EAAE,OAAO,CAAC;IACZ,2CAA2C;IAC3C,IAAI,EAAE,iBAAiB,CAAC;IACxB,wEAAwE;IACxE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,oEAAoE;IACpE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oDAAoD;IACpD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iFAAiF;IACjF,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,0DAA0D;IAC1D,YAAY,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,WAAW,EAAE,wBAAwB,CAAC;CACvC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAC/B,KAAK,EAAE,OAAO,EACd,IAAI,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GACzB,mBAAmB,CAuBrB;AA0TD;;;0CAG0C;AAC1C,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAS1E"}
1
+ {"version":3,"file":"parse-compress-input.d.ts","sourceRoot":"","sources":["../src/parse-compress-input.ts"],"names":[],"mappings":"AAyBA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEpD,MAAM,MAAM,iBAAiB,GACvB,IAAI,GACJ,aAAa,GACb,YAAY,GACZ,iBAAiB,GACjB,mBAAmB,GACnB,gBAAgB,GAChB,WAAW,GACX,iBAAiB,CAAC;AAExB,MAAM,WAAW,wBAAwB;IACrC,uDAAuD;IACvD,EAAE,EAAE,OAAO,CAAC;IACZ,2CAA2C;IAC3C,IAAI,EAAE,iBAAiB,CAAC;IACxB,wEAAwE;IACxE,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,oEAAoE;IACpE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oDAAoD;IACpD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,iFAAiF;IACjF,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,0DAA0D;IAC1D,YAAY,EAAE,MAAM,CAAC;IACrB,oEAAoE;IACpE,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,mBAAmB;IAChC,MAAM,EAAE,iBAAiB,EAAE,CAAC;IAC5B,WAAW,EAAE,wBAAwB,CAAC;CACzC;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,mBAAmB,CAmBjG;AAsQD;;;0CAG0C;AAC1C,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAM1E"}
@@ -14,6 +14,6 @@
14
14
  * - the store never deletes files; cleanup is a downstream decision
15
15
  */
16
16
  export { StateStore, flatFileNameFor } from "./store.js";
17
- export type { PersistedEnvelope, PersistLogger, StateStoreCodec, StateStoreOptions, } from "./store.js";
17
+ export type { PersistedEnvelope, PersistLogger, StateStoreCodec, StateStoreOptions } from "./store.js";
18
18
  export { mergeCompressionState } from "./state-merge.js";
19
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/persist/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACzD,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,eAAe,EACf,iBAAiB,GAClB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/persist/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACzD,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACvG,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -121,12 +121,7 @@ var StateStore = class {
121
121
  } catch {
122
122
  }
123
123
  if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;
124
- Atomics.wait(
125
- new Int32Array(new SharedArrayBuffer(4)),
126
- 0,
127
- 0,
128
- this.backoffMs(attempt)
129
- );
124
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));
130
125
  }
131
126
  }
132
127
  if (!lastErr) {
@@ -145,12 +140,7 @@ var StateStore = class {
145
140
  spillPath = spill;
146
141
  } catch (e) {
147
142
  if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;
148
- Atomics.wait(
149
- new Int32Array(new SharedArrayBuffer(4)),
150
- 0,
151
- 0,
152
- this.backoffMs(attempt)
153
- );
143
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, this.backoffMs(attempt));
154
144
  }
155
145
  }
156
146
  if (spillPath) this.discovered.set(id, spillPath);
@@ -191,9 +181,7 @@ var StateStore = class {
191
181
  const envelope = this.readEnvelope(file);
192
182
  if (!envelope) continue;
193
183
  const base = path.basename(file);
194
- const relBase = path.basename(
195
- this.relPathOf(envelope.id, envelope.payload)
196
- );
184
+ const relBase = path.basename(this.relPathOf(envelope.id, envelope.payload));
197
185
  const flatBase = flatFileNameFor(envelope.id);
198
186
  let owner = null;
199
187
  if (base === relBase || base === flatBase) {
@@ -205,10 +193,7 @@ var StateStore = class {
205
193
  }
206
194
  }
207
195
  if (owner === null) {
208
- this.log(
209
- "warn",
210
- `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`
211
- );
196
+ this.log("warn", `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`);
212
197
  continue;
213
198
  }
214
199
  const existing = out.get(owner);
@@ -242,10 +227,7 @@ var StateStore = class {
242
227
  await Promise.all(
243
228
  [...builders.entries()].map(
244
229
  ([id, build]) => this.writeNow(id, build).catch((e) => {
245
- this.log(
246
- "error",
247
- `[persist] shutdown flush failed for ${id}: ${errText(e)}`
248
- );
230
+ this.log("error", `[persist] shutdown flush failed for ${id}: ${errText(e)}`);
249
231
  })
250
232
  )
251
233
  );
@@ -285,8 +267,7 @@ var StateStore = class {
285
267
  lastErr = e;
286
268
  await fsp.unlink(tmp).catch(() => {
287
269
  });
288
- if (!isTransientFsError(e) || attempt === this.retryAttempts - 1)
289
- break;
270
+ if (!isTransientFsError(e) || attempt === this.retryAttempts - 1) break;
290
271
  const { promise, resolve } = Promise.withResolvers();
291
272
  setTimeout(resolve, this.backoffMs(attempt));
292
273
  await promise;
@@ -350,10 +331,7 @@ var StateStore = class {
350
331
  if (!custom) return flatFileNameFor(id);
351
332
  const rel2 = path.normalize(custom);
352
333
  if (path.isAbsolute(rel2) || rel2.split(/[\\/]+/).includes("..")) {
353
- this.log(
354
- "warn",
355
- `[persist] relPath for ${id} escapes dir; using flat name`
356
- );
334
+ this.log("warn", `[persist] relPath for ${id} escapes dir; using flat name`);
357
335
  return flatFileNameFor(id);
358
336
  }
359
337
  return rel2;
@@ -362,10 +340,7 @@ var StateStore = class {
362
340
  * rename is atomic). Prefixed `.tmp-` so loadAll skips orphans. */
363
341
  tempPath(dest) {
364
342
  const seq = this.tmpSeq++;
365
- return path.join(
366
- path.dirname(dest),
367
- `.tmp-${path.basename(dest, ".json")}-${process.pid}-${seq}`
368
- );
343
+ return path.join(path.dirname(dest), `.tmp-${path.basename(dest, ".json")}-${process.pid}-${seq}`);
369
344
  }
370
345
  backoffMs(attempt) {
371
346
  return Math.min(this.retryBaseMs * 2 ** attempt, this.retryMaxMs);
@@ -408,10 +383,7 @@ var StateStore = class {
408
383
  const alertAt = count === 1 || count >= 2 && (count & count - 1) === 0;
409
384
  if (!alertAt) return;
410
385
  const where = spillPath ? `; data spilled to ${rel(spillPath, this.dir)}` : "; SPILLOVER ALSO FAILED \u2014 data at risk";
411
- this.log(
412
- count === 1 ? "error" : "warn",
413
- `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`
414
- );
386
+ this.log(count === 1 ? "error" : "warn", `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`);
415
387
  }
416
388
  clearFailure(id) {
417
389
  this.failCounts.delete(id);
@@ -426,29 +398,20 @@ var StateStore = class {
426
398
  parsed = JSON.parse(text);
427
399
  } catch (e) {
428
400
  if (e.code !== "ENOENT") {
429
- this.log(
430
- "warn",
431
- `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`
432
- );
401
+ this.log("warn", `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`);
433
402
  }
434
403
  return null;
435
404
  }
436
405
  if (isEnvelopeLike(parsed)) {
437
406
  if (!this.validateFn(parsed)) {
438
- this.log(
439
- "warn",
440
- `[persist] skipping invalid record ${rel(file, this.dir)}`
441
- );
407
+ this.log("warn", `[persist] skipping invalid record ${rel(file, this.dir)}`);
442
408
  return null;
443
409
  }
444
410
  return parsed;
445
411
  }
446
412
  const adopted = this.adoptLegacy(parsed);
447
413
  if (adopted) return adopted;
448
- this.log(
449
- "warn",
450
- `[persist] skipping invalid record ${rel(file, this.dir)}`
451
- );
414
+ this.log("warn", `[persist] skipping invalid record ${rel(file, this.dir)}`);
452
415
  return null;
453
416
  }
454
417
  /** Wrap a legacy (pre-envelope) record as an envelope via the `legacy`
@@ -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 = (\n level: \"info\" | \"warn\" | \"error\",\n msg: string,\n) => 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(\n new Int32Array(new SharedArrayBuffer(4)),\n 0,\n 0,\n this.backoffMs(attempt),\n );\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 (\n let attempt = 0;\n attempt < this.retryAttempts && spillPath === null;\n attempt++\n ) {\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(\n new Int32Array(new SharedArrayBuffer(4)),\n 0,\n 0,\n this.backoffMs(attempt),\n );\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(\n this.relPathOf(envelope.id, envelope.payload),\n );\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(\n \"warn\",\n `[persist] skipping ${rel(file, this.dir)}: filename does not match record id`,\n );\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(\n \"error\",\n `[persist] shutdown flush failed for ${id}: ${errText(e)}`,\n );\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)\n 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 (\n let attempt = 0;\n attempt < this.retryAttempts && spillPath === null;\n attempt++\n ) {\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(\n \"warn\",\n `[persist] relPath for ${id} escapes dir; using flat name`,\n );\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(\n path.dirname(dest),\n `.tmp-${path.basename(dest, \".json\")}-${process.pid}-${seq}`,\n );\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(\n id: string,\n err: unknown,\n spillPath: string | null,\n ): 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(\n count === 1 ? \"error\" : \"warn\",\n `[persist] write failed for ${id} (total ${count}x): ${errText(err)}${where}`,\n );\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(\n \"warn\",\n `[persist] skipping corrupt file ${rel(file, this.dir)}: ${errText(e)}`,\n );\n }\n return null;\n }\n if (isEnvelopeLike(parsed)) {\n if (!this.validateFn(parsed as PersistedEnvelope<T>)) {\n this.log(\n \"warn\",\n `[persist] skipping invalid record ${rel(file, this.dir)}`,\n );\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(\n \"warn\",\n `[persist] skipping invalid record ${rel(file, this.dir)}`,\n );\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 (\n !adoption ||\n typeof adoption.id !== \"string\" ||\n adoption.id.length === 0 ||\n adoption.payload == null\n ) {\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 (\n typeof envelope.id === \"string\" &&\n envelope.id.length > 0 &&\n envelope.payload != null\n );\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 (\n createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\").slice(0, 24) + \".json\"\n );\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 (\n code === \"EPERM\" ||\n code === \"EBUSY\" ||\n code === \"EACCES\" ||\n code === \"ENOENT\" ||\n code === \"ENOTDIR\"\n );\n}\n\nfunction errText(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\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(\n parsed: CompressionState,\n): 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;AA8IV,IAAM,aAAN,MAAoB;AAAA,EAChB;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;AA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,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,KA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AS,IAAI,GAAW,MAAsB;AAC1C,QAAM,IAAI,KAAK,SAAS,MAAM,CAAC;AAC/B,SAAO,KAAK,CAAC,EAAE,WAAW,IAAI,IAAI,IAAI;AAC1C;;;AClrBO,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 +1 @@
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,CACnC,MAAM,EAAE,gBAAgB,GACvB,gBAAgB,CAiBlB"}
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,CAiBhF"}