@konneal/engine 0.2.191 → 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.
@@ -4,10 +4,10 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-ECNBEZGK.js";
8
- import "./chunk-AVNHVFEB.js";
9
- import "./chunk-7YMIUTPY.js";
10
- import "./chunk-22WB6IVC.js";
7
+ } from "./chunk-UZHUND67.js";
8
+ import "./chunk-QYNFNOKE.js";
9
+ import "./chunk-J4UAO5XI.js";
10
+ import "./chunk-5Y3CDK64.js";
11
11
  import "./chunk-3FYJM7LH.js";
12
12
  import "./chunk-H6ZULBW2.js";
13
13
  export {
@@ -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[]>;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  authenticate
3
- } from "../../chunk-GJQT4IMD.js";
4
- import "../../chunk-22WB6IVC.js";
3
+ } from "../../chunk-M4OCMIWU.js";
4
+ import "../../chunk-5Y3CDK64.js";
5
5
  import {
6
6
  P,
7
7
  setProfile
@@ -18,7 +18,7 @@ import {
18
18
  roleModel,
19
19
  sha256Hex,
20
20
  today
21
- } from "../../chunk-22WB6IVC.js";
21
+ } from "../../chunk-5Y3CDK64.js";
22
22
  import "../../chunk-3FYJM7LH.js";
23
23
  export {
24
24
  DATASETS,
@@ -9,16 +9,16 @@ import {
9
9
  listUserDocuments,
10
10
  scoreFaithfulness,
11
11
  scoreJudge
12
- } from "../../chunk-SWCKO4OB.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-ECNBEZGK.js";
18
+ } from "../../chunk-UZHUND67.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-CW6J3HTM.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-3SGGVZZ4.js";
46
+ } from "../../chunk-73GZKS2T.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
50
- } from "../../chunk-AVNHVFEB.js";
50
+ } from "../../chunk-QYNFNOKE.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-GJQT4IMD.js";
59
+ } from "../../chunk-M4OCMIWU.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-7YMIUTPY.js";
66
+ } from "../../chunk-J4UAO5XI.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-22WB6IVC.js";
77
+ } from "../../chunk-5Y3CDK64.js";
78
78
  import {
79
79
  P,
80
80
  setProfile
@@ -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-7GKMDWVB.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-WKHYCVT5.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-KIN474QS.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 });
@@ -4,8 +4,8 @@ import {
4
4
  requestSalt,
5
5
  resolveRequestScope,
6
6
  standardKeysFrom
7
- } from "../../chunk-7YMIUTPY.js";
8
- import "../../chunk-22WB6IVC.js";
7
+ } from "../../chunk-J4UAO5XI.js";
8
+ import "../../chunk-5Y3CDK64.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.191",
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
  }
@@ -181,6 +181,19 @@ export const THRESHOLDS = {
181
181
  /** Section-descent child discount — children fetched from a ranked
182
182
  * depth-1 summary enter discounted. */
183
183
  sectionDescentDiscount: 0.8,
184
+ /** Typed-pin label weight — for an object-seeking question (a stated
185
+ * value, a named table/figure/formula) a query term met in a unit's
186
+ * LABELS (caption, column headers, row labels) is worth this many
187
+ * body mentions. A blank report form mentions every term of the
188
+ * question and holds no answer: measured 2026-12-05 on the R 60
189
+ * family, the test-report symbol list scored 10 against the limits
190
+ * table's 8 and was pinned — the gate lost the class-B value. */
191
+ typedLabelWeight: 4,
192
+ /** Typed-pin clause completion — how many of the top-ranked prose
193
+ * clauses have their typed siblings (table/figure/formula under the
194
+ * same exact clause) fetched from D1, so the answering object is a
195
+ * candidate even when no retrieval lane surfaced it. */
196
+ typedSiblingProse: 5,
184
197
  /** History budget share — the fraction of the context budget the
185
198
  * conversation slice may consume; older turns overflow into the
186
199
  * compacted summary instead of starving the passages. */
@@ -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
 
@@ -5,12 +5,92 @@
5
5
  // without this guarantee the model never sees a unit id to reference.
6
6
  // Includes the small-to-big parent fetch: an embedded object answers
7
7
  // WITH its clause — if the parent clause's prose passage is not already
8
- // among the finals, one metadata-filtered fetch adds it. The typed unit
9
- // cites; the clause grounds.
8
+ // among the finals, one D1 read adds it. The typed unit cites; the
9
+ // clause grounds. And the reverse — clause completion: a ranked clause
10
+ // whose typed object no lane retrieved gets that object from D1.
10
11
  import { LIMITS, THRESHOLDS } from "../config.ts";
11
12
  import type { Hit } from "../../../shared/chunk";
12
13
  import type { Stage } from "./types.ts";
13
14
 
15
+ const UNIT_COLS =
16
+ "id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block";
17
+
18
+ /** Question shapes whose ANSWER is a typed object: a stated quantity
19
+ * (minimum/maximum, a number, a limit, an MPE…) or a named
20
+ * table/figure/formula. Only these get the label-weighted pick and the
21
+ * clause completion — every other question keeps the plain overlap
22
+ * pick it had. */
23
+ const OBJECT_SEEKING =
24
+ /\b(minimum|maximum|min|max|least|lowest|highest|numbers?|counts?|values?|limits?|ranges?|mpe|errors?|intervals?|tiers?|tables?|figures?|formulas?|equations?)\b|how many/i;
25
+
26
+ /** Function words: they match a label by accident, never by meaning. */
27
+ const LABEL_STOP = new Set([
28
+ "the", "and", "for", "per", "with", "from", "into", "that", "this", "what", "which", "according",
29
+ "does", "are", "how", "why", "when", "where", "who", "its", "their", "there", "about", "between",
30
+ "across", "after", "before", "not", "can", "must", "shall", "has", "have", "had", "was", "were",
31
+ "will", "would", "should",
32
+ ]);
33
+
34
+ /** The serialized unit's structural labels — its caption, its column
35
+ * headers and its row labels: the parts that declare WHAT the object
36
+ * holds. Body cells merely mention. */
37
+ function labelText(h: Hit): string {
38
+ const t = h.text.toLowerCase();
39
+ const cols = /columns:(.*?)(?:; row:|$)/s.exec(t)?.[1] ?? "";
40
+ const rows = [...t.matchAll(/(?:^|; )row: ([^|]+)/g)].map((m) => m[1]).join(" ");
41
+ return `${h.metadata.clause_title ?? ""} ${cols} ${rows}`.toLowerCase();
42
+ }
43
+
44
+ /** The exact clause a hit speaks for. An MKO clause unit can carry its
45
+ * parent's anchor ("5.1" for §5.1.2) while its unit id names the
46
+ * clause; a plain chunk's anchor is its own. */
47
+ function clauseKeyOf(h: Hit): string {
48
+ const m = /^u:sec-(.+)$/.exec(String(h.metadata.unit_id ?? ""));
49
+ const key = m ? m[1] : String(h.metadata.clause_anchor ?? "");
50
+ return /^(\d+|[A-Z])(\.\d+)*[A-Z]?$/.test(key) ? key : "";
51
+ }
52
+
53
+ /** A prose passage for the pin's purposes: not a summary, and not a
54
+ * table/figure/formula unit (an MKO clause unit has a unit id and
55
+ * block "clause" — it is still prose). */
56
+ const isProse = (h: Hit) =>
57
+ !h.metadata.section_summary && (!h.metadata.unit_id || h.metadata.block === "clause" || !h.metadata.block);
58
+
59
+ /** Clause completion (big-to-small): the typed objects sitting under the
60
+ * top-ranked prose clauses, read from D1 by doc + exact clause. */
61
+ async function siblingUnits(env: any, prose: Hit[]): Promise<Hit[]> {
62
+ if (!env.DB || !prose.length) return [];
63
+ const found = await Promise.all(
64
+ prose.map(async (h) => {
65
+ const docId = String(h.metadata.doc_id ?? "");
66
+ const key = clauseKeyOf(h);
67
+ if (!docId || !key) return [];
68
+ try {
69
+ const res = await env.DB.prepare(
70
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND block IN ('table','figure','formula') AND unit_id != '' LIMIT 8`,
71
+ )
72
+ .bind(docId, key)
73
+ .all();
74
+ return (res.results ?? []).map(
75
+ (r: any) =>
76
+ ({
77
+ id: String(r.id),
78
+ // it arrives through a ranked passage, like a descent child
79
+ score: h.score * THRESHOLDS.sectionDescentDiscount,
80
+ metadata: r,
81
+ text: String(r.text ?? ""),
82
+ }) as Hit,
83
+ );
84
+ } catch {
85
+ return []; // additive lane; the retrieved pool stands
86
+ }
87
+ }),
88
+ );
89
+ const out: Hit[] = [];
90
+ for (const list of found) for (const h of list) if (!out.some((x) => x.id === h.id)) out.push(h);
91
+ return out;
92
+ }
93
+
14
94
  /** Typed-chunk selection for the pin: among a doc's typed units pick the
15
95
  * one whose text best overlaps the QUERY (the first candidate is wrong as
16
96
  * often as right — annex example tables outrank nothing). Lexical-overlap
@@ -20,12 +100,16 @@ import type { Stage } from "./types.ts";
20
100
  * still pin their table on overlap. When the query NAMES an artifact type
21
101
  * ("figure", "table", "formula"/"equation"), units of that type get a
22
102
  * dominating bonus — without it, clause units of the § tie with the
23
- * figure under rerank variance and the multimodal answer flips on luck. */
103
+ * figure under rerank variance and the multimodal answer flips on luck.
104
+ * For an object-seeking question the unit's LABELS are weighted over its
105
+ * body: the test-report format lists every quantity name of the family
106
+ * in blank forms, which win a plain term count and answer nothing. */
24
107
  function pickTypedChunk(query: string, candidates: Hit[], ranked: Hit[]): Hit | null {
25
108
  if (!candidates.length) return null;
26
109
  const pool = candidates;
27
110
  const q = query.toLowerCase();
28
111
  const terms = q.replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length > 2);
112
+ const labelTerms = OBJECT_SEEKING.test(q) ? terms.filter((t) => !LABEL_STOP.has(t)) : [];
29
113
  const typeBonus: Record<string, number> = {};
30
114
  if (/\bfig(ure)?s?\b/.test(q)) typeBonus.figure = 1;
31
115
  if (/\btables?\b/.test(q)) typeBonus.table = 1;
@@ -48,6 +132,10 @@ function pickTypedChunk(query: string, candidates: Hit[], ranked: Hit[]): Hit |
48
132
  const filled = cells.filter((x) => x.length > 0).length;
49
133
  const density = cells.length ? filled / cells.length : 0;
50
134
  score += density * 2;
135
+ if (labelTerms.length) {
136
+ const labels = labelText(h);
137
+ for (const t of labelTerms) if (labels.includes(t)) score += THRESHOLDS.typedLabelWeight;
138
+ }
51
139
  if (score > bestScore) {
52
140
  bestScore = score;
53
141
  best = h;
@@ -87,7 +175,29 @@ export const typedPin: Stage = {
87
175
  // pins only on real query overlap — the picker always returns
88
176
  // SOMETHING, and a near-zero-overlap table riding the window on
89
177
  // every vocabulary-linked query would be pollution.
90
- const typed = pickTypedChunk(query, hits.filter(sameDocTyped), hits);
178
+ let pool = hits.filter(sameDocTyped);
179
+ const fromClause = new Set<string>();
180
+ if (OBJECT_SEEKING.test(query.toLowerCase())) {
181
+ // clause completion: the answering clause ranks while its table
182
+ // does not (measured 2026-12-05 — R 60-1 §5.1.2's prose was in
183
+ // the window with a blank table cross-reference; its limits
184
+ // table was in the index and in no lane's candidates)
185
+ const prose = hits
186
+ .filter((h) => isProse(h) && pinFamilies.has(base(h.metadata.doc_number)))
187
+ .slice(0, THRESHOLDS.typedSiblingProse);
188
+ const siblings = (await siblingUnits(env, prose)).filter(
189
+ (x) => !pool.some((h) => h.id === x.id) && !c.finalHits.some((h) => h.id === x.id),
190
+ );
191
+ if (siblings.length) {
192
+ pool = [...pool, ...siblings];
193
+ for (const x of siblings) fromClause.add(x.id);
194
+ console.log(
195
+ "typed pin: clause completion —",
196
+ siblings.map((x) => `${x.metadata.docidentifier} §${x.metadata.clause_anchor} (${x.metadata.block})`).join(", "),
197
+ );
198
+ }
199
+ }
200
+ const typed = pickTypedChunk(query, pool, hits);
91
201
  const hardScope = !!pinFamily;
92
202
  const overlap = (() => {
93
203
  if (!typed || hardScope) return Infinity;
@@ -102,7 +212,7 @@ export const typedPin: Stage = {
102
212
  const tableExempt = typed?.metadata.block === "table";
103
213
  if (typed && (overlap >= 3 || tableExempt) && !c.finalHits.some((h) => h.id === typed.id)) {
104
214
  c.finalHits = [...c.finalHits.slice(0, LIMITS.rerankKeep - 1), typed];
105
- console.log("typed pin:", typed.metadata.docidentifier, "§", typed.metadata.clause_anchor, `(${typed.metadata.block})${hardScope ? "" : " [glossary families]"}`);
215
+ console.log("typed pin:", typed.metadata.docidentifier, "§", typed.metadata.clause_anchor, `(${typed.metadata.block})${fromClause.has(typed.id) ? " [clause sibling]" : ""}${hardScope ? "" : " [glossary families]"}`);
106
216
 
107
217
  const anchor = typed.metadata.clause_anchor;
108
218
  const docId = typed.metadata.doc_id;
@@ -114,7 +224,7 @@ export const typedPin: Stage = {
114
224
  // Read the parent prose clause from D1 directly: Vectorize rejects
115
225
  // $and arrays (40026) and does not index doc_id / clause_anchor.
116
226
  const res = await env.DB.prepare(
117
- "SELECT id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2",
227
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2`,
118
228
  )
119
229
  .bind(docId, anchor)
120
230
  .all();
@@ -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[] = [