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

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 (166) hide show
  1. package/.turbo/turbo-build.log +7 -0
  2. package/.turbo/turbo-typecheck.log +4 -0
  3. package/CHANGELOG.md +13 -0
  4. package/examples/README.md +69 -0
  5. package/examples/contradiction.ts +94 -0
  6. package/examples/investigation-context.ts +118 -0
  7. package/examples/questions-and-tasks.ts +55 -0
  8. package/examples/quickstart.ts +97 -0
  9. package/examples/shared.ts +318 -0
  10. package/examples/strict-public-types.ts +143 -0
  11. package/examples/worktree-lifecycle.ts +79 -0
  12. package/package.json +16 -59
  13. package/src/README.md +6 -0
  14. package/src/adminClient.ts +789 -0
  15. package/{dist/lib/platform/sdk/answersClient.d.ts → src/answersClient.ts} +17 -4
  16. package/src/audiencesClient.ts +209 -0
  17. package/src/auditClient.ts +50 -0
  18. package/src/beliefsClient.ts +319 -0
  19. package/src/client.ts +2647 -0
  20. package/src/contextClient.ts +130 -0
  21. package/src/contextFacade.ts +15 -0
  22. package/src/contextPackCompiler.ts +828 -0
  23. package/src/contextPackSchema.ts +251 -0
  24. package/src/contextTypes.ts +153 -0
  25. package/src/contracts/api-enums.contract.ts +202 -0
  26. package/src/contracts/auth-session.contract.ts +109 -0
  27. package/src/contracts/context-pack.contract.ts +700 -0
  28. package/src/contracts/contextPack.ts +1 -0
  29. package/src/contracts/index.ts +10 -0
  30. package/src/contracts/lens-filter.contract.ts +183 -0
  31. package/src/contracts/lens-workflow.contract.ts +162 -0
  32. package/src/contracts/lensFilter.ts +1 -0
  33. package/src/contracts/lensWorkflow.ts +1 -0
  34. package/src/contracts/mcp-tools.contract.ts +3636 -0
  35. package/src/contracts/mcpTools.ts +1 -0
  36. package/src/contracts/prompt.contract.ts +50 -0
  37. package/src/contracts/prompt.ts +1 -0
  38. package/src/contracts/sdk-tools.contract.ts +1457 -0
  39. package/src/contracts/sdkTools.ts +1 -0
  40. package/src/contracts/workflow-runtime.contract.ts +440 -0
  41. package/src/contracts/workflowRuntime.ts +1 -0
  42. package/src/controlObjectOwnership.ts +286 -0
  43. package/src/coreClient.ts +570 -0
  44. package/src/customTools.ts +398 -0
  45. package/src/decisionsClient.ts +286 -0
  46. package/src/domainContext.ts +15 -0
  47. package/src/events.ts +531 -0
  48. package/src/eventsCore.ts +168 -0
  49. package/src/facade/beliefs.ts +83 -0
  50. package/src/facade/context.ts +110 -0
  51. package/src/facade/contradictions.ts +29 -0
  52. package/src/facade/edges.ts +30 -0
  53. package/src/facade/events.ts +23 -0
  54. package/src/facade/evidence.ts +41 -0
  55. package/src/facade/graph.ts +38 -0
  56. package/src/facade/identity.ts +16 -0
  57. package/src/facade/ontologies.ts +34 -0
  58. package/src/facade/questions.ts +59 -0
  59. package/src/facade/search.ts +16 -0
  60. package/src/facade/tasks.ts +37 -0
  61. package/src/facade/topics.ts +42 -0
  62. package/src/facade/webhooks.ts +58 -0
  63. package/src/facade/worktrees.ts +51 -0
  64. package/src/gatewayFacades.ts +1666 -0
  65. package/src/graphClient.ts +529 -0
  66. package/src/harnessClient.ts +585 -0
  67. package/src/identityClient.ts +278 -0
  68. package/{dist/lib/platform/sdk/index.d.ts → src/index.ts} +3 -0
  69. package/src/learningClient.ts +95 -0
  70. package/src/mcpParityClient.ts +240 -0
  71. package/src/mcpParitySurface.ts +70 -0
  72. package/src/ontologyClient.ts +275 -0
  73. package/src/packRuntime.ts +3 -0
  74. package/src/packsClient.ts +260 -0
  75. package/src/policyClient.ts +572 -0
  76. package/src/promptCatalog.ts +1 -0
  77. package/src/realtime/index.ts +51 -0
  78. package/src/realtime/refs.ts +17 -0
  79. package/src/reportsClient.ts +99 -0
  80. package/src/schemaClient.ts +129 -0
  81. package/src/sdkSurface.ts +190 -0
  82. package/src/topicsClient.ts +243 -0
  83. package/src/types.ts +807 -0
  84. package/src/workflowClient.ts +826 -0
  85. package/tsconfig.json +9 -0
  86. package/dist/.generated +0 -2
  87. package/dist/index.d.ts +0 -3
  88. package/dist/index.js +0 -3
  89. package/dist/lib/platform/auth/credentials.d.ts +0 -5
  90. package/dist/lib/platform/auth/credentials.js +0 -40
  91. package/dist/lib/platform/sdk/adminClient.d.ts +0 -404
  92. package/dist/lib/platform/sdk/adminClient.js +0 -384
  93. package/dist/lib/platform/sdk/answersClient.js +0 -21
  94. package/dist/lib/platform/sdk/audiencesClient.d.ts +0 -93
  95. package/dist/lib/platform/sdk/audiencesClient.js +0 -111
  96. package/dist/lib/platform/sdk/auditClient.d.ts +0 -24
  97. package/dist/lib/platform/sdk/auditClient.js +0 -21
  98. package/dist/lib/platform/sdk/beliefsClient.d.ts +0 -157
  99. package/dist/lib/platform/sdk/beliefsClient.js +0 -124
  100. package/dist/lib/platform/sdk/client.d.ts +0 -2369
  101. package/dist/lib/platform/sdk/client.js +0 -1831
  102. package/dist/lib/platform/sdk/contextClient.d.ts +0 -21
  103. package/dist/lib/platform/sdk/contextClient.js +0 -86
  104. package/dist/lib/platform/sdk/contextPackCompiler.d.ts +0 -100
  105. package/dist/lib/platform/sdk/contextPackCompiler.js +0 -534
  106. package/dist/lib/platform/sdk/contextTypes.d.ts +0 -133
  107. package/dist/lib/platform/sdk/contextTypes.js +0 -1
  108. package/dist/lib/platform/sdk/controlObjectOwnership.d.ts +0 -308
  109. package/dist/lib/platform/sdk/controlObjectOwnership.js +0 -220
  110. package/dist/lib/platform/sdk/coreClient.d.ts +0 -139
  111. package/dist/lib/platform/sdk/coreClient.js +0 -366
  112. package/dist/lib/platform/sdk/customTools.d.ts +0 -83
  113. package/dist/lib/platform/sdk/customTools.js +0 -247
  114. package/dist/lib/platform/sdk/decisionsClient.d.ts +0 -106
  115. package/dist/lib/platform/sdk/decisionsClient.js +0 -129
  116. package/dist/lib/platform/sdk/domainContext.d.ts +0 -1
  117. package/dist/lib/platform/sdk/domainContext.js +0 -1
  118. package/dist/lib/platform/sdk/events.d.ts +0 -176
  119. package/dist/lib/platform/sdk/events.js +0 -261
  120. package/dist/lib/platform/sdk/gatewayFacades.d.ts +0 -586
  121. package/dist/lib/platform/sdk/gatewayFacades.js +0 -845
  122. package/dist/lib/platform/sdk/graphClient.d.ts +0 -266
  123. package/dist/lib/platform/sdk/graphClient.js +0 -235
  124. package/dist/lib/platform/sdk/harnessClient.d.ts +0 -309
  125. package/dist/lib/platform/sdk/harnessClient.js +0 -219
  126. package/dist/lib/platform/sdk/identityClient.d.ts +0 -134
  127. package/dist/lib/platform/sdk/identityClient.js +0 -131
  128. package/dist/lib/platform/sdk/index.js +0 -46
  129. package/dist/lib/platform/sdk/learningClient.d.ts +0 -40
  130. package/dist/lib/platform/sdk/learningClient.js +0 -53
  131. package/dist/lib/platform/sdk/mcpParityClient.d.ts +0 -69
  132. package/dist/lib/platform/sdk/mcpParityClient.js +0 -196
  133. package/dist/lib/platform/sdk/mcpParitySurface.d.ts +0 -10
  134. package/dist/lib/platform/sdk/mcpParitySurface.js +0 -57
  135. package/dist/lib/platform/sdk/ontologyClient.d.ts +0 -131
  136. package/dist/lib/platform/sdk/ontologyClient.js +0 -161
  137. package/dist/lib/platform/sdk/packRuntime.d.ts +0 -1
  138. package/dist/lib/platform/sdk/packRuntime.js +0 -1
  139. package/dist/lib/platform/sdk/packsClient.d.ts +0 -126
  140. package/dist/lib/platform/sdk/packsClient.js +0 -157
  141. package/dist/lib/platform/sdk/policyClient.d.ts +0 -293
  142. package/dist/lib/platform/sdk/policyClient.js +0 -277
  143. package/dist/lib/platform/sdk/promptCatalog.d.ts +0 -1
  144. package/dist/lib/platform/sdk/promptCatalog.js +0 -1
  145. package/dist/lib/platform/sdk/reportsClient.d.ts +0 -34
  146. package/dist/lib/platform/sdk/reportsClient.js +0 -64
  147. package/dist/lib/platform/sdk/schemaClient.d.ts +0 -59
  148. package/dist/lib/platform/sdk/schemaClient.js +0 -71
  149. package/dist/lib/platform/sdk/sdkSurface.d.ts +0 -56
  150. package/dist/lib/platform/sdk/sdkSurface.js +0 -140
  151. package/dist/lib/platform/sdk/topicsClient.d.ts +0 -78
  152. package/dist/lib/platform/sdk/topicsClient.js +0 -118
  153. package/dist/lib/platform/sdk/types.d.ts +0 -692
  154. package/dist/lib/platform/sdk/types.js +0 -1
  155. package/dist/lib/platform/sdk/version.d.ts +0 -2
  156. package/dist/lib/platform/sdk/workflowClient.d.ts +0 -313
  157. package/dist/lib/platform/sdk/workflowClient.js +0 -366
  158. package/dist/lucern/contracts/src/api-enums.contract.d.ts +0 -58
  159. package/dist/lucern/contracts/src/api-enums.contract.js +0 -147
  160. package/dist/lucern/contracts/src/lens-filter.contract.d.ts +0 -70
  161. package/dist/lucern/contracts/src/lens-filter.contract.js +0 -95
  162. package/dist/lucern/contracts/src/lens-workflow.contract.d.ts +0 -84
  163. package/dist/lucern/contracts/src/lens-workflow.contract.js +0 -54
  164. package/dist/lucern/contracts/src/mcp-tools.contract.d.ts +0 -151
  165. package/dist/lucern/contracts/src/mcp-tools.contract.js +0 -3281
  166. /package/{dist/lib/platform/sdk/version.js → src/version.ts} +0 -0
@@ -1,534 +0,0 @@
1
- import { CONTEXT_PACK_SCHEMA_VERSION, DEFAULT_COMPILATION_MODE, DEFAULT_ENTITY_LIMIT, MAX_ENTITY_LIMIT, } from "./contracts/context-pack.contract.js";
2
- import { buildInjectionPlan, parseTokenBudget, rankContextSection, rankEntities, resolveEffectiveWeights, } from "../../convex-kernel/src/compat/contextPackPolicy.js";
3
- import { validateContextPackSchema } from "../../mcp/src/contextPackSchema.js";
4
- function assertContextPackSchema(payload) {
5
- const result = validateContextPackSchema(payload);
6
- if (!result.valid) {
7
- throw new Error(`Invalid context pack payload: ${result.errors.join("; ")}`);
8
- }
9
- }
10
- function asStringArray(value) {
11
- if (!Array.isArray(value)) {
12
- return [];
13
- }
14
- return value
15
- .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
16
- .filter((entry) => entry.length > 0);
17
- }
18
- function toPositiveInt(value, fallback, max) {
19
- if (typeof value !== "number" || !Number.isFinite(value)) {
20
- return fallback;
21
- }
22
- const floored = Math.floor(value);
23
- return Math.max(1, Math.min(floored, max));
24
- }
25
- function normalizeQueryTokens(query) {
26
- if (!query) {
27
- return [];
28
- }
29
- return query
30
- .toLowerCase()
31
- .split(/[^a-z0-9]+/)
32
- .map((token) => token.trim())
33
- .filter((token) => token.length >= 2);
34
- }
35
- function parseRankingProfile(value) {
36
- return value === "baseline_v1" ? "baseline_v1" : "weighted_v1";
37
- }
38
- function beliefTypeOf(node) {
39
- if (typeof node.beliefType === "string") {
40
- return node.beliefType;
41
- }
42
- const metadata = (node.metadata || {});
43
- if (typeof metadata.beliefType === "string") {
44
- return metadata.beliefType;
45
- }
46
- return "";
47
- }
48
- function questionStatusOf(node) {
49
- const metadata = (node.metadata || {});
50
- const direct = typeof node.status === "string" ? node.status : "";
51
- const questionStatus = typeof metadata.questionStatus === "string" ? metadata.questionStatus : "";
52
- return (questionStatus || direct || "open").toLowerCase();
53
- }
54
- function isOpenQuestion(status) {
55
- return ![
56
- "answered",
57
- "archived",
58
- "closed",
59
- "resolved",
60
- "resolved_support",
61
- "resolved_contra",
62
- "belief_forked",
63
- ].includes(status);
64
- }
65
- function metadataText(payload) {
66
- return JSON.stringify(payload).toLowerCase();
67
- }
68
- function collectTopicNeighborhood(topics, rootTopicId, maxDescendantDepth = 2) {
69
- const byId = new Map();
70
- const children = new Map();
71
- for (const topic of topics) {
72
- const id = String(topic._id);
73
- byId.set(id, topic);
74
- if (!children.has(id)) {
75
- children.set(id, []);
76
- }
77
- }
78
- for (const topic of topics) {
79
- if (!topic.parentTopicId) {
80
- continue;
81
- }
82
- const parent = String(topic.parentTopicId);
83
- const id = String(topic._id);
84
- const list = children.get(parent) || [];
85
- list.push(id);
86
- children.set(parent, list);
87
- }
88
- const selected = new Set([rootTopicId]);
89
- let cursor = byId.get(rootTopicId);
90
- while (cursor?.parentTopicId) {
91
- const parentId = String(cursor.parentTopicId);
92
- if (selected.has(parentId)) {
93
- break;
94
- }
95
- selected.add(parentId);
96
- cursor = byId.get(parentId);
97
- }
98
- const queue = [
99
- { id: rootTopicId, depth: 0 },
100
- ];
101
- while (queue.length > 0) {
102
- const current = queue.shift();
103
- if (!current || current.depth >= maxDescendantDepth) {
104
- continue;
105
- }
106
- for (const childId of children.get(current.id) || []) {
107
- if (!selected.has(childId)) {
108
- selected.add(childId);
109
- }
110
- queue.push({ id: childId, depth: current.depth + 1 });
111
- }
112
- }
113
- return Array.from(selected);
114
- }
115
- function dedupeById(rows) {
116
- const seen = new Set();
117
- const output = [];
118
- for (const row of rows) {
119
- const id = row?._id ? String(row._id) : "";
120
- if (!id || seen.has(id)) {
121
- continue;
122
- }
123
- seen.add(id);
124
- output.push(row);
125
- }
126
- return output;
127
- }
128
- function candidateTimestamp(candidate) {
129
- if (!candidate || typeof candidate !== "object") {
130
- return 0;
131
- }
132
- const record = candidate;
133
- const timestamps = [record.updatedAt, record.createdAt, record.generatedAt].filter((value) => typeof value === "number" && Number.isFinite(value));
134
- return timestamps.length > 0 ? Math.max(...timestamps) : 0;
135
- }
136
- function resolveReferenceTimeMs(...collections) {
137
- let maxTimestamp = 0;
138
- for (const collection of collections) {
139
- for (const item of collection) {
140
- const timestamp = candidateTimestamp(item);
141
- if (timestamp > maxTimestamp) {
142
- maxTimestamp = timestamp;
143
- }
144
- }
145
- }
146
- return maxTimestamp;
147
- }
148
- export function planContextPackCompilation(input) {
149
- const args = input.args ?? {};
150
- const topicId = String(input.topic._id);
151
- const queryText = typeof args.query === "string" && args.query.trim().length > 0
152
- ? args.query.trim()
153
- : undefined;
154
- const tokens = normalizeQueryTokens(queryText);
155
- const limit = toPositiveInt(args.limit, 8, 25);
156
- const rankingProfile = parseRankingProfile(typeof args.ranking === "string" ? args.ranking : args.rankingProfile);
157
- const tokenBudget = parseTokenBudget(typeof args.budget === "number" ? args.budget : args.tokenBudget, 1800);
158
- const topicDepth = typeof input.topic.depth === "number" && Number.isFinite(input.topic.depth)
159
- ? input.topic.depth
160
- : 0;
161
- const requestedMaxDepth = typeof args.maxDepth === "number" && Number.isFinite(args.maxDepth)
162
- ? Math.max(1, Math.min(Math.floor(args.maxDepth), 6))
163
- : undefined;
164
- const descendantDepth = requestedMaxDepth ?? (topicDepth <= 1 ? 4 : 2);
165
- const includeEntities = args.includeEntities !== false;
166
- const compilationMode = args.mode === "delta" ? "delta" : DEFAULT_COMPILATION_MODE;
167
- const includeFailures = compilationMode === "delta" || args.includeFailures === true;
168
- const worktreeId = typeof args.worktreeId === "string" && args.worktreeId.trim().length > 0
169
- ? args.worktreeId.trim()
170
- : undefined;
171
- const sessionId = typeof args.sessionId === "string" && args.sessionId.trim().length > 0
172
- ? args.sessionId.trim()
173
- : undefined;
174
- const packWeightOverrides = Array.isArray(args.packWeightOverrides)
175
- ? args.packWeightOverrides
176
- : undefined;
177
- const effectiveWeights = resolveEffectiveWeights(packWeightOverrides);
178
- let scopedTopicIds = collectTopicNeighborhood(input.allTopics, topicId, descendantDepth);
179
- const allowedTopicIds = asStringArray(args.allowedTopicIds);
180
- if (allowedTopicIds.length > 0) {
181
- const allowedSet = new Set(allowedTopicIds);
182
- if (!allowedSet.has(topicId)) {
183
- throw new Error(`Access denied to compile context for topic ${topicId}.`);
184
- }
185
- scopedTopicIds = scopedTopicIds.filter((id) => allowedSet.has(id));
186
- }
187
- return {
188
- topicId,
189
- ...(queryText ? { queryText } : {}),
190
- tokens,
191
- limit,
192
- rankingProfile,
193
- tokenBudget,
194
- descendantDepth,
195
- includeEntities,
196
- compilationMode,
197
- includeFailures,
198
- ...(worktreeId ? { worktreeId } : {}),
199
- ...(sessionId ? { sessionId } : {}),
200
- ...(packWeightOverrides ? { packWeightOverrides } : {}),
201
- effectiveWeights,
202
- scopedTopicIds,
203
- };
204
- }
205
- export function compileContextPackFromSnapshot(snapshot) {
206
- const uniqueBeliefs = dedupeById(snapshot.beliefs);
207
- const uniqueQuestions = dedupeById(snapshot.questions);
208
- const uniqueEvidence = dedupeById(snapshot.evidence);
209
- const uniqueContradictions = dedupeById(snapshot.contradictions);
210
- const referenceTimeMs = resolveReferenceTimeMs([snapshot.topic], uniqueBeliefs, uniqueQuestions, uniqueEvidence, uniqueContradictions, snapshot.entities) || 0;
211
- const rankOptions = {
212
- effectiveWeights: snapshot.plan.effectiveWeights,
213
- includeJustifications: snapshot.plan.compilationMode === "delta",
214
- referenceTimeMs,
215
- };
216
- const invariantCandidates = uniqueBeliefs
217
- .filter((belief) => beliefTypeOf(belief).toLowerCase() === "invariant")
218
- .map((belief) => ({
219
- nodeId: String(belief._id),
220
- canonicalText: String(belief.canonicalText || ""),
221
- confidence: typeof belief.confidence === "number" ? belief.confidence : null,
222
- beliefType: beliefTypeOf(belief) || "invariant",
223
- updatedAt: belief.updatedAt || belief.createdAt || null,
224
- }));
225
- const invariants = rankContextSection("invariants", invariantCandidates.map((candidate) => ({
226
- ...candidate,
227
- id: candidate.nodeId,
228
- text: `${candidate.canonicalText} ${candidate.beliefType}`,
229
- })), snapshot.plan.tokens, snapshot.plan.limit, snapshot.plan.rankingProfile, rankOptions).map((row) => ({
230
- nodeId: row.nodeId,
231
- canonicalText: row.canonicalText,
232
- confidence: row.confidence,
233
- beliefType: row.beliefType,
234
- score: row.score,
235
- ...(row.justification ? { justification: row.justification } : {}),
236
- }));
237
- const activeBeliefCandidates = uniqueBeliefs
238
- .filter((belief) => (belief.status || "active") !== "archived")
239
- .map((belief) => ({
240
- nodeId: String(belief._id),
241
- canonicalText: String(belief.canonicalText || ""),
242
- confidence: typeof belief.confidence === "number" ? belief.confidence : null,
243
- beliefType: beliefTypeOf(belief) || null,
244
- status: belief.status || "active",
245
- updatedAt: belief.updatedAt || belief.createdAt || null,
246
- metadataText: belief.metadata && typeof belief.metadata === "object"
247
- ? metadataText(belief.metadata)
248
- : "",
249
- }));
250
- const activeBeliefs = rankContextSection("activeBeliefs", activeBeliefCandidates.map((candidate) => ({
251
- ...candidate,
252
- id: candidate.nodeId,
253
- text: `${candidate.canonicalText} ${candidate.metadataText}`,
254
- })), snapshot.plan.tokens, snapshot.plan.limit, snapshot.plan.rankingProfile, rankOptions).map((row) => ({
255
- nodeId: row.nodeId,
256
- canonicalText: row.canonicalText,
257
- confidence: row.confidence,
258
- beliefType: row.beliefType,
259
- status: row.status,
260
- updatedAt: row.updatedAt,
261
- score: row.score,
262
- ...(row.justification ? { justification: row.justification } : {}),
263
- }));
264
- const openQuestionCandidates = uniqueQuestions
265
- .map((question) => {
266
- const status = questionStatusOf(question);
267
- const metadata = question.metadata && typeof question.metadata === "object"
268
- ? question.metadata
269
- : {};
270
- return {
271
- questionId: String(question._id),
272
- text: String(question.canonicalText || ""),
273
- status,
274
- priority: typeof metadata.priority === "string" ? metadata.priority : "medium",
275
- updatedAt: question.updatedAt || question.createdAt || null,
276
- metadataText: metadataText(metadata),
277
- };
278
- })
279
- .filter((row) => isOpenQuestion(row.status));
280
- const openQuestions = rankContextSection("openQuestions", openQuestionCandidates.map((candidate) => ({
281
- ...candidate,
282
- id: candidate.questionId,
283
- text: `${candidate.text} ${candidate.metadataText}`,
284
- })), snapshot.plan.tokens, snapshot.plan.limit, snapshot.plan.rankingProfile, rankOptions).map((row) => ({
285
- questionId: row.questionId,
286
- text: row.text,
287
- status: row.status,
288
- priority: row.priority,
289
- updatedAt: row.updatedAt,
290
- score: row.score,
291
- ...(row.justification ? { justification: row.justification } : {}),
292
- }));
293
- const evidenceCandidates = uniqueEvidence.map((item) => {
294
- const metadata = item.metadata && typeof item.metadata === "object" ? item.metadata : {};
295
- return {
296
- nodeId: String(item._id),
297
- canonicalText: String(item.canonicalText || ""),
298
- sourceUrl: (typeof metadata.sourceUrl === "string" && metadata.sourceUrl) ||
299
- (typeof item.sourceUrl === "string" && item.sourceUrl) ||
300
- null,
301
- kind: (typeof metadata.kind === "string" && metadata.kind) || "observation",
302
- createdAt: item.createdAt || null,
303
- updatedAt: item.updatedAt || item.createdAt || null,
304
- metadataText: metadataText(metadata),
305
- };
306
- });
307
- const recentEvidence = rankContextSection("recentEvidence", evidenceCandidates.map((candidate) => ({
308
- ...candidate,
309
- id: candidate.nodeId,
310
- text: `${candidate.canonicalText} ${candidate.metadataText}`,
311
- })), snapshot.plan.tokens, snapshot.plan.limit, snapshot.plan.rankingProfile, rankOptions).map((row) => ({
312
- nodeId: row.nodeId,
313
- canonicalText: row.canonicalText,
314
- sourceUrl: row.sourceUrl,
315
- kind: row.kind,
316
- createdAt: row.createdAt,
317
- score: row.score,
318
- ...(row.justification ? { justification: row.justification } : {}),
319
- }));
320
- const contradictionCandidates = uniqueContradictions.map((row) => {
321
- const weight = typeof row.weight === "number" ? row.weight : 0;
322
- const severity = weight <= -0.9
323
- ? "critical"
324
- : weight <= -0.7
325
- ? "high"
326
- : weight <= -0.5
327
- ? "medium"
328
- : "low";
329
- return {
330
- contradictionId: String(row._id || row.globalId || ""),
331
- severity,
332
- status: "active",
333
- description: row.context || row.description || row.summary || "",
334
- updatedAt: row.updatedAt || row.createdAt || null,
335
- };
336
- });
337
- const contradictions = rankContextSection("contradictions", contradictionCandidates.map((candidate) => ({
338
- ...candidate,
339
- id: candidate.contradictionId,
340
- text: `${candidate.description} ${candidate.severity}`,
341
- })), snapshot.plan.tokens, snapshot.plan.limit, snapshot.plan.rankingProfile, rankOptions).map((row) => ({
342
- contradictionId: row.contradictionId,
343
- severity: row.severity,
344
- status: row.status,
345
- description: row.description,
346
- score: row.score,
347
- ...(row.justification ? { justification: row.justification } : {}),
348
- }));
349
- const entityCandidates = snapshot.entities.map((row) => ({
350
- nodeId: String(row._id),
351
- entityType: String(row.nodeType || ""),
352
- title: String(row.title || ""),
353
- canonicalText: String(row.canonicalText || ""),
354
- connectedBeliefCount: typeof row.connectedBeliefCount === "number" ? row.connectedBeliefCount : 0,
355
- connectedEvidenceCount: typeof row.connectedEvidenceCount === "number"
356
- ? row.connectedEvidenceCount
357
- : 0,
358
- metadata: row.metadata && typeof row.metadata === "object" ? row.metadata : {},
359
- updatedAt: row.updatedAt || null,
360
- }));
361
- const entityLimit = toPositiveInt(snapshot.plan.limit, DEFAULT_ENTITY_LIMIT, MAX_ENTITY_LIMIT);
362
- const rankedEntities = snapshot.plan.includeEntities
363
- ? rankEntities(entityCandidates, snapshot.plan.tokens, entityLimit).map((row) => ({
364
- nodeId: row.nodeId,
365
- entityType: row.entityType,
366
- title: row.title,
367
- connectedBeliefCount: row.connectedBeliefCount,
368
- connectedEvidenceCount: row.connectedEvidenceCount,
369
- score: row.score,
370
- ...(Object.keys(row.metadata).length > 0
371
- ? { metadata: row.metadata }
372
- : {}),
373
- }))
374
- : undefined;
375
- let failureContext;
376
- if (snapshot.plan.includeFailures && snapshot.failures) {
377
- const allFailures = snapshot.failures.filter((node) => {
378
- const metadata = (node.metadata || {});
379
- return metadata.failedApproach === true || metadata.isFailedAttempt === true;
380
- });
381
- const rankedFailures = rankContextSection("recentEvidence", allFailures.map((node) => ({
382
- id: String(node._id),
383
- text: String(node.canonicalText || ""),
384
- createdAt: node.createdAt || null,
385
- updatedAt: node.updatedAt || node.createdAt || null,
386
- })), snapshot.plan.tokens, 10, snapshot.plan.rankingProfile, rankOptions);
387
- const failures = rankedFailures.map((row) => {
388
- const original = allFailures.find((node) => String(node._id) === row.id);
389
- const metadata = (original?.metadata || {});
390
- return {
391
- attemptId: row.id,
392
- approach: String(row.text || ""),
393
- outcome: String(metadata.errorMessage || "Failed"),
394
- recordedAt: row.createdAt || referenceTimeMs || 0,
395
- score: row.score,
396
- };
397
- });
398
- const failureTexts = new Set(failures.map((failure) => failure.approach.toLowerCase().slice(0, 100)));
399
- const suppressionIds = new Set();
400
- if (snapshot.plan.sessionId && failureTexts.size > 0) {
401
- for (const evidenceRow of recentEvidence) {
402
- const evidenceText = evidenceRow.canonicalText.toLowerCase().slice(0, 100);
403
- for (const failureText of failureTexts) {
404
- if (evidenceText.includes(failureText) ||
405
- failureText.includes(evidenceText)) {
406
- suppressionIds.add(evidenceRow.nodeId);
407
- break;
408
- }
409
- }
410
- }
411
- }
412
- if (failures.length > 0) {
413
- failureContext = {
414
- failures,
415
- suppressedIds: Array.from(suppressionIds),
416
- };
417
- }
418
- }
419
- const suppressionSet = new Set(failureContext?.suppressedIds || []);
420
- const effectiveEvidence = suppressionSet.size > 0
421
- ? recentEvidence.filter((row) => !suppressionSet.has(row.nodeId))
422
- : recentEvidence;
423
- const suppressedEvidenceIds = suppressionSet.size > 0
424
- ? recentEvidence
425
- .filter((row) => suppressionSet.has(row.nodeId))
426
- .map((row) => row.nodeId)
427
- : [];
428
- const summary = {
429
- totalBeliefs: uniqueBeliefs.length,
430
- invariants: invariants.length,
431
- openQuestions: openQuestions.length,
432
- evidenceItems: uniqueEvidence.length,
433
- contradictions: contradictions.length,
434
- ...(rankedEntities ? { relatedEntities: rankedEntities.length } : {}),
435
- scopedTopics: snapshot.plan.scopedTopicIds.length,
436
- descendantDepth: snapshot.plan.descendantDepth,
437
- query: snapshot.plan.queryText || null,
438
- };
439
- const injectionPolicy = buildInjectionPlan({
440
- tokenBudget: snapshot.plan.tokenBudget,
441
- invariants: invariants.map((row) => ({
442
- nodeId: row.nodeId,
443
- canonicalText: row.canonicalText,
444
- score: row.score,
445
- })),
446
- activeBeliefs: activeBeliefs.map((row) => ({
447
- nodeId: row.nodeId,
448
- canonicalText: row.canonicalText,
449
- score: row.score,
450
- })),
451
- openQuestions: openQuestions.map((row) => ({
452
- questionId: row.questionId,
453
- text: row.text,
454
- score: row.score,
455
- })),
456
- recentEvidence: effectiveEvidence.map((row) => ({
457
- nodeId: row.nodeId,
458
- canonicalText: row.canonicalText,
459
- score: row.score,
460
- })),
461
- contradictions: contradictions.map((row) => ({
462
- contradictionId: row.contradictionId,
463
- description: row.description,
464
- score: row.score,
465
- })),
466
- trackExclusions: snapshot.plan.compilationMode === "delta",
467
- });
468
- const contextNarrative = [
469
- "Prefer invariant beliefs as hard constraints while reasoning over this scope.",
470
- "Treat open questions as unresolved work items and avoid claiming closure without evidence.",
471
- "Use recent evidence for implementation context before creating new beliefs.",
472
- "When contradictions exist, resolve explicitly (fork, lower confidence, or gather counter-evidence).",
473
- `Apply injection token budget of ${injectionPolicy.tokenBudget} with section quotas before prompt assembly.`,
474
- ];
475
- const deltaReport = snapshot.plan.compilationMode === "delta" && snapshot.plan.worktreeId
476
- ? {
477
- changedItems: [],
478
- verificationObligations: [],
479
- referencePoint: snapshot.plan.worktreeId,
480
- }
481
- : undefined;
482
- const excludedItems = [
483
- ...(injectionPolicy.excludedItems || []),
484
- ...suppressedEvidenceIds.map((id) => ({
485
- id,
486
- section: "recentEvidence",
487
- reason: "anti_repetition",
488
- score: recentEvidence.find((row) => row.nodeId === id)?.score ?? 0,
489
- })),
490
- ];
491
- const result = {
492
- schemaVersion: CONTEXT_PACK_SCHEMA_VERSION,
493
- topicId: snapshot.plan.topicId,
494
- topicName: snapshot.topic.name || "Untitled Topic",
495
- scopedTopicIds: snapshot.plan.scopedTopicIds,
496
- generatedAt: referenceTimeMs,
497
- rankingProfile: snapshot.plan.rankingProfile,
498
- summary,
499
- invariants,
500
- activeBeliefs,
501
- openQuestions,
502
- recentEvidence: effectiveEvidence,
503
- contradictions,
504
- ...(rankedEntities ? { relatedEntities: rankedEntities } : {}),
505
- contextNarrative,
506
- injectionPolicy: {
507
- ...injectionPolicy,
508
- ...(excludedItems.length > 0 ? { excludedItems } : {}),
509
- },
510
- diagnostics: {
511
- itemsScored: invariantCandidates.length +
512
- activeBeliefCandidates.length +
513
- openQuestionCandidates.length +
514
- evidenceCandidates.length +
515
- contradictionCandidates.length +
516
- entityCandidates.length,
517
- tokenBudgetUtilization: injectionPolicy.tokenBudget === 0
518
- ? 0
519
- : Number((injectionPolicy.estimatedTokens / injectionPolicy.tokenBudget).toFixed(4)),
520
- referenceTimeMs,
521
- },
522
- ...(snapshot.plan.compilationMode !== "standard"
523
- ? { compilationMode: snapshot.plan.compilationMode }
524
- : {}),
525
- ...(failureContext ? { failureContext } : {}),
526
- ...(deltaReport ? { deltaReport } : {}),
527
- ...(snapshot.plan.packWeightOverrides &&
528
- snapshot.plan.packWeightOverrides.length > 0
529
- ? { appliedWeightOverrides: snapshot.plan.packWeightOverrides }
530
- : {}),
531
- };
532
- assertContextPackSchema(result);
533
- return result;
534
- }
@@ -1,133 +0,0 @@
1
- export type ContextRankingProfile = "baseline_v1" | "hybrid_v1" | "weighted_v1";
2
- export type ContextCompilationMode = "standard" | "delta";
3
- export type ContextPackSectionKey = "invariants" | "activeBeliefs" | "openQuestions" | "recentEvidence" | "contradictions";
4
- export type RankingWeightVector = {
5
- query: number;
6
- recency: number;
7
- confidence?: number;
8
- beliefType?: number;
9
- priority?: number;
10
- severity?: number;
11
- };
12
- export type PackWeightOverride = {
13
- section: ContextPackSectionKey;
14
- weights: Partial<RankingWeightVector>;
15
- };
16
- export type CompileContextInput = {
17
- query?: string;
18
- budget?: number;
19
- ranking?: ContextRankingProfile;
20
- limit?: number;
21
- maxDepth?: number;
22
- includeEntities?: boolean;
23
- mode?: ContextCompilationMode;
24
- includeFailures?: boolean;
25
- worktreeId?: string;
26
- sessionId?: string;
27
- packWeightOverrides?: PackWeightOverride[];
28
- tokenBudget?: number;
29
- rankingProfile?: ContextRankingProfile;
30
- };
31
- export type PublicContextBelief = {
32
- beliefId: string;
33
- text: string;
34
- confidence: number | null;
35
- beliefType?: string | null;
36
- status?: string;
37
- updatedAt?: number | null;
38
- score: number;
39
- justification?: string;
40
- };
41
- export type PublicContextQuestion = {
42
- questionId: string;
43
- text: string;
44
- status: string;
45
- priority: string;
46
- updatedAt?: number | null;
47
- score: number;
48
- justification?: string;
49
- };
50
- export type PublicContextEvidence = {
51
- evidenceId: string;
52
- text: string;
53
- sourceUrl?: string | null;
54
- kind: string;
55
- createdAt?: number | null;
56
- score: number;
57
- justification?: string;
58
- };
59
- export type PublicContextContradiction = {
60
- contradictionId: string;
61
- severity: string;
62
- status: string;
63
- description: string;
64
- score: number;
65
- justification?: string;
66
- };
67
- export type PublicContextEntity = {
68
- entityId: string;
69
- entityType: string;
70
- title: string;
71
- text?: string;
72
- connectedBeliefCount: number;
73
- connectedEvidenceCount: number;
74
- score: number;
75
- metadata?: Record<string, unknown>;
76
- };
77
- export type PublicContextInjectionPolicy = {
78
- tokenBudget: number;
79
- estimatedTokens: number;
80
- sectionBudgets: Record<string, number>;
81
- sectionUsage: Record<string, number>;
82
- selected: Record<string, string[]>;
83
- excludedItems?: Array<{
84
- id: string;
85
- section: string;
86
- reason: "budget_exceeded" | "anti_repetition" | "below_threshold";
87
- score: number;
88
- }>;
89
- };
90
- export type PublicCompiledContext = {
91
- schemaVersion: string;
92
- topicId: string;
93
- topicName: string;
94
- scopedTopicIds: string[];
95
- generatedAt: number;
96
- ranking: ContextRankingProfile;
97
- summary: Record<string, unknown>;
98
- invariants: PublicContextBelief[];
99
- activeBeliefs: PublicContextBelief[];
100
- openQuestions: PublicContextQuestion[];
101
- recentEvidence: PublicContextEvidence[];
102
- contradictions: PublicContextContradiction[];
103
- relatedEntities?: PublicContextEntity[];
104
- contextNarrative: string[];
105
- injectionPolicy: PublicContextInjectionPolicy;
106
- diagnostics: Record<string, unknown>;
107
- compilationMode?: string;
108
- failureContext?: {
109
- failures: Array<{
110
- attemptId: string;
111
- approach: string;
112
- outcome: string;
113
- recordedAt: number;
114
- score: number;
115
- }>;
116
- suppressedIds: string[];
117
- };
118
- deltaReport?: {
119
- changedItems: Array<{
120
- id: string;
121
- section: string;
122
- changeType: string;
123
- summary: string;
124
- }>;
125
- verificationObligations: Array<{
126
- description: string;
127
- source: string;
128
- severity: "critical" | "high" | "medium" | "low";
129
- }>;
130
- referencePoint: string;
131
- };
132
- appliedWeightOverrides?: unknown[];
133
- };
@@ -1 +0,0 @@
1
- export {};