@konneal/engine 0.2.188 → 0.2.189

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/ai.d.ts +7 -0
  2. package/dist/ask-LPNODCPM.js +16 -0
  3. package/dist/{chunk-4AP763GX.js → chunk-22WB6IVC.js} +7 -9
  4. package/dist/{chunk-G435JWGV.js → chunk-5PKKAHY4.js} +5 -5
  5. package/dist/{chunk-4BQA7PJ3.js → chunk-7YMIUTPY.js} +1 -1
  6. package/dist/{chunk-L32WSANI.js → chunk-AVNHVFEB.js} +26 -3
  7. package/dist/{chunk-VT5ZHCOC.js → chunk-ECNBEZGK.js} +5 -5
  8. package/dist/{chunk-A2HQNENL.js → chunk-FCRTWZQE.js} +121 -25
  9. package/dist/{chunk-NHYYMRZC.js → chunk-GJQT4IMD.js} +1 -1
  10. package/dist/{chunk-YGQCVPX6.js → chunk-H6ZULBW2.js} +4 -1
  11. package/dist/{chunk-SLYQ6L52.js → chunk-Q7QL3457.js} +52 -38
  12. package/dist/config.d.ts +1 -2
  13. package/dist/context.d.ts +14 -0
  14. package/dist/docOverview.d.ts +35 -0
  15. package/dist/{env-BZWHCSCL.js → env-4LR6Y5CC.js} +1 -1
  16. package/dist/prompts/understanding.md +2 -1
  17. package/dist/reflect.d.ts +1 -1
  18. package/dist/search-DE5ADCVM.js +14 -0
  19. package/dist/{tools-CYSL26HX.js → tools-7GKMDWVB.js} +5 -5
  20. package/dist/understandContract.d.ts +3 -0
  21. package/dist/worker_mcp/src/index.js +2 -2
  22. package/dist/worker_public/src/config.js +1 -1
  23. package/dist/worker_public/src/index.js +11 -11
  24. package/dist/worker_public/src/requestScope.js +2 -2
  25. package/package.json +1 -1
  26. package/workers/worker_public/prompts/understanding.md +2 -1
  27. package/workers/worker_public/src/ai.ts +30 -6
  28. package/workers/worker_public/src/ask.ts +83 -16
  29. package/workers/worker_public/src/config.ts +7 -9
  30. package/workers/worker_public/src/context.ts +14 -0
  31. package/workers/worker_public/src/docOverview.ts +77 -0
  32. package/workers/worker_public/src/faithfulness.ts +11 -1
  33. package/workers/worker_public/src/lexical.ts +21 -19
  34. package/workers/worker_public/src/ports/cloudflare/adapters.ts +4 -2
  35. package/workers/worker_public/src/reflect.ts +8 -7
  36. package/workers/worker_public/src/stages/dense.ts +29 -42
  37. package/workers/worker_public/src/stages/glossary.ts +1 -1
  38. package/workers/worker_public/src/stages/rerank.ts +6 -2
  39. package/workers/worker_public/src/understandContract.ts +4 -0
  40. package/dist/ask-TJK7DQ45.js +0 -16
  41. package/dist/search-FJAOGMEO.js +0 -14
@@ -12,12 +12,13 @@ import { retrieveInternal } from "./internal_gateway";
12
12
  import { understandQuery } from "./understand";
13
13
  import { gradePassages, gradeRetrieval } from "./grader";
14
14
  import summarizePrompt from "../prompts/summarize.md";
15
- import { embed, generateOnce } from "./ai";
15
+ import { embed, generateOnce, isCapacityError, CAPACITY_PAUSE_MS } from "./ai";
16
16
  import { reflect } from "./reflect";
17
17
  import { scoreFaithfulness } from "./faithfulness";
18
18
  import { entailmentVerdict } from "./entailment";
19
19
  import { checkQuoteAnchors, ANCHOR_CORRECTION_NOTE } from "./anchors";
20
20
  import { cacheableAnswer, canonicalRefusal, exciseMisplacedPin, refusalShaped } from "./refusal";
21
+ import { docOverviewInstruction, docOverviewRefusal } from "./docOverview";
21
22
  import { contractV2, tableRetyped } from "./refs";
22
23
  import { completeTables, completeFigures } from "./completion";
23
24
  import { NO_CONTEXT, appliedContext, contextNote, namedDocumentIn, parseContext, resolveDocScope, syntheticUnderstanding } from "./context";
@@ -233,6 +234,7 @@ async function generateStream(env: Env, model: string, messages: any[], effort?:
233
234
  if (res && res.body && typeof res.body.getReader === "function") return res.body;
234
235
  } catch (e) {
235
236
  console.error("stream failed:", model, String(e).slice(0, 120));
237
+ if (attempt === 0 && isCapacityError(e)) await new Promise((r) => setTimeout(r, CAPACITY_PAUSE_MS));
236
238
  }
237
239
  }
238
240
  return null;
@@ -1450,7 +1452,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1450
1452
  if (grade === "weak" && understanding?.docidentifier) {
1451
1453
  const broaden = `${understanding.standalone_query || q.query} ${understanding.docidentifier}`.trim();
1452
1454
  const tc = Date.now();
1453
- const second = await retrieve(env, q.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...(routeSubset ? { stageSubset: routeSubset } : {}) });
1455
+ const second = await retrieve(env, q.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, licensedDocNumbers, ...(routeSubset ? { stageSubset: routeSubset } : {}) });
1454
1456
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q.query, second.hits.map((h: Hit) => h.text));
1455
1457
  stageTiming.corrective = Date.now() - tc;
1456
1458
  if (grade2 === "good") retrieved = second; // corrective retry must be strictly better
@@ -1560,13 +1562,14 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1560
1562
  const passagePool = registerOwns
1561
1563
  ? [...opsHits, ...hits].filter((h) => !!(h.metadata as any).cert_holder)
1562
1564
  : [...opsHits, ...hits];
1565
+ const baseNotes = [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote];
1566
+ const promptNotes = [...baseNotes, ...(retrieved.notes ?? [])].filter(Boolean).join("\n") || undefined;
1563
1567
  const built = buildMessages(
1564
1568
  q.query,
1565
1569
  passagePool,
1566
1570
  q.lang,
1567
1571
  keptHistory,
1568
- // stage-extracted graph facts (GraphRAG) ride the same note channel
1569
- [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...(retrieved.notes ?? [])].filter(Boolean).join("\n") || undefined,
1572
+ promptNotes,
1570
1573
  summary,
1571
1574
  budget,
1572
1575
  ablate?.noCompress !== true,
@@ -1820,6 +1823,36 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1820
1823
  } catch { /* deliver what we have */ }
1821
1824
  }
1822
1825
  }
1826
+ // the document lane's twin of the guard above (./docOverview):
1827
+ // the question asks what the named document is and that
1828
+ // document's own passages were in the prompt — one bounded
1829
+ // regeneration; the tokens already sent are replaced through
1830
+ // the retry sentinel, and a regeneration that yields nothing
1831
+ // leaves the refusal in place rather than a blank answer
1832
+ if (!escalateAnswer && docOverviewRefusal({ answer: full, refusal: refusalAnswer(), understanding, used: usedHits })) {
1833
+ console.log("blind-answer(doc, stream): the named document's passages were in the prompt but the answer refused — regenerating once");
1834
+ streamRestarts += 1;
1835
+ mark("Re-answering from the document's passages");
1836
+ send({ type: "retry" });
1837
+ const regen = await generateStream(env, model, [
1838
+ ...messages.slice(0, -1),
1839
+ { role: "user", content: docOverviewInstruction(understanding!.docidentifier ?? understanding!.doc_number!) },
1840
+ messages[messages.length - 1],
1841
+ ], routeEffort(routed.route));
1842
+ if (regen) {
1843
+ let replaced = false;
1844
+ try {
1845
+ for await (const tok of sseTokens(regen)) {
1846
+ if (!replaced) {
1847
+ full = "";
1848
+ replaced = true;
1849
+ }
1850
+ full += tok;
1851
+ send({ type: "token", v: tok });
1852
+ }
1853
+ } catch { /* deliver what we have */ }
1854
+ }
1855
+ }
1823
1856
  // the misplaced-pin wall rides the streamed path too: a
1824
1857
  // CITED stream is not a refusal
1825
1858
  // the escalation's citation contract (TODO.sota/21): every
@@ -2032,6 +2065,30 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2032
2065
  // (measured on chip-scoped asks: correct cited answers carrying the
2033
2066
  // pin mid-text, read by users and graders as total refusals)
2034
2067
  if (answer) answer = exciseMisplacedPin(answer!, answerCites(answer!));
2068
+ // the document lane's blind-answer guard (2026-12-03, ./docOverview):
2069
+ // the question asks what the named document is, that document's own
2070
+ // passages were in the prompt, and the answer is still the refusal —
2071
+ // the refusal habit the register guard further down regenerates. One
2072
+ // bounded regeneration here, BEFORE the contract checks, so the new
2073
+ // answer passes through them like a first draft. A specific
2074
+ // requirement the passages lack is not an overview question: its
2075
+ // honest refusal stands. An escalation's refusal is its own verdict.
2076
+ if (answer && !escalateAnswer && docOverviewRefusal({ answer: answer!, refusal: refusalAnswer(), understanding, used: usedHits })) {
2077
+ console.log("blind-answer(doc): the named document's passages were in the prompt but the answer refused — regenerating once");
2078
+ generateRetries += 1;
2079
+ const regen = await generateOnce(env, model, [
2080
+ ...messages.slice(0, -1),
2081
+ { role: "user", content: docOverviewInstruction(understanding!.docidentifier ?? understanding!.doc_number!) },
2082
+ messages[messages.length - 1],
2083
+ ], routeEffort(routed.route));
2084
+ if (regen) {
2085
+ const grounded = exciseMisplacedPin(canonicalRefusal(scrubToolLines(regen), refusalScope(answerCites(regen))), answerCites(regen));
2086
+ if (!grounded.includes(refusalAnswer())) {
2087
+ answer = grounded;
2088
+ console.log("blind-answer(doc): regeneration grounded");
2089
+ }
2090
+ }
2091
+ }
2035
2092
  // the tool-narration leak (2026-10-14, the R 134-1 probe): the answer
2036
2093
  // model sometimes NARRATES the agent loop's call in prose — 'The
2037
2094
  // db.find tool returned, for the query "…": {…json…}' — instead of
@@ -2101,31 +2158,41 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2101
2158
  }
2102
2159
 
2103
2160
  // ── Self-RAG reflection loop ──
2104
- // The model critiques its own answer; if claims are ungrounded, retry
2105
- // retrieval with the missing-info hint (max one retry).
2106
- // Ref: selfrag.github.io; arXiv 2606.05658 bounded reflection
2107
- if (answer && !answer!.includes(refusalAnswer())) {
2108
- const reflection = await reflect(env.AI, MODELS.grader, q.query, answer!, hits.map((h: Hit) => h.text));
2161
+ // Skipped when the answer drew on an assembled full document or the register
2162
+ // lane (their evidence is not in the passage window). Retries forward the
2163
+ // full retrieval scope and authoritative notes, and never replace an already-
2164
+ // answered turn with a refusal.
2165
+ if (answer && !escalateAnswer && !registerOwns && !answer!.includes(refusalAnswer())) {
2166
+ const reflection = await reflect(env.AI, roleModel(env, "grader"), q.query, answer!, used.map((h: Hit) => h.text), promptNotes);
2109
2167
  console.log("reflection:", reflection ? (reflection!.grounded ? "grounded" : "ungrounded") : "null");
2110
2168
  if (reflection && !reflection!.grounded && reflection!.missing_info) {
2111
- // re-retrieve targeting what was missing — the declared context's
2112
- // hard seal binds the retry exactly as the first pass
2113
- // (TODO.ai-platform/02)
2114
2169
  const retryRetrieve = await retrieve(env, q.query, {
2115
2170
  prev,
2116
2171
  understanding: { ...understanding, standalone_query: `${understanding?.standalone_query || q.query} ${reflection!.missing_info}` } as any,
2172
+ federate,
2173
+ userDocs,
2117
2174
  sealScope: declaredScoped ? docScope : null,
2118
2175
  datasetScope: narrowed ? corpora : null,
2119
2176
  standardKeys,
2177
+ lexicalBoost,
2178
+ licensedDocNumbers,
2120
2179
  ...(routeSubset ? { stageSubset: routeSubset ?? undefined } : {}),
2121
2180
  });
2122
2181
  if (retryRetrieve.hits.length > 0) {
2123
- const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q.query, retryRetrieve.hits, q.lang, keptHistory, undefined, summary, budget, ablate?.noCompress !== true);
2182
+ const retryNotes = [...baseNotes, ...(retryRetrieve.notes ?? [])].filter(Boolean).join("\n") || undefined;
2183
+ const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q.query, retryRetrieve.hits, q.lang, keptHistory, retryNotes, summary, budget, ablate?.noCompress !== true);
2124
2184
  const retryAnswer = await generateOnce(env, model, retryMessages, routeEffort(routed.route));
2125
- // the answer now comes from the retry passages — citations must follow
2126
2185
  if (retryAnswer) {
2127
- answer = canonicalRefusal(retryAnswer!, refusalScope(answerCites(retryAnswer!)));
2128
- used = retryUsed;
2186
+ const retryCanonical = exciseMisplacedPin(
2187
+ canonicalRefusal(scrubToolLines(retryAnswer!), refusalScope(answerCites(retryAnswer!))),
2188
+ answerCites(retryAnswer!),
2189
+ );
2190
+ if (!retryCanonical.includes(refusalAnswer())) {
2191
+ answer = retryCanonical;
2192
+ used = retryUsed;
2193
+ } else {
2194
+ console.log("reflection: retry refused — keeping initial answer");
2195
+ }
2129
2196
  }
2130
2197
  }
2131
2198
  }
@@ -36,10 +36,13 @@ export const MODELS = {
36
36
  // operations deployment points ACTS_MODEL at the stronger reasoning
37
37
  // tier; the floor is the understand lane
38
38
  acts: FLASH,
39
- // generation fallback when the answer model is unavailable — the same
40
- // model as the primary while it is the only live cheap option: the
41
- // retry inside generateOnce is the only diversity this lane has
42
- fallback: FLASH,
39
+ // generation fallback when the answer model is unavailable. A fallback
40
+ // has to be ANOTHER model — as the primary's own twin (0.2.188) it added
41
+ // nothing to the retry inside generateOnce. glm-5.3 is a different
42
+ // family and fast; its flagship price only applies on the rare path
43
+ // where the primary failed. Text-only: the call sites flatten image
44
+ // parts before handing messages to it.
45
+ fallback: "@cf/zai-org/glm-5.3",
43
46
  grader: FLASH, // CRAG grader + judges
44
47
  // contextual enrichment is the QUALITY-FIRST lane (one-time spend over
45
48
  // the corpus, its quality persists into every future retrieval)
@@ -107,11 +110,6 @@ export const THRESHOLDS = {
107
110
  // the extractive compression arm (TODO.sota/02 row 5): when ablated
108
111
  // on, each passage body is compressed to this share of its budget
109
112
  compressShare: 0.6,
110
- // the dense scope's starvation fallback (the R 134-2 figure question):
111
- // when the in-code doc scope cuts the vector-level top-K to zero, the
112
- // re-query runs at this depth and scopes in code (the native filter is
113
- // dead — measured 2026-10-05)
114
- denseStarveK: 100,
115
113
  // the decision pass (TODO.decisions): the gate fires at decisionsGateMin
116
114
  // noul; the bands assemble met / not clearly stated / not met
117
115
  decisionsGateMin: 0.5,
@@ -190,6 +190,19 @@ export function matchesDocScope(
190
190
  return last === scopeDocNumber.toLowerCase();
191
191
  }
192
192
 
193
+ /** The platform-side form of a doc scope. Vectorize filters return
194
+ * results only for the fields the index has indexed for filtering — on
195
+ * this index doc_number, edition, language and doctype; a filter on
196
+ * doc_id, clause_anchor or docidentifier returns nothing, and `$and` /
197
+ * `$or` arrays are rejected (measured 2026-12-03 on the production
198
+ * index). The scope's number is asked for as written and, for a part,
199
+ * as its family's base too: the index stores "60" on family grain and
200
+ * "60-1" on some planes. */
201
+ export function docScopeFilter(scopeDocNumber: string): { doc_number: { $in: string[] } } {
202
+ const base = scopeDocNumber.split("-")[0];
203
+ return { doc_number: { $in: base === scopeDocNumber ? [scopeDocNumber] : [scopeDocNumber, base] } };
204
+ }
205
+
193
206
  export async function resolveDocScope(env: any, ctx: DeclaredContext): Promise<DocScope | null> {
194
207
  if (!ctx.doc) return null;
195
208
  const parsed = parseDocRef(ctx.doc, ctx.edition);
@@ -311,6 +324,7 @@ export function syntheticUnderstanding(scope: DocScope) {
311
324
  edition: scope.edition ?? null,
312
325
  language: null,
313
326
  process_intent: false,
327
+ doc_overview: false,
314
328
  term: null,
315
329
  defined_terms: [],
316
330
  standalone_query: "",
@@ -0,0 +1,77 @@
1
+ // The document lane's blind-answer guard (2026-12-03). The register lane
2
+ // has regenerated a refusal since 0.2.80 ("blind-answer" in ask.ts): the
3
+ // refusal habit drafts first even when the prompt carries the answer.
4
+ // Measured on deepseek-v4.1-flash — "What is R 60?" refused 3/20 with
5
+ // R 60's own passages in the prompt while a bulletin outranked them.
6
+ // The same one bounded regeneration, on a trigger narrow enough to keep
7
+ // honest absence intact: the question must ask what the NAMED document
8
+ // is (understanding.doc_overview), and that document's own passages
9
+ // must be in the prompt. A specific requirement the passages lack is
10
+ // not an overview question, so its refusal stands.
11
+ import { matchesDocScope } from "./context.ts";
12
+ import type { QueryUnderstanding } from "./understandContract.ts";
13
+
14
+ type PassageMeta = { doc_number?: string; docidentifier?: string };
15
+
16
+ /** "OIML R 60-1:2021" → "r 60-1": the publisher prefix and the edition
17
+ * drop, the series letter and the number (with any part) stay. */
18
+ export function identKey(docidentifier: string | null | undefined): string | null {
19
+ const m = String(docidentifier ?? "")
20
+ .replace(/\s*\([A-Z]\)\s*$/, "")
21
+ .replace(/:\d+$/, "")
22
+ .match(/([A-Z])\s*-?\s*(\d+(?:-[A-Za-z0-9]+)?)\s*$/i);
23
+ return m ? `${m[1].toLowerCase()} ${m[2].toLowerCase()}` : null;
24
+ }
25
+
26
+ const baseOf = (key: string) => key.split(" ")[1].split("-")[0];
27
+
28
+ /** A passage is the named publication's own when its identifier names
29
+ * the same series and number — every part of a base-named publication
30
+ * ("R 60" covers R 60-1, R 60-A, the 1991 edition), only the named part
31
+ * when a part is named. The identifier decides whenever the passage has
32
+ * one: index metadata keys the number inconsistently (the base "60" on
33
+ * family grain, a part as "60-1" on some planes) and carries no series,
34
+ * so the number alone cannot tell R 60 from a B 60 or R 60-2 from the
35
+ * named R 60-1. A passage with no identifier falls back to the engine's
36
+ * own scope matcher, at the named part's grain. */
37
+ export function isNamedDocumentPassage(meta: PassageMeta, docNumber: string, docidentifier: string | null | undefined): boolean {
38
+ const named = identKey(docidentifier);
39
+ const own = identKey(meta.docidentifier);
40
+ if (!named || !own) return matchesDocScope(meta, named?.split(" ")[1] ?? docNumber);
41
+ const [namedType, namedNum] = named.split(" ");
42
+ const [ownType, ownNum] = own.split(" ");
43
+ if (namedType !== ownType) return false;
44
+ return namedNum.includes("-") ? ownNum === namedNum : baseOf(named) === baseOf(own);
45
+ }
46
+
47
+ /** How many of the prompt's passages are the named publication's own. */
48
+ export function inScopePassages(
49
+ used: ReadonlyArray<{ metadata?: PassageMeta }>,
50
+ docNumber: string,
51
+ docidentifier: string | null | undefined,
52
+ ): number {
53
+ let n = 0;
54
+ for (const h of used) if (h.metadata && isNamedDocumentPassage(h.metadata, docNumber, docidentifier)) n += 1;
55
+ return n;
56
+ }
57
+
58
+ export function docOverviewRefusal(args: {
59
+ answer: string;
60
+ refusal: string;
61
+ understanding: QueryUnderstanding | null | undefined;
62
+ used: ReadonlyArray<{ metadata?: PassageMeta }>;
63
+ }): boolean {
64
+ const { answer, refusal, understanding, used } = args;
65
+ if (!understanding?.doc_overview) return false;
66
+ const docNumber = understanding.doc_number;
67
+ if (!docNumber) return false;
68
+ return answer.includes(refusal) && inScopePassages(used, docNumber, understanding.docidentifier) > 0;
69
+ }
70
+
71
+ /** The regeneration's ground instruction: say what the publication is
72
+ * from its own passages, cite them, and still admit when none of them
73
+ * describes the publication. */
74
+ export function docOverviewInstruction(docidentifier: string): string {
75
+ const doc = docidentifier.trim();
76
+ return `The passages above include ${doc}'s own text, and the question asks what ${doc} is. Answer it from those passages — what the publication is, what it specifies or covers — citing a passage for each claim. Only say the information is missing if none of the ${doc} passages describes the publication.`;
77
+ }
@@ -51,5 +51,15 @@ export async function scoreFaithfulness(
51
51
  return verdict;
52
52
  })();
53
53
 
54
- return await Promise.race([call, timeout]);
54
+ // fail-open like the sibling judges (gradeRetrieval, scoreJudge): a
55
+ // model call that throws — the per-minute inference limit (3021) under
56
+ // concurrent load, a capacity error — leaves the confidence note
57
+ // unmeasured instead of taking the whole answer down with it (the 500s
58
+ // on /v1/ask and /v1/admin/judge in the 2026-12-03 gate)
59
+ try {
60
+ return await Promise.race([call, timeout]);
61
+ } catch (e) {
62
+ console.error("faithfulness: judge failed —", String(e).slice(0, 140));
63
+ return null;
64
+ }
55
65
  }
@@ -53,31 +53,33 @@ function rowMeta(r: any): ChunkMeta {
53
53
  };
54
54
  }
55
55
 
56
+ // SQLite FTS5 bm25() returns negative scores (more negative = stronger match).
57
+ // Map monotonically into [0, 0.5) so stronger lexical matches still outrank
58
+ // weaker ones while staying strictly below dense cosine scores (~0.55–0.85)
59
+ // if rerank falls back to score order.
60
+ function lexicalScore(rank: unknown): number {
61
+ const bm25 = typeof rank === "number" && Number.isFinite(rank) ? rank : 0;
62
+ const strength = Math.abs(bm25);
63
+ return (0.5 * strength) / (1 + strength);
64
+ }
65
+
56
66
  export function rowsToHits(rows: any[]): Hit[] {
57
- return rows.map((r: any) => {
58
- // rank is bm25 (lower better) → convert to positive score that RRF can ignore
59
- // (RRF uses rank position, not score). score kept for logging only.
60
- const bm25 = typeof r.rank === "number" ? r.rank : 0;
61
- return {
62
- id: String(r.id),
63
- score: 1 / (1 + Math.max(0, bm25)),
64
- metadata: rowMeta(r),
65
- text: String(r.text ?? ""),
66
- } satisfies Hit;
67
- });
67
+ return rows.map((r: any) => ({
68
+ id: String(r.id),
69
+ score: lexicalScore(r.rank),
70
+ metadata: rowMeta(r),
71
+ text: String(r.text ?? ""),
72
+ } satisfies Hit));
68
73
  }
69
74
 
70
75
  /** Lexical matches for the lane merges: match-shaped, with the text
71
76
  * riding the metadata (toHits reads chunk_text out of it). */
72
77
  function rowsToMatches(rows: any[]): { id: string; score: number; metadata: Record<string, unknown> }[] {
73
- return rows.map((r: any) => {
74
- const bm25 = typeof r.rank === "number" ? Math.max(0, r.rank) : 0;
75
- return {
76
- id: String(r.id),
77
- score: 1 / (1 + bm25),
78
- metadata: { ...rowMeta(r), chunk_text: String(r.text ?? "") },
79
- };
80
- });
78
+ return rows.map((r: any) => ({
79
+ id: String(r.id),
80
+ score: lexicalScore(r.rank),
81
+ metadata: { ...rowMeta(r), chunk_text: String(r.text ?? "") },
82
+ }));
81
83
  }
82
84
 
83
85
  /** Lexical ranking WITHIN a document set (the graph lanes' identity
@@ -78,6 +78,7 @@ export function cfModelRunner(ai: unknown): ModelRunner {
78
78
  throw new Error(`embedding failed for all request shapes (${texts.length} text(s))`);
79
79
  },
80
80
  async rerank(model, query, texts) {
81
+ let firstErr: unknown = null;
81
82
  for (const body of RERANK_SHAPES(query, texts)) {
82
83
  try {
83
84
  const res: any = await A.run(model, body);
@@ -94,10 +95,11 @@ export function cfModelRunner(ai: unknown): ModelRunner {
94
95
  if (Number.isInteger(id) && id >= 0 && id < texts.length && Number.isFinite(s)) scores[id] = s;
95
96
  });
96
97
  if (scores.some((s) => Number.isFinite(s))) return scores;
97
- } catch {
98
- // next shape
98
+ } catch (e) {
99
+ if (firstErr === null) firstErr = e;
99
100
  }
100
101
  }
102
+ if (firstErr !== null) console.error("rerank adapter failed:", String(firstErr).slice(0, 180));
101
103
  return null;
102
104
  },
103
105
  async run(req: GenerateRequest): Promise<GenerateResult> {
@@ -5,6 +5,7 @@
5
5
 
6
6
  // The prompt is data (prompts/reflect.md), bundled as text.
7
7
  import reflectPrompt from "../prompts/reflect.md";
8
+ import { generationSampling } from "./config";
8
9
 
9
10
  export interface ReflectionResult {
10
11
  grounded: boolean;
@@ -17,12 +18,16 @@ export async function reflect(
17
18
  question: string,
18
19
  answer: string,
19
20
  passages: string[],
21
+ notes?: string,
20
22
  ): Promise<ReflectionResult | null> {
21
23
  if (!answer || !passages.length) return null;
24
+ // 900 chars per passage clears the ~250-char contextual-enrichment prefix
25
+ // so the critic sees the actual clause text alongside the authoritative notes.
22
26
  const ctx = passages
23
27
  .slice(0, 8)
24
- .map((p, i) => `[${i + 1}] ${p.replace(/\s+/g, " ").slice(0, 300)}`)
28
+ .map((p, i) => `[${i + 1}] ${p.replace(/\s+/g, " ").slice(0, 900)}`)
25
29
  .join("\n");
30
+ const noteBlock = notes?.trim() ? `\n\nAuthoritative notes:\n${notes.trim().slice(0, 1500)}` : "";
26
31
 
27
32
  const timeout = new Promise<null>((r) => setTimeout(() => r(null), 6000));
28
33
  const call = (async () => {
@@ -34,16 +39,12 @@ export async function reflect(
34
39
  },
35
40
  {
36
41
  role: "user",
37
- content: `Question: ${question}\n\nAnswer:\n${answer.slice(0, 1500)}\n\nPassages:\n${ctx}`,
42
+ content: `Question: ${question}\n\nAnswer:\n${answer.slice(0, 1500)}\n\nPassages:\n${ctx}${noteBlock}`,
38
43
  },
39
44
  ],
40
- // reasoning shares this budget — starved budgets silently disable
41
- // the reflection layer (null = no retry ever fires); DeepSeek-V4
42
- // card: keep reasoning on with headroom + temp 1.0 / top_p 1.0
43
45
  max_tokens: 3072,
44
46
  reasoning_effort: "low",
45
- temperature: 1.0,
46
- top_p: 1.0,
47
+ ...generationSampling(model),
47
48
  });
48
49
  const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
49
50
  const m = (text ?? "").match(/\{[\s\S]*\}/);
@@ -3,18 +3,19 @@
3
3
  // query, no filter — bit-for-bit same candidates, one serial round-trip
4
4
  // saved), the doc/edition-filtered query with its guessed-pin drop and
5
5
  // sparse-filter widen, and the plain unfiltered query.
6
- import { LIMITS, THRESHOLDS } from "../config.ts";
7
- import { matchesDocScope } from "../context.ts";
6
+ import { LIMITS } from "../config.ts";
7
+ import { docScopeFilter, matchesDocScope } from "../context.ts";
8
8
  import type { Stage } from "./types.ts";
9
9
 
10
10
  export const dense: Stage = {
11
11
  name: "dense",
12
12
  run: async (c) => {
13
13
  const { env, filters, vector, opts, rq, folded } = c;
14
- // the index's metadata filtering is DEAD on this platform (measured
15
- // 2026-10-05: filters return empty for values proven present), so
16
- // the scope never rides the query — the matches filter IN CODE and
17
- // the sparse widen still covers thin scopes
14
+ // The scope does not ride the first query: the platform's metadata
15
+ // filter answers only on the fields the index has indexed for it, so
16
+ // the unfiltered top-K is scoped in code, and the document's own
17
+ // nearest chunks come from the native filter only when that scope
18
+ // starves (below).
18
19
  const q: any = { topK: LIMITS.retrieveK, returnMetadata: "all" };
19
20
  const optimistic = opts.optimisticHits ?? [];
20
21
  const sameLane = rq === folded; // optimistic vector === this lane's vector
@@ -36,48 +37,34 @@ export const dense: Stage = {
36
37
  }
37
38
  if (filters?.doc_number) {
38
39
  const allMatches: any[] = (await env.VECTORIZE.query(vector, q)).matches ?? [];
39
- let matches: any[] = allMatches;
40
- const before = matches.length;
41
- matches = matches.filter((m) => matchesDocScope(m.metadata ?? {}, filters.doc_number!));
42
- if (filters.edition) matches = matches.filter((m) => !m.metadata?.edition || String(m.metadata.edition) === filters.edition);
43
- console.log("dense scope (in code):", before, "→", matches.length, "in doc", filters.doc_number, filters.edition ? `@${filters.edition}` : "");
44
- // the in-code starvation fallback (observed live: the R 134-2
45
- // figure question — the vector-level top-K held ZERO members of
46
- // the asked document, so the scope cut to nothing and the answer
47
- // ran on other lanes' leftovers): re-query at a deep topK and
48
- // scope in code — the NATIVE metadata filter is dead on this
49
- // platform (measured 2026-10-05: filters return empty for values
50
- // proven present), so the document's own nearest neighbors are
51
- // reachable only through a wider net. Fires only when the scope
52
- // starves to zero — zero behavior when the scope matches.
53
- if (!matches.length) {
40
+ const before = allMatches.length;
41
+ let docMatches = allMatches.filter((m) => matchesDocScope(m.metadata ?? {}, filters.doc_number!));
42
+ // When the global top-K holds fewer than rerankKeep hits for the named
43
+ // doc_number (e.g. 0 hits, or 1 stray R 29 hit when asking about D 29),
44
+ // query Vectorize's native doc_number filter before widening to unrelated
45
+ // documents.
46
+ if (docMatches.length < LIMITS.rerankKeep) {
54
47
  try {
55
- const wide: any = await env.VECTORIZE.query(vector, { ...q, topK: THRESHOLDS.denseStarveK });
56
- matches = (wide.matches ?? []).filter((m: any) => matchesDocScope(m.metadata ?? {}, filters.doc_number!));
57
- console.log("dense scope starvation → deep re-query:", matches.length, "doc members in the top", THRESHOLDS.denseStarveK);
48
+ const own: any = await env.VECTORIZE.query(vector, { ...q, filter: docScopeFilter(filters.doc_number) });
49
+ const ownMatches = (own.matches ?? []).filter((m: any) => matchesDocScope(m.metadata ?? {}, filters.doc_number!));
50
+ const seen = new Set(docMatches.map((m: any) => m.id));
51
+ const added = ownMatches.filter((m: any) => !seen.has(m.id));
52
+ if (added.length) {
53
+ docMatches = [...docMatches, ...added];
54
+ console.log("dense scope sparse → native doc filter:", docMatches.length, "doc members");
55
+ }
58
56
  } catch (e) {
59
- // the deep net must never break the ask: a rejected re-query
60
- // (topK above the platform cap, a transient index error)
61
- // degrades to the pre-fallback state — other lanes' leftovers
62
57
  console.log("dense scope starvation re-query failed:", String(e).slice(0, 120));
63
58
  }
64
59
  }
65
- // an edition pin corroborated by (almost) nothing means the pin
66
- // was a guess — understanding emits editions for families it
67
- // mixes up (observed: R 76 pinned @2021, an R 60 year; the corpus
68
- // holds 1988/1992/2006). The index is the ground truth for which
69
- // editions EXIST: a wrong pin starves the doc filter and the
70
- // widen then floods the pool with superseded editions. Drop to
71
- // the doc-only filter and let family-relative steering rank
72
- // editions downstream. A pin the user actually asked for
73
- // survives — its edition exists in the corpus.
74
- // the same guess-drop, in code: a pinned edition that starved the
75
- // scoped set drops to the doc-only scope
60
+ let matches: any[] = filters.edition
61
+ ? docMatches.filter((m) => !m.metadata?.edition || String(m.metadata.edition) === filters.edition)
62
+ : docMatches;
63
+ console.log("dense scope (in code):", before, "→", matches.length, "in doc", filters.doc_number, filters.edition ? `@${filters.edition}` : "");
76
64
  if (filters && filters.edition && matches.length < 3) {
77
- const docOnly = allMatches.filter((m) => matchesDocScope(m.metadata ?? {}, filters.doc_number!));
78
- if (docOnly.length > matches.length) {
79
- console.log("edition pin dropped:", filters.doc_number, "@", filters.edition, "→", docOnly.length, "doc-scoped hits (edition not in corpus)");
80
- matches = docOnly;
65
+ if (docMatches.length > matches.length) {
66
+ console.log("edition pin dropped:", filters.doc_number, "@", filters.edition, "→", docMatches.length, "doc-scoped hits (edition not in corpus)");
67
+ matches = docMatches;
81
68
  filters.edition = undefined;
82
69
  }
83
70
  }
@@ -39,7 +39,7 @@ export const glossary: Stage = {
39
39
  definition: String(m.metadata?.chunk_text ?? "").split(" — ").slice(1).join(" — ").slice(0, 300),
40
40
  docidentifier: String(m.metadata?.docidentifier ?? ""),
41
41
  doc_number: String(m.metadata?.doc_number ?? ""),
42
- score: rs ? rs[i] : m.score,
42
+ score: rs && Number.isFinite(rs[i]) ? rs[i] : m.score,
43
43
  }))
44
44
  .filter((x: any) => x.term && x.definition);
45
45
  })();
@@ -26,7 +26,11 @@ export const rerankStage: Stage = {
26
26
  const scores = await rerank(portModelRunner(c.env), MODELS.rerank, c.query, c.hits.map((h) => h.text));
27
27
  console.log("stage: rerank", Date.now() - tRerank, "ms over", c.hits.length, "candidates");
28
28
  if (scores) {
29
- c.hits.forEach((h, i) => (h.rerank_score = scores[i]));
29
+ const finite = scores.filter((s) => Number.isFinite(s));
30
+ const minFinite = finite.length ? Math.min(...finite) : 0;
31
+ const span = finite.length ? Math.max(...finite) - minFinite : 0;
32
+ const floor = minFinite - Math.max(0.01, span);
33
+ c.hits.forEach((h, i) => (h.rerank_score = Number.isFinite(scores[i]) ? scores[i] : floor));
30
34
  c.hits.sort((a, b) => (b.rerank_score ?? -Infinity) - (a.rerank_score ?? -Infinity));
31
35
  if (c.filter?.doc_number) {
32
36
  // pin the scoped doc's OWN front matter: the synthetic family
@@ -38,7 +42,7 @@ export const rerankStage: Stage = {
38
42
  const families = c.hits.filter((h) => h.metadata.clause_anchor === "family" && String(h.metadata.doc_number ?? "").split("-")[0] === String(c.filter!.doc_number).split("-")[0]);
39
43
  const own = families.length
40
44
  ? families
41
- : c.hits.filter((h) => String(h.metadata.doc_number ?? "") === String(c.filter!.doc_number).split("-")[0] && /^(overview|)$/i.test(String(h.metadata.clause_anchor ?? "")));
45
+ : c.hits.filter((h) => h.text.trim().length > 0 && h.metadata.doctype !== "certificate" && String(h.metadata.doc_number ?? "") === String(c.filter!.doc_number).split("-")[0] && /^(overview|)$/i.test(String(h.metadata.clause_anchor ?? "")));
42
46
  if (own.length) {
43
47
  const ownIds = new Set(own.map((h) => h.id));
44
48
  c.hits = [...own, ...c.hits.filter((h) => !ownIds.has(h.id))];
@@ -13,6 +13,9 @@ export interface QueryUnderstanding {
13
13
  language?: string | null;
14
14
  /** the question is about a process around publications (certify, apply…) */
15
15
  process_intent: boolean;
16
+ /** the question asks what the NAMED publication is or covers as a whole
17
+ * (an overview of the document), not something inside it */
18
+ doc_overview: boolean;
16
19
  /** definition-style question whose subject is `term` */
17
20
  term: string | null;
18
21
  /** corpus-terminology mapping of everyday wording (drift→creep) */
@@ -44,6 +47,7 @@ export function extractJson(text: string): QueryUnderstanding | null {
44
47
  edition: typeof raw.edition === "string" && /^\d{4}$/.test(raw.edition) ? raw.edition : null,
45
48
  language: typeof raw.language === "string" && /^[a-z]{2}$/.test(raw.language) ? raw.language : null,
46
49
  process_intent: raw.process_intent === true,
50
+ doc_overview: raw.doc_overview === true,
47
51
  term: typeof raw.term === "string" && raw.term.trim() ? raw.term.trim().slice(0, 60) : null,
48
52
  defined_terms: Array.isArray(raw.defined_terms)
49
53
  ? raw.defined_terms.filter((t: unknown) => typeof t === "string" && (t as string).trim()).map((t: string) => t.trim().slice(0, 60)).slice(0, 4)
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-A2HQNENL.js";
4
- import "./chunk-IRCDOFP4.js";
5
- import "./chunk-VT5ZHCOC.js";
6
- import "./chunk-SLYQ6L52.js";
7
- import "./chunk-L32WSANI.js";
8
- import "./chunk-NHYYMRZC.js";
9
- import "./chunk-ETLSWSZ7.js";
10
- import "./chunk-4BQA7PJ3.js";
11
- import "./chunk-4AP763GX.js";
12
- import "./chunk-3FYJM7LH.js";
13
- import "./chunk-YGQCVPX6.js";
14
- export {
15
- handleAsk
16
- };
@@ -1,14 +0,0 @@
1
- import {
2
- handleSearch
3
- } from "./chunk-G435JWGV.js";
4
- import "./chunk-SLYQ6L52.js";
5
- import "./chunk-L32WSANI.js";
6
- import "./chunk-NHYYMRZC.js";
7
- import "./chunk-ETLSWSZ7.js";
8
- import "./chunk-4BQA7PJ3.js";
9
- import "./chunk-4AP763GX.js";
10
- import "./chunk-3FYJM7LH.js";
11
- import "./chunk-YGQCVPX6.js";
12
- export {
13
- handleSearch
14
- };