@lucern/graph-primitives 1.0.0 → 1.0.2

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 (202) hide show
  1. package/README.md +13 -12
  2. package/dist/beliefDecay.js +24 -17
  3. package/dist/beliefDecay.js.map +1 -1
  4. package/dist/beliefEvidenceLinks.js +32 -8
  5. package/dist/beliefEvidenceLinks.js.map +1 -1
  6. package/dist/confidencePropagationDispatch.js.map +1 -1
  7. package/dist/contradictions.js +32 -9
  8. package/dist/contradictions.js.map +1 -1
  9. package/dist/convex.d.ts +55 -12
  10. package/dist/convex.js.map +1 -1
  11. package/dist/edgeValidation.d.ts +25 -2
  12. package/dist/edges/index.d.ts +9 -2
  13. package/dist/edges/index.js.map +1 -1
  14. package/dist/edges/propagationTypes.d.ts +2 -3
  15. package/dist/edges/propagationTypes.js.map +1 -1
  16. package/dist/entityBridge.js +10 -3
  17. package/dist/entityBridge.js.map +1 -1
  18. package/dist/entityLifecycle.js +15 -3
  19. package/dist/entityLifecycle.js.map +1 -1
  20. package/dist/epistemicAnswers.js.map +1 -1
  21. package/dist/epistemicBeliefs.admin.d.ts +36 -0
  22. package/dist/epistemicBeliefs.admin.js +745 -0
  23. package/dist/epistemicBeliefs.admin.js.map +1 -0
  24. package/dist/epistemicBeliefs.backfills.d.ts +62 -0
  25. package/dist/epistemicBeliefs.backfills.js +1004 -0
  26. package/dist/epistemicBeliefs.backfills.js.map +1 -0
  27. package/dist/epistemicBeliefs.confidence.d.ts +45 -0
  28. package/dist/epistemicBeliefs.confidence.js +1285 -0
  29. package/dist/epistemicBeliefs.confidence.js.map +1 -0
  30. package/dist/epistemicBeliefs.core.d.ts +35 -0
  31. package/dist/epistemicBeliefs.core.js +1508 -0
  32. package/dist/epistemicBeliefs.core.js.map +1 -0
  33. package/dist/epistemicBeliefs.d.ts +12 -3
  34. package/dist/epistemicBeliefs.helpers.d.ts +168 -0
  35. package/dist/epistemicBeliefs.helpers.js +1060 -0
  36. package/dist/epistemicBeliefs.helpers.js.map +1 -0
  37. package/dist/epistemicBeliefs.internal.d.ts +30 -0
  38. package/dist/epistemicBeliefs.internal.js +1329 -0
  39. package/dist/epistemicBeliefs.internal.js.map +1 -0
  40. package/dist/epistemicBeliefs.js +1196 -1184
  41. package/dist/epistemicBeliefs.js.map +1 -1
  42. package/dist/epistemicBeliefs.lifecycle.d.ts +19 -0
  43. package/dist/epistemicBeliefs.lifecycle.js +1608 -0
  44. package/dist/epistemicBeliefs.lifecycle.js.map +1 -0
  45. package/dist/epistemicBeliefs.links.d.ts +30 -0
  46. package/dist/epistemicBeliefs.links.js +761 -0
  47. package/dist/epistemicBeliefs.links.js.map +1 -0
  48. package/dist/epistemicBeliefs.queries.d.ts +16 -0
  49. package/dist/epistemicBeliefs.queries.js +90 -0
  50. package/dist/epistemicBeliefs.queries.js.map +1 -0
  51. package/dist/epistemicContractHelpers.d.ts +1 -1
  52. package/dist/epistemicContractHelpers.js +1 -1
  53. package/dist/epistemicContracts.d.ts +5 -76
  54. package/dist/epistemicContracts.evaluators.d.ts +36 -0
  55. package/dist/epistemicContracts.evaluators.js +2506 -0
  56. package/dist/epistemicContracts.evaluators.js.map +1 -0
  57. package/dist/epistemicContracts.handlers.d.ts +40 -0
  58. package/dist/epistemicContracts.handlers.js +3029 -0
  59. package/dist/epistemicContracts.handlers.js.map +1 -0
  60. package/dist/epistemicContracts.js +2006 -5281
  61. package/dist/epistemicContracts.js.map +1 -1
  62. package/dist/epistemicContracts.metrics.d.ts +26 -0
  63. package/dist/epistemicContracts.metrics.js +427 -0
  64. package/dist/epistemicContracts.metrics.js.map +1 -0
  65. package/dist/epistemicContracts.types.d.ts +159 -0
  66. package/dist/epistemicContracts.types.js +3 -0
  67. package/dist/epistemicContracts.types.js.map +1 -0
  68. package/dist/epistemicEdgeCreation.d.ts +73 -0
  69. package/dist/epistemicEdgeCreation.js +450 -0
  70. package/dist/epistemicEdgeCreation.js.map +1 -0
  71. package/dist/epistemicEdges-BF-cn4i3.d.ts +43 -0
  72. package/dist/epistemicEdges.d.ts +8 -1
  73. package/dist/epistemicEdges.handlers.d.ts +20 -0
  74. package/dist/epistemicEdges.handlers.js +289 -0
  75. package/dist/epistemicEdges.handlers.js.map +1 -0
  76. package/dist/epistemicEdges.helpers.d.ts +27 -0
  77. package/dist/epistemicEdges.helpers.js +162 -0
  78. package/dist/epistemicEdges.helpers.js.map +1 -0
  79. package/dist/epistemicEdges.js +797 -875
  80. package/dist/epistemicEdges.js.map +1 -1
  81. package/dist/epistemicEdges.mutations.d.ts +39 -0
  82. package/dist/epistemicEdges.mutations.js +1365 -0
  83. package/dist/epistemicEdges.mutations.js.map +1 -0
  84. package/dist/epistemicEdges.queries.d.ts +95 -0
  85. package/dist/epistemicEdges.queries.js +851 -0
  86. package/dist/epistemicEdges.queries.js.map +1 -0
  87. package/dist/epistemicEdges.types.d.ts +32 -0
  88. package/dist/epistemicEdges.types.js +3 -0
  89. package/dist/epistemicEdges.types.js.map +1 -0
  90. package/dist/epistemicEvidence-DvfchNt7.d.ts +46 -0
  91. package/dist/epistemicEvidence.d.ts +5 -2
  92. package/dist/epistemicEvidence.js +801 -807
  93. package/dist/epistemicEvidence.js.map +1 -1
  94. package/dist/epistemicEvidenceHelpers.d.ts +71 -0
  95. package/dist/epistemicEvidenceHelpers.js +769 -0
  96. package/dist/epistemicEvidenceHelpers.js.map +1 -0
  97. package/dist/epistemicEvidenceMutations.d.ts +10 -0
  98. package/dist/epistemicEvidenceMutations.js +1421 -0
  99. package/dist/epistemicEvidenceMutations.js.map +1 -0
  100. package/dist/epistemicEvidenceQueries.d.ts +10 -0
  101. package/dist/epistemicEvidenceQueries.js +1049 -0
  102. package/dist/epistemicEvidenceQueries.js.map +1 -0
  103. package/dist/epistemicHelpers.d.ts +4 -2
  104. package/dist/epistemicHelpers.js +132 -127
  105. package/dist/epistemicHelpers.js.map +1 -1
  106. package/dist/epistemicLayerRules.d.ts +138 -0
  107. package/dist/epistemicLayerRules.js +481 -0
  108. package/dist/epistemicLayerRules.js.map +1 -0
  109. package/dist/epistemicLinking.js +1 -1
  110. package/dist/epistemicLinking.js.map +1 -1
  111. package/dist/epistemicNodeCreation.d.ts +101 -0
  112. package/dist/epistemicNodeCreation.js +709 -0
  113. package/dist/epistemicNodeCreation.js.map +1 -0
  114. package/dist/epistemicNodes-BCQxpYx_.d.ts +54 -0
  115. package/dist/epistemicNodes.d.ts +5 -1
  116. package/dist/epistemicNodes.helpers.d.ts +51 -0
  117. package/dist/epistemicNodes.helpers.js +73 -0
  118. package/dist/epistemicNodes.helpers.js.map +1 -0
  119. package/dist/epistemicNodes.internal.d.ts +34 -0
  120. package/dist/epistemicNodes.internal.js +658 -0
  121. package/dist/epistemicNodes.internal.js.map +1 -0
  122. package/dist/epistemicNodes.js +698 -693
  123. package/dist/epistemicNodes.js.map +1 -1
  124. package/dist/epistemicNodes.mutations.d.ts +34 -0
  125. package/dist/epistemicNodes.mutations.js +1153 -0
  126. package/dist/epistemicNodes.mutations.js.map +1 -0
  127. package/dist/epistemicNodes.queries.d.ts +36 -0
  128. package/dist/epistemicNodes.queries.js +619 -0
  129. package/dist/epistemicNodes.queries.js.map +1 -0
  130. package/dist/epistemicNodes.validators.d.ts +23 -0
  131. package/dist/epistemicNodes.validators.js +105 -0
  132. package/dist/epistemicNodes.validators.js.map +1 -0
  133. package/dist/epistemicQuestions-bwHd2FWE.d.ts +68 -0
  134. package/dist/epistemicQuestions.conviction.d.ts +52 -0
  135. package/dist/epistemicQuestions.conviction.js +1389 -0
  136. package/dist/epistemicQuestions.conviction.js.map +1 -0
  137. package/dist/epistemicQuestions.create.d.ts +29 -0
  138. package/dist/epistemicQuestions.create.js +1300 -0
  139. package/dist/epistemicQuestions.create.js.map +1 -0
  140. package/dist/epistemicQuestions.d.ts +10 -2
  141. package/dist/epistemicQuestions.evidence.d.ts +22 -0
  142. package/dist/epistemicQuestions.evidence.js +929 -0
  143. package/dist/epistemicQuestions.evidence.js.map +1 -0
  144. package/dist/epistemicQuestions.helpers.d.ts +69 -0
  145. package/dist/epistemicQuestions.helpers.js +824 -0
  146. package/dist/epistemicQuestions.helpers.js.map +1 -0
  147. package/dist/epistemicQuestions.js +2435 -2430
  148. package/dist/epistemicQuestions.js.map +1 -1
  149. package/dist/epistemicQuestions.lifecycle.d.ts +24 -0
  150. package/dist/epistemicQuestions.lifecycle.js +838 -0
  151. package/dist/epistemicQuestions.lifecycle.js.map +1 -0
  152. package/dist/epistemicQuestions.queries.d.ts +41 -0
  153. package/dist/epistemicQuestions.queries.js +1013 -0
  154. package/dist/epistemicQuestions.queries.js.map +1 -0
  155. package/dist/epistemicQuestions.sprint.d.ts +22 -0
  156. package/dist/epistemicQuestions.sprint.js +757 -0
  157. package/dist/epistemicQuestions.sprint.js.map +1 -0
  158. package/dist/epistemicQuestions.tail.d.ts +42 -0
  159. package/dist/epistemicQuestions.tail.js +1345 -0
  160. package/dist/epistemicQuestions.tail.js.map +1 -0
  161. package/dist/epistemicSources.js +6 -2
  162. package/dist/epistemicSources.js.map +1 -1
  163. package/dist/evaluators/index.d.ts +2 -2
  164. package/dist/evaluators/index.js +45 -5320
  165. package/dist/evaluators/index.js.map +1 -1
  166. package/dist/evaluators/lintCheckerEvaluator.d.ts +1 -1
  167. package/dist/evaluators/sentryCheckerEvaluator.d.ts +1 -1
  168. package/dist/evaluators/testRunnerEvaluator.d.ts +1 -1
  169. package/dist/evaluators/tscCheckerEvaluator.d.ts +1 -1
  170. package/dist/{graphTypes-CpgIuCdo.d.ts → graphTypes-B8VaIjnl.d.ts} +1 -1
  171. package/dist/graphTypes.d.ts +1 -1
  172. package/dist/{helpers-BYHIk5vU.d.ts → helpers-DNYfg6mo.d.ts} +2 -3
  173. package/dist/helpers.d.ts +2 -2
  174. package/dist/helpers.js.map +1 -1
  175. package/dist/{index-Dq-7R-gi.d.ts → index-C-Kyd7hD.d.ts} +1 -1
  176. package/dist/index.d.ts +160 -14
  177. package/dist/index.js +12291 -13001
  178. package/dist/index.js.map +1 -1
  179. package/dist/logicalRoleInference.js.map +1 -1
  180. package/dist/ontologyApproval.js +1 -1
  181. package/dist/ontologyApproval.js.map +1 -1
  182. package/dist/ontologyDefinitions.js +25 -7
  183. package/dist/ontologyDefinitions.js.map +1 -1
  184. package/dist/ontologyRegistry.js.map +1 -1
  185. package/dist/projectionReconciliation.js.map +1 -1
  186. package/dist/questionEvidenceLinks.js +28 -7
  187. package/dist/questionEvidenceLinks.js.map +1 -1
  188. package/dist/resolvers.js.map +1 -1
  189. package/dist/scopeResolverCompat.js.map +1 -1
  190. package/dist/topicProjectOverlay.js.map +1 -1
  191. package/dist/topicScope.js.map +1 -1
  192. package/dist/workflowBridge.js.map +1 -1
  193. package/dist/workspaceIsolation.js.map +1 -1
  194. package/package.json +4 -5
  195. package/dist/edgeValidation-CeI0wc0r.d.ts +0 -35
  196. package/dist/epistemicBeliefs-DzKjZAeC.d.ts +0 -377
  197. package/dist/epistemicEdges-CvlKnEyy.d.ts +0 -191
  198. package/dist/epistemicEvidence-xw6UUrwh.d.ts +0 -128
  199. package/dist/epistemicHelpers-DevrYgPN.d.ts +0 -329
  200. package/dist/epistemicNodes-DjSUfvyD.d.ts +0 -167
  201. package/dist/epistemicQuestions-B_nUclrH.d.ts +0 -214
  202. package/dist/index-Dct1T70K.d.ts +0 -25
@@ -0,0 +1,824 @@
1
+ import { componentsGeneric, internalMutationGeneric, internalQueryGeneric, mutationGeneric, queryGeneric, anyApi } from 'convex/server';
2
+ import { v } from 'convex/values';
3
+
4
+ // src/convex.ts
5
+ var api = anyApi;
6
+ componentsGeneric();
7
+ var internal = anyApi;
8
+ var internalMutation = internalMutationGeneric;
9
+ var internalQuery = internalQueryGeneric;
10
+ var mutation = mutationGeneric;
11
+ var query = queryGeneric;
12
+
13
+ // src/debug.ts
14
+ function isGraphPrimitiveDebugEnabled() {
15
+ const env = globalThis.process?.env;
16
+ return env?.LUCERN_COMPAT_FALLBACK_DEBUG === "1" || env?.LUCERN_GRAPH_DEBUG === "1";
17
+ }
18
+ function formatGraphPrimitiveError(error) {
19
+ if (error instanceof Error) {
20
+ return `${error.name}: ${error.message}`;
21
+ }
22
+ if (typeof error === "string") {
23
+ return error;
24
+ }
25
+ if (error === null) {
26
+ return "null";
27
+ }
28
+ if (error === void 0) {
29
+ return "undefined";
30
+ }
31
+ try {
32
+ return JSON.stringify(error);
33
+ } catch {
34
+ return Object.prototype.toString.call(error);
35
+ }
36
+ }
37
+ function debugGraphPrimitiveFallback(message, context) {
38
+ if (!isGraphPrimitiveDebugEnabled()) {
39
+ return;
40
+ }
41
+ console.debug(message, context ?? {});
42
+ }
43
+
44
+ // src/topicProjectOverlay.ts
45
+ var LEGACY_SCOPE_FIELD = "graphScopeProjectId";
46
+ function readNonEmptyString(value) {
47
+ if (typeof value !== "string") {
48
+ return;
49
+ }
50
+ const normalized = value.trim();
51
+ return normalized.length > 0 ? normalized : void 0;
52
+ }
53
+ function readStringArray(value) {
54
+ if (!Array.isArray(value)) {
55
+ return [];
56
+ }
57
+ return value.map((entry) => readNonEmptyString(entry)).filter((entry) => Boolean(entry));
58
+ }
59
+ function readMetadata(topic) {
60
+ return topic.metadata && typeof topic.metadata === "object" ? topic.metadata : {};
61
+ }
62
+ function readLegacyProjectId(value) {
63
+ if (!value) {
64
+ return;
65
+ }
66
+ return readNonEmptyString(value[LEGACY_SCOPE_FIELD]);
67
+ }
68
+ function coerceVisibility(value) {
69
+ return value === "private" || value === "team" || value === "firm" || value === "external" || value === "public" ? value : void 0;
70
+ }
71
+ function coerceStatus(value) {
72
+ return value === "active" || value === "archived" || value === "watching" ? value : void 0;
73
+ }
74
+ function mapProjectType(topic, metadata) {
75
+ const explicit = readNonEmptyString(metadata.projectType);
76
+ if (explicit) {
77
+ return explicit;
78
+ }
79
+ if (topic.type === "theme") {
80
+ return "thematic";
81
+ }
82
+ return readNonEmptyString(topic.type) || "general";
83
+ }
84
+ function isProjectLikeTopic(topic) {
85
+ const metadata = readMetadata(topic);
86
+ return topic.type === "theme" || topic.type === "thematic" || topic.type === "deal" || topic.type === "monitoring" || readLegacyProjectId(topic) !== void 0 || readNonEmptyString(metadata.projectType) !== void 0;
87
+ }
88
+ function isMissingLucernChildComponentError(error) {
89
+ const message = getErrorMessage(error);
90
+ return message.includes(
91
+ 'Child component ComponentName(Identifier("lucern")) not found'
92
+ ) || message.includes("Child component") && message.includes("lucern") && message.includes("not found");
93
+ }
94
+ function getErrorMessage(error) {
95
+ if (error instanceof Error) {
96
+ return error.message;
97
+ }
98
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
99
+ return error.message;
100
+ }
101
+ return "unknown error";
102
+ }
103
+ async function resolveTopicDoc(ctx, scopeId) {
104
+ if (ctx?.db && typeof ctx.db.get === "function") {
105
+ try {
106
+ const directTopic = await ctx.db.get(
107
+ scopeId
108
+ );
109
+ if (directTopic) {
110
+ return directTopic;
111
+ }
112
+ } catch (error) {
113
+ debugGraphPrimitiveFallback(
114
+ "[topicProjectOverlay] Failed to resolve topic by direct ID",
115
+ {
116
+ error,
117
+ scopeId
118
+ }
119
+ );
120
+ }
121
+ }
122
+ if (typeof ctx.runQuery !== "function") {
123
+ return null;
124
+ }
125
+ try {
126
+ const topic = await ctx.runQuery(api.topics.get, {
127
+ id: String(scopeId)
128
+ });
129
+ if (topic?.name !== void 0 && topic?.type !== void 0) {
130
+ return topic;
131
+ }
132
+ } catch (error) {
133
+ debugGraphPrimitiveFallback(
134
+ "[topicProjectOverlay] Failed to resolve topic by ID query",
135
+ {
136
+ error,
137
+ scopeId
138
+ }
139
+ );
140
+ }
141
+ try {
142
+ const topic = await ctx.runQuery(api.topics.getByLegacyScopeId, {
143
+ projectId: String(scopeId)
144
+ });
145
+ if (topic?.name !== void 0 && topic?.type !== void 0) {
146
+ return topic;
147
+ }
148
+ } catch (error) {
149
+ debugGraphPrimitiveFallback(
150
+ "[topicProjectOverlay] Failed to resolve topic by legacy scope ID",
151
+ { error, scopeId }
152
+ );
153
+ }
154
+ return null;
155
+ }
156
+ function materializeTopicProjectOverlay(topic, idMode = "legacy") {
157
+ const metadata = readMetadata(topic);
158
+ const topicId = String(topic._id);
159
+ const legacyProjectId = readLegacyProjectId(topic) || readLegacyProjectId(metadata) || readNonEmptyString(metadata.legacyProjectId);
160
+ const storageProjectId = legacyProjectId || topicId;
161
+ const outwardId = idMode === "topic" ? topicId : storageProjectId;
162
+ const visibility = coerceVisibility(topic.visibility) || coerceVisibility(metadata.visibility) || "private";
163
+ const status = coerceStatus(topic.status) || coerceStatus(metadata.status) || "active";
164
+ const createdAt = typeof topic.createdAt === "number" ? topic.createdAt : typeof topic._creationTime === "number" ? topic._creationTime : 0;
165
+ const updatedAt = typeof topic.updatedAt === "number" ? topic.updatedAt : typeof metadata.updatedAt === "number" ? metadata.updatedAt : createdAt;
166
+ return {
167
+ ...metadata,
168
+ _id: outwardId,
169
+ projectId: outwardId,
170
+ topicId,
171
+ storageProjectId,
172
+ legacyProjectId,
173
+ name: readNonEmptyString(topic.name) || "Untitled Theme",
174
+ type: mapProjectType(topic, metadata),
175
+ description: readNonEmptyString(topic.description),
176
+ ownerId: readNonEmptyString(metadata.ownerId) || readNonEmptyString(topic.createdBy) || "system",
177
+ sharedWith: readStringArray(metadata.sharedWith),
178
+ visibility,
179
+ tenantId: readNonEmptyString(topic.tenantId) || readNonEmptyString(metadata.tenantId),
180
+ workspaceId: readNonEmptyString(topic.workspaceId) || readNonEmptyString(metadata.workspaceId),
181
+ status,
182
+ tags: readStringArray(metadata.tags),
183
+ chatCount: typeof metadata.chatCount === "number" ? metadata.chatCount : 0,
184
+ artifactCount: typeof metadata.artifactCount === "number" ? metadata.artifactCount : 0,
185
+ lastActivityAt: typeof metadata.lastActivityAt === "number" ? metadata.lastActivityAt : updatedAt,
186
+ _creationTime: typeof topic._creationTime === "number" ? topic._creationTime : createdAt,
187
+ createdAt,
188
+ updatedAt
189
+ };
190
+ }
191
+ async function resolveTopicProjectOverlay(ctx, scopeId, options = {}) {
192
+ const topic = await resolveTopicDoc(ctx, scopeId);
193
+ if (!topic) {
194
+ return null;
195
+ }
196
+ if (options.projectLikeOnly !== false && !isProjectLikeTopic(topic)) {
197
+ return null;
198
+ }
199
+ return materializeTopicProjectOverlay(topic, options.idMode);
200
+ }
201
+ async function listTopicProjectOverlays(ctx, options = {}) {
202
+ let allTopics = [];
203
+ if (ctx?.db?.query && typeof ctx.db.query === "function") {
204
+ try {
205
+ allTopics = await ctx.db.query("topics").collect();
206
+ } catch (error) {
207
+ debugGraphPrimitiveFallback(
208
+ "[topicProjectOverlay] Failed to read topics table; falling back to API",
209
+ { error }
210
+ );
211
+ allTopics = [];
212
+ }
213
+ }
214
+ if (allTopics.length === 0 && typeof ctx.runQuery === "function") {
215
+ allTopics = (await ctx.runQuery(api.topics.list, {}) ?? []) || [];
216
+ }
217
+ return allTopics.filter(
218
+ (topic) => options.projectLikeOnly === false || isProjectLikeTopic(topic)
219
+ ).map((topic) => materializeTopicProjectOverlay(topic, options.idMode));
220
+ }
221
+ async function patchTopicProjectOverlay(ctx, scopeId, value) {
222
+ const topic = await resolveTopicDoc(ctx, scopeId);
223
+ if (!topic) {
224
+ return null;
225
+ }
226
+ const nextMetadata = { ...readMetadata(topic) };
227
+ const patch = {};
228
+ const topicUpdateArgs = {
229
+ id: String(topic._id)
230
+ };
231
+ for (const [key, rawValue] of Object.entries(value)) {
232
+ switch (key) {
233
+ case "_id":
234
+ case "projectId":
235
+ case "topicId":
236
+ case "legacyProjectId":
237
+ case "storageProjectId":
238
+ break;
239
+ case "name":
240
+ case "description":
241
+ patch[key] = rawValue;
242
+ topicUpdateArgs[key] = rawValue;
243
+ break;
244
+ case "tenantId":
245
+ case "workspaceId":
246
+ case "ownerId":
247
+ throw new Error(
248
+ `patchTopicProjectOverlay cannot mutate ${key} via component-owned topics`
249
+ );
250
+ case "status": {
251
+ const status = coerceStatus(rawValue);
252
+ if (status) {
253
+ patch.status = status;
254
+ topicUpdateArgs.status = status;
255
+ }
256
+ break;
257
+ }
258
+ case "visibility": {
259
+ const visibility = coerceVisibility(rawValue);
260
+ if (visibility) {
261
+ patch.visibility = visibility;
262
+ topicUpdateArgs.visibility = visibility;
263
+ }
264
+ break;
265
+ }
266
+ case "type": {
267
+ const projectType = readNonEmptyString(rawValue);
268
+ if (projectType) {
269
+ nextMetadata.projectType = projectType;
270
+ } else {
271
+ delete nextMetadata.projectType;
272
+ }
273
+ break;
274
+ }
275
+ case "updatedAt":
276
+ case "createdAt":
277
+ break;
278
+ default:
279
+ if (rawValue === void 0) {
280
+ delete nextMetadata[key];
281
+ } else {
282
+ nextMetadata[key] = rawValue;
283
+ }
284
+ }
285
+ }
286
+ patch.updatedAt = Date.now();
287
+ patch.metadata = nextMetadata;
288
+ topicUpdateArgs.metadata = nextMetadata;
289
+ if (typeof ctx.runMutation === "function") {
290
+ try {
291
+ await ctx.runMutation(api.topics.update, topicUpdateArgs);
292
+ } catch (error) {
293
+ if (!isMissingLucernChildComponentError(error) || !ctx?.db || typeof ctx.db.patch !== "function") {
294
+ throw error;
295
+ }
296
+ await ctx.db.patch(String(topic._id), patch);
297
+ }
298
+ } else if (ctx?.db && typeof ctx.db.patch === "function") {
299
+ await ctx.db.patch(String(topic._id), patch);
300
+ } else {
301
+ throw new Error(
302
+ "Cannot patch topic without component adapter (ctx.runMutation unavailable)"
303
+ );
304
+ }
305
+ return materializeTopicProjectOverlay({
306
+ ...topic,
307
+ ...patch,
308
+ metadata: nextMetadata
309
+ });
310
+ }
311
+
312
+ // src/resolvers.ts
313
+ function isMissingLucernChildComponentError2(error) {
314
+ const message = getErrorMessage2(error);
315
+ return message.includes(
316
+ 'Child component ComponentName(Identifier("lucern")) not found'
317
+ ) || message.includes("Child component") && message.includes("lucern") && message.includes("not found");
318
+ }
319
+ function getErrorMessage2(error) {
320
+ if (error instanceof Error) {
321
+ return error.message;
322
+ }
323
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
324
+ return error.message;
325
+ }
326
+ return "unknown error";
327
+ }
328
+ function isAdvisoryTopicPatch(value) {
329
+ const advisoryKeys = /* @__PURE__ */ new Set(["lastActivityAt", "updatedAt"]);
330
+ const keys = Object.keys(value);
331
+ return keys.length > 0 && keys.every((key) => advisoryKeys.has(key));
332
+ }
333
+ async function patchProjectWithTolerance(ctx, projectId, value) {
334
+ try {
335
+ await patchTopicProjectOverlay(ctx, projectId, value);
336
+ } catch (error) {
337
+ if (!isAdvisoryTopicPatch(value) || !isMissingLucernChildComponentError2(error)) {
338
+ throw error;
339
+ }
340
+ console.warn(
341
+ "[lucern graph-primitives] Non-fatal advisory topic patch failure",
342
+ {
343
+ projectId,
344
+ keys: Object.keys(value),
345
+ error: getErrorMessage2(error)
346
+ }
347
+ );
348
+ }
349
+ }
350
+ function defaultResolvers() {
351
+ return {
352
+ getProject: (ctx, projectId) => resolveTopicProjectOverlay(ctx, projectId, {
353
+ idMode: "legacy",
354
+ projectLikeOnly: false
355
+ }),
356
+ patchProject: (ctx, projectId, value) => patchProjectWithTolerance(ctx, projectId, value),
357
+ listTopics: (ctx) => listTopicProjectOverlays(ctx, {
358
+ idMode: "legacy"
359
+ }),
360
+ getFinalArtifact: (ctx, artifactId) => ctx.db.get(artifactId)
361
+ };
362
+ }
363
+ var resolverOverrides = {};
364
+ function resolveGraphPrimitivesAppResolvers(_ctx) {
365
+ return {
366
+ ...defaultResolvers(),
367
+ ...resolverOverrides
368
+ };
369
+ }
370
+ var LEGACY_SCOPE_FIELD2 = "graphScopeProjectId";
371
+ function asMappedProjectId(topic) {
372
+ if (!topic) {
373
+ return;
374
+ }
375
+ const directLegacyProjectId = normalizeScopeValue(topic[LEGACY_SCOPE_FIELD2]);
376
+ if (directLegacyProjectId) {
377
+ return directLegacyProjectId;
378
+ }
379
+ const metadata = topic.metadata || {};
380
+ const candidate = metadata[LEGACY_SCOPE_FIELD2] || metadata.legacyProjectId || metadata.projectId || metadata.scopeProjectId;
381
+ return candidate ? candidate : void 0;
382
+ }
383
+ function normalizeScopeValue(value) {
384
+ if (typeof value !== "string") {
385
+ return;
386
+ }
387
+ const normalized = value.trim();
388
+ return normalized.length > 0 ? normalized : void 0;
389
+ }
390
+ function pickPrimaryTopic(candidates) {
391
+ return [...candidates].sort((a, b) => {
392
+ const depthA = a.depth ?? 9999;
393
+ const depthB = b.depth ?? 9999;
394
+ if (depthA !== depthB) {
395
+ return depthA - depthB;
396
+ }
397
+ const createdA = a.createdAt ?? Number.MAX_SAFE_INTEGER;
398
+ const createdB = b.createdAt ?? Number.MAX_SAFE_INTEGER;
399
+ if (createdA !== createdB) {
400
+ return createdA - createdB;
401
+ }
402
+ return String(a.name || "").localeCompare(String(b.name || ""));
403
+ })[0];
404
+ }
405
+ async function findTopicsByScopeAlias(ctx, scopeId) {
406
+ try {
407
+ return await ctx.db.query("topics").withIndex(
408
+ "by_graph_scope_project",
409
+ (q) => q.eq(LEGACY_SCOPE_FIELD2, scopeId)
410
+ ).collect();
411
+ } catch (error) {
412
+ debugGraphPrimitiveFallback(
413
+ "[topicScope] Failed to resolve scope alias via index",
414
+ {
415
+ error,
416
+ scopeId
417
+ }
418
+ );
419
+ const topics = await ctx.db.query("topics").collect();
420
+ return topics.filter((topic) => {
421
+ const normalizedGlobalId = normalizeScopeValue(topic.globalId);
422
+ const mappedProjectId = asMappedProjectId(topic);
423
+ return String(topic._id) === scopeId || normalizedGlobalId === scopeId || mappedProjectId === scopeId;
424
+ });
425
+ }
426
+ }
427
+ async function tryResolveHostTopicById(ctx, topicId) {
428
+ if (typeof ctx.runQuery !== "function") {
429
+ return null;
430
+ }
431
+ try {
432
+ return await ctx.runQuery(api.topics.get, {
433
+ id: topicId
434
+ }) ?? null;
435
+ } catch (error) {
436
+ debugGraphPrimitiveFallback(
437
+ "[topicScope] Failed to resolve topic by host query",
438
+ {
439
+ error,
440
+ topicId
441
+ }
442
+ );
443
+ return null;
444
+ }
445
+ }
446
+ async function tryResolveHostTopicByLegacyScope(ctx, legacyScopeId) {
447
+ if (typeof ctx.runQuery !== "function") {
448
+ return null;
449
+ }
450
+ try {
451
+ return await ctx.runQuery(api.topics.getByLegacyScopeId, {
452
+ projectId: legacyScopeId
453
+ }) ?? null;
454
+ } catch (error) {
455
+ debugGraphPrimitiveFallback(
456
+ "[topicScope] Failed to resolve topic by legacy scope",
457
+ {
458
+ error,
459
+ legacyScopeId
460
+ }
461
+ );
462
+ return null;
463
+ }
464
+ }
465
+ async function resolveInheritedWorkspaceScope(ctx, topic) {
466
+ const MAX_DEPTH = 10;
467
+ let tenantId = normalizeScopeValue(topic.tenantId);
468
+ let workspaceId = normalizeScopeValue(topic.workspaceId);
469
+ if (tenantId && workspaceId) {
470
+ return { tenantId, workspaceId };
471
+ }
472
+ let current = topic;
473
+ for (let i = 0; i < MAX_DEPTH && current?.parentTopicId; i++) {
474
+ current = await ctx.db.get(current.parentTopicId);
475
+ if (!current) break;
476
+ if (!tenantId) {
477
+ tenantId = normalizeScopeValue(current.tenantId);
478
+ }
479
+ if (!workspaceId) {
480
+ workspaceId = normalizeScopeValue(current.workspaceId);
481
+ }
482
+ if (tenantId && workspaceId) break;
483
+ }
484
+ return { tenantId, workspaceId };
485
+ }
486
+ async function resolveTopicProjectScope(ctx, args) {
487
+ if (args.topicId) {
488
+ let topic = null;
489
+ try {
490
+ topic = await ctx.db.get(
491
+ args.topicId
492
+ );
493
+ } catch (error) {
494
+ debugGraphPrimitiveFallback(
495
+ "[topicScope] Failed to load topic by direct id",
496
+ {
497
+ error,
498
+ topicId: args.topicId
499
+ }
500
+ );
501
+ }
502
+ if (!topic) {
503
+ topic = await tryResolveHostTopicById(ctx, String(args.topicId));
504
+ }
505
+ if (!topic) {
506
+ topic = pickPrimaryTopic(
507
+ await findTopicsByScopeAlias(ctx, String(args.topicId))
508
+ ) ?? null;
509
+ }
510
+ if (!topic) {
511
+ throw new Error(`Topic not found: ${String(args.topicId)}`);
512
+ }
513
+ const inherited = await resolveInheritedWorkspaceScope(ctx, topic);
514
+ const mapped = asMappedProjectId(topic);
515
+ if (mapped) {
516
+ return {
517
+ topicId: topic._id,
518
+ projectId: mapped,
519
+ tenantId: inherited.tenantId,
520
+ workspaceId: inherited.workspaceId,
521
+ source: "topic"
522
+ };
523
+ }
524
+ return {
525
+ topicId: topic._id,
526
+ tenantId: inherited.tenantId,
527
+ workspaceId: inherited.workspaceId,
528
+ source: "topic"
529
+ };
530
+ }
531
+ if (args.projectId) {
532
+ let directTopic = null;
533
+ try {
534
+ directTopic = await ctx.db.get(
535
+ args.projectId
536
+ );
537
+ } catch (error) {
538
+ debugGraphPrimitiveFallback(
539
+ "[topicScope] Failed to load direct project topic",
540
+ {
541
+ error,
542
+ projectId: args.projectId
543
+ }
544
+ );
545
+ }
546
+ if (directTopic) {
547
+ const inherited = await resolveInheritedWorkspaceScope(ctx, directTopic);
548
+ const mapped = asMappedProjectId(directTopic);
549
+ return {
550
+ topicId: directTopic._id,
551
+ projectId: mapped ?? args.projectId,
552
+ tenantId: inherited.tenantId,
553
+ workspaceId: inherited.workspaceId,
554
+ source: "topic_inferred"
555
+ };
556
+ }
557
+ directTopic = await tryResolveHostTopicByLegacyScope(ctx, args.projectId);
558
+ if (directTopic) {
559
+ const inherited = await resolveInheritedWorkspaceScope(ctx, directTopic);
560
+ const mapped = asMappedProjectId(directTopic);
561
+ return {
562
+ topicId: directTopic._id,
563
+ projectId: mapped ?? args.projectId,
564
+ tenantId: inherited.tenantId,
565
+ workspaceId: inherited.workspaceId,
566
+ source: "topic_inferred"
567
+ };
568
+ }
569
+ const topics = await findTopicsByScopeAlias(ctx, args.projectId);
570
+ const primary = pickPrimaryTopic(topics);
571
+ if (primary) {
572
+ const inherited = await resolveInheritedWorkspaceScope(ctx, primary);
573
+ return {
574
+ topicId: primary._id,
575
+ projectId: args.projectId,
576
+ tenantId: inherited.tenantId,
577
+ workspaceId: inherited.workspaceId,
578
+ source: "project_mapped_topic"
579
+ };
580
+ }
581
+ throw new Error(
582
+ `Legacy project scope ${String(args.projectId)} has no mapped topic.`
583
+ );
584
+ }
585
+ throw new Error(
586
+ "Missing scope: provide topicId (preferred) or legacy projectId alias."
587
+ );
588
+ }
589
+ ({
590
+ projectId: v.optional(v.string()),
591
+ topicId: v.optional(v.string())
592
+ });
593
+
594
+ // src/epistemicQuestions.helpers.ts
595
+ var defineEpistemicMutation = mutation;
596
+ var defineEpistemicQuery = query;
597
+ var defineEpistemicInternalMutation = internalMutation;
598
+ var defineEpistemicInternalQuery = internalQuery;
599
+ function generateContentHash(text) {
600
+ const content = `question:${text.trim().toLowerCase().replace(/\s+/g, " ")}`;
601
+ let hash = 5381;
602
+ for (let i = 0; i < content.length; i++) {
603
+ hash = (hash << 5) + hash + content.charCodeAt(i);
604
+ hash &= hash;
605
+ }
606
+ return Math.abs(hash).toString(16).padStart(8, "0");
607
+ }
608
+ function buildTestsEdgeGlobalId(fromGlobalId, toGlobalId) {
609
+ return `edge-${fromGlobalId}-tests-${toGlobalId}`;
610
+ }
611
+ async function markProjectGraphDirty(ctx, projectId, topicId) {
612
+ const normalizedProjectId = typeof projectId === "string" && projectId.trim().length > 0 ? projectId : void 0;
613
+ const normalizedTopicId = typeof topicId === "string" && topicId.trim().length > 0 ? topicId : void 0;
614
+ if (!normalizedProjectId && !normalizedTopicId) {
615
+ return;
616
+ }
617
+ if (normalizedProjectId) {
618
+ await ctx.scheduler.runAfter(
619
+ 0,
620
+ internal.graphAnalysisCache.markCacheStaleInternal,
621
+ {
622
+ projectId: normalizedProjectId
623
+ }
624
+ );
625
+ }
626
+ if (normalizedTopicId) {
627
+ await ctx.scheduler.runAfter(
628
+ 0,
629
+ internal.graphAnalysisCache.markCacheStaleByTopic,
630
+ {
631
+ topicId: normalizedTopicId
632
+ }
633
+ );
634
+ }
635
+ await resolveGraphPrimitivesAppResolvers().patchProject(
636
+ ctx,
637
+ normalizedTopicId ?? normalizedProjectId,
638
+ {
639
+ lastActivityAt: Date.now()
640
+ }
641
+ );
642
+ }
643
+ function normalizeCategory(category) {
644
+ if (!category) {
645
+ return "other";
646
+ }
647
+ const lower = category.toLowerCase();
648
+ if (lower === "financial") {
649
+ return "financials";
650
+ }
651
+ const validCategories = [
652
+ "market",
653
+ "competition",
654
+ "product",
655
+ "team",
656
+ "financials",
657
+ "deal",
658
+ "risks"
659
+ ];
660
+ return validCategories.find((c) => lower.includes(c)) || "other";
661
+ }
662
+ var DEFAULT_QUESTION_PAGE_SIZE = 250;
663
+ var MAX_QUESTION_PAGE_SIZE = 1e3;
664
+ function clampQuestionLimit(limit, fallback = DEFAULT_QUESTION_PAGE_SIZE) {
665
+ if (!Number.isFinite(limit)) {
666
+ return fallback;
667
+ }
668
+ return Math.max(
669
+ 1,
670
+ Math.min(Math.floor(limit), MAX_QUESTION_PAGE_SIZE)
671
+ );
672
+ }
673
+ function dedupeQuestionNodes(nodes) {
674
+ const seen = /* @__PURE__ */ new Set();
675
+ const deduped = [];
676
+ for (const node of nodes) {
677
+ const id = String(node._id);
678
+ if (seen.has(id)) {
679
+ continue;
680
+ }
681
+ seen.add(id);
682
+ deduped.push(node);
683
+ }
684
+ return deduped;
685
+ }
686
+ function normalizeQuestionTopicId(topicId) {
687
+ return typeof topicId === "string" && topicId.trim().length > 0 ? topicId : void 0;
688
+ }
689
+ function resolveQuestionScopeId(scope) {
690
+ return normalizeQuestionTopicId(scope.topicId) ?? scope.projectId ?? void 0;
691
+ }
692
+ function logQuestionFallback(message, error, context) {
693
+ debugGraphPrimitiveFallback(message, {
694
+ error: formatGraphPrimitiveError(error),
695
+ ...context ?? {}
696
+ });
697
+ }
698
+ async function resolveQuestionScopeOrNull(ctx, args) {
699
+ if (!args.projectId && !args.topicId) {
700
+ return null;
701
+ }
702
+ try {
703
+ return await resolveTopicProjectScope(ctx, {
704
+ projectId: args.projectId ?? void 0,
705
+ topicId: args.topicId ?? void 0
706
+ });
707
+ } catch (error) {
708
+ debugGraphPrimitiveFallback(
709
+ "[epistemicQuestions] Failed to resolve question scope",
710
+ {
711
+ error: formatGraphPrimitiveError(error),
712
+ projectId: args.projectId,
713
+ topicId: args.topicId
714
+ }
715
+ );
716
+ return null;
717
+ }
718
+ }
719
+ async function getQuestionNodesForScope(ctx, scope, args) {
720
+ const fetchNodes = (query2) => typeof args?.scanLimit === "number" ? query2.order("desc").take(args.scanLimit) : query2.collect();
721
+ const topicNodes = await fetchNodes(
722
+ ctx.db.query("epistemicNodes").withIndex(
723
+ "by_topic_type",
724
+ (q) => q.eq("topicId", scope.topicId).eq("nodeType", "question")
725
+ )
726
+ );
727
+ return dedupeQuestionNodes(topicNodes).filter(
728
+ (node) => questionMatchesScope(node, scope)
729
+ );
730
+ }
731
+ async function getQuestionEdgesForScope(ctx, scope) {
732
+ const query2 = ctx.db.query("epistemicEdges").withIndex(
733
+ "by_topic",
734
+ (q) => q.eq("topicId", scope.topicId || scope.projectId)
735
+ );
736
+ return await query2.collect();
737
+ }
738
+ function questionMatchesScope(node, scope) {
739
+ return scope.topicId !== void 0 && node.topicId === scope.topicId || scope.projectId !== void 0 && node.projectId === scope.projectId;
740
+ }
741
+ function resolveLinkedWorktreeId(meta) {
742
+ const linkedWorktreeId = meta.linkedWorktreeId;
743
+ return typeof linkedWorktreeId === "string" && linkedWorktreeId.trim() ? linkedWorktreeId : null;
744
+ }
745
+ function buildLinkedWorktreeMetadata(linkedWorktreeId) {
746
+ return linkedWorktreeId ? {
747
+ linkedWorktreeId
748
+ } : {};
749
+ }
750
+ function questionMatchesWorkflowLink(meta, workflow) {
751
+ const linkedWorktreeId = resolveLinkedWorktreeId(meta);
752
+ return Boolean(
753
+ linkedWorktreeId && (linkedWorktreeId === workflow.worktreeId || linkedWorktreeId === workflow.sprintId)
754
+ );
755
+ }
756
+ function flattenQuestionNode(n) {
757
+ const meta = n.metadata || {};
758
+ const linkedWorktreeId = resolveLinkedWorktreeId(meta);
759
+ return {
760
+ ...n,
761
+ question: n.canonicalText || "",
762
+ category: meta.category || "other",
763
+ priority: meta.priority || "medium",
764
+ status: meta.questionStatus || meta.status || "open",
765
+ beliefId: meta.linkedBeliefNodeId || meta.beliefId || null,
766
+ relatedBeliefIds: meta.relatedBeliefIds || [],
767
+ relatedInsightIds: meta.relatedInsightIds || [],
768
+ linkedWorktreeId,
769
+ sprintIndex: meta.sprintIndex || void 0,
770
+ linkedBeliefId: meta.linkedBeliefNodeId || null,
771
+ testType: meta.testType || "validates",
772
+ importance: meta.importance || 5,
773
+ isKeyQuestion: meta.isKeyQuestion || false,
774
+ answer: meta.answer || null,
775
+ convictionStage: meta.convictionStage || null,
776
+ conviction: meta.conviction ?? null,
777
+ source: meta.source || "ai_suggested"
778
+ };
779
+ }
780
+ function flattenInternalQuestionNode(n) {
781
+ const meta = n.metadata || {};
782
+ const flattened = flattenQuestionNode(n);
783
+ return {
784
+ ...flattened,
785
+ _epistemicNodeId: n._id,
786
+ questionType: n.questionType || meta.questionType || flattened.testType,
787
+ linkedBeliefIds: flattened.relatedBeliefIds,
788
+ audienceLabel: n.audienceLabel,
789
+ policyTags: n.policyTags,
790
+ sensitivityTier: n.sensitivityTier,
791
+ exportClass: n.exportClass,
792
+ anonymizationClass: n.anonymizationClass
793
+ };
794
+ }
795
+ var INACTIVE_NODE_STATUSES = /* @__PURE__ */ new Set(["archived", "superseded", "deleted"]);
796
+ var INACTIVE_METADATA_STATUSES = /* @__PURE__ */ new Set([
797
+ "archived",
798
+ "superseded",
799
+ "deleted"
800
+ ]);
801
+ function getQuestionStatusCandidates(node) {
802
+ const meta = node.metadata || {};
803
+ return [meta.questionStatus, meta.status, node.status].filter(
804
+ (value) => typeof value === "string"
805
+ );
806
+ }
807
+ function isActiveQuestionNode(node) {
808
+ if (INACTIVE_NODE_STATUSES.has(node.status)) {
809
+ return false;
810
+ }
811
+ return !getQuestionStatusCandidates(node).some(
812
+ (status) => INACTIVE_METADATA_STATUSES.has(status.toLowerCase())
813
+ );
814
+ }
815
+ function matchesRequestedQuestionStatus(node, requestedStatus) {
816
+ const normalizedStatus = requestedStatus.toLowerCase();
817
+ return getQuestionStatusCandidates(node).some(
818
+ (status) => status.toLowerCase() === normalizedStatus
819
+ );
820
+ }
821
+
822
+ export { MAX_QUESTION_PAGE_SIZE, buildLinkedWorktreeMetadata, buildTestsEdgeGlobalId, clampQuestionLimit, dedupeQuestionNodes, defineEpistemicInternalMutation, defineEpistemicInternalQuery, defineEpistemicMutation, defineEpistemicQuery, flattenInternalQuestionNode, flattenQuestionNode, generateContentHash, getQuestionEdgesForScope, getQuestionNodesForScope, isActiveQuestionNode, logQuestionFallback, markProjectGraphDirty, matchesRequestedQuestionStatus, normalizeCategory, normalizeQuestionTopicId, questionMatchesScope, questionMatchesWorkflowLink, resolveLinkedWorktreeId, resolveQuestionScopeId, resolveQuestionScopeOrNull };
823
+ //# sourceMappingURL=epistemicQuestions.helpers.js.map
824
+ //# sourceMappingURL=epistemicQuestions.helpers.js.map