@useody/detectors 0.0.1

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 (57) hide show
  1. package/LICENSE +198 -0
  2. package/README.md +42 -0
  3. package/dist/claim-comparison.d.ts +12 -0
  4. package/dist/claim-comparison.d.ts.map +1 -0
  5. package/dist/claim-comparison.js +108 -0
  6. package/dist/claim-nli.d.ts +15 -0
  7. package/dist/claim-nli.d.ts.map +1 -0
  8. package/dist/claim-nli.js +181 -0
  9. package/dist/consensus.d.ts +26 -0
  10. package/dist/consensus.d.ts.map +1 -0
  11. package/dist/consensus.js +211 -0
  12. package/dist/consultant-analysis.d.ts +20 -0
  13. package/dist/consultant-analysis.d.ts.map +1 -0
  14. package/dist/consultant-analysis.js +69 -0
  15. package/dist/consultant-prompts.d.ts +83 -0
  16. package/dist/consultant-prompts.d.ts.map +1 -0
  17. package/dist/consultant-prompts.js +135 -0
  18. package/dist/contradiction-helpers.d.ts +40 -0
  19. package/dist/contradiction-helpers.d.ts.map +1 -0
  20. package/dist/contradiction-helpers.js +163 -0
  21. package/dist/contradictions.d.ts +20 -0
  22. package/dist/contradictions.d.ts.map +1 -0
  23. package/dist/contradictions.js +235 -0
  24. package/dist/duplicates.d.ts +14 -0
  25. package/dist/duplicates.d.ts.map +1 -0
  26. package/dist/duplicates.js +95 -0
  27. package/dist/health-score.d.ts +13 -0
  28. package/dist/health-score.d.ts.map +1 -0
  29. package/dist/health-score.js +53 -0
  30. package/dist/helpers/index.d.ts +7 -0
  31. package/dist/helpers/index.d.ts.map +1 -0
  32. package/dist/helpers/index.js +7 -0
  33. package/dist/helpers/llm-timeout.d.ts +14 -0
  34. package/dist/helpers/llm-timeout.d.ts.map +1 -0
  35. package/dist/helpers/llm-timeout.js +30 -0
  36. package/dist/helpers/text-utils.d.ts +21 -0
  37. package/dist/helpers/text-utils.d.ts.map +1 -0
  38. package/dist/helpers/text-utils.js +63 -0
  39. package/dist/index.d.ts +17 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +14 -0
  42. package/dist/run-detection.d.ts +29 -0
  43. package/dist/run-detection.d.ts.map +1 -0
  44. package/dist/run-detection.js +46 -0
  45. package/dist/staleness.d.ts +21 -0
  46. package/dist/staleness.d.ts.map +1 -0
  47. package/dist/staleness.js +128 -0
  48. package/dist/time-bomb-utils.d.ts +23 -0
  49. package/dist/time-bomb-utils.d.ts.map +1 -0
  50. package/dist/time-bomb-utils.js +161 -0
  51. package/dist/time-bombs.d.ts +14 -0
  52. package/dist/time-bombs.d.ts.map +1 -0
  53. package/dist/time-bombs.js +113 -0
  54. package/dist/undocumented.d.ts +13 -0
  55. package/dist/undocumented.d.ts.map +1 -0
  56. package/dist/undocumented.js +84 -0
  57. package/package.json +48 -0
package/LICENSE ADDED
@@ -0,0 +1,198 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format.
185
+
186
+ Copyright 2026 Rodyr Inc.
187
+
188
+ Licensed under the Apache License, Version 2.0 (the "License");
189
+ you may not use this file except in compliance with the License.
190
+ You may obtain a copy of the License at
191
+
192
+ http://www.apache.org/licenses/LICENSE-2.0
193
+
194
+ Unless required by applicable law or agreed to in writing, software
195
+ distributed under the License is distributed on an "AS IS" BASIS,
196
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
197
+ See the License for the specific language governing permissions and
198
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ # @useody/detectors
2
+
3
+ Five pure-function detectors for finding issues in documentation knowledge graphs.
4
+
5
+ ## Detectors
6
+
7
+ | Detector | What it finds |
8
+ |----------|--------------|
9
+ | `detectContradictions` | Two documents disagree on the same fact |
10
+ | `detectDuplicates` | Same topic documented in multiple places |
11
+ | `detectStaleness` | Processes and commitments that went quiet |
12
+ | `detectUndocumented` | Decisions made in chat, never written down |
13
+ | `detectTimeBombs` | Deadlines and SLAs approaching with no action |
14
+
15
+ ## Usage
16
+
17
+ ```typescript
18
+ import { detectContradictions, detectStaleness } from '@useody/detectors';
19
+
20
+ // Each detector is a pure function: (nodes, edges, llm?) -> Detection[]
21
+ const results = await detectContradictions(nodes, edges, llm);
22
+ ```
23
+
24
+ ## Writing a custom detector
25
+
26
+ ```typescript
27
+ import type { DetectorFn } from '@useody/platform-core';
28
+
29
+ const detectMyIssue: DetectorFn = async (nodes, edges, llm) => {
30
+ return []; // Your detection logic
31
+ };
32
+
33
+ detectMyIssue.preFilter = { similarityThreshold: 0.6, topK: 10 };
34
+ ```
35
+
36
+ ## Design principles
37
+
38
+ - **Pure functions** — No I/O, no side effects, no database access
39
+ - **Optional LLM** — Every detector works in heuristic mode (no LLM) with lower accuracy
40
+ - **Pre-filters** — Each detector declares similarity thresholds to avoid brute-force comparison
41
+
42
+ Part of [ody-platform](https://github.com/ufukkaraca/ody-platform). See the root [README](../../README.md) for setup.
@@ -0,0 +1,12 @@
1
+ /**
2
+ * LLM-based claim contradiction detection.
3
+ * Compares extracted facts between knowledge nodes using an LLM.
4
+ * @module claim-comparison
5
+ */
6
+ import type { Detection, KnowledgeNode, LLMProvider } from '@useody/platform-core';
7
+ /**
8
+ * Detect contradictions by sending extracted facts to an LLM for comparison.
9
+ * Only processes nodes that have extracted facts.
10
+ */
11
+ export declare function detectClaimContradictions(nodes: KnowledgeNode[], llm: LLMProvider, out: Detection[], seen: Set<string>): Promise<void>;
12
+ //# sourceMappingURL=claim-comparison.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claim-comparison.d.ts","sourceRoot":"","sources":["../src/claim-comparison.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAEV,SAAS,EACT,aAAa,EACb,WAAW,EACZ,MAAM,uBAAuB,CAAC;AA6E/B;;;GAGG;AACH,wBAAsB,yBAAyB,CAC7C,KAAK,EAAE,aAAa,EAAE,EACtB,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,SAAS,EAAE,EAChB,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,GAChB,OAAO,CAAC,IAAI,CAAC,CAyDf"}
@@ -0,0 +1,108 @@
1
+ import { parseLlmJsonResponse } from '@useody/platform-core';
2
+ import { completeWithTimeout } from './helpers/llm-timeout.js';
3
+ const MAX_LLM_CALLS = 30;
4
+ const LLM_TIMEOUT_MS = 8_000;
5
+ /** Build the system prompt for claim comparison. */
6
+ function buildSystemPrompt() {
7
+ return [
8
+ 'You compare knowledge claims for REAL contradictions. Be STRICT.',
9
+ '',
10
+ 'A contradiction means: BOTH documents make ACTIVE, EXPLICIT claims',
11
+ 'about the SAME specific thing, but state INCOMPATIBLE facts.',
12
+ '',
13
+ 'CRITICAL — Absence is NOT contradiction:',
14
+ 'If Doc A states something and Doc B is SILENT about that topic,',
15
+ 'that is a gap, NOT a contradiction. The undocumented detector handles gaps.',
16
+ 'Both documents must make active assertions that conflict.',
17
+ '',
18
+ 'FALSE POSITIVES to avoid (absence-based):',
19
+ '- "Doc A requires Vitest" vs "Doc B doesn\'t mention a test framework" → NOT a contradiction',
20
+ '- "Doc A has a 250-line limit" vs "Doc B has no line limit rule" → NOT a contradiction',
21
+ '- "Doc A says be kind" vs "Doc B has no kindness requirement" → NOT a contradiction',
22
+ '',
23
+ 'NOT a contradiction (different topics):',
24
+ '- Different pages covering different aspects of a topic',
25
+ '- Complementary information (overview vs details)',
26
+ '- Different resources (CPU vs GPU, memory vs storage)',
27
+ '- General vs specific descriptions of the same thing',
28
+ '',
29
+ 'IS a contradiction (both docs actively conflict):',
30
+ '- "API rate limit is 1000/min" vs "API rate limit is 500/min" → REAL conflict',
31
+ '- "Deploy window Tue-Thu" vs "Deploy Friday 2-4pm" → REAL conflict',
32
+ '- "Remote-first" vs "Must work from office full-time" → REAL conflict',
33
+ '',
34
+ 'When in doubt: NOT a contradiction. Be conservative.',
35
+ '',
36
+ 'Reply ONLY valid JSON:',
37
+ '{"isContradiction":bool,"topic":"the specific thing both discuss",',
38
+ '"claimA":"what A says","claimB":"what B says",',
39
+ '"severity":"critical|warning","explanation":"one sentence"}',
40
+ ].join('\n');
41
+ }
42
+ /** Build the user prompt for a specific fact pair. */
43
+ function buildUserPrompt(nodeA, nodeB, factsA, factsB) {
44
+ return [
45
+ `Claims from "${nodeA.title}":`,
46
+ factsA,
47
+ '',
48
+ `Claims from "${nodeB.title}":`,
49
+ factsB,
50
+ '',
51
+ 'Are any of these claims about the SAME topic but contradictory?',
52
+ ].join('\n');
53
+ }
54
+ /** Canonical pair key for deduplication. */
55
+ function pairKey(id1, id2) {
56
+ return id1 < id2 ? `${id1}:${id2}` : `${id2}:${id1}`;
57
+ }
58
+ /**
59
+ * Detect contradictions by sending extracted facts to an LLM for comparison.
60
+ * Only processes nodes that have extracted facts.
61
+ */
62
+ export async function detectClaimContradictions(nodes, llm, out, seen) {
63
+ const nodesWithFacts = nodes.filter((n) => (n.content.facts?.length ?? 0) > 0);
64
+ if (nodesWithFacts.length < 2)
65
+ return;
66
+ let callCount = 0;
67
+ const systemMsg = buildSystemPrompt();
68
+ for (let i = 0; i < nodesWithFacts.length && callCount < MAX_LLM_CALLS; i++) {
69
+ for (let j = i + 1; j < nodesWithFacts.length && callCount < MAX_LLM_CALLS; j++) {
70
+ const a = nodesWithFacts[i];
71
+ const b = nodesWithFacts[j];
72
+ const key = pairKey(a.id, b.id);
73
+ if (seen.has(key))
74
+ continue;
75
+ const factsA = a.content.facts.join('\n');
76
+ const factsB = b.content.facts.join('\n');
77
+ const messages = [
78
+ { role: 'system', content: systemMsg },
79
+ { role: 'user', content: buildUserPrompt(a, b, factsA, factsB) },
80
+ ];
81
+ const response = await completeWithTimeout(llm, messages, { temperature: 0, maxTokens: 300 }, LLM_TIMEOUT_MS);
82
+ callCount++;
83
+ if (!response)
84
+ continue;
85
+ const parsed = parseLlmJsonResponse(response);
86
+ if (!parsed.data?.isContradiction)
87
+ continue;
88
+ const result = parsed.data;
89
+ const severity = result.severity === 'critical' ? 'critical' : 'warning';
90
+ seen.add(key);
91
+ out.push({
92
+ type: 'contradiction',
93
+ severity,
94
+ nodeIds: [a.id, b.id],
95
+ description: `When discussing ${result.topic}, ${a.title} states: '${result.claimA}'. However, ${b.title} states: '${result.claimB}'.`,
96
+ suggestedAction: `Review and align ${a.title} and ${b.title} on ${result.topic}.`,
97
+ metadata: {
98
+ claimA: result.claimA,
99
+ claimB: result.claimB,
100
+ topic: result.topic,
101
+ impact: result.explanation,
102
+ confidence: severity === 'critical' ? 'high' : 'medium',
103
+ },
104
+ });
105
+ }
106
+ }
107
+ }
108
+ //# sourceMappingURL=claim-comparison.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Claim-based contradiction detection using Natural Language Inference.
3
+ * Extracts atomic claims from each node, clusters by topic similarity,
4
+ * then does pairwise NLI: "can both claims be true simultaneously?"
5
+ * @module claim-nli
6
+ */
7
+ import type { Detection, KnowledgeNode, LLMProvider } from '@useody/platform-core';
8
+ /**
9
+ * Run claim-based NLI contradiction detection.
10
+ * Stage 1: Extract atomic claims from each node.
11
+ * Stage 2: Find related claim pairs (same topic, different sources).
12
+ * Stage 3: Compare each pair via LLM NLI.
13
+ */
14
+ export declare function detectClaimNliContradictions(nodes: KnowledgeNode[], llm: LLMProvider, out: Detection[], seen: Set<string>): Promise<void>;
15
+ //# sourceMappingURL=claim-nli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"claim-nli.d.ts","sourceRoot":"","sources":["../src/claim-nli.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EACV,SAAS,EACT,aAAa,EACb,WAAW,EACZ,MAAM,uBAAuB,CAAC;AA2K/B;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAChD,KAAK,EAAE,aAAa,EAAE,EACtB,GAAG,EAAE,WAAW,EAChB,GAAG,EAAE,SAAS,EAAE,EAChB,IAAI,EAAE,GAAG,CAAC,MAAM,CAAC,GAChB,OAAO,CAAC,IAAI,CAAC,CAqDf"}
@@ -0,0 +1,181 @@
1
+ import { parseLlmJsonResponse } from '@useody/platform-core';
2
+ import { completeWithTimeout } from './helpers/llm-timeout.js';
3
+ const LLM_TIMEOUT_MS = 15_000;
4
+ const BATCH_SIZE = 5;
5
+ const EXTRACT_CLAIMS_PROMPT = `Extract every specific factual assertion from this text.
6
+ Each claim must be a standalone statement that could be verified as true or false.
7
+ Focus on: numbers, policies, rules, deadlines, requirements, schedules.
8
+
9
+ IMPORTANT: Only extract claims that are ACTIVELY STATED in the text.
10
+ Do NOT invent claims about what is missing, absent, or not mentioned.
11
+ Never produce claims like "No X specified" or "X is not mentioned."
12
+
13
+ Return JSON only: {"claims":["claim1","claim2",...]}
14
+
15
+ Examples:
16
+ - "Employees can work remotely up to 3 days per week"
17
+ - "All PRs require 2 reviewer approvals"
18
+ - "On-call response time is 15 minutes"
19
+ - "Annual vacation allowance is 20 days"
20
+ - "Deployments happen on Tuesdays at 2 PM UTC"
21
+
22
+ Text:
23
+ `;
24
+ const NLI_PROMPT = `Check if two claims from different documents contradict each other.
25
+ Contradiction = BOTH claims make ACTIVE assertions about the SAME topic that CANNOT both be true.
26
+
27
+ CRITICAL: Absence is NOT contradiction. If only one claim addresses a topic, that is a gap, not a conflict.
28
+ Both claims must actively disagree on the same specific thing.
29
+
30
+ NOT contradictions: different topics, complementary info, one-sided coverage.
31
+ REAL contradictions: "rate limit 1000/min" vs "rate limit 500/min"; "remote-first" vs "office full-time".
32
+
33
+ Claim A: "{claimA}" (Source: {sourceA})
34
+ Claim B: "{claimB}" (Source: {sourceB})
35
+
36
+ When in doubt, answer false. Reply ONLY valid JSON:
37
+ {"contradiction":true/false,"explanation":"why they conflict or don't","severity":"critical|warning"}`;
38
+ /**
39
+ * Extract atomic claims from a node's content using LLM.
40
+ * Returns precise, verifiable factual assertions.
41
+ */
42
+ async function extractAtomicClaims(node, llm) {
43
+ const text = node.content.raw ?? node.content.summary;
44
+ const response = await completeWithTimeout(llm, [{ role: 'user', content: EXTRACT_CLAIMS_PROMPT + text }], { temperature: 0, maxTokens: 1024 }, LLM_TIMEOUT_MS);
45
+ if (!response)
46
+ return [];
47
+ const parsed = parseLlmJsonResponse(response);
48
+ if (!parsed.data?.claims || !Array.isArray(parsed.data.claims))
49
+ return [];
50
+ const sourceFile = node.content.source?.sourceId ?? '';
51
+ return parsed.data.claims
52
+ .filter((c) => typeof c === 'string' && c.length > 10)
53
+ .map((text) => ({
54
+ text,
55
+ nodeId: node.id,
56
+ nodeTitle: node.title,
57
+ sourceFile,
58
+ }));
59
+ }
60
+ /**
61
+ * Compare two claims using NLI framing.
62
+ * Returns whether they contradict and why.
63
+ */
64
+ async function compareClaims(a, b, llm) {
65
+ const prompt = NLI_PROMPT
66
+ .replace('{claimA}', a.text)
67
+ .replace('{sourceA}', a.nodeTitle)
68
+ .replace('{claimB}', b.text)
69
+ .replace('{sourceB}', b.nodeTitle);
70
+ const response = await completeWithTimeout(llm, [{ role: 'user', content: prompt }], { temperature: 0, maxTokens: 200 }, LLM_TIMEOUT_MS);
71
+ if (!response)
72
+ return null;
73
+ const parsed = parseLlmJsonResponse(response);
74
+ return parsed.data ?? null;
75
+ }
76
+ /**
77
+ * Find claims about the same topic using keyword overlap.
78
+ * Returns pairs of claims from DIFFERENT source files.
79
+ */
80
+ function findRelatedClaimPairs(claims) {
81
+ const pairs = [];
82
+ const STOP = new Set([
83
+ 'the', 'and', 'for', 'are', 'with', 'per', 'our', 'all', 'must',
84
+ 'can', 'may', 'will', 'from', 'that', 'this', 'have', 'each',
85
+ 'not', 'but', 'should', 'any', 'been',
86
+ ]);
87
+ /** Basic stemming: remove trailing s/es/ed/ing for better matching. */
88
+ const stem = (w) => {
89
+ if (w.endsWith('ing') && w.length > 5)
90
+ return w.slice(0, -3);
91
+ if (w.endsWith('ed') && w.length > 4)
92
+ return w.slice(0, -2);
93
+ if (w.endsWith('es') && w.length > 4)
94
+ return w.slice(0, -2);
95
+ if (w.endsWith('s') && w.length > 3)
96
+ return w.slice(0, -1);
97
+ return w;
98
+ };
99
+ const keywordCache = new Map();
100
+ const getKw = (idx) => {
101
+ if (keywordCache.has(idx))
102
+ return keywordCache.get(idx);
103
+ const kw = new Set(claims[idx].text.toLowerCase()
104
+ .replace(/[^\w\s]/g, ' ')
105
+ .split(/\s+/)
106
+ .filter((w) => w.length > 2 && !STOP.has(w))
107
+ .map(stem));
108
+ keywordCache.set(idx, kw);
109
+ return kw;
110
+ };
111
+ for (let i = 0; i < claims.length; i++) {
112
+ for (let j = i + 1; j < claims.length; j++) {
113
+ const a = claims[i];
114
+ const b = claims[j];
115
+ // Only compare claims from DIFFERENT source files
116
+ if (a.sourceFile === b.sourceFile)
117
+ continue;
118
+ // Check keyword overlap — at least 1 meaningful shared word
119
+ const kwA = getKw(i);
120
+ const kwB = getKw(j);
121
+ const shared = [...kwA].filter((w) => kwB.has(w));
122
+ if (shared.length >= 1) {
123
+ pairs.push([a, b]);
124
+ }
125
+ }
126
+ }
127
+ return pairs;
128
+ }
129
+ /**
130
+ * Run claim-based NLI contradiction detection.
131
+ * Stage 1: Extract atomic claims from each node.
132
+ * Stage 2: Find related claim pairs (same topic, different sources).
133
+ * Stage 3: Compare each pair via LLM NLI.
134
+ */
135
+ export async function detectClaimNliContradictions(nodes, llm, out, seen) {
136
+ // Stage 1: Extract atomic claims from all nodes
137
+ const allClaims = [];
138
+ for (let i = 0; i < nodes.length; i += BATCH_SIZE) {
139
+ const batch = nodes.slice(i, i + BATCH_SIZE);
140
+ const results = await Promise.all(batch.map((n) => extractAtomicClaims(n, llm)));
141
+ for (const claims of results) {
142
+ allClaims.push(...claims);
143
+ }
144
+ }
145
+ if (allClaims.length < 2)
146
+ return;
147
+ // Stage 2: Find related claim pairs
148
+ const pairs = findRelatedClaimPairs(allClaims);
149
+ // Cap at 100 LLM calls for NLI comparison
150
+ const MAX_NLI_CALLS = 100;
151
+ const pairsToCheck = pairs.slice(0, MAX_NLI_CALLS);
152
+ // Stage 3: NLI comparison
153
+ for (let i = 0; i < pairsToCheck.length; i += BATCH_SIZE) {
154
+ const batch = pairsToCheck.slice(i, i + BATCH_SIZE);
155
+ const results = await Promise.all(batch.map(([a, b]) => compareClaims(a, b, llm)));
156
+ for (let j = 0; j < batch.length; j++) {
157
+ const result = results[j];
158
+ const [claimA, claimB] = batch[j];
159
+ if (!result?.contradiction)
160
+ continue;
161
+ const key = [claimA.nodeId, claimB.nodeId].sort().join(':');
162
+ if (seen.has(key))
163
+ continue;
164
+ seen.add(key);
165
+ out.push({
166
+ type: 'contradiction',
167
+ severity: result.severity,
168
+ nodeIds: [claimA.nodeId, claimB.nodeId],
169
+ description: `${claimA.nodeTitle} states: "${claimA.text}" — but ${claimB.nodeTitle} states: "${claimB.text}"`,
170
+ suggestedAction: `Review and align: "${claimA.text}" vs "${claimB.text}"`,
171
+ metadata: {
172
+ claimA: claimA.text,
173
+ claimB: claimB.text,
174
+ explanation: result.explanation,
175
+ topic: `${claimA.nodeTitle} vs ${claimB.nodeTitle}`,
176
+ },
177
+ });
178
+ }
179
+ }
180
+ }
181
+ //# sourceMappingURL=claim-nli.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Consensus voting engine for consultant analysis.
3
+ * Runs analysis N times, groups findings by similarity,
4
+ * and keeps only those appearing in a majority of passes.
5
+ * @module consensus
6
+ */
7
+ import type { LLMProvider } from '@useody/platform-core';
8
+ import type { AnalysisInput, AnalysisResult } from './consultant-analysis.js';
9
+ /** Options for consensus analysis. */
10
+ export interface ConsensusOptions {
11
+ /** Number of analysis passes (default 3). */
12
+ passes?: number;
13
+ /** Minimum votes (passes) a finding must appear in to survive. Default: ceil(passes/2). */
14
+ minVotes?: number;
15
+ /** Max tokens per LLM call. */
16
+ maxTokens?: number;
17
+ /** Logger callback for progress. */
18
+ logger?: (msg: string) => void;
19
+ }
20
+ /**
21
+ * Run consensus analysis: multiple passes with majority voting.
22
+ * Findings must appear in >= ceil(N/2) passes to be kept.
23
+ * Health scores are computed deterministically from consensus findings.
24
+ */
25
+ export declare function runConsensusAnalysis(input: AnalysisInput, llm: LLMProvider, options?: ConsensusOptions): Promise<AnalysisResult>;
26
+ //# sourceMappingURL=consensus.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consensus.d.ts","sourceRoot":"","sources":["../src/consensus.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,KAAK,EACV,aAAa,EACb,cAAc,EAGf,MAAM,0BAA0B,CAAC;AAIlC,sCAAsC;AACtC,MAAM,WAAW,gBAAgB;IAC/B,6CAA6C;IAC7C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,2FAA2F;IAC3F,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,+BAA+B;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,oCAAoC;IACpC,MAAM,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAuKD;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,KAAK,EAAE,aAAa,EACpB,GAAG,EAAE,WAAW,EAChB,OAAO,CAAC,EAAE,gBAAgB,GACzB,OAAO,CAAC,cAAc,CAAC,CA4DzB"}