@lucern/sdk 0.2.0-alpha.4 → 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 +31 -0
  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
@@ -0,0 +1,21 @@
1
+ import { type GatewayClientConfig } from "./coreClient";
2
+ import type { CompileContextInput, PublicCompiledContext } from "./contextTypes";
3
+ /** Configuration for the context client. */
4
+ export type ContextClientConfig = GatewayClientConfig;
5
+ /** Alias for the compiled context payload returned by the gateway. */
6
+ export type CompileContextResponse = PublicCompiledContext;
7
+ /**
8
+ * Create the context client for compiling reasoning context packs.
9
+ * @param config - Gateway transport configuration.
10
+ * @returns An object with a `compile` method for building context packs.
11
+ */
12
+ export declare function createContextClient(config?: ContextClientConfig): {
13
+ /**
14
+ * Compile a focused reasoning context pack for a topic scope.
15
+ * @param topicId - The topic to compile context for.
16
+ * @param input - Optional compile parameters (query, budget, ranking, etc.).
17
+ * @returns The compiled context payload with beliefs, questions, and evidence.
18
+ */
19
+ compile(topicId: string, input?: CompileContextInput): Promise<import("./coreClient").PlatformGatewaySuccess<PublicCompiledContext>>;
20
+ };
21
+ export type { CompileContextInput, PublicCompiledContext } from "./contextTypes";
@@ -0,0 +1,86 @@
1
+ import { createGatewayRequestClient, } from "./coreClient.js";
2
+ function cleanString(value) {
3
+ return typeof value === "string" && value.trim().length > 0
4
+ ? value.trim()
5
+ : undefined;
6
+ }
7
+ function cleanNumber(value) {
8
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
9
+ }
10
+ function cleanBoolean(value) {
11
+ return typeof value === "boolean" ? value : undefined;
12
+ }
13
+ function buildCompileContextRequest(topicId, input = {}) {
14
+ const payload = { topicId };
15
+ const query = cleanString(input.query);
16
+ if (query) {
17
+ payload.query = query;
18
+ }
19
+ const budget = cleanNumber(input.budget) ?? cleanNumber(input.tokenBudget);
20
+ if (budget !== undefined) {
21
+ payload.budget = budget;
22
+ }
23
+ const ranking = cleanString(input.ranking) ?? cleanString(input.rankingProfile);
24
+ if (ranking) {
25
+ payload.ranking = ranking;
26
+ }
27
+ const limit = cleanNumber(input.limit);
28
+ if (limit !== undefined) {
29
+ payload.limit = limit;
30
+ }
31
+ const maxDepth = cleanNumber(input.maxDepth);
32
+ if (maxDepth !== undefined) {
33
+ payload.maxDepth = maxDepth;
34
+ }
35
+ const includeEntities = cleanBoolean(input.includeEntities);
36
+ if (includeEntities !== undefined) {
37
+ payload.includeEntities = includeEntities;
38
+ }
39
+ const mode = cleanString(input.mode);
40
+ if (mode) {
41
+ payload.mode = mode;
42
+ }
43
+ const includeFailures = cleanBoolean(input.includeFailures);
44
+ if (includeFailures !== undefined) {
45
+ payload.includeFailures = includeFailures;
46
+ }
47
+ const worktreeId = cleanString(input.worktreeId);
48
+ if (worktreeId) {
49
+ payload.worktreeId = worktreeId;
50
+ }
51
+ const sessionId = cleanString(input.sessionId);
52
+ if (sessionId) {
53
+ payload.sessionId = sessionId;
54
+ }
55
+ if (Array.isArray(input.packWeightOverrides) && input.packWeightOverrides.length > 0) {
56
+ payload.packWeightOverrides = input.packWeightOverrides;
57
+ }
58
+ return {
59
+ path: "/api/platform/v1/context/compile",
60
+ method: "POST",
61
+ body: payload,
62
+ };
63
+ }
64
+ /**
65
+ * Create the context client for compiling reasoning context packs.
66
+ * @param config - Gateway transport configuration.
67
+ * @returns An object with a `compile` method for building context packs.
68
+ */
69
+ export function createContextClient(config = {}) {
70
+ const gateway = createGatewayRequestClient(config);
71
+ return {
72
+ /**
73
+ * Compile a focused reasoning context pack for a topic scope.
74
+ * @param topicId - The topic to compile context for.
75
+ * @param input - Optional compile parameters (query, budget, ranking, etc.).
76
+ * @returns The compiled context payload with beliefs, questions, and evidence.
77
+ */
78
+ async compile(topicId, input = {}) {
79
+ const request = buildCompileContextRequest(topicId, input);
80
+ return gateway.request({
81
+ ...request,
82
+ body: request.body,
83
+ });
84
+ },
85
+ };
86
+ }
@@ -1,6 +1,5 @@
1
- import { type ContextCompilationMode, type ContextPackV1, type PackWeightOverride } from "../../../contracts/src/context-pack.contract";
2
- import { resolveEffectiveWeights } from "../../../mcp-server/src/context-pack-policy";
3
- import { type ContextRankingProfile } from "../../../mcp-server/src/context-pack-schema";
1
+ import { type ContextCompilationMode, type ContextPackV1, type PackWeightOverride, type ContextRankingProfile } from "./contracts/context-pack.contract";
2
+ import { resolveEffectiveWeights } from "../../convex-kernel/src/compat/contextPackPolicy";
4
3
  export type ContextPackTopicRow = {
5
4
  _id: string;
6
5
  name?: string;
@@ -0,0 +1,534 @@
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
+ }