neuralbrain 0.0.1 → 0.1.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 (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +3 -2
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
@@ -0,0 +1,1337 @@
1
+ "use strict";
2
+ /**
3
+ * Deterministic, zero-dependency extractive text condenser, query-focused
4
+ * snippet windowing engine, and information-density analyzer.
5
+ *
6
+ * Designed for both ingest-time observation condensation (zero generative model
7
+ * calls; raw `input`/`output` remain untouched in SQLite) and search-time
8
+ * passage extraction across arbitrarily long observations.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.STOPWORDS = void 0;
12
+ exports.alignUtf16Start = alignUtf16Start;
13
+ exports.alignUtf16End = alignUtf16End;
14
+ exports.safeUtf16Slice = safeUtf16Slice;
15
+ exports.splitIntoPassages = splitIntoPassages;
16
+ exports.isBoilerplatePassage = isBoilerplatePassage;
17
+ exports.scorePassageInformation = scorePassageInformation;
18
+ exports.computeInformationDensity = computeInformationDensity;
19
+ exports.condenseText = condenseText;
20
+ exports.condenseObservation = condenseObservation;
21
+ exports.parseQuerySignals = parseQuerySignals;
22
+ exports.extractQueryFocusedSnippet = extractQueryFocusedSnippet;
23
+ const MAX_SINGLE_PASSAGE_CHARS = 320;
24
+ const SUBCHUNK_TARGET_CHARS = 260;
25
+ const SUBCHUNK_MIN_BREAK_CHARS = 140;
26
+ const MAX_CONDENSE_CANDIDATE_PASSAGES = 160;
27
+ const JACCARD_WINDOW_SIZE = 20;
28
+ const MAX_QUERY_PARSE_CHARS = 8_000;
29
+ const MAX_DENSITY_SAMPLE_CHARS = 12_000;
30
+ const MAX_DENSITY_SAMPLE_LINES = 200;
31
+ function isHighSurrogate(code) {
32
+ return code >= 0xd800 && code <= 0xdbff;
33
+ }
34
+ function isLowSurrogate(code) {
35
+ return code >= 0xdc00 && code <= 0xdfff;
36
+ }
37
+ /**
38
+ * Advances `index` past a trailing low surrogate when `index` splits a valid UTF-16 surrogate pair.
39
+ */
40
+ function alignUtf16Start(text, index) {
41
+ if (index <= 0)
42
+ return 0;
43
+ if (index >= text.length)
44
+ return text.length;
45
+ if (isLowSurrogate(text.charCodeAt(index)) && isHighSurrogate(text.charCodeAt(index - 1))) {
46
+ return index + 1;
47
+ }
48
+ return index;
49
+ }
50
+ /**
51
+ * Retreats `end` before a dangling high surrogate when `end` splits a valid UTF-16 surrogate pair.
52
+ */
53
+ function alignUtf16End(text, end, minStart = 0) {
54
+ if (end <= minStart)
55
+ return minStart;
56
+ if (end >= text.length)
57
+ return text.length;
58
+ if (isHighSurrogate(text.charCodeAt(end - 1)) && isLowSurrogate(text.charCodeAt(end))) {
59
+ return Math.max(minStart, end - 1);
60
+ }
61
+ return end;
62
+ }
63
+ /**
64
+ * Slices `text` cleanly on UTF-16 code-point boundaries so lone surrogates are never emitted.
65
+ */
66
+ function safeUtf16Slice(text, start, end) {
67
+ const len = text.length;
68
+ const s = alignUtf16Start(text, Math.max(0, Math.min(len, start)));
69
+ const rawEnd = end === undefined ? len : Math.max(s, Math.min(len, end));
70
+ const e = alignUtf16End(text, rawEnd, s);
71
+ return text.slice(s, e);
72
+ }
73
+ const NON_BREAKING_ABBREVIATIONS = new Set([
74
+ 'e.g',
75
+ 'i.e',
76
+ 'vs',
77
+ 'v',
78
+ 'etc',
79
+ 'cf',
80
+ 'al',
81
+ 'approx',
82
+ 'est',
83
+ 'min',
84
+ 'max',
85
+ 'fig',
86
+ 'figs',
87
+ 'eq',
88
+ 'no',
89
+ 'nos',
90
+ 'vol',
91
+ 'ch',
92
+ 'sec',
93
+ 'pp',
94
+ 'inc',
95
+ 'corp',
96
+ 'ltd',
97
+ 'co',
98
+ 'jr',
99
+ 'sr',
100
+ 'st',
101
+ 'ave',
102
+ 'blvd',
103
+ 'rd',
104
+ 'dr',
105
+ 'mr',
106
+ 'mrs',
107
+ 'ms',
108
+ 'prof',
109
+ 'rev',
110
+ 'gen',
111
+ 'col',
112
+ 'capt',
113
+ 'sgt',
114
+ 'jan',
115
+ 'feb',
116
+ 'mar',
117
+ 'apr',
118
+ 'jun',
119
+ 'jul',
120
+ 'aug',
121
+ 'sep',
122
+ 'sept',
123
+ 'oct',
124
+ 'nov',
125
+ 'dec',
126
+ 'u.s',
127
+ 'u.k',
128
+ 'e.u',
129
+ 'a.m',
130
+ 'p.m',
131
+ ]);
132
+ exports.STOPWORDS = new Set([
133
+ 'a',
134
+ 'about',
135
+ 'above',
136
+ 'after',
137
+ 'again',
138
+ 'against',
139
+ 'all',
140
+ 'also',
141
+ 'am',
142
+ 'an',
143
+ 'and',
144
+ 'any',
145
+ 'are',
146
+ 'aren',
147
+ 'as',
148
+ 'at',
149
+ 'be',
150
+ 'because',
151
+ 'been',
152
+ 'before',
153
+ 'being',
154
+ 'below',
155
+ 'between',
156
+ 'both',
157
+ 'but',
158
+ 'by',
159
+ 'can',
160
+ 'could',
161
+ 'did',
162
+ 'didn',
163
+ 'do',
164
+ 'does',
165
+ 'doesn',
166
+ 'doing',
167
+ 'don',
168
+ 'down',
169
+ 'during',
170
+ 'each',
171
+ 'few',
172
+ 'for',
173
+ 'from',
174
+ 'further',
175
+ 'get',
176
+ 'got',
177
+ 'had',
178
+ 'has',
179
+ 'have',
180
+ 'having',
181
+ 'he',
182
+ 'her',
183
+ 'here',
184
+ 'hers',
185
+ 'herself',
186
+ 'him',
187
+ 'himself',
188
+ 'his',
189
+ 'how',
190
+ 'i',
191
+ 'if',
192
+ 'in',
193
+ 'into',
194
+ 'is',
195
+ 'isn',
196
+ 'it',
197
+ 'its',
198
+ 'itself',
199
+ 'just',
200
+ 'let',
201
+ 'make',
202
+ 'may',
203
+ 'me',
204
+ 'might',
205
+ 'more',
206
+ 'most',
207
+ 'must',
208
+ 'my',
209
+ 'myself',
210
+ 'no',
211
+ 'nor',
212
+ 'not',
213
+ 'now',
214
+ 'of',
215
+ 'off',
216
+ 'on',
217
+ 'once',
218
+ 'only',
219
+ 'or',
220
+ 'other',
221
+ 'ought',
222
+ 'our',
223
+ 'ours',
224
+ 'ourselves',
225
+ 'out',
226
+ 'over',
227
+ 'own',
228
+ 'please',
229
+ 'same',
230
+ 'she',
231
+ 'should',
232
+ 'so',
233
+ 'some',
234
+ 'such',
235
+ 'than',
236
+ 'that',
237
+ 'the',
238
+ 'their',
239
+ 'theirs',
240
+ 'them',
241
+ 'themselves',
242
+ 'then',
243
+ 'there',
244
+ 'these',
245
+ 'they',
246
+ 'this',
247
+ 'those',
248
+ 'through',
249
+ 'to',
250
+ 'too',
251
+ 'under',
252
+ 'until',
253
+ 'up',
254
+ 'very',
255
+ 'was',
256
+ 'wasn',
257
+ 'we',
258
+ 'were',
259
+ 'weren',
260
+ 'what',
261
+ 'when',
262
+ 'where',
263
+ 'which',
264
+ 'while',
265
+ 'who',
266
+ 'whom',
267
+ 'why',
268
+ 'will',
269
+ 'with',
270
+ 'would',
271
+ 'you',
272
+ 'your',
273
+ 'yours',
274
+ 'yourself',
275
+ 'yourselves',
276
+ // Assistant conversational filler words excluded from content-density vocabulary
277
+ 'sure',
278
+ 'certainly',
279
+ 'absolutely',
280
+ 'definitely',
281
+ 'happy',
282
+ 'glad',
283
+ 'help',
284
+ 'helps',
285
+ 'helping',
286
+ 'hope',
287
+ 'feel',
288
+ 'free',
289
+ 'ask',
290
+ 'questions',
291
+ 'question',
292
+ 'know',
293
+ 'need',
294
+ 'anything',
295
+ 'else',
296
+ 'further',
297
+ 'hesitate',
298
+ 'reach',
299
+ 'additionally',
300
+ 'furthermore',
301
+ 'moreover',
302
+ 'overall',
303
+ ]);
304
+ const CODE_FENCE_ONLY_RE = /^`{3,}[a-zA-Z0-9_-]*$/;
305
+ function isHorizontalRule(trimmed) {
306
+ if (trimmed.length < 3 || trimmed.length > 500)
307
+ return false;
308
+ let markerChar = '';
309
+ let markerCount = 0;
310
+ for (let i = 0; i < trimmed.length; i++) {
311
+ const ch = trimmed[i];
312
+ if (ch === ' ' || ch === '\t')
313
+ continue;
314
+ if (ch !== '-' && ch !== '*' && ch !== '_')
315
+ return false;
316
+ if (!markerChar)
317
+ markerChar = ch;
318
+ else if (ch !== markerChar)
319
+ return false;
320
+ markerCount++;
321
+ }
322
+ return markerCount >= 3;
323
+ }
324
+ const PURE_BOILERPLATE_PATTERNS = [
325
+ /^(?:sure|certainly|absolutely|of course|definitely|great|awesome|no problem|gladly|happy to help)(?:[!,.:\s]+(?:i(?:'d| would) be (?:happy|glad|delighted) to (?:help|assist)[^.!?]{0,90}|i can (?:certainly |definitely )?(?:help|assist)[^.!?]{0,90}|here(?:'s| is| are)\b[^.!?]{0,90}))?[!.:]?$/i,
326
+ /^i(?:'d| would) be (?:more than )?(?:happy|glad|delighted) to (?:help|assist)\b[^.!?]{0,90}[!.:]?$/i,
327
+ /^i can (?:certainly |definitely )?(?:help|assist) you\b[^.!?]{0,90}[!.:]?$/i,
328
+ /^(?:great|good|excellent|wonderful|interesting) question[!.]?$/i,
329
+ /^(?:here(?:'s| is| are)|below (?:is|are)) (?:a |an |the |some )?(?:comprehensive |detailed |quick |brief |step-by-step |helpful |curated |complete |general )?(?:list|overview|breakdown|summary|guide|explanation|look|set|collection|comparison|suggestions?|recommendations?|tips?|steps?|ideas?|options?|ways?|things?|points?)(?: (?:of|on|for|to|about|that|you)[a-zA-Z\s,'-]{0,80})?[:.]$/i,
330
+ /^(?:i )?hope (?:this|that|these)(?: (?:information|explanation|guide|list|suggestions?|tips?))? helps?(?: you)?[!.]?$/i,
331
+ /^feel free to (?:ask|reach out|let me know)(?: if you have (?:any )?(?:more |further |other |additional )?questions?(?: or concerns?)?)?[!.]?$/i,
332
+ /^(?:please )?let me know if (?:you (?:need|have|want|would like)|there(?:'s| is)) (?:anything else|any (?:other |more |further )?questions?|me to [a-zA-Z\s]{1,50})[!.]?$/i,
333
+ /^don't hesitate to (?:ask|reach out)[^.!?]{0,60}[!.]?$/i,
334
+ /^happy (?:coding|building|debugging|helping|travels|cooking)[!.]?$/i,
335
+ /^good luck(?: with your [a-zA-Z\s]{1,40})?[!.]?$/i,
336
+ ];
337
+ const GENERIC_SECTION_HEADING_RE = /^\s*#{1,6}\s*(?:overview|introduction|summary|conclusion|final thoughts|key takeaways|tips(?: and tricks)?|recommendations|things to consider|best practices|general advice|additional tips)\s*:?\s*$/i;
338
+ const GENERIC_BOLD_BULLET_RE = /^\s*(?:[-*+]|\d+[.)])\s+\*\*[^*\n]{2,55}\*\*\s*[:—–-]\s*/;
339
+ const CLOSING_PUNCT_CHARS = new Set(['"', "'", '”', '’', ')', ']', '}', '`']);
340
+ function isWhitespaceChar(code) {
341
+ return code === 32 || code === 9 || code === 10 || code === 13 || code === 12 || code === 11;
342
+ }
343
+ function isSentenceClosingChar(ch) {
344
+ return CLOSING_PUNCT_CHARS.has(ch);
345
+ }
346
+ function isWordTokenChar(ch) {
347
+ const c = ch.charCodeAt(0);
348
+ return ((c >= 48 && c <= 57) || // 0-9
349
+ (c >= 65 && c <= 90) || // A-Z
350
+ (c >= 97 && c <= 122) || // a-z
351
+ c === 46 || // .
352
+ c === 95 || // _
353
+ c === 45 // -
354
+ );
355
+ }
356
+ function trimSpan(text, start, end) {
357
+ let s = alignUtf16Start(text, start);
358
+ let e = alignUtf16End(text, end, s);
359
+ while (s < e && isWhitespaceChar(text.charCodeAt(s)))
360
+ s++;
361
+ while (e > s && isWhitespaceChar(text.charCodeAt(e - 1)))
362
+ e--;
363
+ s = alignUtf16Start(text, s);
364
+ e = alignUtf16End(text, e, s);
365
+ if (s >= e)
366
+ return null;
367
+ return { text: text.slice(s, e), start: s, end: e };
368
+ }
369
+ function pushBoundedSpan(out, fullText, start, end) {
370
+ const trimmed = trimSpan(fullText, start, end);
371
+ if (!trimmed)
372
+ return;
373
+ if (trimmed.end - trimmed.start <= MAX_SINGLE_PASSAGE_CHARS) {
374
+ out.push(trimmed);
375
+ return;
376
+ }
377
+ let cur = trimmed.start;
378
+ const limitEnd = trimmed.end;
379
+ while (cur < limitEnd) {
380
+ if (limitEnd - cur <= MAX_SINGLE_PASSAGE_CHARS) {
381
+ const tail = trimSpan(fullText, cur, limitEnd);
382
+ if (tail)
383
+ out.push(tail);
384
+ break;
385
+ }
386
+ const windowMax = Math.min(limitEnd, cur + MAX_SINGLE_PASSAGE_CHARS);
387
+ const preferredEnd = Math.min(limitEnd, cur + SUBCHUNK_TARGET_CHARS);
388
+ const minBreak = cur + SUBCHUNK_MIN_BREAK_CHARS;
389
+ let splitAt = -1;
390
+ // Prefer clause boundary (; or ,) followed by space
391
+ for (let i = preferredEnd; i >= minBreak; i--) {
392
+ const ch = fullText[i - 1];
393
+ if ((ch === ';' || ch === ',') && i < limitEnd && isWhitespaceChar(fullText.charCodeAt(i))) {
394
+ splitAt = i;
395
+ break;
396
+ }
397
+ }
398
+ // Otherwise split at whitespace near target
399
+ if (splitAt === -1) {
400
+ for (let i = windowMax; i >= minBreak; i--) {
401
+ if (isWhitespaceChar(fullText.charCodeAt(i))) {
402
+ splitAt = i;
403
+ break;
404
+ }
405
+ }
406
+ }
407
+ // Hard cut for whitespace-free blobs (e.g. long hex/base64/emoji/repeated chars)
408
+ if (splitAt === -1 || splitAt <= cur) {
409
+ splitAt = alignUtf16End(fullText, preferredEnd, cur + 1);
410
+ if (splitAt <= cur) {
411
+ splitAt = Math.min(limitEnd, cur + 2);
412
+ }
413
+ }
414
+ else {
415
+ splitAt = alignUtf16End(fullText, splitAt, cur + 1);
416
+ }
417
+ const chunk = trimSpan(fullText, cur, splitAt);
418
+ if (chunk)
419
+ out.push(chunk);
420
+ cur = alignUtf16Start(fullText, splitAt);
421
+ while (cur < limitEnd && isWhitespaceChar(fullText.charCodeAt(cur)))
422
+ cur++;
423
+ }
424
+ }
425
+ /**
426
+ * Splits text into sentence/line passages while preserving exact `{ start, end }`
427
+ * character offsets into `text` (`text.slice(span.start, span.end) === span.text`).
428
+ *
429
+ * Avoids breaking decimals (`3.14`), version numbers (`v1.2.3`), file paths
430
+ * (`src/learning/search.ts`), URLs, list item prefixes (`1. Item`), and common
431
+ * abbreviations (`e.g.`, `i.e.`, `vs.`, `Mr.`, `Mrs.`, `Dr.`, `etc.`).
432
+ */
433
+ function splitIntoPassages(text) {
434
+ if (!text || typeof text !== 'string')
435
+ return [];
436
+ const spans = [];
437
+ const len = text.length;
438
+ let lineStart = 0;
439
+ while (lineStart < len) {
440
+ let lineEnd = lineStart;
441
+ while (lineEnd < len && text.charCodeAt(lineEnd) !== 10 && text.charCodeAt(lineEnd) !== 13) {
442
+ lineEnd++;
443
+ }
444
+ splitLineIntoSentences(text, lineStart, lineEnd, spans);
445
+ lineStart = lineEnd;
446
+ while (lineStart < len && (text.charCodeAt(lineStart) === 10 || text.charCodeAt(lineStart) === 13)) {
447
+ lineStart++;
448
+ }
449
+ }
450
+ return spans;
451
+ }
452
+ function splitLineIntoSentences(text, lineStart, lineEnd, out) {
453
+ let segStart = lineStart;
454
+ while (segStart < lineEnd && isWhitespaceChar(text.charCodeAt(segStart)))
455
+ segStart++;
456
+ if (segStart >= lineEnd)
457
+ return;
458
+ let i = segStart;
459
+ while (i < lineEnd) {
460
+ const ch = text[i];
461
+ if (ch !== '.' && ch !== '!' && ch !== '?') {
462
+ i++;
463
+ continue;
464
+ }
465
+ let pEnd = i;
466
+ while (pEnd + 1 < lineEnd &&
467
+ (text[pEnd + 1] === '.' || text[pEnd + 1] === '!' || text[pEnd + 1] === '?')) {
468
+ pEnd++;
469
+ }
470
+ let afterPunct = pEnd + 1;
471
+ while (afterPunct < lineEnd && isSentenceClosingChar(text[afterPunct])) {
472
+ afterPunct++;
473
+ }
474
+ // End of line: flush at outer loop completion
475
+ if (afterPunct >= lineEnd) {
476
+ break;
477
+ }
478
+ // Sentence-ending punctuation inside a line must be followed by whitespace.
479
+ // This immediately protects `3.14`, `v1.2.3`, `src/learning/search.ts`, and URLs.
480
+ if (!isWhitespaceChar(text.charCodeAt(afterPunct))) {
481
+ i = afterPunct;
482
+ continue;
483
+ }
484
+ let nextNonSpace = afterPunct;
485
+ while (nextNonSpace < lineEnd && isWhitespaceChar(text.charCodeAt(nextNonSpace))) {
486
+ nextNonSpace++;
487
+ }
488
+ if (nextNonSpace >= lineEnd) {
489
+ break;
490
+ }
491
+ if (ch === '.' && pEnd === i) {
492
+ // Inspect token immediately preceding '.'
493
+ let tokStart = i;
494
+ while (tokStart > segStart && isWordTokenChar(text[tokStart - 1])) {
495
+ tokStart--;
496
+ }
497
+ const rawPrevToken = text.slice(tokStart, i);
498
+ const cleanPrevLower = rawPrevToken.replace(/^\.+|\.+$/g, '').toLowerCase();
499
+ // 1. Protect ordered list item markers at start of segment: `1. Foo`, `a. Bar`
500
+ if (tokStart === segStart && /^(?:\d{1,3}|[a-zA-Z])$/.test(rawPrevToken)) {
501
+ i = afterPunct;
502
+ continue;
503
+ }
504
+ // 2. Protect known abbreviations (`e.g.`, `i.e.`, `vs.`, `Mr.`, `Mrs.`, `Dr.`, `etc.`)
505
+ if (NON_BREAKING_ABBREVIATIONS.has(cleanPrevLower) ||
506
+ /^(?:[a-z]\.)+[a-z]$/i.test(cleanPrevLower)) {
507
+ i = afterPunct;
508
+ continue;
509
+ }
510
+ // 3. Protect single-letter initials (`J. K. Rowling`, `E. coli`)
511
+ if (rawPrevToken.length === 1 && /[A-Z]/.test(rawPrevToken)) {
512
+ const nextChar = text[nextNonSpace];
513
+ if (/[A-Z]/.test(nextChar)) {
514
+ i = afterPunct;
515
+ continue;
516
+ }
517
+ }
518
+ // 4. Do not split on '.' when the next token begins with a lowercase letter
519
+ const nextChar = text[nextNonSpace];
520
+ if (nextChar >= 'a' && nextChar <= 'z') {
521
+ i = afterPunct;
522
+ continue;
523
+ }
524
+ }
525
+ pushBoundedSpan(out, text, segStart, afterPunct);
526
+ segStart = nextNonSpace;
527
+ i = segStart;
528
+ }
529
+ if (segStart < lineEnd) {
530
+ pushBoundedSpan(out, text, segStart, lineEnd);
531
+ }
532
+ }
533
+ const HIGH_SIGNAL_CONCRETE_RE = /(?:\b\d+(?:[.:/-]\d+)*\b|(?<![a-zA-Z0-9_.-])[a-z0-9_.-]+\/[a-z0-9_./-]+|\b[a-z]+_[a-z0-9_]+\b|\b[a-z]+[A-Z][a-zA-Z0-9]*\b|`[^`\n]+`|\b(?:ENOENT|ECONNREFUSED|EADDRINUSE|TypeError|SyntaxError|ReferenceError|SqliteError|Exception|HTTP\s+[45]\d\d)\b)/;
534
+ function stripLeadingListMarker(text) {
535
+ return text.replace(/^\s*(?:[-*+]|\d{1,3}[.)])\s+/, '');
536
+ }
537
+ function hasConcreteSignal(text) {
538
+ return HIGH_SIGNAL_CONCRETE_RE.test(stripLeadingListMarker(text));
539
+ }
540
+ /**
541
+ * Returns true if a passage is pure conversational filler, decorative divider,
542
+ * or generic section heading carrying zero concrete domain facts.
543
+ */
544
+ function isBoilerplatePassage(text) {
545
+ if (!text || typeof text !== 'string')
546
+ return true;
547
+ // Fast scan of first/last non-whitespace indices before allocating a trimmed copy on huge blobs
548
+ let start = 0;
549
+ let end = text.length;
550
+ while (start < end && isWhitespaceChar(text.charCodeAt(start)))
551
+ start++;
552
+ while (end > start && isWhitespaceChar(text.charCodeAt(end - 1)))
553
+ end--;
554
+ const trimmedLen = end - start;
555
+ if (trimmedLen <= 0)
556
+ return true;
557
+ if (trimmedLen > 500)
558
+ return false;
559
+ const trimmed = start === 0 && end === text.length ? text : text.slice(start, end);
560
+ if (isHorizontalRule(trimmed))
561
+ return true;
562
+ if (trimmedLen <= 80 && CODE_FENCE_ONLY_RE.test(trimmed))
563
+ return true;
564
+ if (trimmedLen > 280)
565
+ return false;
566
+ if (GENERIC_SECTION_HEADING_RE.test(trimmed))
567
+ return true;
568
+ if (hasConcreteSignal(trimmed)) {
569
+ return false;
570
+ }
571
+ for (const pat of PURE_BOILERPLATE_PATTERNS) {
572
+ if (pat.test(trimmed))
573
+ return true;
574
+ }
575
+ return false;
576
+ }
577
+ const ASCII_ONLY_RE = /^[\x00-\x7f]*$/;
578
+ const ASCII_WORD_RE = /[a-z0-9_]+/g;
579
+ const UNICODE_WORD_RE = /[\p{L}\p{N}_]+/gu;
580
+ const CJK_RUN_RE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu;
581
+ const NON_CJK_WORD_RE = /[^\P{L}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}0-9_]+|[\p{N}_]+/gu;
582
+ function extractNormalizedTokens(text) {
583
+ if (!text)
584
+ return [];
585
+ const lower = text.toLowerCase();
586
+ if (ASCII_ONLY_RE.test(lower)) {
587
+ const matches = lower.match(ASCII_WORD_RE);
588
+ return matches ? matches : [];
589
+ }
590
+ const wordRuns = lower.match(UNICODE_WORD_RE);
591
+ if (!wordRuns)
592
+ return [];
593
+ const tokens = [];
594
+ for (const run of wordRuns) {
595
+ if (ASCII_ONLY_RE.test(run)) {
596
+ tokens.push(run);
597
+ continue;
598
+ }
599
+ let hadCjk = false;
600
+ CJK_RUN_RE.lastIndex = 0;
601
+ let cm;
602
+ while ((cm = CJK_RUN_RE.exec(run)) !== null) {
603
+ hadCjk = true;
604
+ const chars = Array.from(cm[0]);
605
+ if (chars.length === 1) {
606
+ tokens.push(chars[0]);
607
+ }
608
+ else {
609
+ for (let i = 0; i + 1 < chars.length; i++) {
610
+ tokens.push(chars[i] + chars[i + 1]);
611
+ }
612
+ }
613
+ }
614
+ if (!hadCjk) {
615
+ tokens.push(run);
616
+ }
617
+ else {
618
+ const nonCjk = run.replace(CJK_RUN_RE, ' ').trim();
619
+ if (nonCjk) {
620
+ const sub = nonCjk.match(UNICODE_WORD_RE);
621
+ if (sub)
622
+ tokens.push(...sub);
623
+ }
624
+ void NON_CJK_WORD_RE;
625
+ }
626
+ }
627
+ return tokens;
628
+ }
629
+ function tokenSetJaccard(a, b) {
630
+ if (a.size === 0 && b.size === 0)
631
+ return 1;
632
+ if (a.size === 0 || b.size === 0)
633
+ return 0;
634
+ const minSize = a.size <= b.size ? a.size : b.size;
635
+ const maxSize = a.size <= b.size ? b.size : a.size;
636
+ if (minSize / maxSize < 0.85)
637
+ return 0;
638
+ let intersection = 0;
639
+ const smaller = a.size <= b.size ? a : b;
640
+ const larger = a.size <= b.size ? b : a;
641
+ for (const tok of smaller) {
642
+ if (larger.has(tok))
643
+ intersection++;
644
+ }
645
+ const union = a.size + b.size - intersection;
646
+ return union === 0 ? 0 : intersection / union;
647
+ }
648
+ const CODE_IDENTIFIER_RE = /\b(?:[a-z]+[A-Z][a-zA-Z0-9]*|[A-Z][a-z0-9]+[A-Z][a-zA-Z0-9]*|[a-zA-Z0-9]+_[a-zA-Z0-9_]+|[A-Z]{2,}[0-9_]*)\b/g;
649
+ const FILE_OR_URL_RE = /(?:https?:\/\/[^\s)]+|(?<![a-zA-Z0-9_.-])(?:\.{0,2}\/)?[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_./-]+|\b[a-zA-Z0-9_-]+\.(?:ts|tsx|js|jsx|json|py|rs|go|sql|sh|yml|yaml|toml|md|env|conf|lock)\b)/g;
650
+ const CLI_FLAG_OR_CMD_RE = /(?:(?:^|\s)--?[a-zA-Z][a-zA-Z0-9_-]*|\b(?:npm|npx|node|git|docker|curl|jest|tsc|pytest|cargo|kubectl)\s+[a-z0-9_-]+)/g;
651
+ const NUMBER_DATE_UNIT_RE = /(?:[$€£¥]\s?\d+(?:[.,]\d+)*|\b\d+(?:[.,]\d+)?(?:\s?(?:%|ms|s|sec|secs|m|min|mins|h|hr|hrs|d|days?|weeks?|months?|years?|kb|mb|gb|tb|px|rem))?\b|\bv\d+\.\d+(?:\.\d+)*\b|\b\d{4}-\d{2}-\d{2}\b)/gi;
652
+ const ERROR_MARKER_RE = /\b(?:error|exception|failed|failure|enoent|econnrefused|eaddrinuse|eacces|etimedout|typeerror|syntaxerror|referenceerror|sqliteerror|panic|fatal|stderr|[45]\d\d)\b/gi;
653
+ const QUOTED_LITERAL_RE = /(?:"[^"\n]{2,80}"|'[^'\n]{2,80}'|`[^`\n]{1,100}`)/g;
654
+ const FIRST_PERSON_FACT_RE = /\b(?:i\s+(?:prefer|like|love|dislike|hate|use|switched|moved|chose|decided|set|configured|live|work|bought|booked|scheduled|started|stopped|want|need|always|never)|we\s+(?:decided|chose|switched|use|migrated|standardized|agreed|prefer|set)|my\s+[a-z]{2,}|always\b|never\b)\b/gi;
655
+ function countRegexMatches(text, re, cap = 8) {
656
+ re.lastIndex = 0;
657
+ let count = 0;
658
+ while (count < cap && re.exec(text) !== null) {
659
+ count++;
660
+ }
661
+ return count;
662
+ }
663
+ function countMidSentenceProperNouns(text) {
664
+ const words = text.split(/\s+/);
665
+ let count = 0;
666
+ for (let i = 1; i < words.length && count < 6; i++) {
667
+ const cleaned = words[i].replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, '');
668
+ if (/^[A-Z][a-z]{2,}$/.test(cleaned) && !exports.STOPWORDS.has(cleaned.toLowerCase())) {
669
+ count++;
670
+ }
671
+ }
672
+ return count;
673
+ }
674
+ /**
675
+ * Scores a single passage deterministically by information density and position.
676
+ */
677
+ function scorePassageInformation(text, index = 0, totalSubstantive = 1) {
678
+ const trimmed = text.trim();
679
+ if (!trimmed || isBoilerplatePassage(trimmed))
680
+ return 0;
681
+ let score = 1.0;
682
+ const withoutMarker = stripLeadingListMarker(trimmed);
683
+ const codeIds = countRegexMatches(withoutMarker, CODE_IDENTIFIER_RE, 6);
684
+ const pathsUrls = countRegexMatches(withoutMarker, FILE_OR_URL_RE, 4);
685
+ const cliFlags = countRegexMatches(withoutMarker, CLI_FLAG_OR_CMD_RE, 4);
686
+ const numbersDates = countRegexMatches(withoutMarker, NUMBER_DATE_UNIT_RE, 6);
687
+ const errors = countRegexMatches(withoutMarker, ERROR_MARKER_RE, 5);
688
+ const quotes = countRegexMatches(withoutMarker, QUOTED_LITERAL_RE, 4);
689
+ const firstPerson = countRegexMatches(withoutMarker, FIRST_PERSON_FACT_RE, 4);
690
+ const properNouns = countMidSentenceProperNouns(withoutMarker);
691
+ score += codeIds * 1.4;
692
+ score += pathsUrls * 2.2;
693
+ score += cliFlags * 1.5;
694
+ score += numbersDates * 1.6;
695
+ score += errors * 2.0;
696
+ score += quotes * 1.3;
697
+ score += firstPerson * 2.1;
698
+ score += properNouns * 1.1;
699
+ // Content token richness per character
700
+ const tokens = extractNormalizedTokens(trimmed);
701
+ if (tokens.length > 0) {
702
+ const uniqueContent = new Set(tokens.filter((t) => !exports.STOPWORDS.has(t) && t.length >= 2));
703
+ const contentRatio = uniqueContent.size / tokens.length;
704
+ score += contentRatio * 2.0;
705
+ }
706
+ // Position bonuses: lead sentence & conclusion sentence
707
+ if (index === 0) {
708
+ score += 1.35;
709
+ }
710
+ else if (totalSubstantive > 2 && index === totalSubstantive - 1) {
711
+ score += 0.85;
712
+ }
713
+ // Dampen generic markdown `**Bold Title**: generic advice` list items lacking concrete signals
714
+ const concreteCount = codeIds + pathsUrls + cliFlags + numbersDates + errors + firstPerson;
715
+ if (GENERIC_BOLD_BULLET_RE.test(trimmed) && concreteCount === 0) {
716
+ score *= 0.45;
717
+ }
718
+ // Normalize gently against ultra-wordy clauses so crisp high-signal lines win
719
+ const lengthFactor = Math.max(1, Math.sqrt(trimmed.length / 90));
720
+ return score / lengthFactor;
721
+ }
722
+ /**
723
+ * Analyzes overall information density of a text to distinguish concise high-signal
724
+ * memories/logs from verbose generic assistant essays and repetitive lists.
725
+ */
726
+ function computeInformationDensity(text) {
727
+ if (!text || typeof text !== 'string') {
728
+ return { density: 0, uniqueContentRatio: 0, boilerplateListRatio: 0 };
729
+ }
730
+ const trimmed = text.trim();
731
+ if (!trimmed) {
732
+ return { density: 0, uniqueContentRatio: 0, boilerplateListRatio: 0 };
733
+ }
734
+ // Cap analyzed slice to guarantee sub-millisecond scoring on huge tool dumps
735
+ const sample = trimmed.length > MAX_DENSITY_SAMPLE_CHARS
736
+ ? safeUtf16Slice(trimmed, 0, MAX_DENSITY_SAMPLE_CHARS)
737
+ : trimmed;
738
+ const tokens = extractNormalizedTokens(sample);
739
+ if (tokens.length === 0) {
740
+ return { density: 0, uniqueContentRatio: 0, boilerplateListRatio: 0 };
741
+ }
742
+ const uniqueContent = new Set();
743
+ for (const tok of tokens) {
744
+ if (tok.length >= 2 && !exports.STOPWORDS.has(tok)) {
745
+ uniqueContent.add(tok);
746
+ }
747
+ }
748
+ const uniqueContentRatio = Math.min(1, uniqueContent.size / tokens.length);
749
+ const allRawLines = sample
750
+ .split(/\r?\n/)
751
+ .map((l) => l.trim())
752
+ .filter((l) => l.length > 0);
753
+ let rawLines = allRawLines;
754
+ if (allRawLines.length > MAX_DENSITY_SAMPLE_LINES) {
755
+ const step = allRawLines.length / MAX_DENSITY_SAMPLE_LINES;
756
+ rawLines = [];
757
+ for (let i = 0; i < MAX_DENSITY_SAMPLE_LINES; i++) {
758
+ rawLines.push(allRawLines[Math.floor(i * step)]);
759
+ }
760
+ }
761
+ let boilerplateOrGenericLines = 0;
762
+ for (const line of rawLines) {
763
+ if (isBoilerplatePassage(line)) {
764
+ boilerplateOrGenericLines++;
765
+ continue;
766
+ }
767
+ if (GENERIC_BOLD_BULLET_RE.test(line) && !hasConcreteSignal(line)) {
768
+ boilerplateOrGenericLines++;
769
+ continue;
770
+ }
771
+ if (/^\s*(?:[-*+]|\d+[.)])\s+/.test(line) &&
772
+ !hasConcreteSignal(line) &&
773
+ !FIRST_PERSON_FACT_RE.test(line)) {
774
+ FIRST_PERSON_FACT_RE.lastIndex = 0;
775
+ boilerplateOrGenericLines += 0.65;
776
+ }
777
+ FIRST_PERSON_FACT_RE.lastIndex = 0;
778
+ }
779
+ const boilerplateListRatio = rawLines.length > 0 ? Math.min(1, boilerplateOrGenericLines / rawLines.length) : 0;
780
+ const concreteSignals = countRegexMatches(sample, CODE_IDENTIFIER_RE, 20) +
781
+ countRegexMatches(sample, FILE_OR_URL_RE, 15) +
782
+ countRegexMatches(sample, NUMBER_DATE_UNIT_RE, 20) +
783
+ countRegexMatches(sample, ERROR_MARKER_RE, 15) +
784
+ countRegexMatches(sample, FIRST_PERSON_FACT_RE, 12);
785
+ const signalRate = Math.min(1, concreteSignals / Math.max(3, sample.length / 110));
786
+ const rawDensity = 0.50 * uniqueContentRatio + 0.45 * signalRate - 0.35 * boilerplateListRatio + 0.08;
787
+ const density = Math.max(0, Math.min(1, rawDensity));
788
+ return {
789
+ density,
790
+ uniqueContentRatio,
791
+ boilerplateListRatio,
792
+ };
793
+ }
794
+ function clipCleanly(text, maxChars) {
795
+ const clean = text.trim();
796
+ if (clean.length <= maxChars)
797
+ return clean;
798
+ if (maxChars <= 4)
799
+ return safeUtf16Slice(clean, 0, Math.max(0, maxChars));
800
+ const sliceBudget = maxChars - 3;
801
+ const rough = safeUtf16Slice(clean, 0, sliceBudget);
802
+ const lastSpace = rough.lastIndexOf(' ');
803
+ const cut = lastSpace >= Math.floor(sliceBudget * 0.6)
804
+ ? safeUtf16Slice(rough, 0, lastSpace).trimEnd()
805
+ : rough;
806
+ return `${cut}...`;
807
+ }
808
+ function samplePassagesDeterministically(passages, maxCount) {
809
+ if (passages.length <= maxCount)
810
+ return passages;
811
+ const headCount = Math.floor(maxCount * 0.25);
812
+ const tailCount = Math.floor(maxCount * 0.25);
813
+ const midCount = maxCount - headCount - tailCount;
814
+ const sampled = [];
815
+ for (let i = 0; i < headCount; i++) {
816
+ sampled.push(passages[i]);
817
+ }
818
+ const midSpan = passages.length - headCount - tailCount;
819
+ const step = midSpan / midCount;
820
+ for (let i = 0; i < midCount; i++) {
821
+ sampled.push(passages[headCount + Math.floor(i * step)]);
822
+ }
823
+ for (let i = passages.length - tailCount; i < passages.length; i++) {
824
+ sampled.push(passages[i]);
825
+ }
826
+ return sampled;
827
+ }
828
+ /**
829
+ * Deterministic extractive text condenser:
830
+ * - Strips pure conversational filler/boilerplate and bare horizontal rules
831
+ * - Deduplicates near-identical passages (normalized token Jaccard >= 0.85)
832
+ * - Preserves concise prompts (`<= 500` chars) 100% verbatim
833
+ * - Compacts verbose outputs/responses into original-order high-signal passages
834
+ */
835
+ function condenseText(text, options) {
836
+ if (!text || typeof text !== 'string')
837
+ return '';
838
+ const rawTrimmed = text.trim();
839
+ if (!rawTrimmed)
840
+ return '';
841
+ const kind = options?.kind;
842
+ const shortPromptCap = options?.preserveShortThreshold ?? 500;
843
+ const maxChars = Math.max(40, options?.maxChars ?? 380);
844
+ // Concise user prompts (<= 500 chars) preserve 100% of substantive text verbatim
845
+ if (kind === 'prompt' && rawTrimmed.length <= shortPromptCap) {
846
+ const nonRuleLines = rawTrimmed
847
+ .split(/\r?\n/)
848
+ .filter((line) => !isHorizontalRule(line.trim()));
849
+ const joined = nonRuleLines.join('\n').trim();
850
+ return joined || rawTrimmed;
851
+ }
852
+ // Bound input scanning on massive multi-KB dumps by keeping head + strided middle + tail
853
+ let sourceForSplit = rawTrimmed;
854
+ if (rawTrimmed.length > 20_000) {
855
+ const head = safeUtf16Slice(rawTrimmed, 0, 7_000);
856
+ const midStart = Math.floor(rawTrimmed.length / 2) - 3_000;
857
+ const mid = safeUtf16Slice(rawTrimmed, midStart, midStart + 6_000);
858
+ const tail = safeUtf16Slice(rawTrimmed, rawTrimmed.length - 7_000, rawTrimmed.length);
859
+ sourceForSplit = `${head}\n${mid}\n${tail}`;
860
+ }
861
+ const allPassages = samplePassagesDeterministically(splitIntoPassages(sourceForSplit), MAX_CONDENSE_CANDIDATE_PASSAGES);
862
+ if (allPassages.length === 0)
863
+ return clipCleanly(rawTrimmed, maxChars);
864
+ // Filter pure boilerplate & deduplicate near-identical passages (O(1) exact + bounded Jaccard window)
865
+ const substantive = [];
866
+ const seenNormKeys = new Set();
867
+ for (const span of allPassages) {
868
+ if (isBoilerplatePassage(span.text))
869
+ continue;
870
+ const tokArr = extractNormalizedTokens(span.text);
871
+ const normKey = tokArr.join(' ');
872
+ if (normKey && seenNormKeys.has(normKey)) {
873
+ continue;
874
+ }
875
+ const tokSet = new Set(tokArr);
876
+ let isDup = false;
877
+ if (tokSet.size >= 3) {
878
+ const winStart = Math.max(0, substantive.length - JACCARD_WINDOW_SIZE);
879
+ for (let w = substantive.length - 1; w >= winStart; w--) {
880
+ if (tokenSetJaccard(tokSet, substantive[w].tokens) >= 0.85) {
881
+ isDup = true;
882
+ break;
883
+ }
884
+ }
885
+ }
886
+ if (!isDup) {
887
+ if (normKey)
888
+ seenNormKeys.add(normKey);
889
+ substantive.push({ span, tokens: tokSet, normKey });
890
+ }
891
+ }
892
+ if (substantive.length === 0) {
893
+ const compactSample = safeUtf16Slice(rawTrimmed, 0, Math.min(rawTrimmed.length, maxChars * 3));
894
+ return clipCleanly(compactSample.replace(/\s+/g, ' '), maxChars);
895
+ }
896
+ // If already within budget after boilerplate removal + deduplication, keep all substantive spans
897
+ const cleanedFull = substantive.map((s) => s.span.text).join(' ');
898
+ if (cleanedFull.length <= maxChars) {
899
+ return cleanedFull;
900
+ }
901
+ // Score each substantive passage and select highest-density passages within maxChars
902
+ const scored = substantive.map((entry, idx) => ({
903
+ idx,
904
+ span: entry.span,
905
+ score: scorePassageInformation(entry.span.text, idx, substantive.length),
906
+ }));
907
+ scored.sort((a, b) => b.score - a.score || a.idx - b.idx);
908
+ const chosen = [];
909
+ let usedChars = 0;
910
+ for (const cand of scored) {
911
+ const sepChars = chosen.length > 0 ? 1 : 0;
912
+ const needed = sepChars + cand.span.text.length;
913
+ if (usedChars + needed <= maxChars) {
914
+ chosen.push(cand);
915
+ usedChars += needed;
916
+ }
917
+ else if (chosen.length === 0) {
918
+ return clipCleanly(cand.span.text, maxChars);
919
+ }
920
+ }
921
+ chosen.sort((a, b) => a.span.start - b.span.start);
922
+ return chosen.map((c) => c.span.text).join(' ');
923
+ }
924
+ /**
925
+ * Computes an additive, deterministic `condensed_text` representation for an observation
926
+ * without mutating raw `input` or `output`.
927
+ */
928
+ function condenseObservation(obs) {
929
+ const kind = obs.kind || 'tool_call';
930
+ const toolName = obs.toolName?.trim() || '';
931
+ const filePath = obs.filePath?.trim() || '';
932
+ const input = obs.input?.trim() || '';
933
+ const output = obs.output?.trim() || '';
934
+ if (!input && !output && !toolName && !filePath) {
935
+ return null;
936
+ }
937
+ if (kind === 'prompt') {
938
+ const combined = [input, output].filter(Boolean).join('\n').trim();
939
+ if (!combined)
940
+ return null;
941
+ if (combined.length <= 500) {
942
+ return condenseText(combined, { kind: 'prompt', preserveShortThreshold: 500 });
943
+ }
944
+ return condenseText(combined, {
945
+ kind: 'prompt',
946
+ maxChars: obs.maxChars ?? 450,
947
+ preserveShortThreshold: 500,
948
+ });
949
+ }
950
+ const maxChars = obs.maxChars ?? 380;
951
+ if (kind === 'response') {
952
+ const combined = [input, output].filter(Boolean).join('\n').trim();
953
+ if (!combined)
954
+ return null;
955
+ return condenseText(combined, { kind: 'response', maxChars });
956
+ }
957
+ // kind === 'tool_call'
958
+ const headerParts = [toolName, filePath].filter(Boolean);
959
+ const header = headerParts.length > 0 ? `[${headerParts.join(' ')}]` : '';
960
+ const remainingBudget = Math.max(80, maxChars - (header ? header.length + 1 : 0));
961
+ let body = '';
962
+ if (input && output) {
963
+ const inBudget = Math.min(input.length, Math.max(80, Math.floor(remainingBudget * 0.4)));
964
+ const condensedIn = input.length <= inBudget ? input : condenseText(input, { kind: 'tool_call', maxChars: inBudget });
965
+ const outBudget = Math.max(60, remainingBudget - condensedIn.length - 4);
966
+ const condensedOut = output.length <= outBudget
967
+ ? output
968
+ : condenseText(output, { kind: 'tool_call', maxChars: outBudget });
969
+ body = `${condensedIn} -> ${condensedOut}`;
970
+ }
971
+ else if (input) {
972
+ body =
973
+ input.length <= remainingBudget
974
+ ? input
975
+ : condenseText(input, { kind: 'tool_call', maxChars: remainingBudget });
976
+ }
977
+ else if (output) {
978
+ body =
979
+ output.length <= remainingBudget
980
+ ? output
981
+ : condenseText(output, { kind: 'tool_call', maxChars: remainingBudget });
982
+ }
983
+ const assembled = [header, body].filter(Boolean).join(' ').trim();
984
+ if (!assembled)
985
+ return null;
986
+ return assembled.length <= maxChars ? assembled : clipCleanly(assembled, maxChars);
987
+ }
988
+ function lightStem(token) {
989
+ if (token.length < 5)
990
+ return token;
991
+ if (token.endsWith('ing') && token.length >= 6)
992
+ return token.slice(0, -3);
993
+ if (token.endsWith('tion') && token.length >= 7)
994
+ return token.slice(0, -4);
995
+ if (token.endsWith('ed') && token.length >= 5)
996
+ return token.slice(0, -2);
997
+ if (token.endsWith('es') && token.length >= 5)
998
+ return token.slice(0, -2);
999
+ if (token.endsWith('s') && !token.endsWith('ss') && token.length >= 5)
1000
+ return token.slice(0, -1);
1001
+ return token;
1002
+ }
1003
+ /**
1004
+ * Extracts query content tokens (with stopword fallback), quoted phrases,
1005
+ * and technical/numeric literals for query-focused passage ranking.
1006
+ */
1007
+ function parseQuerySignals(query) {
1008
+ if (!query || typeof query !== 'string') {
1009
+ return { contentTokens: [], allTokens: [], phrases: [], specialLiterals: [] };
1010
+ }
1011
+ const bounded = query.length > MAX_QUERY_PARSE_CHARS ? safeUtf16Slice(query, 0, MAX_QUERY_PARSE_CHARS) : query;
1012
+ const phrases = [];
1013
+ const quoteRe = /"([^"\n]{2,120})"|'([^'\n]{2,120})'/g;
1014
+ let m;
1015
+ while ((m = quoteRe.exec(bounded)) !== null && phrases.length < 16) {
1016
+ const p = (m[1] || m[2] || '').trim().toLowerCase();
1017
+ if (p.length >= 2)
1018
+ phrases.push(p);
1019
+ }
1020
+ const specialLiterals = [];
1021
+ const specialRe = /(?:(?<![a-zA-Z0-9_.-])[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_./-]+|\b[a-zA-Z0-9_-]+\.[a-zA-Z0-9]{1,8}\b|\bv?\d+(?:\.\d+)+\b|\b[a-z]+_[a-z0-9_]+\b|\b[a-z]+[A-Z][a-zA-Z0-9]*\b)/g;
1022
+ while ((m = specialRe.exec(bounded)) !== null && specialLiterals.length < 24) {
1023
+ const lit = m[0].toLowerCase();
1024
+ if (lit.length >= 2)
1025
+ specialLiterals.push(lit);
1026
+ }
1027
+ const rawTokens = extractNormalizedTokens(bounded);
1028
+ const allTokens = Array.from(new Set(rawTokens.filter(Boolean))).slice(0, 64);
1029
+ const nonStop = allTokens.filter((t) => !exports.STOPWORDS.has(t));
1030
+ const contentTokens = nonStop.length > 0 ? nonStop : allTokens;
1031
+ return {
1032
+ contentTokens,
1033
+ allTokens,
1034
+ phrases: Array.from(new Set(phrases)),
1035
+ specialLiterals: Array.from(new Set(specialLiterals)),
1036
+ };
1037
+ }
1038
+ function windowAroundMatch(passageText, signals, maxChars) {
1039
+ if (passageText.length <= maxChars)
1040
+ return passageText;
1041
+ const lower = passageText.toLowerCase();
1042
+ let matchIdx = -1;
1043
+ for (const phrase of signals.phrases) {
1044
+ const idx = lower.indexOf(phrase);
1045
+ if (idx !== -1) {
1046
+ matchIdx = idx;
1047
+ break;
1048
+ }
1049
+ }
1050
+ if (matchIdx === -1) {
1051
+ for (const tok of signals.contentTokens) {
1052
+ const idx = lower.indexOf(tok);
1053
+ if (idx !== -1) {
1054
+ matchIdx = idx;
1055
+ break;
1056
+ }
1057
+ }
1058
+ }
1059
+ if (matchIdx === -1) {
1060
+ return clipCleanly(passageText, maxChars);
1061
+ }
1062
+ const ellipsisFront = '[...] ';
1063
+ const ellipsisBack = ' [...]';
1064
+ const reserve = ellipsisFront.length + ellipsisBack.length;
1065
+ if (maxChars <= reserve + 16) {
1066
+ return clipCleanly(passageText, maxChars);
1067
+ }
1068
+ const innerBudget = maxChars - reserve;
1069
+ let winStart = Math.max(0, matchIdx - Math.floor(innerBudget * 0.35));
1070
+ let winEnd = Math.min(passageText.length, winStart + innerBudget);
1071
+ if (winEnd - winStart < innerBudget) {
1072
+ winStart = Math.max(0, winEnd - innerBudget);
1073
+ }
1074
+ winStart = alignUtf16Start(passageText, winStart);
1075
+ winEnd = alignUtf16End(passageText, winEnd, winStart);
1076
+ const needFront = winStart > 0;
1077
+ const needBack = winEnd < passageText.length;
1078
+ if (needFront) {
1079
+ const nextSpace = passageText.indexOf(' ', winStart);
1080
+ if (nextSpace !== -1 && nextSpace < matchIdx && nextSpace - winStart <= 20) {
1081
+ winStart = alignUtf16Start(passageText, nextSpace + 1);
1082
+ }
1083
+ }
1084
+ if (needBack) {
1085
+ const prevSpace = passageText.lastIndexOf(' ', winEnd);
1086
+ if (prevSpace !== -1 && prevSpace > matchIdx + 8 && winEnd - prevSpace <= 20) {
1087
+ winEnd = alignUtf16End(passageText, prevSpace, winStart);
1088
+ }
1089
+ }
1090
+ const core = passageText.slice(winStart, winEnd).trim();
1091
+ const rendered = `${needFront ? ellipsisFront : ''}${core}${needBack ? ellipsisBack : ''}`;
1092
+ return rendered.length <= maxChars ? rendered : safeUtf16Slice(rendered, 0, maxChars);
1093
+ }
1094
+ /**
1095
+ * Extracts a query-focused snippet from the full untruncated `text`.
1096
+ *
1097
+ * - Returns `text` unchanged when `!text` or `text.length <= maxChars`.
1098
+ * - Scores every passage across the full document (including tail offsets at 4KB–50KB+)
1099
+ * by query content-token IDF coverage, phrase/identifier/number match bonuses,
1100
+ * optional `preferredSpan` overlap, and intrinsic density tie-breaker.
1101
+ * - Falls back to `condenseText(text, { maxChars })` when zero passages match the query.
1102
+ * - Selects top 2–4 anchor spans (plus `±contextSentences` neighbors when budget allows),
1103
+ * orders chronologically, joins non-adjacent spans with ` [...] `, and enforces `<= maxChars`.
1104
+ */
1105
+ function extractQueryFocusedSnippet(text, query, options) {
1106
+ const maxChars = Math.max(32, options?.maxChars ?? 600);
1107
+ if (!text || typeof text !== 'string')
1108
+ return '';
1109
+ if (text.length <= maxChars)
1110
+ return text;
1111
+ const contextSentences = Math.max(0, options?.contextSentences ?? 1);
1112
+ const preferredSpan = options?.preferredSpan;
1113
+ const passages = splitIntoPassages(text);
1114
+ if (passages.length === 0) {
1115
+ return clipCleanly(text, maxChars);
1116
+ }
1117
+ const signals = parseQuerySignals(query);
1118
+ const stems = signals.contentTokens.map(lightStem);
1119
+ const cleanFullQuery = query.length > MAX_QUERY_PARSE_CHARS
1120
+ ? safeUtf16Slice(query, 0, MAX_QUERY_PARSE_CHARS).trim().toLowerCase()
1121
+ : query.trim().toLowerCase();
1122
+ // Fast SIMD substring prefilter: only tokenize passages that actually contain a query stem/phrase/literal
1123
+ // or overlap preferredSpan (since `stem` is always a prefix of `qt`, `!lower.includes(stem)` implies 0 token/stem match).
1124
+ const searchNeedles = Array.from(new Set([...stems, ...signals.phrases, ...signals.specialLiterals].filter(Boolean)));
1125
+ const passageTokenSets = new Array(passages.length).fill(null);
1126
+ const passageStemSets = new Array(passages.length).fill(null);
1127
+ const passageLowers = new Array(passages.length);
1128
+ const candidatePassageIndices = [];
1129
+ const docFreq = new Map();
1130
+ for (let i = 0; i < passages.length; i++) {
1131
+ const p = passages[i];
1132
+ const lower = p.text.toLowerCase();
1133
+ passageLowers[i] = lower;
1134
+ let maybeMatches = Boolean(preferredSpan && p.start < preferredSpan.end && p.end > preferredSpan.start) ||
1135
+ (cleanFullQuery.length >= 4 && lower.includes(cleanFullQuery));
1136
+ if (!maybeMatches) {
1137
+ for (let n = 0; n < searchNeedles.length; n++) {
1138
+ if (lower.includes(searchNeedles[n])) {
1139
+ maybeMatches = true;
1140
+ break;
1141
+ }
1142
+ }
1143
+ }
1144
+ if (!maybeMatches)
1145
+ continue;
1146
+ candidatePassageIndices.push(i);
1147
+ const toks = extractNormalizedTokens(lower);
1148
+ const tokSet = new Set(toks);
1149
+ const stemSet = new Set(toks.map(lightStem));
1150
+ passageTokenSets[i] = tokSet;
1151
+ passageStemSets[i] = stemSet;
1152
+ for (const qt of signals.contentTokens) {
1153
+ if (tokSet.has(qt)) {
1154
+ docFreq.set(qt, (docFreq.get(qt) ?? 0) + 1);
1155
+ }
1156
+ }
1157
+ }
1158
+ if (candidatePassageIndices.length === 0) {
1159
+ return condenseText(text, { maxChars });
1160
+ }
1161
+ // Score candidate passages
1162
+ const matchScores = new Array(passages.length).fill(0);
1163
+ let anyQueryMatch = false;
1164
+ for (const i of candidatePassageIndices) {
1165
+ const p = passages[i];
1166
+ const lower = passageLowers[i];
1167
+ const tokSet = passageTokenSets[i];
1168
+ const stemSet = passageStemSets[i];
1169
+ let qScore = 0;
1170
+ let matchedCount = 0;
1171
+ for (let tIdx = 0; tIdx < signals.contentTokens.length; tIdx++) {
1172
+ const qt = signals.contentTokens[tIdx];
1173
+ const stem = stems[tIdx];
1174
+ const df = docFreq.get(qt) ?? 0;
1175
+ const idf = Math.log(1 + passages.length / (1 + df));
1176
+ const specificity = 1 +
1177
+ Math.min(qt.length, 12) / 6 +
1178
+ (/\d/.test(qt) ? 1.2 : 0) +
1179
+ (qt.includes('_') ? 0.8 : 0);
1180
+ if (tokSet.has(qt)) {
1181
+ qScore += specificity * (1 + idf);
1182
+ matchedCount++;
1183
+ }
1184
+ else if (qt.length >= 4 && lower.includes(qt)) {
1185
+ qScore += specificity * 0.75 * (1 + idf * 0.5);
1186
+ matchedCount += 0.7;
1187
+ }
1188
+ else if (stem.length >= 4 && stemSet.has(stem)) {
1189
+ qScore += specificity * 0.55;
1190
+ matchedCount += 0.5;
1191
+ }
1192
+ }
1193
+ // Coverage ratio bonus when multiple distinct query terms co-occur in one passage
1194
+ if (signals.contentTokens.length > 1 && matchedCount > 1) {
1195
+ const coverage = matchedCount / signals.contentTokens.length;
1196
+ qScore += coverage * 4.5;
1197
+ }
1198
+ // Consecutive query content-term bigram bonus
1199
+ for (let tIdx = 0; tIdx + 1 < signals.contentTokens.length; tIdx++) {
1200
+ const bigram = `${signals.contentTokens[tIdx]} ${signals.contentTokens[tIdx + 1]}`;
1201
+ if (lower.includes(bigram)) {
1202
+ qScore += 3.5;
1203
+ }
1204
+ }
1205
+ // Exact full query or quoted phrase bonus
1206
+ if (cleanFullQuery.length >= 4 && lower.includes(cleanFullQuery)) {
1207
+ qScore += 6.0;
1208
+ }
1209
+ for (const phrase of signals.phrases) {
1210
+ if (lower.includes(phrase)) {
1211
+ qScore += 5.5;
1212
+ }
1213
+ }
1214
+ // Exact path / version / snake_case / camelCase literal bonus
1215
+ for (const lit of signals.specialLiterals) {
1216
+ if (lower.includes(lit)) {
1217
+ qScore += 4.0;
1218
+ }
1219
+ }
1220
+ // Preferred span overlap bonus
1221
+ if (preferredSpan && p.start < preferredSpan.end && p.end > preferredSpan.start) {
1222
+ const overlap = Math.min(p.end, preferredSpan.end) - Math.max(p.start, preferredSpan.start);
1223
+ if (overlap > 0) {
1224
+ qScore += 5.0;
1225
+ }
1226
+ }
1227
+ if (qScore > 0) {
1228
+ anyQueryMatch = true;
1229
+ const densityTieBreaker = Math.min(2.5, scorePassageInformation(p.text, i, passages.length) * 0.2);
1230
+ const boilerplatePenalty = isBoilerplatePassage(p.text) ? 0.35 : 1.0;
1231
+ matchScores[i] = (qScore + densityTieBreaker) * boilerplatePenalty;
1232
+ }
1233
+ }
1234
+ if (!anyQueryMatch) {
1235
+ return condenseText(text, { maxChars });
1236
+ }
1237
+ // Rank matching passages
1238
+ const rankedIndices = passages
1239
+ .map((_, idx) => idx)
1240
+ .filter((idx) => matchScores[idx] > 0)
1241
+ .sort((a, b) => matchScores[b] - matchScores[a] || a - b);
1242
+ const JOINER = ' [...] ';
1243
+ const LEAD_ELLIPSIS = '[...] ';
1244
+ const TAIL_ELLIPSIS = ' [...]';
1245
+ const renderSelection = (indices) => {
1246
+ const sorted = Array.from(indices).sort((a, b) => a - b);
1247
+ if (sorted.length === 0)
1248
+ return '';
1249
+ const parts = [];
1250
+ const startsAfterBeginning = passages[sorted[0]].start > 0;
1251
+ const endsBeforeFinish = passages[sorted[sorted.length - 1]].end < text.trimEnd().length;
1252
+ let hasInternalGap = false;
1253
+ for (let k = 0; k < sorted.length; k++) {
1254
+ if (k > 0) {
1255
+ const prevIdx = sorted[k - 1];
1256
+ const curIdx = sorted[k];
1257
+ if (curIdx > prevIdx + 1) {
1258
+ parts.push(JOINER);
1259
+ hasInternalGap = true;
1260
+ }
1261
+ else {
1262
+ parts.push(' ');
1263
+ }
1264
+ }
1265
+ parts.push(passages[sorted[k]].text);
1266
+ }
1267
+ let core = parts.join('');
1268
+ if (startsAfterBeginning && !hasInternalGap) {
1269
+ core = `${LEAD_ELLIPSIS}${core}`;
1270
+ }
1271
+ else if (startsAfterBeginning && core.length + LEAD_ELLIPSIS.length <= maxChars) {
1272
+ core = `${LEAD_ELLIPSIS}${core}`;
1273
+ }
1274
+ if (endsBeforeFinish && core.length + TAIL_ELLIPSIS.length <= maxChars && !core.endsWith('...')) {
1275
+ core = `${core}${TAIL_ELLIPSIS}`;
1276
+ }
1277
+ return core;
1278
+ };
1279
+ const selected = new Set();
1280
+ const selectedTokenSets = [];
1281
+ // 1. Always admit the single highest-scoring anchor first
1282
+ const primaryIdx = rankedIndices[0];
1283
+ const primaryPassage = passages[primaryIdx];
1284
+ if (primaryPassage.text.length + LEAD_ELLIPSIS.length > maxChars) {
1285
+ return windowAroundMatch(primaryPassage.text, signals, maxChars);
1286
+ }
1287
+ selected.add(primaryIdx);
1288
+ selectedTokenSets.push(passageTokenSets[primaryIdx] ?? new Set());
1289
+ // 2. Select up to 3 additional distinct high-scoring anchor spans (2-4 total anchors)
1290
+ const maxAnchors = 4;
1291
+ let anchorCount = 1;
1292
+ for (let r = 1; r < rankedIndices.length && anchorCount < maxAnchors; r++) {
1293
+ const idx = rankedIndices[r];
1294
+ const candToks = passageTokenSets[idx] ?? new Set(extractNormalizedTokens(passageLowers[idx]));
1295
+ let nearDup = false;
1296
+ for (const existingSet of selectedTokenSets) {
1297
+ if (candToks.size >= 3 && tokenSetJaccard(candToks, existingSet) >= 0.85) {
1298
+ nearDup = true;
1299
+ break;
1300
+ }
1301
+ }
1302
+ if (nearDup)
1303
+ continue;
1304
+ const trial = new Set(selected);
1305
+ trial.add(idx);
1306
+ if (renderSelection(trial).length <= maxChars) {
1307
+ selected.add(idx);
1308
+ selectedTokenSets.push(candToks);
1309
+ anchorCount++;
1310
+ }
1311
+ }
1312
+ // 3. Expand ±contextSentences around top anchors when budget permits
1313
+ if (contextSentences > 0) {
1314
+ const anchorsInPriority = Array.from(selected).sort((a, b) => matchScores[b] - matchScores[a] || a - b);
1315
+ for (let dist = 1; dist <= contextSentences; dist++) {
1316
+ for (const anchor of anchorsInPriority) {
1317
+ for (const neighbor of [anchor - dist, anchor + dist]) {
1318
+ if (neighbor < 0 || neighbor >= passages.length || selected.has(neighbor))
1319
+ continue;
1320
+ if (isBoilerplatePassage(passages[neighbor].text))
1321
+ continue;
1322
+ const trial = new Set(selected);
1323
+ trial.add(neighbor);
1324
+ if (renderSelection(trial).length <= maxChars) {
1325
+ selected.add(neighbor);
1326
+ }
1327
+ }
1328
+ }
1329
+ }
1330
+ }
1331
+ const finalSnippet = renderSelection(selected);
1332
+ if (finalSnippet.length <= maxChars) {
1333
+ return finalSnippet;
1334
+ }
1335
+ return windowAroundMatch(primaryPassage.text, signals, maxChars);
1336
+ }
1337
+ //# sourceMappingURL=condenser.js.map