@konneal/engine 0.2.187 → 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 (43) hide show
  1. package/dist/ai.d.ts +7 -0
  2. package/dist/ask-LPNODCPM.js +16 -0
  3. package/dist/{chunk-IZ3GSYMD.js → chunk-22WB6IVC.js} +35 -30
  4. package/dist/{chunk-VDFOVWE6.js → chunk-5PKKAHY4.js} +5 -5
  5. package/dist/{chunk-MZQEI4VJ.js → chunk-7YMIUTPY.js} +1 -1
  6. package/dist/{chunk-BAOKHV2D.js → chunk-AVNHVFEB.js} +29 -6
  7. package/dist/{chunk-BMODSEKT.js → chunk-ECNBEZGK.js} +5 -5
  8. package/dist/{chunk-IDQND3AA.js → chunk-FCRTWZQE.js} +128 -31
  9. package/dist/{chunk-TLPUJMAF.js → chunk-GJQT4IMD.js} +1 -1
  10. package/dist/{chunk-YGQCVPX6.js → chunk-H6ZULBW2.js} +4 -1
  11. package/dist/{chunk-RBRBQJYT.js → chunk-Q7QL3457.js} +58 -44
  12. package/dist/config.d.ts +17 -11
  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/nameplate.d.ts +1 -1
  17. package/dist/prompts/understanding.md +2 -1
  18. package/dist/reflect.d.ts +1 -1
  19. package/dist/search-DE5ADCVM.js +14 -0
  20. package/dist/{tools-VMZSXLXM.js → tools-7GKMDWVB.js} +5 -5
  21. package/dist/understandContract.d.ts +3 -0
  22. package/dist/worker_mcp/src/index.js +2 -2
  23. package/dist/worker_public/src/config.js +3 -1
  24. package/dist/worker_public/src/index.js +11 -11
  25. package/dist/worker_public/src/requestScope.js +2 -2
  26. package/package.json +1 -1
  27. package/workers/worker_public/prompts/understanding.md +2 -1
  28. package/workers/worker_public/src/ai.ts +32 -9
  29. package/workers/worker_public/src/ask.ts +90 -23
  30. package/workers/worker_public/src/config.ts +44 -29
  31. package/workers/worker_public/src/context.ts +14 -0
  32. package/workers/worker_public/src/docOverview.ts +77 -0
  33. package/workers/worker_public/src/faithfulness.ts +11 -1
  34. package/workers/worker_public/src/lexical.ts +21 -19
  35. package/workers/worker_public/src/ports/cloudflare/adapters.ts +4 -2
  36. package/workers/worker_public/src/reflect.ts +8 -7
  37. package/workers/worker_public/src/stages/dense.ts +29 -42
  38. package/workers/worker_public/src/stages/glossary.ts +1 -1
  39. package/workers/worker_public/src/stages/rerank.ts +6 -2
  40. package/workers/worker_public/src/understand.ts +6 -6
  41. package/workers/worker_public/src/understandContract.ts +4 -0
  42. package/dist/ask-O7HJIZPK.js +0 -16
  43. package/dist/search-3H2ENWHQ.js +0 -14
@@ -27,7 +27,17 @@ export async function embed(ai: ModelRunner, _model: string, text: string): Prom
27
27
  throw new Error(`embed failed after retries: ${String(lastError)}`);
28
28
  }
29
29
 
30
- import { answerEffort, effortBudget } from "./config.ts";
30
+ import { answerEffort, effortBudget, generationSampling } from "./config.ts";
31
+
32
+ /** The platform's per-minute inference allowance (3021) and its capacity
33
+ * signal (3040) reset with the minute: an immediate retry hits the same
34
+ * wall, so the caller waits before trying again. Measured 2026-12-03 —
35
+ * with every generation role on one model, two parallel question streams
36
+ * exhausted it and half the judging calls failed. */
37
+ export function isCapacityError(e: unknown): boolean {
38
+ return /3021|rate limit|3040|capacity/i.test(String(e));
39
+ }
40
+ export const CAPACITY_PAUSE_MS = 15_000;
31
41
 
32
42
  export async function rerank(
33
43
  ai: AnyAi,
@@ -35,13 +45,26 @@ export async function rerank(
35
45
  query: string,
36
46
  texts: string[],
37
47
  ): Promise<number[] | null> {
38
- // verified REST shape first: contexts are [{text}] objects; the binding
39
- // may instead want plain strings — try both, then the legacy names
40
- // the adapter's shape probing handles provider variants; two
41
- // attempts cover transient capacity errors
48
+ // Workers AI bge-reranker-base rejects the whole batch (400 / 5006) when any
49
+ // context has text length < 1; score only non-empty candidates and leave
50
+ // empty slots NaN so one empty vector never poisons the pool.
51
+ const idx: number[] = [];
52
+ const nonEmpty: string[] = [];
53
+ for (let i = 0; i < texts.length; i++) {
54
+ if (typeof texts[i] === "string" && texts[i].trim().length > 0) {
55
+ idx.push(i);
56
+ nonEmpty.push(texts[i]);
57
+ }
58
+ }
59
+ if (!nonEmpty.length) return null;
42
60
  for (let attempt = 0; attempt < 2; attempt++) {
43
- const scores = await ai.rerank(model, query, texts);
44
- if (scores && scores.some((s) => Number.isFinite(s))) return scores;
61
+ const scores = await ai.rerank(model, query, nonEmpty);
62
+ if (scores && scores.some((s) => Number.isFinite(s))) {
63
+ if (idx.length === texts.length) return scores;
64
+ const out = new Array<number>(texts.length).fill(NaN);
65
+ idx.forEach((orig, k) => { out[orig] = scores[k]; });
66
+ return out;
67
+ }
45
68
  }
46
69
  console.error("rerank failed, using vector order");
47
70
  return null;
@@ -62,8 +85,7 @@ export async function generateOnce(env: any, model: string, messages: any[], eff
62
85
  messages,
63
86
  max_tokens: effortBudget(effort ?? answerEffort(env)),
64
87
  reasoning_effort: effort ?? answerEffort(env),
65
- temperature: 0.6,
66
- top_p: 0.95,
88
+ ...generationSampling(model),
67
89
  }),
68
90
  new Promise<null>((r) => setTimeout(() => r(null), 120_000)),
69
91
  ]);
@@ -79,6 +101,7 @@ export async function generateOnce(env: any, model: string, messages: any[], eff
79
101
  if (attempt === 0) console.error("generate returned empty:", model);
80
102
  } catch (e) {
81
103
  console.error("generate failed:", model, String(e).slice(0, 120));
104
+ if (attempt === 0 && isCapacityError(e)) await delay(CAPACITY_PAUSE_MS);
82
105
  }
83
106
  }
84
107
  return null;
@@ -3,7 +3,7 @@
3
3
  // echo — everything between "request validated" and "response written".
4
4
  // index.ts routes here; this module owns the answer contract.
5
5
 
6
- import { LIMITS, MODELS, THRESHOLDS, num, sha256Hex, roleModel, answerEffort, requestEffort, effortBudget } from "./config";
6
+ import { LIMITS, MODELS, THRESHOLDS, num, sha256Hex, roleModel, answerEffort, requestEffort, effortBudget, generationSampling } from "./config";
7
7
  import { portModelRunner } from "./env.ts";
8
8
  import { refCodec } from "./codecs";
9
9
  import { buildMessages, citations, fill, promptVars, retrieve, retrievalQuery, identityNote, splitHistory, listwiseRerank, refusalAnswer, Hit } from "./pipeline";
@@ -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";
@@ -227,13 +228,13 @@ async function generateStream(env: Env, model: string, messages: any[], effort?:
227
228
  stream: true,
228
229
  max_tokens: effortBudget(effort ?? answerEffort(env)),
229
230
  reasoning_effort: effort ?? answerEffort(env),
230
- temperature: 0.6,
231
- top_p: 0.95,
231
+ ...generationSampling(model),
232
232
  });
233
233
  if (res && typeof res.getReader === "function") return res as ReadableStream<Uint8Array>;
234
234
  if (res && res.body && typeof res.body.getReader === "function") return res.body;
235
235
  } catch (e) {
236
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));
237
238
  }
238
239
  }
239
240
  return null;
@@ -259,13 +260,14 @@ async function summarizeHistory(
259
260
  },
260
261
  { role: "user", content: convo },
261
262
  ],
262
- max_tokens: 2048,
263
+ // reasoning tokens share this budget — DeepSeek-V4 needs 3072+ or
264
+ // the summary is never reached
265
+ max_tokens: model.includes("deepseek") ? 3072 : 2048,
263
266
  reasoning_effort: "low",
267
+ ...generationSampling(model),
264
268
  // Qwen3 thinking-mode sampling (model card) — prevents the
265
269
  // repetition loops that eat the budget before the summary lands
266
- temperature: 0.6,
267
- top_p: 0.95,
268
- top_k: 20,
270
+ ...(model.includes("deepseek") ? {} : { top_k: 20 }),
269
271
  });
270
272
  const text = typeof res?.response === "string" ? res.response : res?.choices?.[0]?.message?.content;
271
273
  return typeof text === "string" && text.trim() ? text.trim().slice(0, 1200) : 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
  }
@@ -1,50 +1,63 @@
1
1
  import { P } from "./profile.ts";
2
2
 
3
+ // Cloudflare deprecated glm-5.3-flash, glm-5.2, qwen3-30b-a3b-fp8,
4
+ // deepseek-v4-flash-0731 and deepseek-v4-pro-0813 on 2026-11-20 (HTTP 410)
5
+ // and every generation role died with them. Owner decision 2026-12-03:
6
+ // deepseek-v4.1-flash-1017 carries the generation roles — natively
7
+ // multimodal, 1M ctx, reasoning none/low/high/max with HIGH as the default,
8
+ // so every call site states its effort explicitly.
9
+ const FLASH = "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
10
+
3
11
  export const MODELS = {
4
12
  embed: "@cf/qwen/qwen3-embedding-0.6b", rerank: "@cf/baai/bge-reranker-base",
5
- // ANSWER MODEL (all tiers, user decision 2026-08-29): glm-5.3-flash —
6
- // natively multimodal (vision-unified contract), GLM family, flash tier.
7
- // Vision image-parts land with answer contract v2; text answers work now.
8
- anon: "@cf/zai-org/glm-5.3-flash",
9
- member: "@cf/zai-org/glm-5.3-flash",
13
+ // ANSWER MODEL (all tiers): natively multimodal (vision-unified contract)
14
+ anon: FLASH,
15
+ member: FLASH,
10
16
  // figure captions + the vision lane (one-time, quality-first; the A/B
11
17
  // lever is CAPTION_MODEL, the per-request arm is the admin route's
12
- // body.model)
13
- caption: "@cf/zai-org/glm-5.3-flash",
14
- // the pairwise vision judge (sees the image; a THIRD model never
15
- // judges its own arm)
16
- visionJudge: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
17
- // the VLM figure rerank (TODO.sota/18.3): the newly-landed
18
- // vision-capable MoE scores figure IMAGES against figure-seeking
19
- // questions — one bounded call per figure question, ablatable stage
20
- vlmFigure: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
18
+ // body.model). It emptied on 8/24 figure images in the 2026-10-27 A/B —
19
+ // those captions fall to the serve-raw path.
20
+ caption: FLASH,
21
+ // the pairwise vision judge (sees the image; a THIRD model never judges
22
+ // its own arm) — no other live multimodal model exists in the policy
23
+ // line, so a v4.1 caption arm is judged by its own family
24
+ visionJudge: FLASH,
25
+ // the VLM figure rerank (TODO.sota/18.3): a vision-capable MoE scores
26
+ // figure IMAGES against figure-seeking questions — one bounded call per
27
+ // figure question, ablatable stage
28
+ vlmFigure: FLASH,
21
29
  // the decision pass (TODO.decisions/01): clef-flash gates the
22
30
  // requirement-shaped questions, clef decides the derived checklist
23
31
  decisionsGate: "@cf/cloudflare/clef-flash",
24
32
  decisionsModel: "@cf/cloudflare/clef",
25
- // hot-path understanding/summarize stays on the cheap Qwen (cost-first lane)
26
- understand: "@cf/qwen/qwen3-30b-a3b-fp8",
33
+ // hot-path understanding/summarize (cost-first lane)
34
+ understand: FLASH,
27
35
  // the api_call act's intent-to-act mapping (TODO.ai-platform/09) — the
28
36
  // operations deployment points ACTS_MODEL at the stronger reasoning
29
37
  // tier; the floor is the understand lane
30
- acts: "@cf/qwen/qwen3-30b-a3b-fp8",
31
- // generation fallback when the answer model is unavailable
32
- fallback: "@cf/qwen/qwen3-30b-a3b-fp8",
33
- grader: "@cf/deepseek-ai/deepseek-v4-flash-0731", // CRAG grader + judges (unsuffixed slug was retired → silent 5018s)
38
+ acts: 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",
46
+ grader: FLASH, // CRAG grader + judges
34
47
  // contextual enrichment is the QUALITY-FIRST lane (one-time spend over
35
48
  // the corpus, its quality persists into every future retrieval)
36
- enrich: "@cf/deepseek-ai/deepseek-v4-pro-0813",
49
+ enrich: "@cf/zai-org/glm-5.3",
37
50
  // final-tier listwise reranker for hard/member queries (cascade:
38
51
  // cross-encoder prunes, listwise orders jointly)
39
52
  listwise: "@cf/zai-org/glm-4.7-flash",
40
53
  // deep-research loop (G10): bounded agentic iterations, members-only
41
- escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
42
- research: "@cf/zai-org/glm-5.3-flash",
54
+ escalation: FLASH,
55
+ research: FLASH,
43
56
  // speculative draft-verify (TODO.sota/02 row 2): the strong verifier
44
57
  // over the cheap drafts — the research-tier model verifies; the drafter
45
58
  // is the standard answer model (MODELS.member). VERIFIER_MODEL swaps it
46
59
  // live, same lever as every role.
47
- verifier: "@cf/zai-org/glm-5.2",
60
+ verifier: "@cf/zai-org/glm-5.3",
48
61
  } as const;
49
62
 
50
63
  export const LIMITS = {
@@ -97,11 +110,6 @@ export const THRESHOLDS = {
97
110
  // the extractive compression arm (TODO.sota/02 row 5): when ablated
98
111
  // on, each passage body is compressed to this share of its budget
99
112
  compressShare: 0.6,
100
- // the dense scope's starvation fallback (the R 134-2 figure question):
101
- // when the in-code doc scope cuts the vector-level top-K to zero, the
102
- // re-query runs at this depth and scopes in code (the native filter is
103
- // dead — measured 2026-10-05)
104
- denseStarveK: 100,
105
113
  // the decision pass (TODO.decisions): the gate fires at decisionsGateMin
106
114
  // noul; the bands assemble met / not clearly stated / not met
107
115
  decisionsGateMin: 0.5,
@@ -224,6 +232,13 @@ export function effortBudget(effort: string): number {
224
232
  return LIMITS.maxOutputTokens;
225
233
  }
226
234
 
235
+ /** Sampling follows the model's card (the 2026-08-30/31 incidents): the
236
+ * DeepSeek-V4 family degrades under tight sampling (temp 1.0 / top_p 1.0);
237
+ * GLM and Qwen thinking modes take 0.6 / 0.95. */
238
+ export function generationSampling(model: string): { temperature: number; top_p: number } {
239
+ return model.includes("deepseek") ? { temperature: 1.0, top_p: 1.0 } : { temperature: 0.6, top_p: 0.95 };
240
+ }
241
+
227
242
  export function requestEffort(env: any, session: unknown, requested: unknown): string {
228
243
  if (typeof requested !== "string" || !EFFORTS.has(requested)) return answerEffort(env);
229
244
  if (requested === "low") return requested;
@@ -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]*\}/);