@konneal/engine 0.2.191 → 0.2.192

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-ZPNYAANP.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-NHNCW6KQ.js";
6
+ import "./chunk-W4F22Y4M.js";
7
+ import "./chunk-VGBZYYVH.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
+ };
@@ -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,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";
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  embed
3
- } from "./chunk-AVNHVFEB.js";
3
+ } from "./chunk-VGBZYYVH.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-7YMIUTPY.js";
6
+ } from "./chunk-J4UAO5XI.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-22WB6IVC.js";
9
+ } from "./chunk-5Y3CDK64.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -6,25 +6,25 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-3SGGVZZ4.js";
9
+ } from "./chunk-W4F22Y4M.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";
@@ -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));
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  embed,
3
3
  rerank
4
- } from "./chunk-AVNHVFEB.js";
4
+ } from "./chunk-VGBZYYVH.js";
5
5
  import {
6
6
  bubbleConfirmPage,
7
7
  isAllowedBubbleOrigin
8
- } from "./chunk-GJQT4IMD.js";
8
+ } from "./chunk-M4OCMIWU.js";
9
9
  import {
10
10
  DATASETS,
11
11
  LIMITS,
@@ -17,7 +17,7 @@ import {
17
17
  roleModel,
18
18
  sha256Hex,
19
19
  today
20
- } from "./chunk-22WB6IVC.js";
20
+ } from "./chunk-5Y3CDK64.js";
21
21
  import {
22
22
  P
23
23
  } from "./chunk-3FYJM7LH.js";
@@ -23337,11 +23337,96 @@ var diversity = {
23337
23337
  };
23338
23338
 
23339
23339
  // workers/worker_public/src/stages/typedPin.ts
23340
+ 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";
23341
+ 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;
23342
+ var LABEL_STOP = /* @__PURE__ */ new Set([
23343
+ "the",
23344
+ "and",
23345
+ "for",
23346
+ "per",
23347
+ "with",
23348
+ "from",
23349
+ "into",
23350
+ "that",
23351
+ "this",
23352
+ "what",
23353
+ "which",
23354
+ "according",
23355
+ "does",
23356
+ "are",
23357
+ "how",
23358
+ "why",
23359
+ "when",
23360
+ "where",
23361
+ "who",
23362
+ "its",
23363
+ "their",
23364
+ "there",
23365
+ "about",
23366
+ "between",
23367
+ "across",
23368
+ "after",
23369
+ "before",
23370
+ "not",
23371
+ "can",
23372
+ "must",
23373
+ "shall",
23374
+ "has",
23375
+ "have",
23376
+ "had",
23377
+ "was",
23378
+ "were",
23379
+ "will",
23380
+ "would",
23381
+ "should"
23382
+ ]);
23383
+ function labelText(h) {
23384
+ const t = h.text.toLowerCase();
23385
+ const cols = /columns:(.*?)(?:; row:|$)/s.exec(t)?.[1] ?? "";
23386
+ const rows = [...t.matchAll(/(?:^|; )row: ([^|]+)/g)].map((m) => m[1]).join(" ");
23387
+ return `${h.metadata.clause_title ?? ""} ${cols} ${rows}`.toLowerCase();
23388
+ }
23389
+ function clauseKeyOf(h) {
23390
+ const m = /^u:sec-(.+)$/.exec(String(h.metadata.unit_id ?? ""));
23391
+ const key = m ? m[1] : String(h.metadata.clause_anchor ?? "");
23392
+ return /^(\d+|[A-Z])(\.\d+)*[A-Z]?$/.test(key) ? key : "";
23393
+ }
23394
+ var isProse = (h) => !h.metadata.section_summary && (!h.metadata.unit_id || h.metadata.block === "clause" || !h.metadata.block);
23395
+ async function siblingUnits(env, prose) {
23396
+ if (!env.DB || !prose.length) return [];
23397
+ const found = await Promise.all(
23398
+ prose.map(async (h) => {
23399
+ const docId = String(h.metadata.doc_id ?? "");
23400
+ const key = clauseKeyOf(h);
23401
+ if (!docId || !key) return [];
23402
+ try {
23403
+ const res = await env.DB.prepare(
23404
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND block IN ('table','figure','formula') AND unit_id != '' LIMIT 8`
23405
+ ).bind(docId, key).all();
23406
+ return (res.results ?? []).map(
23407
+ (r) => ({
23408
+ id: String(r.id),
23409
+ // it arrives through a ranked passage, like a descent child
23410
+ score: h.score * THRESHOLDS.sectionDescentDiscount,
23411
+ metadata: r,
23412
+ text: String(r.text ?? "")
23413
+ })
23414
+ );
23415
+ } catch {
23416
+ return [];
23417
+ }
23418
+ })
23419
+ );
23420
+ const out = [];
23421
+ for (const list of found) for (const h of list) if (!out.some((x) => x.id === h.id)) out.push(h);
23422
+ return out;
23423
+ }
23340
23424
  function pickTypedChunk(query, candidates, ranked) {
23341
23425
  if (!candidates.length) return null;
23342
23426
  const pool = candidates;
23343
23427
  const q = query.toLowerCase();
23344
23428
  const terms = q.replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((t) => t.length > 2);
23429
+ const labelTerms = OBJECT_SEEKING.test(q) ? terms.filter((t) => !LABEL_STOP.has(t)) : [];
23345
23430
  const typeBonus = {};
23346
23431
  if (/\bfig(ure)?s?\b/.test(q)) typeBonus.figure = 1;
23347
23432
  if (/\btables?\b/.test(q)) typeBonus.table = 1;
@@ -23360,6 +23445,10 @@ function pickTypedChunk(query, candidates, ranked) {
23360
23445
  const filled = cells.filter((x) => x.length > 0).length;
23361
23446
  const density = cells.length ? filled / cells.length : 0;
23362
23447
  score += density * 2;
23448
+ if (labelTerms.length) {
23449
+ const labels = labelText(h);
23450
+ for (const t of labelTerms) if (labels.includes(t)) score += THRESHOLDS.typedLabelWeight;
23451
+ }
23363
23452
  if (score > bestScore) {
23364
23453
  bestScore = score;
23365
23454
  best = h;
@@ -23384,7 +23473,23 @@ var typedPin = {
23384
23473
  const base = (dn) => String(dn ?? "").split("-")[0];
23385
23474
  const sameDocTyped = (h) => !!h.metadata.unit_id && !!h.metadata.block && pinFamilies.has(base(h.metadata.doc_number));
23386
23475
  {
23387
- const typed = pickTypedChunk(query, hits.filter(sameDocTyped), hits);
23476
+ let pool = hits.filter(sameDocTyped);
23477
+ const fromClause = /* @__PURE__ */ new Set();
23478
+ if (OBJECT_SEEKING.test(query.toLowerCase())) {
23479
+ const prose = hits.filter((h) => isProse(h) && pinFamilies.has(base(h.metadata.doc_number))).slice(0, THRESHOLDS.typedSiblingProse);
23480
+ const siblings = (await siblingUnits(env, prose)).filter(
23481
+ (x) => !pool.some((h) => h.id === x.id) && !c.finalHits.some((h) => h.id === x.id)
23482
+ );
23483
+ if (siblings.length) {
23484
+ pool = [...pool, ...siblings];
23485
+ for (const x of siblings) fromClause.add(x.id);
23486
+ console.log(
23487
+ "typed pin: clause completion \u2014",
23488
+ siblings.map((x) => `${x.metadata.docidentifier} \xA7${x.metadata.clause_anchor} (${x.metadata.block})`).join(", ")
23489
+ );
23490
+ }
23491
+ }
23492
+ const typed = pickTypedChunk(query, pool, hits);
23388
23493
  const hardScope = !!pinFamily;
23389
23494
  const overlap2 = (() => {
23390
23495
  if (!typed || hardScope) return Infinity;
@@ -23395,7 +23500,7 @@ var typedPin = {
23395
23500
  const tableExempt = typed?.metadata.block === "table";
23396
23501
  if (typed && (overlap2 >= 3 || tableExempt) && !c.finalHits.some((h) => h.id === typed.id)) {
23397
23502
  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]"}`);
23503
+ 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
23504
  const anchor = typed.metadata.clause_anchor;
23400
23505
  const docId = typed.metadata.doc_id;
23401
23506
  const parentPresent = c.finalHits.some(
@@ -23404,7 +23509,7 @@ var typedPin = {
23404
23509
  if (anchor && docId && !parentPresent && env.DB) {
23405
23510
  try {
23406
23511
  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"
23512
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2`
23408
23513
  ).bind(docId, anchor).all();
23409
23514
  const row = (res.results ?? [])[0];
23410
23515
  if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-ECNBEZGK.js";
36
+ } from "./chunk-NHNCW6KQ.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -77,20 +77,20 @@ import {
77
77
  tokenBudget,
78
78
  understandQuery,
79
79
  usageTotal
80
- } from "./chunk-3SGGVZZ4.js";
80
+ } from "./chunk-W4F22Y4M.js";
81
81
  import {
82
82
  CAPACITY_PAUSE_MS,
83
83
  embed,
84
84
  generateOnce,
85
85
  isCapacityError
86
- } from "./chunk-AVNHVFEB.js";
86
+ } from "./chunk-VGBZYYVH.js";
87
87
  import {
88
88
  corsHeaders,
89
89
  err,
90
90
  json,
91
91
  readJson,
92
92
  validateQuery
93
- } from "./chunk-GJQT4IMD.js";
93
+ } from "./chunk-M4OCMIWU.js";
94
94
  import {
95
95
  cacheableAnswer,
96
96
  canonicalRefusal,
@@ -103,7 +103,7 @@ import {
103
103
  requestSalt,
104
104
  resolveRequestScope,
105
105
  standardKeysFrom
106
- } from "./chunk-7YMIUTPY.js";
106
+ } from "./chunk-J4UAO5XI.js";
107
107
  import {
108
108
  DATASETS,
109
109
  ESCALATION_DAILY_DEFAULT,
@@ -117,7 +117,7 @@ import {
117
117
  requestEffort,
118
118
  roleModel,
119
119
  sha256Hex
120
- } from "./chunk-22WB6IVC.js";
120
+ } from "./chunk-5Y3CDK64.js";
121
121
  import {
122
122
  P
123
123
  } from "./chunk-3FYJM7LH.js";
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. */
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleSearch
3
+ } from "./chunk-UDHM3G5N.js";
4
+ import "./chunk-W4F22Y4M.js";
5
+ import "./chunk-VGBZYYVH.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
+ };
@@ -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-NHNCW6KQ.js";
8
+ import "./chunk-VGBZYYVH.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 {
@@ -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-ZPNYAANP.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-NHNCW6KQ.js";
19
19
  import {
20
20
  handleSearch
21
- } from "../../chunk-CW6J3HTM.js";
21
+ } from "../../chunk-UDHM3G5N.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-W4F22Y4M.js";
47
47
  import {
48
48
  embed,
49
49
  generateOnce
50
- } from "../../chunk-AVNHVFEB.js";
50
+ } from "../../chunk-VGBZYYVH.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-LOQBTAFQ.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-Q63SLXRD.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-7ANUZAYL.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.192",
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",
@@ -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. */
@@ -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();
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-SWCKO4OB.js";
4
- import "./chunk-IRCDOFP4.js";
5
- import "./chunk-ECNBEZGK.js";
6
- import "./chunk-3SGGVZZ4.js";
7
- import "./chunk-AVNHVFEB.js";
8
- import "./chunk-GJQT4IMD.js";
9
- import "./chunk-ETLSWSZ7.js";
10
- import "./chunk-7YMIUTPY.js";
11
- import "./chunk-22WB6IVC.js";
12
- import "./chunk-3FYJM7LH.js";
13
- import "./chunk-H6ZULBW2.js";
14
- export {
15
- handleAsk
16
- };
@@ -1,14 +0,0 @@
1
- import {
2
- handleSearch
3
- } from "./chunk-CW6J3HTM.js";
4
- import "./chunk-3SGGVZZ4.js";
5
- import "./chunk-AVNHVFEB.js";
6
- import "./chunk-GJQT4IMD.js";
7
- import "./chunk-ETLSWSZ7.js";
8
- import "./chunk-7YMIUTPY.js";
9
- import "./chunk-22WB6IVC.js";
10
- import "./chunk-3FYJM7LH.js";
11
- import "./chunk-H6ZULBW2.js";
12
- export {
13
- handleSearch
14
- };