@konneal/engine 0.2.182 → 0.2.184

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-ZFOODZWO.js";
4
+ import "./chunk-IRCDOFP4.js";
5
+ import "./chunk-XO26UIFH.js";
6
+ import "./chunk-XTWH3PS6.js";
7
+ import "./chunk-7RZ2D64X.js";
8
+ import "./chunk-XMUG75ZV.js";
9
+ import "./chunk-ETLSWSZ7.js";
10
+ import "./chunk-5HCVX34C.js";
11
+ import "./chunk-QYTCQIA6.js";
12
+ import "./chunk-3FYJM7LH.js";
13
+ import "./chunk-YGQCVPX6.js";
14
+ export {
15
+ handleAsk
16
+ };
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DATASETS,
3
3
  datasetAllowed
4
- } from "./chunk-HWWJAJWM.js";
4
+ } from "./chunk-QYTCQIA6.js";
5
5
  import {
6
6
  P
7
7
  } from "./chunk-3FYJM7LH.js";
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  answerEffort,
3
3
  effortBudget
4
- } from "./chunk-HWWJAJWM.js";
4
+ } from "./chunk-QYTCQIA6.js";
5
5
 
6
6
  // workers/worker_public/src/ai.ts
7
7
  var delay = (ms) => new Promise((r) => setTimeout(r, ms));
@@ -124,6 +124,9 @@ var THRESHOLDS = {
124
124
  /** Federated-ISO discount — the public corpus answers by default;
125
125
  * internal ISO passages compete but don't preempt. */
126
126
  federateDiscount: 0.95,
127
+ /** the member's own imported documents: how many lane hits may join
128
+ * the pool (TODO.sota/20 slice 4) — their content, their question */
129
+ userLaneK: 3,
127
130
  /** Standard-reference nudge (L5): when the question asks about an
128
131
  * invoked ISO/IEC standard, chunks that CARRY such a citation (their
129
132
  * text contains an ISO/IEC identifier) get a spread-scaled boost —
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  LIMITS,
3
3
  sha256Hex
4
- } from "./chunk-HWWJAJWM.js";
4
+ } from "./chunk-QYTCQIA6.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-ZHT4456M.js";
3
+ } from "./chunk-7RZ2D64X.js";
4
4
  import {
5
5
  standardKeysFrom
6
- } from "./chunk-FNQ7UOEB.js";
6
+ } from "./chunk-5HCVX34C.js";
7
7
  import {
8
8
  THRESHOLDS
9
- } from "./chunk-HWWJAJWM.js";
9
+ } from "./chunk-QYTCQIA6.js";
10
10
  import {
11
11
  P
12
12
  } from "./chunk-3FYJM7LH.js";
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  embed,
3
3
  rerank
4
- } from "./chunk-ZHT4456M.js";
4
+ } from "./chunk-7RZ2D64X.js";
5
5
  import {
6
6
  bubbleConfirmPage,
7
7
  isAllowedBubbleOrigin
8
- } from "./chunk-D7MO4RVQ.js";
8
+ } from "./chunk-XMUG75ZV.js";
9
9
  import {
10
10
  DATASETS,
11
11
  LIMITS,
@@ -15,7 +15,7 @@ import {
15
15
  processExpansion,
16
16
  sha256Hex,
17
17
  today
18
- } from "./chunk-HWWJAJWM.js";
18
+ } from "./chunk-QYTCQIA6.js";
19
19
  import {
20
20
  P
21
21
  } from "./chunk-3FYJM7LH.js";
@@ -22705,6 +22705,22 @@ var federate = {
22705
22705
  }
22706
22706
  };
22707
22707
 
22708
+ // workers/worker_public/src/stages/userLane.ts
22709
+ var userLane = {
22710
+ name: "user-lane",
22711
+ when: (c) => !!c.opts.userDocs,
22712
+ run: async (c) => {
22713
+ const fed = await c.opts.userDocs(c.rq).catch(() => []);
22714
+ const seen = new Set(c.hits.map((h) => h.id));
22715
+ for (const h of fed) {
22716
+ if (!seen.has(h.id)) {
22717
+ c.hits.push({ ...h });
22718
+ seen.add(h.id);
22719
+ }
22720
+ }
22721
+ }
22722
+ };
22723
+
22708
22724
  // workers/worker_public/src/stages/seal.ts
22709
22725
  async function familyChunks(env, familyNumber, query, keep) {
22710
22726
  const match2 = ftsMatchQuery(query) ?? `"${familyNumber}"`;
@@ -23526,6 +23542,7 @@ var STAGES = [
23526
23542
  poolOpen,
23527
23543
  lexicalUnion,
23528
23544
  federate,
23545
+ userLane,
23529
23546
  seal,
23530
23547
  licenseScope,
23531
23548
  overviewDemote,
@@ -6,24 +6,24 @@ import {
6
6
  sessionFrom,
7
7
  telemetry,
8
8
  understandQuery
9
- } from "./chunk-4J47P52J.js";
9
+ } from "./chunk-XTWH3PS6.js";
10
10
  import {
11
11
  corsHeaders,
12
12
  err,
13
13
  json,
14
14
  readJson,
15
15
  validateQuery
16
- } from "./chunk-D7MO4RVQ.js";
16
+ } from "./chunk-XMUG75ZV.js";
17
17
  import {
18
18
  entitlementScope,
19
19
  standardKeysFrom
20
- } from "./chunk-FNQ7UOEB.js";
20
+ } from "./chunk-5HCVX34C.js";
21
21
  import {
22
22
  LIMITS,
23
23
  MODELS,
24
24
  num,
25
25
  sha256Hex
26
- } from "./chunk-HWWJAJWM.js";
26
+ } from "./chunk-QYTCQIA6.js";
27
27
  import {
28
28
  portModelRunner
29
29
  } from "./chunk-YGQCVPX6.js";
@@ -33,7 +33,7 @@ import {
33
33
  tableRetyped,
34
34
  toolNote,
35
35
  verdictNote
36
- } from "./chunk-VRWNS4AI.js";
36
+ } from "./chunk-XO26UIFH.js";
37
37
  import {
38
38
  NO_CONTEXT,
39
39
  STAGE_NAMES,
@@ -76,18 +76,18 @@ import {
76
76
  tokenBudget,
77
77
  understandQuery,
78
78
  usageTotal
79
- } from "./chunk-4J47P52J.js";
79
+ } from "./chunk-XTWH3PS6.js";
80
80
  import {
81
81
  embed,
82
82
  generateOnce
83
- } from "./chunk-ZHT4456M.js";
83
+ } from "./chunk-7RZ2D64X.js";
84
84
  import {
85
85
  corsHeaders,
86
86
  err,
87
87
  json,
88
88
  readJson,
89
89
  validateQuery
90
- } from "./chunk-D7MO4RVQ.js";
90
+ } from "./chunk-XMUG75ZV.js";
91
91
  import {
92
92
  cacheableAnswer,
93
93
  canonicalRefusal,
@@ -100,7 +100,7 @@ import {
100
100
  requestSalt,
101
101
  resolveRequestScope,
102
102
  standardKeysFrom
103
- } from "./chunk-FNQ7UOEB.js";
103
+ } from "./chunk-5HCVX34C.js";
104
104
  import {
105
105
  LIMITS,
106
106
  MODELS,
@@ -111,11 +111,13 @@ import {
111
111
  requestEffort,
112
112
  roleModel,
113
113
  sha256Hex
114
- } from "./chunk-HWWJAJWM.js";
114
+ } from "./chunk-QYTCQIA6.js";
115
115
  import {
116
116
  P
117
117
  } from "./chunk-3FYJM7LH.js";
118
118
  import {
119
+ cfModelRunner,
120
+ cfVectorIndex,
119
121
  portModelRunner,
120
122
  portStore
121
123
  } from "./chunk-YGQCVPX6.js";
@@ -1675,6 +1677,227 @@ function partitionSubsets(hits, k = SPECULATIVE_SUBSETS) {
1675
1677
  // workers/worker_public/prompts/speculative-verify.md
1676
1678
  var speculative_verify_default = "You answer questions about legal-metrology publications for {{PUBLISHER_NAME}}. Candidate draft answers were prepared in parallel, each from a PARTIAL view of the evidence (a subset of the passages); you see every candidate beside the FULL passages. Produce the final answer.\n\nRules:\n1. Compare the candidates against the full passages. Adopt the candidate best supported by the evidence as your starting point; correct every claim the full passages contradict or fail to support, and fold in anything the other candidates got right that the adopted one missed.\n2. Ground every factual claim in the numbered passages and cite them inline as [1], [2], \u2026 exactly as the passages are numbered below. Never cite a passage that is not there.\n3. Quote verbatim \u2014 with quotation marks \u2014 when a clause's exact wording matters (definitions, thresholds, requirements); a quotation must appear word-for-word in the passages.\n4. Numeric and table values come from the passages exactly; never retype a table as markdown \u2014 refer to the table and cite it.\n5. If the passages do not answer the question, say so plainly instead of guessing.\n6. Be complete but compact: answer the question, cite, stop.\n";
1677
1679
 
1680
+ // workers/worker_public/src/userDocuments.ts
1681
+ var USER_DOC_LIMIT = 10;
1682
+ var USER_DOC_MAX_BYTES = 20 * 1024 * 1024;
1683
+ var ACCEPTED_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
1684
+ function userDocumentChunkId(docId) {
1685
+ return `ud-${docId}`;
1686
+ }
1687
+ async function listUserDocuments(store, sub) {
1688
+ const res = await store.prepare("SELECT id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at FROM user_documents WHERE owner_sub = ?1 ORDER BY created_at DESC").bind(sub).all();
1689
+ return { documents: res.results ?? [] };
1690
+ }
1691
+ async function getUserDocument(store, sub, id) {
1692
+ const row = await store.prepare("SELECT id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).first();
1693
+ return row ?? null;
1694
+ }
1695
+ async function quotaRefusal(store, sub) {
1696
+ const row = await store.prepare("SELECT COUNT(*) AS n FROM user_documents WHERE owner_sub = ?1").bind(sub).first();
1697
+ const n = Number(row?.n ?? 0);
1698
+ if (n >= USER_DOC_LIMIT) {
1699
+ return new Response(JSON.stringify({ error: { code: "quota_exceeded", message: `You hold the maximum of ${USER_DOC_LIMIT} documents. Delete one to import another.` } }), { status: 403, headers: { "content-type": "application/json" } });
1700
+ }
1701
+ return null;
1702
+ }
1703
+ async function createImport(ports, waitUntil, sub, file) {
1704
+ const mime = file.type || "";
1705
+ if (!ACCEPTED_MIMES.has(mime)) {
1706
+ return { error: new Response(JSON.stringify({ error: { code: "invalid_type", message: "Upload a PNG, JPEG, WebP image or a PDF." } }), { status: 415, headers: { "content-type": "application/json" } }) };
1707
+ }
1708
+ if (file.size > USER_DOC_MAX_BYTES) {
1709
+ return { error: new Response(JSON.stringify({ error: { code: "too_large", message: `Documents are limited to ${Math.floor(USER_DOC_MAX_BYTES / (1024 * 1024))} MB.` } }), { status: 413, headers: { "content-type": "application/json" } }) };
1710
+ }
1711
+ const refused = await quotaRefusal(ports.store, sub);
1712
+ if (refused) return { error: refused };
1713
+ const id = crypto.randomUUID();
1714
+ const r2Key = `${sub}/${id}`;
1715
+ const bytes = new Uint8Array(await file.arrayBuffer());
1716
+ await ports.blobs.put(r2Key, bytes.buffer, mime);
1717
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1718
+ const row = {
1719
+ id,
1720
+ owner_sub: sub,
1721
+ name: file.name || "document",
1722
+ kind: null,
1723
+ status: "importing",
1724
+ bytes: bytes.byteLength,
1725
+ r2_key: r2Key,
1726
+ fields: null,
1727
+ error: null,
1728
+ created_at: now,
1729
+ updated_at: now
1730
+ };
1731
+ await ports.store.prepare(
1732
+ "INSERT INTO user_documents (id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)"
1733
+ ).bind(id, sub, row.name, row.kind, row.status, row.bytes, row.r2_key, row.fields, row.error, now, now).run();
1734
+ waitUntil(processImport(ports, row, mime, bytes).catch(() => {
1735
+ }));
1736
+ return { document: row };
1737
+ }
1738
+ async function processImport(ports, row, mime, bytes) {
1739
+ const setStatus = async (status, fields, error) => {
1740
+ await ports.store.prepare("UPDATE user_documents SET status = ?1, kind = ?2, fields = ?3, error = ?4, updated_at = ?5 WHERE id = ?6").bind(status, fields ? extractKind(fields) : null, fields ? JSON.stringify(fields) : null, error, (/* @__PURE__ */ new Date()).toISOString(), row.id).run();
1741
+ };
1742
+ try {
1743
+ let text;
1744
+ if (mime === "application/pdf") {
1745
+ text = await pdfTextLayer(bytes);
1746
+ if (!text || text.replace(/\s+/g, "").length < 40) {
1747
+ await setStatus("no_text_layer", null, "This PDF has no extractable text layer. Export page images (PNG/JPEG) and import those \u2014 the vision lane reads them directly.");
1748
+ return;
1749
+ }
1750
+ } else {
1751
+ text = await visionTranscribe(ports.model, mime, bytes);
1752
+ if (!text || text.replace(/\s+/g, "").length < 20) {
1753
+ await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
1754
+ return;
1755
+ }
1756
+ }
1757
+ const extraction = await structureDocument(ports.model, row.name, mime, text);
1758
+ const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
1759
+ const chunkText = `Member document (${extraction.kind}) \u2014 ${row.name}. ${fieldsLine}. ${extraction.summary}
1760
+
1761
+ ${extraction.text.slice(0, 8e3)}`;
1762
+ const [vector] = await ports.model.embed([chunkText]);
1763
+ await ports.lane.upsert([
1764
+ {
1765
+ id: userDocumentChunkId(row.id),
1766
+ values: vector,
1767
+ metadata: {
1768
+ user_sub: row.owner_sub,
1769
+ doc_id: `ud-${row.id}`,
1770
+ docidentifier: `Member document \u2014 ${row.name}`,
1771
+ doctype: "user",
1772
+ doc_number: extraction.kind,
1773
+ edition: "",
1774
+ language: "en",
1775
+ clause_anchor: "",
1776
+ clause_title: row.name.slice(0, 120),
1777
+ tier: "member",
1778
+ corpus: "user_docs",
1779
+ text_ref: "",
1780
+ kind: extraction.kind,
1781
+ name: row.name.slice(0, 120),
1782
+ chunk_text: chunkText.slice(0, 1800)
1783
+ }
1784
+ }
1785
+ ]);
1786
+ await setStatus("ready", { kind: extraction.kind, ...extraction.fields, summary: extraction.summary }, null);
1787
+ } catch (e) {
1788
+ await setStatus("failed", null, String(e).slice(0, 200)).catch(() => {
1789
+ });
1790
+ }
1791
+ }
1792
+ function extractKind(fields) {
1793
+ return fields.kind || "other";
1794
+ }
1795
+ async function visionTranscribe(model, mime, bytes) {
1796
+ let binary = "";
1797
+ const CHUNK = 32768;
1798
+ for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1799
+ const dataUrl = `data:${mime};base64,${btoa(binary)}`;
1800
+ const res = await model.run({
1801
+ model: MODELS.member,
1802
+ messages: [
1803
+ { role: "system", content: "Transcribe everything you can read in this document image \u2014 certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
1804
+ { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }
1805
+ ],
1806
+ maxTokens: 2048,
1807
+ effort: "low",
1808
+ temperature: 0.15
1809
+ });
1810
+ return res.text ?? "";
1811
+ }
1812
+ async function structureDocument(model, name, mime, text) {
1813
+ const res = await model.run({
1814
+ model: MODELS.member,
1815
+ messages: [
1816
+ { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {\u2026short typed fields\u2026}, "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.` },
1817
+ { role: "user", content: `Document name: ${name}
1818
+ Format: ${mime}
1819
+
1820
+ Text:
1821
+ ${text.slice(0, 12e3)}` }
1822
+ ],
1823
+ maxTokens: 2048,
1824
+ effort: "low",
1825
+ temperature: 0.15
1826
+ });
1827
+ const raw = res.text ?? "";
1828
+ const m = /\{[\s\S]*\}/.exec(raw);
1829
+ if (!m) throw new Error("the structuring call returned no JSON object");
1830
+ const parsed = JSON.parse(m[0]);
1831
+ const fields = {};
1832
+ for (const [k, v] of Object.entries(parsed.fields ?? {})) {
1833
+ if (typeof v === "string" || typeof v === "number") fields[k.slice(0, 40)] = String(v).slice(0, 200);
1834
+ }
1835
+ const kind = parsed.kind === "certificate" || parsed.kind === "test_report" ? parsed.kind : "other";
1836
+ return { kind, fields, summary: String(parsed.summary ?? "").slice(0, 1200), text };
1837
+ }
1838
+ async function pdfTextLayer(bytes) {
1839
+ const raw = new TextDecoder("latin1").decode(bytes);
1840
+ const parts = [];
1841
+ const streamRe = /stream\r?\n?/g;
1842
+ let m;
1843
+ while (m = streamRe.exec(raw)) {
1844
+ const start = m.index + m[0].length;
1845
+ const end = raw.indexOf("endstream", start);
1846
+ if (end < 0) break;
1847
+ const chunk = raw.slice(start, end);
1848
+ streamRe.lastIndex = end;
1849
+ let content = "";
1850
+ if (chunk.charCodeAt(0) === 120) {
1851
+ try {
1852
+ const ds = new DecompressionStream("deflate");
1853
+ const stream = new Blob([new Uint8Array([...chunk].map((c) => c.charCodeAt(0) & 255))]).stream().pipeThrough(ds);
1854
+ content = await new Response(stream).text();
1855
+ } catch {
1856
+ continue;
1857
+ }
1858
+ } else if (/\bTj\b|\bTJ\b/.test(chunk)) {
1859
+ content = chunk;
1860
+ } else {
1861
+ continue;
1862
+ }
1863
+ parts.push(pdfTextOps(content));
1864
+ if (parts.join("").length > 2e5) break;
1865
+ }
1866
+ return parts.join("\n");
1867
+ }
1868
+ function pdfTextOps(content) {
1869
+ const out = [];
1870
+ const re = /\((?:\\.|[^\\()])*\)/g;
1871
+ let m;
1872
+ while (m = re.exec(content)) {
1873
+ let s = m[0].slice(1, -1);
1874
+ s = s.replace(/\\([nrtbf()/\\])/g, (_, c) => ({ n: "\n", r: "", t: " ", b: "", f: "", "(": "(", ")": ")", "/": "/", "\\": "\\" })[c] ?? c);
1875
+ s = s.replace(/\\([0-7]{1,3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)));
1876
+ if (s.trim()) out.push(s);
1877
+ }
1878
+ return out.join(" ");
1879
+ }
1880
+ async function queryUserLane(model, lane, sub, query, k) {
1881
+ const [vector] = await model.embed([query]);
1882
+ const matches = await lane.query({ vector, topK: k, filter: { user_sub: sub } });
1883
+ return matches.map((m) => ({
1884
+ id: m.id,
1885
+ score: m.score,
1886
+ metadata: m.metadata,
1887
+ text: String(m.metadata?.chunk_text ?? "")
1888
+ }));
1889
+ }
1890
+ async function deleteUserDocument(ports, sub, id) {
1891
+ const row = await getUserDocument(ports.store, sub, id);
1892
+ if (!row) return null;
1893
+ if (row.r2_key) await ports.blobs.delete(row.r2_key).catch(() => {
1894
+ });
1895
+ await ports.lane.deleteIds([userDocumentChunkId(id)]).catch(() => {
1896
+ });
1897
+ await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
1898
+ return row;
1899
+ }
1900
+
1678
1901
  // workers/worker_public/src/operations.ts
1679
1902
  function isOperationIntent(query) {
1680
1903
  return /\b(operations?|endpoints?)\b/i.test(query);
@@ -2179,6 +2402,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2179
2402
  const requestSaltStr = requestSalt(scope, memoryUsed);
2180
2403
  const salt = requestSaltStr ? `${requestSaltStr}|effort:${effort}` : `effort:${effort}`;
2181
2404
  const federate = (member || keyLicensed) && service && isoOn ? (q2) => retrieveInternal(service, fedAuth, q2) : void 0;
2405
+ const userDocs = member && env.USER_DOCS_INDEX ? (q2) => queryUserLane(cfModelRunner(env.AI), cfVectorIndex(env.USER_DOCS_INDEX), member.sub, q2, THRESHOLDS.userLaneK) : void 0;
2182
2406
  const ns = tier === "key" ? `k:${key.id}` : member ? `m:${member.sub}` : "anon";
2183
2407
  const model = member ? MODELS.member : MODELS.anon;
2184
2408
  const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : void 0;
@@ -2734,6 +2958,7 @@ Answer account questions from these records ONLY: name the record when you use i
2734
2958
  prev,
2735
2959
  understanding,
2736
2960
  federate,
2961
+ userDocs,
2737
2962
  warmEmbed,
2738
2963
  graphDocNumbers,
2739
2964
  sealScope: declaredScoped ? docScope : null,
@@ -2768,7 +2993,7 @@ Answer account questions from these records ONLY: name the record when you use i
2768
2993
  if (grade === "weak" && understanding?.docidentifier) {
2769
2994
  const broaden = `${understanding.standalone_query || q2.query} ${understanding.docidentifier}`.trim();
2770
2995
  const tc = Date.now();
2771
- const second = await retrieve(env, q2.query, { prev, understanding, queryOverride: broaden, federate, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...routeSubset ? { stageSubset: routeSubset } : {} });
2996
+ const second = await retrieve(env, q2.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...routeSubset ? { stageSubset: routeSubset } : {} });
2772
2997
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q2.query, second.hits.map((h) => h.text));
2773
2998
  stageTiming.corrective = Date.now() - tc;
2774
2999
  if (grade2 === "good") retrieved = second;
@@ -3299,6 +3524,11 @@ Answer account questions from these records ONLY: name the record when you use i
3299
3524
 
3300
3525
  export {
3301
3526
  handleMemories,
3527
+ USER_DOC_LIMIT,
3528
+ listUserDocuments,
3529
+ getUserDocument,
3530
+ createImport,
3531
+ deleteUserDocument,
3302
3532
  scoreFaithfulness,
3303
3533
  checkQuoteAnchors,
3304
3534
  scoreJudge,
package/dist/config.d.ts CHANGED
@@ -74,6 +74,9 @@ export declare const THRESHOLDS: {
74
74
  /** Federated-ISO discount — the public corpus answers by default;
75
75
  * internal ISO passages compete but don't preempt. */
76
76
  readonly federateDiscount: 0.95;
77
+ /** the member's own imported documents: how many lane hits may join
78
+ * the pool (TODO.sota/20 slice 4) — their content, their question */
79
+ readonly userLaneK: 3;
77
80
  /** Standard-reference nudge (L5): when the question asks about an
78
81
  * invoked ISO/IEC standard, chunks that CARRY such a citation (their
79
82
  * text contains an ISO/IEC identifier) get a spread-scaled boost —
@@ -0,0 +1,14 @@
1
+ import {
2
+ handleSearch
3
+ } from "./chunk-YQQ3W5CE.js";
4
+ import "./chunk-XTWH3PS6.js";
5
+ import "./chunk-7RZ2D64X.js";
6
+ import "./chunk-XMUG75ZV.js";
7
+ import "./chunk-ETLSWSZ7.js";
8
+ import "./chunk-5HCVX34C.js";
9
+ import "./chunk-QYTCQIA6.js";
10
+ import "./chunk-3FYJM7LH.js";
11
+ import "./chunk-YGQCVPX6.js";
12
+ export {
13
+ handleSearch
14
+ };
@@ -4,10 +4,10 @@ import {
4
4
  parseToolCall,
5
5
  runTool,
6
6
  toolNote
7
- } from "./chunk-VRWNS4AI.js";
8
- import "./chunk-ZHT4456M.js";
9
- import "./chunk-FNQ7UOEB.js";
10
- import "./chunk-HWWJAJWM.js";
7
+ } from "./chunk-XO26UIFH.js";
8
+ import "./chunk-7RZ2D64X.js";
9
+ import "./chunk-5HCVX34C.js";
10
+ import "./chunk-QYTCQIA6.js";
11
11
  import "./chunk-3FYJM7LH.js";
12
12
  import "./chunk-YGQCVPX6.js";
13
13
  export {
@@ -2,6 +2,7 @@ import type { Blobs } from "./ports/blobs.ts";
2
2
  import type { StoreQuery } from "./ports/store.ts";
3
3
  import type { VectorIndex } from "./ports/vector.ts";
4
4
  import type { ModelRunner } from "./ports/model.ts";
5
+ import type { Hit } from "../../shared/chunk.ts";
5
6
  export declare const USER_DOC_LIMIT = 10;
6
7
  export declare const USER_DOC_MAX_BYTES: number;
7
8
  export interface UserDocumentRow {
@@ -61,6 +62,11 @@ export declare function processImport(ports: UserDocumentPorts, row: UserDocumen
61
62
  export declare function pdfTextLayer(bytes: Uint8Array): Promise<string>;
62
63
  /** Pull the string literals out of one content stream's text ops. */
63
64
  export declare function pdfTextOps(content: string): string;
65
+ /** The federation's one door: the caller's OWN lane, filtered by their
66
+ * sub — the filter is a required parameter, there is no unfiltered
67
+ * path. Returns Hit-shaped matches (toHits convention: text from
68
+ * metadata.chunk_text). */
69
+ export declare function queryUserLane(model: ModelRunner, lane: VectorIndex, sub: string, query: string, k: number): Promise<Hit[]>;
64
70
  /** Deletion is immediate and total: the R2 object, the lane vectors,
65
71
  * the row. The caller has already checked ownership. */
66
72
  export declare function deleteUserDocument(ports: UserDocumentPorts, sub: string, id: string): Promise<UserDocumentRow | null>;
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  authenticate
3
- } from "../../chunk-D7MO4RVQ.js";
4
- import "../../chunk-HWWJAJWM.js";
3
+ } from "../../chunk-XMUG75ZV.js";
4
+ import "../../chunk-QYTCQIA6.js";
5
5
  import {
6
6
  P,
7
7
  setProfile
@@ -16,7 +16,7 @@ import {
16
16
  roleModel,
17
17
  sha256Hex,
18
18
  today
19
- } from "../../chunk-HWWJAJWM.js";
19
+ } from "../../chunk-QYTCQIA6.js";
20
20
  import "../../chunk-3FYJM7LH.js";
21
21
  export {
22
22
  DATASETS,
@@ -1,19 +1,24 @@
1
1
  import {
2
+ USER_DOC_LIMIT,
2
3
  checkQuoteAnchors,
4
+ createImport,
5
+ deleteUserDocument,
6
+ getUserDocument,
3
7
  handleAsk,
4
8
  handleMemories,
9
+ listUserDocuments,
5
10
  scoreFaithfulness,
6
11
  scoreJudge
7
- } from "../../chunk-YVQVT7GD.js";
12
+ } from "../../chunk-ZFOODZWO.js";
8
13
  import "../../chunk-IRCDOFP4.js";
9
14
  import {
10
15
  TOOLS_REGISTRY,
11
16
  bindModelNode,
12
17
  modelGroundingBlock
13
- } from "../../chunk-VRWNS4AI.js";
18
+ } from "../../chunk-XO26UIFH.js";
14
19
  import {
15
20
  handleSearch
16
- } from "../../chunk-ZZGKC6WO.js";
21
+ } from "../../chunk-YQQ3W5CE.js";
17
22
  import {
18
23
  buildMessages,
19
24
  citations,
@@ -38,11 +43,11 @@ import {
38
43
  sessionFrom,
39
44
  telemetry,
40
45
  understandQuery
41
- } from "../../chunk-4J47P52J.js";
46
+ } from "../../chunk-XTWH3PS6.js";
42
47
  import {
43
48
  embed,
44
49
  generateOnce
45
- } from "../../chunk-ZHT4456M.js";
50
+ } from "../../chunk-7RZ2D64X.js";
46
51
  import {
47
52
  authenticate,
48
53
  corsHeaders,
@@ -51,14 +56,14 @@ import {
51
56
  readJson,
52
57
  validateQuery,
53
58
  withCors
54
- } from "../../chunk-D7MO4RVQ.js";
59
+ } from "../../chunk-XMUG75ZV.js";
55
60
  import {
56
61
  canonicalRefusal
57
62
  } from "../../chunk-ETLSWSZ7.js";
58
63
  import {
59
64
  entitlementScope,
60
65
  standardKeysFrom
61
- } from "../../chunk-FNQ7UOEB.js";
66
+ } from "../../chunk-5HCVX34C.js";
62
67
  import {
63
68
  LIMITS,
64
69
  MODELS,
@@ -69,7 +74,7 @@ import {
69
74
  roleModel,
70
75
  sha256Hex,
71
76
  today
72
- } from "../../chunk-HWWJAJWM.js";
77
+ } from "../../chunk-QYTCQIA6.js";
73
78
  import {
74
79
  P,
75
80
  setProfile
@@ -200,201 +205,6 @@ async function handleAppendMessage(env, sub, req, convId) {
200
205
  return json({ id: mid }, 201);
201
206
  }
202
207
 
203
- // workers/worker_public/src/userDocuments.ts
204
- var USER_DOC_LIMIT = 10;
205
- var USER_DOC_MAX_BYTES = 20 * 1024 * 1024;
206
- var ACCEPTED_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
207
- function userDocumentChunkId(docId) {
208
- return `ud-${docId}`;
209
- }
210
- async function listUserDocuments(store, sub) {
211
- const res = await store.prepare("SELECT id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at FROM user_documents WHERE owner_sub = ?1 ORDER BY created_at DESC").bind(sub).all();
212
- return { documents: res.results ?? [] };
213
- }
214
- async function getUserDocument(store, sub, id) {
215
- const row = await store.prepare("SELECT id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).first();
216
- return row ?? null;
217
- }
218
- async function quotaRefusal(store, sub) {
219
- const row = await store.prepare("SELECT COUNT(*) AS n FROM user_documents WHERE owner_sub = ?1").bind(sub).first();
220
- const n = Number(row?.n ?? 0);
221
- if (n >= USER_DOC_LIMIT) {
222
- return new Response(JSON.stringify({ error: { code: "quota_exceeded", message: `You hold the maximum of ${USER_DOC_LIMIT} documents. Delete one to import another.` } }), { status: 403, headers: { "content-type": "application/json" } });
223
- }
224
- return null;
225
- }
226
- async function createImport(ports, waitUntil, sub, file) {
227
- const mime = file.type || "";
228
- if (!ACCEPTED_MIMES.has(mime)) {
229
- return { error: new Response(JSON.stringify({ error: { code: "invalid_type", message: "Upload a PNG, JPEG, WebP image or a PDF." } }), { status: 415, headers: { "content-type": "application/json" } }) };
230
- }
231
- if (file.size > USER_DOC_MAX_BYTES) {
232
- return { error: new Response(JSON.stringify({ error: { code: "too_large", message: `Documents are limited to ${Math.floor(USER_DOC_MAX_BYTES / (1024 * 1024))} MB.` } }), { status: 413, headers: { "content-type": "application/json" } }) };
233
- }
234
- const refused = await quotaRefusal(ports.store, sub);
235
- if (refused) return { error: refused };
236
- const id = crypto.randomUUID();
237
- const r2Key = `${sub}/${id}`;
238
- const bytes = new Uint8Array(await file.arrayBuffer());
239
- await ports.blobs.put(r2Key, bytes.buffer, mime);
240
- const now = (/* @__PURE__ */ new Date()).toISOString();
241
- const row = {
242
- id,
243
- owner_sub: sub,
244
- name: file.name || "document",
245
- kind: null,
246
- status: "importing",
247
- bytes: bytes.byteLength,
248
- r2_key: r2Key,
249
- fields: null,
250
- error: null,
251
- created_at: now,
252
- updated_at: now
253
- };
254
- await ports.store.prepare(
255
- "INSERT INTO user_documents (id, owner_sub, name, kind, status, bytes, r2_key, fields, error, created_at, updated_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)"
256
- ).bind(id, sub, row.name, row.kind, row.status, row.bytes, row.r2_key, row.fields, row.error, now, now).run();
257
- waitUntil(processImport(ports, row, mime, bytes).catch(() => {
258
- }));
259
- return { document: row };
260
- }
261
- async function processImport(ports, row, mime, bytes) {
262
- const setStatus = async (status, fields, error) => {
263
- await ports.store.prepare("UPDATE user_documents SET status = ?1, kind = ?2, fields = ?3, error = ?4, updated_at = ?5 WHERE id = ?6").bind(status, fields ? extractKind(fields) : null, fields ? JSON.stringify(fields) : null, error, (/* @__PURE__ */ new Date()).toISOString(), row.id).run();
264
- };
265
- try {
266
- let text;
267
- if (mime === "application/pdf") {
268
- text = await pdfTextLayer(bytes);
269
- if (!text || text.replace(/\s+/g, "").length < 40) {
270
- await setStatus("no_text_layer", null, "This PDF has no extractable text layer. Export page images (PNG/JPEG) and import those \u2014 the vision lane reads them directly.");
271
- return;
272
- }
273
- } else {
274
- text = await visionTranscribe(ports.model, mime, bytes);
275
- if (!text || text.replace(/\s+/g, "").length < 20) {
276
- await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
277
- return;
278
- }
279
- }
280
- const extraction = await structureDocument(ports.model, row.name, mime, text);
281
- const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
282
- const chunkText = `Member document (${extraction.kind}) \u2014 ${row.name}. ${fieldsLine}. ${extraction.summary}
283
-
284
- ${extraction.text.slice(0, 8e3)}`;
285
- const [vector] = await ports.model.embed([chunkText]);
286
- await ports.lane.upsert([
287
- {
288
- id: userDocumentChunkId(row.id),
289
- values: vector,
290
- metadata: { user_sub: row.owner_sub, doc_id: row.id, kind: extraction.kind, name: row.name }
291
- }
292
- ]);
293
- await setStatus("ready", { kind: extraction.kind, ...extraction.fields, summary: extraction.summary }, null);
294
- } catch (e) {
295
- await setStatus("failed", null, String(e).slice(0, 200)).catch(() => {
296
- });
297
- }
298
- }
299
- function extractKind(fields) {
300
- return fields.kind || "other";
301
- }
302
- async function visionTranscribe(model, mime, bytes) {
303
- let binary = "";
304
- const CHUNK = 32768;
305
- for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
306
- const dataUrl = `data:${mime};base64,${btoa(binary)}`;
307
- const res = await model.run({
308
- model: MODELS.member,
309
- messages: [
310
- { role: "system", content: "Transcribe everything you can read in this document image \u2014 certificate numbers, holders, models, values, dates, clause references. Transcribe first; organize nothing." },
311
- { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }
312
- ],
313
- maxTokens: 2048,
314
- effort: "low",
315
- temperature: 0.15
316
- });
317
- return res.text ?? "";
318
- }
319
- async function structureDocument(model, name, mime, text) {
320
- const res = await model.run({
321
- model: MODELS.member,
322
- messages: [
323
- { role: "system", content: `You classify and structure an imported metrology document. Answer with ONE JSON object: {"kind": "certificate"|"test_report"|"other", "fields": {\u2026short typed fields\u2026}, "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.` },
324
- { role: "user", content: `Document name: ${name}
325
- Format: ${mime}
326
-
327
- Text:
328
- ${text.slice(0, 12e3)}` }
329
- ],
330
- maxTokens: 2048,
331
- effort: "low",
332
- temperature: 0.15
333
- });
334
- const raw = res.text ?? "";
335
- const m = /\{[\s\S]*\}/.exec(raw);
336
- if (!m) throw new Error("the structuring call returned no JSON object");
337
- const parsed = JSON.parse(m[0]);
338
- const fields = {};
339
- for (const [k, v] of Object.entries(parsed.fields ?? {})) {
340
- if (typeof v === "string" || typeof v === "number") fields[k.slice(0, 40)] = String(v).slice(0, 200);
341
- }
342
- const kind = parsed.kind === "certificate" || parsed.kind === "test_report" ? parsed.kind : "other";
343
- return { kind, fields, summary: String(parsed.summary ?? "").slice(0, 1200), text };
344
- }
345
- async function pdfTextLayer(bytes) {
346
- const raw = new TextDecoder("latin1").decode(bytes);
347
- const parts = [];
348
- const streamRe = /stream\r?\n?/g;
349
- let m;
350
- while (m = streamRe.exec(raw)) {
351
- const start = m.index + m[0].length;
352
- const end = raw.indexOf("endstream", start);
353
- if (end < 0) break;
354
- const chunk = raw.slice(start, end);
355
- streamRe.lastIndex = end;
356
- let content = "";
357
- if (chunk.charCodeAt(0) === 120) {
358
- try {
359
- const ds = new DecompressionStream("deflate");
360
- const stream = new Blob([new Uint8Array([...chunk].map((c) => c.charCodeAt(0) & 255))]).stream().pipeThrough(ds);
361
- content = await new Response(stream).text();
362
- } catch {
363
- continue;
364
- }
365
- } else if (/\bTj\b|\bTJ\b/.test(chunk)) {
366
- content = chunk;
367
- } else {
368
- continue;
369
- }
370
- parts.push(pdfTextOps(content));
371
- if (parts.join("").length > 2e5) break;
372
- }
373
- return parts.join("\n");
374
- }
375
- function pdfTextOps(content) {
376
- const out = [];
377
- const re = /\((?:\\.|[^\\()])*\)/g;
378
- let m;
379
- while (m = re.exec(content)) {
380
- let s = m[0].slice(1, -1);
381
- s = s.replace(/\\([nrtbf()/\\])/g, (_, c) => ({ n: "\n", r: "", t: " ", b: "", f: "", "(": "(", ")": ")", "/": "/", "\\": "\\" })[c] ?? c);
382
- s = s.replace(/\\([0-7]{1,3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)));
383
- if (s.trim()) out.push(s);
384
- }
385
- return out.join(" ");
386
- }
387
- async function deleteUserDocument(ports, sub, id) {
388
- const row = await getUserDocument(ports.store, sub, id);
389
- if (!row) return null;
390
- if (row.r2_key) await ports.blobs.delete(row.r2_key).catch(() => {
391
- });
392
- await ports.lane.deleteIds([userDocumentChunkId(id)]).catch(() => {
393
- });
394
- await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
395
- return row;
396
- }
397
-
398
208
  // workers/worker_public/src/projects.ts
399
209
  var MAX_FILES = 10;
400
210
  var MAX_CONTENT = 8e3;
@@ -1373,13 +1183,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
1373
1183
  // stream:false forces the JSON lane (anon defaults to SSE)
1374
1184
  body: JSON.stringify({ ...args, stream: false })
1375
1185
  });
1376
- const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-HLA7O2ZK.js");
1186
+ const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-BTH6YAOB.js");
1377
1187
  let payload;
1378
1188
  if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
1379
1189
  const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
1380
1190
  payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
1381
1191
  } else {
1382
- const res = name === "ask" ? await (await import("../../ask-YWYXQ6PE.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-N37WULEM.js")).handleSearch(env, ctx, inner, tier, key);
1192
+ const res = name === "ask" ? await (await import("../../ask-7DFXT4DJ.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-4FWS4HVI.js")).handleSearch(env, ctx, inner, tier, key);
1383
1193
  payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
1384
1194
  }
1385
1195
  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-FNQ7UOEB.js";
8
- import "../../chunk-HWWJAJWM.js";
7
+ } from "../../chunk-5HCVX34C.js";
8
+ import "../../chunk-QYTCQIA6.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.182",
30
+ "version": "0.2.184",
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",
@@ -47,6 +47,8 @@ import { json, err, corsHeaders, readJson, validateQuery, type ApiKey } from "./
47
47
  import { chargeTokens, checkQuota, clientIp, creditBudget, creditEstimate, estimateTokens, telemetry, tokenBudget, usageTotal } from "./quota";
48
48
  import { graphExpand, editionNote } from "./graph";
49
49
  import { registerNote, searchRegister, certificateLinks, registerAggregateIntent, registerAggregate, aggregateNote, aggregateBlock, queryFamily, registerBypassesCache } from "./certificates";
50
+ import { queryUserLane } from "./userDocuments";
51
+ import { cfModelRunner, cfVectorIndex } from "./ports/cloudflare/adapters";
50
52
  import { TOOL_DECLARATION, parseToolCall, runTool, toolNote } from "./tools";
51
53
  import { operationsLane } from "./operations.ts";
52
54
  import { extractNameplate, nameplateRegisterQuery } from "./nameplate.ts";
@@ -518,6 +520,13 @@ async function handleAsk(
518
520
  const federate = (member || keyLicensed) && service && isoOn
519
521
  ? (q2: string) => retrieveInternal(service, fedAuth, q2)
520
522
  : undefined;
523
+ // The member's OWN documents federate beside the corpus (TODO.sota/20
524
+ // slice 4): their lane, filtered by their sub inside the callback —
525
+ // no unfiltered path exists. The lane hits carry the member's
526
+ // citations ("Member document — <name>").
527
+ const userDocs = member && env.USER_DOCS_INDEX
528
+ ? (q2: string) => queryUserLane(cfModelRunner(env.AI), cfVectorIndex(env.USER_DOCS_INDEX), member.sub, q2, THRESHOLDS.userLaneK)
529
+ : undefined;
521
530
 
522
531
  const ns = tier === "key" ? `k:${key!.id}` : member ? `m:${member.sub}` : "anon";
523
532
  const model = member ? MODELS.member : MODELS.anon;
@@ -1380,7 +1389,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1380
1389
  // top-N before a post-hoc seal ever sees one. A document named IN THE
1381
1390
  // QUESTION keeps the soft steer by design (the widen covers sparse
1382
1391
  // publications there).
1383
- retrieved = await retrieve(env, q.query, { prev, understanding, federate, warmEmbed, graphDocNumbers,
1392
+ retrieved = await retrieve(env, q.query, { prev, understanding, federate, userDocs, warmEmbed, graphDocNumbers,
1384
1393
  sealScope: declaredScoped ? docScope : null, optimisticHits, optimisticVec,
1385
1394
  datasetScope: narrowed ? corpora : null, standardKeys, lexicalBoost, licensedDocNumbers,
1386
1395
  ...(routeSubset ? { stageSubset: routeSubset } : {}) });
@@ -1418,7 +1427,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1418
1427
  if (grade === "weak" && understanding?.docidentifier) {
1419
1428
  const broaden = `${understanding.standalone_query || q.query} ${understanding.docidentifier}`.trim();
1420
1429
  const tc = Date.now();
1421
- const second = await retrieve(env, q.query, { prev, understanding, queryOverride: broaden, federate, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...(routeSubset ? { stageSubset: routeSubset } : {}) });
1430
+ const second = await retrieve(env, q.query, { prev, understanding, queryOverride: broaden, federate, userDocs, datasetScope: narrowed ? corpora : null, standardKeys, sealScope: declaredScoped ? docScope : null, lexicalBoost, ...(routeSubset ? { stageSubset: routeSubset } : {}) });
1422
1431
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q.query, second.hits.map((h: Hit) => h.text));
1423
1432
  stageTiming.corrective = Date.now() - tc;
1424
1433
  if (grade2 === "good") retrieved = second; // corrective retry must be strictly better
@@ -121,6 +121,9 @@ export const THRESHOLDS = {
121
121
  /** Federated-ISO discount — the public corpus answers by default;
122
122
  * internal ISO passages compete but don't preempt. */
123
123
  federateDiscount: 0.95,
124
+ /** the member's own imported documents: how many lane hits may join
125
+ * the pool (TODO.sota/20 slice 4) — their content, their question */
126
+ userLaneK: 3,
124
127
  /** Standard-reference nudge (L5): when the question asks about an
125
128
  * invoked ISO/IEC standard, chunks that CARRY such a citation (their
126
129
  * text contains an ISO/IEC identifier) get a spread-scaled boost —
@@ -25,6 +25,7 @@ import { subQuery } from "./subQuery.ts";
25
25
  import { poolOpen } from "./poolOpen.ts";
26
26
  import { lexicalUnion } from "./lexicalUnion.ts";
27
27
  import { federate } from "./federate.ts";
28
+ import { userLane } from "./userLane.ts";
28
29
  import { seal } from "./seal.ts";
29
30
  import { licenseScope } from "./licenseScope.ts";
30
31
  import { corpusScope } from "./corpusScope.ts";
@@ -58,6 +59,7 @@ export const STAGES: Stage[] = [
58
59
  poolOpen,
59
60
  lexicalUnion,
60
61
  federate,
62
+ userLane,
61
63
  seal,
62
64
  licenseScope,
63
65
  overviewDemote,
@@ -18,6 +18,9 @@ export interface RetrieveOptions {
18
18
  * document's own vocabulary would otherwise miss. */
19
19
  lexicalBoost?: string;
20
20
  federate?: (query: string) => Promise<Hit[]>;
21
+ /** The member's own imported documents (TODO.sota/20 slice 4) —
22
+ * the sub filter rides inside the callback; no unfiltered path. */
23
+ userDocs?: (query: string) => Promise<Hit[]>;
21
24
  warmEmbed?: Promise<number[] | null>;
22
25
  graphDocNumbers?: string[];
23
26
  /** The licensed standards the entitled, topically-matched question
@@ -0,0 +1,22 @@
1
+ // The member's OWN documents, federated additively into the candidate
2
+ // pool (TODO.sota/20 v1, slice 4): the caller's lane (their imported
3
+ // certificates and reports) beside the public corpus — no discount,
4
+ // their content answers their question. The callback carries the
5
+ // mandatory sub filter (queryUserLane has no unfiltered path); the
6
+ // stage adds nothing when the caller has no documents.
7
+ import type { Stage } from "./types.ts";
8
+
9
+ export const userLane: Stage = {
10
+ name: "user-lane",
11
+ when: (c) => !!c.opts.userDocs,
12
+ run: async (c) => {
13
+ const fed = await c.opts.userDocs!(c.rq).catch(() => []);
14
+ const seen = new Set(c.hits.map((h) => h.id));
15
+ for (const h of fed) {
16
+ if (!seen.has(h.id)) {
17
+ c.hits.push({ ...h });
18
+ seen.add(h.id);
19
+ }
20
+ }
21
+ },
22
+ };
@@ -30,6 +30,7 @@ import type { StoreQuery } from "./ports/store.ts";
30
30
  import type { VectorIndex } from "./ports/vector.ts";
31
31
  import type { ModelRunner } from "./ports/model.ts";
32
32
  import { MODELS } from "./config.ts";
33
+ import type { Hit } from "../../shared/chunk.ts";
33
34
 
34
35
  export const USER_DOC_LIMIT = 10;
35
36
  export const USER_DOC_MAX_BYTES = 20 * 1024 * 1024;
@@ -170,11 +171,30 @@ export async function processImport(ports: UserDocumentPorts, row: UserDocumentR
170
171
  const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
171
172
  const chunkText = `Member document (${extraction.kind}) — ${row.name}. ${fieldsLine}. ${extraction.summary}\n\n${extraction.text.slice(0, 8000)}`;
172
173
  const [vector] = await ports.model.embed([chunkText]);
174
+ // the lane vector carries the ChunkMeta shape the pipeline speaks
175
+ // (toHits reads text from metadata.chunk_text) plus user_sub — the
176
+ // filter key the federation's mandatory-by-construction scope
173
177
  await ports.lane.upsert([
174
178
  {
175
179
  id: userDocumentChunkId(row.id),
176
180
  values: vector,
177
- metadata: { user_sub: row.owner_sub, doc_id: row.id, kind: extraction.kind, name: row.name },
181
+ metadata: {
182
+ user_sub: row.owner_sub,
183
+ doc_id: `ud-${row.id}`,
184
+ docidentifier: `Member document — ${row.name}`,
185
+ doctype: "user",
186
+ doc_number: extraction.kind,
187
+ edition: "",
188
+ language: "en",
189
+ clause_anchor: "",
190
+ clause_title: row.name.slice(0, 120),
191
+ tier: "member",
192
+ corpus: "user_docs",
193
+ text_ref: "",
194
+ kind: extraction.kind,
195
+ name: row.name.slice(0, 120),
196
+ chunk_text: chunkText.slice(0, 1800),
197
+ },
178
198
  },
179
199
  ]);
180
200
  await setStatus("ready", { kind: extraction.kind, ...extraction.fields, summary: extraction.summary }, null);
@@ -282,6 +302,21 @@ export function pdfTextOps(content: string): string {
282
302
  return out.join(" ");
283
303
  }
284
304
 
305
+ /** The federation's one door: the caller's OWN lane, filtered by their
306
+ * sub — the filter is a required parameter, there is no unfiltered
307
+ * path. Returns Hit-shaped matches (toHits convention: text from
308
+ * metadata.chunk_text). */
309
+ export async function queryUserLane(model: ModelRunner, lane: VectorIndex, sub: string, query: string, k: number): Promise<Hit[]> {
310
+ const [vector] = await model.embed([query]);
311
+ const matches = await lane.query({ vector, topK: k, filter: { user_sub: sub } });
312
+ return matches.map((m) => ({
313
+ id: m.id,
314
+ score: m.score,
315
+ metadata: m.metadata as never,
316
+ text: String((m.metadata as any)?.chunk_text ?? ""),
317
+ }));
318
+ }
319
+
285
320
  /** Deletion is immediate and total: the R2 object, the lane vectors,
286
321
  * the row. The caller has already checked ownership. */
287
322
  export async function deleteUserDocument(ports: UserDocumentPorts, sub: string, id: string): Promise<UserDocumentRow | null> {
@@ -1,16 +0,0 @@
1
- import {
2
- handleAsk
3
- } from "./chunk-YVQVT7GD.js";
4
- import "./chunk-IRCDOFP4.js";
5
- import "./chunk-VRWNS4AI.js";
6
- import "./chunk-4J47P52J.js";
7
- import "./chunk-ZHT4456M.js";
8
- import "./chunk-D7MO4RVQ.js";
9
- import "./chunk-ETLSWSZ7.js";
10
- import "./chunk-FNQ7UOEB.js";
11
- import "./chunk-HWWJAJWM.js";
12
- import "./chunk-3FYJM7LH.js";
13
- import "./chunk-YGQCVPX6.js";
14
- export {
15
- handleAsk
16
- };
@@ -1,14 +0,0 @@
1
- import {
2
- handleSearch
3
- } from "./chunk-ZZGKC6WO.js";
4
- import "./chunk-4J47P52J.js";
5
- import "./chunk-ZHT4456M.js";
6
- import "./chunk-D7MO4RVQ.js";
7
- import "./chunk-ETLSWSZ7.js";
8
- import "./chunk-FNQ7UOEB.js";
9
- import "./chunk-HWWJAJWM.js";
10
- import "./chunk-3FYJM7LH.js";
11
- import "./chunk-YGQCVPX6.js";
12
- export {
13
- handleSearch
14
- };