@konneal/engine 0.2.118 → 0.2.120
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/admin.d.ts +8 -0
- package/dist/{ask-ZZT67FEB.js → ask-3BJKTVLY.js} +3 -3
- package/dist/{chunk-YNQ5BKQW.js → chunk-C5L55VI7.js} +1 -1
- package/dist/{chunk-32UDKBA2.js → chunk-FKG5VGOL.js} +44 -13
- package/dist/{chunk-NUHZMAII.js → chunk-IIQWESHC.js} +8 -1
- package/dist/{chunk-UBQCQ4UQ.js → chunk-SORXE55V.js} +21 -3
- package/dist/openapi-surface.gen.d.ts +1 -1
- package/dist/openapi-types.d.ts +91 -0
- package/dist/prompts/family-summary.md +1 -0
- package/dist/{search-3PBQSMO4.js → search-JDSQPI3A.js} +2 -2
- package/dist/{tools-GSLHFD37.js → tools-CUKFOW7S.js} +1 -1
- package/dist/verdict.d.ts +19 -1
- package/dist/worker_public/src/index.js +67 -6
- package/package.json +1 -1
- package/workers/worker_public/openapi.yaml +50 -0
- package/workers/worker_public/prompts/family-summary.md +1 -0
- package/workers/worker_public/src/admin.ts +50 -0
- package/workers/worker_public/src/ask.ts +24 -2
- package/workers/worker_public/src/graph.ts +14 -1
- package/workers/worker_public/src/index.ts +3 -1
- package/workers/worker_public/src/openapi-surface.gen.ts +12 -0
- package/workers/worker_public/src/verdict.ts +68 -10
package/dist/admin.d.ts
CHANGED
|
@@ -13,6 +13,14 @@ export declare function handleEnrich(env: Env, ctx: ExecutionContext, req: Reque
|
|
|
13
13
|
* descends from it to quotable leaf clauses (pipeline.ts section
|
|
14
14
|
* descent). Credential, batching and ledger mirror /admin/enrich. */
|
|
15
15
|
export declare function handleSectionUnit(env: Env, ctx: ExecutionContext, req: Request): Promise<Response>;
|
|
16
|
+
/** Family community summaries (TODO.sota/06 item 2): one precomputed
|
|
17
|
+
* answer per publication family to "what is this family and what
|
|
18
|
+
* changed between editions" — generated from the registry rows and
|
|
19
|
+
* the successor graph (the family IS the corpus's natural community),
|
|
20
|
+
* stored in KV under famsum:<family>, served by editionNote beside
|
|
21
|
+
* the deterministic registry line. Admin-gated; idempotent (force
|
|
22
|
+
* regenerates); the quality-first lane pays once. */
|
|
23
|
+
export declare function handleFamilySummary(env: Env, req: Request): Promise<Response>;
|
|
16
24
|
/** Ops access to the Vectorize binding (get/upsert by id) for offline
|
|
17
25
|
* passes like embedding smoothing (G-ETSI-4) — the binding is the
|
|
18
26
|
* credential, admin-token gated exactly like /admin/enrich. */
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
handleAsk
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import "./chunk-
|
|
5
|
-
import "./chunk-
|
|
3
|
+
} from "./chunk-SORXE55V.js";
|
|
4
|
+
import "./chunk-FKG5VGOL.js";
|
|
5
|
+
import "./chunk-IIQWESHC.js";
|
|
6
6
|
import "./chunk-TH5XGPD5.js";
|
|
7
7
|
import "./chunk-DJ65EF5G.js";
|
|
8
8
|
import "./chunk-A3QHHUN5.js";
|
|
@@ -268,27 +268,47 @@ function parseNumber(raw) {
|
|
|
268
268
|
s = s.replace(/\.(\d{3})$/, "$1");
|
|
269
269
|
return Number(s.replace(/,(?=\d{3}\b)/g, ""));
|
|
270
270
|
}
|
|
271
|
-
function
|
|
272
|
-
const
|
|
271
|
+
function extractParamsWithUnits(query, symbols) {
|
|
272
|
+
const values = {};
|
|
273
|
+
const units = {};
|
|
273
274
|
for (const sym of symbols) {
|
|
274
275
|
const leaf = sym.split(".").pop() ?? sym;
|
|
275
276
|
const esc = leaf.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
276
|
-
const re = new RegExp(`\\b${esc}\\b\\D{0,14}?([0-9][0-9 ,.]*[0-9])
|
|
277
|
+
const re = new RegExp(`\\b${esc}\\b\\D{0,14}?([0-9][0-9 ,.]*[0-9])\\s*(%|\\u00b0?[A-Za-z\\u00b5\\u03a9]{0,6})?`, "iu");
|
|
277
278
|
const m = query.match(re);
|
|
278
279
|
if (m) {
|
|
279
280
|
const v = parseNumber(m[1]);
|
|
280
|
-
if (Number.isFinite(v))
|
|
281
|
+
if (Number.isFinite(v)) {
|
|
282
|
+
values[sym] = v;
|
|
283
|
+
const u = (m[2] ?? "").trim();
|
|
284
|
+
if (u) units[sym] = u;
|
|
285
|
+
}
|
|
281
286
|
}
|
|
282
287
|
}
|
|
283
|
-
return
|
|
288
|
+
return { values, units };
|
|
289
|
+
}
|
|
290
|
+
function dimensionMismatch(check, units, dimensions) {
|
|
291
|
+
const dims = /* @__PURE__ */ new Map();
|
|
292
|
+
for (const [sym, unit] of Object.entries(units)) {
|
|
293
|
+
const leaf = sym.split(".").pop();
|
|
294
|
+
if (!leaf || !new RegExp(`\\b${leaf}\\b`, "i").test(check)) continue;
|
|
295
|
+
const dim = dimensions[unit.toLowerCase()];
|
|
296
|
+
if (dim) dims.set(sym, dim);
|
|
297
|
+
}
|
|
298
|
+
const distinct = [...new Set(dims.values())];
|
|
299
|
+
if (distinct.length <= 1) return null;
|
|
300
|
+
const parts = [...dims.entries()].map(([sym, dim]) => `${sym} is in ${dim}`);
|
|
301
|
+
return `the stated quantities mix dimensions: ${parts.join(" while ")}`;
|
|
284
302
|
}
|
|
285
|
-
function evaluate(content, query) {
|
|
303
|
+
function evaluate(content, query, opts) {
|
|
286
304
|
const c = content && typeof content === "object" ? content : {};
|
|
287
305
|
const checks = extractChecks(content);
|
|
288
306
|
if (!checks.length) return null;
|
|
289
307
|
const symbols = symbolsIn(checks);
|
|
290
|
-
const
|
|
308
|
+
const bound = extractParamsWithUnits(query, symbols);
|
|
309
|
+
const params = bound.values;
|
|
291
310
|
const missing = symbols.filter((s) => params[s] === void 0);
|
|
311
|
+
let voidReason = null;
|
|
292
312
|
const machine = checks.map((expression) => {
|
|
293
313
|
const values = {};
|
|
294
314
|
try {
|
|
@@ -297,10 +317,15 @@ function evaluate(content, query) {
|
|
|
297
317
|
}
|
|
298
318
|
let result = null;
|
|
299
319
|
if (missing.length === 0) {
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
320
|
+
const mismatch = opts?.dimensions ? dimensionMismatch(expression, bound.units, opts.dimensions) : null;
|
|
321
|
+
if (mismatch) {
|
|
322
|
+
voidReason = voidReason ?? mismatch;
|
|
323
|
+
} else {
|
|
324
|
+
try {
|
|
325
|
+
result = !!parseAndEval(expression, params);
|
|
326
|
+
} catch {
|
|
327
|
+
result = null;
|
|
328
|
+
}
|
|
304
329
|
}
|
|
305
330
|
}
|
|
306
331
|
return { expression, symbolic: expression, values, result };
|
|
@@ -310,7 +335,10 @@ function evaluate(content, query) {
|
|
|
310
335
|
}
|
|
311
336
|
const failed = machine.some((m) => m.result === false);
|
|
312
337
|
const evaluable = machine.some((m) => m.result !== null);
|
|
313
|
-
if (!evaluable)
|
|
338
|
+
if (!evaluable) {
|
|
339
|
+
if (voidReason) return { verdict: "void", missing: [], void_reason: voidReason, checks: machine };
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
314
342
|
return {
|
|
315
343
|
verdict: failed ? "fail" : "pass",
|
|
316
344
|
on_violation: failed ? String(c.on_violation ?? "invalid") : void 0,
|
|
@@ -328,7 +356,7 @@ function verdictNote(v, node) {
|
|
|
328
356
|
lines.push(`- ${c.expression}${vals ? ` [${vals}]` : ""} \u2192 ${c.result === null ? "not evaluated" : c.result ? "holds" : "VIOLATED"}`);
|
|
329
357
|
}
|
|
330
358
|
if (v.verdict === "void") {
|
|
331
|
-
lines.push(`VERDICT: VOID \u2014 the question does not state: ${v.missing.join(", ")}. Say exactly what is missing; never assume values.`);
|
|
359
|
+
lines.push(v.void_reason ? `VERDICT: VOID \u2014 ${v.void_reason}. State the mismatch plainly; the question cannot be decided as stated.` : `VERDICT: VOID \u2014 the question does not state: ${v.missing.join(", ")}. Say exactly what is missing; never assume values.`);
|
|
332
360
|
} else if (v.verdict === "pass") {
|
|
333
361
|
lines.push(`VERDICT: PASS \u2014 every machine check holds at the stated values. Present this verdict, the arithmetic above, and cite the node's clause.`);
|
|
334
362
|
} else {
|
|
@@ -1179,6 +1207,9 @@ ${r.output}`;
|
|
|
1179
1207
|
}
|
|
1180
1208
|
|
|
1181
1209
|
export {
|
|
1210
|
+
extractChecks,
|
|
1211
|
+
symbolsIn,
|
|
1212
|
+
extractParamsWithUnits,
|
|
1182
1213
|
evaluate,
|
|
1183
1214
|
verdictNote,
|
|
1184
1215
|
standardForDocNumber,
|
|
@@ -24756,7 +24756,14 @@ async function editionNote(env, u) {
|
|
|
24756
24756
|
).bind(`% ${u.doc_number}:%`).all();
|
|
24757
24757
|
const actives = (rows.results ?? []).map((r) => r.docidentifier);
|
|
24758
24758
|
if (!actives.length) return void 0;
|
|
24759
|
-
|
|
24759
|
+
const famRow = await env.DB.prepare("SELECT family FROM documents WHERE docidentifier LIKE ?1 || '%:%' LIMIT 1").bind(`% ${u.doc_number}:%`).first().catch(() => null);
|
|
24760
|
+
let summary = "";
|
|
24761
|
+
if (famRow?.family && env.CACHE) {
|
|
24762
|
+
summary = await env.CACHE.get(`famsum:${famRow.family}`).catch(() => "") ?? "";
|
|
24763
|
+
}
|
|
24764
|
+
const registry = `Publication registry (authoritative): the ACTIVE edition(s) for this publication are ${actives.join(", ")}. Passages from other editions are superseded \u2014 use them only for historical comparison and say so.`;
|
|
24765
|
+
return summary ? `${registry}
|
|
24766
|
+
Family summary (precomputed from the registry and the successor graph): ${summary}` : registry;
|
|
24760
24767
|
} catch {
|
|
24761
24768
|
return void 0;
|
|
24762
24769
|
}
|
|
@@ -5,6 +5,8 @@ import {
|
|
|
5
5
|
contractV2,
|
|
6
6
|
evaluate,
|
|
7
7
|
evaluateConditionSets,
|
|
8
|
+
extractChecks,
|
|
9
|
+
extractParamsWithUnits,
|
|
8
10
|
licenseBoundaryNote,
|
|
9
11
|
licenseBoundaryRefusal,
|
|
10
12
|
licensedEntryForPackage,
|
|
@@ -16,10 +18,11 @@ import {
|
|
|
16
18
|
resolveBlocks,
|
|
17
19
|
runTool,
|
|
18
20
|
standardForDocNumber,
|
|
21
|
+
symbolsIn,
|
|
19
22
|
tableRetyped,
|
|
20
23
|
toolNote,
|
|
21
24
|
verdictNote
|
|
22
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-FKG5VGOL.js";
|
|
23
26
|
import {
|
|
24
27
|
NO_CONTEXT,
|
|
25
28
|
STAGE_NAMES,
|
|
@@ -60,7 +63,7 @@ import {
|
|
|
60
63
|
tokenBudget,
|
|
61
64
|
understandQuery,
|
|
62
65
|
usageTotal
|
|
63
|
-
} from "./chunk-
|
|
66
|
+
} from "./chunk-IIQWESHC.js";
|
|
64
67
|
import {
|
|
65
68
|
embed,
|
|
66
69
|
generateOnce,
|
|
@@ -2195,7 +2198,22 @@ ${summary}` }] : [],
|
|
|
2195
2198
|
console.log("model plane: bound", boundModel.node_id, `[${boundModel.standard}]`, boundModel.clause?.urn ?? "no-clause", boundModel.gated ? "(gated: license)" : "");
|
|
2196
2199
|
}
|
|
2197
2200
|
const modelNote = boundModel && !boundModel.gated ? modelGroundingBlock(boundModel) : void 0;
|
|
2198
|
-
|
|
2201
|
+
let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? evaluate(boundModel.content, q.query) : null;
|
|
2202
|
+
if (machineVerdict === null && boundModel && !boundModel.gated) {
|
|
2203
|
+
try {
|
|
2204
|
+
const unitTokens = [...new Set(Object.values(extractParamsWithUnits(q.query, symbolsIn(extractChecks(boundModel.content))).units).map((u) => u.toLowerCase()))];
|
|
2205
|
+
if (unitTokens.length) {
|
|
2206
|
+
const marks = unitTokens.map(() => "?").join(",");
|
|
2207
|
+
const rows = await env.DB.prepare(
|
|
2208
|
+
`SELECT lower(coalesce(json_extract(symbols, '$.ascii'), json_extract(symbols, '$.unicode'))) AS sym, dimension_ascii FROM units_db WHERE lower(coalesce(json_extract(symbols, '$.ascii'), json_extract(symbols, '$.unicode'))) IN (${marks})`
|
|
2209
|
+
).bind(...unitTokens).all().catch(() => ({ results: [] }));
|
|
2210
|
+
const dimensions = {};
|
|
2211
|
+
for (const r of rows.results ?? []) dimensions[String(r.sym)] = String(r.dimension_ascii ?? "");
|
|
2212
|
+
machineVerdict = evaluate(boundModel.content, q.query, { dimensions });
|
|
2213
|
+
}
|
|
2214
|
+
} catch {
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2199
2217
|
const machineNote = machineVerdict && boundModel ? verdictNote(machineVerdict, boundModel) : void 0;
|
|
2200
2218
|
const modelNodeRows = async (kind, docNum) => {
|
|
2201
2219
|
const attempt = (num3) => {
|
|
@@ -3,7 +3,7 @@ export interface OpenApiRoute {
|
|
|
3
3
|
pattern: string;
|
|
4
4
|
operationId: string;
|
|
5
5
|
}
|
|
6
|
-
export type OpenApiOperationId = "askAnonymous" | "askKeyed" | "search" | "searchKeyed" | "verify" | "verifyKeyed" | "research" | "researchKeyed" | "mcp" | "datasets" | "keyUsage" | "health" | "listConversations" | "createConversation" | "getConversation" | "renameConversation" | "deleteConversation" | "appendMessage" | "shareConversation" | "getShared" | "uploadAttachment" | "listAttachments" | "getAttachment" | "deleteAttachment" | "listMemories" | "createMemory" | "deleteMemory" | "listProjects" | "createProject" | "deleteProject" | "listProjectFiles" | "attachProjectFile" | "detachProjectFile" | "laneQuery" | "laneKeyed" | "feedback" | "adminEnrich" | "adminEnrichAlias" | "adminSection" | "adminSectionAlias" | "adminVectors" | "adminCaption" | "adminJudge" | "adminJudgeAlias" | "adminRevokeKey" | "authMe" | "authLogin" | "authCallback" | "authLogout" | "authLogoutLink" | "adminStats" | "adminListKeys" | "adminCreateKey";
|
|
6
|
+
export type OpenApiOperationId = "askAnonymous" | "askKeyed" | "search" | "searchKeyed" | "verify" | "verifyKeyed" | "research" | "researchKeyed" | "mcp" | "datasets" | "keyUsage" | "health" | "listConversations" | "createConversation" | "getConversation" | "renameConversation" | "deleteConversation" | "appendMessage" | "shareConversation" | "getShared" | "uploadAttachment" | "listAttachments" | "getAttachment" | "deleteAttachment" | "listMemories" | "createMemory" | "deleteMemory" | "listProjects" | "createProject" | "deleteProject" | "listProjectFiles" | "attachProjectFile" | "detachProjectFile" | "laneQuery" | "laneKeyed" | "feedback" | "adminEnrich" | "adminEnrichAlias" | "adminSection" | "adminFamilySummary" | "adminSectionAlias" | "adminFamilySummaryAlias" | "adminVectors" | "adminCaption" | "adminJudge" | "adminJudgeAlias" | "adminRevokeKey" | "authMe" | "authLogin" | "authCallback" | "authLogout" | "authLogoutLink" | "adminStats" | "adminListKeys" | "adminCreateKey";
|
|
7
7
|
export declare const OPENAPI_SURFACE: readonly (Omit<OpenApiRoute, "operationId"> & {
|
|
8
8
|
operationId: OpenApiOperationId;
|
|
9
9
|
})[];
|
package/dist/openapi-types.d.ts
CHANGED
|
@@ -613,6 +613,26 @@ export interface paths {
|
|
|
613
613
|
patch?: never;
|
|
614
614
|
trace?: never;
|
|
615
615
|
};
|
|
616
|
+
"/v1/admin/family-summary": {
|
|
617
|
+
parameters: {
|
|
618
|
+
query?: never;
|
|
619
|
+
header?: never;
|
|
620
|
+
path?: never;
|
|
621
|
+
cookie?: never;
|
|
622
|
+
};
|
|
623
|
+
get?: never;
|
|
624
|
+
put?: never;
|
|
625
|
+
/**
|
|
626
|
+
* Write a family's community summary
|
|
627
|
+
* @description Generates the precomputed answer to "what is this family and what changed between editions" from the registry rows and the successor graph, and stores it in KV; editionNote serves it beside the deterministic registry line on doc-scoped answers. Families need at least two editions. force regenerates.
|
|
628
|
+
*/
|
|
629
|
+
post: operations["adminFamilySummary"];
|
|
630
|
+
delete?: never;
|
|
631
|
+
options?: never;
|
|
632
|
+
head?: never;
|
|
633
|
+
patch?: never;
|
|
634
|
+
trace?: never;
|
|
635
|
+
};
|
|
616
636
|
"/admin/section": {
|
|
617
637
|
parameters: {
|
|
618
638
|
query?: never;
|
|
@@ -633,6 +653,26 @@ export interface paths {
|
|
|
633
653
|
patch?: never;
|
|
634
654
|
trace?: never;
|
|
635
655
|
};
|
|
656
|
+
"/admin/family-summary": {
|
|
657
|
+
parameters: {
|
|
658
|
+
query?: never;
|
|
659
|
+
header?: never;
|
|
660
|
+
path?: never;
|
|
661
|
+
cookie?: never;
|
|
662
|
+
};
|
|
663
|
+
get?: never;
|
|
664
|
+
put?: never;
|
|
665
|
+
/**
|
|
666
|
+
* Write a family's community summary (the operational path)
|
|
667
|
+
* @description The operational alias of /v1/admin/family-summary; the behaviour and the credential are identical.
|
|
668
|
+
*/
|
|
669
|
+
post: operations["adminFamilySummaryAlias"];
|
|
670
|
+
delete?: never;
|
|
671
|
+
options?: never;
|
|
672
|
+
head?: never;
|
|
673
|
+
patch?: never;
|
|
674
|
+
trace?: never;
|
|
675
|
+
};
|
|
636
676
|
"/admin/vectors": {
|
|
637
677
|
parameters: {
|
|
638
678
|
query?: never;
|
|
@@ -1932,6 +1972,33 @@ export interface operations {
|
|
|
1932
1972
|
};
|
|
1933
1973
|
};
|
|
1934
1974
|
};
|
|
1975
|
+
adminFamilySummary: {
|
|
1976
|
+
parameters: {
|
|
1977
|
+
query?: never;
|
|
1978
|
+
header?: never;
|
|
1979
|
+
path?: never;
|
|
1980
|
+
cookie?: never;
|
|
1981
|
+
};
|
|
1982
|
+
requestBody: {
|
|
1983
|
+
content: {
|
|
1984
|
+
"application/json": {
|
|
1985
|
+
/** @description The family key, for example R-60. */
|
|
1986
|
+
family: string;
|
|
1987
|
+
/** @default false */
|
|
1988
|
+
force?: boolean;
|
|
1989
|
+
};
|
|
1990
|
+
};
|
|
1991
|
+
};
|
|
1992
|
+
responses: {
|
|
1993
|
+
/** @description The stored summary with its provenance counts. */
|
|
1994
|
+
200: {
|
|
1995
|
+
headers: {
|
|
1996
|
+
[name: string]: unknown;
|
|
1997
|
+
};
|
|
1998
|
+
content?: never;
|
|
1999
|
+
};
|
|
2000
|
+
};
|
|
2001
|
+
};
|
|
1935
2002
|
adminSectionAlias: {
|
|
1936
2003
|
parameters: {
|
|
1937
2004
|
query?: never;
|
|
@@ -1956,6 +2023,30 @@ export interface operations {
|
|
|
1956
2023
|
};
|
|
1957
2024
|
};
|
|
1958
2025
|
};
|
|
2026
|
+
adminFamilySummaryAlias: {
|
|
2027
|
+
parameters: {
|
|
2028
|
+
query?: never;
|
|
2029
|
+
header?: never;
|
|
2030
|
+
path?: never;
|
|
2031
|
+
cookie?: never;
|
|
2032
|
+
};
|
|
2033
|
+
requestBody: {
|
|
2034
|
+
content: {
|
|
2035
|
+
"application/json": {
|
|
2036
|
+
family: string;
|
|
2037
|
+
};
|
|
2038
|
+
};
|
|
2039
|
+
};
|
|
2040
|
+
responses: {
|
|
2041
|
+
/** @description The stored summary. */
|
|
2042
|
+
200: {
|
|
2043
|
+
headers: {
|
|
2044
|
+
[name: string]: unknown;
|
|
2045
|
+
};
|
|
2046
|
+
content?: never;
|
|
2047
|
+
};
|
|
2048
|
+
};
|
|
2049
|
+
};
|
|
1959
2050
|
adminVectors: {
|
|
1960
2051
|
parameters: {
|
|
1961
2052
|
query?: never;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
You write the community summary of one publication family for {{PUBLISHER_NAME}}'s retrieval index — the precomputed answer to "what is this family and what changed between editions". The registry rows and the successor graph below are your ONLY facts. Write three to five sentences: what the family regulates or provides, its structure (parts, annexes), and the edition lineage — which editions are active, which are superseded, and what the successor chain says changed. Never invent a change the lineage does not show; when the chain only says one edition replaced another, say exactly that. Name editions exactly as the registry does. No preamble.
|
package/dist/verdict.d.ts
CHANGED
|
@@ -9,12 +9,30 @@ export interface Verdict {
|
|
|
9
9
|
on_violation?: string;
|
|
10
10
|
violation_meaning?: string;
|
|
11
11
|
missing: string[];
|
|
12
|
+
/** why a fully-stated question still cannot evaluate (TODO.sota/04):
|
|
13
|
+
* the stated quantities' units carry conflicting dimensions */
|
|
14
|
+
void_reason?: string;
|
|
12
15
|
checks: MachineCheck[];
|
|
13
16
|
}
|
|
14
17
|
export declare function extractChecks(content: unknown): string[];
|
|
15
18
|
export declare function symbolsIn(checks: string[]): string[];
|
|
16
19
|
export declare function extractParams(query: string, symbols: string[]): Record<string, number>;
|
|
17
|
-
|
|
20
|
+
/** The stated values WITH their unit tokens (TODO.sota/04's unit
|
|
21
|
+
* semantics): "E_max 30000 v" binds e_max=30000 and the unit "v" —
|
|
22
|
+
* the dimension check needs both. */
|
|
23
|
+
export declare function extractParamsWithUnits(query: string, symbols: string[]): {
|
|
24
|
+
values: Record<string, number>;
|
|
25
|
+
units: Record<string, string>;
|
|
26
|
+
};
|
|
27
|
+
/** Dimension coherence (TODO.sota/04 item 2): the units plane gives
|
|
28
|
+
* each unit token a dimension; a parameter set whose bound symbols
|
|
29
|
+
* carry CONFLICTING known dimensions is incoherent — the check
|
|
30
|
+
* compares quantities that are not comparable. Pure: the dimensions
|
|
31
|
+
* map arrives from the caller (the units register at load). */
|
|
32
|
+
export declare function dimensionMismatch(check: string, units: Record<string, string>, dimensions: Record<string, string>): string | null;
|
|
33
|
+
export declare function evaluate(content: unknown, query: string, opts?: {
|
|
34
|
+
dimensions?: Record<string, string>;
|
|
35
|
+
}): Verdict | null;
|
|
18
36
|
/** The deterministic note the answer model narrates — never recomputes. */
|
|
19
37
|
export declare function verdictNote(v: Verdict, node: {
|
|
20
38
|
node_id: string;
|
|
@@ -4,15 +4,15 @@ import {
|
|
|
4
4
|
handleMemories,
|
|
5
5
|
scoreFaithfulness,
|
|
6
6
|
scoreJudge
|
|
7
|
-
} from "../../chunk-
|
|
7
|
+
} from "../../chunk-SORXE55V.js";
|
|
8
8
|
import {
|
|
9
9
|
TOOLS_REGISTRY,
|
|
10
10
|
bindModelNode,
|
|
11
11
|
modelGroundingBlock
|
|
12
|
-
} from "../../chunk-
|
|
12
|
+
} from "../../chunk-FKG5VGOL.js";
|
|
13
13
|
import {
|
|
14
14
|
handleSearch
|
|
15
|
-
} from "../../chunk-
|
|
15
|
+
} from "../../chunk-C5L55VI7.js";
|
|
16
16
|
import {
|
|
17
17
|
buildMessages,
|
|
18
18
|
citations,
|
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
sessionFrom,
|
|
35
35
|
telemetry,
|
|
36
36
|
understandQuery
|
|
37
|
-
} from "../../chunk-
|
|
37
|
+
} from "../../chunk-IIQWESHC.js";
|
|
38
38
|
import {
|
|
39
39
|
cfBlobs,
|
|
40
40
|
embed,
|
|
@@ -350,6 +350,10 @@ var enrichment_default = "You write a retrieval context for a passage from {{COR
|
|
|
350
350
|
// workers/worker_public/prompts/doc-summary.md
|
|
351
351
|
var doc_summary_default = "You write the document-level summary for a legal-metrology publication in {{PUBLISHER_NAME}}'s retrieval index. The section summaries below cover the publication clause by clause. Write one compact abstract, three to five sentences: what the publication regulates or provides, its scope and applicability, and the structure a reader should know (parts, annexes, where the normative core sits). Use the publication's own terms exactly. No preamble, no headings.\n";
|
|
352
352
|
|
|
353
|
+
// workers/worker_public/prompts/family-summary.md
|
|
354
|
+
var family_summary_default = `You write the community summary of one publication family for {{PUBLISHER_NAME}}'s retrieval index \u2014 the precomputed answer to "what is this family and what changed between editions". The registry rows and the successor graph below are your ONLY facts. Write three to five sentences: what the family regulates or provides, its structure (parts, annexes), and the edition lineage \u2014 which editions are active, which are superseded, and what the successor chain says changed. Never invent a change the lineage does not show; when the chain only says one edition replaced another, say exactly that. Name editions exactly as the registry does. No preamble.
|
|
355
|
+
`;
|
|
356
|
+
|
|
353
357
|
// workers/worker_public/prompts/section-summary.md
|
|
354
358
|
var section_summary_default = "You summarize one numbered clause of a metrology publication for a retrieval index. You are given the publication, the clause number, and excerpts of its sub-clauses.\n\nWrite a dense summary of 3 to 5 sentences stating what the clause governs and how its sub-clauses divide the subject. Name each sub-clause number together with its topic, in document order.\n\nPlain factual prose. No preamble, no headings, no bullet list, no quotation marks around the whole text. Write in the same language as the excerpts.\n";
|
|
355
359
|
|
|
@@ -510,6 +514,51 @@ Covers: ${childAnchors}`;
|
|
|
510
514
|
}
|
|
511
515
|
return json({ results, usage });
|
|
512
516
|
}
|
|
517
|
+
async function handleFamilySummary(env, req) {
|
|
518
|
+
if (!env.ADMIN_TOKEN) return err(501, "admin_disabled", "ADMIN_TOKEN secret is not configured");
|
|
519
|
+
const auth = req.headers.get("authorization") ?? "";
|
|
520
|
+
if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
|
|
521
|
+
const body = await readJson(req);
|
|
522
|
+
const family = typeof body?.family === "string" ? body.family.trim().slice(0, 24) : "";
|
|
523
|
+
if (!/^[A-Z]+-\d+$/.test(family)) return err(400, "invalid_input", "family must look like R-60 (type-number)");
|
|
524
|
+
try {
|
|
525
|
+
const docs = await env.DB.prepare(
|
|
526
|
+
"SELECT docidentifier, edition, status, active, superseded_by, title FROM documents WHERE family = ?1 ORDER BY edition"
|
|
527
|
+
).bind(family).all();
|
|
528
|
+
const rows = docs.results ?? [];
|
|
529
|
+
if (rows.length < 2) return json({ family, ok: false, note: "fewer than two editions \u2014 no lineage to summarize" });
|
|
530
|
+
const succ = await env.DB.prepare(
|
|
531
|
+
"SELECT e.src AS src, e.dst AS dst FROM graph_edges e WHERE e.kind = 'successor' AND (e.src IN (SELECT src FROM graph_edges WHERE kind = 'part_of' AND dst = ?2) OR e.dst IN (SELECT src FROM graph_edges WHERE kind = 'part_of' AND dst = ?2)) LIMIT 40"
|
|
532
|
+
).bind(family, `family:${family}`).all();
|
|
533
|
+
const key = `famsum:${family}`;
|
|
534
|
+
const cached = body?.force === true ? null : await env.CACHE.get(key);
|
|
535
|
+
if (cached) return json({ family, ok: true, cached: true, summary: cached });
|
|
536
|
+
const listing = rows.map((r) => `- ${r.docidentifier} \u2014 ${r.status}${r.active ? " (ACTIVE)" : ""}${r.title ? ` \u2014 ${String(r.title).slice(0, 120)}` : ""}`).join("\n");
|
|
537
|
+
const chain = (succ.results ?? []).map((r) => `${String(r.src).replace("doc:", "")} \u2192 superseded by \u2192 ${String(r.dst).replace("doc:", "")}`).join("\n");
|
|
538
|
+
const model = typeof env.ENRICH_MODEL === "string" && env.ENRICH_MODEL ? env.ENRICH_MODEL : MODELS.enrich;
|
|
539
|
+
const res = await env.AI.run(model, {
|
|
540
|
+
messages: [
|
|
541
|
+
{ role: "system", content: family_summary_default.trimEnd() },
|
|
542
|
+
{ role: "user", content: `Family ${family}
|
|
543
|
+
|
|
544
|
+
Registry rows:
|
|
545
|
+
${listing}
|
|
546
|
+
|
|
547
|
+
Successor chain:
|
|
548
|
+
${chain || "(no successor edges recorded)"}` }
|
|
549
|
+
],
|
|
550
|
+
max_tokens: 1600,
|
|
551
|
+
reasoning_effort: "low"
|
|
552
|
+
});
|
|
553
|
+
const raw = typeof res?.response === "string" && res.response.trim() ? res.response : res?.choices?.[0]?.message?.content;
|
|
554
|
+
const summary = typeof raw === "string" ? raw.trim().replace(/^["']|["']$/g, "").slice(0, 1200) : "";
|
|
555
|
+
if (!summary) return json({ family, ok: false, error: "empty summary" });
|
|
556
|
+
await env.CACHE.put(key, summary);
|
|
557
|
+
return json({ family, ok: true, cached: false, summary, editions: rows.length, successors: (succ.results ?? []).length });
|
|
558
|
+
} catch (e) {
|
|
559
|
+
return err(502, "family_summary_failed", String(e?.message ?? e).slice(0, 200));
|
|
560
|
+
}
|
|
561
|
+
}
|
|
513
562
|
async function handleCaption(env, req) {
|
|
514
563
|
if (!env.ADMIN_TOKEN) return err(501, "admin_disabled", "ADMIN_TOKEN secret is not configured");
|
|
515
564
|
const auth = req.headers.get("authorization") ?? "";
|
|
@@ -994,13 +1043,13 @@ async function callToolOnce(env, ctx, _req, tier, key, name, args, t0) {
|
|
|
994
1043
|
// stream:false forces the JSON lane (anon defaults to SSE)
|
|
995
1044
|
body: JSON.stringify({ ...args, stream: false })
|
|
996
1045
|
});
|
|
997
|
-
const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-
|
|
1046
|
+
const { runTool, TOOLS_REGISTRY: TOOLS_REGISTRY2 } = await import("../../tools-CUKFOW7S.js");
|
|
998
1047
|
let payload;
|
|
999
1048
|
if (TOOLS_REGISTRY2.some((t) => t.name === name && t.audiences.includes("mcp"))) {
|
|
1000
1049
|
const r = await runTool({ ...env, DB: env.DB }, { name, args }, "mcp");
|
|
1001
1050
|
payload = r ? { tool: r.name, query: r.query, result: r.output } : { error: { message: `tool ${name} returned nothing for the given arguments` } };
|
|
1002
1051
|
} else {
|
|
1003
|
-
const res = name === "ask" ? await (await import("../../ask-
|
|
1052
|
+
const res = name === "ask" ? await (await import("../../ask-3BJKTVLY.js")).handleAsk(env, ctx, inner, tier, key) : await (await import("../../search-JDSQPI3A.js")).handleSearch(env, ctx, inner, tier, key);
|
|
1004
1053
|
payload = await res.json().catch(() => ({ error: { message: "tool transport failed", status: res.status } }));
|
|
1005
1054
|
}
|
|
1006
1055
|
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 });
|
|
@@ -1232,11 +1281,21 @@ var OPENAPI_SURFACE = [
|
|
|
1232
1281
|
"pattern": "/v1/admin/section",
|
|
1233
1282
|
"operationId": "adminSection"
|
|
1234
1283
|
},
|
|
1284
|
+
{
|
|
1285
|
+
"method": "POST",
|
|
1286
|
+
"pattern": "/v1/admin/family-summary",
|
|
1287
|
+
"operationId": "adminFamilySummary"
|
|
1288
|
+
},
|
|
1235
1289
|
{
|
|
1236
1290
|
"method": "POST",
|
|
1237
1291
|
"pattern": "/admin/section",
|
|
1238
1292
|
"operationId": "adminSectionAlias"
|
|
1239
1293
|
},
|
|
1294
|
+
{
|
|
1295
|
+
"method": "POST",
|
|
1296
|
+
"pattern": "/admin/family-summary",
|
|
1297
|
+
"operationId": "adminFamilySummaryAlias"
|
|
1298
|
+
},
|
|
1240
1299
|
{
|
|
1241
1300
|
"method": "POST",
|
|
1242
1301
|
"pattern": "/admin/vectors",
|
|
@@ -1772,6 +1831,8 @@ var OPENAPI_HANDLERS = {
|
|
|
1772
1831
|
adminEnrich: (c) => handleEnrich(c.env, c.ctx, c.req),
|
|
1773
1832
|
adminEnrichAlias: (c) => handleEnrich(c.env, c.ctx, c.req),
|
|
1774
1833
|
adminSection: (c) => handleSectionUnit(c.env, c.ctx, c.req),
|
|
1834
|
+
adminFamilySummary: (c) => handleFamilySummary(c.env, c.req),
|
|
1835
|
+
adminFamilySummaryAlias: (c) => handleFamilySummary(c.env, c.req),
|
|
1775
1836
|
adminSectionAlias: (c) => handleSectionUnit(c.env, c.ctx, c.req),
|
|
1776
1837
|
adminVectors: (c) => handleVectors(c.env, c.req),
|
|
1777
1838
|
adminCaption: (c) => handleCaption(c.env, c.req),
|
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.120",
|
|
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",
|
|
@@ -866,6 +866,35 @@ paths:
|
|
|
866
866
|
responses:
|
|
867
867
|
'200':
|
|
868
868
|
description: The written units with their usage.
|
|
869
|
+
/v1/admin/family-summary:
|
|
870
|
+
post:
|
|
871
|
+
tags: [Administration]
|
|
872
|
+
summary: Write a family's community summary
|
|
873
|
+
description: >-
|
|
874
|
+
Generates the precomputed answer to "what is this family and
|
|
875
|
+
what changed between editions" from the registry rows and the
|
|
876
|
+
successor graph, and stores it in KV; editionNote serves it
|
|
877
|
+
beside the deterministic registry line on doc-scoped answers.
|
|
878
|
+
Families need at least two editions. force regenerates.
|
|
879
|
+
operationId: adminFamilySummary
|
|
880
|
+
security: [{ adminAuth: [] }]
|
|
881
|
+
requestBody:
|
|
882
|
+
required: true
|
|
883
|
+
content:
|
|
884
|
+
application/json:
|
|
885
|
+
schema:
|
|
886
|
+
type: object
|
|
887
|
+
required: [family]
|
|
888
|
+
properties:
|
|
889
|
+
family:
|
|
890
|
+
type: string
|
|
891
|
+
description: The family key, for example R-60.
|
|
892
|
+
force:
|
|
893
|
+
type: boolean
|
|
894
|
+
default: false
|
|
895
|
+
responses:
|
|
896
|
+
'200':
|
|
897
|
+
description: The stored summary with its provenance counts.
|
|
869
898
|
/admin/section:
|
|
870
899
|
post:
|
|
871
900
|
tags: [Administration]
|
|
@@ -887,6 +916,27 @@ paths:
|
|
|
887
916
|
responses:
|
|
888
917
|
'200':
|
|
889
918
|
description: The written units with their usage.
|
|
919
|
+
/admin/family-summary:
|
|
920
|
+
post:
|
|
921
|
+
tags: [Administration]
|
|
922
|
+
summary: Write a family's community summary (the operational path)
|
|
923
|
+
description: >-
|
|
924
|
+
The operational alias of /v1/admin/family-summary; the behaviour
|
|
925
|
+
and the credential are identical.
|
|
926
|
+
operationId: adminFamilySummaryAlias
|
|
927
|
+
security: [{ adminAuth: [] }]
|
|
928
|
+
requestBody:
|
|
929
|
+
required: true
|
|
930
|
+
content:
|
|
931
|
+
application/json:
|
|
932
|
+
schema:
|
|
933
|
+
type: object
|
|
934
|
+
required: [family]
|
|
935
|
+
properties:
|
|
936
|
+
family: { type: string }
|
|
937
|
+
responses:
|
|
938
|
+
'200':
|
|
939
|
+
description: The stored summary.
|
|
890
940
|
/admin/vectors:
|
|
891
941
|
post:
|
|
892
942
|
tags: [Administration]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
You write the community summary of one publication family for {{PUBLISHER_NAME}}'s retrieval index — the precomputed answer to "what is this family and what changed between editions". The registry rows and the successor graph below are your ONLY facts. Write three to five sentences: what the family regulates or provides, its structure (parts, annexes), and the edition lineage — which editions are active, which are superseded, and what the successor chain says changed. Never invent a change the lineage does not show; when the chain only says one edition replaced another, say exactly that. Name editions exactly as the registry does. No preamble.
|
|
@@ -7,6 +7,7 @@ import { err, json, corsHeaders, readJson, authenticate } from "./lib/http";
|
|
|
7
7
|
import type { Env } from "./env";
|
|
8
8
|
import enrichmentPrompt from "../prompts/enrichment.md";
|
|
9
9
|
import docSummaryPrompt from "../prompts/doc-summary.md";
|
|
10
|
+
import familySummaryPrompt from "../prompts/family-summary.md";
|
|
10
11
|
import sectionSummaryPrompt from "../prompts/section-summary.md";
|
|
11
12
|
import relevancyPrompt from "../prompts/relevancy.md";
|
|
12
13
|
import precisionPrompt from "../prompts/precision.md";
|
|
@@ -202,6 +203,55 @@ export async function handleSectionUnit(env: Env, ctx: ExecutionContext, req: Re
|
|
|
202
203
|
return json({ results, usage });
|
|
203
204
|
}
|
|
204
205
|
|
|
206
|
+
/** Family community summaries (TODO.sota/06 item 2): one precomputed
|
|
207
|
+
* answer per publication family to "what is this family and what
|
|
208
|
+
* changed between editions" — generated from the registry rows and
|
|
209
|
+
* the successor graph (the family IS the corpus's natural community),
|
|
210
|
+
* stored in KV under famsum:<family>, served by editionNote beside
|
|
211
|
+
* the deterministic registry line. Admin-gated; idempotent (force
|
|
212
|
+
* regenerates); the quality-first lane pays once. */
|
|
213
|
+
export async function handleFamilySummary(env: Env, req: Request): Promise<Response> {
|
|
214
|
+
if (!env.ADMIN_TOKEN) return err(501, "admin_disabled", "ADMIN_TOKEN secret is not configured");
|
|
215
|
+
const auth = req.headers.get("authorization") ?? "";
|
|
216
|
+
if (auth !== `Bearer ${env.ADMIN_TOKEN}`) return err(401, "unauthorized", "Invalid admin token");
|
|
217
|
+
const body = await readJson(req);
|
|
218
|
+
const family = typeof body?.family === "string" ? body.family.trim().slice(0, 24) : "";
|
|
219
|
+
if (!/^[A-Z]+-\d+$/.test(family)) return err(400, "invalid_input", "family must look like R-60 (type-number)");
|
|
220
|
+
try {
|
|
221
|
+
const docs = await env.DB.prepare(
|
|
222
|
+
"SELECT docidentifier, edition, status, active, superseded_by, title FROM documents WHERE family = ?1 ORDER BY edition",
|
|
223
|
+
).bind(family).all<any>();
|
|
224
|
+
const rows = docs.results ?? [];
|
|
225
|
+
if (rows.length < 2) return json({ family, ok: false, note: "fewer than two editions — no lineage to summarize" });
|
|
226
|
+
// the family's docs through the part_of edges (publisher-pure: no
|
|
227
|
+
// identifier literal — the family node is the join key)
|
|
228
|
+
const succ = await env.DB.prepare(
|
|
229
|
+
"SELECT e.src AS src, e.dst AS dst FROM graph_edges e WHERE e.kind = 'successor' AND (e.src IN (SELECT src FROM graph_edges WHERE kind = 'part_of' AND dst = ?2) OR e.dst IN (SELECT src FROM graph_edges WHERE kind = 'part_of' AND dst = ?2)) LIMIT 40",
|
|
230
|
+
).bind(family, `family:${family}`).all<any>();
|
|
231
|
+
const key = `famsum:${family}`;
|
|
232
|
+
const cached = body?.force === true ? null : await env.CACHE.get(key);
|
|
233
|
+
if (cached) return json({ family, ok: true, cached: true, summary: cached });
|
|
234
|
+
const listing = rows.map((r: any) => `- ${r.docidentifier} — ${r.status}${r.active ? " (ACTIVE)" : ""}${r.title ? ` — ${String(r.title).slice(0, 120)}` : ""}`).join("\n");
|
|
235
|
+
const chain = ((succ.results ?? []) as any[]).map((r: any) => `${String(r.src).replace("doc:", "")} → superseded by → ${String(r.dst).replace("doc:", "")}`).join("\n");
|
|
236
|
+
const model = typeof env.ENRICH_MODEL === "string" && env.ENRICH_MODEL ? env.ENRICH_MODEL : MODELS.enrich;
|
|
237
|
+
const res: any = await env.AI.run(model, {
|
|
238
|
+
messages: [
|
|
239
|
+
{ role: "system", content: familySummaryPrompt.trimEnd() },
|
|
240
|
+
{ role: "user", content: `Family ${family}\n\nRegistry rows:\n${listing}\n\nSuccessor chain:\n${chain || "(no successor edges recorded)"}` },
|
|
241
|
+
],
|
|
242
|
+
max_tokens: 1600,
|
|
243
|
+
reasoning_effort: "low",
|
|
244
|
+
});
|
|
245
|
+
const raw = typeof res?.response === "string" && res.response.trim() ? res.response : res?.choices?.[0]?.message?.content;
|
|
246
|
+
const summary = typeof raw === "string" ? raw.trim().replace(/^["']|["']$/g, "").slice(0, 1200) : "";
|
|
247
|
+
if (!summary) return json({ family, ok: false, error: "empty summary" });
|
|
248
|
+
await env.CACHE.put(key, summary);
|
|
249
|
+
return json({ family, ok: true, cached: false, summary, editions: rows.length, successors: (succ.results ?? []).length });
|
|
250
|
+
} catch (e: any) {
|
|
251
|
+
return err(502, "family_summary_failed", String(e?.message ?? e).slice(0, 200));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
205
255
|
/** Ops access to the Vectorize binding (get/upsert by id) for offline
|
|
206
256
|
* passes like embedding smoothing (G-ETSI-4) — the binding is the
|
|
207
257
|
* credential, admin-token gated exactly like /admin/enrich. */
|
|
@@ -23,7 +23,7 @@ import { completeTables, completeFigures } from "./completion";
|
|
|
23
23
|
import { NO_CONTEXT, appliedContext, contextNote, namedDocumentIn, parseContext, resolveDocScope, syntheticUnderstanding } from "./context";
|
|
24
24
|
import { liveDataConfig, liveTokenFor, opCfg, opTokenMember, resolveLiveAccount, type LiveRecord } from "./livedata";
|
|
25
25
|
import { bindModelNode, bindConstraintByQuantities, licenseBoundaryNote, licenseBoundaryRefusal, licensedEntryForPackage, modelCitation, modelEcho, modelGroundingBlock, standardForDocNumber } from "./modelplane";
|
|
26
|
-
import { evaluate as machineEvaluate, verdictNote } from "./verdict";
|
|
26
|
+
import { evaluate as machineEvaluate, extractChecks, extractParamsWithUnits, symbolsIn, verdictNote } from "./verdict";
|
|
27
27
|
import { evaluateConditionSets, quantitiesIn, type ConditionVerdict } from "./conditions";
|
|
28
28
|
import { evaluateAggregation, type AggregationVerdict } from "./aggregation";
|
|
29
29
|
import { matchLicensedTopic, boundaryNoteText } from "./boundary";
|
|
@@ -946,7 +946,29 @@ let convEntities: Array<{ entity: string; kind: string }> = [];
|
|
|
946
946
|
// the worker EXECUTES the bound node's machine checks against the
|
|
947
947
|
// question's stated values; the model narrates the computed verdict
|
|
948
948
|
// and the verdict BLOCK is server-built — data, never generated prose
|
|
949
|
-
|
|
949
|
+
let machineVerdict = boundModel && !boundModel.gated && !ablate?.noVerdict ? machineEvaluate(boundModel.content, q.query) : null;
|
|
950
|
+
if (machineVerdict === null && boundModel && !boundModel.gated) {
|
|
951
|
+
// unit semantics (TODO.sota/04): the stated values' units reach the
|
|
952
|
+
// units register for their dimensions; a comparison mixing
|
|
953
|
+
// dimensions voids with the reason instead of answering a number
|
|
954
|
+
try {
|
|
955
|
+
const unitTokens = [...new Set(Object.values(extractParamsWithUnits(q.query, symbolsIn(extractChecks(boundModel.content))).units).map((u) => u.toLowerCase()))];
|
|
956
|
+
if (unitTokens.length) {
|
|
957
|
+
const marks = unitTokens.map(() => "?").join(",");
|
|
958
|
+
// the register keys symbols in the symbols JSON (ascii/unicode),
|
|
959
|
+
// not in `short` (full names) — D1's json_extract reads them
|
|
960
|
+
const rows = await env.DB.prepare(
|
|
961
|
+
`SELECT lower(coalesce(json_extract(symbols, '$.ascii'), json_extract(symbols, '$.unicode'))) AS sym, dimension_ascii FROM units_db WHERE lower(coalesce(json_extract(symbols, '$.ascii'), json_extract(symbols, '$.unicode'))) IN (${marks})`,
|
|
962
|
+
)
|
|
963
|
+
.bind(...unitTokens).all().catch(() => ({ results: [] }));
|
|
964
|
+
const dimensions: Record<string, string> = {};
|
|
965
|
+
for (const r of (rows.results ?? []) as any[]) dimensions[String(r.sym)] = String(r.dimension_ascii ?? "");
|
|
966
|
+
machineVerdict = machineEvaluate(boundModel.content, q.query, { dimensions });
|
|
967
|
+
}
|
|
968
|
+
} catch {
|
|
969
|
+
// the plain evaluation above already ran; nothing to salvage
|
|
970
|
+
}
|
|
971
|
+
}
|
|
950
972
|
const machineNote = machineVerdict && boundModel ? verdictNote(machineVerdict, boundModel) : undefined;
|
|
951
973
|
// ── condition-set membership (konneal/engine#90): the test-method
|
|
952
974
|
// packages' severity menus as machine-verifiable membership. Fires
|
|
@@ -55,7 +55,20 @@ export async function editionNote(env: Env, u: { doc_number?: string | null } |
|
|
|
55
55
|
.all<{ docidentifier: string }>();
|
|
56
56
|
const actives = (rows.results ?? []).map((r) => r.docidentifier);
|
|
57
57
|
if (!actives.length) return undefined;
|
|
58
|
-
|
|
58
|
+
// the family's community summary (TODO.sota/06): the precomputed
|
|
59
|
+
// what-changed-between-editions answer rides beside the
|
|
60
|
+
// deterministic registry line — provenance-carrying (generated from
|
|
61
|
+
// the registry and the successor graph, never free narration)
|
|
62
|
+
const famRow = await env.DB.prepare("SELECT family FROM documents WHERE docidentifier LIKE ?1 || '%:%' LIMIT 1")
|
|
63
|
+
.bind(`% ${u.doc_number}:%`)
|
|
64
|
+
.first<{ family: string }>()
|
|
65
|
+
.catch(() => null);
|
|
66
|
+
let summary = "";
|
|
67
|
+
if (famRow?.family && env.CACHE) {
|
|
68
|
+
summary = ((await env.CACHE.get(`famsum:${famRow.family}`).catch(() => "")) ?? "");
|
|
69
|
+
}
|
|
70
|
+
const registry = `Publication registry (authoritative): the ACTIVE edition(s) for this publication are ${actives.join(", ")}. Passages from other editions are superseded — use them only for historical comparison and say so.`;
|
|
71
|
+
return summary ? `${registry}\nFamily summary (precomputed from the registry and the successor graph): ${summary}` : registry;
|
|
59
72
|
} catch {
|
|
60
73
|
return undefined;
|
|
61
74
|
}
|
|
@@ -22,7 +22,7 @@ export type { Env };
|
|
|
22
22
|
import { json, err, corsHeaders, withCors, readJson, authenticate, type ApiKey } from "./lib/http";
|
|
23
23
|
|
|
24
24
|
import { handleSearch } from "./search";
|
|
25
|
-
import { handleEnrich, handleSectionUnit, handleCaption, handleVectors, handleJudge, handleCreateKey, handleListKeys, handleRevokeKey, handleKeyUsage } from "./admin";
|
|
25
|
+
import { handleEnrich, handleSectionUnit, handleCaption, handleVectors, handleJudge, handleCreateKey, handleListKeys, handleRevokeKey, handleKeyUsage, handleFamilySummary } from "./admin";
|
|
26
26
|
import { handleResearch } from "./research";
|
|
27
27
|
import { uploadAttachment, readAttachment, deleteAttachment, type AttachmentDeps } from "./attachments";
|
|
28
28
|
import { cfBlobs } from "./ports/cloudflare/adapters";
|
|
@@ -618,6 +618,8 @@ const OPENAPI_HANDLERS: Record<OpenApiOperationId, RouteHandler> = {
|
|
|
618
618
|
adminEnrich: (c) => handleEnrich(c.env, c.ctx, c.req),
|
|
619
619
|
adminEnrichAlias: (c) => handleEnrich(c.env, c.ctx, c.req),
|
|
620
620
|
adminSection: (c) => handleSectionUnit(c.env, c.ctx, c.req),
|
|
621
|
+
adminFamilySummary: (c) => handleFamilySummary(c.env, c.req),
|
|
622
|
+
adminFamilySummaryAlias: (c) => handleFamilySummary(c.env, c.req),
|
|
621
623
|
adminSectionAlias: (c) => handleSectionUnit(c.env, c.ctx, c.req),
|
|
622
624
|
adminVectors: (c) => handleVectors(c.env, c.req),
|
|
623
625
|
adminCaption: (c) => handleCaption(c.env, c.req),
|
|
@@ -46,7 +46,9 @@ export type OpenApiOperationId =
|
|
|
46
46
|
| "adminEnrich"
|
|
47
47
|
| "adminEnrichAlias"
|
|
48
48
|
| "adminSection"
|
|
49
|
+
| "adminFamilySummary"
|
|
49
50
|
| "adminSectionAlias"
|
|
51
|
+
| "adminFamilySummaryAlias"
|
|
50
52
|
| "adminVectors"
|
|
51
53
|
| "adminCaption"
|
|
52
54
|
| "adminJudge"
|
|
@@ -257,11 +259,21 @@ export const OPENAPI_SURFACE: readonly (Omit<OpenApiRoute, "operationId"> & { op
|
|
|
257
259
|
"pattern": "/v1/admin/section",
|
|
258
260
|
"operationId": "adminSection"
|
|
259
261
|
},
|
|
262
|
+
{
|
|
263
|
+
"method": "POST",
|
|
264
|
+
"pattern": "/v1/admin/family-summary",
|
|
265
|
+
"operationId": "adminFamilySummary"
|
|
266
|
+
},
|
|
260
267
|
{
|
|
261
268
|
"method": "POST",
|
|
262
269
|
"pattern": "/admin/section",
|
|
263
270
|
"operationId": "adminSectionAlias"
|
|
264
271
|
},
|
|
272
|
+
{
|
|
273
|
+
"method": "POST",
|
|
274
|
+
"pattern": "/admin/family-summary",
|
|
275
|
+
"operationId": "adminFamilySummaryAlias"
|
|
276
|
+
},
|
|
265
277
|
{
|
|
266
278
|
"method": "POST",
|
|
267
279
|
"pattern": "/admin/vectors",
|
|
@@ -20,6 +20,9 @@ export interface Verdict {
|
|
|
20
20
|
on_violation?: string;
|
|
21
21
|
violation_meaning?: string;
|
|
22
22
|
missing: string[];
|
|
23
|
+
/** why a fully-stated question still cannot evaluate (TODO.sota/04):
|
|
24
|
+
* the stated quantities' units carry conflicting dimensions */
|
|
25
|
+
void_reason?: string;
|
|
23
26
|
checks: MachineCheck[];
|
|
24
27
|
}
|
|
25
28
|
|
|
@@ -190,29 +193,72 @@ function parseNumber(raw: string): number {
|
|
|
190
193
|
}
|
|
191
194
|
|
|
192
195
|
export function extractParams(query: string, symbols: string[]): Record<string, number> {
|
|
193
|
-
|
|
196
|
+
return extractParamsWithUnits(query, symbols).values;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The stated values WITH their unit tokens (TODO.sota/04's unit
|
|
200
|
+
* semantics): "E_max 30000 v" binds e_max=30000 and the unit "v" —
|
|
201
|
+
* the dimension check needs both. */
|
|
202
|
+
export function extractParamsWithUnits(
|
|
203
|
+
query: string,
|
|
204
|
+
symbols: string[],
|
|
205
|
+
): { values: Record<string, number>; units: Record<string, string> } {
|
|
206
|
+
const values: Record<string, number> = {};
|
|
207
|
+
const units: Record<string, string> = {};
|
|
194
208
|
for (const sym of symbols) {
|
|
195
209
|
const leaf = sym.split(".").pop() ?? sym;
|
|
196
210
|
const esc = leaf.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
197
211
|
// symbol, a short non-numeric gap (words like "were"/"of" allowed),
|
|
198
|
-
// then the number
|
|
199
|
-
const re = new RegExp(`\\b${esc}\\b\\D{0,14}?([0-9][0-9 ,.]*[0-9])
|
|
212
|
+
// then the number, then an optional unit token directly after
|
|
213
|
+
const re = new RegExp(`\\b${esc}\\b\\D{0,14}?([0-9][0-9 ,.]*[0-9])\\s*(%|\\u00b0?[A-Za-z\\u00b5\\u03a9]{0,6})?`, "iu");
|
|
200
214
|
const m = query.match(re);
|
|
201
215
|
if (m) {
|
|
202
216
|
const v = parseNumber(m[1]!);
|
|
203
|
-
if (Number.isFinite(v))
|
|
217
|
+
if (Number.isFinite(v)) {
|
|
218
|
+
values[sym] = v;
|
|
219
|
+
const u = (m[2] ?? "").trim();
|
|
220
|
+
if (u) units[sym] = u;
|
|
221
|
+
}
|
|
204
222
|
}
|
|
205
223
|
}
|
|
206
|
-
return
|
|
224
|
+
return { values, units };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Dimension coherence (TODO.sota/04 item 2): the units plane gives
|
|
228
|
+
* each unit token a dimension; a parameter set whose bound symbols
|
|
229
|
+
* carry CONFLICTING known dimensions is incoherent — the check
|
|
230
|
+
* compares quantities that are not comparable. Pure: the dimensions
|
|
231
|
+
* map arrives from the caller (the units register at load). */
|
|
232
|
+
export function dimensionMismatch(
|
|
233
|
+
check: string,
|
|
234
|
+
units: Record<string, string>,
|
|
235
|
+
dimensions: Record<string, string>,
|
|
236
|
+
): string | null {
|
|
237
|
+
// the symbols THIS check compares, each mapped through its stated
|
|
238
|
+
// unit's dimension; more than one distinct dimension in one
|
|
239
|
+
// comparison is incoherent (a length is not a voltage)
|
|
240
|
+
const dims = new Map<string, string>();
|
|
241
|
+
for (const [sym, unit] of Object.entries(units)) {
|
|
242
|
+
const leaf = sym.split(".").pop();
|
|
243
|
+
if (!leaf || !new RegExp(`\\b${leaf}\\b`, "i").test(check)) continue;
|
|
244
|
+
const dim = dimensions[unit.toLowerCase()];
|
|
245
|
+
if (dim) dims.set(sym, dim);
|
|
246
|
+
}
|
|
247
|
+
const distinct = [...new Set(dims.values())];
|
|
248
|
+
if (distinct.length <= 1) return null;
|
|
249
|
+
const parts = [...dims.entries()].map(([sym, dim]) => `${sym} is in ${dim}`);
|
|
250
|
+
return `the stated quantities mix dimensions: ${parts.join(" while ")}`;
|
|
207
251
|
}
|
|
208
252
|
|
|
209
|
-
export function evaluate(content: unknown, query: string): Verdict | null {
|
|
253
|
+
export function evaluate(content: unknown, query: string, opts?: { dimensions?: Record<string, string> }): Verdict | null {
|
|
210
254
|
const c = (content && typeof content === "object" ? content : {}) as Record<string, any>;
|
|
211
255
|
const checks = extractChecks(content);
|
|
212
256
|
if (!checks.length) return null;
|
|
213
257
|
const symbols = symbolsIn(checks);
|
|
214
|
-
const
|
|
258
|
+
const bound = extractParamsWithUnits(query, symbols);
|
|
259
|
+
const params = bound.values;
|
|
215
260
|
const missing = symbols.filter((s) => params[s] === undefined);
|
|
261
|
+
let voidReason: string | null = null;
|
|
216
262
|
const machine: MachineCheck[] = checks.map((expression) => {
|
|
217
263
|
const values: Record<string, number> = {};
|
|
218
264
|
try {
|
|
@@ -220,7 +266,14 @@ export function evaluate(content: unknown, query: string): Verdict | null {
|
|
|
220
266
|
} catch { /* values stay partial */ }
|
|
221
267
|
let result: boolean | null = null;
|
|
222
268
|
if (missing.length === 0) {
|
|
223
|
-
|
|
269
|
+
// unit semantics (TODO.sota/04): a comparison mixing dimensions
|
|
270
|
+
// cannot evaluate — void with the reason, never a number answer
|
|
271
|
+
const mismatch = opts?.dimensions ? dimensionMismatch(expression, bound.units, opts.dimensions) : null;
|
|
272
|
+
if (mismatch) {
|
|
273
|
+
voidReason = voidReason ?? mismatch;
|
|
274
|
+
} else {
|
|
275
|
+
try { result = !!parseAndEval(expression, params); } catch { result = null; }
|
|
276
|
+
}
|
|
224
277
|
}
|
|
225
278
|
return { expression, symbolic: expression, values, result };
|
|
226
279
|
});
|
|
@@ -229,7 +282,10 @@ export function evaluate(content: unknown, query: string): Verdict | null {
|
|
|
229
282
|
}
|
|
230
283
|
const failed = machine.some((m) => m.result === false);
|
|
231
284
|
const evaluable = machine.some((m) => m.result !== null);
|
|
232
|
-
if (!evaluable)
|
|
285
|
+
if (!evaluable) {
|
|
286
|
+
if (voidReason) return { verdict: "void", missing: [], void_reason: voidReason, checks: machine };
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
233
289
|
return {
|
|
234
290
|
verdict: failed ? "fail" : "pass",
|
|
235
291
|
on_violation: failed ? String(c.on_violation ?? "invalid") : undefined,
|
|
@@ -249,7 +305,9 @@ export function verdictNote(v: Verdict, node: { node_id: string; clause?: { urn?
|
|
|
249
305
|
lines.push(`- ${c.expression}${vals ? ` [${vals}]` : ""} → ${c.result === null ? "not evaluated" : c.result ? "holds" : "VIOLATED"}`);
|
|
250
306
|
}
|
|
251
307
|
if (v.verdict === "void") {
|
|
252
|
-
lines.push(
|
|
308
|
+
lines.push(v.void_reason
|
|
309
|
+
? `VERDICT: VOID — ${v.void_reason}. State the mismatch plainly; the question cannot be decided as stated.`
|
|
310
|
+
: `VERDICT: VOID — the question does not state: ${v.missing.join(", ")}. Say exactly what is missing; never assume values.`);
|
|
253
311
|
} else if (v.verdict === "pass") {
|
|
254
312
|
lines.push(`VERDICT: PASS — every machine check holds at the stated values. Present this verdict, the arithmetic above, and cite the node's clause.`);
|
|
255
313
|
} else {
|