@konneal/engine 0.2.184 → 0.2.186

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.
@@ -0,0 +1,16 @@
1
+ import {
2
+ handleAsk
3
+ } from "./chunk-PLONBTNM.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-BMODSEKT.js";
6
+ import "./chunk-5ISPTV5G.js";
7
+ import "./chunk-BAOKHV2D.js";
8
+ import "./chunk-TLPUJMAF.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-MZQEI4VJ.js";
11
+ import "./chunk-IZ3GSYMD.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-YGQCVPX6.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  embed,
3
3
  rerank
4
- } from "./chunk-7RZ2D64X.js";
4
+ } from "./chunk-BAOKHV2D.js";
5
5
  import {
6
6
  bubbleConfirmPage,
7
7
  isAllowedBubbleOrigin
8
- } from "./chunk-XMUG75ZV.js";
8
+ } from "./chunk-TLPUJMAF.js";
9
9
  import {
10
10
  DATASETS,
11
11
  LIMITS,
@@ -15,7 +15,7 @@ import {
15
15
  processExpansion,
16
16
  sha256Hex,
17
17
  today
18
- } from "./chunk-QYTCQIA6.js";
18
+ } from "./chunk-IZ3GSYMD.js";
19
19
  import {
20
20
  P
21
21
  } from "./chunk-3FYJM7LH.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answerEffort,
3
3
  effortBudget
4
- } from "./chunk-QYTCQIA6.js";
4
+ } from "./chunk-IZ3GSYMD.js";
5
5
 
6
6
  // workers/worker_public/src/ai.ts
7
7
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  embed
3
- } from "./chunk-7RZ2D64X.js";
3
+ } from "./chunk-BAOKHV2D.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-5HCVX34C.js";
6
+ } from "./chunk-MZQEI4VJ.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-QYTCQIA6.js";
9
+ } from "./chunk-IZ3GSYMD.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -43,6 +43,7 @@ var MODELS = {
43
43
  // cross-encoder prunes, listwise orders jointly)
44
44
  listwise: "@cf/zai-org/glm-4.7-flash",
45
45
  // deep-research loop (G10): bounded agentic iterations, members-only
46
+ escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
46
47
  research: "@cf/zai-org/glm-5.3-flash",
47
48
  // speculative draft-verify (TODO.sota/02 row 2): the strong verifier
48
49
  // over the cheap drafts — the research-tier model verifies; the drafter
@@ -183,6 +184,7 @@ var THRESHOLDS = {
183
184
  function processExpansion() {
184
185
  return P().retrieval.process_expansion;
185
186
  }
187
+ var ESCALATION_DAILY_DEFAULT = 10;
186
188
  function roleModel(env, role) {
187
189
  const ov = env[`${role.toUpperCase()}_MODEL`];
188
190
  return typeof ov === "string" && ov.startsWith("@cf/") ? ov : MODELS[role];
@@ -247,6 +249,7 @@ export {
247
249
  LIMITS,
248
250
  THRESHOLDS,
249
251
  processExpansion,
252
+ ESCALATION_DAILY_DEFAULT,
250
253
  roleModel,
251
254
  answerEffort,
252
255
  effortBudget,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-QYTCQIA6.js";
4
+ } from "./chunk-IZ3GSYMD.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-XO26UIFH.js";
36
+ } from "./chunk-BMODSEKT.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -76,18 +76,18 @@ import {
76
76
  tokenBudget,
77
77
  understandQuery,
78
78
  usageTotal
79
- } from "./chunk-XTWH3PS6.js";
79
+ } from "./chunk-5ISPTV5G.js";
80
80
  import {
81
81
  embed,
82
82
  generateOnce
83
- } from "./chunk-7RZ2D64X.js";
83
+ } from "./chunk-BAOKHV2D.js";
84
84
  import {
85
85
  corsHeaders,
86
86
  err,
87
87
  json,
88
88
  readJson,
89
89
  validateQuery
90
- } from "./chunk-XMUG75ZV.js";
90
+ } from "./chunk-TLPUJMAF.js";
91
91
  import {
92
92
  cacheableAnswer,
93
93
  canonicalRefusal,
@@ -100,8 +100,9 @@ import {
100
100
  requestSalt,
101
101
  resolveRequestScope,
102
102
  standardKeysFrom
103
- } from "./chunk-5HCVX34C.js";
103
+ } from "./chunk-MZQEI4VJ.js";
104
104
  import {
105
+ ESCALATION_DAILY_DEFAULT,
105
106
  LIMITS,
106
107
  MODELS,
107
108
  THRESHOLDS,
@@ -111,12 +112,13 @@ import {
111
112
  requestEffort,
112
113
  roleModel,
113
114
  sha256Hex
114
- } from "./chunk-QYTCQIA6.js";
115
+ } from "./chunk-IZ3GSYMD.js";
115
116
  import {
116
117
  P
117
118
  } from "./chunk-3FYJM7LH.js";
118
119
  import {
119
120
  cfModelRunner,
121
+ cfStore,
120
122
  cfVectorIndex,
121
123
  portModelRunner,
122
124
  portStore
@@ -1518,7 +1520,7 @@ function matchAnswers(mode, requirements, answers, metBand, refuteBand) {
1518
1520
  items.push({
1519
1521
  text: r.text,
1520
1522
  clause: r.clause,
1521
- band: mode === "check" ? bandFor(probability, metBand, refuteBand) : "met",
1523
+ band: mode === "check" ? bandFor(probability, metBand, refuteBand) : null,
1522
1524
  probability: Math.round(probability * 100) / 100
1523
1525
  });
1524
1526
  });
@@ -1530,10 +1532,11 @@ function assembleSection(mode, items) {
1530
1532
  if (!items.length) return "";
1531
1533
  const title = mode === "check" ? "Requirements check (automated)" : "Requirements (from the cited clauses)";
1532
1534
  const lines = items.map((it) => {
1533
- const mark = mode === "check" ? MARK[it.band] : "\u2022";
1535
+ const band = mode === "check" ? it.band : null;
1536
+ const mark = band ? MARK[band] : "\u2022";
1534
1537
  const clause = it.clause ? ` \u2014 ${it.clause}` : "";
1535
- const prob = mode === "check" ? ` (${Math.round(it.probability * 100)}%)` : "";
1536
- return `- ${mark} ${it.text}${clause}${prob}${mode === "check" ? ` \u2014 ${WORD[it.band]}` : ""}`;
1538
+ const prob = band ? ` (${Math.round(it.probability * 100)}%)` : "";
1539
+ return `- ${mark} ${it.text}${clause}${prob}${band ? ` \u2014 ${WORD[band]}` : ""}`;
1537
1540
  });
1538
1541
  return `
1539
1542
 
@@ -1629,7 +1632,7 @@ function telemetryDecisions(env, ctx, tier, queryHash, result, durationMs) {
1629
1632
  try {
1630
1633
  telemetry(env, ctx, tier, "ask-decisions", result ? result.gate.toFixed(2) : "0", !!result, result?.items.length ?? 0, queryHash, result?.mode ?? void 0, void 0, { durationMs });
1631
1634
  for (const it of result?.items ?? []) {
1632
- telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band, void 0, {});
1635
+ telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band ?? void 0, void 0, {});
1633
1636
  }
1634
1637
  } catch {
1635
1638
  }
@@ -1897,6 +1900,76 @@ async function deleteUserDocument(ports, sub, id) {
1897
1900
  await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
1898
1901
  return row;
1899
1902
  }
1903
+ async function memberDocFields(store, sub) {
1904
+ const res = await store.prepare("SELECT id, name, fields FROM user_documents WHERE owner_sub = ?1 AND status = 'ready' AND fields IS NOT NULL ORDER BY created_at DESC").bind(sub).all();
1905
+ const out = [];
1906
+ for (const r of res.results ?? []) {
1907
+ try {
1908
+ const parsed = JSON.parse(r.fields);
1909
+ const fields = {};
1910
+ for (const [k, v] of Object.entries(parsed)) {
1911
+ if (typeof v === "string" || typeof v === "number") fields[k] = String(v);
1912
+ }
1913
+ if (Object.keys(fields).length) out.push({ doc_id: r.id, name: r.name, fields });
1914
+ } catch {
1915
+ }
1916
+ }
1917
+ return out;
1918
+ }
1919
+ function fieldsAsText(docs) {
1920
+ return docs.map((d) => Object.entries(d.fields).map(([k, v]) => `${k.replace(/_/g, " ")}: ${v}`).join("; ")).join("\n");
1921
+ }
1922
+
1923
+ // workers/worker_public/src/escalation.ts
1924
+ async function assembleDocument(store, docidentifier, capChars, lang = "en") {
1925
+ const res = await store.prepare(
1926
+ `SELECT text, clause_anchor, status, language FROM chunks
1927
+ WHERE docidentifier = ?1 AND language = ?2 AND status = 'in-force'
1928
+ ORDER BY rowid`
1929
+ ).bind(docidentifier, lang).all();
1930
+ const rows = res.results ?? [];
1931
+ if (!rows.length) return null;
1932
+ const clauses = /* @__PURE__ */ new Set();
1933
+ const parts = [];
1934
+ let total = 0;
1935
+ let truncated = false;
1936
+ for (const r of rows) {
1937
+ const anchor = (r.clause_anchor || "").trim();
1938
+ if (anchor) {
1939
+ clauses.add(anchor);
1940
+ const segs = anchor.split(".");
1941
+ for (let i = 1; i < segs.length; i++) clauses.add(segs.slice(0, i).join("."));
1942
+ }
1943
+ if (total + r.text.length > capChars) {
1944
+ truncated = true;
1945
+ break;
1946
+ }
1947
+ parts.push(r.text);
1948
+ total += r.text.length;
1949
+ }
1950
+ if (!parts.length) return null;
1951
+ return { docidentifier, text: parts.join("\n\n"), clauses, truncated };
1952
+ }
1953
+ function verifyAnchors(answer, clauses) {
1954
+ const cited = /* @__PURE__ */ new Set();
1955
+ for (const m of answer.matchAll(/\b(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[1]);
1956
+ for (const m of answer.matchAll(/\b(\d{1,2}\.\d{1,2})\s?[–—-]\s?(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[2]);
1957
+ const missing = [];
1958
+ for (const c of cited) {
1959
+ if (!clauses.has(c) && ![...clauses].some((k) => k.startsWith(`${c}.`) || k === c)) missing.push(c);
1960
+ }
1961
+ return { ok: missing.length === 0, missing };
1962
+ }
1963
+ var escalationSystem = () => `You are ${P().publisher.name}, the answer service over legal-metrology publications. Answer the question using ONLY the publication text below. Cite the clause numbers you use. If the publication does not answer it, say so plainly.`;
1964
+ async function escalationAllowed(kv, bucketId, dailyCap, day) {
1965
+ if (dailyCap <= 0) return false;
1966
+ const n = Number(await kv.get(`esc:${day}:${bucketId}`) ?? "0");
1967
+ return n < dailyCap;
1968
+ }
1969
+ async function chargeEscalation(kv, bucketId, day) {
1970
+ const key = `esc:${day}:${bucketId}`;
1971
+ await kv.put(key, String(Number(await kv.get(key) ?? "0") + 1), { expirationTtl: 172800 });
1972
+ }
1900
1973
 
1901
1974
  // workers/worker_public/src/operations.ts
1902
1975
  function isOperationIntent(query) {
@@ -2661,6 +2734,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2661
2734
  const ops = await operationsLane(env.DB, q2.query);
2662
2735
  const registerOwns = !!register?.rows?.length;
2663
2736
  const registerCitation = registerOwns ? [{ docidentifier: `${P().publisher.name}-CS certificate register`, corpus: "register" }] : [];
2737
+ const escalationCitation = () => escalatedDoc ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }] : [];
2664
2738
  if (understanding?.intent === "conversational") {
2665
2739
  const queryHash2 = await sha256Hex(q2.query);
2666
2740
  const messages2 = [
@@ -2778,7 +2852,13 @@ ${summary}` }] : [],
2778
2852
  console.log("model plane: bound", boundModel.node_id, `[${boundModel.standard}]`, boundModel.clause?.urn ?? "no-clause", boundModel.gated ? "(gated: license)" : "");
2779
2853
  }
2780
2854
  const modelNote = boundModel && !boundModel.gated ? modelGroundingBlock(boundModel) : void 0;
2781
- let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? evaluate(boundModel.content, q2.query) : null;
2855
+ const memberDocs = member && !ablate?.noVerdict ? await memberDocFields(cfStore(env.DB), member.sub).catch(() => []) : [];
2856
+ const memberFieldsText = memberDocs.length ? fieldsAsText(memberDocs) : "";
2857
+ const statedText = memberFieldsText ? `${q2.query}
2858
+ ${memberFieldsText}` : q2.query;
2859
+ const memberDocNote = memberDocs.length ? `MEMBER DOCUMENT DATA \u2014 these are the QUESTION-ASKER'S OWN recorded values from their imported documents; treat them as the stated state for any conformance check, and cite the document name when you use them:
2860
+ ${memberFieldsText}` : void 0;
2861
+ let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? evaluate(boundModel.content, statedText) : null;
2782
2862
  if (machineVerdict === null && boundModel && !boundModel.gated) {
2783
2863
  try {
2784
2864
  const unitTokens = [...new Set(Object.values(extractParamsWithUnits(q2.query, symbolsIn(extractChecks(boundModel.content))).units).map((u) => u.toLowerCase()))];
@@ -2811,7 +2891,7 @@ ${summary}` }] : [],
2811
2891
  if (!machineVerdict && !boundModel && !ablate?.noVerdict && P().publisher.features?.model_plane) {
2812
2892
  const ql = q2.query.toLowerCase();
2813
2893
  const severityWord = /\b(severity|test|valid|tolerance|condition|within)\b/.test(ql);
2814
- const stated = quantitiesIn(q2.query);
2894
+ const stated = quantitiesIn(statedText);
2815
2895
  if (severityWord && Object.keys(stated).length >= 1) {
2816
2896
  const docNum = modelDocHint?.doc_number;
2817
2897
  const rows = await modelNodeRows("condition_set", docNum);
@@ -3059,17 +3139,46 @@ Answer account questions from these records ONLY: name the record when you use i
3059
3139
  text: `${m.anchor} \u2014 ${m.text}`
3060
3140
  }));
3061
3141
  const passagePool = registerOwns ? [...opsHits, ...hits].filter((h) => !!h.metadata.cert_holder) : [...opsHits, ...hits];
3062
- const { messages, usedHits } = buildMessages(
3142
+ const built = buildMessages(
3063
3143
  q2.query,
3064
3144
  passagePool,
3065
3145
  q2.lang,
3066
3146
  keptHistory,
3067
3147
  // stage-extracted graph facts (GraphRAG) ride the same note channel
3068
- [ops.note, processNote, eNote, regNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0,
3148
+ [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0,
3069
3149
  summary,
3070
3150
  budget,
3071
3151
  ablate?.noCompress !== true
3072
3152
  );
3153
+ let escalateAnswer = false;
3154
+ let escalatedDoc = null;
3155
+ let messages = built.messages;
3156
+ let usedHits = built.usedHits;
3157
+ const escalateWanted = crag.grade === "weak" && !crag.corrective?.accepted;
3158
+ if (escalateWanted && understanding?.docidentifier && (tier === "member" || tier === "key") && !withImage) {
3159
+ const day = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
3160
+ const bucket = tier === "key" ? `key:${key.id}` : `sub:${member.sub}`;
3161
+ if (await escalationAllowed(env.CACHE, bucket, num(env, "ESCALATION_DAILY", ESCALATION_DAILY_DEFAULT), day)) {
3162
+ const doc = await assembleDocument(cfStore(env.DB), understanding.docidentifier, 9e5, q2.lang || "en").catch(() => null);
3163
+ if (doc && doc.text.length > 2e4) {
3164
+ const history2 = keptHistory.slice(-6);
3165
+ messages = [
3166
+ { role: "system", content: escalationSystem() },
3167
+ ...history2,
3168
+ { role: "user", content: `Question: ${q2.query}
3169
+
3170
+ Publication ${doc.docidentifier}${doc.truncated ? " (truncated)" : ""}:
3171
+
3172
+ ${doc.text}` }
3173
+ ];
3174
+ usedHits = [];
3175
+ escalatedDoc = doc;
3176
+ escalateAnswer = true;
3177
+ await chargeEscalation(env.CACHE, bucket, day);
3178
+ console.log("escalation: answering from the whole", doc.docidentifier, `(${doc.text.length} chars)`);
3179
+ }
3180
+ }
3181
+ }
3073
3182
  const decisionPromise = decisionsArmed && decisionsGatePromise ? decisionsGatePromise.then((g) => g != null && g >= THRESHOLDS.decisionsGateMin ? runDecisionPass(env, {
3074
3183
  question: q2.query,
3075
3184
  gate: g,
@@ -3130,7 +3239,7 @@ Answer account questions from these records ONLY: name the record when you use i
3130
3239
  console.log("user image attached to generation");
3131
3240
  }
3132
3241
  const queryHash = await sha256Hex(q2.query);
3133
- const cites = [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3242
+ const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3134
3243
  if (live2) {
3135
3244
  const stream = await generateStream(env, model, messages, routeEffort(routed.route));
3136
3245
  if (stream) {
@@ -3213,6 +3322,14 @@ Answer account questions from these records ONLY: name the record when you use i
3213
3322
  }
3214
3323
  }
3215
3324
  }
3325
+ if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
3326
+ const verdict = verifyAnchors(full, escalatedDoc.clauses);
3327
+ if (!verdict.ok) {
3328
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "\u2014 refusing honestly");
3329
+ full = refusalAnswer();
3330
+ send({ type: "token", v: refusalAnswer() });
3331
+ }
3332
+ }
3216
3333
  let canonical0 = exciseMisplacedPin(canonicalRefusal(full.replace(/^TOOL [a-z_.]+.*$\n?/gm, "").replace(/^\n+/, ""), refusalScope(answerCites(full))), answerCites(full));
3217
3334
  const c2 = canonical0.includes(refusalAnswer()) ? { text: canonical0, blocks: [], dropped: [] } : await contractV2(env.DB, canonical0, usedHits);
3218
3335
  let streamedCompletionBlocks = [];
@@ -3419,7 +3536,14 @@ Answer account questions from these records ONLY: name the record when you use i
3419
3536
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q2.lang, void 0, telemetryMeta());
3420
3537
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
3421
3538
  }
3422
- const finalCites = [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(used)] : citations(used)];
3539
+ const finalCites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(used)] : citations(used)];
3540
+ if (escalateAnswer && escalatedDoc && !answer.includes(refusalAnswer())) {
3541
+ const verdict = verifyAnchors(answer, escalatedDoc.clauses);
3542
+ if (!verdict.ok) {
3543
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "\u2014 refusing honestly");
3544
+ answer = canonicalRefusal(refusalAnswer(), refusalScope(false));
3545
+ }
3546
+ }
3423
3547
  const c2ns = answer.includes(refusalAnswer()) ? { text: answer, blocks: [], dropped: [] } : await contractV2(env.DB, answer, used);
3424
3548
  answer = c2ns.text;
3425
3549
  const finalAnchors = answer.includes(refusalAnswer()) ? { total: 0, violations: [] } : checkQuoteAnchors(answer, used.map((h) => h.text));
@@ -6,24 +6,24 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-XTWH3PS6.js";
9
+ } from "./chunk-5ISPTV5G.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-XMUG75ZV.js";
16
+ } from "./chunk-TLPUJMAF.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-5HCVX34C.js";
20
+ } from "./chunk-MZQEI4VJ.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  sha256Hex
26
- } from "./chunk-QYTCQIA6.js";
26
+ } from "./chunk-IZ3GSYMD.js";
27
27
  import {
28
28
  portModelRunner
29
29
  } from "./chunk-YGQCVPX6.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-QYTCQIA6.js";
4
+ } from "./chunk-IZ3GSYMD.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
package/dist/config.d.ts CHANGED
@@ -14,6 +14,7 @@ export declare const MODELS: {
14
14
  readonly grader: "@cf/deepseek-ai/deepseek-v4-flash-0731";
15
15
  readonly enrich: "@cf/deepseek-ai/deepseek-v4-pro-0813";
16
16
  readonly listwise: "@cf/zai-org/glm-4.7-flash";
17
+ readonly escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017";
17
18
  readonly research: "@cf/zai-org/glm-5.3-flash";
18
19
  readonly verifier: "@cf/zai-org/glm-5.2";
19
20
  };
@@ -136,6 +137,10 @@ export declare function processExpansion(): string;
136
137
  /** Per-deployment model override: <ROLE>_MODEL (e.g. UNDERSTAND_MODEL)
137
138
  * replaces the pinned default for that role. Ops lever for A/B-ing a
138
139
  * role's model without a code change; absent/invalid = the default. */
140
+ /** The escalation's daily per-bucket cap (TODO.sota/21): the whole-doc
141
+ * answer costs ~200–250k input tokens, so the spend is capped hard
142
+ * and measured (route "ask-escalation"). */
143
+ export declare const ESCALATION_DAILY_DEFAULT = 10;
139
144
  export declare function roleModel(env: any, role: keyof typeof MODELS): string;
140
145
  /** Per-deployment effort override for the answer lane (ANSWER_EFFORT).
141
146
  * The effort–accuracy curve is front-loaded (DeepSeek-V4.1-Flash report,
@@ -5,7 +5,11 @@ export interface DerivedRequirement {
5
5
  export interface DecisionItem {
6
6
  text: string;
7
7
  clause: string;
8
- band: "met" | "not-met" | "unclear";
8
+ /** null in LIST mode: a requirements inventory makes no conformance
9
+ * claim, so met/not-met/unclear would all lie (the calibration
10
+ * reader's first week caught the hardcoded "met" this replaces —
11
+ * 2026-11-05, TODO.decisions/03). */
12
+ band: "met" | "not-met" | "unclear" | null;
9
13
  probability: number;
10
14
  }
11
15
  export type DecisionMode = "check" | "list";
@@ -0,0 +1,27 @@
1
+ import type { StoreQuery } from "./ports/store.ts";
2
+ export interface AssembledDocument {
3
+ docidentifier: string;
4
+ text: string;
5
+ clauses: Set<string>;
6
+ truncated: boolean;
7
+ }
8
+ /** Assemble the WHOLE document from the chunks table in reading order
9
+ * (rowid preserves the parse's order — TODO.impl/02's invariant),
10
+ * capped. The clause set is every clause anchor the document carries,
11
+ * plus their dotted prefixes (a citation of 5.3.2 verifies when the
12
+ * document carries 5.3.2 itself or a longer clause beneath it). */
13
+ export declare function assembleDocument(store: StoreQuery, docidentifier: string, capChars: number, lang?: string): Promise<AssembledDocument | null>;
14
+ /** The clause-like tokens the ANSWER references (d.d and d.d.d shapes,
15
+ * including ranges "5.3–5.5"). Every token must resolve in the
16
+ * document's clause set — a cited clause the document does not carry
17
+ * makes the whole answer unverifiable. */
18
+ export declare function verifyAnchors(answer: string, clauses: Set<string>): {
19
+ ok: boolean;
20
+ missing: string[];
21
+ };
22
+ /** The system prompt reads the publisher from the profile — the
23
+ * publisher-leak lint's law (a hardcoded name is a leak). */
24
+ export declare const escalationSystem: () => string;
25
+ /** The escalation's daily budget: a per-bucket KV counter. */
26
+ export declare function escalationAllowed(kv: any, bucketId: string, dailyCap: number, day: string): Promise<boolean>;
27
+ export declare function chargeEscalation(kv: any, bucketId: string, day: string): Promise<void>;
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleSearch
3
+ } from "./chunk-TKGBLDLK.js";
4
+ import "./chunk-5ISPTV5G.js";
5
+ import "./chunk-BAOKHV2D.js";
6
+ import "./chunk-TLPUJMAF.js";
7
+ import "./chunk-ETLSWSZ7.js";
8
+ import "./chunk-MZQEI4VJ.js";
9
+ import "./chunk-IZ3GSYMD.js";
10
+ import "./chunk-3FYJM7LH.js";
11
+ import "./chunk-YGQCVPX6.js";
12
+ export {
13
+ handleSearch
14
+ };
@@ -4,10 +4,10 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-XO26UIFH.js";
8
- import "./chunk-7RZ2D64X.js";
9
- import "./chunk-5HCVX34C.js";
10
- import "./chunk-QYTCQIA6.js";
7
+ } from "./chunk-BMODSEKT.js";
8
+ import "./chunk-BAOKHV2D.js";
9
+ import "./chunk-MZQEI4VJ.js";
10
+ import "./chunk-IZ3GSYMD.js";
11
11
  import "./chunk-3FYJM7LH.js";
12
12
  import "./chunk-YGQCVPX6.js";
13
13
  export {
@@ -70,3 +70,21 @@ export declare function queryUserLane(model: ModelRunner, lane: VectorIndex, sub
70
70
  /** Deletion is immediate and total: the R2 object, the lane vectors,
71
71
  * the row. The caller has already checked ownership. */
72
72
  export declare function deleteUserDocument(ports: UserDocumentPorts, sub: string, id: string): Promise<UserDocumentRow | null>;
73
+ /** The member's own recorded values, ready to serve as the STATED STATE
74
+ * of a check (TODO.sota/20's "the verdict engine evaluates THEIR
75
+ * recorded values"): the ready documents' extracted fields, verbatim.
76
+ * The verdict extraction parses numbers-with-units out of these the
77
+ * same way it parses the question's own phrases. */
78
+ export declare function memberDocFields(store: StoreQuery, sub: string): Promise<{
79
+ doc_id: string;
80
+ name: string;
81
+ fields: Record<string, string>;
82
+ }[]>;
83
+ /** The fields' flat text for the stated-state extraction: one line per
84
+ * field, keyed — numbers-with-units parse from this the same way the
85
+ * question's own phrases do. */
86
+ export declare function fieldsAsText(docs: {
87
+ doc_id: string;
88
+ name: string;
89
+ fields: Record<string, string>;
90
+ }[]): string;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  authenticate
3
- } from "../../chunk-XMUG75ZV.js";
4
- import "../../chunk-QYTCQIA6.js";
3
+ } from "../../chunk-TLPUJMAF.js";
4
+ import "../../chunk-IZ3GSYMD.js";
5
5
  import {
6
6
  P,
7
7
  setProfile
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  DATASETS,
3
+ ESCALATION_DAILY_DEFAULT,
3
4
  LIMITS,
4
5
  MODELS,
5
6
  STARTERS,
@@ -16,10 +17,11 @@ import {
16
17
  roleModel,
17
18
  sha256Hex,
18
19
  today
19
- } from "../../chunk-QYTCQIA6.js";
20
+ } from "../../chunk-IZ3GSYMD.js";
20
21
  import "../../chunk-3FYJM7LH.js";
21
22
  export {
22
23
  DATASETS,
24
+ ESCALATION_DAILY_DEFAULT,
23
25
  LIMITS,
24
26
  MODELS,
25
27
  STARTERS,
@@ -9,16 +9,16 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-ZFOODZWO.js";
12
+ } from "../../chunk-PLONBTNM.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
16
16
  bindModelNode,
17
17
  modelGroundingBlock
18
- } from "../../chunk-XO26UIFH.js";
18
+ } from "../../chunk-BMODSEKT.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-YQQ3W5CE.js";
21
+ } from "../../chunk-TKGBLDLK.js";
22
22
  import {
23
23
  buildMessages,
24
24
  citations,
@@ -43,11 +43,11 @@ import {
43
43
  sessionFrom,
44
44
  telemetry,
45
45
  understandQuery
46
- } from "../../chunk-XTWH3PS6.js";
46
+ } from "../../chunk-5ISPTV5G.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
50
- } from "../../chunk-7RZ2D64X.js";
50
+ } from "../../chunk-BAOKHV2D.js";
51
51
  import {
52
52
  authenticate,
53
53
  corsHeaders,
@@ -56,14 +56,14 @@ import {
56
56
  readJson,
57
57
  validateQuery,
58
58
  withCors
59
- } from "../../chunk-XMUG75ZV.js";
59
+ } from "../../chunk-TLPUJMAF.js";
60
60
  import {
61
61
  canonicalRefusal
62
62
  } from "../../chunk-ETLSWSZ7.js";
63
63
  import {
64
64
  entitlementScope,
65
65
  standardKeysFrom
66
- } from "../../chunk-5HCVX34C.js";
66
+ } from "../../chunk-MZQEI4VJ.js";
67
67
  import {
68
68
  LIMITS,
69
69
  MODELS,
@@ -74,7 +74,7 @@ import {
74
74
  roleModel,
75
75
  sha256Hex,
76
76
  today
77
- } from "../../chunk-QYTCQIA6.js";
77
+ } from "../../chunk-IZ3GSYMD.js";
78
78
  import {
79
79
  P,
80
80
  setProfile
@@ -1183,13 +1183,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1183
1183
  // stream:false forces the JSON lane (anon defaults to SSE)
1184
1184
  body: JSON.stringify({ ...args, stream: false })
1185
1185
  });
1186
- const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-BTH6YAOB.js");
1186
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-VMZSXLXM.js");
1187
1187
  let payload;
1188
1188
  if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
1189
1189
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1190
1190
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1191
1191
  } else {
1192
- const res = name === "ask" ? await (await import("../../ask-7DFXT4DJ.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-4FWS4HVI.js")).handleSearch(env, ctx, inner, tier, key);
1192
+ const res = name === "ask" ? await (await import("../../ask-CTYDXEQN.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-5QSGBDBI.js")).handleSearch(env, ctx, inner, tier, key);
1193
1193
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1194
1194
  }
1195
1195
  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 });
@@ -4,8 +4,8 @@ import {
4
4
  requestSalt,
5
5
  resolveRequestScope,
6
6
  standardKeysFrom
7
- } from "../../chunk-5HCVX34C.js";
8
- import "../../chunk-QYTCQIA6.js";
7
+ } from "../../chunk-MZQEI4VJ.js";
8
+ import "../../chunk-IZ3GSYMD.js";
9
9
  import "../../chunk-3FYJM7LH.js";
10
10
  export {
11
11
  entitlementScope,
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.184",
30
+ "version": "0.2.186",
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",
@@ -47,8 +47,10 @@ import { json, err, corsHeaders, readJson, validateQuery, type ApiKey } from "./
47
47
  import { chargeTokens, checkQuota, clientIp, creditBudget, creditEstimate, estimateTokens, telemetry, tokenBudget, usageTotal } from "./quota";
48
48
  import { graphExpand, editionNote } from "./graph";
49
49
  import { registerNote, searchRegister, certificateLinks, registerAggregateIntent, registerAggregate, aggregateNote, aggregateBlock, queryFamily, registerBypassesCache } from "./certificates";
50
- import { queryUserLane } from "./userDocuments";
51
- import { cfModelRunner, cfVectorIndex } from "./ports/cloudflare/adapters";
50
+ import { queryUserLane, memberDocFields, fieldsAsText } from "./userDocuments";
51
+ import { assembleDocument, verifyAnchors, escalationAllowed, chargeEscalation, escalationSystem } from "./escalation";
52
+ import { ESCALATION_DAILY_DEFAULT } from "./config";
53
+ import { cfModelRunner, cfStore, cfVectorIndex } from "./ports/cloudflare/adapters";
52
54
  import { TOOL_DECLARATION, parseToolCall, runTool, toolNote } from "./tools";
53
55
  import { operationsLane } from "./operations.ts";
54
56
  import { extractNameplate, nameplateRegisterQuery } from "./nameplate.ts";
@@ -938,6 +940,10 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
938
940
  const registerCitation = registerOwns
939
941
  ? [{ docidentifier: `${P().publisher.name}-CS certificate register`, corpus: "register" }]
940
942
  : [];
943
+ const escalationCitation = () =>
944
+ escalatedDoc
945
+ ? [{ docidentifier: `${escalatedDoc.docidentifier} (the complete publication)`, corpus: "escalated" }]
946
+ : [];
941
947
 
942
948
  // Conversational route, decided by query UNDERSTANDING (any language, any
943
949
  // phrasing) — not string matching. No retrieval: nothing in the corpus
@@ -1114,7 +1120,18 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1114
1120
  // the worker EXECUTES the bound node's machine checks against the
1115
1121
  // question's stated values; the model narrates the computed verdict
1116
1122
  // and the verdict BLOCK is server-built — data, never generated prose
1117
- let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? machineEvaluate(boundModel.content, q.query) : null;
1123
+ // The member's own imported values are the STATED STATE for their
1124
+ // checks (TODO.sota/20: "compare my recorded errors against R 60
1125
+ // Table 4"): fetched directly (the verdict paths precede retrieval),
1126
+ // composed once, and fed to BOTH the machine evaluation and the note
1127
+ // channel. Member-gated, ready documents only.
1128
+ const memberDocs = member && !ablate?.noVerdict ? await memberDocFields(cfStore(env.DB), member.sub).catch(() => []) : [];
1129
+ const memberFieldsText = memberDocs.length ? fieldsAsText(memberDocs) : "";
1130
+ const statedText = memberFieldsText ? `${q.query}\n${memberFieldsText}` : q.query;
1131
+ const memberDocNote = memberDocs.length
1132
+ ? `MEMBER DOCUMENT DATA — these are the QUESTION-ASKER'S OWN recorded values from their imported documents; treat them as the stated state for any conformance check, and cite the document name when you use them:\n${memberFieldsText}`
1133
+ : undefined;
1134
+ let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? machineEvaluate(boundModel.content, statedText) : null;
1118
1135
  if (machineVerdict === null && boundModel && !boundModel.gated) {
1119
1136
  // unit semantics (TODO.sota/04): the stated values' units reach the
1120
1137
  // units register for their dimensions; a comparison mixing
@@ -1165,7 +1182,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1165
1182
  if (!machineVerdict && !boundModel && !ablate?.noVerdict && P().publisher.features?.model_plane) {
1166
1183
  const ql = q.query.toLowerCase();
1167
1184
  const severityWord = /\b(severity|test|valid|tolerance|condition|within)\b/.test(ql);
1168
- const stated = quantitiesIn(q.query);
1185
+ const stated = quantitiesIn(statedText);
1169
1186
  if (severityWord && Object.keys(stated).length >= 1) {
1170
1187
  const docNum = modelDocHint?.doc_number;
1171
1188
  // the doc number joins the STANDARD id (iec-60068-2-78), which is
@@ -1537,17 +1554,54 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1537
1554
  const passagePool = registerOwns
1538
1555
  ? [...opsHits, ...hits].filter((h) => !!(h.metadata as any).cert_holder)
1539
1556
  : [...opsHits, ...hits];
1540
- const { messages, usedHits } = buildMessages(
1557
+ const built = buildMessages(
1541
1558
  q.query,
1542
1559
  passagePool,
1543
1560
  q.lang,
1544
1561
  keptHistory,
1545
1562
  // stage-extracted graph facts (GraphRAG) ride the same note channel
1546
- [ops.note, processNote, eNote, regNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...(retrieved.notes ?? [])].filter(Boolean).join("\n") || undefined,
1563
+ [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,
1547
1564
  summary,
1548
1565
  budget,
1549
1566
  ablate?.noCompress !== true,
1550
1567
  );
1568
+ // The selective brute-force escalation (TODO.sota/21): the compressed
1569
+ // pipeline graded weak on a DOCUMENT-SCOPED question and the
1570
+ // corrective retry did not recover — answer from the WHOLE publication
1571
+ // uncut on the 1M-ctx model. The measured trade (18.1): brute force
1572
+ // 100% vs the window's ~92.9% at ~1/20th... reversed: the escalation
1573
+ // BUYS ~7pp at ~250k tokens, member/key only, daily-capped. One
1574
+ // message swap here feeds both delivery lanes.
1575
+ let escalateAnswer = false;
1576
+ let escalatedDoc: Awaited<ReturnType<typeof assembleDocument>> | null = null;
1577
+ let messages = built.messages;
1578
+ let usedHits = built.usedHits;
1579
+ const escalateWanted = crag.grade === "weak" && !crag.corrective?.accepted;
1580
+ if (
1581
+ escalateWanted &&
1582
+ understanding?.docidentifier &&
1583
+ (tier === "member" || tier === "key") &&
1584
+ !withImage
1585
+ ) {
1586
+ const day = new Date().toISOString().slice(0, 10);
1587
+ const bucket = tier === "key" ? `key:${key!.id}` : `sub:${member!.sub}`;
1588
+ if (await escalationAllowed(env.CACHE, bucket, num(env as any, "ESCALATION_DAILY", ESCALATION_DAILY_DEFAULT), day)) {
1589
+ const doc = await assembleDocument(cfStore(env.DB), understanding.docidentifier, 900_000, q.lang || "en").catch(() => null);
1590
+ if (doc && doc.text.length > 20_000) {
1591
+ const history = keptHistory.slice(-6);
1592
+ messages = [
1593
+ { role: "system", content: escalationSystem() },
1594
+ ...history,
1595
+ { role: "user", content: `Question: ${q.query}\n\nPublication ${doc.docidentifier}${doc.truncated ? " (truncated)" : ""}:\n\n${doc.text}` },
1596
+ ];
1597
+ usedHits = [];
1598
+ escalatedDoc = doc;
1599
+ escalateAnswer = true;
1600
+ await chargeEscalation(env.CACHE, bucket, day);
1601
+ console.log("escalation: answering from the whole", doc.docidentifier, `(${doc.text.length} chars)`);
1602
+ }
1603
+ }
1604
+ }
1551
1605
  // the decision pass (TODO.decisions/01): starts here so its calls run
1552
1606
  // concurrently with generation — the checklist section arrives the
1553
1607
  // moment the model's last token lands, never delaying the answer
@@ -1664,7 +1718,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1664
1718
  // provenance — ahead of the prose passages. The register rides first
1665
1719
  // when it owns the answer (the standing citation the aggregate path
1666
1720
  // has always attached).
1667
- const cites = [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1721
+ const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1668
1722
 
1669
1723
  if (live) {
1670
1724
  const stream = await generateStream(env, model, messages, routeEffort(routed.route));
@@ -1762,6 +1816,17 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1762
1816
  }
1763
1817
  // the misplaced-pin wall rides the streamed path too: a
1764
1818
  // CITED stream is not a refusal
1819
+ // the escalation's citation contract (TODO.sota/21): every
1820
+ // clause the answer references must exist in the assembled
1821
+ // document — an unverifiable escalation IS the honest refusal
1822
+ if (escalateAnswer && escalatedDoc && !full.includes(refusalAnswer())) {
1823
+ const verdict = verifyAnchors(full, escalatedDoc.clauses);
1824
+ if (!verdict.ok) {
1825
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "— refusing honestly");
1826
+ full = refusalAnswer();
1827
+ send({ type: "token", v: refusalAnswer() });
1828
+ }
1829
+ }
1765
1830
  let canonical0 = exciseMisplacedPin(canonicalRefusal(full.replace(/^TOOL [a-z_.]+.*$\n?/gm, "").replace(/^\n+/, ""), refusalScope(answerCites(full))), answerCites(full));
1766
1831
  // answer contract v2: validate [[u:]] refs, resolve typed blocks
1767
1832
  const c2 = canonical0.includes(refusalAnswer())
@@ -2064,7 +2129,15 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2064
2129
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q.lang, undefined, telemetryMeta());
2065
2130
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
2066
2131
  }
2067
- const finalCites = [...registerCitation, ...(boundModel ? [modelCitation(boundModel!), ...citations(used)] : citations(used))];
2132
+ const finalCites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel!), ...citations(used)] : citations(used))];
2133
+ // the escalation's citation contract (the JSON lane's half)
2134
+ if (escalateAnswer && escalatedDoc && !answer!.includes(refusalAnswer())) {
2135
+ const verdict = verifyAnchors(answer!, escalatedDoc.clauses);
2136
+ if (!verdict.ok) {
2137
+ console.log("escalation: unverifiable clause citations", verdict.missing.join(","), "— refusing honestly");
2138
+ answer = canonicalRefusal(refusalAnswer(), refusalScope(false));
2139
+ }
2140
+ }
2068
2141
  const c2ns = answer!.includes(refusalAnswer())
2069
2142
  ? { text: answer, blocks: [] as Awaited<ReturnType<typeof contractV2>>["blocks"], dropped: [] as string[] }
2070
2143
  : await contractV2(env.DB, answer!, used);
@@ -38,6 +38,7 @@ export const MODELS = {
38
38
  // cross-encoder prunes, listwise orders jointly)
39
39
  listwise: "@cf/zai-org/glm-4.7-flash",
40
40
  // deep-research loop (G10): bounded agentic iterations, members-only
41
+ escalation: "@cf/deepseek-ai/deepseek-v4.1-flash-1017",
41
42
  research: "@cf/zai-org/glm-5.3-flash",
42
43
  // speculative draft-verify (TODO.sota/02 row 2): the strong verifier
43
44
  // over the cheap drafts — the research-tier model verifies; the drafter
@@ -187,6 +188,11 @@ export function processExpansion(): string {
187
188
  /** Per-deployment model override: <ROLE>_MODEL (e.g. UNDERSTAND_MODEL)
188
189
  * replaces the pinned default for that role. Ops lever for A/B-ing a
189
190
  * role's model without a code change; absent/invalid = the default. */
191
+ /** The escalation's daily per-bucket cap (TODO.sota/21): the whole-doc
192
+ * answer costs ~200–250k input tokens, so the spend is capped hard
193
+ * and measured (route "ask-escalation"). */
194
+ export const ESCALATION_DAILY_DEFAULT = 10;
195
+
190
196
  export function roleModel(env: any, role: keyof typeof MODELS): string {
191
197
  const ov = env[`${role.toUpperCase()}_MODEL`];
192
198
  return typeof ov === "string" && ov.startsWith("@cf/") ? ov : MODELS[role];
@@ -147,7 +147,7 @@ export function telemetryDecisions(
147
147
  try {
148
148
  telemetry(env, ctx, tier, "ask-decisions", result ? result.gate.toFixed(2) : "0", !!result, result?.items.length ?? 0, queryHash, result?.mode ?? undefined, undefined, { durationMs });
149
149
  for (const it of result?.items ?? []) {
150
- telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band, undefined, {});
150
+ telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band ?? undefined, undefined, {});
151
151
  }
152
152
  } catch { /* telemetry never answers for the answer */ }
153
153
  }
@@ -13,7 +13,11 @@ export interface DerivedRequirement {
13
13
  export interface DecisionItem {
14
14
  text: string;
15
15
  clause: string;
16
- band: "met" | "not-met" | "unclear";
16
+ /** null in LIST mode: a requirements inventory makes no conformance
17
+ * claim, so met/not-met/unclear would all lie (the calibration
18
+ * reader's first week caught the hardcoded "met" this replaces —
19
+ * 2026-11-05, TODO.decisions/03). */
20
+ band: "met" | "not-met" | "unclear" | null;
17
21
  probability: number;
18
22
  }
19
23
 
@@ -123,15 +127,15 @@ export function matchAnswers(
123
127
  items.push({
124
128
  text: r.text,
125
129
  clause: r.clause,
126
- band: mode === "check" ? bandFor(probability, metBand, refuteBand) : "met",
130
+ band: mode === "check" ? bandFor(probability, metBand, refuteBand) : null,
127
131
  probability: Math.round(probability * 100) / 100,
128
132
  });
129
133
  });
130
134
  return items;
131
135
  }
132
136
 
133
- const MARK: Record<DecisionItem["band"], string> = { met: "✓", "not-met": "✗", unclear: "?" };
134
- const WORD: Record<DecisionItem["band"], string> = { met: "met", "not-met": "not met", unclear: "not clearly stated" };
137
+ const MARK: Record<Exclude<DecisionItem["band"], null>, string> = { met: "✓", "not-met": "✗", unclear: "?" };
138
+ const WORD: Record<Exclude<DecisionItem["band"], null>, string> = { met: "met", "not-met": "not met", unclear: "not clearly stated" };
135
139
 
136
140
  /** The deterministic checklist section appended to the answer. The
137
141
  * model never writes this — the server composes it from the decisions. */
@@ -139,10 +143,13 @@ export function assembleSection(mode: DecisionMode, items: DecisionItem[]): stri
139
143
  if (!items.length) return "";
140
144
  const title = mode === "check" ? "Requirements check (automated)" : "Requirements (from the cited clauses)";
141
145
  const lines = items.map((it) => {
142
- const mark = mode === "check" ? MARK[it.band] : "•";
146
+ // check mode guarantees a band (bandFor ran); list mode renders no
147
+ // mark, probability, or word at all
148
+ const band = mode === "check" ? it.band : null;
149
+ const mark = band ? MARK[band] : "•";
143
150
  const clause = it.clause ? ` — ${it.clause}` : "";
144
- const prob = mode === "check" ? ` (${Math.round(it.probability * 100)}%)` : "";
145
- return `- ${mark} ${it.text}${clause}${prob}${mode === "check" ? ` — ${WORD[it.band]}` : ""}`;
151
+ const prob = band ? ` (${Math.round(it.probability * 100)}%)` : "";
152
+ return `- ${mark} ${it.text}${clause}${prob}${band ? ` — ${WORD[band]}` : ""}`;
146
153
  });
147
154
  return `\n\n${title}:\n${lines.join("\n")}`;
148
155
  }
@@ -0,0 +1,97 @@
1
+ // The selective brute-force escalation (TODO.sota/21): when the
2
+ // compressed pipeline's retrieval grades weak on a DOCUMENT-SCOPED
3
+ // question, answer from the WHOLE publication uncut — deepseek's 1M
4
+ // context — instead of the window. The measured justification
5
+ // (TODO.sota/18.1): brute force answers 13/13 doc-scoped dev cases
6
+ // (100%) where the compressed window scores ~92.9%, at ~200–250k
7
+ // tokens per question. The trigger gates the spend: member/key tier
8
+ // only, one resolved document, after the corrective retry failed.
9
+ //
10
+ // The citation contract (settled in writing before the build,
11
+ // TODO.sota/21): the escalated answer cites clause numbers in prose,
12
+ // verified AGAINST THE ASSEMBLED DOCUMENT — every clause-like token
13
+ // the answer references must exist in the document's own clause set.
14
+ // Verified clause citations are honest anchors; anything else fails
15
+ // the answer to the honest refusal.
16
+
17
+ import type { StoreQuery } from "./ports/store.ts";
18
+ import { P } from "./profile.ts";
19
+
20
+ export interface AssembledDocument {
21
+ docidentifier: string;
22
+ text: string;
23
+ clauses: Set<string>;
24
+ truncated: boolean;
25
+ }
26
+
27
+ /** Assemble the WHOLE document from the chunks table in reading order
28
+ * (rowid preserves the parse's order — TODO.impl/02's invariant),
29
+ * capped. The clause set is every clause anchor the document carries,
30
+ * plus their dotted prefixes (a citation of 5.3.2 verifies when the
31
+ * document carries 5.3.2 itself or a longer clause beneath it). */
32
+ export async function assembleDocument(store: StoreQuery, docidentifier: string, capChars: number, lang = "en"): Promise<AssembledDocument | null> {
33
+ const res = await store
34
+ .prepare(
35
+ `SELECT text, clause_anchor, status, language FROM chunks
36
+ WHERE docidentifier = ?1 AND language = ?2 AND status = 'in-force'
37
+ ORDER BY rowid`,
38
+ )
39
+ .bind(docidentifier, lang)
40
+ .all();
41
+ const rows = (res.results ?? []) as unknown as { text: string; clause_anchor: string }[];
42
+ if (!rows.length) return null;
43
+ const clauses = new Set<string>();
44
+ const parts: string[] = [];
45
+ let total = 0;
46
+ let truncated = false;
47
+ for (const r of rows) {
48
+ const anchor = (r.clause_anchor || "").trim();
49
+ if (anchor) {
50
+ clauses.add(anchor);
51
+ const segs = anchor.split(".");
52
+ for (let i = 1; i < segs.length; i++) clauses.add(segs.slice(0, i).join("."));
53
+ }
54
+ if (total + r.text.length > capChars) {
55
+ truncated = true;
56
+ break;
57
+ }
58
+ parts.push(r.text);
59
+ total += r.text.length;
60
+ }
61
+ if (!parts.length) return null;
62
+ return { docidentifier, text: parts.join("\n\n"), clauses, truncated };
63
+ }
64
+
65
+ /** The clause-like tokens the ANSWER references (d.d and d.d.d shapes,
66
+ * including ranges "5.3–5.5"). Every token must resolve in the
67
+ * document's clause set — a cited clause the document does not carry
68
+ * makes the whole answer unverifiable. */
69
+ export function verifyAnchors(answer: string, clauses: Set<string>): { ok: boolean; missing: string[] } {
70
+ const cited = new Set<string>();
71
+ for (const m of answer.matchAll(/\b(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[1]);
72
+ for (const m of answer.matchAll(/\b(\d{1,2}\.\d{1,2})\s?[–—-]\s?(\d{1,2}(?:\.\d{1,2}){1,3})\b/g)) cited.add(m[2]);
73
+ const missing: string[] = [];
74
+ for (const c of cited) {
75
+ if (!clauses.has(c) && ![...clauses].some((k) => k.startsWith(`${c}.`) || k === c)) missing.push(c);
76
+ }
77
+ return { ok: missing.length === 0, missing };
78
+ }
79
+
80
+ /** The system prompt reads the publisher from the profile — the
81
+ * publisher-leak lint's law (a hardcoded name is a leak). */
82
+ export const escalationSystem = (): string =>
83
+ `You are ${P().publisher.name}, the answer service over legal-metrology publications. ` +
84
+ "Answer the question using ONLY the publication text below. Cite the clause numbers you use. " +
85
+ "If the publication does not answer it, say so plainly.";
86
+
87
+ /** The escalation's daily budget: a per-bucket KV counter. */
88
+ export async function escalationAllowed(kv: any, bucketId: string, dailyCap: number, day: string): Promise<boolean> {
89
+ if (dailyCap <= 0) return false;
90
+ const n = Number((await kv.get(`esc:${day}:${bucketId}`)) ?? "0");
91
+ return n < dailyCap;
92
+ }
93
+
94
+ export async function chargeEscalation(kv: any, bucketId: string, day: string): Promise<void> {
95
+ const key = `esc:${day}:${bucketId}`;
96
+ await kv.put(key, String(Number((await kv.get(key)) ?? "0") + 1), { expirationTtl: 172_800 });
97
+ }
@@ -327,3 +327,38 @@ export async function deleteUserDocument(ports: UserDocumentPorts, sub: string,
327
327
  await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
328
328
  return row;
329
329
  }
330
+
331
+ /** The member's own recorded values, ready to serve as the STATED STATE
332
+ * of a check (TODO.sota/20's "the verdict engine evaluates THEIR
333
+ * recorded values"): the ready documents' extracted fields, verbatim.
334
+ * The verdict extraction parses numbers-with-units out of these the
335
+ * same way it parses the question's own phrases. */
336
+ export async function memberDocFields(store: StoreQuery, sub: string): Promise<{ doc_id: string; name: string; fields: Record<string, string> }[]> {
337
+ const res = await store
338
+ .prepare("SELECT id, name, fields FROM user_documents WHERE owner_sub = ?1 AND status = 'ready' AND fields IS NOT NULL ORDER BY created_at DESC")
339
+ .bind(sub)
340
+ .all();
341
+ const out: { doc_id: string; name: string; fields: Record<string, string> }[] = [];
342
+ for (const r of (res.results ?? []) as unknown as { id: string; name: string; fields: string }[]) {
343
+ try {
344
+ const parsed = JSON.parse(r.fields) as Record<string, unknown>;
345
+ const fields: Record<string, string> = {};
346
+ for (const [k, v] of Object.entries(parsed)) {
347
+ if (typeof v === "string" || typeof v === "number") fields[k] = String(v);
348
+ }
349
+ if (Object.keys(fields).length) out.push({ doc_id: r.id, name: r.name, fields });
350
+ } catch {
351
+ // a fields blob that fails to parse contributes nothing
352
+ }
353
+ }
354
+ return out;
355
+ }
356
+
357
+ /** The fields' flat text for the stated-state extraction: one line per
358
+ * field, keyed — numbers-with-units parse from this the same way the
359
+ * question's own phrases do. */
360
+ export function fieldsAsText(docs: { doc_id: string; name: string; fields: Record<string, string> }[]): string {
361
+ return docs
362
+ .map((d) => Object.entries(d.fields).map(([k, v]) => `${k.replace(/_/g, " ")}: ${v}`).join("; "))
363
+ .join("\n");
364
+ }
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-ZFOODZWO.js";
4
- import "./chunk-IRCDOFP4.js";
5
- import "./chunk-XO26UIFH.js";
6
- import "./chunk-XTWH3PS6.js";
7
- import "./chunk-7RZ2D64X.js";
8
- import "./chunk-XMUG75ZV.js";
9
- import "./chunk-ETLSWSZ7.js";
10
- import "./chunk-5HCVX34C.js";
11
- import "./chunk-QYTCQIA6.js";
12
- import "./chunk-3FYJM7LH.js";
13
- import "./chunk-YGQCVPX6.js";
14
- export {
15
- handleAsk
16
- };
@@ -1,14 +0,0 @@
1
- import {
2
- handleSearch
3
- } from "./chunk-YQQ3W5CE.js";
4
- import "./chunk-XTWH3PS6.js";
5
- import "./chunk-7RZ2D64X.js";
6
- import "./chunk-XMUG75ZV.js";
7
- import "./chunk-ETLSWSZ7.js";
8
- import "./chunk-5HCVX34C.js";
9
- import "./chunk-QYTCQIA6.js";
10
- import "./chunk-3FYJM7LH.js";
11
- import "./chunk-YGQCVPX6.js";
12
- export {
13
- handleSearch
14
- };