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