@lucern/sdk 0.2.0-alpha.3 → 0.2.0-alpha.5

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 (155) hide show
  1. package/README.md +615 -112
  2. package/dist/.generated +2 -0
  3. package/dist/index.d.ts +3 -0
  4. package/dist/index.js +3 -8894
  5. package/dist/lib/platform/auth/credentials.d.ts +5 -0
  6. package/dist/lib/platform/auth/credentials.js +40 -0
  7. package/dist/lib/platform/sdk/adminClient.d.ts +404 -0
  8. package/dist/lib/platform/sdk/adminClient.js +384 -0
  9. package/dist/lib/platform/sdk/answersClient.d.ts +16 -0
  10. package/dist/lib/platform/sdk/answersClient.js +21 -0
  11. package/dist/{packages/sdk/src → lib/platform/sdk}/audiencesClient.d.ts +6 -0
  12. package/dist/lib/platform/sdk/audiencesClient.js +111 -0
  13. package/dist/{packages/sdk/src → lib/platform/sdk}/auditClient.d.ts +3 -0
  14. package/dist/lib/platform/sdk/auditClient.js +21 -0
  15. package/dist/lib/platform/sdk/beliefsClient.d.ts +157 -0
  16. package/dist/lib/platform/sdk/beliefsClient.js +124 -0
  17. package/dist/{packages/sdk/src → lib/platform/sdk}/client.d.ts +957 -146
  18. package/dist/lib/platform/sdk/client.js +1831 -0
  19. package/dist/lib/platform/sdk/contextClient.d.ts +21 -0
  20. package/dist/lib/platform/sdk/contextClient.js +86 -0
  21. package/dist/{lucern/packages/domain-context/src/context-pack-compiler.d.ts → lib/platform/sdk/contextPackCompiler.d.ts} +2 -3
  22. package/dist/lib/platform/sdk/contextPackCompiler.js +534 -0
  23. package/dist/lib/platform/sdk/contextTypes.d.ts +133 -0
  24. package/dist/lib/platform/sdk/contextTypes.js +1 -0
  25. package/dist/{packages/sdk/src → lib/platform/sdk}/controlObjectOwnership.d.ts +15 -0
  26. package/dist/lib/platform/sdk/controlObjectOwnership.js +220 -0
  27. package/dist/{packages/sdk/src → lib/platform/sdk}/coreClient.d.ts +19 -0
  28. package/dist/lib/platform/sdk/coreClient.js +366 -0
  29. package/dist/{packages/sdk/src → lib/platform/sdk}/customTools.d.ts +21 -3
  30. package/dist/lib/platform/sdk/customTools.js +247 -0
  31. package/dist/{packages/sdk/src → lib/platform/sdk}/decisionsClient.d.ts +9 -0
  32. package/dist/lib/platform/sdk/decisionsClient.js +129 -0
  33. package/dist/lib/platform/sdk/domainContext.d.ts +1 -0
  34. package/dist/lib/platform/sdk/domainContext.js +1 -0
  35. package/dist/{lucern/packages/events/src/types.d.ts → lib/platform/sdk/events.d.ts} +25 -0
  36. package/dist/lib/platform/sdk/events.js +261 -0
  37. package/dist/lib/platform/sdk/gatewayFacades.d.ts +586 -0
  38. package/dist/lib/platform/sdk/gatewayFacades.js +845 -0
  39. package/dist/{packages/sdk/src → lib/platform/sdk}/graphClient.d.ts +75 -0
  40. package/dist/lib/platform/sdk/graphClient.js +235 -0
  41. package/dist/{packages/sdk/src → lib/platform/sdk}/harnessClient.d.ts +90 -1
  42. package/dist/lib/platform/sdk/harnessClient.js +219 -0
  43. package/dist/{packages/sdk/src → lib/platform/sdk}/identityClient.d.ts +45 -15
  44. package/dist/lib/platform/sdk/identityClient.js +131 -0
  45. package/dist/{packages/sdk/src → lib/platform/sdk}/index.d.ts +21 -3
  46. package/dist/lib/platform/sdk/index.js +46 -0
  47. package/dist/{packages/sdk/src → lib/platform/sdk}/learningClient.d.ts +3 -0
  48. package/dist/lib/platform/sdk/learningClient.js +53 -0
  49. package/dist/{packages/sdk/src → lib/platform/sdk}/mcpParityClient.d.ts +1 -0
  50. package/dist/lib/platform/sdk/mcpParityClient.js +196 -0
  51. package/dist/{packages/sdk/src → lib/platform/sdk}/mcpParitySurface.d.ts +2 -0
  52. package/dist/lib/platform/sdk/mcpParitySurface.js +57 -0
  53. package/dist/{packages/sdk/src → lib/platform/sdk}/ontologyClient.d.ts +16 -0
  54. package/dist/lib/platform/sdk/ontologyClient.js +161 -0
  55. package/dist/lib/platform/sdk/packRuntime.d.ts +1 -0
  56. package/dist/lib/platform/sdk/packRuntime.js +1 -0
  57. package/dist/{packages/sdk/src → lib/platform/sdk}/packsClient.d.ts +25 -0
  58. package/dist/lib/platform/sdk/packsClient.js +157 -0
  59. package/dist/{packages/sdk/src → lib/platform/sdk}/policyClient.d.ts +90 -1
  60. package/dist/lib/platform/sdk/policyClient.js +277 -0
  61. package/dist/lib/platform/sdk/promptCatalog.d.ts +1 -0
  62. package/dist/lib/platform/sdk/promptCatalog.js +1 -0
  63. package/dist/{packages/sdk/src → lib/platform/sdk}/reportsClient.d.ts +3 -0
  64. package/dist/lib/platform/sdk/reportsClient.js +64 -0
  65. package/dist/{packages/sdk/src → lib/platform/sdk}/schemaClient.d.ts +5 -0
  66. package/dist/lib/platform/sdk/schemaClient.js +71 -0
  67. package/dist/{packages/sdk/src → lib/platform/sdk}/sdkSurface.d.ts +1 -0
  68. package/dist/lib/platform/sdk/sdkSurface.js +140 -0
  69. package/dist/{packages/sdk/src → lib/platform/sdk}/topicsClient.d.ts +33 -0
  70. package/dist/lib/platform/sdk/topicsClient.js +118 -0
  71. package/dist/{packages/sdk/src → lib/platform/sdk}/types.d.ts +224 -2
  72. package/dist/lib/platform/sdk/types.js +1 -0
  73. package/dist/lib/platform/sdk/version.js +2 -0
  74. package/dist/{packages/sdk/src → lib/platform/sdk}/workflowClient.d.ts +63 -2
  75. package/dist/lib/platform/sdk/workflowClient.js +366 -0
  76. package/dist/lucern/contracts/src/api-enums.contract.d.ts +58 -0
  77. package/dist/lucern/contracts/src/api-enums.contract.js +147 -0
  78. package/dist/lucern/contracts/src/lens-filter.contract.js +95 -0
  79. package/dist/lucern/contracts/src/lens-workflow.contract.js +54 -0
  80. package/dist/lucern/contracts/src/mcp-tools.contract.js +3281 -0
  81. package/package.json +17 -3
  82. package/dist/index.js.map +0 -1
  83. package/dist/lucern/contracts/src/auth-session.contract.d.ts +0 -53
  84. package/dist/lucern/contracts/src/context-pack.contract.d.ts +0 -494
  85. package/dist/lucern/contracts/src/workflow-runtime.contract.d.ts +0 -161
  86. package/dist/lucern/mcp-server/src/context-pack-policy.d.ts +0 -119
  87. package/dist/lucern/mcp-server/src/context-pack-schema.d.ts +0 -18
  88. package/dist/lucern/modules/graph-primitives/src/ontology-matching.d.ts +0 -78
  89. package/dist/lucern/modules/graph-primitives/src/text-matching.d.ts +0 -53
  90. package/dist/lucern/packages/client-core/src/beliefs.d.ts +0 -30
  91. package/dist/lucern/packages/client-core/src/context.d.ts +0 -29
  92. package/dist/lucern/packages/client-core/src/contradictions.d.ts +0 -11
  93. package/dist/lucern/packages/client-core/src/edges.d.ts +0 -11
  94. package/dist/lucern/packages/client-core/src/events.d.ts +0 -9
  95. package/dist/lucern/packages/client-core/src/evidence.d.ts +0 -21
  96. package/dist/lucern/packages/client-core/src/graph.d.ts +0 -17
  97. package/dist/lucern/packages/client-core/src/identity.d.ts +0 -7
  98. package/dist/lucern/packages/client-core/src/ids.d.ts +0 -7
  99. package/dist/lucern/packages/client-core/src/ontologies.d.ts +0 -13
  100. package/dist/lucern/packages/client-core/src/questions.d.ts +0 -39
  101. package/dist/lucern/packages/client-core/src/search.d.ts +0 -7
  102. package/dist/lucern/packages/client-core/src/tasks.d.ts +0 -13
  103. package/dist/lucern/packages/client-core/src/topics.d.ts +0 -17
  104. package/dist/lucern/packages/client-core/src/webhooks.d.ts +0 -35
  105. package/dist/lucern/packages/client-core/src/worktrees.d.ts +0 -17
  106. package/dist/lucern/packages/domain-beliefs/src/beliefs.d.ts +0 -283
  107. package/dist/lucern/packages/domain-beliefs/src/index.d.ts +0 -1
  108. package/dist/lucern/packages/domain-context/src/compile.d.ts +0 -11
  109. package/dist/lucern/packages/domain-context/src/index.d.ts +0 -4
  110. package/dist/lucern/packages/domain-context/src/ports.d.ts +0 -58
  111. package/dist/lucern/packages/domain-context/src/public-types.d.ts +0 -1
  112. package/dist/lucern/packages/domain-edges/src/contradictions.d.ts +0 -59
  113. package/dist/lucern/packages/domain-edges/src/edges.d.ts +0 -91
  114. package/dist/lucern/packages/domain-edges/src/index.d.ts +0 -2
  115. package/dist/lucern/packages/domain-evidence/src/evidence.d.ts +0 -115
  116. package/dist/lucern/packages/domain-evidence/src/index.d.ts +0 -1
  117. package/dist/lucern/packages/domain-graph/src/graph.d.ts +0 -150
  118. package/dist/lucern/packages/domain-identity/src/index.d.ts +0 -1
  119. package/dist/lucern/packages/domain-identity/src/whoami.d.ts +0 -13
  120. package/dist/lucern/packages/domain-ontologies/src/ontologies.d.ts +0 -123
  121. package/dist/lucern/packages/domain-questions/src/index.d.ts +0 -1
  122. package/dist/lucern/packages/domain-questions/src/questions.d.ts +0 -147
  123. package/dist/lucern/packages/domain-search/src/search.d.ts +0 -97
  124. package/dist/lucern/packages/domain-tasks/src/index.d.ts +0 -1
  125. package/dist/lucern/packages/domain-tasks/src/tasks.d.ts +0 -102
  126. package/dist/lucern/packages/domain-topics/src/index.d.ts +0 -1
  127. package/dist/lucern/packages/domain-topics/src/topics.d.ts +0 -147
  128. package/dist/lucern/packages/domain-worktrees/src/index.d.ts +0 -1
  129. package/dist/lucern/packages/domain-worktrees/src/worktrees.d.ts +0 -185
  130. package/dist/lucern/packages/events/src/index.d.ts +0 -4
  131. package/dist/lucern/packages/events/src/matching.d.ts +0 -3
  132. package/dist/lucern/packages/events/src/outbox.d.ts +0 -15
  133. package/dist/lucern/packages/events/src/webhooks.d.ts +0 -9
  134. package/dist/lucern/packages/sdk-typescript/src/facade/beliefs.d.ts +0 -15
  135. package/dist/lucern/packages/sdk-typescript/src/facade/context.d.ts +0 -12
  136. package/dist/lucern/packages/sdk-typescript/src/facade/contradictions.d.ts +0 -7
  137. package/dist/lucern/packages/sdk-typescript/src/facade/edges.d.ts +0 -7
  138. package/dist/lucern/packages/sdk-typescript/src/facade/events.d.ts +0 -6
  139. package/dist/lucern/packages/sdk-typescript/src/facade/evidence.d.ts +0 -21
  140. package/dist/lucern/packages/sdk-typescript/src/facade/graph.d.ts +0 -10
  141. package/dist/lucern/packages/sdk-typescript/src/facade/identity.d.ts +0 -5
  142. package/dist/lucern/packages/sdk-typescript/src/facade/ontologies.d.ts +0 -8
  143. package/dist/lucern/packages/sdk-typescript/src/facade/questions.d.ts +0 -39
  144. package/dist/lucern/packages/sdk-typescript/src/facade/search.d.ts +0 -5
  145. package/dist/lucern/packages/sdk-typescript/src/facade/tasks.d.ts +0 -8
  146. package/dist/lucern/packages/sdk-typescript/src/facade/topics.d.ts +0 -10
  147. package/dist/lucern/packages/sdk-typescript/src/facade/webhooks.d.ts +0 -16
  148. package/dist/lucern/packages/sdk-typescript/src/facade/worktrees.d.ts +0 -10
  149. package/dist/lucern/packages/sdk-typescript/src/index.d.ts +0 -28
  150. package/dist/packages/sdk/src/adminClient.d.ts +0 -89
  151. package/dist/packages/sdk/src/answersClient.d.ts +0 -5
  152. package/dist/packages/sdk/src/beliefsClient.d.ts +0 -52
  153. package/dist/packages/sdk/src/contextClient.d.ts +0 -9
  154. package/dist/packages/sdk/src/contracts/api-enums.contract.d.ts +0 -79
  155. /package/dist/{packages/sdk/src → lib/platform/sdk}/version.d.ts +0 -0
package/README.md CHANGED
@@ -2,19 +2,52 @@
2
2
 
3
3
  The reasoning operating system for AI-native applications.
4
4
 
5
- Your AI agent reads 50 documents. It generates insights. A week later, it reads 50 more and has no memory of what it learned before. Every session starts from zero.
5
+ Your AI agent reads 50 documents, generates insights, and forgets everything by tomorrow. Every session starts from zero. The same questions get re-investigated. The same dead ends get explored. Nothing compounds.
6
6
 
7
- Lucern fixes this. It gives your application a knowledge graph that accumulates understanding over time. Beliefs strengthen or weaken as evidence arrives. Contradictions are detected, not hidden. Your agents get smarter with every interaction because the graph remembers what was learned, when, and why.
8
-
9
- ## Install
7
+ Lucern gives your agents a reasoning graph that accumulates understanding across sessions, across agents, and across time. Beliefs have confidence scores that change as evidence arrives. Contradictions are detected and tracked. Investigations are structured with hypotheses, evidence, and outcomes. Every mutation is traceable, every decision auditable.
10
8
 
11
9
  ```bash
12
10
  npm install @lucern/sdk
13
11
  ```
14
12
 
15
- ## Quickstart — Build an Agent That Remembers
13
+ ## Canonical Interface
14
+
15
+ `@lucern/sdk` is the canonical public interface for Lucern.
16
+
17
+ - Build applications, automations, and backend integrations against the SDK first.
18
+ - Treat `/api/platform/v1/*` as the transport mirror of the SDK surface.
19
+ - Treat MCP as an agent-facing client of the same surface, not as a privileged bypass around SDK or HTTP semantics.
20
+
21
+ IA-7 closes the remaining SDK surface gaps needed for SDK-first clients:
22
+
23
+ - Kernel mutations that previously only existed behind route or MCP adapters now have SDK wrappers across beliefs, evidence, questions, edges, topics, worktrees, and nodes.
24
+ - `lucern.identity.whoami()` exposes resolved principal context for service principals, tenant API keys, and interactive users.
25
+ - Public SDK types now export `SdkPrincipalContext` plus the `Platform*Record` and `Workflow*Record` families for typed client code.
26
+
27
+ ```typescript
28
+ import {
29
+ createLucernClient,
30
+ type PlatformBeliefRecord,
31
+ type SdkPrincipalContext,
32
+ type WorkflowWorktreeRecord,
33
+ } from "@lucern/sdk";
34
+
35
+ const lucern = createLucernClient({
36
+ apiKey: process.env.LUCERN_API_KEY,
37
+ baseUrl: "https://api.lucern.ai",
38
+ });
39
+
40
+ const identity = await lucern.identity.whoami();
41
+ const principal: SdkPrincipalContext = identity.data;
42
+ ```
43
+
44
+ ## The Full Developer Journey
45
+
46
+ This walkthrough mirrors what a developer building an AI-powered code review system would experience in a real coding session. Every API call is something you would actually use.
47
+
48
+ ### 1. Set Up Your Reasoning Scope
16
49
 
17
- Your agent processes customer support tickets and builds an evolving understanding of product issues:
50
+ Topics are how you organize knowledge. They nest hierarchically, like folders that think.
18
51
 
19
52
  ```typescript
20
53
  import { createLucernClient } from "@lucern/sdk";
@@ -24,184 +57,654 @@ const lucern = createLucernClient({
24
57
  baseUrl: "https://api.lucern.ai",
25
58
  });
26
59
 
27
- // Create a reasoning scope
28
- const topic = await lucern.topics.create({
29
- name: "Product Issue Tracker",
60
+ // Create a parent topic for your domain
61
+ const codeQuality = await lucern.topics.create({
62
+ name: "Code Quality Intelligence",
30
63
  type: "domain",
31
64
  });
32
- const topicId = topic.data.topicId;
33
65
 
34
- // Your agent processes a batch of support tickets and forms a belief
35
- const belief = await lucern.beliefs.create({
36
- topicId,
37
- canonicalText: "Authentication timeout errors are caused by the session refresh race condition, not the auth provider",
66
+ // Create child topics for specific areas
67
+ const securityTopic = await lucern.topics.create({
68
+ name: "Security Patterns",
69
+ type: "theme",
70
+ parentTopicId: codeQuality.data.topicId,
38
71
  });
39
72
 
40
- // Attach the evidence that led to this belief
41
- await lucern.evidence.create({
73
+ const performanceTopic = await lucern.topics.create({
74
+ name: "Performance Patterns",
75
+ type: "theme",
76
+ parentTopicId: codeQuality.data.topicId,
77
+ });
78
+ ```
79
+
80
+ ### 2. Populate the Graph With What You Know
81
+
82
+ Beliefs represent understanding at different epistemic levels: facts (verified), beliefs (confident), hypotheses (testing), and assumptions (untested).
83
+
84
+ ```typescript
85
+ const topicId = securityTopic.data.topicId;
86
+
87
+ // A fact — verified and anchored
88
+ const sqlFact = await lucern.beliefs.create({
42
89
  topicId,
43
- text: "12 of 15 timeout tickets occur within 200ms of token refresh. Stack traces show concurrent refresh calls.",
44
- targetId: belief.data.nodeId,
45
- weight: 0.85,
90
+ canonicalText: "Parameterized queries prevent SQL injection in all major database drivers",
91
+ beliefType: "fact",
92
+ });
93
+ await lucern.beliefs.modulateConfidence(sqlFact.data.nodeId, {
94
+ confidence: 0.95,
95
+ trigger: "evidence_added",
96
+ rationale: "OWASP verified, industry standard for 20+ years",
46
97
  });
47
98
 
48
- // Score confidence based on evidence strength
49
- await lucern.beliefs.modulateConfidence(belief.data.nodeId, {
50
- confidence: 0.75,
99
+ // A belief confident from observation
100
+ const patternBelief = await lucern.beliefs.create({
101
+ topicId,
102
+ canonicalText: "Most security vulnerabilities in our codebase come from unvalidated user input at API boundaries, not from cryptographic weaknesses",
103
+ });
104
+ await lucern.beliefs.modulateConfidence(patternBelief.data.nodeId, {
105
+ confidence: 0.82,
51
106
  trigger: "evidence_added",
52
- rationale: "Strong correlation in timing data, but haven't reproduced in staging yet",
107
+ rationale: "Last 6 months of security audits: 14 input validation issues, 1 crypto issue",
53
108
  });
54
109
 
55
- // Flag what would change this understanding
56
- await lucern.questions.create({
110
+ // A hypothesis under active testing
111
+ const hypothesis = await lucern.beliefs.create({
57
112
  topicId,
58
- text: "Does disabling concurrent refresh eliminate the timeout pattern?",
59
- priority: "high",
60
- linkedBeliefId: belief.data.nodeId,
113
+ canonicalText: "Automated static analysis catches fewer than 30% of the input validation vulnerabilities that human reviewers find",
114
+ beliefType: "hypothesis",
115
+ });
116
+ await lucern.beliefs.modulateConfidence(hypothesis.data.nodeId, {
117
+ confidence: 0.6,
118
+ trigger: "manual",
119
+ rationale: "Anecdotal — need to run a proper comparison study",
120
+ });
121
+
122
+ // An assumption — untested but used as a basis for decisions
123
+ const assumption = await lucern.beliefs.create({
124
+ topicId,
125
+ canonicalText: "Our CI pipeline runs all static analysis rules on every PR",
126
+ beliefType: "assumption",
127
+ });
128
+ ```
129
+
130
+ ### 3. Connect Beliefs With Edges
131
+
132
+ Edges express the reasoning relationships between beliefs.
133
+
134
+ ```typescript
135
+ // The pattern belief depends on the SQL injection fact
136
+ await lucern.graph.createEdge({
137
+ topicId,
138
+ sourceId: patternBelief.data.nodeId,
139
+ targetId: sqlFact.data.nodeId,
140
+ edgeType: "depends_on",
141
+ reasoning: "Input validation pattern includes SQL injection as a subclass",
142
+ reasoningMethod: "deductive",
143
+ });
144
+
145
+ // The hypothesis is derived from the pattern belief
146
+ await lucern.graph.createEdge({
147
+ topicId,
148
+ sourceId: hypothesis.data.nodeId,
149
+ targetId: patternBelief.data.nodeId,
150
+ edgeType: "derived_from",
151
+ reasoning: "If most vulns are input validation, and static analysis misses them, the tooling gap is at the input boundary",
152
+ reasoningMethod: "inductive",
153
+ });
154
+
155
+ // The hypothesis depends on an untested assumption
156
+ await lucern.graph.createEdge({
157
+ topicId,
158
+ sourceId: hypothesis.data.nodeId,
159
+ targetId: assumption.data.nodeId,
160
+ edgeType: "depends_on",
161
+ reasoning: "If the CI pipeline is not running all rules, the comparison would be invalid",
162
+ reasoningMethod: "deductive",
163
+ });
164
+ ```
165
+
166
+ ### 4. Open an Investigation With a Worktree
167
+
168
+ Worktrees are focused investigations — like a feature branch for knowledge. You test beliefs, gather evidence, and merge the findings.
169
+
170
+ ```typescript
171
+ const investigation = await lucern.worktrees.create({
172
+ topicId,
173
+ title: "Static analysis vs human review comparison",
174
+ hypothesis: "Running the same 50 PRs through both static analysis and manual review will show static analysis catches less than 30% of what humans find",
175
+ beliefIds: [hypothesis.data.nodeId],
176
+ });
177
+
178
+ // Create tasks to drive the investigation
179
+ await lucern.tasks.create({
180
+ topicId,
181
+ title: "Run Semgrep + CodeQL on the last 50 merged PRs and log findings",
182
+ linkedWorktreeId: investigation.data.worktreeId,
183
+ linkedQuestionId: comparisonQuestion.data.questionId,
184
+ taskType: "data_collection",
185
+ });
186
+
187
+ await lucern.tasks.create({
188
+ topicId,
189
+ title: "Have two senior engineers independently review the same 50 PRs",
190
+ linkedWorktreeId: investigation.data.worktreeId,
191
+ taskType: "research",
61
192
  });
62
193
  ```
63
194
 
64
- Next week, your agent processes more tickets:
195
+ ### 5. Add Evidence as You Work
196
+
197
+ Your agent processes the results and commits evidence to the graph.
65
198
 
66
199
  ```typescript
67
- // New evidence arrives that contradicts the original belief
200
+ // Static analysis results
201
+ await lucern.evidence.create({
202
+ topicId,
203
+ text: "Semgrep + CodeQL found 23 issues across 50 PRs. 18 were true positives. Categories: 12 input validation, 4 auth bypass patterns, 2 information disclosure.",
204
+ sourceUrl: "ci://semgrep-run/batch-50pr-comparison",
205
+ targetId: hypothesis.data.nodeId,
206
+ weight: 0.6, // partially supports
207
+ });
208
+
209
+ // Human review results
68
210
  await lucern.evidence.create({
69
211
  topicId,
70
- text: "Timeouts persist after disabling concurrent refresh. Network traces show upstream latency spikes from the auth provider during peak hours.",
71
- targetId: belief.data.nodeId,
72
- weight: -0.7, // contradicts
212
+ text: "Two senior engineers found 41 issues across the same 50 PRs (34 unique after dedup). Categories: 22 input validation, 7 business logic flaws, 3 auth, 2 race conditions.",
213
+ sourceUrl: "review://manual-audit/batch-50pr",
214
+ targetId: hypothesis.data.nodeId,
215
+ weight: 0.9, // strongly supports — 18/34 = 53%, even worse than hypothesized
216
+ });
217
+
218
+ // Answer the question with data
219
+ const comparisonQuestion = await lucern.questions.create({
220
+ topicId,
221
+ text: "What percentage of vulnerabilities does static analysis catch compared to human reviewers?",
222
+ priority: "high",
223
+ linkedBeliefId: hypothesis.data.nodeId,
73
224
  });
74
225
 
75
- // Confidence drops — the graph tracks the evolution
76
- await lucern.beliefs.modulateConfidence(belief.data.nodeId, {
77
- confidence: 0.3,
226
+ await lucern.questions.answer(comparisonQuestion.data.questionId, {
227
+ text: "Static analysis caught 18 of 34 unique issues (53%). However, it missed all 7 business logic flaws and both race conditions — categories where it found 0%.",
228
+ confidence: "strong",
229
+ evidenceIds: [staticEvidence.data.nodeId, humanEvidence.data.nodeId],
230
+ });
231
+ ```
232
+
233
+ ### 6. Fork a Belief When Understanding Evolves
234
+
235
+ The original hypothesis said "less than 30%." The data shows 53% — but the story is more nuanced. Fork the belief to capture the evolved understanding.
236
+
237
+ ```typescript
238
+ // Drop confidence on the original (it was too pessimistic about overall catch rate)
239
+ await lucern.beliefs.modulateConfidence(hypothesis.data.nodeId, {
240
+ confidence: 0.2,
78
241
  trigger: "evidence_added",
79
- rationale: "Fix attempt failed. Evidence now points to upstream provider, not our code.",
242
+ rationale: "Static analysis catches 53% overall, not <30%. But the category breakdown reveals something more important.",
80
243
  });
81
244
 
82
- // Fork the belief understanding has evolved
83
- const revised = await lucern.beliefs.fork(belief.data.nodeId, {
84
- newFormulation: "Authentication timeouts are caused by upstream provider latency during peak hours, compounded by our lack of request queuing",
85
- forkReason: "contradiction_response",
245
+ // Fork into a more precise belief
246
+ const evolved = await lucern.beliefs.fork(hypothesis.data.nodeId, {
247
+ newFormulation: "Static analysis catches 53% of vulnerabilities overall, but has a complete blind spot for business logic flaws and race conditions — the hardest categories to detect",
248
+ forkReason: "refinement",
86
249
  });
87
250
 
88
- await lucern.beliefs.modulateConfidence(revised.data.nodeId, {
89
- confidence: 0.82,
251
+ await lucern.beliefs.modulateConfidence(evolved.data.nodeId, {
252
+ confidence: 0.88,
90
253
  trigger: "evidence_added",
91
- rationale: "Network traces confirm provider latency. Queuing fix in PR #847 eliminated 90% of timeouts in staging.",
254
+ rationale: "Direct comparison data: 0/7 business logic flaws caught, 0/2 race conditions caught, while input validation catch rate was 12/22 (55%)",
92
255
  });
93
- ```
94
256
 
95
- The graph now tells the complete story: your agent initially believed the issue was a race condition (75% confidence), new evidence contradicted that (dropped to 30%), and the understanding evolved to identify the real cause (82% confidence on the revised belief). Every step is traceable.
257
+ // This creates a new actionable belief
258
+ const actionable = await lucern.beliefs.create({
259
+ topicId,
260
+ canonicalText: "Human code review should focus on business logic and concurrency — the categories where static analysis provides zero coverage",
261
+ beliefType: "belief",
262
+ });
96
263
 
97
- ## Why This Matters
264
+ await lucern.beliefs.modulateConfidence(actionable.data.nodeId, {
265
+ confidence: 0.85,
266
+ trigger: "worktree_outcome",
267
+ rationale: "Direct implication of the comparison study findings",
268
+ });
98
269
 
99
- Without Lucern, your agent would process the second batch of tickets with no memory of the first. It would re-discover the race condition theory, waste time investigating it again, and maybe reach the right answer — or maybe not.
270
+ // Link them
271
+ await lucern.graph.createEdge({
272
+ topicId,
273
+ sourceId: actionable.data.nodeId,
274
+ targetId: evolved.data.nodeId,
275
+ edgeType: "derived_from",
276
+ reasoning: "The review focus recommendation follows directly from the coverage gap data",
277
+ reasoningMethod: "deductive",
278
+ });
279
+ ```
280
+
281
+ ### 7. Compile Context for Your Next Agent Session
100
282
 
101
- With Lucern, the agent reads its prior beliefs before processing new tickets. It knows what it already tried. It knows what questions are still open. It starts from understanding, not from zero.
283
+ Before your agent starts its next session, it reads the graph:
102
284
 
103
285
  ```typescript
104
- // Before processing new data, the agent reads its current understanding
105
286
  const context = await lucern.context.compile(topicId, {
106
- query: "authentication timeout root cause",
287
+ query: "code review strategy and static analysis coverage",
107
288
  ranking: "weighted_v1",
108
289
  tokenBudget: 2000,
109
290
  });
110
291
 
111
- // The context pack contains:
112
- // - Active beliefs ranked by relevance and confidence
113
- // - Open questions that still need answers
114
- // - Unresolved contradictions the agent should address
115
- // - Recent evidence for grounding
116
-
117
- // Feed this to your LLM as working memory
118
- const prompt = `
119
- Current understanding:
120
- ${context.data.activeBeliefs.map(b =>
121
- `[${b.confidence}] ${b.canonicalText}`
122
- ).join("\n ")}
123
-
124
- Open questions:
125
- ${context.data.openQuestions.map(q => q.text).join("\n ")}
126
-
127
- Given this foundation, analyze the following new tickets...
128
- `;
292
+ // context.data contains:
293
+ // - activeBeliefs: ranked by confidence and relevance
294
+ // - openQuestions: what still needs investigation
295
+ // - contradictions: tensions the agent should address
296
+ // - recentEvidence: latest findings for grounding
297
+
298
+ // Your agent starts from understanding, not from zero
299
+ console.log(`
300
+ ${context.data.summary.totalBeliefs} beliefs in scope
301
+ ${context.data.summary.openQuestions} open questions
302
+ ${context.data.summary.contradictions} unresolved contradictions
303
+ `);
129
304
  ```
130
305
 
131
- This is the compound intelligence loop. Read from the graph, reason, write back. Every cycle makes the next one smarter.
306
+ This is the compound intelligence loop. Every session reads the graph, reasons against it, and writes findings back. The graph gets smarter every cycle.
307
+
308
+ ---
132
309
 
133
310
  ## Core Concepts
134
311
 
135
312
  | Concept | What It Does |
136
313
  |---------|-------------|
137
- | **Topic** | Scopes reasoning to a domain (like a database for understanding) |
138
- | **Belief** | A statement held to be true, with a confidence score that changes over time |
139
- | **Evidence** | A fact that supports or contradicts a belief, with weight and source |
140
- | **Question** | An open investigation that drives evidence collection |
141
- | **Contradiction** | An explicit tension between beliefs that must be addressed |
142
- | **Worktree** | A focused investigation (branch, test hypotheses, merge findings) |
143
- | **Confidence** | A 0-to-1 score on every belief, with append-only history showing how it changed |
314
+ | **Topic** | Scopes reasoning into a domain. Topics nest hierarchically. |
315
+ | **Belief** | A statement with a confidence score. Types: fact, belief, hypothesis, assumption. |
316
+ | **Evidence** | A weighted fact linked to beliefs. Positive weight supports, negative contradicts. |
317
+ | **Question** | An open investigation. Linked to the belief it tests. |
318
+ | **Contradiction** | An explicit tension between two beliefs. May remain permanently unresolved. |
319
+ | **Worktree** | A focused investigation. Create hypotheses, gather evidence, merge findings. |
320
+ | **Edge** | A typed relationship: supports, informs, depends_on, derived_from, contains, tests. |
321
+ | **Confidence** | 0 to 1 score with append-only history. Every change has a trigger and rationale. |
322
+ | **Task** | Execution work linked to a question or worktree. |
323
+ | **Context Pack** | The graph compiled into ranked, budgeted context for LLM injection. |
144
324
 
145
325
  ## SDK Surface
146
326
 
147
327
  ```typescript
148
328
  const lucern = createLucernClient({ apiKey, baseUrl });
149
329
 
150
- lucern.beliefs // Create, fork, archive, score beliefs
151
- lucern.evidence // Add evidence, link to beliefs with weight
152
- lucern.questions // Track what needs investigation
153
- lucern.contradictions // Detect and manage tensions
154
- lucern.topics // Organize reasoning into domains
155
- lucern.worktrees // Run focused investigations
156
- lucern.context // Compile the graph into agent-ready context
157
- lucern.graph // Traverse, analyze structure, detect bias
158
- lucern.ontologies // Define domain vocabulary
159
- lucern.tasks // Track execution work
330
+ lucern.beliefs // Create, fork, score, archive
331
+ lucern.evidence // Add weighted evidence, link to beliefs
332
+ lucern.questions // Ask, answer, track status
333
+ lucern.contradictions // Flag tensions between beliefs
334
+ lucern.topics // Nested topic hierarchy
335
+ lucern.worktrees // Focused investigations
336
+ lucern.graph // Edges, traversal, structural analysis
337
+ lucern.context // Compile graph into agent-ready context
338
+ lucern.ontologies // Domain vocabulary
339
+ lucern.tasks // Execution tracking
160
340
  lucern.audit // Full mutation history
161
- lucern.identity // Manage API keys and sessions
341
+ lucern.identity // API keys and sessions
342
+ ```
343
+
344
+ ## Graph Intelligence
345
+
346
+ The graph doesn't just store knowledge — it analyzes itself.
347
+
348
+ ### Structural Analysis
349
+
350
+ ```typescript
351
+ // Run the full analysis suite: PageRank, Louvain clustering,
352
+ // Tarjan SCC, spectral analysis, confirmation bias detection
353
+ const analysis = await lucern.graph.analyze({ topicId });
354
+
355
+ // Which beliefs are most central to your reasoning?
356
+ analysis.data.pageRank.topNodes.forEach(node => {
357
+ console.log(`${node.canonicalText} — centrality: ${node.score}`);
358
+ });
359
+
360
+ // Are there isolated belief clusters that should be connected?
361
+ analysis.data.communities.forEach(cluster => {
362
+ console.log(`Cluster "${cluster.label}": ${cluster.nodeCount} beliefs`);
363
+ });
364
+
365
+ // Any circular dependencies in your reasoning?
366
+ if (analysis.data.cycles.length > 0) {
367
+ console.warn(`Found ${analysis.data.cycles.length} circular reasoning chains`);
368
+ }
162
369
  ```
163
370
 
164
- ## Edge Types
371
+ ### Confirmation Bias Detection
165
372
 
166
- Six canonical reasoning relationships:
373
+ ```typescript
374
+ // Are you only collecting evidence that supports your beliefs?
375
+ const bias = await lucern.graph.detectBias({ topicId });
376
+
377
+ bias.data.beliefs.forEach(b => {
378
+ if (b.riskLevel === "critical") {
379
+ console.warn(
380
+ `"${b.canonicalText}" has ${b.supportingEvidence} supporting ` +
381
+ `and ${b.contradictingEvidence} contradicting evidence — ` +
382
+ `one-sided evidence base`
383
+ );
384
+ }
385
+ });
386
+ ```
387
+
388
+ ### Find Gaps in Your Reasoning
389
+
390
+ ```typescript
391
+ // What beliefs have no evidence? What questions have no answers?
392
+ const gaps = await lucern.graph.findGaps({ topicId });
393
+
394
+ console.log(`Beliefs without evidence: ${gaps.data.unsupportedBeliefs.length}`);
395
+ console.log(`Beliefs without questions: ${gaps.data.untestedBeliefs.length}`);
396
+ console.log(`Orphan evidence: ${gaps.data.unlinkedEvidence.length}`);
397
+ ```
398
+
399
+ ### Falsification — What Would Disprove Your Beliefs?
400
+
401
+ ```typescript
402
+ // Generate the questions most likely to disprove your strongest beliefs
403
+ const questions = await lucern.graph.falsify({ topicId });
404
+
405
+ questions.data.forEach(q => {
406
+ console.log(`To disprove "${q.beliefText}", ask: "${q.question}"`);
407
+ });
408
+ ```
409
+
410
+ ### Traverse the Graph
167
411
 
168
- | Edge | Meaning |
169
- |------|---------|
170
- | `supports` | Evidence reinforces a belief |
171
- | `informs` | Evidence bears on a belief (directional, weighted) |
172
- | `depends_on` | Belief B requires belief A to hold |
173
- | `derived_from` | Belief was derived from another (lineage) |
174
- | `contains` | Structural containment |
175
- | `tests` | Question tests a belief (falsification link) |
412
+ ```typescript
413
+ // Walk the reasoning chain from a belief down to its evidence
414
+ const traversal = await lucern.graph.traverse({
415
+ startNodeId: belief.data.nodeId,
416
+ direction: "down", // L3 belief -> L2 evidence -> L1 sources
417
+ maxDepth: 3,
418
+ });
419
+
420
+ traversal.data.nodes.forEach(node => {
421
+ console.log(`[${node.epistemicLayer}] ${node.canonicalText}`);
422
+ });
423
+ ```
176
424
 
177
- ## Custom Tools
425
+ ## LLM Integration Patterns
178
426
 
179
- Extend the graph with domain operations any agent can invoke:
427
+ ### Inject Reasoning Context Into Any LLM Call
180
428
 
181
429
  ```typescript
182
- import { z } from "zod";
430
+ const context = await lucern.context.compile(topicId, {
431
+ query: "security review priorities",
432
+ ranking: "weighted_v1",
433
+ tokenBudget: 3000,
434
+ includeEntities: true,
435
+ });
436
+
437
+ // The context pack is structured for direct prompt injection
438
+ const systemPrompt = `
439
+ You are a security-focused code reviewer. Your reasoning state:
440
+
441
+ FACTS (high confidence, treat as ground truth):
442
+ ${context.data.invariants
443
+ .map(b => `- [${b.confidence}] ${b.canonicalText}`)
444
+ .join("\n")}
445
+
446
+ ACTIVE BELIEFS (current understanding, may evolve):
447
+ ${context.data.activeBeliefs
448
+ .map(b => `- [${b.confidence}] ${b.canonicalText}`)
449
+ .join("\n")}
450
+
451
+ OPEN QUESTIONS (unresolved — investigate these):
452
+ ${context.data.openQuestions
453
+ .map(q => `- [${q.priority}] ${q.text}`)
454
+ .join("\n")}
455
+
456
+ CONTRADICTIONS (tensions you must address):
457
+ ${context.data.contradictions
458
+ .map(c => `- [${c.severity}] ${c.description}`)
459
+ .join("\n")}
460
+
461
+ RULES:
462
+ - If your analysis contradicts an active belief, flag it explicitly
463
+ - If you discover evidence for an open question, answer it
464
+ - Never silently override a high-confidence belief without evidence
465
+ - When uncertain, create a new question rather than stating a conclusion
466
+ `;
467
+ ```
468
+
469
+ ### Let the LLM Write Back to the Graph
470
+
471
+ ```typescript
472
+ // After your LLM generates analysis, parse its output
473
+ // and write structured findings back to the graph
474
+
475
+ const findings = await llm.generate({
476
+ system: systemPrompt,
477
+ prompt: `Review this PR diff and identify security concerns:\n${prDiff}`,
478
+ tools: [{
479
+ name: "record_finding",
480
+ description: "Record a security finding as evidence in the reasoning graph",
481
+ parameters: {
482
+ finding: { type: "string" },
483
+ severity: { type: "string", enum: ["low", "medium", "high", "critical"] },
484
+ relatedBeliefId: { type: "string", description: "ID of the belief this relates to" },
485
+ supportsOrContradicts: { type: "number", description: "-1 to 1" },
486
+ },
487
+ }],
488
+ });
489
+
490
+ // Each tool call becomes evidence in the graph
491
+ for (const call of findings.toolCalls) {
492
+ await lucern.evidence.create({
493
+ topicId,
494
+ text: call.args.finding,
495
+ sourceUrl: `pr://review/${prNumber}`,
496
+ targetId: call.args.relatedBeliefId,
497
+ weight: call.args.supportsOrContradicts,
498
+ });
499
+ }
500
+ ```
501
+
502
+ ### Search the Graph Semantically
503
+
504
+ ```typescript
505
+ // Find beliefs related to a natural language query
506
+ const results = await lucern.search.beliefs({
507
+ topicId,
508
+ query: "race conditions in authentication",
509
+ minConfidence: 0.5,
510
+ limit: 10,
511
+ });
512
+
513
+ results.data.forEach(b => {
514
+ console.log(`[${b.confidence}] ${b.canonicalText}`);
515
+ });
516
+
517
+ // Search evidence
518
+ const evidence = await lucern.search.evidence({
519
+ topicId,
520
+ query: "token refresh timing data",
521
+ limit: 5,
522
+ });
523
+ ```
524
+
525
+ ## Agent Configuration
526
+
527
+ ### CLAUDE.md / AGENTS.md Integration
528
+
529
+ Add Lucern context to your coding agent's system instructions:
530
+
531
+ ```markdown
532
+ <!-- In your CLAUDE.md or AGENTS.md -->
533
+
534
+ ## Reasoning Graph
535
+
536
+ This project uses Lucern for knowledge management. Before making
537
+ architectural decisions, check the reasoning graph:
538
+
539
+ - Read current beliefs: `lucern.beliefs.list({ topicId: "..." })`
540
+ - Check for contradictions: `lucern.contradictions.list({ topicId: "..." })`
541
+ - Compile context before analysis: `lucern.context.compile(topicId, { query: "..." })`
542
+
543
+ After making decisions, write them back:
544
+ - Create beliefs for architectural decisions
545
+ - Add evidence linking to the code/PR that validates them
546
+ - Flag contradictions when new evidence conflicts with existing beliefs
547
+ - Answer open questions when your work resolves them
183
548
 
549
+ Confidence scale:
550
+ - 0.90+: Verified in production
551
+ - 0.80-0.90: Strong evidence, working implementation
552
+ - 0.70-0.80: Directionally right, needs validation
553
+ - Below 0.70: Hypothesis, needs investigation
554
+ ```
555
+
556
+ ### Claude Code Skill
557
+
558
+ Create a Lucern skill for your coding agents at `~/.claude/skills/lucern-sdk/SKILL.md`:
559
+
560
+ ```markdown
561
+ # Lucern SDK Skill
562
+
563
+ Use this skill when building features that read or write to the
564
+ reasoning graph, or when the user asks about beliefs, evidence,
565
+ contradictions, or knowledge state.
566
+
567
+ ## Before Starting Work
568
+
569
+ Compile the current context to understand what the graph knows:
570
+
571
+ \`\`\`typescript
572
+ const context = await lucern.context.compile(topicId, {
573
+ query: "<what you're working on>",
574
+ tokenBudget: 2000,
575
+ });
576
+ \`\`\`
577
+
578
+ Check for open questions related to your task. If one exists, your work
579
+ should aim to answer it.
580
+
581
+ ## After Completing Work
582
+
583
+ Record what you learned:
584
+
585
+ \`\`\`typescript
586
+ // Create a belief for decisions made
587
+ await lucern.beliefs.create({
588
+ topicId,
589
+ canonicalText: "<what you now believe to be true>",
590
+ });
591
+
592
+ // Add evidence from your implementation
593
+ await lucern.evidence.create({
594
+ topicId,
595
+ text: "<what you observed or built>",
596
+ sourceUrl: "commit://<sha>",
597
+ targetId: beliefId,
598
+ weight: 0.8,
599
+ });
600
+
601
+ // Answer questions your work resolved
602
+ await lucern.questions.answer(questionId, {
603
+ text: "<the answer>",
604
+ confidence: "strong",
605
+ });
606
+ \`\`\`
607
+ ```
608
+
609
+ ### Custom Tool Registration for Agents
610
+
611
+ Give your agents domain-specific capabilities that interact with the graph:
612
+
613
+ ```typescript
184
614
  lucern.tools.register({
185
- namespace: "support",
186
- name: "classify_ticket",
187
- description: "Classify a support ticket and link it to relevant beliefs",
615
+ namespace: "codebase",
616
+ name: "trace_dependency",
617
+ description: "Trace how a code change would affect beliefs in the reasoning graph",
188
618
  inputSchema: z.object({
189
- ticketId: z.string(),
190
- content: z.string(),
619
+ filePath: z.string(),
620
+ changeDescription: z.string(),
191
621
  topicId: z.string(),
192
622
  }),
193
623
  outputSchema: z.object({
194
- category: z.string(),
195
- linkedBeliefs: z.array(z.string()),
196
- suggestedQuestions: z.array(z.string()),
624
+ affectedBeliefs: z.array(z.object({
625
+ beliefId: z.string(),
626
+ text: z.string(),
627
+ currentConfidence: z.number(),
628
+ impact: z.enum(["strengthens", "weakens", "invalidates"]),
629
+ })),
197
630
  }),
198
- handler: async ({ ticketId, content, topicId }) => {
199
- // Your classification logic
200
- return classifyAndLink(ticketId, content, topicId);
631
+ handler: async ({ filePath, changeDescription, topicId }) => {
632
+ // Search for beliefs related to this file/area
633
+ const related = await lucern.search.beliefs({
634
+ topicId,
635
+ query: `${filePath} ${changeDescription}`,
636
+ });
637
+ // Analyze impact...
638
+ return { affectedBeliefs: analyzeImpact(related, changeDescription) };
201
639
  },
202
640
  });
203
641
  ```
204
642
 
643
+ ## Worktree Patterns
644
+
645
+ ### List and Resume Investigations
646
+
647
+ ```typescript
648
+ // See all active investigations
649
+ const worktrees = await lucern.worktrees.list({
650
+ topicId,
651
+ status: "active",
652
+ });
653
+
654
+ worktrees.data.forEach(wt => {
655
+ console.log(`${wt.title} — phase: ${wt.phase}, beliefs: ${wt.beliefCount}`);
656
+ });
657
+
658
+ // Get the full state of an investigation
659
+ const investigation = await lucern.worktrees.get(worktreeId);
660
+ console.log(`Hypothesis: ${investigation.data.hypothesis}`);
661
+ console.log(`Questions: ${investigation.data.questionCount} open`);
662
+ console.log(`Evidence: ${investigation.data.evidenceCount} collected`);
663
+ ```
664
+
665
+ ### Merge an Investigation
666
+
667
+ When the investigation is complete, merge findings into the main graph:
668
+
669
+ ```typescript
670
+ await lucern.worktrees.merge(worktreeId, {
671
+ summary: "Static analysis catches 53% of vulns overall but has zero coverage for business logic flaws",
672
+ outcomes: [
673
+ {
674
+ beliefId: hypothesis.data.nodeId,
675
+ confidence: 0.2,
676
+ rationale: "Overall catch rate was 53%, not <30% — but the category breakdown is more important",
677
+ },
678
+ {
679
+ beliefId: evolved.data.nodeId,
680
+ confidence: 0.88,
681
+ rationale: "Direct comparison data confirms the coverage gap hypothesis at category level",
682
+ },
683
+ ],
684
+ });
685
+ ```
686
+
687
+ ## Confidence History
688
+
689
+ Every confidence change is recorded with full provenance:
690
+
691
+ ```typescript
692
+ const history = await lucern.beliefs.confidenceHistory(beliefId);
693
+
694
+ history.data.forEach(entry => {
695
+ console.log(
696
+ `${new Date(entry.timestamp).toISOString()} ` +
697
+ `${entry.previousConfidence} -> ${entry.confidence} ` +
698
+ `[${entry.trigger}] ${entry.rationale}`
699
+ );
700
+ });
701
+
702
+ // Example output:
703
+ // 2026-04-10T14:00:00Z null -> 0.60 [manual] Anecdotal observation
704
+ // 2026-04-11T09:30:00Z 0.60 -> 0.75 [evidence_added] Semgrep data supports
705
+ // 2026-04-11T16:00:00Z 0.75 -> 0.20 [evidence_added] Comparison study contradicted
706
+ ```
707
+
205
708
  ## Authentication
206
709
 
207
710
  ```typescript