@gmickel/gno 2.15.0 → 2.17.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 (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -1,10 +1,7 @@
1
1
  import type { ContextCapsuleV1 } from "../core/context-capsule";
2
2
  import type { ContextCapsuleVerification } from "../core/context-capsule-verification";
3
3
 
4
- import {
5
- contextCapsuleV1Schema,
6
- parseContextCapsuleV1,
7
- } from "../core/context-capsule";
4
+ import { parseContextCapsuleV1 } from "../core/context-capsule";
8
5
  import { sha256Text } from "../core/context-capsule-validation";
9
6
  import { contextCapsuleVerificationSchema } from "../core/context-capsule-verification";
10
7
  import {
@@ -131,17 +128,6 @@ const fencedCodeEnd = (answer: string, start: number): number => {
131
128
  return closing === -1 ? answer.length : closing + 3;
132
129
  };
133
130
 
134
- const assertCitationLimit = (answer: string): void => {
135
- CITATION_PATTERN.lastIndex = 0;
136
- let count = 0;
137
- for (const _match of answer.matchAll(CITATION_PATTERN)) {
138
- count += 1;
139
- if (count > MAX_CITATIONS) {
140
- throw new Error(`Citation limit exceeded (${MAX_CITATIONS})`);
141
- }
142
- }
143
- };
144
-
145
131
  const claimIdentity = (
146
132
  capsuleId: string,
147
133
  start: number,
@@ -275,67 +261,37 @@ const evidenceReference = (evidence: Evidence): ClaimEvidenceReference => ({
275
261
  passageHash: evidence.passageHash,
276
262
  });
277
263
 
278
- const citationsForClaim = (
279
- answer: string,
280
- claim: ClaimSpan,
281
- evidenceById: ReadonlyMap<string, Evidence>,
282
- freshness: FreshnessState
283
- ): { accepted: Evidence[]; rejected: RejectedCitation[] } => {
284
- const accepted = new Map<string, Evidence>();
285
- const rejected: RejectedCitation[] = [];
286
- CITATION_PATTERN.lastIndex = claim.start;
287
- for (const match of answer.matchAll(CITATION_PATTERN)) {
288
- const start = match.index;
289
- const end = start + match[0].length;
290
- if (start >= claim.end) break;
291
- if (start < claim.start) continue;
292
- const rawId = match[1] ?? "";
293
- const closed = match[2] === "]";
294
- const evidenceId = closed && SHA256_PATTERN.test(rawId) ? rawId : null;
295
- const evidence =
296
- evidenceId === null ? undefined : evidenceById.get(evidenceId);
297
- const reason =
298
- evidenceId === null
299
- ? "malformed_citation"
300
- : rejectedReason(evidence, freshness);
301
- if (reason) {
302
- rejected.push({
303
- marker: match[0],
304
- start,
305
- end,
306
- evidenceId,
307
- reason,
308
- });
309
- } else if (evidence) {
310
- accepted.set(evidence.evidenceId, evidence);
311
- }
312
- if (accepted.size + rejected.length > MAX_CITATIONS) {
313
- throw new Error(`Citation limit exceeded (${MAX_CITATIONS})`);
314
- }
264
+ const parseSemanticJudgmentsIndex = (
265
+ inputs: readonly unknown[]
266
+ ): Map<string, SemanticClaimJudgment[]> => {
267
+ const byClaimId = new Map<string, SemanticClaimJudgment[]>();
268
+ for (const input of inputs) {
269
+ const parsed = semanticClaimJudgmentSchema.safeParse(input);
270
+ if (!parsed.success) continue;
271
+ const list = byClaimId.get(parsed.data.claimId);
272
+ if (list) list.push(parsed.data);
273
+ else byClaimId.set(parsed.data.claimId, [parsed.data]);
315
274
  }
316
- return { accepted: [...accepted.values()], rejected };
275
+ return byClaimId;
317
276
  };
318
277
 
319
278
  const judgmentForClaim = (
320
279
  claim: ClaimSpan,
321
280
  acceptedIds: ReadonlySet<string>,
322
- inputs: readonly unknown[]
281
+ judgmentsByClaimId: ReadonlyMap<string, readonly SemanticClaimJudgment[]>
323
282
  ): SemanticClaimJudgment | null => {
324
- const matches: SemanticClaimJudgment[] = [];
325
- for (const input of inputs) {
326
- const parsed = semanticClaimJudgmentSchema.safeParse(input);
327
- if (
328
- parsed.success &&
329
- parsed.data.claimId === claim.claimId &&
330
- parsed.data.evidenceIds.every((id) => acceptedIds.has(id))
331
- ) {
332
- matches.push(parsed.data);
283
+ const candidates = judgmentsByClaimId.get(claim.claimId);
284
+ if (!candidates || candidates.length === 0) return null;
285
+ let matched: SemanticClaimJudgment | null = null;
286
+ for (const judgment of candidates) {
287
+ if (judgment.evidenceIds.every((id) => acceptedIds.has(id))) {
288
+ if (matched !== null) return null;
289
+ matched = judgment;
333
290
  }
334
291
  }
335
- return matches.length === 1 ? (matches[0] ?? null) : null;
292
+ return matched;
336
293
  };
337
294
 
338
- /** Straight or curly double-quoted spans of at least two words. */
339
295
  /**
340
296
  * Quotations by delimiter pair. A single quote opens only after the start, a
341
297
  * space or a bracket and closes only before the end, a space, punctuation or
@@ -348,6 +304,8 @@ const QUOTATION_PATTERNS = [
348
304
  /(?<=^|[\s([{])\u2018(.+?)\u2019(?=$|[\s.,;:!?)\]}])/g,
349
305
  ] as const;
350
306
 
307
+ const QUOTE_DELIMITER_PATTERN = /["'\u2018\u2019\u201C\u201D]/;
308
+
351
309
  /** Whitespace, quote style and case differences are not misquotes. */
352
310
  const normalizeQuoted = (text: string): string =>
353
311
  text
@@ -360,154 +318,291 @@ const normalizeQuoted = (text: string): string =>
360
318
 
361
319
  const quotesFoundInEvidence = (
362
320
  claimText: string,
363
- evidence: readonly Evidence[]
321
+ evidence: readonly Evidence[],
322
+ normalizedCache: Map<string, string>
364
323
  ): boolean => {
365
- const haystacks = evidence.map((item) => normalizeQuoted(item.text));
324
+ if (!QUOTE_DELIMITER_PATTERN.test(claimText)) return true;
325
+ let quotedSpans: string[] | null = null;
366
326
  for (const pattern of QUOTATION_PATTERNS) {
367
327
  for (const match of claimText.matchAll(pattern)) {
368
328
  // Closing punctuation inside a quote often ends the claim's sentence.
369
329
  const quoted = normalizeQuoted(match[1] ?? "").replace(/[.,;:!?]+$/, "");
370
330
  if (quoted === "") continue;
371
- if (!haystacks.some((text) => text.includes(quoted))) return false;
331
+ quotedSpans ??= [];
332
+ quotedSpans.push(quoted);
372
333
  }
373
334
  }
335
+ if (!quotedSpans) return true;
336
+ const haystacks = evidence.map((item) => {
337
+ let normalized = normalizedCache.get(item.evidenceId);
338
+ if (normalized === undefined) {
339
+ normalized = normalizeQuoted(item.text);
340
+ normalizedCache.set(item.evidenceId, normalized);
341
+ }
342
+ return normalized;
343
+ });
344
+ for (const quoted of quotedSpans) {
345
+ if (!haystacks.some((text) => text.includes(quoted))) return false;
346
+ }
374
347
  return true;
375
348
  };
376
349
 
377
- const verifyClaim = (
378
- answer: string,
379
- claim: ClaimSpan,
380
- evidenceById: ReadonlyMap<string, Evidence>,
381
- freshness: FreshnessState,
382
- judgments: readonly unknown[]
383
- ): VerifiedClaim => {
384
- const citations = citationsForClaim(answer, claim, evidenceById, freshness);
385
- const references = citations.accepted.map(evidenceReference);
386
- const acceptedIds = new Set(references.map((item) => item.evidenceId));
387
- const judgment = judgmentForClaim(claim, acceptedIds, judgments);
388
- if (references.length === 0) {
389
- return {
390
- ...claim,
391
- status: "insufficient",
392
- confidence: null,
393
- rationaleCode: "no_valid_evidence",
394
- verifierFingerprint: null,
395
- evidence: [],
396
- rejectedCitations: citations.rejected,
397
- };
398
- }
399
- // An explicit quotation must appear in the cited evidence; the semantic
400
- // judgment cannot vouch for wording it never compared.
401
- if (!quotesFoundInEvidence(claim.text, citations.accepted)) {
402
- return {
403
- ...claim,
404
- status: "uncertain",
405
- confidence: null,
406
- rationaleCode: "quote_not_in_evidence",
407
- verifierFingerprint: null,
408
- evidence: references,
409
- rejectedCitations: citations.rejected,
410
- };
411
- }
412
- if (!judgment) {
413
- return {
414
- ...claim,
415
- status: "uncertain",
416
- confidence: null,
417
- rationaleCode: "semantic_judgment_unavailable",
418
- verifierFingerprint: null,
419
- evidence: references,
420
- rejectedCitations: citations.rejected,
421
- };
422
- }
423
- const selected = new Set(judgment.evidenceIds);
424
- return {
425
- ...claim,
426
- status: judgment.verdict,
427
- confidence: judgment.confidence,
428
- rationaleCode: judgment.rationaleCode,
429
- verifierFingerprint: judgment.verifierFingerprint,
430
- evidence: references.filter((item) => selected.has(item.evidenceId)),
431
- rejectedCitations: citations.rejected,
432
- };
433
- };
350
+ interface PreparedClaim {
351
+ claim: ClaimSpan;
352
+ references: ClaimEvidenceReference[];
353
+ acceptedIds: Set<string>;
354
+ rejectedCitations: RejectedCitation[];
355
+ quotesValid: boolean;
356
+ }
434
357
 
435
- const orphanCitations = (
436
- answer: string,
437
- claims: readonly ClaimSpan[],
438
- evidenceById: ReadonlyMap<string, Evidence>,
439
- freshness: FreshnessState
440
- ): RejectedCitation[] => {
441
- const rejected: RejectedCitation[] = [];
358
+ export interface PreparedClaimVerification {
359
+ capsuleId: string;
360
+ answerHash: string;
361
+ claims: PreparedClaim[];
362
+ rejectedCitations: RejectedCitation[];
363
+ }
364
+
365
+ /**
366
+ * Run deterministic capsule parsing, claim segmentation, single-pass two-pointer
367
+ * citation attribution, and quote checking once so semantic verifiers can apply
368
+ * judgments without repeating deterministic work.
369
+ */
370
+ export const prepareClaimVerification = (
371
+ input: Omit<VerifyClaimsInput, "semanticJudgments">
372
+ ): PreparedClaimVerification => {
373
+ const capsule = parseContextCapsuleV1(input.capsule);
374
+ // Single pass over CITATION_PATTERN enforces MAX_CITATIONS before claim
375
+ // segmentation (preserving exact error priority), then attributes claim and
376
+ // orphan citations via a two-pointer sweep over sorted non-overlapping claims.
442
377
  CITATION_PATTERN.lastIndex = 0;
443
- for (const match of answer.matchAll(CITATION_PATTERN)) {
444
- const start = match.index;
445
- const end = start + match[0].length;
446
- if (claims.some((claim) => start >= claim.start && start < claim.end)) {
447
- continue;
378
+ const rawCitations: Array<{
379
+ marker: string;
380
+ start: number;
381
+ end: number;
382
+ evidenceId: string | null;
383
+ }> = [];
384
+ for (const match of input.answer.matchAll(CITATION_PATTERN)) {
385
+ if (rawCitations.length >= MAX_CITATIONS) {
386
+ throw new Error(`Citation limit exceeded (${MAX_CITATIONS})`);
448
387
  }
388
+ const start = match.index;
449
389
  const rawId = match[1] ?? "";
450
- const evidenceId =
451
- match[2] === "]" && SHA256_PATTERN.test(rawId) ? rawId : null;
452
- const evidence =
453
- evidenceId === null ? undefined : evidenceById.get(evidenceId);
454
- rejected.push({
390
+ rawCitations.push({
455
391
  marker: match[0],
456
392
  start,
457
- end,
458
- evidenceId,
459
- reason:
393
+ end: start + match[0].length,
394
+ evidenceId: match[2] === "]" && SHA256_PATTERN.test(rawId) ? rawId : null,
395
+ });
396
+ }
397
+ const claims = segmentSubstantiveClaims(input.answer, capsule.capsuleId);
398
+ const freshness = freshnessState(capsule, input.freshness);
399
+ const evidenceById = new Map(
400
+ capsule.evidence.map((evidence) => [evidence.evidenceId, evidence])
401
+ );
402
+ const perClaimAccepted: Map<string, Evidence>[] = claims.map(() => new Map());
403
+ const perClaimRejected: RejectedCitation[][] = claims.map(() => []);
404
+ const orphanRejected: RejectedCitation[] = [];
405
+ const boundaryAffectedClaims = new Set<number>();
406
+
407
+ let claimIdx = 0;
408
+ for (const citation of rawCitations) {
409
+ const { marker, start, end, evidenceId } = citation;
410
+ while (claimIdx < claims.length && claims[claimIdx]!.end <= start) {
411
+ claimIdx += 1;
412
+ }
413
+ const evidence =
414
+ evidenceId === null ? undefined : evidenceById.get(evidenceId);
415
+ const inClaim =
416
+ claimIdx < claims.length &&
417
+ start >= claims[claimIdx]!.start &&
418
+ start < claims[claimIdx]!.end;
419
+ if (inClaim) {
420
+ if (end > claims[claimIdx]!.end) {
421
+ // A malformed marker spanning past this claim's boundary could swallow
422
+ // markers in this or subsequent claims; re-scan affected claim slices locally.
423
+ for (
424
+ let k = claimIdx;
425
+ k < claims.length && claims[k]!.start < end;
426
+ k++
427
+ ) {
428
+ boundaryAffectedClaims.add(k);
429
+ }
430
+ } else {
431
+ const reason =
432
+ evidenceId === null
433
+ ? "malformed_citation"
434
+ : rejectedReason(evidence, freshness);
435
+ if (reason) {
436
+ perClaimRejected[claimIdx]!.push({
437
+ marker,
438
+ start,
439
+ end,
440
+ evidenceId,
441
+ reason,
442
+ });
443
+ } else if (evidence) {
444
+ perClaimAccepted[claimIdx]!.set(evidence.evidenceId, evidence);
445
+ }
446
+ }
447
+ } else {
448
+ orphanRejected.push({
449
+ marker,
450
+ start,
451
+ end,
452
+ evidenceId,
453
+ reason:
454
+ evidenceId === null
455
+ ? "malformed_citation"
456
+ : (rejectedReason(evidence, freshness) ?? "orphan_citation"),
457
+ });
458
+ // If an orphan malformed span extends into subsequent claims, re-scan
459
+ // those claim slices locally so valid citations inside them are preserved.
460
+ if (claimIdx < claims.length && end > claims[claimIdx]!.start) {
461
+ for (
462
+ let k = claimIdx;
463
+ k < claims.length && claims[k]!.start < end;
464
+ k++
465
+ ) {
466
+ boundaryAffectedClaims.add(k);
467
+ }
468
+ }
469
+ }
470
+ }
471
+
472
+ for (const idx of boundaryAffectedClaims) {
473
+ const claim = claims[idx]!;
474
+ perClaimAccepted[idx]!.clear();
475
+ perClaimRejected[idx]!.length = 0;
476
+ CITATION_PATTERN.lastIndex = 0;
477
+ for (const match of claim.text.matchAll(CITATION_PATTERN)) {
478
+ const start = claim.start + match.index;
479
+ const end = start + match[0].length;
480
+ const rawId = match[1] ?? "";
481
+ const evidenceId =
482
+ match[2] === "]" && SHA256_PATTERN.test(rawId) ? rawId : null;
483
+ const evidence =
484
+ evidenceId === null ? undefined : evidenceById.get(evidenceId);
485
+ const reason =
460
486
  evidenceId === null
461
487
  ? "malformed_citation"
462
- : (rejectedReason(evidence, freshness) ?? "orphan_citation"),
463
- });
464
- if (rejected.length > MAX_CITATIONS) {
465
- throw new Error(`Citation limit exceeded (${MAX_CITATIONS})`);
488
+ : rejectedReason(evidence, freshness);
489
+ if (reason) {
490
+ perClaimRejected[idx]!.push({
491
+ marker: match[0],
492
+ start,
493
+ end,
494
+ evidenceId,
495
+ reason,
496
+ });
497
+ } else if (evidence) {
498
+ perClaimAccepted[idx]!.set(evidence.evidenceId, evidence);
499
+ }
466
500
  }
467
501
  }
468
- return rejected;
502
+
503
+ const normalizedEvidenceCache = new Map<string, string>();
504
+ const preparedClaims: PreparedClaim[] = claims.map((claim, index) => {
505
+ const accepted = [...perClaimAccepted[index]!.values()];
506
+ const references = accepted.map(evidenceReference);
507
+ const acceptedIds = new Set(references.map((item) => item.evidenceId));
508
+ const quotesValid =
509
+ references.length === 0
510
+ ? true
511
+ : quotesFoundInEvidence(claim.text, accepted, normalizedEvidenceCache);
512
+ return {
513
+ claim,
514
+ references,
515
+ acceptedIds,
516
+ rejectedCitations: perClaimRejected[index]!,
517
+ quotesValid,
518
+ };
519
+ });
520
+
521
+ return {
522
+ capsuleId: capsule.capsuleId,
523
+ answerHash: sha256Text(input.answer),
524
+ claims: preparedClaims,
525
+ rejectedCitations: orphanRejected,
526
+ };
469
527
  };
470
528
 
471
- export const verifyClaimsDeterministically = (
472
- input: VerifyClaimsInput
529
+ export const applySemanticJudgments = (
530
+ prepared: PreparedClaimVerification,
531
+ semanticJudgments: readonly unknown[] = []
473
532
  ): ClaimVerificationResult => {
474
- if ((input.semanticJudgments?.length ?? 0) > MAX_CLAIMS) {
533
+ if (semanticJudgments.length > MAX_CLAIMS) {
475
534
  throw new Error(`Semantic judgment limit exceeded (${MAX_CLAIMS})`);
476
535
  }
477
- const capsule = parseContextCapsuleV1(input.capsule);
478
- // A second strict parse makes the identity and nested contract requirement
479
- // explicit at this pipeline boundary.
480
- contextCapsuleV1Schema.parse(capsule);
481
- assertCitationLimit(input.answer);
482
- const claims = segmentSubstantiveClaims(input.answer, capsule.capsuleId);
483
- const freshness = freshnessState(capsule, input.freshness);
484
- const evidenceById = new Map(
485
- capsule.evidence.map((evidence) => [evidence.evidenceId, evidence])
486
- );
487
- const verifiedClaims = claims.map((claim) =>
488
- verifyClaim(
489
- input.answer,
490
- claim,
491
- evidenceById,
492
- freshness,
493
- input.semanticJudgments ?? []
494
- )
495
- );
496
- const rejectedCitations = orphanCitations(
497
- input.answer,
498
- claims,
499
- evidenceById,
500
- freshness
501
- );
502
- const count = (status: ClaimVerificationStatus): number =>
503
- verifiedClaims.filter((claim) => claim.status === status).length;
504
- const supportedClaims = count("supported");
536
+ const judgmentsByClaimId = parseSemanticJudgmentsIndex(semanticJudgments);
537
+ const verifiedClaims: VerifiedClaim[] = prepared.claims.map((entry) => {
538
+ const { claim, references, acceptedIds, rejectedCitations, quotesValid } =
539
+ entry;
540
+ if (references.length === 0) {
541
+ return {
542
+ ...claim,
543
+ status: "insufficient",
544
+ confidence: null,
545
+ rationaleCode: "no_valid_evidence",
546
+ verifierFingerprint: null,
547
+ evidence: [],
548
+ rejectedCitations,
549
+ };
550
+ }
551
+ // An explicit quotation must appear in the cited evidence; the semantic
552
+ // judgment cannot vouch for wording it never compared.
553
+ if (!quotesValid) {
554
+ return {
555
+ ...claim,
556
+ status: "uncertain",
557
+ confidence: null,
558
+ rationaleCode: "quote_not_in_evidence",
559
+ verifierFingerprint: null,
560
+ evidence: references,
561
+ rejectedCitations,
562
+ };
563
+ }
564
+ const judgment = judgmentForClaim(claim, acceptedIds, judgmentsByClaimId);
565
+ if (!judgment) {
566
+ return {
567
+ ...claim,
568
+ status: "uncertain",
569
+ confidence: null,
570
+ rationaleCode: "semantic_judgment_unavailable",
571
+ verifierFingerprint: null,
572
+ evidence: references,
573
+ rejectedCitations,
574
+ };
575
+ }
576
+ const selected = new Set(judgment.evidenceIds);
577
+ return {
578
+ ...claim,
579
+ status: judgment.verdict,
580
+ confidence: judgment.confidence,
581
+ rationaleCode: judgment.rationaleCode,
582
+ verifierFingerprint: judgment.verifierFingerprint,
583
+ evidence: references.filter((item) => selected.has(item.evidenceId)),
584
+ rejectedCitations,
585
+ };
586
+ });
587
+
588
+ let supportedClaims = 0;
589
+ let contradictedClaims = 0;
590
+ let insufficientClaims = 0;
591
+ let uncertainClaims = 0;
592
+ let anyClaimRejected = false;
593
+ for (const claim of verifiedClaims) {
594
+ if (claim.status === "supported") supportedClaims += 1;
595
+ else if (claim.status === "contradicted") contradictedClaims += 1;
596
+ else if (claim.status === "insufficient") insufficientClaims += 1;
597
+ else uncertainClaims += 1;
598
+ if (claim.rejectedCitations.length > 0) anyClaimRejected = true;
599
+ }
505
600
  const coverage = {
506
601
  totalClaims: verifiedClaims.length,
507
602
  supportedClaims,
508
- contradictedClaims: count("contradicted"),
509
- insufficientClaims: count("insufficient"),
510
- uncertainClaims: count("uncertain"),
603
+ contradictedClaims,
604
+ insufficientClaims,
605
+ uncertainClaims,
511
606
  supportedRatio:
512
607
  verifiedClaims.length === 0 ? 0 : supportedClaims / verifiedClaims.length,
513
608
  };
@@ -516,8 +611,7 @@ export const verifyClaimsDeterministically = (
516
611
  ? "no_substantive_claims"
517
612
  : coverage.contradictedClaims > 0
518
613
  ? "contradiction_detected"
519
- : rejectedCitations.length > 0 ||
520
- verifiedClaims.some((claim) => claim.rejectedCitations.length > 0)
614
+ : prepared.rejectedCitations.length > 0 || anyClaimRejected
521
615
  ? "citation_hygiene_failed"
522
616
  : coverage.supportedRatio < COVERAGE_THRESHOLD
523
617
  ? "coverage_below_threshold"
@@ -526,11 +620,11 @@ export const verifyClaimsDeterministically = (
526
620
  return claimVerificationResultSchema.parse({
527
621
  schemaVersion: CLAIM_VERIFICATION_SCHEMA_VERSION,
528
622
  coordinateSpace: CLAIM_COORDINATE_SPACE,
529
- capsuleId: capsule.capsuleId,
530
- answerHash: sha256Text(input.answer),
623
+ capsuleId: prepared.capsuleId,
624
+ answerHash: prepared.answerHash,
531
625
  coverageThreshold: COVERAGE_THRESHOLD,
532
626
  claims: verifiedClaims,
533
- rejectedCitations,
627
+ rejectedCitations: prepared.rejectedCitations,
534
628
  coverage,
535
629
  answerStatus: abstained ? "abstained" : "verified",
536
630
  abstained,
@@ -538,3 +632,13 @@ export const verifyClaimsDeterministically = (
538
632
  abstentionText: abstained ? CLAIM_ABSTENTION_TEXT : null,
539
633
  });
540
634
  };
635
+
636
+ export const verifyClaimsDeterministically = (
637
+ input: VerifyClaimsInput
638
+ ): ClaimVerificationResult => {
639
+ if ((input.semanticJudgments?.length ?? 0) > MAX_CLAIMS) {
640
+ throw new Error(`Semantic judgment limit exceeded (${MAX_CLAIMS})`);
641
+ }
642
+ const prepared = prepareClaimVerification(input);
643
+ return applySemanticJudgments(prepared, input.semanticJudgments ?? []);
644
+ };
@@ -13,8 +13,9 @@ import {
13
13
  assertInferenceResult,
14
14
  } from "../llm/inference-scope";
15
15
  import {
16
+ applySemanticJudgments,
17
+ prepareClaimVerification,
16
18
  semanticClaimJudgmentSchema,
17
- verifyClaimsDeterministically,
18
19
  } from "./claim-verification";
19
20
 
20
21
  const SHA256_PATTERN = /^[a-f0-9]{64}$/;
@@ -317,7 +318,8 @@ export const verifyClaimsSemantically = async (
317
318
  }
318
319
  const now = input.now ?? performance.now.bind(performance);
319
320
  const startedAt = now();
320
- const deterministic = verifyClaimsDeterministically(input);
321
+ const prepared = prepareClaimVerification(input);
322
+ const deterministic = applySemanticJudgments(prepared, []);
321
323
  const candidates = candidateClaims(deterministic);
322
324
  const modelFingerprint = input.genPort
323
325
  ? sha256Text(input.genPort.modelUri)
@@ -402,7 +404,7 @@ export const verifyClaimsSemantically = async (
402
404
  deterministic.answerHash,
403
405
  candidates
404
406
  );
405
- if (new TextEncoder().encode(prompt).byteLength > MAX_PROMPT_BYTES) {
407
+ if (Buffer.byteLength(prompt, "utf8") > MAX_PROMPT_BYTES) {
406
408
  return failedResult(
407
409
  deterministic,
408
410
  "input_limit_exceeded",
@@ -453,10 +455,7 @@ export const verifyClaimsSemantically = async (
453
455
  verifierFingerprint
454
456
  );
455
457
  }
456
- const verification = verifyClaimsDeterministically({
457
- ...input,
458
- semanticJudgments: envelope.judgments,
459
- });
458
+ const verification = applySemanticJudgments(prepared, envelope.judgments);
460
459
  return {
461
460
  verification,
462
461
  semanticVerification: capability(