@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +289 -0
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +115 -3
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,1271 @@
1
+ /**
2
+ * CASI v2: Append-Only Content-Addressed Gutter-Normalized FastCDC Delta Store.
3
+ *
4
+ * Scans tool outputs monotonically in prefix order (`0 -> N-1`). Each block `k`
5
+ * queries ONLY intact prior entries `0..k-1`, guaranteeing 100% prefix-cache
6
+ * invariance across multi-turn conversations: turn T's prefix bytes remain bit-
7
+ * identical when turn T+1 appends new messages.
8
+ *
9
+ * Emits:
10
+ * - Exact / gutter-shifted duplicate reference (`[fiche cas: ...]`)
11
+ * - Anchor-aligned unified diff hunk (`[fiche cas-delta vs ... (±2 context)]`)
12
+ * - FastCDC sub-block slice splice (`[fiche cas-slice: ...]`)
13
+ *
14
+ * Deltas and slices are never re-indexed as bases (chain depth <= 1). Zero `node:` imports.
15
+ */
16
+ const MAX_CASI_ENTRIES = 128;
17
+ const MAX_SEED_ENTRIES = 48;
18
+ const MAX_LINE_POSTINGS = 24;
19
+ const HOT_POSTING_VOTE_SKIP = 16;
20
+ const MIN_EXACT_DUP_CHARS = 400;
21
+ const MIN_DELTA_CHARS = 800;
22
+ const MIN_DELTA_LINES = 16;
23
+ const MAX_INPUT_CHARS = 512_000;
24
+ const HUNK_CONTEXT = 2;
25
+ const HISTOGRAM_MAX_DEPTH = 16;
26
+ const HISTOGRAM_MAX_OCCURRENCES = 64;
27
+ const PREPARED_CACHE_MAX_ENTRIES = 192;
28
+ const PREPARED_CACHE_MAX_CHARS = 16 * 1024 * 1024;
29
+ const PREPARED_CACHE_MIN_CHARS = 256;
30
+ const CDC_MIN_LINES = 8;
31
+ const CDC_AVG_LINES = 20;
32
+ const CDC_MAX_LINES = 48;
33
+ // High-bit Normalized FastCDC masks operating on the 8-line Gear rolling window
34
+ // (4 left-shifts per line across 32 bits): stricter below avg, relaxed at/above avg.
35
+ const CDC_MASK_S = 0xf8000000;
36
+ const CDC_MASK_L = 0xe0000000;
37
+ const MAX_CHUNK_REFS_PER_KEY = 8;
38
+ const GUTTER_NUM_RE = /^\s*(\d{1,7})(?:\t|→|\s*[|│](?:\s|$))/;
39
+ const ALT_GUTTER_NUM_RE = /^L(\d{1,7}):\s/;
40
+ const ISO_TS_RE = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b/g;
41
+ const CLOCK_TS_RE = /\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b/g;
42
+ const VOLATILE_DURATION_RE = /\b\d+(?:\.\d+)?\s*(?:ns|us|µs|ms|s)\b/g;
43
+ /** Deterministic 256-entry FastCDC Gear table generated via SplitMix32 constants. */
44
+ export const GEAR_TABLE = (() => {
45
+ const table = new Uint32Array(256);
46
+ let state = 0x9e3779b9;
47
+ for (let i = 0; i < 256; i++) {
48
+ state = (state + 0x9e3779b9) | 0;
49
+ let z = state;
50
+ z = Math.imul(z ^ (z >>> 16), 0x85ebca6b);
51
+ z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35);
52
+ table[i] = (z ^ (z >>> 16)) >>> 0;
53
+ }
54
+ return table;
55
+ })();
56
+ /**
57
+ * Strip `read_file` / `bat` / `view_file` line-number gutters (`1→`, `1\t`, `1 │ `, `L1: `)
58
+ * into `{ lineNum, body }` without altering body indentation.
59
+ */
60
+ export function stripLineGutter(line) {
61
+ if (!line)
62
+ return { lineNum: null, body: line };
63
+ const c0 = line.charCodeAt(0);
64
+ if (c0 === 76) {
65
+ const m = ALT_GUTTER_NUM_RE.exec(line);
66
+ if (m) {
67
+ return {
68
+ lineNum: Number.parseInt(m[1], 10),
69
+ body: line.slice(m[0].length),
70
+ };
71
+ }
72
+ return { lineNum: null, body: line };
73
+ }
74
+ if ((c0 >= 48 && c0 <= 57) || c0 === 32 || c0 === 9) {
75
+ const m = GUTTER_NUM_RE.exec(line);
76
+ if (m) {
77
+ return {
78
+ lineNum: Number.parseInt(m[1], 10),
79
+ body: line.slice(m[0].length),
80
+ };
81
+ }
82
+ }
83
+ return { lineNum: null, body: line };
84
+ }
85
+ /**
86
+ * Normalize volatile ISO timestamps, clock timestamps, and durations ONLY for
87
+ * similarity voting and chunk matching while preserving exact `curLines` in output.
88
+ */
89
+ export function canonicalForMatching(body) {
90
+ if (!body)
91
+ return body;
92
+ let out = body;
93
+ if (out.includes(':')) {
94
+ out = out.replace(ISO_TS_RE, '<TS>').replace(CLOCK_TS_RE, '<TIME>');
95
+ }
96
+ if (out.includes('s') || out.includes('S')) {
97
+ out = out.replace(VOLATILE_DURATION_RE, '<DUR>');
98
+ }
99
+ return out;
100
+ }
101
+ // Allocation-free check matching `line.trim().length >= 4` on hot CASI scan paths.
102
+ function hasAtLeast4NonWs(line) {
103
+ let count = 0;
104
+ for (let i = 0; i < line.length; i++) {
105
+ const c = line.charCodeAt(i);
106
+ if (c !== 32 && !(c >= 9 && c <= 13) && c !== 160) {
107
+ if (++count >= 4)
108
+ return true;
109
+ }
110
+ }
111
+ return false;
112
+ }
113
+ function fnv1a32(s, seed = 0x811c9dc5) {
114
+ let h = seed >>> 0;
115
+ for (let i = 0; i < s.length; i++) {
116
+ h ^= s.charCodeAt(i);
117
+ h = Math.imul(h, 0x01000193);
118
+ }
119
+ return h >>> 0;
120
+ }
121
+ function dualHash64Hex(s) {
122
+ let h1 = 0x811c9dc5 >>> 0;
123
+ let h2 = 0x9e3779b1 >>> 0;
124
+ for (let i = 0; i < s.length; i++) {
125
+ const c = s.charCodeAt(i);
126
+ h1 = Math.imul((h1 ^ c) >>> 0, 0x01000193) >>> 0;
127
+ h2 = Math.imul((h2 ^ ((c + (i & 0xff)) >>> 0)) >>> 0, 0x85ebca6b) >>> 0;
128
+ }
129
+ return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
130
+ }
131
+ function estimateSavedTokens(raw, compacted) {
132
+ const diff = raw.length - compacted.length;
133
+ return diff > 0 ? Math.max(1, Math.round(diff / 3.5)) : 0;
134
+ }
135
+ /** O(K log K) Longest Increasing Subsequence on `baseIdx` ordered by `curIdx`. */
136
+ function lisAnchors(pairs) {
137
+ const n = pairs.length;
138
+ if (n === 0)
139
+ return [];
140
+ const tailsVal = [];
141
+ const tailsIdx = [];
142
+ const prev = new Int32Array(n).fill(-1);
143
+ for (let i = 0; i < n; i++) {
144
+ const x = pairs[i].baseIdx;
145
+ let lo = 0;
146
+ let hi = tailsVal.length;
147
+ while (lo < hi) {
148
+ const mid = (lo + hi) >> 1;
149
+ if (tailsVal[mid] < x)
150
+ lo = mid + 1;
151
+ else
152
+ hi = mid;
153
+ }
154
+ if (lo > 0)
155
+ prev[i] = tailsIdx[lo - 1];
156
+ if (lo === tailsVal.length) {
157
+ tailsVal.push(x);
158
+ tailsIdx.push(i);
159
+ }
160
+ else {
161
+ tailsVal[lo] = x;
162
+ tailsIdx[lo] = i;
163
+ }
164
+ }
165
+ const out = [];
166
+ let cur = tailsIdx[tailsIdx.length - 1];
167
+ while (cur >= 0) {
168
+ out.push(pairs[cur]);
169
+ cur = prev[cur];
170
+ }
171
+ out.reverse();
172
+ return out;
173
+ }
174
+ function chunkHash64(canonLines, start, end) {
175
+ let h1 = 0x811c9dc5 >>> 0;
176
+ let h2 = 0x9e3779b1 >>> 0;
177
+ for (let i = start; i < end; i++) {
178
+ const rel = i - start;
179
+ if (i > start) {
180
+ h1 = Math.imul((h1 ^ 10) >>> 0, 0x01000193) >>> 0;
181
+ h2 = Math.imul((h2 ^ (10 + (rel & 0xff))) >>> 0, 0x85ebca6b) >>> 0;
182
+ }
183
+ const line = canonLines[i];
184
+ for (let j = 0; j < line.length; j++) {
185
+ const c = line.charCodeAt(j);
186
+ h1 = Math.imul((h1 ^ c) >>> 0, 0x01000193) >>> 0;
187
+ h2 = Math.imul((h2 ^ ((c + (j & 0xff)) >>> 0)) >>> 0, 0x85ebca6b) >>> 0;
188
+ }
189
+ }
190
+ return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
191
+ }
192
+ function computeFastCdcChunks(canonLines, canonHashes) {
193
+ const n = canonLines.length;
194
+ if (n < CDC_MIN_LINES)
195
+ return [];
196
+ const chunks = [];
197
+ let start = 0;
198
+ let gear = 0;
199
+ for (let i = 0; i < n; i++) {
200
+ const h = canonHashes[i];
201
+ gear = ((gear << 1) + GEAR_TABLE[h & 0xff]) >>> 0;
202
+ gear = ((gear << 1) + GEAR_TABLE[(h >>> 8) & 0xff]) >>> 0;
203
+ gear = ((gear << 1) + GEAR_TABLE[(h >>> 16) & 0xff]) >>> 0;
204
+ gear = ((gear << 1) + GEAR_TABLE[(h >>> 24) & 0xff]) >>> 0;
205
+ const lineCount = i - start + 1;
206
+ const mask = lineCount < CDC_AVG_LINES ? CDC_MASK_S : CDC_MASK_L;
207
+ if (lineCount >= CDC_MAX_LINES || (lineCount >= CDC_MIN_LINES && ((gear & mask) >>> 0) === 0)) {
208
+ chunks.push({
209
+ startLine: start,
210
+ endLine: i + 1,
211
+ lineCount,
212
+ key: chunkHash64(canonLines, start, i + 1),
213
+ });
214
+ start = i + 1;
215
+ gear = 0;
216
+ }
217
+ }
218
+ if (n - start >= CDC_MIN_LINES) {
219
+ chunks.push({
220
+ startLine: start,
221
+ endLine: n,
222
+ lineCount: n - start,
223
+ key: chunkHash64(canonLines, start, n),
224
+ });
225
+ }
226
+ return chunks;
227
+ }
228
+ const PREPARED_LINES_CACHE = new Map();
229
+ let preparedCacheChars = 0;
230
+ export function clearCasiPreparedCacheForTests() {
231
+ PREPARED_LINES_CACHE.clear();
232
+ preparedCacheChars = 0;
233
+ }
234
+ function getPreparedAndChunks(rawText, hash64) {
235
+ const canCache = rawText.length >= PREPARED_CACHE_MIN_CHARS &&
236
+ rawText.length <= MAX_INPUT_CHARS &&
237
+ rawText.length <= PREPARED_CACHE_MAX_CHARS;
238
+ const cacheKey = canCache ? `${rawText.length}:${hash64 ?? dualHash64Hex(rawText)}` : '';
239
+ if (canCache) {
240
+ const cached = PREPARED_LINES_CACHE.get(cacheKey);
241
+ if (cached && cached.rawText === rawText) {
242
+ PREPARED_LINES_CACHE.delete(cacheKey);
243
+ PREPARED_LINES_CACHE.set(cacheKey, cached);
244
+ return { prep: cached.prep, chunks: cached.chunks };
245
+ }
246
+ }
247
+ const prep = prepareLines(rawText);
248
+ const chunks = computeFastCdcChunks(prep.canonLines, prep.canonHashes);
249
+ if (canCache) {
250
+ const existing = PREPARED_LINES_CACHE.get(cacheKey);
251
+ if (existing) {
252
+ preparedCacheChars -= existing.rawText.length;
253
+ PREPARED_LINES_CACHE.delete(cacheKey);
254
+ }
255
+ while ((PREPARED_LINES_CACHE.size >= PREPARED_CACHE_MAX_ENTRIES ||
256
+ preparedCacheChars + rawText.length > PREPARED_CACHE_MAX_CHARS) &&
257
+ PREPARED_LINES_CACHE.size > 0) {
258
+ const oldestKey = PREPARED_LINES_CACHE.keys().next().value;
259
+ if (oldestKey === undefined)
260
+ break;
261
+ const oldest = PREPARED_LINES_CACHE.get(oldestKey);
262
+ PREPARED_LINES_CACHE.delete(oldestKey);
263
+ if (oldest)
264
+ preparedCacheChars -= oldest.rawText.length;
265
+ }
266
+ PREPARED_LINES_CACHE.set(cacheKey, { rawText, prep, chunks });
267
+ preparedCacheChars += rawText.length;
268
+ }
269
+ return { prep, chunks };
270
+ }
271
+ const CODE_HINT_RE = /(?:^|\s)(?:export|import|function|const|let|var|class|interface|type|enum|def|async|fn|pub|func|struct|return|throw)\b|=>|;\s*$/;
272
+ const LOG_LINE_HINT_RE = /\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}|\b\d{2}:\d{2}:\d{2}(?:\.\d+)?\b|^\s*\[?(?:INFO|WARN|WARNING|ERROR|DEBUG|TRACE|FATAL)\]?(?:\s|:)/i;
273
+ function isMonotonicLineNums(lineNums, count) {
274
+ for (let i = 1; i < count; i++) {
275
+ if (lineNums[i] <= lineNums[i - 1])
276
+ return false;
277
+ }
278
+ return count > 0 && lineNums[0] >= 0;
279
+ }
280
+ function prepareLines(rawText) {
281
+ const lines = rawText.split('\n');
282
+ const n = lines.length;
283
+ // Ignore a single trailing empty line produced by a final `\n`.
284
+ const effectiveLineCount = n > 1 && lines[n - 1] === '' ? n - 1 : n;
285
+ const bodies = new Array(n);
286
+ const canonLines = new Array(n);
287
+ const lineNums = new Int32Array(n);
288
+ const canonHashes = new Uint32Array(n);
289
+ let allHaveLineNums = effectiveLineCount > 0;
290
+ let codeHintHits = 0;
291
+ let logHintHits = 0;
292
+ let ch1 = 0x811c9dc5 >>> 0;
293
+ let ch2 = 0x9e3779b1 >>> 0;
294
+ for (let i = 0; i < n; i++) {
295
+ const { lineNum, body } = stripLineGutter(lines[i]);
296
+ bodies[i] = body;
297
+ const canon = canonicalForMatching(body);
298
+ canonLines[i] = canon;
299
+ if (lineNum === null) {
300
+ lineNums[i] = -1;
301
+ if (i < effectiveLineCount)
302
+ allHaveLineNums = false;
303
+ }
304
+ else {
305
+ lineNums[i] = lineNum;
306
+ }
307
+ if (i < effectiveLineCount && codeHintHits < 3 && CODE_HINT_RE.test(body)) {
308
+ codeHintHits++;
309
+ }
310
+ if (i < effectiveLineCount && logHintHits < 4 && LOG_LINE_HINT_RE.test(body)) {
311
+ logHintHits++;
312
+ }
313
+ canonHashes[i] = fnv1a32(canon);
314
+ if (i < effectiveLineCount) {
315
+ if (i > 0) {
316
+ ch1 = Math.imul((ch1 ^ 10) >>> 0, 0x01000193) >>> 0;
317
+ ch2 = Math.imul((ch2 ^ 10) >>> 0, 0x01000193) >>> 0;
318
+ }
319
+ for (let j = 0; j < body.length; j++) {
320
+ const c = body.charCodeAt(j);
321
+ ch1 = Math.imul((ch1 ^ c) >>> 0, 0x01000193) >>> 0;
322
+ ch2 = Math.imul((ch2 ^ c) >>> 0, 0x01000193) >>> 0;
323
+ }
324
+ }
325
+ }
326
+ const bodyDocHash = (ch1 >>> 0).toString(16).padStart(8, '0') + (ch2 >>> 0).toString(16).padStart(8, '0');
327
+ return {
328
+ lines,
329
+ bodies,
330
+ canonLines,
331
+ lineNums,
332
+ canonHashes,
333
+ effectiveLineCount,
334
+ allHaveLineNums,
335
+ isCodeLike: codeHintHits >= 2,
336
+ isLogLike: logHintHits >= 3,
337
+ bodyDocHash,
338
+ rawLength: rawText.length,
339
+ };
340
+ }
341
+ function sliceCharLength(lines, start, end) {
342
+ let len = Math.max(0, end - start - 1);
343
+ for (let i = start; i < end; i++) {
344
+ len += lines[i].length;
345
+ }
346
+ return len;
347
+ }
348
+ function formatUnifiedDelta(base, cur) {
349
+ const { lines: curLines, bodies: curBodies, canonLines: curCanonLines, canonHashes: curCanonHashes } = cur;
350
+ // Use canonical matching only on unguttered non-code log streams; any guttered,
351
+ // code-like, or structured non-log payload (YAML/JSON/config) MUST verify exact body equality.
352
+ const strictBody = base.allHaveLineNums ||
353
+ cur.allHaveLineNums ||
354
+ base.isCodeLike ||
355
+ cur.isCodeLike ||
356
+ !(base.isLogLike && cur.isLogLike);
357
+ const matchCanon = (bIdx, cIdx) => strictBody ? base.bodies[bIdx] === curBodies[cIdx] : base.canonLines[bIdx] === curCanonLines[cIdx];
358
+ const baseLen = base.lines.length;
359
+ const curLen = curLines.length;
360
+ const baseHas4 = new Uint8Array(baseLen);
361
+ for (let i = 0; i < baseLen; i++) {
362
+ if (hasAtLeast4NonWs(base.canonLines[i]))
363
+ baseHas4[i] = 1;
364
+ }
365
+ // Build hash -> unique base line position map (freq == 1 in base, 1..3 in cur).
366
+ const curHas4 = new Uint8Array(curLen);
367
+ const curFreq = new Map();
368
+ for (let i = 0; i < curLen; i++) {
369
+ if (!hasAtLeast4NonWs(curCanonLines[i]))
370
+ continue;
371
+ curHas4[i] = 1;
372
+ const h = curCanonHashes[i];
373
+ curFreq.set(h, (curFreq.get(h) ?? 0) + 1);
374
+ }
375
+ const basePosUnique = new Map();
376
+ for (let i = 0; i < baseLen; i++) {
377
+ if (!baseHas4[i])
378
+ continue;
379
+ const h = base.canonHashes[i];
380
+ if ((base.lineFreq.get(h) ?? 0) !== 1)
381
+ continue;
382
+ const cf = curFreq.get(h) ?? 0;
383
+ if (cf === 0 || cf > 3)
384
+ continue;
385
+ basePosUnique.set(h, i);
386
+ }
387
+ const rawPairs = [];
388
+ for (let cIdx = 0; cIdx < curLen; cIdx++) {
389
+ if (!curHas4[cIdx])
390
+ continue;
391
+ const h = curCanonHashes[cIdx];
392
+ const bIdx = basePosUnique.get(h);
393
+ if (bIdx === undefined)
394
+ continue;
395
+ if (matchCanon(bIdx, cIdx)) {
396
+ rawPairs.push({ baseIdx: bIdx, curIdx: cIdx });
397
+ }
398
+ }
399
+ // Compute monotonic alignment segments by expanding around pinned LIS anchors,
400
+ // then recursively anchor remaining unmatched intervals via Histogram Diff.
401
+ const matchedCur = new Int32Array(curLen).fill(-1);
402
+ const usedBase = new Uint8Array(baseLen);
403
+ if (rawPairs.length > 0) {
404
+ const anchors = lisAnchors(rawPairs);
405
+ for (const a of anchors) {
406
+ if (matchedCur[a.curIdx] !== -1 || usedBase[a.baseIdx])
407
+ continue;
408
+ matchedCur[a.curIdx] = a.baseIdx;
409
+ usedBase[a.baseIdx] = 1;
410
+ }
411
+ // Forward & backward greedy expansion bounded by strictly monotonic neighbors.
412
+ for (let i = 0; i < anchors.length; i++) {
413
+ const curStart = anchors[i].curIdx;
414
+ const baseStart = anchors[i].baseIdx;
415
+ const nextCurBound = i + 1 < anchors.length ? anchors[i + 1].curIdx : curLen;
416
+ const nextBaseBound = i + 1 < anchors.length ? anchors[i + 1].baseIdx : baseLen;
417
+ let c = curStart + 1;
418
+ let b = baseStart + 1;
419
+ while (c < nextCurBound &&
420
+ b < nextBaseBound &&
421
+ matchedCur[c] === -1 &&
422
+ !usedBase[b] &&
423
+ curCanonHashes[c] === base.canonHashes[b] &&
424
+ matchCanon(b, c)) {
425
+ matchedCur[c] = b;
426
+ usedBase[b] = 1;
427
+ c++;
428
+ b++;
429
+ }
430
+ const prevCurBound = i > 0 ? anchors[i - 1].curIdx : -1;
431
+ const prevBaseBound = i > 0 ? anchors[i - 1].baseIdx : -1;
432
+ c = curStart - 1;
433
+ b = baseStart - 1;
434
+ while (c > prevCurBound &&
435
+ b > prevBaseBound &&
436
+ matchedCur[c] === -1 &&
437
+ !usedBase[b] &&
438
+ curCanonHashes[c] === base.canonHashes[b] &&
439
+ matchCanon(b, c)) {
440
+ matchedCur[c] = b;
441
+ usedBase[b] = 1;
442
+ c--;
443
+ b--;
444
+ }
445
+ }
446
+ }
447
+ const lisIntervalFallback = (bStart, bEnd, cStart, cEnd) => {
448
+ const localCurFreq = new Map();
449
+ for (let c = cStart; c < cEnd; c++) {
450
+ if (matchedCur[c] !== -1 || !curHas4[c])
451
+ continue;
452
+ const h = curCanonHashes[c];
453
+ localCurFreq.set(h, (localCurFreq.get(h) ?? 0) + 1);
454
+ }
455
+ const localBaseFreq = new Map();
456
+ const localBasePos = new Map();
457
+ for (let b = bStart; b < bEnd; b++) {
458
+ if (usedBase[b] || !baseHas4[b])
459
+ continue;
460
+ const h = base.canonHashes[b];
461
+ localBaseFreq.set(h, (localBaseFreq.get(h) ?? 0) + 1);
462
+ localBasePos.set(h, b);
463
+ }
464
+ const pairs = [];
465
+ for (let c = cStart; c < cEnd; c++) {
466
+ if (matchedCur[c] !== -1 || !curHas4[c])
467
+ continue;
468
+ const h = curCanonHashes[c];
469
+ if (localBaseFreq.get(h) !== 1)
470
+ continue;
471
+ const cf = localCurFreq.get(h) ?? 0;
472
+ if (cf === 0 || cf > 3)
473
+ continue;
474
+ const b = localBasePos.get(h);
475
+ if (matchCanon(b, c)) {
476
+ pairs.push({ baseIdx: b, curIdx: c });
477
+ }
478
+ }
479
+ if (pairs.length === 0)
480
+ return;
481
+ const subAnchors = lisAnchors(pairs);
482
+ for (const a of subAnchors) {
483
+ if (matchedCur[a.curIdx] !== -1 || usedBase[a.baseIdx])
484
+ continue;
485
+ matchedCur[a.curIdx] = a.baseIdx;
486
+ usedBase[a.baseIdx] = 1;
487
+ }
488
+ for (let i = 0; i < subAnchors.length; i++) {
489
+ const curStart = subAnchors[i].curIdx;
490
+ const baseStart = subAnchors[i].baseIdx;
491
+ const nextC = i + 1 < subAnchors.length ? subAnchors[i + 1].curIdx : cEnd;
492
+ const nextB = i + 1 < subAnchors.length ? subAnchors[i + 1].baseIdx : bEnd;
493
+ let c = curStart + 1;
494
+ let b = baseStart + 1;
495
+ while (c < nextC &&
496
+ b < nextB &&
497
+ matchedCur[c] === -1 &&
498
+ !usedBase[b] &&
499
+ curCanonHashes[c] === base.canonHashes[b] &&
500
+ matchCanon(b, c)) {
501
+ matchedCur[c] = b;
502
+ usedBase[b] = 1;
503
+ c++;
504
+ b++;
505
+ }
506
+ const prevC = i > 0 ? subAnchors[i - 1].curIdx : cStart - 1;
507
+ const prevB = i > 0 ? subAnchors[i - 1].baseIdx : bStart - 1;
508
+ c = curStart - 1;
509
+ b = baseStart - 1;
510
+ while (c > prevC &&
511
+ b > prevB &&
512
+ matchedCur[c] === -1 &&
513
+ !usedBase[b] &&
514
+ curCanonHashes[c] === base.canonHashes[b] &&
515
+ matchCanon(b, c)) {
516
+ matchedCur[c] = b;
517
+ usedBase[b] = 1;
518
+ c--;
519
+ b--;
520
+ }
521
+ }
522
+ };
523
+ // Recursive Histogram Diff on unmatched intervals: resolves repeated boilerplate
524
+ // blocks (freq >= 2) where globally unique anchors are sparse or exhausted.
525
+ const histogramAnchors = (bStart, bEnd, cStart, cEnd, depth) => {
526
+ if (bEnd <= bStart || cEnd <= cStart)
527
+ return;
528
+ if (depth >= HISTOGRAM_MAX_DEPTH) {
529
+ lisIntervalFallback(bStart, bEnd, cStart, cEnd);
530
+ return;
531
+ }
532
+ const basePositions = new Map();
533
+ for (let b = bStart; b < bEnd; b++) {
534
+ if (usedBase[b] || !baseHas4[b])
535
+ continue;
536
+ const h = base.canonHashes[b];
537
+ let arr = basePositions.get(h);
538
+ if (!arr) {
539
+ arr = [b];
540
+ basePositions.set(h, arr);
541
+ }
542
+ else if (arr.length <= HISTOGRAM_MAX_OCCURRENCES) {
543
+ arr.push(b);
544
+ }
545
+ }
546
+ if (basePositions.size === 0)
547
+ return;
548
+ const curPositions = new Map();
549
+ for (let c = cStart; c < cEnd; c++) {
550
+ if (matchedCur[c] !== -1 || !curHas4[c])
551
+ continue;
552
+ const h = curCanonHashes[c];
553
+ const bArr = basePositions.get(h);
554
+ if (!bArr || bArr.length > HISTOGRAM_MAX_OCCURRENCES)
555
+ continue;
556
+ let cArr = curPositions.get(h);
557
+ if (!cArr) {
558
+ cArr = [c];
559
+ curPositions.set(h, cArr);
560
+ }
561
+ else if (cArr.length <= HISTOGRAM_MAX_OCCURRENCES) {
562
+ cArr.push(c);
563
+ }
564
+ }
565
+ if (curPositions.size === 0)
566
+ return;
567
+ const candidates = [];
568
+ for (const [h, cArr] of curPositions) {
569
+ if (cArr.length > HISTOGRAM_MAX_OCCURRENCES)
570
+ continue;
571
+ const bArr = basePositions.get(h);
572
+ candidates.push({
573
+ score: bArr.length + cArr.length,
574
+ bArr,
575
+ cArr,
576
+ });
577
+ }
578
+ if (candidates.length === 0) {
579
+ lisIntervalFallback(bStart, bEnd, cStart, cEnd);
580
+ return;
581
+ }
582
+ candidates.sort((a, b) => a.score - b.score || a.cArr[0] - b.cArr[0]);
583
+ let bestScore = Infinity;
584
+ let bestRunLen = 0;
585
+ let bestBStart = 0;
586
+ let bestBEnd = 0;
587
+ let bestCStart = 0;
588
+ let bestCEnd = 0;
589
+ const diagCovered = new Map();
590
+ for (const cand of candidates) {
591
+ if (bestRunLen > 0 && cand.score > bestScore)
592
+ break;
593
+ for (let bi = 0; bi < cand.bArr.length; bi++) {
594
+ const bIdx = cand.bArr[bi];
595
+ for (let ci = 0; ci < cand.cArr.length; ci++) {
596
+ const cIdx = cand.cArr[ci];
597
+ const diag = bIdx - cIdx;
598
+ const spans = diagCovered.get(diag);
599
+ if (spans) {
600
+ let already = false;
601
+ for (let s = 0; s < spans.length; s++) {
602
+ const sp = spans[s];
603
+ if (cIdx >= sp[0] && cIdx < sp[1]) {
604
+ already = true;
605
+ break;
606
+ }
607
+ }
608
+ if (already)
609
+ continue;
610
+ }
611
+ if (!matchCanon(bIdx, cIdx))
612
+ continue;
613
+ let rbStart = bIdx;
614
+ let rcStart = cIdx;
615
+ while (rbStart > bStart &&
616
+ rcStart > cStart &&
617
+ !usedBase[rbStart - 1] &&
618
+ matchedCur[rcStart - 1] === -1 &&
619
+ curCanonHashes[rcStart - 1] === base.canonHashes[rbStart - 1] &&
620
+ matchCanon(rbStart - 1, rcStart - 1)) {
621
+ rbStart--;
622
+ rcStart--;
623
+ }
624
+ let rbEnd = bIdx + 1;
625
+ let rcEnd = cIdx + 1;
626
+ while (rbEnd < bEnd &&
627
+ rcEnd < cEnd &&
628
+ !usedBase[rbEnd] &&
629
+ matchedCur[rcEnd] === -1 &&
630
+ curCanonHashes[rcEnd] === base.canonHashes[rbEnd] &&
631
+ matchCanon(rbEnd, rcEnd)) {
632
+ rbEnd++;
633
+ rcEnd++;
634
+ }
635
+ if (spans) {
636
+ spans.push([rcStart, rcEnd]);
637
+ }
638
+ else {
639
+ diagCovered.set(diag, [[rcStart, rcEnd]]);
640
+ }
641
+ const runLen = rcEnd - rcStart;
642
+ const isBetter = bestRunLen === 0 ||
643
+ runLen > bestRunLen ||
644
+ (runLen === bestRunLen &&
645
+ (rcStart < bestCStart || (rcStart === bestCStart && rbStart < bestBStart)));
646
+ if (isBetter) {
647
+ bestScore = cand.score;
648
+ bestRunLen = runLen;
649
+ bestBStart = rbStart;
650
+ bestBEnd = rbEnd;
651
+ bestCStart = rcStart;
652
+ bestCEnd = rcEnd;
653
+ }
654
+ }
655
+ }
656
+ }
657
+ if (bestRunLen === 0)
658
+ return;
659
+ for (let k = 0; k < bestRunLen; k++) {
660
+ const b = bestBStart + k;
661
+ const c = bestCStart + k;
662
+ matchedCur[c] = b;
663
+ usedBase[b] = 1;
664
+ }
665
+ histogramAnchors(bStart, bestBStart, cStart, bestCStart, depth + 1);
666
+ histogramAnchors(bestBEnd, bEnd, bestCEnd, cEnd, depth + 1);
667
+ };
668
+ const initialIntervals = [];
669
+ {
670
+ let pC = -1;
671
+ let pB = -1;
672
+ for (let c = 0; c <= curLen; c++) {
673
+ const b = c < curLen ? matchedCur[c] : baseLen;
674
+ if (c < curLen && b < 0)
675
+ continue;
676
+ const bStart = pB + 1;
677
+ const bEnd = b;
678
+ const cStart = pC + 1;
679
+ const cEnd = c;
680
+ if (bEnd > bStart && cEnd > cStart) {
681
+ initialIntervals.push([bStart, bEnd, cStart, cEnd]);
682
+ }
683
+ pC = c;
684
+ pB = b;
685
+ }
686
+ }
687
+ for (const [bStart, bEnd, cStart, cEnd] of initialIntervals) {
688
+ histogramAnchors(bStart, bEnd, cStart, cEnd, 0);
689
+ }
690
+ // Gap fill between consecutive matched anchors for identical lines.
691
+ let prevC = -1;
692
+ let prevB = -1;
693
+ for (let c = 0; c <= curLines.length; c++) {
694
+ const b = c < curLines.length ? matchedCur[c] : base.lines.length;
695
+ if (c < curLines.length && b < 0)
696
+ continue;
697
+ let lc = prevC + 1;
698
+ let lb = prevB + 1;
699
+ while (lc < c && lb < b && matchCanon(lb, lc)) {
700
+ matchedCur[lc] = lb;
701
+ usedBase[lb] = 1;
702
+ lc++;
703
+ lb++;
704
+ }
705
+ let rc = c - 1;
706
+ let rb = b - 1;
707
+ while (rc >= lc && rb >= lb && matchCanon(rb, rc)) {
708
+ matchedCur[rc] = rb;
709
+ usedBase[rb] = 1;
710
+ rc--;
711
+ rb--;
712
+ }
713
+ prevC = c;
714
+ prevB = b;
715
+ }
716
+ let matchedLines = 0;
717
+ for (let c = 0; c < curLines.length; c++) {
718
+ if (matchedCur[c] >= 0)
719
+ matchedLines++;
720
+ }
721
+ if (matchedLines / Math.max(1, curLines.length, base.lines.length) < 0.65)
722
+ return null;
723
+ const gaps = [];
724
+ prevC = -1;
725
+ prevB = -1;
726
+ for (let c = 0; c <= curLines.length; c++) {
727
+ const b = c < curLines.length ? matchedCur[c] : base.lines.length;
728
+ if (c < curLines.length && b < 0)
729
+ continue;
730
+ const bStart = prevB + 1;
731
+ const bEnd = b;
732
+ const cStart = prevC + 1;
733
+ const cEnd = c;
734
+ if (bEnd > bStart || cEnd > cStart) {
735
+ gaps.push({ bStart, bEnd, cStart, cEnd });
736
+ }
737
+ prevC = c;
738
+ prevB = b;
739
+ }
740
+ if (gaps.length === 0) {
741
+ if (base.effectiveLineCount === cur.effectiveLineCount) {
742
+ let exact = true;
743
+ for (let i = 0; i < cur.effectiveLineCount; i++) {
744
+ if (base.bodies[i] !== curBodies[i]) {
745
+ exact = false;
746
+ break;
747
+ }
748
+ }
749
+ if (exact) {
750
+ const range = cur.allHaveLineNums && isMonotonicLineNums(cur.lineNums, cur.effectiveLineCount)
751
+ ? `L${cur.lineNums[0]}..${cur.lineNums[cur.effectiveLineCount - 1]}, `
752
+ : '';
753
+ return {
754
+ text: `[fiche cas: body identical to ${base.refId} (${range}${cur.effectiveLineCount} lines, ${cur.rawLength} chars) — unchanged]`,
755
+ matchedLines,
756
+ exactBodyMatch: true,
757
+ };
758
+ }
759
+ }
760
+ return null;
761
+ }
762
+ // Merge gaps whose ±HUNK_CONTEXT regions overlap, then render hunks with exact raw lines.
763
+ const hunks = [];
764
+ let gIdx = 0;
765
+ while (gIdx < gaps.length) {
766
+ const firstIdx = gIdx;
767
+ const first = gaps[firstIdx];
768
+ let last = first;
769
+ while (gIdx + 1 < gaps.length) {
770
+ const next = gaps[gIdx + 1];
771
+ if (next.cStart - HUNK_CONTEXT <= last.cEnd + HUNK_CONTEXT) {
772
+ last = next;
773
+ gIdx++;
774
+ }
775
+ else {
776
+ break;
777
+ }
778
+ }
779
+ gIdx++;
780
+ const ctxCStart = Math.max(0, first.cStart - HUNK_CONTEXT);
781
+ const ctxBStart = Math.max(0, first.bStart - HUNK_CONTEXT);
782
+ const ctxCEnd = Math.min(curLines.length, last.cEnd + HUNK_CONTEXT);
783
+ const ctxBEnd = Math.min(base.lines.length, last.bEnd + HUNK_CONTEXT);
784
+ const resolveHunkEndLineNum = (prepared, startIdx, endIdx, startNum) => {
785
+ if (prepared.allHaveLineNums && endIdx > startIdx) {
786
+ for (let k = endIdx - 1; k >= startIdx; k--) {
787
+ const ln = prepared.lineNums[k];
788
+ if (ln > 0)
789
+ return ln;
790
+ }
791
+ }
792
+ return endIdx > startIdx ? Math.max(startNum, endIdx) : endIdx;
793
+ };
794
+ const ctxBNumStart = base.allHaveLineNums && base.lineNums[ctxBStart] > 0 ? base.lineNums[ctxBStart] : ctxBStart + 1;
795
+ const ctxBNumEnd = resolveHunkEndLineNum(base, ctxBStart, ctxBEnd, ctxBNumStart);
796
+ const ctxCNumStart = cur.allHaveLineNums && cur.lineNums[ctxCStart] > 0 ? cur.lineNums[ctxCStart] : ctxCStart + 1;
797
+ const ctxCNumEnd = resolveHunkEndLineNum(cur, ctxCStart, ctxCEnd, ctxCNumStart);
798
+ const hunkLines = [
799
+ `@@ base:${ctxBNumStart}-${ctxBNumEnd} -> cur:${ctxCNumStart}-${ctxCNumEnd} @@`,
800
+ ];
801
+ for (let c = ctxCStart; c < first.cStart; c++) {
802
+ hunkLines.push(` ${curLines[c]}`);
803
+ }
804
+ for (let k = firstIdx;; k++) {
805
+ const g = gaps[k];
806
+ for (let b = g.bStart; b < g.bEnd; b++)
807
+ hunkLines.push(`-${base.lines[b]}`);
808
+ for (let c = g.cStart; c < g.cEnd; c++)
809
+ hunkLines.push(`+${curLines[c]}`);
810
+ if (g === last)
811
+ break;
812
+ const nextG = gaps[k + 1];
813
+ for (let c = g.cEnd; c < nextG.cStart; c++) {
814
+ hunkLines.push(` ${curLines[c]}`);
815
+ }
816
+ }
817
+ for (let c = last.cEnd; c < ctxCEnd; c++) {
818
+ hunkLines.push(` ${curLines[c]}`);
819
+ }
820
+ hunks.push(hunkLines.join('\n'));
821
+ }
822
+ const outText = `[fiche cas-delta vs ${base.refId}: ${matchedLines}/${curLines.length} lines unchanged; only changed hunks below (±${HUNK_CONTEXT} context)]\n` +
823
+ hunks.join('\n');
824
+ return { text: outText, matchedLines };
825
+ }
826
+ export class CasiIndex {
827
+ exactByHash = new Map();
828
+ exactBodyByHash = new Map();
829
+ lineIndex = new Map();
830
+ chunkIndex = new Map();
831
+ entries = [];
832
+ seedHashes = new Set();
833
+ seedCount = 0;
834
+ indexEntry(rawText, refId, hash64, prep, turnGroup, precomputedChunks) {
835
+ if (this.entries.length >= MAX_CASI_ENTRIES)
836
+ return;
837
+ const entryIdx = this.entries.length;
838
+ const lineFreq = new Map();
839
+ for (let i = 0; i < prep.effectiveLineCount; i++) {
840
+ if (!hasAtLeast4NonWs(prep.canonLines[i]))
841
+ continue;
842
+ const h = prep.canonHashes[i];
843
+ lineFreq.set(h, (lineFreq.get(h) ?? 0) + 1);
844
+ }
845
+ const chunks = precomputedChunks ?? computeFastCdcChunks(prep.canonLines, prep.canonHashes);
846
+ const entry = {
847
+ idx: entryIdx,
848
+ refId,
849
+ turnGroup,
850
+ rawText,
851
+ lineCount: prep.lines.length,
852
+ effectiveLineCount: prep.effectiveLineCount,
853
+ hash64,
854
+ bodyDocHash: prep.bodyDocHash,
855
+ allHaveLineNums: prep.allHaveLineNums,
856
+ isCodeLike: prep.isCodeLike,
857
+ isLogLike: prep.isLogLike,
858
+ lines: prep.lines,
859
+ bodies: prep.bodies,
860
+ canonLines: prep.canonLines,
861
+ lineNums: prep.lineNums,
862
+ canonHashes: prep.canonHashes,
863
+ lineFreq,
864
+ chunks,
865
+ };
866
+ this.entries.push(entry);
867
+ const exactBucket = this.exactByHash.get(hash64);
868
+ if (exactBucket)
869
+ exactBucket.push(entry);
870
+ else
871
+ this.exactByHash.set(hash64, [entry]);
872
+ const bodyBucket = this.exactBodyByHash.get(prep.bodyDocHash);
873
+ if (bodyBucket)
874
+ bodyBucket.push(entry);
875
+ else
876
+ this.exactBodyByHash.set(prep.bodyDocHash, [entry]);
877
+ const seenEntryHashes = new Set();
878
+ for (let i = 0; i < prep.canonLines.length; i++) {
879
+ if (!hasAtLeast4NonWs(prep.canonLines[i]))
880
+ continue;
881
+ const h = prep.canonHashes[i];
882
+ if (seenEntryHashes.has(h))
883
+ continue;
884
+ seenEntryHashes.add(h);
885
+ let postings = this.lineIndex.get(h);
886
+ if (!postings) {
887
+ postings = { total: 1, entries: [entryIdx] };
888
+ this.lineIndex.set(h, postings);
889
+ }
890
+ else {
891
+ postings.total += 1;
892
+ if (postings.total <= MAX_LINE_POSTINGS) {
893
+ postings.entries.push(entryIdx);
894
+ }
895
+ }
896
+ }
897
+ // Prefix-monotonic chunk index: first occurrence sits at the head.
898
+ const seenChunks = new Set();
899
+ for (const chunk of chunks) {
900
+ if (seenChunks.has(chunk.key))
901
+ continue;
902
+ seenChunks.add(chunk.key);
903
+ const ref = {
904
+ entryIdx,
905
+ startLine: chunk.startLine,
906
+ endLine: chunk.endLine,
907
+ lineCount: chunk.lineCount,
908
+ };
909
+ const head = this.chunkIndex.get(chunk.key);
910
+ if (!head) {
911
+ this.chunkIndex.set(chunk.key, ref);
912
+ }
913
+ else {
914
+ let cur = head;
915
+ let count = 1;
916
+ while (cur.next && count < MAX_CHUNK_REFS_PER_KEY) {
917
+ cur = cur.next;
918
+ count++;
919
+ }
920
+ if (!cur.next && count < MAX_CHUNK_REFS_PER_KEY) {
921
+ cur.next = ref;
922
+ }
923
+ }
924
+ }
925
+ }
926
+ /**
927
+ * Read-only base seeding (e.g. from `tool_use.input` / `functionCall.args` payloads >= 400 chars)
928
+ * without mutating assistant/model messages.
929
+ */
930
+ seedBase(rawText, refId, turnGroup) {
931
+ if (typeof rawText !== 'string' ||
932
+ rawText.length < MIN_EXACT_DUP_CHARS ||
933
+ rawText.length > MAX_INPUT_CHARS ||
934
+ this.entries.length >= MAX_CASI_ENTRIES ||
935
+ this.seedCount >= MAX_SEED_ENTRIES) {
936
+ return;
937
+ }
938
+ const hash64 = dualHash64Hex(rawText);
939
+ if (this.seedHashes.has(hash64))
940
+ return;
941
+ this.seedHashes.add(hash64);
942
+ this.seedCount++;
943
+ const { prep, chunks } = getPreparedAndChunks(rawText, hash64);
944
+ this.indexEntry(rawText, refId, hash64, prep, turnGroup, chunks);
945
+ }
946
+ /**
947
+ * Warm-replay counterpart of an unmatched `ingest()` base, bounded by `MAX_CASI_ENTRIES`
948
+ * (128) and independent of `MAX_SEED_ENTRIES` / `seedHashes`.
949
+ */
950
+ replayIndexedBase(rawText, refId, turnGroup) {
951
+ if (typeof rawText !== 'string' ||
952
+ rawText.length < MIN_EXACT_DUP_CHARS ||
953
+ rawText.length > MAX_INPUT_CHARS ||
954
+ this.entries.length >= MAX_CASI_ENTRIES) {
955
+ return;
956
+ }
957
+ const hash64 = dualHash64Hex(rawText);
958
+ const { prep, chunks } = getPreparedAndChunks(rawText, hash64);
959
+ this.indexEntry(rawText, refId, hash64, prep, turnGroup, chunks);
960
+ }
961
+ tryFastCdcSplice(rawText, prep, curChunks, isEligibleBase) {
962
+ if (this.chunkIndex.size === 0)
963
+ return null;
964
+ if (curChunks.length === 0)
965
+ return null;
966
+ const rawSpans = [];
967
+ // Sub-block slice omission ALWAYS verifies exact body line equality so
968
+ // numeric/timestamp/duration differences (e.g. latency tables) are never masked.
969
+ const linesEqual = (base, bIdx, cIdx) => bIdx < base.effectiveLineCount &&
970
+ cIdx < prep.effectiveLineCount &&
971
+ base.bodies[bIdx] === prep.bodies[cIdx];
972
+ for (const chunk of curChunks) {
973
+ let ref = this.chunkIndex.get(chunk.key);
974
+ while (ref) {
975
+ const base = this.entries[ref.entryIdx];
976
+ if (base && isEligibleBase(base) && ref.lineCount === chunk.lineCount) {
977
+ let exact = true;
978
+ for (let k = 0; k < chunk.lineCount; k++) {
979
+ if (!linesEqual(base, ref.startLine + k, chunk.startLine + k)) {
980
+ exact = false;
981
+ break;
982
+ }
983
+ }
984
+ if (exact) {
985
+ rawSpans.push({
986
+ curStart: chunk.startLine,
987
+ curEnd: chunk.endLine,
988
+ baseEntryIdx: ref.entryIdx,
989
+ baseStart: ref.startLine,
990
+ baseEnd: ref.endLine,
991
+ });
992
+ break;
993
+ }
994
+ }
995
+ ref = ref.next;
996
+ }
997
+ }
998
+ if (rawSpans.length === 0)
999
+ return null;
1000
+ // Pass 1: coalesce adjacent matched chunks pointing to contiguous lines in the same base.
1001
+ const merged = [rawSpans[0]];
1002
+ for (let i = 1; i < rawSpans.length; i++) {
1003
+ const prev = merged[merged.length - 1];
1004
+ const cur = rawSpans[i];
1005
+ if (prev.baseEntryIdx === cur.baseEntryIdx &&
1006
+ prev.curEnd === cur.curStart &&
1007
+ prev.baseEnd === cur.baseStart) {
1008
+ prev.curEnd = cur.curEnd;
1009
+ prev.baseEnd = cur.baseEnd;
1010
+ }
1011
+ else {
1012
+ merged.push(cur);
1013
+ }
1014
+ }
1015
+ // Pass 2: extend each span backward & forward line-by-line within non-overlapping bounds.
1016
+ for (let i = 0; i < merged.length; i++) {
1017
+ const s = merged[i];
1018
+ const base = this.entries[s.baseEntryIdx];
1019
+ const minCur = i > 0 ? merged[i - 1].curEnd : 0;
1020
+ const maxCur = i + 1 < merged.length ? merged[i + 1].curStart : prep.lines.length;
1021
+ while (s.curStart > minCur && s.baseStart > 0 && linesEqual(base, s.baseStart - 1, s.curStart - 1)) {
1022
+ s.curStart--;
1023
+ s.baseStart--;
1024
+ }
1025
+ while (s.curEnd < maxCur &&
1026
+ s.baseEnd < base.effectiveLineCount &&
1027
+ linesEqual(base, s.baseEnd, s.curEnd)) {
1028
+ s.curEnd++;
1029
+ s.baseEnd++;
1030
+ }
1031
+ }
1032
+ // Pass 3: coalesce spans that touched after line extension.
1033
+ const finalSpans = [merged[0]];
1034
+ for (let i = 1; i < merged.length; i++) {
1035
+ const prev = finalSpans[finalSpans.length - 1];
1036
+ const cur = merged[i];
1037
+ if (prev.baseEntryIdx === cur.baseEntryIdx &&
1038
+ prev.curEnd === cur.curStart &&
1039
+ prev.baseEnd === cur.baseStart) {
1040
+ prev.curEnd = cur.curEnd;
1041
+ prev.baseEnd = cur.baseEnd;
1042
+ }
1043
+ else {
1044
+ finalSpans.push(cur);
1045
+ }
1046
+ }
1047
+ const keptSlices = [];
1048
+ for (const s of finalSpans) {
1049
+ const matchLen = s.curEnd - s.curStart;
1050
+ if (matchLen < CDC_MIN_LINES)
1051
+ continue;
1052
+ const base = this.entries[s.baseEntryIdx];
1053
+ const rawSliceChars = sliceCharLength(prep.lines, s.curStart, s.curEnd);
1054
+ const baseStartNum = base.allHaveLineNums && base.lineNums[s.baseStart] > 0 ? base.lineNums[s.baseStart] : s.baseStart + 1;
1055
+ const baseEndNum = base.allHaveLineNums && s.baseEnd > 0 && base.lineNums[s.baseEnd - 1] > 0 ? base.lineNums[s.baseEnd - 1] : s.baseEnd;
1056
+ const curGutterNote = prep.allHaveLineNums && prep.lineNums[s.curStart] > 0 && prep.lineNums[s.curStart] !== s.curStart + 1
1057
+ ? `; file L${prep.lineNums[s.curStart]}..${prep.lineNums[s.curEnd - 1]}`
1058
+ : '';
1059
+ const marker = `[fiche cas-slice: lines ${s.curStart + 1}..${s.curEnd} identical to ${base.refId}:${baseStartNum}..${baseEndNum} (${matchLen} lines, ${rawSliceChars} chars) — omitted${curGutterNote}]`;
1060
+ const saved = rawSliceChars - marker.length;
1061
+ if (saved < 40)
1062
+ continue;
1063
+ keptSlices.push({ span: s, marker, saved, baseRefId: base.refId });
1064
+ }
1065
+ if (keptSlices.length === 0)
1066
+ return null;
1067
+ const outLines = [];
1068
+ let cursor = 0;
1069
+ let bestSlice = keptSlices[0];
1070
+ for (const ks of keptSlices) {
1071
+ if (ks.saved > bestSlice.saved)
1072
+ bestSlice = ks;
1073
+ for (let i = cursor; i < ks.span.curStart; i++) {
1074
+ outLines.push(prep.lines[i]);
1075
+ }
1076
+ outLines.push(ks.marker);
1077
+ cursor = ks.span.curEnd;
1078
+ }
1079
+ for (let i = cursor; i < prep.lines.length; i++) {
1080
+ outLines.push(prep.lines[i]);
1081
+ }
1082
+ const outText = outLines.join('\n');
1083
+ const savedChars = rawText.length - outText.length;
1084
+ if (savedChars < 400)
1085
+ return null;
1086
+ return {
1087
+ text: outText,
1088
+ changed: true,
1089
+ kind: 'slice',
1090
+ baseRefId: bestSlice.baseRefId,
1091
+ savedChars,
1092
+ savedTokens: estimateSavedTokens(rawText, outText),
1093
+ };
1094
+ }
1095
+ ingest(rawText, refId, turnGroup, minBaseTurnGroup) {
1096
+ if (typeof rawText !== 'string' ||
1097
+ rawText.length < MIN_EXACT_DUP_CHARS ||
1098
+ rawText.length > MAX_INPUT_CHARS) {
1099
+ return { text: rawText, changed: false, savedChars: 0, savedTokens: 0 };
1100
+ }
1101
+ const isEligibleBase = (entry) => {
1102
+ if (turnGroup !== undefined && entry.turnGroup !== undefined && !(entry.turnGroup < turnGroup)) {
1103
+ return false;
1104
+ }
1105
+ if (minBaseTurnGroup !== undefined && entry.turnGroup !== undefined && entry.turnGroup < minBaseTurnGroup) {
1106
+ return false;
1107
+ }
1108
+ return true;
1109
+ };
1110
+ // Step 1a: Exact raw duplicate check.
1111
+ const hash64 = dualHash64Hex(rawText);
1112
+ const exactCandidates = this.exactByHash.get(hash64);
1113
+ let exactHit;
1114
+ if (exactCandidates) {
1115
+ for (let i = exactCandidates.length - 1; i >= 0; i--) {
1116
+ const candidate = exactCandidates[i];
1117
+ if (isEligibleBase(candidate) && candidate.rawText === rawText) {
1118
+ exactHit = candidate;
1119
+ break;
1120
+ }
1121
+ }
1122
+ }
1123
+ if (exactHit) {
1124
+ const marker = `[fiche cas: exact duplicate of earlier tool output ${exactHit.refId} (${exactHit.lineCount} lines, ${rawText.length} chars) — unchanged; reuse verbatim content above]`;
1125
+ if (rawText.length - marker.length >= 200) {
1126
+ return {
1127
+ text: marker,
1128
+ changed: true,
1129
+ kind: 'exact_dup',
1130
+ baseRefId: exactHit.refId,
1131
+ savedChars: rawText.length - marker.length,
1132
+ savedTokens: estimateSavedTokens(rawText, marker),
1133
+ };
1134
+ }
1135
+ return { text: rawText, changed: false, savedChars: 0, savedTokens: 0 };
1136
+ }
1137
+ const { prep, chunks } = getPreparedAndChunks(rawText, hash64);
1138
+ // Step 1b: Gutter-normalized exact body duplicate (uniform line-number shift deltaL !== 0,
1139
+ // or guttered Read matching an unguttered Write seedBase).
1140
+ const bodyCandidates = this.exactBodyByHash.get(prep.bodyDocHash);
1141
+ if (bodyCandidates && prep.allHaveLineNums && isMonotonicLineNums(prep.lineNums, prep.effectiveLineCount)) {
1142
+ for (let i = bodyCandidates.length - 1; i >= 0; i--) {
1143
+ const base = bodyCandidates[i];
1144
+ if (!isEligibleBase(base) || base.effectiveLineCount !== prep.effectiveLineCount) {
1145
+ continue;
1146
+ }
1147
+ if (base.allHaveLineNums) {
1148
+ if (!isMonotonicLineNums(base.lineNums, base.effectiveLineCount))
1149
+ continue;
1150
+ const deltaL = prep.lineNums[0] - base.lineNums[0];
1151
+ if (deltaL === 0)
1152
+ continue;
1153
+ let uniform = true;
1154
+ for (let k = 0; k < prep.effectiveLineCount; k++) {
1155
+ if (prep.lineNums[k] - base.lineNums[k] !== deltaL ||
1156
+ prep.bodies[k] !== base.bodies[k]) {
1157
+ uniform = false;
1158
+ break;
1159
+ }
1160
+ }
1161
+ if (!uniform)
1162
+ continue;
1163
+ const marker = `[fiche cas: lines shifted ${deltaL > 0 ? '+' : ''}${deltaL}L vs ${base.refId} (${prep.effectiveLineCount} lines, ${rawText.length} chars) — body unchanged]`;
1164
+ if (rawText.length - marker.length >= 200) {
1165
+ return {
1166
+ text: marker,
1167
+ changed: true,
1168
+ kind: 'exact_dup',
1169
+ baseRefId: base.refId,
1170
+ savedChars: rawText.length - marker.length,
1171
+ savedTokens: estimateSavedTokens(rawText, marker),
1172
+ };
1173
+ }
1174
+ }
1175
+ else {
1176
+ let exact = true;
1177
+ for (let k = 0; k < prep.effectiveLineCount; k++) {
1178
+ if (prep.bodies[k] !== base.bodies[k]) {
1179
+ exact = false;
1180
+ break;
1181
+ }
1182
+ }
1183
+ if (!exact)
1184
+ continue;
1185
+ const first = prep.lineNums[0];
1186
+ const last = prep.lineNums[prep.effectiveLineCount - 1];
1187
+ const marker = `[fiche cas: body identical to ${base.refId} (L${first}..${last}, ${prep.effectiveLineCount} lines, ${rawText.length} chars) — unchanged]`;
1188
+ if (rawText.length - marker.length >= 200) {
1189
+ return {
1190
+ text: marker,
1191
+ changed: true,
1192
+ kind: 'exact_dup',
1193
+ baseRefId: base.refId,
1194
+ savedChars: rawText.length - marker.length,
1195
+ savedTokens: estimateSavedTokens(rawText, marker),
1196
+ };
1197
+ }
1198
+ }
1199
+ }
1200
+ }
1201
+ const canVote = this.entries.length > 0 && rawText.length >= MIN_DELTA_CHARS && prep.effectiveLineCount >= MIN_DELTA_LINES;
1202
+ if (!canVote) {
1203
+ this.indexEntry(rawText, refId, hash64, prep, turnGroup, chunks);
1204
+ return { text: rawText, changed: false, savedChars: 0, savedTokens: 0 };
1205
+ }
1206
+ // Step 2: Canonical whole-block voting & anchor-aligned unified delta.
1207
+ const votes = new Int32Array(this.entries.length);
1208
+ const seenQueryHashes = new Set();
1209
+ let anyVote = false;
1210
+ for (let i = 0; i < prep.canonLines.length; i++) {
1211
+ const canon = prep.canonLines[i];
1212
+ if (!hasAtLeast4NonWs(canon))
1213
+ continue;
1214
+ const h = prep.canonHashes[i];
1215
+ if (seenQueryHashes.has(h))
1216
+ continue;
1217
+ seenQueryHashes.add(h);
1218
+ const postings = this.lineIndex.get(h);
1219
+ if (!postings || postings.total > HOT_POSTING_VOTE_SKIP)
1220
+ continue;
1221
+ for (let p = 0; p < postings.entries.length; p++) {
1222
+ const entryIdx = postings.entries[p];
1223
+ const candidate = this.entries[entryIdx];
1224
+ if (!candidate || !isEligibleBase(candidate))
1225
+ continue;
1226
+ votes[entryIdx] += 1;
1227
+ anyVote = true;
1228
+ }
1229
+ }
1230
+ if (anyVote) {
1231
+ let bestEntryIdx = -1;
1232
+ let bestVotes = 0;
1233
+ for (let idx = 0; idx < votes.length; idx++) {
1234
+ const count = votes[idx];
1235
+ if (count > bestVotes) {
1236
+ bestVotes = count;
1237
+ bestEntryIdx = idx;
1238
+ }
1239
+ }
1240
+ if (bestEntryIdx >= 0) {
1241
+ const base = this.entries[bestEntryIdx];
1242
+ if (bestVotes >= Math.max(prep.lines.length, base.lines.length) * 0.45) {
1243
+ const delta = formatUnifiedDelta(base, prep);
1244
+ if (delta &&
1245
+ rawText.length - delta.text.length >= (delta.exactBodyMatch ? 200 : 400) &&
1246
+ (delta.exactBodyMatch || delta.text.length <= rawText.length * 0.55)) {
1247
+ return {
1248
+ text: delta.text,
1249
+ changed: true,
1250
+ kind: delta.exactBodyMatch ? 'exact_dup' : 'delta',
1251
+ baseRefId: base.refId,
1252
+ savedChars: rawText.length - delta.text.length,
1253
+ savedTokens: estimateSavedTokens(rawText, delta.text),
1254
+ };
1255
+ }
1256
+ }
1257
+ }
1258
+ }
1259
+ // Step 3: Sub-block FastCDC splice fallback when whole-block overlap < 65%.
1260
+ const spliced = this.tryFastCdcSplice(rawText, prep, chunks, isEligibleBase);
1261
+ if (spliced) {
1262
+ return spliced;
1263
+ }
1264
+ this.indexEntry(rawText, refId, hash64, prep, turnGroup, chunks);
1265
+ return { text: rawText, changed: false, savedChars: 0, savedTokens: 0 };
1266
+ }
1267
+ }
1268
+ export function createCasiIndex() {
1269
+ return new CasiIndex();
1270
+ }
1271
+ //# sourceMappingURL=casi-delta.js.map