@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.
@@ -0,0 +1,16 @@
1
+ import {
2
+ handleAsk
3
+ } from "./chunk-RX7FL5D6.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-UZHUND67.js";
6
+ import "./chunk-73GZKS2T.js";
7
+ import "./chunk-QYNFNOKE.js";
8
+ import "./chunk-M4OCMIWU.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-J4UAO5XI.js";
11
+ import "./chunk-5Y3CDK64.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-H6ZULBW2.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -6,25 +6,25 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-3SGGVZZ4.js";
9
+ } from "./chunk-73GZKS2T.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-GJQT4IMD.js";
16
+ } from "./chunk-M4OCMIWU.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-7YMIUTPY.js";
20
+ } from "./chunk-J4UAO5XI.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  roleModel,
26
26
  sha256Hex
27
- } from "./chunk-22WB6IVC.js";
27
+ } from "./chunk-5Y3CDK64.js";
28
28
  import {
29
29
  portModelRunner
30
30
  } from "./chunk-H6ZULBW2.js";
@@ -177,6 +177,19 @@ var THRESHOLDS = {
177
177
  /** Section-descent child discount — children fetched from a ranked
178
178
  * depth-1 summary enter discounted. */
179
179
  sectionDescentDiscount: 0.8,
180
+ /** Typed-pin label weight — for an object-seeking question (a stated
181
+ * value, a named table/figure/formula) a query term met in a unit's
182
+ * LABELS (caption, column headers, row labels) is worth this many
183
+ * body mentions. A blank report form mentions every term of the
184
+ * question and holds no answer: measured 2026-12-05 on the R 60
185
+ * family, the test-report symbol list scored 10 against the limits
186
+ * table's 8 and was pinned — the gate lost the class-B value. */
187
+ typedLabelWeight: 4,
188
+ /** Typed-pin clause completion — how many of the top-ranked prose
189
+ * clauses have their typed siblings (table/figure/formula under the
190
+ * same exact clause) fetched from D1, so the answering object is a
191
+ * candidate even when no retrieval lane surfaced it. */
192
+ typedSiblingProse: 5,
180
193
  /** History budget share — the fraction of the context budget the
181
194
  * conversation slice may consume; older turns overflow into the
182
195
  * compacted summary instead of starving the passages. */
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  embed,
3
- rerank
4
- } from "./chunk-AVNHVFEB.js";
3
+ rerank,
4
+ unitPayloadRows
5
+ } from "./chunk-QYNFNOKE.js";
5
6
  import {
6
7
  bubbleConfirmPage,
7
8
  isAllowedBubbleOrigin
8
- } from "./chunk-GJQT4IMD.js";
9
+ } from "./chunk-M4OCMIWU.js";
9
10
  import {
10
11
  DATASETS,
11
12
  LIMITS,
@@ -17,7 +18,7 @@ import {
17
18
  roleModel,
18
19
  sha256Hex,
19
20
  today
20
- } from "./chunk-22WB6IVC.js";
21
+ } from "./chunk-5Y3CDK64.js";
21
22
  import {
22
23
  P
23
24
  } from "./chunk-3FYJM7LH.js";
@@ -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",
@@ -23337,11 +23345,96 @@ var diversity = {
23337
23345
  };
23338
23346
 
23339
23347
  // workers/worker_public/src/stages/typedPin.ts
23348
+ var UNIT_COLS = "id, doc_id, docidentifier, doctype, doc_number, edition, language, clause_anchor, clause_title, status, superseded_by, corpus, tier, text, unit_id, block";
23349
+ var OBJECT_SEEKING = /\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;
23350
+ var LABEL_STOP = /* @__PURE__ */ new Set([
23351
+ "the",
23352
+ "and",
23353
+ "for",
23354
+ "per",
23355
+ "with",
23356
+ "from",
23357
+ "into",
23358
+ "that",
23359
+ "this",
23360
+ "what",
23361
+ "which",
23362
+ "according",
23363
+ "does",
23364
+ "are",
23365
+ "how",
23366
+ "why",
23367
+ "when",
23368
+ "where",
23369
+ "who",
23370
+ "its",
23371
+ "their",
23372
+ "there",
23373
+ "about",
23374
+ "between",
23375
+ "across",
23376
+ "after",
23377
+ "before",
23378
+ "not",
23379
+ "can",
23380
+ "must",
23381
+ "shall",
23382
+ "has",
23383
+ "have",
23384
+ "had",
23385
+ "was",
23386
+ "were",
23387
+ "will",
23388
+ "would",
23389
+ "should"
23390
+ ]);
23391
+ function labelText(h) {
23392
+ const t = h.text.toLowerCase();
23393
+ const cols = /columns:(.*?)(?:; row:|$)/s.exec(t)?.[1] ?? "";
23394
+ const rows = [...t.matchAll(/(?:^|; )row: ([^|]+)/g)].map((m) => m[1]).join(" ");
23395
+ return `${h.metadata.clause_title ?? ""} ${cols} ${rows}`.toLowerCase();
23396
+ }
23397
+ function clauseKeyOf(h) {
23398
+ const m = /^u:sec-(.+)$/.exec(String(h.metadata.unit_id ?? ""));
23399
+ const key = m ? m[1] : String(h.metadata.clause_anchor ?? "");
23400
+ return /^(\d+|[A-Z])(\.\d+)*[A-Z]?$/.test(key) ? key : "";
23401
+ }
23402
+ var isProse = (h) => !h.metadata.section_summary && (!h.metadata.unit_id || h.metadata.block === "clause" || !h.metadata.block);
23403
+ async function siblingUnits(env, prose) {
23404
+ if (!env.DB || !prose.length) return [];
23405
+ const found = await Promise.all(
23406
+ prose.map(async (h) => {
23407
+ const docId = String(h.metadata.doc_id ?? "");
23408
+ const key = clauseKeyOf(h);
23409
+ if (!docId || !key) return [];
23410
+ try {
23411
+ const res = await env.DB.prepare(
23412
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND block IN ('table','figure','formula') AND unit_id != '' LIMIT 8`
23413
+ ).bind(docId, key).all();
23414
+ return (res.results ?? []).map(
23415
+ (r) => ({
23416
+ id: String(r.id),
23417
+ // it arrives through a ranked passage, like a descent child
23418
+ score: h.score * THRESHOLDS.sectionDescentDiscount,
23419
+ metadata: r,
23420
+ text: String(r.text ?? "")
23421
+ })
23422
+ );
23423
+ } catch {
23424
+ return [];
23425
+ }
23426
+ })
23427
+ );
23428
+ const out = [];
23429
+ for (const list of found) for (const h of list) if (!out.some((x) => x.id === h.id)) out.push(h);
23430
+ return out;
23431
+ }
23340
23432
  function pickTypedChunk(query, candidates, ranked) {
23341
23433
  if (!candidates.length) return null;
23342
23434
  const pool = candidates;
23343
23435
  const q = query.toLowerCase();
23344
23436
  const terms = q.replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length > 2);
23437
+ const labelTerms = OBJECT_SEEKING.test(q) ? terms.filter((t) => !LABEL_STOP.has(t)) : [];
23345
23438
  const typeBonus = {};
23346
23439
  if (/\bfig(ure)?s?\b/.test(q)) typeBonus.figure = 1;
23347
23440
  if (/\btables?\b/.test(q)) typeBonus.table = 1;
@@ -23360,6 +23453,10 @@ function pickTypedChunk(query, candidates, ranked) {
23360
23453
  const filled = cells.filter((x) => x.length > 0).length;
23361
23454
  const density = cells.length ? filled / cells.length : 0;
23362
23455
  score += density * 2;
23456
+ if (labelTerms.length) {
23457
+ const labels = labelText(h);
23458
+ for (const t of labelTerms) if (labels.includes(t)) score += THRESHOLDS.typedLabelWeight;
23459
+ }
23363
23460
  if (score > bestScore) {
23364
23461
  bestScore = score;
23365
23462
  best = h;
@@ -23384,7 +23481,23 @@ var typedPin = {
23384
23481
  const base = (dn) => String(dn ?? "").split("-")[0];
23385
23482
  const sameDocTyped = (h) => !!h.metadata.unit_id && !!h.metadata.block && pinFamilies.has(base(h.metadata.doc_number));
23386
23483
  {
23387
- const typed = pickTypedChunk(query, hits.filter(sameDocTyped), hits);
23484
+ let pool = hits.filter(sameDocTyped);
23485
+ const fromClause = /* @__PURE__ */ new Set();
23486
+ if (OBJECT_SEEKING.test(query.toLowerCase())) {
23487
+ const prose = hits.filter((h) => isProse(h) && pinFamilies.has(base(h.metadata.doc_number))).slice(0, THRESHOLDS.typedSiblingProse);
23488
+ const siblings = (await siblingUnits(env, prose)).filter(
23489
+ (x) => !pool.some((h) => h.id === x.id) && !c.finalHits.some((h) => h.id === x.id)
23490
+ );
23491
+ if (siblings.length) {
23492
+ pool = [...pool, ...siblings];
23493
+ for (const x of siblings) fromClause.add(x.id);
23494
+ console.log(
23495
+ "typed pin: clause completion \u2014",
23496
+ siblings.map((x) => `${x.metadata.docidentifier} \xA7${x.metadata.clause_anchor} (${x.metadata.block})`).join(", ")
23497
+ );
23498
+ }
23499
+ }
23500
+ const typed = pickTypedChunk(query, pool, hits);
23388
23501
  const hardScope = !!pinFamily;
23389
23502
  const overlap2 = (() => {
23390
23503
  if (!typed || hardScope) return Infinity;
@@ -23395,7 +23508,7 @@ var typedPin = {
23395
23508
  const tableExempt = typed?.metadata.block === "table";
23396
23509
  if (typed && (overlap2 >= 3 || tableExempt) && !c.finalHits.some((h) => h.id === typed.id)) {
23397
23510
  c.finalHits = [...c.finalHits.slice(0, LIMITS.rerankKeep - 1), typed];
23398
- console.log("typed pin:", typed.metadata.docidentifier, "\xA7", typed.metadata.clause_anchor, `(${typed.metadata.block})${hardScope ? "" : " [glossary families]"}`);
23511
+ console.log("typed pin:", typed.metadata.docidentifier, "\xA7", typed.metadata.clause_anchor, `(${typed.metadata.block})${fromClause.has(typed.id) ? " [clause sibling]" : ""}${hardScope ? "" : " [glossary families]"}`);
23399
23512
  const anchor = typed.metadata.clause_anchor;
23400
23513
  const docId = typed.metadata.doc_id;
23401
23514
  const parentPresent = c.finalHits.some(
@@ -23404,7 +23517,7 @@ var typedPin = {
23404
23517
  if (anchor && docId && !parentPresent && env.DB) {
23405
23518
  try {
23406
23519
  const res = await env.DB.prepare(
23407
- "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"
23520
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2`
23408
23521
  ).bind(docId, anchor).all();
23409
23522
  const row = (res.results ?? [])[0];
23410
23523
  if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-22WB6IVC.js";
4
+ } from "./chunk-5Y3CDK64.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-22WB6IVC.js";
4
+ } from "./chunk-5Y3CDK64.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -2,7 +2,7 @@ import {
2
2
  answerEffort,
3
3
  effortBudget,
4
4
  generationSampling
5
- } from "./chunk-22WB6IVC.js";
5
+ } from "./chunk-5Y3CDK64.js";
6
6
 
7
7
  // workers/worker_public/src/ai.ts
8
8
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -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-ECNBEZGK.js";
36
+ } from "./chunk-UZHUND67.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -77,20 +77,22 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-3SGGVZZ4.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-AVNHVFEB.js";
85
+ isCapacityError,
86
+ publicationUnitRows,
87
+ unitPayloadRows
88
+ } from "./chunk-QYNFNOKE.js";
87
89
  import {
88
90
  corsHeaders,
89
91
  err,
90
92
  json,
91
93
  readJson,
92
94
  validateQuery
93
- } from "./chunk-GJQT4IMD.js";
95
+ } from "./chunk-M4OCMIWU.js";
94
96
  import {
95
97
  cacheableAnswer,
96
98
  canonicalRefusal,
@@ -103,7 +105,7 @@ import {
103
105
  requestSalt,
104
106
  resolveRequestScope,
105
107
  standardKeysFrom
106
- } from "./chunk-7YMIUTPY.js";
108
+ } from "./chunk-J4UAO5XI.js";
107
109
  import {
108
110
  DATASETS,
109
111
  ESCALATION_DAILY_DEFAULT,
@@ -117,7 +119,7 @@ import {
117
119
  requestEffort,
118
120
  roleModel,
119
121
  sha256Hex
120
- } from "./chunk-22WB6IVC.js";
122
+ } from "./chunk-5Y3CDK64.js";
121
123
  import {
122
124
  P
123
125
  } from "./chunk-3FYJM7LH.js";
@@ -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,12 +1,13 @@
1
1
  import {
2
- embed
3
- } from "./chunk-AVNHVFEB.js";
2
+ embed,
3
+ unitPayloadRows
4
+ } from "./chunk-QYNFNOKE.js";
4
5
  import {
5
6
  standardKeysFrom
6
- } from "./chunk-7YMIUTPY.js";
7
+ } from "./chunk-J4UAO5XI.js";
7
8
  import {
8
9
  THRESHOLDS
9
- } from "./chunk-22WB6IVC.js";
10
+ } from "./chunk-5Y3CDK64.js";
10
11
  import {
11
12
  P
12
13
  } from "./chunk-3FYJM7LH.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/config.d.ts CHANGED
@@ -125,6 +125,19 @@ export declare const THRESHOLDS: {
125
125
  /** Section-descent child discount — children fetched from a ranked
126
126
  * depth-1 summary enter discounted. */
127
127
  readonly sectionDescentDiscount: 0.8;
128
+ /** Typed-pin label weight — for an object-seeking question (a stated
129
+ * value, a named table/figure/formula) a query term met in a unit's
130
+ * LABELS (caption, column headers, row labels) is worth this many
131
+ * body mentions. A blank report form mentions every term of the
132
+ * question and holds no answer: measured 2026-12-05 on the R 60
133
+ * family, the test-report symbol list scored 10 against the limits
134
+ * table's 8 and was pinned — the gate lost the class-B value. */
135
+ readonly typedLabelWeight: 4;
136
+ /** Typed-pin clause completion — how many of the top-ranked prose
137
+ * clauses have their typed siblings (table/figure/formula under the
138
+ * same exact clause) fetched from D1, so the answering object is a
139
+ * candidate even when no retrieval lane surfaced it. */
140
+ readonly typedSiblingProse: 5;
128
141
  /** History budget share — the fraction of the context budget the
129
142
  * conversation slice may consume; older turns overflow into the
130
143
  * compacted summary instead of starving the passages. */
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;
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleSearch
3
+ } from "./chunk-3MV3UO6Q.js";
4
+ import "./chunk-73GZKS2T.js";
5
+ import "./chunk-QYNFNOKE.js";
6
+ import "./chunk-M4OCMIWU.js";
7
+ import "./chunk-ETLSWSZ7.js";
8
+ import "./chunk-J4UAO5XI.js";
9
+ import "./chunk-5Y3CDK64.js";
10
+ import "./chunk-3FYJM7LH.js";
11
+ import "./chunk-H6ZULBW2.js";
12
+ export {
13
+ handleSearch
14
+ };