@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.
@@ -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-JVKJWLI7.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-5KXF53IL.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.185",
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, memberDocFields, fieldsAsText } from "./userDocuments";
51
+ import { cfModelRunner, cfStore, 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;
@@ -1105,7 +1114,18 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1105
1114
  // the worker EXECUTES the bound node's machine checks against the
1106
1115
  // question's stated values; the model narrates the computed verdict
1107
1116
  // and the verdict BLOCK is server-built — data, never generated prose
1108
- let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? machineEvaluate(boundModel.content, q.query) : null;
1117
+ // The member's own imported values are the STATED STATE for their
1118
+ // checks (TODO.sota/20: "compare my recorded errors against R 60
1119
+ // Table 4"): fetched directly (the verdict paths precede retrieval),
1120
+ // composed once, and fed to BOTH the machine evaluation and the note
1121
+ // channel. Member-gated, ready documents only.
1122
+ const memberDocs = member && !ablate?.noVerdict ? await memberDocFields(cfStore(env.DB), member.sub).catch(() => []) : [];
1123
+ const memberFieldsText = memberDocs.length ? fieldsAsText(memberDocs) : "";
1124
+ const statedText = memberFieldsText ? `${q.query}\n${memberFieldsText}` : q.query;
1125
+ const memberDocNote = memberDocs.length
1126
+ ? `MEMBER DOCUMENT DATA — 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:\n${memberFieldsText}`
1127
+ : undefined;
1128
+ let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? machineEvaluate(boundModel.content, statedText) : null;
1109
1129
  if (machineVerdict === null && boundModel && !boundModel.gated) {
1110
1130
  // unit semantics (TODO.sota/04): the stated values' units reach the
1111
1131
  // units register for their dimensions; a comparison mixing
@@ -1156,7 +1176,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1156
1176
  if (!machineVerdict && !boundModel && !ablate?.noVerdict && P().publisher.features?.model_plane) {
1157
1177
  const ql = q.query.toLowerCase();
1158
1178
  const severityWord = /\b(severity|test|valid|tolerance|condition|within)\b/.test(ql);
1159
- const stated = quantitiesIn(q.query);
1179
+ const stated = quantitiesIn(statedText);
1160
1180
  if (severityWord && Object.keys(stated).length >= 1) {
1161
1181
  const docNum = modelDocHint?.doc_number;
1162
1182
  // the doc number joins the STANDARD id (iec-60068-2-78), which is
@@ -1380,7 +1400,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1380
1400
  // top-N before a post-hoc seal ever sees one. A document named IN THE
1381
1401
  // QUESTION keeps the soft steer by design (the widen covers sparse
1382
1402
  // publications there).
1383
- retrieved = await retrieve(env, q.query, { prev, understanding, federate, warmEmbed, graphDocNumbers,
1403
+ retrieved = await retrieve(env, q.query, { prev, understanding, federate, userDocs, warmEmbed, graphDocNumbers,
1384
1404
  sealScope: declaredScoped ? docScope : null, optimisticHits, optimisticVec,
1385
1405
  datasetScope: narrowed ? corpora : null, standardKeys, lexicalBoost, licensedDocNumbers,
1386
1406
  ...(routeSubset ? { stageSubset: routeSubset } : {}) });
@@ -1418,7 +1438,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1418
1438
  if (grade === "weak" && understanding?.docidentifier) {
1419
1439
  const broaden = `${understanding.standalone_query || q.query} ${understanding.docidentifier}`.trim();
1420
1440
  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 } : {}) });
1441
+ 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
1442
  const grade2 = await gradeRetrieval(env.AI, roleModel(env, "grader"), q.query, second.hits.map((h: Hit) => h.text));
1423
1443
  stageTiming.corrective = Date.now() - tc;
1424
1444
  if (grade2 === "good") retrieved = second; // corrective retry must be strictly better
@@ -1534,7 +1554,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
1534
1554
  q.lang,
1535
1555
  keptHistory,
1536
1556
  // stage-extracted graph facts (GraphRAG) ride the same note channel
1537
- [ops.note, processNote, eNote, regNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...(retrieved.notes ?? [])].filter(Boolean).join("\n") || undefined,
1557
+ [ops.note, processNote, eNote, regNote, memberDocNote, contextNote(declaredCtx, docScope), accountNote, modelNote, vocabNote, memNote, machineNote, conditionNote, aggregationNote, boundaryNote, licenseNote, ...(retrieved.notes ?? [])].filter(Boolean).join("\n") || undefined,
1538
1558
  summary,
1539
1559
  budget,
1540
1560
  ablate?.noCompress !== true,
@@ -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 —
@@ -147,7 +147,7 @@ export function telemetryDecisions(
147
147
  try {
148
148
  telemetry(env, ctx, tier, "ask-decisions", result ? result.gate.toFixed(2) : "0", !!result, result?.items.length ?? 0, queryHash, result?.mode ?? undefined, undefined, { durationMs });
149
149
  for (const it of result?.items ?? []) {
150
- telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band, undefined, {});
150
+ telemetry(env, ctx, tier, "ask-decision", it.probability.toFixed(2), it.band === "met", 1, queryHash, it.band ?? undefined, undefined, {});
151
151
  }
152
152
  } catch { /* telemetry never answers for the answer */ }
153
153
  }
@@ -13,7 +13,11 @@ export interface DerivedRequirement {
13
13
  export interface DecisionItem {
14
14
  text: string;
15
15
  clause: string;
16
- band: "met" | "not-met" | "unclear";
16
+ /** null in LIST mode: a requirements inventory makes no conformance
17
+ * claim, so met/not-met/unclear would all lie (the calibration
18
+ * reader's first week caught the hardcoded "met" this replaces —
19
+ * 2026-11-05, TODO.decisions/03). */
20
+ band: "met" | "not-met" | "unclear" | null;
17
21
  probability: number;
18
22
  }
19
23
 
@@ -123,15 +127,15 @@ export function matchAnswers(
123
127
  items.push({
124
128
  text: r.text,
125
129
  clause: r.clause,
126
- band: mode === "check" ? bandFor(probability, metBand, refuteBand) : "met",
130
+ band: mode === "check" ? bandFor(probability, metBand, refuteBand) : null,
127
131
  probability: Math.round(probability * 100) / 100,
128
132
  });
129
133
  });
130
134
  return items;
131
135
  }
132
136
 
133
- const MARK: Record<DecisionItem["band"], string> = { met: "✓", "not-met": "✗", unclear: "?" };
134
- const WORD: Record<DecisionItem["band"], string> = { met: "met", "not-met": "not met", unclear: "not clearly stated" };
137
+ const MARK: Record<Exclude<DecisionItem["band"], null>, string> = { met: "✓", "not-met": "✗", unclear: "?" };
138
+ const WORD: Record<Exclude<DecisionItem["band"], null>, string> = { met: "met", "not-met": "not met", unclear: "not clearly stated" };
135
139
 
136
140
  /** The deterministic checklist section appended to the answer. The
137
141
  * model never writes this — the server composes it from the decisions. */
@@ -139,10 +143,13 @@ export function assembleSection(mode: DecisionMode, items: DecisionItem[]): stri
139
143
  if (!items.length) return "";
140
144
  const title = mode === "check" ? "Requirements check (automated)" : "Requirements (from the cited clauses)";
141
145
  const lines = items.map((it) => {
142
- const mark = mode === "check" ? MARK[it.band] : "•";
146
+ // check mode guarantees a band (bandFor ran); list mode renders no
147
+ // mark, probability, or word at all
148
+ const band = mode === "check" ? it.band : null;
149
+ const mark = band ? MARK[band] : "•";
143
150
  const clause = it.clause ? ` — ${it.clause}` : "";
144
- const prob = mode === "check" ? ` (${Math.round(it.probability * 100)}%)` : "";
145
- return `- ${mark} ${it.text}${clause}${prob}${mode === "check" ? ` — ${WORD[it.band]}` : ""}`;
151
+ const prob = band ? ` (${Math.round(it.probability * 100)}%)` : "";
152
+ return `- ${mark} ${it.text}${clause}${prob}${band ? ` — ${WORD[band]}` : ""}`;
146
153
  });
147
154
  return `\n\n${title}:\n${lines.join("\n")}`;
148
155
  }
@@ -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> {
@@ -292,3 +327,38 @@ export async function deleteUserDocument(ports: UserDocumentPorts, sub: string,
292
327
  await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
293
328
  return row;
294
329
  }
330
+
331
+ /** The member's own recorded values, ready to serve as the STATED STATE
332
+ * of a check (TODO.sota/20's "the verdict engine evaluates THEIR
333
+ * recorded values"): the ready documents' extracted fields, verbatim.
334
+ * The verdict extraction parses numbers-with-units out of these the
335
+ * same way it parses the question's own phrases. */
336
+ export async function memberDocFields(store: StoreQuery, sub: string): Promise<{ doc_id: string; name: string; fields: Record<string, string> }[]> {
337
+ const res = await store
338
+ .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")
339
+ .bind(sub)
340
+ .all();
341
+ const out: { doc_id: string; name: string; fields: Record<string, string> }[] = [];
342
+ for (const r of (res.results ?? []) as unknown as { id: string; name: string; fields: string }[]) {
343
+ try {
344
+ const parsed = JSON.parse(r.fields) as Record<string, unknown>;
345
+ const fields: Record<string, string> = {};
346
+ for (const [k, v] of Object.entries(parsed)) {
347
+ if (typeof v === "string" || typeof v === "number") fields[k] = String(v);
348
+ }
349
+ if (Object.keys(fields).length) out.push({ doc_id: r.id, name: r.name, fields });
350
+ } catch {
351
+ // a fields blob that fails to parse contributes nothing
352
+ }
353
+ }
354
+ return out;
355
+ }
356
+
357
+ /** The fields' flat text for the stated-state extraction: one line per
358
+ * field, keyed — numbers-with-units parse from this the same way the
359
+ * question's own phrases do. */
360
+ export function fieldsAsText(docs: { doc_id: string; name: string; fields: Record<string, string> }[]): string {
361
+ return docs
362
+ .map((d) => Object.entries(d.fields).map(([k, v]) => `${k.replace(/_/g, " ")}: ${v}`).join("; "))
363
+ .join("\n");
364
+ }
@@ -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
- };