@lucern/sdk 0.2.0-alpha.13 → 0.2.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +166 -609
- package/dist/index.js +3539 -6269
- package/dist/index.js.map +1 -1
- package/dist/{contracts → lucern/contracts/src}/auth-session.contract.d.ts +12 -14
- package/dist/{contracts → lucern/contracts/src}/context-pack.contract.d.ts +58 -56
- package/dist/{contracts → lucern/contracts/src}/lens-filter.contract.d.ts +8 -10
- package/dist/lucern/contracts/src/lens-workflow.contract.d.ts +84 -0
- package/dist/lucern/contracts/src/mcp-tools.contract.d.ts +151 -0
- package/dist/lucern/contracts/src/workflow-runtime.contract.d.ts +161 -0
- package/dist/lucern/mcp-server/src/context-pack-policy.d.ts +119 -0
- package/dist/lucern/mcp-server/src/context-pack-schema.d.ts +18 -0
- package/dist/lucern/modules/graph-primitives/src/ontology-matching.d.ts +78 -0
- package/dist/lucern/modules/graph-primitives/src/text-matching.d.ts +53 -0
- package/dist/lucern/packages/client-core/src/beliefs.d.ts +30 -0
- package/dist/lucern/packages/client-core/src/context.d.ts +29 -0
- package/dist/lucern/packages/client-core/src/contradictions.d.ts +11 -0
- package/dist/lucern/packages/client-core/src/edges.d.ts +11 -0
- package/dist/lucern/packages/client-core/src/events.d.ts +9 -0
- package/dist/lucern/packages/client-core/src/evidence.d.ts +21 -0
- package/dist/lucern/packages/client-core/src/graph.d.ts +17 -0
- package/dist/lucern/packages/client-core/src/identity.d.ts +7 -0
- package/dist/lucern/packages/client-core/src/ids.d.ts +7 -0
- package/dist/lucern/packages/client-core/src/ontologies.d.ts +13 -0
- package/dist/lucern/packages/client-core/src/questions.d.ts +39 -0
- package/dist/lucern/packages/client-core/src/search.d.ts +7 -0
- package/dist/lucern/packages/client-core/src/tasks.d.ts +13 -0
- package/dist/lucern/packages/client-core/src/topics.d.ts +17 -0
- package/dist/lucern/packages/client-core/src/webhooks.d.ts +35 -0
- package/dist/lucern/packages/client-core/src/worktrees.d.ts +17 -0
- package/dist/lucern/packages/domain-beliefs/src/beliefs.d.ts +283 -0
- package/dist/lucern/packages/domain-beliefs/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-context/src/compile.d.ts +11 -0
- package/dist/{contextPackCompiler.d.ts → lucern/packages/domain-context/src/context-pack-compiler.d.ts} +10 -11
- package/dist/lucern/packages/domain-context/src/index.d.ts +4 -0
- package/dist/lucern/packages/domain-context/src/ports.d.ts +58 -0
- package/dist/lucern/packages/domain-context/src/public-types.d.ts +1 -0
- package/dist/lucern/packages/domain-edges/src/contradictions.d.ts +59 -0
- package/dist/lucern/packages/domain-edges/src/edges.d.ts +91 -0
- package/dist/lucern/packages/domain-edges/src/index.d.ts +2 -0
- package/dist/lucern/packages/domain-evidence/src/evidence.d.ts +115 -0
- package/dist/lucern/packages/domain-evidence/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-graph/src/graph.d.ts +150 -0
- package/dist/lucern/packages/domain-identity/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-identity/src/whoami.d.ts +13 -0
- package/dist/lucern/packages/domain-ontologies/src/ontologies.d.ts +123 -0
- package/dist/lucern/packages/domain-questions/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-questions/src/questions.d.ts +147 -0
- package/dist/lucern/packages/domain-search/src/search.d.ts +97 -0
- package/dist/lucern/packages/domain-tasks/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-tasks/src/tasks.d.ts +102 -0
- package/dist/lucern/packages/domain-topics/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-topics/src/topics.d.ts +147 -0
- package/dist/lucern/packages/domain-worktrees/src/index.d.ts +1 -0
- package/dist/lucern/packages/domain-worktrees/src/worktrees.d.ts +185 -0
- package/dist/lucern/packages/events/src/index.d.ts +4 -0
- package/dist/lucern/packages/events/src/matching.d.ts +3 -0
- package/dist/lucern/packages/events/src/outbox.d.ts +15 -0
- package/dist/lucern/packages/events/src/types.d.ts +151 -0
- package/dist/lucern/packages/events/src/webhooks.d.ts +9 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/beliefs.d.ts +15 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/context.d.ts +12 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/contradictions.d.ts +7 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/edges.d.ts +7 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/events.d.ts +6 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/evidence.d.ts +21 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/graph.d.ts +10 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/identity.d.ts +5 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/ontologies.d.ts +8 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/questions.d.ts +39 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/search.d.ts +5 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/tasks.d.ts +8 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/topics.d.ts +10 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/webhooks.d.ts +16 -0
- package/dist/lucern/packages/sdk-typescript/src/facade/worktrees.d.ts +10 -0
- package/dist/lucern/packages/sdk-typescript/src/index.d.ts +28 -0
- package/dist/packages/sdk/src/adminClient.d.ts +89 -0
- package/dist/packages/sdk/src/answersClient.d.ts +5 -0
- package/dist/{audiencesClient.d.ts → packages/sdk/src/audiencesClient.d.ts} +18 -30
- package/dist/packages/sdk/src/auditClient.d.ts +21 -0
- package/dist/packages/sdk/src/beliefsClient.d.ts +52 -0
- package/dist/packages/sdk/src/client.d.ts +1558 -0
- package/dist/packages/sdk/src/contextClient.d.ts +9 -0
- package/dist/packages/sdk/src/contracts/api-enums.contract.d.ts +58 -0
- package/dist/{controlObjectOwnership.d.ts → packages/sdk/src/controlObjectOwnership.d.ts} +18 -35
- package/dist/{coreClient.d.ts → packages/sdk/src/coreClient.d.ts} +14 -38
- package/dist/packages/sdk/src/customTools.d.ts +65 -0
- package/dist/packages/sdk/src/decisionsClient.d.ts +97 -0
- package/dist/packages/sdk/src/graphClient.d.ts +191 -0
- package/dist/{harnessClient.d.ts → packages/sdk/src/harnessClient.d.ts} +33 -127
- package/dist/packages/sdk/src/identityClient.d.ts +104 -0
- package/dist/packages/sdk/src/index.d.ts +28 -0
- package/dist/packages/sdk/src/learningClient.d.ts +37 -0
- package/dist/{mcpParityClient.d.ts → packages/sdk/src/mcpParityClient.d.ts} +5 -11
- package/dist/packages/sdk/src/mcpParitySurface.d.ts +8 -0
- package/dist/{ontologyClient.d.ts → packages/sdk/src/ontologyClient.d.ts} +22 -44
- package/dist/packages/sdk/src/packsClient.d.ts +101 -0
- package/dist/{policyClient.d.ts → packages/sdk/src/policyClient.d.ts} +18 -113
- package/dist/packages/sdk/src/reportsClient.d.ts +31 -0
- package/dist/packages/sdk/src/schemaClient.d.ts +54 -0
- package/dist/packages/sdk/src/sdkSurface.d.ts +55 -0
- package/dist/packages/sdk/src/topicsClient.d.ts +45 -0
- package/dist/packages/sdk/src/types.d.ts +470 -0
- package/dist/packages/sdk/src/version.d.ts +2 -0
- package/dist/packages/sdk/src/workflowClient.d.ts +252 -0
- package/package.json +37 -92
- package/CHANGELOG.md +0 -13
- package/dist/adminClient.d.ts +0 -409
- package/dist/adminClient.js +0 -755
- package/dist/adminClient.js.map +0 -1
- package/dist/answersClient.d.ts +0 -23
- package/dist/answersClient.js +0 -333
- package/dist/answersClient.js.map +0 -1
- package/dist/audience/index.d.ts +0 -38
- package/dist/audience/index.js +0 -110
- package/dist/audience/index.js.map +0 -1
- package/dist/audiencesClient.js +0 -472
- package/dist/audiencesClient.js.map +0 -1
- package/dist/auditClient.d.ts +0 -29
- package/dist/auditClient.js +0 -386
- package/dist/auditClient.js.map +0 -1
- package/dist/beliefs/index.d.ts +0 -465
- package/dist/beliefs/index.js +0 -6433
- package/dist/beliefs/index.js.map +0 -1
- package/dist/beliefs/lifecycle.d.ts +0 -24
- package/dist/beliefs/lifecycle.js +0 -98
- package/dist/beliefs/lifecycle.js.map +0 -1
- package/dist/beliefsClient.d.ts +0 -241
- package/dist/beliefsClient.js +0 -646
- package/dist/beliefsClient.js.map +0 -1
- package/dist/client.d.ts +0 -2398
- package/dist/client.js +0 -6411
- package/dist/client.js.map +0 -1
- package/dist/contextClient.d.ts +0 -27
- package/dist/contextClient.js +0 -396
- package/dist/contextClient.js.map +0 -1
- package/dist/contextFacade.d.ts +0 -2
- package/dist/contextFacade.js +0 -73
- package/dist/contextFacade.js.map +0 -1
- package/dist/contextPackCompiler.js +0 -1091
- package/dist/contextPackCompiler.js.map +0 -1
- package/dist/contextPackPolicy.d.ts +0 -84
- package/dist/contextPackPolicy.js +0 -347
- package/dist/contextPackPolicy.js.map +0 -1
- package/dist/contextPackSchema.d.ts +0 -7
- package/dist/contextPackSchema.js +0 -203
- package/dist/contextPackSchema.js.map +0 -1
- package/dist/contextTypes.d.ts +0 -135
- package/dist/contextTypes.js +0 -3
- package/dist/contextTypes.js.map +0 -1
- package/dist/contracts/api-enums.contract.d.ts +0 -81
- package/dist/contracts/api-enums.contract.js +0 -98
- package/dist/contracts/api-enums.contract.js.map +0 -1
- package/dist/contracts/auth-session.contract.js +0 -48
- package/dist/contracts/auth-session.contract.js.map +0 -1
- package/dist/contracts/context-pack.contract.js +0 -98
- package/dist/contracts/context-pack.contract.js.map +0 -1
- package/dist/contracts/contextPack.d.ts +0 -1
- package/dist/contracts/contextPack.js +0 -98
- package/dist/contracts/contextPack.js.map +0 -1
- package/dist/contracts/index.d.ts +0 -9
- package/dist/contracts/index.js +0 -4928
- package/dist/contracts/index.js.map +0 -1
- package/dist/contracts/lens-filter.contract.js +0 -71
- package/dist/contracts/lens-filter.contract.js.map +0 -1
- package/dist/contracts/lens-workflow.contract.d.ts +0 -87
- package/dist/contracts/lens-workflow.contract.js +0 -123
- package/dist/contracts/lens-workflow.contract.js.map +0 -1
- package/dist/contracts/lensFilter.d.ts +0 -1
- package/dist/contracts/lensFilter.js +0 -71
- package/dist/contracts/lensFilter.js.map +0 -1
- package/dist/contracts/lensWorkflow.d.ts +0 -2
- package/dist/contracts/lensWorkflow.js +0 -123
- package/dist/contracts/lensWorkflow.js.map +0 -1
- package/dist/contracts/mcp-tools.contract.d.ts +0 -1
- package/dist/contracts/mcp-tools.contract.js +0 -3016
- package/dist/contracts/mcp-tools.contract.js.map +0 -1
- package/dist/contracts/mcpTools.d.ts +0 -1
- package/dist/contracts/mcpTools.js +0 -3016
- package/dist/contracts/mcpTools.js.map +0 -1
- package/dist/contracts/prompt.contract.d.ts +0 -26
- package/dist/contracts/prompt.contract.js +0 -12
- package/dist/contracts/prompt.contract.js.map +0 -1
- package/dist/contracts/prompt.d.ts +0 -1
- package/dist/contracts/prompt.js +0 -12
- package/dist/contracts/prompt.js.map +0 -1
- package/dist/contracts/sdk-tools.contract.d.ts +0 -2
- package/dist/contracts/sdk-tools.contract.js +0 -4164
- package/dist/contracts/sdk-tools.contract.js.map +0 -1
- package/dist/contracts/sdkTools.d.ts +0 -2
- package/dist/contracts/sdkTools.js +0 -4164
- package/dist/contracts/sdkTools.js.map +0 -1
- package/dist/contracts/workflow-runtime.contract.d.ts +0 -163
- package/dist/contracts/workflow-runtime.contract.js +0 -245
- package/dist/contracts/workflow-runtime.contract.js.map +0 -1
- package/dist/contracts/workflowRuntime.d.ts +0 -1
- package/dist/contracts/workflowRuntime.js +0 -245
- package/dist/contracts/workflowRuntime.js.map +0 -1
- package/dist/contradictions/index.d.ts +0 -158
- package/dist/contradictions/index.js +0 -6427
- package/dist/contradictions/index.js.map +0 -1
- package/dist/controlObjectOwnership.js +0 -215
- package/dist/controlObjectOwnership.js.map +0 -1
- package/dist/coreClient.js +0 -339
- package/dist/coreClient.js.map +0 -1
- package/dist/customTools.d.ts +0 -88
- package/dist/customTools.js +0 -248
- package/dist/customTools.js.map +0 -1
- package/dist/decisions/index.d.ts +0 -68
- package/dist/decisions/index.js +0 -6429
- package/dist/decisions/index.js.map +0 -1
- package/dist/decisionsClient.d.ts +0 -111
- package/dist/decisionsClient.js +0 -522
- package/dist/decisionsClient.js.map +0 -1
- package/dist/domainContext.d.ts +0 -1
- package/dist/domainContext.js +0 -3
- package/dist/domainContext.js.map +0 -1
- package/dist/edges/index.d.ts +0 -204
- package/dist/edges/index.js +0 -6428
- package/dist/edges/index.js.map +0 -1
- package/dist/events.d.ts +0 -178
- package/dist/events.js +0 -251
- package/dist/events.js.map +0 -1
- package/dist/eventsCore.d.ts +0 -49
- package/dist/eventsCore.js +0 -429
- package/dist/eventsCore.js.map +0 -1
- package/dist/evidence/index.d.ts +0 -295
- package/dist/evidence/index.js +0 -6428
- package/dist/evidence/index.js.map +0 -1
- package/dist/evidenceClient.d.ts +0 -119
- package/dist/evidenceClient.js +0 -350
- package/dist/evidenceClient.js.map +0 -1
- package/dist/facade/context.d.ts +0 -18
- package/dist/facade/context.js +0 -73
- package/dist/facade/context.js.map +0 -1
- package/dist/gatewayFacades.d.ts +0 -589
- package/dist/gatewayFacades.js +0 -2006
- package/dist/gatewayFacades.js.map +0 -1
- package/dist/graphClient.d.ts +0 -271
- package/dist/graphClient.js +0 -698
- package/dist/graphClient.js.map +0 -1
- package/dist/harnessClient.js +0 -607
- package/dist/harnessClient.js.map +0 -1
- package/dist/identityClient.d.ts +0 -140
- package/dist/identityClient.js +0 -497
- package/dist/identityClient.js.map +0 -1
- package/dist/index.d.ts +0 -45
- package/dist/learningClient.d.ts +0 -46
- package/dist/learningClient.js +0 -409
- package/dist/learningClient.js.map +0 -1
- package/dist/lenses/index.d.ts +0 -194
- package/dist/lenses/index.js +0 -6427
- package/dist/lenses/index.js.map +0 -1
- package/dist/mcpParityClient.js +0 -516
- package/dist/mcpParityClient.js.map +0 -1
- package/dist/mcpParitySurface.d.ts +0 -12
- package/dist/mcpParitySurface.js +0 -65
- package/dist/mcpParitySurface.js.map +0 -1
- package/dist/mcpTools-DPZxowDX.d.ts +0 -254
- package/dist/nodes/index.d.ts +0 -62
- package/dist/nodes/index.js +0 -6429
- package/dist/nodes/index.js.map +0 -1
- package/dist/ontologies/index.d.ts +0 -178
- package/dist/ontologies/index.js +0 -6430
- package/dist/ontologies/index.js.map +0 -1
- package/dist/ontologyClient.js +0 -513
- package/dist/ontologyClient.js.map +0 -1
- package/dist/opinion.d.ts +0 -11
- package/dist/opinion.js +0 -35
- package/dist/opinion.js.map +0 -1
- package/dist/packRuntime.d.ts +0 -2
- package/dist/packRuntime.js +0 -3
- package/dist/packRuntime.js.map +0 -1
- package/dist/packsClient.d.ts +0 -131
- package/dist/packsClient.js +0 -525
- package/dist/packsClient.js.map +0 -1
- package/dist/policyClient.js +0 -625
- package/dist/policyClient.js.map +0 -1
- package/dist/questions/index.d.ts +0 -297
- package/dist/questions/index.js +0 -6430
- package/dist/questions/index.js.map +0 -1
- package/dist/realtime/index.d.ts +0 -29
- package/dist/realtime/index.js +0 -23
- package/dist/realtime/index.js.map +0 -1
- package/dist/realtime/refs.d.ts +0 -17
- package/dist/realtime/refs.js +0 -9
- package/dist/realtime/refs.js.map +0 -1
- package/dist/reportsClient.d.ts +0 -41
- package/dist/reportsClient.js +0 -418
- package/dist/reportsClient.js.map +0 -1
- package/dist/schemaClient.d.ts +0 -64
- package/dist/schemaClient.js +0 -434
- package/dist/schemaClient.js.map +0 -1
- package/dist/sdkSurface.d.ts +0 -61
- package/dist/sdkSurface.js +0 -112
- package/dist/sdkSurface.js.map +0 -1
- package/dist/sdkTools-CwXJDACb.d.ts +0 -150
- package/dist/sourcesClient.d.ts +0 -24
- package/dist/sourcesClient.js +0 -339
- package/dist/sourcesClient.js.map +0 -1
- package/dist/topics/index.d.ts +0 -68
- package/dist/topics/index.js +0 -6428
- package/dist/topics/index.js.map +0 -1
- package/dist/topicsClient.d.ts +0 -84
- package/dist/topicsClient.js +0 -492
- package/dist/topicsClient.js.map +0 -1
- package/dist/types.d.ts +0 -715
- package/dist/types.js +0 -3
- package/dist/types.js.map +0 -1
- package/dist/version.d.ts +0 -4
- package/dist/version.js +0 -6
- package/dist/version.js.map +0 -1
- package/dist/workflowClient.d.ts +0 -316
- package/dist/workflowClient.js +0 -830
- package/dist/workflowClient.js.map +0 -1
- package/dist/worktrees/index.d.ts +0 -210
- package/dist/worktrees/index.js +0 -6430
- package/dist/worktrees/index.js.map +0 -1
|
@@ -1,1091 +0,0 @@
|
|
|
1
|
-
// src/contracts/context-pack.contract.ts
|
|
2
|
-
var CONTEXT_PACK_SCHEMA_VERSION = "1.0.0";
|
|
3
|
-
var DEFAULT_COMPILATION_MODE = "standard";
|
|
4
|
-
var SECTION_BUDGET_RATIOS = {
|
|
5
|
-
invariants: 0.28,
|
|
6
|
-
activeBeliefs: 0.3,
|
|
7
|
-
openQuestions: 0.17,
|
|
8
|
-
recentEvidence: 0.17,
|
|
9
|
-
contradictions: 0.08
|
|
10
|
-
};
|
|
11
|
-
var MIN_TOKEN_BUDGET = 400;
|
|
12
|
-
var MAX_TOKEN_BUDGET = 8e3;
|
|
13
|
-
var DEFAULT_TOKEN_BUDGET = 1800;
|
|
14
|
-
var MIN_CONTRADICTION_BUDGET = 40;
|
|
15
|
-
var RANKING_WEIGHTS = {
|
|
16
|
-
invariants: {
|
|
17
|
-
query: 0.35,
|
|
18
|
-
recency: 0.1,
|
|
19
|
-
confidence: 0.4,
|
|
20
|
-
beliefType: 0.15
|
|
21
|
-
},
|
|
22
|
-
activeBeliefs: {
|
|
23
|
-
query: 0.5,
|
|
24
|
-
recency: 0.2,
|
|
25
|
-
confidence: 0.2,
|
|
26
|
-
beliefType: 0.1
|
|
27
|
-
},
|
|
28
|
-
openQuestions: {
|
|
29
|
-
query: 0.55,
|
|
30
|
-
recency: 0.2,
|
|
31
|
-
priority: 0.25
|
|
32
|
-
},
|
|
33
|
-
recentEvidence: {
|
|
34
|
-
query: 0.6,
|
|
35
|
-
recency: 0.4
|
|
36
|
-
},
|
|
37
|
-
contradictions: {
|
|
38
|
-
query: 0.4,
|
|
39
|
-
recency: 0.2,
|
|
40
|
-
severity: 0.4
|
|
41
|
-
}
|
|
42
|
-
};
|
|
43
|
-
var RECENCY_HALF_LIFE_DAYS = 30;
|
|
44
|
-
var ENTITY_RANKING_WEIGHTS = {
|
|
45
|
-
query: 0.4,
|
|
46
|
-
connectivity: 0.6
|
|
47
|
-
};
|
|
48
|
-
var DEFAULT_ENTITY_LIMIT = 10;
|
|
49
|
-
var MAX_ENTITY_LIMIT = 50;
|
|
50
|
-
var BELIEF_TYPE_BONUS = {
|
|
51
|
-
invariant: 1,
|
|
52
|
-
tenet: 0.8,
|
|
53
|
-
principle: 0.6
|
|
54
|
-
};
|
|
55
|
-
var DEFAULT_BELIEF_TYPE_BONUS = 0.4;
|
|
56
|
-
var PRIORITY_SCORES = {
|
|
57
|
-
critical: 1,
|
|
58
|
-
high: 0.85,
|
|
59
|
-
medium: 0.55,
|
|
60
|
-
low: 0.35
|
|
61
|
-
};
|
|
62
|
-
var DEFAULT_PRIORITY_SCORE = 0.5;
|
|
63
|
-
var SEVERITY_SCORES = {
|
|
64
|
-
critical: 1,
|
|
65
|
-
high: 0.85,
|
|
66
|
-
medium: 0.6,
|
|
67
|
-
low: 0.35
|
|
68
|
-
};
|
|
69
|
-
var DEFAULT_SEVERITY_SCORE = 0.5;
|
|
70
|
-
var TOKENS_PER_WORD = 1.35;
|
|
71
|
-
var MIN_TOKEN_ESTIMATE = 8;
|
|
72
|
-
|
|
73
|
-
// src/contextPackPolicy.ts
|
|
74
|
-
function nowMs() {
|
|
75
|
-
return Date.now();
|
|
76
|
-
}
|
|
77
|
-
function normalizeText(text) {
|
|
78
|
-
return text.trim().toLowerCase();
|
|
79
|
-
}
|
|
80
|
-
function tokenHits(text, tokens) {
|
|
81
|
-
if (tokens.length === 0) {
|
|
82
|
-
return 1;
|
|
83
|
-
}
|
|
84
|
-
const haystack = normalizeText(text);
|
|
85
|
-
let hits = 0;
|
|
86
|
-
for (const token of tokens) {
|
|
87
|
-
if (haystack.includes(token)) {
|
|
88
|
-
hits += 1;
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
return hits;
|
|
92
|
-
}
|
|
93
|
-
function clamp01(value) {
|
|
94
|
-
if (!Number.isFinite(value)) {
|
|
95
|
-
return 0;
|
|
96
|
-
}
|
|
97
|
-
return Math.max(0, Math.min(1, value));
|
|
98
|
-
}
|
|
99
|
-
function recencyScore(updatedAt, referenceTimeMs = nowMs()) {
|
|
100
|
-
if (!updatedAt || !Number.isFinite(updatedAt)) {
|
|
101
|
-
return 0.25;
|
|
102
|
-
}
|
|
103
|
-
const ageMs = Math.max(0, referenceTimeMs - updatedAt);
|
|
104
|
-
const ageDays = ageMs / (1e3 * 60 * 60 * 24);
|
|
105
|
-
const decay = 0.5 ** (ageDays / RECENCY_HALF_LIFE_DAYS);
|
|
106
|
-
return clamp01(decay);
|
|
107
|
-
}
|
|
108
|
-
function confidenceScore(confidence) {
|
|
109
|
-
if (typeof confidence !== "number" || !Number.isFinite(confidence)) {
|
|
110
|
-
return 0.5;
|
|
111
|
-
}
|
|
112
|
-
return clamp01(confidence);
|
|
113
|
-
}
|
|
114
|
-
function priorityScore(priority) {
|
|
115
|
-
const value = normalizeText(priority || "");
|
|
116
|
-
return PRIORITY_SCORES[value] ?? DEFAULT_PRIORITY_SCORE;
|
|
117
|
-
}
|
|
118
|
-
function severityScore(severity) {
|
|
119
|
-
const value = normalizeText(severity || "");
|
|
120
|
-
return SEVERITY_SCORES[value] ?? DEFAULT_SEVERITY_SCORE;
|
|
121
|
-
}
|
|
122
|
-
function beliefTypeBonus(beliefType) {
|
|
123
|
-
const value = normalizeText(beliefType || "");
|
|
124
|
-
return BELIEF_TYPE_BONUS[value] ?? DEFAULT_BELIEF_TYPE_BONUS;
|
|
125
|
-
}
|
|
126
|
-
function resolveEffectiveWeights(overrides) {
|
|
127
|
-
if (!overrides || overrides.length === 0) {
|
|
128
|
-
return RANKING_WEIGHTS;
|
|
129
|
-
}
|
|
130
|
-
const result = { ...RANKING_WEIGHTS };
|
|
131
|
-
for (const override of overrides) {
|
|
132
|
-
const base = RANKING_WEIGHTS[override.section];
|
|
133
|
-
if (base) {
|
|
134
|
-
result[override.section] = { ...base, ...override.weights };
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
return result;
|
|
138
|
-
}
|
|
139
|
-
function generateJustification(_section, candidate, queryTokens, weights) {
|
|
140
|
-
const parts = [];
|
|
141
|
-
const hits = tokenHits(candidate.text, queryTokens);
|
|
142
|
-
if (queryTokens.length > 0 && hits > 0) {
|
|
143
|
-
parts.push(`${hits}/${queryTokens.length} query terms matched`);
|
|
144
|
-
} else if (queryTokens.length === 0) {
|
|
145
|
-
parts.push("no query filter");
|
|
146
|
-
}
|
|
147
|
-
const ts = candidate.updatedAt || candidate.createdAt || null;
|
|
148
|
-
if (ts && Number.isFinite(ts)) {
|
|
149
|
-
const ageDays = Math.max(0, nowMs() - ts) / (1e3 * 60 * 60 * 24);
|
|
150
|
-
if (ageDays < 1) {
|
|
151
|
-
parts.push("updated today");
|
|
152
|
-
} else if (ageDays < 7) {
|
|
153
|
-
parts.push(`updated ${Math.floor(ageDays)}d ago`);
|
|
154
|
-
} else if (ageDays < 30) {
|
|
155
|
-
parts.push(`updated ${Math.floor(ageDays / 7)}w ago`);
|
|
156
|
-
} else {
|
|
157
|
-
parts.push(`updated ${Math.floor(ageDays)}d ago (decayed)`);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
if (weights.confidence !== void 0 && candidate.confidence !== null && candidate.confidence !== void 0) {
|
|
161
|
-
parts.push(`confidence=${candidate.confidence.toFixed(2)}`);
|
|
162
|
-
}
|
|
163
|
-
if (weights.beliefType !== void 0 && candidate.beliefType) {
|
|
164
|
-
parts.push(`type=${candidate.beliefType}`);
|
|
165
|
-
}
|
|
166
|
-
if (weights.priority !== void 0 && candidate.priority) {
|
|
167
|
-
parts.push(`priority=${candidate.priority}`);
|
|
168
|
-
}
|
|
169
|
-
if (weights.severity !== void 0 && candidate.severity) {
|
|
170
|
-
parts.push(`severity=${candidate.severity}`);
|
|
171
|
-
}
|
|
172
|
-
return parts.join(", ");
|
|
173
|
-
}
|
|
174
|
-
function computeBaselineScore(candidate, queryTokens) {
|
|
175
|
-
const hits = tokenHits(candidate.text, queryTokens);
|
|
176
|
-
return queryTokens.length === 0 ? 1 : hits;
|
|
177
|
-
}
|
|
178
|
-
function computeWeightedScore(section, candidate, queryTokens, effectiveWeights, referenceTimeMs) {
|
|
179
|
-
const weights = (effectiveWeights ?? RANKING_WEIGHTS)[section];
|
|
180
|
-
const queryComponent = queryTokens.length === 0 ? 0.4 : clamp01(tokenHits(candidate.text, queryTokens) / queryTokens.length);
|
|
181
|
-
const recencyComponent = recencyScore(
|
|
182
|
-
candidate.updatedAt || candidate.createdAt || null,
|
|
183
|
-
referenceTimeMs
|
|
184
|
-
);
|
|
185
|
-
let score = queryComponent * weights.query + recencyComponent * weights.recency;
|
|
186
|
-
if (weights.confidence !== void 0) {
|
|
187
|
-
score += confidenceScore(candidate.confidence) * weights.confidence;
|
|
188
|
-
}
|
|
189
|
-
if (weights.beliefType !== void 0) {
|
|
190
|
-
score += beliefTypeBonus(candidate.beliefType) * weights.beliefType;
|
|
191
|
-
}
|
|
192
|
-
if (weights.priority !== void 0) {
|
|
193
|
-
score += priorityScore(candidate.priority) * weights.priority;
|
|
194
|
-
}
|
|
195
|
-
if (weights.severity !== void 0) {
|
|
196
|
-
score += severityScore(candidate.severity) * weights.severity;
|
|
197
|
-
}
|
|
198
|
-
return score;
|
|
199
|
-
}
|
|
200
|
-
function rankContextSection(section, rows, queryTokens, limit, profile, options) {
|
|
201
|
-
const effectiveWeights = options?.effectiveWeights;
|
|
202
|
-
const includeJustifications = options?.includeJustifications ?? false;
|
|
203
|
-
const referenceTimeMs = options?.referenceTimeMs;
|
|
204
|
-
const scored = rows.map((row) => {
|
|
205
|
-
const score = profile === "weighted_v1" ? computeWeightedScore(
|
|
206
|
-
section,
|
|
207
|
-
row,
|
|
208
|
-
queryTokens,
|
|
209
|
-
effectiveWeights,
|
|
210
|
-
referenceTimeMs
|
|
211
|
-
) : computeBaselineScore(row, queryTokens);
|
|
212
|
-
const result = { ...row, score };
|
|
213
|
-
if (includeJustifications && profile === "weighted_v1") {
|
|
214
|
-
const weights = (effectiveWeights ?? RANKING_WEIGHTS)[section];
|
|
215
|
-
result.justification = generateJustification(section, row, queryTokens, weights);
|
|
216
|
-
}
|
|
217
|
-
return result;
|
|
218
|
-
});
|
|
219
|
-
const filtered = queryTokens.length === 0 ? scored : scored.filter((row) => row.score > 0);
|
|
220
|
-
filtered.sort((left, right) => {
|
|
221
|
-
if (right.score !== left.score) {
|
|
222
|
-
return right.score - left.score;
|
|
223
|
-
}
|
|
224
|
-
const rightTs = right.updatedAt || right.createdAt || 0;
|
|
225
|
-
const leftTs = left.updatedAt || left.createdAt || 0;
|
|
226
|
-
return rightTs - leftTs;
|
|
227
|
-
});
|
|
228
|
-
return filtered.slice(0, limit);
|
|
229
|
-
}
|
|
230
|
-
function parseTokenBudget(value, fallback = DEFAULT_TOKEN_BUDGET) {
|
|
231
|
-
const parsed = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : fallback;
|
|
232
|
-
return Math.max(MIN_TOKEN_BUDGET, Math.min(MAX_TOKEN_BUDGET, parsed));
|
|
233
|
-
}
|
|
234
|
-
function estimateTokens(text) {
|
|
235
|
-
const words = text.trim().split(/\s+/).filter(Boolean).length;
|
|
236
|
-
return Math.max(MIN_TOKEN_ESTIMATE, Math.ceil(words * TOKENS_PER_WORD));
|
|
237
|
-
}
|
|
238
|
-
function buildInjectionPlan(args) {
|
|
239
|
-
const tokenBudget = parseTokenBudget(args.tokenBudget);
|
|
240
|
-
const trackExclusions = args.trackExclusions ?? false;
|
|
241
|
-
const sectionBudgets = {
|
|
242
|
-
invariants: Math.floor(tokenBudget * SECTION_BUDGET_RATIOS.invariants),
|
|
243
|
-
activeBeliefs: Math.floor(
|
|
244
|
-
tokenBudget * SECTION_BUDGET_RATIOS.activeBeliefs
|
|
245
|
-
),
|
|
246
|
-
openQuestions: Math.floor(
|
|
247
|
-
tokenBudget * SECTION_BUDGET_RATIOS.openQuestions
|
|
248
|
-
),
|
|
249
|
-
recentEvidence: Math.floor(
|
|
250
|
-
tokenBudget * SECTION_BUDGET_RATIOS.recentEvidence
|
|
251
|
-
),
|
|
252
|
-
contradictions: Math.max(
|
|
253
|
-
MIN_CONTRADICTION_BUDGET,
|
|
254
|
-
Math.floor(tokenBudget * SECTION_BUDGET_RATIOS.contradictions)
|
|
255
|
-
)
|
|
256
|
-
};
|
|
257
|
-
const selected = {
|
|
258
|
-
invariants: [],
|
|
259
|
-
activeBeliefs: [],
|
|
260
|
-
openQuestions: [],
|
|
261
|
-
recentEvidence: [],
|
|
262
|
-
contradictions: []
|
|
263
|
-
};
|
|
264
|
-
const sectionUsage = {
|
|
265
|
-
invariants: 0,
|
|
266
|
-
activeBeliefs: 0,
|
|
267
|
-
openQuestions: 0,
|
|
268
|
-
recentEvidence: 0,
|
|
269
|
-
contradictions: 0
|
|
270
|
-
};
|
|
271
|
-
const excludedItems = [];
|
|
272
|
-
const pushItem = (section, id, text, score) => {
|
|
273
|
-
const itemTokens = estimateTokens(text);
|
|
274
|
-
const nextUsage = sectionUsage[section] + itemTokens;
|
|
275
|
-
if (nextUsage > sectionBudgets[section]) {
|
|
276
|
-
if (trackExclusions) {
|
|
277
|
-
excludedItems.push({
|
|
278
|
-
id,
|
|
279
|
-
section,
|
|
280
|
-
reason: "budget_exceeded",
|
|
281
|
-
score: score ?? 0
|
|
282
|
-
});
|
|
283
|
-
}
|
|
284
|
-
return;
|
|
285
|
-
}
|
|
286
|
-
selected[section].push(id);
|
|
287
|
-
sectionUsage[section] = nextUsage;
|
|
288
|
-
};
|
|
289
|
-
for (const row of args.invariants) {
|
|
290
|
-
pushItem("invariants", row.nodeId, row.canonicalText, row.score);
|
|
291
|
-
}
|
|
292
|
-
for (const row of args.activeBeliefs) {
|
|
293
|
-
pushItem("activeBeliefs", row.nodeId, row.canonicalText, row.score);
|
|
294
|
-
}
|
|
295
|
-
for (const row of args.openQuestions) {
|
|
296
|
-
pushItem("openQuestions", row.questionId, row.text, row.score);
|
|
297
|
-
}
|
|
298
|
-
for (const row of args.recentEvidence) {
|
|
299
|
-
pushItem("recentEvidence", row.nodeId, row.canonicalText, row.score);
|
|
300
|
-
}
|
|
301
|
-
for (const row of args.contradictions) {
|
|
302
|
-
pushItem("contradictions", row.contradictionId, row.description, row.score);
|
|
303
|
-
}
|
|
304
|
-
const estimatedTokens = sectionUsage.invariants + sectionUsage.activeBeliefs + sectionUsage.openQuestions + sectionUsage.recentEvidence + sectionUsage.contradictions;
|
|
305
|
-
return {
|
|
306
|
-
tokenBudget,
|
|
307
|
-
estimatedTokens,
|
|
308
|
-
sectionBudgets,
|
|
309
|
-
sectionUsage,
|
|
310
|
-
selected,
|
|
311
|
-
...trackExclusions ? { excludedItems } : {}
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
function rankEntities(candidates, queryTokens, limit) {
|
|
315
|
-
if (candidates.length === 0) {
|
|
316
|
-
return [];
|
|
317
|
-
}
|
|
318
|
-
const effectiveLimit = Math.max(
|
|
319
|
-
1,
|
|
320
|
-
Math.min(limit ?? DEFAULT_ENTITY_LIMIT, MAX_ENTITY_LIMIT)
|
|
321
|
-
);
|
|
322
|
-
const maxConnections = Math.max(
|
|
323
|
-
1,
|
|
324
|
-
...candidates.map(
|
|
325
|
-
(candidate) => candidate.connectedBeliefCount + candidate.connectedEvidenceCount
|
|
326
|
-
)
|
|
327
|
-
);
|
|
328
|
-
const scored = candidates.map((candidate) => {
|
|
329
|
-
const searchText = `${candidate.title} ${candidate.entityType} ${candidate.canonicalText}`;
|
|
330
|
-
const queryScore = queryTokens.length === 0 ? 0.4 : clamp01(tokenHits(searchText, queryTokens) / queryTokens.length);
|
|
331
|
-
const totalConnections = candidate.connectedBeliefCount + candidate.connectedEvidenceCount;
|
|
332
|
-
const connectivityScore = clamp01(totalConnections / maxConnections);
|
|
333
|
-
const score = queryScore * ENTITY_RANKING_WEIGHTS.query + connectivityScore * ENTITY_RANKING_WEIGHTS.connectivity;
|
|
334
|
-
return { ...candidate, score };
|
|
335
|
-
});
|
|
336
|
-
scored.sort((left, right) => {
|
|
337
|
-
if (right.score !== left.score) {
|
|
338
|
-
return right.score - left.score;
|
|
339
|
-
}
|
|
340
|
-
const rightConn = right.connectedBeliefCount + right.connectedEvidenceCount;
|
|
341
|
-
const leftConn = left.connectedBeliefCount + left.connectedEvidenceCount;
|
|
342
|
-
return rightConn - leftConn;
|
|
343
|
-
});
|
|
344
|
-
return scored.slice(0, effectiveLimit);
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
// src/contextPackSchema.ts
|
|
348
|
-
var CONTEXT_PACK_SCHEMA_VERSION2 = "1.0.0";
|
|
349
|
-
function isObject(value) {
|
|
350
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
351
|
-
}
|
|
352
|
-
function isString(value) {
|
|
353
|
-
return typeof value === "string";
|
|
354
|
-
}
|
|
355
|
-
function isNumber(value) {
|
|
356
|
-
return typeof value === "number" && Number.isFinite(value);
|
|
357
|
-
}
|
|
358
|
-
function isNullableNumber(value) {
|
|
359
|
-
return value === null || isNumber(value);
|
|
360
|
-
}
|
|
361
|
-
function isStringArray(value) {
|
|
362
|
-
return Array.isArray(value) && value.every((entry) => isString(entry));
|
|
363
|
-
}
|
|
364
|
-
function requireObject(parent, key, errors) {
|
|
365
|
-
const value = parent[key];
|
|
366
|
-
if (!isObject(value)) {
|
|
367
|
-
errors.push(`Expected '${key}' to be an object`);
|
|
368
|
-
return null;
|
|
369
|
-
}
|
|
370
|
-
return value;
|
|
371
|
-
}
|
|
372
|
-
function validateBeliefArray(key, value, errors) {
|
|
373
|
-
if (!Array.isArray(value)) {
|
|
374
|
-
errors.push(`Expected '${key}' to be an array`);
|
|
375
|
-
return;
|
|
376
|
-
}
|
|
377
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
378
|
-
const row = value[index];
|
|
379
|
-
if (!isObject(row)) {
|
|
380
|
-
errors.push(`Expected '${key}[${index}]' to be an object`);
|
|
381
|
-
continue;
|
|
382
|
-
}
|
|
383
|
-
if (!isString(row.nodeId)) {
|
|
384
|
-
errors.push(`Expected '${key}[${index}].nodeId' to be a string`);
|
|
385
|
-
}
|
|
386
|
-
if (!isString(row.canonicalText)) {
|
|
387
|
-
errors.push(`Expected '${key}[${index}].canonicalText' to be a string`);
|
|
388
|
-
}
|
|
389
|
-
if (!isNullableNumber(row.confidence)) {
|
|
390
|
-
errors.push(`Expected '${key}[${index}].confidence' to be number|null`);
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
}
|
|
394
|
-
function validateQuestionArray(key, value, errors) {
|
|
395
|
-
if (!Array.isArray(value)) {
|
|
396
|
-
errors.push(`Expected '${key}' to be an array`);
|
|
397
|
-
return;
|
|
398
|
-
}
|
|
399
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
400
|
-
const row = value[index];
|
|
401
|
-
if (!isObject(row)) {
|
|
402
|
-
errors.push(`Expected '${key}[${index}]' to be an object`);
|
|
403
|
-
continue;
|
|
404
|
-
}
|
|
405
|
-
if (!isString(row.questionId)) {
|
|
406
|
-
errors.push(`Expected '${key}[${index}].questionId' to be a string`);
|
|
407
|
-
}
|
|
408
|
-
if (!isString(row.text)) {
|
|
409
|
-
errors.push(`Expected '${key}[${index}].text' to be a string`);
|
|
410
|
-
}
|
|
411
|
-
if (!isString(row.status)) {
|
|
412
|
-
errors.push(`Expected '${key}[${index}].status' to be a string`);
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
function validateEvidenceArray(key, value, errors) {
|
|
417
|
-
if (!Array.isArray(value)) {
|
|
418
|
-
errors.push(`Expected '${key}' to be an array`);
|
|
419
|
-
return;
|
|
420
|
-
}
|
|
421
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
422
|
-
const row = value[index];
|
|
423
|
-
if (!isObject(row)) {
|
|
424
|
-
errors.push(`Expected '${key}[${index}]' to be an object`);
|
|
425
|
-
continue;
|
|
426
|
-
}
|
|
427
|
-
if (!isString(row.nodeId)) {
|
|
428
|
-
errors.push(`Expected '${key}[${index}].nodeId' to be a string`);
|
|
429
|
-
}
|
|
430
|
-
if (!isString(row.canonicalText)) {
|
|
431
|
-
errors.push(`Expected '${key}[${index}].canonicalText' to be a string`);
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
}
|
|
435
|
-
function validateEntityArray(key, value, errors) {
|
|
436
|
-
if (!Array.isArray(value)) {
|
|
437
|
-
errors.push(`Expected '${key}' to be an array`);
|
|
438
|
-
return;
|
|
439
|
-
}
|
|
440
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
441
|
-
const row = value[index];
|
|
442
|
-
if (!isObject(row)) {
|
|
443
|
-
errors.push(`Expected '${key}[${index}]' to be an object`);
|
|
444
|
-
continue;
|
|
445
|
-
}
|
|
446
|
-
if (!isString(row.nodeId)) {
|
|
447
|
-
errors.push(`Expected '${key}[${index}].nodeId' to be a string`);
|
|
448
|
-
}
|
|
449
|
-
if (!isString(row.entityType)) {
|
|
450
|
-
errors.push(`Expected '${key}[${index}].entityType' to be a string`);
|
|
451
|
-
}
|
|
452
|
-
if (!isString(row.title)) {
|
|
453
|
-
errors.push(`Expected '${key}[${index}].title' to be a string`);
|
|
454
|
-
}
|
|
455
|
-
if (!isNumber(row.connectedBeliefCount)) {
|
|
456
|
-
errors.push(`Expected '${key}[${index}].connectedBeliefCount' to be a number`);
|
|
457
|
-
}
|
|
458
|
-
if (!isNumber(row.connectedEvidenceCount)) {
|
|
459
|
-
errors.push(`Expected '${key}[${index}].connectedEvidenceCount' to be a number`);
|
|
460
|
-
}
|
|
461
|
-
if (!isNumber(row.score)) {
|
|
462
|
-
errors.push(`Expected '${key}[${index}].score' to be a number`);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
function validateContradictionArray(key, value, errors) {
|
|
467
|
-
if (!Array.isArray(value)) {
|
|
468
|
-
errors.push(`Expected '${key}' to be an array`);
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
472
|
-
const row = value[index];
|
|
473
|
-
if (!isObject(row)) {
|
|
474
|
-
errors.push(`Expected '${key}[${index}]' to be an object`);
|
|
475
|
-
continue;
|
|
476
|
-
}
|
|
477
|
-
if (!isString(row.contradictionId)) {
|
|
478
|
-
errors.push(`Expected '${key}[${index}].contradictionId' to be a string`);
|
|
479
|
-
}
|
|
480
|
-
if (!isString(row.status)) {
|
|
481
|
-
errors.push(`Expected '${key}[${index}].status' to be a string`);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
function validateContextPackSchema(payload) {
|
|
486
|
-
const errors = [];
|
|
487
|
-
if (!isObject(payload)) {
|
|
488
|
-
return {
|
|
489
|
-
valid: false,
|
|
490
|
-
errors: ["Expected context pack payload to be an object"]
|
|
491
|
-
};
|
|
492
|
-
}
|
|
493
|
-
if (payload.schemaVersion !== CONTEXT_PACK_SCHEMA_VERSION2) {
|
|
494
|
-
errors.push(
|
|
495
|
-
`Expected schemaVersion='${CONTEXT_PACK_SCHEMA_VERSION2}', received '${String(
|
|
496
|
-
payload.schemaVersion
|
|
497
|
-
)}'`
|
|
498
|
-
);
|
|
499
|
-
}
|
|
500
|
-
if (!isString(payload.topicId)) {
|
|
501
|
-
errors.push("Expected 'topicId' to be a string");
|
|
502
|
-
}
|
|
503
|
-
if (!isString(payload.topicName)) {
|
|
504
|
-
errors.push("Expected 'topicName' to be a string");
|
|
505
|
-
}
|
|
506
|
-
if (!isStringArray(payload.scopedTopicIds)) {
|
|
507
|
-
errors.push("Expected 'scopedTopicIds' to be string[]");
|
|
508
|
-
}
|
|
509
|
-
if (!isNumber(payload.generatedAt)) {
|
|
510
|
-
errors.push("Expected 'generatedAt' to be a number");
|
|
511
|
-
}
|
|
512
|
-
if (!isString(payload.ranking)) {
|
|
513
|
-
errors.push("Expected 'ranking' to be a string");
|
|
514
|
-
}
|
|
515
|
-
validateBeliefArray("invariants", payload.invariants, errors);
|
|
516
|
-
validateBeliefArray("activeBeliefs", payload.activeBeliefs, errors);
|
|
517
|
-
validateQuestionArray("openQuestions", payload.openQuestions, errors);
|
|
518
|
-
validateEvidenceArray("recentEvidence", payload.recentEvidence, errors);
|
|
519
|
-
validateContradictionArray("contradictions", payload.contradictions, errors);
|
|
520
|
-
if (payload.relatedEntities !== void 0 && payload.relatedEntities !== null) {
|
|
521
|
-
validateEntityArray("relatedEntities", payload.relatedEntities, errors);
|
|
522
|
-
}
|
|
523
|
-
if (!Array.isArray(payload.contextNarrative)) {
|
|
524
|
-
errors.push("Expected 'contextNarrative' to be an array");
|
|
525
|
-
}
|
|
526
|
-
const injectionPolicy = requireObject(payload, "injectionPolicy", errors);
|
|
527
|
-
if (injectionPolicy) {
|
|
528
|
-
if (!isNumber(injectionPolicy.tokenBudget)) {
|
|
529
|
-
errors.push("Expected 'injectionPolicy.tokenBudget' to be a number");
|
|
530
|
-
}
|
|
531
|
-
if (!isNumber(injectionPolicy.estimatedTokens)) {
|
|
532
|
-
errors.push("Expected 'injectionPolicy.estimatedTokens' to be a number");
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
if (!isObject(payload.summary)) {
|
|
536
|
-
errors.push("Expected 'summary' to be an object");
|
|
537
|
-
}
|
|
538
|
-
if (!isObject(payload.diagnostics)) {
|
|
539
|
-
errors.push("Expected 'diagnostics' to be an object");
|
|
540
|
-
}
|
|
541
|
-
return {
|
|
542
|
-
valid: errors.length === 0,
|
|
543
|
-
errors
|
|
544
|
-
};
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// src/contextPackCompiler.ts
|
|
548
|
-
function assertContextPackSchema(payload) {
|
|
549
|
-
const result = validateContextPackSchema(payload);
|
|
550
|
-
if (!result.valid) {
|
|
551
|
-
throw new Error(
|
|
552
|
-
`Invalid context pack payload: ${result.errors.join("; ")}`
|
|
553
|
-
);
|
|
554
|
-
}
|
|
555
|
-
}
|
|
556
|
-
function asStringArray(value) {
|
|
557
|
-
if (!Array.isArray(value)) {
|
|
558
|
-
return [];
|
|
559
|
-
}
|
|
560
|
-
return value.map((entry) => typeof entry === "string" ? entry.trim() : "").filter((entry) => entry.length > 0);
|
|
561
|
-
}
|
|
562
|
-
function toPositiveInt(value, fallback, max) {
|
|
563
|
-
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
564
|
-
return fallback;
|
|
565
|
-
}
|
|
566
|
-
const floored = Math.floor(value);
|
|
567
|
-
return Math.max(1, Math.min(floored, max));
|
|
568
|
-
}
|
|
569
|
-
function normalizeQueryTokens(query) {
|
|
570
|
-
if (!query) {
|
|
571
|
-
return [];
|
|
572
|
-
}
|
|
573
|
-
return query.toLowerCase().split(/[^a-z0-9]+/).map((token) => token.trim()).filter((token) => token.length >= 2);
|
|
574
|
-
}
|
|
575
|
-
function parseRankingProfile(value) {
|
|
576
|
-
return value === "baseline_v1" ? "baseline_v1" : "weighted_v1";
|
|
577
|
-
}
|
|
578
|
-
function beliefTypeOf(node) {
|
|
579
|
-
if (typeof node.beliefType === "string") {
|
|
580
|
-
return node.beliefType;
|
|
581
|
-
}
|
|
582
|
-
const metadata = node.metadata || {};
|
|
583
|
-
if (typeof metadata.beliefType === "string") {
|
|
584
|
-
return metadata.beliefType;
|
|
585
|
-
}
|
|
586
|
-
return "";
|
|
587
|
-
}
|
|
588
|
-
function questionStatusOf(node) {
|
|
589
|
-
const metadata = node.metadata || {};
|
|
590
|
-
const direct = typeof node.status === "string" ? node.status : "";
|
|
591
|
-
const questionStatus = typeof metadata.questionStatus === "string" ? metadata.questionStatus : "";
|
|
592
|
-
return (questionStatus || direct || "open").toLowerCase();
|
|
593
|
-
}
|
|
594
|
-
function isOpenQuestion(status) {
|
|
595
|
-
return ![
|
|
596
|
-
"answered",
|
|
597
|
-
"archived",
|
|
598
|
-
"closed",
|
|
599
|
-
"resolved",
|
|
600
|
-
"resolved_support",
|
|
601
|
-
"resolved_contra",
|
|
602
|
-
"belief_forked"
|
|
603
|
-
].includes(status);
|
|
604
|
-
}
|
|
605
|
-
function metadataText(payload) {
|
|
606
|
-
return JSON.stringify(payload).toLowerCase();
|
|
607
|
-
}
|
|
608
|
-
function collectTopicNeighborhood(topics, rootTopicId, maxDescendantDepth = 2) {
|
|
609
|
-
const byId = /* @__PURE__ */ new Map();
|
|
610
|
-
const children = /* @__PURE__ */ new Map();
|
|
611
|
-
for (const topic of topics) {
|
|
612
|
-
const id = String(topic._id);
|
|
613
|
-
byId.set(id, topic);
|
|
614
|
-
if (!children.has(id)) {
|
|
615
|
-
children.set(id, []);
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
for (const topic of topics) {
|
|
619
|
-
if (!topic.parentTopicId) {
|
|
620
|
-
continue;
|
|
621
|
-
}
|
|
622
|
-
const parent = String(topic.parentTopicId);
|
|
623
|
-
const id = String(topic._id);
|
|
624
|
-
const list = children.get(parent) || [];
|
|
625
|
-
list.push(id);
|
|
626
|
-
children.set(parent, list);
|
|
627
|
-
}
|
|
628
|
-
const selected = /* @__PURE__ */ new Set([rootTopicId]);
|
|
629
|
-
let cursor = byId.get(rootTopicId);
|
|
630
|
-
while (cursor?.parentTopicId) {
|
|
631
|
-
const parentId = String(cursor.parentTopicId);
|
|
632
|
-
if (selected.has(parentId)) {
|
|
633
|
-
break;
|
|
634
|
-
}
|
|
635
|
-
selected.add(parentId);
|
|
636
|
-
cursor = byId.get(parentId);
|
|
637
|
-
}
|
|
638
|
-
const queue = [
|
|
639
|
-
{ id: rootTopicId, depth: 0 }
|
|
640
|
-
];
|
|
641
|
-
while (queue.length > 0) {
|
|
642
|
-
const current = queue.shift();
|
|
643
|
-
if (!current || current.depth >= maxDescendantDepth) {
|
|
644
|
-
continue;
|
|
645
|
-
}
|
|
646
|
-
for (const childId of children.get(current.id) || []) {
|
|
647
|
-
if (!selected.has(childId)) {
|
|
648
|
-
selected.add(childId);
|
|
649
|
-
}
|
|
650
|
-
queue.push({ id: childId, depth: current.depth + 1 });
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
return Array.from(selected);
|
|
654
|
-
}
|
|
655
|
-
function dedupeById(rows) {
|
|
656
|
-
const seen = /* @__PURE__ */ new Set();
|
|
657
|
-
const output = [];
|
|
658
|
-
for (const row of rows) {
|
|
659
|
-
const id = row?._id ? String(row._id) : "";
|
|
660
|
-
if (!id || seen.has(id)) {
|
|
661
|
-
continue;
|
|
662
|
-
}
|
|
663
|
-
seen.add(id);
|
|
664
|
-
output.push(row);
|
|
665
|
-
}
|
|
666
|
-
return output;
|
|
667
|
-
}
|
|
668
|
-
function candidateTimestamp(candidate) {
|
|
669
|
-
if (!candidate || typeof candidate !== "object") {
|
|
670
|
-
return 0;
|
|
671
|
-
}
|
|
672
|
-
const record = candidate;
|
|
673
|
-
const timestamps = [record.updatedAt, record.createdAt, record.generatedAt].filter(
|
|
674
|
-
(value) => typeof value === "number" && Number.isFinite(value)
|
|
675
|
-
);
|
|
676
|
-
return timestamps.length > 0 ? Math.max(...timestamps) : 0;
|
|
677
|
-
}
|
|
678
|
-
function resolveReferenceTimeMs(...collections) {
|
|
679
|
-
let maxTimestamp = 0;
|
|
680
|
-
for (const collection of collections) {
|
|
681
|
-
for (const item of collection) {
|
|
682
|
-
const timestamp = candidateTimestamp(item);
|
|
683
|
-
if (timestamp > maxTimestamp) {
|
|
684
|
-
maxTimestamp = timestamp;
|
|
685
|
-
}
|
|
686
|
-
}
|
|
687
|
-
}
|
|
688
|
-
return maxTimestamp;
|
|
689
|
-
}
|
|
690
|
-
function planContextPackCompilation(input) {
|
|
691
|
-
const args = input.args ?? {};
|
|
692
|
-
const topicId = String(input.topic._id);
|
|
693
|
-
const queryText = typeof args.query === "string" && args.query.trim().length > 0 ? args.query.trim() : void 0;
|
|
694
|
-
const tokens = normalizeQueryTokens(queryText);
|
|
695
|
-
const limit = toPositiveInt(args.limit, 8, 25);
|
|
696
|
-
const rankingProfile = parseRankingProfile(
|
|
697
|
-
typeof args.ranking === "string" ? args.ranking : args.rankingProfile
|
|
698
|
-
);
|
|
699
|
-
const tokenBudget = parseTokenBudget(
|
|
700
|
-
typeof args.budget === "number" ? args.budget : args.tokenBudget,
|
|
701
|
-
1800
|
|
702
|
-
);
|
|
703
|
-
const topicDepth = typeof input.topic.depth === "number" && Number.isFinite(input.topic.depth) ? input.topic.depth : 0;
|
|
704
|
-
const requestedMaxDepth = typeof args.maxDepth === "number" && Number.isFinite(args.maxDepth) ? Math.max(1, Math.min(Math.floor(args.maxDepth), 6)) : void 0;
|
|
705
|
-
const descendantDepth = requestedMaxDepth ?? (topicDepth <= 1 ? 4 : 2);
|
|
706
|
-
const includeEntities = args.includeEntities !== false;
|
|
707
|
-
const compilationMode = args.mode === "delta" ? "delta" : DEFAULT_COMPILATION_MODE;
|
|
708
|
-
const includeFailures = compilationMode === "delta" || args.includeFailures === true;
|
|
709
|
-
const worktreeId = typeof args.worktreeId === "string" && args.worktreeId.trim().length > 0 ? args.worktreeId.trim() : void 0;
|
|
710
|
-
const sessionId = typeof args.sessionId === "string" && args.sessionId.trim().length > 0 ? args.sessionId.trim() : void 0;
|
|
711
|
-
const packWeightOverrides = Array.isArray(args.packWeightOverrides) ? args.packWeightOverrides : void 0;
|
|
712
|
-
const effectiveWeights = resolveEffectiveWeights(packWeightOverrides);
|
|
713
|
-
let scopedTopicIds = collectTopicNeighborhood(
|
|
714
|
-
input.allTopics,
|
|
715
|
-
topicId,
|
|
716
|
-
descendantDepth
|
|
717
|
-
);
|
|
718
|
-
const allowedTopicIds = asStringArray(args.allowedTopicIds);
|
|
719
|
-
if (allowedTopicIds.length > 0) {
|
|
720
|
-
const allowedSet = new Set(allowedTopicIds);
|
|
721
|
-
if (!allowedSet.has(topicId)) {
|
|
722
|
-
throw new Error(`Access denied to compile context for topic ${topicId}.`);
|
|
723
|
-
}
|
|
724
|
-
scopedTopicIds = scopedTopicIds.filter((id) => allowedSet.has(id));
|
|
725
|
-
}
|
|
726
|
-
return {
|
|
727
|
-
topicId,
|
|
728
|
-
...queryText ? { queryText } : {},
|
|
729
|
-
tokens,
|
|
730
|
-
limit,
|
|
731
|
-
rankingProfile,
|
|
732
|
-
tokenBudget,
|
|
733
|
-
descendantDepth,
|
|
734
|
-
includeEntities,
|
|
735
|
-
compilationMode,
|
|
736
|
-
includeFailures,
|
|
737
|
-
...worktreeId ? { worktreeId } : {},
|
|
738
|
-
...sessionId ? { sessionId } : {},
|
|
739
|
-
...packWeightOverrides ? { packWeightOverrides } : {},
|
|
740
|
-
effectiveWeights,
|
|
741
|
-
scopedTopicIds
|
|
742
|
-
};
|
|
743
|
-
}
|
|
744
|
-
function compileContextPackFromSnapshot(snapshot) {
|
|
745
|
-
const uniqueBeliefs = dedupeById(snapshot.beliefs);
|
|
746
|
-
const uniqueQuestions = dedupeById(snapshot.questions);
|
|
747
|
-
const uniqueEvidence = dedupeById(snapshot.evidence);
|
|
748
|
-
const uniqueContradictions = dedupeById(snapshot.contradictions);
|
|
749
|
-
const referenceTimeMs = resolveReferenceTimeMs(
|
|
750
|
-
[snapshot.topic],
|
|
751
|
-
uniqueBeliefs,
|
|
752
|
-
uniqueQuestions,
|
|
753
|
-
uniqueEvidence,
|
|
754
|
-
uniqueContradictions,
|
|
755
|
-
snapshot.entities
|
|
756
|
-
) || 0;
|
|
757
|
-
const rankOptions = {
|
|
758
|
-
effectiveWeights: snapshot.plan.effectiveWeights,
|
|
759
|
-
includeJustifications: snapshot.plan.compilationMode === "delta",
|
|
760
|
-
referenceTimeMs
|
|
761
|
-
};
|
|
762
|
-
const invariantCandidates = uniqueBeliefs.filter((belief) => beliefTypeOf(belief).toLowerCase() === "invariant").map((belief) => ({
|
|
763
|
-
nodeId: String(belief._id),
|
|
764
|
-
canonicalText: String(belief.canonicalText || ""),
|
|
765
|
-
confidence: typeof belief.confidence === "number" ? belief.confidence : null,
|
|
766
|
-
beliefType: beliefTypeOf(belief) || "invariant",
|
|
767
|
-
updatedAt: belief.updatedAt || belief.createdAt || null
|
|
768
|
-
}));
|
|
769
|
-
const invariants = rankContextSection(
|
|
770
|
-
"invariants",
|
|
771
|
-
invariantCandidates.map((candidate) => ({
|
|
772
|
-
...candidate,
|
|
773
|
-
id: candidate.nodeId,
|
|
774
|
-
text: `${candidate.canonicalText} ${candidate.beliefType}`
|
|
775
|
-
})),
|
|
776
|
-
snapshot.plan.tokens,
|
|
777
|
-
snapshot.plan.limit,
|
|
778
|
-
snapshot.plan.rankingProfile,
|
|
779
|
-
rankOptions
|
|
780
|
-
).map((row) => ({
|
|
781
|
-
nodeId: row.nodeId,
|
|
782
|
-
canonicalText: row.canonicalText,
|
|
783
|
-
confidence: row.confidence,
|
|
784
|
-
beliefType: row.beliefType,
|
|
785
|
-
score: row.score,
|
|
786
|
-
...row.justification ? { justification: row.justification } : {}
|
|
787
|
-
}));
|
|
788
|
-
const activeBeliefCandidates = uniqueBeliefs.filter((belief) => (belief.status || "active") !== "archived").map((belief) => ({
|
|
789
|
-
nodeId: String(belief._id),
|
|
790
|
-
canonicalText: String(belief.canonicalText || ""),
|
|
791
|
-
confidence: typeof belief.confidence === "number" ? belief.confidence : null,
|
|
792
|
-
beliefType: beliefTypeOf(belief) || null,
|
|
793
|
-
status: belief.status || "active",
|
|
794
|
-
updatedAt: belief.updatedAt || belief.createdAt || null,
|
|
795
|
-
metadataText: belief.metadata && typeof belief.metadata === "object" ? metadataText(belief.metadata) : ""
|
|
796
|
-
}));
|
|
797
|
-
const activeBeliefs = rankContextSection(
|
|
798
|
-
"activeBeliefs",
|
|
799
|
-
activeBeliefCandidates.map((candidate) => ({
|
|
800
|
-
...candidate,
|
|
801
|
-
id: candidate.nodeId,
|
|
802
|
-
text: `${candidate.canonicalText} ${candidate.metadataText}`
|
|
803
|
-
})),
|
|
804
|
-
snapshot.plan.tokens,
|
|
805
|
-
snapshot.plan.limit,
|
|
806
|
-
snapshot.plan.rankingProfile,
|
|
807
|
-
rankOptions
|
|
808
|
-
).map((row) => ({
|
|
809
|
-
nodeId: row.nodeId,
|
|
810
|
-
canonicalText: row.canonicalText,
|
|
811
|
-
confidence: row.confidence,
|
|
812
|
-
beliefType: row.beliefType,
|
|
813
|
-
status: row.status,
|
|
814
|
-
updatedAt: row.updatedAt,
|
|
815
|
-
score: row.score,
|
|
816
|
-
...row.justification ? { justification: row.justification } : {}
|
|
817
|
-
}));
|
|
818
|
-
const openQuestionCandidates = uniqueQuestions.map((question) => {
|
|
819
|
-
const status = questionStatusOf(question);
|
|
820
|
-
const metadata = question.metadata && typeof question.metadata === "object" ? question.metadata : {};
|
|
821
|
-
return {
|
|
822
|
-
questionId: String(question._id),
|
|
823
|
-
text: String(question.canonicalText || ""),
|
|
824
|
-
status,
|
|
825
|
-
priority: typeof metadata.priority === "string" ? metadata.priority : "medium",
|
|
826
|
-
updatedAt: question.updatedAt || question.createdAt || null,
|
|
827
|
-
metadataText: metadataText(metadata)
|
|
828
|
-
};
|
|
829
|
-
}).filter((row) => isOpenQuestion(row.status));
|
|
830
|
-
const openQuestions = rankContextSection(
|
|
831
|
-
"openQuestions",
|
|
832
|
-
openQuestionCandidates.map((candidate) => ({
|
|
833
|
-
...candidate,
|
|
834
|
-
id: candidate.questionId,
|
|
835
|
-
text: `${candidate.text} ${candidate.metadataText}`
|
|
836
|
-
})),
|
|
837
|
-
snapshot.plan.tokens,
|
|
838
|
-
snapshot.plan.limit,
|
|
839
|
-
snapshot.plan.rankingProfile,
|
|
840
|
-
rankOptions
|
|
841
|
-
).map((row) => ({
|
|
842
|
-
questionId: row.questionId,
|
|
843
|
-
text: row.text,
|
|
844
|
-
status: row.status,
|
|
845
|
-
priority: row.priority,
|
|
846
|
-
updatedAt: row.updatedAt,
|
|
847
|
-
score: row.score,
|
|
848
|
-
...row.justification ? { justification: row.justification } : {}
|
|
849
|
-
}));
|
|
850
|
-
const evidenceCandidates = uniqueEvidence.map((item) => {
|
|
851
|
-
const metadata = item.metadata && typeof item.metadata === "object" ? item.metadata : {};
|
|
852
|
-
return {
|
|
853
|
-
nodeId: String(item._id),
|
|
854
|
-
canonicalText: String(item.canonicalText || ""),
|
|
855
|
-
sourceUrl: typeof metadata.sourceUrl === "string" && metadata.sourceUrl || typeof item.sourceUrl === "string" && item.sourceUrl || null,
|
|
856
|
-
kind: typeof metadata.kind === "string" && metadata.kind || "observation",
|
|
857
|
-
createdAt: item.createdAt || null,
|
|
858
|
-
updatedAt: item.updatedAt || item.createdAt || null,
|
|
859
|
-
metadataText: metadataText(metadata)
|
|
860
|
-
};
|
|
861
|
-
});
|
|
862
|
-
const recentEvidence = rankContextSection(
|
|
863
|
-
"recentEvidence",
|
|
864
|
-
evidenceCandidates.map((candidate) => ({
|
|
865
|
-
...candidate,
|
|
866
|
-
id: candidate.nodeId,
|
|
867
|
-
text: `${candidate.canonicalText} ${candidate.metadataText}`
|
|
868
|
-
})),
|
|
869
|
-
snapshot.plan.tokens,
|
|
870
|
-
snapshot.plan.limit,
|
|
871
|
-
snapshot.plan.rankingProfile,
|
|
872
|
-
rankOptions
|
|
873
|
-
).map((row) => ({
|
|
874
|
-
nodeId: row.nodeId,
|
|
875
|
-
canonicalText: row.canonicalText,
|
|
876
|
-
sourceUrl: row.sourceUrl,
|
|
877
|
-
kind: row.kind,
|
|
878
|
-
createdAt: row.createdAt,
|
|
879
|
-
score: row.score,
|
|
880
|
-
...row.justification ? { justification: row.justification } : {}
|
|
881
|
-
}));
|
|
882
|
-
const contradictionCandidates = uniqueContradictions.map((row) => {
|
|
883
|
-
const weight = typeof row.weight === "number" ? row.weight : 0;
|
|
884
|
-
const severity = weight <= -0.9 ? "critical" : weight <= -0.7 ? "high" : weight <= -0.5 ? "medium" : "low";
|
|
885
|
-
return {
|
|
886
|
-
contradictionId: String(row._id || row.globalId || ""),
|
|
887
|
-
severity,
|
|
888
|
-
status: "active",
|
|
889
|
-
description: row.context || row.description || row.summary || "",
|
|
890
|
-
updatedAt: row.updatedAt || row.createdAt || null
|
|
891
|
-
};
|
|
892
|
-
});
|
|
893
|
-
const contradictions = rankContextSection(
|
|
894
|
-
"contradictions",
|
|
895
|
-
contradictionCandidates.map((candidate) => ({
|
|
896
|
-
...candidate,
|
|
897
|
-
id: candidate.contradictionId,
|
|
898
|
-
text: `${candidate.description} ${candidate.severity}`
|
|
899
|
-
})),
|
|
900
|
-
snapshot.plan.tokens,
|
|
901
|
-
snapshot.plan.limit,
|
|
902
|
-
snapshot.plan.rankingProfile,
|
|
903
|
-
rankOptions
|
|
904
|
-
).map((row) => ({
|
|
905
|
-
contradictionId: row.contradictionId,
|
|
906
|
-
severity: row.severity,
|
|
907
|
-
status: row.status,
|
|
908
|
-
description: row.description,
|
|
909
|
-
score: row.score,
|
|
910
|
-
...row.justification ? { justification: row.justification } : {}
|
|
911
|
-
}));
|
|
912
|
-
const entityCandidates = snapshot.entities.map((row) => ({
|
|
913
|
-
nodeId: String(row._id),
|
|
914
|
-
entityType: String(row.nodeType || ""),
|
|
915
|
-
title: String(row.title || ""),
|
|
916
|
-
canonicalText: String(row.canonicalText || ""),
|
|
917
|
-
connectedBeliefCount: typeof row.connectedBeliefCount === "number" ? row.connectedBeliefCount : 0,
|
|
918
|
-
connectedEvidenceCount: typeof row.connectedEvidenceCount === "number" ? row.connectedEvidenceCount : 0,
|
|
919
|
-
metadata: row.metadata && typeof row.metadata === "object" ? row.metadata : {},
|
|
920
|
-
updatedAt: row.updatedAt || null
|
|
921
|
-
}));
|
|
922
|
-
const entityLimit = toPositiveInt(
|
|
923
|
-
snapshot.plan.limit,
|
|
924
|
-
DEFAULT_ENTITY_LIMIT,
|
|
925
|
-
MAX_ENTITY_LIMIT
|
|
926
|
-
);
|
|
927
|
-
const rankedEntities = snapshot.plan.includeEntities ? rankEntities(entityCandidates, snapshot.plan.tokens, entityLimit).map(
|
|
928
|
-
(row) => ({
|
|
929
|
-
nodeId: row.nodeId,
|
|
930
|
-
entityType: row.entityType,
|
|
931
|
-
title: row.title,
|
|
932
|
-
connectedBeliefCount: row.connectedBeliefCount,
|
|
933
|
-
connectedEvidenceCount: row.connectedEvidenceCount,
|
|
934
|
-
score: row.score,
|
|
935
|
-
...Object.keys(row.metadata).length > 0 ? { metadata: row.metadata } : {}
|
|
936
|
-
})
|
|
937
|
-
) : void 0;
|
|
938
|
-
let failureContext;
|
|
939
|
-
if (snapshot.plan.includeFailures && snapshot.failures) {
|
|
940
|
-
const allFailures = snapshot.failures.filter((node) => {
|
|
941
|
-
const metadata = node.metadata || {};
|
|
942
|
-
return metadata.failedApproach === true || metadata.isFailedAttempt === true;
|
|
943
|
-
});
|
|
944
|
-
const rankedFailures = rankContextSection(
|
|
945
|
-
"recentEvidence",
|
|
946
|
-
allFailures.map((node) => ({
|
|
947
|
-
id: String(node._id),
|
|
948
|
-
text: String(node.canonicalText || ""),
|
|
949
|
-
createdAt: node.createdAt || null,
|
|
950
|
-
updatedAt: node.updatedAt || node.createdAt || null
|
|
951
|
-
})),
|
|
952
|
-
snapshot.plan.tokens,
|
|
953
|
-
10,
|
|
954
|
-
snapshot.plan.rankingProfile,
|
|
955
|
-
rankOptions
|
|
956
|
-
);
|
|
957
|
-
const failures = rankedFailures.map((row) => {
|
|
958
|
-
const original = allFailures.find((node) => String(node._id) === row.id);
|
|
959
|
-
const metadata = original?.metadata || {};
|
|
960
|
-
return {
|
|
961
|
-
attemptId: row.id,
|
|
962
|
-
approach: String(row.text || ""),
|
|
963
|
-
outcome: String(metadata.errorMessage || "Failed"),
|
|
964
|
-
recordedAt: row.createdAt || referenceTimeMs || 0,
|
|
965
|
-
score: row.score
|
|
966
|
-
};
|
|
967
|
-
});
|
|
968
|
-
const failureTexts = new Set(
|
|
969
|
-
failures.map((failure) => failure.approach.toLowerCase().slice(0, 100))
|
|
970
|
-
);
|
|
971
|
-
const suppressionIds = /* @__PURE__ */ new Set();
|
|
972
|
-
if (snapshot.plan.sessionId && failureTexts.size > 0) {
|
|
973
|
-
for (const evidenceRow of recentEvidence) {
|
|
974
|
-
const evidenceText = evidenceRow.canonicalText.toLowerCase().slice(0, 100);
|
|
975
|
-
for (const failureText of failureTexts) {
|
|
976
|
-
if (evidenceText.includes(failureText) || failureText.includes(evidenceText)) {
|
|
977
|
-
suppressionIds.add(evidenceRow.nodeId);
|
|
978
|
-
break;
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
if (failures.length > 0) {
|
|
984
|
-
failureContext = {
|
|
985
|
-
failures,
|
|
986
|
-
suppressedIds: Array.from(suppressionIds)
|
|
987
|
-
};
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
const suppressionSet = new Set(failureContext?.suppressedIds || []);
|
|
991
|
-
const effectiveEvidence = suppressionSet.size > 0 ? recentEvidence.filter((row) => !suppressionSet.has(row.nodeId)) : recentEvidence;
|
|
992
|
-
const suppressedEvidenceIds = suppressionSet.size > 0 ? recentEvidence.filter((row) => suppressionSet.has(row.nodeId)).map((row) => row.nodeId) : [];
|
|
993
|
-
const summary = {
|
|
994
|
-
totalBeliefs: uniqueBeliefs.length,
|
|
995
|
-
invariants: invariants.length,
|
|
996
|
-
openQuestions: openQuestions.length,
|
|
997
|
-
evidenceItems: uniqueEvidence.length,
|
|
998
|
-
contradictions: contradictions.length,
|
|
999
|
-
...rankedEntities ? { relatedEntities: rankedEntities.length } : {},
|
|
1000
|
-
scopedTopics: snapshot.plan.scopedTopicIds.length,
|
|
1001
|
-
descendantDepth: snapshot.plan.descendantDepth,
|
|
1002
|
-
query: snapshot.plan.queryText || null
|
|
1003
|
-
};
|
|
1004
|
-
const injectionPolicy = buildInjectionPlan({
|
|
1005
|
-
tokenBudget: snapshot.plan.tokenBudget,
|
|
1006
|
-
invariants: invariants.map((row) => ({
|
|
1007
|
-
nodeId: row.nodeId,
|
|
1008
|
-
canonicalText: row.canonicalText,
|
|
1009
|
-
score: row.score
|
|
1010
|
-
})),
|
|
1011
|
-
activeBeliefs: activeBeliefs.map((row) => ({
|
|
1012
|
-
nodeId: row.nodeId,
|
|
1013
|
-
canonicalText: row.canonicalText,
|
|
1014
|
-
score: row.score
|
|
1015
|
-
})),
|
|
1016
|
-
openQuestions: openQuestions.map((row) => ({
|
|
1017
|
-
questionId: row.questionId,
|
|
1018
|
-
text: row.text,
|
|
1019
|
-
score: row.score
|
|
1020
|
-
})),
|
|
1021
|
-
recentEvidence: effectiveEvidence.map((row) => ({
|
|
1022
|
-
nodeId: row.nodeId,
|
|
1023
|
-
canonicalText: row.canonicalText,
|
|
1024
|
-
score: row.score
|
|
1025
|
-
})),
|
|
1026
|
-
contradictions: contradictions.map((row) => ({
|
|
1027
|
-
contradictionId: row.contradictionId,
|
|
1028
|
-
description: row.description,
|
|
1029
|
-
score: row.score
|
|
1030
|
-
})),
|
|
1031
|
-
trackExclusions: snapshot.plan.compilationMode === "delta"
|
|
1032
|
-
});
|
|
1033
|
-
const contextNarrative = [
|
|
1034
|
-
"Prefer invariant beliefs as hard constraints while reasoning over this scope.",
|
|
1035
|
-
"Treat open questions as unresolved work items and avoid claiming closure without evidence.",
|
|
1036
|
-
"Use recent evidence for implementation context before creating new beliefs.",
|
|
1037
|
-
"When contradictions exist, resolve explicitly (fork, lower confidence, or gather counter-evidence).",
|
|
1038
|
-
`Apply injection token budget of ${injectionPolicy.tokenBudget} with section quotas before prompt assembly.`
|
|
1039
|
-
];
|
|
1040
|
-
const deltaReport = snapshot.plan.compilationMode === "delta" && snapshot.plan.worktreeId ? {
|
|
1041
|
-
changedItems: [],
|
|
1042
|
-
verificationObligations: [],
|
|
1043
|
-
referencePoint: snapshot.plan.worktreeId
|
|
1044
|
-
} : void 0;
|
|
1045
|
-
const excludedItems = [
|
|
1046
|
-
...injectionPolicy.excludedItems || [],
|
|
1047
|
-
...suppressedEvidenceIds.map((id) => ({
|
|
1048
|
-
id,
|
|
1049
|
-
section: "recentEvidence",
|
|
1050
|
-
reason: "anti_repetition",
|
|
1051
|
-
score: recentEvidence.find((row) => row.nodeId === id)?.score ?? 0
|
|
1052
|
-
}))
|
|
1053
|
-
];
|
|
1054
|
-
const result = {
|
|
1055
|
-
schemaVersion: CONTEXT_PACK_SCHEMA_VERSION,
|
|
1056
|
-
topicId: snapshot.plan.topicId,
|
|
1057
|
-
topicName: snapshot.topic.name || "Untitled Topic",
|
|
1058
|
-
scopedTopicIds: snapshot.plan.scopedTopicIds,
|
|
1059
|
-
generatedAt: referenceTimeMs,
|
|
1060
|
-
rankingProfile: snapshot.plan.rankingProfile,
|
|
1061
|
-
summary,
|
|
1062
|
-
invariants,
|
|
1063
|
-
activeBeliefs,
|
|
1064
|
-
openQuestions,
|
|
1065
|
-
recentEvidence: effectiveEvidence,
|
|
1066
|
-
contradictions,
|
|
1067
|
-
...rankedEntities ? { relatedEntities: rankedEntities } : {},
|
|
1068
|
-
contextNarrative,
|
|
1069
|
-
injectionPolicy: {
|
|
1070
|
-
...injectionPolicy,
|
|
1071
|
-
...excludedItems.length > 0 ? { excludedItems } : {}
|
|
1072
|
-
},
|
|
1073
|
-
diagnostics: {
|
|
1074
|
-
itemsScored: invariantCandidates.length + activeBeliefCandidates.length + openQuestionCandidates.length + evidenceCandidates.length + contradictionCandidates.length + entityCandidates.length,
|
|
1075
|
-
tokenBudgetUtilization: injectionPolicy.tokenBudget === 0 ? 0 : Number(
|
|
1076
|
-
(injectionPolicy.estimatedTokens / injectionPolicy.tokenBudget).toFixed(4)
|
|
1077
|
-
),
|
|
1078
|
-
referenceTimeMs
|
|
1079
|
-
},
|
|
1080
|
-
...snapshot.plan.compilationMode !== "standard" ? { compilationMode: snapshot.plan.compilationMode } : {},
|
|
1081
|
-
...failureContext ? { failureContext } : {},
|
|
1082
|
-
...deltaReport ? { deltaReport } : {},
|
|
1083
|
-
...snapshot.plan.packWeightOverrides && snapshot.plan.packWeightOverrides.length > 0 ? { appliedWeightOverrides: snapshot.plan.packWeightOverrides } : {}
|
|
1084
|
-
};
|
|
1085
|
-
assertContextPackSchema(result);
|
|
1086
|
-
return result;
|
|
1087
|
-
}
|
|
1088
|
-
|
|
1089
|
-
export { compileContextPackFromSnapshot, planContextPackCompilation };
|
|
1090
|
-
//# sourceMappingURL=contextPackCompiler.js.map
|
|
1091
|
-
//# sourceMappingURL=contextPackCompiler.js.map
|