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