@lucern/graph-primitives 0.1.0-alpha.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 (224) hide show
  1. package/README.md +29 -0
  2. package/dist/beliefDecay-Q_26RTc-.d.ts +72 -0
  3. package/dist/beliefDecay.d.ts +2 -0
  4. package/dist/beliefDecay.js +1628 -0
  5. package/dist/beliefDecay.js.map +1 -0
  6. package/dist/beliefEvidenceLinks-42FlR48t.d.ts +77 -0
  7. package/dist/beliefEvidenceLinks.d.ts +1 -0
  8. package/dist/beliefEvidenceLinks.js +1978 -0
  9. package/dist/beliefEvidenceLinks.js.map +1 -0
  10. package/dist/beliefLifecycle-C-AehZgF.d.ts +43 -0
  11. package/dist/beliefLifecycle.d.ts +1 -0
  12. package/dist/beliefLifecycle.js +98 -0
  13. package/dist/beliefLifecycle.js.map +1 -0
  14. package/dist/confidencePropagationDispatch.d.ts +46 -0
  15. package/dist/confidencePropagationDispatch.js +744 -0
  16. package/dist/confidencePropagationDispatch.js.map +1 -0
  17. package/dist/contradictions-Hdwl7zid.d.ts +71 -0
  18. package/dist/contradictions.d.ts +1 -0
  19. package/dist/contradictions.js +1557 -0
  20. package/dist/contradictions.js.map +1 -0
  21. package/dist/convex.d.ts +23 -0
  22. package/dist/convex.js +17 -0
  23. package/dist/convex.js.map +1 -0
  24. package/dist/edgeValidation-CeI0wc0r.d.ts +35 -0
  25. package/dist/edgeValidation.d.ts +2 -0
  26. package/dist/edgeValidation.js +307 -0
  27. package/dist/edgeValidation.js.map +1 -0
  28. package/dist/edges/contains.d.ts +6 -0
  29. package/dist/edges/contains.js +14 -0
  30. package/dist/edges/contains.js.map +1 -0
  31. package/dist/edges/contradicts.d.ts +6 -0
  32. package/dist/edges/contradicts.js +183 -0
  33. package/dist/edges/contradicts.js.map +1 -0
  34. package/dist/edges/dependsOn.d.ts +6 -0
  35. package/dist/edges/dependsOn.js +240 -0
  36. package/dist/edges/dependsOn.js.map +1 -0
  37. package/dist/edges/derivedFrom.d.ts +6 -0
  38. package/dist/edges/derivedFrom.js +14 -0
  39. package/dist/edges/derivedFrom.js.map +1 -0
  40. package/dist/edges/elaborates.d.ts +6 -0
  41. package/dist/edges/elaborates.js +100 -0
  42. package/dist/edges/elaborates.js.map +1 -0
  43. package/dist/edges/index.d.ts +3 -0
  44. package/dist/edges/index.js +556 -0
  45. package/dist/edges/index.js.map +1 -0
  46. package/dist/edges/informs.d.ts +6 -0
  47. package/dist/edges/informs.js +112 -0
  48. package/dist/edges/informs.js.map +1 -0
  49. package/dist/edges/propagationTypes.d.ts +39 -0
  50. package/dist/edges/propagationTypes.js +17 -0
  51. package/dist/edges/propagationTypes.js.map +1 -0
  52. package/dist/edges/refutes.d.ts +6 -0
  53. package/dist/edges/refutes.js +108 -0
  54. package/dist/edges/refutes.js.map +1 -0
  55. package/dist/edges/supports.d.ts +6 -0
  56. package/dist/edges/supports.js +193 -0
  57. package/dist/edges/supports.js.map +1 -0
  58. package/dist/edges/tests.d.ts +6 -0
  59. package/dist/edges/tests.js +14 -0
  60. package/dist/edges/tests.js.map +1 -0
  61. package/dist/edges/utils.d.ts +12 -0
  62. package/dist/edges/utils.js +188 -0
  63. package/dist/edges/utils.js.map +1 -0
  64. package/dist/embeddingTrigger.d.ts +24 -0
  65. package/dist/embeddingTrigger.js +24 -0
  66. package/dist/embeddingTrigger.js.map +1 -0
  67. package/dist/entityBridge-DMaKooYn.d.ts +59 -0
  68. package/dist/entityBridge.d.ts +1 -0
  69. package/dist/entityBridge.js +663 -0
  70. package/dist/entityBridge.js.map +1 -0
  71. package/dist/entityLifecycle-BkhRJ-XI.d.ts +69 -0
  72. package/dist/entityLifecycle.d.ts +1 -0
  73. package/dist/entityLifecycle.js +2083 -0
  74. package/dist/entityLifecycle.js.map +1 -0
  75. package/dist/entityValidation-KLZ_Xl2D.d.ts +50 -0
  76. package/dist/entityValidation.d.ts +3 -0
  77. package/dist/entityValidation.js +71 -0
  78. package/dist/entityValidation.js.map +1 -0
  79. package/dist/epistemicAnswers-DSP1slZ9.d.ts +67 -0
  80. package/dist/epistemicAnswers.d.ts +1 -0
  81. package/dist/epistemicAnswers.js +1650 -0
  82. package/dist/epistemicAnswers.js.map +1 -0
  83. package/dist/epistemicBeliefs-DtFVTp-k.d.ts +377 -0
  84. package/dist/epistemicBeliefs.d.ts +5 -0
  85. package/dist/epistemicBeliefs.js +6386 -0
  86. package/dist/epistemicBeliefs.js.map +1 -0
  87. package/dist/epistemicContractHelpers.d.ts +1 -0
  88. package/dist/epistemicContractHelpers.js +320 -0
  89. package/dist/epistemicContractHelpers.js.map +1 -0
  90. package/dist/epistemicContracts.d.ts +77 -0
  91. package/dist/epistemicContracts.js +8436 -0
  92. package/dist/epistemicContracts.js.map +1 -0
  93. package/dist/epistemicEdges-DcA8ErUG.d.ts +191 -0
  94. package/dist/epistemicEdges.d.ts +2 -0
  95. package/dist/epistemicEdges.js +2749 -0
  96. package/dist/epistemicEdges.js.map +1 -0
  97. package/dist/epistemicEvidence-Bo638XDP.d.ts +128 -0
  98. package/dist/epistemicEvidence.d.ts +3 -0
  99. package/dist/epistemicEvidence.js +3282 -0
  100. package/dist/epistemicEvidence.js.map +1 -0
  101. package/dist/epistemicHelpers-Bd9xbaib.d.ts +329 -0
  102. package/dist/epistemicHelpers.d.ts +4 -0
  103. package/dist/epistemicHelpers.js +999 -0
  104. package/dist/epistemicHelpers.js.map +1 -0
  105. package/dist/epistemicLinking-CyeLOIzN.d.ts +35 -0
  106. package/dist/epistemicLinking.d.ts +1 -0
  107. package/dist/epistemicLinking.js +1391 -0
  108. package/dist/epistemicLinking.js.map +1 -0
  109. package/dist/epistemicNodes-BpD6Koud.d.ts +167 -0
  110. package/dist/epistemicNodes.d.ts +2 -0
  111. package/dist/epistemicNodes.js +2942 -0
  112. package/dist/epistemicNodes.js.map +1 -0
  113. package/dist/epistemicQuestions-CmEeY6zQ.d.ts +214 -0
  114. package/dist/epistemicQuestions.d.ts +3 -0
  115. package/dist/epistemicQuestions.js +4993 -0
  116. package/dist/epistemicQuestions.js.map +1 -0
  117. package/dist/epistemicSources-ZazxHOK1.d.ts +25 -0
  118. package/dist/epistemicSources.d.ts +1 -0
  119. package/dist/epistemicSources.js +2025 -0
  120. package/dist/epistemicSources.js.map +1 -0
  121. package/dist/evaluators/index.d.ts +9 -0
  122. package/dist/evaluators/index.js +8440 -0
  123. package/dist/evaluators/index.js.map +1 -0
  124. package/dist/evaluators/lintCheckerEvaluator.d.ts +11 -0
  125. package/dist/evaluators/lintCheckerEvaluator.js +155 -0
  126. package/dist/evaluators/lintCheckerEvaluator.js.map +1 -0
  127. package/dist/evaluators/sentryCheckerEvaluator.d.ts +11 -0
  128. package/dist/evaluators/sentryCheckerEvaluator.js +126 -0
  129. package/dist/evaluators/sentryCheckerEvaluator.js.map +1 -0
  130. package/dist/evaluators/shared.d.ts +27 -0
  131. package/dist/evaluators/shared.js +92 -0
  132. package/dist/evaluators/shared.js.map +1 -0
  133. package/dist/evaluators/testRunnerEvaluator.d.ts +17 -0
  134. package/dist/evaluators/testRunnerEvaluator.js +232 -0
  135. package/dist/evaluators/testRunnerEvaluator.js.map +1 -0
  136. package/dist/evaluators/tscCheckerEvaluator.d.ts +11 -0
  137. package/dist/evaluators/tscCheckerEvaluator.js +189 -0
  138. package/dist/evaluators/tscCheckerEvaluator.js.map +1 -0
  139. package/dist/globalId-DKh9d_uD.d.ts +20 -0
  140. package/dist/globalId.d.ts +1 -0
  141. package/dist/globalId.js +15 -0
  142. package/dist/globalId.js.map +1 -0
  143. package/dist/graphTypes-CpgIuCdo.d.ts +52 -0
  144. package/dist/graphTypes.d.ts +1 -0
  145. package/dist/graphTypes.js +120 -0
  146. package/dist/graphTypes.js.map +1 -0
  147. package/dist/helpers-BYHIk5vU.d.ts +27 -0
  148. package/dist/helpers.d.ts +4 -0
  149. package/dist/helpers.js +313 -0
  150. package/dist/helpers.js.map +1 -0
  151. package/dist/index-Dct1T70K.d.ts +25 -0
  152. package/dist/index-Dq-7R-gi.d.ts +31 -0
  153. package/dist/index.d.ts +45 -0
  154. package/dist/index.js +22294 -0
  155. package/dist/index.js.map +1 -0
  156. package/dist/invariantEnforcement.d.ts +52 -0
  157. package/dist/invariantEnforcement.js +231 -0
  158. package/dist/invariantEnforcement.js.map +1 -0
  159. package/dist/logicalRoleInference-CJxqWi3u.d.ts +16 -0
  160. package/dist/logicalRoleInference.d.ts +3 -0
  161. package/dist/logicalRoleInference.js +64 -0
  162. package/dist/logicalRoleInference.js.map +1 -0
  163. package/dist/matcherFeedbackUtils.d.ts +33 -0
  164. package/dist/matcherFeedbackUtils.js +95 -0
  165. package/dist/matcherFeedbackUtils.js.map +1 -0
  166. package/dist/ontology-matching-Buhu23ss.d.ts +48 -0
  167. package/dist/ontology-matching.d.ts +2 -0
  168. package/dist/ontology-matching.js +346 -0
  169. package/dist/ontology-matching.js.map +1 -0
  170. package/dist/ontologyApproval-Ba0Jjk1k.d.ts +26 -0
  171. package/dist/ontologyApproval.d.ts +1 -0
  172. package/dist/ontologyApproval.js +78 -0
  173. package/dist/ontologyApproval.js.map +1 -0
  174. package/dist/ontologyDefinitions.d.ts +72 -0
  175. package/dist/ontologyDefinitions.js +635 -0
  176. package/dist/ontologyDefinitions.js.map +1 -0
  177. package/dist/ontologyHelpers.d.ts +79 -0
  178. package/dist/ontologyHelpers.js +81 -0
  179. package/dist/ontologyHelpers.js.map +1 -0
  180. package/dist/ontologyRegistry-B67rPJ16.d.ts +31 -0
  181. package/dist/ontologyRegistry.d.ts +1 -0
  182. package/dist/ontologyRegistry.js +296 -0
  183. package/dist/ontologyRegistry.js.map +1 -0
  184. package/dist/projectionReconciliation-CxrXYGaB.d.ts +20 -0
  185. package/dist/projectionReconciliation.d.ts +1 -0
  186. package/dist/projectionReconciliation.js +261 -0
  187. package/dist/projectionReconciliation.js.map +1 -0
  188. package/dist/projectionStaleness-CAdpIsaW.d.ts +51 -0
  189. package/dist/projectionStaleness.d.ts +1 -0
  190. package/dist/projectionStaleness.js +57 -0
  191. package/dist/projectionStaleness.js.map +1 -0
  192. package/dist/questionEvidenceLinks-BdQD0TkM.d.ts +34 -0
  193. package/dist/questionEvidenceLinks.d.ts +1 -0
  194. package/dist/questionEvidenceLinks.js +1690 -0
  195. package/dist/questionEvidenceLinks.js.map +1 -0
  196. package/dist/resolverTypes-CC8Ea2E2.d.ts +20 -0
  197. package/dist/resolverTypes.d.ts +4 -0
  198. package/dist/resolverTypes.js +3 -0
  199. package/dist/resolverTypes.js.map +1 -0
  200. package/dist/resolvers-Br1a6eLV.d.ts +14 -0
  201. package/dist/resolvers.d.ts +5 -0
  202. package/dist/resolvers.js +308 -0
  203. package/dist/resolvers.js.map +1 -0
  204. package/dist/scopeResolverCompat.d.ts +26 -0
  205. package/dist/scopeResolverCompat.js +242 -0
  206. package/dist/scopeResolverCompat.js.map +1 -0
  207. package/dist/text-matching-CMn2WnVD.d.ts +40 -0
  208. package/dist/text-matching.d.ts +2 -0
  209. package/dist/text-matching.js +246 -0
  210. package/dist/text-matching.js.map +1 -0
  211. package/dist/topicOntologyResolver.d.ts +80 -0
  212. package/dist/topicOntologyResolver.js +67 -0
  213. package/dist/topicOntologyResolver.js.map +1 -0
  214. package/dist/topicProjectOverlay.d.ts +92 -0
  215. package/dist/topicProjectOverlay.js +249 -0
  216. package/dist/topicProjectOverlay.js.map +1 -0
  217. package/dist/topicScope-By_zp4tt.d.ts +34 -0
  218. package/dist/topicScope.d.ts +3 -0
  219. package/dist/topicScope.js +206 -0
  220. package/dist/topicScope.js.map +1 -0
  221. package/dist/workspaceIsolation.d.ts +44 -0
  222. package/dist/workspaceIsolation.js +950 -0
  223. package/dist/workspaceIsolation.js.map +1 -0
  224. package/package.json +46 -0
@@ -0,0 +1,1690 @@
1
+ import { v } from 'convex/values';
2
+ import { componentsGeneric, mutationGeneric, queryGeneric, anyApi } from 'convex/server';
3
+
4
+ // src/questionEvidenceLinks.ts
5
+ var api = anyApi;
6
+ componentsGeneric();
7
+
8
+ // ../access-control/src/topicProjectOverlay.ts
9
+ var LEGACY_SCOPE_FIELD = "graphScopeProjectId";
10
+ function readNonEmptyString(value) {
11
+ if (typeof value !== "string") {
12
+ return;
13
+ }
14
+ const normalized = value.trim();
15
+ return normalized.length > 0 ? normalized : void 0;
16
+ }
17
+ function readStringArray(value) {
18
+ if (!Array.isArray(value)) {
19
+ return [];
20
+ }
21
+ return value.map((entry) => readNonEmptyString(entry)).filter((entry) => Boolean(entry));
22
+ }
23
+ function readMetadata(topic) {
24
+ return topic.metadata && typeof topic.metadata === "object" ? topic.metadata : {};
25
+ }
26
+ function readLegacyProjectId(value) {
27
+ if (!value) {
28
+ return;
29
+ }
30
+ return readNonEmptyString(value[LEGACY_SCOPE_FIELD]);
31
+ }
32
+ function coerceVisibility(value) {
33
+ return value === "private" || value === "team" || value === "firm" || value === "external" || value === "public" ? value : void 0;
34
+ }
35
+ function coerceStatus(value) {
36
+ return value === "active" || value === "archived" || value === "watching" ? value : void 0;
37
+ }
38
+ function mapProjectType(topic, metadata) {
39
+ const explicit = readNonEmptyString(metadata.projectType);
40
+ if (explicit) {
41
+ return explicit;
42
+ }
43
+ if (topic.type === "theme") {
44
+ return "thematic";
45
+ }
46
+ return readNonEmptyString(topic.type) || "general";
47
+ }
48
+ function isProjectLikeTopic(topic) {
49
+ const metadata = readMetadata(topic);
50
+ return topic.type === "theme" || topic.type === "thematic" || topic.type === "deal" || topic.type === "monitoring" || readLegacyProjectId(topic) !== void 0 || readNonEmptyString(metadata.projectType) !== void 0;
51
+ }
52
+ async function resolveTopicDoc(ctx, scopeId) {
53
+ if (ctx?.db && typeof ctx.db.get === "function") {
54
+ try {
55
+ const directTopic = await ctx.db.get(scopeId);
56
+ if (directTopic) {
57
+ return directTopic;
58
+ }
59
+ } catch {
60
+ }
61
+ }
62
+ if (typeof ctx.runQuery !== "function") {
63
+ return null;
64
+ }
65
+ try {
66
+ const topic = await ctx.runQuery(api.topics.get, {
67
+ id: String(scopeId)
68
+ });
69
+ if (topic?.name !== void 0 && topic?.type !== void 0) {
70
+ return topic;
71
+ }
72
+ } catch {
73
+ }
74
+ try {
75
+ const topic = await ctx.runQuery(api.topics.getByLegacyScopeId, {
76
+ projectId: String(scopeId)
77
+ });
78
+ if (topic?.name !== void 0 && topic?.type !== void 0) {
79
+ return topic;
80
+ }
81
+ } catch {
82
+ }
83
+ return null;
84
+ }
85
+ function materializeTopicProjectOverlay(topic, idMode = "legacy") {
86
+ const metadata = readMetadata(topic);
87
+ const topicId = String(topic._id);
88
+ const legacyProjectId = readLegacyProjectId(topic) || readLegacyProjectId(metadata) || readNonEmptyString(metadata.legacyProjectId);
89
+ const storageProjectId = legacyProjectId || topicId;
90
+ const outwardId = idMode === "topic" ? topicId : storageProjectId;
91
+ const visibility = coerceVisibility(topic.visibility) || coerceVisibility(metadata.visibility) || "private";
92
+ const status = coerceStatus(topic.status) || coerceStatus(metadata.status) || "active";
93
+ const createdAt = typeof topic.createdAt === "number" ? topic.createdAt : typeof topic._creationTime === "number" ? topic._creationTime : 0;
94
+ const updatedAt = typeof topic.updatedAt === "number" ? topic.updatedAt : typeof metadata.updatedAt === "number" ? metadata.updatedAt : createdAt;
95
+ return {
96
+ ...metadata,
97
+ _id: outwardId,
98
+ projectId: outwardId,
99
+ topicId,
100
+ storageProjectId,
101
+ legacyProjectId,
102
+ name: readNonEmptyString(topic.name) || "Untitled Theme",
103
+ type: mapProjectType(topic, metadata),
104
+ description: readNonEmptyString(topic.description),
105
+ ownerId: readNonEmptyString(metadata.ownerId) || readNonEmptyString(topic.createdBy) || "system",
106
+ sharedWith: readStringArray(metadata.sharedWith),
107
+ visibility,
108
+ tenantId: readNonEmptyString(topic.tenantId) || readNonEmptyString(metadata.tenantId),
109
+ workspaceId: readNonEmptyString(topic.workspaceId) || readNonEmptyString(metadata.workspaceId),
110
+ status,
111
+ tags: readStringArray(metadata.tags),
112
+ chatCount: typeof metadata.chatCount === "number" ? metadata.chatCount : 0,
113
+ artifactCount: typeof metadata.artifactCount === "number" ? metadata.artifactCount : 0,
114
+ lastActivityAt: typeof metadata.lastActivityAt === "number" ? metadata.lastActivityAt : updatedAt,
115
+ _creationTime: typeof topic._creationTime === "number" ? topic._creationTime : createdAt,
116
+ createdAt,
117
+ updatedAt
118
+ };
119
+ }
120
+ async function resolveTopicProjectOverlay(ctx, scopeId, options = {}) {
121
+ const topic = await resolveTopicDoc(ctx, scopeId);
122
+ if (!topic) {
123
+ return null;
124
+ }
125
+ if (options.projectLikeOnly !== false && !isProjectLikeTopic(topic)) {
126
+ return null;
127
+ }
128
+ return materializeTopicProjectOverlay(topic, options.idMode);
129
+ }
130
+ async function listTopicProjectOverlays(ctx, options = {}) {
131
+ let allTopics = [];
132
+ if (ctx?.db?.query && typeof ctx.db.query === "function") {
133
+ try {
134
+ allTopics = await ctx.db.query("topics").collect();
135
+ } catch {
136
+ allTopics = [];
137
+ }
138
+ }
139
+ if (allTopics.length === 0 && typeof ctx.runQuery === "function") {
140
+ allTopics = (await ctx.runQuery(api.topics.list, {}) ?? []) || [];
141
+ }
142
+ return allTopics.filter(
143
+ (topic) => options.projectLikeOnly === false || isProjectLikeTopic(topic)
144
+ ).map((topic) => materializeTopicProjectOverlay(topic, options.idMode));
145
+ }
146
+
147
+ // ../access-control/src/projectGrantsBridge.ts
148
+ var PROJECT_GRANT_STATUSES = ["active", "revoked", "expired"];
149
+ function normalizeString(value) {
150
+ if (typeof value !== "string") {
151
+ return;
152
+ }
153
+ const trimmed = value.trim();
154
+ return trimmed.length > 0 ? trimmed : void 0;
155
+ }
156
+ async function resolveGrantScopeIds(ctx, args) {
157
+ const topicId = normalizeString(args.topicId);
158
+ const projectId = normalizeString(args.projectId);
159
+ for (const scopeId of [topicId, projectId]) {
160
+ if (!scopeId) {
161
+ continue;
162
+ }
163
+ try {
164
+ const overlay = await resolveTopicProjectOverlay(ctx, scopeId, {
165
+ idMode: "legacy",
166
+ projectLikeOnly: false
167
+ });
168
+ if (overlay) {
169
+ return {
170
+ topicId: normalizeString(overlay.topicId) ?? topicId,
171
+ projectId: normalizeString(overlay.projectId) ?? projectId ?? scopeId
172
+ };
173
+ }
174
+ } catch {
175
+ }
176
+ }
177
+ return { topicId, projectId };
178
+ }
179
+ async function normalizeProjectGrantRow(ctx, row) {
180
+ const scope = await resolveGrantScopeIds(ctx, {
181
+ topicId: row.topicId,
182
+ projectId: row.projectId
183
+ });
184
+ return {
185
+ ...row,
186
+ ...scope.topicId ? { topicId: scope.topicId } : {},
187
+ ...scope.projectId ?? scope.topicId ? { projectId: scope.projectId ?? scope.topicId } : {}
188
+ };
189
+ }
190
+ async function normalizeProjectGrantRows(ctx, rows) {
191
+ return await Promise.all(rows.map((row) => normalizeProjectGrantRow(ctx, row)));
192
+ }
193
+ async function listProjectGrantsByPrincipal(ctx, principalId) {
194
+ const rows = await Promise.all(
195
+ PROJECT_GRANT_STATUSES.map(
196
+ (status) => ctx.db.query("projectGrants").withIndex(
197
+ "by_principal_status",
198
+ (q) => q.eq("principalId", principalId).eq("status", status)
199
+ ).collect()
200
+ )
201
+ );
202
+ return await normalizeProjectGrantRows(ctx, rows.flat());
203
+ }
204
+ async function listProjectGrantsByGroup(ctx, groupId) {
205
+ const rows = await Promise.all(
206
+ PROJECT_GRANT_STATUSES.map(
207
+ (status) => ctx.db.query("projectGrants").withIndex(
208
+ "by_group_status",
209
+ (q) => q.eq("groupId", groupId).eq("status", status)
210
+ ).collect()
211
+ )
212
+ );
213
+ return await normalizeProjectGrantRows(ctx, rows.flat());
214
+ }
215
+ function buildScopeMatchers(inputScopeId, resolved) {
216
+ return new Set(
217
+ [inputScopeId, resolved.topicId, resolved.projectId].map((value) => normalizeString(value)).filter((value) => Boolean(value))
218
+ );
219
+ }
220
+ function matchesResolvedScope(row, scopeIds) {
221
+ const rowTopicId = normalizeString(row.topicId);
222
+ const rowProjectId = normalizeString(row.projectId);
223
+ return rowTopicId !== void 0 && scopeIds.has(rowTopicId) || rowProjectId !== void 0 && scopeIds.has(rowProjectId);
224
+ }
225
+ async function bridgeListProjectGrantsByTopicAndPrincipal(ctx, topicId, principalId) {
226
+ const resolved = await resolveGrantScopeIds(ctx, { topicId });
227
+ const scopeIds = buildScopeMatchers(topicId, resolved);
228
+ const rows = await listProjectGrantsByPrincipal(ctx, principalId);
229
+ return rows.filter((row) => matchesResolvedScope(row, scopeIds));
230
+ }
231
+ async function bridgeListProjectGrantsByTopicAndGroup(ctx, topicId, groupId) {
232
+ const resolved = await resolveGrantScopeIds(ctx, { topicId });
233
+ const scopeIds = buildScopeMatchers(topicId, resolved);
234
+ const rows = await listProjectGrantsByGroup(ctx, groupId);
235
+ return rows.filter((row) => matchesResolvedScope(row, scopeIds));
236
+ }
237
+ async function bridgeListProjectGrantsByPrincipalStatus(ctx, principalId, status) {
238
+ const rows = await listProjectGrantsByPrincipal(ctx, principalId);
239
+ return rows.filter((row) => row.status === status);
240
+ }
241
+ async function bridgeListProjectGrantsByGroupStatus(ctx, groupId, status) {
242
+ const rows = await listProjectGrantsByGroup(ctx, groupId);
243
+ return rows.filter((row) => row.status === status);
244
+ }
245
+ async function bridgeInsertProjectGrant(ctx, value) {
246
+ const resolved = await resolveGrantScopeIds(ctx, value);
247
+ return await ctx.db.insert("projectGrants", {
248
+ ...value,
249
+ ...resolved.topicId ? { topicId: resolved.topicId } : {},
250
+ ...resolved.projectId ?? resolved.topicId ? { projectId: resolved.projectId ?? resolved.topicId } : {}
251
+ });
252
+ }
253
+
254
+ // ../access-control/src/resolvers.ts
255
+ async function findUserByClerkId(ctx, clerkId) {
256
+ const normalizedClerkId = clerkId.trim();
257
+ if (!normalizedClerkId) {
258
+ return null;
259
+ }
260
+ if (typeof ctx.runQuery === "function") {
261
+ try {
262
+ const bridgedUser = await ctx.runQuery(api.users.getUserByClerkId, {
263
+ clerkId: normalizedClerkId
264
+ });
265
+ if (bridgedUser) {
266
+ return bridgedUser;
267
+ }
268
+ } catch {
269
+ }
270
+ }
271
+ try {
272
+ const users = await ctx.db.query("users").collect();
273
+ return users.find((user) => String(user.clerkId ?? "") === normalizedClerkId) ?? null;
274
+ } catch {
275
+ return null;
276
+ }
277
+ }
278
+ async function findUserByPrincipalId(ctx, principalId) {
279
+ const normalizedPrincipalId = principalId.trim();
280
+ if (!normalizedPrincipalId) {
281
+ return null;
282
+ }
283
+ try {
284
+ const users = await ctx.db.query("users").collect();
285
+ return users.find(
286
+ (user) => String(user.defaultPrincipalId ?? "") === normalizedPrincipalId
287
+ ) ?? null;
288
+ } catch {
289
+ return null;
290
+ }
291
+ }
292
+ async function findAgentByPrincipalId(ctx, principalId) {
293
+ const normalizedPrincipalId = principalId.trim();
294
+ if (!normalizedPrincipalId) {
295
+ return null;
296
+ }
297
+ if (typeof ctx.runQuery === "function") {
298
+ try {
299
+ const bridgedAgent = await ctx.runQuery(
300
+ api.agents.getAgentByPrincipalId,
301
+ {
302
+ principalId: normalizedPrincipalId
303
+ }
304
+ );
305
+ if (bridgedAgent) {
306
+ return bridgedAgent;
307
+ }
308
+ } catch {
309
+ }
310
+ }
311
+ try {
312
+ const agents = await ctx.db.query("agents").collect();
313
+ return agents.find(
314
+ (agent) => String(agent.principalId ?? "") === normalizedPrincipalId
315
+ ) ?? null;
316
+ } catch {
317
+ return null;
318
+ }
319
+ }
320
+ function defaultResolvers() {
321
+ return {
322
+ async getProject(ctx, topicId) {
323
+ return await resolveTopicProjectOverlay(ctx, topicId, {
324
+ idMode: "legacy",
325
+ projectLikeOnly: false
326
+ });
327
+ },
328
+ async listTopics(ctx) {
329
+ return await listTopicProjectOverlays(ctx, { idMode: "legacy" });
330
+ },
331
+ async listTopicsByOwner(ctx, ownerId) {
332
+ const topics = await listTopicProjectOverlays(ctx, { idMode: "legacy" });
333
+ return topics.filter((topic) => topic.ownerId === ownerId);
334
+ },
335
+ async listTopicsByVisibility(ctx, visibility) {
336
+ const topics = await listTopicProjectOverlays(ctx, { idMode: "legacy" });
337
+ return topics.filter((topic) => topic.visibility === visibility);
338
+ },
339
+ async listProjectGrantsByProjectAndPrincipal(ctx, topicId, principalId) {
340
+ return await bridgeListProjectGrantsByTopicAndPrincipal(
341
+ ctx,
342
+ topicId,
343
+ principalId
344
+ );
345
+ },
346
+ async listProjectGrantsByProjectAndGroup(ctx, topicId, groupId) {
347
+ return await bridgeListProjectGrantsByTopicAndGroup(ctx, topicId, groupId);
348
+ },
349
+ async listProjectGrantsByPrincipalStatus(ctx, principalId, status) {
350
+ return await bridgeListProjectGrantsByPrincipalStatus(
351
+ ctx,
352
+ principalId,
353
+ status
354
+ );
355
+ },
356
+ async listProjectGrantsByGroupStatus(ctx, groupId, status) {
357
+ return await bridgeListProjectGrantsByGroupStatus(ctx, groupId, status);
358
+ },
359
+ async insertProjectGrant(ctx, value) {
360
+ return await bridgeInsertProjectGrant(ctx, value);
361
+ },
362
+ async getAgentByPrincipalId(ctx, principalId) {
363
+ return await findAgentByPrincipalId(ctx, principalId);
364
+ },
365
+ async getUserByClerkId(ctx, clerkId) {
366
+ return await findUserByClerkId(ctx, clerkId);
367
+ },
368
+ async getUserByPrincipalId(ctx, principalId) {
369
+ return await findUserByPrincipalId(ctx, principalId);
370
+ }
371
+ };
372
+ }
373
+ var resolverOverrides = {};
374
+ function resolveAccessControlAppResolvers(_ctx) {
375
+ return {
376
+ ...defaultResolvers(),
377
+ ...resolverOverrides
378
+ };
379
+ }
380
+
381
+ // ../access-control/src/principalContext.ts
382
+ function requireCanonicalResolvedUser(user, clerkId) {
383
+ const resolved = user;
384
+ if (!resolved) {
385
+ throw new Error(
386
+ `[AccessControl] Canonical user identity required for ${clerkId}. Sync users.upsertUser before user-bound access checks.`
387
+ );
388
+ }
389
+ const { mcRole, defaultTenantId, defaultWorkspaceId, defaultPrincipalId } = resolved;
390
+ if (mcRole !== "platform_admin" && mcRole !== "tenant_admin" && mcRole !== "workspace_admin" && mcRole !== "editor" && mcRole !== "viewer" && mcRole !== "auditor" && mcRole !== "service_agent") {
391
+ throw new Error(
392
+ `[AccessControl] Canonical MC role required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
393
+ );
394
+ }
395
+ if (typeof defaultTenantId !== "string" || defaultTenantId.trim().length === 0) {
396
+ throw new Error(
397
+ `[AccessControl] Canonical home tenant required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
398
+ );
399
+ }
400
+ if (typeof defaultWorkspaceId !== "string" || defaultWorkspaceId.trim().length === 0) {
401
+ throw new Error(
402
+ `[AccessControl] Canonical home workspace required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
403
+ );
404
+ }
405
+ if (typeof defaultPrincipalId !== "string" || defaultPrincipalId.trim().length === 0) {
406
+ throw new Error(
407
+ `[AccessControl] Canonical federated principal required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
408
+ );
409
+ }
410
+ return {
411
+ mcRole,
412
+ defaultTenantId: defaultTenantId.trim(),
413
+ defaultWorkspaceId: defaultWorkspaceId.trim(),
414
+ defaultPrincipalId: defaultPrincipalId.trim()
415
+ };
416
+ }
417
+ function isPrincipalIdInput(value) {
418
+ return value.startsWith("user:") || value.startsWith("group:") || value.startsWith("service:") || value.startsWith("agent:") || value.startsWith("external_viewer:");
419
+ }
420
+ async function resolveCanonicalUserRecord(ctx, actorId) {
421
+ const normalizedActorId = actorId.trim();
422
+ const clerkId = isPrincipalIdInput(normalizedActorId) && normalizedActorId.startsWith("user:") ? normalizedActorId.slice("user:".length) : normalizedActorId;
423
+ const resolvers = resolveAccessControlAppResolvers();
424
+ const resolvedByClerkId = await resolvers.getUserByClerkId(ctx, clerkId);
425
+ if (resolvedByClerkId) {
426
+ return {
427
+ resolvedUser: resolvedByClerkId,
428
+ clerkId,
429
+ contextClerkId: clerkId
430
+ };
431
+ }
432
+ const resolvedByPrincipalId = await resolvers.getUserByPrincipalId(
433
+ ctx,
434
+ normalizedActorId
435
+ );
436
+ return {
437
+ resolvedUser: resolvedByPrincipalId ?? null,
438
+ clerkId,
439
+ contextClerkId: normalizedActorId.startsWith("user:") && clerkId.length > 0 ? clerkId : normalizedActorId
440
+ };
441
+ }
442
+ function uniqRoles(roles) {
443
+ const roleSet = /* @__PURE__ */ new Set();
444
+ for (const role of roles) {
445
+ if (role === "platform_admin" || role === "tenant_admin" || role === "workspace_admin" || role === "editor" || role === "viewer" || role === "auditor" || role === "service_agent") {
446
+ roleSet.add(role);
447
+ }
448
+ }
449
+ return [...roleSet];
450
+ }
451
+ function normalizeGroupIds(value) {
452
+ if (!Array.isArray(value)) {
453
+ return [];
454
+ }
455
+ return [...new Set(
456
+ value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)
457
+ )];
458
+ }
459
+ function requireServiceAgentUser(user, actorId) {
460
+ const canonicalUser = requireCanonicalResolvedUser(user, actorId);
461
+ if (canonicalUser.mcRole !== "service_agent") {
462
+ throw new Error(
463
+ `[AccessControl] Canonical service_agent identity required for ${actorId}. Sync users.upsertUser before agent-bound access checks.`
464
+ );
465
+ }
466
+ return canonicalUser;
467
+ }
468
+ function requireCanonicalResolvedAgent(agent, actorId) {
469
+ const resolved = agent;
470
+ if (!resolved) {
471
+ throw new Error(
472
+ `[AccessControl] Agent "${actorId}" not found in agents or users table.`
473
+ );
474
+ }
475
+ if (typeof resolved.principalId !== "string" || resolved.principalId.trim().length === 0) {
476
+ throw new Error(
477
+ `[AccessControl] Canonical agent principalId required for ${actorId}.`
478
+ );
479
+ }
480
+ if (typeof resolved.tenantId !== "string" || resolved.tenantId.trim().length === 0) {
481
+ throw new Error(
482
+ `[AccessControl] Canonical home tenant required for ${actorId}.`
483
+ );
484
+ }
485
+ if (typeof resolved.workspaceId !== "string" || resolved.workspaceId.trim().length === 0) {
486
+ throw new Error(
487
+ `[AccessControl] Canonical home workspace required for ${actorId}.`
488
+ );
489
+ }
490
+ return {
491
+ principalId: resolved.principalId.trim(),
492
+ tenantId: resolved.tenantId.trim(),
493
+ workspaceId: resolved.workspaceId.trim(),
494
+ roles: uniqRoles(Array.isArray(resolved.roles) ? resolved.roles : []) ?? ["service_agent"],
495
+ groupIds: normalizeGroupIds(resolved.groupIds)
496
+ };
497
+ }
498
+ async function resolvePrincipalContext(ctx, actorId) {
499
+ if (actorId.startsWith("agent:")) {
500
+ const resolvers = resolveAccessControlAppResolvers();
501
+ const resolvedAgent = await resolvers.getAgentByPrincipalId(ctx, actorId);
502
+ if (resolvedAgent) {
503
+ const agent = requireCanonicalResolvedAgent(
504
+ resolvedAgent,
505
+ actorId
506
+ );
507
+ return {
508
+ principalId: agent.principalId,
509
+ principalType: "service",
510
+ clerkId: actorId,
511
+ tenantId: agent.tenantId,
512
+ workspaceId: agent.workspaceId,
513
+ roles: agent.roles.length > 0 ? agent.roles : ["service_agent"],
514
+ groupIds: agent.groupIds,
515
+ isPlatformAdmin: false,
516
+ isTenantAdmin: false,
517
+ isWorkspaceAdmin: false,
518
+ isSystemFallback: false
519
+ };
520
+ }
521
+ const resolvedUser2 = await resolvers.getUserByClerkId(
522
+ ctx,
523
+ actorId
524
+ );
525
+ if (!resolvedUser2) {
526
+ throw new Error(
527
+ `[AccessControl] Agent "${actorId}" not found in agents or users table.`
528
+ );
529
+ }
530
+ const user2 = requireServiceAgentUser(
531
+ resolvedUser2,
532
+ actorId
533
+ );
534
+ console.warn(
535
+ `[AccessControl] Deprecated legacy service-agent fallback for ${actorId}; migrate this principal into identity.agents.`
536
+ );
537
+ return {
538
+ principalId: user2.defaultPrincipalId,
539
+ principalType: "service",
540
+ clerkId: actorId,
541
+ tenantId: user2.defaultTenantId,
542
+ workspaceId: user2.defaultWorkspaceId,
543
+ roles: ["service_agent"],
544
+ groupIds: normalizeGroupIds(resolvedUser2?.principalGroupIds),
545
+ isPlatformAdmin: false,
546
+ isTenantAdmin: false,
547
+ isWorkspaceAdmin: false,
548
+ isSystemFallback: false
549
+ };
550
+ }
551
+ const {
552
+ resolvedUser,
553
+ contextClerkId
554
+ } = await resolveCanonicalUserRecord(ctx, actorId);
555
+ const user = requireCanonicalResolvedUser(
556
+ resolvedUser,
557
+ contextClerkId
558
+ );
559
+ if (!user.defaultPrincipalId) {
560
+ throw new Error(
561
+ `[AccessControl] Canonical federated principal required for ${contextClerkId}. Re-sync Master Control identity before user-bound access checks.`
562
+ );
563
+ }
564
+ if (user.mcRole === "service_agent") {
565
+ return {
566
+ principalId: user.defaultPrincipalId,
567
+ principalType: "service",
568
+ clerkId: contextClerkId,
569
+ tenantId: user.defaultTenantId,
570
+ workspaceId: user.defaultWorkspaceId,
571
+ roles: ["service_agent"],
572
+ groupIds: normalizeGroupIds(resolvedUser?.principalGroupIds),
573
+ isPlatformAdmin: false,
574
+ isTenantAdmin: false,
575
+ isWorkspaceAdmin: false,
576
+ isSystemFallback: false
577
+ };
578
+ }
579
+ const principalId = user.defaultPrincipalId;
580
+ const effectiveRole = user.mcRole;
581
+ const roles = effectiveRole === "platform_admin" ? ["platform_admin", "tenant_admin"] : effectiveRole === "tenant_admin" ? ["tenant_admin"] : [effectiveRole];
582
+ const tenantId = user.defaultTenantId;
583
+ const workspaceId = user.defaultWorkspaceId;
584
+ const isPlatformAdmin = effectiveRole === "platform_admin";
585
+ return {
586
+ principalId,
587
+ principalType: "user",
588
+ clerkId: contextClerkId,
589
+ tenantId,
590
+ workspaceId,
591
+ roles: uniqRoles(roles),
592
+ groupIds: normalizeGroupIds(resolvedUser?.principalGroupIds),
593
+ isPlatformAdmin,
594
+ isTenantAdmin: isPlatformAdmin || effectiveRole === "tenant_admin",
595
+ isWorkspaceAdmin: isPlatformAdmin || effectiveRole === "tenant_admin" || effectiveRole === "workspace_admin",
596
+ isSystemFallback: false
597
+ };
598
+ }
599
+
600
+ // ../access-control/src/access.ts
601
+ function isTopicInPrincipalTenant(topic, principalTenantId) {
602
+ if (!topic.tenantId) {
603
+ return false;
604
+ }
605
+ if (!principalTenantId) {
606
+ return false;
607
+ }
608
+ return String(topic.tenantId) === String(principalTenantId);
609
+ }
610
+ function isTopicInPrincipalWorkspace(topic, principalWorkspaceId) {
611
+ if (!topic.workspaceId) {
612
+ return false;
613
+ }
614
+ if (!principalWorkspaceId) {
615
+ return false;
616
+ }
617
+ return String(topic.workspaceId) === String(principalWorkspaceId);
618
+ }
619
+ function isLegacyUnscopedTopic(topic) {
620
+ return !topic.tenantId || !topic.workspaceId;
621
+ }
622
+ function isGrantScopeAlignedToTopic(topic, grant) {
623
+ if (topic.tenantId && grant.tenantId && String(topic.tenantId) !== String(grant.tenantId)) {
624
+ return false;
625
+ }
626
+ if (topic.workspaceId && grant.workspaceId && String(topic.workspaceId) !== String(grant.workspaceId)) {
627
+ return false;
628
+ }
629
+ return true;
630
+ }
631
+ function isGrantSourceAllowedForVisibility(visibility, source) {
632
+ if (source !== "external_share") {
633
+ return true;
634
+ }
635
+ return visibility === "external" || visibility === "public";
636
+ }
637
+ function isGrantActive(grant) {
638
+ if (grant.status !== "active") {
639
+ return false;
640
+ }
641
+ if (grant.expiresAt !== void 0 && grant.expiresAt <= Date.now()) {
642
+ return false;
643
+ }
644
+ return true;
645
+ }
646
+ async function hasPrincipalGrant(ctx, args) {
647
+ const grants = await resolveAccessControlAppResolvers().listProjectGrantsByProjectAndPrincipal(
648
+ ctx,
649
+ args.topic._id,
650
+ args.principalId
651
+ );
652
+ if (grants.some(
653
+ (grant) => isGrantActive(grant) && isGrantScopeAlignedToTopic(args.topic, grant) && isGrantSourceAllowedForVisibility(
654
+ args.topic.visibility,
655
+ grant.source
656
+ ) && (!args.principalIsExternal || args.topic.visibility === "public" || grant.source === "external_share")
657
+ )) {
658
+ return true;
659
+ }
660
+ return false;
661
+ }
662
+ async function hasGroupGrant(ctx, args) {
663
+ if (args.groupIds.length === 0) {
664
+ return false;
665
+ }
666
+ for (const groupId of args.groupIds) {
667
+ const grants = await resolveAccessControlAppResolvers().listProjectGrantsByProjectAndGroup(ctx, args.topic._id, groupId);
668
+ if (grants.some(
669
+ (grant) => isGrantActive(grant) && isGrantScopeAlignedToTopic(args.topic, grant) && isGrantSourceAllowedForVisibility(
670
+ args.topic.visibility,
671
+ grant.source
672
+ )
673
+ )) {
674
+ return true;
675
+ }
676
+ }
677
+ return false;
678
+ }
679
+ function isExternalPrincipal(_ctx, _args) {
680
+ return false;
681
+ }
682
+ async function evaluateTopicAccessDetailed(ctx, args) {
683
+ if (args.legacyUserId) {
684
+ return {
685
+ hasAccess: true,
686
+ isAdmin: false,
687
+ isOwner: false,
688
+ isShared: false,
689
+ hasGrant: true,
690
+ isFirmVisible: true,
691
+ isExternalVisible: false,
692
+ isPublicVisible: false,
693
+ isTenantScopeMatch: true,
694
+ isWorkspaceScopeMatch: true,
695
+ isPrincipalExternal: false
696
+ };
697
+ }
698
+ const topic = await resolveAccessControlAppResolvers().getProject(
699
+ ctx,
700
+ args.topicId
701
+ );
702
+ if (!topic) {
703
+ return {
704
+ hasAccess: false,
705
+ isAdmin: false,
706
+ isOwner: false,
707
+ isShared: false,
708
+ hasGrant: false,
709
+ isFirmVisible: false,
710
+ isExternalVisible: false,
711
+ isPublicVisible: false,
712
+ isTenantScopeMatch: false,
713
+ isWorkspaceScopeMatch: false,
714
+ isPrincipalExternal: false
715
+ };
716
+ }
717
+ const { principalContext, legacyUserId } = args;
718
+ const userIsAdmin = principalContext.isPlatformAdmin;
719
+ const isOwner = topic.ownerId === legacyUserId;
720
+ const isShared = (topic.sharedWith ?? []).includes(legacyUserId);
721
+ const principalIsExternal = await isExternalPrincipal(ctx, {
722
+ groupIds: principalContext.groupIds,
723
+ topicTenantId: topic.tenantId,
724
+ topicWorkspaceId: topic.workspaceId
725
+ });
726
+ const hasPrincipalGrantResult = await hasPrincipalGrant(ctx, {
727
+ topic,
728
+ principalId: principalContext.principalId,
729
+ principalIsExternal
730
+ });
731
+ const hasGroupGrantResult = await hasGroupGrant(ctx, {
732
+ topic,
733
+ groupIds: principalContext.groupIds
734
+ });
735
+ const hasGrant = isShared || hasPrincipalGrantResult || hasGroupGrantResult;
736
+ const legacyUnscoped = isLegacyUnscopedTopic(topic);
737
+ const tenantScopeMatch = isTopicInPrincipalTenant(
738
+ topic,
739
+ principalContext.tenantId
740
+ );
741
+ const workspaceScopeMatch = isTopicInPrincipalWorkspace(
742
+ topic,
743
+ principalContext.workspaceId
744
+ );
745
+ const isPublicVisible = topic.visibility === "public";
746
+ const isFirmVisible = topic.visibility === "firm" && !legacyUnscoped && tenantScopeMatch && workspaceScopeMatch && !principalIsExternal;
747
+ const hasScopedGrant = hasGrant && (legacyUnscoped || tenantScopeMatch && workspaceScopeMatch);
748
+ const isExternalVisible = topic.visibility === "external" && hasScopedGrant;
749
+ const hasAccess = userIsAdmin || isOwner || hasScopedGrant || isPublicVisible || isFirmVisible;
750
+ return {
751
+ hasAccess,
752
+ isAdmin: userIsAdmin,
753
+ isOwner,
754
+ isShared,
755
+ hasGrant,
756
+ isFirmVisible,
757
+ isExternalVisible,
758
+ isPublicVisible,
759
+ isTenantScopeMatch: tenantScopeMatch,
760
+ isWorkspaceScopeMatch: workspaceScopeMatch,
761
+ isPrincipalExternal: principalIsExternal
762
+ };
763
+ }
764
+ async function checkTopicAccessDetailed(ctx, topicId, userId) {
765
+ const principalContext = await resolvePrincipalContext(ctx, userId);
766
+ return evaluateTopicAccessDetailed(ctx, {
767
+ topicId,
768
+ legacyUserId: userId,
769
+ principalContext
770
+ });
771
+ }
772
+ async function checkTopicAccess(ctx, topicId, userId) {
773
+ const result = await checkTopicAccessDetailed(ctx, topicId, userId);
774
+ return result.hasAccess;
775
+ }
776
+ var checkProjectAccess = checkTopicAccess;
777
+ var permissiveReturn = v.optional(v.any());
778
+ var looseJsonObject = v.record(v.string(), v.any());
779
+ var looseJsonArray = v.array(v.any());
780
+ v.union(
781
+ v.string(),
782
+ v.number(),
783
+ v.boolean(),
784
+ v.null(),
785
+ looseJsonObject,
786
+ looseJsonArray
787
+ );
788
+ var api2 = anyApi;
789
+ componentsGeneric();
790
+ var internal = anyApi;
791
+ var mutation = mutationGeneric;
792
+ var query = queryGeneric;
793
+
794
+ // src/matcherFeedbackUtils.ts
795
+ function isOperationalLinkStatus(status) {
796
+ return status !== "suggested" && status !== "dismissed";
797
+ }
798
+ function mergeLinkSuggestionStatus(existing, requested) {
799
+ if (requested === void 0 || requested === null) {
800
+ return existing ?? void 0;
801
+ }
802
+ if (existing && isOperationalLinkStatus(existing) && !isOperationalLinkStatus(requested)) {
803
+ return existing;
804
+ }
805
+ return requested;
806
+ }
807
+ function resolveReviewedLinkStatus(requested) {
808
+ return requested;
809
+ }
810
+ function deriveMatcherReviewStatus(input) {
811
+ if (input.explicitReviewStatus) {
812
+ return input.explicitReviewStatus;
813
+ }
814
+ if (input.autoAccepted) {
815
+ return "auto_accepted";
816
+ }
817
+ if (input.linkStatus === "suggested") {
818
+ return "pending";
819
+ }
820
+ if (input.linkStatus === "dismissed") {
821
+ return "rejected";
822
+ }
823
+ return "accepted";
824
+ }
825
+
826
+ // src/topicProjectOverlay.ts
827
+ var LEGACY_SCOPE_FIELD2 = "graphScopeProjectId";
828
+ function readNonEmptyString2(value) {
829
+ if (typeof value !== "string") {
830
+ return;
831
+ }
832
+ const normalized = value.trim();
833
+ return normalized.length > 0 ? normalized : void 0;
834
+ }
835
+ function readStringArray2(value) {
836
+ if (!Array.isArray(value)) {
837
+ return [];
838
+ }
839
+ return value.map((entry) => readNonEmptyString2(entry)).filter((entry) => Boolean(entry));
840
+ }
841
+ function readMetadata2(topic) {
842
+ return topic.metadata && typeof topic.metadata === "object" ? topic.metadata : {};
843
+ }
844
+ function readLegacyProjectId2(value) {
845
+ if (!value) {
846
+ return;
847
+ }
848
+ return readNonEmptyString2(value[LEGACY_SCOPE_FIELD2]);
849
+ }
850
+ function coerceVisibility2(value) {
851
+ return value === "private" || value === "team" || value === "firm" || value === "external" || value === "public" ? value : void 0;
852
+ }
853
+ function coerceStatus2(value) {
854
+ return value === "active" || value === "archived" || value === "watching" ? value : void 0;
855
+ }
856
+ function mapProjectType2(topic, metadata) {
857
+ const explicit = readNonEmptyString2(metadata.projectType);
858
+ if (explicit) {
859
+ return explicit;
860
+ }
861
+ if (topic.type === "theme") {
862
+ return "thematic";
863
+ }
864
+ return readNonEmptyString2(topic.type) || "general";
865
+ }
866
+ function isProjectLikeTopic2(topic) {
867
+ const metadata = readMetadata2(topic);
868
+ return topic.type === "theme" || topic.type === "thematic" || topic.type === "deal" || topic.type === "monitoring" || readLegacyProjectId2(topic) !== void 0 || readNonEmptyString2(metadata.projectType) !== void 0;
869
+ }
870
+ function isMissingLucernChildComponentError(error) {
871
+ const message = error instanceof Error ? error.message : String(error);
872
+ return message.includes(
873
+ 'Child component ComponentName(Identifier("lucern")) not found'
874
+ ) || message.includes("Child component") && message.includes("lucern") && message.includes("not found");
875
+ }
876
+ async function resolveTopicDoc2(ctx, scopeId) {
877
+ if (ctx?.db && typeof ctx.db.get === "function") {
878
+ try {
879
+ const directTopic = await ctx.db.get(scopeId);
880
+ if (directTopic) {
881
+ return directTopic;
882
+ }
883
+ } catch {
884
+ }
885
+ }
886
+ if (typeof ctx.runQuery !== "function") {
887
+ return null;
888
+ }
889
+ try {
890
+ const topic = await ctx.runQuery(api2.topics.get, {
891
+ id: String(scopeId)
892
+ });
893
+ if (topic?.name !== void 0 && topic?.type !== void 0) {
894
+ return topic;
895
+ }
896
+ } catch {
897
+ }
898
+ try {
899
+ const topic = await ctx.runQuery(api2.topics.getByLegacyScopeId, {
900
+ projectId: String(scopeId)
901
+ });
902
+ if (topic?.name !== void 0 && topic?.type !== void 0) {
903
+ return topic;
904
+ }
905
+ } catch {
906
+ }
907
+ return null;
908
+ }
909
+ function materializeTopicProjectOverlay2(topic, idMode = "legacy") {
910
+ const metadata = readMetadata2(topic);
911
+ const topicId = String(topic._id);
912
+ const legacyProjectId = readLegacyProjectId2(topic) || readLegacyProjectId2(metadata) || readNonEmptyString2(metadata.legacyProjectId);
913
+ const storageProjectId = legacyProjectId || topicId;
914
+ const outwardId = idMode === "topic" ? topicId : storageProjectId;
915
+ const visibility = coerceVisibility2(topic.visibility) || coerceVisibility2(metadata.visibility) || "private";
916
+ const status = coerceStatus2(topic.status) || coerceStatus2(metadata.status) || "active";
917
+ const createdAt = typeof topic.createdAt === "number" ? topic.createdAt : typeof topic._creationTime === "number" ? topic._creationTime : 0;
918
+ const updatedAt = typeof topic.updatedAt === "number" ? topic.updatedAt : typeof metadata.updatedAt === "number" ? metadata.updatedAt : createdAt;
919
+ return {
920
+ ...metadata,
921
+ _id: outwardId,
922
+ projectId: outwardId,
923
+ topicId,
924
+ storageProjectId,
925
+ legacyProjectId,
926
+ name: readNonEmptyString2(topic.name) || "Untitled Theme",
927
+ type: mapProjectType2(topic, metadata),
928
+ description: readNonEmptyString2(topic.description),
929
+ ownerId: readNonEmptyString2(metadata.ownerId) || readNonEmptyString2(topic.createdBy) || "system",
930
+ sharedWith: readStringArray2(metadata.sharedWith),
931
+ visibility,
932
+ tenantId: readNonEmptyString2(topic.tenantId) || readNonEmptyString2(metadata.tenantId),
933
+ workspaceId: readNonEmptyString2(topic.workspaceId) || readNonEmptyString2(metadata.workspaceId),
934
+ status,
935
+ tags: readStringArray2(metadata.tags),
936
+ chatCount: typeof metadata.chatCount === "number" ? metadata.chatCount : 0,
937
+ artifactCount: typeof metadata.artifactCount === "number" ? metadata.artifactCount : 0,
938
+ lastActivityAt: typeof metadata.lastActivityAt === "number" ? metadata.lastActivityAt : updatedAt,
939
+ _creationTime: typeof topic._creationTime === "number" ? topic._creationTime : createdAt,
940
+ createdAt,
941
+ updatedAt
942
+ };
943
+ }
944
+ async function resolveTopicProjectOverlay2(ctx, scopeId, options = {}) {
945
+ const topic = await resolveTopicDoc2(ctx, scopeId);
946
+ if (!topic) {
947
+ return null;
948
+ }
949
+ if (options.projectLikeOnly !== false && !isProjectLikeTopic2(topic)) {
950
+ return null;
951
+ }
952
+ return materializeTopicProjectOverlay2(topic, options.idMode);
953
+ }
954
+ async function listTopicProjectOverlays2(ctx, options = {}) {
955
+ let allTopics = [];
956
+ if (ctx?.db?.query && typeof ctx.db.query === "function") {
957
+ try {
958
+ allTopics = await ctx.db.query("topics").collect();
959
+ } catch {
960
+ allTopics = [];
961
+ }
962
+ }
963
+ if (allTopics.length === 0 && typeof ctx.runQuery === "function") {
964
+ allTopics = (await ctx.runQuery(api2.topics.list, {}) ?? []) || [];
965
+ }
966
+ return allTopics.filter(
967
+ (topic) => options.projectLikeOnly === false || isProjectLikeTopic2(topic)
968
+ ).map((topic) => materializeTopicProjectOverlay2(topic, options.idMode));
969
+ }
970
+ async function patchTopicProjectOverlay(ctx, scopeId, value) {
971
+ const topic = await resolveTopicDoc2(ctx, scopeId);
972
+ if (!topic) {
973
+ return null;
974
+ }
975
+ const nextMetadata = { ...readMetadata2(topic) };
976
+ const patch = {};
977
+ const topicUpdateArgs = {
978
+ id: String(topic._id)
979
+ };
980
+ for (const [key, rawValue] of Object.entries(value)) {
981
+ switch (key) {
982
+ case "_id":
983
+ case "projectId":
984
+ case "topicId":
985
+ case "legacyProjectId":
986
+ case "storageProjectId":
987
+ break;
988
+ case "name":
989
+ case "description":
990
+ patch[key] = rawValue;
991
+ topicUpdateArgs[key] = rawValue;
992
+ break;
993
+ case "tenantId":
994
+ case "workspaceId":
995
+ case "ownerId":
996
+ throw new Error(
997
+ `patchTopicProjectOverlay cannot mutate ${key} via component-owned topics`
998
+ );
999
+ case "status": {
1000
+ const status = coerceStatus2(rawValue);
1001
+ if (status) {
1002
+ patch.status = status;
1003
+ topicUpdateArgs.status = status;
1004
+ }
1005
+ break;
1006
+ }
1007
+ case "visibility": {
1008
+ const visibility = coerceVisibility2(rawValue);
1009
+ if (visibility) {
1010
+ patch.visibility = visibility;
1011
+ topicUpdateArgs.visibility = visibility;
1012
+ }
1013
+ break;
1014
+ }
1015
+ case "type": {
1016
+ const projectType = readNonEmptyString2(rawValue);
1017
+ if (projectType) {
1018
+ nextMetadata.projectType = projectType;
1019
+ } else {
1020
+ delete nextMetadata.projectType;
1021
+ }
1022
+ break;
1023
+ }
1024
+ case "updatedAt":
1025
+ case "createdAt":
1026
+ break;
1027
+ default:
1028
+ if (rawValue === void 0) {
1029
+ delete nextMetadata[key];
1030
+ } else {
1031
+ nextMetadata[key] = rawValue;
1032
+ }
1033
+ }
1034
+ }
1035
+ patch.updatedAt = Date.now();
1036
+ patch.metadata = nextMetadata;
1037
+ topicUpdateArgs.metadata = nextMetadata;
1038
+ if (typeof ctx.runMutation === "function") {
1039
+ try {
1040
+ await ctx.runMutation(api2.topics.update, topicUpdateArgs);
1041
+ } catch (error) {
1042
+ if (!isMissingLucernChildComponentError(error) || !ctx?.db || typeof ctx.db.patch !== "function") {
1043
+ throw error;
1044
+ }
1045
+ await ctx.db.patch(String(topic._id), patch);
1046
+ }
1047
+ } else if (ctx?.db && typeof ctx.db.patch === "function") {
1048
+ await ctx.db.patch(String(topic._id), patch);
1049
+ } else {
1050
+ throw new Error(
1051
+ "Cannot patch topic without component adapter (ctx.runMutation unavailable)"
1052
+ );
1053
+ }
1054
+ return materializeTopicProjectOverlay2(
1055
+ {
1056
+ ...topic,
1057
+ ...patch,
1058
+ metadata: nextMetadata
1059
+ }
1060
+ );
1061
+ }
1062
+
1063
+ // src/resolvers.ts
1064
+ function isMissingLucernChildComponentError2(error) {
1065
+ const message = error instanceof Error ? error.message : String(error);
1066
+ return message.includes('Child component ComponentName(Identifier("lucern")) not found') || message.includes("Child component") && message.includes("lucern") && message.includes("not found");
1067
+ }
1068
+ function isAdvisoryTopicPatch(value) {
1069
+ const advisoryKeys = /* @__PURE__ */ new Set(["lastActivityAt", "updatedAt"]);
1070
+ const keys = Object.keys(value);
1071
+ return keys.length > 0 && keys.every((key) => advisoryKeys.has(key));
1072
+ }
1073
+ async function patchProjectWithTolerance(ctx, projectId, value) {
1074
+ try {
1075
+ await patchTopicProjectOverlay(ctx, projectId, value);
1076
+ } catch (error) {
1077
+ if (!isAdvisoryTopicPatch(value) || !isMissingLucernChildComponentError2(error)) {
1078
+ throw error;
1079
+ }
1080
+ console.warn("[lucern graph-primitives] Non-fatal advisory topic patch failure", {
1081
+ projectId,
1082
+ keys: Object.keys(value),
1083
+ error: error instanceof Error ? error.message : error
1084
+ });
1085
+ }
1086
+ }
1087
+ function defaultResolvers2() {
1088
+ return {
1089
+ async getProject(ctx, projectId) {
1090
+ return await resolveTopicProjectOverlay2(ctx, projectId, {
1091
+ idMode: "legacy",
1092
+ projectLikeOnly: false
1093
+ });
1094
+ },
1095
+ async patchProject(ctx, projectId, value) {
1096
+ await patchProjectWithTolerance(ctx, projectId, value);
1097
+ },
1098
+ async listTopics(ctx) {
1099
+ return await listTopicProjectOverlays2(ctx, {
1100
+ idMode: "legacy"
1101
+ });
1102
+ },
1103
+ async getFinalArtifact(ctx, artifactId) {
1104
+ return await ctx.db.get(artifactId);
1105
+ }
1106
+ };
1107
+ }
1108
+ var resolverOverrides2 = {};
1109
+ function resolveGraphPrimitivesAppResolvers(_ctx) {
1110
+ return {
1111
+ ...defaultResolvers2(),
1112
+ ...resolverOverrides2
1113
+ };
1114
+ }
1115
+ var optionalScopeArgs = {
1116
+ projectId: v.optional(v.string()),
1117
+ topicId: v.optional(v.string())
1118
+ };
1119
+
1120
+ // src/questionEvidenceLinks.ts
1121
+ var questionIdUnion = v.id("epistemicNodes");
1122
+ var insightIdUnion = v.id("epistemicNodes");
1123
+ var suggestionStatusValidator = v.union(
1124
+ v.literal("suggested"),
1125
+ v.literal("approved"),
1126
+ v.literal("dismissed")
1127
+ );
1128
+ var matcherMetadataValidator = v.object({
1129
+ surface: v.string(),
1130
+ matcherFamily: v.optional(v.string()),
1131
+ matcherKey: v.optional(v.string()),
1132
+ matcherVersion: v.optional(v.string()),
1133
+ reviewStatus: v.optional(
1134
+ v.union(
1135
+ v.literal("pending"),
1136
+ v.literal("accepted"),
1137
+ v.literal("rejected"),
1138
+ v.literal("auto_accepted"),
1139
+ v.literal("superseded")
1140
+ )
1141
+ ),
1142
+ configSnapshot: v.optional(v.any()),
1143
+ signalSnapshot: v.optional(v.any()),
1144
+ outcomeMetadata: v.optional(v.any())
1145
+ });
1146
+ async function markProjectGraphDirty(ctx, projectId) {
1147
+ if (!projectId) {
1148
+ return;
1149
+ }
1150
+ await ctx.scheduler.runAfter(
1151
+ 0,
1152
+ internal.graphAnalysisCache.markCacheStaleInternal,
1153
+ { projectId }
1154
+ );
1155
+ await resolveGraphPrimitivesAppResolvers().patchProject(ctx, projectId, {
1156
+ lastActivityAt: Date.now()
1157
+ });
1158
+ }
1159
+ async function recordMatcherDecision(ctx, args) {
1160
+ if (!args.matcherMetadata) {
1161
+ return;
1162
+ }
1163
+ await ctx.runMutation("matcherFeedback:recordDecision", {
1164
+ projectId: args.questionNode.projectId,
1165
+ topicId: args.questionNode.topicId,
1166
+ surface: args.matcherMetadata.surface,
1167
+ matcherFamily: args.matcherMetadata.matcherFamily,
1168
+ matcherKey: args.matcherMetadata.matcherKey,
1169
+ matcherVersion: args.matcherMetadata.matcherVersion,
1170
+ sourceEntityId: String(args.insightId),
1171
+ targetEntityId: String(args.questionId),
1172
+ suggestionTable: "questionEvidenceLinks",
1173
+ suggestionId: args.linkId,
1174
+ reviewStatus: deriveMatcherReviewStatus({
1175
+ explicitReviewStatus: args.matcherMetadata.reviewStatus,
1176
+ linkStatus: args.linkStatus
1177
+ }),
1178
+ reviewedBy: args.reviewedBy,
1179
+ decisionReason: args.decisionReason,
1180
+ configSnapshot: args.matcherMetadata.configSnapshot,
1181
+ signalSnapshot: args.matcherMetadata.signalSnapshot,
1182
+ outcomeMetadata: args.matcherMetadata.outcomeMetadata
1183
+ });
1184
+ }
1185
+ async function applyOperationalLinkEffects(ctx, args) {
1186
+ const meta = args.questionNode.metadata || {};
1187
+ const currentRelated = meta.relatedInsightIds || [];
1188
+ if (!currentRelated.includes(args.insightId)) {
1189
+ await ctx.db.patch(args.questionId, {
1190
+ updatedAt: Date.now(),
1191
+ metadata: {
1192
+ ...meta,
1193
+ relatedInsightIds: [...currentRelated, args.insightId]
1194
+ }
1195
+ });
1196
+ }
1197
+ try {
1198
+ const questionNode = await ctx.db.get(args.questionId);
1199
+ const evidenceNode = await ctx.db.get(args.insightId);
1200
+ if (questionNode && questionNode.nodeType === "question" && evidenceNode && evidenceNode.nodeType === "evidence" && questionNode.globalId && evidenceNode.globalId) {
1201
+ const existingEdge = await ctx.db.query("epistemicEdges").withIndex(
1202
+ "by_from_to",
1203
+ (q) => q.eq("fromNodeId", evidenceNode._id).eq("toNodeId", questionNode._id)
1204
+ ).first();
1205
+ if (!existingEdge) {
1206
+ const globalId = `edge-derived_from-${evidenceNode._id}-${questionNode._id}-${Date.now()}`;
1207
+ await ctx.scheduler.runAfter(0, internal.neo4jEdgeAPI.createEdge, {
1208
+ globalId,
1209
+ fromGlobalId: evidenceNode.globalId,
1210
+ toGlobalId: questionNode.globalId,
1211
+ edgeType: "derived_from",
1212
+ weight: args.relevance ?? 0.5,
1213
+ context: args.rationale || "Linked from question evidence links",
1214
+ projectId: args.questionNode.projectId ? String(args.questionNode.projectId) : void 0,
1215
+ createdBy: args.createdBy,
1216
+ fromNodeType: "evidence",
1217
+ toNodeType: "question",
1218
+ fromLayer: "L2",
1219
+ toLayer: "L3"
1220
+ });
1221
+ }
1222
+ }
1223
+ } catch (e) {
1224
+ console.error("[EpistemicSpine] Failed to create derived_from edge:", e);
1225
+ }
1226
+ if (args.questionNode.projectId) {
1227
+ await ctx.scheduler.runAfter(
1228
+ 0,
1229
+ "verificationActions:deepVerifyEvidence",
1230
+ {
1231
+ insightId: args.insightId,
1232
+ targetType: "question",
1233
+ targetId: args.questionId,
1234
+ projectId: args.questionNode.projectId,
1235
+ userId: args.createdBy
1236
+ }
1237
+ );
1238
+ }
1239
+ }
1240
+ async function removeOperationalLinkEffects(ctx, args) {
1241
+ const question = await ctx.db.get(args.questionId);
1242
+ if (question) {
1243
+ const meta = question.metadata || {};
1244
+ const currentRelated = meta.relatedInsightIds || [];
1245
+ await ctx.db.patch(args.questionId, {
1246
+ updatedAt: Date.now(),
1247
+ metadata: {
1248
+ ...meta,
1249
+ relatedInsightIds: currentRelated.filter(
1250
+ (id) => id !== args.insightId
1251
+ )
1252
+ }
1253
+ });
1254
+ }
1255
+ try {
1256
+ const questionNode = await ctx.db.get(args.questionId);
1257
+ const evidenceNode = await ctx.db.get(args.insightId);
1258
+ if (questionNode && questionNode.nodeType === "question" && evidenceNode && evidenceNode.nodeType === "evidence") {
1259
+ const edge = await ctx.db.query("epistemicEdges").withIndex(
1260
+ "by_from_to",
1261
+ (q) => q.eq("fromNodeId", evidenceNode._id).eq("toNodeId", questionNode._id)
1262
+ ).first();
1263
+ if (edge) {
1264
+ await ctx.scheduler.runAfter(0, internal.neo4jEdgeAPI.deleteEdge, {
1265
+ globalId: edge.globalId
1266
+ });
1267
+ await ctx.db.delete(edge._id);
1268
+ }
1269
+ }
1270
+ } catch (e) {
1271
+ console.error("[EpistemicSpine] Failed to remove edge:", e);
1272
+ }
1273
+ }
1274
+ var create = mutation({
1275
+ args: {
1276
+ questionId: questionIdUnion,
1277
+ insightId: insightIdUnion,
1278
+ helpsAnswer: v.boolean(),
1279
+ relevance: v.optional(v.number()),
1280
+ rationale: v.optional(v.string()),
1281
+ impactScore: v.optional(v.number()),
1282
+ impact: v.optional(
1283
+ v.union(
1284
+ v.literal("supports"),
1285
+ v.literal("contradicts"),
1286
+ v.literal("neutral")
1287
+ )
1288
+ ),
1289
+ status: v.optional(suggestionStatusValidator),
1290
+ matcherMetadata: v.optional(matcherMetadataValidator),
1291
+ createdBy: v.string()
1292
+ },
1293
+ returns: permissiveReturn,
1294
+ handler: async (ctx, args) => {
1295
+ const question = await ctx.db.get(args.questionId);
1296
+ if (!question) {
1297
+ throw new Error("Question not found");
1298
+ }
1299
+ const insight = await ctx.db.get(args.insightId);
1300
+ if (!insight) {
1301
+ throw new Error("Insight not found");
1302
+ }
1303
+ const existingLinks = await ctx.db.query("questionEvidenceLinks").withIndex("by_questionId", (q) => q.eq("questionId", args.questionId)).collect();
1304
+ const duplicate = existingLinks.find(
1305
+ (link) => link.insightId === args.insightId
1306
+ );
1307
+ const impactScore = args.impactScore;
1308
+ const derivedImpact = impactScore !== void 0 ? impactScore > 0 ? "supports" : impactScore < 0 ? "contradicts" : "neutral" : args.impact;
1309
+ if (duplicate) {
1310
+ const nextStatus = mergeLinkSuggestionStatus(
1311
+ duplicate.status,
1312
+ args.status
1313
+ );
1314
+ await ctx.db.patch(duplicate._id, {
1315
+ helpsAnswer: args.helpsAnswer,
1316
+ relevance: args.relevance,
1317
+ rationale: args.rationale,
1318
+ impactScore: args.impactScore,
1319
+ impact: derivedImpact,
1320
+ status: nextStatus
1321
+ });
1322
+ if (isOperationalLinkStatus(nextStatus) && !isOperationalLinkStatus(
1323
+ duplicate.status
1324
+ )) {
1325
+ await applyOperationalLinkEffects(ctx, {
1326
+ questionNode: question,
1327
+ questionId: args.questionId,
1328
+ insightId: args.insightId,
1329
+ relevance: args.relevance,
1330
+ rationale: args.rationale,
1331
+ createdBy: args.createdBy
1332
+ });
1333
+ }
1334
+ await recordMatcherDecision(ctx, {
1335
+ questionNode: question,
1336
+ questionId: args.questionId,
1337
+ insightId: args.insightId,
1338
+ linkId: duplicate._id,
1339
+ linkStatus: nextStatus,
1340
+ matcherMetadata: args.matcherMetadata
1341
+ });
1342
+ await markProjectGraphDirty(ctx, question.projectId);
1343
+ return duplicate._id;
1344
+ }
1345
+ const linkId = await ctx.db.insert("questionEvidenceLinks", {
1346
+ questionId: args.questionId,
1347
+ insightId: args.insightId,
1348
+ helpsAnswer: args.helpsAnswer,
1349
+ relevance: args.relevance,
1350
+ rationale: args.rationale,
1351
+ impactScore: args.impactScore,
1352
+ impact: derivedImpact,
1353
+ status: args.status,
1354
+ createdBy: args.createdBy,
1355
+ createdAt: Date.now()
1356
+ });
1357
+ await recordMatcherDecision(ctx, {
1358
+ questionNode: question,
1359
+ questionId: args.questionId,
1360
+ insightId: args.insightId,
1361
+ linkId,
1362
+ linkStatus: args.status,
1363
+ matcherMetadata: args.matcherMetadata
1364
+ });
1365
+ if (isOperationalLinkStatus(args.status)) {
1366
+ await applyOperationalLinkEffects(ctx, {
1367
+ questionNode: question,
1368
+ questionId: args.questionId,
1369
+ insightId: args.insightId,
1370
+ relevance: args.relevance,
1371
+ rationale: args.rationale,
1372
+ createdBy: args.createdBy
1373
+ });
1374
+ }
1375
+ await markProjectGraphDirty(ctx, question.projectId);
1376
+ return linkId;
1377
+ }
1378
+ });
1379
+ var updateImpact = mutation({
1380
+ args: {
1381
+ linkId: v.id("questionEvidenceLinks"),
1382
+ impactScore: v.optional(v.number()),
1383
+ impact: v.optional(
1384
+ v.union(
1385
+ v.literal("supports"),
1386
+ v.literal("contradicts"),
1387
+ v.literal("neutral")
1388
+ )
1389
+ ),
1390
+ userId: v.string()
1391
+ },
1392
+ returns: permissiveReturn,
1393
+ handler: async (ctx, args) => {
1394
+ const link = await ctx.db.get(args.linkId);
1395
+ if (!link) {
1396
+ throw new Error("Link not found");
1397
+ }
1398
+ const newImpactScore = args.impactScore;
1399
+ const newImpact = newImpactScore !== void 0 ? newImpactScore > 0 ? "supports" : newImpactScore < 0 ? "contradicts" : "neutral" : args.impact;
1400
+ const updateData = {};
1401
+ if (newImpact) {
1402
+ updateData.impact = newImpact;
1403
+ }
1404
+ if (newImpactScore !== void 0) {
1405
+ updateData.impactScore = newImpactScore;
1406
+ }
1407
+ await ctx.db.patch(args.linkId, updateData);
1408
+ const question = await ctx.db.get(link.questionId);
1409
+ await markProjectGraphDirty(ctx, question?.projectId);
1410
+ return { success: true, newImpact, newImpactScore };
1411
+ }
1412
+ });
1413
+ var reviewSuggestion = mutation({
1414
+ args: {
1415
+ linkId: v.id("questionEvidenceLinks"),
1416
+ status: v.union(v.literal("approved"), v.literal("dismissed")),
1417
+ userId: v.string(),
1418
+ reason: v.optional(v.string())
1419
+ },
1420
+ returns: permissiveReturn,
1421
+ handler: async (ctx, args) => {
1422
+ const link = await ctx.db.get(args.linkId);
1423
+ if (!link) {
1424
+ throw new Error("Link not found");
1425
+ }
1426
+ const question = await ctx.db.get(link.questionId);
1427
+ if (!question) {
1428
+ throw new Error("Question not found");
1429
+ }
1430
+ let hasAccess = link.createdBy === args.userId;
1431
+ if (!hasAccess && question.projectId) {
1432
+ hasAccess = await checkProjectAccess(
1433
+ ctx,
1434
+ question.projectId,
1435
+ args.userId
1436
+ );
1437
+ }
1438
+ if (!hasAccess) {
1439
+ throw new Error("No permission to review this link");
1440
+ }
1441
+ const previousStatus = link.status;
1442
+ const nextStatus = resolveReviewedLinkStatus(args.status);
1443
+ await ctx.db.patch(args.linkId, { status: nextStatus });
1444
+ if (nextStatus === "approved" && !isOperationalLinkStatus(previousStatus)) {
1445
+ await applyOperationalLinkEffects(ctx, {
1446
+ questionNode: question,
1447
+ questionId: link.questionId,
1448
+ insightId: link.insightId,
1449
+ relevance: link.relevance,
1450
+ rationale: link.rationale,
1451
+ createdBy: args.userId
1452
+ });
1453
+ }
1454
+ if (nextStatus === "dismissed" && isOperationalLinkStatus(previousStatus)) {
1455
+ await removeOperationalLinkEffects(ctx, {
1456
+ questionId: link.questionId,
1457
+ insightId: link.insightId
1458
+ });
1459
+ }
1460
+ await ctx.runMutation("matcherFeedback:recordDecision", {
1461
+ projectId: question.projectId,
1462
+ topicId: question.topicId,
1463
+ sourceEntityId: String(link.insightId),
1464
+ targetEntityId: String(link.questionId),
1465
+ suggestionTable: "questionEvidenceLinks",
1466
+ suggestionId: args.linkId,
1467
+ reviewStatus: deriveMatcherReviewStatus({ linkStatus: nextStatus }),
1468
+ reviewedBy: args.userId,
1469
+ decisionReason: args.reason,
1470
+ outcomeMetadata: args.reason ? { reason: args.reason } : void 0
1471
+ });
1472
+ await markProjectGraphDirty(ctx, question.projectId);
1473
+ return { success: true, status: nextStatus };
1474
+ }
1475
+ });
1476
+ var remove = mutation({
1477
+ args: {
1478
+ linkId: v.id("questionEvidenceLinks"),
1479
+ userId: v.string()
1480
+ },
1481
+ returns: permissiveReturn,
1482
+ handler: async (ctx, args) => {
1483
+ const link = await ctx.db.get(args.linkId);
1484
+ if (!link) {
1485
+ throw new Error("Link not found");
1486
+ }
1487
+ if (link.createdBy !== args.userId) {
1488
+ throw new Error("Only the creator can remove this link");
1489
+ }
1490
+ const question = await ctx.db.get(link.questionId);
1491
+ if (isOperationalLinkStatus(link.status)) {
1492
+ await removeOperationalLinkEffects(ctx, {
1493
+ questionId: link.questionId,
1494
+ insightId: link.insightId
1495
+ });
1496
+ }
1497
+ await ctx.db.delete(args.linkId);
1498
+ await markProjectGraphDirty(ctx, question?.projectId);
1499
+ }
1500
+ });
1501
+ var getByQuestion = query({
1502
+ args: {
1503
+ questionId: v.id("epistemicNodes")
1504
+ },
1505
+ returns: permissiveReturn,
1506
+ handler: async (ctx, args) => {
1507
+ const links = await ctx.db.query("questionEvidenceLinks").withIndex("by_questionId", (q) => q.eq("questionId", args.questionId)).collect();
1508
+ return links.filter(
1509
+ (link) => isOperationalLinkStatus(link.status)
1510
+ );
1511
+ }
1512
+ });
1513
+ var getPendingSuggestions = query({
1514
+ args: {
1515
+ questionId: v.id("epistemicNodes")
1516
+ },
1517
+ returns: permissiveReturn,
1518
+ handler: async (ctx, args) => {
1519
+ const links = await ctx.db.query("questionEvidenceLinks").withIndex("by_questionId", (q) => q.eq("questionId", args.questionId)).collect();
1520
+ return links.filter((link) => link.status === "suggested");
1521
+ }
1522
+ });
1523
+ var getByInsight = query({
1524
+ args: {
1525
+ insightId: v.id("epistemicNodes")
1526
+ },
1527
+ returns: permissiveReturn,
1528
+ handler: async (ctx, args) => {
1529
+ const links = await ctx.db.query("questionEvidenceLinks").withIndex("by_insightId", (q) => q.eq("insightId", args.insightId)).collect();
1530
+ return links.filter(
1531
+ (link) => isOperationalLinkStatus(link.status)
1532
+ );
1533
+ }
1534
+ });
1535
+ var getEvidenceWithDetails = query({
1536
+ args: {
1537
+ questionId: v.id("epistemicNodes")
1538
+ },
1539
+ returns: permissiveReturn,
1540
+ handler: async (ctx, args) => {
1541
+ const questionNode = await ctx.db.get(args.questionId);
1542
+ if (!questionNode || questionNode.nodeType !== "question") {
1543
+ return [];
1544
+ }
1545
+ const links = await ctx.db.query("questionEvidenceLinks").withIndex("by_questionId", (q) => q.eq("questionId", args.questionId)).collect();
1546
+ const linksWithDetails = await Promise.all(
1547
+ links.filter(
1548
+ (link) => isOperationalLinkStatus(
1549
+ link.status
1550
+ )
1551
+ ).map(async (link) => {
1552
+ const insight = await ctx.db.get(link.insightId);
1553
+ return {
1554
+ ...link,
1555
+ insight
1556
+ };
1557
+ })
1558
+ );
1559
+ const filtered = linksWithDetails.filter((l) => l.insight !== null);
1560
+ const epistemicEdgeResults = [];
1561
+ const seenEvidenceIds = new Set(filtered.map((l) => String(l.insightId)));
1562
+ const edges = await ctx.db.query("epistemicEdges").withIndex(
1563
+ "by_to_type",
1564
+ (q) => q.eq("toNodeId", args.questionId).eq("edgeType", "derived_from")
1565
+ ).collect();
1566
+ for (const edge of edges) {
1567
+ if (!edge.fromNodeId || seenEvidenceIds.has(String(edge.fromNodeId))) {
1568
+ continue;
1569
+ }
1570
+ seenEvidenceIds.add(String(edge.fromNodeId));
1571
+ const evidenceNode = await ctx.db.get(edge.fromNodeId);
1572
+ if (!evidenceNode || evidenceNode.nodeType !== "evidence" || evidenceNode.status !== "active") {
1573
+ continue;
1574
+ }
1575
+ const meta = evidenceNode.metadata || {};
1576
+ epistemicEdgeResults.push({
1577
+ _id: edge._id,
1578
+ _creationTime: edge.createdAt,
1579
+ questionId: args.questionId,
1580
+ insightId: edge.fromNodeId,
1581
+ impact: (edge.weight ?? 0) > 0 ? "supports" : (edge.weight ?? 0) < 0 ? "contradicts" : "neutral",
1582
+ impactScore: edge.weight != null ? Math.round(edge.weight * 10) : 0,
1583
+ rationale: edge.context || null,
1584
+ userId: edge.createdBy,
1585
+ createdAt: edge.createdAt,
1586
+ insight: {
1587
+ _id: evidenceNode._id,
1588
+ _creationTime: evidenceNode.createdAt,
1589
+ insight: evidenceNode.canonicalText || evidenceNode.title || meta.snippet || null,
1590
+ text: evidenceNode.canonicalText || evidenceNode.title || meta.snippet || null,
1591
+ title: evidenceNode.title || null,
1592
+ canonicalText: evidenceNode.canonicalText || null,
1593
+ source: meta.sourceTitle || null,
1594
+ sourceUrl: meta.sourceUrl || null,
1595
+ verificationStatus: evidenceNode.verificationStatus || "unverified"
1596
+ }
1597
+ });
1598
+ }
1599
+ return [...filtered, ...epistemicEdgeResults];
1600
+ }
1601
+ });
1602
+ var getByProject = query({
1603
+ args: {
1604
+ ...optionalScopeArgs,
1605
+ userId: v.string(),
1606
+ limit: v.optional(v.number())
1607
+ },
1608
+ returns: permissiveReturn,
1609
+ handler: async (ctx, args) => {
1610
+ if (!args.projectId) {
1611
+ return [];
1612
+ }
1613
+ const hasAccess = await checkProjectAccess(
1614
+ ctx,
1615
+ args.projectId,
1616
+ args.userId
1617
+ );
1618
+ if (!hasAccess) {
1619
+ return [];
1620
+ }
1621
+ const pageSize = Math.max(1, Math.min(Math.floor(args.limit ?? 300), 1e3));
1622
+ const questionScanLimit = Math.min(pageSize * 2, 1e3);
1623
+ const questions = await ctx.db.query("epistemicNodes").withIndex(
1624
+ args.topicId ? "by_topic_type" : "by_project_type",
1625
+ (q) => args.topicId ? q.eq("topicId", args.topicId).eq("nodeType", "question") : q.eq("projectId", args.projectId).eq("nodeType", "question")
1626
+ ).order("desc").take(questionScanLimit);
1627
+ const questionIds = questions.slice(0, pageSize).map((q) => q._id);
1628
+ const allLinks = await Promise.all(
1629
+ questionIds.map(async (questionId) => {
1630
+ const links = await ctx.db.query("questionEvidenceLinks").withIndex("by_questionId", (q) => q.eq("questionId", questionId)).collect();
1631
+ return links.filter(
1632
+ (link) => isOperationalLinkStatus(
1633
+ link.status
1634
+ )
1635
+ );
1636
+ })
1637
+ );
1638
+ const flattenedLinks = allLinks.flat().slice(0, pageSize * 5);
1639
+ const questionDetails = {};
1640
+ for (const question of questions) {
1641
+ const meta = question.metadata || {};
1642
+ questionDetails[question._id] = {
1643
+ _id: question._id,
1644
+ question: question.canonicalText || question.title || "",
1645
+ status: meta.status || question.status || "active"
1646
+ };
1647
+ }
1648
+ return {
1649
+ links: flattenedLinks,
1650
+ questionDetails
1651
+ };
1652
+ }
1653
+ });
1654
+ var getLinkedQuestionsForInsight = query({
1655
+ args: {
1656
+ insightId: v.id("epistemicNodes")
1657
+ },
1658
+ returns: permissiveReturn,
1659
+ handler: async (ctx, args) => {
1660
+ const links = await ctx.db.query("questionEvidenceLinks").withIndex("by_insightId", (q) => q.eq("insightId", args.insightId)).collect();
1661
+ const linkedQuestions = await Promise.all(
1662
+ links.filter(
1663
+ (link) => isOperationalLinkStatus(
1664
+ link.status
1665
+ )
1666
+ ).map(async (link) => {
1667
+ const question = await ctx.db.get(link.questionId);
1668
+ return {
1669
+ linkId: link._id,
1670
+ questionId: link.questionId,
1671
+ helpsAnswer: link.helpsAnswer,
1672
+ relevance: link.relevance,
1673
+ rationale: link.rationale,
1674
+ createdBy: link.createdBy,
1675
+ createdAt: link.createdAt,
1676
+ question: question ? {
1677
+ _id: question._id,
1678
+ question: question.question || question.canonicalText || "",
1679
+ status: question.status
1680
+ } : null
1681
+ };
1682
+ })
1683
+ );
1684
+ return linkedQuestions.filter((row) => row.question !== null);
1685
+ }
1686
+ });
1687
+
1688
+ export { create, getByInsight, getByProject, getByQuestion, getEvidenceWithDetails, getLinkedQuestionsForInsight, getPendingSuggestions, remove, reviewSuggestion, updateImpact };
1689
+ //# sourceMappingURL=questionEvidenceLinks.js.map
1690
+ //# sourceMappingURL=questionEvidenceLinks.js.map