@lucern/graph-primitives 1.0.0 → 1.0.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.
- package/README.md +13 -12
- package/dist/beliefDecay.js +24 -17
- package/dist/beliefDecay.js.map +1 -1
- package/dist/beliefEvidenceLinks.js +32 -8
- package/dist/beliefEvidenceLinks.js.map +1 -1
- package/dist/confidencePropagationDispatch.js.map +1 -1
- package/dist/contradictions.js +32 -9
- package/dist/contradictions.js.map +1 -1
- package/dist/convex.d.ts +55 -12
- package/dist/convex.js.map +1 -1
- package/dist/edgeValidation.d.ts +25 -2
- package/dist/edges/index.d.ts +9 -2
- package/dist/edges/index.js.map +1 -1
- package/dist/edges/propagationTypes.d.ts +2 -3
- package/dist/edges/propagationTypes.js.map +1 -1
- package/dist/entityBridge.js +10 -3
- package/dist/entityBridge.js.map +1 -1
- package/dist/entityLifecycle.js +15 -3
- package/dist/entityLifecycle.js.map +1 -1
- package/dist/epistemicAnswers.js.map +1 -1
- package/dist/epistemicBeliefs.admin.d.ts +36 -0
- package/dist/epistemicBeliefs.admin.js +745 -0
- package/dist/epistemicBeliefs.admin.js.map +1 -0
- package/dist/epistemicBeliefs.backfills.d.ts +62 -0
- package/dist/epistemicBeliefs.backfills.js +1004 -0
- package/dist/epistemicBeliefs.backfills.js.map +1 -0
- package/dist/epistemicBeliefs.confidence.d.ts +45 -0
- package/dist/epistemicBeliefs.confidence.js +1285 -0
- package/dist/epistemicBeliefs.confidence.js.map +1 -0
- package/dist/epistemicBeliefs.core.d.ts +35 -0
- package/dist/epistemicBeliefs.core.js +1508 -0
- package/dist/epistemicBeliefs.core.js.map +1 -0
- package/dist/epistemicBeliefs.d.ts +12 -3
- package/dist/epistemicBeliefs.helpers.d.ts +168 -0
- package/dist/epistemicBeliefs.helpers.js +1060 -0
- package/dist/epistemicBeliefs.helpers.js.map +1 -0
- package/dist/epistemicBeliefs.internal.d.ts +30 -0
- package/dist/epistemicBeliefs.internal.js +1329 -0
- package/dist/epistemicBeliefs.internal.js.map +1 -0
- package/dist/epistemicBeliefs.js +1196 -1184
- package/dist/epistemicBeliefs.js.map +1 -1
- package/dist/epistemicBeliefs.lifecycle.d.ts +19 -0
- package/dist/epistemicBeliefs.lifecycle.js +1608 -0
- package/dist/epistemicBeliefs.lifecycle.js.map +1 -0
- package/dist/epistemicBeliefs.links.d.ts +30 -0
- package/dist/epistemicBeliefs.links.js +761 -0
- package/dist/epistemicBeliefs.links.js.map +1 -0
- package/dist/epistemicBeliefs.queries.d.ts +16 -0
- package/dist/epistemicBeliefs.queries.js +90 -0
- package/dist/epistemicBeliefs.queries.js.map +1 -0
- package/dist/epistemicContractHelpers.d.ts +1 -1
- package/dist/epistemicContractHelpers.js +1 -1
- package/dist/epistemicContracts.d.ts +5 -76
- package/dist/epistemicContracts.evaluators.d.ts +36 -0
- package/dist/epistemicContracts.evaluators.js +2506 -0
- package/dist/epistemicContracts.evaluators.js.map +1 -0
- package/dist/epistemicContracts.handlers.d.ts +40 -0
- package/dist/epistemicContracts.handlers.js +3029 -0
- package/dist/epistemicContracts.handlers.js.map +1 -0
- package/dist/epistemicContracts.js +2006 -5281
- package/dist/epistemicContracts.js.map +1 -1
- package/dist/epistemicContracts.metrics.d.ts +26 -0
- package/dist/epistemicContracts.metrics.js +427 -0
- package/dist/epistemicContracts.metrics.js.map +1 -0
- package/dist/epistemicContracts.types.d.ts +159 -0
- package/dist/epistemicContracts.types.js +3 -0
- package/dist/epistemicContracts.types.js.map +1 -0
- package/dist/epistemicEdgeCreation.d.ts +73 -0
- package/dist/epistemicEdgeCreation.js +450 -0
- package/dist/epistemicEdgeCreation.js.map +1 -0
- package/dist/epistemicEdges-BF-cn4i3.d.ts +43 -0
- package/dist/epistemicEdges.d.ts +8 -1
- package/dist/epistemicEdges.handlers.d.ts +20 -0
- package/dist/epistemicEdges.handlers.js +289 -0
- package/dist/epistemicEdges.handlers.js.map +1 -0
- package/dist/epistemicEdges.helpers.d.ts +27 -0
- package/dist/epistemicEdges.helpers.js +162 -0
- package/dist/epistemicEdges.helpers.js.map +1 -0
- package/dist/epistemicEdges.js +797 -875
- package/dist/epistemicEdges.js.map +1 -1
- package/dist/epistemicEdges.mutations.d.ts +39 -0
- package/dist/epistemicEdges.mutations.js +1365 -0
- package/dist/epistemicEdges.mutations.js.map +1 -0
- package/dist/epistemicEdges.queries.d.ts +95 -0
- package/dist/epistemicEdges.queries.js +851 -0
- package/dist/epistemicEdges.queries.js.map +1 -0
- package/dist/epistemicEdges.types.d.ts +32 -0
- package/dist/epistemicEdges.types.js +3 -0
- package/dist/epistemicEdges.types.js.map +1 -0
- package/dist/epistemicEvidence-DvfchNt7.d.ts +46 -0
- package/dist/epistemicEvidence.d.ts +5 -2
- package/dist/epistemicEvidence.js +801 -807
- package/dist/epistemicEvidence.js.map +1 -1
- package/dist/epistemicEvidenceHelpers.d.ts +71 -0
- package/dist/epistemicEvidenceHelpers.js +769 -0
- package/dist/epistemicEvidenceHelpers.js.map +1 -0
- package/dist/epistemicEvidenceMutations.d.ts +10 -0
- package/dist/epistemicEvidenceMutations.js +1421 -0
- package/dist/epistemicEvidenceMutations.js.map +1 -0
- package/dist/epistemicEvidenceQueries.d.ts +10 -0
- package/dist/epistemicEvidenceQueries.js +1049 -0
- package/dist/epistemicEvidenceQueries.js.map +1 -0
- package/dist/epistemicHelpers.d.ts +4 -2
- package/dist/epistemicHelpers.js +132 -127
- package/dist/epistemicHelpers.js.map +1 -1
- package/dist/epistemicLayerRules.d.ts +138 -0
- package/dist/epistemicLayerRules.js +481 -0
- package/dist/epistemicLayerRules.js.map +1 -0
- package/dist/epistemicLinking.js +1 -1
- package/dist/epistemicLinking.js.map +1 -1
- package/dist/epistemicNodeCreation.d.ts +101 -0
- package/dist/epistemicNodeCreation.js +709 -0
- package/dist/epistemicNodeCreation.js.map +1 -0
- package/dist/epistemicNodes-BCQxpYx_.d.ts +54 -0
- package/dist/epistemicNodes.d.ts +5 -1
- package/dist/epistemicNodes.helpers.d.ts +51 -0
- package/dist/epistemicNodes.helpers.js +73 -0
- package/dist/epistemicNodes.helpers.js.map +1 -0
- package/dist/epistemicNodes.internal.d.ts +34 -0
- package/dist/epistemicNodes.internal.js +658 -0
- package/dist/epistemicNodes.internal.js.map +1 -0
- package/dist/epistemicNodes.js +698 -693
- package/dist/epistemicNodes.js.map +1 -1
- package/dist/epistemicNodes.mutations.d.ts +34 -0
- package/dist/epistemicNodes.mutations.js +1153 -0
- package/dist/epistemicNodes.mutations.js.map +1 -0
- package/dist/epistemicNodes.queries.d.ts +36 -0
- package/dist/epistemicNodes.queries.js +619 -0
- package/dist/epistemicNodes.queries.js.map +1 -0
- package/dist/epistemicNodes.validators.d.ts +23 -0
- package/dist/epistemicNodes.validators.js +105 -0
- package/dist/epistemicNodes.validators.js.map +1 -0
- package/dist/epistemicQuestions-bwHd2FWE.d.ts +68 -0
- package/dist/epistemicQuestions.conviction.d.ts +52 -0
- package/dist/epistemicQuestions.conviction.js +1389 -0
- package/dist/epistemicQuestions.conviction.js.map +1 -0
- package/dist/epistemicQuestions.create.d.ts +29 -0
- package/dist/epistemicQuestions.create.js +1300 -0
- package/dist/epistemicQuestions.create.js.map +1 -0
- package/dist/epistemicQuestions.d.ts +10 -2
- package/dist/epistemicQuestions.evidence.d.ts +22 -0
- package/dist/epistemicQuestions.evidence.js +929 -0
- package/dist/epistemicQuestions.evidence.js.map +1 -0
- package/dist/epistemicQuestions.helpers.d.ts +69 -0
- package/dist/epistemicQuestions.helpers.js +824 -0
- package/dist/epistemicQuestions.helpers.js.map +1 -0
- package/dist/epistemicQuestions.js +2435 -2430
- package/dist/epistemicQuestions.js.map +1 -1
- package/dist/epistemicQuestions.lifecycle.d.ts +24 -0
- package/dist/epistemicQuestions.lifecycle.js +838 -0
- package/dist/epistemicQuestions.lifecycle.js.map +1 -0
- package/dist/epistemicQuestions.queries.d.ts +41 -0
- package/dist/epistemicQuestions.queries.js +1013 -0
- package/dist/epistemicQuestions.queries.js.map +1 -0
- package/dist/epistemicQuestions.sprint.d.ts +22 -0
- package/dist/epistemicQuestions.sprint.js +757 -0
- package/dist/epistemicQuestions.sprint.js.map +1 -0
- package/dist/epistemicQuestions.tail.d.ts +42 -0
- package/dist/epistemicQuestions.tail.js +1345 -0
- package/dist/epistemicQuestions.tail.js.map +1 -0
- package/dist/epistemicSources.js +6 -2
- package/dist/epistemicSources.js.map +1 -1
- package/dist/evaluators/index.d.ts +2 -2
- package/dist/evaluators/index.js +45 -5320
- package/dist/evaluators/index.js.map +1 -1
- package/dist/evaluators/lintCheckerEvaluator.d.ts +1 -1
- package/dist/evaluators/sentryCheckerEvaluator.d.ts +1 -1
- package/dist/evaluators/testRunnerEvaluator.d.ts +1 -1
- package/dist/evaluators/tscCheckerEvaluator.d.ts +1 -1
- package/dist/{graphTypes-CpgIuCdo.d.ts → graphTypes-B8VaIjnl.d.ts} +1 -1
- package/dist/graphTypes.d.ts +1 -1
- package/dist/{helpers-BYHIk5vU.d.ts → helpers-DNYfg6mo.d.ts} +2 -3
- package/dist/helpers.d.ts +2 -2
- package/dist/helpers.js.map +1 -1
- package/dist/{index-Dq-7R-gi.d.ts → index-C-Kyd7hD.d.ts} +1 -1
- package/dist/index.d.ts +160 -14
- package/dist/index.js +12291 -13001
- package/dist/index.js.map +1 -1
- package/dist/logicalRoleInference.js.map +1 -1
- package/dist/ontologyApproval.js +1 -1
- package/dist/ontologyApproval.js.map +1 -1
- package/dist/ontologyDefinitions.js +25 -7
- package/dist/ontologyDefinitions.js.map +1 -1
- package/dist/ontologyRegistry.js.map +1 -1
- package/dist/projectionReconciliation.js.map +1 -1
- package/dist/questionEvidenceLinks.js +28 -7
- package/dist/questionEvidenceLinks.js.map +1 -1
- package/dist/resolvers.js.map +1 -1
- package/dist/scopeResolverCompat.js.map +1 -1
- package/dist/topicProjectOverlay.js.map +1 -1
- package/dist/topicScope.js.map +1 -1
- package/dist/workflowBridge.js.map +1 -1
- package/dist/workspaceIsolation.js.map +1 -1
- package/package.json +4 -5
- package/dist/edgeValidation-CeI0wc0r.d.ts +0 -35
- package/dist/epistemicBeliefs-DzKjZAeC.d.ts +0 -377
- package/dist/epistemicEdges-CvlKnEyy.d.ts +0 -191
- package/dist/epistemicEvidence-xw6UUrwh.d.ts +0 -128
- package/dist/epistemicHelpers-DevrYgPN.d.ts +0 -329
- package/dist/epistemicNodes-DjSUfvyD.d.ts +0 -167
- package/dist/epistemicQuestions-B_nUclrH.d.ts +0 -214
- package/dist/index-Dct1T70K.d.ts +0 -25
|
@@ -0,0 +1,1060 @@
|
|
|
1
|
+
import { v } from 'convex/values';
|
|
2
|
+
import { normalizeTupleContradictionPolicy, confidenceFromSL, readOpinionFromRecord, mkOpinion } from '@lucern/confidence';
|
|
3
|
+
import { checkProjectAccess } from '@lucern/access-control/access';
|
|
4
|
+
import { normalizeAudienceKey, classFromAudienceKey } from '@lucern/access-control/audience';
|
|
5
|
+
import { getCurrentUserId } from '@lucern/access-control/auth';
|
|
6
|
+
import { componentsGeneric, anyApi } from 'convex/server';
|
|
7
|
+
import '@lucern/contracts/schema-helpers/spine/tables/epistemicNodes';
|
|
8
|
+
|
|
9
|
+
// src/epistemicBeliefs.helpers.ts
|
|
10
|
+
|
|
11
|
+
// src/beliefLifecycle.ts
|
|
12
|
+
var BELIEF_STATUS_VALUES = [
|
|
13
|
+
"assumption",
|
|
14
|
+
"hypothesis",
|
|
15
|
+
"belief",
|
|
16
|
+
"fact"
|
|
17
|
+
];
|
|
18
|
+
var RESOLVED_PREDICTION_OUTCOMES = [
|
|
19
|
+
"confirmed",
|
|
20
|
+
"disconfirmed",
|
|
21
|
+
"partial",
|
|
22
|
+
"expired"
|
|
23
|
+
];
|
|
24
|
+
function isBeliefLifecycleStatus(value) {
|
|
25
|
+
return typeof value === "string" && BELIEF_STATUS_VALUES.includes(value);
|
|
26
|
+
}
|
|
27
|
+
function normalizeBeliefConfidence(confidence) {
|
|
28
|
+
if (typeof confidence !== "number" || !Number.isFinite(confidence)) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (confidence >= 0 && confidence <= 1) {
|
|
32
|
+
return confidence;
|
|
33
|
+
}
|
|
34
|
+
if (confidence > 1 && confidence <= 100) {
|
|
35
|
+
return confidence / 100;
|
|
36
|
+
}
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
function isResolvedByConfidence(confidence) {
|
|
40
|
+
const normalized = normalizeBeliefConfidence(confidence);
|
|
41
|
+
if (normalized === null) {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
return normalized <= 0 || normalized >= 1;
|
|
45
|
+
}
|
|
46
|
+
function hasResolvedPredictionOutcome(predictionMeta) {
|
|
47
|
+
if (!predictionMeta || typeof predictionMeta !== "object") {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
const outcome = predictionMeta.outcome;
|
|
51
|
+
return typeof outcome === "string" && RESOLVED_PREDICTION_OUTCOMES.includes(outcome);
|
|
52
|
+
}
|
|
53
|
+
function getPredictionMetaFromMetadata(metadata) {
|
|
54
|
+
return metadata?.predictionMeta;
|
|
55
|
+
}
|
|
56
|
+
function shouldTreatBeliefAsFact(opts) {
|
|
57
|
+
if (isResolvedByConfidence(opts.confidence)) {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
if (hasResolvedPredictionOutcome(opts.predictionMeta)) {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
if (hasResolvedPredictionOutcome(getPredictionMetaFromMetadata(opts.metadata))) {
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
function resolveBeliefLifecycleStatus(opts) {
|
|
69
|
+
if (shouldTreatBeliefAsFact(opts)) {
|
|
70
|
+
return "fact";
|
|
71
|
+
}
|
|
72
|
+
const direct = opts.beliefStatus;
|
|
73
|
+
if (isBeliefLifecycleStatus(direct)) {
|
|
74
|
+
const normalized = normalizeBeliefConfidence(opts.confidence);
|
|
75
|
+
if (normalized !== null && isPreValidationBeliefStatus(direct)) {
|
|
76
|
+
return "belief";
|
|
77
|
+
}
|
|
78
|
+
return direct;
|
|
79
|
+
}
|
|
80
|
+
const metaStatus = opts.metadata?.beliefStatus;
|
|
81
|
+
if (isBeliefLifecycleStatus(metaStatus)) {
|
|
82
|
+
const normalized = normalizeBeliefConfidence(opts.confidence);
|
|
83
|
+
if (normalized !== null && isPreValidationBeliefStatus(metaStatus)) {
|
|
84
|
+
return "belief";
|
|
85
|
+
}
|
|
86
|
+
return metaStatus;
|
|
87
|
+
}
|
|
88
|
+
return "assumption";
|
|
89
|
+
}
|
|
90
|
+
function isPreValidationBeliefStatus(status) {
|
|
91
|
+
return status === "assumption" || status === "hypothesis";
|
|
92
|
+
}
|
|
93
|
+
var api = anyApi;
|
|
94
|
+
componentsGeneric();
|
|
95
|
+
var internal = anyApi;
|
|
96
|
+
|
|
97
|
+
// src/debug.ts
|
|
98
|
+
function isGraphPrimitiveDebugEnabled() {
|
|
99
|
+
const env = globalThis.process?.env;
|
|
100
|
+
return env?.LUCERN_COMPAT_FALLBACK_DEBUG === "1" || env?.LUCERN_GRAPH_DEBUG === "1";
|
|
101
|
+
}
|
|
102
|
+
function debugGraphPrimitiveFallback(message, context) {
|
|
103
|
+
if (!isGraphPrimitiveDebugEnabled()) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
console.debug(message, context ?? {});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// src/topicProjectOverlay.ts
|
|
110
|
+
var LEGACY_SCOPE_FIELD = "graphScopeProjectId";
|
|
111
|
+
function readNonEmptyString(value) {
|
|
112
|
+
if (typeof value !== "string") {
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const normalized = value.trim();
|
|
116
|
+
return normalized.length > 0 ? normalized : void 0;
|
|
117
|
+
}
|
|
118
|
+
function readStringArray(value) {
|
|
119
|
+
if (!Array.isArray(value)) {
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
return value.map((entry) => readNonEmptyString(entry)).filter((entry) => Boolean(entry));
|
|
123
|
+
}
|
|
124
|
+
function readMetadata(topic) {
|
|
125
|
+
return topic.metadata && typeof topic.metadata === "object" ? topic.metadata : {};
|
|
126
|
+
}
|
|
127
|
+
function readLegacyProjectId(value) {
|
|
128
|
+
if (!value) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
return readNonEmptyString(value[LEGACY_SCOPE_FIELD]);
|
|
132
|
+
}
|
|
133
|
+
function coerceVisibility(value) {
|
|
134
|
+
return value === "private" || value === "team" || value === "firm" || value === "external" || value === "public" ? value : void 0;
|
|
135
|
+
}
|
|
136
|
+
function coerceStatus(value) {
|
|
137
|
+
return value === "active" || value === "archived" || value === "watching" ? value : void 0;
|
|
138
|
+
}
|
|
139
|
+
function mapProjectType(topic, metadata) {
|
|
140
|
+
const explicit = readNonEmptyString(metadata.projectType);
|
|
141
|
+
if (explicit) {
|
|
142
|
+
return explicit;
|
|
143
|
+
}
|
|
144
|
+
if (topic.type === "theme") {
|
|
145
|
+
return "thematic";
|
|
146
|
+
}
|
|
147
|
+
return readNonEmptyString(topic.type) || "general";
|
|
148
|
+
}
|
|
149
|
+
function isProjectLikeTopic(topic) {
|
|
150
|
+
const metadata = readMetadata(topic);
|
|
151
|
+
return topic.type === "theme" || topic.type === "thematic" || topic.type === "deal" || topic.type === "monitoring" || readLegacyProjectId(topic) !== void 0 || readNonEmptyString(metadata.projectType) !== void 0;
|
|
152
|
+
}
|
|
153
|
+
function isMissingLucernChildComponentError(error) {
|
|
154
|
+
const message = getErrorMessage(error);
|
|
155
|
+
return message.includes(
|
|
156
|
+
'Child component ComponentName(Identifier("lucern")) not found'
|
|
157
|
+
) || message.includes("Child component") && message.includes("lucern") && message.includes("not found");
|
|
158
|
+
}
|
|
159
|
+
function getErrorMessage(error) {
|
|
160
|
+
if (error instanceof Error) {
|
|
161
|
+
return error.message;
|
|
162
|
+
}
|
|
163
|
+
if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
|
|
164
|
+
return error.message;
|
|
165
|
+
}
|
|
166
|
+
return "unknown error";
|
|
167
|
+
}
|
|
168
|
+
async function resolveTopicDoc(ctx, scopeId) {
|
|
169
|
+
if (ctx?.db && typeof ctx.db.get === "function") {
|
|
170
|
+
try {
|
|
171
|
+
const directTopic = await ctx.db.get(
|
|
172
|
+
scopeId
|
|
173
|
+
);
|
|
174
|
+
if (directTopic) {
|
|
175
|
+
return directTopic;
|
|
176
|
+
}
|
|
177
|
+
} catch (error) {
|
|
178
|
+
debugGraphPrimitiveFallback(
|
|
179
|
+
"[topicProjectOverlay] Failed to resolve topic by direct ID",
|
|
180
|
+
{
|
|
181
|
+
error,
|
|
182
|
+
scopeId
|
|
183
|
+
}
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (typeof ctx.runQuery !== "function") {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
const topic = await ctx.runQuery(api.topics.get, {
|
|
192
|
+
id: String(scopeId)
|
|
193
|
+
});
|
|
194
|
+
if (topic?.name !== void 0 && topic?.type !== void 0) {
|
|
195
|
+
return topic;
|
|
196
|
+
}
|
|
197
|
+
} catch (error) {
|
|
198
|
+
debugGraphPrimitiveFallback(
|
|
199
|
+
"[topicProjectOverlay] Failed to resolve topic by ID query",
|
|
200
|
+
{
|
|
201
|
+
error,
|
|
202
|
+
scopeId
|
|
203
|
+
}
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
try {
|
|
207
|
+
const topic = await ctx.runQuery(api.topics.getByLegacyScopeId, {
|
|
208
|
+
projectId: String(scopeId)
|
|
209
|
+
});
|
|
210
|
+
if (topic?.name !== void 0 && topic?.type !== void 0) {
|
|
211
|
+
return topic;
|
|
212
|
+
}
|
|
213
|
+
} catch (error) {
|
|
214
|
+
debugGraphPrimitiveFallback(
|
|
215
|
+
"[topicProjectOverlay] Failed to resolve topic by legacy scope ID",
|
|
216
|
+
{ error, scopeId }
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
return null;
|
|
220
|
+
}
|
|
221
|
+
function materializeTopicProjectOverlay(topic, idMode = "legacy") {
|
|
222
|
+
const metadata = readMetadata(topic);
|
|
223
|
+
const topicId = String(topic._id);
|
|
224
|
+
const legacyProjectId = readLegacyProjectId(topic) || readLegacyProjectId(metadata) || readNonEmptyString(metadata.legacyProjectId);
|
|
225
|
+
const storageProjectId = legacyProjectId || topicId;
|
|
226
|
+
const outwardId = idMode === "topic" ? topicId : storageProjectId;
|
|
227
|
+
const visibility = coerceVisibility(topic.visibility) || coerceVisibility(metadata.visibility) || "private";
|
|
228
|
+
const status = coerceStatus(topic.status) || coerceStatus(metadata.status) || "active";
|
|
229
|
+
const createdAt = typeof topic.createdAt === "number" ? topic.createdAt : typeof topic._creationTime === "number" ? topic._creationTime : 0;
|
|
230
|
+
const updatedAt = typeof topic.updatedAt === "number" ? topic.updatedAt : typeof metadata.updatedAt === "number" ? metadata.updatedAt : createdAt;
|
|
231
|
+
return {
|
|
232
|
+
...metadata,
|
|
233
|
+
_id: outwardId,
|
|
234
|
+
projectId: outwardId,
|
|
235
|
+
topicId,
|
|
236
|
+
storageProjectId,
|
|
237
|
+
legacyProjectId,
|
|
238
|
+
name: readNonEmptyString(topic.name) || "Untitled Theme",
|
|
239
|
+
type: mapProjectType(topic, metadata),
|
|
240
|
+
description: readNonEmptyString(topic.description),
|
|
241
|
+
ownerId: readNonEmptyString(metadata.ownerId) || readNonEmptyString(topic.createdBy) || "system",
|
|
242
|
+
sharedWith: readStringArray(metadata.sharedWith),
|
|
243
|
+
visibility,
|
|
244
|
+
tenantId: readNonEmptyString(topic.tenantId) || readNonEmptyString(metadata.tenantId),
|
|
245
|
+
workspaceId: readNonEmptyString(topic.workspaceId) || readNonEmptyString(metadata.workspaceId),
|
|
246
|
+
status,
|
|
247
|
+
tags: readStringArray(metadata.tags),
|
|
248
|
+
chatCount: typeof metadata.chatCount === "number" ? metadata.chatCount : 0,
|
|
249
|
+
artifactCount: typeof metadata.artifactCount === "number" ? metadata.artifactCount : 0,
|
|
250
|
+
lastActivityAt: typeof metadata.lastActivityAt === "number" ? metadata.lastActivityAt : updatedAt,
|
|
251
|
+
_creationTime: typeof topic._creationTime === "number" ? topic._creationTime : createdAt,
|
|
252
|
+
createdAt,
|
|
253
|
+
updatedAt
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
async function resolveTopicProjectOverlay(ctx, scopeId, options = {}) {
|
|
257
|
+
const topic = await resolveTopicDoc(ctx, scopeId);
|
|
258
|
+
if (!topic) {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
if (options.projectLikeOnly !== false && !isProjectLikeTopic(topic)) {
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
return materializeTopicProjectOverlay(topic, options.idMode);
|
|
265
|
+
}
|
|
266
|
+
async function listTopicProjectOverlays(ctx, options = {}) {
|
|
267
|
+
let allTopics = [];
|
|
268
|
+
if (ctx?.db?.query && typeof ctx.db.query === "function") {
|
|
269
|
+
try {
|
|
270
|
+
allTopics = await ctx.db.query("topics").collect();
|
|
271
|
+
} catch (error) {
|
|
272
|
+
debugGraphPrimitiveFallback(
|
|
273
|
+
"[topicProjectOverlay] Failed to read topics table; falling back to API",
|
|
274
|
+
{ error }
|
|
275
|
+
);
|
|
276
|
+
allTopics = [];
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (allTopics.length === 0 && typeof ctx.runQuery === "function") {
|
|
280
|
+
allTopics = (await ctx.runQuery(api.topics.list, {}) ?? []) || [];
|
|
281
|
+
}
|
|
282
|
+
return allTopics.filter(
|
|
283
|
+
(topic) => options.projectLikeOnly === false || isProjectLikeTopic(topic)
|
|
284
|
+
).map((topic) => materializeTopicProjectOverlay(topic, options.idMode));
|
|
285
|
+
}
|
|
286
|
+
async function patchTopicProjectOverlay(ctx, scopeId, value) {
|
|
287
|
+
const topic = await resolveTopicDoc(ctx, scopeId);
|
|
288
|
+
if (!topic) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
const nextMetadata = { ...readMetadata(topic) };
|
|
292
|
+
const patch = {};
|
|
293
|
+
const topicUpdateArgs = {
|
|
294
|
+
id: String(topic._id)
|
|
295
|
+
};
|
|
296
|
+
for (const [key, rawValue] of Object.entries(value)) {
|
|
297
|
+
switch (key) {
|
|
298
|
+
case "_id":
|
|
299
|
+
case "projectId":
|
|
300
|
+
case "topicId":
|
|
301
|
+
case "legacyProjectId":
|
|
302
|
+
case "storageProjectId":
|
|
303
|
+
break;
|
|
304
|
+
case "name":
|
|
305
|
+
case "description":
|
|
306
|
+
patch[key] = rawValue;
|
|
307
|
+
topicUpdateArgs[key] = rawValue;
|
|
308
|
+
break;
|
|
309
|
+
case "tenantId":
|
|
310
|
+
case "workspaceId":
|
|
311
|
+
case "ownerId":
|
|
312
|
+
throw new Error(
|
|
313
|
+
`patchTopicProjectOverlay cannot mutate ${key} via component-owned topics`
|
|
314
|
+
);
|
|
315
|
+
case "status": {
|
|
316
|
+
const status = coerceStatus(rawValue);
|
|
317
|
+
if (status) {
|
|
318
|
+
patch.status = status;
|
|
319
|
+
topicUpdateArgs.status = status;
|
|
320
|
+
}
|
|
321
|
+
break;
|
|
322
|
+
}
|
|
323
|
+
case "visibility": {
|
|
324
|
+
const visibility = coerceVisibility(rawValue);
|
|
325
|
+
if (visibility) {
|
|
326
|
+
patch.visibility = visibility;
|
|
327
|
+
topicUpdateArgs.visibility = visibility;
|
|
328
|
+
}
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
case "type": {
|
|
332
|
+
const projectType = readNonEmptyString(rawValue);
|
|
333
|
+
if (projectType) {
|
|
334
|
+
nextMetadata.projectType = projectType;
|
|
335
|
+
} else {
|
|
336
|
+
delete nextMetadata.projectType;
|
|
337
|
+
}
|
|
338
|
+
break;
|
|
339
|
+
}
|
|
340
|
+
case "updatedAt":
|
|
341
|
+
case "createdAt":
|
|
342
|
+
break;
|
|
343
|
+
default:
|
|
344
|
+
if (rawValue === void 0) {
|
|
345
|
+
delete nextMetadata[key];
|
|
346
|
+
} else {
|
|
347
|
+
nextMetadata[key] = rawValue;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
patch.updatedAt = Date.now();
|
|
352
|
+
patch.metadata = nextMetadata;
|
|
353
|
+
topicUpdateArgs.metadata = nextMetadata;
|
|
354
|
+
if (typeof ctx.runMutation === "function") {
|
|
355
|
+
try {
|
|
356
|
+
await ctx.runMutation(api.topics.update, topicUpdateArgs);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
if (!isMissingLucernChildComponentError(error) || !ctx?.db || typeof ctx.db.patch !== "function") {
|
|
359
|
+
throw error;
|
|
360
|
+
}
|
|
361
|
+
await ctx.db.patch(String(topic._id), patch);
|
|
362
|
+
}
|
|
363
|
+
} else if (ctx?.db && typeof ctx.db.patch === "function") {
|
|
364
|
+
await ctx.db.patch(String(topic._id), patch);
|
|
365
|
+
} else {
|
|
366
|
+
throw new Error(
|
|
367
|
+
"Cannot patch topic without component adapter (ctx.runMutation unavailable)"
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
return materializeTopicProjectOverlay({
|
|
371
|
+
...topic,
|
|
372
|
+
...patch,
|
|
373
|
+
metadata: nextMetadata
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// src/resolvers.ts
|
|
378
|
+
function isMissingLucernChildComponentError2(error) {
|
|
379
|
+
const message = getErrorMessage2(error);
|
|
380
|
+
return message.includes(
|
|
381
|
+
'Child component ComponentName(Identifier("lucern")) not found'
|
|
382
|
+
) || message.includes("Child component") && message.includes("lucern") && message.includes("not found");
|
|
383
|
+
}
|
|
384
|
+
function getErrorMessage2(error) {
|
|
385
|
+
if (error instanceof Error) {
|
|
386
|
+
return error.message;
|
|
387
|
+
}
|
|
388
|
+
if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
|
|
389
|
+
return error.message;
|
|
390
|
+
}
|
|
391
|
+
return "unknown error";
|
|
392
|
+
}
|
|
393
|
+
function isAdvisoryTopicPatch(value) {
|
|
394
|
+
const advisoryKeys = /* @__PURE__ */ new Set(["lastActivityAt", "updatedAt"]);
|
|
395
|
+
const keys = Object.keys(value);
|
|
396
|
+
return keys.length > 0 && keys.every((key) => advisoryKeys.has(key));
|
|
397
|
+
}
|
|
398
|
+
async function patchProjectWithTolerance(ctx, projectId, value) {
|
|
399
|
+
try {
|
|
400
|
+
await patchTopicProjectOverlay(ctx, projectId, value);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
if (!isAdvisoryTopicPatch(value) || !isMissingLucernChildComponentError2(error)) {
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
405
|
+
console.warn(
|
|
406
|
+
"[lucern graph-primitives] Non-fatal advisory topic patch failure",
|
|
407
|
+
{
|
|
408
|
+
projectId,
|
|
409
|
+
keys: Object.keys(value),
|
|
410
|
+
error: getErrorMessage2(error)
|
|
411
|
+
}
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
function defaultResolvers() {
|
|
416
|
+
return {
|
|
417
|
+
getProject: (ctx, projectId) => resolveTopicProjectOverlay(ctx, projectId, {
|
|
418
|
+
idMode: "legacy",
|
|
419
|
+
projectLikeOnly: false
|
|
420
|
+
}),
|
|
421
|
+
patchProject: (ctx, projectId, value) => patchProjectWithTolerance(ctx, projectId, value),
|
|
422
|
+
listTopics: (ctx) => listTopicProjectOverlays(ctx, {
|
|
423
|
+
idMode: "legacy"
|
|
424
|
+
}),
|
|
425
|
+
getFinalArtifact: (ctx, artifactId) => ctx.db.get(artifactId)
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
var resolverOverrides = {};
|
|
429
|
+
function resolveGraphPrimitivesAppResolvers(_ctx) {
|
|
430
|
+
return {
|
|
431
|
+
...defaultResolvers(),
|
|
432
|
+
...resolverOverrides
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
var LEGACY_SCOPE_FIELD2 = "graphScopeProjectId";
|
|
436
|
+
function asMappedProjectId(topic) {
|
|
437
|
+
if (!topic) {
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
const directLegacyProjectId = normalizeScopeValue(topic[LEGACY_SCOPE_FIELD2]);
|
|
441
|
+
if (directLegacyProjectId) {
|
|
442
|
+
return directLegacyProjectId;
|
|
443
|
+
}
|
|
444
|
+
const metadata = topic.metadata || {};
|
|
445
|
+
const candidate = metadata[LEGACY_SCOPE_FIELD2] || metadata.legacyProjectId || metadata.projectId || metadata.scopeProjectId;
|
|
446
|
+
return candidate ? candidate : void 0;
|
|
447
|
+
}
|
|
448
|
+
function normalizeScopeValue(value) {
|
|
449
|
+
if (typeof value !== "string") {
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
const normalized = value.trim();
|
|
453
|
+
return normalized.length > 0 ? normalized : void 0;
|
|
454
|
+
}
|
|
455
|
+
function pickPrimaryTopic(candidates) {
|
|
456
|
+
return [...candidates].sort((a, b) => {
|
|
457
|
+
const depthA = a.depth ?? 9999;
|
|
458
|
+
const depthB = b.depth ?? 9999;
|
|
459
|
+
if (depthA !== depthB) {
|
|
460
|
+
return depthA - depthB;
|
|
461
|
+
}
|
|
462
|
+
const createdA = a.createdAt ?? Number.MAX_SAFE_INTEGER;
|
|
463
|
+
const createdB = b.createdAt ?? Number.MAX_SAFE_INTEGER;
|
|
464
|
+
if (createdA !== createdB) {
|
|
465
|
+
return createdA - createdB;
|
|
466
|
+
}
|
|
467
|
+
return String(a.name || "").localeCompare(String(b.name || ""));
|
|
468
|
+
})[0];
|
|
469
|
+
}
|
|
470
|
+
async function findTopicsByScopeAlias(ctx, scopeId) {
|
|
471
|
+
try {
|
|
472
|
+
return await ctx.db.query("topics").withIndex(
|
|
473
|
+
"by_graph_scope_project",
|
|
474
|
+
(q) => q.eq(LEGACY_SCOPE_FIELD2, scopeId)
|
|
475
|
+
).collect();
|
|
476
|
+
} catch (error) {
|
|
477
|
+
debugGraphPrimitiveFallback(
|
|
478
|
+
"[topicScope] Failed to resolve scope alias via index",
|
|
479
|
+
{
|
|
480
|
+
error,
|
|
481
|
+
scopeId
|
|
482
|
+
}
|
|
483
|
+
);
|
|
484
|
+
const topics = await ctx.db.query("topics").collect();
|
|
485
|
+
return topics.filter((topic) => {
|
|
486
|
+
const normalizedGlobalId = normalizeScopeValue(topic.globalId);
|
|
487
|
+
const mappedProjectId = asMappedProjectId(topic);
|
|
488
|
+
return String(topic._id) === scopeId || normalizedGlobalId === scopeId || mappedProjectId === scopeId;
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
async function tryResolveHostTopicById(ctx, topicId) {
|
|
493
|
+
if (typeof ctx.runQuery !== "function") {
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
try {
|
|
497
|
+
return await ctx.runQuery(api.topics.get, {
|
|
498
|
+
id: topicId
|
|
499
|
+
}) ?? null;
|
|
500
|
+
} catch (error) {
|
|
501
|
+
debugGraphPrimitiveFallback(
|
|
502
|
+
"[topicScope] Failed to resolve topic by host query",
|
|
503
|
+
{
|
|
504
|
+
error,
|
|
505
|
+
topicId
|
|
506
|
+
}
|
|
507
|
+
);
|
|
508
|
+
return null;
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
async function tryResolveHostTopicByLegacyScope(ctx, legacyScopeId) {
|
|
512
|
+
if (typeof ctx.runQuery !== "function") {
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
try {
|
|
516
|
+
return await ctx.runQuery(api.topics.getByLegacyScopeId, {
|
|
517
|
+
projectId: legacyScopeId
|
|
518
|
+
}) ?? null;
|
|
519
|
+
} catch (error) {
|
|
520
|
+
debugGraphPrimitiveFallback(
|
|
521
|
+
"[topicScope] Failed to resolve topic by legacy scope",
|
|
522
|
+
{
|
|
523
|
+
error,
|
|
524
|
+
legacyScopeId
|
|
525
|
+
}
|
|
526
|
+
);
|
|
527
|
+
return null;
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
async function resolveInheritedWorkspaceScope(ctx, topic) {
|
|
531
|
+
const MAX_DEPTH = 10;
|
|
532
|
+
let tenantId = normalizeScopeValue(topic.tenantId);
|
|
533
|
+
let workspaceId = normalizeScopeValue(topic.workspaceId);
|
|
534
|
+
if (tenantId && workspaceId) {
|
|
535
|
+
return { tenantId, workspaceId };
|
|
536
|
+
}
|
|
537
|
+
let current = topic;
|
|
538
|
+
for (let i = 0; i < MAX_DEPTH && current?.parentTopicId; i++) {
|
|
539
|
+
current = await ctx.db.get(current.parentTopicId);
|
|
540
|
+
if (!current) break;
|
|
541
|
+
if (!tenantId) {
|
|
542
|
+
tenantId = normalizeScopeValue(current.tenantId);
|
|
543
|
+
}
|
|
544
|
+
if (!workspaceId) {
|
|
545
|
+
workspaceId = normalizeScopeValue(current.workspaceId);
|
|
546
|
+
}
|
|
547
|
+
if (tenantId && workspaceId) break;
|
|
548
|
+
}
|
|
549
|
+
return { tenantId, workspaceId };
|
|
550
|
+
}
|
|
551
|
+
async function resolveTopicProjectScope(ctx, args) {
|
|
552
|
+
if (args.topicId) {
|
|
553
|
+
let topic = null;
|
|
554
|
+
try {
|
|
555
|
+
topic = await ctx.db.get(
|
|
556
|
+
args.topicId
|
|
557
|
+
);
|
|
558
|
+
} catch (error) {
|
|
559
|
+
debugGraphPrimitiveFallback(
|
|
560
|
+
"[topicScope] Failed to load topic by direct id",
|
|
561
|
+
{
|
|
562
|
+
error,
|
|
563
|
+
topicId: args.topicId
|
|
564
|
+
}
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
if (!topic) {
|
|
568
|
+
topic = await tryResolveHostTopicById(ctx, String(args.topicId));
|
|
569
|
+
}
|
|
570
|
+
if (!topic) {
|
|
571
|
+
topic = pickPrimaryTopic(
|
|
572
|
+
await findTopicsByScopeAlias(ctx, String(args.topicId))
|
|
573
|
+
) ?? null;
|
|
574
|
+
}
|
|
575
|
+
if (!topic) {
|
|
576
|
+
throw new Error(`Topic not found: ${String(args.topicId)}`);
|
|
577
|
+
}
|
|
578
|
+
const inherited = await resolveInheritedWorkspaceScope(ctx, topic);
|
|
579
|
+
const mapped = asMappedProjectId(topic);
|
|
580
|
+
if (mapped) {
|
|
581
|
+
return {
|
|
582
|
+
topicId: topic._id,
|
|
583
|
+
projectId: mapped,
|
|
584
|
+
tenantId: inherited.tenantId,
|
|
585
|
+
workspaceId: inherited.workspaceId,
|
|
586
|
+
source: "topic"
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
return {
|
|
590
|
+
topicId: topic._id,
|
|
591
|
+
tenantId: inherited.tenantId,
|
|
592
|
+
workspaceId: inherited.workspaceId,
|
|
593
|
+
source: "topic"
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
if (args.projectId) {
|
|
597
|
+
let directTopic = null;
|
|
598
|
+
try {
|
|
599
|
+
directTopic = await ctx.db.get(
|
|
600
|
+
args.projectId
|
|
601
|
+
);
|
|
602
|
+
} catch (error) {
|
|
603
|
+
debugGraphPrimitiveFallback(
|
|
604
|
+
"[topicScope] Failed to load direct project topic",
|
|
605
|
+
{
|
|
606
|
+
error,
|
|
607
|
+
projectId: args.projectId
|
|
608
|
+
}
|
|
609
|
+
);
|
|
610
|
+
}
|
|
611
|
+
if (directTopic) {
|
|
612
|
+
const inherited = await resolveInheritedWorkspaceScope(ctx, directTopic);
|
|
613
|
+
const mapped = asMappedProjectId(directTopic);
|
|
614
|
+
return {
|
|
615
|
+
topicId: directTopic._id,
|
|
616
|
+
projectId: mapped ?? args.projectId,
|
|
617
|
+
tenantId: inherited.tenantId,
|
|
618
|
+
workspaceId: inherited.workspaceId,
|
|
619
|
+
source: "topic_inferred"
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
directTopic = await tryResolveHostTopicByLegacyScope(ctx, args.projectId);
|
|
623
|
+
if (directTopic) {
|
|
624
|
+
const inherited = await resolveInheritedWorkspaceScope(ctx, directTopic);
|
|
625
|
+
const mapped = asMappedProjectId(directTopic);
|
|
626
|
+
return {
|
|
627
|
+
topicId: directTopic._id,
|
|
628
|
+
projectId: mapped ?? args.projectId,
|
|
629
|
+
tenantId: inherited.tenantId,
|
|
630
|
+
workspaceId: inherited.workspaceId,
|
|
631
|
+
source: "topic_inferred"
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
const topics = await findTopicsByScopeAlias(ctx, args.projectId);
|
|
635
|
+
const primary = pickPrimaryTopic(topics);
|
|
636
|
+
if (primary) {
|
|
637
|
+
const inherited = await resolveInheritedWorkspaceScope(ctx, primary);
|
|
638
|
+
return {
|
|
639
|
+
topicId: primary._id,
|
|
640
|
+
projectId: args.projectId,
|
|
641
|
+
tenantId: inherited.tenantId,
|
|
642
|
+
workspaceId: inherited.workspaceId,
|
|
643
|
+
source: "project_mapped_topic"
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
throw new Error(
|
|
647
|
+
`Legacy project scope ${String(args.projectId)} has no mapped topic.`
|
|
648
|
+
);
|
|
649
|
+
}
|
|
650
|
+
throw new Error(
|
|
651
|
+
"Missing scope: provide topicId (preferred) or legacy projectId alias."
|
|
652
|
+
);
|
|
653
|
+
}
|
|
654
|
+
var optionalScopeArgs = {
|
|
655
|
+
projectId: v.optional(v.string()),
|
|
656
|
+
topicId: v.optional(v.string())
|
|
657
|
+
};
|
|
658
|
+
function normalizeScopeValue2(value) {
|
|
659
|
+
if (typeof value !== "string") {
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
const normalized = value.trim();
|
|
663
|
+
return normalized.length > 0 ? normalized : void 0;
|
|
664
|
+
}
|
|
665
|
+
function nodeMatchesWorkspaceReasoningScope(node, scope) {
|
|
666
|
+
if (!node) {
|
|
667
|
+
return false;
|
|
668
|
+
}
|
|
669
|
+
const scopeTenantId = normalizeScopeValue2(scope.tenantId);
|
|
670
|
+
const scopeWorkspaceId = normalizeScopeValue2(scope.workspaceId);
|
|
671
|
+
const nodeTenantId = normalizeScopeValue2(node.tenantId);
|
|
672
|
+
const nodeWorkspaceId = normalizeScopeValue2(node.workspaceId);
|
|
673
|
+
const epistemicLayer = typeof node.epistemicLayer === "string" ? node.epistemicLayer : void 0;
|
|
674
|
+
if (scopeTenantId && nodeTenantId && scopeTenantId !== nodeTenantId) {
|
|
675
|
+
return false;
|
|
676
|
+
}
|
|
677
|
+
if (epistemicLayer === "ontological" && nodeWorkspaceId === void 0) {
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
if (!scopeWorkspaceId && node.publicationStatus === "published") {
|
|
681
|
+
return true;
|
|
682
|
+
}
|
|
683
|
+
if (!scopeWorkspaceId) {
|
|
684
|
+
return nodeWorkspaceId === void 0;
|
|
685
|
+
}
|
|
686
|
+
return scopeWorkspaceId === nodeWorkspaceId;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// src/epistemicBeliefs.helpers.ts
|
|
690
|
+
var insightIdUnion = v.id("epistemicNodes");
|
|
691
|
+
var DEFAULT_PROJECT_BELIEF_LIMIT = 250;
|
|
692
|
+
var MAX_PROJECT_BELIEF_LIMIT = 1e3;
|
|
693
|
+
var optionalBeliefScopeArgs = optionalScopeArgs;
|
|
694
|
+
var DEFAULT_CONFIDENCE_POLICY = {
|
|
695
|
+
scoringMode: "after_worktree",
|
|
696
|
+
tupleContradiction: normalizeTupleContradictionPolicy()
|
|
697
|
+
};
|
|
698
|
+
function throwStructuredMutationError(args) {
|
|
699
|
+
const error = new Error(args.message);
|
|
700
|
+
error.status = args.status;
|
|
701
|
+
error.code = args.code;
|
|
702
|
+
error.invariantCode = args.invariantCode;
|
|
703
|
+
error.suggestion = args.suggestion;
|
|
704
|
+
error.details = args.details;
|
|
705
|
+
throw error;
|
|
706
|
+
}
|
|
707
|
+
function readFiniteNumber(value) {
|
|
708
|
+
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
709
|
+
}
|
|
710
|
+
function clamp01(value) {
|
|
711
|
+
return Math.max(0, Math.min(1, value));
|
|
712
|
+
}
|
|
713
|
+
function assertBaseRateInRange(baseRate, field = "baseRate") {
|
|
714
|
+
if (baseRate < 0 || baseRate > 1) {
|
|
715
|
+
throwStructuredMutationError({
|
|
716
|
+
message: `${field} must be within [0, 1].`,
|
|
717
|
+
status: 400,
|
|
718
|
+
code: "INVALID_ARGUMENT",
|
|
719
|
+
invariantCode: "request.valid_shape",
|
|
720
|
+
suggestion: `Clamp ${field} into the inclusive [0, 1] interval.`,
|
|
721
|
+
details: { field, baseRate }
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
return baseRate;
|
|
725
|
+
}
|
|
726
|
+
function buildBeliefConfidenceRow(args) {
|
|
727
|
+
return {
|
|
728
|
+
beliefId: args.beliefId,
|
|
729
|
+
confidence: confidenceFromSL(
|
|
730
|
+
args.belief,
|
|
731
|
+
args.disbelief,
|
|
732
|
+
args.uncertainty,
|
|
733
|
+
args.baseRate
|
|
734
|
+
),
|
|
735
|
+
belief: args.belief,
|
|
736
|
+
disbelief: args.disbelief,
|
|
737
|
+
uncertainty: args.uncertainty,
|
|
738
|
+
baseRate: args.baseRate,
|
|
739
|
+
slOperator: args.slOperator ?? "manual_assessment",
|
|
740
|
+
trigger: args.trigger,
|
|
741
|
+
...args.rationale ? { rationale: args.rationale } : {},
|
|
742
|
+
assessedBy: args.assessedBy,
|
|
743
|
+
assessedAt: args.assessedAt,
|
|
744
|
+
...args.triggeringEvidenceId ? {
|
|
745
|
+
triggeringEvidenceId: args.triggeringEvidenceId,
|
|
746
|
+
triggeringEvidenceIds: [String(args.triggeringEvidenceId)]
|
|
747
|
+
} : {},
|
|
748
|
+
...args.triggeringContradictionId ? {
|
|
749
|
+
triggeringContradictionId: args.triggeringContradictionId
|
|
750
|
+
} : {},
|
|
751
|
+
...args.triggeringWorktreeId ? { triggeringWorktreeId: args.triggeringWorktreeId } : {}
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
function buildBeliefStatusSuccessResult() {
|
|
755
|
+
return { success: true };
|
|
756
|
+
}
|
|
757
|
+
function buildBeliefEvidenceNotFoundResult() {
|
|
758
|
+
const result = {};
|
|
759
|
+
result.success = false;
|
|
760
|
+
result.message = "Evidence node not found";
|
|
761
|
+
return result;
|
|
762
|
+
}
|
|
763
|
+
function deriveSyntheticBackfillOpinion(source) {
|
|
764
|
+
const belief = readFiniteNumber(source.opinion_b) ?? readFiniteNumber(source.belief);
|
|
765
|
+
const disbelief = readFiniteNumber(source.opinion_d) ?? readFiniteNumber(source.disbelief);
|
|
766
|
+
const uncertainty = readFiniteNumber(source.opinion_u) ?? readFiniteNumber(source.uncertainty);
|
|
767
|
+
const baseRate = readFiniteNumber(source.opinion_a) ?? readFiniteNumber(source.baseRate);
|
|
768
|
+
if (belief !== void 0 || disbelief !== void 0 || uncertainty !== void 0 || baseRate !== void 0) {
|
|
769
|
+
try {
|
|
770
|
+
return readOpinionFromRecord(source);
|
|
771
|
+
} catch (error) {
|
|
772
|
+
debugGraphPrimitiveFallback(
|
|
773
|
+
"[epistemicBeliefs] Failed to decode legacy belief opinion",
|
|
774
|
+
{
|
|
775
|
+
error
|
|
776
|
+
}
|
|
777
|
+
);
|
|
778
|
+
return mkOpinion(0, 0, 1, 0.5);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
const confidence = clamp01(readFiniteNumber(source.confidence) ?? 0);
|
|
782
|
+
return mkOpinion(confidence, 1 - confidence, 0, 0.5);
|
|
783
|
+
}
|
|
784
|
+
function clampBeliefLimit(limit, fallback = DEFAULT_PROJECT_BELIEF_LIMIT) {
|
|
785
|
+
if (!Number.isFinite(limit)) {
|
|
786
|
+
return fallback;
|
|
787
|
+
}
|
|
788
|
+
return Math.max(
|
|
789
|
+
1,
|
|
790
|
+
Math.min(Math.floor(limit), MAX_PROJECT_BELIEF_LIMIT)
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
function readTupleContradictedFlag(value) {
|
|
794
|
+
return typeof value === "boolean" ? value : void 0;
|
|
795
|
+
}
|
|
796
|
+
function readBeliefOpinionSnapshot(node, metadata) {
|
|
797
|
+
try {
|
|
798
|
+
return readOpinionFromRecord({
|
|
799
|
+
...metadata,
|
|
800
|
+
opinion_b: node.opinion_b,
|
|
801
|
+
opinion_d: node.opinion_d,
|
|
802
|
+
opinion_u: node.opinion_u,
|
|
803
|
+
opinion_a: node.opinion_a
|
|
804
|
+
});
|
|
805
|
+
} catch (error) {
|
|
806
|
+
debugGraphPrimitiveFallback(
|
|
807
|
+
"[epistemicBeliefs] Failed to read belief opinion snapshot",
|
|
808
|
+
{
|
|
809
|
+
error,
|
|
810
|
+
beliefId: node._id
|
|
811
|
+
}
|
|
812
|
+
);
|
|
813
|
+
return mkOpinion(0, 0, 1, 0.5);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
function deriveTupleContradictionSeverity(node) {
|
|
817
|
+
const metadata = node.metadata || {};
|
|
818
|
+
const criticality = typeof metadata.criticality === "string" ? metadata.criticality : void 0;
|
|
819
|
+
if (criticality === "blocking") {
|
|
820
|
+
return "critical";
|
|
821
|
+
}
|
|
822
|
+
if (criticality === "supporting") {
|
|
823
|
+
return "minor";
|
|
824
|
+
}
|
|
825
|
+
return "significant";
|
|
826
|
+
}
|
|
827
|
+
function formatTupleContradictionDescription(args) {
|
|
828
|
+
return `Tuple-space contradiction detected: b=${args.opinion.b.toFixed(2)} > ${args.policy.beliefThreshold.toFixed(2)} and d=${args.opinion.d.toFixed(2)} > ${args.policy.disbeliefThreshold.toFixed(2)}.`;
|
|
829
|
+
}
|
|
830
|
+
function generateContentHash(text) {
|
|
831
|
+
const content = `belief:${text.trim().toLowerCase().replace(/\s+/g, " ")}`;
|
|
832
|
+
let hash = 5381;
|
|
833
|
+
for (let i = 0; i < content.length; i++) {
|
|
834
|
+
hash = (hash << 5) + hash + content.charCodeAt(i);
|
|
835
|
+
hash &= hash;
|
|
836
|
+
}
|
|
837
|
+
return Math.abs(hash).toString(16).padStart(8, "0");
|
|
838
|
+
}
|
|
839
|
+
function resolveBeliefWorktreeId(metadata) {
|
|
840
|
+
const worktreeId = metadata?.worktreeId;
|
|
841
|
+
if (typeof worktreeId === "string" && worktreeId.trim().length > 0) {
|
|
842
|
+
return worktreeId;
|
|
843
|
+
}
|
|
844
|
+
const sprintId = metadata?.sprintId;
|
|
845
|
+
return typeof sprintId === "string" && sprintId.trim().length > 0 ? sprintId : void 0;
|
|
846
|
+
}
|
|
847
|
+
function normalizePillar(pillar) {
|
|
848
|
+
if (!pillar) {
|
|
849
|
+
return "other";
|
|
850
|
+
}
|
|
851
|
+
const lower = pillar.toLowerCase();
|
|
852
|
+
const validPillars = [
|
|
853
|
+
"market",
|
|
854
|
+
"competition",
|
|
855
|
+
"product",
|
|
856
|
+
"team",
|
|
857
|
+
"financials",
|
|
858
|
+
"regulatory",
|
|
859
|
+
"timing",
|
|
860
|
+
"customer",
|
|
861
|
+
"technology",
|
|
862
|
+
"distribution",
|
|
863
|
+
"deal",
|
|
864
|
+
"risks"
|
|
865
|
+
];
|
|
866
|
+
return validPillars.find((p) => lower.includes(p)) || "other";
|
|
867
|
+
}
|
|
868
|
+
async function markBeliefGraphDirty(ctx, scope) {
|
|
869
|
+
const projectId = typeof scope.projectId === "string" && scope.projectId.trim().length > 0 ? scope.projectId : void 0;
|
|
870
|
+
const topicId = typeof scope.topicId === "string" && scope.topicId.trim().length > 0 ? scope.topicId : void 0;
|
|
871
|
+
if (!projectId && !topicId) {
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
if (projectId) {
|
|
875
|
+
await ctx.scheduler.runAfter(
|
|
876
|
+
0,
|
|
877
|
+
internal.graphAnalysisCache.markCacheStaleInternal,
|
|
878
|
+
{ projectId }
|
|
879
|
+
);
|
|
880
|
+
}
|
|
881
|
+
if (topicId) {
|
|
882
|
+
await ctx.scheduler.runAfter(
|
|
883
|
+
0,
|
|
884
|
+
internal.graphAnalysisCache.markCacheStaleByTopic,
|
|
885
|
+
{ topicId }
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
await resolveGraphPrimitivesAppResolvers().patchProject(
|
|
889
|
+
ctx,
|
|
890
|
+
topicId ?? projectId,
|
|
891
|
+
{
|
|
892
|
+
lastActivityAt: Date.now()
|
|
893
|
+
}
|
|
894
|
+
);
|
|
895
|
+
}
|
|
896
|
+
async function resolveBeliefScopeOrNull(ctx, args) {
|
|
897
|
+
if (!args.projectId && !args.topicId) {
|
|
898
|
+
return null;
|
|
899
|
+
}
|
|
900
|
+
try {
|
|
901
|
+
return await resolveTopicProjectScope(ctx, {
|
|
902
|
+
projectId: args.projectId ?? void 0,
|
|
903
|
+
topicId: args.topicId ?? void 0
|
|
904
|
+
});
|
|
905
|
+
} catch (error) {
|
|
906
|
+
debugGraphPrimitiveFallback(
|
|
907
|
+
"[epistemicBeliefs] Failed to resolve belief scope",
|
|
908
|
+
{
|
|
909
|
+
error,
|
|
910
|
+
projectId: args.projectId,
|
|
911
|
+
topicId: args.topicId
|
|
912
|
+
}
|
|
913
|
+
);
|
|
914
|
+
return null;
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
async function getBeliefNodesForScope(ctx, scope, args) {
|
|
918
|
+
const baseQuery = ctx.db.query("epistemicNodes").withIndex(
|
|
919
|
+
"by_topic_type",
|
|
920
|
+
(q) => q.eq("topicId", scope.topicId).eq("nodeType", "belief")
|
|
921
|
+
);
|
|
922
|
+
const nodes = typeof args?.scanLimit === "number" ? await baseQuery.order("desc").take(args.scanLimit) : await baseQuery.collect();
|
|
923
|
+
const scopedNodes = nodes.filter(
|
|
924
|
+
(node) => nodeMatchesWorkspaceReasoningScope(node, scope)
|
|
925
|
+
);
|
|
926
|
+
if (!args?.status) {
|
|
927
|
+
return scopedNodes;
|
|
928
|
+
}
|
|
929
|
+
return scopedNodes.filter((node) => node.status === args.status);
|
|
930
|
+
}
|
|
931
|
+
function createBeliefAudienceResolver(registryRows) {
|
|
932
|
+
const audienceClassByKey = new Map(
|
|
933
|
+
registryRows.map((row) => [
|
|
934
|
+
normalizeAudienceKey(row.audienceKey),
|
|
935
|
+
row.audienceClass
|
|
936
|
+
])
|
|
937
|
+
);
|
|
938
|
+
return (audienceKey, fallback) => {
|
|
939
|
+
const key = normalizeAudienceKey(audienceKey);
|
|
940
|
+
if (!key) {
|
|
941
|
+
return fallback;
|
|
942
|
+
}
|
|
943
|
+
return audienceClassByKey.get(key) ?? classFromAudienceKey(key, fallback);
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function flattenBeliefNode(node) {
|
|
947
|
+
const meta = node.metadata || {};
|
|
948
|
+
const worktreeId = resolveBeliefWorktreeId(meta);
|
|
949
|
+
const tupleContradicted = readTupleContradictedFlag(
|
|
950
|
+
node.tupleContradicted
|
|
951
|
+
) ?? readTupleContradictedFlag(meta.tupleContradicted) ?? false;
|
|
952
|
+
return {
|
|
953
|
+
_id: node._id,
|
|
954
|
+
_epistemicNodeId: node._id,
|
|
955
|
+
_creationTime: node._creationTime,
|
|
956
|
+
belief: node.canonicalText,
|
|
957
|
+
formulation: node.canonicalText,
|
|
958
|
+
projectId: node.projectId,
|
|
959
|
+
topicId: node.topicId,
|
|
960
|
+
userId: node.userId || node.createdBy || "",
|
|
961
|
+
confidence: meta.confidence || "untested",
|
|
962
|
+
status: node.status,
|
|
963
|
+
beliefStatus: resolveBeliefStatus(node, meta),
|
|
964
|
+
topic: meta.topic || meta.pillar || "other",
|
|
965
|
+
pillar: meta.pillar || meta.topic || "",
|
|
966
|
+
category: meta.category || "",
|
|
967
|
+
subcategory: meta.subcategory || "",
|
|
968
|
+
categoryIcon: meta.categoryIcon || "",
|
|
969
|
+
supportingEvidence: meta.supportingEvidenceIds || [],
|
|
970
|
+
contradictingEvidence: meta.contradictingEvidenceIds || [],
|
|
971
|
+
testingQuestions: meta.testingQuestionIds || [],
|
|
972
|
+
linkedInsights: meta.linkedInsightIds || [],
|
|
973
|
+
createdAt: node.createdAt,
|
|
974
|
+
updatedAt: node.updatedAt || node.createdAt,
|
|
975
|
+
tupleContradicted,
|
|
976
|
+
sprintId: meta.sprintId || void 0,
|
|
977
|
+
worktreeId,
|
|
978
|
+
sourceBeliefIds: meta.sourceBeliefIds || void 0,
|
|
979
|
+
criticality: meta.criticality || "unanalyzed",
|
|
980
|
+
rationale: meta.rationale || "",
|
|
981
|
+
audienceLabel: node.audienceLabel,
|
|
982
|
+
policyTags: node.policyTags,
|
|
983
|
+
sensitivityTier: node.sensitivityTier,
|
|
984
|
+
exportClass: node.exportClass,
|
|
985
|
+
anonymizationClass: node.anonymizationClass
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
function resolveBeliefStatus(node, metadata) {
|
|
989
|
+
return resolveBeliefLifecycleStatus({
|
|
990
|
+
beliefStatus: node.beliefStatus,
|
|
991
|
+
confidence: node.confidence,
|
|
992
|
+
predictionMeta: node.predictionMeta,
|
|
993
|
+
metadata
|
|
994
|
+
});
|
|
995
|
+
}
|
|
996
|
+
async function hasCompletedWorktreeForBelief(ctx, beliefNodeId) {
|
|
997
|
+
const clusterMembership = await ctx.db.query("worktreeBeliefCluster").withIndex("by_belief", (q) => q.eq("beliefId", beliefNodeId)).collect();
|
|
998
|
+
for (const membership of clusterMembership) {
|
|
999
|
+
const worktree = await ctx.db.get(membership.worktreeId);
|
|
1000
|
+
if (worktree?.status === "completed" || worktree?.status === "merged") {
|
|
1001
|
+
return true;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return false;
|
|
1005
|
+
}
|
|
1006
|
+
async function getActiveConfidencePolicy(ctx) {
|
|
1007
|
+
try {
|
|
1008
|
+
const activeConfig = await ctx.db.query("logicSprintScoring").withIndex("by_active", (q) => q.eq("isActive", true)).first();
|
|
1009
|
+
return {
|
|
1010
|
+
scoringMode: activeConfig?.confidencePolicy === "always" ? "always" : DEFAULT_CONFIDENCE_POLICY.scoringMode,
|
|
1011
|
+
tupleContradiction: normalizeTupleContradictionPolicy(
|
|
1012
|
+
activeConfig?.tupleContradictionPolicy
|
|
1013
|
+
)
|
|
1014
|
+
};
|
|
1015
|
+
} catch (error) {
|
|
1016
|
+
debugGraphPrimitiveFallback(
|
|
1017
|
+
"[epistemicBeliefs] Failed to load active confidence policy",
|
|
1018
|
+
{
|
|
1019
|
+
error
|
|
1020
|
+
}
|
|
1021
|
+
);
|
|
1022
|
+
return DEFAULT_CONFIDENCE_POLICY;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
async function requireAuthenticatedUserId(ctx) {
|
|
1026
|
+
const userId = await getCurrentUserId(
|
|
1027
|
+
ctx
|
|
1028
|
+
);
|
|
1029
|
+
if (!userId) {
|
|
1030
|
+
throwStructuredMutationError({
|
|
1031
|
+
message: "Authentication required.",
|
|
1032
|
+
status: 401,
|
|
1033
|
+
code: "AUTHENTICATION_REQUIRED",
|
|
1034
|
+
invariantCode: "auth.required",
|
|
1035
|
+
suggestion: "Provide a valid bearer token before invoking belief mutations."
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
return userId;
|
|
1039
|
+
}
|
|
1040
|
+
async function requireProjectWriteAccess(ctx, projectId, userId) {
|
|
1041
|
+
const hasAccess = await checkProjectAccess(
|
|
1042
|
+
ctx,
|
|
1043
|
+
projectId,
|
|
1044
|
+
userId
|
|
1045
|
+
);
|
|
1046
|
+
if (!hasAccess) {
|
|
1047
|
+
throwStructuredMutationError({
|
|
1048
|
+
message: "Project access required.",
|
|
1049
|
+
status: 403,
|
|
1050
|
+
code: "FORBIDDEN",
|
|
1051
|
+
invariantCode: "policy.scope_required",
|
|
1052
|
+
suggestion: "Request write access for the project and retry.",
|
|
1053
|
+
details: { projectId, userId }
|
|
1054
|
+
});
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
export { MAX_PROJECT_BELIEF_LIMIT, assertBaseRateInRange, buildBeliefConfidenceRow, buildBeliefEvidenceNotFoundResult, buildBeliefStatusSuccessResult, clampBeliefLimit, createBeliefAudienceResolver, deriveSyntheticBackfillOpinion, deriveTupleContradictionSeverity, flattenBeliefNode, formatTupleContradictionDescription, generateContentHash, getActiveConfidencePolicy, getBeliefNodesForScope, hasCompletedWorktreeForBelief, insightIdUnion, markBeliefGraphDirty, normalizePillar, optionalBeliefScopeArgs, readBeliefOpinionSnapshot, readFiniteNumber, readTupleContradictedFlag, requireAuthenticatedUserId, requireProjectWriteAccess, resolveBeliefScopeOrNull, resolveBeliefStatus, resolveBeliefWorktreeId, throwStructuredMutationError };
|
|
1059
|
+
//# sourceMappingURL=epistemicBeliefs.helpers.js.map
|
|
1060
|
+
//# sourceMappingURL=epistemicBeliefs.helpers.js.map
|