@konneal/engine 0.2.192 → 0.2.194

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-GJHB3LY4.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-2DBXRO4E.js";
6
+ import "./chunk-JEPZ7SNP.js";
7
+ import "./chunk-5OSQMWRV.js";
8
8
  import "./chunk-M4OCMIWU.js";
9
9
  import "./chunk-ETLSWSZ7.js";
10
10
  import "./chunk-J4UAO5XI.js";
@@ -1,6 +1,7 @@
1
1
  import {
2
- embed
3
- } from "./chunk-VGBZYYVH.js";
2
+ embed,
3
+ unitPayloadRows
4
+ } from "./chunk-5OSQMWRV.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) {
@@ -71,10 +71,66 @@ 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
+ async function writeUnitDescription(db, unitId, description, docId) {
118
+ if (docId) {
119
+ try {
120
+ await db.prepare("UPDATE unit_payloads_doc SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND doc_id = ?3").bind(description, unitId, docId).run();
121
+ } catch {
122
+ }
123
+ }
124
+ await db.prepare("UPDATE unit_payloads SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND (?3 IS NULL OR doc_id = ?3)").bind(description, unitId, docId ?? null).run();
125
+ }
126
+
74
127
  export {
75
128
  embed,
76
129
  isCapacityError,
77
130
  CAPACITY_PAUSE_MS,
78
131
  rerank,
79
- generateOnce
132
+ generateOnce,
133
+ unitPayloadRows,
134
+ publicationUnitRows,
135
+ writeUnitDescription
80
136
  };
@@ -6,7 +6,7 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-W4F22Y4M.js";
9
+ } from "./chunk-JEPZ7SNP.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-NHNCW6KQ.js";
36
+ } from "./chunk-2DBXRO4E.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-JEPZ7SNP.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-5OSQMWRV.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,7 +1,8 @@
1
1
  import {
2
2
  embed,
3
- rerank
4
- } from "./chunk-VGBZYYVH.js";
3
+ rerank,
4
+ unitPayloadRows
5
+ } from "./chunk-5OSQMWRV.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",
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-6HW7R5SI.js";
4
+ import "./chunk-JEPZ7SNP.js";
5
+ import "./chunk-5OSQMWRV.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-2DBXRO4E.js";
8
+ import "./chunk-5OSQMWRV.js";
9
9
  import "./chunk-J4UAO5XI.js";
10
10
  import "./chunk-5Y3CDK64.js";
11
11
  import "./chunk-3FYJM7LH.js";
@@ -0,0 +1,29 @@
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[]>;
25
+ /** Store a generated description on a unit — on its document's row when
26
+ * the document is known, and on the legacy row only when that row IS
27
+ * the same document's: a bare unit id names the last writer, and a
28
+ * caption meant for one publication must never land on another's. */
29
+ export declare function writeUnitDescription(db: StoreQuery, unitId: string, description: string, docId?: string | null): Promise<void>;
@@ -9,16 +9,16 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-ZPNYAANP.js";
12
+ } from "../../chunk-GJHB3LY4.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-2DBXRO4E.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-UDHM3G5N.js";
21
+ } from "../../chunk-6HW7R5SI.js";
22
22
  import {
23
23
  buildMessages,
24
24
  citations,
@@ -43,11 +43,13 @@ import {
43
43
  sessionFrom,
44
44
  telemetry,
45
45
  understandQuery
46
- } from "../../chunk-W4F22Y4M.js";
46
+ } from "../../chunk-JEPZ7SNP.js";
47
47
  import {
48
48
  embed,
49
- generateOnce
50
- } from "../../chunk-VGBZYYVH.js";
49
+ generateOnce,
50
+ unitPayloadRows,
51
+ writeUnitDescription
52
+ } from "../../chunk-5OSQMWRV.js";
51
53
  import {
52
54
  authenticate,
53
55
  corsHeaders,
@@ -589,8 +591,8 @@ ${chain || "(no successor edges recorded)"}` }
589
591
  return err(502, "family_summary_failed", String(e?.message ?? e).slice(0, 200));
590
592
  }
591
593
  }
592
- async function loadUnitAsset(env, unitId) {
593
- const row = await env.DB.prepare("SELECT payload, docidentifier FROM unit_payloads WHERE unit_id = ?1").bind(unitId).first();
594
+ async function loadUnitAsset(env, unitId, docId) {
595
+ const [row] = await unitPayloadRows(env.DB, [{ unit_id: unitId, doc_id: docId || null }]);
594
596
  if (!row) return { error: err(404, "not_found", "no unit_payload row for that id") };
595
597
  const payload = JSON.parse(String(row.payload));
596
598
  const uri = payload.uri ?? "";
@@ -612,11 +614,12 @@ async function handleVisionJudge(env, req) {
612
614
  if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
613
615
  const body = await readJson(req);
614
616
  const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
617
+ const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
615
618
  const capA = typeof body?.captions?.a === "string" ? body.captions.a.slice(0, 2e3) : "";
616
619
  const capB = typeof body?.captions?.b === "string" ? body.captions.b.slice(0, 2e3) : "";
617
620
  if (!unitId || !capA || !capB) return err(400, "invalid_input", "unit_id and captions.a/.b required");
618
621
  try {
619
- const loaded = await loadUnitAsset(env, unitId);
622
+ const loaded = await loadUnitAsset(env, unitId, docId);
620
623
  if (loaded.error) return loaded.error;
621
624
  const swap = Math.random() < 0.5;
622
625
  const first = swap ? capB : capA;
@@ -659,12 +662,13 @@ async function handleCaption(env, req) {
659
662
  if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
660
663
  const body = await readJson(req);
661
664
  const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
665
+ const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
662
666
  const context = typeof body?.context === "string" ? body.context.slice(0, 400) : "";
663
667
  const override = typeof body?.model === "string" && body.model.startsWith("@cf/") ? body.model : null;
664
668
  const dryRun = body?.dry_run === true;
665
669
  if (!unitId) return err(400, "invalid_input", "unit_id required");
666
670
  try {
667
- const loaded = await loadUnitAsset(env, unitId);
671
+ const loaded = await loadUnitAsset(env, unitId, docId);
668
672
  if (loaded.error) return loaded.error;
669
673
  const row = loaded.row;
670
674
  const b64 = loaded.b64;
@@ -700,8 +704,8 @@ async function handleCaption(env, req) {
700
704
  const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));
701
705
  return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
702
706
  })();
703
- if (!dryRun) await env.DB.prepare("UPDATE unit_payloads SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2").bind(desc, unitId).run();
704
- return json({ ok: true, unit_id: unitId, model: override ?? roleModel(env, "caption"), dry_run: dryRun || void 0, description: desc });
707
+ if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
708
+ return json({ ok: true, unit_id: unitId, doc_id: docId || void 0, model: override ?? roleModel(env, "caption"), dry_run: dryRun || void 0, description: desc });
705
709
  } catch (e) {
706
710
  return err(502, "caption_failed", String(e).slice(0, 200));
707
711
  }
@@ -1184,13 +1188,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1184
1188
  // stream:false forces the JSON lane (anon defaults to SSE)
1185
1189
  body: JSON.stringify({ ...args, stream: false })
1186
1190
  });
1187
- const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-LOQBTAFQ.js");
1191
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-JBCL7UQO.js");
1188
1192
  let payload;
1189
1193
  if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
1190
1194
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1191
1195
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1192
1196
  } 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);
1197
+ const res = name === "ask" ? await (await import("../../ask-CDJCSFI4.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-3V6EFKFX.js")).handleSearch(env, ctx, inner, tier, key);
1194
1198
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1195
1199
  }
1196
1200
  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.194",
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",
@@ -15,6 +15,7 @@ import precisionPrompt from "../prompts/precision.md";
15
15
  import { scoreFaithfulness } from "./faithfulness";
16
16
  import { scoreJudge } from "./grader";
17
17
  import { portModelRunner } from "./env.ts";
18
+ import { unitPayloadRows, writeUnitDescription } from "./unitPayloads.ts";
18
19
  import { P } from "./profile.ts";
19
20
  import { fill, promptVars } from "./pipeline.ts";
20
21
 
@@ -265,9 +266,11 @@ export async function handleFamilySummary(env: Env, req: Request): Promise<Respo
265
266
  * passes like embedding smoothing (G-ETSI-4) — the binding is the
266
267
  * credential, admin-token gated exactly like /admin/enrich. */
267
268
  /** The unit's vision asset, base64-encoded for the message part — the
268
- * one load path the caption and the pairwise judge share. */
269
- async function loadUnitAsset(env: Env, unitId: string) {
270
- const row = await env.DB.prepare("SELECT payload, docidentifier FROM unit_payloads WHERE unit_id = ?1").bind(unitId).first<any>();
269
+ * one load path the caption and the pairwise judge share. The unit is
270
+ * read within its document when the caller names one: a unit id alone
271
+ * is shared across publications and names only its last writer. */
272
+ async function loadUnitAsset(env: Env, unitId: string, docId?: string) {
273
+ const [row] = await unitPayloadRows(env.DB, [{ unit_id: unitId, doc_id: docId || null }]);
271
274
  if (!row) return { error: err(404, "not_found", "no unit_payload row for that id") };
272
275
  const payload = JSON.parse(String(row.payload));
273
276
  const uri = payload.uri ?? "";
@@ -296,11 +299,12 @@ export async function handleVisionJudge(env: Env, req: Request): Promise<Respons
296
299
  if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
297
300
  const body = await readJson(req);
298
301
  const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
302
+ const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
299
303
  const capA = typeof body?.captions?.a === "string" ? body.captions.a.slice(0, 2000) : "";
300
304
  const capB = typeof body?.captions?.b === "string" ? body.captions.b.slice(0, 2000) : "";
301
305
  if (!unitId || !capA || !capB) return err(400, "invalid_input", "unit_id and captions.a/.b required");
302
306
  try {
303
- const loaded = await loadUnitAsset(env, unitId);
307
+ const loaded = await loadUnitAsset(env, unitId, docId);
304
308
  if (loaded.error) return loaded.error;
305
309
  // randomized presentation order: the judge's letter bias must not
306
310
  // correlate with either arm
@@ -344,15 +348,16 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
344
348
  if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
345
349
  const body = await readJson(req);
346
350
  const unitId = typeof body?.unit_id === "string" ? body.unit_id : "";
351
+ const docId = typeof body?.doc_id === "string" ? body.doc_id.slice(0, 200) : "";
347
352
  const context = typeof body?.context === "string" ? body.context.slice(0, 400) : "";
348
353
  // the A/B arm (TODO.sota/18.4): a per-request model override for the
349
354
  // measurement, admin-gated like the route itself; dry_run skips the
350
- // payload write so the arms never mix state in unit_payloads
355
+ // payload write so the arms never mix state in the unit payloads
351
356
  const override = typeof body?.model === "string" && body.model.startsWith("@cf/") ? body.model : null;
352
357
  const dryRun = body?.dry_run === true;
353
358
  if (!unitId) return err(400, "invalid_input", "unit_id required");
354
359
  try {
355
- const loaded = await loadUnitAsset(env, unitId);
360
+ const loaded = await loadUnitAsset(env, unitId, docId);
356
361
  if (loaded.error) return loaded.error;
357
362
  const row = loaded.row;
358
363
  const b64 = loaded.b64;
@@ -395,8 +400,8 @@ export async function handleCaption(env: Env, req: Request): Promise<Response> {
395
400
  const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));
396
401
  return end === -1 ? cut.slice(0, cut.lastIndexOf(" ")) : cut.slice(0, end + 1);
397
402
  })();
398
- if (!dryRun) await env.DB.prepare("UPDATE unit_payloads SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2").bind(desc, unitId).run();
399
- return json({ ok: true, unit_id: unitId, model: override ?? roleModel(env, "caption"), dry_run: dryRun || undefined, description: desc });
403
+ if (!dryRun) await writeUnitDescription(env.DB, unitId, desc, docId);
404
+ return json({ ok: true, unit_id: unitId, doc_id: docId || undefined, model: override ?? roleModel(env, "caption"), dry_run: dryRun || undefined, description: desc });
400
405
  } catch (e) {
401
406
  return err(502, "caption_failed", String(e).slice(0, 200));
402
407
  }
@@ -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,113 @@
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
+ }
93
+
94
+ /** Store a generated description on a unit — on its document's row when
95
+ * the document is known, and on the legacy row only when that row IS
96
+ * the same document's: a bare unit id names the last writer, and a
97
+ * caption meant for one publication must never land on another's. */
98
+ export async function writeUnitDescription(db: StoreQuery, unitId: string, description: string, docId?: string | null): Promise<void> {
99
+ if (docId) {
100
+ try {
101
+ await db
102
+ .prepare("UPDATE unit_payloads_doc SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND doc_id = ?3")
103
+ .bind(description, unitId, docId)
104
+ .run();
105
+ } catch {
106
+ // a deployment without the document-scoped table
107
+ }
108
+ }
109
+ await db
110
+ .prepare("UPDATE unit_payloads SET payload = json_set(payload, '$.description', ?1) WHERE unit_id = ?2 AND (?3 IS NULL OR doc_id = ?3)")
111
+ .bind(description, unitId, docId ?? null)
112
+ .run();
113
+ }