| 1 | // Context manager: selecting the history by RELEVANCE against the live |
| 2 | // question. BM25 with endogenous IDF + redundancy control (MMR), and optionally |
| 3 | // a second, semantic opinion fused by rank. |
| 4 | // |
| 5 | // ── what changed from the previous version, and why ───────────────────────── |
| 6 | // |
| 7 | // 1. OUT goes the hand-written stoplist. There used to be a STOP list of ~90 |
| 8 | // Spanish words. IDF is already computed over the history itself, so |
| 9 | // whatever is ubiquitous gets near-zero weight by construction — with no |
| 10 | // dictionary and without knowing what language we are in. A hand-written |
| 11 | // list only knew Spanish: in an English coding session it filtered nothing, |
| 12 | // and in any language it aged. Endogenous IDF adapts to every conversation. |
| 13 | // |
| 14 | // 2. OUT goes the blind trimming of old results. Old `[resultado …]` messages |
| 15 | // used to be truncated to 600 characters BEFORE being scored. You cannot |
| 16 | // retrieve what you threw away before measuring whether it mattered: if the |
| 17 | // answer was at character 900, there was no longer any way to find it. Now |
| 18 | // it is scored first and trimmed afterwards, and per line. |
| 19 | // |
| 20 | // 3. LINE granularity, not message granularity. A tool result is mostly noise |
| 21 | // with two useful lines in it; keeping it whole or dropping it whole wastes |
| 22 | // budget in both directions. |
| 23 | // |
| 24 | // 4. REDUNDANCY control (MMR). It is the only thing that adds anything on top |
| 25 | // of BM25, and not much: +2.4 points at full scale. (A 3-seed smoke test |
| 26 | // said +8.9; that was seed noise. BM25 with endogenous IDF does almost all |
| 27 | // of the work.) |
| 28 | // |
| 29 | // 5. The knobs come from the measured PRESSURE, not from constants — see prepare(). |
| 30 | // |
| 31 | // 6. ABSOLUTE DATES at write time. "yesterday", said on turn 3, is a lie on |
| 32 | // turn 40, and that is NOT a retrieval failure: the line is retrieved just |
| 33 | // fine and what it carries is false. The turn's date is annotated next to |
| 34 | // the original — see annotateDates. Our own probe (the fact benchmark cannot |
| 35 | // see this): the date goes from being present 0% of the time to 100% of the |
| 36 | // time, for +7 tokens. |
| 37 | // |
| 38 | // 7. TALLY CARD, behind a flag. "how many files have you touched?" is in no |
| 39 | // line at all; no top-k finds it, by construction. It is counted at write |
| 40 | // time — see buildLedger. It costs −0.7 points of recall at budget 3,000 and |
| 41 | // nothing at 16,000, so it is off by default. |
| 42 | // |
| 43 | // Measured at equal token budget (fact recall, no LLM judge; 25 sessions, |
| 44 | // 174 probes): |
| 45 | // tail truncation ............. 7.0% |
| 46 | // previous packer ............. 15.1% |
| 47 | // this one .................... 65.3% ± 8.5 |
| 48 | // |
| 49 | // The budget is in tokens (~4 chars/token). The last RECENT messages are kept |
| 50 | // verbatim as long as they fit in their reserve; everything else competes. |
| 51 | |
| 52 | const RECENT = 6; |
| 53 | // The recent-messages reserve is no longer a constant: it comes out of the |
| 54 | // measured pressure (see prepare). Without a cap, one huge result eats the |
| 55 | // entire budget. |
| 56 | const MAX_MSG_CHARS = 12000; |
| 57 | // λ and the number of candidates are NOT constants: see measureRedundancy() and |
| 58 | // selectAndEmit(). A fixed λ destroys good information when the material is not |
| 59 | // redundant, and a fixed 600 candidates leaves most of the history unlooked-at |
| 60 | // as soon as the budget is large — which is the real case. |
| 61 | const RRF_K = 60; |
| 62 | |
| 63 | // No stoplist: IDF takes care of that. Two-character tokens are allowed |
| 64 | // because in code the short identifiers are sometimes exactly what is being |
| 65 | // looked for (`fs`, `db`, `id`). |
| 66 | // It emits the COMPOUND token and also its PARTS. |
| 67 | // |
| 68 | // The previous tokeniser was tuned for code and lost in dialogue: it required |
| 69 | // starting with a letter — so "3pm", "2nd" or "5" disappeared entirely, and in |
| 70 | // conversation those are times, ordinals and dates — and it kept |
| 71 | // `src/utils.js` as ONE token, so asking about "utils" did not match the line |
| 72 | // that contains it. |
| 73 | // |
| 74 | // Measured: changing ONLY this, with everything else equal, explained 3.5 of |
| 75 | // the 4.8 points that separated us from a BM25 with a different tokeniser on a |
| 76 | // dialogue benchmark. And on the agent-session benchmark it raised fact recall |
| 77 | // from 82.1% to 94.9% (budget 3,000) and from 85.9% to 100% (16,000). It was |
| 78 | // not the packing policy: it was the word splitter. |
| 79 | // |
| 80 | // The compound form is kept because in code it IS the identifier and it matches |
| 81 | // exactly; the parts are added for partial matching. You pay for more terms per |
| 82 | // line, and length normalisation already takes care of that. |
| 83 | const tokens = s => { |
| 84 | const out = [], seen = new Set(); |
| 85 | const push = t => { if (t.length >= 2 && !seen.has(t)) { seen.add(t); out.push(t); } }; |
| 86 | for (const m of (s || '').toLowerCase().match(/[a-z0-9_áéíóúñü][\wáéíóúñü./-]*/g) || []) { |
| 87 | push(m); |
| 88 | if (/[./-]/.test(m)) for (const part of m.split(/[./-]+/)) push(part); |
| 89 | } |
| 90 | return out; |
| 91 | }; |
| 92 | // Token estimator. `length/4` works for prose but badly UNDERESTIMATES code: |
| 93 | // dense punctuation (`{`, `=>`, `.`, `(`) are one-character tokens. Measured, |
| 94 | // counting by length alone made the packer believe things fitted and overshoot |
| 95 | // the budget by ~1.5× — that is, the "Too many tokens" this file exists to |
| 96 | // prevent. The LARGER of the two estimates is taken. |
| 97 | const estTok = s => { |
| 98 | if (!s) return 0; |
| 99 | const pieces = (s.match(/\w+|[^\w\s]/g) || []).length; |
| 100 | return Math.max(Math.ceil(pieces * 1.25), Math.ceil(s.length / 4)); |
| 101 | }; |
| 102 | const tokEstimate = m => estTok(m.content) + 4; |
| 103 | |
| 104 | function clampMsg(m) { |
| 105 | const c = m.content || ''; |
| 106 | if (c.length <= MAX_MSG_CHARS) return m; |
| 107 | const head = Math.floor(MAX_MSG_CHARS * 0.7); |
| 108 | const tail = MAX_MSG_CHARS - head - 40; |
| 109 | return { ...m, content: c.slice(0, head) + `\n… [recortado ${c.length - MAX_MSG_CHARS} caracteres] …\n` + c.slice(-tail) }; |
| 110 | } |
| 111 | |
| 112 | // BM25 with saturation (k1) and length normalisation (b). The IDF comes out of |
| 113 | // the very corpus it is handed — that is the whole point. |
| 114 | // |
| 115 | // Okapi BM25: Robertson, Walker, Jones, Hancock-Beaulieu & Gatford, "Okapi at |
| 116 | // TREC-3", TREC-3, 1994. Modern formulation and justification of k1/b: |
| 117 | // Robertson & Zaragoza, "The Probabilistic Relevance Framework: BM25 and |
| 118 | // Beyond", FnTIR 3(4), 2009 — https://doi.org/10.1561/1500000019 |
| 119 | // The IDF comes from Sparck Jones, Journal of Documentation 28(1), 1972: the |
| 120 | // idea that what is rare is what informs, which is what all of this rests on. |
| 121 | function buildBM25(docs, k1 = 1.2, b = 0.75) { |
| 122 | const N = docs.length || 1; |
| 123 | const df = new Map(), tfs = []; |
| 124 | let totalLen = 0; |
| 125 | for (const d of docs) { |
| 126 | const t = tokens(d), tf = new Map(); |
| 127 | for (const w of t) tf.set(w, (tf.get(w) || 0) + 1); |
| 128 | tfs.push({ tf, len: t.length }); |
| 129 | totalLen += t.length; |
| 130 | for (const w of tf.keys()) df.set(w, (df.get(w) || 0) + 1); |
| 131 | } |
| 132 | const avgdl = totalLen / N || 1; |
| 133 | return (i, q) => { |
| 134 | const { tf, len } = tfs[i]; |
| 135 | if (!len) return 0; |
| 136 | let s = 0; |
| 137 | for (const w of q) { |
| 138 | const f = tf.get(w); if (!f) continue; |
| 139 | const n = df.get(w) || 0; |
| 140 | const idf = Math.max(Math.log(1 + (N - n + 0.5) / (n + 0.5)), 1e-6); |
| 141 | s += idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * len / avgdl)); |
| 142 | } |
| 143 | return s; |
| 144 | }; |
| 145 | } |
| 146 | |
| 147 | const simTokens = s => new Set(((s || '').toLowerCase().match(/[a-z0-9_./-]{2,}/g) || [])); |
| 148 | |
| 149 | // The material's REAL redundancy, sampled. A history of near-identical tool |
| 150 | // results calls for a hard penalty; a conversation where every line is |
| 151 | // different, almost none — and there a high λ only throws good information away. |
| 152 | function measureRedundancy(items, sample = 240) { |
| 153 | if (items.length < 4) return 0; |
| 154 | const step = Math.max(1, Math.floor(items.length / sample)); |
| 155 | const picked = []; |
| 156 | for (let i = 0; i < items.length; i += step) picked.push(simTokens(items[i].line)); |
| 157 | let sum = 0, pairs = 0; |
| 158 | for (let i = 0; i < picked.length; i++) |
| 159 | for (let j = i + 1; j < Math.min(i + 8, picked.length); j++) { sum += jaccard(picked[i], picked[j]); pairs++; } |
| 160 | return pairs ? sum / pairs : 0; |
| 161 | } |
| 162 | function jaccard(a, b) { |
| 163 | if (!a.size || !b.size) return 0; |
| 164 | let inter = 0; const [small, big] = a.size <= b.size ? [a, b] : [b, a]; |
| 165 | for (const t of small) if (big.has(t)) inter++; |
| 166 | return inter / (a.size + b.size - inter); |
| 167 | } |
| 168 | function cosine(a, b) { |
| 169 | if (!a || !b || a.length !== b.length) return 0; |
| 170 | let d = 0, na = 0, nb = 0; |
| 171 | for (let i = 0; i < a.length; i++) { d += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } |
| 172 | return (na && nb) ? d / Math.sqrt(na * nb) : 0; |
| 173 | } |
| 174 | |
| 175 | // Reciprocal rank fusion (RRF — Cormack, Clarke & Buettcher, SIGIR 2009, |
| 176 | // https://doi.org/10.1145/1571941.1572114): POSITIONS are mixed, not scores, so |
| 177 | // there is no need to calibrate scales between an unbounded BM25 and a cosine |
| 178 | // in [-1,1]. |
| 179 | function rrf(lists, k = RRF_K) { |
| 180 | const out = new Map(); |
| 181 | for (const list of lists) list.forEach((id, r) => out.set(id, (out.get(id) || 0) + 1 / (k + r + 1))); |
| 182 | return out; |
| 183 | } |
| 184 | |
| 185 | /** |
| 186 | * STALENESS — the same problem we already solved in the folder watcher, one |
| 187 | * floor up. |
| 188 | * |
| 189 | * The agent reads a file on turn 3 and EDITS it on turn 20. BM25 retrieves both |
| 190 | * versions and the old one scores just as high, because it shares all of its |
| 191 | * vocabulary with the new one. The model sees stale content with no signal that |
| 192 | * it is stale — and that is not inefficiency, it is INCORRECTNESS: no amount of |
| 193 | * relevance fixes the fact that the datum is false. Measured with a |
| 194 | * read→edit→re-read probe (8 seeds): the FALSE version survived 8/8; with this, |
| 195 | * 0/8, and the true one still survives 8/8, at no cost in recall. |
| 196 | * |
| 197 | * The target does NOT come in the result: it comes from the preceding |
| 198 | * assistant call. It is DEMOTED, not deleted — with one measured caveat: asking |
| 199 | * EXPRESSLY for the previous value, the old one comes back 0 times out of 8. It |
| 200 | * is in the set and it does not get retrieved, because it competes among |
| 201 | * hundreds of zero-scoring lines and what comes back is decided by diversity, |
| 202 | * not by the question. REACHABLE IS NOT RETRIEVABLE: the difference between "it |
| 203 | * is no longer true" and "it never existed" is real in the structure and not |
| 204 | * yet in the behaviour. |
| 205 | */ |
| 206 | function markSuperseded(msgs) { |
| 207 | const lastFor = new Map(), targetOf = new Map(); |
| 208 | for (let i = 0; i < msgs.length; i++) { |
| 209 | if (!(msgs[i].content || '').startsWith('[resultado')) continue; |
| 210 | const call = i > 0 ? (msgs[i - 1].content || '') : ''; |
| 211 | const m = call.match(/"tool"\s*:\s*"([^"]+)"[\s\S]{0,200}?"(?:path|file|command)"\s*:\s*"([^"]+)"/); |
| 212 | if (!m) continue; |
| 213 | const key = m[1].split('.')[0] + ':' + m[2]; |
| 214 | targetOf.set(i, key); lastFor.set(key, i); |
| 215 | } |
| 216 | const stale = new Set(); |
| 217 | for (const [i, key] of targetOf) if (lastFor.get(key) !== i) stale.add(i); |
| 218 | return stale; |
| 219 | } |
| 220 | |
| 221 | /** |
| 222 | * ABSOLUTE DATES AT WRITE TIME — the other face of markSuperseded. |
| 223 | * |
| 224 | * "we deployed it yesterday", written on turn 3, is a LIE on turn 40. And no |
| 225 | * BM25 knob fixes this, because it is not a retrieval failure: the line is |
| 226 | * retrieved perfectly and the datum it carries is false. Same as staleness — |
| 227 | * perfect relevance, incorrect content — except that here what goes stale is |
| 228 | * the word, not the file. |
| 229 | * |
| 230 | * That is why it is resolved at WRITE time: while indexing, we still know when |
| 231 | * it was said. One turn later, we no longer do. |
| 232 | * |
| 233 | * · It is ANNOTATED next to the original, not substituted: "ayer |
| 234 | * (2026-08-07)". If the resolution gets it wrong, the model still sees the |
| 235 | * real sentence. |
| 236 | * · The reference is the TURN's stamp (`m.ts`/time/timestamp/date). With no |
| 237 | * stamp and no explicit `now`, NOTHING IS ANNOTATED: making up a date is |
| 238 | * precisely the failure this came to remove. |
| 239 | * · Honest precision: what the language states with day precision gets a day; |
| 240 | * what it states by week or month gets the range of that week or month. |
| 241 | * · ⚠️ Code fences and tool results are left alone: a `2026-08-07` inside a |
| 242 | * diff is not a temporal reference. |
| 243 | * |
| 244 | * Measured with our own probe (the fact benchmark cannot see this: it asks |
| 245 | * about identifiers), 32 real sessions, the sentence in four different |
| 246 | * positions: the line is retrieved 100% · the DATE is there unannotated 0% · |
| 247 | * annotated 100% · false date (had "now" been used) 0%. Cost: +7 tokens on |
| 248 | * top of 2,223. |
| 249 | */ |
| 250 | const DAY = 86400000; |
| 251 | const isoDay = d => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; |
| 252 | const isoMonth = d => isoDay(d).slice(0, 7); |
| 253 | const plusDays = (d, n) => { const x = new Date(d.getTime()); x.setDate(x.getDate() + n); return x; }; |
| 254 | const plusMonths = (d, n) => { const x = new Date(d.getTime()); x.setDate(1); x.setMonth(x.getMonth() + n); return x; }; |
| 255 | const weekOf = d => { const mon = plusDays(d, -((d.getDay() + 6) % 7)); return `${isoDay(mon)}…${isoDay(plusDays(mon, 6))}`; }; |
| 256 | const DOW = { domingo: 0, lunes: 1, martes: 2, miércoles: 3, miercoles: 3, jueves: 4, viernes: 5, sábado: 6, sabado: 6, |
| 257 | sunday: 0, monday: 1, tuesday: 2, wednesday: 3, thursday: 4, friday: 5, saturday: 6 }; |
| 258 | const WORD_N = { un: 1, una: 1, uno: 1, dos: 2, tres: 3, cuatro: 4, cinco: 5, seis: 6, siete: 7, ocho: 8, nueve: 9, diez: 10, |
| 259 | a: 1, an: 1, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10 }; |
| 260 | const asNum = s => (/^\d+$/.test(s) ? parseInt(s, 10) : (WORD_N[s.toLowerCase()] || null)); |
| 261 | // Honest precision: day → day, week → range of the week, month → month. |
| 262 | function shiftBy(ref, n, unit, sign) { |
| 263 | if (n == null || n > 500) return null; |
| 264 | const u = unit.toLowerCase()[0]; |
| 265 | if (u === 'd') return isoDay(plusDays(ref, sign * n)); |
| 266 | if (u === 's' || u === 'w') return weekOf(plusDays(ref, sign * 7 * n)); |
| 267 | if (u === 'm') return isoMonth(plusMonths(ref, sign * n)); |
| 268 | if (u === 'a' || u === 'y') return String(plusMonths(ref, sign * 12 * n).getFullYear()); |
| 269 | return null; |
| 270 | } |
| 271 | // dir<0 the strictly previous one · dir>0 the next one · dir=0 the most recent |
| 272 | // one, counting today. A bare weekday ("el lunes") is AMBIGUOUS in both |
| 273 | // languages: it resolves as backward-looking because in a work log it almost |
| 274 | // always is. It is the only rule here that can be wrong, and that is why the |
| 275 | // original stays. |
| 276 | function nearestDow(ref, target, dir) { |
| 277 | const cur = ref.getDay(); |
| 278 | if (dir > 0) { const f = (target - cur + 7) % 7; return plusDays(ref, f || 7); } |
| 279 | const b = (cur - target + 7) % 7; |
| 280 | return plusDays(ref, -(dir < 0 ? (b || 7) : b)); |
| 281 | } |
| 282 | const NUM_P = '\\d{1,3}|un[ao]?|dos|tres|cuatro|cinco|seis|siete|ocho|nueve|diez|an?|one|two|three|four|five|six|seven|eight|nine|ten'; |
| 283 | const UNIT_P = 'd[ií]as?|semanas?|mes(?:es)?|años?|anos?|days?|weeks?|months?|years?'; |
| 284 | const DOW_ES = 'lunes|martes|mi[ée]rcoles|jueves|viernes|s[áa]bado|domingo'; |
| 285 | const DOW_EN = 'monday|tuesday|wednesday|thursday|friday|saturday|sunday'; |
| 286 | // Order = precedence: the alternation keeps the FIRST one that fits. |
| 287 | const WHEN = [ |
| 288 | // "por la mañana" (in the morning) is not "mañana" (tomorrow): it is matched |
| 289 | // so that it is NOT annotated, and so the short rule never gets to see it. |
| 290 | ['\\b(?:por|de|a|en|desde|hasta)\\s+la\\s+mañana\\b|\\b(?:esta|una|cada|toda\\s+la|la)\\s+mañana\\b', () => null], |
| 291 | ['\\bantes\\s+de\\s+ayer\\b|\\banteayer\\b|\\bthe\\s+day\\s+before\\s+yesterday\\b', (m, r) => isoDay(plusDays(r, -2))], |
| 292 | ['\\bpasado\\s+mañana\\b|\\bthe\\s+day\\s+after\\s+tomorrow\\b', (m, r) => isoDay(plusDays(r, 2))], |
| 293 | [`\\bhace\\s+(${NUM_P})\\s+(${UNIT_P})\\b`, (m, r) => shiftBy(r, asNum(m[1]), m[2], -1)], |
| 294 | [`\\b(${NUM_P})\\s+(${UNIT_P})\\s+ago\\b`, (m, r) => shiftBy(r, asNum(m[1]), m[2], -1)], |
| 295 | [`\\bdentro\\s+de\\s+(${NUM_P})\\s+(${UNIT_P})\\b`, (m, r) => shiftBy(r, asNum(m[1]), m[2], 1)], |
| 296 | [`\\bin\\s+(${NUM_P})\\s+(${UNIT_P})\\b`, (m, r) => shiftBy(r, asNum(m[1]), m[2], 1)], |
| 297 | ['\\b(?:la\\s+)?semana\\s+(pasada|anterior|que\\s+viene|pr[óo]xima)\\b', |
| 298 | (m, r) => weekOf(plusDays(r, /pasada|anterior/i.test(m[1]) ? -7 : 7))], |
| 299 | ['\\b(last|next)\\s+week\\b', (m, r) => weekOf(plusDays(r, /last/i.test(m[1]) ? -7 : 7))], |
| 300 | ['\\b(?:el\\s+)?mes\\s+(pasado|anterior|que\\s+viene|pr[óo]ximo)\\b', |
| 301 | (m, r) => isoMonth(plusMonths(r, /pasado|anterior/i.test(m[1]) ? -1 : 1))], |
| 302 | ['\\b(last|next)\\s+month\\b', (m, r) => isoMonth(plusMonths(r, /last/i.test(m[1]) ? -1 : 1))], |
| 303 | [`\\bel\\s+(${DOW_ES})\\s+(pasado|que\\s+viene|pr[óo]ximo)\\b`, |
| 304 | (m, r) => isoDay(nearestDow(r, DOW[m[1].toLowerCase()], /pasado/i.test(m[2]) ? -1 : 1))], |
| 305 | [`\\b(last|next|this)\\s+(${DOW_EN})\\b`, |
| 306 | (m, r) => isoDay(nearestDow(r, DOW[m[2].toLowerCase()], /last/i.test(m[1]) ? -1 : (/next/i.test(m[1]) ? 1 : 0)))], |
| 307 | // With no modifier, an article or preposition is required: a bare "Monday" |
| 308 | // may be a proper name or a file. |
| 309 | [`\\bel\\s+(${DOW_ES})\\b`, (m, r) => isoDay(nearestDow(r, DOW[m[1].toLowerCase()], 0))], |
| 310 | [`\\bon\\s+(${DOW_EN})\\b`, (m, r) => isoDay(nearestDow(r, DOW[m[1].toLowerCase()], 0))], |
| 311 | ['\\banoche\\b|\\blast\\s+night\\b', (m, r) => isoDay(plusDays(r, -1))], |
| 312 | ['\\bayer\\b|\\byesterday\\b', (m, r) => isoDay(plusDays(r, -1))], |
| 313 | ['\\bhoy\\b|\\btoday\\b', (m, r) => isoDay(r)], |
| 314 | ['\\bmañana\\b|\\btomorrow\\b', (m, r) => isoDay(plusDays(r, 1))], |
| 315 | ]; |
| 316 | const WHEN_RE = new RegExp(WHEN.map(w => `(?:${w[0]})`).join('|'), 'gi'); |
| 317 | const WHEN_ONE = WHEN.map(w => new RegExp(`^(?:${w[0]})$`, 'i')); |
| 318 | // Fences, backticks, and an unclosed fence (a message still arriving). |
| 319 | const FENCE = /```[\s\S]*?```|```[\s\S]*$|~~~[\s\S]*?~~~|`[^`\n]+`/g; |
| 320 | |
| 321 | export function annotateDates(text, refMs) { |
| 322 | if (!text) return text; |
| 323 | WHEN_RE.lastIndex = 0; |
| 324 | if (!WHEN_RE.test(text)) return text; // single sweep: the normal case leaves here |
| 325 | const ref = new Date(refMs); |
| 326 | if (isNaN(ref.getTime())) return text; |
| 327 | const parts = []; let last = 0, f; |
| 328 | FENCE.lastIndex = 0; |
| 329 | while ((f = FENCE.exec(text))) { |
| 330 | parts.push([text.slice(last, f.index), false], [f[0], true]); |
| 331 | last = f.index + f[0].length; |
| 332 | } |
| 333 | parts.push([text.slice(last), false]); |
| 334 | return parts.map(([s, isCode]) => isCode ? s : s.replace(WHEN_RE, (hit, ...rest) => { |
| 335 | const whole = rest[rest.length - 1], at = rest[rest.length - 2]; |
| 336 | if (/^\s*\(\d{4}-\d{2}/.test(whole.slice(at + hit.length))) return hit; // idempotent |
| 337 | // `today()`, `memory::today`, `hoy_str` or `ayer.js` are CODE even when they |
| 338 | // arrive without a fence: an unfenced tool call carries paths, and |
| 339 | // annotating inside a path breaks it. A sentence-final full stop ("lo |
| 340 | // hicimos ayer.") does get annotated. |
| 341 | if (/[.:_/\\]$/.test(whole.slice(0, at)) || /^[(_]|^\.\w/.test(whole.slice(at + hit.length))) return hit; |
| 342 | for (let i = 0; i < WHEN.length; i++) { |
| 343 | const g = WHEN_ONE[i].exec(hit); |
| 344 | if (!g) continue; |
| 345 | const v = WHEN[i][1](g, ref); |
| 346 | return v ? `${hit} (${v})` : hit; |
| 347 | } |
| 348 | return hit; |
| 349 | })).join(''); |
| 350 | } |
| 351 | |
| 352 | const asTime = v => { |
| 353 | if (v == null) return null; |
| 354 | if (typeof v === 'number') return Number.isFinite(v) && v > 0 ? (v < 1e11 ? v * 1000 : v) : null; |
| 355 | if (typeof v.getTime === 'function') return Number.isFinite(v.getTime()) ? v.getTime() : null; |
| 356 | const t = Date.parse(v); |
| 357 | return Number.isFinite(t) ? t : null; |
| 358 | }; |
| 359 | |
| 360 | // History with the temporal references resolved. Returns the SAME array if |
| 361 | // there was nothing to annotate, so the normal case pays for no copies. |
| 362 | function datedHistory(history, now) { |
| 363 | let touched = false; |
| 364 | const out = history.map(m => { |
| 365 | const c = m.content || ''; |
| 366 | if (!c || c.startsWith('[resultado')) return m; // tool output: untouchable |
| 367 | const ref = asTime(m.ts ?? m.time ?? m.timestamp ?? m.date ?? m.createdAt) ?? asTime(now); |
| 368 | if (ref == null) return m; // no known date → nothing is invented |
| 369 | const a = annotateDates(c, ref); |
| 370 | if (a === c) return m; |
| 371 | touched = true; |
| 372 | return { ...m, content: a }; |
| 373 | }); |
| 374 | return touched ? out : history; |
| 375 | } |
| 376 | |
| 377 | /** |
| 378 | * AGGREGATION — what is in no line at all. |
| 379 | * |
| 380 | * "How many files have you touched?" is not spread across forty lines: it is |
| 381 | * that the line to look for DOES NOT EXIST. No top-k finds it, and not because |
| 382 | * it scores badly, but by construction. Like the dates, it is resolved at WRITE |
| 383 | * time: counting as the results go past. A counter and nothing else — no model, |
| 384 | * no generated summary, no judgement: it is a tally, and it reads the way |
| 385 | * `wc -l` reads. |
| 386 | * |
| 387 | * The target of each call comes from the ASSISTANT's call (the result does not |
| 388 | * carry it), same as in markSuperseded, and the family is decided by the VERB |
| 389 | * in the tool's name: the products that share this design have different tools |
| 390 | * (`code.read` / `fs.read`) and a closed list of names would go stale with the |
| 391 | * first new product. |
| 392 | */ |
| 393 | const V_EDIT = /^(?:write|edit|create|save|patch|append|delete|remove|rm|move|rename|copy)$/; |
| 394 | const V_READ = /^(?:read|view|open|cat|show)$/; |
| 395 | const V_RUN = /^(?:run|exec|shell|bash|cmd)$/; |
| 396 | const CALL = /"tool"\s*:\s*"([^"]+)"[\s\S]{0,300}?"(?:path|file|filename|command|cmd)"\s*:\s*"((?:[^"\\]|\\.)*)"/g; |
| 397 | const ERR = /^\s*(?:ERROR\b|Error:|error:|Traceback \(most recent call last\))/; |
| 398 | |
| 399 | export function buildLedger(msgs) { |
| 400 | const read = new Map(), edited = new Map(), ran = new Map(), errs = new Map(); |
| 401 | let errN = 0; |
| 402 | msgs.forEach((msg, i) => { |
| 403 | const c = msg.content || ''; |
| 404 | if (c.startsWith('[resultado')) { |
| 405 | for (const line of c.split('\n')) { |
| 406 | if (!ERR.test(line)) continue; |
| 407 | errN++; errs.set(line.trim().slice(0, 90), i); |
| 408 | break; // we count failed RESULTS, not traceback lines |
| 409 | } |
| 410 | return; |
| 411 | } |
| 412 | if (msg.role !== 'assistant') return; |
| 413 | CALL.lastIndex = 0; |
| 414 | let m; |
| 415 | while ((m = CALL.exec(c))) { |
| 416 | const verb = m[1].split('.').pop().toLowerCase(); |
| 417 | if (!m[2]) continue; |
| 418 | if (V_EDIT.test(verb)) edited.set(m[2], i); |
| 419 | else if (V_READ.test(verb)) read.set(m[2], i); |
| 420 | else if (V_RUN.test(verb)) ran.set(m[2], i); |
| 421 | } |
| 422 | }); |
| 423 | // An edited file is not counted as read as well: "how many have you touched" |
| 424 | // cannot count the same file twice. |
| 425 | for (const k of edited.keys()) read.delete(k); |
| 426 | return { read, edited, ran, errs, errN }; |
| 427 | } |
| 428 | |
| 429 | /** |
| 430 | * The card, bounded. Three rules, and all three come from measuring: |
| 431 | * |
| 432 | * 1. The TALLY always goes in and is the true total; the enumeration is what |
| 433 | * gets trimmed. A truncated tally that LOOKS complete ("8 files" when there |
| 434 | * were 200) is worse than giving none at all, so the number goes separately |
| 435 | * and the list says "+N más". When not even one entry fits, the row is left |
| 436 | * as just the number. |
| 437 | * 2. The ceiling comes from the BUDGET, not from a constant. |
| 438 | * 3. Room is taken from the row that spends the most TOKENS, not from the one |
| 439 | * with the most entries: two long error paths cost more than eight short |
| 440 | * names. Measured (32 sessions, budget 3,000, coverage of the files |
| 441 | * actually edited, at equal cost of ~148 tokens): trimming by number of |
| 442 | * entries 67.7% · trimming by cost 90.6%. With no card, 58.9%. |
| 443 | * And with the ceiling at 3% it drops to 57.3%: a card squeezed too tight |
| 444 | * gives the tally for free but its enumeration GETS IN THE WAY. |
| 445 | * |
| 446 | * ⚠️ The card is NOT free: on the usual fact benchmark (32 real sessions) it |
| 447 | * costs −0.7 points at budget 3,000 (65.7% → 65.0%) and ±0.0 at 16,000. That is |
| 448 | * why it sits behind a flag and off: whoever asks "how many files" wants it; |
| 449 | * whoever does not is paying for nothing. |
| 450 | */ |
| 451 | function summaryCard(L, maxTok) { |
| 452 | const rows = [['ficheros leídos', L.read], ['ficheros editados', L.edited], |
| 453 | ['comandos', L.ran], ['errores', L.errs]]; |
| 454 | const totals = [L.read.size, L.edited.size, L.ran.size, L.errN]; |
| 455 | if (!totals.some(Boolean)) return null; |
| 456 | // MOST RECENT first: if trimming is needed, whatever was just touched is what |
| 457 | // they are most likely to ask about. |
| 458 | const listed = rows.map(([, m]) => [...m.entries()].sort((a, b) => b[1] - a[1]).map(e => e[0])); |
| 459 | const caps = rows.map(() => 8); |
| 460 | const line = i => { |
| 461 | const items = listed[i].slice(0, caps[i]).map(s => s.length > 60 ? s.slice(0, 57) + '…' : s); |
| 462 | const rest = totals[i] - items.length; |
| 463 | return `${rows[i][0]} (${totals[i]})${items.length ? ': ' + items.join(' · ') : ''}` + |
| 464 | `${rest > 0 && items.length ? ` · +${rest} más` : ''}`; |
| 465 | }; |
| 466 | const compose = () => ['[recuento de la sesión · automático]'] |
| 467 | .concat(rows.map((r, i) => totals[i] ? line(i) : null).filter(Boolean)).join('\n'); |
| 468 | let text = compose(); |
| 469 | while (estTok(text) > maxTok) { |
| 470 | let worst = -1, cost = 0; |
| 471 | rows.forEach((r, i) => { |
| 472 | if (!totals[i] || !caps[i]) return; |
| 473 | const c = estTok(line(i)); |
| 474 | if (c > cost) { cost = c; worst = i; } |
| 475 | }); |
| 476 | if (worst < 0) break; |
| 477 | caps[worst] = Math.min(caps[worst], totals[worst]) - 1; |
| 478 | text = compose(); |
| 479 | } |
| 480 | return { role: 'user', content: text }; |
| 481 | } |
| 482 | |
| 483 | // Prepares the shared state: recent reserve, live question, lines and BM25. |
| 484 | function prepare(history, budgetTokens, opts = {}) { |
| 485 | // Whatever is resolved at WRITE time goes before anything else, because it |
| 486 | // changes the material that is about to be scored and what is going to fit: |
| 487 | // the dates are annotated over the history, and the card is charged against |
| 488 | // the budget BEFORE it is shared out — which is what makes it unconditional |
| 489 | // without breaking the token contract. |
| 490 | if (opts.dates !== false) history = datedHistory(history, opts.now); |
| 491 | const card = opts.summary ? summaryCard(buildLedger(history), |
| 492 | Math.max(24, Math.floor(budgetTokens * (opts.summaryFrac || 0.05)))) : null; |
| 493 | const cardTok = card ? estTok(card.content) + 4 : 0; |
| 494 | budgetTokens = Math.max(1, budgetTokens - cardTok); |
| 495 | |
| 496 | // Compression PRESSURE: what fraction of the history fits. Every knob that |
| 497 | // depends on the regime comes from here, not from constants — 200k of history |
| 498 | // against a 32k budget is not ruled by the same thing as 5k against 3k. |
| 499 | const historyTok = history.reduce((s, m) => s + tokEstimate(m), 0); |
| 500 | const pressure = Math.max(0, Math.min(1, budgetTokens / (historyTok || 1))); |
| 501 | // With room to spare, keeping the last turns is cheap; under strain you have |
| 502 | // to leave room for the SEARCH, which is what brings back the line from 30 |
| 503 | // turns ago. |
| 504 | const recentFrac = 0.35 + 0.45 * pressure; |
| 505 | // Recency only breaks ties UNDER PRESSURE. Measured in a sweep: under strain |
| 506 | // (16× as much context as budget) it adds +11 points, because almost no line |
| 507 | // has any relevance and what is new is the only bet left. With room to spare |
| 508 | // it SUBTRACTS −8: there document order wins, because it keeps the stretches |
| 509 | // together, and one contiguous fragment is worth more than scattered new lines. |
| 510 | const recTie = pressure < 0.25; |
| 511 | // The head goes in ALWAYS, with no gate: with the elastic window it stopped |
| 512 | // being true that "with room to spare the brief survives on its own" — it |
| 513 | // survived because we were filling right up to the edge. Measured, once we |
| 514 | // stopped filling it fell from 100% to 0% at budget 16,000. It was an |
| 515 | // accident of the padding, not of having room. |
| 516 | |
| 517 | // ── TAIL RESERVE — it is a FLOOR, not just a ceiling ─────────────────────── |
| 518 | // Stopping at the first message that does not fit turns the reserve into a cap |
| 519 | // rather than a guarantee: measured, at budget 3,000 the tail was getting |
| 520 | // 3-5% instead of the ~38% reserved, because ONE big tool result in the |
| 521 | // second-to-last position blocked everything before it. The last turns are |
| 522 | // what the model absolutely needs in order to know where it is, and that |
| 523 | // cannot depend on the preceding turn having been bulky. |
| 524 | // Until the floor (10%) is reached, a message that does not fit is TRUNCATED |
| 525 | // through the middle instead of discarded. Above it, the usual behaviour. |
| 526 | const reserve = Math.floor(budgetTokens * recentFrac); |
| 527 | const floorTok = Math.floor(budgetTokens * 0.05); |
| 528 | const recent = []; let used = 0; |
| 529 | for (let i = history.length - 1, k = 0; i >= 0 && k < RECENT; i--, k++) { |
| 530 | const m = clampMsg(history[i]), t = tokEstimate(m); |
| 531 | if (used + t <= reserve) { recent.unshift(m); used += t; continue; } |
| 532 | if (used >= floorTok) break; |
| 533 | const room = Math.max(40, Math.min(reserve, floorTok) - used - 4); |
| 534 | if (room < 40) break; |
| 535 | const c = m.content || ''; |
| 536 | const keep = Math.max(20, room * 2); |
| 537 | recent.unshift({ ...m, content: c.length <= keep ? c |
| 538 | : c.slice(0, keep) + `\n… [recortado ${c.length - keep} caracteres] …` }); |
| 539 | used += room + 4; |
| 540 | if (used >= floorTok) break; |
| 541 | } |
| 542 | let old = history.slice(0, history.length - recent.length); |
| 543 | if (!old.length || used >= budgetTokens) return { done: true, recent, used, head: [], card, budget: budgetTokens }; |
| 544 | |
| 545 | // ── HEAD RESERVE ─────────────────────────────────────────────────────────── |
| 546 | // The FIRST messages are kept verbatim and UNSCORED, just like the last ones, |
| 547 | // and only under pressure (same gate as recency, same reason). |
| 548 | // |
| 549 | // The opening carries the BRIEF: what has to be done, under what constraints. |
| 550 | // The rest of the session takes it as given, so nobody repeats it — and with |
| 551 | // no repetitions there is no lexical overlap with the current question, which |
| 552 | // means BM25 cannot rescue it no matter how much it matters. It is the only |
| 553 | // content the agent CANNOT reconstruct by looking at the code. |
| 554 | // |
| 555 | // External backing: it is the central result of StreamingLLM (Xiao, Tian, |
| 556 | // Chen, Han & Lewis, ICLR 2024, https://arxiv.org/abs/2309.17453) — the first |
| 557 | // tokens act as attention SINKS and absorb 45-55% of the mass. A pure |
| 558 | // retriever cannot see that: it is not a property of the text, but of how the |
| 559 | // model uses it. |
| 560 | // |
| 561 | // Measured (A/B on the same code, 8 seeds, a probe asking about the brief |
| 562 | // halfway through the session): |
| 563 | // budget 3,000: the brief survives 0% → 100% |
| 564 | // budget 16,000: the brief survives 100% → 100% |
| 565 | // mid-session facts: 85.7% → 85.7% · 91.1% → 91.1% |
| 566 | // That is: it rescues the brief from never to always and costs NOTHING. |
| 567 | // Head reserve DISABLED: it helped in agent sessions (the original brief went |
| 568 | // from 0/5 to 5/5) but in dialogue there is no brief to protect and the |
| 569 | // reserve charges without giving anything back — on LoCoMo it drops evidence |
| 570 | // recall from 62.5% to 56.2% at the same token count. Set 0.05 to re-enable. |
| 571 | const headReserve = 0; |
| 572 | const head = []; let headUsed = 0; |
| 573 | for (let i = 0; i < old.length; i++) { |
| 574 | const m = clampMsg(old[i]), t = tokEstimate(m); |
| 575 | if (headUsed + t > headReserve) break; |
| 576 | head.push(m); headUsed += t; |
| 577 | } |
| 578 | old = old.slice(head.length); |
| 579 | used += headUsed; |
| 580 | if (!old.length || used >= budgetTokens) return { done: true, recent, used, head, card, budget: budgetTokens }; |
| 581 | |
| 582 | // The LIVE question: the last user turn that is not a tool result. This is |
| 583 | // what everything is scored against, not the initial task — what is relevant |
| 584 | // changes on every turn. |
| 585 | const query = [...history].reverse().find(m => |
| 586 | m.role === 'user' && !(m.content || '').startsWith('[resultado'))?.content || ''; |
| 587 | |
| 588 | const stale = markSuperseded(old); |
| 589 | const items = []; |
| 590 | old.forEach((m, mi) => (m.content || '').split('\n').forEach((line, li) => |
| 591 | items.push({ mi, li, line, first: li === 0, stale: stale.has(mi) }))); |
| 592 | |
| 593 | const score = buildBM25(items.map(it => it.line)); |
| 594 | const q = [...new Set(tokens(query))]; |
| 595 | const nMsg = Math.max(old.length - 1, 1); |
| 596 | items.forEach((it, i) => { it.bm = score(i, q); it.rec = it.mi / nMsg; }); |
| 597 | return { done: false, recent, old, used, items, query, recTie, pressure, head, card, budget: budgetTokens }; |
| 598 | } |
| 599 | |
| 600 | // Selection under a single global budget, with MMR, and emission with omission |
| 601 | // markers so that the model knows something is missing. |
| 602 | function selectAndEmit(ctx, budgetTokens) { |
| 603 | const { recent, old, items } = ctx; |
| 604 | const head = ctx.head || []; |
| 605 | let used = ctx.used; |
| 606 | const cap = Math.max(40, Math.floor((budgetTokens - used) * 0.5)); |
| 607 | const idOf = it => it.mi * 100000 + it.li; |
| 608 | const cost = it => Math.min(estTok(it.line), cap) + 1; |
| 609 | |
| 610 | const pool = [...items].sort((a, b) => b.score - a.score); |
| 611 | const keep = new Set(); |
| 612 | |
| 613 | // MMR: when choosing, penalise similarity to what has already been chosen. It |
| 614 | // is the only thing that measures above plain BM25 — and not by much: |
| 615 | // +2.4 points at full scale. A 3-seed smoke test said +8.9 and that was |
| 616 | // seed noise; the header carries the honest figure. |
| 617 | // MMR is off: measured at zero contribution on both benchmarks (94.9% with |
| 618 | // and without at a 3,000 budget, 100.0% and 100.0% at 16,000). It earned its |
| 619 | // +2.4 before the elastic window and the splitter fix; those removed its job. |
| 620 | const MMR_ON = false; |
| 621 | const lambda = Math.max(0.15, Math.min(0.8, 2 * measureRedundancy(pool))); |
| 622 | const nCand = Math.max(400, Math.min(8000, Math.round(budgetTokens / 6))); |
| 623 | const cand = pool.slice(0, nCand); |
| 624 | const tok = new Map(cand.map(it => [idOf(it), simTokens(it.line)])); |
| 625 | const maxSim = new Map(cand.map(it => [idOf(it), 0])); |
| 626 | const byId = new Map(cand.map(it => [idOf(it), it])); |
| 627 | const remaining = new Set(MMR_ON ? cand.map(idOf) : []); |
| 628 | while (remaining.size && used < budgetTokens) { |
| 629 | let best = null, bestVal = -Infinity; |
| 630 | for (const id of remaining) { |
| 631 | const v = byId.get(id).score - lambda * maxSim.get(id); |
| 632 | if (v > bestVal) { bestVal = v; best = id; } |
| 633 | } |
| 634 | remaining.delete(best); |
| 635 | const it = byId.get(best), c = cost(it); |
| 636 | if (it.score < 10) continue; // MMR diversifies WITHIN what is relevant |
| 637 | if (used + c > budgetTokens) continue; |
| 638 | keep.add(best); used += c; |
| 639 | const bs = tok.get(best); |
| 640 | for (const id of remaining) maxSim.set(id, Math.max(maxSim.get(id), jaccard(tok.get(id), bs))); |
| 641 | } |
| 642 | // ELASTIC WINDOW: the budget is a CEILING, not a quota to be used up. Without |
| 643 | // this, 38% of the budget at 3,000 and 56% at 16,000 went on lines without a |
| 644 | // single word in common with the question. And what is irrelevant is not |
| 645 | // neutral ballast: retrieving well BEATS the full context (F1 28.09 vs |
| 646 | // 22.56), which means filling right up to the edge puts back by hand exactly |
| 647 | // what the compression came to remove. The window stops when the evidence |
| 648 | // runs out (stratum ≥ 10), not when the tokens run out. |
| 649 | // ⚠️ It is a TRADE-OFF: free with a tight budget (the products' case), but at |
| 650 | // 32,000 it saves 60% of the tokens at the cost of 8.9 points of the datum |
| 651 | // being present. Whether that pays off depends on whether less noise improves |
| 652 | // the answer, and this benchmark measures presence, not quality. |
| 653 | for (const it of pool) { |
| 654 | const id = idOf(it); if (keep.has(id)) continue; |
| 655 | if (it.score < 10) break; // the relevant material has run out |
| 656 | const c = cost(it); |
| 657 | if (used + c > budgetTokens) continue; |
| 658 | keep.add(id); used += c; |
| 659 | } |
| 660 | |
| 661 | // ── BUDGET CONTRACT ──────────────────────────────────────────────────────── |
| 662 | // The per-line cost ignores the per-message overhead and the omission |
| 663 | // markers, so the sum of the costs is NOT what gets emitted. Without this |
| 664 | // correction the packer overshoots what it was asked for by ~1.6-1.8× — |
| 665 | // measured — and that is precisely the "Too many tokens" this file exists to |
| 666 | // prevent. The REAL emitted size is measured and the worst-scoring lines are |
| 667 | // handed back until the output genuinely fits. |
| 668 | const emit = () => { |
| 669 | let t = recent.reduce((s, m) => s + tokEstimate(m), 0) + head.reduce((s, m) => s + tokEstimate(m), 0); |
| 670 | let open = 0; |
| 671 | old.forEach((m, mi) => { |
| 672 | let any = false, run = 0, sub = 0; |
| 673 | (m.content || '').split('\n').forEach((line, li) => { |
| 674 | if (keep.has(mi * 100000 + li)) { |
| 675 | if (run) { sub += 8; run = 0; } |
| 676 | sub += Math.min(estTok(line), cap); any = true; |
| 677 | } else run++; |
| 678 | }); |
| 679 | if (any) { if (run) sub += 8; t += sub + 4; open++; } |
| 680 | }); |
| 681 | if (open < old.length) t += 12; |
| 682 | return t; |
| 683 | }; |
| 684 | let realized = emit(); |
| 685 | if (realized > budgetTokens) { |
| 686 | const kept = items.filter(it => keep.has(idOf(it))).sort((a, b) => a.score - b.score); |
| 687 | let p = 0; |
| 688 | while (realized > budgetTokens && p < kept.length) { |
| 689 | const over = realized - budgetTokens; let freed = 0; |
| 690 | while (p < kept.length && freed < over) { |
| 691 | const it = kept[p++]; |
| 692 | keep.delete(idOf(it)); |
| 693 | freed += Math.min(estTok(it.line), cap); |
| 694 | } |
| 695 | realized = emit(); |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | const packed = []; |
| 700 | let droppedMsgs = 0; |
| 701 | old.forEach((m, mi) => { |
| 702 | const out = []; let skipped = 0; |
| 703 | (m.content || '').split('\n').forEach((line, li) => { |
| 704 | if (keep.has(mi * 100000 + li)) { |
| 705 | if (skipped) { out.push(` […${skipped} líneas omitidas…]`); skipped = 0; } |
| 706 | out.push(estTok(line) > cap ? line.slice(0, cap * 3) + ' …' : line); |
| 707 | } else skipped++; |
| 708 | }); |
| 709 | if (skipped && out.length) out.push(` […${skipped} líneas omitidas…]`); |
| 710 | if (!out.length) { droppedMsgs++; return; } |
| 711 | packed.push({ role: m.role, content: out.join('\n') }); |
| 712 | }); |
| 713 | if (droppedMsgs) packed.push({ role: 'user', content: `[…${droppedMsgs} mensajes antiguos omitidos…]` }); |
| 714 | // The card is PROTECTED, like the head and the tail, and for the very same |
| 715 | // reason: it does not compete on relevance because it cannot win — it is a |
| 716 | // tally, it shares vocabulary with nothing, and BM25 would drop it every |
| 717 | // time, which is exactly the failure it came to cover. It sits right next to |
| 718 | // the last turns, with the live question, not at the beginning. |
| 719 | return [...head, ...packed, ...(ctx.card ? [ctx.card] : []), ...recent]; |
| 720 | } |
| 721 | |
| 722 | /** |
| 723 | * Packs the history into `budgetTokens` — lexical path, synchronous. |
| 724 | * This is the one used by default: it needs no model, no network, nothing. |
| 725 | */ |
| 726 | export function packHistory(history, budgetTokens = 2200, opts = {}) { |
| 727 | if (!history.length) return history; |
| 728 | const ctx = prepare(history, budgetTokens, { summary: resumenOn(), ...opts }); |
| 729 | if (ctx.done) return [...(ctx.head || []), ...(ctx.card ? [ctx.card] : []), ...ctx.recent]; |
| 730 | const max = ctx.items.reduce((m, it) => Math.max(m, it.bm), 0) || 1; |
| 731 | for (const it of ctx.items) { |
| 732 | // Two strata separated by 10 — more than the MMR penalty (≤0.5) can span, |
| 733 | // so a line with no relevance NEVER overtakes one that has some. Within |
| 734 | // each stratum: BM25 on top, tie-break underneath. |
| 735 | it.score = (it.bm > 0 && !it.stale) ? 10 + it.bm / max : (ctx.recTie ? it.rec : 0); |
| 736 | if (it.first) it.score = Math.max(it.score, 0.5); // provenance header |
| 737 | } |
| 738 | return selectAndEmit(ctx, ctx.budget); |
| 739 | } |
| 740 | |
| 741 | /** |
| 742 | * The same, plus a second SEMANTIC opinion fused by rank. |
| 743 | * |
| 744 | * `embed(texts) -> vectors`. Encoding happens per block of lines, not line by |
| 745 | * line, because encoding every line is prohibitive and the signal survives the |
| 746 | * chunking. |
| 747 | * |
| 748 | * ★ The block size is FIXED on purpose, and that is what makes the cache worth |
| 749 | * anything. With fixed blocks the boundaries do not move as the history grows |
| 750 | * (0-4, 5-9, …), so the text of an already-encoded block NEVER changes and a |
| 751 | * turn only pays for what is NEW. If the size is DERIVED from the number of |
| 752 | * lines, then every time that number crosses a threshold ALL the blocks change |
| 753 | * and the cache misses entirely — measured, the turn starts getting more |
| 754 | * expensive as the session advances instead of cheaper. It is the "index at |
| 755 | * write time" that all of this depends on. If no `embed` is passed, or if it |
| 756 | * fails, it falls back cleanly to the lexical path. |
| 757 | * |
| 758 | * Why fuse instead of replace: measured, BM25 and the embeddings TIE overall, |
| 759 | * but they do NOT do the same job. Splitting the questions by vocabulary |
| 760 | * overlap with the answer: with no overlap, embeddings 24.28 > BM25 18.60; with |
| 761 | * overlap, BM25 29.33 > embeddings 23.58. Rank fusion keeps BOTH (24.05 / |
| 762 | * 32.73). The semantic side does not replace the lexical one: it covers its |
| 763 | * blind spot. |
| 764 | */ |
| 765 | // The semantic side sits behind a flag and is OFF by default. The gain is real |
| 766 | // (+4.50 F1) but the price is not negligible and it depends on whoever is |
| 767 | // running it: ~235 MB the first time, and without WebGPU every turn gets more |
| 768 | // expensive, always. Wired up, tested, and switched on on request. With the |
| 769 | // flag off, embed.js — and with it transformers.js and the model — IS NOT EVEN |
| 770 | // IMPORTED: exactly zero cost. |
| 771 | // localStorage.setItem('elffuss.semantic', 'on') |
| 772 | function semanticoOn() { |
| 773 | try { return localStorage.getItem('elffuss.semantic') === 'on'; } catch { return false; } |
| 774 | } |
| 775 | |
| 776 | // The TALLY CARD is also behind a flag, and for the same reason: it costs ~150 |
| 777 | // tokens of the budget and −0.7 points of recall at budget 3,000 (nothing at |
| 778 | // 16,000). In exchange the tally goes from 0% to 100% and the enumeration of |
| 779 | // what was edited from 58.9% to 90.6%. It pays off in the session that ends |
| 780 | // with "give me the list of what you touched"; in the rest you pay for nothing. |
| 781 | // localStorage.setItem('elffuss.resumen', 'on') |
| 782 | function resumenOn() { |
| 783 | try { return localStorage.getItem('elffuss.resumen') === 'on'; } catch { return false; } |
| 784 | } |
| 785 | |
| 786 | export async function packHistoryAsync(history, budgetTokens = 2200, opts = {}) { |
| 787 | let { embed, block = 5, cache } = opts; |
| 788 | if (!history.length) return history; |
| 789 | // With no explicit `embed`, it is resolved by flag with a DYNAMIC import. |
| 790 | if (!embed && semanticoOn()) { |
| 791 | try { |
| 792 | const m = await import('./embed.js'); |
| 793 | embed = m.embed; cache = cache || m.embedCache(); |
| 794 | } catch { /* no model → lexical path, the app does NOT stop working */ } |
| 795 | } |
| 796 | if (!embed) return packHistory(history, budgetTokens, opts); |
| 797 | const ctx = prepare(history, budgetTokens, { summary: resumenOn(), ...opts }); |
| 798 | if (ctx.done) return [...(ctx.head || []), ...(ctx.card ? [ctx.card] : []), ...ctx.recent]; |
| 799 | |
| 800 | try { |
| 801 | const blocks = []; |
| 802 | for (let i = 0; i < ctx.items.length; i += block) { |
| 803 | blocks.push({ from: i, text: ctx.items.slice(i, i + block).map(x => x.line).join('\n').slice(0, 2000) }); |
| 804 | } |
| 805 | const enc = cache ? (t => cache.encode(t)) : (t => embed(t)); |
| 806 | const [qv] = await enc([ctx.query.slice(0, 2000)]); |
| 807 | const bv = await enc(blocks.map(b => b.text)); |
| 808 | blocks.forEach((bl, bi) => { |
| 809 | const s = cosine(qv, bv[bi]); |
| 810 | for (let i = bl.from; i < Math.min(bl.from + block, ctx.items.length); i++) ctx.items[i].sem = s; |
| 811 | }); |
| 812 | |
| 813 | const idOf = it => it.mi * 100000 + it.li; |
| 814 | const byLex = [...ctx.items].sort((a, b) => b.bm - a.bm).map(idOf); |
| 815 | const bySem = [...ctx.items].sort((a, b) => (b.sem || 0) - (a.sem || 0)).map(idOf); |
| 816 | const fused = rrf([byLex, bySem]); |
| 817 | const max = Math.max(...fused.values()) || 1; |
| 818 | for (const it of ctx.items) { |
| 819 | const rel = !it.stale && (it.bm > 0 || (it.sem || 0) > 0); |
| 820 | it.score = rel ? 10 + (fused.get(idOf(it)) || 0) / max : (ctx.recTie ? it.rec : 0); |
| 821 | if (it.first) it.score = Math.max(it.score, 0.5); |
| 822 | } |
| 823 | return selectAndEmit(ctx, ctx.budget); |
| 824 | } catch { |
| 825 | return packHistory(history, budgetTokens, opts); // no model, no network, no quota → lexical |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | /** |
| 830 | * Embedding cache keyed by content — "think at write time": a text is encoded |
| 831 | * ONCE per session even if it reappears twenty turns later. |
| 832 | */ |
| 833 | export function createEmbedCache(embed, max = 4000) { |
| 834 | const store = new Map(); |
| 835 | return { |
| 836 | size: () => store.size, |
| 837 | async encode(texts) { |
| 838 | const miss = texts.filter(t => !store.has(t)); |
| 839 | if (miss.length) { |
| 840 | const v = await embed(miss); |
| 841 | miss.forEach((t, i) => store.set(t, v[i])); |
| 842 | while (store.size > max) store.delete(store.keys().next().value); |
| 843 | } |
| 844 | return texts.map(t => store.get(t)); |
| 845 | }, |
| 846 | }; |
| 847 | } |