nox-mem 3.9.1 → 3.10.1
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/dist/api-server.js +0 -14
- package/dist/index.js +13 -1
- package/dist/ingest-entity.js +3 -3
- package/dist/ingest.js +3 -3
- package/dist/lib/ingest-router.js +2 -3
- package/dist/lib/tombstone.js +6 -7
- package/dist/lib/workspace.js +36 -2
- package/dist/reindex.js +3 -3
- package/dist/retention.js +1 -0
- package/dist/session-distill.js +7 -2
- package/dist/watch.js +4 -4
- package/package.json +2 -3
- package/dist/lib/regex-extract/extractor.js +0 -91
- package/dist/lib/regex-extract/frontmatter.js +0 -169
- package/dist/lib/regex-extract/index.js +0 -14
- package/dist/lib/regex-extract/ingest-router-l4.js +0 -102
- package/dist/lib/regex-extract/patterns.js +0 -91
- package/dist/lib/regex-extract/production-wire.js +0 -202
- package/dist/lib/regex-extract/reconcile.js +0 -210
- package/dist/lib/regex-extract/strip-code.js +0 -52
- package/dist/lib/regex-extract/types.js +0 -25
- package/dist/lib/reranker.js +0 -327
package/dist/lib/reranker.js
DELETED
|
@@ -1,327 +0,0 @@
|
|
|
1
|
-
// D01 — Cross-encoder Reranker (shadow)
|
|
2
|
-
// 2026-05-07 impl. Spec: specs/2026-05-07-D01-cross-encoder-reranker.md (memoria-nox)
|
|
3
|
-
//
|
|
4
|
-
// Adiciona camada de cross-encoder pós-RRF ao hybrid pipeline. BGE-reranker-base
|
|
5
|
-
// via @xenova/transformers (ONNX in Node, ~85MB on disk). Default off; shadow
|
|
6
|
-
// computa lift sem mutar resultados; active substitui ranking pelo reranker.
|
|
7
|
-
//
|
|
8
|
-
// Modes (env NOX_RERANKER_MODE):
|
|
9
|
-
// off — disabled (default), no compute, no apply
|
|
10
|
-
// shadow — rerank executa, telemetria, ranking final = original (não muta)
|
|
11
|
-
// active — rerank substitui ranking final
|
|
12
|
-
//
|
|
13
|
-
// Fail-open: model load falha, ONNX timeout, exception qualquer → log + retorna
|
|
14
|
-
// candidates originais (off-mode efetivo). Zero crash exposto ao caller.
|
|
15
|
-
//
|
|
16
|
-
// Telemetria computada mesmo em shadow:
|
|
17
|
-
// - position_changes: chunks que mudaram posição entre orig top-K e rerank top-K
|
|
18
|
-
// - lift_score: |sum(orig_pos − new_pos)| / K_OUT, normalizado [0,1]
|
|
19
|
-
//
|
|
20
|
-
// Cache do modelo: default em node_modules/@xenova/transformers/.cache/
|
|
21
|
-
// Override via env TRANSFORMERS_CACHE (recomendado prod: /var/cache/nox-mem-models/).
|
|
22
|
-
// ─── Defaults ────────────────────────────────────────────────────────────────
|
|
23
|
-
export const DEFAULT_TOP_K_IN = 50;
|
|
24
|
-
export const DEFAULT_TOP_K_OUT = 10;
|
|
25
|
-
export const DEFAULT_MODEL = "Xenova/bge-reranker-base";
|
|
26
|
-
export const DEFAULT_TIMEOUT_MS = 2000;
|
|
27
|
-
// ─── Env config ──────────────────────────────────────────────────────────────
|
|
28
|
-
export function getMode() {
|
|
29
|
-
const v = (process.env.NOX_RERANKER_MODE || "off").toLowerCase();
|
|
30
|
-
if (v === "off" || v === "shadow" || v === "active")
|
|
31
|
-
return v;
|
|
32
|
-
return "off";
|
|
33
|
-
}
|
|
34
|
-
export function getTopKIn() {
|
|
35
|
-
const raw = process.env.NOX_RERANKER_TOP_K_IN;
|
|
36
|
-
if (!raw)
|
|
37
|
-
return DEFAULT_TOP_K_IN;
|
|
38
|
-
const n = parseInt(raw, 10);
|
|
39
|
-
if (!Number.isFinite(n) || n <= 0)
|
|
40
|
-
return DEFAULT_TOP_K_IN;
|
|
41
|
-
return n;
|
|
42
|
-
}
|
|
43
|
-
export function getTopKOut() {
|
|
44
|
-
const raw = process.env.NOX_RERANKER_TOP_K_OUT;
|
|
45
|
-
if (!raw)
|
|
46
|
-
return DEFAULT_TOP_K_OUT;
|
|
47
|
-
const n = parseInt(raw, 10);
|
|
48
|
-
if (!Number.isFinite(n) || n <= 0)
|
|
49
|
-
return DEFAULT_TOP_K_OUT;
|
|
50
|
-
return n;
|
|
51
|
-
}
|
|
52
|
-
export function getModelName() {
|
|
53
|
-
return process.env.NOX_RERANKER_MODEL || DEFAULT_MODEL;
|
|
54
|
-
}
|
|
55
|
-
export function getTimeoutMs() {
|
|
56
|
-
const raw = process.env.NOX_RERANKER_TIMEOUT_MS;
|
|
57
|
-
if (!raw)
|
|
58
|
-
return DEFAULT_TIMEOUT_MS;
|
|
59
|
-
const n = parseInt(raw, 10);
|
|
60
|
-
if (!Number.isFinite(n) || n < 100)
|
|
61
|
-
return DEFAULT_TIMEOUT_MS;
|
|
62
|
-
return n;
|
|
63
|
-
}
|
|
64
|
-
let cachedFn = null;
|
|
65
|
-
let cachedModelName = null;
|
|
66
|
-
let cachedFactoryError = null;
|
|
67
|
-
/**
|
|
68
|
-
* Test hook: injetar uma fn mock pra evitar download do modelo.
|
|
69
|
-
* Em produção, NÃO chamar — `rerank()` carrega lazy via @xenova/transformers.
|
|
70
|
-
*
|
|
71
|
-
* Quando fn=null + reset=true (default), limpa singleton + cached error.
|
|
72
|
-
* Use reset=false só pra cenários onde você quer preservar erro cacheado.
|
|
73
|
-
*/
|
|
74
|
-
export function __setRerankerFnForTesting(fn, reset = true) {
|
|
75
|
-
cachedFn = fn;
|
|
76
|
-
if (reset || fn !== null) {
|
|
77
|
-
cachedFactoryError = null;
|
|
78
|
-
}
|
|
79
|
-
cachedModelName = fn ? "__test__" : null;
|
|
80
|
-
}
|
|
81
|
-
/**
|
|
82
|
-
* Lazy-load do modelo. First call paga ~2-4s de cold start (ONNX bind).
|
|
83
|
-
* Subsequent calls reusam singleton. Fail-open: se carga falha, cacheia error
|
|
84
|
-
* pra evitar retry-storm.
|
|
85
|
-
*/
|
|
86
|
-
async function getRerankerFn() {
|
|
87
|
-
const wantedModel = getModelName();
|
|
88
|
-
// Test injection bypass: __test__ marker overrides model match check.
|
|
89
|
-
if (cachedFn && (cachedModelName === "__test__" || cachedModelName === wantedModel))
|
|
90
|
-
return cachedFn;
|
|
91
|
-
if (cachedFactoryError)
|
|
92
|
-
throw cachedFactoryError;
|
|
93
|
-
try {
|
|
94
|
-
// Dynamic import: Node ESM, evita carga em paths off-mode.
|
|
95
|
-
// Specifier held in a variable so tsc does not require the optional
|
|
96
|
-
// dependency at build time; a clone without it still type-checks.
|
|
97
|
-
const xenovaSpecifier = "@xenova/transformers";
|
|
98
|
-
const t = await import(xenovaSpecifier);
|
|
99
|
-
// BGE-reranker-base é cross-encoder. xenova text-classification pipeline NÃO
|
|
100
|
-
// suporta text_pair (passa pares como string única → tokenizer ignora pair).
|
|
101
|
-
// Usar API low-level: AutoTokenizer + AutoModelForSequenceClassification com
|
|
102
|
-
// tokenize batch de pares (queries + docs) → logits.
|
|
103
|
-
// Quantized=true reduz disk de ~430MB → ~85MB sem perda significativa.
|
|
104
|
-
const tokenizer = await t.AutoTokenizer.from_pretrained(wantedModel);
|
|
105
|
-
const model = await t.AutoModelForSequenceClassification.from_pretrained(wantedModel, {
|
|
106
|
-
quantized: true,
|
|
107
|
-
});
|
|
108
|
-
const fn = async (pairs) => {
|
|
109
|
-
if (pairs.length === 0)
|
|
110
|
-
return [];
|
|
111
|
-
const queries = pairs.map((p) => p.text);
|
|
112
|
-
const docs = pairs.map((p) => p.text_pair);
|
|
113
|
-
const encoded = await tokenizer(queries, {
|
|
114
|
-
text_pair: docs,
|
|
115
|
-
padding: true,
|
|
116
|
-
truncation: true,
|
|
117
|
-
});
|
|
118
|
-
const out = await model(encoded);
|
|
119
|
-
// out.logits.dims = [batch, 1]; data = Float32Array
|
|
120
|
-
const data = Array.from(out.logits.data);
|
|
121
|
-
// Sigmoid-like normalize não obrigatório (sort desc por logit funciona).
|
|
122
|
-
// Mantemos raw logits — sort desc preserva ordem correta.
|
|
123
|
-
return data.map((s) => ({ score: s }));
|
|
124
|
-
};
|
|
125
|
-
cachedFn = fn;
|
|
126
|
-
cachedModelName = wantedModel;
|
|
127
|
-
return fn;
|
|
128
|
-
}
|
|
129
|
-
catch (e) {
|
|
130
|
-
cachedFactoryError = e instanceof Error ? e : new Error(String(e));
|
|
131
|
-
throw cachedFactoryError;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
/**
|
|
135
|
-
* Pre-warm o singleton do modelo. Chamado pelo nox-mem-api boot quando
|
|
136
|
-
* NOX_RERANKER_MODE != off, pra evitar cold-start de ~12-90s no primeiro
|
|
137
|
-
* search request (D01 spec §risks §1). Idempotente: subsequent calls são no-op.
|
|
138
|
-
*/
|
|
139
|
-
export async function preloadModel() {
|
|
140
|
-
await getRerankerFn();
|
|
141
|
-
}
|
|
142
|
-
// ─── Helpers: telemetry math (pure, testable) ────────────────────────────────
|
|
143
|
-
/**
|
|
144
|
-
* Conta chunks que mudaram posição entre os top-K original e o pós-rerank.
|
|
145
|
-
* Trabalha por id (campo opcional). Chunks sem id são ignorados (não rastreáveis).
|
|
146
|
-
*/
|
|
147
|
-
export function computePositionChanges(origTopK, newTopK) {
|
|
148
|
-
const origPos = new Map();
|
|
149
|
-
const newPos = new Map();
|
|
150
|
-
origTopK.forEach((c, i) => {
|
|
151
|
-
if (typeof c.id === "number")
|
|
152
|
-
origPos.set(c.id, i);
|
|
153
|
-
});
|
|
154
|
-
newTopK.forEach((c, i) => {
|
|
155
|
-
if (typeof c.id === "number")
|
|
156
|
-
newPos.set(c.id, i);
|
|
157
|
-
});
|
|
158
|
-
const allIds = new Set([...origPos.keys(), ...newPos.keys()]);
|
|
159
|
-
let changes = 0;
|
|
160
|
-
for (const id of allIds) {
|
|
161
|
-
const a = origPos.get(id);
|
|
162
|
-
const b = newPos.get(id);
|
|
163
|
-
if (a === undefined || b === undefined) {
|
|
164
|
-
// chunk entrou ou saiu do top-K → mudança
|
|
165
|
-
changes++;
|
|
166
|
-
}
|
|
167
|
-
else if (a !== b) {
|
|
168
|
-
changes++;
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
return changes;
|
|
172
|
-
}
|
|
173
|
-
/**
|
|
174
|
-
* Lift score: mean displacement normalizado em [0, 1].
|
|
175
|
-
*
|
|
176
|
-
* Combina dois sinais:
|
|
177
|
-
* 1) displacement intra-intersection: |orig_pos − new_pos| pra ids em ambos
|
|
178
|
-
* 2) turnover (set churn): id que entrou OU saiu conta como displacement = K
|
|
179
|
-
*
|
|
180
|
-
* Total = sum(deltas) / (count * K), onde K = max(|orig|, |new|).
|
|
181
|
-
*
|
|
182
|
-
* Edge cases:
|
|
183
|
-
* - sets disjoint → todos turnover, score = 1
|
|
184
|
-
* - identical → 0
|
|
185
|
-
* - swap top-2 (K=5) → 2 ids movem 1 cada → 2/(5*4) = 0.1
|
|
186
|
-
*/
|
|
187
|
-
export function computeLiftScore(origTopK, newTopK) {
|
|
188
|
-
if (origTopK.length === 0 || newTopK.length === 0)
|
|
189
|
-
return 0;
|
|
190
|
-
const k = Math.max(origTopK.length, newTopK.length);
|
|
191
|
-
if (k <= 1)
|
|
192
|
-
return 0;
|
|
193
|
-
const origPos = new Map();
|
|
194
|
-
const newPos = new Map();
|
|
195
|
-
origTopK.forEach((c, i) => {
|
|
196
|
-
if (typeof c.id === "number")
|
|
197
|
-
origPos.set(c.id, i);
|
|
198
|
-
});
|
|
199
|
-
newTopK.forEach((c, i) => {
|
|
200
|
-
if (typeof c.id === "number")
|
|
201
|
-
newPos.set(c.id, i);
|
|
202
|
-
});
|
|
203
|
-
const allIds = new Set([...origPos.keys(), ...newPos.keys()]);
|
|
204
|
-
if (allIds.size === 0)
|
|
205
|
-
return 0;
|
|
206
|
-
let sumDelta = 0;
|
|
207
|
-
for (const id of allIds) {
|
|
208
|
-
const a = origPos.get(id);
|
|
209
|
-
const b = newPos.get(id);
|
|
210
|
-
if (a === undefined || b === undefined) {
|
|
211
|
-
// turnover: id entrou ou saiu → trata como displacement máximo (k)
|
|
212
|
-
sumDelta += k;
|
|
213
|
-
}
|
|
214
|
-
else {
|
|
215
|
-
sumDelta += Math.abs(a - b);
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
// Normalize: max possible = allIds.size * k (all turned over)
|
|
219
|
-
const norm = sumDelta / (allIds.size * k);
|
|
220
|
-
return Math.min(1, Math.max(0, norm));
|
|
221
|
-
}
|
|
222
|
-
// ─── Core rerank function ────────────────────────────────────────────────────
|
|
223
|
-
/**
|
|
224
|
-
* Rerank candidates via cross-encoder. Comportamento per mode:
|
|
225
|
-
*
|
|
226
|
-
* - off: no-op, retorna candidates.slice(0, topK), summary mode='off'
|
|
227
|
-
* - shadow: roda reranker, calcula lift, retorna candidates ORIGINAIS top-K
|
|
228
|
-
* (não muta ranking — caller recebe ordem pre-rerank)
|
|
229
|
-
* - active: roda reranker, retorna pós-rerank top-K (muta ranking)
|
|
230
|
-
*
|
|
231
|
-
* Fail-open: qualquer erro (model load, timeout, ONNX crash) → retorna
|
|
232
|
-
* candidates.slice(0, topK) original com summary.failed=true. Não joga.
|
|
233
|
-
*/
|
|
234
|
-
export async function rerank(query, candidates, topKOut) {
|
|
235
|
-
const mode = getMode();
|
|
236
|
-
const kIn = getTopKIn();
|
|
237
|
-
const kOut = topKOut ?? getTopKOut();
|
|
238
|
-
const t0 = Date.now();
|
|
239
|
-
const summaryBase = (overrides = {}) => ({
|
|
240
|
-
mode,
|
|
241
|
-
topKIn: 0,
|
|
242
|
-
topKOut: 0,
|
|
243
|
-
latencyMs: 0,
|
|
244
|
-
positionChanges: 0,
|
|
245
|
-
liftScore: 0,
|
|
246
|
-
failed: false,
|
|
247
|
-
...overrides,
|
|
248
|
-
});
|
|
249
|
-
// off-mode: bypass total
|
|
250
|
-
if (mode === "off") {
|
|
251
|
-
return {
|
|
252
|
-
results: candidates.slice(0, kOut),
|
|
253
|
-
summary: summaryBase({ topKOut: Math.min(candidates.length, kOut) }),
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
// empty / single candidate: nothing to rerank
|
|
257
|
-
if (candidates.length <= 1 || !query || query.trim().length === 0) {
|
|
258
|
-
return {
|
|
259
|
-
results: candidates.slice(0, kOut),
|
|
260
|
-
summary: summaryBase({ topKOut: Math.min(candidates.length, kOut), latencyMs: Date.now() - t0 }),
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
const slice = candidates.slice(0, kIn);
|
|
264
|
-
const origTopK = candidates.slice(0, kOut);
|
|
265
|
-
let scored;
|
|
266
|
-
try {
|
|
267
|
-
const fn = await getRerankerFn();
|
|
268
|
-
const pairs = slice.map((c) => ({
|
|
269
|
-
text: query,
|
|
270
|
-
text_pair: (c.chunk_text || "").slice(0, 4000), // safety truncate (model max 512 tokens)
|
|
271
|
-
}));
|
|
272
|
-
const timeoutMs = getTimeoutMs();
|
|
273
|
-
// Race contra timeout
|
|
274
|
-
const rerankPromise = fn(pairs);
|
|
275
|
-
const timer = new Promise((_, reject) => setTimeout(() => reject(new Error(`reranker timeout after ${timeoutMs}ms`)), timeoutMs));
|
|
276
|
-
const scores = await Promise.race([rerankPromise, timer]);
|
|
277
|
-
if (!Array.isArray(scores) || scores.length !== slice.length) {
|
|
278
|
-
throw new Error(`reranker returned ${Array.isArray(scores) ? scores.length : "non-array"} scores for ${slice.length} pairs`);
|
|
279
|
-
}
|
|
280
|
-
scored = slice.map((c, i) => ({ candidate: c, score: scores[i].score }));
|
|
281
|
-
}
|
|
282
|
-
catch (e) {
|
|
283
|
-
const msg = e?.message || String(e);
|
|
284
|
-
if (process.env.NOX_RERANKER_LOG === "1") {
|
|
285
|
-
logRerank(query, mode, kIn, kOut, Date.now() - t0, 0, 0, true, msg);
|
|
286
|
-
}
|
|
287
|
-
return {
|
|
288
|
-
results: origTopK,
|
|
289
|
-
summary: summaryBase({
|
|
290
|
-
topKIn: slice.length,
|
|
291
|
-
topKOut: origTopK.length,
|
|
292
|
-
latencyMs: Date.now() - t0,
|
|
293
|
-
failed: true,
|
|
294
|
-
failureReason: msg.slice(0, 200),
|
|
295
|
-
}),
|
|
296
|
-
};
|
|
297
|
-
}
|
|
298
|
-
// Sort by reranker score desc
|
|
299
|
-
scored.sort((a, b) => b.score - a.score);
|
|
300
|
-
const newTopK = scored.slice(0, kOut).map((s) => s.candidate);
|
|
301
|
-
const positionChanges = computePositionChanges(origTopK, newTopK);
|
|
302
|
-
const liftScore = computeLiftScore(origTopK, newTopK);
|
|
303
|
-
const latencyMs = Date.now() - t0;
|
|
304
|
-
if (process.env.NOX_RERANKER_LOG === "1") {
|
|
305
|
-
logRerank(query, mode, kIn, kOut, latencyMs, positionChanges, liftScore, false);
|
|
306
|
-
}
|
|
307
|
-
const summary = summaryBase({
|
|
308
|
-
topKIn: slice.length,
|
|
309
|
-
topKOut: kOut,
|
|
310
|
-
latencyMs,
|
|
311
|
-
positionChanges,
|
|
312
|
-
liftScore,
|
|
313
|
-
failed: false,
|
|
314
|
-
});
|
|
315
|
-
// mode=shadow: NÃO muta resultado retornado (ranking original)
|
|
316
|
-
// mode=active: substitui pelo rerank
|
|
317
|
-
return {
|
|
318
|
-
results: mode === "active" ? newTopK : origTopK,
|
|
319
|
-
summary,
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
function logRerank(query, mode, kIn, kOut, latencyMs, positionChanges, liftScore, failed, failureReason) {
|
|
323
|
-
const safeQuery = (query || "").replace(/[\r\n"]/g, " ").slice(0, 80);
|
|
324
|
-
const tag = mode === "active" ? "rerank-active" : mode === "shadow" ? "rerank-shadow" : "rerank-off";
|
|
325
|
-
const status = failed ? `FAILED reason="${(failureReason || "").slice(0, 120)}"` : "ok";
|
|
326
|
-
console.error(`[${tag}] query="${safeQuery}" kIn=${kIn} kOut=${kOut} lat=${latencyMs}ms changes=${positionChanges} lift=${liftScore.toFixed(3)} ${status}`);
|
|
327
|
-
}
|