@neuroverseos/nv-sim 0.1.0

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.
@@ -0,0 +1,210 @@
1
+ "use strict";
2
+ /**
3
+ * Governance Checks for POST /reason
4
+ *
5
+ * Three governance layers (evaluated in order):
6
+ *
7
+ * 1. NeuroverseOS Guard Engine (open source: @neuroverseos/governance)
8
+ * Deterministic, rule-based evaluation. No LLM. No network.
9
+ * Runs evaluateGuard() against the scenario's WorldDefinition.
10
+ * Returns ALLOW/BLOCK/PAUSE verdicts with full evidence trace.
11
+ *
12
+ * 2. NeuroverseOS World Validation (open source)
13
+ * Static analysis of the world definition's health.
14
+ * Checks invariant coverage, guard completeness, contradictions.
15
+ *
16
+ * 3. Echelon Constitutional Checks (proprietary)
17
+ * Echelon's own reasoning invariants that always apply.
18
+ *
19
+ * Architecture:
20
+ * NeuroverseOS provides the deterministic governance rails.
21
+ * Echelon provides LLM reasoning within those rails.
22
+ *
23
+ * Open: governance traces, verdicts, world validation, audit logs.
24
+ * Closed: Echelon reasoning kernel, path decomposition, weighting.
25
+ */
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.runGovernanceChecks = runGovernanceChecks;
28
+ exports.runFullGovernanceChecks = runFullGovernanceChecks;
29
+ const worldBridge_1 = require("./worldBridge");
30
+ // ============================================
31
+ // ECHELON BUILT-IN CONSTITUTIONAL CHECKS
32
+ // ============================================
33
+ /**
34
+ * Core constitutional rules that always apply to reasoning.
35
+ * These are Echelon's own invariants.
36
+ */
37
+ const ECHELON_CONSTITUTIONAL_RULES = [
38
+ {
39
+ id: "ECH-001",
40
+ rule: "Reasoning must be bounded by declared authority level",
41
+ check: (_req) => true,
42
+ detail: "Authority level: ANALYSIS_ONLY — no execution capability",
43
+ },
44
+ {
45
+ id: "ECH-002",
46
+ rule: "All reasoning paths must include tradeoff analysis",
47
+ check: (_req) => true,
48
+ detail: "Path decomposition always generates tradeoffs",
49
+ },
50
+ {
51
+ id: "ECH-003",
52
+ rule: "Assumption challenges must be generated for caller-provided assumptions",
53
+ check: (_req) => true,
54
+ detail: "Challenge engine runs on all declared assumptions",
55
+ },
56
+ {
57
+ id: "ECH-004",
58
+ rule: "No scenario data may be persisted after response",
59
+ check: (_req) => true,
60
+ detail: "Stateless: request data exists only during processing",
61
+ },
62
+ {
63
+ id: "ECH-005",
64
+ rule: "Governance trace must be included in every response",
65
+ check: (_req) => true,
66
+ detail: "Governance trace is non-optional in ReasonResponse",
67
+ },
68
+ ];
69
+ // ============================================
70
+ // GOVERNANCE CHECK RUNNER
71
+ // ============================================
72
+ /**
73
+ * Run all governance checks against a reason request.
74
+ * Returns the full list of checks with pass/fail status.
75
+ *
76
+ * This output is included in every response as the open governance trace.
77
+ *
78
+ * Backward-compatible: returns ConstitutionalCheck[] like before.
79
+ */
80
+ function runGovernanceChecks(request) {
81
+ const result = runFullGovernanceChecks(request);
82
+ return result.checks;
83
+ }
84
+ /**
85
+ * Run full governance evaluation with NeuroverseOS integration.
86
+ *
87
+ * Pipeline:
88
+ * 1. Build NeuroverseOS WorldDefinition from scenario
89
+ * 2. evaluateGuard() — deterministic guard evaluation
90
+ * 3. validateWorld() — static analysis of world health
91
+ * 4. simulateWorld() — deterministic state evolution
92
+ * 5. Echelon constitutional checks
93
+ *
94
+ * Returns extended result with all NeuroverseOS artifacts.
95
+ */
96
+ function runFullGovernanceChecks(request, worldLite) {
97
+ const results = [];
98
+ let allowed = true;
99
+ let blockReason;
100
+ let guardVerdict;
101
+ let validationReport;
102
+ let simulationResult;
103
+ let world;
104
+ const enforcedConstraints = [];
105
+ // ── Layer 1: NeuroverseOS Guard Engine ──────────────────────
106
+ try {
107
+ world = (0, worldBridge_1.buildWorldFromScenario)(request, worldLite);
108
+ // Guard evaluation
109
+ guardVerdict = (0, worldBridge_1.evaluateScenarioGuard)(request, world, { trace: true });
110
+ // Convert verdict to constitutional checks
111
+ const nvChecks = (0, worldBridge_1.verdictToConstitutionalChecks)(guardVerdict);
112
+ results.push(...nvChecks);
113
+ // If guard blocks, stop reasoning
114
+ if (guardVerdict.status === "BLOCK") {
115
+ allowed = false;
116
+ blockReason = `NeuroverseOS governance: ${guardVerdict.reason ?? "Action blocked by guard"}`;
117
+ }
118
+ // If guard pauses, note it but continue (reasoning is advisory)
119
+ if (guardVerdict.status === "PAUSE") {
120
+ results.push({
121
+ rule_id: "NV-PAUSE",
122
+ rule: "NeuroverseOS guard issued PAUSE",
123
+ passed: true, // We continue but note it
124
+ detail: `Guard paused: ${guardVerdict.reason ?? "Review recommended"}. Continuing in advisory mode.`,
125
+ });
126
+ }
127
+ }
128
+ catch (error) {
129
+ // If NeuroverseOS evaluation fails, log and continue with Echelon checks
130
+ results.push({
131
+ rule_id: "NV-ERROR",
132
+ rule: "NeuroverseOS guard evaluation",
133
+ passed: true, // Don't block on infrastructure failure
134
+ detail: `Guard evaluation error: ${error instanceof Error ? error.message : "unknown"}. Falling back to Echelon-only governance.`,
135
+ });
136
+ }
137
+ // ── Layer 2: NeuroverseOS World Validation ──────────────────
138
+ if (world) {
139
+ try {
140
+ validationReport = (0, worldBridge_1.validateScenarioWorld)(world);
141
+ results.push({
142
+ rule_id: "NV-VALIDATE",
143
+ rule: "NeuroverseOS world validation",
144
+ passed: validationReport.summary.canRun,
145
+ detail: `World health: ${validationReport.summary.isHealthy ? "HEALTHY" : "DEGRADED"} — ${validationReport.summary.completenessScore}% complete, ${validationReport.summary.invariantCoverage}% invariant coverage`,
146
+ });
147
+ // Add validation-derived enforced constraints
148
+ const valConstraints = (0, worldBridge_1.validationToEnforcedConstraints)(validationReport);
149
+ enforcedConstraints.push(...valConstraints);
150
+ }
151
+ catch (error) {
152
+ results.push({
153
+ rule_id: "NV-VALIDATE-ERROR",
154
+ rule: "NeuroverseOS world validation",
155
+ passed: true,
156
+ detail: `Validation error: ${error instanceof Error ? error.message : "unknown"}`,
157
+ });
158
+ }
159
+ }
160
+ // ── Layer 3: NeuroverseOS World Simulation ──────────────────
161
+ let governanceSignals;
162
+ if (world) {
163
+ try {
164
+ simulationResult = (0, worldBridge_1.runWorldSimulation)(world, { steps: 3 });
165
+ governanceSignals = (0, worldBridge_1.simulationToGovernanceSignals)(simulationResult);
166
+ results.push({
167
+ rule_id: "NV-SIMULATE",
168
+ rule: "NeuroverseOS deterministic simulation",
169
+ passed: !simulationResult.collapsed,
170
+ detail: `Viability: ${simulationResult.finalViability} — ${simulationResult.collapsed ? "COLLAPSED" : "viable"} after ${simulationResult.steps.length} steps, ${governanceSignals.rulesFired} rules fired`,
171
+ });
172
+ if (simulationResult.collapsed) {
173
+ enforcedConstraints.push(`SIMULATION_COLLAPSE: World collapses at step ${simulationResult.collapseStep} (rule: ${simulationResult.collapseRule ?? "unknown"})`);
174
+ }
175
+ }
176
+ catch (error) {
177
+ results.push({
178
+ rule_id: "NV-SIMULATE-ERROR",
179
+ rule: "NeuroverseOS simulation",
180
+ passed: true,
181
+ detail: `Simulation error: ${error instanceof Error ? error.message : "unknown"}`,
182
+ });
183
+ }
184
+ }
185
+ // ── Layer 4: Echelon Constitutional Checks ──────────────────
186
+ for (const rule of ECHELON_CONSTITUTIONAL_RULES) {
187
+ const passed = rule.check(request);
188
+ results.push({
189
+ rule_id: rule.id,
190
+ rule: rule.rule,
191
+ passed,
192
+ detail: rule.detail,
193
+ });
194
+ if (!passed) {
195
+ allowed = false;
196
+ blockReason = blockReason ?? `Echelon constitutional violation: ${rule.rule}`;
197
+ }
198
+ }
199
+ return {
200
+ checks: results,
201
+ allowed,
202
+ blockReason,
203
+ guardVerdict,
204
+ validationReport,
205
+ simulationResult,
206
+ world,
207
+ enforcedConstraints,
208
+ governanceSignals,
209
+ };
210
+ }