@konneal/engine 0.2.185 → 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,7 +112,7 @@ 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";
@@ -1919,6 +1920,57 @@ function fieldsAsText(docs) {
1919
1920
  return docs.map((d) => Object.entries(d.fields).map(([k, v]) => `${k.replace(/_/g, " ")}: ${v}`).join("; ")).join("\n");
1920
1921
  }
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
+ }
1973
+
1922
1974
  // workers/worker_public/src/operations.ts
1923
1975
  function isOperationIntent(query) {
1924
1976
  return /\b(operations?|endpoints?)\b/i.test(query);
@@ -2682,6 +2734,7 @@ Certificates are issued per recommendation family \u2014 the register carries no
2682
2734
  const ops = await operationsLane(env.DB, q2.query);
2683
2735
  const registerOwns = !!register?.rows?.length;
2684
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" }] : [];
2685
2738
  if (understanding?.intent === "conversational") {
2686
2739
  const queryHash2 = await sha256Hex(q2.query);
2687
2740
  const messages2 = [
@@ -3086,7 +3139,7 @@ Answer account questions from these records ONLY: name the record when you use i
3086
3139
  text: `${m.anchor} \u2014 ${m.text}`
3087
3140
  }));
3088
3141
  const passagePool = registerOwns ? [...opsHits, ...hits].filter((h) => !!h.metadata.cert_holder) : [...opsHits, ...hits];
3089
- const { messages, usedHits } = buildMessages(
3142
+ const built = buildMessages(
3090
3143
  q2.query,
3091
3144
  passagePool,
3092
3145
  q2.lang,
@@ -3097,6 +3150,35 @@ Answer account questions from these records ONLY: name the record when you use i
3097
3150
  budget,
3098
3151
  ablate?.noCompress !== true
3099
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
+ }
3100
3182
  const decisionPromise = decisionsArmed && decisionsGatePromise ? decisionsGatePromise.then((g) => g != null && g >= THRESHOLDS.decisionsGateMin ? runDecisionPass(env, {
3101
3183
  question: q2.query,
3102
3184
  gate: g,
@@ -3157,7 +3239,7 @@ Answer account questions from these records ONLY: name the record when you use i
3157
3239
  console.log("user image attached to generation");
3158
3240
  }
3159
3241
  const queryHash = await sha256Hex(q2.query);
3160
- const cites = [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3242
+ const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits)];
3161
3243
  if (live2) {
3162
3244
  const stream = await generateStream(env, model, messages, routeEffort(routed.route));
3163
3245
  if (stream) {
@@ -3240,6 +3322,14 @@ Answer account questions from these records ONLY: name the record when you use i
3240
3322
  }
3241
3323
  }
3242
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
+ }
3243
3333
  let canonical0 = exciseMisplacedPin(canonicalRefusal(full.replace(/^TOOL [a-z_.]+.*$\n?/gm, "").replace(/^\n+/, ""), refusalScope(answerCites(full))), answerCites(full));
3244
3334
  const c2 = canonical0.includes(refusalAnswer()) ? { text: canonical0, blocks: [], dropped: [] } : await contractV2(env.DB, canonical0, usedHits);
3245
3335
  let streamedCompletionBlocks = [];
@@ -3446,7 +3536,14 @@ Answer account questions from these records ONLY: name the record when you use i
3446
3536
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q2.lang, void 0, telemetryMeta());
3447
3537
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
3448
3538
  }
3449
- 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
+ }
3450
3547
  const c2ns = answer.includes(refusalAnswer()) ? { text: answer, blocks: [], dropped: [] } : await contractV2(env.DB, answer, used);
3451
3548
  answer = c2ns.text;
3452
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,
@@ -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 {
@@ -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-JVKJWLI7.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-5KXF53IL.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.185",
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",
@@ -48,6 +48,8 @@ import { chargeTokens, checkQuota, clientIp, creditBudget, creditEstimate, estim
48
48
  import { graphExpand, editionNote } from "./graph";
49
49
  import { registerNote, searchRegister, certificateLinks, registerAggregateIntent, registerAggregate, aggregateNote, aggregateBlock, queryFamily, registerBypassesCache } from "./certificates";
50
50
  import { queryUserLane, memberDocFields, fieldsAsText } from "./userDocuments";
51
+ import { assembleDocument, verifyAnchors, escalationAllowed, chargeEscalation, escalationSystem } from "./escalation";
52
+ import { ESCALATION_DAILY_DEFAULT } from "./config";
51
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";
@@ -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
@@ -1548,7 +1554,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1548
1554
  const passagePool = registerOwns
1549
1555
  ? [...opsHits, ...hits].filter((h) => !!(h.metadata as any).cert_holder)
1550
1556
  : [...opsHits, ...hits];
1551
- const { messages, usedHits } = buildMessages(
1557
+ const built = buildMessages(
1552
1558
  q.query,
1553
1559
  passagePool,
1554
1560
  q.lang,
@@ -1559,6 +1565,43 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1559
1565
  budget,
1560
1566
  ablate?.noCompress !== true,
1561
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
+ }
1562
1605
  // the decision pass (TODO.decisions/01): starts here so its calls run
1563
1606
  // concurrently with generation — the checklist section arrives the
1564
1607
  // moment the model's last token lands, never delaying the answer
@@ -1675,7 +1718,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1675
1718
  // provenance — ahead of the prose passages. The register rides first
1676
1719
  // when it owns the answer (the standing citation the aggregate path
1677
1720
  // has always attached).
1678
- const cites = [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1721
+ const cites = escalateAnswer ? escalationCitation() : [...registerCitation, ...(boundModel ? [modelCitation(boundModel), ...citations(usedHits)] : citations(usedHits))];
1679
1722
 
1680
1723
  if (live) {
1681
1724
  const stream = await generateStream(env, model, messages, routeEffort(routed.route));
@@ -1773,6 +1816,17 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1773
1816
  }
1774
1817
  // the misplaced-pin wall rides the streamed path too: a
1775
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
+ }
1776
1830
  let canonical0 = exciseMisplacedPin(canonicalRefusal(full.replace(/^TOOL [a-z_.]+.*$\n?/gm, "").replace(/^\n+/, ""), refusalScope(answerCites(full))), answerCites(full));
1777
1831
  // answer contract v2: validate [[u:]] refs, resolve typed blocks
1778
1832
  const c2 = canonical0.includes(refusalAnswer())
@@ -2075,7 +2129,15 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
2075
2129
  telemetry(env, ctx, tier, "ask", model, false, 0, queryHash, q.lang, undefined, telemetryMeta());
2076
2130
  return err(502, "generation_failed", "The generation model is unavailable; please retry.");
2077
2131
  }
2078
- 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
+ }
2079
2141
  const c2ns = answer!.includes(refusalAnswer())
2080
2142
  ? { text: answer, blocks: [] as Awaited<ReturnType<typeof contractV2>>["blocks"], dropped: [] as string[] }
2081
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];
@@ -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
+ }
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-JVKJWLI7.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
- };