claude-memory-layer 1.0.31 → 1.0.33

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 (343) hide show
  1. package/README.md +9 -2
  2. package/dist/cli/index.js +1110 -72
  3. package/dist/cli/index.js.map +4 -4
  4. package/dist/core/index.js +414 -25
  5. package/dist/core/index.js.map +2 -2
  6. package/dist/hooks/post-tool-use.js +416 -27
  7. package/dist/hooks/post-tool-use.js.map +2 -2
  8. package/dist/hooks/semantic-daemon.js +416 -27
  9. package/dist/hooks/semantic-daemon.js.map +2 -2
  10. package/dist/hooks/session-end.js +416 -27
  11. package/dist/hooks/session-end.js.map +2 -2
  12. package/dist/hooks/session-start.js +416 -27
  13. package/dist/hooks/session-start.js.map +2 -2
  14. package/dist/hooks/stop.js +416 -27
  15. package/dist/hooks/stop.js.map +2 -2
  16. package/dist/hooks/user-prompt-submit.js +504 -34
  17. package/dist/hooks/user-prompt-submit.js.map +2 -2
  18. package/dist/index.js +416 -27
  19. package/dist/index.js.map +2 -2
  20. package/dist/mcp/index.js +407 -32
  21. package/dist/mcp/index.js.map +2 -2
  22. package/dist/server/api/index.js +850 -44
  23. package/dist/server/api/index.js.map +3 -3
  24. package/dist/server/index.js +1073 -64
  25. package/dist/server/index.js.map +3 -3
  26. package/dist/services/memory-service.js +416 -27
  27. package/dist/services/memory-service.js.map +2 -2
  28. package/dist/ui/assets/js/bootstrap.js +2 -0
  29. package/dist/ui/assets/js/overview.js +166 -3
  30. package/dist/ui/assets/js/state.js +3 -0
  31. package/dist/ui/index.html +20 -0
  32. package/dist/ui/style.css +193 -0
  33. package/package.json +15 -2
  34. package/scripts/postinstall-embedding-backend.cjs +16 -12
  35. package/AGENTS.md +0 -71
  36. package/CLAUDE.md +0 -30
  37. package/HANDOFF.md +0 -92
  38. package/Memo.txt +0 -558
  39. package/benchmarks/replay/anonymized-real-sessions.json +0 -48
  40. package/config/kpi-thresholds.json +0 -7
  41. package/context.md +0 -636
  42. package/docs/ARCHITECTURE_COMPARISON_AND_RECOMMENDATIONS.md +0 -627
  43. package/docs/HERMES_MEMORY_INGESTION_ANALYSIS.md +0 -440
  44. package/docs/MCP_MEMORY_SERVICE_COMPARATIVE_REVIEW.md +0 -271
  45. package/docs/MEMORY_USEFULNESS_AUDIT.md +0 -371
  46. package/docs/MEMORY_USEFULNESS_AUDIT_RAW.json +0 -80
  47. package/docs/MEMSEARCH_PROJECT_STRUCTURE_ANALYSIS.md +0 -333
  48. package/docs/MEMU_ADOPTION.md +0 -40
  49. package/docs/OPERATIONS.md +0 -18
  50. package/docs/PRODUCT_VALIDATION_MATRIX.md +0 -82
  51. package/docs/PROJECT_STRUCTURE_ANALYSIS.md +0 -421
  52. package/docs/REFACTORING_MILESTONES_AND_ISSUES.md +0 -501
  53. package/docs/REFACTORING_PLAN_THIN_CORE.md +0 -414
  54. package/docs/REFERENCE_PROJECT_ANALYSES.md +0 -25
  55. package/docs/SUPERLOCALMEMORY_PROJECT_STRUCTURE_ANALYSIS.md +0 -452
  56. package/docs/TARGET_ARCHITECTURE_AND_FOLDER_STRUCTURE.md +0 -446
  57. package/docs/architecture/comparison-index.md +0 -47
  58. package/docs/reports/codex-real-data-validation-20260505T040447Z.md +0 -46
  59. package/plan.md +0 -1642
  60. package/scripts/build.ts +0 -159
  61. package/scripts/bump-patch-version.sh +0 -18
  62. package/scripts/delete-unknown-projects.js +0 -154
  63. package/scripts/fix-sync-gap.js +0 -32
  64. package/scripts/generate-session-qrels.ts +0 -126
  65. package/scripts/heartbeat-memory-orchestrator.sh +0 -28
  66. package/scripts/replay-retrieval-benchmark.ts +0 -69
  67. package/scripts/report-sync-gap.js +0 -26
  68. package/scripts/review-queue-auto-resolve.js +0 -21
  69. package/scripts/sync-gap-auto-heal.sh +0 -17
  70. package/spec.md +0 -624
  71. package/specs/20260207-dashboard-upgrade/context.md +0 -38
  72. package/specs/20260207-dashboard-upgrade/spec.md +0 -96
  73. package/specs/citations-system/context.md +0 -243
  74. package/specs/citations-system/plan.md +0 -495
  75. package/specs/citations-system/spec.md +0 -371
  76. package/specs/endless-mode/context.md +0 -305
  77. package/specs/endless-mode/plan.md +0 -620
  78. package/specs/endless-mode/spec.md +0 -455
  79. package/specs/entity-edge-model/context.md +0 -401
  80. package/specs/entity-edge-model/plan.md +0 -459
  81. package/specs/entity-edge-model/spec.md +0 -391
  82. package/specs/evidence-aligner-v2/context.md +0 -401
  83. package/specs/evidence-aligner-v2/plan.md +0 -303
  84. package/specs/evidence-aligner-v2/spec.md +0 -312
  85. package/specs/mcp-desktop-integration/context.md +0 -278
  86. package/specs/mcp-desktop-integration/plan.md +0 -550
  87. package/specs/mcp-desktop-integration/spec.md +0 -494
  88. package/specs/memory-utilization-improvements/context.md +0 -145
  89. package/specs/memory-utilization-improvements/plan.md +0 -361
  90. package/specs/memory-utilization-improvements/spec.md +0 -361
  91. package/specs/post-tool-use-hook/context.md +0 -319
  92. package/specs/post-tool-use-hook/plan.md +0 -469
  93. package/specs/post-tool-use-hook/spec.md +0 -364
  94. package/specs/private-tags/context.md +0 -288
  95. package/specs/private-tags/plan.md +0 -412
  96. package/specs/private-tags/spec.md +0 -345
  97. package/specs/progressive-disclosure/context.md +0 -346
  98. package/specs/progressive-disclosure/plan.md +0 -663
  99. package/specs/progressive-disclosure/spec.md +0 -415
  100. package/specs/selective-tool-observation/context.md +0 -100
  101. package/specs/selective-tool-observation/plan.md +0 -158
  102. package/specs/selective-tool-observation/spec.md +0 -127
  103. package/specs/task-entity-system/context.md +0 -297
  104. package/specs/task-entity-system/plan.md +0 -301
  105. package/specs/task-entity-system/spec.md +0 -314
  106. package/specs/thin-core-refactor/context.md +0 -275
  107. package/specs/thin-core-refactor/plan.md +0 -536
  108. package/specs/thin-core-refactor/spec.md +0 -465
  109. package/specs/vector-outbox-v2/context.md +0 -470
  110. package/specs/vector-outbox-v2/plan.md +0 -562
  111. package/specs/vector-outbox-v2/spec.md +0 -466
  112. package/specs/web-viewer-ui/context.md +0 -384
  113. package/specs/web-viewer-ui/plan.md +0 -797
  114. package/specs/web-viewer-ui/spec.md +0 -516
  115. package/src/adapters/claude/capture/index.ts +0 -3
  116. package/src/adapters/claude/context/index.ts +0 -3
  117. package/src/adapters/claude/hooks/index.ts +0 -21
  118. package/src/adapters/claude/hooks/post-tool-use.ts +0 -239
  119. package/src/adapters/claude/hooks/prompt-injection-policy.ts +0 -104
  120. package/src/adapters/claude/hooks/semantic-daemon-client.ts +0 -209
  121. package/src/adapters/claude/hooks/semantic-daemon.ts +0 -283
  122. package/src/adapters/claude/hooks/session-end.ts +0 -59
  123. package/src/adapters/claude/hooks/session-start.ts +0 -73
  124. package/src/adapters/claude/hooks/stop.ts +0 -128
  125. package/src/adapters/claude/hooks/user-prompt-submit.ts +0 -361
  126. package/src/adapters/claude/index.ts +0 -4
  127. package/src/adapters/claude/transcript/index.ts +0 -4
  128. package/src/adapters/claude/transcript/transcript-reader.ts +0 -57
  129. package/src/adapters/claude/transcript/turn-reconstructor.ts +0 -65
  130. package/src/apps/cli/claude-settings-hooks.ts +0 -138
  131. package/src/apps/cli/codex-import-runner.ts +0 -125
  132. package/src/apps/cli/codex-validation-output.ts +0 -95
  133. package/src/apps/cli/hermes-import-runner.ts +0 -130
  134. package/src/apps/cli/hermes-validation-output.ts +0 -91
  135. package/src/apps/cli/index.ts +0 -1735
  136. package/src/apps/cli/mcp-install.ts +0 -106
  137. package/src/apps/cli/retrieval-disclosure-output.ts +0 -196
  138. package/src/apps/dashboard/assets/js/bootstrap.js +0 -244
  139. package/src/apps/dashboard/assets/js/chat.js +0 -373
  140. package/src/apps/dashboard/assets/js/disclosure.js +0 -232
  141. package/src/apps/dashboard/assets/js/modals.js +0 -298
  142. package/src/apps/dashboard/assets/js/overview.js +0 -655
  143. package/src/apps/dashboard/assets/js/state.js +0 -72
  144. package/src/apps/dashboard/assets/js/views.js +0 -468
  145. package/src/apps/dashboard/index.html +0 -543
  146. package/src/apps/dashboard/index.ts +0 -3
  147. package/src/apps/dashboard/style.css +0 -1750
  148. package/src/apps/index.ts +0 -5
  149. package/src/apps/server/api/chat.ts +0 -244
  150. package/src/apps/server/api/citations.ts +0 -105
  151. package/src/apps/server/api/events.ts +0 -137
  152. package/src/apps/server/api/health.ts +0 -53
  153. package/src/apps/server/api/index.ts +0 -26
  154. package/src/apps/server/api/projects.ts +0 -74
  155. package/src/apps/server/api/search.ts +0 -184
  156. package/src/apps/server/api/sessions.ts +0 -115
  157. package/src/apps/server/api/stats.ts +0 -723
  158. package/src/apps/server/api/turns.ts +0 -143
  159. package/src/apps/server/api/utils.ts +0 -65
  160. package/src/apps/server/index.ts +0 -111
  161. package/src/cli/index.ts +0 -3
  162. package/src/cli/retrieval-disclosure-output.ts +0 -2
  163. package/src/compat/index.ts +0 -5
  164. package/src/core/canonical-key.ts +0 -186
  165. package/src/core/citation-generator.ts +0 -63
  166. package/src/core/consolidated-store.ts +0 -356
  167. package/src/core/consolidation-worker.ts +0 -493
  168. package/src/core/context-formatter.ts +0 -276
  169. package/src/core/continuity-manager.ts +0 -341
  170. package/src/core/db-wrapper.ts +0 -64
  171. package/src/core/derive/fact-deriver.ts +0 -170
  172. package/src/core/derive/index.ts +0 -2
  173. package/src/core/derive/summary-deriver.ts +0 -76
  174. package/src/core/edge-repo.ts +0 -333
  175. package/src/core/embedder.ts +0 -4
  176. package/src/core/engine/embedding-maintenance-service.ts +0 -187
  177. package/src/core/engine/endless-memory-services.ts +0 -4
  178. package/src/core/engine/index.ts +0 -19
  179. package/src/core/engine/memory-engine-services.ts +0 -170
  180. package/src/core/engine/memory-ingest-service.ts +0 -317
  181. package/src/core/engine/memory-query-service.ts +0 -173
  182. package/src/core/engine/memory-runtime-service.ts +0 -162
  183. package/src/core/engine/memory-service-composition.ts +0 -231
  184. package/src/core/engine/retrieval-analytics-service.ts +0 -181
  185. package/src/core/engine/retrieval-disclosure-service.ts +0 -420
  186. package/src/core/engine/retrieval-orchestrator.ts +0 -377
  187. package/src/core/engine/retrieval-services.ts +0 -176
  188. package/src/core/engine/shared-memory-services.ts +0 -4
  189. package/src/core/entity-repo.ts +0 -349
  190. package/src/core/event-store.ts +0 -779
  191. package/src/core/evidence-aligner.ts +0 -635
  192. package/src/core/external-market-context.ts +0 -582
  193. package/src/core/graduation-worker.ts +0 -171
  194. package/src/core/graduation.ts +0 -377
  195. package/src/core/index.ts +0 -64
  196. package/src/core/ingest-interceptor.ts +0 -80
  197. package/src/core/markdown-mirror.ts +0 -70
  198. package/src/core/matcher.ts +0 -208
  199. package/src/core/md-mirror.ts +0 -92
  200. package/src/core/metadata-extractor.ts +0 -203
  201. package/src/core/model/memory-fact.ts +0 -30
  202. package/src/core/model/memory-rule.ts +0 -14
  203. package/src/core/model/memory-summary.ts +0 -21
  204. package/src/core/model/raw-event.ts +0 -28
  205. package/src/core/model/retrieval-result.ts +0 -35
  206. package/src/core/mongo-sync-config.ts +0 -165
  207. package/src/core/mongo-sync-worker.ts +0 -381
  208. package/src/core/privacy/filter.ts +0 -190
  209. package/src/core/privacy/index.ts +0 -20
  210. package/src/core/privacy/tag-parser.ts +0 -145
  211. package/src/core/product-validation-matrix.ts +0 -314
  212. package/src/core/progressive-retriever.ts +0 -414
  213. package/src/core/registry/project-path.ts +0 -54
  214. package/src/core/registry/session-registry.ts +0 -69
  215. package/src/core/replay-evaluator.ts +0 -625
  216. package/src/core/retrieval-benchmark.ts +0 -117
  217. package/src/core/retrieval-quality.ts +0 -109
  218. package/src/core/retriever.ts +0 -800
  219. package/src/core/session-qrels.ts +0 -360
  220. package/src/core/shared-event-store.ts +0 -114
  221. package/src/core/shared-promoter.ts +0 -249
  222. package/src/core/shared-store.ts +0 -289
  223. package/src/core/shared-vector-store.ts +0 -203
  224. package/src/core/sqlite-event-store.ts +0 -1846
  225. package/src/core/sqlite-wrapper.ts +0 -116
  226. package/src/core/sync-worker.ts +0 -228
  227. package/src/core/tag-taxonomy.ts +0 -51
  228. package/src/core/task/blocker-resolver.ts +0 -333
  229. package/src/core/task/index.ts +0 -9
  230. package/src/core/task/task-matcher.ts +0 -240
  231. package/src/core/task/task-projector.ts +0 -358
  232. package/src/core/task/task-resolver.ts +0 -421
  233. package/src/core/turn-state.ts +0 -207
  234. package/src/core/types.ts +0 -952
  235. package/src/core/vector-outbox.ts +0 -299
  236. package/src/core/vector-store.ts +0 -231
  237. package/src/core/vector-worker.ts +0 -521
  238. package/src/core/working-set-store.ts +0 -257
  239. package/src/extensions/endless-memory/endless-memory-services.ts +0 -350
  240. package/src/extensions/endless-memory/index.ts +0 -1
  241. package/src/extensions/index.ts +0 -5
  242. package/src/extensions/mcp/handlers.ts +0 -960
  243. package/src/extensions/mcp/index.ts +0 -48
  244. package/src/extensions/mcp/tools.ts +0 -252
  245. package/src/extensions/shared-memory/index.ts +0 -1
  246. package/src/extensions/shared-memory/shared-memory-services.ts +0 -211
  247. package/src/extensions/vector/embedder.ts +0 -234
  248. package/src/extensions/vector/index.ts +0 -1
  249. package/src/hooks/post-tool-use.ts +0 -9
  250. package/src/hooks/semantic-daemon-client.ts +0 -1
  251. package/src/hooks/semantic-daemon.ts +0 -11
  252. package/src/hooks/session-end.ts +0 -9
  253. package/src/hooks/session-start.ts +0 -9
  254. package/src/hooks/stop.ts +0 -9
  255. package/src/hooks/user-prompt-submit.ts +0 -9
  256. package/src/index.ts +0 -13
  257. package/src/mcp/handlers.ts +0 -2
  258. package/src/mcp/index.ts +0 -4
  259. package/src/mcp/tools.ts +0 -2
  260. package/src/server/api/chat.ts +0 -2
  261. package/src/server/api/citations.ts +0 -2
  262. package/src/server/api/events.ts +0 -2
  263. package/src/server/api/health.ts +0 -2
  264. package/src/server/api/index.ts +0 -2
  265. package/src/server/api/projects.ts +0 -2
  266. package/src/server/api/search.ts +0 -2
  267. package/src/server/api/sessions.ts +0 -2
  268. package/src/server/api/stats.ts +0 -2
  269. package/src/server/api/turns.ts +0 -2
  270. package/src/server/api/utils.ts +0 -2
  271. package/src/server/index.ts +0 -2
  272. package/src/services/bootstrap-organizer.ts +0 -463
  273. package/src/services/codex-session-history-importer.ts +0 -966
  274. package/src/services/hermes-session-history-importer.ts +0 -733
  275. package/src/services/memory-service-config.ts +0 -36
  276. package/src/services/memory-service-registry.ts +0 -150
  277. package/src/services/memory-service.ts +0 -688
  278. package/src/services/session-history-importer.ts +0 -629
  279. package/tests/README.md +0 -23
  280. package/tests/adapters/claude/claude-semantic-daemon-adapter.test.ts +0 -54
  281. package/tests/adapters/claude/claude-transcript-reconstructor.test.ts +0 -98
  282. package/tests/adapters/claude-hook-prompt-injection-policy.test.ts +0 -99
  283. package/tests/apps/app-layer-boundary.test.ts +0 -48
  284. package/tests/apps/claude-settings-hooks.test.ts +0 -107
  285. package/tests/apps/cli-disclosure-output.test.ts +0 -212
  286. package/tests/apps/codex-import-runner.test.ts +0 -99
  287. package/tests/apps/codex-validation-output.test.ts +0 -100
  288. package/tests/apps/hermes-import-runner.test.ts +0 -99
  289. package/tests/apps/mcp-install-command.test.ts +0 -59
  290. package/tests/apps/package-build-entrypoints.test.ts +0 -30
  291. package/tests/apps/postinstall-embedding-backend.test.ts +0 -185
  292. package/tests/apps/search-api-disclosure.test.ts +0 -162
  293. package/tests/apps/stats-api-lightweight.test.ts +0 -67
  294. package/tests/apps/ui-disclosure-output.test.ts +0 -140
  295. package/tests/core/bootstrap-organizer.test.ts +0 -111
  296. package/tests/core/canonical-key.test.ts +0 -101
  297. package/tests/core/codex-session-history-importer-validation.test.ts +0 -185
  298. package/tests/core/consolidation-worker.test.ts +0 -75
  299. package/tests/core/embedding-maintenance-service.test.ts +0 -282
  300. package/tests/core/evidence-aligner.test.ts +0 -152
  301. package/tests/core/external-market-context.test.ts +0 -209
  302. package/tests/core/fact-deriver.test.ts +0 -79
  303. package/tests/core/hermes-session-history-importer-validation.test.ts +0 -609
  304. package/tests/core/ingest-interceptor.test.ts +0 -38
  305. package/tests/core/markdown-mirror.test.ts +0 -85
  306. package/tests/core/matcher.test.ts +0 -112
  307. package/tests/core/md-mirror.test.ts +0 -50
  308. package/tests/core/memory-engine-services.test.ts +0 -240
  309. package/tests/core/memory-ingest-service.test.ts +0 -296
  310. package/tests/core/memory-query-service.test.ts +0 -129
  311. package/tests/core/memory-runtime-service.test.ts +0 -201
  312. package/tests/core/memory-service-composition.test.ts +0 -192
  313. package/tests/core/memory-service-config.test.ts +0 -41
  314. package/tests/core/memory-service-facade.test.ts +0 -30
  315. package/tests/core/memory-service-registry.test.ts +0 -206
  316. package/tests/core/product-validation-matrix.test.ts +0 -61
  317. package/tests/core/project-registry.test.ts +0 -78
  318. package/tests/core/replay-evaluator.test.ts +0 -181
  319. package/tests/core/retrieval-analytics-service.test.ts +0 -210
  320. package/tests/core/retrieval-benchmark.test.ts +0 -93
  321. package/tests/core/retrieval-disclosure-service.test.ts +0 -264
  322. package/tests/core/retrieval-orchestrator.test.ts +0 -403
  323. package/tests/core/retrieval-quality.test.ts +0 -31
  324. package/tests/core/retrieval-services.test.ts +0 -185
  325. package/tests/core/retriever-fallback-chain.test.ts +0 -223
  326. package/tests/core/retriever-strategy-scope.test.ts +0 -164
  327. package/tests/core/retriever.memu-adoption.test.ts +0 -122
  328. package/tests/core/session-history-importer-filter.test.ts +0 -78
  329. package/tests/core/session-qrels.test.ts +0 -250
  330. package/tests/core/sqlite-event-store-replication.test.ts +0 -127
  331. package/tests/core/summary-deriver.test.ts +0 -66
  332. package/tests/extensions/embedder-warning-suppression.test.ts +0 -84
  333. package/tests/extensions/endless-memory-extension-boundary.test.ts +0 -17
  334. package/tests/extensions/endless-memory-services.test.ts +0 -325
  335. package/tests/extensions/mcp-context-tools.test.ts +0 -905
  336. package/tests/extensions/mcp-extension-boundary.test.ts +0 -21
  337. package/tests/extensions/mcp-package-build.test.ts +0 -22
  338. package/tests/extensions/mcp-project-aware-tools.test.ts +0 -102
  339. package/tests/extensions/shared-memory-extension-boundary.test.ts +0 -24
  340. package/tests/extensions/shared-memory-services.test.ts +0 -309
  341. package/tests/extensions/vector-extension-boundary.test.ts +0 -21
  342. package/tsconfig.json +0 -24
  343. package/vitest.config.ts +0 -15
@@ -1,635 +0,0 @@
1
- /**
2
- * Evidence Aligner V2 - AXIOMMIND Principle 4
3
- * Quote-only approach: LLM provides quote, pipeline calculates span
4
- * 3-step alignment: exact → normalized → fuzzy
5
- */
6
-
7
- import { createHash } from 'crypto';
8
- import type {
9
- EvidenceSpan,
10
- ExtractedEvidence,
11
- AlignedEvidence,
12
- FailedEvidence,
13
- EvidenceAlignResult
14
- } from './types.js';
15
-
16
- export interface AlignmentResult {
17
- isAligned: boolean;
18
- confidence: number;
19
- spans: EvidenceSpan[];
20
- missingClaims: string[];
21
- }
22
-
23
- export interface AlignmentOptions {
24
- minMatchLength: number;
25
- fuzzyThreshold: number;
26
- maxMissingClaims: number;
27
- }
28
-
29
- // V2 Options
30
- export interface AlignmentOptionsV2 {
31
- minMatchLength: number;
32
- exactMatchBonus: number;
33
- normalizedThreshold: number;
34
- fuzzyThreshold: number;
35
- maxMissingRatio: number;
36
- }
37
-
38
- const DEFAULT_OPTIONS: AlignmentOptions = {
39
- minMatchLength: 10,
40
- fuzzyThreshold: 0.8,
41
- maxMissingClaims: 2
42
- };
43
-
44
- const DEFAULT_OPTIONS_V2: AlignmentOptionsV2 = {
45
- minMatchLength: 5,
46
- exactMatchBonus: 1.0,
47
- normalizedThreshold: 0.95,
48
- fuzzyThreshold: 0.85,
49
- maxMissingRatio: 0.2
50
- };
51
-
52
- // V2 Alignment result for entries
53
- export interface AlignResultV2 {
54
- evidenceAligned: boolean;
55
- alignedCount: number;
56
- failedCount: number;
57
- results: EvidenceAlignResult[];
58
- overallConfidence: number;
59
- }
60
-
61
- export class EvidenceAligner {
62
- private readonly options: AlignmentOptions;
63
-
64
- constructor(options: Partial<AlignmentOptions> = {}) {
65
- this.options = { ...DEFAULT_OPTIONS, ...options };
66
- }
67
-
68
- /**
69
- * Align claims against source content
70
- * Returns evidence spans showing where claims are supported
71
- */
72
- align(claims: string[], sourceContent: string): AlignmentResult {
73
- const spans: EvidenceSpan[] = [];
74
- const missingClaims: string[] = [];
75
- const normalizedSource = this.normalize(sourceContent);
76
-
77
- for (const claim of claims) {
78
- const normalizedClaim = this.normalize(claim);
79
-
80
- // Skip very short claims
81
- if (normalizedClaim.length < this.options.minMatchLength) {
82
- continue;
83
- }
84
-
85
- // Try exact match first
86
- const exactSpan = this.findExactMatch(normalizedClaim, normalizedSource, sourceContent);
87
- if (exactSpan) {
88
- spans.push(exactSpan);
89
- continue;
90
- }
91
-
92
- // Try fuzzy match
93
- const fuzzySpan = this.findFuzzyMatch(normalizedClaim, normalizedSource, sourceContent);
94
- if (fuzzySpan && fuzzySpan.confidence >= this.options.fuzzyThreshold) {
95
- spans.push(fuzzySpan);
96
- continue;
97
- }
98
-
99
- // Claim not found in source
100
- missingClaims.push(claim);
101
- }
102
-
103
- // Calculate overall alignment confidence
104
- const totalClaims = claims.length;
105
- const alignedClaims = spans.length;
106
- const confidence = totalClaims > 0 ? alignedClaims / totalClaims : 1.0;
107
-
108
- // Alignment is valid if missing claims are within threshold
109
- const isAligned = missingClaims.length <= this.options.maxMissingClaims;
110
-
111
- return {
112
- isAligned,
113
- confidence,
114
- spans,
115
- missingClaims
116
- };
117
- }
118
-
119
- /**
120
- * Find exact substring match
121
- */
122
- private findExactMatch(
123
- normalizedClaim: string,
124
- normalizedSource: string,
125
- originalSource: string
126
- ): EvidenceSpan | null {
127
- const index = normalizedSource.indexOf(normalizedClaim);
128
-
129
- if (index === -1) {
130
- return null;
131
- }
132
-
133
- return {
134
- start: index,
135
- end: index + normalizedClaim.length,
136
- confidence: 1.0,
137
- matchType: 'exact',
138
- originalQuote: originalSource.slice(index, index + normalizedClaim.length),
139
- alignedText: normalizedClaim
140
- };
141
- }
142
-
143
- /**
144
- * Find fuzzy match using sliding window
145
- */
146
- private findFuzzyMatch(
147
- normalizedClaim: string,
148
- normalizedSource: string,
149
- originalSource: string
150
- ): EvidenceSpan | null {
151
- const windowSize = normalizedClaim.length;
152
- let bestMatch: { index: number; similarity: number } | null = null;
153
-
154
- // Slide window across source
155
- for (let i = 0; i <= normalizedSource.length - windowSize; i++) {
156
- const window = normalizedSource.slice(i, i + windowSize);
157
- const similarity = this.calculateSimilarity(normalizedClaim, window);
158
-
159
- if (!bestMatch || similarity > bestMatch.similarity) {
160
- bestMatch = { index: i, similarity };
161
- }
162
- }
163
-
164
- if (!bestMatch || bestMatch.similarity < this.options.fuzzyThreshold) {
165
- return null;
166
- }
167
-
168
- return {
169
- start: bestMatch.index,
170
- end: bestMatch.index + windowSize,
171
- confidence: bestMatch.similarity,
172
- matchType: 'fuzzy',
173
- originalQuote: originalSource.slice(bestMatch.index, bestMatch.index + windowSize),
174
- alignedText: normalizedClaim
175
- };
176
- }
177
-
178
- /**
179
- * Calculate similarity between two strings using Jaccard coefficient
180
- */
181
- private calculateSimilarity(a: string, b: string): number {
182
- const setA = new Set(this.tokenize(a));
183
- const setB = new Set(this.tokenize(b));
184
-
185
- const intersection = new Set([...setA].filter(x => setB.has(x)));
186
- const union = new Set([...setA, ...setB]);
187
-
188
- return intersection.size / union.size;
189
- }
190
-
191
- /**
192
- * Tokenize text into words
193
- */
194
- private tokenize(text: string): string[] {
195
- return text.toLowerCase().split(/\s+/).filter(t => t.length > 0);
196
- }
197
-
198
- /**
199
- * Normalize text for comparison
200
- */
201
- private normalize(text: string): string {
202
- return text
203
- .normalize('NFKC')
204
- .toLowerCase()
205
- .replace(/[^\p{L}\p{N}\s]/gu, '')
206
- .replace(/\s+/g, ' ')
207
- .trim();
208
- }
209
-
210
- /**
211
- * Extract claims from a response text
212
- * Splits on sentence boundaries and filters short sentences
213
- */
214
- extractClaims(text: string): string[] {
215
- // Keep terminal punctuation while splitting so questions can be filtered reliably.
216
- const sentences = text.match(/[^.!?]+[.!?]?/g)?.map(s => s.trim()).filter(s => s.length > 0) || [];
217
-
218
- // Filter out very short sentences and questions
219
- return sentences.filter(s => {
220
- return s.length >= this.options.minMatchLength && !s.endsWith('?');
221
- });
222
- }
223
-
224
- /**
225
- * Verify that a response is grounded in the provided context
226
- */
227
- verifyGrounding(response: string, context: string[]): AlignmentResult {
228
- const claims = this.extractClaims(response);
229
- const combinedContext = context.join(' ');
230
-
231
- return this.align(claims, combinedContext);
232
- }
233
-
234
- // ============================================================
235
- // V2 Methods: Quote-only alignment
236
- // ============================================================
237
-
238
- private optionsV2: AlignmentOptionsV2 = DEFAULT_OPTIONS_V2;
239
-
240
- /**
241
- * Configure V2 options
242
- */
243
- configureV2(options: Partial<AlignmentOptionsV2>): void {
244
- this.optionsV2 = { ...DEFAULT_OPTIONS_V2, ...options };
245
- }
246
-
247
- /**
248
- * Align V2: Process extracted evidence with messageIndex and quote
249
- * @param sessionMessages - Array of session messages (original text)
250
- * @param evidence - Array of extracted evidence (messageIndex + quote)
251
- */
252
- alignV2(
253
- sessionMessages: string[],
254
- evidence: ExtractedEvidence[]
255
- ): AlignResultV2 {
256
- const results: EvidenceAlignResult[] = [];
257
- let alignedCount = 0;
258
- let totalConfidence = 0;
259
-
260
- for (const ev of evidence) {
261
- const result = this.alignSingleEvidence(sessionMessages, ev);
262
- results.push(result);
263
-
264
- if (result.aligned) {
265
- alignedCount++;
266
- totalConfidence += result.evidence.confidence;
267
- }
268
- }
269
-
270
- const failedCount = evidence.length - alignedCount;
271
- const maxMissing = Math.floor(evidence.length * this.optionsV2.maxMissingRatio);
272
- const evidenceAligned = failedCount <= maxMissing;
273
- const overallConfidence = evidence.length > 0
274
- ? totalConfidence / evidence.length
275
- : 1.0;
276
-
277
- return {
278
- evidenceAligned,
279
- alignedCount,
280
- failedCount,
281
- results,
282
- overallConfidence
283
- };
284
- }
285
-
286
- /**
287
- * Align a single evidence item
288
- */
289
- private alignSingleEvidence(
290
- sessionMessages: string[],
291
- evidence: ExtractedEvidence
292
- ): EvidenceAlignResult {
293
- const { messageIndex, quote } = evidence;
294
-
295
- // Validate messageIndex
296
- if (messageIndex < 0 || messageIndex >= sessionMessages.length) {
297
- return {
298
- aligned: false,
299
- evidence: {
300
- messageIndex,
301
- quote,
302
- failureReason: 'invalid_index'
303
- }
304
- };
305
- }
306
-
307
- // Validate quote
308
- if (!quote || quote.trim().length === 0) {
309
- return {
310
- aligned: false,
311
- evidence: {
312
- messageIndex,
313
- quote,
314
- failureReason: 'empty_quote'
315
- }
316
- };
317
- }
318
-
319
- const sourceMessage = sessionMessages[messageIndex];
320
-
321
- // Step 1: Try exact match
322
- const exactResult = this.tryExactMatchV2(quote, sourceMessage, messageIndex);
323
- if (exactResult) {
324
- return exactResult;
325
- }
326
-
327
- // Step 2: Try normalized match
328
- const normalizedResult = this.tryNormalizedMatchV2(quote, sourceMessage, messageIndex);
329
- if (normalizedResult) {
330
- return normalizedResult;
331
- }
332
-
333
- // Step 3: Try fuzzy match
334
- const fuzzyResult = this.tryFuzzyMatchV2(quote, sourceMessage, messageIndex);
335
- if (fuzzyResult) {
336
- return fuzzyResult;
337
- }
338
-
339
- // No match found
340
- return {
341
- aligned: false,
342
- evidence: {
343
- messageIndex,
344
- quote,
345
- failureReason: 'not_found'
346
- }
347
- };
348
- }
349
-
350
- /**
351
- * Try exact substring match
352
- */
353
- private tryExactMatchV2(
354
- quote: string,
355
- source: string,
356
- messageIndex: number
357
- ): EvidenceAlignResult | null {
358
- const index = source.indexOf(quote);
359
-
360
- if (index === -1) {
361
- return null;
362
- }
363
-
364
- return {
365
- aligned: true,
366
- evidence: {
367
- messageIndex,
368
- quote,
369
- spanStart: index,
370
- spanEnd: index + quote.length,
371
- quoteHash: this.hashQuote(quote),
372
- confidence: 1.0,
373
- matchMethod: 'exact'
374
- }
375
- };
376
- }
377
-
378
- /**
379
- * Try normalized match (whitespace collapsed)
380
- */
381
- private tryNormalizedMatchV2(
382
- quote: string,
383
- source: string,
384
- messageIndex: number
385
- ): EvidenceAlignResult | null {
386
- const normalizedQuote = this.normalizeWhitespace(quote);
387
- const normalizedSource = this.normalizeWhitespace(source);
388
-
389
- const normalizedIndex = normalizedSource.indexOf(normalizedQuote);
390
- if (normalizedIndex === -1) {
391
- return null;
392
- }
393
-
394
- // Map back to original positions
395
- const originalSpan = this.mapToOriginalPositions(
396
- source,
397
- normalizedSource,
398
- normalizedIndex,
399
- normalizedIndex + normalizedQuote.length
400
- );
401
-
402
- if (!originalSpan) {
403
- return null;
404
- }
405
-
406
- return {
407
- aligned: true,
408
- evidence: {
409
- messageIndex,
410
- quote,
411
- spanStart: originalSpan.start,
412
- spanEnd: originalSpan.end,
413
- quoteHash: this.hashQuote(quote),
414
- confidence: 0.95,
415
- matchMethod: 'normalized'
416
- }
417
- };
418
- }
419
-
420
- /**
421
- * Try fuzzy match using sliding window
422
- */
423
- private tryFuzzyMatchV2(
424
- quote: string,
425
- source: string,
426
- messageIndex: number
427
- ): EvidenceAlignResult | null {
428
- const normalizedQuote = this.normalize(quote);
429
- const normalizedSource = this.normalize(source);
430
-
431
- if (normalizedQuote.length < this.optionsV2.minMatchLength) {
432
- return null;
433
- }
434
-
435
- // Try different window sizes
436
- const windowSizes = [
437
- normalizedQuote.length,
438
- Math.floor(normalizedQuote.length * 1.1),
439
- Math.floor(normalizedQuote.length * 1.2)
440
- ];
441
-
442
- let bestMatch: {
443
- index: number;
444
- windowSize: number;
445
- similarity: number;
446
- } | null = null;
447
-
448
- for (const windowSize of windowSizes) {
449
- for (let i = 0; i <= normalizedSource.length - windowSize; i++) {
450
- const window = normalizedSource.slice(i, i + windowSize);
451
- const similarity = this.calculateLevenshteinSimilarity(normalizedQuote, window);
452
-
453
- if (similarity >= this.optionsV2.fuzzyThreshold) {
454
- if (!bestMatch || similarity > bestMatch.similarity) {
455
- bestMatch = { index: i, windowSize, similarity };
456
- }
457
- }
458
- }
459
- }
460
-
461
- if (!bestMatch) {
462
- return null;
463
- }
464
-
465
- // Map back to original positions (approximate)
466
- const originalSpan = this.mapToOriginalPositions(
467
- source,
468
- normalizedSource,
469
- bestMatch.index,
470
- bestMatch.index + bestMatch.windowSize
471
- );
472
-
473
- if (!originalSpan) {
474
- return null;
475
- }
476
-
477
- return {
478
- aligned: true,
479
- evidence: {
480
- messageIndex,
481
- quote,
482
- spanStart: originalSpan.start,
483
- spanEnd: originalSpan.end,
484
- quoteHash: this.hashQuote(quote),
485
- confidence: bestMatch.similarity,
486
- matchMethod: 'fuzzy'
487
- }
488
- };
489
- }
490
-
491
- /**
492
- * Normalize whitespace only (preserve other characters)
493
- */
494
- private normalizeWhitespace(text: string): string {
495
- return text
496
- .replace(/[\t\r]/g, ' ')
497
- .replace(/\n+/g, ' ')
498
- .replace(/ +/g, ' ')
499
- .trim();
500
- }
501
-
502
- /**
503
- * Map normalized positions back to original
504
- */
505
- private mapToOriginalPositions(
506
- original: string,
507
- normalized: string,
508
- normalizedStart: number,
509
- normalizedEnd: number
510
- ): { start: number; end: number } | null {
511
- // Build position map
512
- const normalizedToOriginal: Map<number, number> = new Map();
513
- let normalizedPos = 0;
514
-
515
- for (let origPos = 0; origPos < original.length; origPos++) {
516
- const char = original[origPos];
517
-
518
- // Skip extra whitespace in original
519
- if (/\s/.test(char)) {
520
- // Check if this whitespace contributes to normalized
521
- if (normalizedPos < normalized.length && /\s/.test(normalized[normalizedPos])) {
522
- normalizedToOriginal.set(normalizedPos, origPos);
523
- normalizedPos++;
524
-
525
- // Skip consecutive whitespace in original
526
- while (origPos + 1 < original.length && /\s/.test(original[origPos + 1])) {
527
- origPos++;
528
- }
529
- }
530
- } else {
531
- normalizedToOriginal.set(normalizedPos, origPos);
532
- normalizedPos++;
533
- }
534
- }
535
-
536
- const startOrig = normalizedToOriginal.get(normalizedStart);
537
- let endOrig = normalizedToOriginal.get(normalizedEnd - 1);
538
-
539
- if (startOrig === undefined) {
540
- return null;
541
- }
542
-
543
- if (endOrig === undefined) {
544
- // Use end of string
545
- endOrig = original.length - 1;
546
- }
547
-
548
- return {
549
- start: startOrig,
550
- end: endOrig + 1
551
- };
552
- }
553
-
554
- /**
555
- * Calculate Levenshtein distance similarity
556
- */
557
- private calculateLevenshteinSimilarity(a: string, b: string): number {
558
- const m = a.length;
559
- const n = b.length;
560
-
561
- if (m === 0) return n === 0 ? 1 : 0;
562
- if (n === 0) return 0;
563
-
564
- const dp: number[][] = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
565
-
566
- for (let i = 0; i <= m; i++) dp[i][0] = i;
567
- for (let j = 0; j <= n; j++) dp[0][j] = j;
568
-
569
- for (let i = 1; i <= m; i++) {
570
- for (let j = 1; j <= n; j++) {
571
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
572
- dp[i][j] = Math.min(
573
- dp[i - 1][j] + 1, // deletion
574
- dp[i][j - 1] + 1, // insertion
575
- dp[i - 1][j - 1] + cost // substitution
576
- );
577
- }
578
- }
579
-
580
- const distance = dp[m][n];
581
- const maxLen = Math.max(m, n);
582
- return 1 - distance / maxLen;
583
- }
584
-
585
- /**
586
- * Hash quote for deduplication
587
- */
588
- private hashQuote(quote: string): string {
589
- return createHash('sha256').update(quote).digest('hex').slice(0, 16);
590
- }
591
-
592
- /**
593
- * Convert V2 result to V1 format for backwards compatibility
594
- */
595
- convertToV1Result(v2Result: AlignResultV2): AlignmentResult {
596
- const spans: EvidenceSpan[] = [];
597
- const missingClaims: string[] = [];
598
-
599
- for (const result of v2Result.results) {
600
- if (result.aligned) {
601
- const ev = result.evidence as AlignedEvidence;
602
- spans.push({
603
- start: ev.spanStart,
604
- end: ev.spanEnd,
605
- confidence: ev.confidence,
606
- matchType: ev.matchMethod === 'exact' ? 'exact' : 'fuzzy',
607
- originalQuote: ev.quote,
608
- alignedText: ev.quote
609
- });
610
- } else {
611
- const ev = result.evidence as FailedEvidence;
612
- missingClaims.push(ev.quote);
613
- }
614
- }
615
-
616
- return {
617
- isAligned: v2Result.evidenceAligned,
618
- confidence: v2Result.overallConfidence,
619
- spans,
620
- missingClaims
621
- };
622
- }
623
- }
624
-
625
- /**
626
- * Default evidence aligner instance
627
- */
628
- let defaultAligner: EvidenceAligner | null = null;
629
-
630
- export function getDefaultAligner(): EvidenceAligner {
631
- if (!defaultAligner) {
632
- defaultAligner = new EvidenceAligner();
633
- }
634
- return defaultAligner;
635
- }