@konneal/engine 0.2.188 → 0.2.190

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-6SWT3KSC.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-NHYYMRZC.js → chunk-GJQT4IMD.js} +1 -1
  9. package/dist/{chunk-YGQCVPX6.js → chunk-H6ZULBW2.js} +4 -1
  10. package/dist/{chunk-SLYQ6L52.js → chunk-Q7QL3457.js} +52 -38
  11. package/dist/{chunk-A2HQNENL.js → chunk-WRSUXIS7.js} +139 -28
  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/operations.d.ts +34 -0
  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-CYSL26HX.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 +1 -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 +30 -6
  29. package/workers/worker_public/src/ask.ts +118 -21
  30. package/workers/worker_public/src/config.ts +7 -9
  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/operations.ts +40 -0
  36. package/workers/worker_public/src/ports/cloudflare/adapters.ts +4 -2
  37. package/workers/worker_public/src/reflect.ts +8 -7
  38. package/workers/worker_public/src/stages/dense.ts +29 -42
  39. package/workers/worker_public/src/stages/glossary.ts +1 -1
  40. package/workers/worker_public/src/stages/rerank.ts +6 -2
  41. package/workers/worker_public/src/understandContract.ts +4 -0
  42. package/dist/ask-TJK7DQ45.js +0 -16
  43. package/dist/search-FJAOGMEO.js +0 -14
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  "playwright": "^1.62.1",
28
28
  "yaml": "^2.9.1"
29
29
  },
30
- "version": "0.2.188",
30
+ "version": "0.2.190",
31
31
  "description": "The Konneal engine: the publisher-agnostic build pipeline and API plane for standards intelligence (retrieval, answer contract, verdicts, evaluation).",
32
32
  "license": "BSD-3-Clause",
33
33
  "type": "module",
@@ -1,11 +1,12 @@
1
1
  You normalize a user question for a retrieval system over {{CORPUS_KIND_PLURAL}} (English corpus).
2
2
  Reply with ONLY a JSON object, no prose, no markdown fence:
3
- {"intent": "knowledge", "docidentifier": "{{DOCID_EXAMPLE}}" | null, "docnumber": "76" | null, "edition": "2021" | null, "language": "en" | null, "process_intent": true | false, "term": "accuracy class" | null, "defined_terms": [], "standalone_query": "...", "complexity": "simple", "query_variants": [], "sub_queries": [], "hypothetical_answer": "...", "follow_ups": []}
3
+ {"intent": "knowledge", "docidentifier": "{{DOCID_EXAMPLE}}" | null, "docnumber": "76" | null, "edition": "2021" | null, "language": "en" | null, "process_intent": true | false, "doc_overview": true | false, "term": "accuracy class" | null, "defined_terms": [], "standalone_query": "...", "complexity": "simple", "query_variants": [], "sub_queries": [], "hypothetical_answer": "...", "follow_ups": []}
4
4
  Rules:
5
5
  - intent: "conversational" ONLY when the latest message is about the assistant or this service itself (who you are, which model you are, what you can do, how you work) or is a pure social nicety (greeting, thanks, farewell, small talk) — e.g. "hi!", "who are you?", "what can you do?", "merci !", "was kannst du?". ANY question about a subject — legal metrology, other technical fields, cooking, sports, current events, ANYTHING — is "knowledge", even when the corpus cannot answer it; do NOT use "conversational" to mean off-topic.
6
6
  - docidentifier: the publication the user names, in any spelling ({{SPELLING_EXAMPLES}}, "the nonautomatic weighing instruments recommendation" → resolve to the {{PUBLISHER_NAME}} identifier you can infer; include the part ("-1", "-2") only when clearly meant). docnumber is the base number without part.
7
7
  - edition: only when the user pins a year.
8
8
  - language: only when the user asks for a specific answer language; otherwise null (the corpus is English; answering in the user's language is handled elsewhere).
9
+ - doc_overview: true ONLY when the question asks what the NAMED publication is or covers as a whole — an overview, purpose, scope or summary of the document itself ("what is R 60", "describe OIML D 11", "give me an overview of R 76-1") — and docidentifier is set. false for anything inside it (a requirement, value, term, test, table or citation question: "what is the MPE in R 76-1" → false), and false when no publication is named.
9
10
  - citation questions ("what does X cite/reference/list?", "which standards does X reference?"): ALWAYS include a query variant that names the document's bibliography or normative-references section explicitly, WITHOUT edition scoping (e.g. for "What ISO standards does R 60 cite?" generate BOTH "R 60 bibliography normative references" AND "R 60 2017 bibliography ISO IEC") — bibliographies embed differently than the query's phrasing, and prior editions may carry references the current edition dropped; set edition to null for these queries so retrieval covers the whole family.
10
11
  - process_intent: true when the question is about the GOVERNING SYSTEM around publications rather than a publication's own technical content — HOW to get certified/apply/comply, OR which framework/vocabulary/{{PROCESS_VOCAB}}. Naming a Recommendation (e.g. "R 60") inside such a question does NOT make it a technical-content question: leave process_intent true and still emit docnumber when named, but the retrieval path must NOT seal to that document alone.
11
12
  - term: the defined term when the question asks what something is ("what is an accuracy class" → "accuracy class"); otherwise null.
@@ -29,19 +29,42 @@ export async function embed(ai: ModelRunner, _model: string, text: string): Prom
29
29
 
30
30
  import { answerEffort, effortBudget, generationSampling } from "./config.ts";
31
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;
41
+
32
42
  export async function rerank(
33
43
  ai: AnyAi,
34
44
  model: string,
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;
@@ -78,6 +101,7 @@ export async function generateOnce(env: any, model: string, messages: any[], eff
78
101
  if (attempt === 0) console.error("generate returned empty:", model);
79
102
  } catch (e) {
80
103
  console.error("generate failed:", model, String(e).slice(0, 120));
104
+ if (attempt === 0 && isCapacityError(e)) await delay(CAPACITY_PAUSE_MS);
81
105
  }
82
106
  }
83
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, generationSampling } from "./config";
6
+ import { LIMITS, MODELS, THRESHOLDS, num, sha256Hex, roleModel, answerEffort, requestEffort, effortBudget, generationSampling, DATASETS } 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";
@@ -52,7 +53,7 @@ import { assembleDocument, verifyAnchors, escalationAllowed, chargeEscalation, e
52
53
  import { ESCALATION_DAILY_DEFAULT } from "./config";
53
54
  import { cfModelRunner, cfStore, cfVectorIndex } from "./ports/cloudflare/adapters";
54
55
  import { TOOL_DECLARATION, parseToolCall, runTool, toolNote } from "./tools";
55
- import { operationsLane } from "./operations.ts";
56
+ import { operationsLane, platformCorporaOf, platformKnowledgeQuestion, type OperationsLane } from "./operations.ts";
56
57
  import { extractNameplate, nameplateRegisterQuery } from "./nameplate.ts";
57
58
  import { P } from "./profile.ts";
58
59
  import { toolNarration, intentPreamble, TOOL_NARRATION_NOTICE, INTENT_PREAMBLE_NOTICE } from "./answerGuards.ts";
@@ -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;
@@ -724,7 +726,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
724
726
  // refusal) — gating on usedHits left every refusal "cited" and the
725
727
  // wall dark through three deploys (2026-10-11)
726
728
  const answerCites = (t: string) => /\[[^\]]+\]/.test(t);
727
- const refusalScope = (cited: boolean) => ({ cited, conversational: understanding?.intent === "conversational" });
729
+ const refusalScope = (cited: boolean) => ({ cited, conversational: understanding?.intent === "conversational" && !platformQuestion.knowledge });
728
730
  // a query naming a model node (/req/…, /term/…) is node-SCOPED: its
729
731
  // ── Option C: optimistic parallel retrieval ──
730
732
  // The dense lane (folded-query embed + unfiltered Vectorize query) runs
@@ -930,7 +932,17 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
930
932
  }
931
933
  const regNote = aggregateNoteText
932
934
  ?? (register ? [registerNote(register.rows), certificateLinks(register.rows)].filter(Boolean).join("\n") : undefined);
933
- const ops = await operationsLane(env.DB, q.query);
935
+ // The operations catalog lane belongs to a deployment that serves the
936
+ // API plane: it runs only where the profile's datasets name a platform
937
+ // corpus (the operations origin). The same engine serves the public
938
+ // origin, whose datasets name none — there the lane's AUTHORITATIVE
939
+ // note and its citable operation passages must never enter the prompt
940
+ // (observed 2026-12-04, the moment the lane's rows returned to D1: the
941
+ // public origin began answering platform-operation questions).
942
+ const platformCorpora = platformCorporaOf(DATASETS());
943
+ const ops = platformCorpora.length
944
+ ? await operationsLane(env.DB, q.query)
945
+ : { matched: [] as OperationsLane["matched"] };
934
946
  // The register lane owns the answer surface when it holds rows — the
935
947
  // aggregate path's philosophy (the note answers the structure, the
936
948
  // model narrates) extended to the standing lane. Measured 2026-10-28:
@@ -951,13 +963,33 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
951
963
  ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }]
952
964
  : [];
953
965
 
966
+ // A platform-knowledge question the understanding step filed as
967
+ // "conversational" takes the knowledge route instead (./operations
968
+ // platformKnowledgeQuestion): on the operations origin the assistant's
969
+ // identity is "you answer questions about the platform's API
970
+ // operations", so a question about the PLATFORM reads to the
971
+ // classifier as one about the SERVICE — measured 2026-12-04: the
972
+ // deploy smoke's "Which platform operation updates an entity record?"
973
+ // classified conversational in 5 of 12 draws and answered 1/6 from
974
+ // the identity prompt, no retrieval. The deterministic operations
975
+ // lane matching an operation BY NAME is the evidence the indexed
976
+ // material answers it; the matched operation rides the pool as a
977
+ // citable passage either way. Everything else keeps the classifier's
978
+ // verdict — this is a narrow yield, not a second classifier.
979
+ const platformQuestion = understanding?.intent === "conversational"
980
+ ? platformKnowledgeQuestion(q.query, ops, [], DATASETS())
981
+ : { knowledge: false, corpora: platformCorpora };
982
+ // the refusal scope and the read echo report the route the turn
983
+ // actually took
984
+ const conversational = understanding?.intent === "conversational" && !platformQuestion.knowledge;
985
+
954
986
  // Conversational route, decided by query UNDERSTANDING (any language, any
955
987
  // phrasing) — not string matching. No retrieval: nothing in the corpus
956
988
  // answers "who are you". The model speaks for itself from the service
957
989
  // facts in identityNote (composed from the DATASETS catalog). A declared
958
990
  // context is honestly NOT applied here (nothing grounds a conversational
959
991
  // turn) — the echo reports none.
960
- if (understanding?.intent === "conversational") {
992
+ if (conversational) {
961
993
  const queryHash = await sha256Hex(q.query);
962
994
  const messages = [
963
995
  { role: "system", content: identityNote(!!member) },
@@ -1450,7 +1482,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1450
1482
  if (grade === "weak" && understanding?.docidentifier) {
1451
1483
  const broaden = `${understanding.standalone_query || q.query} ${understanding.docidentifier}`.trim();
1452
1484
  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 } : {}) });
1485
+ 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
1486
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q.query, second.hits.map((h: Hit) => h.text));
1455
1487
  stageTiming.corrective = Date.now() - tc;
1456
1488
  if (grade2 === "good") retrieved = second; // corrective retry must be strictly better
@@ -1560,13 +1592,14 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1560
1592
  const passagePool = registerOwns
1561
1593
  ? [...opsHits, ...hits].filter((h) => !!(h.metadata as any).cert_holder)
1562
1594
  : [...opsHits, ...hits];
1595
+ const baseNotes = [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote];
1596
+ const promptNotes = [...baseNotes, ...(retrieved.notes ?? [])].filter(Boolean).join("\n") || undefined;
1563
1597
  const built = buildMessages(
1564
1598
  q.query,
1565
1599
  passagePool,
1566
1600
  q.lang,
1567
1601
  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,
1602
+ promptNotes,
1570
1603
  summary,
1571
1604
  budget,
1572
1605
  ablate?.noCompress !== true,
@@ -1820,6 +1853,36 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1820
1853
  } catch { /* deliver what we have */ }
1821
1854
  }
1822
1855
  }
1856
+ // the document lane's twin of the guard above (./docOverview):
1857
+ // the question asks what the named document is and that
1858
+ // document's own passages were in the prompt — one bounded
1859
+ // regeneration; the tokens already sent are replaced through
1860
+ // the retry sentinel, and a regeneration that yields nothing
1861
+ // leaves the refusal in place rather than a blank answer
1862
+ if (!escalateAnswer && docOverviewRefusal({ answer: full, refusal: refusalAnswer(), understanding, used: usedHits })) {
1863
+ console.log("blind-answer(doc, stream): the named document's passages were in the prompt but the answer refused — regenerating once");
1864
+ streamRestarts += 1;
1865
+ mark("Re-answering from the document's passages");
1866
+ send({ type: "retry" });
1867
+ const regen = await generateStream(env, model, [
1868
+ ...messages.slice(0, -1),
1869
+ { role: "user", content: docOverviewInstruction(understanding!.docidentifier ?? understanding!.doc_number!) },
1870
+ messages[messages.length - 1],
1871
+ ], routeEffort(routed.route));
1872
+ if (regen) {
1873
+ let replaced = false;
1874
+ try {
1875
+ for await (const tok of sseTokens(regen)) {
1876
+ if (!replaced) {
1877
+ full = "";
1878
+ replaced = true;
1879
+ }
1880
+ full += tok;
1881
+ send({ type: "token", v: tok });
1882
+ }
1883
+ } catch { /* deliver what we have */ }
1884
+ }
1885
+ }
1823
1886
  // the misplaced-pin wall rides the streamed path too: a
1824
1887
  // CITED stream is not a refusal
1825
1888
  // the escalation's citation contract (TODO.sota/21): every
@@ -2032,6 +2095,30 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2032
2095
  // (measured on chip-scoped asks: correct cited answers carrying the
2033
2096
  // pin mid-text, read by users and graders as total refusals)
2034
2097
  if (answer) answer = exciseMisplacedPin(answer!, answerCites(answer!));
2098
+ // the document lane's blind-answer guard (2026-12-03, ./docOverview):
2099
+ // the question asks what the named document is, that document's own
2100
+ // passages were in the prompt, and the answer is still the refusal —
2101
+ // the refusal habit the register guard further down regenerates. One
2102
+ // bounded regeneration here, BEFORE the contract checks, so the new
2103
+ // answer passes through them like a first draft. A specific
2104
+ // requirement the passages lack is not an overview question: its
2105
+ // honest refusal stands. An escalation's refusal is its own verdict.
2106
+ if (answer && !escalateAnswer && docOverviewRefusal({ answer: answer!, refusal: refusalAnswer(), understanding, used: usedHits })) {
2107
+ console.log("blind-answer(doc): the named document's passages were in the prompt but the answer refused — regenerating once");
2108
+ generateRetries += 1;
2109
+ const regen = await generateOnce(env, model, [
2110
+ ...messages.slice(0, -1),
2111
+ { role: "user", content: docOverviewInstruction(understanding!.docidentifier ?? understanding!.doc_number!) },
2112
+ messages[messages.length - 1],
2113
+ ], routeEffort(routed.route));
2114
+ if (regen) {
2115
+ const grounded = exciseMisplacedPin(canonicalRefusal(scrubToolLines(regen), refusalScope(answerCites(regen))), answerCites(regen));
2116
+ if (!grounded.includes(refusalAnswer())) {
2117
+ answer = grounded;
2118
+ console.log("blind-answer(doc): regeneration grounded");
2119
+ }
2120
+ }
2121
+ }
2035
2122
  // the tool-narration leak (2026-10-14, the R 134-1 probe): the answer
2036
2123
  // model sometimes NARRATES the agent loop's call in prose — 'The
2037
2124
  // db.find tool returned, for the query "…": {…json…}' — instead of
@@ -2101,31 +2188,41 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2101
2188
  }
2102
2189
 
2103
2190
  // ── 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));
2191
+ // Skipped when the answer drew on an assembled full document or the register
2192
+ // lane (their evidence is not in the passage window). Retries forward the
2193
+ // full retrieval scope and authoritative notes, and never replace an already-
2194
+ // answered turn with a refusal.
2195
+ if (answer && !escalateAnswer && !registerOwns && !answer!.includes(refusalAnswer())) {
2196
+ const reflection = await reflect(env.AI, roleModel(env, "grader"), q.query, answer!, used.map((h: Hit) => h.text), promptNotes);
2109
2197
  console.log("reflection:", reflection ? (reflection!.grounded ? "grounded" : "ungrounded") : "null");
2110
2198
  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
2199
  const retryRetrieve = await retrieve(env, q.query, {
2115
2200
  prev,
2116
2201
  understanding: { ...understanding, standalone_query: `${understanding?.standalone_query || q.query} ${reflection!.missing_info}` } as any,
2202
+ federate,
2203
+ userDocs,
2117
2204
  sealScope: declaredScoped ? docScope : null,
2118
2205
  datasetScope: narrowed ? corpora : null,
2119
2206
  standardKeys,
2207
+ lexicalBoost,
2208
+ licensedDocNumbers,
2120
2209
  ...(routeSubset ? { stageSubset: routeSubset ?? undefined } : {}),
2121
2210
  });
2122
2211
  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);
2212
+ const retryNotes = [...baseNotes, ...(retryRetrieve.notes ?? [])].filter(Boolean).join("\n") || undefined;
2213
+ const { messages: retryMessages, usedHits: retryUsed } = buildMessages(q.query, retryRetrieve.hits, q.lang, keptHistory, retryNotes, summary, budget, ablate?.noCompress !== true);
2124
2214
  const retryAnswer = await generateOnce(env, model, retryMessages, routeEffort(routed.route));
2125
- // the answer now comes from the retry passages — citations must follow
2126
2215
  if (retryAnswer) {
2127
- answer = canonicalRefusal(retryAnswer!, refusalScope(answerCites(retryAnswer!)));
2128
- used = retryUsed;
2216
+ const retryCanonical = exciseMisplacedPin(
2217
+ canonicalRefusal(scrubToolLines(retryAnswer!), refusalScope(answerCites(retryAnswer!))),
2218
+ answerCites(retryAnswer!),
2219
+ );
2220
+ if (!retryCanonical.includes(refusalAnswer())) {
2221
+ answer = retryCanonical;
2222
+ used = retryUsed;
2223
+ } else {
2224
+ console.log("reflection: retry refused — keeping initial answer");
2225
+ }
2129
2226
  }
2130
2227
  }
2131
2228
  }
@@ -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
@@ -38,6 +38,46 @@ export function anchorWords(anchor: string): string[] {
38
38
 
39
39
  const singular = (w: string) => (w.length > 3 && w.endsWith("s") ? w.slice(0, -1) : w);
40
40
 
41
+ /** The platform-source corpora a deployment serves — the ones its
42
+ * datasets name (the API plane, the guides). The operations lane and
43
+ * the conversational yield both key on this: the SAME engine serves the
44
+ * public origin, whose datasets name no platform corpus. */
45
+ export function platformCorporaOf(datasets: readonly { corpora?: readonly string[] }[]): string[] {
46
+ return datasets.filter((d) => (d.corpora ?? []).some((c) => /^smart-(ops|guides)$/.test(c))).flatMap((d) => [...(d.corpora ?? [])]);
47
+ }
48
+
49
+ /** A platform-knowledge question the understanding step filed as
50
+ * "conversational". On the operations origin the assistant's own
51
+ * identity is "you answer questions about the platform's API
52
+ * operations", so a question about the PLATFORM reads to the
53
+ * classifier as a question about the SERVICE — measured 2026-12-04:
54
+ * "Which platform operation updates an entity record?" came back
55
+ * intent=conversational in 5 of 12 draws and the turn answered from
56
+ * the identity prompt, no retrieval. The subject decides: the
57
+ * deterministic operations lane matched an operation by name, or the
58
+ * retrieval pool holds a passage from a platform-source corpus — the
59
+ * indexed material answers it, so it is a knowledge question. Only the
60
+ * operations lane's own NAME match counts (a verb-only match is the
61
+ * lane's documented noise), and a service that indexes no platform
62
+ * source never re-routes. Pure service questions ("who are you?",
63
+ * "what can you do?") match no operation by name and hold no platform
64
+ * passage — they stay conversational. */
65
+ export function platformKnowledgeQuestion(
66
+ query: string,
67
+ ops: Pick<OperationsLane, "matched">,
68
+ pool: readonly { metadata?: { corpus?: string } }[] = [],
69
+ datasets: readonly { corpora?: readonly string[]; session?: boolean }[] = [],
70
+ ): { knowledge: boolean; corpora: string[] } {
71
+ const platformCorpora = platformCorporaOf(datasets);
72
+ if (!platformCorpora.length) return { knowledge: false, corpora: platformCorpora };
73
+ // an explicit operation question needs the lane's name match; a
74
+ // pool-derived re-route needs a platform passage actually in it
75
+ const objects = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP_WORDS.has(w)).map(singular);
76
+ const byName = isOperationIntent(query) && ops.matched.some((m) => anchorWords(m.anchor).map(singular).some((w) => objects.includes(w)));
77
+ const inPool = pool.some((h) => platformCorpora.includes(String(h.metadata?.corpus ?? "")));
78
+ return { knowledge: byName || inPool, corpora: platformCorpora };
79
+ }
80
+
41
81
  export function matchOperations(query: string, rows: { anchor: string; text: string; docidentifier?: string }[]): { anchor: string; text: string; docidentifier?: string }[] {
42
82
  const q = query.toLowerCase();
43
83
  const stems = ACTION_STEMS.filter((s) => q.includes(s));
@@ -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> {