@lucern/graph-primitives 0.1.0-alpha.4 → 0.3.0-alpha.1

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 (78) hide show
  1. package/dist/beliefDecay.js +229 -1115
  2. package/dist/beliefDecay.js.map +1 -1
  3. package/dist/beliefEvidenceLinks.js +53 -834
  4. package/dist/beliefEvidenceLinks.js.map +1 -1
  5. package/dist/confidencePropagationDispatch.d.ts +3 -3
  6. package/dist/confidencePropagationDispatch.js +30 -308
  7. package/dist/confidencePropagationDispatch.js.map +1 -1
  8. package/dist/contradictions.js +5 -797
  9. package/dist/contradictions.js.map +1 -1
  10. package/dist/edges/contradicts.js +1 -122
  11. package/dist/edges/contradicts.js.map +1 -1
  12. package/dist/edges/dependsOn.js +14 -172
  13. package/dist/edges/dependsOn.js.map +1 -1
  14. package/dist/edges/elaborates.js +1 -49
  15. package/dist/edges/elaborates.js.map +1 -1
  16. package/dist/edges/index.js +14 -277
  17. package/dist/edges/index.js.map +1 -1
  18. package/dist/edges/informs.js +1 -62
  19. package/dist/edges/informs.js.map +1 -1
  20. package/dist/edges/propagationTypes.d.ts +2 -2
  21. package/dist/edges/propagationTypes.js.map +1 -1
  22. package/dist/edges/refutes.js +1 -62
  23. package/dist/edges/refutes.js.map +1 -1
  24. package/dist/edges/supports.js +1 -122
  25. package/dist/edges/supports.js.map +1 -1
  26. package/dist/edges/utils.d.ts +6 -6
  27. package/dist/edges/utils.js +1 -130
  28. package/dist/edges/utils.js.map +1 -1
  29. package/dist/entityBridge.js +2 -17
  30. package/dist/entityBridge.js.map +1 -1
  31. package/dist/entityLifecycle.js +62 -848
  32. package/dist/entityLifecycle.js.map +1 -1
  33. package/dist/epistemicAnswers.js +27 -838
  34. package/dist/epistemicAnswers.js.map +1 -1
  35. package/dist/epistemicBeliefs.js +186 -2214
  36. package/dist/epistemicBeliefs.js.map +1 -1
  37. package/dist/epistemicContractHelpers.js +1 -318
  38. package/dist/epistemicContractHelpers.js.map +1 -1
  39. package/dist/epistemicContracts.js +163 -2467
  40. package/dist/epistemicContracts.js.map +1 -1
  41. package/dist/epistemicEdges.js +60 -863
  42. package/dist/epistemicEdges.js.map +1 -1
  43. package/dist/epistemicEvidence.js +116 -1647
  44. package/dist/epistemicEvidence.js.map +1 -1
  45. package/dist/epistemicHelpers.js +3 -2
  46. package/dist/epistemicHelpers.js.map +1 -1
  47. package/dist/epistemicLinking.js +2 -785
  48. package/dist/epistemicLinking.js.map +1 -1
  49. package/dist/epistemicNodes.js +34 -1427
  50. package/dist/epistemicNodes.js.map +1 -1
  51. package/dist/epistemicQuestions.js +88 -1637
  52. package/dist/epistemicQuestions.js.map +1 -1
  53. package/dist/epistemicSources.js +28 -1421
  54. package/dist/epistemicSources.js.map +1 -1
  55. package/dist/evaluators/index.js +163 -2467
  56. package/dist/evaluators/index.js.map +1 -1
  57. package/dist/index.js +486 -3649
  58. package/dist/index.js.map +1 -1
  59. package/dist/ontology-matching.js +1 -344
  60. package/dist/ontology-matching.js.map +1 -1
  61. package/dist/ontologyApproval.js +1 -13
  62. package/dist/ontologyApproval.js.map +1 -1
  63. package/dist/ontologyDefinitions.js +2 -17
  64. package/dist/ontologyDefinitions.js.map +1 -1
  65. package/dist/ontologyRegistry.js +2 -17
  66. package/dist/ontologyRegistry.js.map +1 -1
  67. package/dist/projectionReconciliation.js +2 -17
  68. package/dist/projectionReconciliation.js.map +1 -1
  69. package/dist/questionEvidenceLinks.js +242 -837
  70. package/dist/questionEvidenceLinks.js.map +1 -1
  71. package/dist/text-matching.js +1 -244
  72. package/dist/text-matching.js.map +1 -1
  73. package/dist/workflowBridge.d.ts +27 -0
  74. package/dist/workflowBridge.js +303 -0
  75. package/dist/workflowBridge.js.map +1 -0
  76. package/dist/workspaceIsolation.js +8 -609
  77. package/dist/workspaceIsolation.js.map +1 -1
  78. package/package.json +6 -6
@@ -1,5 +1,7 @@
1
1
  import { v } from 'convex/values';
2
2
  import { componentsGeneric, mutationGeneric, anyApi, internalMutationGeneric, queryGeneric } from 'convex/server';
3
+ import { checkScopeAccess } from '@lucern/access-control/access';
4
+ import { permissiveReturn } from '@lucern/contracts/schema-helpers/validators';
3
5
 
4
6
  // src/epistemicAnswers.ts
5
7
  var api = anyApi;
@@ -8,791 +10,6 @@ var internal = anyApi;
8
10
  var internalMutation = internalMutationGeneric;
9
11
  var mutation = mutationGeneric;
10
12
  var query = queryGeneric;
11
- var api2 = anyApi;
12
- componentsGeneric();
13
-
14
- // ../access-control/src/topicProjectOverlay.ts
15
- var LEGACY_SCOPE_FIELD = "graphScopeProjectId";
16
- function readNonEmptyString(value) {
17
- if (typeof value !== "string") {
18
- return;
19
- }
20
- const normalized = value.trim();
21
- return normalized.length > 0 ? normalized : void 0;
22
- }
23
- function readStringArray(value) {
24
- if (!Array.isArray(value)) {
25
- return [];
26
- }
27
- return value.map((entry) => readNonEmptyString(entry)).filter((entry) => Boolean(entry));
28
- }
29
- function readMetadata(topic) {
30
- return topic.metadata && typeof topic.metadata === "object" ? topic.metadata : {};
31
- }
32
- function readLegacyProjectId(value) {
33
- if (!value) {
34
- return;
35
- }
36
- return readNonEmptyString(value[LEGACY_SCOPE_FIELD]);
37
- }
38
- function coerceVisibility(value) {
39
- return value === "private" || value === "team" || value === "firm" || value === "external" || value === "public" ? value : void 0;
40
- }
41
- function coerceStatus(value) {
42
- return value === "active" || value === "archived" || value === "watching" ? value : void 0;
43
- }
44
- function mapProjectType(topic, metadata) {
45
- const explicit = readNonEmptyString(metadata.projectType);
46
- if (explicit) {
47
- return explicit;
48
- }
49
- if (topic.type === "theme") {
50
- return "thematic";
51
- }
52
- return readNonEmptyString(topic.type) || "general";
53
- }
54
- function isProjectLikeTopic(topic) {
55
- const metadata = readMetadata(topic);
56
- return topic.type === "theme" || topic.type === "thematic" || topic.type === "deal" || topic.type === "monitoring" || readLegacyProjectId(topic) !== void 0 || readNonEmptyString(metadata.projectType) !== void 0;
57
- }
58
- async function resolveTopicDoc(ctx, scopeId) {
59
- if (ctx?.db && typeof ctx.db.get === "function") {
60
- try {
61
- const directTopic = await ctx.db.get(scopeId);
62
- if (directTopic) {
63
- return directTopic;
64
- }
65
- } catch {
66
- }
67
- }
68
- if (typeof ctx.runQuery !== "function") {
69
- return null;
70
- }
71
- try {
72
- const topic = await ctx.runQuery(api2.topics.get, {
73
- id: String(scopeId)
74
- });
75
- if (topic?.name !== void 0 && topic?.type !== void 0) {
76
- return topic;
77
- }
78
- } catch {
79
- }
80
- try {
81
- const topic = await ctx.runQuery(api2.topics.getByLegacyScopeId, {
82
- projectId: String(scopeId)
83
- });
84
- if (topic?.name !== void 0 && topic?.type !== void 0) {
85
- return topic;
86
- }
87
- } catch {
88
- }
89
- return null;
90
- }
91
- function materializeTopicProjectOverlay(topic, idMode = "legacy") {
92
- const metadata = readMetadata(topic);
93
- const topicId = String(topic._id);
94
- const legacyProjectId = readLegacyProjectId(topic) || readLegacyProjectId(metadata) || readNonEmptyString(metadata.legacyProjectId);
95
- const storageProjectId = legacyProjectId || topicId;
96
- const outwardId = idMode === "topic" ? topicId : storageProjectId;
97
- const visibility = coerceVisibility(topic.visibility) || coerceVisibility(metadata.visibility) || "private";
98
- const status = coerceStatus(topic.status) || coerceStatus(metadata.status) || "active";
99
- const createdAt = typeof topic.createdAt === "number" ? topic.createdAt : typeof topic._creationTime === "number" ? topic._creationTime : 0;
100
- const updatedAt = typeof topic.updatedAt === "number" ? topic.updatedAt : typeof metadata.updatedAt === "number" ? metadata.updatedAt : createdAt;
101
- return {
102
- ...metadata,
103
- _id: outwardId,
104
- projectId: outwardId,
105
- topicId,
106
- storageProjectId,
107
- legacyProjectId,
108
- name: readNonEmptyString(topic.name) || "Untitled Theme",
109
- type: mapProjectType(topic, metadata),
110
- description: readNonEmptyString(topic.description),
111
- ownerId: readNonEmptyString(metadata.ownerId) || readNonEmptyString(topic.createdBy) || "system",
112
- sharedWith: readStringArray(metadata.sharedWith),
113
- visibility,
114
- tenantId: readNonEmptyString(topic.tenantId) || readNonEmptyString(metadata.tenantId),
115
- workspaceId: readNonEmptyString(topic.workspaceId) || readNonEmptyString(metadata.workspaceId),
116
- status,
117
- tags: readStringArray(metadata.tags),
118
- chatCount: typeof metadata.chatCount === "number" ? metadata.chatCount : 0,
119
- artifactCount: typeof metadata.artifactCount === "number" ? metadata.artifactCount : 0,
120
- lastActivityAt: typeof metadata.lastActivityAt === "number" ? metadata.lastActivityAt : updatedAt,
121
- _creationTime: typeof topic._creationTime === "number" ? topic._creationTime : createdAt,
122
- createdAt,
123
- updatedAt
124
- };
125
- }
126
- async function resolveTopicProjectOverlay(ctx, scopeId, options = {}) {
127
- const topic = await resolveTopicDoc(ctx, scopeId);
128
- if (!topic) {
129
- return null;
130
- }
131
- if (options.projectLikeOnly !== false && !isProjectLikeTopic(topic)) {
132
- return null;
133
- }
134
- return materializeTopicProjectOverlay(topic, options.idMode);
135
- }
136
- async function listTopicProjectOverlays(ctx, options = {}) {
137
- let allTopics = [];
138
- if (ctx?.db?.query && typeof ctx.db.query === "function") {
139
- try {
140
- allTopics = await ctx.db.query("topics").collect();
141
- } catch {
142
- allTopics = [];
143
- }
144
- }
145
- if (allTopics.length === 0 && typeof ctx.runQuery === "function") {
146
- allTopics = (await ctx.runQuery(api2.topics.list, {}) ?? []) || [];
147
- }
148
- return allTopics.filter(
149
- (topic) => options.projectLikeOnly === false || isProjectLikeTopic(topic)
150
- ).map((topic) => materializeTopicProjectOverlay(topic, options.idMode));
151
- }
152
-
153
- // ../access-control/src/projectGrantsBridge.ts
154
- var PROJECT_GRANT_STATUSES = ["active", "revoked", "expired"];
155
- function normalizeString(value) {
156
- if (typeof value !== "string") {
157
- return;
158
- }
159
- const trimmed = value.trim();
160
- return trimmed.length > 0 ? trimmed : void 0;
161
- }
162
- async function resolveGrantScopeIds(ctx, args) {
163
- const topicId = normalizeString(args.topicId);
164
- const projectId = normalizeString(args.projectId);
165
- for (const scopeId of [topicId, projectId]) {
166
- if (!scopeId) {
167
- continue;
168
- }
169
- try {
170
- const overlay = await resolveTopicProjectOverlay(ctx, scopeId, {
171
- idMode: "legacy",
172
- projectLikeOnly: false
173
- });
174
- if (overlay) {
175
- return {
176
- topicId: normalizeString(overlay.topicId) ?? topicId,
177
- projectId: normalizeString(overlay.projectId) ?? projectId ?? scopeId
178
- };
179
- }
180
- } catch {
181
- }
182
- }
183
- return { topicId, projectId };
184
- }
185
- async function normalizeProjectGrantRow(ctx, row) {
186
- const scope = await resolveGrantScopeIds(ctx, {
187
- topicId: row.topicId,
188
- projectId: row.projectId
189
- });
190
- return {
191
- ...row,
192
- ...scope.topicId ? { topicId: scope.topicId } : {},
193
- ...scope.projectId ?? scope.topicId ? { projectId: scope.projectId ?? scope.topicId } : {}
194
- };
195
- }
196
- async function normalizeProjectGrantRows(ctx, rows) {
197
- return await Promise.all(rows.map((row) => normalizeProjectGrantRow(ctx, row)));
198
- }
199
- async function listProjectGrantsByPrincipal(ctx, principalId) {
200
- const rows = await Promise.all(
201
- PROJECT_GRANT_STATUSES.map(
202
- (status) => ctx.db.query("projectGrants").withIndex(
203
- "by_principal_status",
204
- (q) => q.eq("principalId", principalId).eq("status", status)
205
- ).collect()
206
- )
207
- );
208
- return await normalizeProjectGrantRows(ctx, rows.flat());
209
- }
210
- async function listProjectGrantsByGroup(ctx, groupId) {
211
- const rows = await Promise.all(
212
- PROJECT_GRANT_STATUSES.map(
213
- (status) => ctx.db.query("projectGrants").withIndex(
214
- "by_group_status",
215
- (q) => q.eq("groupId", groupId).eq("status", status)
216
- ).collect()
217
- )
218
- );
219
- return await normalizeProjectGrantRows(ctx, rows.flat());
220
- }
221
- function buildScopeMatchers(inputScopeId, resolved) {
222
- return new Set(
223
- [inputScopeId, resolved.topicId, resolved.projectId].map((value) => normalizeString(value)).filter((value) => Boolean(value))
224
- );
225
- }
226
- function matchesResolvedScope(row, scopeIds) {
227
- const rowTopicId = normalizeString(row.topicId);
228
- const rowProjectId = normalizeString(row.projectId);
229
- return rowTopicId !== void 0 && scopeIds.has(rowTopicId) || rowProjectId !== void 0 && scopeIds.has(rowProjectId);
230
- }
231
- async function bridgeListProjectGrantsByTopicAndPrincipal(ctx, topicId, principalId) {
232
- const resolved = await resolveGrantScopeIds(ctx, { topicId });
233
- const scopeIds = buildScopeMatchers(topicId, resolved);
234
- const rows = await listProjectGrantsByPrincipal(ctx, principalId);
235
- return rows.filter((row) => matchesResolvedScope(row, scopeIds));
236
- }
237
- async function bridgeListProjectGrantsByTopicAndGroup(ctx, topicId, groupId) {
238
- const resolved = await resolveGrantScopeIds(ctx, { topicId });
239
- const scopeIds = buildScopeMatchers(topicId, resolved);
240
- const rows = await listProjectGrantsByGroup(ctx, groupId);
241
- return rows.filter((row) => matchesResolvedScope(row, scopeIds));
242
- }
243
- async function bridgeListProjectGrantsByPrincipalStatus(ctx, principalId, status) {
244
- const rows = await listProjectGrantsByPrincipal(ctx, principalId);
245
- return rows.filter((row) => row.status === status);
246
- }
247
- async function bridgeListProjectGrantsByGroupStatus(ctx, groupId, status) {
248
- const rows = await listProjectGrantsByGroup(ctx, groupId);
249
- return rows.filter((row) => row.status === status);
250
- }
251
- async function bridgeInsertProjectGrant(ctx, value) {
252
- const resolved = await resolveGrantScopeIds(ctx, value);
253
- return await ctx.db.insert("projectGrants", {
254
- ...value,
255
- ...resolved.topicId ? { topicId: resolved.topicId } : {},
256
- ...resolved.projectId ?? resolved.topicId ? { projectId: resolved.projectId ?? resolved.topicId } : {}
257
- });
258
- }
259
-
260
- // ../access-control/src/resolvers.ts
261
- async function findUserByClerkId(ctx, clerkId) {
262
- const normalizedClerkId = clerkId.trim();
263
- if (!normalizedClerkId) {
264
- return null;
265
- }
266
- if (typeof ctx.runQuery === "function") {
267
- try {
268
- const bridgedUser = await ctx.runQuery(api2.users.getUserByClerkId, {
269
- clerkId: normalizedClerkId
270
- });
271
- if (bridgedUser) {
272
- return bridgedUser;
273
- }
274
- } catch {
275
- }
276
- }
277
- try {
278
- const users = await ctx.db.query("users").collect();
279
- return users.find((user) => String(user.clerkId ?? "") === normalizedClerkId) ?? null;
280
- } catch {
281
- return null;
282
- }
283
- }
284
- async function findUserByPrincipalId(ctx, principalId) {
285
- const normalizedPrincipalId = principalId.trim();
286
- if (!normalizedPrincipalId) {
287
- return null;
288
- }
289
- try {
290
- const users = await ctx.db.query("users").collect();
291
- return users.find(
292
- (user) => String(user.defaultPrincipalId ?? "") === normalizedPrincipalId
293
- ) ?? null;
294
- } catch {
295
- return null;
296
- }
297
- }
298
- async function findAgentByPrincipalId(ctx, principalId) {
299
- const normalizedPrincipalId = principalId.trim();
300
- if (!normalizedPrincipalId) {
301
- return null;
302
- }
303
- if (typeof ctx.runQuery === "function") {
304
- try {
305
- const bridgedAgent = await ctx.runQuery(
306
- api2.agents.getAgentByPrincipalId,
307
- {
308
- principalId: normalizedPrincipalId
309
- }
310
- );
311
- if (bridgedAgent) {
312
- return bridgedAgent;
313
- }
314
- } catch {
315
- }
316
- }
317
- try {
318
- const agents = await ctx.db.query("agents").collect();
319
- return agents.find(
320
- (agent) => String(agent.principalId ?? "") === normalizedPrincipalId
321
- ) ?? null;
322
- } catch {
323
- return null;
324
- }
325
- }
326
- function defaultResolvers() {
327
- return {
328
- async getProject(ctx, topicId) {
329
- return await resolveTopicProjectOverlay(ctx, topicId, {
330
- idMode: "legacy",
331
- projectLikeOnly: false
332
- });
333
- },
334
- async listTopics(ctx) {
335
- return await listTopicProjectOverlays(ctx, { idMode: "legacy" });
336
- },
337
- async listTopicsByOwner(ctx, ownerId) {
338
- const topics = await listTopicProjectOverlays(ctx, { idMode: "legacy" });
339
- return topics.filter((topic) => topic.ownerId === ownerId);
340
- },
341
- async listTopicsByVisibility(ctx, visibility) {
342
- const topics = await listTopicProjectOverlays(ctx, { idMode: "legacy" });
343
- return topics.filter((topic) => topic.visibility === visibility);
344
- },
345
- async listProjectGrantsByProjectAndPrincipal(ctx, topicId, principalId) {
346
- return await bridgeListProjectGrantsByTopicAndPrincipal(
347
- ctx,
348
- topicId,
349
- principalId
350
- );
351
- },
352
- async listProjectGrantsByProjectAndGroup(ctx, topicId, groupId) {
353
- return await bridgeListProjectGrantsByTopicAndGroup(ctx, topicId, groupId);
354
- },
355
- async listProjectGrantsByPrincipalStatus(ctx, principalId, status) {
356
- return await bridgeListProjectGrantsByPrincipalStatus(
357
- ctx,
358
- principalId,
359
- status
360
- );
361
- },
362
- async listProjectGrantsByGroupStatus(ctx, groupId, status) {
363
- return await bridgeListProjectGrantsByGroupStatus(ctx, groupId, status);
364
- },
365
- async insertProjectGrant(ctx, value) {
366
- return await bridgeInsertProjectGrant(ctx, value);
367
- },
368
- async getAgentByPrincipalId(ctx, principalId) {
369
- return await findAgentByPrincipalId(ctx, principalId);
370
- },
371
- async getUserByClerkId(ctx, clerkId) {
372
- return await findUserByClerkId(ctx, clerkId);
373
- },
374
- async getUserByPrincipalId(ctx, principalId) {
375
- return await findUserByPrincipalId(ctx, principalId);
376
- }
377
- };
378
- }
379
- var resolverOverrides = {};
380
- function resolveAccessControlAppResolvers(_ctx) {
381
- return {
382
- ...defaultResolvers(),
383
- ...resolverOverrides
384
- };
385
- }
386
-
387
- // ../access-control/src/principalContext.ts
388
- function requireCanonicalResolvedUser(user, clerkId) {
389
- const resolved = user;
390
- if (!resolved) {
391
- throw new Error(
392
- `[AccessControl] Canonical user identity required for ${clerkId}. Sync users.upsertUser before user-bound access checks.`
393
- );
394
- }
395
- const { mcRole, defaultTenantId, defaultWorkspaceId, defaultPrincipalId } = resolved;
396
- if (mcRole !== "platform_admin" && mcRole !== "tenant_admin" && mcRole !== "workspace_admin" && mcRole !== "editor" && mcRole !== "viewer" && mcRole !== "auditor" && mcRole !== "service_agent") {
397
- throw new Error(
398
- `[AccessControl] Canonical MC role required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
399
- );
400
- }
401
- if (typeof defaultTenantId !== "string" || defaultTenantId.trim().length === 0) {
402
- throw new Error(
403
- `[AccessControl] Canonical home tenant required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
404
- );
405
- }
406
- if (typeof defaultWorkspaceId !== "string" || defaultWorkspaceId.trim().length === 0) {
407
- throw new Error(
408
- `[AccessControl] Canonical home workspace required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
409
- );
410
- }
411
- if (typeof defaultPrincipalId !== "string" || defaultPrincipalId.trim().length === 0) {
412
- throw new Error(
413
- `[AccessControl] Canonical federated principal required for ${clerkId}. Re-sync Master Control identity before user-bound access checks.`
414
- );
415
- }
416
- return {
417
- mcRole,
418
- defaultTenantId: defaultTenantId.trim(),
419
- defaultWorkspaceId: defaultWorkspaceId.trim(),
420
- defaultPrincipalId: defaultPrincipalId.trim()
421
- };
422
- }
423
- function isPrincipalIdInput(value) {
424
- return value.startsWith("user:") || value.startsWith("group:") || value.startsWith("service:") || value.startsWith("agent:") || value.startsWith("external_viewer:");
425
- }
426
- async function resolveCanonicalUserRecord(ctx, actorId) {
427
- const normalizedActorId = actorId.trim();
428
- const clerkId = isPrincipalIdInput(normalizedActorId) && normalizedActorId.startsWith("user:") ? normalizedActorId.slice("user:".length) : normalizedActorId;
429
- const resolvers = resolveAccessControlAppResolvers();
430
- const resolvedByClerkId = await resolvers.getUserByClerkId(ctx, clerkId);
431
- if (resolvedByClerkId) {
432
- return {
433
- resolvedUser: resolvedByClerkId,
434
- clerkId,
435
- contextClerkId: clerkId
436
- };
437
- }
438
- const resolvedByPrincipalId = await resolvers.getUserByPrincipalId(
439
- ctx,
440
- normalizedActorId
441
- );
442
- return {
443
- resolvedUser: resolvedByPrincipalId ?? null,
444
- clerkId,
445
- contextClerkId: normalizedActorId.startsWith("user:") && clerkId.length > 0 ? clerkId : normalizedActorId
446
- };
447
- }
448
- function uniqRoles(roles) {
449
- const roleSet = /* @__PURE__ */ new Set();
450
- for (const role of roles) {
451
- if (role === "platform_admin" || role === "tenant_admin" || role === "workspace_admin" || role === "editor" || role === "viewer" || role === "auditor" || role === "service_agent") {
452
- roleSet.add(role);
453
- }
454
- }
455
- return [...roleSet];
456
- }
457
- function normalizeGroupIds(value) {
458
- if (!Array.isArray(value)) {
459
- return [];
460
- }
461
- return [...new Set(
462
- value.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)
463
- )];
464
- }
465
- function requireServiceAgentUser(user, actorId) {
466
- const canonicalUser = requireCanonicalResolvedUser(user, actorId);
467
- if (canonicalUser.mcRole !== "service_agent") {
468
- throw new Error(
469
- `[AccessControl] Canonical service_agent identity required for ${actorId}. Sync users.upsertUser before agent-bound access checks.`
470
- );
471
- }
472
- return canonicalUser;
473
- }
474
- function requireCanonicalResolvedAgent(agent, actorId) {
475
- const resolved = agent;
476
- if (!resolved) {
477
- throw new Error(
478
- `[AccessControl] Agent "${actorId}" not found in agents or users table.`
479
- );
480
- }
481
- if (typeof resolved.principalId !== "string" || resolved.principalId.trim().length === 0) {
482
- throw new Error(
483
- `[AccessControl] Canonical agent principalId required for ${actorId}.`
484
- );
485
- }
486
- if (typeof resolved.tenantId !== "string" || resolved.tenantId.trim().length === 0) {
487
- throw new Error(
488
- `[AccessControl] Canonical home tenant required for ${actorId}.`
489
- );
490
- }
491
- if (typeof resolved.workspaceId !== "string" || resolved.workspaceId.trim().length === 0) {
492
- throw new Error(
493
- `[AccessControl] Canonical home workspace required for ${actorId}.`
494
- );
495
- }
496
- return {
497
- principalId: resolved.principalId.trim(),
498
- tenantId: resolved.tenantId.trim(),
499
- workspaceId: resolved.workspaceId.trim(),
500
- roles: uniqRoles(Array.isArray(resolved.roles) ? resolved.roles : []) ?? ["service_agent"],
501
- groupIds: normalizeGroupIds(resolved.groupIds)
502
- };
503
- }
504
- async function resolvePrincipalContext(ctx, actorId) {
505
- if (actorId.startsWith("agent:")) {
506
- const resolvers = resolveAccessControlAppResolvers();
507
- const resolvedAgent = await resolvers.getAgentByPrincipalId(ctx, actorId);
508
- if (resolvedAgent) {
509
- const agent = requireCanonicalResolvedAgent(
510
- resolvedAgent,
511
- actorId
512
- );
513
- return {
514
- principalId: agent.principalId,
515
- principalType: "service",
516
- clerkId: actorId,
517
- tenantId: agent.tenantId,
518
- workspaceId: agent.workspaceId,
519
- roles: agent.roles.length > 0 ? agent.roles : ["service_agent"],
520
- groupIds: agent.groupIds,
521
- isPlatformAdmin: false,
522
- isTenantAdmin: false,
523
- isWorkspaceAdmin: false,
524
- isSystemFallback: false
525
- };
526
- }
527
- const resolvedUser2 = await resolvers.getUserByClerkId(
528
- ctx,
529
- actorId
530
- );
531
- if (!resolvedUser2) {
532
- throw new Error(
533
- `[AccessControl] Agent "${actorId}" not found in agents or users table.`
534
- );
535
- }
536
- const user2 = requireServiceAgentUser(
537
- resolvedUser2,
538
- actorId
539
- );
540
- console.warn(
541
- `[AccessControl] Deprecated legacy service-agent fallback for ${actorId}; migrate this principal into identity.agents.`
542
- );
543
- return {
544
- principalId: user2.defaultPrincipalId,
545
- principalType: "service",
546
- clerkId: actorId,
547
- tenantId: user2.defaultTenantId,
548
- workspaceId: user2.defaultWorkspaceId,
549
- roles: ["service_agent"],
550
- groupIds: normalizeGroupIds(resolvedUser2?.principalGroupIds),
551
- isPlatformAdmin: false,
552
- isTenantAdmin: false,
553
- isWorkspaceAdmin: false,
554
- isSystemFallback: false
555
- };
556
- }
557
- const {
558
- resolvedUser,
559
- contextClerkId
560
- } = await resolveCanonicalUserRecord(ctx, actorId);
561
- const user = requireCanonicalResolvedUser(
562
- resolvedUser,
563
- contextClerkId
564
- );
565
- if (!user.defaultPrincipalId) {
566
- throw new Error(
567
- `[AccessControl] Canonical federated principal required for ${contextClerkId}. Re-sync Master Control identity before user-bound access checks.`
568
- );
569
- }
570
- if (user.mcRole === "service_agent") {
571
- return {
572
- principalId: user.defaultPrincipalId,
573
- principalType: "service",
574
- clerkId: contextClerkId,
575
- tenantId: user.defaultTenantId,
576
- workspaceId: user.defaultWorkspaceId,
577
- roles: ["service_agent"],
578
- groupIds: normalizeGroupIds(resolvedUser?.principalGroupIds),
579
- isPlatformAdmin: false,
580
- isTenantAdmin: false,
581
- isWorkspaceAdmin: false,
582
- isSystemFallback: false
583
- };
584
- }
585
- const principalId = user.defaultPrincipalId;
586
- const effectiveRole = user.mcRole;
587
- const roles = effectiveRole === "platform_admin" ? ["platform_admin", "tenant_admin"] : effectiveRole === "tenant_admin" ? ["tenant_admin"] : [effectiveRole];
588
- const tenantId = user.defaultTenantId;
589
- const workspaceId = user.defaultWorkspaceId;
590
- const isPlatformAdmin = effectiveRole === "platform_admin";
591
- return {
592
- principalId,
593
- principalType: "user",
594
- clerkId: contextClerkId,
595
- tenantId,
596
- workspaceId,
597
- roles: uniqRoles(roles),
598
- groupIds: normalizeGroupIds(resolvedUser?.principalGroupIds),
599
- isPlatformAdmin,
600
- isTenantAdmin: isPlatformAdmin || effectiveRole === "tenant_admin",
601
- isWorkspaceAdmin: isPlatformAdmin || effectiveRole === "tenant_admin" || effectiveRole === "workspace_admin",
602
- isSystemFallback: false
603
- };
604
- }
605
-
606
- // ../access-control/src/access.ts
607
- function isTopicInPrincipalTenant(topic, principalTenantId) {
608
- if (!topic.tenantId) {
609
- return false;
610
- }
611
- if (!principalTenantId) {
612
- return false;
613
- }
614
- return String(topic.tenantId) === String(principalTenantId);
615
- }
616
- function isTopicInPrincipalWorkspace(topic, principalWorkspaceId) {
617
- if (!topic.workspaceId) {
618
- return false;
619
- }
620
- if (!principalWorkspaceId) {
621
- return false;
622
- }
623
- return String(topic.workspaceId) === String(principalWorkspaceId);
624
- }
625
- function isLegacyUnscopedTopic(topic) {
626
- return !topic.tenantId || !topic.workspaceId;
627
- }
628
- function isGrantScopeAlignedToTopic(topic, grant) {
629
- if (topic.tenantId && grant.tenantId && String(topic.tenantId) !== String(grant.tenantId)) {
630
- return false;
631
- }
632
- if (topic.workspaceId && grant.workspaceId && String(topic.workspaceId) !== String(grant.workspaceId)) {
633
- return false;
634
- }
635
- return true;
636
- }
637
- function isGrantSourceAllowedForVisibility(visibility, source) {
638
- if (source !== "external_share") {
639
- return true;
640
- }
641
- return visibility === "external" || visibility === "public";
642
- }
643
- function isGrantActive(grant) {
644
- if (grant.status !== "active") {
645
- return false;
646
- }
647
- if (grant.expiresAt !== void 0 && grant.expiresAt <= Date.now()) {
648
- return false;
649
- }
650
- return true;
651
- }
652
- async function hasPrincipalGrant(ctx, args) {
653
- const grants = await resolveAccessControlAppResolvers().listProjectGrantsByProjectAndPrincipal(
654
- ctx,
655
- args.topic._id,
656
- args.principalId
657
- );
658
- if (grants.some(
659
- (grant) => isGrantActive(grant) && isGrantScopeAlignedToTopic(args.topic, grant) && isGrantSourceAllowedForVisibility(
660
- args.topic.visibility,
661
- grant.source
662
- ) && (!args.principalIsExternal || args.topic.visibility === "public" || grant.source === "external_share")
663
- )) {
664
- return true;
665
- }
666
- return false;
667
- }
668
- async function hasGroupGrant(ctx, args) {
669
- if (args.groupIds.length === 0) {
670
- return false;
671
- }
672
- for (const groupId of args.groupIds) {
673
- const grants = await resolveAccessControlAppResolvers().listProjectGrantsByProjectAndGroup(ctx, args.topic._id, groupId);
674
- if (grants.some(
675
- (grant) => isGrantActive(grant) && isGrantScopeAlignedToTopic(args.topic, grant) && isGrantSourceAllowedForVisibility(
676
- args.topic.visibility,
677
- grant.source
678
- )
679
- )) {
680
- return true;
681
- }
682
- }
683
- return false;
684
- }
685
- function isExternalPrincipal(_ctx, _args) {
686
- return false;
687
- }
688
- async function evaluateTopicAccessDetailed(ctx, args) {
689
- if (args.legacyUserId) {
690
- return {
691
- hasAccess: true,
692
- isAdmin: false,
693
- isOwner: false,
694
- isShared: false,
695
- hasGrant: true,
696
- isFirmVisible: true,
697
- isExternalVisible: false,
698
- isPublicVisible: false,
699
- isTenantScopeMatch: true,
700
- isWorkspaceScopeMatch: true,
701
- isPrincipalExternal: false
702
- };
703
- }
704
- const topic = await resolveAccessControlAppResolvers().getProject(
705
- ctx,
706
- args.topicId
707
- );
708
- if (!topic) {
709
- return {
710
- hasAccess: false,
711
- isAdmin: false,
712
- isOwner: false,
713
- isShared: false,
714
- hasGrant: false,
715
- isFirmVisible: false,
716
- isExternalVisible: false,
717
- isPublicVisible: false,
718
- isTenantScopeMatch: false,
719
- isWorkspaceScopeMatch: false,
720
- isPrincipalExternal: false
721
- };
722
- }
723
- const { principalContext, legacyUserId } = args;
724
- const userIsAdmin = principalContext.isPlatformAdmin;
725
- const isOwner = topic.ownerId === legacyUserId;
726
- const isShared = (topic.sharedWith ?? []).includes(legacyUserId);
727
- const principalIsExternal = await isExternalPrincipal(ctx, {
728
- groupIds: principalContext.groupIds,
729
- topicTenantId: topic.tenantId,
730
- topicWorkspaceId: topic.workspaceId
731
- });
732
- const hasPrincipalGrantResult = await hasPrincipalGrant(ctx, {
733
- topic,
734
- principalId: principalContext.principalId,
735
- principalIsExternal
736
- });
737
- const hasGroupGrantResult = await hasGroupGrant(ctx, {
738
- topic,
739
- groupIds: principalContext.groupIds
740
- });
741
- const hasGrant = isShared || hasPrincipalGrantResult || hasGroupGrantResult;
742
- const legacyUnscoped = isLegacyUnscopedTopic(topic);
743
- const tenantScopeMatch = isTopicInPrincipalTenant(
744
- topic,
745
- principalContext.tenantId
746
- );
747
- const workspaceScopeMatch = isTopicInPrincipalWorkspace(
748
- topic,
749
- principalContext.workspaceId
750
- );
751
- const isPublicVisible = topic.visibility === "public";
752
- const isFirmVisible = topic.visibility === "firm" && !legacyUnscoped && tenantScopeMatch && workspaceScopeMatch && !principalIsExternal;
753
- const hasScopedGrant = hasGrant && (legacyUnscoped || tenantScopeMatch && workspaceScopeMatch);
754
- const isExternalVisible = topic.visibility === "external" && hasScopedGrant;
755
- const hasAccess = userIsAdmin || isOwner || hasScopedGrant || isPublicVisible || isFirmVisible;
756
- return {
757
- hasAccess,
758
- isAdmin: userIsAdmin,
759
- isOwner,
760
- isShared,
761
- hasGrant,
762
- isFirmVisible,
763
- isExternalVisible,
764
- isPublicVisible,
765
- isTenantScopeMatch: tenantScopeMatch,
766
- isWorkspaceScopeMatch: workspaceScopeMatch,
767
- isPrincipalExternal: principalIsExternal
768
- };
769
- }
770
- async function checkTopicAccessDetailed(ctx, topicId, userId) {
771
- const principalContext = await resolvePrincipalContext(ctx, userId);
772
- return evaluateTopicAccessDetailed(ctx, {
773
- topicId,
774
- legacyUserId: userId,
775
- principalContext
776
- });
777
- }
778
- async function checkTopicAccess(ctx, topicId, userId) {
779
- const result = await checkTopicAccessDetailed(ctx, topicId, userId);
780
- return result.hasAccess;
781
- }
782
- async function checkScopeAccess(ctx, scopeId, userId) {
783
- try {
784
- const topic = await ctx.db.get(scopeId);
785
- if (topic && topic.name !== void 0 && topic.type !== void 0) {
786
- return true;
787
- }
788
- } catch {
789
- }
790
- try {
791
- return await checkTopicAccess(ctx, scopeId, userId);
792
- } catch {
793
- return false;
794
- }
795
- }
796
13
 
797
14
  // src/globalId.ts
798
15
  function generateGlobalId() {
@@ -805,17 +22,17 @@ function generateGlobalId() {
805
22
  );
806
23
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
807
24
  }
808
- var LEGACY_SCOPE_FIELD2 = "graphScopeProjectId";
25
+ var LEGACY_SCOPE_FIELD = "graphScopeProjectId";
809
26
  function asMappedProjectId(topic) {
810
27
  if (!topic) {
811
28
  return;
812
29
  }
813
- const directLegacyProjectId = normalizeScopeValue(topic[LEGACY_SCOPE_FIELD2]);
30
+ const directLegacyProjectId = normalizeScopeValue(topic[LEGACY_SCOPE_FIELD]);
814
31
  if (directLegacyProjectId) {
815
32
  return directLegacyProjectId;
816
33
  }
817
34
  const metadata = topic.metadata || {};
818
- const candidate = metadata[LEGACY_SCOPE_FIELD2] || metadata.legacyProjectId || metadata.projectId || metadata.scopeProjectId;
35
+ const candidate = metadata[LEGACY_SCOPE_FIELD] || metadata.legacyProjectId || metadata.projectId || metadata.scopeProjectId;
819
36
  return candidate ? candidate : void 0;
820
37
  }
821
38
  function normalizeScopeValue(value) {
@@ -844,7 +61,7 @@ async function findTopicsByScopeAlias(ctx, scopeId) {
844
61
  try {
845
62
  return await ctx.db.query("topics").withIndex(
846
63
  "by_graph_scope_project",
847
- (q) => q.eq(LEGACY_SCOPE_FIELD2, scopeId)
64
+ (q) => q.eq(LEGACY_SCOPE_FIELD, scopeId)
848
65
  ).collect();
849
66
  } catch {
850
67
  const topics = await ctx.db.query("topics").collect();
@@ -1016,19 +233,6 @@ async function resolveScope(ctx, args) {
1016
233
  return null;
1017
234
  }
1018
235
  }
1019
- var permissiveReturn = v.optional(v.any());
1020
- var looseJsonObject = v.record(v.string(), v.any());
1021
- var looseJsonArray = v.array(v.any());
1022
- v.union(
1023
- v.string(),
1024
- v.number(),
1025
- v.boolean(),
1026
- v.null(),
1027
- looseJsonObject,
1028
- looseJsonArray
1029
- );
1030
-
1031
- // src/epistemicAnswers.ts
1032
236
  function generateContentHash(text) {
1033
237
  const content = `answer:${text.trim().toLowerCase().replace(/\s+/g, " ").slice(0, 500)}`;
1034
238
  let hash = 5381;
@@ -1461,12 +665,12 @@ var getByQuestion = query({
1461
665
  return [];
1462
666
  }
1463
667
  const topicId = questionNode.topicId;
1464
- const answers = topicId ? await ctx.db.query("epistemicNodes").withIndex(
668
+ if (!topicId) {
669
+ return [];
670
+ }
671
+ const answers = await ctx.db.query("epistemicNodes").withIndex(
1465
672
  "by_topic_type",
1466
673
  (q) => q.eq("topicId", topicId).eq("nodeType", "answer")
1467
- ).collect() : await ctx.db.query("epistemicNodes").withIndex(
1468
- "by_project_type",
1469
- (q) => q.eq("projectId", questionNode.projectId).eq("nodeType", "answer")
1470
674
  ).collect();
1471
675
  const questionIdStr = String(args.questionNodeId);
1472
676
  const filtered = answers.filter((a) => {
@@ -1494,18 +698,13 @@ var getLatestForQuestion = query({
1494
698
  if (!questionNode || questionNode.nodeType !== "question") {
1495
699
  return null;
1496
700
  }
1497
- let answers;
1498
- if (questionNode.topicId) {
1499
- answers = await ctx.db.query("epistemicNodes").withIndex(
1500
- "by_topic_type",
1501
- (q) => q.eq("topicId", questionNode.topicId).eq("nodeType", "answer")
1502
- ).filter((q) => q.eq(q.field("status"), "active")).collect();
1503
- } else {
1504
- answers = await ctx.db.query("epistemicNodes").withIndex(
1505
- "by_project_type",
1506
- (q) => q.eq("projectId", questionNode.projectId).eq("nodeType", "answer")
1507
- ).filter((q) => q.eq(q.field("status"), "active")).collect();
701
+ if (!questionNode.topicId) {
702
+ return null;
1508
703
  }
704
+ const answers = await ctx.db.query("epistemicNodes").withIndex(
705
+ "by_topic_type",
706
+ (q) => q.eq("topicId", questionNode.topicId).eq("nodeType", "answer")
707
+ ).filter((q) => q.eq(q.field("status"), "active")).collect();
1509
708
  const questionIdStr = String(args.questionNodeId);
1510
709
  const latest = answers.find((a) => {
1511
710
  const meta = a.metadata || {};
@@ -1524,28 +723,18 @@ var getVersionHistory = query({
1524
723
  if (!questionNode || questionNode.nodeType !== "question") {
1525
724
  return [];
1526
725
  }
1527
- let answers;
1528
- if (questionNode.topicId) {
1529
- answers = await ctx.db.query("epistemicNodes").withIndex(
1530
- "by_topic_type",
1531
- (q) => q.eq("topicId", questionNode.topicId).eq("nodeType", "answer")
1532
- ).filter(
1533
- (q) => q.or(
1534
- q.eq(q.field("status"), "active"),
1535
- q.eq(q.field("status"), "superseded")
1536
- )
1537
- ).collect();
1538
- } else {
1539
- answers = await ctx.db.query("epistemicNodes").withIndex(
1540
- "by_project_type",
1541
- (q) => q.eq("projectId", questionNode.projectId).eq("nodeType", "answer")
1542
- ).filter(
1543
- (q) => q.or(
1544
- q.eq(q.field("status"), "active"),
1545
- q.eq(q.field("status"), "superseded")
1546
- )
1547
- ).collect();
726
+ if (!questionNode.topicId) {
727
+ return [];
1548
728
  }
729
+ const answers = await ctx.db.query("epistemicNodes").withIndex(
730
+ "by_topic_type",
731
+ (q) => q.eq("topicId", questionNode.topicId).eq("nodeType", "answer")
732
+ ).filter(
733
+ (q) => q.or(
734
+ q.eq(q.field("status"), "active"),
735
+ q.eq(q.field("status"), "superseded")
736
+ )
737
+ ).collect();
1549
738
  const questionIdStr = String(args.questionNodeId);
1550
739
  const history = answers.filter((a) => {
1551
740
  const meta = a.metadata || {};