@lucern/sdk 0.2.0-alpha.6 → 0.2.0-alpha.7
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/.turbo/turbo-build.log +7 -0
- package/.turbo/turbo-typecheck.log +4 -0
- package/CHANGELOG.md +13 -0
- package/examples/README.md +69 -0
- package/examples/contradiction.ts +94 -0
- package/examples/investigation-context.ts +118 -0
- package/examples/questions-and-tasks.ts +55 -0
- package/examples/quickstart.ts +97 -0
- package/examples/shared.ts +318 -0
- package/examples/strict-public-types.ts +143 -0
- package/examples/worktree-lifecycle.ts +79 -0
- package/package.json +16 -58
- package/src/README.md +6 -0
- package/src/adminClient.ts +789 -0
- package/{dist/lib/platform/sdk/answersClient.d.ts → src/answersClient.ts} +17 -4
- package/src/audiencesClient.ts +209 -0
- package/src/auditClient.ts +50 -0
- package/src/beliefsClient.ts +319 -0
- package/src/client.ts +2647 -0
- package/src/contextClient.ts +130 -0
- package/{dist/lib/platform/sdk/contextFacade.d.ts → src/contextFacade.ts} +6 -1
- package/src/contextPackCompiler.ts +828 -0
- package/src/contextPackSchema.ts +251 -0
- package/src/contextTypes.ts +153 -0
- package/src/contracts/api-enums.contract.ts +202 -0
- package/src/contracts/auth-session.contract.ts +109 -0
- package/src/contracts/context-pack.contract.ts +700 -0
- package/src/contracts/contextPack.ts +1 -0
- package/src/contracts/index.ts +10 -0
- package/src/contracts/lens-filter.contract.ts +183 -0
- package/src/contracts/lens-workflow.contract.ts +162 -0
- package/src/contracts/lensFilter.ts +1 -0
- package/src/contracts/lensWorkflow.ts +1 -0
- package/src/contracts/mcp-tools.contract.ts +3636 -0
- package/src/contracts/mcpTools.ts +1 -0
- package/src/contracts/prompt.contract.ts +50 -0
- package/src/contracts/prompt.ts +1 -0
- package/src/contracts/sdk-tools.contract.ts +1457 -0
- package/src/contracts/sdkTools.ts +1 -0
- package/src/contracts/workflow-runtime.contract.ts +440 -0
- package/src/contracts/workflowRuntime.ts +1 -0
- package/src/controlObjectOwnership.ts +286 -0
- package/src/coreClient.ts +570 -0
- package/src/customTools.ts +398 -0
- package/src/decisionsClient.ts +286 -0
- package/src/domainContext.ts +15 -0
- package/src/events.ts +531 -0
- package/src/eventsCore.ts +168 -0
- package/src/facade/beliefs.ts +83 -0
- package/src/facade/context.ts +110 -0
- package/src/facade/contradictions.ts +29 -0
- package/src/facade/edges.ts +30 -0
- package/src/facade/events.ts +23 -0
- package/src/facade/evidence.ts +41 -0
- package/src/facade/graph.ts +38 -0
- package/src/facade/identity.ts +16 -0
- package/src/facade/ontologies.ts +34 -0
- package/src/facade/questions.ts +59 -0
- package/src/facade/search.ts +16 -0
- package/src/facade/tasks.ts +37 -0
- package/src/facade/topics.ts +42 -0
- package/src/facade/webhooks.ts +58 -0
- package/src/facade/worktrees.ts +51 -0
- package/src/gatewayFacades.ts +1666 -0
- package/src/graphClient.ts +529 -0
- package/src/harnessClient.ts +585 -0
- package/src/identityClient.ts +278 -0
- package/src/learningClient.ts +95 -0
- package/src/mcpParityClient.ts +240 -0
- package/src/mcpParitySurface.ts +70 -0
- package/src/ontologyClient.ts +275 -0
- package/src/packRuntime.ts +3 -0
- package/src/packsClient.ts +260 -0
- package/src/policyClient.ts +572 -0
- package/src/realtime/index.ts +51 -0
- package/src/realtime/refs.ts +17 -0
- package/src/reportsClient.ts +99 -0
- package/src/schemaClient.ts +129 -0
- package/src/sdkSurface.ts +190 -0
- package/src/topicsClient.ts +243 -0
- package/src/types.ts +807 -0
- package/src/workflowClient.ts +826 -0
- package/tsconfig.json +9 -0
- package/dist/.generated +0 -2
- package/dist/index.d.ts +0 -3
- package/dist/index.js +0 -3
- package/dist/lib/platform/auth/credentials.d.ts +0 -5
- package/dist/lib/platform/auth/credentials.js +0 -40
- package/dist/lib/platform/sdk/adminClient.d.ts +0 -404
- package/dist/lib/platform/sdk/adminClient.js +0 -384
- package/dist/lib/platform/sdk/answersClient.js +0 -21
- package/dist/lib/platform/sdk/audiencesClient.d.ts +0 -93
- package/dist/lib/platform/sdk/audiencesClient.js +0 -111
- package/dist/lib/platform/sdk/auditClient.d.ts +0 -24
- package/dist/lib/platform/sdk/auditClient.js +0 -21
- package/dist/lib/platform/sdk/beliefsClient.d.ts +0 -157
- package/dist/lib/platform/sdk/beliefsClient.js +0 -124
- package/dist/lib/platform/sdk/client.d.ts +0 -2369
- package/dist/lib/platform/sdk/client.js +0 -1831
- package/dist/lib/platform/sdk/contextClient.d.ts +0 -21
- package/dist/lib/platform/sdk/contextClient.js +0 -86
- package/dist/lib/platform/sdk/contextFacade.js +0 -10
- package/dist/lib/platform/sdk/contextPackCompiler.d.ts +0 -100
- package/dist/lib/platform/sdk/contextPackCompiler.js +0 -534
- package/dist/lib/platform/sdk/contextTypes.d.ts +0 -133
- package/dist/lib/platform/sdk/contextTypes.js +0 -1
- package/dist/lib/platform/sdk/controlObjectOwnership.d.ts +0 -308
- package/dist/lib/platform/sdk/controlObjectOwnership.js +0 -220
- package/dist/lib/platform/sdk/coreClient.d.ts +0 -139
- package/dist/lib/platform/sdk/coreClient.js +0 -366
- package/dist/lib/platform/sdk/customTools.d.ts +0 -83
- package/dist/lib/platform/sdk/customTools.js +0 -247
- package/dist/lib/platform/sdk/decisionsClient.d.ts +0 -106
- package/dist/lib/platform/sdk/decisionsClient.js +0 -129
- package/dist/lib/platform/sdk/domainContext.d.ts +0 -1
- package/dist/lib/platform/sdk/domainContext.js +0 -1
- package/dist/lib/platform/sdk/events.d.ts +0 -176
- package/dist/lib/platform/sdk/events.js +0 -261
- package/dist/lib/platform/sdk/eventsCore.d.ts +0 -13
- package/dist/lib/platform/sdk/eventsCore.js +0 -13
- package/dist/lib/platform/sdk/gatewayFacades.d.ts +0 -586
- package/dist/lib/platform/sdk/gatewayFacades.js +0 -845
- package/dist/lib/platform/sdk/graphClient.d.ts +0 -266
- package/dist/lib/platform/sdk/graphClient.js +0 -235
- package/dist/lib/platform/sdk/harnessClient.d.ts +0 -309
- package/dist/lib/platform/sdk/harnessClient.js +0 -219
- package/dist/lib/platform/sdk/identityClient.d.ts +0 -134
- package/dist/lib/platform/sdk/identityClient.js +0 -131
- package/dist/lib/platform/sdk/index.js +0 -49
- package/dist/lib/platform/sdk/learningClient.d.ts +0 -40
- package/dist/lib/platform/sdk/learningClient.js +0 -53
- package/dist/lib/platform/sdk/mcpParityClient.d.ts +0 -69
- package/dist/lib/platform/sdk/mcpParityClient.js +0 -196
- package/dist/lib/platform/sdk/mcpParitySurface.d.ts +0 -10
- package/dist/lib/platform/sdk/mcpParitySurface.js +0 -57
- package/dist/lib/platform/sdk/ontologyClient.d.ts +0 -131
- package/dist/lib/platform/sdk/ontologyClient.js +0 -161
- package/dist/lib/platform/sdk/packRuntime.d.ts +0 -1
- package/dist/lib/platform/sdk/packRuntime.js +0 -1
- package/dist/lib/platform/sdk/packsClient.d.ts +0 -126
- package/dist/lib/platform/sdk/packsClient.js +0 -157
- package/dist/lib/platform/sdk/policyClient.d.ts +0 -293
- package/dist/lib/platform/sdk/policyClient.js +0 -277
- package/dist/lib/platform/sdk/promptCatalog.js +0 -1
- package/dist/lib/platform/sdk/reportsClient.d.ts +0 -34
- package/dist/lib/platform/sdk/reportsClient.js +0 -64
- package/dist/lib/platform/sdk/schemaClient.d.ts +0 -59
- package/dist/lib/platform/sdk/schemaClient.js +0 -71
- package/dist/lib/platform/sdk/sdkSurface.d.ts +0 -56
- package/dist/lib/platform/sdk/sdkSurface.js +0 -140
- package/dist/lib/platform/sdk/topicsClient.d.ts +0 -78
- package/dist/lib/platform/sdk/topicsClient.js +0 -118
- package/dist/lib/platform/sdk/types.d.ts +0 -692
- package/dist/lib/platform/sdk/types.js +0 -1
- package/dist/lib/platform/sdk/version.d.ts +0 -2
- package/dist/lib/platform/sdk/workflowClient.d.ts +0 -313
- package/dist/lib/platform/sdk/workflowClient.js +0 -366
- package/dist/lucern/contracts/src/api-enums.contract.d.ts +0 -58
- package/dist/lucern/contracts/src/api-enums.contract.js +0 -147
- package/dist/lucern/contracts/src/auth-context.contract.d.ts +0 -8
- package/dist/lucern/contracts/src/auth-context.contract.js +0 -8
- package/dist/lucern/contracts/src/auth-session.contract.d.ts +0 -8
- package/dist/lucern/contracts/src/auth-session.contract.js +0 -8
- package/dist/lucern/contracts/src/auth.contract.d.ts +0 -88
- package/dist/lucern/contracts/src/auth.contract.js +0 -57
- package/dist/lucern/contracts/src/context-pack.contract.d.ts +0 -494
- package/dist/lucern/contracts/src/context-pack.contract.js +0 -169
- package/dist/lucern/contracts/src/convex-admin.contract.d.ts +0 -5
- package/dist/lucern/contracts/src/convex-admin.contract.js +0 -1
- package/dist/lucern/contracts/src/events-types.contract.d.ts +0 -8
- package/dist/lucern/contracts/src/events-types.contract.js +0 -8
- package/dist/lucern/contracts/src/events.contract.d.ts +0 -176
- package/dist/lucern/contracts/src/events.contract.js +0 -159
- package/dist/lucern/contracts/src/gateway.contract.d.ts +0 -74
- package/dist/lucern/contracts/src/gateway.contract.js +0 -19
- package/dist/lucern/contracts/src/ids.contract.d.ts +0 -7
- package/dist/lucern/contracts/src/ids.contract.js +0 -24
- package/dist/lucern/contracts/src/index.d.ts +0 -29
- package/dist/lucern/contracts/src/index.js +0 -29
- package/dist/lucern/contracts/src/lens-filter.contract.d.ts +0 -70
- package/dist/lucern/contracts/src/lens-filter.contract.js +0 -95
- package/dist/lucern/contracts/src/lens-workflow.contract.d.ts +0 -84
- package/dist/lucern/contracts/src/lens-workflow.contract.js +0 -54
- package/dist/lucern/contracts/src/mcp-tools.contract.d.ts +0 -151
- package/dist/lucern/contracts/src/mcp-tools.contract.js +0 -3281
- package/dist/lucern/contracts/src/ontology-matching.contract.d.ts +0 -8
- package/dist/lucern/contracts/src/ontology-matching.contract.js +0 -8
- package/dist/lucern/contracts/src/prompt.contract.d.ts +0 -24
- package/dist/lucern/contracts/src/prompt.contract.js +0 -24
- package/dist/lucern/contracts/src/sdk-methods.contract.d.ts +0 -358
- package/dist/lucern/contracts/src/sdk-methods.contract.js +0 -19
- package/dist/lucern/contracts/src/sdk-tools.contract.d.ts +0 -92
- package/dist/lucern/contracts/src/sdk-tools.contract.js +0 -1398
- package/dist/lucern/contracts/src/text-matching.contract.d.ts +0 -53
- package/dist/lucern/contracts/src/text-matching.contract.js +0 -277
- package/dist/lucern/contracts/src/topic-scope.contract.d.ts +0 -8
- package/dist/lucern/contracts/src/topic-scope.contract.js +0 -8
- package/dist/lucern/contracts/src/workflow-runtime.contract.d.ts +0 -161
- package/dist/lucern/contracts/src/workflow-runtime.contract.js +0 -257
- package/dist/realtime-refs.d.ts +0 -1
- package/dist/realtime-refs.js +0 -1
- package/dist/realtime.d.ts +0 -1
- package/dist/realtime.js +0 -1
- /package/{dist/lib/platform/sdk/index.d.ts → src/index.ts} +0 -0
- /package/{dist/lib/platform/sdk/promptCatalog.d.ts → src/promptCatalog.ts} +0 -0
- /package/{dist/lib/platform/sdk/version.js → src/version.ts} +0 -0
|
@@ -0,0 +1,828 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ContextCompilationMode,
|
|
3
|
+
type ContextPackDeltaReport,
|
|
4
|
+
type ContextPackV1,
|
|
5
|
+
CONTEXT_PACK_SCHEMA_VERSION,
|
|
6
|
+
DEFAULT_COMPILATION_MODE,
|
|
7
|
+
DEFAULT_ENTITY_LIMIT,
|
|
8
|
+
MAX_ENTITY_LIMIT,
|
|
9
|
+
type PackWeightOverride,
|
|
10
|
+
type ContextRankingProfile,
|
|
11
|
+
} from "./contracts/context-pack.contract";
|
|
12
|
+
import {
|
|
13
|
+
buildInjectionPlan,
|
|
14
|
+
type EntityCandidate,
|
|
15
|
+
parseTokenBudget,
|
|
16
|
+
rankContextSection,
|
|
17
|
+
rankEntities,
|
|
18
|
+
resolveEffectiveWeights,
|
|
19
|
+
} from "@lucern/reasoning-kernel/compat/contextPackPolicy";
|
|
20
|
+
import { validateContextPackSchema } from "./contextPackSchema";
|
|
21
|
+
|
|
22
|
+
export type ContextPackTopicRow = {
|
|
23
|
+
_id: string;
|
|
24
|
+
name?: string;
|
|
25
|
+
parentTopicId?: string;
|
|
26
|
+
depth?: number;
|
|
27
|
+
status?: string;
|
|
28
|
+
updatedAt?: number;
|
|
29
|
+
createdAt?: number;
|
|
30
|
+
generatedAt?: number;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
type ContextPackBeliefRow = {
|
|
34
|
+
_id: string;
|
|
35
|
+
canonicalText?: string;
|
|
36
|
+
confidence?: number;
|
|
37
|
+
beliefType?: string;
|
|
38
|
+
status?: string;
|
|
39
|
+
metadata?: Record<string, unknown>;
|
|
40
|
+
updatedAt?: number;
|
|
41
|
+
createdAt?: number;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
type ContextPackQuestionRow = {
|
|
45
|
+
_id: string;
|
|
46
|
+
canonicalText?: string;
|
|
47
|
+
status?: string;
|
|
48
|
+
metadata?: Record<string, unknown>;
|
|
49
|
+
updatedAt?: number;
|
|
50
|
+
createdAt?: number;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
type ContextPackEvidenceRow = {
|
|
54
|
+
_id: string;
|
|
55
|
+
canonicalText?: string;
|
|
56
|
+
sourceUrl?: string;
|
|
57
|
+
metadata?: Record<string, unknown>;
|
|
58
|
+
updatedAt?: number;
|
|
59
|
+
createdAt?: number;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
type ContextPackContradictionRow = {
|
|
63
|
+
_id?: string;
|
|
64
|
+
globalId?: string;
|
|
65
|
+
weight?: number;
|
|
66
|
+
context?: string;
|
|
67
|
+
description?: string;
|
|
68
|
+
summary?: string;
|
|
69
|
+
updatedAt?: number;
|
|
70
|
+
createdAt?: number;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
type ContextPackEntityRow = {
|
|
74
|
+
_id: string;
|
|
75
|
+
nodeType?: string;
|
|
76
|
+
title?: string;
|
|
77
|
+
canonicalText?: string;
|
|
78
|
+
connectedBeliefCount?: number;
|
|
79
|
+
connectedEvidenceCount?: number;
|
|
80
|
+
metadata?: Record<string, unknown>;
|
|
81
|
+
updatedAt?: number;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
type ContextPackFailureRow = {
|
|
85
|
+
_id: string;
|
|
86
|
+
canonicalText?: string;
|
|
87
|
+
metadata?: Record<string, unknown>;
|
|
88
|
+
updatedAt?: number;
|
|
89
|
+
createdAt?: number;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
export type CompileContextPackPlan = {
|
|
93
|
+
topicId: string;
|
|
94
|
+
queryText?: string;
|
|
95
|
+
tokens: string[];
|
|
96
|
+
limit: number;
|
|
97
|
+
rankingProfile: ContextRankingProfile;
|
|
98
|
+
tokenBudget: number;
|
|
99
|
+
descendantDepth: number;
|
|
100
|
+
includeEntities: boolean;
|
|
101
|
+
compilationMode: ContextCompilationMode;
|
|
102
|
+
includeFailures: boolean;
|
|
103
|
+
worktreeId?: string;
|
|
104
|
+
sessionId?: string;
|
|
105
|
+
packWeightOverrides?: PackWeightOverride[];
|
|
106
|
+
effectiveWeights: ReturnType<typeof resolveEffectiveWeights>;
|
|
107
|
+
scopedTopicIds: string[];
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
export type CompileContextPackPlanInput = {
|
|
111
|
+
args: Record<string, unknown> | undefined;
|
|
112
|
+
topic: ContextPackTopicRow;
|
|
113
|
+
allTopics: ContextPackTopicRow[];
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export type CompileContextPackSnapshot = {
|
|
117
|
+
topic: ContextPackTopicRow;
|
|
118
|
+
plan: CompileContextPackPlan;
|
|
119
|
+
beliefs: ContextPackBeliefRow[];
|
|
120
|
+
questions: ContextPackQuestionRow[];
|
|
121
|
+
evidence: ContextPackEvidenceRow[];
|
|
122
|
+
contradictions: ContextPackContradictionRow[];
|
|
123
|
+
entities: ContextPackEntityRow[];
|
|
124
|
+
failures?: ContextPackFailureRow[];
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
function assertContextPackSchema(payload: unknown): void {
|
|
128
|
+
const result = validateContextPackSchema(payload);
|
|
129
|
+
if (!result.valid) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`Invalid context pack payload: ${result.errors.join("; ")}`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function asStringArray(value: unknown): string[] {
|
|
137
|
+
if (!Array.isArray(value)) {
|
|
138
|
+
return [];
|
|
139
|
+
}
|
|
140
|
+
return value
|
|
141
|
+
.map((entry) => (typeof entry === "string" ? entry.trim() : ""))
|
|
142
|
+
.filter((entry) => entry.length > 0);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function toPositiveInt(value: unknown, fallback: number, max: number): number {
|
|
146
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
147
|
+
return fallback;
|
|
148
|
+
}
|
|
149
|
+
const floored = Math.floor(value);
|
|
150
|
+
return Math.max(1, Math.min(floored, max));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function normalizeQueryTokens(query: string | undefined): string[] {
|
|
154
|
+
if (!query) {
|
|
155
|
+
return [];
|
|
156
|
+
}
|
|
157
|
+
return query
|
|
158
|
+
.toLowerCase()
|
|
159
|
+
.split(/[^a-z0-9]+/)
|
|
160
|
+
.map((token) => token.trim())
|
|
161
|
+
.filter((token) => token.length >= 2);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function parseRankingProfile(value: unknown): ContextRankingProfile {
|
|
165
|
+
return value === "baseline_v1" ? "baseline_v1" : "weighted_v1";
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function beliefTypeOf(node: ContextPackBeliefRow): string {
|
|
169
|
+
if (typeof node.beliefType === "string") {
|
|
170
|
+
return node.beliefType;
|
|
171
|
+
}
|
|
172
|
+
const metadata = (node.metadata || {}) as Record<string, unknown>;
|
|
173
|
+
if (typeof metadata.beliefType === "string") {
|
|
174
|
+
return metadata.beliefType;
|
|
175
|
+
}
|
|
176
|
+
return "";
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function questionStatusOf(node: ContextPackQuestionRow): string {
|
|
180
|
+
const metadata = (node.metadata || {}) as Record<string, unknown>;
|
|
181
|
+
const direct = typeof node.status === "string" ? node.status : "";
|
|
182
|
+
const questionStatus =
|
|
183
|
+
typeof metadata.questionStatus === "string" ? metadata.questionStatus : "";
|
|
184
|
+
return (questionStatus || direct || "open").toLowerCase();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function isOpenQuestion(status: string): boolean {
|
|
188
|
+
return ![
|
|
189
|
+
"answered",
|
|
190
|
+
"archived",
|
|
191
|
+
"closed",
|
|
192
|
+
"resolved",
|
|
193
|
+
"resolved_support",
|
|
194
|
+
"resolved_contra",
|
|
195
|
+
"belief_forked",
|
|
196
|
+
].includes(status);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function metadataText(payload: Record<string, unknown>): string {
|
|
200
|
+
return JSON.stringify(payload).toLowerCase();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function collectTopicNeighborhood(
|
|
204
|
+
topics: ContextPackTopicRow[],
|
|
205
|
+
rootTopicId: string,
|
|
206
|
+
maxDescendantDepth = 2
|
|
207
|
+
): string[] {
|
|
208
|
+
const byId = new Map<string, ContextPackTopicRow>();
|
|
209
|
+
const children = new Map<string, string[]>();
|
|
210
|
+
for (const topic of topics) {
|
|
211
|
+
const id = String(topic._id);
|
|
212
|
+
byId.set(id, topic);
|
|
213
|
+
if (!children.has(id)) {
|
|
214
|
+
children.set(id, []);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
for (const topic of topics) {
|
|
218
|
+
if (!topic.parentTopicId) {
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
const parent = String(topic.parentTopicId);
|
|
222
|
+
const id = String(topic._id);
|
|
223
|
+
const list = children.get(parent) || [];
|
|
224
|
+
list.push(id);
|
|
225
|
+
children.set(parent, list);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const selected = new Set<string>([rootTopicId]);
|
|
229
|
+
|
|
230
|
+
let cursor = byId.get(rootTopicId);
|
|
231
|
+
while (cursor?.parentTopicId) {
|
|
232
|
+
const parentId = String(cursor.parentTopicId);
|
|
233
|
+
if (selected.has(parentId)) {
|
|
234
|
+
break;
|
|
235
|
+
}
|
|
236
|
+
selected.add(parentId);
|
|
237
|
+
cursor = byId.get(parentId);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const queue: Array<{ id: string; depth: number }> = [
|
|
241
|
+
{ id: rootTopicId, depth: 0 },
|
|
242
|
+
];
|
|
243
|
+
while (queue.length > 0) {
|
|
244
|
+
const current = queue.shift();
|
|
245
|
+
if (!current || current.depth >= maxDescendantDepth) {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
for (const childId of children.get(current.id) || []) {
|
|
249
|
+
if (!selected.has(childId)) {
|
|
250
|
+
selected.add(childId);
|
|
251
|
+
}
|
|
252
|
+
queue.push({ id: childId, depth: current.depth + 1 });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return Array.from(selected);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function dedupeById<T extends { _id?: string }>(rows: T[]): T[] {
|
|
260
|
+
const seen = new Set<string>();
|
|
261
|
+
const output: T[] = [];
|
|
262
|
+
for (const row of rows) {
|
|
263
|
+
const id = row?._id ? String(row._id) : "";
|
|
264
|
+
if (!id || seen.has(id)) {
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
seen.add(id);
|
|
268
|
+
output.push(row);
|
|
269
|
+
}
|
|
270
|
+
return output;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function candidateTimestamp(candidate: unknown): number {
|
|
274
|
+
if (!candidate || typeof candidate !== "object") {
|
|
275
|
+
return 0;
|
|
276
|
+
}
|
|
277
|
+
const record = candidate as Record<string, unknown>;
|
|
278
|
+
const timestamps = [record.updatedAt, record.createdAt, record.generatedAt].filter(
|
|
279
|
+
(value): value is number => typeof value === "number" && Number.isFinite(value)
|
|
280
|
+
);
|
|
281
|
+
return timestamps.length > 0 ? Math.max(...timestamps) : 0;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function resolveReferenceTimeMs(...collections: unknown[][]): number {
|
|
285
|
+
let maxTimestamp = 0;
|
|
286
|
+
for (const collection of collections) {
|
|
287
|
+
for (const item of collection) {
|
|
288
|
+
const timestamp = candidateTimestamp(item);
|
|
289
|
+
if (timestamp > maxTimestamp) {
|
|
290
|
+
maxTimestamp = timestamp;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return maxTimestamp;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
export function planContextPackCompilation(
|
|
298
|
+
input: CompileContextPackPlanInput
|
|
299
|
+
): CompileContextPackPlan {
|
|
300
|
+
const args = input.args ?? {};
|
|
301
|
+
const topicId = String(input.topic._id);
|
|
302
|
+
const queryText =
|
|
303
|
+
typeof args.query === "string" && args.query.trim().length > 0
|
|
304
|
+
? args.query.trim()
|
|
305
|
+
: undefined;
|
|
306
|
+
const tokens = normalizeQueryTokens(queryText);
|
|
307
|
+
const limit = toPositiveInt(args.limit, 8, 25);
|
|
308
|
+
const rankingProfile = parseRankingProfile(
|
|
309
|
+
typeof args.ranking === "string" ? args.ranking : args.rankingProfile
|
|
310
|
+
);
|
|
311
|
+
const tokenBudget = parseTokenBudget(
|
|
312
|
+
typeof args.budget === "number" ? args.budget : args.tokenBudget,
|
|
313
|
+
1800
|
|
314
|
+
);
|
|
315
|
+
const topicDepth =
|
|
316
|
+
typeof input.topic.depth === "number" && Number.isFinite(input.topic.depth)
|
|
317
|
+
? input.topic.depth
|
|
318
|
+
: 0;
|
|
319
|
+
const requestedMaxDepth =
|
|
320
|
+
typeof args.maxDepth === "number" && Number.isFinite(args.maxDepth)
|
|
321
|
+
? Math.max(1, Math.min(Math.floor(args.maxDepth), 6))
|
|
322
|
+
: undefined;
|
|
323
|
+
const descendantDepth = requestedMaxDepth ?? (topicDepth <= 1 ? 4 : 2);
|
|
324
|
+
const includeEntities = args.includeEntities !== false;
|
|
325
|
+
const compilationMode: ContextCompilationMode =
|
|
326
|
+
args.mode === "delta" ? "delta" : DEFAULT_COMPILATION_MODE;
|
|
327
|
+
const includeFailures =
|
|
328
|
+
compilationMode === "delta" || args.includeFailures === true;
|
|
329
|
+
const worktreeId =
|
|
330
|
+
typeof args.worktreeId === "string" && args.worktreeId.trim().length > 0
|
|
331
|
+
? args.worktreeId.trim()
|
|
332
|
+
: undefined;
|
|
333
|
+
const sessionId =
|
|
334
|
+
typeof args.sessionId === "string" && args.sessionId.trim().length > 0
|
|
335
|
+
? args.sessionId.trim()
|
|
336
|
+
: undefined;
|
|
337
|
+
const packWeightOverrides = Array.isArray(args.packWeightOverrides)
|
|
338
|
+
? (args.packWeightOverrides as PackWeightOverride[])
|
|
339
|
+
: undefined;
|
|
340
|
+
const effectiveWeights = resolveEffectiveWeights(packWeightOverrides);
|
|
341
|
+
|
|
342
|
+
let scopedTopicIds = collectTopicNeighborhood(
|
|
343
|
+
input.allTopics,
|
|
344
|
+
topicId,
|
|
345
|
+
descendantDepth
|
|
346
|
+
);
|
|
347
|
+
|
|
348
|
+
const allowedTopicIds = asStringArray(args.allowedTopicIds);
|
|
349
|
+
if (allowedTopicIds.length > 0) {
|
|
350
|
+
const allowedSet = new Set(allowedTopicIds);
|
|
351
|
+
if (!allowedSet.has(topicId)) {
|
|
352
|
+
throw new Error(`Access denied to compile context for topic ${topicId}.`);
|
|
353
|
+
}
|
|
354
|
+
scopedTopicIds = scopedTopicIds.filter((id) => allowedSet.has(id));
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
topicId,
|
|
359
|
+
...(queryText ? { queryText } : {}),
|
|
360
|
+
tokens,
|
|
361
|
+
limit,
|
|
362
|
+
rankingProfile,
|
|
363
|
+
tokenBudget,
|
|
364
|
+
descendantDepth,
|
|
365
|
+
includeEntities,
|
|
366
|
+
compilationMode,
|
|
367
|
+
includeFailures,
|
|
368
|
+
...(worktreeId ? { worktreeId } : {}),
|
|
369
|
+
...(sessionId ? { sessionId } : {}),
|
|
370
|
+
...(packWeightOverrides ? { packWeightOverrides } : {}),
|
|
371
|
+
effectiveWeights,
|
|
372
|
+
scopedTopicIds,
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export function compileContextPackFromSnapshot(
|
|
377
|
+
snapshot: CompileContextPackSnapshot
|
|
378
|
+
): ContextPackV1 {
|
|
379
|
+
const uniqueBeliefs = dedupeById(snapshot.beliefs);
|
|
380
|
+
const uniqueQuestions = dedupeById(snapshot.questions);
|
|
381
|
+
const uniqueEvidence = dedupeById(snapshot.evidence);
|
|
382
|
+
const uniqueContradictions = dedupeById(snapshot.contradictions);
|
|
383
|
+
const referenceTimeMs =
|
|
384
|
+
resolveReferenceTimeMs(
|
|
385
|
+
[snapshot.topic],
|
|
386
|
+
uniqueBeliefs,
|
|
387
|
+
uniqueQuestions,
|
|
388
|
+
uniqueEvidence,
|
|
389
|
+
uniqueContradictions,
|
|
390
|
+
snapshot.entities
|
|
391
|
+
) || 0;
|
|
392
|
+
|
|
393
|
+
const rankOptions = {
|
|
394
|
+
effectiveWeights: snapshot.plan.effectiveWeights,
|
|
395
|
+
includeJustifications: snapshot.plan.compilationMode === "delta",
|
|
396
|
+
referenceTimeMs,
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const invariantCandidates = uniqueBeliefs
|
|
400
|
+
.filter((belief) => beliefTypeOf(belief).toLowerCase() === "invariant")
|
|
401
|
+
.map((belief) => ({
|
|
402
|
+
nodeId: String(belief._id),
|
|
403
|
+
canonicalText: String(belief.canonicalText || ""),
|
|
404
|
+
confidence:
|
|
405
|
+
typeof belief.confidence === "number" ? belief.confidence : null,
|
|
406
|
+
beliefType: beliefTypeOf(belief) || "invariant",
|
|
407
|
+
updatedAt: belief.updatedAt || belief.createdAt || null,
|
|
408
|
+
}));
|
|
409
|
+
|
|
410
|
+
const invariants = rankContextSection(
|
|
411
|
+
"invariants",
|
|
412
|
+
invariantCandidates.map((candidate) => ({
|
|
413
|
+
...candidate,
|
|
414
|
+
id: candidate.nodeId,
|
|
415
|
+
text: `${candidate.canonicalText} ${candidate.beliefType}`,
|
|
416
|
+
})),
|
|
417
|
+
snapshot.plan.tokens,
|
|
418
|
+
snapshot.plan.limit,
|
|
419
|
+
snapshot.plan.rankingProfile,
|
|
420
|
+
rankOptions
|
|
421
|
+
).map((row) => ({
|
|
422
|
+
nodeId: row.nodeId,
|
|
423
|
+
canonicalText: row.canonicalText,
|
|
424
|
+
confidence: row.confidence,
|
|
425
|
+
beliefType: row.beliefType,
|
|
426
|
+
score: row.score,
|
|
427
|
+
...(row.justification ? { justification: row.justification } : {}),
|
|
428
|
+
}));
|
|
429
|
+
|
|
430
|
+
const activeBeliefCandidates = uniqueBeliefs
|
|
431
|
+
.filter((belief) => (belief.status || "active") !== "archived")
|
|
432
|
+
.map((belief) => ({
|
|
433
|
+
nodeId: String(belief._id),
|
|
434
|
+
canonicalText: String(belief.canonicalText || ""),
|
|
435
|
+
confidence:
|
|
436
|
+
typeof belief.confidence === "number" ? belief.confidence : null,
|
|
437
|
+
beliefType: beliefTypeOf(belief) || null,
|
|
438
|
+
status: belief.status || "active",
|
|
439
|
+
updatedAt: belief.updatedAt || belief.createdAt || null,
|
|
440
|
+
metadataText:
|
|
441
|
+
belief.metadata && typeof belief.metadata === "object"
|
|
442
|
+
? metadataText(belief.metadata)
|
|
443
|
+
: "",
|
|
444
|
+
}));
|
|
445
|
+
|
|
446
|
+
const activeBeliefs = rankContextSection(
|
|
447
|
+
"activeBeliefs",
|
|
448
|
+
activeBeliefCandidates.map((candidate) => ({
|
|
449
|
+
...candidate,
|
|
450
|
+
id: candidate.nodeId,
|
|
451
|
+
text: `${candidate.canonicalText} ${candidate.metadataText}`,
|
|
452
|
+
})),
|
|
453
|
+
snapshot.plan.tokens,
|
|
454
|
+
snapshot.plan.limit,
|
|
455
|
+
snapshot.plan.rankingProfile,
|
|
456
|
+
rankOptions
|
|
457
|
+
).map((row) => ({
|
|
458
|
+
nodeId: row.nodeId,
|
|
459
|
+
canonicalText: row.canonicalText,
|
|
460
|
+
confidence: row.confidence,
|
|
461
|
+
beliefType: row.beliefType,
|
|
462
|
+
status: row.status,
|
|
463
|
+
updatedAt: row.updatedAt,
|
|
464
|
+
score: row.score,
|
|
465
|
+
...(row.justification ? { justification: row.justification } : {}),
|
|
466
|
+
}));
|
|
467
|
+
|
|
468
|
+
const openQuestionCandidates = uniqueQuestions
|
|
469
|
+
.map((question) => {
|
|
470
|
+
const status = questionStatusOf(question);
|
|
471
|
+
const metadata =
|
|
472
|
+
question.metadata && typeof question.metadata === "object"
|
|
473
|
+
? question.metadata
|
|
474
|
+
: {};
|
|
475
|
+
return {
|
|
476
|
+
questionId: String(question._id),
|
|
477
|
+
text: String(question.canonicalText || ""),
|
|
478
|
+
status,
|
|
479
|
+
priority:
|
|
480
|
+
typeof metadata.priority === "string" ? metadata.priority : "medium",
|
|
481
|
+
updatedAt: question.updatedAt || question.createdAt || null,
|
|
482
|
+
metadataText: metadataText(metadata),
|
|
483
|
+
};
|
|
484
|
+
})
|
|
485
|
+
.filter((row) => isOpenQuestion(row.status));
|
|
486
|
+
|
|
487
|
+
const openQuestions = rankContextSection(
|
|
488
|
+
"openQuestions",
|
|
489
|
+
openQuestionCandidates.map((candidate) => ({
|
|
490
|
+
...candidate,
|
|
491
|
+
id: candidate.questionId,
|
|
492
|
+
text: `${candidate.text} ${candidate.metadataText}`,
|
|
493
|
+
})),
|
|
494
|
+
snapshot.plan.tokens,
|
|
495
|
+
snapshot.plan.limit,
|
|
496
|
+
snapshot.plan.rankingProfile,
|
|
497
|
+
rankOptions
|
|
498
|
+
).map((row) => ({
|
|
499
|
+
questionId: row.questionId,
|
|
500
|
+
text: row.text,
|
|
501
|
+
status: row.status,
|
|
502
|
+
priority: row.priority,
|
|
503
|
+
updatedAt: row.updatedAt,
|
|
504
|
+
score: row.score,
|
|
505
|
+
...(row.justification ? { justification: row.justification } : {}),
|
|
506
|
+
}));
|
|
507
|
+
|
|
508
|
+
const evidenceCandidates = uniqueEvidence.map((item) => {
|
|
509
|
+
const metadata =
|
|
510
|
+
item.metadata && typeof item.metadata === "object" ? item.metadata : {};
|
|
511
|
+
return {
|
|
512
|
+
nodeId: String(item._id),
|
|
513
|
+
canonicalText: String(item.canonicalText || ""),
|
|
514
|
+
sourceUrl:
|
|
515
|
+
(typeof metadata.sourceUrl === "string" && metadata.sourceUrl) ||
|
|
516
|
+
(typeof item.sourceUrl === "string" && item.sourceUrl) ||
|
|
517
|
+
null,
|
|
518
|
+
kind:
|
|
519
|
+
(typeof metadata.kind === "string" && metadata.kind) || "observation",
|
|
520
|
+
createdAt: item.createdAt || null,
|
|
521
|
+
updatedAt: item.updatedAt || item.createdAt || null,
|
|
522
|
+
metadataText: metadataText(metadata),
|
|
523
|
+
};
|
|
524
|
+
});
|
|
525
|
+
|
|
526
|
+
const recentEvidence = rankContextSection(
|
|
527
|
+
"recentEvidence",
|
|
528
|
+
evidenceCandidates.map((candidate) => ({
|
|
529
|
+
...candidate,
|
|
530
|
+
id: candidate.nodeId,
|
|
531
|
+
text: `${candidate.canonicalText} ${candidate.metadataText}`,
|
|
532
|
+
})),
|
|
533
|
+
snapshot.plan.tokens,
|
|
534
|
+
snapshot.plan.limit,
|
|
535
|
+
snapshot.plan.rankingProfile,
|
|
536
|
+
rankOptions
|
|
537
|
+
).map((row) => ({
|
|
538
|
+
nodeId: row.nodeId,
|
|
539
|
+
canonicalText: row.canonicalText,
|
|
540
|
+
sourceUrl: row.sourceUrl,
|
|
541
|
+
kind: row.kind,
|
|
542
|
+
createdAt: row.createdAt,
|
|
543
|
+
score: row.score,
|
|
544
|
+
...(row.justification ? { justification: row.justification } : {}),
|
|
545
|
+
}));
|
|
546
|
+
|
|
547
|
+
const contradictionCandidates = uniqueContradictions.map((row) => {
|
|
548
|
+
const weight = typeof row.weight === "number" ? row.weight : 0;
|
|
549
|
+
const severity =
|
|
550
|
+
weight <= -0.9
|
|
551
|
+
? "critical"
|
|
552
|
+
: weight <= -0.7
|
|
553
|
+
? "high"
|
|
554
|
+
: weight <= -0.5
|
|
555
|
+
? "medium"
|
|
556
|
+
: "low";
|
|
557
|
+
return {
|
|
558
|
+
contradictionId: String(row._id || row.globalId || ""),
|
|
559
|
+
severity,
|
|
560
|
+
status: "active",
|
|
561
|
+
description: row.context || row.description || row.summary || "",
|
|
562
|
+
updatedAt: row.updatedAt || row.createdAt || null,
|
|
563
|
+
};
|
|
564
|
+
});
|
|
565
|
+
|
|
566
|
+
const contradictions = rankContextSection(
|
|
567
|
+
"contradictions",
|
|
568
|
+
contradictionCandidates.map((candidate) => ({
|
|
569
|
+
...candidate,
|
|
570
|
+
id: candidate.contradictionId,
|
|
571
|
+
text: `${candidate.description} ${candidate.severity}`,
|
|
572
|
+
})),
|
|
573
|
+
snapshot.plan.tokens,
|
|
574
|
+
snapshot.plan.limit,
|
|
575
|
+
snapshot.plan.rankingProfile,
|
|
576
|
+
rankOptions
|
|
577
|
+
).map((row) => ({
|
|
578
|
+
contradictionId: row.contradictionId,
|
|
579
|
+
severity: row.severity,
|
|
580
|
+
status: row.status,
|
|
581
|
+
description: row.description,
|
|
582
|
+
score: row.score,
|
|
583
|
+
...(row.justification ? { justification: row.justification } : {}),
|
|
584
|
+
}));
|
|
585
|
+
|
|
586
|
+
const entityCandidates: EntityCandidate[] = snapshot.entities.map((row) => ({
|
|
587
|
+
nodeId: String(row._id),
|
|
588
|
+
entityType: String(row.nodeType || ""),
|
|
589
|
+
title: String(row.title || ""),
|
|
590
|
+
canonicalText: String(row.canonicalText || ""),
|
|
591
|
+
connectedBeliefCount:
|
|
592
|
+
typeof row.connectedBeliefCount === "number" ? row.connectedBeliefCount : 0,
|
|
593
|
+
connectedEvidenceCount:
|
|
594
|
+
typeof row.connectedEvidenceCount === "number"
|
|
595
|
+
? row.connectedEvidenceCount
|
|
596
|
+
: 0,
|
|
597
|
+
metadata:
|
|
598
|
+
row.metadata && typeof row.metadata === "object" ? row.metadata : {},
|
|
599
|
+
updatedAt: row.updatedAt || null,
|
|
600
|
+
}));
|
|
601
|
+
|
|
602
|
+
const entityLimit = toPositiveInt(
|
|
603
|
+
snapshot.plan.limit,
|
|
604
|
+
DEFAULT_ENTITY_LIMIT,
|
|
605
|
+
MAX_ENTITY_LIMIT
|
|
606
|
+
);
|
|
607
|
+
const rankedEntities = snapshot.plan.includeEntities
|
|
608
|
+
? rankEntities(entityCandidates, snapshot.plan.tokens, entityLimit).map(
|
|
609
|
+
(row) => ({
|
|
610
|
+
nodeId: row.nodeId,
|
|
611
|
+
entityType: row.entityType,
|
|
612
|
+
title: row.title,
|
|
613
|
+
connectedBeliefCount: row.connectedBeliefCount,
|
|
614
|
+
connectedEvidenceCount: row.connectedEvidenceCount,
|
|
615
|
+
score: row.score,
|
|
616
|
+
...(Object.keys(row.metadata).length > 0
|
|
617
|
+
? { metadata: row.metadata }
|
|
618
|
+
: {}),
|
|
619
|
+
})
|
|
620
|
+
)
|
|
621
|
+
: undefined;
|
|
622
|
+
|
|
623
|
+
let failureContext:
|
|
624
|
+
| {
|
|
625
|
+
failures: Array<{
|
|
626
|
+
attemptId: string;
|
|
627
|
+
approach: string;
|
|
628
|
+
outcome: string;
|
|
629
|
+
recordedAt: number;
|
|
630
|
+
score: number;
|
|
631
|
+
}>;
|
|
632
|
+
suppressedIds: string[];
|
|
633
|
+
}
|
|
634
|
+
| undefined;
|
|
635
|
+
|
|
636
|
+
if (snapshot.plan.includeFailures && snapshot.failures) {
|
|
637
|
+
const allFailures = snapshot.failures.filter((node) => {
|
|
638
|
+
const metadata = (node.metadata || {}) as Record<string, unknown>;
|
|
639
|
+
return metadata.failedApproach === true || metadata.isFailedAttempt === true;
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
const rankedFailures = rankContextSection(
|
|
643
|
+
"recentEvidence",
|
|
644
|
+
allFailures.map((node) => ({
|
|
645
|
+
id: String(node._id),
|
|
646
|
+
text: String(node.canonicalText || ""),
|
|
647
|
+
createdAt: node.createdAt || null,
|
|
648
|
+
updatedAt: node.updatedAt || node.createdAt || null,
|
|
649
|
+
})),
|
|
650
|
+
snapshot.plan.tokens,
|
|
651
|
+
10,
|
|
652
|
+
snapshot.plan.rankingProfile,
|
|
653
|
+
rankOptions
|
|
654
|
+
);
|
|
655
|
+
|
|
656
|
+
const failures = rankedFailures.map((row) => {
|
|
657
|
+
const original = allFailures.find((node) => String(node._id) === row.id);
|
|
658
|
+
const metadata = (original?.metadata || {}) as Record<string, unknown>;
|
|
659
|
+
return {
|
|
660
|
+
attemptId: row.id,
|
|
661
|
+
approach: String(row.text || ""),
|
|
662
|
+
outcome: String(metadata.errorMessage || "Failed"),
|
|
663
|
+
recordedAt: (row.createdAt as number) || referenceTimeMs || 0,
|
|
664
|
+
score: row.score,
|
|
665
|
+
};
|
|
666
|
+
});
|
|
667
|
+
|
|
668
|
+
const failureTexts = new Set(
|
|
669
|
+
failures.map((failure) => failure.approach.toLowerCase().slice(0, 100))
|
|
670
|
+
);
|
|
671
|
+
const suppressionIds = new Set<string>();
|
|
672
|
+
|
|
673
|
+
if (snapshot.plan.sessionId && failureTexts.size > 0) {
|
|
674
|
+
for (const evidenceRow of recentEvidence) {
|
|
675
|
+
const evidenceText = evidenceRow.canonicalText.toLowerCase().slice(0, 100);
|
|
676
|
+
for (const failureText of failureTexts) {
|
|
677
|
+
if (
|
|
678
|
+
evidenceText.includes(failureText) ||
|
|
679
|
+
failureText.includes(evidenceText)
|
|
680
|
+
) {
|
|
681
|
+
suppressionIds.add(evidenceRow.nodeId);
|
|
682
|
+
break;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
if (failures.length > 0) {
|
|
689
|
+
failureContext = {
|
|
690
|
+
failures,
|
|
691
|
+
suppressedIds: Array.from(suppressionIds),
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
const suppressionSet = new Set(failureContext?.suppressedIds || []);
|
|
697
|
+
const effectiveEvidence =
|
|
698
|
+
suppressionSet.size > 0
|
|
699
|
+
? recentEvidence.filter((row) => !suppressionSet.has(row.nodeId))
|
|
700
|
+
: recentEvidence;
|
|
701
|
+
const suppressedEvidenceIds =
|
|
702
|
+
suppressionSet.size > 0
|
|
703
|
+
? recentEvidence
|
|
704
|
+
.filter((row) => suppressionSet.has(row.nodeId))
|
|
705
|
+
.map((row) => row.nodeId)
|
|
706
|
+
: [];
|
|
707
|
+
|
|
708
|
+
const summary = {
|
|
709
|
+
totalBeliefs: uniqueBeliefs.length,
|
|
710
|
+
invariants: invariants.length,
|
|
711
|
+
openQuestions: openQuestions.length,
|
|
712
|
+
evidenceItems: uniqueEvidence.length,
|
|
713
|
+
contradictions: contradictions.length,
|
|
714
|
+
...(rankedEntities ? { relatedEntities: rankedEntities.length } : {}),
|
|
715
|
+
scopedTopics: snapshot.plan.scopedTopicIds.length,
|
|
716
|
+
descendantDepth: snapshot.plan.descendantDepth,
|
|
717
|
+
query: snapshot.plan.queryText || null,
|
|
718
|
+
};
|
|
719
|
+
|
|
720
|
+
const injectionPolicy = buildInjectionPlan({
|
|
721
|
+
tokenBudget: snapshot.plan.tokenBudget,
|
|
722
|
+
invariants: invariants.map((row) => ({
|
|
723
|
+
nodeId: row.nodeId,
|
|
724
|
+
canonicalText: row.canonicalText,
|
|
725
|
+
score: row.score,
|
|
726
|
+
})),
|
|
727
|
+
activeBeliefs: activeBeliefs.map((row) => ({
|
|
728
|
+
nodeId: row.nodeId,
|
|
729
|
+
canonicalText: row.canonicalText,
|
|
730
|
+
score: row.score,
|
|
731
|
+
})),
|
|
732
|
+
openQuestions: openQuestions.map((row) => ({
|
|
733
|
+
questionId: row.questionId,
|
|
734
|
+
text: row.text,
|
|
735
|
+
score: row.score,
|
|
736
|
+
})),
|
|
737
|
+
recentEvidence: effectiveEvidence.map((row) => ({
|
|
738
|
+
nodeId: row.nodeId,
|
|
739
|
+
canonicalText: row.canonicalText,
|
|
740
|
+
score: row.score,
|
|
741
|
+
})),
|
|
742
|
+
contradictions: contradictions.map((row) => ({
|
|
743
|
+
contradictionId: row.contradictionId,
|
|
744
|
+
description: row.description,
|
|
745
|
+
score: row.score,
|
|
746
|
+
})),
|
|
747
|
+
trackExclusions: snapshot.plan.compilationMode === "delta",
|
|
748
|
+
});
|
|
749
|
+
|
|
750
|
+
const contextNarrative = [
|
|
751
|
+
"Prefer invariant beliefs as hard constraints while reasoning over this scope.",
|
|
752
|
+
"Treat open questions as unresolved work items and avoid claiming closure without evidence.",
|
|
753
|
+
"Use recent evidence for implementation context before creating new beliefs.",
|
|
754
|
+
"When contradictions exist, resolve explicitly (fork, lower confidence, or gather counter-evidence).",
|
|
755
|
+
`Apply injection token budget of ${injectionPolicy.tokenBudget} with section quotas before prompt assembly.`,
|
|
756
|
+
];
|
|
757
|
+
|
|
758
|
+
const deltaReport: ContextPackDeltaReport | undefined =
|
|
759
|
+
snapshot.plan.compilationMode === "delta" && snapshot.plan.worktreeId
|
|
760
|
+
? {
|
|
761
|
+
changedItems: [] as ContextPackDeltaReport["changedItems"],
|
|
762
|
+
verificationObligations:
|
|
763
|
+
[] as ContextPackDeltaReport["verificationObligations"],
|
|
764
|
+
referencePoint: snapshot.plan.worktreeId,
|
|
765
|
+
}
|
|
766
|
+
: undefined;
|
|
767
|
+
|
|
768
|
+
const excludedItems = [
|
|
769
|
+
...(injectionPolicy.excludedItems || []),
|
|
770
|
+
...suppressedEvidenceIds.map((id) => ({
|
|
771
|
+
id,
|
|
772
|
+
section: "recentEvidence" as const,
|
|
773
|
+
reason: "anti_repetition" as const,
|
|
774
|
+
score: recentEvidence.find((row) => row.nodeId === id)?.score ?? 0,
|
|
775
|
+
})),
|
|
776
|
+
];
|
|
777
|
+
|
|
778
|
+
const result = {
|
|
779
|
+
schemaVersion: CONTEXT_PACK_SCHEMA_VERSION,
|
|
780
|
+
topicId: snapshot.plan.topicId,
|
|
781
|
+
topicName: snapshot.topic.name || "Untitled Topic",
|
|
782
|
+
scopedTopicIds: snapshot.plan.scopedTopicIds,
|
|
783
|
+
generatedAt: referenceTimeMs,
|
|
784
|
+
rankingProfile: snapshot.plan.rankingProfile,
|
|
785
|
+
summary,
|
|
786
|
+
invariants,
|
|
787
|
+
activeBeliefs,
|
|
788
|
+
openQuestions,
|
|
789
|
+
recentEvidence: effectiveEvidence,
|
|
790
|
+
contradictions,
|
|
791
|
+
...(rankedEntities ? { relatedEntities: rankedEntities } : {}),
|
|
792
|
+
contextNarrative,
|
|
793
|
+
injectionPolicy: {
|
|
794
|
+
...injectionPolicy,
|
|
795
|
+
...(excludedItems.length > 0 ? { excludedItems } : {}),
|
|
796
|
+
},
|
|
797
|
+
diagnostics: {
|
|
798
|
+
itemsScored:
|
|
799
|
+
invariantCandidates.length +
|
|
800
|
+
activeBeliefCandidates.length +
|
|
801
|
+
openQuestionCandidates.length +
|
|
802
|
+
evidenceCandidates.length +
|
|
803
|
+
contradictionCandidates.length +
|
|
804
|
+
entityCandidates.length,
|
|
805
|
+
tokenBudgetUtilization:
|
|
806
|
+
injectionPolicy.tokenBudget === 0
|
|
807
|
+
? 0
|
|
808
|
+
: Number(
|
|
809
|
+
(
|
|
810
|
+
injectionPolicy.estimatedTokens / injectionPolicy.tokenBudget
|
|
811
|
+
).toFixed(4)
|
|
812
|
+
),
|
|
813
|
+
referenceTimeMs,
|
|
814
|
+
},
|
|
815
|
+
...(snapshot.plan.compilationMode !== "standard"
|
|
816
|
+
? { compilationMode: snapshot.plan.compilationMode }
|
|
817
|
+
: {}),
|
|
818
|
+
...(failureContext ? { failureContext } : {}),
|
|
819
|
+
...(deltaReport ? { deltaReport } : {}),
|
|
820
|
+
...(snapshot.plan.packWeightOverrides &&
|
|
821
|
+
snapshot.plan.packWeightOverrides.length > 0
|
|
822
|
+
? { appliedWeightOverrides: snapshot.plan.packWeightOverrides }
|
|
823
|
+
: {}),
|
|
824
|
+
};
|
|
825
|
+
|
|
826
|
+
assertContextPackSchema(result);
|
|
827
|
+
return result as ContextPackV1;
|
|
828
|
+
}
|