@konneal/engine 0.2.182 → 0.2.185

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-JVKJWLI7.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));
@@ -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,14 @@ 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
+ cfStore,
121
+ cfVectorIndex,
119
122
  portModelRunner,
120
123
  portStore
121
124
  } from "./chunk-YGQCVPX6.js";
@@ -1516,7 +1519,7 @@ function matchAnswers(mode, requirements, answers, metBand, refuteBand) {
1516
1519
  items.push({
1517
1520
  text: r.text,
1518
1521
  clause: r.clause,
1519
- band: mode === "check" ? bandFor(probability, metBand, refuteBand) : "met",
1522
+ band: mode === "check" ? bandFor(probability, metBand, refuteBand) : null,
1520
1523
  probability: Math.round(probability * 100) / 100
1521
1524
  });
1522
1525
  });
@@ -1528,10 +1531,11 @@ function assembleSection(mode, items) {
1528
1531
  if (!items.length) return "";
1529
1532
  const title = mode === "check" ? "Requirements check (automated)" : "Requirements (from the cited clauses)";
1530
1533
  const lines = items.map((it) => {
1531
- const mark = mode === "check" ? MARK[it.band] : "\u2022";
1534
+ const band = mode === "check" ? it.band : null;
1535
+ const mark = band ? MARK[band] : "\u2022";
1532
1536
  const clause = it.clause ? ` \u2014 ${it.clause}` : "";
1533
- const prob = mode === "check" ? ` (${Math.round(it.probability * 100)}%)` : "";
1534
- return `- ${mark} ${it.text}${clause}${prob}${mode === "check" ? ` \u2014 ${WORD[it.band]}` : ""}`;
1537
+ const prob = band ? ` (${Math.round(it.probability * 100)}%)` : "";
1538
+ return `- ${mark} ${it.text}${clause}${prob}${band ? ` \u2014 ${WORD[band]}` : ""}`;
1535
1539
  });
1536
1540
  return `
1537
1541
 
@@ -1627,7 +1631,7 @@ function telemetryDecisions(env, ctx, tier, queryHash, result, durationMs) {
1627
1631
  try {
1628
1632
  telemetry(env, ctx, tier, "ask-decisions", result ? result.gate.toFixed(2) : "0", !!result, result?.items.length ?? 0, queryHash, result?.mode ?? void 0, void 0, { durationMs });
1629
1633
  for (const it of result?.items ?? []) {
1630
- telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band, void 0, {});
1634
+ telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band ?? void 0, void 0, {});
1631
1635
  }
1632
1636
  } catch {
1633
1637
  }
@@ -1675,6 +1679,246 @@ function partitionSubsets(hits, k = SPECULATIVE_SUBSETS) {
1675
1679
  // workers/worker_public/prompts/speculative-verify.md
1676
1680
  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
1681
 
1682
+ // workers/worker_public/src/userDocuments.ts
1683
+ var USER_DOC_LIMIT = 10;
1684
+ var USER_DOC_MAX_BYTES = 20 * 1024 * 1024;
1685
+ var ACCEPTED_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
1686
+ function userDocumentChunkId(docId) {
1687
+ return `ud-${docId}`;
1688
+ }
1689
+ async function listUserDocuments(store, sub) {
1690
+ 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();
1691
+ return { documents: res.results ?? [] };
1692
+ }
1693
+ async function getUserDocument(store, sub, id) {
1694
+ 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();
1695
+ return row ?? null;
1696
+ }
1697
+ async function quotaRefusal(store, sub) {
1698
+ const row = await store.prepare("SELECT COUNT(*) AS n FROM user_documents WHERE owner_sub = ?1").bind(sub).first();
1699
+ const n = Number(row?.n ?? 0);
1700
+ if (n >= USER_DOC_LIMIT) {
1701
+ 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" } });
1702
+ }
1703
+ return null;
1704
+ }
1705
+ async function createImport(ports, waitUntil, sub, file) {
1706
+ const mime = file.type || "";
1707
+ if (!ACCEPTED_MIMES.has(mime)) {
1708
+ 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" } }) };
1709
+ }
1710
+ if (file.size > USER_DOC_MAX_BYTES) {
1711
+ 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" } }) };
1712
+ }
1713
+ const refused = await quotaRefusal(ports.store, sub);
1714
+ if (refused) return { error: refused };
1715
+ const id = crypto.randomUUID();
1716
+ const r2Key = `${sub}/${id}`;
1717
+ const bytes = new Uint8Array(await file.arrayBuffer());
1718
+ await ports.blobs.put(r2Key, bytes.buffer, mime);
1719
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1720
+ const row = {
1721
+ id,
1722
+ owner_sub: sub,
1723
+ name: file.name || "document",
1724
+ kind: null,
1725
+ status: "importing",
1726
+ bytes: bytes.byteLength,
1727
+ r2_key: r2Key,
1728
+ fields: null,
1729
+ error: null,
1730
+ created_at: now,
1731
+ updated_at: now
1732
+ };
1733
+ await ports.store.prepare(
1734
+ "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)"
1735
+ ).bind(id, sub, row.name, row.kind, row.status, row.bytes, row.r2_key, row.fields, row.error, now, now).run();
1736
+ waitUntil(processImport(ports, row, mime, bytes).catch(() => {
1737
+ }));
1738
+ return { document: row };
1739
+ }
1740
+ async function processImport(ports, row, mime, bytes) {
1741
+ const setStatus = async (status, fields, error) => {
1742
+ 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();
1743
+ };
1744
+ try {
1745
+ let text;
1746
+ if (mime === "application/pdf") {
1747
+ text = await pdfTextLayer(bytes);
1748
+ if (!text || text.replace(/\s+/g, "").length < 40) {
1749
+ 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.");
1750
+ return;
1751
+ }
1752
+ } else {
1753
+ text = await visionTranscribe(ports.model, mime, bytes);
1754
+ if (!text || text.replace(/\s+/g, "").length < 20) {
1755
+ await setStatus("failed", null, "The vision lane could not read this image. Try a sharper photo.");
1756
+ return;
1757
+ }
1758
+ }
1759
+ const extraction = await structureDocument(ports.model, row.name, mime, text);
1760
+ const fieldsLine = Object.entries(extraction.fields).map(([k, v]) => `${k}: ${v}`).join("; ");
1761
+ const chunkText = `Member document (${extraction.kind}) \u2014 ${row.name}. ${fieldsLine}. ${extraction.summary}
1762
+
1763
+ ${extraction.text.slice(0, 8e3)}`;
1764
+ const [vector] = await ports.model.embed([chunkText]);
1765
+ await ports.lane.upsert([
1766
+ {
1767
+ id: userDocumentChunkId(row.id),
1768
+ values: vector,
1769
+ metadata: {
1770
+ user_sub: row.owner_sub,
1771
+ doc_id: `ud-${row.id}`,
1772
+ docidentifier: `Member document \u2014 ${row.name}`,
1773
+ doctype: "user",
1774
+ doc_number: extraction.kind,
1775
+ edition: "",
1776
+ language: "en",
1777
+ clause_anchor: "",
1778
+ clause_title: row.name.slice(0, 120),
1779
+ tier: "member",
1780
+ corpus: "user_docs",
1781
+ text_ref: "",
1782
+ kind: extraction.kind,
1783
+ name: row.name.slice(0, 120),
1784
+ chunk_text: chunkText.slice(0, 1800)
1785
+ }
1786
+ }
1787
+ ]);
1788
+ await setStatus("ready", { kind: extraction.kind, ...extraction.fields, summary: extraction.summary }, null);
1789
+ } catch (e) {
1790
+ await setStatus("failed", null, String(e).slice(0, 200)).catch(() => {
1791
+ });
1792
+ }
1793
+ }
1794
+ function extractKind(fields) {
1795
+ return fields.kind || "other";
1796
+ }
1797
+ async function visionTranscribe(model, mime, bytes) {
1798
+ let binary = "";
1799
+ const CHUNK = 32768;
1800
+ for (let i = 0; i < bytes.length; i += CHUNK) binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
1801
+ const dataUrl = `data:${mime};base64,${btoa(binary)}`;
1802
+ const res = await model.run({
1803
+ model: MODELS.member,
1804
+ messages: [
1805
+ { 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." },
1806
+ { role: "user", content: [{ type: "image_url", image_url: { url: dataUrl } }] }
1807
+ ],
1808
+ maxTokens: 2048,
1809
+ effort: "low",
1810
+ temperature: 0.15
1811
+ });
1812
+ return res.text ?? "";
1813
+ }
1814
+ async function structureDocument(model, name, mime, text) {
1815
+ const res = await model.run({
1816
+ model: MODELS.member,
1817
+ messages: [
1818
+ { 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.` },
1819
+ { role: "user", content: `Document name: ${name}
1820
+ Format: ${mime}
1821
+
1822
+ Text:
1823
+ ${text.slice(0, 12e3)}` }
1824
+ ],
1825
+ maxTokens: 2048,
1826
+ effort: "low",
1827
+ temperature: 0.15
1828
+ });
1829
+ const raw = res.text ?? "";
1830
+ const m = /\{[\s\S]*\}/.exec(raw);
1831
+ if (!m) throw new Error("the structuring call returned no JSON object");
1832
+ const parsed = JSON.parse(m[0]);
1833
+ const fields = {};
1834
+ for (const [k, v] of Object.entries(parsed.fields ?? {})) {
1835
+ if (typeof v === "string" || typeof v === "number") fields[k.slice(0, 40)] = String(v).slice(0, 200);
1836
+ }
1837
+ const kind = parsed.kind === "certificate" || parsed.kind === "test_report" ? parsed.kind : "other";
1838
+ return { kind, fields, summary: String(parsed.summary ?? "").slice(0, 1200), text };
1839
+ }
1840
+ async function pdfTextLayer(bytes) {
1841
+ const raw = new TextDecoder("latin1").decode(bytes);
1842
+ const parts = [];
1843
+ const streamRe = /stream\r?\n?/g;
1844
+ let m;
1845
+ while (m = streamRe.exec(raw)) {
1846
+ const start = m.index + m[0].length;
1847
+ const end = raw.indexOf("endstream", start);
1848
+ if (end < 0) break;
1849
+ const chunk = raw.slice(start, end);
1850
+ streamRe.lastIndex = end;
1851
+ let content = "";
1852
+ if (chunk.charCodeAt(0) === 120) {
1853
+ try {
1854
+ const ds = new DecompressionStream("deflate");
1855
+ const stream = new Blob([new Uint8Array([...chunk].map((c) => c.charCodeAt(0) & 255))]).stream().pipeThrough(ds);
1856
+ content = await new Response(stream).text();
1857
+ } catch {
1858
+ continue;
1859
+ }
1860
+ } else if (/\bTj\b|\bTJ\b/.test(chunk)) {
1861
+ content = chunk;
1862
+ } else {
1863
+ continue;
1864
+ }
1865
+ parts.push(pdfTextOps(content));
1866
+ if (parts.join("").length > 2e5) break;
1867
+ }
1868
+ return parts.join("\n");
1869
+ }
1870
+ function pdfTextOps(content) {
1871
+ const out = [];
1872
+ const re = /\((?:\\.|[^\\()])*\)/g;
1873
+ let m;
1874
+ while (m = re.exec(content)) {
1875
+ let s = m[0].slice(1, -1);
1876
+ s = s.replace(/\\([nrtbf()/\\])/g, (_, c) => ({ n: "\n", r: "", t: " ", b: "", f: "", "(": "(", ")": ")", "/": "/", "\\": "\\" })[c] ?? c);
1877
+ s = s.replace(/\\([0-7]{1,3})/g, (_, o) => String.fromCharCode(parseInt(o, 8)));
1878
+ if (s.trim()) out.push(s);
1879
+ }
1880
+ return out.join(" ");
1881
+ }
1882
+ async function queryUserLane(model, lane, sub, query, k) {
1883
+ const [vector] = await model.embed([query]);
1884
+ const matches = await lane.query({ vector, topK: k, filter: { user_sub: sub } });
1885
+ return matches.map((m) => ({
1886
+ id: m.id,
1887
+ score: m.score,
1888
+ metadata: m.metadata,
1889
+ text: String(m.metadata?.chunk_text ?? "")
1890
+ }));
1891
+ }
1892
+ async function deleteUserDocument(ports, sub, id) {
1893
+ const row = await getUserDocument(ports.store, sub, id);
1894
+ if (!row) return null;
1895
+ if (row.r2_key) await ports.blobs.delete(row.r2_key).catch(() => {
1896
+ });
1897
+ await ports.lane.deleteIds([userDocumentChunkId(id)]).catch(() => {
1898
+ });
1899
+ await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
1900
+ return row;
1901
+ }
1902
+ async function memberDocFields(store, sub) {
1903
+ const res = await store.prepare("SELECT id, name, fields FROM user_documents WHERE owner_sub = ?1 AND status = 'ready' AND fields IS NOT NULL ORDER BY created_at DESC").bind(sub).all();
1904
+ const out = [];
1905
+ for (const r of res.results ?? []) {
1906
+ try {
1907
+ const parsed = JSON.parse(r.fields);
1908
+ const fields = {};
1909
+ for (const [k, v] of Object.entries(parsed)) {
1910
+ if (typeof v === "string" || typeof v === "number") fields[k] = String(v);
1911
+ }
1912
+ if (Object.keys(fields).length) out.push({ doc_id: r.id, name: r.name, fields });
1913
+ } catch {
1914
+ }
1915
+ }
1916
+ return out;
1917
+ }
1918
+ function fieldsAsText(docs) {
1919
+ return docs.map((d) => Object.entries(d.fields).map(([k, v]) => `${k.replace(/_/g, " ")}: ${v}`).join("; ")).join("\n");
1920
+ }
1921
+
1678
1922
  // workers/worker_public/src/operations.ts
1679
1923
  function isOperationIntent(query) {
1680
1924
  return /\b(operations?|endpoints?)\b/i.test(query);
@@ -2179,6 +2423,7 @@ async function handleAsk(env, ctx, req, tier, key) {
2179
2423
  const requestSaltStr = requestSalt(scope, memoryUsed);
2180
2424
  const salt = requestSaltStr ? `${requestSaltStr}|effort:${effort}` : `effort:${effort}`;
2181
2425
  const federate = (member || keyLicensed) && service && isoOn ? (q2) => retrieveInternal(service, fedAuth, q2) : void 0;
2426
+ 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
2427
  const ns = tier === "key" ? `k:${key.id}` : member ? `m:${member.sub}` : "anon";
2183
2428
  const model = member ? MODELS.member : MODELS.anon;
2184
2429
  const prev = typeof body?.prev === "string" ? body.prev.slice(0, 800) : void 0;
@@ -2554,7 +2799,13 @@ ${summary}` }] : [],
2554
2799
  console.log("model plane: bound", boundModel.node_id, `[${boundModel.standard}]`, boundModel.clause?.urn ?? "no-clause", boundModel.gated ? "(gated: license)" : "");
2555
2800
  }
2556
2801
  const modelNote = boundModel && !boundModel.gated ? modelGroundingBlock(boundModel) : void 0;
2557
- let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? evaluate(boundModel.content, q2.query) : null;
2802
+ const memberDocs = member && !ablate?.noVerdict ? await memberDocFields(cfStore(env.DB), member.sub).catch(() => []) : [];
2803
+ const memberFieldsText = memberDocs.length ? fieldsAsText(memberDocs) : "";
2804
+ const statedText = memberFieldsText ? `${q2.query}
2805
+ ${memberFieldsText}` : q2.query;
2806
+ const memberDocNote = memberDocs.length ? `MEMBER DOCUMENT DATA \u2014 these are the QUESTION-ASKER'S OWN recorded values from their imported documents; treat them as the stated state for any conformance check, and cite the document name when you use them:
2807
+ ${memberFieldsText}` : void 0;
2808
+ let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? evaluate(boundModel.content, statedText) : null;
2558
2809
  if (machineVerdict === null && boundModel && !boundModel.gated) {
2559
2810
  try {
2560
2811
  const unitTokens = [...new Set(Object.values(extractParamsWithUnits(q2.query, symbolsIn(extractChecks(boundModel.content))).units).map((u) => u.toLowerCase()))];
@@ -2587,7 +2838,7 @@ ${summary}` }] : [],
2587
2838
  if (!machineVerdict && !boundModel && !ablate?.noVerdict && P().publisher.features?.model_plane) {
2588
2839
  const ql = q2.query.toLowerCase();
2589
2840
  const severityWord = /\b(severity|test|valid|tolerance|condition|within)\b/.test(ql);
2590
- const stated = quantitiesIn(q2.query);
2841
+ const stated = quantitiesIn(statedText);
2591
2842
  if (severityWord && Object.keys(stated).length >= 1) {
2592
2843
  const docNum = modelDocHint?.doc_number;
2593
2844
  const rows = await modelNodeRows("condition_set", docNum);
@@ -2734,6 +2985,7 @@ Answer account questions from these records ONLY: name the record when you use i
2734
2985
  prev,
2735
2986
  understanding,
2736
2987
  federate,
2988
+ userDocs,
2737
2989
  warmEmbed,
2738
2990
  graphDocNumbers,
2739
2991
  sealScope: declaredScoped ? docScope : null,
@@ -2768,7 +3020,7 @@ Answer account questions from these records ONLY: name the record when you use i
2768
3020
  if (grade === "weak" && understanding?.docidentifier) {
2769
3021
  const broaden = `${understanding.standalone_query || q2.query} ${understanding.docidentifier}`.trim();
2770
3022
  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 } : {} });
3023
+ 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
3024
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q2.query, second.hits.map((h) => h.text));
2773
3025
  stageTiming.corrective = Date.now() - tc;
2774
3026
  if (grade2 === "good") retrieved = second;
@@ -2840,7 +3092,7 @@ Answer account questions from these records ONLY: name the record when you use i
2840
3092
  q2.lang,
2841
3093
  keptHistory,
2842
3094
  // stage-extracted graph facts (GraphRAG) ride the same note channel
2843
- [ops.note, processNote, eNote, regNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0,
3095
+ [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...retrieved.notes ?? []].filter(Boolean).join("\n") || void 0,
2844
3096
  summary,
2845
3097
  budget,
2846
3098
  ablate?.noCompress !== true
@@ -3299,6 +3551,11 @@ Answer account questions from these records ONLY: name the record when you use i
3299
3551
 
3300
3552
  export {
3301
3553
  handleMemories,
3554
+ USER_DOC_LIMIT,
3555
+ listUserDocuments,
3556
+ getUserDocument,
3557
+ createImport,
3558
+ deleteUserDocument,
3302
3559
  scoreFaithfulness,
3303
3560
  checkQuoteAnchors,
3304
3561
  scoreJudge,
@@ -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";
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 —
@@ -5,7 +5,11 @@ export interface DerivedRequirement {
5
5
  export interface DecisionItem {
6
6
  text: string;
7
7
  clause: string;
8
- band: "met" | "not-met" | "unclear";
8
+ /** null in LIST mode: a requirements inventory makes no conformance
9
+ * claim, so met/not-met/unclear would all lie (the calibration
10
+ * reader's first week caught the hardcoded "met" this replaces —
11
+ * 2026-11-05, TODO.decisions/03). */
12
+ band: "met" | "not-met" | "unclear" | null;
9
13
  probability: number;
10
14
  }
11
15
  export type DecisionMode = "check" | "list";
@@ -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,29 @@ 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>;
73
+ /** The member's own recorded values, ready to serve as the STATED STATE
74
+ * of a check (TODO.sota/20's "the verdict engine evaluates THEIR
75
+ * recorded values"): the ready documents' extracted fields, verbatim.
76
+ * The verdict extraction parses numbers-with-units out of these the
77
+ * same way it parses the question's own phrases. */
78
+ export declare function memberDocFields(store: StoreQuery, sub: string): Promise<{
79
+ doc_id: string;
80
+ name: string;
81
+ fields: Record<string, string>;
82
+ }[]>;
83
+ /** The fields' flat text for the stated-state extraction: one line per
84
+ * field, keyed — numbers-with-units parse from this the same way the
85
+ * question's own phrases do. */
86
+ export declare function fieldsAsText(docs: {
87
+ doc_id: string;
88
+ name: string;
89
+ fields: Record<string, string>;
90
+ }[]): string;
@@ -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