@exulu/backend 5.1.1 → 5.2.0

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.
Files changed (56) hide show
  1. package/dist/{chunk-UXHMHM4E.js → chunk-ASF74XFZ.js} +271 -33
  2. package/dist/{convert-exulu-tools-to-ai-sdk-tools-FHFMJSD2.js → convert-exulu-tools-to-ai-sdk-tools-MFLZQONB.js} +3 -1
  3. package/dist/index.cjs +2761 -355
  4. package/dist/index.js +2425 -305
  5. package/ee/agentic-retrieval/pipeline/config.test.ts +42 -0
  6. package/ee/agentic-retrieval/pipeline/config.ts +36 -0
  7. package/ee/agentic-retrieval/pipeline/index.test.ts +3 -3
  8. package/ee/agentic-retrieval/pipeline/index.ts +43 -1
  9. package/ee/agentic-retrieval/pipeline/micro-call.test.ts +58 -0
  10. package/ee/agentic-retrieval/pipeline/micro-call.ts +20 -3
  11. package/ee/agentic-retrieval/pipeline/near-duplicates.test.ts +50 -0
  12. package/ee/agentic-retrieval/pipeline/near-duplicates.ts +74 -0
  13. package/ee/agentic-retrieval/pipeline/prefilter.test.ts +32 -0
  14. package/ee/agentic-retrieval/pipeline/prefilter.ts +13 -1
  15. package/ee/agentic-retrieval/pipeline/rerank.test.ts +79 -0
  16. package/ee/agentic-retrieval/pipeline/rerank.ts +61 -6
  17. package/ee/claim-check/agent-config.ts +26 -0
  18. package/ee/claim-check/concurrency.test.ts +33 -0
  19. package/ee/claim-check/concurrency.ts +30 -0
  20. package/ee/claim-check/evidence.test.ts +198 -0
  21. package/ee/claim-check/evidence.ts +162 -0
  22. package/ee/claim-check/prompts/decompose.ts +52 -0
  23. package/ee/claim-check/prompts/disambiguate.ts +58 -0
  24. package/ee/claim-check/prompts/select-disambiguate.ts +17 -0
  25. package/ee/claim-check/prompts/select.ts +55 -0
  26. package/ee/claim-check/prompts/shared.test.ts +193 -0
  27. package/ee/claim-check/prompts/shared.ts +89 -0
  28. package/ee/claim-check/prompts/verify.ts +56 -0
  29. package/ee/claim-check/rate-limit.test.ts +40 -0
  30. package/ee/claim-check/rate-limit.ts +82 -0
  31. package/ee/claim-check/routes.test.ts +1188 -0
  32. package/ee/claim-check/routes.ts +682 -0
  33. package/ee/claim-check/run.test.ts +1317 -0
  34. package/ee/claim-check/run.ts +710 -0
  35. package/ee/claim-check/score.test.ts +108 -0
  36. package/ee/claim-check/score.ts +75 -0
  37. package/ee/claim-check/second-chance.test.ts +89 -0
  38. package/ee/claim-check/second-chance.ts +80 -0
  39. package/ee/claim-check/split.test.ts +179 -0
  40. package/ee/claim-check/split.ts +220 -0
  41. package/ee/claim-check/stages/decompose.test.ts +129 -0
  42. package/ee/claim-check/stages/decompose.ts +64 -0
  43. package/ee/claim-check/stages/disambiguate.test.ts +130 -0
  44. package/ee/claim-check/stages/disambiguate.ts +74 -0
  45. package/ee/claim-check/stages/select-disambiguate.test.ts +137 -0
  46. package/ee/claim-check/stages/select-disambiguate.ts +90 -0
  47. package/ee/claim-check/stages/select.test.ts +155 -0
  48. package/ee/claim-check/stages/select.ts +94 -0
  49. package/ee/claim-check/stages/usage.ts +11 -0
  50. package/ee/claim-check/stages/verify.test.ts +154 -0
  51. package/ee/claim-check/stages/verify.ts +78 -0
  52. package/ee/claim-check/types.ts +178 -0
  53. package/ee/entitlements.ts +3 -0
  54. package/ee/schemas.ts +71 -0
  55. package/ee/workers.ts +16 -0
  56. package/package.json +1 -1
@@ -0,0 +1,78 @@
1
+ import { z } from "zod";
2
+ import type { LanguageModel } from "ai";
3
+ import { microCall } from "@EE/agentic-retrieval/pipeline/micro-call";
4
+ import { CLAIM_CHECK_MAX_OUTPUT_TOKENS, type EvidenceSnippet, type VerifyOutcome } from "../types";
5
+ import { VERIFY_SYSTEM, verifyUserPrompt } from "../prompts/verify";
6
+ import { EMPTY_USAGE, type StageUsage } from "./usage";
7
+
8
+ const schema = z.object({
9
+ claims: z.array(
10
+ z.object({
11
+ claimId: z.string(),
12
+ verdict: z.enum(["supported", "contradicted", "unsupported"]),
13
+ evidence: z.array(z.object({ sourceId: z.string(), quote: z.string() })),
14
+ rationale: z.string(),
15
+ }),
16
+ ),
17
+ });
18
+
19
+ export async function runVerification(args: {
20
+ claims: { id: string; text: string }[];
21
+ evidence: EvidenceSnippet[];
22
+ model: LanguageModel;
23
+ temperature?: number;
24
+ /** Cancels the provider call when the request's deadline passes. */
25
+ signal?: AbortSignal;
26
+ }): Promise<{ outcomes: VerifyOutcome[]; usage: StageUsage }> {
27
+ if (args.claims.length === 0) return { outcomes: [], usage: { ...EMPTY_USAGE } };
28
+
29
+ // No evidence means nothing to check against. Asking a model anyway would
30
+ // invite it to answer from its own knowledge, which is exactly the failure
31
+ // this feature exists to detect.
32
+ if (args.evidence.length === 0) {
33
+ return {
34
+ outcomes: args.claims.map((c) => ({
35
+ claimId: c.id,
36
+ verdict: "unsupported" as const,
37
+ evidence: [],
38
+ rationale: "no evidence was available for this claim",
39
+ })),
40
+ usage: { ...EMPTY_USAGE },
41
+ };
42
+ }
43
+
44
+ const { output, usage } = await microCall({
45
+ model: args.model,
46
+ system: VERIFY_SYSTEM,
47
+ prompt: verifyUserPrompt({ claims: args.claims, evidence: args.evidence }),
48
+ schema,
49
+ temperature: args.temperature ?? 0,
50
+ maxOutputTokens: CLAIM_CHECK_MAX_OUTPUT_TOKENS,
51
+ ...(args.signal ? { abortSignal: args.signal } : {}),
52
+ });
53
+
54
+ const knownSourceIds = new Set(args.evidence.map((e) => e.sourceId));
55
+ const returned = new Map((output?.claims ?? []).map((c) => [c.claimId, c]));
56
+
57
+ // Finding 4: a claim the model dropped from a long JSON array is the
58
+ // likeliest failure of this stage, and reporting it as "unsupported" put the
59
+ // model's silence into the score as a finding against the ANSWER. No outcome
60
+ // is returned for it instead; run.ts drops the claim and marks its sentence
61
+ // not_checked, exactly as it already does for a call that failed outright.
62
+ const outcomes = args.claims.flatMap(({ id }) => {
63
+ const hit = returned.get(id);
64
+ if (!hit) return [];
65
+ return [
66
+ {
67
+ claimId: id,
68
+ verdict: hit.verdict,
69
+ // A citation to a source that was never shown is not traceable, so it is
70
+ // dropped; the verdict itself stands with its rationale.
71
+ evidence: hit.evidence.filter((e) => knownSourceIds.has(e.sourceId)),
72
+ rationale: hit.rationale,
73
+ },
74
+ ];
75
+ });
76
+
77
+ return { outcomes, usage: { calls: 1, ...usage } };
78
+ }
@@ -0,0 +1,178 @@
1
+ // ee/claim-check/types.ts
2
+ //
3
+ // The whole data contract of the claim-check engine. Every stage is a pure
4
+ // function over these types, so a stage can be tested without a provider and
5
+ // without the orchestrator.
6
+
7
+ /**
8
+ * Raised output cap: the staged prompts reason before answering, and the
9
+ * shared MICRO_CALL_MAX_OUTPUT_TOKENS (2000) truncates a batch of sentences.
10
+ *
11
+ * Still 8000 at the raised BATCH sizes, measured (o200k_base) against German
12
+ * maintenance prose rather than estimated. Worst case per stage, with every
13
+ * optional field returned at full length:
14
+ *
15
+ * selection+disambiguation, 25 sentences, both `rewritten` and `clarified`
16
+ * returned in full and a 15-word reason: 2,131 tok at the measured average
17
+ * sentence (77 chars), 3,481 at 205 chars, 4,981 at 356 chars.
18
+ * decomposition, 15 sentences: 966 tok at 2 claims x 77 chars, 2,601 at
19
+ * 3 x 205, 4,251 at 5 x 205, and 6,501 in the pathological 5 x 356 shape
20
+ * (five claims per sentence, each restating a 356-character sentence in
21
+ * full — a 5x expansion of the input).
22
+ * verification, 8 sentences: 1,877 tok at 3 claims x 77-char quotes, 2,525
23
+ * at 3 x 205, 5,405 at 5 x 356.
24
+ *
25
+ * So the binding case is a pathological decomposition batch at 6,501 of 8,000,
26
+ * leaving 1,499 for a reasoning model's thinking (which counts against this
27
+ * cap — see MICRO_CALL_MAX_OUTPUT_TOKENS). It is deliberately NOT raised:
28
+ * 8,000 sits just under the 8,192-token output ceiling of a whole generation of
29
+ * models that a self-hosted CLAIM_CHECK_DEFAULT_MODEL may well be, where a
30
+ * higher value fails every call outright, and a truncated batch already
31
+ * degrades safely — the parse fails, the batch fails, and run.ts's recursive
32
+ * bisect retries it at 8 and 7 sentences, which fit with room to spare.
33
+ */
34
+ export const CLAIM_CHECK_MAX_OUTPUT_TOKENS = 8000;
35
+
36
+ export type ClaimCheckSource = { id: string; name?: string; content: string };
37
+
38
+ /**
39
+ * Every kind of source a request or a manifest can name (Stage 4, spec §3-4).
40
+ * Declared once here — rather than once in the chat's manifest
41
+ * (src/exulu/claim-check/finish-metadata.ts) and again in the request schema
42
+ * (ee/claim-check/routes.ts) — so a type added to one side cannot silently
43
+ * fail to exist on the other. `"other"` is request-only: the chat's own
44
+ * manifest always knows exactly which of the five specific kinds it is
45
+ * naming, and never emits it.
46
+ */
47
+ export type ClaimCheckSourceType = "knowledge_base" | "document" | "memory" | "web" | "session_item" | "other";
48
+
49
+ export type Sentence = {
50
+ index: number;
51
+ /** Char offsets into the ORIGINAL answer string; answer.slice(start, end) === text. */
52
+ start: number;
53
+ end: number;
54
+ text: string;
55
+ /** Markdown heading hierarchy above this sentence, outermost first. */
56
+ headingPath: string[];
57
+ };
58
+
59
+ export type SentenceWindow = {
60
+ sentence: Sentence;
61
+ preceding: Sentence[];
62
+ following: Sentence[];
63
+ };
64
+
65
+ export type SelectionOutcome = {
66
+ index: number;
67
+ verifiable: boolean;
68
+ /** Rewritten verifiable-only sentence, or null when unchanged. */
69
+ rewritten: string | null;
70
+ reason: string;
71
+ /**
72
+ * False when the model returned no outcome for this sentence at all. The
73
+ * stage still reports verifiable=false (it must never promote a sentence
74
+ * nobody judged), but "the model skipped this" is NOT the finding
75
+ * "this sentence asserts nothing checkable", so the orchestrator needs to
76
+ * tell the two apart without matching on reason strings.
77
+ */
78
+ answered: boolean;
79
+ };
80
+
81
+ export type DisambiguationOutcome = {
82
+ index: number;
83
+ resolvable: boolean;
84
+ /** Clarified sentence, or null when no change was needed. */
85
+ clarified: string | null;
86
+ reason: string;
87
+ /** False when the model returned no outcome for this sentence. See SelectionOutcome.answered. */
88
+ answered: boolean;
89
+ };
90
+
91
+ export type DecompositionOutcome = {
92
+ index: number;
93
+ claims: { text: string; inferred: boolean }[];
94
+ };
95
+
96
+ export type EvidenceSnippet = {
97
+ sourceId: string;
98
+ sourceName?: string;
99
+ text: string;
100
+ score: number;
101
+ };
102
+
103
+ export type Verdict = "supported" | "contradicted" | "unsupported";
104
+
105
+ export type VerifyOutcome = {
106
+ claimId: string;
107
+ verdict: Verdict;
108
+ evidence: { sourceId: string; quote: string }[];
109
+ rationale: string;
110
+ };
111
+
112
+ export type Claim = {
113
+ /** Stable within one result: "c1", "c2", … in extraction order. */
114
+ id: string;
115
+ sentenceIndex: number;
116
+ text: string;
117
+ inferred: boolean;
118
+ verdict: Verdict;
119
+ evidence: { sourceId: string; quote: string }[];
120
+ rationale: string;
121
+ /** True when a second-chance retrieval supplied the evidence. */
122
+ rechecked: boolean;
123
+ };
124
+
125
+ export type SentenceState =
126
+ | "checked"
127
+ | "no_verifiable_content"
128
+ | "cannot_disambiguate"
129
+ | "not_checked";
130
+
131
+ export type SentenceResult = {
132
+ index: number;
133
+ start: number;
134
+ end: number;
135
+ state: SentenceState;
136
+ reason?: string;
137
+ claimIds: string[];
138
+ };
139
+
140
+ export type ScoreLabel = "ok" | "warn" | "alert" | "n/a";
141
+
142
+ export type ClaimCheckScore = {
143
+ /** Checked claims only — the denominator. */
144
+ claims: number;
145
+ supported: number;
146
+ contradicted: number;
147
+ unsupported: number;
148
+ /** (contradicted + unsupported) / claims; 0 when claims === 0. */
149
+ unsupportedShare: number;
150
+ label: ScoreLabel;
151
+ };
152
+
153
+ export type ClaimCheckResult = {
154
+ status: "ok" | "partial";
155
+ score: ClaimCheckScore;
156
+ sentences: SentenceResult[];
157
+ claims: Claim[];
158
+ usage: { calls: number; inputTokens: number; outputTokens: number };
159
+ timings: Record<string, number>;
160
+ limits: { truncated: boolean; sentencesSkipped: number };
161
+ notes: string[];
162
+ };
163
+
164
+ export type ClaimCheckOptions = {
165
+ fidelity: "fast" | "paper";
166
+ completions: number;
167
+ reRetrieve: boolean;
168
+ thresholds: { warn: number; alert: number };
169
+ caps: { maxSentences: number; maxClaims: number; maxReRetrievals: number };
170
+ };
171
+
172
+ export const CLAIM_CHECK_DEFAULTS: ClaimCheckOptions = {
173
+ fidelity: "fast",
174
+ completions: 1,
175
+ reRetrieve: true,
176
+ thresholds: { warn: 0.1, alert: 0.3 },
177
+ caps: { maxSentences: 120, maxClaims: 200, maxReRetrievals: 10 },
178
+ };
@@ -10,6 +10,7 @@ export const ENTITLEMENTS: {
10
10
  "multi-agent-tooling": boolean,
11
11
  "advanced-document-processing": boolean,
12
12
  "rate-limits": boolean,
13
+ "claim-check": boolean,
13
14
  } = {
14
15
  "rbac": false,
15
16
  "advanced-markdown-chunker": false,
@@ -22,6 +23,7 @@ export const ENTITLEMENTS: {
22
23
  "multi-agent-tooling": false,
23
24
  "advanced-document-processing": false,
24
25
  "rate-limits": false,
26
+ "claim-check": false,
25
27
  }
26
28
 
27
29
  export const checkLicense = () => {
@@ -46,6 +48,7 @@ export const checkLicense = () => {
46
48
  "multi-agent-tooling": true,
47
49
  "advanced-document-processing": true,
48
50
  "rate-limits": true,
51
+ "claim-check": true,
49
52
  }
50
53
  }
51
54
 
package/ee/schemas.ts CHANGED
@@ -38,6 +38,77 @@ export const feedbackSchema: ExuluTableDefinition = {
38
38
  ]
39
39
  }
40
40
 
41
+ /**
42
+ * One stored claim check per assistant message (spec §5.2).
43
+ *
44
+ * `payload` holds the endpoint's whole response, so the chat can re-render a
45
+ * panel after a reload without re-spending ~8 provider calls. `score_label` is
46
+ * duplicated out of it only so a list view can colour a row without parsing
47
+ * every payload — that list view still needs either a scoped route or a
48
+ * verified RBAC story before it can be built; `graphql: false` below is not
49
+ * an oversight blocking it.
50
+ *
51
+ * `graphql: false`: nothing consumes a GraphQL claim-checks API today — the
52
+ * frontend reads these rows through the REST route the next task adds,
53
+ * scoped to the calling user. `payload` holds the whole check result,
54
+ * including the answer's sentences and verbatim quotes from source
55
+ * documents — customer content — and the generated pagination/`ById`
56
+ * surface's cross-tenant read scoping is not verified here, so this table
57
+ * is kept off the auto-CRUD generator until it is. Same shape as
58
+ * `workflowTriggersSchema` below.
59
+ *
60
+ * Because of that flag, registering this schema with `createSDL` is a
61
+ * deliberate NO-OP for the GraphQL surface: `createSDL` skips every table with
62
+ * `graphql: false` (src/graphql/schemas/index.ts, `if (table.graphql ===
63
+ * false) continue`), so a printed SDL contains no `claim_check` type at all.
64
+ * A `grep -c claim_check` over the SDL returning **zero is the expected
65
+ * result**, not a missing registration — the stage-3 plan asked for a non-zero
66
+ * count, which was never achievable. The registration exists so the table is
67
+ * created and migrated by the initdb path like every other core table.
68
+ *
69
+ * Row uniqueness is (session, message_id, user) — read-scoping is by
70
+ * (session, user), so a unique index on (session, message_id) alone would
71
+ * let two different users racing the same session uuid and message id
72
+ * collide on one row. A composite UNIQUE index on (session, message_id,
73
+ * user) is created in init-exulu-db.ts (the schema's `index` flag is
74
+ * informational only, same as `memoryUsagesSchema` in core-schema.ts) — it
75
+ * backs the real upsert in src/exulu/claim-check/store.ts, which is
76
+ * `onConflict(["session", "message_id", "user"]).merge()`, never a
77
+ * delete-then-insert: a row belonging to a different user can never
78
+ * conflict with, and therefore is never touched by, another user's write.
79
+ */
80
+ export const claimChecksSchema: ExuluTableDefinition = {
81
+ type: "claim_checks",
82
+ graphql: false,
83
+ name: {
84
+ plural: "claim_checks",
85
+ singular: "claim_check",
86
+ },
87
+ fields: [
88
+ {
89
+ name: "session",
90
+ type: "uuid",
91
+ },
92
+ {
93
+ name: "message_id",
94
+ type: "text",
95
+ },
96
+ {
97
+ name: "payload",
98
+ type: "json",
99
+ },
100
+ {
101
+ name: "score_label",
102
+ type: "enum",
103
+ enumValues: ["ok", "warn", "alert", "n/a"],
104
+ },
105
+ {
106
+ name: "user",
107
+ type: "number",
108
+ },
109
+ ],
110
+ }
111
+
41
112
  export const rolesSchema: ExuluTableDefinition = {
42
113
  type: "roles",
43
114
  name: {
package/ee/workers.ts CHANGED
@@ -10,6 +10,7 @@ import { ExuluStorage } from "@SRC/exulu/storage.ts";
10
10
  import type { ExuluAgent } from "@EXULU_TYPES/models/agent.ts";
11
11
  import type { ExuluQueueConfig } from "@EXULU_TYPES/queue-config.ts";
12
12
  import { getTableName, type ExuluContext } from "@SRC/exulu/context.ts";
13
+ import { refreshContextEmbeddersIfStale } from "@SRC/exulu/hydrate-embedders";
13
14
  import type { ExuluEval } from "@SRC/exulu/evals.ts";
14
15
  import type { ExuluTool } from "@SRC/exulu/tool.ts";
15
16
  import { resolveModel } from "@SRC/exulu/resolve-model.ts";
@@ -311,6 +312,21 @@ export const createWorkers = async (
311
312
  throw new Error(`Context ${data.context} not found in the registry.`);
312
313
  }
313
314
 
315
+ // A context whose embedder is configured in the database rather than
316
+ // declared in code (the framework-provided transcripts base, for one)
317
+ // only gets `embedder` set by hydrateContextEmbedders. This process
318
+ // builds its registry from code and hands it to createWorkers without
319
+ // hydrating, and createAndUpsertEmbeddings' only other caller already
320
+ // refreshes before use — so the embedder job is the one entry point
321
+ // that would otherwise read a context the override never reached, and
322
+ // reject its own queued job with "No embedder configured".
323
+ try {
324
+ await refreshContextEmbeddersIfStale(contexts);
325
+ } catch {
326
+ // Singleton not initialised (e.g. tests, early boot) — the embedder
327
+ // set at construction/boot-hydration still stands.
328
+ }
329
+
314
330
  if (!context.embedder) {
315
331
  throw new Error(`No embedder configured for context ${data.context}.`);
316
332
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@exulu/backend",
3
3
  "author": "Qventu B.V.",
4
- "version": "5.1.1",
4
+ "version": "5.2.0",
5
5
  "main": "./dist/index.js",
6
6
  "private": false,
7
7
  "publishConfig": {