@konneal/engine 0.2.184 → 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.
- package/dist/{ask-7DFXT4DJ.js → ask-5KXF53IL.js} +1 -1
- package/dist/{chunk-ZFOODZWO.js → chunk-JVKJWLI7.js} +35 -8
- package/dist/decisions.d.ts +5 -1
- package/dist/userDocuments.d.ts +18 -0
- package/dist/worker_public/src/index.js +2 -2
- package/package.json +1 -1
- package/workers/worker_public/src/ask.ts +16 -5
- package/workers/worker_public/src/decisionWire.ts +1 -1
- package/workers/worker_public/src/decisions.ts +14 -7
- package/workers/worker_public/src/userDocuments.ts +35 -0
|
@@ -117,6 +117,7 @@ import {
|
|
|
117
117
|
} from "./chunk-3FYJM7LH.js";
|
|
118
118
|
import {
|
|
119
119
|
cfModelRunner,
|
|
120
|
+
cfStore,
|
|
120
121
|
cfVectorIndex,
|
|
121
122
|
portModelRunner,
|
|
122
123
|
portStore
|
|
@@ -1518,7 +1519,7 @@ function matchAnswers(mode, requirements, answers, metBand, refuteBand) {
|
|
|
1518
1519
|
items.push({
|
|
1519
1520
|
text: r.text,
|
|
1520
1521
|
clause: r.clause,
|
|
1521
|
-
band: mode === "check" ? bandFor(probability, metBand, refuteBand) :
|
|
1522
|
+
band: mode === "check" ? bandFor(probability, metBand, refuteBand) : null,
|
|
1522
1523
|
probability: Math.round(probability * 100) / 100
|
|
1523
1524
|
});
|
|
1524
1525
|
});
|
|
@@ -1530,10 +1531,11 @@ function assembleSection(mode, items) {
|
|
|
1530
1531
|
if (!items.length) return "";
|
|
1531
1532
|
const title = mode === "check" ? "Requirements check (automated)" : "Requirements (from the cited clauses)";
|
|
1532
1533
|
const lines = items.map((it) => {
|
|
1533
|
-
const
|
|
1534
|
+
const band = mode === "check" ? it.band : null;
|
|
1535
|
+
const mark = band ? MARK[band] : "\u2022";
|
|
1534
1536
|
const clause = it.clause ? ` \u2014 ${it.clause}` : "";
|
|
1535
|
-
const prob =
|
|
1536
|
-
return `- ${mark} ${it.text}${clause}${prob}${
|
|
1537
|
+
const prob = band ? ` (${Math.round(it.probability * 100)}%)` : "";
|
|
1538
|
+
return `- ${mark} ${it.text}${clause}${prob}${band ? ` \u2014 ${WORD[band]}` : ""}`;
|
|
1537
1539
|
});
|
|
1538
1540
|
return `
|
|
1539
1541
|
|
|
@@ -1629,7 +1631,7 @@ function telemetryDecisions(env, ctx, tier, queryHash, result, durationMs) {
|
|
|
1629
1631
|
try {
|
|
1630
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 });
|
|
1631
1633
|
for (const it of result?.items ?? []) {
|
|
1632
|
-
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, {});
|
|
1633
1635
|
}
|
|
1634
1636
|
} catch {
|
|
1635
1637
|
}
|
|
@@ -1897,6 +1899,25 @@ async function deleteUserDocument(ports, sub, id) {
|
|
|
1897
1899
|
await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
|
|
1898
1900
|
return row;
|
|
1899
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
|
+
}
|
|
1900
1921
|
|
|
1901
1922
|
// workers/worker_public/src/operations.ts
|
|
1902
1923
|
function isOperationIntent(query) {
|
|
@@ -2778,7 +2799,13 @@ ${summary}` }] : [],
|
|
|
2778
2799
|
console.log("model plane: bound", boundModel.node_id, `[${boundModel.standard}]`, boundModel.clause?.urn ?? "no-clause", boundModel.gated ? "(gated: license)" : "");
|
|
2779
2800
|
}
|
|
2780
2801
|
const modelNote = boundModel && !boundModel.gated ? modelGroundingBlock(boundModel) : void 0;
|
|
2781
|
-
|
|
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;
|
|
2782
2809
|
if (machineVerdict === null && boundModel && !boundModel.gated) {
|
|
2783
2810
|
try {
|
|
2784
2811
|
const unitTokens = [...new Set(Object.values(extractParamsWithUnits(q2.query, symbolsIn(extractChecks(boundModel.content))).units).map((u) => u.toLowerCase()))];
|
|
@@ -2811,7 +2838,7 @@ ${summary}` }] : [],
|
|
|
2811
2838
|
if (!machineVerdict && !boundModel && !ablate?.noVerdict && P().publisher.features?.model_plane) {
|
|
2812
2839
|
const ql = q2.query.toLowerCase();
|
|
2813
2840
|
const severityWord = /\b(severity|test|valid|tolerance|condition|within)\b/.test(ql);
|
|
2814
|
-
const stated = quantitiesIn(
|
|
2841
|
+
const stated = quantitiesIn(statedText);
|
|
2815
2842
|
if (severityWord && Object.keys(stated).length >= 1) {
|
|
2816
2843
|
const docNum = modelDocHint?.doc_number;
|
|
2817
2844
|
const rows = await modelNodeRows("condition_set", docNum);
|
|
@@ -3065,7 +3092,7 @@ Answer account questions from these records ONLY: name the record when you use i
|
|
|
3065
3092
|
q2.lang,
|
|
3066
3093
|
keptHistory,
|
|
3067
3094
|
// stage-extracted graph facts (GraphRAG) ride the same note channel
|
|
3068
|
-
[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,
|
|
3069
3096
|
summary,
|
|
3070
3097
|
budget,
|
|
3071
3098
|
ablate?.noCompress !== true
|
package/dist/decisions.d.ts
CHANGED
|
@@ -5,7 +5,11 @@ export interface DerivedRequirement {
|
|
|
5
5
|
export interface DecisionItem {
|
|
6
6
|
text: string;
|
|
7
7
|
clause: string;
|
|
8
|
-
|
|
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";
|
package/dist/userDocuments.d.ts
CHANGED
|
@@ -70,3 +70,21 @@ export declare function queryUserLane(model: ModelRunner, lane: VectorIndex, sub
|
|
|
70
70
|
/** Deletion is immediate and total: the R2 object, the lane vectors,
|
|
71
71
|
* the row. The caller has already checked ownership. */
|
|
72
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;
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
listUserDocuments,
|
|
10
10
|
scoreFaithfulness,
|
|
11
11
|
scoreJudge
|
|
12
|
-
} from "../../chunk-
|
|
12
|
+
} from "../../chunk-JVKJWLI7.js";
|
|
13
13
|
import "../../chunk-IRCDOFP4.js";
|
|
14
14
|
import {
|
|
15
15
|
TOOLS_REGISTRY,
|
|
@@ -1189,7 +1189,7 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
|
|
|
1189
1189
|
const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
|
|
1190
1190
|
payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
|
|
1191
1191
|
} else {
|
|
1192
|
-
const res = name === "ask" ? await (await import("../../ask-
|
|
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);
|
|
1193
1193
|
payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
|
|
1194
1194
|
}
|
|
1195
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 });
|
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.
|
|
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,8 +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
|
+
import { queryUserLane, memberDocFields, fieldsAsText } from "./userDocuments";
|
|
51
|
+
import { cfModelRunner, cfStore, cfVectorIndex } from "./ports/cloudflare/adapters";
|
|
52
52
|
import { TOOL_DECLARATION, parseToolCall, runTool, toolNote } from "./tools";
|
|
53
53
|
import { operationsLane } from "./operations.ts";
|
|
54
54
|
import { extractNameplate, nameplateRegisterQuery } from "./nameplate.ts";
|
|
@@ -1114,7 +1114,18 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
1114
1114
|
// the worker EXECUTES the bound node's machine checks against the
|
|
1115
1115
|
// question's stated values; the model narrates the computed verdict
|
|
1116
1116
|
// and the verdict BLOCK is server-built — data, never generated prose
|
|
1117
|
-
|
|
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;
|
|
1118
1129
|
if (machineVerdict === null && boundModel && !boundModel.gated) {
|
|
1119
1130
|
// unit semantics (TODO.sota/04): the stated values' units reach the
|
|
1120
1131
|
// units register for their dimensions; a comparison mixing
|
|
@@ -1165,7 +1176,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
1165
1176
|
if (!machineVerdict && !boundModel && !ablate?.noVerdict && P().publisher.features?.model_plane) {
|
|
1166
1177
|
const ql = q.query.toLowerCase();
|
|
1167
1178
|
const severityWord = /\b(severity|test|valid|tolerance|condition|within)\b/.test(ql);
|
|
1168
|
-
const stated = quantitiesIn(
|
|
1179
|
+
const stated = quantitiesIn(statedText);
|
|
1169
1180
|
if (severityWord && Object.keys(stated).length >= 1) {
|
|
1170
1181
|
const docNum = modelDocHint?.doc_number;
|
|
1171
1182
|
// the doc number joins the STANDARD id (iec-60068-2-78), which is
|
|
@@ -1543,7 +1554,7 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
1543
1554
|
q.lang,
|
|
1544
1555
|
keptHistory,
|
|
1545
1556
|
// stage-extracted graph facts (GraphRAG) ride the same note channel
|
|
1546
|
-
[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,
|
|
1547
1558
|
summary,
|
|
1548
1559
|
budget,
|
|
1549
1560
|
ablate?.noCompress !== true,
|
|
@@ -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
|
-
|
|
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) :
|
|
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
|
-
|
|
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 =
|
|
145
|
-
return `- ${mark} ${it.text}${clause}${prob}${
|
|
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
|
}
|
|
@@ -327,3 +327,38 @@ export async function deleteUserDocument(ports: UserDocumentPorts, sub: string,
|
|
|
327
327
|
await ports.store.prepare("DELETE FROM user_documents WHERE id = ?1 AND owner_sub = ?2").bind(id, sub).run();
|
|
328
328
|
return row;
|
|
329
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
|
+
}
|