@konneal/engine 0.2.192 → 0.2.193

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,10 +1,10 @@
1
1
  import {
2
2
  handleAsk
3
- } from "./chunk-ZPNYAANP.js";
3
+ } from "./chunk-RX7FL5D6.js";
4
4
  import "./chunk-IRCDOFP4.js";
5
- import "./chunk-NHNCW6KQ.js";
6
- import "./chunk-W4F22Y4M.js";
7
- import "./chunk-VGBZYYVH.js";
5
+ import "./chunk-UZHUND67.js";
6
+ import "./chunk-73GZKS2T.js";
7
+ import "./chunk-QYNFNOKE.js";
8
8
  import "./chunk-M4OCMIWU.js";
9
9
  import "./chunk-ETLSWSZ7.js";
10
10
  import "./chunk-J4UAO5XI.js";
@@ -6,7 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-W4F22Y4M.js";
9
+ } from "./chunk-73GZKS2T.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  embed,
3
- rerank
4
- } from "./chunk-VGBZYYVH.js";
3
+ rerank,
4
+ unitPayloadRows
5
+ } from "./chunk-QYNFNOKE.js";
5
6
  import {
6
7
  bubbleConfirmPage,
7
8
  isAllowedBubbleOrigin
@@ -22976,12 +22977,19 @@ var vlmFigureRerank = {
22976
22977
  const figures = c.finalHits.filter((h) => h.metadata.block === "figure" && h.metadata.unit_id).slice(0, 3);
22977
22978
  if (!figures.length) return;
22978
22979
  try {
22979
- const ids = figures.map((h) => String(h.metadata.unit_id));
22980
- const ph = ids.map((_, i) => `?${i + 1}`).join(",");
22981
- const rows = await portStore(c.env).prepare(
22982
- `SELECT unit_id, json_extract(payload,'$.uri') AS uri FROM unit_payloads WHERE unit_id IN (${ph})`
22983
- ).bind(...ids).all();
22984
- const uris = new Map((rows.results ?? []).map((r) => [r.unit_id, r.uri]));
22980
+ const rows = await unitPayloadRows(
22981
+ portStore(c.env),
22982
+ figures.map((h) => ({ unit_id: String(h.metadata.unit_id), doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier }))
22983
+ );
22984
+ const uris = /* @__PURE__ */ new Map();
22985
+ rows.forEach((row, i) => {
22986
+ if (!row) return;
22987
+ try {
22988
+ const uri = JSON.parse(String(row.payload))?.uri;
22989
+ if (typeof uri === "string") uris.set(String(figures[i].metadata.unit_id), uri);
22990
+ } catch {
22991
+ }
22992
+ });
22985
22993
  const content = [
22986
22994
  {
22987
22995
  type: "text",
@@ -71,10 +71,56 @@ async function generateOnce(env, model, messages, effort) {
71
71
  return null;
72
72
  }
73
73
 
74
+ // workers/worker_public/src/unitPayloads.ts
75
+ var COLS = "unit_id, doc_id, type, docidentifier, edition, payload";
76
+ function belongs(row, key) {
77
+ if (!key.doc_id && !key.docidentifier) return true;
78
+ if (key.doc_id) return row.doc_id === key.doc_id;
79
+ return row.docidentifier === key.docidentifier;
80
+ }
81
+ async function byIds(db, table, ids) {
82
+ const ph = ids.map((_, i) => `?${i + 1}`).join(",");
83
+ try {
84
+ const res = await db.prepare(`SELECT ${COLS} FROM ${table} WHERE unit_id IN (${ph})`).bind(...ids).all();
85
+ return res.results ?? [];
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ async function unitPayloadRows(db, keys) {
91
+ const out = new Array(keys.length).fill(null);
92
+ if (!keys.length) return out;
93
+ const ids = [...new Set(keys.map((k) => k.unit_id))];
94
+ const scoped = keys.some((k) => k.doc_id) ? await byIds(db, "unit_payloads_doc", ids) : null;
95
+ const byDoc = /* @__PURE__ */ new Map();
96
+ for (const r of scoped ?? []) byDoc.set(`${r.unit_id}|${r.doc_id}`, r);
97
+ const legacy = /* @__PURE__ */ new Map();
98
+ for (const r of await byIds(db, "unit_payloads", ids) ?? []) if (!legacy.has(r.unit_id)) legacy.set(r.unit_id, r);
99
+ keys.forEach((key, i) => {
100
+ let row = key.doc_id ? byDoc.get(`${key.unit_id}|${key.doc_id}`) ?? null : null;
101
+ const l = legacy.get(key.unit_id);
102
+ if (!row && l && belongs(l, key)) row = l;
103
+ out[i] = row;
104
+ });
105
+ return out;
106
+ }
107
+ async function publicationUnitRows(db, type, docidentifierLike, limit) {
108
+ for (const table of ["unit_payloads_doc", "unit_payloads"]) {
109
+ try {
110
+ const res = await db.prepare(`SELECT ${COLS} FROM ${table} WHERE type = ?1 AND docidentifier LIKE ?2 LIMIT ${limit}`).bind(type, docidentifierLike).all();
111
+ return res.results ?? [];
112
+ } catch {
113
+ }
114
+ }
115
+ return [];
116
+ }
117
+
74
118
  export {
75
119
  embed,
76
120
  isCapacityError,
77
121
  CAPACITY_PAUSE_MS,
78
122
  rerank,
79
- generateOnce
123
+ generateOnce,
124
+ unitPayloadRows,
125
+ publicationUnitRows
80
126
  };
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-NHNCW6KQ.js";
36
+ } from "./chunk-UZHUND67.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -77,13 +77,15 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-W4F22Y4M.js";
80
+ } from "./chunk-73GZKS2T.js";
81
81
  import {
82
82
  CAPACITY_PAUSE_MS,
83
83
  embed,
84
84
  generateOnce,
85
- isCapacityError
86
- } from "./chunk-VGBZYYVH.js";
85
+ isCapacityError,
86
+ publicationUnitRows,
87
+ unitPayloadRows
88
+ } from "./chunk-QYNFNOKE.js";
87
89
  import {
88
90
  corsHeaders,
89
91
  err,
@@ -499,13 +501,13 @@ async function completeTables(db, answer, used) {
499
501
  const fams = [...new Set(used.map((h) => h.metadata.docidentifier).filter(Boolean))].slice(0, 3);
500
502
  for (const fam of fams) {
501
503
  const base = String(fam).replace(/\s*\([A-Z]\)\s*$/, "").split(":")[0].trim();
502
- const rows = await db.prepare("SELECT unit_id, payload FROM unit_payloads WHERE type = 'table' AND docidentifier LIKE ?1 LIMIT 8").bind(`%${base}%`).all();
503
- for (const r of rows.results ?? []) {
504
+ const rows = await publicationUnitRows(db, "table", `%${base}%`, 8);
505
+ for (const r of rows) {
504
506
  const tableNums = new Set((String(r.payload).match(/\d[\d ,.]{1,8}\d/g) ?? []).map((x) => x.replace(/[ ,.]/g, "")));
505
507
  let hits = 0;
506
508
  for (const n of answerNums) if (tableNums.has(n)) hits++;
507
509
  if (hits >= 1) {
508
- const resolved = await resolveBlocks(db, [r.unit_id]);
510
+ const resolved = await resolveBlocks(db, [r.unit_id], /* @__PURE__ */ new Map([[r.unit_id, { unit_id: r.unit_id, doc_id: r.doc_id, docidentifier: r.docidentifier }]]));
509
511
  blocks.push(...resolved);
510
512
  console.log("contract D1 completion: table", r.unit_id, "in", base, "\u2014", hits, "matching values");
511
513
  break;
@@ -521,12 +523,16 @@ async function completeFigures(db, answer, alreadyAttached, used = [], query) {
521
523
  const unitForm = (answer.match(/u:fig[\w.-]*/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
522
524
  const bareForm = (answer.match(/\bfig-[\w.-]+\b/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
523
525
  let mentioned = [.../* @__PURE__ */ new Set([...unitForm, ...bareForm.map((x) => x.startsWith("u:") ? x : "u:" + x)])].slice(0, 6);
526
+ const docOf = /* @__PURE__ */ new Map();
524
527
  const proseNums = new Set(
525
528
  (answer.match(/\bFig(?:ure|\.)s?\s*([0-9]{1,2}[a-z]?)/g) ?? []).map((x) => x.replace(/\bFig(?:ure|\.)s?\s*/i, "").toLowerCase())
526
529
  );
527
530
  if (query && /\bfig(ure|s)?\b/i.test(query)) {
528
531
  for (const h of used.slice(0, 12)) {
529
- if (h.metadata.unit_id && h.metadata.block === "figure") mentioned.push(h.metadata.unit_id);
532
+ if (h.metadata.unit_id && h.metadata.block === "figure") {
533
+ mentioned.push(h.metadata.unit_id);
534
+ if (!docOf.has(h.metadata.unit_id)) docOf.set(h.metadata.unit_id, { unit_id: h.metadata.unit_id, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier });
535
+ }
530
536
  }
531
537
  mentioned = [...new Set(mentioned)].slice(0, 6);
532
538
  }
@@ -534,10 +540,13 @@ async function completeFigures(db, answer, alreadyAttached, used = [], query) {
534
540
  const fams = [...new Set(used.map((h) => h.metadata.docidentifier).filter(Boolean))].slice(0, 3);
535
541
  for (const fam of fams) {
536
542
  const base = String(fam).replace(/\s*\([A-Z]\)\s*$/, "").split(":")[0].trim();
537
- const rows = await db.prepare("SELECT unit_id FROM unit_payloads WHERE type = 'figure' AND docidentifier LIKE ?1 LIMIT 24").bind(`%${base}%`).all();
538
- for (const r of rows.results ?? []) {
543
+ const rows = await publicationUnitRows(db, "figure", `%${base}%`, 24);
544
+ for (const r of rows) {
539
545
  const m = r.unit_id.match(/fig-?([0-9]{1,2}[a-z]?)/i);
540
- if (m && proseNums.has(m[1].toLowerCase())) mentioned.push(r.unit_id);
546
+ if (m && proseNums.has(m[1].toLowerCase())) {
547
+ mentioned.push(r.unit_id);
548
+ if (!docOf.has(r.unit_id)) docOf.set(r.unit_id, { unit_id: r.unit_id, doc_id: r.doc_id, docidentifier: r.docidentifier });
549
+ }
541
550
  }
542
551
  }
543
552
  mentioned = [...new Set(mentioned)].slice(0, 6);
@@ -545,7 +554,7 @@ async function completeFigures(db, answer, alreadyAttached, used = [], query) {
545
554
  const have = new Set(alreadyAttached.map((b) => b.unit_id));
546
555
  const missing = mentioned.filter((id) => !have.has(id));
547
556
  if (!missing.length) return [];
548
- const figs = await resolveBlocks(db, missing);
557
+ const figs = await resolveBlocks(db, missing, docOf);
549
558
  if (figs.length) console.log("figure completion:", figs.map((b) => b.unit_id).join(", "), "attached from D1");
550
559
  return figs;
551
560
  }
@@ -2305,7 +2314,7 @@ async function attachFigureImages(env, messages, usedHits, query) {
2305
2314
  let figCaption = "";
2306
2315
  for (const h of figures) {
2307
2316
  try {
2308
- const row = await env.DB.prepare("SELECT payload FROM unit_payloads WHERE unit_id = ?1").bind(h.metadata.unit_id).first();
2317
+ const [row] = await unitPayloadRows(env.DB, [{ unit_id: h.metadata.unit_id, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier }]);
2309
2318
  const payload = row ? JSON.parse(String(row.payload)) : {};
2310
2319
  const uri = typeof payload.uri === "string" ? payload.uri : "";
2311
2320
  if (typeof payload.caption === "string" && payload.caption.trim()) figCaption = payload.caption.trim();
@@ -3149,19 +3158,23 @@ Answer account questions from these records ONLY: name the record when you use i
3149
3158
  return finishLine("Search is briefly busy \u2014 please retry in a moment.");
3150
3159
  }
3151
3160
  {
3152
- const figs = retrieved.hits.filter((h) => h.metadata.block === "figure" && h.metadata.unit_id);
3161
+ const figs = retrieved.hits.filter((h) => h.metadata.block === "figure" && h.metadata.unit_id).slice(0, 20);
3153
3162
  if (figs.length) {
3154
3163
  try {
3155
- const ids = [...new Set(figs.map((h) => String(h.metadata.unit_id)))].slice(0, 20);
3156
- const ph = ids.map((_, i) => `?${i + 1}`).join(",");
3157
- const res = await env.DB.prepare(
3158
- `SELECT unit_id, json_extract(payload,'$.description') AS d FROM unit_payloads WHERE unit_id IN (${ph})`
3159
- ).bind(...ids).all();
3160
- const byId = new Map((res.results ?? []).map((r) => [r.unit_id, r.d]));
3161
- for (const h of figs) {
3162
- const d = byId.get(String(h.metadata.unit_id));
3163
- if (d) h.metadata.figure_description = String(d).slice(0, 600);
3164
- }
3164
+ const rows = await unitPayloadRows(
3165
+ env.DB,
3166
+ figs.map((h) => ({ unit_id: String(h.metadata.unit_id), doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier }))
3167
+ );
3168
+ rows.forEach((row, i) => {
3169
+ if (!row) return;
3170
+ let d;
3171
+ try {
3172
+ d = JSON.parse(String(row.payload))?.description;
3173
+ } catch {
3174
+ return;
3175
+ }
3176
+ if (typeof d === "string" && d.trim()) figs[i].metadata.figure_description = d.slice(0, 600);
3177
+ });
3165
3178
  } catch {
3166
3179
  }
3167
3180
  }
@@ -1,6 +1,7 @@
1
1
  import {
2
- embed
3
- } from "./chunk-VGBZYYVH.js";
2
+ embed,
3
+ unitPayloadRows
4
+ } from "./chunk-QYNFNOKE.js";
4
5
  import {
5
6
  standardKeysFrom
6
7
  } from "./chunk-J4UAO5XI.js";
@@ -43,33 +44,26 @@ function sanitizeRefs(text, available) {
43
44
  });
44
45
  return { text: out, dropped };
45
46
  }
46
- async function resolveBlocks(db, refs) {
47
+ async function resolveBlocks(db, refs, docs) {
47
48
  if (!refs.length) return [];
48
49
  const uniq = [...new Set(refs)].slice(0, 12);
50
+ const keys = uniq.map((id) => docs?.get(id) ?? { unit_id: id });
49
51
  const blocks = [];
50
- for (let i = 0; i < uniq.length; i += 20) {
51
- const batch = uniq.slice(i, i + 20);
52
- const placeholders = batch.map((_, n) => `?${n + 1}`).join(",");
52
+ for (const r of await unitPayloadRows(db, keys)) {
53
+ if (!r) continue;
54
+ let payload = {};
53
55
  try {
54
- const res = await db.prepare(`SELECT unit_id, type, docidentifier, edition, payload FROM unit_payloads WHERE unit_id IN (${placeholders})`).bind(...batch).all();
55
- for (const r of res.results) {
56
- let payload = {};
57
- try {
58
- payload = JSON.parse(String(r.payload));
59
- } catch {
60
- continue;
61
- }
62
- blocks.push({
63
- unit_id: String(r.unit_id),
64
- type: String(r.type),
65
- docidentifier: String(r.docidentifier ?? ""),
66
- edition: r.edition ? String(r.edition) : void 0,
67
- payload
68
- });
69
- }
70
- } catch (e) {
71
- console.log("resolveBlocks failed:", String(e).slice(0, 150));
56
+ payload = JSON.parse(String(r.payload));
57
+ } catch {
58
+ continue;
72
59
  }
60
+ blocks.push({
61
+ unit_id: String(r.unit_id),
62
+ type: String(r.type),
63
+ docidentifier: String(r.docidentifier ?? ""),
64
+ edition: r.edition ? String(r.edition) : void 0,
65
+ payload
66
+ });
73
67
  }
74
68
  return blocks;
75
69
  }
@@ -78,7 +72,12 @@ async function contractV2(db, answer, usedHits) {
78
72
  const { text, dropped } = sanitizeRefs(answer, available);
79
73
  if (dropped.length) console.log("refs: dropped", dropped.length, "invalid (not in passages)");
80
74
  const refs = parseRefs(text);
81
- const blocks = await resolveBlocks(db, refs);
75
+ const docs = /* @__PURE__ */ new Map();
76
+ for (const h of usedHits) {
77
+ const u = h.metadata?.unit_id;
78
+ if (u && !docs.has(u)) docs.set(u, { unit_id: u, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier });
79
+ }
80
+ const blocks = await resolveBlocks(db, refs, docs);
82
81
  return { text, blocks, dropped };
83
82
  }
84
83
  function tableRetyped(text, availableTable) {
package/dist/refs.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { StoreQuery } from "./ports/store.ts";
2
+ import { type UnitKey } from "./unitPayloads.ts";
2
3
  export interface ResolvedBlock {
3
4
  unit_id: string;
4
5
  type: string;
@@ -20,14 +21,18 @@ export declare function sanitizeRefs(text: string, available: ReadonlySet<string
20
21
  text: string;
21
22
  dropped: string[];
22
23
  };
23
- /** Resolve validated refs to producer payloads from D1 (unit_payloads).
24
- * Unknown-to-D1 ids are skipped — a ref without a payload renders as a
25
- * plain token, never as fabricated data. */
26
- export declare function resolveBlocks(db: StoreQuery, refs: string[]): Promise<ResolvedBlock[]>;
24
+ /** Resolve validated refs to producer payloads from D1. A ref is tied to
25
+ * the document of the passage that carried the unit (`docs`): the same
26
+ * unit id lives in many publications, and another document's payload is
27
+ * never rendered in its place. Unknown-to-D1 ids are skipped — a ref
28
+ * without a payload renders as a plain token, never as fabricated data. */
29
+ export declare function resolveBlocks(db: StoreQuery, refs: string[], docs?: ReadonlyMap<string, UnitKey>): Promise<ResolvedBlock[]>;
27
30
  /** One pass: validate + resolve + strip invalid tokens. */
28
31
  export declare function contractV2(db: StoreQuery, answer: string, usedHits: ReadonlyArray<{
29
32
  metadata: {
30
33
  unit_id?: string | undefined;
34
+ doc_id?: string | undefined;
35
+ docidentifier?: string | undefined;
31
36
  };
32
37
  }>): Promise<{
33
38
  text: string;
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  handleSearch
3
- } from "./chunk-UDHM3G5N.js";
4
- import "./chunk-W4F22Y4M.js";
5
- import "./chunk-VGBZYYVH.js";
3
+ } from "./chunk-3MV3UO6Q.js";
4
+ import "./chunk-73GZKS2T.js";
5
+ import "./chunk-QYNFNOKE.js";
6
6
  import "./chunk-M4OCMIWU.js";
7
7
  import "./chunk-ETLSWSZ7.js";
8
8
  import "./chunk-J4UAO5XI.js";
@@ -4,8 +4,8 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-NHNCW6KQ.js";
8
- import "./chunk-VGBZYYVH.js";
7
+ } from "./chunk-UZHUND67.js";
8
+ import "./chunk-QYNFNOKE.js";
9
9
  import "./chunk-J4UAO5XI.js";
10
10
  import "./chunk-5Y3CDK64.js";
11
11
  import "./chunk-3FYJM7LH.js";
@@ -0,0 +1,24 @@
1
+ import type { StoreQuery } from "./ports/store.ts";
2
+ export interface UnitRow {
3
+ unit_id: string;
4
+ doc_id: string | null;
5
+ type: string;
6
+ docidentifier: string | null;
7
+ edition: string | null;
8
+ payload: string;
9
+ }
10
+ /** A unit as its citing passage names it: the id and the document. */
11
+ export interface UnitKey {
12
+ unit_id: string;
13
+ doc_id?: string | null;
14
+ docidentifier?: string | null;
15
+ }
16
+ /** The payload rows for the given unit keys, aligned with them: null
17
+ * where no row belongs to the citing document. The document-scoped
18
+ * table answers first; the legacy table fills a key only with its own
19
+ * document's row. */
20
+ export declare function unitPayloadRows(db: StoreQuery, keys: readonly UnitKey[]): Promise<(UnitRow | null)[]>;
21
+ /** Every unit of one type under a publication (by docidentifier
22
+ * pattern), from the document-scoped table — or the legacy one where
23
+ * that deployment has none. */
24
+ export declare function publicationUnitRows(db: StoreQuery, type: string, docidentifierLike: string, limit: number): Promise<UnitRow[]>;
@@ -9,16 +9,16 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-ZPNYAANP.js";
12
+ } from "../../chunk-RX7FL5D6.js";
13
13
  import "../../chunk-IRCDOFP4.js";
14
14
  import {
15
15
  TOOLS_REGISTRY,
16
16
  bindModelNode,
17
17
  modelGroundingBlock
18
- } from "../../chunk-NHNCW6KQ.js";
18
+ } from "../../chunk-UZHUND67.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-UDHM3G5N.js";
21
+ } from "../../chunk-3MV3UO6Q.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-W4F22Y4M.js";
46
+ } from "../../chunk-73GZKS2T.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
50
- } from "../../chunk-VGBZYYVH.js";
50
+ } from "../../chunk-QYNFNOKE.js";
51
51
  import {
52
52
  authenticate,
53
53
  corsHeaders,
@@ -1184,13 +1184,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1184
1184
  // stream:false forces the JSON lane (anon defaults to SSE)
1185
1185
  body: JSON.stringify({ ...args, stream: false })
1186
1186
  });
1187
- const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-LOQBTAFQ.js");
1187
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-JWKGPVEG.js");
1188
1188
  let payload;
1189
1189
  if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
1190
1190
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1191
1191
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1192
1192
  } else {
1193
- const res = name === "ask" ? await (await import("../../ask-Q63SLXRD.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-7ANUZAYL.js")).handleSearch(env, ctx, inner, tier, key);
1193
+ const res = name === "ask" ? await (await import("../../ask-XQR7LQPG.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-UMSZNYGP.js")).handleSearch(env, ctx, inner, tier, key);
1194
1194
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1195
1195
  }
1196
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 });
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.192",
30
+ "version": "0.2.193",
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",
@@ -21,6 +21,7 @@ import { cacheableAnswer, canonicalRefusal, exciseMisplacedPin, refusalShaped }
21
21
  import { docOverviewInstruction, docOverviewRefusal } from "./docOverview";
22
22
  import { contractV2, tableRetyped } from "./refs";
23
23
  import { completeTables, completeFigures } from "./completion";
24
+ import { unitPayloadRows } from "./unitPayloads.ts";
24
25
  import { NO_CONTEXT, appliedContext, contextNote, namedDocumentIn, parseContext, resolveDocScope, syntheticUnderstanding } from "./context";
25
26
  import { liveDataConfig, liveTokenFor, opCfg, opTokenMember, resolveLiveAccount, type LiveRecord } from "./livedata";
26
27
  import { bindModelNode, bindConstraintByQuantities, licenseBoundaryNote, licenseBoundaryRefusal, licensedEntryForPackage, modelCitation, modelEcho, modelGroundingBlock, standardForDocNumber } from "./modelplane";
@@ -177,7 +178,9 @@ async function attachFigureImages(env: Env, messages: { role: string; content: a
177
178
  let figCaption = "";
178
179
  for (const h of figures) {
179
180
  try {
180
- const row = await env.DB.prepare("SELECT payload FROM unit_payloads WHERE unit_id = ?1").bind(h.metadata.unit_id!).first<any>();
181
+ // the figure's payload is its OWN document's — the unit id alone is
182
+ // shared across the corpus's publications
183
+ const [row] = await unitPayloadRows(env.DB, [{ unit_id: h.metadata.unit_id!, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier }]);
181
184
  const payload = row ? JSON.parse(String(row.payload)) : {};
182
185
  const uri = typeof payload.uri === "string" ? payload.uri : "";
183
186
  // the producer's caption first; the caption LANE's output (a
@@ -1517,19 +1520,24 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1517
1520
  // model has words for the drawing and a reason to cite the unit —
1518
1521
  // one batched D1 read per turn that retrieved figures, fail-open
1519
1522
  {
1520
- const figs = retrieved.hits.filter((h: Hit) => (h.metadata as any).block === "figure" && (h.metadata as any).unit_id);
1523
+ const figs = retrieved.hits.filter((h: Hit) => (h.metadata as any).block === "figure" && (h.metadata as any).unit_id).slice(0, 20);
1521
1524
  if (figs.length) {
1522
1525
  try {
1523
- const ids = [...new Set(figs.map((h: Hit) => String((h.metadata as any).unit_id)))].slice(0, 20);
1524
- const ph = ids.map((_, i) => `?${i + 1}`).join(",");
1525
- const res = await env.DB.prepare(
1526
- `SELECT unit_id, json_extract(payload,'$.description') AS d FROM unit_payloads WHERE unit_id IN (${ph})`,
1527
- ).bind(...ids).all<{ unit_id: string; d: string | null }>();
1528
- const byId = new Map((res.results ?? []).map((r) => [r.unit_id, r.d]));
1529
- for (const h of figs) {
1530
- const d = byId.get(String((h.metadata as any).unit_id));
1531
- if (d) (h.metadata as any).figure_description = String(d).slice(0, 600);
1532
- }
1526
+ // each figure's caption is read within its own document
1527
+ const rows = await unitPayloadRows(
1528
+ env.DB,
1529
+ figs.map((h: Hit) => ({ unit_id: String((h.metadata as any).unit_id), doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier })),
1530
+ );
1531
+ rows.forEach((row, i) => {
1532
+ if (!row) return;
1533
+ let d: unknown;
1534
+ try {
1535
+ d = JSON.parse(String(row.payload))?.description;
1536
+ } catch {
1537
+ return;
1538
+ }
1539
+ if (typeof d === "string" && d.trim()) (figs[i].metadata as any).figure_description = d.slice(0, 600);
1540
+ });
1533
1541
  } catch { /* the caption is additive — the passage serves without it */ }
1534
1542
  }
1535
1543
  }
@@ -14,6 +14,7 @@
14
14
  // Additive throughout: any failure returns what it has.
15
15
  import type { StoreQuery } from "./ports/store.ts";
16
16
  import { resolveBlocks, type ResolvedBlock } from "./refs.ts";
17
+ import { publicationUnitRows, type UnitKey } from "./unitPayloads.ts";
17
18
  import type { Hit } from "./pipeline.ts";
18
19
 
19
20
  export async function completeTables(
@@ -31,16 +32,14 @@ export async function completeTables(
31
32
  const fams = [...new Set(used.map((h) => h.metadata.docidentifier).filter(Boolean))].slice(0, 3);
32
33
  for (const fam of fams) {
33
34
  const base = String(fam).replace(/\s*\([A-Z]\)\s*$/, "").split(":")[0].trim();
34
- const rows = await db
35
- .prepare("SELECT unit_id, payload FROM unit_payloads WHERE type = 'table' AND docidentifier LIKE ?1 LIMIT 8")
36
- .bind(`%${base}%`)
37
- .all<{ unit_id: string; payload: string }>();
38
- for (const r of rows.results ?? []) {
35
+ const rows = await publicationUnitRows(db, "table", `%${base}%`, 8);
36
+ for (const r of rows) {
39
37
  const tableNums = new Set((String(r.payload).match(/\d[\d ,.]{1,8}\d/g) ?? []).map((x) => x.replace(/[ ,.]/g, "")));
40
38
  let hits = 0;
41
39
  for (const n of answerNums) if (tableNums.has(n)) hits++;
42
40
  if (hits >= 1) {
43
- const resolved = await resolveBlocks(db, [r.unit_id]);
41
+ // the table resolves within its own document — the unit id alone is shared across publications
42
+ const resolved = await resolveBlocks(db, [r.unit_id], new Map([[r.unit_id, { unit_id: r.unit_id, doc_id: r.doc_id, docidentifier: r.docidentifier }]]));
44
43
  blocks.push(...resolved);
45
44
  console.log("contract D1 completion: table", r.unit_id, "in", base, "—", hits, "matching values");
46
45
  break;
@@ -68,6 +67,8 @@ export async function completeFigures(
68
67
  const unitForm = (answer.match(/u:fig[\w.-]*/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
69
68
  const bareForm = (answer.match(/\bfig-[\w.-]+\b/g) ?? []).map((x) => x.replace(/[.,;:)]+$/, ""));
70
69
  let mentioned = [...new Set([...unitForm, ...bareForm.map((x) => (x.startsWith("u:") ? x : "u:" + x))])].slice(0, 6);
70
+ // the document behind each mentioned unit — a unit id is shared across publications, so a block resolves within the document that named it
71
+ const docOf = new Map<string, UnitKey>();
71
72
  // natural prose names figures without any identifier at all — "Figure 3
72
73
  // of R 60-2 shows…" (the #172 residual): resolve those by number within
73
74
  // the publications the answer used, never across the corpus at large
@@ -83,7 +84,10 @@ export async function completeFigures(
83
84
  // a hope that the model names an unnameable id
84
85
  if (query && /\bfig(ure|s)?\b/i.test(query)) {
85
86
  for (const h of used.slice(0, 12)) {
86
- if (h.metadata.unit_id && h.metadata.block === "figure") mentioned.push(h.metadata.unit_id);
87
+ if (h.metadata.unit_id && h.metadata.block === "figure") {
88
+ mentioned.push(h.metadata.unit_id);
89
+ if (!docOf.has(h.metadata.unit_id)) docOf.set(h.metadata.unit_id, { unit_id: h.metadata.unit_id, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier });
90
+ }
87
91
  }
88
92
  mentioned = [...new Set(mentioned)].slice(0, 6);
89
93
  }
@@ -91,13 +95,13 @@ export async function completeFigures(
91
95
  const fams = [...new Set(used.map((h) => h.metadata.docidentifier).filter(Boolean))].slice(0, 3);
92
96
  for (const fam of fams) {
93
97
  const base = String(fam).replace(/\s*\([A-Z]\)\s*$/, "").split(":")[0].trim();
94
- const rows = await db
95
- .prepare("SELECT unit_id FROM unit_payloads WHERE type = 'figure' AND docidentifier LIKE ?1 LIMIT 24")
96
- .bind(`%${base}%`)
97
- .all<{ unit_id: string }>();
98
- for (const r of rows.results ?? []) {
98
+ const rows = await publicationUnitRows(db, "figure", `%${base}%`, 24);
99
+ for (const r of rows) {
99
100
  const m = r.unit_id.match(/fig-?([0-9]{1,2}[a-z]?)/i);
100
- if (m && proseNums.has(m[1].toLowerCase())) mentioned.push(r.unit_id);
101
+ if (m && proseNums.has(m[1].toLowerCase())) {
102
+ mentioned.push(r.unit_id);
103
+ if (!docOf.has(r.unit_id)) docOf.set(r.unit_id, { unit_id: r.unit_id, doc_id: r.doc_id, docidentifier: r.docidentifier });
104
+ }
101
105
  }
102
106
  }
103
107
  mentioned = [...new Set(mentioned)].slice(0, 6);
@@ -105,7 +109,7 @@ export async function completeFigures(
105
109
  const have = new Set(alreadyAttached.map((b) => b.unit_id));
106
110
  const missing = mentioned.filter((id) => !have.has(id));
107
111
  if (!missing.length) return [];
108
- const figs = await resolveBlocks(db, missing);
112
+ const figs = await resolveBlocks(db, missing, docOf);
109
113
  if (figs.length) console.log("figure completion:", figs.map((b) => b.unit_id).join(", "), "attached from D1");
110
114
  return figs;
111
115
  }
@@ -7,6 +7,7 @@
7
7
  // the producer-validated D1 unit_payloads table.
8
8
 
9
9
  import type { StoreQuery } from "./ports/store.ts";
10
+ import { unitPayloadRows, type UnitKey } from "./unitPayloads.ts";
10
11
  export interface ResolvedBlock {
11
12
  unit_id: string;
12
13
  type: string;
@@ -58,42 +59,35 @@ export function sanitizeRefs(text: string, available: ReadonlySet<string>): { te
58
59
  return { text: out, dropped };
59
60
  }
60
61
 
61
- /** Resolve validated refs to producer payloads from D1 (unit_payloads).
62
- * Unknown-to-D1 ids are skipped — a ref without a payload renders as a
63
- * plain token, never as fabricated data. */
62
+ /** Resolve validated refs to producer payloads from D1. A ref is tied to
63
+ * the document of the passage that carried the unit (`docs`): the same
64
+ * unit id lives in many publications, and another document's payload is
65
+ * never rendered in its place. Unknown-to-D1 ids are skipped — a ref
66
+ * without a payload renders as a plain token, never as fabricated data. */
64
67
  export async function resolveBlocks(
65
68
  db: StoreQuery,
66
69
  refs: string[],
70
+ docs?: ReadonlyMap<string, UnitKey>,
67
71
  ): Promise<ResolvedBlock[]> {
68
72
  if (!refs.length) return [];
69
73
  const uniq = [...new Set(refs)].slice(0, 12);
74
+ const keys = uniq.map((id) => docs?.get(id) ?? { unit_id: id });
70
75
  const blocks: ResolvedBlock[] = [];
71
- for (let i = 0; i < uniq.length; i += 20) {
72
- const batch = uniq.slice(i, i + 20);
73
- const placeholders = batch.map((_, n) => `?${n + 1}`).join(",");
76
+ for (const r of await unitPayloadRows(db, keys)) {
77
+ if (!r) continue;
78
+ let payload: Record<string, unknown> = {};
74
79
  try {
75
- const res = await db
76
- .prepare(`SELECT unit_id, type, docidentifier, edition, payload FROM unit_payloads WHERE unit_id IN (${placeholders})`)
77
- .bind(...batch)
78
- .all<{ unit_id: string; type: string; docidentifier: string | null; edition: string | null; payload: string }>();
79
- for (const r of res.results) {
80
- let payload: Record<string, unknown> = {};
81
- try {
82
- payload = JSON.parse(String(r.payload));
83
- } catch {
84
- continue;
85
- }
86
- blocks.push({
87
- unit_id: String(r.unit_id),
88
- type: String(r.type),
89
- docidentifier: String(r.docidentifier ?? ""),
90
- edition: r.edition ? String(r.edition) : undefined,
91
- payload,
92
- });
93
- }
94
- } catch (e) {
95
- console.log("resolveBlocks failed:", String(e).slice(0, 150));
80
+ payload = JSON.parse(String(r.payload));
81
+ } catch {
82
+ continue;
96
83
  }
84
+ blocks.push({
85
+ unit_id: String(r.unit_id),
86
+ type: String(r.type),
87
+ docidentifier: String(r.docidentifier ?? ""),
88
+ edition: r.edition ? String(r.edition) : undefined,
89
+ payload,
90
+ });
97
91
  }
98
92
  return blocks;
99
93
  }
@@ -102,13 +96,19 @@ export async function resolveBlocks(
102
96
  export async function contractV2(
103
97
  db: StoreQuery,
104
98
  answer: string,
105
- usedHits: ReadonlyArray<{ metadata: { unit_id?: string | undefined } }>,
99
+ usedHits: ReadonlyArray<{ metadata: { unit_id?: string | undefined; doc_id?: string | undefined; docidentifier?: string | undefined } }>,
106
100
  ): Promise<{ text: string; blocks: ResolvedBlock[]; dropped: string[] }> {
107
101
  const available = availableUnitIds(usedHits);
108
102
  const { text, dropped } = sanitizeRefs(answer, available);
109
103
  if (dropped.length) console.log("refs: dropped", dropped.length, "invalid (not in passages)");
110
104
  const refs = parseRefs(text);
111
- const blocks = await resolveBlocks(db, refs);
105
+ // each ref resolves within the document of the passage that carried it
106
+ const docs = new Map<string, UnitKey>();
107
+ for (const h of usedHits) {
108
+ const u = h.metadata?.unit_id;
109
+ if (u && !docs.has(u)) docs.set(u, { unit_id: u, doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier });
110
+ }
111
+ const blocks = await resolveBlocks(db, refs, docs);
112
112
  return { text, blocks, dropped };
113
113
  }
114
114
 
@@ -9,6 +9,7 @@
9
9
  // projection like any stage (ablate_stages drops it).
10
10
  import { roleModel } from "../config.ts";
11
11
  import { portBlobs, portModelRunner, portStore } from "../env.ts";
12
+ import { unitPayloadRows } from "../unitPayloads.ts";
12
13
  import type { Stage } from "./types.ts";
13
14
  import type { Hit } from "../../../shared/chunk";
14
15
 
@@ -29,14 +30,21 @@ export const vlmFigureRerank: Stage = {
29
30
  const figures = c.finalHits.filter((h: Hit) => (h.metadata as any).block === "figure" && (h.metadata as any).unit_id).slice(0, 3);
30
31
  if (!figures.length) return;
31
32
  try {
32
- const ids = figures.map((h: Hit) => String((h.metadata as any).unit_id));
33
- const ph = ids.map((_, i) => `?${i + 1}`).join(",");
34
- const rows = await portStore(c.env).prepare(
35
- `SELECT unit_id, json_extract(payload,'$.uri') AS uri FROM unit_payloads WHERE unit_id IN (${ph})`,
36
- )
37
- .bind(...ids)
38
- .all();
39
- const uris = new Map(((rows.results ?? []) as any[]).map((r: any) => [r.unit_id as string, r.uri as string | null]));
33
+ // each figure's pixels come from its OWN document's payload — the unit id alone is shared across publications
34
+ const rows = await unitPayloadRows(
35
+ portStore(c.env),
36
+ figures.map((h: Hit) => ({ unit_id: String(h.metadata.unit_id), doc_id: h.metadata.doc_id, docidentifier: h.metadata.docidentifier })),
37
+ );
38
+ const uris = new Map<string, string>();
39
+ rows.forEach((row, i) => {
40
+ if (!row) return;
41
+ try {
42
+ const uri = JSON.parse(String(row.payload))?.uri;
43
+ if (typeof uri === "string") uris.set(String(figures[i].metadata.unit_id), uri);
44
+ } catch {
45
+ // no readable payload — the figure reranks without its pixels
46
+ }
47
+ });
40
48
  // the multimodal gotcha (2026-09-09): image parts ride a SHORT
41
49
  // message — the question and the labels, nothing else
42
50
  const content: any[] = [
@@ -0,0 +1,92 @@
1
+ // Typed-unit payloads are per DOCUMENT: a unit id is unique only within
2
+ // its publication — `u:table-1` exists in eleven of them. The legacy
3
+ // unit_payloads table is keyed by unit_id alone, so every MKO load
4
+ // overwrote the earlier documents' payloads and a reference resolved to
5
+ // whichever document loaded last (observed 2026-12-05: an answer citing
6
+ // OIML R 60-1 §5.1.2 Table 1 rendered OIML R 91-2's influence-factors
7
+ // table under it). unit_payloads_doc is keyed by (unit_id, doc_id); a
8
+ // legacy row stands only for the document that cited the unit.
9
+ import type { StoreQuery } from "./ports/store.ts";
10
+
11
+ export interface UnitRow {
12
+ unit_id: string;
13
+ doc_id: string | null;
14
+ type: string;
15
+ docidentifier: string | null;
16
+ edition: string | null;
17
+ payload: string;
18
+ }
19
+
20
+ /** A unit as its citing passage names it: the id and the document. */
21
+ export interface UnitKey {
22
+ unit_id: string;
23
+ doc_id?: string | null;
24
+ docidentifier?: string | null;
25
+ }
26
+
27
+ const COLS = "unit_id, doc_id, type, docidentifier, edition, payload";
28
+
29
+ /** May a legacy row stand for this key? A key that names no document
30
+ * keeps the legacy reading (the by-id tool contract); one that names a
31
+ * document accepts only that document's row — another publication's
32
+ * payload is never rendered in its place. */
33
+ function belongs(row: UnitRow, key: UnitKey): boolean {
34
+ if (!key.doc_id && !key.docidentifier) return true;
35
+ if (key.doc_id) return row.doc_id === key.doc_id;
36
+ return row.docidentifier === key.docidentifier;
37
+ }
38
+
39
+ async function byIds(db: StoreQuery, table: string, ids: string[]): Promise<UnitRow[] | null> {
40
+ const ph = ids.map((_, i) => `?${i + 1}`).join(",");
41
+ try {
42
+ const res = await db.prepare(`SELECT ${COLS} FROM ${table} WHERE unit_id IN (${ph})`).bind(...ids).all<UnitRow>();
43
+ return res.results ?? [];
44
+ } catch {
45
+ return null; // a deployment without that table
46
+ }
47
+ }
48
+
49
+ /** The payload rows for the given unit keys, aligned with them: null
50
+ * where no row belongs to the citing document. The document-scoped
51
+ * table answers first; the legacy table fills a key only with its own
52
+ * document's row. */
53
+ export async function unitPayloadRows(db: StoreQuery, keys: readonly UnitKey[]): Promise<(UnitRow | null)[]> {
54
+ const out: (UnitRow | null)[] = new Array(keys.length).fill(null);
55
+ if (!keys.length) return out;
56
+ const ids = [...new Set(keys.map((k) => k.unit_id))];
57
+ const scoped = keys.some((k) => k.doc_id) ? await byIds(db, "unit_payloads_doc", ids) : null;
58
+ const byDoc = new Map<string, UnitRow>();
59
+ for (const r of scoped ?? []) byDoc.set(`${r.unit_id}|${r.doc_id}`, r);
60
+ const legacy = new Map<string, UnitRow>();
61
+ for (const r of (await byIds(db, "unit_payloads", ids)) ?? []) if (!legacy.has(r.unit_id)) legacy.set(r.unit_id, r);
62
+ keys.forEach((key, i) => {
63
+ let row: UnitRow | null = key.doc_id ? (byDoc.get(`${key.unit_id}|${key.doc_id}`) ?? null) : null;
64
+ const l = legacy.get(key.unit_id);
65
+ if (!row && l && belongs(l, key)) row = l;
66
+ out[i] = row;
67
+ });
68
+ return out;
69
+ }
70
+
71
+ /** Every unit of one type under a publication (by docidentifier
72
+ * pattern), from the document-scoped table — or the legacy one where
73
+ * that deployment has none. */
74
+ export async function publicationUnitRows(
75
+ db: StoreQuery,
76
+ type: string,
77
+ docidentifierLike: string,
78
+ limit: number,
79
+ ): Promise<UnitRow[]> {
80
+ for (const table of ["unit_payloads_doc", "unit_payloads"]) {
81
+ try {
82
+ const res = await db
83
+ .prepare(`SELECT ${COLS} FROM ${table} WHERE type = ?1 AND docidentifier LIKE ?2 LIMIT ${limit}`)
84
+ .bind(type, docidentifierLike)
85
+ .all<UnitRow>();
86
+ return res.results ?? [];
87
+ } catch {
88
+ // the document-scoped table is absent — the legacy one stands
89
+ }
90
+ }
91
+ return [];
92
+ }