@konneal/engine 0.2.190 → 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.
Files changed (34) hide show
  1. package/dist/ask-Q63SLXRD.js +16 -0
  2. package/dist/{chunk-22WB6IVC.js → chunk-5Y3CDK64.js} +13 -0
  3. package/dist/{chunk-7YMIUTPY.js → chunk-J4UAO5XI.js} +1 -1
  4. package/dist/{chunk-GJQT4IMD.js → chunk-M4OCMIWU.js} +1 -1
  5. package/dist/{chunk-ECNBEZGK.js → chunk-NHNCW6KQ.js} +3 -3
  6. package/dist/{chunk-5PKKAHY4.js → chunk-UDHM3G5N.js} +6 -5
  7. package/dist/{chunk-AVNHVFEB.js → chunk-VGBZYYVH.js} +1 -1
  8. package/dist/{chunk-Q7QL3457.js → chunk-W4F22Y4M.js} +134 -34
  9. package/dist/{chunk-WRSUXIS7.js → chunk-ZPNYAANP.js} +35 -32
  10. package/dist/config.d.ts +13 -0
  11. package/dist/nameplate.d.ts +0 -1
  12. package/dist/search-7ANUZAYL.js +14 -0
  13. package/dist/{tools-7GKMDWVB.js → tools-LOQBTAFQ.js} +4 -4
  14. package/dist/userDocuments.d.ts +1 -0
  15. package/dist/worker_mcp/src/index.js +2 -2
  16. package/dist/worker_public/src/config.js +1 -1
  17. package/dist/worker_public/src/index.js +19 -18
  18. package/dist/worker_public/src/requestScope.js +2 -2
  19. package/docs/ARCHITECTURE.md +7 -5
  20. package/package.json +1 -1
  21. package/workers/worker_public/src/ask.ts +42 -32
  22. package/workers/worker_public/src/config.ts +13 -0
  23. package/workers/worker_public/src/decisionWire.ts +2 -2
  24. package/workers/worker_public/src/index.ts +1 -1
  25. package/workers/worker_public/src/nameplate.ts +0 -3
  26. package/workers/worker_public/src/quota.ts +8 -1
  27. package/workers/worker_public/src/research.ts +9 -8
  28. package/workers/worker_public/src/search.ts +2 -2
  29. package/workers/worker_public/src/stages/sectionDescent.ts +9 -21
  30. package/workers/worker_public/src/stages/typedPin.ts +133 -15
  31. package/workers/worker_public/src/stages/vlmFigureRerank.ts +2 -2
  32. package/workers/worker_public/src/userDocuments.ts +7 -6
  33. package/dist/ask-6SWT3KSC.js +0 -16
  34. package/dist/search-DE5ADCVM.js +0 -14
@@ -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;
@@ -72,7 +160,7 @@ export const typedPin: Stage = {
72
160
  return new Set<string>(pinFamily ? [pinFamily.split("-")[0]] : [...glossaryFamilies]).size > 0;
73
161
  },
74
162
  run: async (c) => {
75
- const { query, filters, u, glossary, hits, env, vector } = c;
163
+ const { query, filters, u, glossary, hits, env } = c;
76
164
  const glossaryFamilies = new Set<string>();
77
165
  for (const g of glossary) if (g.doc_number) glossaryFamilies.add(g.doc_number.split("-")[0]);
78
166
  const pinFamily = filters?.doc_number ?? u?.doc_number ?? null;
@@ -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,23 +212,31 @@ 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;
109
219
  const parentPresent = c.finalHits.some(
110
220
  (h) => h.metadata.doc_id === docId && h.metadata.clause_anchor === anchor && !h.metadata.unit_id,
111
221
  );
112
- if (anchor && docId && !parentPresent) {
222
+ if (anchor && docId && !parentPresent && env.DB) {
113
223
  try {
114
- const pv = await env.VECTORIZE.query(vector, {
115
- topK: 4,
116
- returnMetadata: "all",
117
- filter: { $and: [{ doc_id: { $eq: docId } }, { clause_anchor: { $eq: anchor } }] },
118
- });
119
- const parent = (pv.matches ?? []).map((m: any) => ({ id: m.id, score: m.score, metadata: m.metadata, text: m.metadata?.chunk_text ?? "" })).find((h: any) => !h.metadata?.unit_id);
120
- if (parent && !c.finalHits.some((h) => h.id === parent.id)) {
121
- c.finalHits = [...c.finalHits, { ...parent, score: parent.score * THRESHOLDS.smallToBigDiscount }];
224
+ // Read the parent prose clause from D1 directly: Vectorize rejects
225
+ // $and arrays (40026) and does not index doc_id / clause_anchor.
226
+ const res = await env.DB.prepare(
227
+ `SELECT ${UNIT_COLS} FROM chunks WHERE doc_id = ?1 AND clause_anchor = ?2 AND (unit_id IS NULL OR unit_id = '') LIMIT 2`,
228
+ )
229
+ .bind(docId, anchor)
230
+ .all();
231
+ const row = (res.results ?? [])[0] as any;
232
+ if (row && !c.finalHits.some((h) => h.id === String(row.id))) {
233
+ const parent: Hit = {
234
+ id: String(row.id),
235
+ score: typed.score * THRESHOLDS.smallToBigDiscount,
236
+ metadata: { ...row, unit_id: undefined, block: row.block || undefined },
237
+ text: String(row.text ?? ""),
238
+ };
239
+ c.finalHits = [...c.finalHits, parent];
122
240
  console.log("small-to-big: parent §", anchor, "of", typed.metadata.docidentifier, "added");
123
241
  }
124
242
  } catch {
@@ -7,7 +7,7 @@
7
7
  // the window with a rerank score above the incumbent top; every failure
8
8
  // mode is additive (the text ranking stands). Off via the registry
9
9
  // projection like any stage (ablate_stages drops it).
10
- import { MODELS } from "../config.ts";
10
+ import { roleModel } from "../config.ts";
11
11
  import { portBlobs, portModelRunner, portStore } from "../env.ts";
12
12
  import type { Stage } from "./types.ts";
13
13
  import type { Hit } from "../../../shared/chunk";
@@ -63,7 +63,7 @@ export const vlmFigureRerank: Stage = {
63
63
  }
64
64
  if (!kept.length) return;
65
65
  const raced: any = await Promise.race([
66
- portModelRunner(c.env).run({ model: MODELS.vlmFigure, messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
66
+ portModelRunner(c.env).run({ model: roleModel(c.env, "vlmFigure"), messages: [{ role: "user", content }], maxTokens: 256, effort: "low" }),
67
67
  new Promise<null>((r) => setTimeout(() => r(null), 15000)),
68
68
  ]);
69
69
  const pick = parsePick(raced?.text ?? raced, kept.length);
@@ -55,6 +55,7 @@ export interface UserDocumentPorts {
55
55
  blobs: Blobs;
56
56
  lane: VectorIndex;
57
57
  model: ModelRunner;
58
+ answerModel?: string;
58
59
  }
59
60
 
60
61
  export interface UploadBlob {
@@ -159,13 +160,13 @@ export async function processImport(ports: UserDocumentPorts, row: UserDocumentR
159
160
  } else {
160
161
  // images: the vision lane transcribes (the nameplate pattern —
161
162
  // transcription-first framing beats extract-a-JSON on plates)
162
- text = await visionTranscribe(ports.model, mime, bytes);
163
+ text = await visionTranscribe(ports.model, mime, bytes, ports.answerModel ?? MODELS.member);
163
164
  if (!text || text.replace(/\s+/g, "").length < 20) {
164
165
  await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
165
166
  return;
166
167
  }
167
168
  }
168
- const extraction = await structureDocument(ports.model, row.name, mime, text);
169
+ const extraction = await structureDocument(ports.model, row.name, mime, text, ports.answerModel ?? MODELS.member);
169
170
  // the lane chunk: the summary leads, the verbatim text carries the
170
171
  // rest — the federation cites THIS document's content
171
172
  const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
@@ -207,13 +208,13 @@ function extractKind(fields: Record<string, string>): string {
207
208
  return fields.kind || "other";
208
209
  }
209
210
 
210
- async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Array): Promise<string> {
211
+ async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Array, modelId: string): Promise<string> {
211
212
  let binary = "";
212
213
  const CHUNK = 0x8000;
213
214
  for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
214
215
  const dataUrl = `data:${mime};base64,${btoa(binary)}`;
215
216
  const res = await model.run({
216
- model: MODELS.member,
217
+ model: modelId,
217
218
  messages: [
218
219
  { role: "system", content: "Transcribe everything you can read in this document image — certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
219
220
  { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] },
@@ -227,9 +228,9 @@ async function visionTranscribe(model: ModelRunner, mime: string, bytes: Uint8Ar
227
228
 
228
229
  /** One structuring call: classify + typed fields + a retrieval summary.
229
230
  * The response's JSON object is taken; prose around it is ignored. */
230
- async function structureDocument(model: ModelRunner, name: string, mime: string, text: string): Promise<Extraction> {
231
+ async function structureDocument(model: ModelRunner, name: string, mime: string, text: string, modelId: string): Promise<Extraction> {
231
232
  const res = await model.run({
232
- model: MODELS.member,
233
+ model: modelId,
233
234
  messages: [
234
235
  { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {…short typed fields…}, "summary": "one paragraph a retrieval engine can answer from"}. Certificates carry certificate numbers (like R60/2021-XX1-24.01), holders, models, issue dates. Test reports carry measured values, uncertainties, instruments, clause references. Fields use snake_case names, values verbatim from the text. Never invent a value the text does not carry.` },
235
236
  { role: "user", content: `Document name: ${name}\nFormat: ${mime}\n\nText:\n${text.slice(0, 12000)}` },
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-WRSUXIS7.js";
4
- import "./chunk-IRCDOFP4.js";
5
- import "./chunk-ECNBEZGK.js";
6
- import "./chunk-Q7QL3457.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-5PKKAHY4.js";
4
- import "./chunk-Q7QL3457.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
- };