@konneal/engine 0.2.189 → 0.2.191

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.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  handleAsk
3
- } from "./chunk-FCRTWZQE.js";
3
+ } from "./chunk-SWCKO4OB.js";
4
4
  import "./chunk-IRCDOFP4.js";
5
5
  import "./chunk-ECNBEZGK.js";
6
- import "./chunk-Q7QL3457.js";
6
+ import "./chunk-3SGGVZZ4.js";
7
7
  import "./chunk-AVNHVFEB.js";
8
8
  import "./chunk-GJQT4IMD.js";
9
9
  import "./chunk-ETLSWSZ7.js";
@@ -14,6 +14,7 @@ import {
14
14
  generationSampling,
15
15
  num,
16
16
  processExpansion,
17
+ roleModel,
17
18
  sha256Hex,
18
19
  today
19
20
  } from "./chunk-22WB6IVC.js";
@@ -23007,7 +23008,7 @@ Which of these figures best answers the question? Reply with ONLY: {"pick": N} u
23007
23008
  }
23008
23009
  if (!kept.length) return;
23009
23010
  const raced = await Promise.race([
23010
- portModelRunner(c.env).run({ model: MODELS.vlmFigure, messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
23011
+ portModelRunner(c.env).run({ model: roleModel(c.env, "vlmFigure"), messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
23011
23012
  new Promise((r) => setTimeout(() => r(null), 15e3))
23012
23013
  ]);
23013
23014
  const pick = parsePick(raced?.text ?? raced, kept.length);
@@ -23375,7 +23376,7 @@ var typedPin = {
23375
23376
  return new Set(pinFamily ? [pinFamily.split("-")[0]] : [...glossaryFamilies]).size > 0;
23376
23377
  },
23377
23378
  run: async (c) => {
23378
- const { query, filters, u, glossary: glossary2, hits, env, vector } = c;
23379
+ const { query, filters, u, glossary: glossary2, hits, env } = c;
23379
23380
  const glossaryFamilies = /* @__PURE__ */ new Set();
23380
23381
  for (const g of glossary2) if (g.doc_number) glossaryFamilies.add(g.doc_number.split("-")[0]);
23381
23382
  const pinFamily = filters?.doc_number ?? u?.doc_number ?? null;
@@ -23400,16 +23401,20 @@ var typedPin = {
23400
23401
  const parentPresent = c.finalHits.some(
23401
23402
  (h) => h.metadata.doc_id === docId && h.metadata.clause_anchor === anchor && !h.metadata.unit_id
23402
23403
  );
23403
- if (anchor && docId && !parentPresent) {
23404
+ if (anchor && docId && !parentPresent && env.DB) {
23404
23405
  try {
23405
- const pv = await env.VECTORIZE.query(vector, {
23406
- topK: 4,
23407
- returnMetadata: "all",
23408
- filter: { $and: [{ doc_id: { $eq: docId } }, { clause_anchor: { $eq: anchor } }] }
23409
- });
23410
- const parent = (pv.matches ?? []).map((m) => ({ id: m.id, score: m.score, metadata: m.metadata, text: m.metadata?.chunk_text ?? "" })).find((h) => !h.metadata?.unit_id);
23411
- if (parent && !c.finalHits.some((h) => h.id === parent.id)) {
23412
- c.finalHits = [...c.finalHits, { ...parent, score: parent.score * THRESHOLDS.smallToBigDiscount }];
23406
+ const res = await env.DB.prepare(
23407
+ "SELECT id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2"
23408
+ ).bind(docId, anchor).all();
23409
+ const row = (res.results ?? [])[0];
23410
+ if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
23411
+ const parent = {
23412
+ id: String(row.id),
23413
+ score: typed.score * THRESHOLDS.smallToBigDiscount,
23414
+ metadata: { ...row, unit_id: void 0, block: row.block || void 0 },
23415
+ text: String(row.text ?? "")
23416
+ };
23417
+ c.finalHits = [...c.finalHits, parent];
23413
23418
  console.log("small-to-big: parent \xA7", anchor, "of", typed.metadata.docidentifier, "added");
23414
23419
  }
23415
23420
  } catch {
@@ -23486,23 +23491,9 @@ var sectionDescent = {
23486
23491
  return;
23487
23492
  }
23488
23493
  const kids = sectionHit.metadata.child_anchors.split(",").map((s8) => s8.trim()).filter(Boolean).slice(0, 25);
23489
- if (kids.length) {
23490
- const cv = await c.env.VECTORIZE.query(c.vector, {
23491
- topK: 3,
23492
- returnMetadata: "all",
23493
- filter: {
23494
- $and: [
23495
- { doc_id: { $eq: sectionHit.metadata.doc_id } },
23496
- { clause_anchor: { $in: kids } }
23497
- ]
23498
- }
23499
- });
23500
- const childHits = (cv.matches ?? []).filter((m) => !m.metadata?.section_summary).map((m) => ({
23501
- id: m.id,
23502
- score: m.score * THRESHOLDS.sectionDescentDiscount,
23503
- metadata: m.metadata,
23504
- text: m.metadata?.chunk_text ?? ""
23505
- })).filter((x) => !c.finalHits.some((h) => h.id === x.id)).slice(0, 2);
23494
+ if (kids.length && c.env.DB) {
23495
+ const order = new Map(kids.map((a, i) => [a, i]));
23496
+ const childHits = (await clausesOf(c.env, String(sectionHit.metadata.doc_id), kids, 6)).filter((x) => !x.metadata?.section_summary && !c.finalHits.some((h) => h.id === x.id)).sort((a, b) => (order.get(String(a.metadata.clause_anchor ?? "")) ?? 99) - (order.get(String(b.metadata.clause_anchor ?? "")) ?? 99)).slice(0, 2).map((x) => ({ ...x, score: sectionHit.score * THRESHOLDS.sectionDescentDiscount }));
23506
23497
  if (childHits.length) {
23507
23498
  c.finalHits = [...c.finalHits.filter((h) => h !== sectionHit), ...childHits];
23508
23499
  console.log(
@@ -24886,7 +24877,11 @@ async function understandQuery(ai, model, query, history, entities = []) {
24886
24877
  async function kvIncr(cache, key, step = 1) {
24887
24878
  const cur = Number(await cache.get(key) ?? "0");
24888
24879
  const next = cur + step;
24889
- await cache.put(key, String(next), { expirationTtl: 9e4 });
24880
+ try {
24881
+ await cache.put(key, String(next), { expirationTtl: 9e4 });
24882
+ } catch (e) {
24883
+ console.error("kvIncr: put failed \u2014", String(e).slice(0, 120));
24884
+ }
24890
24885
  return next;
24891
24886
  }
24892
24887
  function clientIp(req) {
@@ -6,7 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-Q7QL3457.js";
9
+ } from "./chunk-3SGGVZZ4.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
@@ -22,6 +22,7 @@ import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
+ roleModel,
25
26
  sha256Hex
26
27
  } from "./chunk-22WB6IVC.js";
27
28
  import {
@@ -40,7 +41,7 @@ async function handleSearch(env, ctx, req, tier, key) {
40
41
  if (!quota.ok) {
41
42
  return err(429, "quota_exceeded", `Daily search limit reached (${quota.limit}). Try again tomorrow.`);
42
43
  }
43
- const understanding = await understandQuery(portModelRunner(env), MODELS.understand, q.query, []);
44
+ const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, []);
44
45
  const graphDocNumbers = await graphExpand(env, understanding);
45
46
  const standardKeys = entitlementScope(standardKeysFrom(body));
46
47
  let retrieved;
@@ -77,7 +77,7 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-Q7QL3457.js";
80
+ } from "./chunk-3SGGVZZ4.js";
81
81
  import {
82
82
  CAPACITY_PAUSE_MS,
83
83
  embed,
@@ -105,6 +105,7 @@ import {
105
105
  standardKeysFrom
106
106
  } from "./chunk-7YMIUTPY.js";
107
107
  import {
108
+ DATASETS,
108
109
  ESCALATION_DAILY_DEFAULT,
109
110
  LIMITS,
110
111
  MODELS,
@@ -1621,7 +1622,7 @@ async function runDecisionPass(env, opts) {
1621
1622
  const passages = opts.passages.filter(Boolean).slice(0, 8).map((p) => p.slice(0, 1600));
1622
1623
  if (!passages.length) return null;
1623
1624
  try {
1624
- const deriveModel = env.DECISIONS_EXTRACT_MODEL || MODELS.member;
1625
+ const deriveModel = env.DECISIONS_EXTRACT_MODEL || roleModel(env, "member");
1625
1626
  const derived = await portModelRunner(env).run({
1626
1627
  model: deriveModel,
1627
1628
  messages: [
@@ -1792,13 +1793,13 @@ async function processImport(ports, row, mime, bytes) {
1792
1793
  return;
1793
1794
  }
1794
1795
  } else {
1795
- text = await visionTranscribe(ports.model, mime, bytes);
1796
+ text = await visionTranscribe(ports.model, mime, bytes, ports.answerModel ?? MODELS.member);
1796
1797
  if (!text || text.replace(/\s+/g, "").length < 20) {
1797
1798
  await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
1798
1799
  return;
1799
1800
  }
1800
1801
  }
1801
- const extraction = await structureDocument(ports.model, row.name, mime, text);
1802
+ const extraction = await structureDocument(ports.model, row.name, mime, text, ports.answerModel ?? MODELS.member);
1802
1803
  const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
1803
1804
  const chunkText = `Member document (${extraction.kind}) \u2014 ${row.name}. ${fieldsLine}. ${extraction.summary}
1804
1805
 
@@ -1836,13 +1837,13 @@ ${extraction.text.slice(0, 8e3)}`;
1836
1837
  function extractKind(fields) {
1837
1838
  return fields.kind || "other";
1838
1839
  }
1839
- async function visionTranscribe(model, mime, bytes) {
1840
+ async function visionTranscribe(model, mime, bytes, modelId) {
1840
1841
  let binary = "";
1841
1842
  const CHUNK = 32768;
1842
1843
  for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1843
1844
  const dataUrl = `data:${mime};base64,${btoa(binary)}`;
1844
1845
  const res = await model.run({
1845
- model: MODELS.member,
1846
+ model: modelId,
1846
1847
  messages: [
1847
1848
  { role: "system", content: "Transcribe everything you can read in this document image \u2014 certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
1848
1849
  { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }
@@ -1853,9 +1854,9 @@ async function visionTranscribe(model, mime, bytes) {
1853
1854
  });
1854
1855
  return res.text ?? "";
1855
1856
  }
1856
- async function structureDocument(model, name, mime, text) {
1857
+ async function structureDocument(model, name, mime, text, modelId) {
1857
1858
  const res = await model.run({
1858
- model: MODELS.member,
1859
+ model: modelId,
1859
1860
  messages: [
1860
1861
  { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {\u2026short typed fields\u2026}, "summary": "one paragraph a retrieval engine can answer from"}. Certificates carry certificate numbers (like R60/2021-XX1-24.01), holders, models, issue dates. Test reports carry measured values, uncertainties, instruments, clause references. Fields use snake_case names, values verbatim from the text. Never invent a value the text does not carry.` },
1861
1862
  { role: "user", content: `Document name: ${name}
@@ -2077,6 +2078,17 @@ function anchorWords(anchor) {
2077
2078
  return anchor.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2078
2079
  }
2079
2080
  var singular = (w) => w.length > 3 && w.endsWith("s") ? w.slice(0, -1) : w;
2081
+ function platformCorporaOf(datasets) {
2082
+ return datasets.filter((d) => (d.corpora ?? []).some((c) => /^smart-(ops|guides)$/.test(c))).flatMap((d) => [...d.corpora ?? []]);
2083
+ }
2084
+ function platformKnowledgeQuestion(query, ops, pool = [], datasets = []) {
2085
+ const platformCorpora = platformCorporaOf(datasets);
2086
+ if (!platformCorpora.length) return { knowledge: false, corpora: platformCorpora };
2087
+ const objects = query.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length > 2 && !STOP_WORDS.has(w)).map(singular);
2088
+ const byName = isOperationIntent(query) && ops.matched.some((m) => anchorWords(m.anchor).map(singular).some((w) => objects.includes(w)));
2089
+ const inPool = pool.some((h) => platformCorpora.includes(String(h.metadata?.corpus ?? "")));
2090
+ return { knowledge: byName || inPool, corpora: platformCorpora };
2091
+ }
2080
2092
  function matchOperations(query, rows) {
2081
2093
  const q = query.toLowerCase();
2082
2094
  const stems = ACTION_STEMS.filter((s) => q.includes(s));
@@ -2348,6 +2360,12 @@ async function generateStream(env, model, messages, effort) {
2348
2360
  }
2349
2361
  return null;
2350
2362
  }
2363
+ function flattenForTextModel(messages) {
2364
+ const isFigureAttachMessage = (m) => Array.isArray(m.content) && m.content.some((part) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
2365
+ return messages.filter((m) => !isFigureAttachMessage(m)).map(
2366
+ (m) => typeof m.content === "string" ? m : { ...m, content: m.content.filter((p) => p?.type === "text").map((p) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") }
2367
+ );
2368
+ }
2351
2369
  async function summarizeHistory(env, model, turns) {
2352
2370
  try {
2353
2371
  const convo = turns.map((t) => `${t.role === "user" ? "User" : "Assistant"}: ${t.content.slice(0, 1200)}`).join("\n").slice(0, 24e3);
@@ -2520,7 +2538,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2520
2538
  const federate = (member || keyLicensed) && service && isoOn ? (q2) => retrieveInternal(service, fedAuth, q2) : void 0;
2521
2539
  const userDocs = member && env.USER_DOCS_INDEX ? (q2) => queryUserLane(cfModelRunner(env.AI), cfVectorIndex(env.USER_DOCS_INDEX), member.sub, q2, THRESHOLDS.userLaneK) : void 0;
2522
2540
  const ns = tier === "key" ? `k:${key.id}` : member ? `m:${member.sub}` : "anon";
2523
- const model = member ? MODELS.member : MODELS.anon;
2541
+ const model = roleModel(env, member ? "member" : "anon");
2524
2542
  const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : void 0;
2525
2543
  const rawHistory = Array.isArray(body?.history) ? body.history : [];
2526
2544
  const history = rawHistory.filter((h) => (h?.role === "user" || h?.role === "assistant") && typeof h?.content === "string" && h.content.trim()).slice(-24).map((h) => ({ role: h.role, content: h.content.slice(0, 4e3) }));
@@ -2549,14 +2567,14 @@ async function handleAsk(env, ctx, req, tier, key) {
2549
2567
  let nameplate = null;
2550
2568
  if (effectiveImage && /certificate|certified|certification/i.test(q.query)) {
2551
2569
  mark("Reading the nameplate photograph");
2552
- nameplate = await extractNameplate(env.AI, MODELS.member, effectiveImage).catch(() => null);
2570
+ nameplate = await extractNameplate(env.AI, roleModel(env, "member"), effectiveImage).catch(() => null);
2553
2571
  if (nameplate?.manufacturer) {
2554
2572
  mark(`Nameplate read: ${nameplate.manufacturer}${nameplate.model ? ` ${nameplate.model}` : ""}`);
2555
2573
  }
2556
2574
  }
2557
2575
  const budget = num(env, "INPUT_TOKEN_BUDGET", LIMITS.inputTokenBudget);
2558
2576
  const { kept: keptHistory, overflow } = splitHistory(history, budget);
2559
- const summary = overflow.length >= 2 ? await summarizeHistory(env, MODELS.understand, overflow) ?? void 0 : void 0;
2577
+ const summary = overflow.length >= 2 ? await summarizeHistory(env, roleModel(env, "understand"), overflow) ?? void 0 : void 0;
2560
2578
  let retrieved;
2561
2579
  const fresh = freshRequested(body);
2562
2580
  const multiTurn = body?.multi_turn !== false;
@@ -2571,7 +2589,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2571
2589
  const finishLine = (message) => {
2572
2590
  if (live2) {
2573
2591
  live2.send({ type: "token", v: message });
2574
- live2.send({ type: "done", model: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
2592
+ live2.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
2575
2593
  live2.close();
2576
2594
  return null;
2577
2595
  }
@@ -2591,7 +2609,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2591
2609
  if (live2) {
2592
2610
  live2.send({ type: "citations", citations: cached.value.citations ?? [], quota, context_applied: cctx, ...cached.value.source_quality ? { source_quality: cached.value.source_quality, confidence_note: cached.value.confidence_note ?? null, ...cached.value.experimental_sources ? { experimental_sources: cached.value.experimental_sources } : {}, ...cached.value.entailment ? { entailment: cached.value.entailment } : {} } : {} });
2593
2611
  live2.send({ type: "token", v: cached.value.answer ?? "" });
2594
- live2.send({ type: "done", model: cached.value.model ?? MODELS.member, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
2612
+ live2.send({ type: "done", model: cached.value.model ?? model, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
2595
2613
  live2.close();
2596
2614
  return null;
2597
2615
  }
@@ -2628,7 +2646,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2628
2646
  }
2629
2647
  let understanding = null;
2630
2648
  const answerCites = (t) => /\[[^\]]+\]/.test(t);
2631
- const refusalScope = (cited) => ({ cited, conversational: understanding?.intent === "conversational" });
2649
+ const refusalScope = (cited) => ({ cited, conversational: understanding?.intent === "conversational" && !platformQuestion.knowledge });
2632
2650
  let optimisticVec = null;
2633
2651
  let optimisticHits = [];
2634
2652
  const t0 = Date.now();
@@ -2747,12 +2765,12 @@ Certificates are issued per recommendation family \u2014 the register carries no
2747
2765
  registerBlock = block;
2748
2766
  aggregateNoteText = aggregateNote(agg);
2749
2767
  const queryHash2 = await sha256Hex(q2.query);
2750
- telemetry(env, ctx, tier, "ask", MODELS.member, true, answer2.length, queryHash2, q2.lang, void 0, telemetryMeta());
2768
+ telemetry(env, ctx, tier, "ask", model, true, answer2.length, queryHash2, q2.lang, void 0, telemetryMeta());
2751
2769
  const tq2 = await chargeAnswerTokens(env, bucketId, void 0, q2.query.length, answer2.length, keyDayLimit);
2752
2770
  const payload = {
2753
2771
  answer: answer2,
2754
2772
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
2755
- model: MODELS.member,
2773
+ model,
2756
2774
  query_hash: queryHash2,
2757
2775
  follow_ups: [],
2758
2776
  blocks: [block],
@@ -2764,7 +2782,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2764
2782
  if (live2) {
2765
2783
  live2.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
2766
2784
  live2.send({ type: "token", v: answer2 });
2767
- live2.send({ type: "done", model: MODELS.member, query_hash: queryHash2, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
2785
+ live2.send({ type: "done", model, query_hash: queryHash2, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
2768
2786
  live2.send({ type: "quota", quota: payload.quota });
2769
2787
  live2.close();
2770
2788
  return null;
@@ -2774,11 +2792,14 @@ Certificates are issued per recommendation family \u2014 the register carries no
2774
2792
  }
2775
2793
  }
2776
2794
  const regNote = aggregateNoteText ?? (register ? [registerNote(register.rows), certificateLinks(register.rows)].filter(Boolean).join("\n") : void 0);
2777
- const ops = await operationsLane(env.DB, q2.query);
2795
+ const platformCorpora = platformCorporaOf(DATASETS());
2796
+ const ops = platformCorpora.length ? await operationsLane(env.DB, q2.query) : { matched: [] };
2778
2797
  const registerOwns = !!register?.rows?.length;
2779
2798
  const registerCitation = registerOwns ? [{ docidentifier: `${P().publisher.name}-CS certificate register`, corpus: "register" }] : [];
2780
2799
  const escalationCitation = () => escalatedDoc ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }] : [];
2781
- if (understanding?.intent === "conversational") {
2800
+ const platformQuestion = understanding?.intent === "conversational" ? platformKnowledgeQuestion(q2.query, ops, [], DATASETS()) : { knowledge: false, corpora: platformCorpora };
2801
+ const conversational = understanding?.intent === "conversational" && !platformQuestion.knowledge;
2802
+ if (conversational) {
2782
2803
  const queryHash2 = await sha256Hex(q2.query);
2783
2804
  const messages2 = [
2784
2805
  { role: "system", content: identityNote(!!member) },
@@ -2812,7 +2833,7 @@ ${summary}` }] : [],
2812
2833
  return null;
2813
2834
  }
2814
2835
  let answer2 = await generateOnce(env, model, messages2, effort);
2815
- if (answer2 === null) answer2 = await generateOnce(env, MODELS.fallback, messages2, effort);
2836
+ if (answer2 === null) answer2 = await generateOnce(env, roleModel(env, "fallback"), messages2, effort);
2816
2837
  if (answer2 === null) {
2817
2838
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash2, q2.lang, void 0, telemetryMeta());
2818
2839
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
@@ -3102,7 +3123,7 @@ Answer account questions from these records ONLY: name the record when you use i
3102
3123
  })();
3103
3124
  if (retrieved.hits.length >= 4 && (member || understanding?.complexity === "complex")) {
3104
3125
  const tl = Date.now();
3105
- const reordered = await listwiseRerank(env, MODELS.listwise, understanding?.standalone_query || q2.query, retrieved.hits);
3126
+ const reordered = await listwiseRerank(env, roleModel(env, "listwise"), understanding?.standalone_query || q2.query, retrieved.hits);
3106
3127
  stageTiming.listwise = Date.now() - tl;
3107
3128
  if (reordered) {
3108
3129
  console.log("listwise: reordered", reordered[0]?.metadata?.docidentifier ?? "?", "to top");
@@ -3285,7 +3306,7 @@ ${doc.text}` }
3285
3306
  const queryHash = await sha256Hex(q2.query);
3286
3307
  const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3287
3308
  if (live2) {
3288
- const stream = await generateStream(env, model, messages, routeEffort(routed.route));
3309
+ const stream = await generateStream(env, model, messages, routeEffort(routed.route)) ?? await generateStream(env, roleModel(env, "fallback"), flattenForTextModel(messages), routeEffort(routed.route));
3289
3310
  if (stream) {
3290
3311
  const send = (obj) => live2.send(obj);
3291
3312
  for (const step of agentSteps) {
@@ -3504,7 +3525,7 @@ ${doc.text}` }
3504
3525
  live2.close();
3505
3526
  } else {
3506
3527
  live2.send({ type: "token", v: "The generation model is unavailable; please retry." });
3507
- live2.send({ type: "done", model: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
3528
+ live2.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
3508
3529
  live2.close();
3509
3530
  return null;
3510
3531
  }
@@ -3517,7 +3538,7 @@ ${doc.text}` }
3517
3538
  query: q2.query,
3518
3539
  hits: usedHits,
3519
3540
  lang: q2.lang,
3520
- draftModel: MODELS.member,
3541
+ draftModel: roleModel(env, "member"),
3521
3542
  verifierModel: roleModel(env, "verifier")
3522
3543
  }).catch((e) => {
3523
3544
  console.log("speculative: failed, falling through \u2014", String(e).slice(0, 120));
@@ -3532,11 +3553,8 @@ ${doc.text}` }
3532
3553
  if (!answer) answer = await generateOnce(env, model, messages, routeEffort(routed.route));
3533
3554
  if (answer === null) {
3534
3555
  generateRetries += 1;
3535
- const isFigureAttachMessage = (m) => Array.isArray(m.content) && m.content.some((part) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
3536
- const flat = messages.filter((m) => !isFigureAttachMessage(m)).map(
3537
- (m) => typeof m.content === "string" ? m : { ...m, content: m.content.filter((p) => p?.type === "text").map((p) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") }
3538
- );
3539
- answer = await generateOnce(env, MODELS.fallback, flat, routeEffort(routed.route));
3556
+ const flat = flattenForTextModel(messages);
3557
+ answer = await generateOnce(env, roleModel(env, "fallback"), flat, routeEffort(routed.route));
3540
3558
  }
3541
3559
  if (answer === null) {
3542
3560
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q2.lang, void 0, telemetryMeta());
@@ -3691,7 +3709,7 @@ ${doc.text}` }
3691
3709
  }
3692
3710
  telemetryDecisions(env, ctx, tier, queryHash, decisionsOut ?? null, Date.now() - tStart);
3693
3711
  }
3694
- const out = { answer, citations: finalCites, ...jsonQuality ? { source_quality: jsonQuality, confidence_note: entailmentNote || qualityNote(jsonQuality), ...entailment ? { entailment } : {}, ...jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {} } : {}, model: MODELS.member, query_hash: queryHash, follow_ups: refusalShaped(answer, refusalScope(answerCites(answer))) ? [] : understanding?.follow_ups ?? [], blocks: [...c2ns.blocks, ...verdictBlock ? [verdictBlock] : [], ...conditionBlock ? [conditionBlock] : [], ...aggregationBlock ? [aggregationBlock] : [], ...registerBlock ? [registerBlock] : [], ...completionBlocks], context_applied: ctxApplied, ...liveRecords ? { records: liveRecords } : {}, ...decisionsOut ? { decisions: decisionsOut } : {}, ...ablate ? { ablate } : {}, route: { route: routed.route, features: routed.features } };
3712
+ const out = { answer, citations: finalCites, ...jsonQuality ? { source_quality: jsonQuality, confidence_note: entailmentNote || qualityNote(jsonQuality), ...entailment ? { entailment } : {}, ...jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {} } : {}, model, query_hash: queryHash, follow_ups: refusalShaped(answer, refusalScope(answerCites(answer))) ? [] : understanding?.follow_ups ?? [], blocks: [...c2ns.blocks, ...verdictBlock ? [verdictBlock] : [], ...conditionBlock ? [conditionBlock] : [], ...aggregationBlock ? [aggregationBlock] : [], ...registerBlock ? [registerBlock] : [], ...completionBlocks], context_applied: ctxApplied, ...liveRecords ? { records: liveRecords } : {}, ...decisionsOut ? { decisions: decisionsOut } : {}, ...ablate ? { ablate } : {}, route: { route: routed.route, features: routed.features } };
3695
3713
  const cacheable = !contextual && !declaredCtx && !ablate && !registerBypass && cacheableAnswer(answer, refusalScope(answerCites(answer))) && finalAnchors.violations.length === 0;
3696
3714
  if (cacheable) {
3697
3715
  const ck = exactCacheKey(env.INDEX_VERSION, gen, ns, await sha256Hex(cacheKeyMaterial(q2.query, q2.lang, salt)));
@@ -2,4 +2,3 @@ import { nameplateRegisterQuery, type Nameplate } from "./nameplate-parse.ts";
2
2
  export type { Nameplate };
3
3
  export { nameplateRegisterQuery };
4
4
  export declare function extractNameplate(ai: any, model: string, image: string): Promise<Nameplate | null>;
5
- export declare const nameplateModel: () => "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
@@ -3,6 +3,40 @@ export declare function isOperationIntent(query: string): boolean;
3
3
  * entity record" must reach putEntityRecord even when its description
4
4
  * words the action differently ("replaces the stored…"). */
5
5
  export declare function anchorWords(anchor: string): string[];
6
+ /** The platform-source corpora a deployment serves — the ones its
7
+ * datasets name (the API plane, the guides). The operations lane and
8
+ * the conversational yield both key on this: the SAME engine serves the
9
+ * public origin, whose datasets name no platform corpus. */
10
+ export declare function platformCorporaOf(datasets: readonly {
11
+ corpora?: readonly string[];
12
+ }[]): string[];
13
+ /** A platform-knowledge question the understanding step filed as
14
+ * "conversational". On the operations origin the assistant's own
15
+ * identity is "you answer questions about the platform's API
16
+ * operations", so a question about the PLATFORM reads to the
17
+ * classifier as a question about the SERVICE — measured 2026-12-04:
18
+ * "Which platform operation updates an entity record?" came back
19
+ * intent=conversational in 5 of 12 draws and the turn answered from
20
+ * the identity prompt, no retrieval. The subject decides: the
21
+ * deterministic operations lane matched an operation by name, or the
22
+ * retrieval pool holds a passage from a platform-source corpus — the
23
+ * indexed material answers it, so it is a knowledge question. Only the
24
+ * operations lane's own NAME match counts (a verb-only match is the
25
+ * lane's documented noise), and a service that indexes no platform
26
+ * source never re-routes. Pure service questions ("who are you?",
27
+ * "what can you do?") match no operation by name and hold no platform
28
+ * passage — they stay conversational. */
29
+ export declare function platformKnowledgeQuestion(query: string, ops: Pick<OperationsLane, "matched">, pool?: readonly {
30
+ metadata?: {
31
+ corpus?: string;
32
+ };
33
+ }[], datasets?: readonly {
34
+ corpora?: readonly string[];
35
+ session?: boolean;
36
+ }[]): {
37
+ knowledge: boolean;
38
+ corpora: string[];
39
+ };
6
40
  export declare function matchOperations(query: string, rows: {
7
41
  anchor: string;
8
42
  text: string;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  handleSearch
3
- } from "./chunk-5PKKAHY4.js";
4
- import "./chunk-Q7QL3457.js";
3
+ } from "./chunk-CW6J3HTM.js";
4
+ import "./chunk-3SGGVZZ4.js";
5
5
  import "./chunk-AVNHVFEB.js";
6
6
  import "./chunk-GJQT4IMD.js";
7
7
  import "./chunk-ETLSWSZ7.js";
@@ -23,6 +23,7 @@ export interface UserDocumentPorts {
23
23
  blobs: Blobs;
24
24
  lane: VectorIndex;
25
25
  model: ModelRunner;
26
+ answerModel?: string;
26
27
  }
27
28
  export interface UploadBlob {
28
29
  arrayBuffer(): Promise<ArrayBuffer>;
@@ -9,7 +9,7 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-FCRTWZQE.js";
12
+ } from "../../chunk-SWCKO4OB.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
@@ -18,7 +18,7 @@ import {
18
18
  } from "../../chunk-ECNBEZGK.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-5PKKAHY4.js";
21
+ } from "../../chunk-CW6J3HTM.js";
22
22
  import {
23
23
  buildMessages,
24
24
  citations,
@@ -43,7 +43,7 @@ import {
43
43
  sessionFrom,
44
44
  telemetry,
45
45
  understandQuery
46
- } from "../../chunk-Q7QL3457.js";
46
+ } from "../../chunk-3SGGVZZ4.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
@@ -878,7 +878,7 @@ async function handleResearch(env, ctx, req, session) {
878
878
  async function run(env, ctx, q, maxIters, emit) {
879
879
  const started = Date.now();
880
880
  const queryHash = await sha256Hex(q.query);
881
- const understanding = await understandQuery(portModelRunner(env), MODELS.understand, q.query, [], []);
881
+ const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, [], []);
882
882
  const graphDocNumbers = await graphExpand(env, understanding);
883
883
  const eNote = await editionNote(env, understanding);
884
884
  const accumulated = /* @__PURE__ */ new Map();
@@ -910,7 +910,7 @@ ${older.map((h) => `- ${h.metadata.docidentifier ?? ""} \xA7${h.metadata.clause_
910
910
  ` : "";
911
911
  judge = await (async () => {
912
912
  try {
913
- const res = await env.AI.run(MODELS.grader, {
913
+ const res = await env.AI.run(roleModel(env, "grader"), {
914
914
  messages: [
915
915
  { role: "system", content: fill(research_default, promptVars()).trimEnd() },
916
916
  { role: "user", content: `Research question: ${q.query}
@@ -955,10 +955,11 @@ ${recent.map((h, n) => `[${n + 1}] ${h.metadata.docidentifier ?? ""} \xA7${h.met
955
955
  throw new Error("Search is briefly busy \u2014 please retry in a moment.");
956
956
  }
957
957
  const { messages, usedHits } = buildMessages(q.query, used, q.lang, [], eNote || void 0, void 0, LIMITS.inputTokenBudget);
958
- let answer = await generateOnce(env, MODELS.research, messages);
959
- if (answer === null) answer = await generateOnce(env, MODELS.fallback, messages);
958
+ const researchModel = roleModel(env, "research");
959
+ let answer = await generateOnce(env, researchModel, messages);
960
+ if (answer === null) answer = await generateOnce(env, roleModel(env, "fallback"), messages);
960
961
  if (answer === null) {
961
- telemetry(env, ctx, "member", "research", MODELS.research, false, 0, queryHash, q.lang);
962
+ telemetry(env, ctx, "member", "research", researchModel, false, 0, queryHash, q.lang);
962
963
  throw new Error("The generation model is unavailable; please retry.");
963
964
  }
964
965
  answer = canonicalRefusal(answer, { cited: /\[[^\]]+\]/.test(answer), conversational: false });
@@ -967,11 +968,11 @@ ${recent.map((h, n) => `[${n + 1}] ${h.metadata.docidentifier ?? ""} \xA7${h.met
967
968
  const out = {
968
969
  answer,
969
970
  citations: citations(usedHits),
970
- model: MODELS.research,
971
+ model: researchModel,
971
972
  query_hash: queryHash,
972
973
  research: { iterations, passages: used.length, elapsed_ms: Date.now() - started, sufficient: judge?.sufficient ?? null }
973
974
  };
974
- telemetry(env, ctx, "member", "research", MODELS.research, true, answer.length, queryHash, q.lang);
975
+ telemetry(env, ctx, "member", "research", researchModel, true, answer.length, queryHash, q.lang);
975
976
  emit?.({ type: "pass", n: iterations, of: maxIters, phase: "writing", passages: used.length });
976
977
  return out;
977
978
  }
@@ -1189,7 +1190,7 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1189
1190
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1190
1191
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1191
1192
  } else {
1192
- const res = name === "ask" ? await (await import("../../ask-LPNODCPM.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-DE5ADCVM.js")).handleSearch(env, ctx, inner, tier, key);
1193
+ const res = name === "ask" ? await (await import("../../ask-WKHYCVT5.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-KIN474QS.js")).handleSearch(env, ctx, inner, tier, key);
1193
1194
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1194
1195
  }
1195
1196
  telemetry(env, ctx, tier, `mcp:${name}`, null, !payload?.error, JSON.stringify(payload).length, await sha256Hex(`${name}:${JSON.stringify(args ?? {})}`), void 0, void 0, { durationMs: Date.now() - t0 });
@@ -1605,7 +1606,7 @@ async function memoriesRoute(c) {
1605
1606
  return withCors(await handleMemories(c.env, who.sub, c.req, { method: c.req.method, id: c.params.id }), corsHeaders(c.req));
1606
1607
  }
1607
1608
  function userDocumentPorts(env) {
1608
- return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI) };
1609
+ return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI), answerModel: roleModel(env, "member") };
1609
1610
  }
1610
1611
  async function userDocumentsRoute(c) {
1611
1612
  const who = await opIdentity(c, "Sign in to manage your documents");
@@ -29,7 +29,7 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
29
29
  │ └────────────────────────────────────────────────────────────────┘ │
30
30
  │ ↓ │
31
31
  │ ┌─ 1. QUERY UNDERSTANDING (LLM) ─────────────────────────────────┐ │
32
- │ │ qwen3-30b-a3b → strict JSON (prompts/understanding.md): │ │
32
+ │ │ deepseek-v4.1-flash (roleModel "understand") → strict JSON: │ │
33
33
  │ │ · intent (see layer 0) · docidentifier/docnumber │ │
34
34
  │ │ · process_intent (certify/apply → B-series, not R-series) │ │
35
35
  │ │ · term ("what is a load cell" → "load cell") │ │
@@ -92,7 +92,7 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
92
92
  │ └────────────────────────────────────────────────────────────────┘ │
93
93
  │ ↓ │
94
94
  │ ┌─ 9. CRAG GRADER ───────────────────────────────────────────────┐ │
95
- │ │ deepseek-v4-flash grades passages good/weak/bad │ │
95
+ │ │ deepseek-v4.1-flash (roleModel "grader") grades good/weak/bad │ │
96
96
  │ │ · good → generate │ │
97
97
  │ │ · weak → ONE corrective re-retrieval (doc ident made │ │
98
98
  │ │ explicit); accepted only on strictly better grade │ │
@@ -101,7 +101,8 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
101
101
  │ └────────────────────────────────────────────────────────────────┘ │
102
102
  │ ↓ │
103
103
  │ ┌─ 10. GENERATION ───────────────────────────────────────────────┐ │
104
- │ │ Anon: qwen3-30b-a3b-fp8 | Member: qwen3.8-27b │ │
104
+ │ │ Both tiers: deepseek-v4.1-flash (roleModel member/anon; │ │
105
+ │ │ glm-5.3 fallback). Every model call goes through roleModel() │ │
105
106
  │ │ System prompt is DATA (prompts/system.md, {{PLACEHOLDERS}} │ │
106
107
  │ │ filled from code; per-corpus notes travel with the DATASETS │ │
107
108
  │ │ catalog entry) │ │
@@ -232,7 +233,7 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
232
233
  │ ES256 via JWKS, RFC 8414 discovery) │
233
234
  │ · RAG-minted HMAC session cookie (7-day, sliding renewal) │
234
235
  │ · Anon: 20/day per IP (KV counter) │
235
- │ · Member: 300/day, qwen3.8-27b model │
236
+ │ · Member: 300/day, deepseek-v4.1-flash (roleModel member) │
236
237
  │ · API key: per-key limits, D1-backed │
237
238
  │ · Operator IP exemption (env + KV override) │
238
239
  │ · Role-gated datasets panel (ISO corpus: mc_member, etc.) │
@@ -283,7 +284,8 @@ failure modes in `docs/spec-pipeline.md`; the HTTP surface in
283
284
  ## 2026-09 additions (delta over the 2026-08-26 map)
284
285
 
285
286
  - **Multimodal generation**: figure units among the used passages attach
286
- their R2 pixels to the glm-5.3-flash call (`attachFigureImages`) — the
287
+ their R2 pixels to the answer model's call (`attachFigureImages`;
288
+ glm-5.3 fallback) — the
287
289
  model reads labels that exist only in the image. Users can attach a
288
290
  photo (`image` data URL on /v1/ask, validated, 6MB) — text still drives
289
291
  retrieval; image asks bypass both caches.
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.189",
30
+ "version": "0.2.191",
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",
@@ -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";
@@ -53,7 +53,7 @@ import { assembleDocument, verifyAnchors, escalationAllowed, chargeEscalation, e
53
53
  import { ESCALATION_DAILY_DEFAULT } from "./config";
54
54
  import { cfModelRunner, cfStore, cfVectorIndex } from "./ports/cloudflare/adapters";
55
55
  import { TOOL_DECLARATION, parseToolCall, runTool, toolNote } from "./tools";
56
- import { operationsLane } from "./operations.ts";
56
+ import { operationsLane, platformCorporaOf, platformKnowledgeQuestion, type OperationsLane } from "./operations.ts";
57
57
  import { extractNameplate, nameplateRegisterQuery } from "./nameplate.ts";
58
58
  import { P } from "./profile.ts";
59
59
  import { toolNarration, intentPreamble, TOOL_NARRATION_NOTICE, INTENT_PREAMBLE_NOTICE } from "./answerGuards.ts";
@@ -240,6 +240,25 @@ async function generateStream(env: Env, model: string, messages: any[], effort?:
240
240
  return null;
241
241
  }
242
242
 
243
+ /** The fallback is a text-only model: image parts must be flattened out
244
+ * first or it errors on (or silently ignores) the pixels the primary
245
+ * was carrying — and the figure-attach NOTE with them: a message saying
246
+ * "the image is attached" to a model that cannot see images gets
247
+ * ANSWERED instead of the question (observed in the wild). The
248
+ * user-image message keeps its text (the question) minus its note. */
249
+ function flattenForTextModel(messages: any[]): any[] {
250
+ const isFigureAttachMessage = (m: any) =>
251
+ Array.isArray(m.content) &&
252
+ m.content.some((part: any) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
253
+ return messages
254
+ .filter((m: any) => !isFigureAttachMessage(m))
255
+ .map((m: any) =>
256
+ typeof m.content === "string"
257
+ ? m
258
+ : { ...m, content: m.content.filter((p: any) => p?.type === "text").map((p: any) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") },
259
+ );
260
+ }
261
+
243
262
  /** Compact overflow history into a short continuity summary. Null = keep
244
263
  * nothing (degrades to plain truncation, never to failure). */
245
264
  async function summarizeHistory(
@@ -539,7 +558,7 @@ async function handleAsk(
539
558
  : undefined;
540
559
 
541
560
  const ns = tier === "key" ? `k:${key!.id}` : member ? `m:${member.sub}` : "anon";
542
- const model = member ? MODELS.member : MODELS.anon;
561
+ const model = roleModel(env, member ? "member" : "anon");
543
562
  const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : undefined;
544
563
  const rawHistory = Array.isArray(body?.history) ? body.history : [];
545
564
  const history = rawHistory
@@ -586,7 +605,7 @@ async function handleAsk(
586
605
  let nameplate: Awaited<ReturnType<typeof extractNameplate>> | null = null;
587
606
  if (effectiveImage && /certificate|certified|certification/i.test(q.query)) {
588
607
  mark("Reading the nameplate photograph");
589
- nameplate = await extractNameplate((env as any).AI, MODELS.member, effectiveImage).catch(() => null);
608
+ nameplate = await extractNameplate((env as any).AI, roleModel(env, "member"), effectiveImage).catch(() => null);
590
609
  if (nameplate?.manufacturer) {
591
610
  mark(`Nameplate read: ${nameplate.manufacturer}${nameplate.model ? ` ${nameplate.model}` : ""}`);
592
611
  }
@@ -596,7 +615,7 @@ async function handleAsk(
596
615
  // continuity block (below) instead of silently dropped
597
616
  const budget = num(env as any, "INPUT_TOKEN_BUDGET", LIMITS.inputTokenBudget);
598
617
  const { kept: keptHistory, overflow } = splitHistory(history, budget);
599
- const summary = overflow.length >= 2 ? ((await summarizeHistory(env, MODELS.understand, overflow)) ?? undefined) : undefined;
618
+ const summary = overflow.length >= 2 ? ((await summarizeHistory(env, roleModel(env, "understand"), overflow)) ?? undefined) : undefined;
600
619
  let retrieved;
601
620
  // fresh (regenerate) skips the cache read; contextual follow-ups,
602
621
  // declared-context asks, draft asks and image asks skip the cache
@@ -634,7 +653,7 @@ async function handleAsk(
634
653
  const finishLine = (message: string) => {
635
654
  if (live) {
636
655
  live!.send({ type: "token", v: message });
637
- live!.send({ type: "done", model: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
656
+ live!.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
638
657
  live!.close();
639
658
  return null;
640
659
  }
@@ -662,7 +681,7 @@ async function handleAsk(
662
681
  if (live) {
663
682
  live!.send({ type: "citations", citations: cached.value.citations ?? [], quota, context_applied: cctx, ...(cached.value.source_quality ? { source_quality: cached.value.source_quality, confidence_note: cached.value.confidence_note ?? null, ...(cached.value.experimental_sources ? { experimental_sources: cached.value.experimental_sources } : {}), ...(cached.value.entailment ? { entailment: cached.value.entailment } : {}) } : {}) });
664
683
  live!.send({ type: "token", v: cached.value.answer ?? "" });
665
- live!.send({ type: "done", model: cached.value.model ?? MODELS.member, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
684
+ live!.send({ type: "done", model: cached.value.model ?? model, query_hash: cached.value.query_hash, served_from: "cache", context_applied: cctx });
666
685
  live!.close();
667
686
  return null;
668
687
  }
@@ -726,7 +745,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
726
745
  // refusal) — gating on usedHits left every refusal "cited" and the
727
746
  // wall dark through three deploys (2026-10-11)
728
747
  const answerCites = (t: string) => /\[[^\]]+\]/.test(t);
729
- const refusalScope = (cited: boolean) => ({ cited, conversational: understanding?.intent === "conversational" });
748
+ const refusalScope = (cited: boolean) => ({ cited, conversational: understanding?.intent === "conversational" && !platformQuestion.knowledge });
730
749
  // a query naming a model node (/req/…, /term/…) is node-SCOPED: its
731
750
  // ── Option C: optimistic parallel retrieval ──
732
751
  // The dense lane (folded-query embed + unfiltered Vectorize query) runs
@@ -904,12 +923,12 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
904
923
  registerBlock = block;
905
924
  aggregateNoteText = aggregateNote(agg);
906
925
  const queryHash = await sha256Hex(q.query);
907
- telemetry(env, ctx, tier, "ask", MODELS.member, true, answer!.length, queryHash, q.lang, undefined, telemetryMeta());
926
+ telemetry(env, ctx, tier, "ask", model, true, answer!.length, queryHash, q.lang, undefined, telemetryMeta());
908
927
  const tq = await chargeAnswerTokens(env, bucketId, undefined, q.query.length, answer!.length, keyDayLimit);
909
928
  const payload = {
910
929
  answer,
911
930
  citations: [{ docidentifier: `${P().publisher.name}-CS certificate register (family ${agg.family})`, corpus: "register" }],
912
- model: MODELS.member,
931
+ model,
913
932
  query_hash: queryHash,
914
933
  follow_ups: [] as string[],
915
934
  blocks: [block],
@@ -921,7 +940,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
921
940
  if (live) {
922
941
  live!.send({ type: "citations", citations: payload.citations, quota: payload.quota, context_applied: NO_CONTEXT });
923
942
  live!.send({ type: "token", v: answer });
924
- live!.send({ type: "done", model: MODELS.member, query_hash: queryHash, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
943
+ live!.send({ type: "done", model, query_hash: queryHash, blocks: [block], follow_ups: [], context_applied: NO_CONTEXT, read: readAs() });
925
944
  live!.send({ type: "quota", quota: payload.quota });
926
945
  live!.close();
927
946
  return null;
@@ -932,7 +951,17 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
932
951
  }
933
952
  const regNote = aggregateNoteText
934
953
  ?? (register ? [registerNote(register.rows), certificateLinks(register.rows)].filter(Boolean).join("\n") : undefined);
935
- const ops = await operationsLane(env.DB, q.query);
954
+ // The operations catalog lane belongs to a deployment that serves the
955
+ // API plane: it runs only where the profile's datasets name a platform
956
+ // corpus (the operations origin). The same engine serves the public
957
+ // origin, whose datasets name none — there the lane's AUTHORITATIVE
958
+ // note and its citable operation passages must never enter the prompt
959
+ // (observed 2026-12-04, the moment the lane's rows returned to D1: the
960
+ // public origin began answering platform-operation questions).
961
+ const platformCorpora = platformCorporaOf(DATASETS());
962
+ const ops = platformCorpora.length
963
+ ? await operationsLane(env.DB, q.query)
964
+ : { matched: [] as OperationsLane["matched"] };
936
965
  // The register lane owns the answer surface when it holds rows — the
937
966
  // aggregate path's philosophy (the note answers the structure, the
938
967
  // model narrates) extended to the standing lane. Measured 2026-10-28:
@@ -953,13 +982,33 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
953
982
  ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }]
954
983
  : [];
955
984
 
985
+ // A platform-knowledge question the understanding step filed as
986
+ // "conversational" takes the knowledge route instead (./operations
987
+ // platformKnowledgeQuestion): on the operations origin the assistant's
988
+ // identity is "you answer questions about the platform's API
989
+ // operations", so a question about the PLATFORM reads to the
990
+ // classifier as one about the SERVICE — measured 2026-12-04: the
991
+ // deploy smoke's "Which platform operation updates an entity record?"
992
+ // classified conversational in 5 of 12 draws and answered 1/6 from
993
+ // the identity prompt, no retrieval. The deterministic operations
994
+ // lane matching an operation BY NAME is the evidence the indexed
995
+ // material answers it; the matched operation rides the pool as a
996
+ // citable passage either way. Everything else keeps the classifier's
997
+ // verdict — this is a narrow yield, not a second classifier.
998
+ const platformQuestion = understanding?.intent === "conversational"
999
+ ? platformKnowledgeQuestion(q.query, ops, [], DATASETS())
1000
+ : { knowledge: false, corpora: platformCorpora };
1001
+ // the refusal scope and the read echo report the route the turn
1002
+ // actually took
1003
+ const conversational = understanding?.intent === "conversational" && !platformQuestion.knowledge;
1004
+
956
1005
  // Conversational route, decided by query UNDERSTANDING (any language, any
957
1006
  // phrasing) — not string matching. No retrieval: nothing in the corpus
958
1007
  // answers "who are you". The model speaks for itself from the service
959
1008
  // facts in identityNote (composed from the DATASETS catalog). A declared
960
1009
  // context is honestly NOT applied here (nothing grounds a conversational
961
1010
  // turn) — the echo reports none.
962
- if (understanding?.intent === "conversational") {
1011
+ if (conversational) {
963
1012
  const queryHash = await sha256Hex(q.query);
964
1013
  const messages = [
965
1014
  { role: "system", content: identityNote(!!member) },
@@ -994,7 +1043,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
994
1043
  return null;
995
1044
  }
996
1045
  let answer = await generateOnce(env, model, messages, effort);
997
- if (answer === null) answer = await generateOnce(env, MODELS.fallback, messages, effort);
1046
+ if (answer === null) answer = await generateOnce(env, roleModel(env, "fallback"), messages, effort);
998
1047
  if (answer === null) {
999
1048
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q.lang, undefined, telemetryMeta());
1000
1049
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
@@ -1438,7 +1487,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1438
1487
  })();
1439
1488
  if (retrieved.hits.length >= 4 && (member || understanding?.complexity === "complex")) {
1440
1489
  const tl = Date.now();
1441
- const reordered = await listwiseRerank(env, MODELS.listwise, understanding?.standalone_query || q.query, retrieved.hits);
1490
+ const reordered = await listwiseRerank(env, roleModel(env, "listwise"), understanding?.standalone_query || q.query, retrieved.hits);
1442
1491
  stageTiming.listwise = Date.now() - tl;
1443
1492
  if (reordered) {
1444
1493
  console.log("listwise: reordered", reordered[0]?.metadata?.docidentifier ?? "?", "to top");
@@ -1730,7 +1779,12 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1730
1779
  const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1731
1780
 
1732
1781
  if (live) {
1733
- const stream = await generateStream(env, model, messages, routeEffort(routed.route));
1782
+ // the streamed lane gets the same fallback diversity as the JSON
1783
+ // lane: when the primary's stream cannot be established after its
1784
+ // retry, one attempt on the fallback model (text-only — the image
1785
+ // parts are flattened first) before the honest unavailable line
1786
+ const stream = (await generateStream(env, model, messages, routeEffort(routed.route)))
1787
+ ?? (await generateStream(env, roleModel(env, "fallback"), flattenForTextModel(messages), routeEffort(routed.route)));
1734
1788
  if (stream) {
1735
1789
  const send = (obj: unknown) => live!.send(obj);
1736
1790
  // the agent trace arrives first: every questioning round the
@@ -1995,7 +2049,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1995
2049
  // the streamed lane's generation is unavailable — the line goes
1996
2050
  // out on the already-open SSE; the json lane never enters this block
1997
2051
  live!.send({ type: "token", v: "The generation model is unavailable; please retry." });
1998
- live!.send({ type: "done", model: MODELS.member, query_hash: "", context_applied: NO_CONTEXT });
2052
+ live!.send({ type: "done", model, query_hash: "", context_applied: NO_CONTEXT });
1999
2053
  live!.close();
2000
2054
  return null;
2001
2055
  }
@@ -2013,7 +2067,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2013
2067
  if (ablate?.speculative) {
2014
2068
  const spec = await speculativeDraftVerify(env, {
2015
2069
  query: q.query, hits: usedHits, lang: q.lang,
2016
- draftModel: MODELS.member, verifierModel: roleModel(env, "verifier"),
2070
+ draftModel: roleModel(env, "member"), verifierModel: roleModel(env, "verifier"),
2017
2071
  }).catch((e: unknown) => {
2018
2072
  console.log("speculative: failed, falling through —", String(e).slice(0, 120));
2019
2073
  return null;
@@ -2027,24 +2081,10 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2027
2081
  if (!answer) answer = await generateOnce(env, model, messages, routeEffort(routed.route));
2028
2082
  if (answer === null) {
2029
2083
  generateRetries += 1;
2030
- // the fallback is a text-only model: image parts must be flattened
2031
- // out first or it errors on (or silently ignores) the pixels the
2032
- // primary was carrying — and the figure-attach NOTE with them: a
2033
- // message saying "the image is attached" to a model that cannot see
2034
- // images gets ANSWERED ("I don't have access to the original
2035
- // image…") instead of the question (observed in the wild). The
2036
- // user-image message keeps its text (the question) minus its note.
2037
- const isFigureAttachMessage = (m: any) =>
2038
- Array.isArray(m.content) &&
2039
- m.content.some((part: any) => part?.type === "text" && /^The original image of figure unit /.test(part.text ?? ""));
2040
- const flat = messages
2041
- .filter((m: any) => !isFigureAttachMessage(m))
2042
- .map((m: any) =>
2043
- typeof m.content === "string"
2044
- ? m
2045
- : { ...m, content: m.content.filter((p: any) => p?.type === "text").map((p: any) => (p?.text ?? "").replace(/\n?\(The user attached an image with this question; interpret it directly when answering\.\)/, "")).join("\n") },
2046
- );
2047
- answer = await generateOnce(env, MODELS.fallback, flat, routeEffort(routed.route));
2084
+ // the fallback is a text-only model: flatten the image parts first
2085
+ // (and the figure-attach NOTE with them)
2086
+ const flat = flattenForTextModel(messages);
2087
+ answer = await generateOnce(env, roleModel(env, "fallback"), flat, routeEffort(routed.route));
2048
2088
  }
2049
2089
  if (answer === null) {
2050
2090
  // both generations failed — the json lane returns the error shape; the
@@ -2285,7 +2325,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2285
2325
  }
2286
2326
  telemetryDecisions(env, ctx, tier, queryHash, decisionsOut ?? null, Date.now() - tStart);
2287
2327
  }
2288
- const out = { answer, citations: finalCites, ...(jsonQuality ? { source_quality: jsonQuality!, confidence_note: entailmentNote || qualityNote(jsonQuality!), ...(entailment ? { entailment } : {}), ...(jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {}) } : {}), model: MODELS.member, query_hash: queryHash, follow_ups: refusalShaped(answer!, refusalScope(answerCites(answer!))) ? [] : (understanding?.follow_ups ?? []), blocks: [...c2ns.blocks, ...(verdictBlock ? [verdictBlock] : []), ...(conditionBlock ? [conditionBlock] : []), ...(aggregationBlock ? [aggregationBlock] : []), ...(registerBlock ? [registerBlock] : []), ...completionBlocks], context_applied: ctxApplied, ...(liveRecords ? { records: liveRecords } : {}), ...(decisionsOut ? { decisions: decisionsOut } : {}), ...(ablate ? { ablate } : {}), route: { route: routed.route, features: routed.features } };
2328
+ const out = { answer, citations: finalCites, ...(jsonQuality ? { source_quality: jsonQuality!, confidence_note: entailmentNote || qualityNote(jsonQuality!), ...(entailment ? { entailment } : {}), ...(jsonQuality === "ocr" ? { experimental_sources: experimentalSourceLabels(finalCites) } : {}) } : {}), model, query_hash: queryHash, follow_ups: refusalShaped(answer!, refusalScope(answerCites(answer!))) ? [] : (understanding?.follow_ups ?? []), blocks: [...c2ns.blocks, ...(verdictBlock ? [verdictBlock] : []), ...(conditionBlock ? [conditionBlock] : []), ...(aggregationBlock ? [aggregationBlock] : []), ...(registerBlock ? [registerBlock] : []), ...completionBlocks], context_applied: ctxApplied, ...(liveRecords ? { records: liveRecords } : {}), ...(decisionsOut ? { decisions: decisionsOut } : {}), ...(ablate ? { ablate } : {}), route: { route: routed.route, features: routed.features } };
2289
2329
  const cacheable = !contextual && !declaredCtx && !ablate && !registerBypass && cacheableAnswer(answer!, refusalScope(answerCites(answer!))) && finalAnchors.violations.length === 0;
2290
2330
  if (cacheable) {
2291
2331
  const ck = exactCacheKey(env.INDEX_VERSION, gen, ns, await sha256Hex(cacheKeyMaterial(q.query, q.lang, salt)));
@@ -5,7 +5,7 @@
5
5
  // bound, and the gate's noul clears decisionsGateMin.
6
6
  import { portModelRunner } from "./env.ts";
7
7
  import { telemetry } from "./quota";
8
- import { MODELS, THRESHOLDS } from "./config.ts";
8
+ import { MODELS, THRESHOLDS, roleModel } from "./config.ts";
9
9
  import {
10
10
  buildDecisionQuestions, matchAnswers, parseDerivation,
11
11
  assembleSection, type DecisionItem, type DecisionMode,
@@ -74,7 +74,7 @@ export async function runDecisionPass(
74
74
  if (!passages.length) return null;
75
75
  try {
76
76
  // 1. derive the checklist candidates from the used passages
77
- const deriveModel = (env as any).DECISIONS_EXTRACT_MODEL || MODELS.member;
77
+ const deriveModel = (env as any).DECISIONS_EXTRACT_MODEL || roleModel(env, "member");
78
78
  const derived = await portModelRunner(env).run({
79
79
  model: deriveModel,
80
80
  messages: [
@@ -129,7 +129,7 @@ async function memoriesRoute(c: RouteContext): Promise<Response> {
129
129
  }
130
130
 
131
131
  function userDocumentPorts(env: Env): UserDocumentPorts {
132
- return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI) };
132
+ return { store: cfStore(env.DB), blobs: cfBlobs(env.USER_DOCS), lane: cfVectorIndex(env.USER_DOCS_INDEX), model: cfModelRunner(env.AI), answerModel: roleModel(env, "member") };
133
133
  }
134
134
 
135
135
  async function userDocumentsRoute(c: RouteContext): Promise<Response> {
@@ -8,7 +8,6 @@
8
8
  // rides its OWN short user message, never a long passage.
9
9
  import nameplatePrompt from "../prompts/nameplate.md";
10
10
  import { parseNameplate, nameplateRegisterQuery, type Nameplate } from "./nameplate-parse.ts";
11
- import { MODELS } from "./config.ts";
12
11
 
13
12
  export type { Nameplate };
14
13
  export { nameplateRegisterQuery };
@@ -59,5 +58,3 @@ export async function extractNameplate(ai: any, model: string, image: string): P
59
58
  }
60
59
  return null; // the bridge is optional — the ask never depends on it
61
60
  }
62
-
63
- export const nameplateModel = () => MODELS.member;
@@ -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));
@@ -7,7 +7,14 @@ import type { Background } from "./ports/runtime.ts";
7
7
  export async function kvIncr(cache: KVNamespace, key: string, step = 1): Promise<number> {
8
8
  const cur = Number((await cache.get(key)) ?? "0");
9
9
  const next = cur + step;
10
- await cache.put(key, String(next), { expirationTtl: 90000 });
10
+ // Cloudflare KV rate-limits writes to the same key to 1/s (429 Too Many
11
+ // Requests). Fail open on a rejected counter write so rapid back-to-back
12
+ // requests (e.g. /mcp tool calls) never 500 on telemetry/quota accounting.
13
+ try {
14
+ await cache.put(key, String(next), { expirationTtl: 90000 });
15
+ } catch (e) {
16
+ console.error("kvIncr: put failed —", String(e).slice(0, 120));
17
+ }
11
18
  return next;
12
19
  }
13
20
 
@@ -3,7 +3,7 @@
3
3
  import { err, json, corsHeaders, readJson, validateQuery } from "./lib/http";
4
4
  import { portModelRunner } from "./env.ts";
5
5
  import { telemetry } from "./quota";
6
- import { LIMITS, MODELS, sha256Hex } from "./config";
6
+ import { LIMITS, sha256Hex, roleModel } from "./config";
7
7
  import { retrieve, buildMessages, citations } from "./pipeline";
8
8
  import { understandQuery } from "./understand";
9
9
  import { generateOnce } from "./ai";
@@ -75,7 +75,7 @@ async function run(
75
75
  ): Promise<{ answer: string; citations: unknown[]; model: string; query_hash: string; research: { iterations: number; passages: number; elapsed_ms: number; sufficient: boolean | null } }> {
76
76
  const started = Date.now();
77
77
  const queryHash = await sha256Hex(q.query);
78
- const understanding = await understandQuery(portModelRunner(env), MODELS.understand, q.query, [], []);
78
+ const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, [], []);
79
79
  const graphDocNumbers = await graphExpand(env, understanding);
80
80
  const eNote = await editionNote(env, understanding);
81
81
 
@@ -114,7 +114,7 @@ async function run(
114
114
  : "";
115
115
  judge = await (async () => {
116
116
  try {
117
- const res: any = await env.AI.run(MODELS.grader, {
117
+ const res: any = await env.AI.run(roleModel(env, "grader"), {
118
118
  messages: [
119
119
  { role: "system", content: fill(researchPromptText, promptVars()).trimEnd() },
120
120
  { role: "user", content: `Research question: ${q.query}\n\n${digest}Collected passages (${recent.length}):\n${recent.map((h, n) => `[${n + 1}] ${h.metadata.docidentifier ?? ""} §${h.metadata.clause_anchor ?? ""}: ${h.text.slice(0, 700)}`).join("\n")}` },
@@ -159,10 +159,11 @@ async function run(
159
159
  throw new Error("Search is briefly busy — please retry in a moment.");
160
160
  }
161
161
  const { messages, usedHits } = buildMessages(q.query, used, q.lang, [], eNote || undefined, undefined, LIMITS.inputTokenBudget);
162
- let answer = await generateOnce(env, MODELS.research, messages);
163
- if (answer === null) answer = await generateOnce(env, MODELS.fallback, messages);
162
+ const researchModel = roleModel(env, "research");
163
+ let answer = await generateOnce(env, researchModel, messages);
164
+ if (answer === null) answer = await generateOnce(env, roleModel(env, "fallback"), messages);
164
165
  if (answer === null) {
165
- telemetry(env, ctx, "member", "research", MODELS.research, false, 0, queryHash, q.lang);
166
+ telemetry(env, ctx, "member", "research", researchModel, false, 0, queryHash, q.lang);
166
167
  throw new Error("The generation model is unavailable; please retry.");
167
168
  }
168
169
  answer = canonicalRefusal(answer, { cited: /\[[^\]]+\]/.test(answer), conversational: false });
@@ -171,11 +172,11 @@ async function run(
171
172
  const out = {
172
173
  answer,
173
174
  citations: citations(usedHits),
174
- model: MODELS.research,
175
+ model: researchModel,
175
176
  query_hash: queryHash,
176
177
  research: { iterations, passages: used.length, elapsed_ms: Date.now() - started, sufficient: judge?.sufficient ?? null },
177
178
  };
178
- telemetry(env, ctx, "member", "research", MODELS.research, true, answer.length, queryHash, q.lang);
179
+ telemetry(env, ctx, "member", "research", researchModel, true, answer.length, queryHash, q.lang);
179
180
  emit?.({ type: "pass", n: iterations, of: maxIters, phase: "writing", passages: used.length });
180
181
  return out;
181
182
  }
@@ -1,5 +1,5 @@
1
1
  // Passage search: retrieval without generation (TODO.impl/23).
2
- import { LIMITS, MODELS, num, sha256Hex } from "./config";
2
+ import { LIMITS, MODELS, num, sha256Hex, roleModel } from "./config";
3
3
  import { portModelRunner } from "./env.ts";
4
4
  import type { Background } from "./ports/runtime.ts";
5
5
  import { retrieve } from "./pipeline";
@@ -31,7 +31,7 @@ export async function handleSearch(
31
31
  return err(429, "quota_exceeded", `Daily search limit reached (${quota.limit}). Try again tomorrow.`);
32
32
  }
33
33
 
34
- const understanding = await understandQuery(portModelRunner(env), MODELS.understand, q.query, []);
34
+ const understanding = await understandQuery(portModelRunner(env), roleModel(env, "understand"), q.query, []);
35
35
  const graphDocNumbers = await graphExpand(env, understanding);
36
36
  // the license entitlement set rides the body exactly as it does on the
37
37
  // ask path (TODO.external-refs/08): request-scoped, whitelist-validated,
@@ -109,27 +109,15 @@ export const sectionDescent: Stage = {
109
109
  .map((s) => s.trim())
110
110
  .filter(Boolean)
111
111
  .slice(0, 25);
112
- if (kids.length) {
113
- const cv = await c.env.VECTORIZE.query(c.vector, {
114
- topK: 3,
115
- returnMetadata: "all",
116
- filter: {
117
- $and: [
118
- { doc_id: { $eq: sectionHit.metadata.doc_id } },
119
- { clause_anchor: { $in: kids } },
120
- ],
121
- },
122
- });
123
- const childHits = (cv.matches ?? [])
124
- .filter((m: any) => !m.metadata?.section_summary)
125
- .map((m: any) => ({
126
- id: m.id,
127
- score: m.score * THRESHOLDS.sectionDescentDiscount,
128
- metadata: m.metadata as ChunkMeta,
129
- text: (m.metadata?.chunk_text as string) ?? "",
130
- }))
131
- .filter((x: Hit) => !c.finalHits.some((h) => h.id === x.id))
132
- .slice(0, 2);
112
+ if (kids.length && c.env.DB) {
113
+ // Read child clauses from D1 directly (same as level 2 above): Vectorize
114
+ // rejects $and arrays (40026) and does not index doc_id / clause_anchor.
115
+ const order = new Map(kids.map((a, i) => [a, i]));
116
+ const childHits = (await clausesOf(c.env, String(sectionHit.metadata.doc_id), kids, 6))
117
+ .filter((x) => !x.metadata?.section_summary && !c.finalHits.some((h) => h.id === x.id))
118
+ .sort((a, b) => (order.get(String(a.metadata.clause_anchor ?? "")) ?? 99) - (order.get(String(b.metadata.clause_anchor ?? "")) ?? 99))
119
+ .slice(0, 2)
120
+ .map((x) => ({ ...x, score: sectionHit.score * THRESHOLDS.sectionDescentDiscount }));
133
121
  if (childHits.length) {
134
122
  c.finalHits = [...c.finalHits.filter((h) => h !== sectionHit), ...childHits];
135
123
  console.log(
@@ -72,7 +72,7 @@ export const typedPin: Stage = {
72
72
  return new Set<string>(pinFamily ? [pinFamily.split("-")[0]] : [...glossaryFamilies]).size > 0;
73
73
  },
74
74
  run: async (c) => {
75
- const { query, filters, u, glossary, hits, env, vector } = c;
75
+ const { query, filters, u, glossary, hits, env } = c;
76
76
  const glossaryFamilies = new Set<string>();
77
77
  for (const g of glossary) if (g.doc_number) glossaryFamilies.add(g.doc_number.split("-")[0]);
78
78
  const pinFamily = filters?.doc_number ?? u?.doc_number ?? null;
@@ -109,16 +109,24 @@ export const typedPin: Stage = {
109
109
  const parentPresent = c.finalHits.some(
110
110
  (h) => h.metadata.doc_id === docId && h.metadata.clause_anchor === anchor && !h.metadata.unit_id,
111
111
  );
112
- if (anchor && docId && !parentPresent) {
112
+ if (anchor && docId && !parentPresent && env.DB) {
113
113
  try {
114
- const pv = await env.VECTORIZE.query(vector, {
115
- topK: 4,
116
- returnMetadata: "all",
117
- filter: { $and: [{ doc_id: { $eq: docId } }, { clause_anchor: { $eq: anchor } }] },
118
- });
119
- const parent = (pv.matches ?? []).map((m: any) => ({ id: m.id, score: m.score, metadata: m.metadata, text: m.metadata?.chunk_text ?? "" })).find((h: any) => !h.metadata?.unit_id);
120
- if (parent && !c.finalHits.some((h) => h.id === parent.id)) {
121
- c.finalHits = [...c.finalHits, { ...parent, score: parent.score * THRESHOLDS.smallToBigDiscount }];
114
+ // Read the parent prose clause from D1 directly: Vectorize rejects
115
+ // $and arrays (40026) and does not index doc_id / clause_anchor.
116
+ const res = await env.DB.prepare(
117
+ "SELECT id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2",
118
+ )
119
+ .bind(docId, anchor)
120
+ .all();
121
+ const row = (res.results ?? [])[0] as any;
122
+ if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
123
+ const parent: Hit = {
124
+ id: String(row.id),
125
+ score: typed.score * THRESHOLDS.smallToBigDiscount,
126
+ metadata: { ...row, unit_id: undefined, block: row.block || undefined },
127
+ text: String(row.text ?? ""),
128
+ };
129
+ c.finalHits = [...c.finalHits, parent];
122
130
  console.log("small-to-big: parent §", anchor, "of", typed.metadata.docidentifier, "added");
123
131
  }
124
132
  } catch {
@@ -7,7 +7,7 @@
7
7
  // the window with a rerank score above the incumbent top; every failure
8
8
  // mode is additive (the text ranking stands). Off via the registry
9
9
  // projection like any stage (ablate_stages drops it).
10
- import { MODELS } from "../config.ts";
10
+ import { roleModel } from "../config.ts";
11
11
  import { portBlobs, portModelRunner, portStore } from "../env.ts";
12
12
  import type { Stage } from "./types.ts";
13
13
  import type { Hit } from "../../../shared/chunk";
@@ -63,7 +63,7 @@ export const vlmFigureRerank: Stage = {
63
63
  }
64
64
  if (!kept.length) return;
65
65
  const raced: any = await Promise.race([
66
- portModelRunner(c.env).run({ model: MODELS.vlmFigure, messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
66
+ portModelRunner(c.env).run({ model: roleModel(c.env, "vlmFigure"), messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
67
67
  new Promise<null>((r) => setTimeout(() => r(null), 15000)),
68
68
  ]);
69
69
  const pick = parsePick(raced?.text ?? raced, kept.length);
@@ -55,6 +55,7 @@ export interface UserDocumentPorts {
55
55
  blobs: Blobs;
56
56
  lane: VectorIndex;
57
57
  model: ModelRunner;
58
+ answerModel?: string;
58
59
  }
59
60
 
60
61
  export interface UploadBlob {
@@ -159,13 +160,13 @@ export async function processImport(ports: UserDocumentPorts, row: UserDocumentR
159
160
  } else {
160
161
  // images: the vision lane transcribes (the nameplate pattern —
161
162
  // transcription-first framing beats extract-a-JSON on plates)
162
- text = await visionTranscribe(ports.model, mime, bytes);
163
+ text = await visionTranscribe(ports.model, mime, bytes, ports.answerModel ?? MODELS.member);
163
164
  if (!text || text.replace(/\s+/g, "").length < 20) {
164
165
  await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
165
166
  return;
166
167
  }
167
168
  }
168
- const extraction = await structureDocument(ports.model, row.name, mime, text);
169
+ const extraction = await structureDocument(ports.model, row.name, mime, text, ports.answerModel ?? MODELS.member);
169
170
  // the lane chunk: the summary leads, the verbatim text carries the
170
171
  // rest — the federation cites THIS document's content
171
172
  const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
@@ -207,13 +208,13 @@ function extractKind(fields: Record<string, string>): string {
207
208
  return fields.kind || "other";
208
209
  }
209
210
 
210
- async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Array): Promise<string> {
211
+ async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Array, modelId: string): Promise<string> {
211
212
  let binary = "";
212
213
  const CHUNK = 0x8000;
213
214
  for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
214
215
  const dataUrl = `data:${mime};base64,${btoa(binary)}`;
215
216
  const res = await model.run({
216
- model: MODELS.member,
217
+ model: modelId,
217
218
  messages: [
218
219
  { role: "system", content: "Transcribe everything you can read in this document image — certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
219
220
  { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] },
@@ -227,9 +228,9 @@ async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Ar
227
228
 
228
229
  /** One structuring call: classify + typed fields + a retrieval summary.
229
230
  * The response's JSON object is taken; prose around it is ignored. */
230
- async function structureDocument(model: ModelRunner, name: string, mime: string, text: string): Promise<Extraction> {
231
+ async function structureDocument(model: ModelRunner, name: string, mime: string, text: string, modelId: string): Promise<Extraction> {
231
232
  const res = await model.run({
232
- model: MODELS.member,
233
+ model: modelId,
233
234
  messages: [
234
235
  { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {…short typed fields…}, "summary": "one paragraph a retrieval engine can answer from"}. Certificates carry certificate numbers (like R60/2021-XX1-24.01), holders, models, issue dates. Test reports carry measured values, uncertainties, instruments, clause references. Fields use snake_case names, values verbatim from the text. Never invent a value the text does not carry.` },
235
236
  { role: "user", content: `Document name: ${name}\nFormat: ${mime}\n\nText:\n${text.slice(0, 12000)}` },