@neuroverseos/governance 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/package.json +4 -2
  2. package/policies/content-moderation-rules.txt +8 -0
  3. package/policies/marketing-rules.txt +8 -0
  4. package/policies/science-research-rules.txt +11 -0
  5. package/policies/social-media-rules.txt +7 -0
  6. package/policies/strict-rules.txt +8 -0
  7. package/policies/trading-rules.txt +8 -0
  8. package/simulate.html +1899 -0
  9. package/dist/adapters/autoresearch.cjs +0 -196
  10. package/dist/adapters/autoresearch.d.cts +0 -103
  11. package/dist/adapters/autoresearch.d.ts +0 -103
  12. package/dist/adapters/autoresearch.js +0 -7
  13. package/dist/adapters/deep-agents.cjs +0 -1472
  14. package/dist/adapters/deep-agents.d.cts +0 -181
  15. package/dist/adapters/deep-agents.d.ts +0 -181
  16. package/dist/adapters/deep-agents.js +0 -17
  17. package/dist/adapters/express.cjs +0 -1196
  18. package/dist/adapters/express.d.cts +0 -66
  19. package/dist/adapters/express.d.ts +0 -66
  20. package/dist/adapters/express.js +0 -12
  21. package/dist/adapters/index.cjs +0 -2038
  22. package/dist/adapters/index.d.cts +0 -8
  23. package/dist/adapters/index.d.ts +0 -8
  24. package/dist/adapters/index.js +0 -68
  25. package/dist/adapters/langchain.cjs +0 -1259
  26. package/dist/adapters/langchain.d.cts +0 -89
  27. package/dist/adapters/langchain.d.ts +0 -89
  28. package/dist/adapters/langchain.js +0 -17
  29. package/dist/adapters/openai.cjs +0 -1289
  30. package/dist/adapters/openai.d.cts +0 -99
  31. package/dist/adapters/openai.d.ts +0 -99
  32. package/dist/adapters/openai.js +0 -17
  33. package/dist/adapters/openclaw.cjs +0 -1281
  34. package/dist/adapters/openclaw.d.cts +0 -99
  35. package/dist/adapters/openclaw.d.ts +0 -99
  36. package/dist/adapters/openclaw.js +0 -17
  37. package/dist/bootstrap-GXVDZNF7.js +0 -114
  38. package/dist/build-X5MZY4IA.js +0 -339
  39. package/dist/chunk-4L6OPKMQ.js +0 -100
  40. package/dist/chunk-4NGDRRQH.js +0 -10
  41. package/dist/chunk-5U2MQO5P.js +0 -57
  42. package/dist/chunk-6BB55YJI.js +0 -113
  43. package/dist/chunk-6CZSKEY5.js +0 -164
  44. package/dist/chunk-7P3S7MAY.js +0 -1090
  45. package/dist/chunk-A5W4GNQO.js +0 -130
  46. package/dist/chunk-AF2VX4AL.js +0 -363
  47. package/dist/chunk-AKW5YVCE.js +0 -96
  48. package/dist/chunk-BMOXICAB.js +0 -340
  49. package/dist/chunk-BQZMOEML.js +0 -43
  50. package/dist/chunk-D2UCV5AK.js +0 -326
  51. package/dist/chunk-EVDJUSZ2.js +0 -91
  52. package/dist/chunk-FYS2CBUW.js +0 -304
  53. package/dist/chunk-I3RRAYK2.js +0 -11
  54. package/dist/chunk-IZSO75NZ.js +0 -792
  55. package/dist/chunk-JCKSW2PZ.js +0 -304
  56. package/dist/chunk-JZPQGIKR.js +0 -79
  57. package/dist/chunk-KTFTTLTP.js +0 -246
  58. package/dist/chunk-MH7BT4VH.js +0 -15
  59. package/dist/chunk-ORJ3NOE6.js +0 -622
  60. package/dist/chunk-OT6PXH54.js +0 -61
  61. package/dist/chunk-Q6O7ZLO2.js +0 -62
  62. package/dist/chunk-QLPTHTVB.js +0 -253
  63. package/dist/chunk-REXY4LUL.js +0 -226
  64. package/dist/chunk-T5EUJQE5.js +0 -172
  65. package/dist/chunk-TTBKTF3P.js +0 -608
  66. package/dist/chunk-XPDMYECO.js +0 -642
  67. package/dist/chunk-YZFATT7X.js +0 -9
  68. package/dist/chunk-ZIVQNSZU.js +0 -119
  69. package/dist/chunk-ZJTDUCC2.js +0 -194
  70. package/dist/cli/neuroverse.cjs +0 -12564
  71. package/dist/cli/neuroverse.d.cts +0 -1
  72. package/dist/cli/neuroverse.d.ts +0 -1
  73. package/dist/cli/neuroverse.js +0 -208
  74. package/dist/cli/plan.cjs +0 -1686
  75. package/dist/cli/plan.d.cts +0 -20
  76. package/dist/cli/plan.d.ts +0 -20
  77. package/dist/cli/plan.js +0 -353
  78. package/dist/cli/run.cjs +0 -1945
  79. package/dist/cli/run.d.cts +0 -20
  80. package/dist/cli/run.d.ts +0 -20
  81. package/dist/cli/run.js +0 -143
  82. package/dist/configure-ai-TK67ZWZL.js +0 -132
  83. package/dist/decision-flow-LETV5NWY.js +0 -61
  84. package/dist/derive-7365SUFU.js +0 -152
  85. package/dist/doctor-QYISMKEL.js +0 -173
  86. package/dist/equity-penalties-63FGB3I2.js +0 -244
  87. package/dist/explain-A2EWI2OL.js +0 -51
  88. package/dist/guard-3BWL3IGH.js +0 -92
  89. package/dist/guard-contract-C9_zKbzd.d.cts +0 -821
  90. package/dist/guard-contract-C9_zKbzd.d.ts +0 -821
  91. package/dist/guard-engine-QFMIBWJY.js +0 -10
  92. package/dist/impact-UB6DXKSX.js +0 -59
  93. package/dist/improve-XZA57GER.js +0 -66
  94. package/dist/index.cjs +0 -6821
  95. package/dist/index.d.cts +0 -1829
  96. package/dist/index.d.ts +0 -1829
  97. package/dist/index.js +0 -430
  98. package/dist/infer-world-7GVZWFX4.js +0 -543
  99. package/dist/init-PKPIYHYE.js +0 -144
  100. package/dist/init-world-VWMQZQC7.js +0 -223
  101. package/dist/mcp-server-XWQZXNW7.js +0 -13
  102. package/dist/model-adapter-BB7G4MFI.js +0 -11
  103. package/dist/playground-ADWZORNV.js +0 -550
  104. package/dist/redteam-JRQ7FD2F.js +0 -357
  105. package/dist/session-MMYX5YCF.js +0 -15
  106. package/dist/shared--Q8wPBVN.d.ts +0 -60
  107. package/dist/shared-HpAG90PX.d.cts +0 -60
  108. package/dist/shared-U2QFV7JH.js +0 -16
  109. package/dist/simulate-GMIFFXYV.js +0 -83
  110. package/dist/test-JBBZ65X4.js +0 -217
  111. package/dist/trace-3MYWIDEF.js +0 -166
  112. package/dist/validate-LLBWVPGV.js +0 -81
  113. package/dist/validate-engine-UIABSIHD.js +0 -7
  114. package/dist/world-BFJCIQSH.js +0 -378
  115. package/dist/world-loader-HMPTOEA2.js +0 -9
  116. package/dist/worlds/autoresearch.nv-world.md +0 -230
  117. package/dist/worlds/coding-agent.nv-world.md +0 -211
  118. package/dist/worlds/derivation-world.nv-world.md +0 -278
@@ -1,99 +0,0 @@
1
- import { a as GuardVerdict, b as GuardEngineOptions, P as PlanDefinition, W as WorldDefinition, G as GuardEvent, c as PlanProgress } from '../guard-contract-C9_zKbzd.cjs';
2
- import { G as GovernanceBlockedError$1 } from '../shared-HpAG90PX.cjs';
3
-
4
- /**
5
- * NeuroVerse Adapter — OpenClaw
6
- *
7
- * Integrates NeuroVerse governance as an OpenClaw plugin.
8
- * Provides pre-action and post-action governance hooks that
9
- * evaluate agent actions against a world definition.
10
- *
11
- * Usage:
12
- * import { createNeuroVersePlugin } from 'neuroverse-governance/adapters/openclaw';
13
- *
14
- * const plugin = await createNeuroVersePlugin('./world/');
15
- * agent.use(plugin);
16
- */
17
-
18
- /** Generic agent action shape (OpenClaw-compatible). */
19
- interface AgentAction {
20
- type: string;
21
- tool?: string;
22
- input?: Record<string, unknown>;
23
- metadata?: Record<string, unknown>;
24
- }
25
- /** Plugin hook result. */
26
- interface HookResult {
27
- allowed: boolean;
28
- verdict: GuardVerdict;
29
- action: AgentAction;
30
- }
31
- interface NeuroVersePluginOptions {
32
- /** Include full evaluation trace. Default: false. */
33
- trace?: boolean;
34
- /** Enforcement level override. */
35
- level?: 'basic' | 'standard' | 'strict';
36
- /** Called for every evaluation. */
37
- onEvaluate?: (result: HookResult) => void;
38
- /** Custom action → GuardEvent mapping. */
39
- mapAction?: (action: AgentAction, direction: 'input' | 'output') => GuardEvent;
40
- /** Whether to evaluate output actions (post-action). Default: false. */
41
- evaluateOutputs?: boolean;
42
- /** Active plan overlay for task-scoped governance. */
43
- plan?: PlanDefinition;
44
- /** Called when plan progress changes. */
45
- onPlanProgress?: (progress: PlanProgress) => void;
46
- /** Called when all plan steps are completed. */
47
- onPlanComplete?: () => void;
48
- }
49
- declare class GovernanceBlockedError extends GovernanceBlockedError$1 {
50
- readonly action: AgentAction;
51
- constructor(verdict: GuardVerdict, action: AgentAction);
52
- }
53
- /**
54
- * NeuroVerse governance plugin for OpenClaw agents.
55
- *
56
- * Provides two hooks:
57
- * - beforeAction: evaluates before the agent executes an action
58
- * - afterAction: optionally evaluates outputs for post-action governance
59
- */
60
- declare class NeuroVersePlugin {
61
- readonly name = "neuroverse-governance";
62
- private world;
63
- private options;
64
- engineOptions: GuardEngineOptions;
65
- private mapAction;
66
- activePlan?: PlanDefinition;
67
- constructor(world: WorldDefinition, options?: NeuroVersePluginOptions);
68
- /**
69
- * Evaluate an action before execution.
70
- *
71
- * @throws GovernanceBlockedError if BLOCKED
72
- * @returns HookResult with verdict details
73
- */
74
- beforeAction(action: AgentAction): HookResult;
75
- /**
76
- * Evaluate an action's output (post-execution governance).
77
- * Only runs if evaluateOutputs is enabled.
78
- *
79
- * @returns HookResult or null if output evaluation is disabled
80
- */
81
- afterAction(action: AgentAction, _output?: unknown): HookResult | null;
82
- /**
83
- * Get the plugin hooks object for agent.use().
84
- */
85
- hooks(): {
86
- beforeAction: (action: AgentAction) => HookResult;
87
- afterAction: (action: AgentAction, output?: unknown) => HookResult;
88
- };
89
- }
90
- /**
91
- * Create a NeuroVerse plugin from a world path.
92
- */
93
- declare function createNeuroVersePlugin(worldPath: string, options?: NeuroVersePluginOptions): Promise<NeuroVersePlugin>;
94
- /**
95
- * Create a NeuroVerse plugin from a pre-loaded world.
96
- */
97
- declare function createNeuroVersePluginFromWorld(world: WorldDefinition, options?: NeuroVersePluginOptions): NeuroVersePlugin;
98
-
99
- export { type AgentAction, GovernanceBlockedError, type HookResult, NeuroVersePlugin, type NeuroVersePluginOptions, createNeuroVersePlugin, createNeuroVersePluginFromWorld };
@@ -1,99 +0,0 @@
1
- import { a as GuardVerdict, b as GuardEngineOptions, P as PlanDefinition, W as WorldDefinition, G as GuardEvent, c as PlanProgress } from '../guard-contract-C9_zKbzd.js';
2
- import { G as GovernanceBlockedError$1 } from '../shared--Q8wPBVN.js';
3
-
4
- /**
5
- * NeuroVerse Adapter — OpenClaw
6
- *
7
- * Integrates NeuroVerse governance as an OpenClaw plugin.
8
- * Provides pre-action and post-action governance hooks that
9
- * evaluate agent actions against a world definition.
10
- *
11
- * Usage:
12
- * import { createNeuroVersePlugin } from 'neuroverse-governance/adapters/openclaw';
13
- *
14
- * const plugin = await createNeuroVersePlugin('./world/');
15
- * agent.use(plugin);
16
- */
17
-
18
- /** Generic agent action shape (OpenClaw-compatible). */
19
- interface AgentAction {
20
- type: string;
21
- tool?: string;
22
- input?: Record<string, unknown>;
23
- metadata?: Record<string, unknown>;
24
- }
25
- /** Plugin hook result. */
26
- interface HookResult {
27
- allowed: boolean;
28
- verdict: GuardVerdict;
29
- action: AgentAction;
30
- }
31
- interface NeuroVersePluginOptions {
32
- /** Include full evaluation trace. Default: false. */
33
- trace?: boolean;
34
- /** Enforcement level override. */
35
- level?: 'basic' | 'standard' | 'strict';
36
- /** Called for every evaluation. */
37
- onEvaluate?: (result: HookResult) => void;
38
- /** Custom action → GuardEvent mapping. */
39
- mapAction?: (action: AgentAction, direction: 'input' | 'output') => GuardEvent;
40
- /** Whether to evaluate output actions (post-action). Default: false. */
41
- evaluateOutputs?: boolean;
42
- /** Active plan overlay for task-scoped governance. */
43
- plan?: PlanDefinition;
44
- /** Called when plan progress changes. */
45
- onPlanProgress?: (progress: PlanProgress) => void;
46
- /** Called when all plan steps are completed. */
47
- onPlanComplete?: () => void;
48
- }
49
- declare class GovernanceBlockedError extends GovernanceBlockedError$1 {
50
- readonly action: AgentAction;
51
- constructor(verdict: GuardVerdict, action: AgentAction);
52
- }
53
- /**
54
- * NeuroVerse governance plugin for OpenClaw agents.
55
- *
56
- * Provides two hooks:
57
- * - beforeAction: evaluates before the agent executes an action
58
- * - afterAction: optionally evaluates outputs for post-action governance
59
- */
60
- declare class NeuroVersePlugin {
61
- readonly name = "neuroverse-governance";
62
- private world;
63
- private options;
64
- engineOptions: GuardEngineOptions;
65
- private mapAction;
66
- activePlan?: PlanDefinition;
67
- constructor(world: WorldDefinition, options?: NeuroVersePluginOptions);
68
- /**
69
- * Evaluate an action before execution.
70
- *
71
- * @throws GovernanceBlockedError if BLOCKED
72
- * @returns HookResult with verdict details
73
- */
74
- beforeAction(action: AgentAction): HookResult;
75
- /**
76
- * Evaluate an action's output (post-execution governance).
77
- * Only runs if evaluateOutputs is enabled.
78
- *
79
- * @returns HookResult or null if output evaluation is disabled
80
- */
81
- afterAction(action: AgentAction, _output?: unknown): HookResult | null;
82
- /**
83
- * Get the plugin hooks object for agent.use().
84
- */
85
- hooks(): {
86
- beforeAction: (action: AgentAction) => HookResult;
87
- afterAction: (action: AgentAction, output?: unknown) => HookResult;
88
- };
89
- }
90
- /**
91
- * Create a NeuroVerse plugin from a world path.
92
- */
93
- declare function createNeuroVersePlugin(worldPath: string, options?: NeuroVersePluginOptions): Promise<NeuroVersePlugin>;
94
- /**
95
- * Create a NeuroVerse plugin from a pre-loaded world.
96
- */
97
- declare function createNeuroVersePluginFromWorld(world: WorldDefinition, options?: NeuroVersePluginOptions): NeuroVersePlugin;
98
-
99
- export { type AgentAction, GovernanceBlockedError, type HookResult, NeuroVersePlugin, type NeuroVersePluginOptions, createNeuroVersePlugin, createNeuroVersePluginFromWorld };
@@ -1,17 +0,0 @@
1
- import {
2
- GovernanceBlockedError,
3
- NeuroVersePlugin,
4
- createNeuroVersePlugin,
5
- createNeuroVersePluginFromWorld
6
- } from "../chunk-6BB55YJI.js";
7
- import "../chunk-5U2MQO5P.js";
8
- import "../chunk-IZSO75NZ.js";
9
- import "../chunk-QLPTHTVB.js";
10
- import "../chunk-JZPQGIKR.js";
11
- import "../chunk-YZFATT7X.js";
12
- export {
13
- GovernanceBlockedError,
14
- NeuroVersePlugin,
15
- createNeuroVersePlugin,
16
- createNeuroVersePluginFromWorld
17
- };
@@ -1,114 +0,0 @@
1
- import {
2
- BOOTSTRAP_EXIT_CODES
3
- } from "./chunk-4NGDRRQH.js";
4
- import {
5
- emitWorldDefinition,
6
- parseWorldMarkdown
7
- } from "./chunk-XPDMYECO.js";
8
- import "./chunk-YZFATT7X.js";
9
-
10
- // src/cli/bootstrap.ts
11
- function parseArgs(argv) {
12
- let inputPath = "";
13
- let outputPath = "";
14
- let validate = false;
15
- let format = "full";
16
- for (let i = 0; i < argv.length; i++) {
17
- const arg = argv[i];
18
- if (arg === "--input" && i + 1 < argv.length) {
19
- inputPath = argv[++i];
20
- } else if (arg === "--output" && i + 1 < argv.length) {
21
- outputPath = argv[++i];
22
- } else if (arg === "--validate") {
23
- validate = true;
24
- } else if (arg === "--format" && i + 1 < argv.length) {
25
- const val = argv[++i];
26
- if (val === "full" || val === "summary") format = val;
27
- }
28
- }
29
- if (!inputPath) throw new Error("--input <path> is required");
30
- if (!outputPath) throw new Error("--output <path> is required");
31
- return { inputPath, outputPath, validate, format };
32
- }
33
- async function writeWorldFiles(outputDir, world) {
34
- const { writeFile, mkdir } = await import("fs/promises");
35
- const { join } = await import("path");
36
- await mkdir(outputDir, { recursive: true });
37
- await writeFile(join(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
38
- await writeFile(join(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
39
- await writeFile(join(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
40
- await writeFile(join(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
41
- const rulesDir = join(outputDir, "rules");
42
- await mkdir(rulesDir, { recursive: true });
43
- const sortedRules = [...world.rules].sort((a, b) => a.order - b.order);
44
- for (let i = 0; i < sortedRules.length; i++) {
45
- const ruleNum = String(i + 1).padStart(3, "0");
46
- await writeFile(join(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
47
- }
48
- await writeFile(join(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
49
- await writeFile(join(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
50
- await writeFile(join(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
51
- }
52
- async function main(argv = process.argv.slice(2)) {
53
- const startTime = performance.now();
54
- try {
55
- const args = parseArgs(argv);
56
- const { readFile } = await import("fs/promises");
57
- let markdown;
58
- try {
59
- markdown = await readFile(args.inputPath, "utf-8");
60
- } catch {
61
- const errorResult = { error: `Cannot read file: ${args.inputPath}` };
62
- process.stderr.write(JSON.stringify(errorResult, null, 2) + "\n");
63
- process.exit(BOOTSTRAP_EXIT_CODES.ERROR);
64
- return;
65
- }
66
- const parseResult = parseWorldMarkdown(markdown);
67
- const parseErrors = parseResult.issues.filter((i) => i.severity === "error");
68
- if (parseErrors.length > 0 || !parseResult.world) {
69
- const result2 = {
70
- success: false,
71
- sourcePath: args.inputPath,
72
- issues: parseResult.issues,
73
- parsedSections: [],
74
- durationMs: performance.now() - startTime
75
- };
76
- process.stdout.write(JSON.stringify(result2, null, 2) + "\n");
77
- process.exit(BOOTSTRAP_EXIT_CODES.FAIL);
78
- return;
79
- }
80
- const emitResult = emitWorldDefinition(parseResult.world);
81
- const allIssues = [...parseResult.issues, ...emitResult.issues];
82
- await writeWorldFiles(args.outputPath, emitResult.world);
83
- let validateReport;
84
- if (args.validate) {
85
- const { validateWorld } = await import("./validate-engine-UIABSIHD.js");
86
- validateReport = validateWorld(emitResult.world);
87
- }
88
- const result = {
89
- success: true,
90
- sourcePath: args.inputPath,
91
- issues: allIssues,
92
- parsedSections: Object.keys(parseResult.world).filter((k) => {
93
- const val = parseResult.world[k];
94
- if (Array.isArray(val)) return val.length > 0;
95
- if (typeof val === "string") return val.length > 0;
96
- return !!val;
97
- }),
98
- durationMs: performance.now() - startTime
99
- };
100
- if (validateReport) {
101
- result.validateReport = args.format === "summary" ? { summary: validateReport.summary } : validateReport;
102
- }
103
- process.stdout.write(JSON.stringify(result, null, 2) + "\n");
104
- const hasErrors = allIssues.some((i) => i.severity === "error");
105
- process.exit(hasErrors ? BOOTSTRAP_EXIT_CODES.FAIL : BOOTSTRAP_EXIT_CODES.SUCCESS);
106
- } catch (e) {
107
- const errorResult = { error: "Bootstrap failed", detail: String(e) };
108
- process.stderr.write(JSON.stringify(errorResult, null, 2) + "\n");
109
- process.exit(BOOTSTRAP_EXIT_CODES.ERROR);
110
- }
111
- }
112
- export {
113
- main
114
- };
@@ -1,339 +0,0 @@
1
- import {
2
- DeriveInputError,
3
- DeriveProviderError,
4
- deriveWorld
5
- } from "./chunk-ORJ3NOE6.js";
6
- import {
7
- DERIVE_EXIT_CODES
8
- } from "./chunk-Q6O7ZLO2.js";
9
- import {
10
- emitWorldDefinition,
11
- parseWorldMarkdown
12
- } from "./chunk-XPDMYECO.js";
13
- import "./chunk-OT6PXH54.js";
14
- import "./chunk-7P3S7MAY.js";
15
- import "./chunk-YZFATT7X.js";
16
-
17
- // src/cli/build.ts
18
- var FINDING_LABELS = {
19
- "guard-coverage": "STORY INSIGHT",
20
- "semantic-tension": "DRAMATIC TENSION",
21
- "orphan": "MISSING CAUSALITY",
22
- "contradiction": "CONFLICT DETECTED",
23
- "referential-integrity": "BROKEN REFERENCE",
24
- "completeness": "INCOMPLETE STRUCTURE",
25
- "schema-violation": "VALUE OUT OF RANGE"
26
- };
27
- function humanLabel(section) {
28
- const category = section.replace(/^Validate:/, "");
29
- return FINDING_LABELS[category] ?? section.toUpperCase();
30
- }
31
- function traceCausalChains(rules) {
32
- const effectToTrigger = /* @__PURE__ */ new Map();
33
- for (const rule of rules) {
34
- for (const trigger of rule.triggers) {
35
- if (!effectToTrigger.has(trigger.field)) effectToTrigger.set(trigger.field, /* @__PURE__ */ new Set());
36
- effectToTrigger.get(trigger.field).add(rule.id);
37
- }
38
- }
39
- const chains = [];
40
- const ruleById = new Map(rules.map((r) => [r.id, r]));
41
- for (const startRule of rules) {
42
- const chain = [startRule.effects[0]?.target].filter(Boolean);
43
- if (chain.length === 0) continue;
44
- const visited = /* @__PURE__ */ new Set([startRule.id]);
45
- let current = startRule;
46
- for (let depth = 0; depth < 5; depth++) {
47
- const lastTarget = current.effects[0]?.target;
48
- if (!lastTarget) break;
49
- const triggeredRuleIds = effectToTrigger.get(lastTarget);
50
- if (!triggeredRuleIds) break;
51
- let nextRule;
52
- for (const id of triggeredRuleIds) {
53
- if (!visited.has(id)) {
54
- nextRule = ruleById.get(id);
55
- break;
56
- }
57
- }
58
- if (!nextRule) break;
59
- visited.add(nextRule.id);
60
- const nextTarget = nextRule.effects[0]?.target;
61
- if (nextTarget && !chain.includes(nextTarget)) {
62
- chain.push(nextTarget);
63
- }
64
- current = nextRule;
65
- }
66
- if (chain.length >= 2) {
67
- chains.push(chain);
68
- }
69
- }
70
- const sorted = chains.sort((a, b) => b.length - a.length);
71
- const unique = [];
72
- for (const chain of sorted) {
73
- const key = chain.join(" -> ");
74
- const isSubset = unique.some((existing) => existing.join(" -> ").includes(key));
75
- if (!isSubset) unique.push(chain);
76
- }
77
- return unique.slice(0, 3);
78
- }
79
- function renderGovernanceHealth(health) {
80
- const lines = [];
81
- lines.push("GOVERNANCE HEALTH");
82
- lines.push(` Coverage: ${health.surfacesCovered} / ${health.surfacesTotal} action surfaces governed`);
83
- lines.push(` Invariants enforced: ${health.invariantsEnforced} / ${health.invariantsTotal}`);
84
- if (health.shadowedGuards > 0) {
85
- lines.push(` Shadowed guards: ${health.shadowedGuards}`);
86
- }
87
- if (health.unenforcedInvariants > 0) {
88
- lines.push(` Unenforced invariants: ${health.unenforcedInvariants}`);
89
- }
90
- if (health.unreachableRules > 0) {
91
- lines.push(` Unreachable rules: ${health.unreachableRules}`);
92
- }
93
- if (health.incompleteStateCoverage > 0) {
94
- lines.push(` Incomplete state coverage: ${health.incompleteStateCoverage}`);
95
- }
96
- if (health.surfaces.length > 0) {
97
- lines.push("");
98
- lines.push(" Surfaces:");
99
- for (const s of health.surfaces) {
100
- lines.push(` ${s.name}: ${s.governed ? "governed" : "unguarded"}`);
101
- }
102
- }
103
- lines.push("");
104
- lines.push(` Risk level: ${health.riskLevel.charAt(0).toUpperCase() + health.riskLevel.slice(1)}`);
105
- return lines.join("\n");
106
- }
107
- function parseArgs(argv) {
108
- let inputPath = "";
109
- let outputDir;
110
- let validate = true;
111
- let dryRun = false;
112
- let provider;
113
- let model;
114
- let endpoint;
115
- for (let i = 0; i < argv.length; i++) {
116
- const arg = argv[i];
117
- if (arg === "--output" && i + 1 < argv.length) {
118
- outputDir = argv[++i];
119
- } else if (arg === "--no-validate") {
120
- validate = false;
121
- } else if (arg === "--dry-run") {
122
- dryRun = true;
123
- } else if (arg === "--provider" && i + 1 < argv.length) {
124
- provider = argv[++i];
125
- } else if (arg === "--model" && i + 1 < argv.length) {
126
- model = argv[++i];
127
- } else if (arg === "--endpoint" && i + 1 < argv.length) {
128
- endpoint = argv[++i];
129
- } else if (!arg.startsWith("--") && !inputPath) {
130
- inputPath = arg;
131
- }
132
- }
133
- if (!inputPath) throw new DeriveInputError("Usage: neuroverse build <input.md> [--output <dir>]");
134
- return { inputPath, outputDir, validate, dryRun, provider, model, endpoint };
135
- }
136
- async function writeWorldFiles(outputDir, world) {
137
- const { writeFile, mkdir } = await import("fs/promises");
138
- const { join } = await import("path");
139
- await mkdir(outputDir, { recursive: true });
140
- await writeFile(join(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
141
- await writeFile(join(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
142
- await writeFile(join(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
143
- await writeFile(join(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
144
- await writeFile(join(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
145
- await writeFile(join(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
146
- await writeFile(join(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
147
- const rulesDir = join(outputDir, "rules");
148
- await mkdir(rulesDir, { recursive: true });
149
- const sortedRules = [...world.rules].sort((a, b) => a.order - b.order);
150
- for (let i = 0; i < sortedRules.length; i++) {
151
- const ruleNum = String(i + 1).padStart(3, "0");
152
- await writeFile(join(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
153
- }
154
- }
155
- function write(msg) {
156
- process.stderr.write(msg);
157
- }
158
- function printInsight(finding) {
159
- const label = humanLabel(finding.section);
160
- const icon = finding.severity === "error" ? "x" : "!";
161
- write(` ${icon} ${label}: ${finding.message}
162
- `);
163
- }
164
- async function main(argv = process.argv.slice(2)) {
165
- try {
166
- const args = parseArgs(argv);
167
- const { basename } = await import("path");
168
- write(`
169
- NeuroVerse World Builder
170
- `);
171
- write(`
172
- Analyzing: ${basename(args.inputPath)}
173
- `);
174
- const derivedPath = args.outputDir ? `${args.outputDir}/source.nv-world.md` : ".neuroverse/build-output.nv-world.md";
175
- const { mkdir } = await import("fs/promises");
176
- const { dirname } = await import("path");
177
- await mkdir(dirname(derivedPath), { recursive: true });
178
- const { result, exitCode, dryRunOutput } = await deriveWorld({
179
- inputPath: args.inputPath,
180
- outputPath: derivedPath,
181
- validate: args.validate,
182
- dryRun: args.dryRun,
183
- providerOverride: args.provider || args.model || args.endpoint ? { provider: args.provider, model: args.model, endpoint: args.endpoint } : void 0
184
- });
185
- if (dryRunOutput) {
186
- process.stdout.write(JSON.stringify({
187
- dryRun: true,
188
- systemPrompt: dryRunOutput.systemPrompt,
189
- userPrompt: dryRunOutput.userPrompt,
190
- durationMs: result.durationMs
191
- }, null, 2) + "\n");
192
- process.exit(DERIVE_EXIT_CODES.SUCCESS);
193
- return;
194
- }
195
- const { readFile } = await import("fs/promises");
196
- const derivedContent = await readFile(derivedPath, "utf-8");
197
- const parseResult = parseWorldMarkdown(derivedContent);
198
- const worldName = parseResult.world?.frontmatter?.name ?? "Derived World";
199
- const worldId = parseResult.world?.frontmatter?.world_id ?? "derived_world";
200
- const thesis = parseResult.world?.thesis ?? "";
201
- write(`
202
- World: ${worldName}
203
- `);
204
- if (thesis) {
205
- const firstLine = thesis.split(/[.\n]/)[0].trim();
206
- if (firstLine) write(`Theme: ${firstLine}
207
- `);
208
- }
209
- const parsedRules = parseResult.world?.rules ?? [];
210
- if (parsedRules.length > 0) {
211
- const chains = traceCausalChains(parsedRules);
212
- if (chains.length > 0) {
213
- write(`
214
- Core dynamics:
215
- `);
216
- for (const chain of chains) {
217
- write(` ${chain.join(" -> ")}
218
- `);
219
- }
220
- }
221
- }
222
- write(`
223
- Structure:
224
- `);
225
- const sectionLabels = {
226
- frontmatter: "Metadata",
227
- thesis: "Thesis",
228
- invariants: "Invariants",
229
- state: "State variables",
230
- assumptions: "Assumptions",
231
- rules: "Rules",
232
- gates: "Gates",
233
- outcomes: "Outcomes"
234
- };
235
- for (const [key, label] of Object.entries(sectionLabels)) {
236
- if (result.sectionsDetected.includes(key)) {
237
- const val = parseResult.world?.[key];
238
- const count = Array.isArray(val) ? ` (${val.length})` : "";
239
- write(` + ${label}${count}
240
- `);
241
- }
242
- }
243
- if (result.normalization) {
244
- const n = result.normalization;
245
- write(`
246
- Auto-corrections: ${n.fixCount}
247
- `);
248
- if (n.invariantIds > 0) write(` - ${n.invariantIds} invariant ID(s) formatted
249
- `);
250
- if (n.gateThresholds > 0) write(` - ${n.gateThresholds} gate threshold(s) converted
251
- `);
252
- if (n.triggerTags > 0) write(` - ${n.triggerTags} trigger(s) tagged
253
- `);
254
- }
255
- const errors = result.findings.filter((f) => f.severity === "error");
256
- const warnings = result.findings.filter((f) => f.severity === "warning");
257
- if (warnings.length > 0) {
258
- write(`
259
- Insights:
260
- `);
261
- for (const w of warnings) printInsight(w);
262
- }
263
- if (errors.length > 0) {
264
- write(`
265
- Issues:
266
- `);
267
- for (const e of errors) printInsight(e);
268
- }
269
- if (exitCode !== 0 || !parseResult.world) {
270
- write(`
271
- World source written to: ${derivedPath}
272
- `);
273
- write(`Fix the issues above, then run: neuroverse build ${derivedPath}
274
-
275
- `);
276
- process.exit(exitCode);
277
- return;
278
- }
279
- const outputDir = args.outputDir ?? `.neuroverse/worlds/${worldId}`;
280
- try {
281
- const emitResult = emitWorldDefinition(parseResult.world);
282
- await writeWorldFiles(outputDir, emitResult.world);
283
- const { join } = await import("path");
284
- const { copyFile } = await import("fs/promises");
285
- const sourceDest = join(outputDir, "source.nv-world.md");
286
- if (derivedPath !== sourceDest) {
287
- await copyFile(derivedPath, sourceDest);
288
- }
289
- write(`
290
- World ready: ${worldId}
291
- `);
292
- write(` ${outputDir}/
293
- `);
294
- } catch (bootstrapError) {
295
- write(`
296
- World source written to: ${derivedPath}
297
- `);
298
- write(`Bootstrap failed: ${bootstrapError instanceof Error ? bootstrapError.message : String(bootstrapError)}
299
- `);
300
- write(`Run: neuroverse bootstrap --input ${derivedPath} --output <dir>
301
-
302
- `);
303
- process.exit(1);
304
- return;
305
- }
306
- write(`
307
- Next steps:
308
- `);
309
- write(` Explore neuroverse explain ${worldId}
310
- `);
311
- write(` Simulate neuroverse simulate ${worldId}
312
- `);
313
- write(` Improve neuroverse improve ${worldId}
314
- `);
315
- write(`
316
- `);
317
- process.exit(0);
318
- } catch (e) {
319
- if (e instanceof DeriveInputError) {
320
- process.stderr.write(`Input error: ${e.message}
321
- `);
322
- process.exit(DERIVE_EXIT_CODES.INPUT_ERROR);
323
- } else if (e instanceof DeriveProviderError) {
324
- process.stderr.write(`Provider error: ${e.message}
325
- `);
326
- process.exit(DERIVE_EXIT_CODES.PROVIDER_ERROR);
327
- } else {
328
- process.stderr.write(`Build failed: ${e instanceof Error ? e.message : String(e)}
329
- `);
330
- process.exit(DERIVE_EXIT_CODES.PROVIDER_ERROR);
331
- }
332
- }
333
- }
334
- export {
335
- humanLabel,
336
- main,
337
- renderGovernanceHealth,
338
- traceCausalChains
339
- };