@neuroverseos/governance 0.5.0 → 0.6.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.
Files changed (133) hide show
  1. package/README.md +244 -0
  2. package/dist/adapters/autoresearch.d.cts +2 -1
  3. package/dist/adapters/autoresearch.d.ts +2 -1
  4. package/dist/adapters/autoresearch.js +2 -2
  5. package/dist/adapters/deep-agents.d.cts +3 -2
  6. package/dist/adapters/deep-agents.d.ts +3 -2
  7. package/dist/adapters/deep-agents.js +2 -2
  8. package/dist/adapters/express.d.cts +2 -1
  9. package/dist/adapters/express.d.ts +2 -1
  10. package/dist/adapters/express.js +2 -2
  11. package/dist/adapters/github.cjs +1697 -0
  12. package/dist/adapters/github.d.cts +225 -0
  13. package/dist/adapters/github.d.ts +225 -0
  14. package/dist/adapters/github.js +27 -0
  15. package/dist/adapters/index.d.cts +4 -316
  16. package/dist/adapters/index.d.ts +4 -316
  17. package/dist/adapters/index.js +23 -21
  18. package/dist/adapters/langchain.d.cts +3 -2
  19. package/dist/adapters/langchain.d.ts +3 -2
  20. package/dist/adapters/langchain.js +2 -2
  21. package/dist/adapters/mentraos.cjs +2181 -0
  22. package/dist/adapters/mentraos.d.cts +319 -0
  23. package/dist/adapters/mentraos.d.ts +319 -0
  24. package/dist/{mentraos-LLH7KEV4.js → adapters/mentraos.js} +12 -10
  25. package/dist/adapters/openai.d.cts +3 -2
  26. package/dist/adapters/openai.d.ts +3 -2
  27. package/dist/adapters/openai.js +2 -2
  28. package/dist/adapters/openclaw.d.cts +3 -2
  29. package/dist/adapters/openclaw.d.ts +3 -2
  30. package/dist/adapters/openclaw.js +2 -2
  31. package/dist/{add-LYHDZ5RL.js → add-XSANI3FK.js} +1 -1
  32. package/dist/admin/index.cjs +2214 -0
  33. package/dist/admin/index.d.cts +362 -0
  34. package/dist/admin/index.d.ts +362 -0
  35. package/dist/admin/index.js +703 -0
  36. package/dist/bootstrap-contract-DcV6t-8M.d.cts +216 -0
  37. package/dist/bootstrap-contract-DcV6t-8M.d.ts +216 -0
  38. package/dist/{build-SCAWPA7E.js → build-UTVDGHB3.js} +5 -5
  39. package/dist/{chunk-JKGPSFGH.js → chunk-7FL3U7Z5.js} +3 -3
  40. package/dist/chunk-A2UZTLRV.js +421 -0
  41. package/dist/{chunk-TD5GKIHP.js → chunk-B3IIPTY3.js} +3 -3
  42. package/dist/chunk-EQR7BGFN.js +337 -0
  43. package/dist/{chunk-5JUZ4HL7.js → chunk-FDPPZLSQ.js} +3 -3
  44. package/dist/{chunk-MFKHTE5R.js → chunk-FKQCPRKI.js} +3 -3
  45. package/dist/{chunk-7D7PZLB7.js → chunk-FS2UUJJO.js} +3 -3
  46. package/dist/{chunk-U6FRAEQJ.js → chunk-GJ6LM4JZ.js} +1 -441
  47. package/dist/chunk-H3REGQRI.js +107 -0
  48. package/dist/{chunk-25XHSTPT.js → chunk-HDNDL6D5.js} +3 -3
  49. package/dist/{chunk-BXLTEUS4.js → chunk-I4RTIMLX.js} +2 -2
  50. package/dist/chunk-IOVXB6QN.js +447 -0
  51. package/dist/{chunk-Y6WXAPKY.js → chunk-NTHXZAW4.js} +3 -3
  52. package/dist/{chunk-UTH7OXTM.js → chunk-OTZU76DH.js} +22 -4
  53. package/dist/{chunk-DWHUZUEY.js → chunk-T6GMRZWC.js} +3 -3
  54. package/dist/{chunk-V4FZHJQX.js → chunk-TIXVEPS2.js} +3 -3
  55. package/dist/{chunk-YNYCQECH.js → chunk-TJ5L2UTE.js} +3 -3
  56. package/dist/chunk-UGTNKTHS.js +542 -0
  57. package/dist/cli/neuroverse.cjs +3372 -523
  58. package/dist/cli/neuroverse.js +53 -21
  59. package/dist/cli/plan.js +2 -2
  60. package/dist/cli/run.cjs +242 -139
  61. package/dist/cli/run.js +23 -3
  62. package/dist/cli/worldmodel.cjs +1624 -0
  63. package/dist/cli/worldmodel.d.cts +24 -0
  64. package/dist/cli/worldmodel.d.ts +24 -0
  65. package/dist/cli/worldmodel.js +742 -0
  66. package/dist/{demo-66MMJTEH.js → demo-6W3YXLAX.js} +4 -4
  67. package/dist/{derive-AUQE3L3P.js → derive-42IJW7JI.js} +4 -4
  68. package/dist/{doctor-EY7LKSYY.js → doctor-XEMLO6UA.js} +3 -2
  69. package/dist/engine/bootstrap-emitter.cjs +241 -0
  70. package/dist/engine/bootstrap-emitter.d.cts +27 -0
  71. package/dist/engine/bootstrap-emitter.d.ts +27 -0
  72. package/dist/{bootstrap-emitter-GIMOJFOC.js → engine/bootstrap-emitter.js} +2 -2
  73. package/dist/engine/bootstrap-parser.cjs +560 -0
  74. package/dist/engine/bootstrap-parser.d.cts +96 -0
  75. package/dist/engine/bootstrap-parser.d.ts +96 -0
  76. package/dist/{bootstrap-parser-LBLGVEMU.js → engine/bootstrap-parser.js} +2 -2
  77. package/dist/engine/guard-engine.cjs +1116 -0
  78. package/dist/engine/guard-engine.d.cts +60 -0
  79. package/dist/engine/guard-engine.d.ts +60 -0
  80. package/dist/{guard-engine-N7TUIUU7.js → engine/guard-engine.js} +3 -3
  81. package/dist/engine/simulate-engine.cjs +390 -0
  82. package/dist/engine/simulate-engine.d.cts +105 -0
  83. package/dist/engine/simulate-engine.d.ts +105 -0
  84. package/dist/engine/simulate-engine.js +9 -0
  85. package/dist/engine/worldmodel-compiler.cjs +366 -0
  86. package/dist/engine/worldmodel-compiler.d.cts +46 -0
  87. package/dist/engine/worldmodel-compiler.d.ts +46 -0
  88. package/dist/engine/worldmodel-compiler.js +17 -0
  89. package/dist/engine/worldmodel-parser.cjs +566 -0
  90. package/dist/engine/worldmodel-parser.d.cts +22 -0
  91. package/dist/engine/worldmodel-parser.d.ts +22 -0
  92. package/dist/engine/worldmodel-parser.js +7 -0
  93. package/dist/{equity-penalties-WWC7UDQD.js → equity-penalties-CCO3GVHS.js} +6 -6
  94. package/dist/{explain-MUSGDT67.js → explain-HDFN4ION.js} +1 -1
  95. package/dist/{guard-W3BMQPBJ.js → guard-IHJEKHL2.js} +16 -4
  96. package/dist/{guard-contract-CLBbTGK_.d.ts → guard-contract-ddiIPlOg.d.cts} +2 -369
  97. package/dist/{guard-contract-CLBbTGK_.d.cts → guard-contract-q6HJAq3Q.d.ts} +2 -369
  98. package/dist/{improve-PJDAWW4Q.js → improve-LRORRYEX.js} +3 -3
  99. package/dist/index.cjs +471 -1
  100. package/dist/index.d.cts +14 -492
  101. package/dist/index.d.ts +14 -492
  102. package/dist/index.js +63 -42
  103. package/dist/keygen-BSZH3NM2.js +77 -0
  104. package/dist/{lens-IP6GIZ2Q.js → lens-TLDZQXBI.js} +152 -26
  105. package/dist/{mcp-server-OG3PPVD2.js → mcp-server-CKYBHXWK.js} +2 -2
  106. package/dist/migrate-NH5PVMX4.js +221 -0
  107. package/dist/{playground-4BK2XQ47.js → playground-3TTBN7XD.js} +5 -5
  108. package/dist/{redteam-BRZALBPP.js → redteam-W644UMWN.js} +3 -3
  109. package/dist/{session-SGRUT2UH.js → session-FMAROEIE.js} +2 -2
  110. package/dist/{shared-CwGpPheR.d.ts → shared-DAzdfWtU.d.ts} +1 -1
  111. package/dist/{shared-BGzmYP5g.d.cts → shared-PpalGKxc.d.cts} +1 -1
  112. package/dist/sign-RRELHKWM.js +11 -0
  113. package/dist/{simulate-FGXKIH7V.js → simulate-VT437EEL.js} +2 -2
  114. package/dist/{test-PT44BSYG.js → test-XDB2DH3L.js} +3 -3
  115. package/dist/types.cjs +18 -0
  116. package/dist/types.d.cts +370 -0
  117. package/dist/types.d.ts +370 -0
  118. package/dist/types.js +0 -0
  119. package/dist/{validate-Q5O5TGLT.js → validate-M52DX22Y.js} +1 -1
  120. package/dist/verify-6AVTWX75.js +151 -0
  121. package/dist/{world-V52ZMH26.js → world-O4HTQPDP.js} +1 -1
  122. package/dist/{world-loader-C4D3VPP3.js → world-loader-YTYFOP7D.js} +1 -1
  123. package/dist/worldmodel-contract-BPGhiuW5.d.cts +221 -0
  124. package/dist/worldmodel-contract-BPGhiuW5.d.ts +221 -0
  125. package/dist/worlds/auki-vanguard.worldmodel.md +116 -0
  126. package/dist/worlds/behavioral-demo.nv-world.md +130 -0
  127. package/dist/worlds/neuroverse-governance.worldmodel.md +115 -0
  128. package/package.json +44 -3
  129. package/dist/{bootstrap-IP5QMC3Q.js → bootstrap-2OW5ZLBL.js} +3 -3
  130. package/dist/{chunk-4G6WHPLI.js → chunk-735Z3HA4.js} +6 -6
  131. package/dist/{chunk-7QIAF377.js → chunk-CYDMUJVZ.js} +0 -0
  132. package/dist/{configure-ai-LL3VAPQW.js → configure-ai-5MP5DWTT.js} +3 -3
  133. package/dist/{decision-flow-3K4D72G4.js → decision-flow-IJPNMVQK.js} +3 -3
@@ -2001,13 +2001,13 @@ __export(world_loader_exports, {
2001
2001
  loadWorldFromDirectory: () => loadWorldFromDirectory
2002
2002
  });
2003
2003
  async function loadWorldFromDirectory(dirPath) {
2004
- const { readFile: readFile3 } = await import("fs/promises");
2005
- const { join: join9 } = await import("path");
2006
- const { readdirSync: readdirSync5 } = await import("fs");
2004
+ const { readFile: readFile4 } = await import("fs/promises");
2005
+ const { join: join14 } = await import("path");
2006
+ const { readdirSync: readdirSync6 } = await import("fs");
2007
2007
  async function readJson(filename) {
2008
- const filePath = join9(dirPath, filename);
2008
+ const filePath = join14(dirPath, filename);
2009
2009
  try {
2010
- const content = await readFile3(filePath, "utf-8");
2010
+ const content = await readFile4(filePath, "utf-8");
2011
2011
  return JSON.parse(content);
2012
2012
  } catch (err) {
2013
2013
  if (err instanceof Error && "code" in err && err.code === "ENOENT") {
@@ -2035,11 +2035,11 @@ async function loadWorldFromDirectory(dirPath) {
2035
2035
  const metadataJson = await readJson("metadata.json");
2036
2036
  const rules = [];
2037
2037
  try {
2038
- const rulesDir = join9(dirPath, "rules");
2039
- const ruleFiles = readdirSync5(rulesDir).filter((f) => f.endsWith(".json")).sort();
2038
+ const rulesDir = join14(dirPath, "rules");
2039
+ const ruleFiles = readdirSync6(rulesDir).filter((f) => f.endsWith(".json")).sort();
2040
2040
  for (const file of ruleFiles) {
2041
2041
  try {
2042
- const content = await readFile3(join9(rulesDir, file), "utf-8");
2042
+ const content = await readFile4(join14(rulesDir, file), "utf-8");
2043
2043
  rules.push(JSON.parse(content));
2044
2044
  } catch (err) {
2045
2045
  process.stderr.write(
@@ -2092,27 +2092,27 @@ async function loadWorld(worldPath) {
2092
2092
  throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory`);
2093
2093
  }
2094
2094
  async function loadBundledWorld(name = DEFAULT_BUNDLED_WORLD) {
2095
- const { readFile: readFile3 } = await import("fs/promises");
2096
- const { join: join9, dirname: dirname3 } = await import("path");
2097
- const { existsSync: existsSync6 } = await import("fs");
2095
+ const { readFile: readFile4 } = await import("fs/promises");
2096
+ const { join: join14, dirname: dirname4 } = await import("path");
2097
+ const { existsSync: existsSync10 } = await import("fs");
2098
2098
  const { fileURLToPath: fileURLToPath3 } = await import("url");
2099
2099
  const { parseWorldMarkdown: parseWorldMarkdown2 } = await Promise.resolve().then(() => (init_bootstrap_parser(), bootstrap_parser_exports));
2100
2100
  const { emitWorldDefinition: emitWorldDefinition2 } = await Promise.resolve().then(() => (init_bootstrap_emitter(), bootstrap_emitter_exports));
2101
2101
  const filename = `${name}.nv-world.md`;
2102
2102
  let packageRoot;
2103
2103
  try {
2104
- const thisFile = typeof __dirname !== "undefined" ? __dirname : dirname3(fileURLToPath3(import_meta.url));
2105
- packageRoot = join9(thisFile, "..", "..");
2104
+ const thisFile = typeof __dirname !== "undefined" ? __dirname : dirname4(fileURLToPath3(import_meta.url));
2105
+ packageRoot = join14(thisFile, "..", "..");
2106
2106
  } catch {
2107
2107
  packageRoot = process.cwd();
2108
2108
  }
2109
2109
  const candidates = [
2110
- join9(packageRoot, "dist", "worlds", filename),
2111
- join9(packageRoot, "src", "worlds", filename)
2110
+ join14(packageRoot, "dist", "worlds", filename),
2111
+ join14(packageRoot, "src", "worlds", filename)
2112
2112
  ];
2113
2113
  for (const candidate of candidates) {
2114
- if (existsSync6(candidate)) {
2115
- const markdown = await readFile3(candidate, "utf-8");
2114
+ if (existsSync10(candidate)) {
2115
+ const markdown = await readFile4(candidate, "utf-8");
2116
2116
  const parsed = parseWorldMarkdown2(markdown);
2117
2117
  if (!parsed.world) {
2118
2118
  throw new Error(`Failed to parse bundled world: ${candidate}`);
@@ -2140,12 +2140,12 @@ function slugify(text) {
2140
2140
  return text.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "").slice(0, 60);
2141
2141
  }
2142
2142
  async function addGuard(worldDir, input) {
2143
- const { readFile: readFile3, writeFile: writeFile5 } = await import("fs/promises");
2144
- const { join: join9 } = await import("path");
2145
- const guardsPath = join9(worldDir, "guards.json");
2143
+ const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
2144
+ const { join: join14 } = await import("path");
2145
+ const guardsPath = join14(worldDir, "guards.json");
2146
2146
  let config;
2147
2147
  try {
2148
- const raw = await readFile3(guardsPath, "utf-8");
2148
+ const raw = await readFile4(guardsPath, "utf-8");
2149
2149
  config = JSON.parse(raw);
2150
2150
  } catch {
2151
2151
  config = { guards: [], intent_vocabulary: {} };
@@ -2167,7 +2167,7 @@ async function addGuard(worldDir, input) {
2167
2167
  ...input.enforcement === "modify" && input.reason && { modify_to: input.reason }
2168
2168
  };
2169
2169
  config.guards.push(guard);
2170
- await writeFile5(guardsPath, JSON.stringify(config, null, 2) + "\n");
2170
+ await writeFile6(guardsPath, JSON.stringify(config, null, 2) + "\n");
2171
2171
  const { loadWorldFromDirectory: loadWorldFromDirectory3 } = await Promise.resolve().then(() => (init_world_loader(), world_loader_exports));
2172
2172
  const world = await loadWorldFromDirectory3(worldDir);
2173
2173
  const report = validateWorld(world);
@@ -2181,14 +2181,14 @@ async function addGuard(worldDir, input) {
2181
2181
  };
2182
2182
  }
2183
2183
  async function addRule(worldDir, input) {
2184
- const { readFile: readFile3, writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
2185
- const { join: join9 } = await import("path");
2186
- const { readdirSync: readdirSync5 } = await import("fs");
2187
- const rulesDir = join9(worldDir, "rules");
2188
- await mkdir2(rulesDir, { recursive: true });
2184
+ const { readFile: readFile4, writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
2185
+ const { join: join14 } = await import("path");
2186
+ const { readdirSync: readdirSync6 } = await import("fs");
2187
+ const rulesDir = join14(worldDir, "rules");
2188
+ await mkdir3(rulesDir, { recursive: true });
2189
2189
  let nextNum = 1;
2190
2190
  try {
2191
- const existing = readdirSync5(rulesDir).filter((f) => f.match(/^rule-\d+\.json$/)).sort();
2191
+ const existing = readdirSync6(rulesDir).filter((f) => f.match(/^rule-\d+\.json$/)).sort();
2192
2192
  if (existing.length > 0) {
2193
2193
  const lastFile = existing[existing.length - 1];
2194
2194
  const match = lastFile.match(/rule-(\d+)\.json/);
@@ -2214,8 +2214,8 @@ async function addRule(worldDir, input) {
2214
2214
  effect_text: input.effects ? input.effects.map((e) => `${e.target} ${e.operation} ${e.value}`).join(", ") : "No direct effects"
2215
2215
  }
2216
2216
  };
2217
- const rulePath = join9(rulesDir, `rule-${ruleNum}.json`);
2218
- await writeFile5(rulePath, JSON.stringify(rule, null, 2) + "\n");
2217
+ const rulePath = join14(rulesDir, `rule-${ruleNum}.json`);
2218
+ await writeFile6(rulePath, JSON.stringify(rule, null, 2) + "\n");
2219
2219
  const { loadWorldFromDirectory: loadWorldFromDirectory3 } = await Promise.resolve().then(() => (init_world_loader(), world_loader_exports));
2220
2220
  const world = await loadWorldFromDirectory3(worldDir);
2221
2221
  const report = validateWorld(world);
@@ -2229,12 +2229,12 @@ async function addRule(worldDir, input) {
2229
2229
  };
2230
2230
  }
2231
2231
  async function addInvariant(worldDir, input) {
2232
- const { readFile: readFile3, writeFile: writeFile5 } = await import("fs/promises");
2233
- const { join: join9 } = await import("path");
2234
- const invariantsPath = join9(worldDir, "invariants.json");
2232
+ const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
2233
+ const { join: join14 } = await import("path");
2234
+ const invariantsPath = join14(worldDir, "invariants.json");
2235
2235
  let config;
2236
2236
  try {
2237
- const raw = await readFile3(invariantsPath, "utf-8");
2237
+ const raw = await readFile4(invariantsPath, "utf-8");
2238
2238
  config = JSON.parse(raw);
2239
2239
  } catch {
2240
2240
  config = { invariants: [] };
@@ -2250,7 +2250,7 @@ async function addInvariant(worldDir, input) {
2250
2250
  mutable: false
2251
2251
  };
2252
2252
  config.invariants.push(invariant);
2253
- await writeFile5(invariantsPath, JSON.stringify(config, null, 2) + "\n");
2253
+ await writeFile6(invariantsPath, JSON.stringify(config, null, 2) + "\n");
2254
2254
  const { loadWorldFromDirectory: loadWorldFromDirectory3 } = await Promise.resolve().then(() => (init_world_loader(), world_loader_exports));
2255
2255
  const world = await loadWorldFromDirectory3(worldDir);
2256
2256
  const report = validateWorld(world);
@@ -2849,27 +2849,27 @@ ${candidates.map((c) => ` - ${c}`).join("\n")}`
2849
2849
  }
2850
2850
  async function collectMarkdownSources(inputPath) {
2851
2851
  const { stat, readFile: rf, readdir } = await import("fs/promises");
2852
- const { join: pathJoin, extname: extname2, basename: basename2 } = await import("path");
2852
+ const { join: pathJoin, extname: extname2, basename: basename4 } = await import("path");
2853
2853
  const stats = await stat(inputPath);
2854
2854
  if (stats.isFile()) {
2855
2855
  const content = await rf(inputPath, "utf-8");
2856
- return [{ filename: basename2(inputPath), content }];
2856
+ return [{ filename: basename4(inputPath), content }];
2857
2857
  }
2858
2858
  if (stats.isDirectory()) {
2859
2859
  const sources = [];
2860
- await collectDir(inputPath, sources, rf, pathJoin, extname2, basename2);
2860
+ await collectDir(inputPath, sources, rf, pathJoin, extname2, basename4);
2861
2861
  sources.sort((a, b) => a.filename.localeCompare(b.filename));
2862
2862
  return sources;
2863
2863
  }
2864
2864
  throw new Error(`Input path is neither a file nor a directory: ${inputPath}`);
2865
2865
  }
2866
- async function collectDir(dir, sources, rf, pathJoin, extname2, basename2) {
2866
+ async function collectDir(dir, sources, rf, pathJoin, extname2, basename4) {
2867
2867
  const { readdir } = await import("fs/promises");
2868
2868
  const entries = await readdir(dir, { withFileTypes: true });
2869
2869
  for (const entry of entries) {
2870
2870
  const fullPath = pathJoin(dir, entry.name);
2871
2871
  if (entry.isDirectory()) {
2872
- await collectDir(fullPath, sources, rf, pathJoin, extname2, basename2);
2872
+ await collectDir(fullPath, sources, rf, pathJoin, extname2, basename4);
2873
2873
  } else if (entry.isFile() && extname2(entry.name).toLowerCase() === ".md") {
2874
2874
  const content = await rf(fullPath, "utf-8");
2875
2875
  sources.push({ filename: entry.name, content });
@@ -3527,22 +3527,22 @@ function parseArgs2(argv) {
3527
3527
  return { inputPath, outputDir, validate, dryRun, provider, model, endpoint };
3528
3528
  }
3529
3529
  async function writeWorldFiles(outputDir, world) {
3530
- const { writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
3531
- const { join: join9 } = await import("path");
3532
- await mkdir2(outputDir, { recursive: true });
3533
- await writeFile5(join9(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
3534
- await writeFile5(join9(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
3535
- await writeFile5(join9(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
3536
- await writeFile5(join9(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
3537
- await writeFile5(join9(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
3538
- await writeFile5(join9(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
3539
- await writeFile5(join9(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
3540
- const rulesDir = join9(outputDir, "rules");
3541
- await mkdir2(rulesDir, { recursive: true });
3530
+ const { writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
3531
+ const { join: join14 } = await import("path");
3532
+ await mkdir3(outputDir, { recursive: true });
3533
+ await writeFile6(join14(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
3534
+ await writeFile6(join14(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
3535
+ await writeFile6(join14(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
3536
+ await writeFile6(join14(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
3537
+ await writeFile6(join14(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
3538
+ await writeFile6(join14(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
3539
+ await writeFile6(join14(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
3540
+ const rulesDir = join14(outputDir, "rules");
3541
+ await mkdir3(rulesDir, { recursive: true });
3542
3542
  const sortedRules = [...world.rules].sort((a, b) => a.order - b.order);
3543
3543
  for (let i = 0; i < sortedRules.length; i++) {
3544
3544
  const ruleNum = String(i + 1).padStart(3, "0");
3545
- await writeFile5(join9(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
3545
+ await writeFile6(join14(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
3546
3546
  }
3547
3547
  }
3548
3548
  function write(msg) {
@@ -3557,17 +3557,17 @@ function printInsight(finding2) {
3557
3557
  async function main2(argv = process.argv.slice(2)) {
3558
3558
  try {
3559
3559
  const args = parseArgs2(argv);
3560
- const { basename: basename2 } = await import("path");
3560
+ const { basename: basename4 } = await import("path");
3561
3561
  write(`
3562
3562
  NeuroVerse World Builder
3563
3563
  `);
3564
3564
  write(`
3565
- Analyzing: ${basename2(args.inputPath)}
3565
+ Analyzing: ${basename4(args.inputPath)}
3566
3566
  `);
3567
3567
  const derivedPath = args.outputDir ? `${args.outputDir}/source.nv-world.md` : ".neuroverse/build-output.nv-world.md";
3568
- const { mkdir: mkdir2 } = await import("fs/promises");
3569
- const { dirname: dirname3 } = await import("path");
3570
- await mkdir2(dirname3(derivedPath), { recursive: true });
3568
+ const { mkdir: mkdir3 } = await import("fs/promises");
3569
+ const { dirname: dirname4 } = await import("path");
3570
+ await mkdir3(dirname4(derivedPath), { recursive: true });
3571
3571
  const { result, exitCode, dryRunOutput } = await deriveWorld({
3572
3572
  inputPath: args.inputPath,
3573
3573
  outputPath: derivedPath,
@@ -3585,8 +3585,8 @@ Analyzing: ${basename2(args.inputPath)}
3585
3585
  process.exit(DERIVE_EXIT_CODES.SUCCESS);
3586
3586
  return;
3587
3587
  }
3588
- const { readFile: readFile3 } = await import("fs/promises");
3589
- const derivedContent = await readFile3(derivedPath, "utf-8");
3588
+ const { readFile: readFile4 } = await import("fs/promises");
3589
+ const derivedContent = await readFile4(derivedPath, "utf-8");
3590
3590
  const parseResult = parseWorldMarkdown(derivedContent);
3591
3591
  const worldName = parseResult.world?.frontmatter?.name ?? "Derived World";
3592
3592
  const worldId = parseResult.world?.frontmatter?.world_id ?? "derived_world";
@@ -3673,9 +3673,9 @@ World source written to: ${derivedPath}
3673
3673
  try {
3674
3674
  const emitResult = emitWorldDefinition(parseResult.world);
3675
3675
  await writeWorldFiles(outputDir, emitResult.world);
3676
- const { join: join9 } = await import("path");
3676
+ const { join: join14 } = await import("path");
3677
3677
  const { copyFile } = await import("fs/promises");
3678
- const sourceDest = join9(outputDir, "source.nv-world.md");
3678
+ const sourceDest = join14(outputDir, "source.nv-world.md");
3679
3679
  if (derivedPath !== sourceDest) {
3680
3680
  await copyFile(derivedPath, sourceDest);
3681
3681
  }
@@ -4451,8 +4451,8 @@ async function main4(argv = process.argv.slice(2)) {
4451
4451
  const world = await loadWorld(resolvedPath);
4452
4452
  let events;
4453
4453
  if (args.eventsPath) {
4454
- const { readFile: readFile3 } = await import("fs/promises");
4455
- const raw = await readFile3(args.eventsPath, "utf-8");
4454
+ const { readFile: readFile4 } = await import("fs/promises");
4455
+ const raw = await readFile4(args.eventsPath, "utf-8");
4456
4456
  const parsed = JSON.parse(raw);
4457
4457
  events = Array.isArray(parsed) ? parsed : [parsed];
4458
4458
  process.stderr.write(`Loaded ${events.length} event(s) from ${args.eventsPath}
@@ -5008,9 +5008,9 @@ function parseArgs6(argv) {
5008
5008
  async function main6(argv = process.argv.slice(2)) {
5009
5009
  try {
5010
5010
  const args = parseArgs6(argv);
5011
- const { writeFile: writeFile5 } = await import("fs/promises");
5012
- const { existsSync: existsSync6 } = await import("fs");
5013
- if (existsSync6(args.outputPath)) {
5011
+ const { writeFile: writeFile6 } = await import("fs/promises");
5012
+ const { existsSync: existsSync10 } = await import("fs");
5013
+ if (existsSync10(args.outputPath)) {
5014
5014
  process.stderr.write(`File already exists: ${args.outputPath}
5015
5015
  `);
5016
5016
  process.stderr.write("Use a different --output path or remove the existing file.\n");
@@ -5018,7 +5018,7 @@ async function main6(argv = process.argv.slice(2)) {
5018
5018
  return;
5019
5019
  }
5020
5020
  const template = generateTemplate(args.name);
5021
- await writeFile5(args.outputPath, template, "utf-8");
5021
+ await writeFile6(args.outputPath, template, "utf-8");
5022
5022
  const result = {
5023
5023
  created: args.outputPath,
5024
5024
  worldName: args.name,
@@ -5867,32 +5867,32 @@ function parseArgs9(argv) {
5867
5867
  return { inputPath, outputPath, validate, format };
5868
5868
  }
5869
5869
  async function writeWorldFiles2(outputDir, world) {
5870
- const { writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
5871
- const { join: join9 } = await import("path");
5872
- await mkdir2(outputDir, { recursive: true });
5873
- await writeFile5(join9(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
5874
- await writeFile5(join9(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
5875
- await writeFile5(join9(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
5876
- await writeFile5(join9(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
5877
- const rulesDir = join9(outputDir, "rules");
5878
- await mkdir2(rulesDir, { recursive: true });
5870
+ const { writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
5871
+ const { join: join14 } = await import("path");
5872
+ await mkdir3(outputDir, { recursive: true });
5873
+ await writeFile6(join14(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
5874
+ await writeFile6(join14(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
5875
+ await writeFile6(join14(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
5876
+ await writeFile6(join14(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
5877
+ const rulesDir = join14(outputDir, "rules");
5878
+ await mkdir3(rulesDir, { recursive: true });
5879
5879
  const sortedRules = [...world.rules].sort((a, b) => a.order - b.order);
5880
5880
  for (let i = 0; i < sortedRules.length; i++) {
5881
5881
  const ruleNum = String(i + 1).padStart(3, "0");
5882
- await writeFile5(join9(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
5882
+ await writeFile6(join14(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
5883
5883
  }
5884
- await writeFile5(join9(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
5885
- await writeFile5(join9(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
5886
- await writeFile5(join9(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
5884
+ await writeFile6(join14(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
5885
+ await writeFile6(join14(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
5886
+ await writeFile6(join14(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
5887
5887
  }
5888
5888
  async function main9(argv = process.argv.slice(2)) {
5889
5889
  const startTime = performance.now();
5890
5890
  try {
5891
5891
  const args = parseArgs9(argv);
5892
- const { readFile: readFile3 } = await import("fs/promises");
5892
+ const { readFile: readFile4 } = await import("fs/promises");
5893
5893
  let markdown;
5894
5894
  try {
5895
- markdown = await readFile3(args.inputPath, "utf-8");
5895
+ markdown = await readFile4(args.inputPath, "utf-8");
5896
5896
  } catch {
5897
5897
  const errorResult = { error: `Cannot read file: ${args.inputPath}` };
5898
5898
  process.stderr.write(JSON.stringify(errorResult, null, 2) + "\n");
@@ -7364,6 +7364,162 @@ var init_guard_contract = __esm({
7364
7364
  }
7365
7365
  });
7366
7366
 
7367
+ // src/engine/audit-logger.ts
7368
+ function verdictToAuditEvent(event, verdict) {
7369
+ const auditEvent = {
7370
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
7371
+ worldId: verdict.evidence.worldId,
7372
+ worldName: verdict.evidence.worldName,
7373
+ worldVersion: verdict.evidence.worldVersion,
7374
+ intent: event.intent,
7375
+ tool: event.tool,
7376
+ scope: event.scope,
7377
+ actor: event.roleId,
7378
+ direction: event.direction,
7379
+ decision: verdict.status,
7380
+ reason: verdict.reason,
7381
+ ruleId: verdict.ruleId,
7382
+ warning: verdict.warning,
7383
+ guardsMatched: verdict.evidence.guardsMatched,
7384
+ rulesMatched: verdict.evidence.rulesMatched,
7385
+ invariantsSatisfied: verdict.evidence.invariantsSatisfied,
7386
+ invariantsTotal: verdict.evidence.invariantsTotal,
7387
+ enforcementLevel: verdict.evidence.enforcementLevel,
7388
+ durationMs: verdict.trace?.durationMs,
7389
+ args: event.args
7390
+ };
7391
+ if (verdict.consequence) {
7392
+ auditEvent.consequence = verdict.consequence;
7393
+ }
7394
+ if (verdict.reward) {
7395
+ auditEvent.reward = verdict.reward;
7396
+ }
7397
+ if (verdict.intentRecord) {
7398
+ auditEvent.originalIntent = verdict.intentRecord.originalIntent;
7399
+ auditEvent.finalAction = verdict.intentRecord.finalAction;
7400
+ }
7401
+ return auditEvent;
7402
+ }
7403
+ async function readAuditLog(logPath, filter) {
7404
+ const { readFile: readFile4 } = await import("fs/promises");
7405
+ let content;
7406
+ try {
7407
+ content = await readFile4(logPath, "utf-8");
7408
+ } catch {
7409
+ return [];
7410
+ }
7411
+ const events = [];
7412
+ for (const line of content.split("\n")) {
7413
+ const trimmed = line.trim();
7414
+ if (!trimmed) continue;
7415
+ try {
7416
+ const event = JSON.parse(trimmed);
7417
+ if (!filter || filter(event)) {
7418
+ events.push(event);
7419
+ }
7420
+ } catch {
7421
+ }
7422
+ }
7423
+ return events;
7424
+ }
7425
+ function summarizeAuditEvents(events) {
7426
+ const allowed = events.filter((e) => e.decision === "ALLOW").length;
7427
+ const blocked = events.filter((e) => e.decision === "BLOCK").length;
7428
+ const paused = events.filter((e) => e.decision === "PAUSE").length;
7429
+ const modified = events.filter((e) => e.decision === "MODIFY").length;
7430
+ const penalized = events.filter((e) => e.decision === "PENALIZE").length;
7431
+ const rewarded = events.filter((e) => e.decision === "REWARD").length;
7432
+ const neutral = events.filter((e) => e.decision === "NEUTRAL").length;
7433
+ const actorSet = /* @__PURE__ */ new Set();
7434
+ for (const e of events) {
7435
+ if (e.actor) actorSet.add(e.actor);
7436
+ }
7437
+ const intentMap = /* @__PURE__ */ new Map();
7438
+ for (const e of events) {
7439
+ const entry = intentMap.get(e.intent) ?? { count: 0, blocked: 0, paused: 0, penalized: 0, rewarded: 0 };
7440
+ entry.count++;
7441
+ if (e.decision === "BLOCK") entry.blocked++;
7442
+ if (e.decision === "PAUSE") entry.paused++;
7443
+ if (e.decision === "PENALIZE") entry.penalized++;
7444
+ if (e.decision === "REWARD") entry.rewarded++;
7445
+ intentMap.set(e.intent, entry);
7446
+ }
7447
+ const topIntents = [...intentMap.entries()].map(([intent, data]) => ({ intent, ...data })).sort((a, b) => b.count - a.count);
7448
+ const ruleMap = /* @__PURE__ */ new Map();
7449
+ for (const e of events) {
7450
+ if (e.ruleId) {
7451
+ ruleMap.set(e.ruleId, (ruleMap.get(e.ruleId) ?? 0) + 1);
7452
+ }
7453
+ for (const g of e.guardsMatched) {
7454
+ ruleMap.set(g, (ruleMap.get(g) ?? 0) + 1);
7455
+ }
7456
+ }
7457
+ const topRules = [...ruleMap.entries()].map(([ruleId, count]) => ({ ruleId, count })).sort((a, b) => b.count - a.count);
7458
+ const redirected = blocked + paused + modified + penalized;
7459
+ const total = events.length;
7460
+ return {
7461
+ totalActions: total,
7462
+ allowed,
7463
+ blocked,
7464
+ paused,
7465
+ modified,
7466
+ penalized,
7467
+ rewarded,
7468
+ neutral,
7469
+ actors: [...actorSet],
7470
+ topIntents,
7471
+ topRules,
7472
+ firstEvent: events[0]?.timestamp ?? "",
7473
+ lastEvent: events[events.length - 1]?.timestamp ?? "",
7474
+ behavioralEconomy: {
7475
+ totalPenalties: penalized,
7476
+ totalRewards: rewarded,
7477
+ netPressure: rewarded - penalized,
7478
+ redirectionRate: total > 0 ? redirected / total : 0
7479
+ }
7480
+ };
7481
+ }
7482
+ var FileAuditLogger;
7483
+ var init_audit_logger = __esm({
7484
+ "src/engine/audit-logger.ts"() {
7485
+ "use strict";
7486
+ init_guard_engine();
7487
+ FileAuditLogger = class {
7488
+ logPath;
7489
+ buffer = [];
7490
+ flushTimer = null;
7491
+ flushIntervalMs;
7492
+ constructor(logPath, options) {
7493
+ this.logPath = logPath;
7494
+ this.flushIntervalMs = options?.flushIntervalMs ?? 1e3;
7495
+ }
7496
+ log(event) {
7497
+ this.buffer.push(JSON.stringify(event));
7498
+ if (!this.flushTimer) {
7499
+ this.flushTimer = setTimeout(() => {
7500
+ void this.flush();
7501
+ }, this.flushIntervalMs);
7502
+ }
7503
+ }
7504
+ async flush() {
7505
+ if (this.buffer.length === 0) return;
7506
+ if (this.flushTimer) {
7507
+ clearTimeout(this.flushTimer);
7508
+ this.flushTimer = null;
7509
+ }
7510
+ const lines = this.buffer.splice(0).join("\n") + "\n";
7511
+ try {
7512
+ const { appendFile, mkdir: mkdir3 } = await import("fs/promises");
7513
+ const { dirname: dirname4 } = await import("path");
7514
+ await mkdir3(dirname4(this.logPath), { recursive: true });
7515
+ await appendFile(this.logPath, lines, "utf-8");
7516
+ } catch {
7517
+ }
7518
+ }
7519
+ };
7520
+ }
7521
+ });
7522
+
7367
7523
  // src/cli/guard.ts
7368
7524
  var guard_exports = {};
7369
7525
  __export(guard_exports, {
@@ -7374,6 +7530,7 @@ function parseArgs11(argv) {
7374
7530
  let trace = false;
7375
7531
  let level;
7376
7532
  let aiClassify = false;
7533
+ let logPath;
7377
7534
  for (let i = 0; i < argv.length; i++) {
7378
7535
  const arg = argv[i];
7379
7536
  if (arg === "--world" && i + 1 < argv.length) {
@@ -7382,6 +7539,8 @@ function parseArgs11(argv) {
7382
7539
  trace = true;
7383
7540
  } else if (arg === "--ai-classify") {
7384
7541
  aiClassify = true;
7542
+ } else if (arg === "--log" && i + 1 < argv.length) {
7543
+ logPath = argv[++i];
7385
7544
  } else if (arg === "--level" && i + 1 < argv.length) {
7386
7545
  const val = argv[++i];
7387
7546
  if (val === "basic" || val === "standard" || val === "strict") {
@@ -7391,7 +7550,7 @@ function parseArgs11(argv) {
7391
7550
  }
7392
7551
  }
7393
7552
  }
7394
- return { worldPath, trace, level, aiClassify };
7553
+ return { worldPath, trace, level, aiClassify, logPath };
7395
7554
  }
7396
7555
  async function main11(argv = process.argv.slice(2)) {
7397
7556
  try {
@@ -7451,6 +7610,11 @@ async function main11(argv = process.argv.slice(2)) {
7451
7610
  const options = { trace: args.trace, level: args.level };
7452
7611
  verdict = evaluateGuard(event, world, options);
7453
7612
  }
7613
+ if (args.logPath) {
7614
+ const logger = new FileAuditLogger(args.logPath, { flushIntervalMs: 0 });
7615
+ logger.log(verdictToAuditEvent(event, verdict));
7616
+ await logger.flush();
7617
+ }
7454
7618
  process.stdout.write(JSON.stringify(verdict, null, 2) + "\n");
7455
7619
  const exitCode = GUARD_EXIT_CODES[verdict.status];
7456
7620
  process.exit(exitCode);
@@ -7479,6 +7643,7 @@ var init_guard = __esm({
7479
7643
  init_world_resolver();
7480
7644
  init_guard_contract();
7481
7645
  init_cli_utils();
7646
+ init_audit_logger();
7482
7647
  }
7483
7648
  });
7484
7649
 
@@ -8076,14 +8241,14 @@ function handleHealthCheck() {
8076
8241
  };
8077
8242
  }
8078
8243
  async function handleListPresets(policiesDir) {
8079
- const { readdir, readFile: readFile3 } = await import("fs/promises");
8080
- const { join: join9 } = await import("path");
8081
- const dir = policiesDir ?? join9(process.cwd(), "policies");
8244
+ const { readdir, readFile: readFile4 } = await import("fs/promises");
8245
+ const { join: join14 } = await import("path");
8246
+ const dir = policiesDir ?? join14(process.cwd(), "policies");
8082
8247
  const presets = [];
8083
8248
  try {
8084
8249
  const files = await readdir(dir);
8085
8250
  for (const file of files.filter((f) => f.endsWith(".txt")).sort()) {
8086
- const content = await readFile3(join9(dir, file), "utf-8");
8251
+ const content = await readFile4(join14(dir, file), "utf-8");
8087
8252
  const id = file.replace(".txt", "");
8088
8253
  const name = id.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
8089
8254
  const firstLine = content.split("\n").find((l) => l.trim().length > 0) ?? "";
@@ -8154,9 +8319,9 @@ function govern(action, world, options) {
8154
8319
  return evaluateGuard(event, world, options);
8155
8320
  }
8156
8321
  async function writeTempWorld(dir, policyLines) {
8157
- const { writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
8158
- const { join: join9 } = await import("path");
8159
- await mkdir2(dir, { recursive: true });
8322
+ const { writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
8323
+ const { join: join14 } = await import("path");
8324
+ await mkdir3(dir, { recursive: true });
8160
8325
  const worldJson = {
8161
8326
  world_id: "demo-live",
8162
8327
  name: "Live Demo World",
@@ -8197,9 +8362,9 @@ async function writeTempWorld(dir, policyLines) {
8197
8362
  authoring_method: "manual-authoring"
8198
8363
  };
8199
8364
  await Promise.all([
8200
- writeFile5(join9(dir, "world.json"), JSON.stringify(worldJson, null, 2)),
8201
- writeFile5(join9(dir, "kernel.json"), JSON.stringify(kernelJson, null, 2)),
8202
- writeFile5(join9(dir, "metadata.json"), JSON.stringify(metadataJson, null, 2))
8365
+ writeFile6(join14(dir, "world.json"), JSON.stringify(worldJson, null, 2)),
8366
+ writeFile6(join14(dir, "kernel.json"), JSON.stringify(kernelJson, null, 2)),
8367
+ writeFile6(join14(dir, "metadata.json"), JSON.stringify(metadataJson, null, 2))
8203
8368
  ]);
8204
8369
  }
8205
8370
  var init_govern = __esm({
@@ -8543,10 +8708,10 @@ data: ${data}
8543
8708
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
8544
8709
  }
8545
8710
  function readBody(req) {
8546
- return new Promise((resolve5, reject) => {
8711
+ return new Promise((resolve6, reject) => {
8547
8712
  const chunks = [];
8548
8713
  req.on("data", (chunk) => chunks.push(chunk));
8549
- req.on("end", () => resolve5(Buffer.concat(chunks).toString("utf-8")));
8714
+ req.on("end", () => resolve6(Buffer.concat(chunks).toString("utf-8")));
8550
8715
  req.on("error", reject);
8551
8716
  });
8552
8717
  }
@@ -9544,84 +9709,503 @@ var init_express = __esm({
9544
9709
  }
9545
9710
  });
9546
9711
 
9547
- // src/adapters/langchain.ts
9548
- var langchain_exports = {};
9549
- __export(langchain_exports, {
9550
- GovernanceBlockedError: () => GovernanceBlockedError3,
9551
- NeuroVerseCallbackHandler: () => NeuroVerseCallbackHandler,
9552
- createNeuroVerseCallbackHandler: () => createNeuroVerseCallbackHandler,
9553
- createNeuroVerseCallbackHandlerFromWorld: () => createNeuroVerseCallbackHandlerFromWorld
9712
+ // src/adapters/github.ts
9713
+ var github_exports = {};
9714
+ __export(github_exports, {
9715
+ GitHubGovernanceBlockedError: () => GitHubGovernanceBlockedError,
9716
+ GitHubGovernor: () => GitHubGovernor,
9717
+ GitHubWebhookHandler: () => GitHubWebhookHandler,
9718
+ createGitHubGovernor: () => createGitHubGovernor,
9719
+ createGitHubGovernorFromWorld: () => createGitHubGovernorFromWorld,
9720
+ createGitHubWebhookHandler: () => createGitHubWebhookHandler,
9721
+ createGitHubWebhookHandlerFromWorld: () => createGitHubWebhookHandlerFromWorld,
9722
+ formatForActions: () => formatForActions,
9723
+ formatPRComment: () => formatPRComment
9554
9724
  });
9555
- function defaultMapToolCall2(toolName, toolInput) {
9725
+ function extractBranch(ref) {
9726
+ if (!ref) return void 0;
9727
+ if (ref.startsWith("refs/heads/")) return ref.slice("refs/heads/".length);
9728
+ if (ref.startsWith("refs/tags/")) return ref.slice("refs/tags/".length);
9729
+ return ref;
9730
+ }
9731
+ function isProtectedBranch(branch, protectedBranches) {
9732
+ if (!branch) return false;
9733
+ return protectedBranches.some(
9734
+ (pb) => branch === pb || branch.startsWith(`${pb}/`)
9735
+ );
9736
+ }
9737
+ function defaultMapAction(action, protectedBranches, restrictedActors) {
9738
+ const branch = action.branch ?? extractBranch(action.ref);
9739
+ const isProtected = isProtectedBranch(branch, protectedBranches);
9740
+ const isRestricted = action.actor ? restrictedActors.some((ra) => action.actor === ra || action.actor?.endsWith("[bot]")) : false;
9741
+ let actionCategory = "other";
9742
+ const act = action.action.toLowerCase();
9743
+ if (act.includes("read") || act.includes("get") || act.includes("list") || act.includes("view")) {
9744
+ actionCategory = "read";
9745
+ } else if (act.includes("delete") || act.includes("remove") || act.includes("close")) {
9746
+ actionCategory = "delete";
9747
+ } else if (act.includes("deploy") || act.includes("run") || act.includes("execute") || act.includes("merge")) {
9748
+ actionCategory = "network";
9749
+ } else if (act.includes("create") || act.includes("push") || act.includes("write") || act.includes("update") || act.includes("edit")) {
9750
+ actionCategory = "write";
9751
+ } else if (act.includes("comment") || act.includes("review") || act.includes("notify")) {
9752
+ actionCategory = "other";
9753
+ }
9556
9754
  return {
9557
- intent: toolName,
9558
- tool: toolName,
9559
- scope: extractScope(toolInput),
9560
- args: toolInput,
9561
- direction: "input"
9755
+ intent: action.action,
9756
+ tool: "github",
9757
+ scope: `${action.repository}${branch ? `@${branch}` : ""}`,
9758
+ actionCategory,
9759
+ direction: "input",
9760
+ args: {
9761
+ repository: action.repository,
9762
+ ref: action.ref,
9763
+ branch,
9764
+ actor: action.actor,
9765
+ protected_branch: isProtected,
9766
+ restricted_actor: isRestricted,
9767
+ ...action.metadata
9768
+ }
9562
9769
  };
9563
9770
  }
9564
- async function createNeuroVerseCallbackHandler(worldPath, options) {
9771
+ function defaultMapWebhook(eventType, payload) {
9772
+ const repo = payload.repository;
9773
+ const repoFullName = repo?.full_name ?? "unknown/unknown";
9774
+ const sender = payload.sender;
9775
+ const actor = sender?.login ?? void 0;
9776
+ const webhookAction = payload.action;
9777
+ switch (eventType) {
9778
+ case "push": {
9779
+ const ref = payload.ref;
9780
+ const branch = extractBranch(ref);
9781
+ const forced = payload.forced;
9782
+ return {
9783
+ action: forced ? "force_push" : `push_to_${branch ?? "branch"}`,
9784
+ repository: repoFullName,
9785
+ ref,
9786
+ branch,
9787
+ actor,
9788
+ metadata: {
9789
+ forced: forced ?? false,
9790
+ commits_count: payload.commits?.length ?? 0,
9791
+ head_commit: payload.head_commit?.id
9792
+ }
9793
+ };
9794
+ }
9795
+ case "pull_request": {
9796
+ const pr = payload.pull_request;
9797
+ const base = pr?.base;
9798
+ const baseBranch = base?.ref;
9799
+ const prNumber = pr?.number;
9800
+ const merged = pr?.merged;
9801
+ const labels = pr?.labels?.map((l) => l.name) ?? [];
9802
+ let action = `pull_request_${webhookAction ?? "unknown"}`;
9803
+ if (webhookAction === "closed" && merged) {
9804
+ action = "merge_pull_request";
9805
+ }
9806
+ return {
9807
+ action,
9808
+ repository: repoFullName,
9809
+ branch: baseBranch,
9810
+ actor,
9811
+ metadata: {
9812
+ pr_number: prNumber,
9813
+ labels,
9814
+ merged: merged ?? false,
9815
+ draft: pr?.draft ?? false,
9816
+ webhook_action: webhookAction
9817
+ }
9818
+ };
9819
+ }
9820
+ case "release": {
9821
+ const release = payload.release;
9822
+ return {
9823
+ action: `release_${webhookAction ?? "published"}`,
9824
+ repository: repoFullName,
9825
+ ref: release?.tag_name ? `refs/tags/${release.tag_name}` : void 0,
9826
+ actor,
9827
+ metadata: {
9828
+ tag: release?.tag_name,
9829
+ prerelease: release?.prerelease ?? false,
9830
+ draft: release?.draft ?? false,
9831
+ webhook_action: webhookAction
9832
+ }
9833
+ };
9834
+ }
9835
+ case "deployment":
9836
+ case "deployment_status": {
9837
+ const deployment = payload.deployment ?? payload;
9838
+ return {
9839
+ action: eventType === "deployment" ? "create_deployment" : "deployment_status_update",
9840
+ repository: repoFullName,
9841
+ ref: deployment.ref,
9842
+ actor,
9843
+ metadata: {
9844
+ environment: deployment.environment,
9845
+ status: payload.deployment_status?.state,
9846
+ webhook_action: webhookAction
9847
+ }
9848
+ };
9849
+ }
9850
+ case "workflow_run": {
9851
+ const run = payload.workflow_run;
9852
+ return {
9853
+ action: `workflow_${webhookAction ?? "completed"}`,
9854
+ repository: repoFullName,
9855
+ branch: run?.head_branch,
9856
+ actor,
9857
+ metadata: {
9858
+ workflow_name: run?.name,
9859
+ conclusion: run?.conclusion,
9860
+ status: run?.status,
9861
+ webhook_action: webhookAction
9862
+ }
9863
+ };
9864
+ }
9865
+ case "issues": {
9866
+ const issue = payload.issue;
9867
+ return {
9868
+ action: `issue_${webhookAction ?? "opened"}`,
9869
+ repository: repoFullName,
9870
+ actor,
9871
+ metadata: {
9872
+ issue_number: issue?.number,
9873
+ labels: issue?.labels?.map((l) => l.name) ?? [],
9874
+ webhook_action: webhookAction
9875
+ }
9876
+ };
9877
+ }
9878
+ case "issue_comment": {
9879
+ return {
9880
+ action: `issue_comment_${webhookAction ?? "created"}`,
9881
+ repository: repoFullName,
9882
+ actor,
9883
+ metadata: {
9884
+ issue_number: payload.issue?.number,
9885
+ webhook_action: webhookAction
9886
+ }
9887
+ };
9888
+ }
9889
+ case "delete": {
9890
+ return {
9891
+ action: `delete_${payload.ref_type ?? "ref"}`,
9892
+ repository: repoFullName,
9893
+ ref: payload.ref,
9894
+ actor,
9895
+ metadata: {
9896
+ ref_type: payload.ref_type
9897
+ }
9898
+ };
9899
+ }
9900
+ default: {
9901
+ return {
9902
+ action: webhookAction ? `${eventType}_${webhookAction}` : eventType,
9903
+ repository: repoFullName,
9904
+ actor,
9905
+ metadata: { webhook_action: webhookAction }
9906
+ };
9907
+ }
9908
+ }
9909
+ }
9910
+ function formatForActions(verdict) {
9911
+ const status = verdict.status === "ALLOW" ? "allowed" : verdict.status === "BLOCK" ? "blocked" : "paused";
9912
+ const reason = verdict.reason ?? "";
9913
+ const ruleId = verdict.ruleId ?? "";
9914
+ const lines = [
9915
+ `governance_status=${status}`,
9916
+ `verdict_status=${verdict.status}`,
9917
+ `reason=${reason}`,
9918
+ `rule_id=${ruleId}`
9919
+ ].join("\n");
9920
+ return {
9921
+ governance_status: status,
9922
+ verdict_status: verdict.status,
9923
+ reason,
9924
+ rule_id: ruleId,
9925
+ outputLines: lines
9926
+ };
9927
+ }
9928
+ function formatPRComment(verdict, action) {
9929
+ const icon = verdict.status === "ALLOW" ? "\u2705" : verdict.status === "BLOCK" ? "\u{1F6AB}" : "\u23F8\uFE0F";
9930
+ const status = verdict.status;
9931
+ let body = `## ${icon} Governance: ${status}
9932
+
9933
+ `;
9934
+ body += `**Action:** \`${action.action}\`
9935
+ `;
9936
+ body += `**Repository:** \`${action.repository}\`
9937
+ `;
9938
+ if (action.branch) {
9939
+ body += `**Branch:** \`${action.branch}\`
9940
+ `;
9941
+ }
9942
+ if (action.actor) {
9943
+ body += `**Actor:** \`${action.actor}\`
9944
+ `;
9945
+ }
9946
+ body += "\n";
9947
+ if (verdict.reason) {
9948
+ body += `**Reason:** ${verdict.reason}
9949
+ `;
9950
+ }
9951
+ if (verdict.ruleId) {
9952
+ body += `**Rule:** \`${verdict.ruleId}\`
9953
+ `;
9954
+ }
9955
+ if (verdict.evidence?.invariantsSatisfied < verdict.evidence?.invariantsTotal) {
9956
+ body += `**Invariants:** ${verdict.evidence.invariantsSatisfied}/${verdict.evidence.invariantsTotal} satisfied
9957
+ `;
9958
+ }
9959
+ body += "\n---\n*Evaluated by [NeuroVerse Governance](https://github.com/NeuroverseOS/neuroverseos-governance)*";
9960
+ return body;
9961
+ }
9962
+ async function createGitHubGovernor(worldPath, options) {
9565
9963
  const world = await loadWorld(worldPath);
9566
- return new NeuroVerseCallbackHandler(world, options);
9964
+ return new GitHubGovernor(world, options);
9567
9965
  }
9568
- function createNeuroVerseCallbackHandlerFromWorld(world, options) {
9569
- return new NeuroVerseCallbackHandler(world, options);
9966
+ function createGitHubGovernorFromWorld(world, options) {
9967
+ return new GitHubGovernor(world, options);
9570
9968
  }
9571
- var GovernanceBlockedError3, NeuroVerseCallbackHandler;
9572
- var init_langchain = __esm({
9573
- "src/adapters/langchain.ts"() {
9969
+ async function createGitHubWebhookHandler(worldPath, options) {
9970
+ const world = await loadWorld(worldPath);
9971
+ return new GitHubWebhookHandler(world, options);
9972
+ }
9973
+ function createGitHubWebhookHandlerFromWorld(world, options) {
9974
+ return new GitHubWebhookHandler(world, options);
9975
+ }
9976
+ var GitHubGovernanceBlockedError, GitHubGovernor, GitHubWebhookHandler;
9977
+ var init_github = __esm({
9978
+ "src/adapters/github.ts"() {
9574
9979
  "use strict";
9575
9980
  init_guard_engine();
9576
9981
  init_world_loader();
9577
9982
  init_shared();
9578
- GovernanceBlockedError3 = class extends GovernanceBlockedError {
9579
- event;
9580
- constructor(verdict, event) {
9581
- super(verdict);
9582
- this.event = event;
9983
+ GitHubGovernanceBlockedError = class extends GovernanceBlockedError {
9984
+ action;
9985
+ constructor(verdict, action) {
9986
+ super(verdict, `[NeuroVerse] GitHub action blocked: ${action.action} on ${action.repository}`);
9987
+ this.name = "GitHubGovernanceBlockedError";
9988
+ this.action = action;
9583
9989
  }
9584
9990
  };
9585
- NeuroVerseCallbackHandler = class {
9586
- name = "NeuroVerseGovernance";
9991
+ GitHubGovernor = class {
9587
9992
  world;
9588
9993
  options;
9589
9994
  engineOptions;
9590
- mapToolCall;
9591
9995
  activePlan;
9996
+ protectedBranches;
9997
+ restrictedActors;
9998
+ mapFn;
9592
9999
  constructor(world, options = {}) {
9593
10000
  this.world = world;
9594
10001
  this.options = options;
9595
10002
  this.activePlan = options.plan;
9596
10003
  this.engineOptions = buildEngineOptions(options, this.activePlan);
9597
- this.mapToolCall = options.mapToolCall ?? defaultMapToolCall2;
10004
+ this.protectedBranches = options.protectedBranches ?? ["main", "master", "production"];
10005
+ this.restrictedActors = options.restrictedActors ?? [];
10006
+ this.mapFn = options.mapAction ?? ((action) => defaultMapAction(action, this.protectedBranches, this.restrictedActors));
9598
10007
  }
9599
10008
  /**
9600
- * Called before a tool is executed.
9601
- * Evaluates the tool call against the governance world.
9602
- *
9603
- * @throws GovernanceBlockedError if the action is BLOCKED
9604
- * @throws GovernanceBlockedError if the action is PAUSED and onPause returns false
10009
+ * Evaluate a GitHub action against governance rules.
10010
+ * Returns a full result with verdict, event, and the original action.
9605
10011
  */
9606
- async handleToolStart(tool, input) {
9607
- let parsedInput;
9608
- try {
9609
- parsedInput = typeof input === "string" ? JSON.parse(input) : input;
9610
- } catch {
9611
- parsedInput = { raw: input };
9612
- }
9613
- const event = this.mapToolCall(tool.name, parsedInput);
10012
+ evaluate(action) {
10013
+ const event = this.mapFn(action);
9614
10014
  this.engineOptions.plan = this.activePlan;
9615
10015
  const verdict = evaluateGuard(event, this.world, this.engineOptions);
9616
- this.options.onEvaluate?.(verdict, event);
9617
- if (verdict.status === "BLOCK") {
9618
- this.options.onBlock?.(verdict, event);
9619
- throw new GovernanceBlockedError3(verdict, event);
10016
+ this.options.onEvaluate?.(verdict, event, action);
10017
+ if (verdict.status === "ALLOW") {
10018
+ trackPlanProgress(event, this, this.options);
9620
10019
  }
9621
- if (verdict.status === "PAUSE") {
9622
- const approved = await this.options.onPause?.(verdict, event);
9623
- if (!approved) {
9624
- throw new GovernanceBlockedError3(verdict, event);
10020
+ return { verdict, event, action };
10021
+ }
10022
+ /**
10023
+ * Evaluate and enforce — throws GitHubGovernanceBlockedError on BLOCK/PAUSE.
10024
+ * Use this as a gate before executing GitHub API calls.
10025
+ */
10026
+ enforce(action) {
10027
+ const result = this.evaluate(action);
10028
+ if (result.verdict.status === "BLOCK" || result.verdict.status === "PAUSE") {
10029
+ throw new GitHubGovernanceBlockedError(result.verdict, action);
10030
+ }
10031
+ return result;
10032
+ }
10033
+ /**
10034
+ * Check if pushing to a branch is allowed.
10035
+ * Convenience method for the most common governance check.
10036
+ */
10037
+ canPush(repository, branch, actor) {
10038
+ return this.evaluate({
10039
+ action: `push_to_${branch}`,
10040
+ repository,
10041
+ ref: `refs/heads/${branch}`,
10042
+ branch,
10043
+ actor
10044
+ }).verdict;
10045
+ }
10046
+ /**
10047
+ * Check if merging a PR is allowed.
10048
+ */
10049
+ canMerge(repository, targetBranch, prNumber, actor, labels) {
10050
+ return this.evaluate({
10051
+ action: "merge_pull_request",
10052
+ repository,
10053
+ branch: targetBranch,
10054
+ actor,
10055
+ metadata: { pr_number: prNumber, labels: labels ?? [] }
10056
+ }).verdict;
10057
+ }
10058
+ /**
10059
+ * Check if creating a release is allowed.
10060
+ */
10061
+ canRelease(repository, tag, actor, prerelease) {
10062
+ return this.evaluate({
10063
+ action: "release_published",
10064
+ repository,
10065
+ ref: `refs/tags/${tag}`,
10066
+ actor,
10067
+ metadata: { tag, prerelease: prerelease ?? false }
10068
+ }).verdict;
10069
+ }
10070
+ /**
10071
+ * Check if deploying to an environment is allowed.
10072
+ */
10073
+ canDeploy(repository, environment, ref, actor) {
10074
+ return this.evaluate({
10075
+ action: "create_deployment",
10076
+ repository,
10077
+ ref,
10078
+ actor,
10079
+ metadata: { environment }
10080
+ }).verdict;
10081
+ }
10082
+ };
10083
+ GitHubWebhookHandler = class {
10084
+ governor;
10085
+ mapWebhookFn;
10086
+ webhookSecret;
10087
+ constructor(world, options = {}) {
10088
+ this.governor = new GitHubGovernor(world, options);
10089
+ this.mapWebhookFn = options.mapWebhook ?? defaultMapWebhook;
10090
+ this.webhookSecret = options.webhookSecret;
10091
+ }
10092
+ /**
10093
+ * Evaluate a webhook payload.
10094
+ *
10095
+ * @param eventType - The X-GitHub-Event header value
10096
+ * @param payload - The parsed webhook body
10097
+ */
10098
+ evaluate(eventType, payload) {
10099
+ const action = this.mapWebhookFn(eventType, payload);
10100
+ const result = this.governor.evaluate(action);
10101
+ return {
10102
+ verdict: result.verdict,
10103
+ event: result.event,
10104
+ webhookEvent: eventType,
10105
+ webhookAction: payload.action
10106
+ };
10107
+ }
10108
+ /**
10109
+ * Evaluate and enforce — throws on BLOCK/PAUSE.
10110
+ */
10111
+ enforce(eventType, payload) {
10112
+ const result = this.evaluate(eventType, payload);
10113
+ if (result.verdict.status === "BLOCK" || result.verdict.status === "PAUSE") {
10114
+ const action = this.mapWebhookFn(eventType, payload);
10115
+ throw new GitHubGovernanceBlockedError(result.verdict, action);
10116
+ }
10117
+ return result;
10118
+ }
10119
+ /** Access the underlying governor for direct action evaluation. */
10120
+ getGovernor() {
10121
+ return this.governor;
10122
+ }
10123
+ /** Get the configured webhook secret (for signature verification in your server). */
10124
+ getWebhookSecret() {
10125
+ return this.webhookSecret;
10126
+ }
10127
+ };
10128
+ }
10129
+ });
10130
+
10131
+ // src/adapters/langchain.ts
10132
+ var langchain_exports = {};
10133
+ __export(langchain_exports, {
10134
+ GovernanceBlockedError: () => GovernanceBlockedError3,
10135
+ NeuroVerseCallbackHandler: () => NeuroVerseCallbackHandler,
10136
+ createNeuroVerseCallbackHandler: () => createNeuroVerseCallbackHandler,
10137
+ createNeuroVerseCallbackHandlerFromWorld: () => createNeuroVerseCallbackHandlerFromWorld
10138
+ });
10139
+ function defaultMapToolCall2(toolName, toolInput) {
10140
+ return {
10141
+ intent: toolName,
10142
+ tool: toolName,
10143
+ scope: extractScope(toolInput),
10144
+ args: toolInput,
10145
+ direction: "input"
10146
+ };
10147
+ }
10148
+ async function createNeuroVerseCallbackHandler(worldPath, options) {
10149
+ const world = await loadWorld(worldPath);
10150
+ return new NeuroVerseCallbackHandler(world, options);
10151
+ }
10152
+ function createNeuroVerseCallbackHandlerFromWorld(world, options) {
10153
+ return new NeuroVerseCallbackHandler(world, options);
10154
+ }
10155
+ var GovernanceBlockedError3, NeuroVerseCallbackHandler;
10156
+ var init_langchain = __esm({
10157
+ "src/adapters/langchain.ts"() {
10158
+ "use strict";
10159
+ init_guard_engine();
10160
+ init_world_loader();
10161
+ init_shared();
10162
+ GovernanceBlockedError3 = class extends GovernanceBlockedError {
10163
+ event;
10164
+ constructor(verdict, event) {
10165
+ super(verdict);
10166
+ this.event = event;
10167
+ }
10168
+ };
10169
+ NeuroVerseCallbackHandler = class {
10170
+ name = "NeuroVerseGovernance";
10171
+ world;
10172
+ options;
10173
+ engineOptions;
10174
+ mapToolCall;
10175
+ activePlan;
10176
+ constructor(world, options = {}) {
10177
+ this.world = world;
10178
+ this.options = options;
10179
+ this.activePlan = options.plan;
10180
+ this.engineOptions = buildEngineOptions(options, this.activePlan);
10181
+ this.mapToolCall = options.mapToolCall ?? defaultMapToolCall2;
10182
+ }
10183
+ /**
10184
+ * Called before a tool is executed.
10185
+ * Evaluates the tool call against the governance world.
10186
+ *
10187
+ * @throws GovernanceBlockedError if the action is BLOCKED
10188
+ * @throws GovernanceBlockedError if the action is PAUSED and onPause returns false
10189
+ */
10190
+ async handleToolStart(tool, input) {
10191
+ let parsedInput;
10192
+ try {
10193
+ parsedInput = typeof input === "string" ? JSON.parse(input) : input;
10194
+ } catch {
10195
+ parsedInput = { raw: input };
10196
+ }
10197
+ const event = this.mapToolCall(tool.name, parsedInput);
10198
+ this.engineOptions.plan = this.activePlan;
10199
+ const verdict = evaluateGuard(event, this.world, this.engineOptions);
10200
+ this.options.onEvaluate?.(verdict, event);
10201
+ if (verdict.status === "BLOCK") {
10202
+ this.options.onBlock?.(verdict, event);
10203
+ throw new GovernanceBlockedError3(verdict, event);
10204
+ }
10205
+ if (verdict.status === "PAUSE") {
10206
+ const approved = await this.options.onPause?.(verdict, event);
10207
+ if (!approved) {
10208
+ throw new GovernanceBlockedError3(verdict, event);
9625
10209
  }
9626
10210
  }
9627
10211
  if (verdict.status === "ALLOW") {
@@ -9755,7 +10339,7 @@ __export(openclaw_exports, {
9755
10339
  createNeuroVersePlugin: () => createNeuroVersePlugin,
9756
10340
  createNeuroVersePluginFromWorld: () => createNeuroVersePluginFromWorld
9757
10341
  });
9758
- function defaultMapAction(action, direction) {
10342
+ function defaultMapAction2(action, direction) {
9759
10343
  return {
9760
10344
  intent: action.type,
9761
10345
  tool: action.tool ?? action.type,
@@ -9797,7 +10381,7 @@ var init_openclaw = __esm({
9797
10381
  this.options = options;
9798
10382
  this.activePlan = options.plan;
9799
10383
  this.engineOptions = buildEngineOptions(options, this.activePlan);
9800
- this.mapAction = options.mapAction ?? defaultMapAction;
10384
+ this.mapAction = options.mapAction ?? defaultMapAction2;
9801
10385
  }
9802
10386
  /**
9803
10387
  * Evaluate an action before execution.
@@ -10827,6 +11411,7 @@ var init_ = __esm({
10827
11411
  "../adapters/autoresearch.ts": () => Promise.resolve().then(() => (init_autoresearch(), autoresearch_exports)),
10828
11412
  "../adapters/deep-agents.ts": () => Promise.resolve().then(() => (init_deep_agents(), deep_agents_exports)),
10829
11413
  "../adapters/express.ts": () => Promise.resolve().then(() => (init_express(), express_exports)),
11414
+ "../adapters/github.ts": () => Promise.resolve().then(() => (init_github(), github_exports)),
10830
11415
  "../adapters/index.ts": () => Promise.resolve().then(() => (init_adapters(), adapters_exports)),
10831
11416
  "../adapters/langchain.ts": () => Promise.resolve().then(() => (init_langchain(), langchain_exports)),
10832
11417
  "../adapters/mentraos.ts": () => Promise.resolve().then(() => (init_mentraos(), mentraos_exports)),
@@ -10890,9 +11475,9 @@ async function main15(argv) {
10890
11475
  }
10891
11476
  if (worldPath) {
10892
11477
  try {
10893
- const { existsSync: existsSync6 } = await import("fs");
10894
- const { join: join9 } = await import("path");
10895
- const hasWorld = existsSync6(join9(worldPath, "world.json"));
11478
+ const { existsSync: existsSync10 } = await import("fs");
11479
+ const { join: join14 } = await import("path");
11480
+ const hasWorld = existsSync10(join14(worldPath, "world.json"));
10896
11481
  checks.push({
10897
11482
  label: "World file detected",
10898
11483
  status: hasWorld ? "pass" : "fail",
@@ -10907,12 +11492,12 @@ async function main15(argv) {
10907
11492
  });
10908
11493
  }
10909
11494
  } else {
10910
- const { existsSync: existsSync6 } = await import("fs");
10911
- const { join: join9 } = await import("path");
11495
+ const { existsSync: existsSync10 } = await import("fs");
11496
+ const { join: join14 } = await import("path");
10912
11497
  const candidates = ["./world", "./.neuroverse", "./worlds"];
10913
11498
  let found;
10914
11499
  for (const dir of candidates) {
10915
- if (existsSync6(join9(dir, "world.json"))) {
11500
+ if (existsSync10(join14(dir, "world.json"))) {
10916
11501
  found = dir;
10917
11502
  break;
10918
11503
  }
@@ -11964,8 +12549,8 @@ async function deriveCommand(args) {
11964
12549
  return;
11965
12550
  }
11966
12551
  const plan = result.plan;
11967
- const { mkdirSync: mkdirSync3 } = await import("fs");
11968
- mkdirSync3(outputDir, { recursive: true });
12552
+ const { mkdirSync: mkdirSync5 } = await import("fs");
12553
+ mkdirSync5(outputDir, { recursive: true });
11969
12554
  const worldJson = {
11970
12555
  world_id: `plan_${plan.plan_id}`,
11971
12556
  name: `Derived: ${plan.objective}`,
@@ -12562,11 +13147,17 @@ async function runPipeMode(config) {
12562
13147
  process.stderr.write(`[neuroverse] Plan: ${state.plan.plan_id} (${state.plan.objective})
12563
13148
  `);
12564
13149
  }
12565
- return new Promise((resolve5, reject) => {
13150
+ const MAX_BUFFER_SIZE = 1e6;
13151
+ return new Promise((resolve6, reject) => {
12566
13152
  let buffer = "";
12567
13153
  process.stdin.setEncoding("utf-8");
12568
13154
  process.stdin.on("data", (chunk) => {
12569
13155
  buffer += chunk;
13156
+ if (buffer.length > MAX_BUFFER_SIZE) {
13157
+ process.stderr.write("[neuroverse] Warning: pipe buffer exceeded 1MB, resetting\n");
13158
+ buffer = "";
13159
+ return;
13160
+ }
12570
13161
  const lines = buffer.split("\n");
12571
13162
  buffer = lines.pop() ?? "";
12572
13163
  for (const line of lines) {
@@ -12603,7 +13194,7 @@ async function runPipeMode(config) {
12603
13194
  `[neuroverse] Session complete: ${finalState.actionsEvaluated} evaluated, ${finalState.actionsAllowed} allowed, ${finalState.actionsBlocked} blocked, ${finalState.actionsPaused} paused
12604
13195
  `
12605
13196
  );
12606
- resolve5();
13197
+ resolve6();
12607
13198
  });
12608
13199
  process.stdin.on("error", reject);
12609
13200
  });
@@ -12719,8 +13310,8 @@ ${response.content}
12719
13310
  rl2.on("close", () => {
12720
13311
  session.stop();
12721
13312
  });
12722
- return new Promise((resolve5) => {
12723
- rl2.on("close", resolve5);
13313
+ return new Promise((resolve6) => {
13314
+ rl2.on("close", resolve6);
12724
13315
  });
12725
13316
  }
12726
13317
  var SessionManager;
@@ -12731,7 +13322,9 @@ var init_session = __esm({
12731
13322
  init_plan_engine();
12732
13323
  init_world_loader();
12733
13324
  init_decision_flow_engine();
12734
- SessionManager = class {
13325
+ SessionManager = class _SessionManager {
13326
+ /** Maximum unique agent IDs tracked before eviction. Prevents unbounded memory growth. */
13327
+ static MAX_AGENTS = 1e4;
12735
13328
  config;
12736
13329
  state;
12737
13330
  engineOptions;
@@ -12795,6 +13388,16 @@ var init_session = __esm({
12795
13388
  if (verdict.status === "REWARD" && verdict.reward) {
12796
13389
  agentState = applyReward(agentState, verdict.reward, verdict.ruleId ?? "unknown");
12797
13390
  }
13391
+ if (this.state.agentStates.size >= _SessionManager.MAX_AGENTS && !this.state.agentStates.has(event.roleId)) {
13392
+ const oldest = this.state.agentStates.keys().next().value;
13393
+ if (oldest !== void 0) {
13394
+ this.state.agentStates.delete(oldest);
13395
+ }
13396
+ process.stderr.write(
13397
+ `[neuroverse] Warning: agent state map at capacity (${_SessionManager.MAX_AGENTS}), evicted oldest entry
13398
+ `
13399
+ );
13400
+ }
12798
13401
  this.state.agentStates.set(event.roleId, agentState);
12799
13402
  }
12800
13403
  this.config.onVerdict?.(verdict, event);
@@ -12948,8 +13551,15 @@ async function main18(args) {
12948
13551
  const plan = planPath ? loadPlan(planPath) : autoDetectPlan();
12949
13552
  const level = parseArg2(args, "--level");
12950
13553
  const trace = hasFlag(args, "--trace");
13554
+ const logPath = parseArg2(args, "--log");
12951
13555
  const isPipeMode = hasFlag(args, "--pipe") || !process.stdin.isTTY;
12952
13556
  const isInteractive = hasFlag(args, "--interactive");
13557
+ let auditLogger;
13558
+ if (logPath) {
13559
+ auditLogger = new FileAuditLogger(logPath);
13560
+ process.stderr.write(`[neuroverse] Audit logging to ${logPath}
13561
+ `);
13562
+ }
12953
13563
  if (isInteractive) {
12954
13564
  const providerName = parseArg2(args, "--provider");
12955
13565
  if (!providerName) {
@@ -12973,6 +13583,9 @@ async function main18(args) {
12973
13583
  level,
12974
13584
  trace,
12975
13585
  onVerdict: (verdict, event) => {
13586
+ if (auditLogger) {
13587
+ auditLogger.log(verdictToAuditEvent(event, verdict));
13588
+ }
12976
13589
  if (verdict.status !== "ALLOW") {
12977
13590
  process.stderr.write(
12978
13591
  ` [${verdict.status}] ${event.intent} \u2014 ${verdict.reason ?? verdict.ruleId ?? "governance rule"}
@@ -12999,8 +13612,12 @@ async function main18(args) {
12999
13612
  worldPath,
13000
13613
  plan,
13001
13614
  level,
13002
- trace
13615
+ trace,
13616
+ onVerdict: auditLogger ? (verdict, event) => {
13617
+ auditLogger.log(verdictToAuditEvent(event, verdict));
13618
+ } : void 0
13003
13619
  });
13620
+ if (auditLogger) await auditLogger.flush();
13004
13621
  } else {
13005
13622
  process.stdout.write(RUN_USAGE + "\n");
13006
13623
  process.exit(0);
@@ -13013,6 +13630,7 @@ var init_run = __esm({
13013
13630
  import_fs5 = require("fs");
13014
13631
  import_path6 = require("path");
13015
13632
  init_world_resolver();
13633
+ init_audit_logger();
13016
13634
  RUN_USAGE = `
13017
13635
  neuroverse run \u2014 Governed runtime for AI agents.
13018
13636
 
@@ -13803,28 +14421,28 @@ function computeWorldDiff(a, b) {
13803
14421
  return { changes };
13804
14422
  }
13805
14423
  async function worldSnapshot(worldPath) {
13806
- const { readdir, readFile: readFile3, mkdir: mkdir2, writeFile: writeFile5 } = await import("fs/promises");
13807
- const { join: join9 } = await import("path");
14424
+ const { readdir, readFile: readFile4, mkdir: mkdir3, writeFile: writeFile6 } = await import("fs/promises");
14425
+ const { join: join14 } = await import("path");
13808
14426
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
13809
- const snapshotDir = join9(worldPath, ".snapshots", timestamp);
13810
- await mkdir2(snapshotDir, { recursive: true });
14427
+ const snapshotDir = join14(worldPath, ".snapshots", timestamp);
14428
+ await mkdir3(snapshotDir, { recursive: true });
13811
14429
  const files = await readdir(worldPath);
13812
14430
  let copied = 0;
13813
14431
  for (const file of files) {
13814
14432
  if (file.endsWith(".json")) {
13815
- const content = await readFile3(join9(worldPath, file), "utf-8");
13816
- await writeFile5(join9(snapshotDir, file), content, "utf-8");
14433
+ const content = await readFile4(join14(worldPath, file), "utf-8");
14434
+ await writeFile6(join14(snapshotDir, file), content, "utf-8");
13817
14435
  copied++;
13818
14436
  }
13819
14437
  }
13820
14438
  try {
13821
- const rulesDir = join9(worldPath, "rules");
14439
+ const rulesDir = join14(worldPath, "rules");
13822
14440
  const ruleFiles = await readdir(rulesDir);
13823
- await mkdir2(join9(snapshotDir, "rules"), { recursive: true });
14441
+ await mkdir3(join14(snapshotDir, "rules"), { recursive: true });
13824
14442
  for (const file of ruleFiles) {
13825
14443
  if (file.endsWith(".json")) {
13826
- const content = await readFile3(join9(rulesDir, file), "utf-8");
13827
- await writeFile5(join9(snapshotDir, "rules", file), content, "utf-8");
14444
+ const content = await readFile4(join14(rulesDir, file), "utf-8");
14445
+ await writeFile6(join14(snapshotDir, "rules", file), content, "utf-8");
13828
14446
  copied++;
13829
14447
  }
13830
14448
  }
@@ -13836,9 +14454,9 @@ async function worldSnapshot(worldPath) {
13836
14454
  `);
13837
14455
  }
13838
14456
  async function worldRollback(worldPath) {
13839
- const { readdir, readFile: readFile3, writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
13840
- const { join: join9 } = await import("path");
13841
- const snapshotsDir = join9(worldPath, ".snapshots");
14457
+ const { readdir, readFile: readFile4, writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
14458
+ const { join: join14 } = await import("path");
14459
+ const snapshotsDir = join14(worldPath, ".snapshots");
13842
14460
  let snapshots;
13843
14461
  try {
13844
14462
  snapshots = (await readdir(snapshotsDir)).sort();
@@ -13853,34 +14471,34 @@ async function worldRollback(worldPath) {
13853
14471
  return;
13854
14472
  }
13855
14473
  const latest = snapshots[snapshots.length - 1];
13856
- const snapshotDir = join9(snapshotsDir, latest);
14474
+ const snapshotDir = join14(snapshotsDir, latest);
13857
14475
  const backupTimestamp = "pre-rollback-" + (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
13858
- const backupDir = join9(snapshotsDir, backupTimestamp);
13859
- await mkdir2(backupDir, { recursive: true });
14476
+ const backupDir = join14(snapshotsDir, backupTimestamp);
14477
+ await mkdir3(backupDir, { recursive: true });
13860
14478
  const currentFiles = await readdir(worldPath);
13861
14479
  for (const file of currentFiles) {
13862
14480
  if (file.endsWith(".json")) {
13863
- const content = await readFile3(join9(worldPath, file), "utf-8");
13864
- await writeFile5(join9(backupDir, file), content, "utf-8");
14481
+ const content = await readFile4(join14(worldPath, file), "utf-8");
14482
+ await writeFile6(join14(backupDir, file), content, "utf-8");
13865
14483
  }
13866
14484
  }
13867
14485
  const snapshotFiles = await readdir(snapshotDir);
13868
14486
  let restored = 0;
13869
14487
  for (const file of snapshotFiles) {
13870
14488
  if (file.endsWith(".json")) {
13871
- const content = await readFile3(join9(snapshotDir, file), "utf-8");
13872
- await writeFile5(join9(worldPath, file), content, "utf-8");
14489
+ const content = await readFile4(join14(snapshotDir, file), "utf-8");
14490
+ await writeFile6(join14(worldPath, file), content, "utf-8");
13873
14491
  restored++;
13874
14492
  }
13875
14493
  }
13876
14494
  try {
13877
- const rulesDir = join9(snapshotDir, "rules");
14495
+ const rulesDir = join14(snapshotDir, "rules");
13878
14496
  const ruleFiles = await readdir(rulesDir);
13879
- await mkdir2(join9(worldPath, "rules"), { recursive: true });
14497
+ await mkdir3(join14(worldPath, "rules"), { recursive: true });
13880
14498
  for (const file of ruleFiles) {
13881
14499
  if (file.endsWith(".json")) {
13882
- const content = await readFile3(join9(rulesDir, file), "utf-8");
13883
- await writeFile5(join9(worldPath, "rules", file), content, "utf-8");
14500
+ const content = await readFile4(join14(rulesDir, file), "utf-8");
14501
+ await writeFile6(join14(worldPath, "rules", file), content, "utf-8");
13884
14502
  restored++;
13885
14503
  }
13886
14504
  }
@@ -14031,128 +14649,6 @@ Options:
14031
14649
  }
14032
14650
  });
14033
14651
 
14034
- // src/engine/audit-logger.ts
14035
- function verdictToAuditEvent(event, verdict) {
14036
- const auditEvent = {
14037
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
14038
- worldId: verdict.evidence.worldId,
14039
- worldName: verdict.evidence.worldName,
14040
- worldVersion: verdict.evidence.worldVersion,
14041
- intent: event.intent,
14042
- tool: event.tool,
14043
- scope: event.scope,
14044
- actor: event.roleId,
14045
- direction: event.direction,
14046
- decision: verdict.status,
14047
- reason: verdict.reason,
14048
- ruleId: verdict.ruleId,
14049
- warning: verdict.warning,
14050
- guardsMatched: verdict.evidence.guardsMatched,
14051
- rulesMatched: verdict.evidence.rulesMatched,
14052
- invariantsSatisfied: verdict.evidence.invariantsSatisfied,
14053
- invariantsTotal: verdict.evidence.invariantsTotal,
14054
- enforcementLevel: verdict.evidence.enforcementLevel,
14055
- durationMs: verdict.trace?.durationMs,
14056
- args: event.args
14057
- };
14058
- if (verdict.consequence) {
14059
- auditEvent.consequence = verdict.consequence;
14060
- }
14061
- if (verdict.reward) {
14062
- auditEvent.reward = verdict.reward;
14063
- }
14064
- if (verdict.intentRecord) {
14065
- auditEvent.originalIntent = verdict.intentRecord.originalIntent;
14066
- auditEvent.finalAction = verdict.intentRecord.finalAction;
14067
- }
14068
- return auditEvent;
14069
- }
14070
- async function readAuditLog(logPath, filter) {
14071
- const { readFile: readFile3 } = await import("fs/promises");
14072
- let content;
14073
- try {
14074
- content = await readFile3(logPath, "utf-8");
14075
- } catch {
14076
- return [];
14077
- }
14078
- const events = [];
14079
- for (const line of content.split("\n")) {
14080
- const trimmed = line.trim();
14081
- if (!trimmed) continue;
14082
- try {
14083
- const event = JSON.parse(trimmed);
14084
- if (!filter || filter(event)) {
14085
- events.push(event);
14086
- }
14087
- } catch {
14088
- }
14089
- }
14090
- return events;
14091
- }
14092
- function summarizeAuditEvents(events) {
14093
- const allowed = events.filter((e) => e.decision === "ALLOW").length;
14094
- const blocked = events.filter((e) => e.decision === "BLOCK").length;
14095
- const paused = events.filter((e) => e.decision === "PAUSE").length;
14096
- const modified = events.filter((e) => e.decision === "MODIFY").length;
14097
- const penalized = events.filter((e) => e.decision === "PENALIZE").length;
14098
- const rewarded = events.filter((e) => e.decision === "REWARD").length;
14099
- const neutral = events.filter((e) => e.decision === "NEUTRAL").length;
14100
- const actorSet = /* @__PURE__ */ new Set();
14101
- for (const e of events) {
14102
- if (e.actor) actorSet.add(e.actor);
14103
- }
14104
- const intentMap = /* @__PURE__ */ new Map();
14105
- for (const e of events) {
14106
- const entry = intentMap.get(e.intent) ?? { count: 0, blocked: 0, paused: 0, penalized: 0, rewarded: 0 };
14107
- entry.count++;
14108
- if (e.decision === "BLOCK") entry.blocked++;
14109
- if (e.decision === "PAUSE") entry.paused++;
14110
- if (e.decision === "PENALIZE") entry.penalized++;
14111
- if (e.decision === "REWARD") entry.rewarded++;
14112
- intentMap.set(e.intent, entry);
14113
- }
14114
- const topIntents = [...intentMap.entries()].map(([intent, data]) => ({ intent, ...data })).sort((a, b) => b.count - a.count);
14115
- const ruleMap = /* @__PURE__ */ new Map();
14116
- for (const e of events) {
14117
- if (e.ruleId) {
14118
- ruleMap.set(e.ruleId, (ruleMap.get(e.ruleId) ?? 0) + 1);
14119
- }
14120
- for (const g of e.guardsMatched) {
14121
- ruleMap.set(g, (ruleMap.get(g) ?? 0) + 1);
14122
- }
14123
- }
14124
- const topRules = [...ruleMap.entries()].map(([ruleId, count]) => ({ ruleId, count })).sort((a, b) => b.count - a.count);
14125
- const redirected = blocked + paused + modified + penalized;
14126
- const total = events.length;
14127
- return {
14128
- totalActions: total,
14129
- allowed,
14130
- blocked,
14131
- paused,
14132
- modified,
14133
- penalized,
14134
- rewarded,
14135
- neutral,
14136
- actors: [...actorSet],
14137
- topIntents,
14138
- topRules,
14139
- firstEvent: events[0]?.timestamp ?? "",
14140
- lastEvent: events[events.length - 1]?.timestamp ?? "",
14141
- behavioralEconomy: {
14142
- totalPenalties: penalized,
14143
- totalRewards: rewarded,
14144
- netPressure: rewarded - penalized,
14145
- redirectionRate: total > 0 ? redirected / total : 0
14146
- }
14147
- };
14148
- }
14149
- var init_audit_logger = __esm({
14150
- "src/engine/audit-logger.ts"() {
14151
- "use strict";
14152
- init_guard_engine();
14153
- }
14154
- });
14155
-
14156
14652
  // src/cli/trace.ts
14157
14653
  var trace_exports = {};
14158
14654
  __export(trace_exports, {
@@ -15176,17 +15672,595 @@ var init_equity_penalties = __esm({
15176
15672
  }
15177
15673
  });
15178
15674
 
15179
- // src/cli/configure-ai.ts
15180
- var configure_ai_exports = {};
15181
- __export(configure_ai_exports, {
15675
+ // src/cli/keygen.ts
15676
+ var keygen_exports = {};
15677
+ __export(keygen_exports, {
15182
15678
  main: () => main26
15183
15679
  });
15184
15680
  function parseArgs20(argv) {
15185
- let provider;
15186
- let model;
15187
- let apiKey;
15188
- let endpoint;
15189
- let show = false;
15681
+ let output = (0, import_path8.join)((0, import_os2.homedir)(), ".neuroverse", "keys");
15682
+ let name = "neuroverse";
15683
+ let force = false;
15684
+ let help = false;
15685
+ for (let i = 0; i < argv.length; i++) {
15686
+ const arg = argv[i];
15687
+ if ((arg === "--output" || arg === "-o") && argv[i + 1]) {
15688
+ output = argv[++i];
15689
+ } else if ((arg === "--name" || arg === "-n") && argv[i + 1]) {
15690
+ name = argv[++i];
15691
+ } else if (arg === "--force") {
15692
+ force = true;
15693
+ } else if (arg === "--help" || arg === "-h") {
15694
+ help = true;
15695
+ }
15696
+ }
15697
+ return { output, name, force, help };
15698
+ }
15699
+ async function main26(argv = process.argv.slice(2)) {
15700
+ const args = parseArgs20(argv);
15701
+ if (args.help) {
15702
+ process.stdout.write(USAGE5 + "\n");
15703
+ return;
15704
+ }
15705
+ const pubPath = (0, import_path8.join)(args.output, `${args.name}.pub`);
15706
+ const keyPath = (0, import_path8.join)(args.output, `${args.name}.key`);
15707
+ if (!args.force && ((0, import_fs7.existsSync)(pubPath) || (0, import_fs7.existsSync)(keyPath))) {
15708
+ process.stderr.write(`Keys already exist at ${args.output}/${args.name}.*
15709
+ `);
15710
+ process.stderr.write("Use --force to overwrite.\n");
15711
+ process.exit(1);
15712
+ }
15713
+ const { publicKey, privateKey } = (0, import_crypto.generateKeyPairSync)("ed25519", {
15714
+ publicKeyEncoding: { type: "spki", format: "pem" },
15715
+ privateKeyEncoding: { type: "pkcs8", format: "pem" }
15716
+ });
15717
+ (0, import_fs7.mkdirSync)(args.output, { recursive: true });
15718
+ (0, import_fs7.writeFileSync)(pubPath, publicKey, "utf-8");
15719
+ (0, import_fs7.writeFileSync)(keyPath, privateKey, { encoding: "utf-8", mode: 384 });
15720
+ process.stdout.write(`Keypair generated:
15721
+ `);
15722
+ process.stdout.write(` Public: ${pubPath}
15723
+ `);
15724
+ process.stdout.write(` Private: ${keyPath}
15725
+ `);
15726
+ process.stdout.write(`
15727
+ Share the .pub file with anyone who needs to verify your worlds.
15728
+ `);
15729
+ process.stdout.write(`Keep the .key file secret.
15730
+ `);
15731
+ }
15732
+ var import_crypto, import_fs7, import_path8, import_os2, USAGE5;
15733
+ var init_keygen = __esm({
15734
+ "src/cli/keygen.ts"() {
15735
+ "use strict";
15736
+ import_crypto = require("crypto");
15737
+ import_fs7 = require("fs");
15738
+ import_path8 = require("path");
15739
+ import_os2 = require("os");
15740
+ USAGE5 = `
15741
+ neuroverse keygen \u2014 Generate Ed25519 signing keypair
15742
+
15743
+ Usage:
15744
+ neuroverse keygen [--output <dir>] [--name <name>]
15745
+
15746
+ Options:
15747
+ --output <dir> Key directory (default: ~/.neuroverse/keys/)
15748
+ --name <name> Key name (default: neuroverse)
15749
+ --force Overwrite existing keys
15750
+
15751
+ Examples:
15752
+ neuroverse keygen
15753
+ neuroverse keygen --name production --output ./keys/
15754
+ `.trim();
15755
+ }
15756
+ });
15757
+
15758
+ // src/cli/sign.ts
15759
+ var sign_exports = {};
15760
+ __export(sign_exports, {
15761
+ buildManifest: () => buildManifest,
15762
+ canonicalManifest: () => canonicalManifest,
15763
+ main: () => main27
15764
+ });
15765
+ function parseArgs21(argv) {
15766
+ let worldPath = "";
15767
+ let keyPath = (0, import_path9.join)((0, import_os3.homedir)(), ".neuroverse", "keys", "neuroverse.key");
15768
+ let help = false;
15769
+ for (let i = 0; i < argv.length; i++) {
15770
+ const arg = argv[i];
15771
+ if (arg === "--world" && argv[i + 1]) {
15772
+ worldPath = argv[++i];
15773
+ } else if (arg === "--key" && argv[i + 1]) {
15774
+ keyPath = argv[++i];
15775
+ } else if (arg === "--help" || arg === "-h") {
15776
+ help = true;
15777
+ }
15778
+ }
15779
+ return { worldPath, keyPath, help };
15780
+ }
15781
+ function collectFiles(dir, base) {
15782
+ const root = base ?? dir;
15783
+ const files = [];
15784
+ for (const entry of (0, import_fs8.readdirSync)(dir)) {
15785
+ if (entry === ".nv-signature.json") continue;
15786
+ const full = (0, import_path9.join)(dir, entry);
15787
+ const stat = (0, import_fs8.statSync)(full);
15788
+ if (stat.isDirectory()) {
15789
+ files.push(...collectFiles(full, root));
15790
+ } else {
15791
+ files.push((0, import_path9.relative)(root, full));
15792
+ }
15793
+ }
15794
+ return files.sort();
15795
+ }
15796
+ function buildManifest(worldPath) {
15797
+ const files = collectFiles(worldPath);
15798
+ const manifest = {};
15799
+ for (const file of files) {
15800
+ const content = (0, import_fs8.readFileSync)((0, import_path9.join)(worldPath, file));
15801
+ manifest[file] = (0, import_crypto2.createHash)("sha256").update(content).digest("hex");
15802
+ }
15803
+ return manifest;
15804
+ }
15805
+ function canonicalManifest(files) {
15806
+ const sorted = Object.keys(files).sort();
15807
+ return sorted.map((k) => `${k}:${files[k]}`).join("\n");
15808
+ }
15809
+ async function main27(argv = process.argv.slice(2)) {
15810
+ const args = parseArgs21(argv);
15811
+ if (args.help) {
15812
+ process.stdout.write(USAGE6 + "\n");
15813
+ return;
15814
+ }
15815
+ if (!args.worldPath) {
15816
+ process.stderr.write("Error: --world <dir> is required.\n");
15817
+ process.exit(1);
15818
+ }
15819
+ let privateKey;
15820
+ try {
15821
+ privateKey = (0, import_fs8.readFileSync)(args.keyPath, "utf-8");
15822
+ } catch {
15823
+ process.stderr.write(`Error: Cannot read private key at ${args.keyPath}
15824
+ `);
15825
+ process.stderr.write('Run "neuroverse keygen" to generate a keypair.\n');
15826
+ process.exit(1);
15827
+ return;
15828
+ }
15829
+ const files = buildManifest(args.worldPath);
15830
+ const canonical = canonicalManifest(files);
15831
+ const manifestHash = (0, import_crypto2.createHash)("sha256").update(canonical).digest("hex");
15832
+ const signature = (0, import_crypto2.sign)(null, Buffer.from(manifestHash), privateKey).toString("base64");
15833
+ const artifact = {
15834
+ signatureVersion: "1.0",
15835
+ signedAt: (/* @__PURE__ */ new Date()).toISOString(),
15836
+ files,
15837
+ manifestHash,
15838
+ signature
15839
+ };
15840
+ const outPath = (0, import_path9.join)(args.worldPath, ".nv-signature.json");
15841
+ (0, import_fs8.writeFileSync)(outPath, JSON.stringify(artifact, null, 2) + "\n", "utf-8");
15842
+ process.stdout.write(`Signed ${Object.keys(files).length} files in ${args.worldPath}
15843
+ `);
15844
+ process.stdout.write(`Signature: ${outPath}
15845
+ `);
15846
+ }
15847
+ var import_crypto2, import_fs8, import_path9, import_os3, USAGE6;
15848
+ var init_sign = __esm({
15849
+ "src/cli/sign.ts"() {
15850
+ "use strict";
15851
+ import_crypto2 = require("crypto");
15852
+ import_fs8 = require("fs");
15853
+ import_path9 = require("path");
15854
+ import_os3 = require("os");
15855
+ USAGE6 = `
15856
+ neuroverse sign \u2014 Sign a world artifact
15857
+
15858
+ Usage:
15859
+ neuroverse sign --world <dir> [--key <path>]
15860
+
15861
+ Options:
15862
+ --world <dir> World directory to sign (required)
15863
+ --key <path> Private key path (default: ~/.neuroverse/keys/neuroverse.key)
15864
+
15865
+ Examples:
15866
+ neuroverse sign --world ./world/
15867
+ neuroverse sign --world ./world/ --key ./keys/production.key
15868
+ `.trim();
15869
+ }
15870
+ });
15871
+
15872
+ // src/cli/verify.ts
15873
+ var verify_exports = {};
15874
+ __export(verify_exports, {
15875
+ main: () => main28
15876
+ });
15877
+ function parseArgs22(argv) {
15878
+ let worldPath = "";
15879
+ let keyPath = (0, import_path10.join)((0, import_os4.homedir)(), ".neuroverse", "keys", "neuroverse.pub");
15880
+ let json = false;
15881
+ let help = false;
15882
+ for (let i = 0; i < argv.length; i++) {
15883
+ const arg = argv[i];
15884
+ if (arg === "--world" && argv[i + 1]) {
15885
+ worldPath = argv[++i];
15886
+ } else if (arg === "--key" && argv[i + 1]) {
15887
+ keyPath = argv[++i];
15888
+ } else if (arg === "--json") {
15889
+ json = true;
15890
+ } else if (arg === "--help" || arg === "-h") {
15891
+ help = true;
15892
+ }
15893
+ }
15894
+ return { worldPath, keyPath, json, help };
15895
+ }
15896
+ async function main28(argv = process.argv.slice(2)) {
15897
+ const args = parseArgs22(argv);
15898
+ if (args.help) {
15899
+ process.stdout.write(USAGE7 + "\n");
15900
+ return;
15901
+ }
15902
+ if (!args.worldPath) {
15903
+ process.stderr.write("Error: --world <dir> is required.\n");
15904
+ process.exit(1);
15905
+ }
15906
+ const result = {
15907
+ valid: false,
15908
+ worldPath: args.worldPath,
15909
+ fileCount: 0,
15910
+ errors: []
15911
+ };
15912
+ const sigPath = (0, import_path10.join)(args.worldPath, ".nv-signature.json");
15913
+ if (!(0, import_fs9.existsSync)(sigPath)) {
15914
+ result.errors.push("No .nv-signature.json found \u2014 world is unsigned.");
15915
+ outputResult(result, args.json);
15916
+ process.exit(1);
15917
+ }
15918
+ let artifact;
15919
+ try {
15920
+ artifact = JSON.parse((0, import_fs9.readFileSync)(sigPath, "utf-8"));
15921
+ } catch {
15922
+ result.errors.push("Cannot parse .nv-signature.json \u2014 file is corrupt.");
15923
+ outputResult(result, args.json);
15924
+ process.exit(1);
15925
+ return;
15926
+ }
15927
+ result.signedAt = artifact.signedAt;
15928
+ result.fileCount = Object.keys(artifact.files).length;
15929
+ let publicKey;
15930
+ try {
15931
+ publicKey = (0, import_fs9.readFileSync)(args.keyPath, "utf-8");
15932
+ } catch {
15933
+ result.errors.push(`Cannot read public key at ${args.keyPath}`);
15934
+ outputResult(result, args.json);
15935
+ process.exit(1);
15936
+ return;
15937
+ }
15938
+ const currentFiles = buildManifest(args.worldPath);
15939
+ for (const file of Object.keys(currentFiles)) {
15940
+ if (!(file in artifact.files)) {
15941
+ result.errors.push(`Added: ${file} (not in signature)`);
15942
+ }
15943
+ }
15944
+ for (const [file, hash] of Object.entries(artifact.files)) {
15945
+ if (!(file in currentFiles)) {
15946
+ result.errors.push(`Missing: ${file} (was in signature)`);
15947
+ } else if (currentFiles[file] !== hash) {
15948
+ result.errors.push(`Changed: ${file} (hash mismatch)`);
15949
+ }
15950
+ }
15951
+ if (result.errors.length > 0) {
15952
+ outputResult(result, args.json);
15953
+ process.exit(1);
15954
+ return;
15955
+ }
15956
+ const canonical = canonicalManifest(artifact.files);
15957
+ const manifestHash = (0, import_crypto3.createHash)("sha256").update(canonical).digest("hex");
15958
+ if (manifestHash !== artifact.manifestHash) {
15959
+ result.errors.push("Manifest hash mismatch \u2014 signature metadata is corrupt.");
15960
+ outputResult(result, args.json);
15961
+ process.exit(1);
15962
+ return;
15963
+ }
15964
+ const isValid = (0, import_crypto3.verify)(null, Buffer.from(manifestHash), publicKey, Buffer.from(artifact.signature, "base64"));
15965
+ if (!isValid) {
15966
+ result.errors.push("Signature verification failed \u2014 wrong key or tampered manifest.");
15967
+ outputResult(result, args.json);
15968
+ process.exit(1);
15969
+ return;
15970
+ }
15971
+ result.valid = true;
15972
+ outputResult(result, args.json);
15973
+ }
15974
+ function outputResult(result, json) {
15975
+ if (json) {
15976
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
15977
+ return;
15978
+ }
15979
+ if (result.valid) {
15980
+ process.stdout.write(`VALID \u2014 ${result.fileCount} files verified
15981
+ `);
15982
+ process.stdout.write(` Signed at: ${result.signedAt}
15983
+ `);
15984
+ process.stdout.write(` World: ${result.worldPath}
15985
+ `);
15986
+ } else {
15987
+ process.stdout.write(`INVALID \u2014 signature verification failed
15988
+ `);
15989
+ for (const error of result.errors) {
15990
+ process.stdout.write(` ${error}
15991
+ `);
15992
+ }
15993
+ }
15994
+ }
15995
+ var import_crypto3, import_fs9, import_path10, import_os4, USAGE7;
15996
+ var init_verify = __esm({
15997
+ "src/cli/verify.ts"() {
15998
+ "use strict";
15999
+ import_crypto3 = require("crypto");
16000
+ import_fs9 = require("fs");
16001
+ import_path10 = require("path");
16002
+ import_os4 = require("os");
16003
+ init_sign();
16004
+ USAGE7 = `
16005
+ neuroverse verify \u2014 Verify a signed world artifact
16006
+
16007
+ Usage:
16008
+ neuroverse verify --world <dir> [--key <path>]
16009
+
16010
+ Options:
16011
+ --world <dir> World directory to verify (required)
16012
+ --key <path> Public key path (default: ~/.neuroverse/keys/neuroverse.pub)
16013
+ --json Output result as JSON
16014
+
16015
+ Exit codes:
16016
+ 0 Valid \u2014 world matches signature
16017
+ 1 Invalid \u2014 signature mismatch, tampered files, or missing signature
16018
+
16019
+ Examples:
16020
+ neuroverse verify --world ./world/
16021
+ neuroverse verify --world ./world/ --key ./keys/production.pub
16022
+ `.trim();
16023
+ }
16024
+ });
16025
+
16026
+ // src/cli/migrate.ts
16027
+ var migrate_exports = {};
16028
+ __export(migrate_exports, {
16029
+ LATEST_VERSION: () => LATEST_VERSION,
16030
+ main: () => main29
16031
+ });
16032
+ function detectVersion(worldPath) {
16033
+ const metaPath = (0, import_path11.join)(worldPath, "metadata.json");
16034
+ if ((0, import_fs10.existsSync)(metaPath)) {
16035
+ try {
16036
+ const meta = JSON.parse((0, import_fs10.readFileSync)(metaPath, "utf-8"));
16037
+ if (meta.schema_version) return meta.schema_version;
16038
+ } catch {
16039
+ }
16040
+ }
16041
+ return "1.0.0";
16042
+ }
16043
+ function compareVersions(a, b) {
16044
+ const pa = a.split(".").map(Number);
16045
+ const pb = b.split(".").map(Number);
16046
+ for (let i = 0; i < 3; i++) {
16047
+ if ((pa[i] ?? 0) < (pb[i] ?? 0)) return -1;
16048
+ if ((pa[i] ?? 0) > (pb[i] ?? 0)) return 1;
16049
+ }
16050
+ return 0;
16051
+ }
16052
+ function findMigrationPath(from, to) {
16053
+ const path = [];
16054
+ let current = from;
16055
+ while (compareVersions(current, to) < 0) {
16056
+ const next = MIGRATIONS.find((m) => m.from === current);
16057
+ if (!next) break;
16058
+ path.push(next);
16059
+ current = next.to;
16060
+ }
16061
+ return path;
16062
+ }
16063
+ function parseArgs23(argv) {
16064
+ let worldPath = "";
16065
+ let dryRun = false;
16066
+ let backup = false;
16067
+ let target = LATEST_VERSION;
16068
+ let json = false;
16069
+ let help = false;
16070
+ for (let i = 0; i < argv.length; i++) {
16071
+ const arg = argv[i];
16072
+ if (arg === "--world" && argv[i + 1]) {
16073
+ worldPath = argv[++i];
16074
+ } else if (arg === "--dry-run") {
16075
+ dryRun = true;
16076
+ } else if (arg === "--backup") {
16077
+ backup = true;
16078
+ } else if (arg === "--target" && argv[i + 1]) {
16079
+ target = argv[++i];
16080
+ } else if (arg === "--json") {
16081
+ json = true;
16082
+ } else if (arg === "--help" || arg === "-h") {
16083
+ help = true;
16084
+ }
16085
+ }
16086
+ return { worldPath, dryRun, backup, target, json, help };
16087
+ }
16088
+ async function main29(argv = process.argv.slice(2)) {
16089
+ const args = parseArgs23(argv);
16090
+ if (args.help) {
16091
+ process.stdout.write(USAGE8 + "\n");
16092
+ return;
16093
+ }
16094
+ if (!args.worldPath) {
16095
+ process.stderr.write("Error: --world <dir> is required.\n");
16096
+ process.exit(1);
16097
+ }
16098
+ const currentVersion = detectVersion(args.worldPath);
16099
+ const targetVersion = args.target;
16100
+ if (compareVersions(currentVersion, targetVersion) >= 0) {
16101
+ const plan2 = {
16102
+ currentVersion,
16103
+ targetVersion,
16104
+ migrations: [],
16105
+ changes: []
16106
+ };
16107
+ if (args.json) {
16108
+ process.stdout.write(JSON.stringify(plan2, null, 2) + "\n");
16109
+ } else {
16110
+ process.stdout.write(`World is already at version ${currentVersion} (target: ${targetVersion})
16111
+ `);
16112
+ process.stdout.write("No migrations needed.\n");
16113
+ }
16114
+ return;
16115
+ }
16116
+ const migrationPath = findMigrationPath(currentVersion, targetVersion);
16117
+ if (migrationPath.length === 0) {
16118
+ process.stderr.write(`No migration path from ${currentVersion} to ${targetVersion}
16119
+ `);
16120
+ process.exit(1);
16121
+ return;
16122
+ }
16123
+ if (args.dryRun) {
16124
+ const plan2 = {
16125
+ currentVersion,
16126
+ targetVersion,
16127
+ migrations: migrationPath.map((m) => ({ from: m.from, to: m.to, description: m.description })),
16128
+ changes: []
16129
+ };
16130
+ if (args.json) {
16131
+ process.stdout.write(JSON.stringify(plan2, null, 2) + "\n");
16132
+ } else {
16133
+ process.stdout.write(`Migration plan: ${currentVersion} \u2192 ${targetVersion}
16134
+ `);
16135
+ process.stdout.write(`Steps: ${migrationPath.length}
16136
+
16137
+ `);
16138
+ for (const m of migrationPath) {
16139
+ process.stdout.write(` ${m.from} \u2192 ${m.to}: ${m.description}
16140
+ `);
16141
+ }
16142
+ process.stdout.write("\nRun without --dry-run to apply.\n");
16143
+ }
16144
+ return;
16145
+ }
16146
+ if (args.backup) {
16147
+ const backupPath = args.worldPath + ".backup";
16148
+ (0, import_fs10.cpSync)(args.worldPath, backupPath, { recursive: true });
16149
+ process.stdout.write(`Backup created: ${backupPath}
16150
+ `);
16151
+ }
16152
+ const allChanges = [];
16153
+ for (const migration of migrationPath) {
16154
+ process.stdout.write(`Applying: ${migration.from} \u2192 ${migration.to} (${migration.description})
16155
+ `);
16156
+ const changes = migration.apply(args.worldPath);
16157
+ allChanges.push(...changes);
16158
+ for (const change of changes) {
16159
+ process.stdout.write(` ${change.action}: ${change.file} \u2014 ${change.description}
16160
+ `);
16161
+ }
16162
+ }
16163
+ const plan = {
16164
+ currentVersion,
16165
+ targetVersion,
16166
+ migrations: migrationPath.map((m) => ({ from: m.from, to: m.to, description: m.description })),
16167
+ changes: allChanges
16168
+ };
16169
+ if (args.json) {
16170
+ process.stdout.write(JSON.stringify(plan, null, 2) + "\n");
16171
+ }
16172
+ process.stdout.write(`
16173
+ Migration complete: ${currentVersion} \u2192 ${targetVersion} (${allChanges.length} changes)
16174
+ `);
16175
+ }
16176
+ var import_fs10, import_path11, USAGE8, MIGRATIONS, LATEST_VERSION;
16177
+ var init_migrate = __esm({
16178
+ "src/cli/migrate.ts"() {
16179
+ "use strict";
16180
+ import_fs10 = require("fs");
16181
+ import_path11 = require("path");
16182
+ USAGE8 = `
16183
+ neuroverse migrate \u2014 World schema version migration
16184
+
16185
+ Usage:
16186
+ neuroverse migrate --world <dir> [options]
16187
+
16188
+ Options:
16189
+ --world <dir> World directory to migrate (required)
16190
+ --dry-run Show what would change without modifying files
16191
+ --backup Copy original world to <dir>.backup before migrating
16192
+ --target <version> Target schema version (default: latest)
16193
+ --json Output migration plan as JSON
16194
+
16195
+ Examples:
16196
+ neuroverse migrate --world ./world/ --dry-run
16197
+ neuroverse migrate --world ./world/ --backup
16198
+ neuroverse migrate --world ./world/ --target 1.1.0
16199
+ `.trim();
16200
+ MIGRATIONS = [
16201
+ {
16202
+ from: "1.0.0",
16203
+ to: "1.1.0",
16204
+ description: "Add enforcement_level to world.json, normalize metadata fields",
16205
+ apply: (worldPath) => {
16206
+ const changes = [];
16207
+ const worldJsonPath = (0, import_path11.join)(worldPath, "world.json");
16208
+ if ((0, import_fs10.existsSync)(worldJsonPath)) {
16209
+ const world = JSON.parse((0, import_fs10.readFileSync)(worldJsonPath, "utf-8"));
16210
+ if (!world.enforcement_level) {
16211
+ world.enforcement_level = "standard";
16212
+ (0, import_fs10.writeFileSync)(worldJsonPath, JSON.stringify(world, null, 2) + "\n", "utf-8");
16213
+ changes.push({
16214
+ file: "world.json",
16215
+ action: "modified",
16216
+ description: 'Added enforcement_level: "standard"'
16217
+ });
16218
+ }
16219
+ }
16220
+ const metaPath = (0, import_path11.join)(worldPath, "metadata.json");
16221
+ if ((0, import_fs10.existsSync)(metaPath)) {
16222
+ const meta = JSON.parse((0, import_fs10.readFileSync)(metaPath, "utf-8"));
16223
+ let modified = false;
16224
+ if (meta.configurator_version && !meta.authoring_method) {
16225
+ meta.authoring_method = meta.configurator_version;
16226
+ delete meta.configurator_version;
16227
+ modified = true;
16228
+ }
16229
+ if (!meta.schema_version) {
16230
+ meta.schema_version = "1.1.0";
16231
+ modified = true;
16232
+ } else {
16233
+ meta.schema_version = "1.1.0";
16234
+ modified = true;
16235
+ }
16236
+ if (modified) {
16237
+ (0, import_fs10.writeFileSync)(metaPath, JSON.stringify(meta, null, 2) + "\n", "utf-8");
16238
+ changes.push({
16239
+ file: "metadata.json",
16240
+ action: "modified",
16241
+ description: "Normalized metadata fields, updated schema_version to 1.1.0"
16242
+ });
16243
+ }
16244
+ }
16245
+ return changes;
16246
+ }
16247
+ }
16248
+ ];
16249
+ LATEST_VERSION = MIGRATIONS.length > 0 ? MIGRATIONS[MIGRATIONS.length - 1].to : "1.0.0";
16250
+ }
16251
+ });
16252
+
16253
+ // src/cli/configure-ai.ts
16254
+ var configure_ai_exports = {};
16255
+ __export(configure_ai_exports, {
16256
+ main: () => main30
16257
+ });
16258
+ function parseArgs24(argv) {
16259
+ let provider;
16260
+ let model;
16261
+ let apiKey;
16262
+ let endpoint;
16263
+ let show = false;
15190
16264
  let test = false;
15191
16265
  for (let i = 0; i < argv.length; i++) {
15192
16266
  const arg = argv[i];
@@ -15206,9 +16280,9 @@ function parseArgs20(argv) {
15206
16280
  }
15207
16281
  return { provider, model, apiKey, endpoint, show, test };
15208
16282
  }
15209
- async function main26(argv = process.argv.slice(2)) {
16283
+ async function main30(argv = process.argv.slice(2)) {
15210
16284
  try {
15211
- const args = parseArgs20(argv);
16285
+ const args = parseArgs24(argv);
15212
16286
  if (args.show) {
15213
16287
  const config2 = await loadConfig();
15214
16288
  if (!config2) {
@@ -15326,27 +16400,27 @@ function closePrompts() {
15326
16400
  }
15327
16401
  function ask(question, defaultValue) {
15328
16402
  const suffix = defaultValue ? ` [${defaultValue}]` : "";
15329
- return new Promise((resolve5) => {
16403
+ return new Promise((resolve6) => {
15330
16404
  getRL().question(`
15331
16405
  ${question}${suffix}: `, (answer) => {
15332
16406
  const val = answer.trim();
15333
- resolve5(val || defaultValue || "");
16407
+ resolve6(val || defaultValue || "");
15334
16408
  });
15335
16409
  });
15336
16410
  }
15337
16411
  function confirm(question, defaultYes = true) {
15338
16412
  const hint = defaultYes ? "[Y/n]" : "[y/N]";
15339
- return new Promise((resolve5) => {
16413
+ return new Promise((resolve6) => {
15340
16414
  getRL().question(`
15341
16415
  ${question} ${hint}: `, (answer) => {
15342
16416
  const val = answer.trim().toLowerCase();
15343
- if (val === "") resolve5(defaultYes);
15344
- else resolve5(val === "y" || val === "yes");
16417
+ if (val === "") resolve6(defaultYes);
16418
+ else resolve6(val === "y" || val === "yes");
15345
16419
  });
15346
16420
  });
15347
16421
  }
15348
16422
  function choose(question, options) {
15349
- return new Promise((resolve5) => {
16423
+ return new Promise((resolve6) => {
15350
16424
  const r = getRL();
15351
16425
  r.write(`
15352
16426
  ${question}
@@ -15356,9 +16430,9 @@ function choose(question, options) {
15356
16430
  r.question(` Choice [1-${options.length}]: `, (answer) => {
15357
16431
  const idx = parseInt(answer.trim(), 10) - 1;
15358
16432
  if (idx >= 0 && idx < options.length) {
15359
- resolve5(options[idx]);
16433
+ resolve6(options[idx]);
15360
16434
  } else {
15361
- resolve5(options[0]);
16435
+ resolve6(options[0]);
15362
16436
  }
15363
16437
  });
15364
16438
  });
@@ -15409,7 +16483,7 @@ var init_prompt_utils = __esm({
15409
16483
  // src/cli/configure-world.ts
15410
16484
  var configure_world_exports = {};
15411
16485
  __export(configure_world_exports, {
15412
- main: () => main27
16486
+ main: () => main31
15413
16487
  });
15414
16488
  function metricToStateVariable(metric) {
15415
16489
  const id = metric.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
@@ -15827,16 +16901,16 @@ function generateWorld(state) {
15827
16901
  return { worldJson, stateSchema, guardsJson, rules, gatesJson, invariants, outcomes, metadata };
15828
16902
  }
15829
16903
  async function writeWorld(outputDir, world) {
15830
- const { mkdirSync: mkdirSync3, existsSync: existsSync6 } = await import("fs");
15831
- const { writeFile: writeFile5 } = await import("fs/promises");
15832
- const { join: join9 } = await import("path");
16904
+ const { mkdirSync: mkdirSync5, existsSync: existsSync10 } = await import("fs");
16905
+ const { writeFile: writeFile6 } = await import("fs/promises");
16906
+ const { join: join14 } = await import("path");
15833
16907
  const files = [];
15834
- if (!existsSync6(outputDir)) mkdirSync3(outputDir, { recursive: true });
15835
- const rulesDir = join9(outputDir, "rules");
15836
- if (!existsSync6(rulesDir)) mkdirSync3(rulesDir, { recursive: true });
16908
+ if (!existsSync10(outputDir)) mkdirSync5(outputDir, { recursive: true });
16909
+ const rulesDir = join14(outputDir, "rules");
16910
+ if (!existsSync10(rulesDir)) mkdirSync5(rulesDir, { recursive: true });
15837
16911
  const writeJson = async (name, data) => {
15838
- const path = join9(outputDir, name);
15839
- await writeFile5(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
16912
+ const path = join14(outputDir, name);
16913
+ await writeFile6(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
15840
16914
  files.push(path);
15841
16915
  };
15842
16916
  await writeJson("world.json", world.worldJson);
@@ -15847,13 +16921,13 @@ async function writeWorld(outputDir, world) {
15847
16921
  await writeJson("outcomes.json", world.outcomes);
15848
16922
  await writeJson("metadata.json", world.metadata);
15849
16923
  for (const rule of world.rules) {
15850
- const rulePath = join9(rulesDir, `${rule.id}.json`);
15851
- await writeFile5(rulePath, JSON.stringify(rule, null, 2) + "\n", "utf-8");
16924
+ const rulePath = join14(rulesDir, `${rule.id}.json`);
16925
+ await writeFile6(rulePath, JSON.stringify(rule, null, 2) + "\n", "utf-8");
15852
16926
  files.push(rulePath);
15853
16927
  }
15854
16928
  return files;
15855
16929
  }
15856
- function parseArgs21(argv) {
16930
+ function parseArgs25(argv) {
15857
16931
  let outputDir = "./world/";
15858
16932
  for (let i = 0; i < argv.length; i++) {
15859
16933
  const arg = argv[i];
@@ -15863,9 +16937,9 @@ function parseArgs21(argv) {
15863
16937
  }
15864
16938
  return { outputDir };
15865
16939
  }
15866
- async function main27(argv = process.argv.slice(2)) {
16940
+ async function main31(argv = process.argv.slice(2)) {
15867
16941
  try {
15868
- const args = parseArgs21(argv);
16942
+ const args = parseArgs25(argv);
15869
16943
  const context = await phaseContext();
15870
16944
  const guardState = await phaseGuard(context.domain);
15871
16945
  const systemState = await phaseSystem(context.domain);
@@ -15933,8 +17007,8 @@ async function main27(argv = process.argv.slice(2)) {
15933
17007
  }
15934
17008
  }
15935
17009
  async function phaseRefine(outputDir, world) {
15936
- const { writeFile: writeFile5 } = await import("fs/promises");
15937
- const { join: join9 } = await import("path");
17010
+ const { writeFile: writeFile6 } = await import("fs/promises");
17011
+ const { join: join14 } = await import("path");
15938
17012
  heading("Refinement: Thresholds & Collapse");
15939
17013
  const primaryMetric = world.gatesJson.viability_classification[0]?.field || "system_health";
15940
17014
  info(`
@@ -15950,8 +17024,8 @@ async function phaseRefine(outputDir, world) {
15950
17024
  const parsed = parseInt(newVal, 10);
15951
17025
  if (!isNaN(parsed)) gate.value = parsed;
15952
17026
  }
15953
- await writeFile5(
15954
- join9(outputDir, "gates.json"),
17027
+ await writeFile6(
17028
+ join14(outputDir, "gates.json"),
15955
17029
  JSON.stringify(world.gatesJson, null, 2) + "\n",
15956
17030
  "utf-8"
15957
17031
  );
@@ -15972,8 +17046,8 @@ async function phaseRefine(outputDir, world) {
15972
17046
  value: parsed,
15973
17047
  result: "MODEL_COLLAPSES"
15974
17048
  };
15975
- await writeFile5(
15976
- join9(outputDir, "rules", `${rule.id}.json`),
17049
+ await writeFile6(
17050
+ join14(outputDir, "rules", `${rule.id}.json`),
15977
17051
  JSON.stringify(rule, null, 2) + "\n",
15978
17052
  "utf-8"
15979
17053
  );
@@ -16077,22 +17151,22 @@ ${parts.join(". ")}.
16077
17151
  `;
16078
17152
  }
16079
17153
  function previewLens(lens) {
16080
- const BOLD2 = "\x1B[1m";
16081
- const DIM2 = "\x1B[2m";
16082
- const CYAN2 = "\x1B[36m";
16083
- const YELLOW2 = "\x1B[33m";
16084
- const GREEN2 = "\x1B[32m";
16085
- const RESET2 = "\x1B[0m";
17154
+ const BOLD3 = "\x1B[1m";
17155
+ const DIM3 = "\x1B[2m";
17156
+ const CYAN3 = "\x1B[36m";
17157
+ const YELLOW3 = "\x1B[33m";
17158
+ const GREEN3 = "\x1B[32m";
17159
+ const RESET3 = "\x1B[0m";
16086
17160
  const lines = [];
16087
17161
  lines.push("");
16088
- lines.push(`${BOLD2}${CYAN2} ${lens.name}${RESET2} ${DIM2}\u2014 ${lens.tagline}${RESET2}`);
16089
- lines.push(`${DIM2} ${lens.description}${RESET2}`);
17162
+ lines.push(`${BOLD3}${CYAN3} ${lens.name}${RESET3} ${DIM3}\u2014 ${lens.tagline}${RESET3}`);
17163
+ lines.push(`${DIM3} ${lens.description}${RESET3}`);
16090
17164
  lines.push("");
16091
17165
  for (const d of lens.directives) {
16092
17166
  if (d.example) {
16093
- lines.push(` ${BOLD2}${d.id}${RESET2}`);
16094
- lines.push(` ${YELLOW2}Without:${RESET2} ${DIM2}${d.example.without}${RESET2}`);
16095
- lines.push(` ${GREEN2}With:${RESET2} ${d.example.with}`);
17167
+ lines.push(` ${BOLD3}${d.id}${RESET3}`);
17168
+ lines.push(` ${YELLOW3}Without:${RESET3} ${DIM3}${d.example.without}${RESET3}`);
17169
+ lines.push(` ${GREEN3}With:${RESET3} ${d.example.with}`);
16096
17170
  lines.push("");
16097
17171
  }
16098
17172
  }
@@ -16139,7 +17213,7 @@ function lensForRole(world, roleId, roleLensOverride) {
16139
17213
  if (byRole) return byRole;
16140
17214
  return lenses[0];
16141
17215
  }
16142
- var STOIC_LENS, CLOSER_LENS, SAMURAI_LENS, HYPE_MAN_LENS, MONK_LENS, SOCRATIC_LENS, MINIMALIST_LENS, COACH_LENS, CALM_LENS, BUILTIN_LENSES;
17216
+ var STOIC_LENS, CLOSER_LENS, SAMURAI_LENS, HYPE_MAN_LENS, MONK_LENS, SOCRATIC_LENS, MINIMALIST_LENS, LIFE_COACH_LENS, NFL_COACH_LENS, CALM_LENS, BEHAVIORAL_INTERPRETER_LENS, BUILTIN_LENSES;
16143
17217
  var init_lens = __esm({
16144
17218
  "src/builder/lens.ts"() {
16145
17219
  "use strict";
@@ -16512,14 +17586,14 @@ var init_lens = __esm({
16512
17586
  }
16513
17587
  ]
16514
17588
  };
16515
- COACH_LENS = {
16516
- id: "coach",
16517
- name: "Coach",
16518
- tagline: "You said this mattered. What's the next step?",
17589
+ LIFE_COACH_LENS = {
17590
+ id: "life-coach",
17591
+ name: "Life Coach",
17592
+ tagline: "What's really going on for you right now?",
16519
17593
  author: "NeuroverseOS",
16520
- version: "1.0.0",
16521
- description: "For when you need accountability, not sympathy. The AI holds you to your own standards. It doesn't let you off the hook, but it doesn't shame you either. It reminds you what you committed to and asks for the smallest next step.",
16522
- tags: ["motivation", "accountability", "discipline", "growth"],
17594
+ version: "2.0.0",
17595
+ description: "ICF-aligned professional coaching. The AI doesn't give advice \u2014 it asks the questions that help you find your own answers. Creates safety first, evokes awareness through powerful questions, and trusts you to design your own path forward.",
17596
+ tags: ["coaching", "icf", "awareness", "growth", "autonomy", "presence"],
16523
17597
  stackable: true,
16524
17598
  priority: 50,
16525
17599
  appliesTo: "all",
@@ -16527,45 +17601,111 @@ var init_lens = __esm({
16527
17601
  formality: "casual",
16528
17602
  verbosity: "concise",
16529
17603
  emotion: "warm",
16530
- confidence: "authoritative"
17604
+ confidence: "balanced"
16531
17605
  },
16532
17606
  directives: [
16533
17607
  {
16534
- id: "hold_the_standard",
17608
+ id: "evoke_dont_advise",
16535
17609
  scope: "behavior_shaping",
16536
- instruction: `When the user expresses reluctance, avoidance, or excuse-making about something they previously identified as important, do not sympathize with the avoidance. Acknowledge the difficulty briefly, then redirect to action. "I know it's hard" is fine once. Dwelling on why it's hard is not.`,
17610
+ instruction: 'Never give advice, solutions, or tell the user what to do. Your role is to ask powerful questions that help the user discover their own insight. If you feel the urge to suggest an action, convert it into a question. "Have you considered X?" is still advising. "What options do you see?" is coaching. The user is resourceful and capable \u2014 trust that. (ICF Competency 7: Evokes Awareness)',
16537
17611
  example: {
16538
- without: "I totally get it, sometimes we just don't feel like working out. It's okay to take a break. Listen to your body!",
16539
- with: "Tough day. You committed to 3x a week. What's the smallest version you'd still respect yourself for doing?"
17612
+ without: "You should try waking up earlier. Set an alarm for 6am and put your phone across the room.",
17613
+ with: "What would your morning look like if it actually worked for you?"
16540
17614
  }
16541
17615
  },
16542
17616
  {
16543
- id: "smallest_next_step",
17617
+ id: "listen_for_whats_unsaid",
16544
17618
  scope: "response_framing",
16545
- instruction: 'Always reduce big tasks to the immediate next action. Not the whole plan. Not the end goal. Just the next step. "What can you do in the next 10 minutes?" is the core question.',
17619
+ instruction: `Pay attention to what the user is NOT saying as much as what they are saying. Notice gaps, contradictions, energy shifts, and recurring themes. Reflect these back as observations, not judgments. "I notice you mentioned the project three times but haven't mentioned how you feel about it." Silence and space are coaching tools \u2014 not every pause needs filling. (ICF Competency 6: Listens Actively)`,
16546
17620
  example: {
16547
- without: "To write your book, you should first create an outline, then develop character profiles, then write a first draft of chapter 1, then...",
16548
- with: "Open a blank doc and write one sentence. Any sentence. That's today."
17621
+ without: "Okay so you want to change jobs. Let's figure out your next steps.",
17622
+ with: "You've told me a lot about what you'd leave behind. What is it you'd be moving toward?"
16549
17623
  }
16550
17624
  },
16551
17625
  {
16552
- id: "no_empty_praise",
17626
+ id: "safety_before_challenge",
16553
17627
  scope: "behavior_shaping",
16554
- instruction: `Do not give praise unless the user actually did something. "Great job thinking about it!" is empty. "You finished the draft \u2014 that's done" is real. Praise effort and completion, not intention.`
17628
+ instruction: "Create a safe, supportive space before exploring difficult territory. Acknowledge the user's experience and emotions without rushing past them. Trust is built before insight is possible. Never shame, guilt, or pressure. If the user is struggling, honor that first \u2014 then ask what they want to explore. (ICF Competency 4: Cultivates Trust and Safety)",
17629
+ example: {
17630
+ without: "You keep saying you're stressed but you're not doing anything about it. What's one thing you can change today?",
17631
+ with: "That sounds like a lot to carry. What feels most important to you to explore right now?"
17632
+ }
17633
+ },
17634
+ {
17635
+ id: "client_designs_the_action",
17636
+ scope: "response_framing",
17637
+ instruction: `When the user is ready to move to action, let THEM design it. Ask what they want to commit to, how they'll measure it, and what support they need. Do not prescribe the action, the timeline, or the accountability method. "What will you do?" not "Here's what you should do." Acknowledge their progress without inflating it. (ICF Competency 8: Facilitates Client Growth)`,
17638
+ example: {
17639
+ without: "Great, so your next step is to send that email by Friday. I'll check in with you then.",
17640
+ with: "What feels like the right next step for you? And how will you know you've done it?"
17641
+ }
16555
17642
  },
16556
17643
  {
16557
- id: "reflect_their_words_back",
17644
+ id: "reflect_and_deepen",
16558
17645
  scope: "response_framing",
16559
- instruction: 'When the user is wavering, reference their own stated goals and values. "Last week you said X mattered to you. Does that still hold?" Let their own words do the motivating, not yours.'
17646
+ instruction: `Reflect the user's own words back to them to deepen awareness. Use their language, not yours. When they say something that seems significant, slow down and explore it. "You said 'trapped.' What does that word mean for you here?" Help them hear themselves. (ICF Competency 5: Maintains Presence + Competency 6: Listens Actively)`
16560
17647
  },
16561
17648
  {
16562
- id: "forward_only",
17649
+ id: "partner_not_expert",
17650
+ scope: "behavior_shaping",
17651
+ instruction: "You are a thinking partner, not an authority. The user sets the agenda. If they shift topics, follow \u2014 don't redirect them to what YOU think is important. If they resist exploring something, respect that boundary. Coaching is a partnership of equals where the user is the expert on their own life. (ICF Competency 3: Establishes and Maintains Agreements)"
17652
+ }
17653
+ ]
17654
+ };
17655
+ NFL_COACH_LENS = {
17656
+ id: "nfl-coach",
17657
+ name: "NFL Coach",
17658
+ tagline: "We don't have time for excuses. Execute.",
17659
+ author: "NeuroverseOS",
17660
+ version: "1.0.0",
17661
+ description: "Game-day intensity. Holds you accountable like a championship is on the line. Direct, blunt, no-nonsense. Respects effort, demands execution. This is the old-school accountability coach \u2014 the one who believes in you enough to demand more.",
17662
+ tags: ["accountability", "discipline", "intensity", "motivation", "sports"],
17663
+ stackable: true,
17664
+ priority: 50,
17665
+ appliesTo: "all",
17666
+ tone: {
17667
+ formality: "casual",
17668
+ verbosity: "concise",
17669
+ emotion: "warm",
17670
+ confidence: "authoritative"
17671
+ },
17672
+ directives: [
17673
+ {
17674
+ id: "next_play_mentality",
16563
17675
  scope: "response_framing",
16564
- instruction: "Do not dwell on missed goals or past failures. Acknowledge them in one sentence, then pivot to what happens next. The past is data, not a verdict.",
17676
+ instruction: 'Do not dwell on missed reps, blown deadlines, or past failures. Acknowledge in one sentence, extract the lesson, then move to the next play. "That drive is over. What are we running next?" The past is film \u2014 you watch it to get better, not to feel bad.',
16565
17677
  example: {
16566
17678
  without: "You missed your deadline again. This is becoming a pattern. You really need to figure out why you keep procrastinating.",
16567
- with: "Missed the deadline. What got in the way? And what's the new deadline you'll actually hit?"
17679
+ with: "Missed the deadline. What got in your way? Good \u2014 now you know. What's the new deadline and what's different this time?"
17680
+ }
17681
+ },
17682
+ {
17683
+ id: "demand_execution",
17684
+ scope: "behavior_shaping",
17685
+ instruction: 'When the user expresses reluctance or makes excuses about something they committed to, do not let it slide. Acknowledge the difficulty in one sentence, then redirect to the play call. "I hear you. Now what are you going to do about it?" No coddling \u2014 but never shame. You demand more because you believe they have more.',
17686
+ example: {
17687
+ without: "I totally get it, sometimes we just don't feel like working out. It's okay to take a break.",
17688
+ with: "Nobody feels like it. Champions do it anyway. What's the smallest rep you can do right now?"
17689
+ }
17690
+ },
17691
+ {
17692
+ id: "reps_over_plans",
17693
+ scope: "response_framing",
17694
+ instruction: 'Always reduce big goals to the next rep. Not the season plan. Not the playbook. The next rep. "What can you execute in the next 10 minutes?" Planning is preparation. Execution is the game.',
17695
+ example: {
17696
+ without: "To write your book, you should create an outline, then character profiles, then a first draft of chapter 1...",
17697
+ with: "One page. Today. That's your rep. Go."
16568
17698
  }
17699
+ },
17700
+ {
17701
+ id: "earned_respect",
17702
+ scope: "behavior_shaping",
17703
+ instruction: 'Only acknowledge real execution. "Good thinking" is meaningless. "You did the work \u2014 respect" is real. Acknowledge effort and completion, not intention or planning. When the user actually executes, give them their props \u2014 brief, genuine, earned.'
17704
+ },
17705
+ {
17706
+ id: "trust_the_process",
17707
+ scope: "response_framing",
17708
+ instruction: `When the user is frustrated with slow progress, remind them that consistency beats intensity. "You don't win the Super Bowl in week 3. You win it by showing up for every practice." Reference their own stated commitments \u2014 their words, their standards.`
16569
17709
  }
16570
17710
  ]
16571
17711
  };
@@ -16622,17 +17762,77 @@ var init_lens = __esm({
16622
17762
  }
16623
17763
  ]
16624
17764
  };
17765
+ BEHAVIORAL_INTERPRETER_LENS = {
17766
+ id: "behavioral-interpreter",
17767
+ name: "Behavioral Interpreter",
17768
+ tagline: "Read patterns, not promises.",
17769
+ author: "NeuroverseOS",
17770
+ version: "1.0.0",
17771
+ description: "Interprets actions as behavioral signals. Prioritizes observed behavior over declared intent, identifies ambiguity, ownership diffusion, resistance, and alignment patterns, and frames outputs around recurring behavior rather than isolated statements.",
17772
+ tags: ["behavior", "signals", "alignment", "analysis", "interpretation"],
17773
+ stackable: true,
17774
+ priority: 65,
17775
+ appliesTo: "all",
17776
+ tone: {
17777
+ formality: "neutral",
17778
+ verbosity: "concise",
17779
+ emotion: "neutral",
17780
+ confidence: "balanced"
17781
+ },
17782
+ directives: [
17783
+ {
17784
+ id: "actions_over_claims",
17785
+ scope: "response_framing",
17786
+ instruction: "Prioritize observed actions, repeated choices, and follow-through over stated intent or self-description. Treat behavior as stronger evidence than promises.",
17787
+ example: {
17788
+ without: "They said they're committed to the project and will prioritize it going forward.",
17789
+ with: "They've said they'll prioritize it three times. Each time, other work was chosen instead. The pattern suggests this is not currently a priority regardless of stated intent."
17790
+ }
17791
+ },
17792
+ {
17793
+ id: "pattern_over_incident",
17794
+ scope: "behavior_shaping",
17795
+ instruction: "Interpret events in sequence. Look for recurring patterns across time rather than over-weighting one isolated incident.",
17796
+ example: {
17797
+ without: "They missed the deadline. That's a red flag.",
17798
+ with: "One missed deadline is an event. Three missed deadlines with similar explanations is a pattern. What does the sequence tell you?"
17799
+ }
17800
+ },
17801
+ {
17802
+ id: "flag_ambiguity",
17803
+ scope: "behavior_shaping",
17804
+ instruction: "Notice ambiguity, indirectness, delayed commitment, and ownership diffusion. Treat these as meaningful signals when they repeat."
17805
+ },
17806
+ {
17807
+ id: "separate_observed_inferred_speculative",
17808
+ scope: "content_filtering",
17809
+ instruction: "Clearly distinguish between what is directly observed, what is reasonably inferred from patterns, and what remains speculative."
17810
+ },
17811
+ {
17812
+ id: "alignment_read",
17813
+ scope: "value_emphasis",
17814
+ instruction: "Assess whether words, timing, decisions, and follow-through align. Misalignment between stated priorities and actual behavior should be named clearly.",
17815
+ example: {
17816
+ without: "They seem supportive of the initiative.",
17817
+ with: "They endorsed the initiative publicly but have not allocated budget, time, or personnel to it. Words and resource allocation are misaligned."
17818
+ }
17819
+ }
17820
+ ]
17821
+ };
16625
17822
  BUILTIN_LENSES = [
16626
17823
  // Character lenses — each one is a person you'd want in your corner
16627
17824
  STOIC_LENS,
16628
- COACH_LENS,
17825
+ LIFE_COACH_LENS,
17826
+ NFL_COACH_LENS,
16629
17827
  CALM_LENS,
16630
17828
  CLOSER_LENS,
16631
17829
  SAMURAI_LENS,
16632
17830
  HYPE_MAN_LENS,
16633
17831
  MONK_LENS,
16634
17832
  SOCRATIC_LENS,
16635
- MINIMALIST_LENS
17833
+ MINIMALIST_LENS,
17834
+ // Behavioral lenses — governance overlays that interpret action, not tone
17835
+ BEHAVIORAL_INTERPRETER_LENS
16636
17836
  ];
16637
17837
  }
16638
17838
  });
@@ -16640,7 +17840,7 @@ var init_lens = __esm({
16640
17840
  // src/cli/lens.ts
16641
17841
  var lens_exports = {};
16642
17842
  __export(lens_exports, {
16643
- main: () => main28
17843
+ main: () => main32
16644
17844
  });
16645
17845
  async function cmdList(argv) {
16646
17846
  let worldPath = "";
@@ -16899,10 +18099,10 @@ async function cmdAdd(argv) {
16899
18099
  if (!id) {
16900
18100
  id = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
16901
18101
  }
16902
- const { readFile: readFile3, writeFile: writeFile5 } = await import("fs/promises");
16903
- const { join: join9 } = await import("path");
18102
+ const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
18103
+ const { join: join14 } = await import("path");
16904
18104
  const possiblePaths = [
16905
- join9(worldPath, "world.nv-world.md"),
18105
+ join14(worldPath, "world.nv-world.md"),
16906
18106
  worldPath
16907
18107
  ];
16908
18108
  let mdPath = "";
@@ -16910,7 +18110,7 @@ async function cmdAdd(argv) {
16910
18110
  for (const p of possiblePaths) {
16911
18111
  try {
16912
18112
  if (p.endsWith(".md")) {
16913
- mdContent = await readFile3(p, "utf-8");
18113
+ mdContent = await readFile4(p, "utf-8");
16914
18114
  mdPath = p;
16915
18115
  break;
16916
18116
  }
@@ -16923,8 +18123,8 @@ async function cmdAdd(argv) {
16923
18123
  const files = await readdir(worldPath);
16924
18124
  const mdFile = files.find((f) => f.endsWith(".nv-world.md"));
16925
18125
  if (mdFile) {
16926
- mdPath = join9(worldPath, mdFile);
16927
- mdContent = await readFile3(mdPath, "utf-8");
18126
+ mdPath = join14(worldPath, mdFile);
18127
+ mdContent = await readFile4(mdPath, "utf-8");
16928
18128
  }
16929
18129
  } catch {
16930
18130
  }
@@ -16958,7 +18158,7 @@ async function cmdAdd(argv) {
16958
18158
  } else {
16959
18159
  mdContent = mdContent.trimEnd() + "\n\n# Lenses\n" + lensBlock + "\n";
16960
18160
  }
16961
- await writeFile5(mdPath, mdContent, "utf-8");
18161
+ await writeFile6(mdPath, mdContent, "utf-8");
16962
18162
  process.stderr.write("\n");
16963
18163
  process.stderr.write(`${GREEN} Added lens "${name}" (${id}) to ${mdPath}${RESET}
16964
18164
  `);
@@ -16973,7 +18173,7 @@ async function cmdAdd(argv) {
16973
18173
 
16974
18174
  `);
16975
18175
  }
16976
- async function main28(argv = process.argv.slice(2)) {
18176
+ async function main32(argv = process.argv.slice(2)) {
16977
18177
  const subcommand = argv[0];
16978
18178
  const subArgs = argv.slice(1);
16979
18179
  try {
@@ -17050,136 +18250,1765 @@ Examples:
17050
18250
  }
17051
18251
  });
17052
18252
 
17053
- // src/cli/neuroverse.ts
17054
- var USAGE5 = `
17055
- neuroverse \u2014 Turn ideas into worlds.
17056
-
17057
- Commands:
17058
- add Add a guard, rule, or invariant to a world
17059
- build Build a world from markdown (derive + compile in one step)
17060
- explain Human-readable summary of a compiled world
17061
- simulate Step-by-step state evolution
17062
- improve Actionable suggestions for strengthening a world
17063
- init Scaffold a new .nv-world.md template
17064
- init-world Generate a governed world from a template (e.g., autoresearch)
17065
- infer-world Scan a repo and infer a governance world from its structure
17066
- validate Static analysis on world files
17067
- guard Runtime governance evaluation (stdin \u2192 stdout)
17068
- test Run guard simulation suite against a world
17069
- redteam Adversarial containment testing (agent escape detection)
17070
- demo Interactive governance demo (flow viz + simulation)
17071
- doctor Environment sanity check
17072
- playground Interactive web demo (opens in browser)
17073
- plan Plan enforcement (compile, check, status, advance, derive)
17074
- run Governed runtime (pipe mode or interactive chat)
17075
- mcp MCP governance server (for Claude, Cursor, etc.)
17076
- worlds List available worlds (alias for world list)
17077
- trace Runtime action audit log
17078
- impact Counterfactual governance impact report
17079
- decision-flow Intent \u2192 Rule \u2192 Outcome visualization (behavioral governance)
17080
- equity-penalties Fortune 500 equity PENALIZE/REWARD simulation
17081
- world World management (status, diff, snapshot, rollback)
17082
- derive AI-assisted synthesis of .nv-world.md from markdown
17083
- bootstrap Compile .nv-world.md \u2192 world JSON files
17084
- configure-ai Configure AI provider credentials
17085
- configure-world Interactive wizard: define your system in plain language
17086
- lens Manage behavioral lenses (list, preview, compile, compare, add)
17087
-
17088
- Usage:
17089
- neuroverse add "Block dairy orders" --world <dir>
17090
- neuroverse add guard --world <dir> --label "Block dairy" --pattern "*dairy*"
17091
- neuroverse add rule --world <dir> --label "Cost overrun" --trigger "cost > 100" --effect "viability *= 0.5"
17092
- neuroverse add invariant --world <dir> --label "Budget must never exceed 1000"
17093
- neuroverse build <input.md> [--output <dir>]
17094
- neuroverse explain <world-path-or-id> [--json]
17095
- neuroverse simulate <world-path-or-id> [--steps N] [--set key=value] [--profile name]
17096
- neuroverse improve <world-path-or-id> [--json]
17097
- neuroverse init [--name "World Name"] [--output path]
17098
- neuroverse init-world autoresearch [--context "topic"] [--dataset "name"] [--goal "goal"]
17099
- neuroverse infer-world ./repo [--output path] [--json] [--dry-run]
17100
- neuroverse validate --world <dir> [--format full|summary|findings]
17101
- neuroverse guard --world <dir> [--trace] [--level basic|standard|strict]
17102
- neuroverse test --world <dir> [--fuzz] [--count N]
17103
- neuroverse redteam --world <dir> [--level basic|standard|strict]
17104
- neuroverse demo [--world social-media] [--port 3456] [--no-browser]
17105
- neuroverse doctor [--world <dir>] [--json]
17106
- neuroverse playground --world <dir> [--port 4242]
17107
- neuroverse trace [--log <path>] [--summary] [--filter BLOCK] [--last 20]
17108
- neuroverse impact [--log <path>] [--json]
17109
- neuroverse world status <path>
17110
- neuroverse world diff <path1> <path2>
17111
- neuroverse world snapshot <path>
17112
- neuroverse world rollback <path>
17113
- neuroverse derive --input <path> [--output <path>] [--dry-run]
17114
- neuroverse bootstrap --input <.md> --output <dir> [--validate]
17115
- neuroverse decision-flow [--log <path>] [--json]
17116
- neuroverse equity-penalties --world <dir> [--agents N] [--rounds N] [--json]
17117
- neuroverse configure-ai --provider <name> --model <name> --api-key <key>
17118
- neuroverse configure-world [--output <dir>]
17119
- neuroverse lens list [--world <dir>] [--json]
17120
- neuroverse lens preview <id> [--world <dir>]
17121
- neuroverse lens compile <id,...> [--world <dir>] [--role <role>] [--json]
17122
- neuroverse lens compare --input "text" --lenses stoic,coach,calm
17123
- neuroverse lens add --world <dir> --name "Name" --tagline "..." [options]
17124
-
17125
- Examples:
17126
- neuroverse build horror-notes.md
17127
- neuroverse explain inherited_silence
17128
- neuroverse simulate inherited_silence --steps 5
17129
- neuroverse improve inherited_silence
17130
- neuroverse build ./docs/ --output ./my-world/
17131
- neuroverse init --name "Customer Service Governance"
17132
- neuroverse validate --world ./world/ --format summary
17133
- echo '{"intent":"delete user data"}' | neuroverse guard --world ./world/ --trace
17134
- neuroverse plan compile plan.md --output plan.json
17135
- echo '{"intent":"write blog"}' | neuroverse plan check --plan plan.json
17136
- neuroverse plan status --plan plan.json
17137
- neuroverse plan advance write_blog_post --plan plan.json
17138
- neuroverse plan derive plan.md --output ./derived-world/
17139
- neuroverse run --pipe --world ./world/ --plan plan.json
17140
- neuroverse run --interactive --world ./world/ --provider openai
17141
- neuroverse mcp --world ./world/ --plan plan.json
17142
- neuroverse test --world ./world/ --fuzz --count 50
17143
- neuroverse redteam --world ./world/ --level strict
17144
- neuroverse doctor
17145
- neuroverse playground --world ./world/
17146
- `.trim();
17147
- async function main29() {
17148
- const args = process.argv.slice(2);
17149
- const command = args[0];
17150
- const subArgs = args.slice(1);
17151
- switch (command) {
17152
- case "add": {
17153
- const { main: addMain } = await Promise.resolve().then(() => (init_add(), add_exports));
17154
- return addMain(subArgs);
17155
- }
17156
- case "build": {
17157
- const { main: buildMain } = await Promise.resolve().then(() => (init_build(), build_exports));
17158
- return buildMain(subArgs);
17159
- }
17160
- case "explain": {
17161
- const { main: explainMain } = await Promise.resolve().then(() => (init_explain(), explain_exports));
17162
- return explainMain(subArgs);
17163
- }
17164
- case "simulate": {
17165
- const { main: simulateMain } = await Promise.resolve().then(() => (init_simulate(), simulate_exports));
17166
- return simulateMain(subArgs);
17167
- }
17168
- case "improve": {
17169
- const { main: improveMain } = await Promise.resolve().then(() => (init_improve(), improve_exports));
17170
- return improveMain(subArgs);
17171
- }
17172
- case "init": {
17173
- const { main: initMain } = await Promise.resolve().then(() => (init_init(), init_exports));
17174
- return initMain(subArgs);
18253
+ // src/engine/worldmodel-parser.ts
18254
+ function splitSections2(markdown) {
18255
+ const lines = markdown.split("\n");
18256
+ let frontmatter = "";
18257
+ let bodyStart = 0;
18258
+ if (lines[0]?.trim() === "---") {
18259
+ const endIdx = lines.indexOf("---", 1);
18260
+ if (endIdx > 0) {
18261
+ frontmatter = lines.slice(1, endIdx).join("\n");
18262
+ bodyStart = endIdx + 1;
17175
18263
  }
17176
- case "init-world": {
17177
- const { main: initWorldMain } = await Promise.resolve().then(() => (init_init_world(), init_world_exports));
17178
- return initWorldMain(subArgs);
18264
+ }
18265
+ const sections = [];
18266
+ let currentSection = null;
18267
+ const contentLines = [];
18268
+ for (let i = bodyStart; i < lines.length; i++) {
18269
+ const line = lines[i];
18270
+ if (line.startsWith("# ")) {
18271
+ if (currentSection) {
18272
+ currentSection.content = contentLines.join("\n").trim();
18273
+ sections.push(currentSection);
18274
+ contentLines.length = 0;
18275
+ }
18276
+ currentSection = {
18277
+ name: line.replace(/^#\s+/, "").trim(),
18278
+ content: "",
18279
+ startLine: i + 1
18280
+ // 1-based
18281
+ };
18282
+ } else if (currentSection) {
18283
+ contentLines.push(line);
17179
18284
  }
17180
- case "infer-world": {
17181
- const { main: inferWorldMain } = await Promise.resolve().then(() => (init_infer_world(), infer_world_exports));
17182
- return inferWorldMain(subArgs);
18285
+ }
18286
+ if (currentSection) {
18287
+ currentSection.content = contentLines.join("\n").trim();
18288
+ sections.push(currentSection);
18289
+ }
18290
+ return { frontmatter, sections };
18291
+ }
18292
+ function splitH2Sections2(content, baseLine) {
18293
+ const lines = content.split("\n");
18294
+ const sections = [];
18295
+ let currentSection = null;
18296
+ const contentLines = [];
18297
+ for (let i = 0; i < lines.length; i++) {
18298
+ const line = lines[i];
18299
+ if (line.startsWith("## ")) {
18300
+ if (currentSection) {
18301
+ currentSection.content = contentLines.join("\n").trim();
18302
+ sections.push(currentSection);
18303
+ contentLines.length = 0;
18304
+ }
18305
+ currentSection = {
18306
+ name: line.replace(/^##\s+/, "").trim(),
18307
+ content: "",
18308
+ startLine: baseLine + i
18309
+ };
18310
+ } else if (currentSection) {
18311
+ contentLines.push(line);
18312
+ }
18313
+ }
18314
+ if (currentSection) {
18315
+ currentSection.content = contentLines.join("\n").trim();
18316
+ sections.push(currentSection);
18317
+ }
18318
+ return sections;
18319
+ }
18320
+ function splitH3Sections(content, baseLine) {
18321
+ const lines = content.split("\n");
18322
+ const sections = [];
18323
+ let currentSection = null;
18324
+ const contentLines = [];
18325
+ for (let i = 0; i < lines.length; i++) {
18326
+ const line = lines[i];
18327
+ if (line.startsWith("### ")) {
18328
+ if (currentSection) {
18329
+ currentSection.content = contentLines.join("\n").trim();
18330
+ sections.push(currentSection);
18331
+ contentLines.length = 0;
18332
+ }
18333
+ currentSection = {
18334
+ name: line.replace(/^###\s+/, "").trim(),
18335
+ content: "",
18336
+ startLine: baseLine + i
18337
+ };
18338
+ } else if (currentSection) {
18339
+ contentLines.push(line);
18340
+ }
18341
+ }
18342
+ if (currentSection) {
18343
+ currentSection.content = contentLines.join("\n").trim();
18344
+ sections.push(currentSection);
18345
+ }
18346
+ return sections;
18347
+ }
18348
+ function splitH4Sections(content, baseLine) {
18349
+ const lines = content.split("\n");
18350
+ const sections = [];
18351
+ let currentSection = null;
18352
+ const contentLines = [];
18353
+ for (let i = 0; i < lines.length; i++) {
18354
+ const line = lines[i];
18355
+ if (line.startsWith("#### ")) {
18356
+ if (currentSection) {
18357
+ currentSection.content = contentLines.join("\n").trim();
18358
+ sections.push(currentSection);
18359
+ contentLines.length = 0;
18360
+ }
18361
+ currentSection = {
18362
+ name: line.replace(/^####\s+/, "").trim(),
18363
+ content: "",
18364
+ startLine: baseLine + i
18365
+ };
18366
+ } else if (currentSection) {
18367
+ contentLines.push(line);
18368
+ }
18369
+ }
18370
+ if (currentSection) {
18371
+ currentSection.content = contentLines.join("\n").trim();
18372
+ sections.push(currentSection);
18373
+ }
18374
+ return sections;
18375
+ }
18376
+ function parseBulletList(content) {
18377
+ const items = [];
18378
+ let inComment = false;
18379
+ for (const line of content.split("\n")) {
18380
+ const trimmed = line.trim();
18381
+ if (trimmed.startsWith("<!--")) {
18382
+ inComment = true;
18383
+ }
18384
+ if (inComment) {
18385
+ if (trimmed.includes("-->")) {
18386
+ inComment = false;
18387
+ }
18388
+ continue;
18389
+ }
18390
+ if (trimmed.startsWith("- ")) {
18391
+ items.push(trimmed.slice(2).trim());
18392
+ }
18393
+ }
18394
+ return items;
18395
+ }
18396
+ function extractTextContent(content) {
18397
+ const lines = content.split("\n");
18398
+ const textLines = [];
18399
+ let inComment = false;
18400
+ for (const line of lines) {
18401
+ const trimmed = line.trim();
18402
+ if (trimmed.startsWith("<!--")) {
18403
+ inComment = true;
18404
+ }
18405
+ if (inComment) {
18406
+ if (trimmed.includes("-->")) {
18407
+ inComment = false;
18408
+ }
18409
+ continue;
18410
+ }
18411
+ if (trimmed && !trimmed.startsWith("#")) {
18412
+ textLines.push(trimmed);
18413
+ }
18414
+ }
18415
+ return textLines.join("\n").trim();
18416
+ }
18417
+ function toKebabCase(name) {
18418
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
18419
+ }
18420
+ function parseFrontmatter3(yaml, issues) {
18421
+ const result = {};
18422
+ for (const line of yaml.split("\n")) {
18423
+ const trimmed = line.trim();
18424
+ if (!trimmed || trimmed.startsWith("#")) continue;
18425
+ const colonIdx = trimmed.indexOf(":");
18426
+ if (colonIdx === -1) continue;
18427
+ const key = trimmed.slice(0, colonIdx).trim();
18428
+ const value = trimmed.slice(colonIdx + 1).trim();
18429
+ result[key] = value;
18430
+ }
18431
+ const name = result.name || "";
18432
+ if (!name) {
18433
+ issues.push({
18434
+ line: 1,
18435
+ section: "frontmatter",
18436
+ message: "Missing name in frontmatter. Provide a human-readable model name.",
18437
+ severity: "error"
18438
+ });
18439
+ }
18440
+ const model_id = result.model_id || toKebabCase(name);
18441
+ return {
18442
+ model_id,
18443
+ name,
18444
+ version: result.version || "1.0.0"
18445
+ };
18446
+ }
18447
+ function parseGeometry(section, issues) {
18448
+ const geometry = {
18449
+ mission: "",
18450
+ domains: [],
18451
+ overlapEffects: [],
18452
+ centerIdentity: ""
18453
+ };
18454
+ if (!section) {
18455
+ issues.push({
18456
+ line: 0,
18457
+ section: "Core Model Geometry",
18458
+ message: "Missing # Core Model Geometry section. Define the structural model: mission, domains with embedded skills and values, overlaps, and center identity.",
18459
+ severity: "error"
18460
+ });
18461
+ return geometry;
18462
+ }
18463
+ const h2Sections = splitH2Sections2(section.content, section.startLine);
18464
+ const missionSection = h2Sections.find((s) => s.name.toLowerCase() === "mission");
18465
+ if (missionSection) {
18466
+ geometry.mission = extractTextContent(missionSection.content);
18467
+ }
18468
+ if (!geometry.mission) {
18469
+ issues.push({
18470
+ line: missionSection?.startLine ?? section.startLine,
18471
+ section: "Mission",
18472
+ message: "Missing ## Mission. Define what this system is trying to achieve \u2014 the core aim, not a slogan.",
18473
+ severity: "error"
18474
+ });
18475
+ }
18476
+ const domainsSection = h2Sections.find((s) => s.name.toLowerCase() === "domains");
18477
+ if (domainsSection) {
18478
+ const domainSections = splitH3Sections(domainsSection.content, domainsSection.startLine);
18479
+ for (const ds of domainSections) {
18480
+ const domain = {
18481
+ id: toKebabCase(ds.name),
18482
+ name: ds.name,
18483
+ skills: [],
18484
+ values: [],
18485
+ line: ds.startLine
18486
+ };
18487
+ const h4Sections = splitH4Sections(ds.content, ds.startLine);
18488
+ const skillsH4 = h4Sections.find((s) => s.name.toLowerCase() === "skills");
18489
+ if (skillsH4) {
18490
+ domain.skills = parseBulletList(skillsH4.content);
18491
+ }
18492
+ const valuesH4 = h4Sections.find((s) => s.name.toLowerCase() === "values");
18493
+ if (valuesH4) {
18494
+ domain.values = parseBulletList(valuesH4.content);
18495
+ }
18496
+ if (domain.skills.length === 0) {
18497
+ issues.push({
18498
+ line: ds.startLine,
18499
+ section: "Domains",
18500
+ message: `Domain '${ds.name}' has no skills defined. Skills are the capabilities within this domain.`,
18501
+ severity: "warning"
18502
+ });
18503
+ }
18504
+ if (domain.values.length === 0) {
18505
+ issues.push({
18506
+ line: ds.startLine,
18507
+ section: "Domains",
18508
+ message: `Domain '${ds.name}' has no values defined. Behavior has no constraints without values.`,
18509
+ severity: "warning"
18510
+ });
18511
+ }
18512
+ geometry.domains.push(domain);
18513
+ }
18514
+ }
18515
+ if (geometry.domains.length < 2) {
18516
+ issues.push({
18517
+ line: domainsSection?.startLine ?? section.startLine,
18518
+ section: "Domains",
18519
+ message: "At least 2 domains required. Domains are the major operating modes of the system, each carrying skills and values.",
18520
+ severity: "error"
18521
+ });
18522
+ }
18523
+ const overlapsSection = h2Sections.find(
18524
+ (s) => s.name.toLowerCase() === "overlap effects"
18525
+ );
18526
+ if (overlapsSection) {
18527
+ const bullets = parseBulletList(overlapsSection.content);
18528
+ const domainNames = new Set(geometry.domains.map((d) => d.name.toLowerCase()));
18529
+ for (let i = 0; i < bullets.length; i++) {
18530
+ const bullet = bullets[i];
18531
+ const match = bullet.match(/^(.+?)\s*\+\s*(.+?)\s*=\s*(.+)$/);
18532
+ if (match) {
18533
+ const domainA = match[1].trim();
18534
+ const domainB = match[2].trim();
18535
+ const effect = match[3].trim();
18536
+ if (!domainNames.has(domainA.toLowerCase())) {
18537
+ issues.push({
18538
+ line: overlapsSection.startLine + i,
18539
+ section: "Overlap Effects",
18540
+ message: `Overlap references unknown domain '${domainA}'. Must reference a declared domain.`,
18541
+ severity: "warning"
18542
+ });
18543
+ }
18544
+ if (!domainNames.has(domainB.toLowerCase())) {
18545
+ issues.push({
18546
+ line: overlapsSection.startLine + i,
18547
+ section: "Overlap Effects",
18548
+ message: `Overlap references unknown domain '${domainB}'. Must reference a declared domain.`,
18549
+ severity: "warning"
18550
+ });
18551
+ }
18552
+ geometry.overlapEffects.push({
18553
+ domainA,
18554
+ domainB,
18555
+ effect,
18556
+ line: overlapsSection.startLine + i
18557
+ });
18558
+ } else {
18559
+ issues.push({
18560
+ line: overlapsSection.startLine + i,
18561
+ section: "Overlap Effects",
18562
+ message: `Cannot parse overlap: '${bullet}'. Expected format: 'Domain A + Domain B = Emergent State'.`,
18563
+ severity: "warning"
18564
+ });
18565
+ }
18566
+ }
18567
+ }
18568
+ if (geometry.overlapEffects.length === 0) {
18569
+ issues.push({
18570
+ line: overlapsSection?.startLine ?? section.startLine,
18571
+ section: "Overlap Effects",
18572
+ message: 'No overlap effects defined. Define what emerges when two domains interact well (e.g., "Domain A + Domain B = Inspiration").',
18573
+ severity: "warning"
18574
+ });
18575
+ }
18576
+ const identitySection = h2Sections.find(
18577
+ (s) => s.name.toLowerCase() === "center identity"
18578
+ );
18579
+ if (identitySection) {
18580
+ geometry.centerIdentity = extractTextContent(identitySection.content);
18581
+ }
18582
+ if (!geometry.centerIdentity) {
18583
+ issues.push({
18584
+ line: identitySection?.startLine ?? section.startLine,
18585
+ section: "Center Identity",
18586
+ message: "No center identity defined. Define what the system becomes when all domains are aligned \u2014 the core identity.",
18587
+ severity: "warning"
18588
+ });
18589
+ }
18590
+ return geometry;
18591
+ }
18592
+ function parseModifiers(section, issues) {
18593
+ const modifiers = {
18594
+ authorityLayers: [],
18595
+ spatialContexts: [],
18596
+ interpretationRules: []
18597
+ };
18598
+ if (!section) {
18599
+ issues.push({
18600
+ line: 0,
18601
+ section: "Contextual Modifiers",
18602
+ message: "Missing # Contextual Modifiers section. Define how authority, role, and spatial context change how behavior is interpreted.",
18603
+ severity: "warning"
18604
+ });
18605
+ return modifiers;
18606
+ }
18607
+ const h2Sections = splitH2Sections2(section.content, section.startLine);
18608
+ const authoritySection = h2Sections.find(
18609
+ (s) => s.name.toLowerCase() === "authority layers"
18610
+ );
18611
+ if (authoritySection) {
18612
+ modifiers.authorityLayers = parseBulletList(authoritySection.content);
18613
+ }
18614
+ const spatialSection = h2Sections.find(
18615
+ (s) => s.name.toLowerCase() === "spatial contexts"
18616
+ );
18617
+ if (spatialSection) {
18618
+ modifiers.spatialContexts = parseBulletList(spatialSection.content);
18619
+ }
18620
+ const rulesSection = h2Sections.find(
18621
+ (s) => s.name.toLowerCase() === "interpretation rules"
18622
+ );
18623
+ if (rulesSection) {
18624
+ modifiers.interpretationRules = parseBulletList(rulesSection.content);
18625
+ }
18626
+ return modifiers;
18627
+ }
18628
+ function parseEvolution(section, issues) {
18629
+ const evolution = {
18630
+ alignedBehaviors: [],
18631
+ driftBehaviors: [],
18632
+ signals: [],
18633
+ decisionPriorities: [],
18634
+ evolutionConditions: []
18635
+ };
18636
+ if (!section) {
18637
+ issues.push({
18638
+ line: 0,
18639
+ section: "Evolution Layer",
18640
+ message: "Missing # Evolution Layer section. Define observable behaviors, signals, decision priorities, and adaptation conditions.",
18641
+ severity: "error"
18642
+ });
18643
+ return evolution;
18644
+ }
18645
+ const h2Sections = splitH2Sections2(section.content, section.startLine);
18646
+ const alignedSection = h2Sections.find(
18647
+ (s) => s.name.toLowerCase() === "aligned behaviors"
18648
+ );
18649
+ if (alignedSection) {
18650
+ evolution.alignedBehaviors = parseBulletList(alignedSection.content);
18651
+ }
18652
+ if (evolution.alignedBehaviors.length === 0) {
18653
+ issues.push({
18654
+ line: alignedSection?.startLine ?? section.startLine,
18655
+ section: "Aligned Behaviors",
18656
+ message: "No aligned behaviors defined. Define what success looks like in action.",
18657
+ severity: "warning"
18658
+ });
18659
+ }
18660
+ const driftSection = h2Sections.find(
18661
+ (s) => s.name.toLowerCase() === "drift behaviors"
18662
+ );
18663
+ if (driftSection) {
18664
+ evolution.driftBehaviors = parseBulletList(driftSection.content);
18665
+ }
18666
+ if (evolution.driftBehaviors.length === 0) {
18667
+ issues.push({
18668
+ line: driftSection?.startLine ?? section.startLine,
18669
+ section: "Drift Behaviors",
18670
+ message: "No drift behaviors defined. Define what misalignment looks like so the system can detect behavioral drift over time.",
18671
+ severity: "warning"
18672
+ });
18673
+ }
18674
+ const signalsSection = h2Sections.find(
18675
+ (s) => s.name.toLowerCase() === "signals"
18676
+ );
18677
+ if (signalsSection) {
18678
+ evolution.signals = parseBulletList(signalsSection.content);
18679
+ }
18680
+ if (evolution.signals.length < 2) {
18681
+ issues.push({
18682
+ line: signalsSection?.startLine ?? section.startLine,
18683
+ section: "Signals",
18684
+ message: "At least 2 signals required. Signals are the observable metrics for detecting alignment or drift.",
18685
+ severity: "error"
18686
+ });
18687
+ }
18688
+ const prioritiesSection = h2Sections.find(
18689
+ (s) => s.name.toLowerCase() === "decision priorities"
18690
+ );
18691
+ if (prioritiesSection) {
18692
+ const bullets = parseBulletList(prioritiesSection.content);
18693
+ for (let i = 0; i < bullets.length; i++) {
18694
+ const bullet = bullets[i];
18695
+ const match = bullet.match(/^(.+?)\s*>\s*(.+)$/);
18696
+ if (match) {
18697
+ evolution.decisionPriorities.push({
18698
+ preferred: match[1].trim(),
18699
+ over: match[2].trim(),
18700
+ line: prioritiesSection.startLine + i
18701
+ });
18702
+ } else {
18703
+ issues.push({
18704
+ line: prioritiesSection.startLine + i,
18705
+ section: "Decision Priorities",
18706
+ message: `Cannot parse priority: '${bullet}'. Expected format: 'preferred > over'.`,
18707
+ severity: "warning"
18708
+ });
18709
+ }
18710
+ }
18711
+ }
18712
+ if (evolution.decisionPriorities.length === 0) {
18713
+ issues.push({
18714
+ line: prioritiesSection?.startLine ?? section.startLine,
18715
+ section: "Decision Priorities",
18716
+ message: "No decision priorities defined. Define what wins when tradeoffs appear.",
18717
+ severity: "warning"
18718
+ });
18719
+ }
18720
+ const evoSection = h2Sections.find(
18721
+ (s) => s.name.toLowerCase() === "evolution conditions"
18722
+ );
18723
+ if (evoSection) {
18724
+ evolution.evolutionConditions = parseBulletList(evoSection.content);
18725
+ }
18726
+ if (evolution.signals.length > 0 && evolution.driftBehaviors.length === 0) {
18727
+ issues.push({
18728
+ line: signalsSection?.startLine ?? section.startLine,
18729
+ section: "Evolution Layer",
18730
+ message: "Signals defined but no drift behaviors. System cannot detect failure without drift definitions.",
18731
+ severity: "warning"
18732
+ });
18733
+ }
18734
+ return evolution;
18735
+ }
18736
+ function parseWorldModel(markdown) {
18737
+ const issues = [];
18738
+ if (!markdown || !markdown.trim()) {
18739
+ issues.push({
18740
+ line: 0,
18741
+ section: "file",
18742
+ message: "Empty input. Provide a .worldmodel.md file with three layers: Core Model Geometry, Contextual Modifiers, Evolution Layer.",
18743
+ severity: "error"
18744
+ });
18745
+ return { model: null, issues };
18746
+ }
18747
+ const { frontmatter: fmRaw, sections } = splitSections2(markdown);
18748
+ const frontmatter = parseFrontmatter3(fmRaw, issues);
18749
+ const geometrySection = sections.find(
18750
+ (s) => s.name.toLowerCase() === "core model geometry"
18751
+ );
18752
+ const modifiersSection = sections.find(
18753
+ (s) => s.name.toLowerCase() === "contextual modifiers"
18754
+ );
18755
+ const evolutionSection = sections.find(
18756
+ (s) => s.name.toLowerCase() === "evolution layer"
18757
+ );
18758
+ const geometry = parseGeometry(geometrySection, issues);
18759
+ const modifiers = parseModifiers(modifiersSection, issues);
18760
+ const evolution = parseEvolution(evolutionSection, issues);
18761
+ if (geometry.overlapEffects.length > 0 && !geometry.centerIdentity) {
18762
+ issues.push({
18763
+ line: 0,
18764
+ section: "Core Model Geometry",
18765
+ message: "Overlaps defined but no center identity. System lacks coherence without an aligned identity.",
18766
+ severity: "warning"
18767
+ });
18768
+ }
18769
+ const hasErrors = issues.some((i) => i.severity === "error");
18770
+ if (hasErrors) {
18771
+ return {
18772
+ model: {
18773
+ frontmatter,
18774
+ geometry,
18775
+ modifiers,
18776
+ evolution
18777
+ },
18778
+ issues
18779
+ };
18780
+ }
18781
+ return {
18782
+ model: {
18783
+ frontmatter,
18784
+ geometry,
18785
+ modifiers,
18786
+ evolution
18787
+ },
18788
+ issues
18789
+ };
18790
+ }
18791
+ var init_worldmodel_parser = __esm({
18792
+ "src/engine/worldmodel-parser.ts"() {
18793
+ "use strict";
18794
+ }
18795
+ });
18796
+
18797
+ // src/engine/worldmodel-compiler.ts
18798
+ function toSnakeCase(text) {
18799
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
18800
+ }
18801
+ function toKebabCase2(text) {
18802
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
18803
+ }
18804
+ function titleCase(text) {
18805
+ return text.split(/[\s_-]+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ");
18806
+ }
18807
+ function matchSignal(behaviorText, signals) {
18808
+ const lowerText = behaviorText.toLowerCase();
18809
+ for (const signal of signals) {
18810
+ const signalWords = signal.toLowerCase().split("_");
18811
+ if (signalWords.some((w) => w.length > 3 && lowerText.includes(w))) {
18812
+ return signal;
18813
+ }
18814
+ }
18815
+ return "alignment_score";
18816
+ }
18817
+ function emitWorldMarkdown(model) {
18818
+ const lines = [];
18819
+ const worldId = model.frontmatter.model_id;
18820
+ const worldName = model.frontmatter.name;
18821
+ const version = model.frontmatter.version;
18822
+ lines.push("---");
18823
+ lines.push(`world_id: ${worldId}`);
18824
+ lines.push(`name: ${worldName}`);
18825
+ lines.push(`version: ${version}`);
18826
+ lines.push("runtime_mode: COMPLIANCE");
18827
+ lines.push("default_profile: aligned");
18828
+ lines.push("alternative_profile: drifting");
18829
+ lines.push("---");
18830
+ lines.push("");
18831
+ lines.push("# Thesis");
18832
+ lines.push("");
18833
+ lines.push(model.geometry.mission);
18834
+ if (model.geometry.centerIdentity) {
18835
+ lines.push(
18836
+ `When all domains are aligned, the system operates as: ${model.geometry.centerIdentity}.`
18837
+ );
18838
+ }
18839
+ lines.push("");
18840
+ lines.push("# Invariants");
18841
+ lines.push("");
18842
+ let invariantIdx = 0;
18843
+ for (const domain of model.geometry.domains) {
18844
+ for (const value of domain.values) {
18845
+ invariantIdx++;
18846
+ const invId = `${toSnakeCase(domain.name)}_value_${String(invariantIdx).padStart(2, "0")}`;
18847
+ lines.push(
18848
+ `- \`${invId}\` \u2014 ${value} [${domain.name}] (structural, immutable)`
18849
+ );
18850
+ }
18851
+ }
18852
+ lines.push("");
18853
+ lines.push("# State");
18854
+ lines.push("");
18855
+ lines.push("## alignment_score");
18856
+ lines.push("- type: number");
18857
+ lines.push("- min: 0");
18858
+ lines.push("- max: 100");
18859
+ lines.push("- step: 5");
18860
+ lines.push("- default: 70");
18861
+ lines.push("- label: Alignment Score");
18862
+ lines.push(
18863
+ "- description: Composite behavioral alignment metric derived from all signals"
18864
+ );
18865
+ lines.push("");
18866
+ for (const signal of model.evolution.signals) {
18867
+ const signalId = toSnakeCase(signal);
18868
+ const signalLabel = titleCase(signal);
18869
+ lines.push(`## ${signalId}`);
18870
+ lines.push("- type: number");
18871
+ lines.push("- min: 0");
18872
+ lines.push("- max: 100");
18873
+ lines.push("- step: 5");
18874
+ lines.push("- default: 70");
18875
+ lines.push(`- label: ${signalLabel}`);
18876
+ lines.push(`- description: Behavioral signal measuring ${signal.replace(/_/g, " ")}`);
18877
+ lines.push("");
18878
+ }
18879
+ lines.push("# Assumptions");
18880
+ lines.push("");
18881
+ lines.push("## aligned");
18882
+ lines.push("- name: Aligned");
18883
+ lines.push("- description: All behavioral signals at healthy levels");
18884
+ lines.push("- pressure_level: low");
18885
+ lines.push("");
18886
+ lines.push("## drifting");
18887
+ lines.push("- name: Drifting");
18888
+ lines.push("- description: Behavioral signals under pressure with drift risk");
18889
+ lines.push("- pressure_level: high");
18890
+ lines.push("");
18891
+ lines.push("# Rules");
18892
+ lines.push("");
18893
+ let ruleIdx = 0;
18894
+ for (const drift of model.evolution.driftBehaviors) {
18895
+ ruleIdx++;
18896
+ const ruleId = `rule-${String(ruleIdx).padStart(3, "0")}`;
18897
+ const matchedSignal = matchSignal(drift, model.evolution.signals);
18898
+ const signalId = toSnakeCase(matchedSignal);
18899
+ lines.push(`## ${ruleId}: ${drift} (degradation)`);
18900
+ lines.push(`Drift behavior detected: ${drift}`);
18901
+ lines.push("");
18902
+ lines.push(`When ${signalId} < 50 [state]`);
18903
+ lines.push("Then alignment_score *= 0.80");
18904
+ lines.push("");
18905
+ lines.push(`> trigger: ${signalId} drops below threshold`);
18906
+ lines.push(`> rule: Drift behavior weakens alignment`);
18907
+ lines.push(`> shift: Behavioral alignment decreases`);
18908
+ lines.push(`> effect: Alignment score reduced by 20%`);
18909
+ lines.push("");
18910
+ }
18911
+ for (const aligned of model.evolution.alignedBehaviors) {
18912
+ ruleIdx++;
18913
+ const ruleId = `rule-${String(ruleIdx).padStart(3, "0")}`;
18914
+ const matchedSignal = matchSignal(aligned, model.evolution.signals);
18915
+ const signalId = toSnakeCase(matchedSignal);
18916
+ lines.push(`## ${ruleId}: ${aligned} (advantage)`);
18917
+ lines.push(`Aligned behavior reinforced: ${aligned}`);
18918
+ lines.push("");
18919
+ lines.push(`When ${signalId} >= 70 [state]`);
18920
+ lines.push("Then alignment_score *= 1.10");
18921
+ lines.push("");
18922
+ lines.push(`> trigger: ${signalId} above healthy threshold`);
18923
+ lines.push(`> rule: Aligned behavior strengthens system`);
18924
+ lines.push(`> shift: Behavioral alignment increases`);
18925
+ lines.push(`> effect: Alignment score boosted by 10%`);
18926
+ lines.push("");
18927
+ }
18928
+ for (let i = 0; i < model.evolution.decisionPriorities.length; i++) {
18929
+ ruleIdx++;
18930
+ const priority = model.evolution.decisionPriorities[i];
18931
+ const ruleId = `rule-${String(ruleIdx).padStart(3, "0")}`;
18932
+ lines.push(
18933
+ `## ${ruleId}: ${priority.preferred} over ${priority.over} (structural)`
18934
+ );
18935
+ lines.push(
18936
+ `Priority: ${priority.preferred} takes precedence over ${priority.over} in tradeoff situations.`
18937
+ );
18938
+ lines.push("");
18939
+ lines.push("When alignment_score < 40 [state]");
18940
+ lines.push("Then alignment_score *= 0.70");
18941
+ lines.push("Collapse: alignment_score < 10");
18942
+ lines.push("");
18943
+ lines.push(`> trigger: Alignment score critically low`);
18944
+ lines.push(
18945
+ `> rule: Priority violation \u2014 ${priority.preferred} must outweigh ${priority.over}`
18946
+ );
18947
+ lines.push(`> shift: System enters structural enforcement`);
18948
+ lines.push(`> effect: Alignment sharply reduced; collapse if critical`);
18949
+ lines.push("");
18950
+ }
18951
+ lines.push("# Gates");
18952
+ lines.push("");
18953
+ lines.push("- STRONG: alignment_score >= 85");
18954
+ lines.push("- STABLE: alignment_score >= 65");
18955
+ lines.push("- WATCHING: alignment_score >= 45");
18956
+ lines.push("- FRAGILE: alignment_score > 30");
18957
+ lines.push("- MISALIGNED: alignment_score <= 30");
18958
+ lines.push("");
18959
+ lines.push("# Outcomes");
18960
+ lines.push("");
18961
+ lines.push("## alignment_score");
18962
+ lines.push("- type: number");
18963
+ lines.push("- range: 0-100");
18964
+ lines.push("- display: percentage");
18965
+ lines.push("- label: Alignment Score");
18966
+ lines.push("- primary: true");
18967
+ lines.push("");
18968
+ for (const signal of model.evolution.signals) {
18969
+ const signalId = toSnakeCase(signal);
18970
+ const signalLabel = titleCase(signal);
18971
+ lines.push(`## ${signalId}`);
18972
+ lines.push("- type: number");
18973
+ lines.push("- range: 0-100");
18974
+ lines.push("- display: percentage");
18975
+ lines.push(`- label: ${signalLabel}`);
18976
+ lines.push("");
18977
+ }
18978
+ const lensSuggestions = buildLensSuggestions(model);
18979
+ if (lensSuggestions.length > 0) {
18980
+ lines.push("# Lenses");
18981
+ lines.push("- policy: role_default");
18982
+ lines.push("");
18983
+ for (const lens of lensSuggestions) {
18984
+ lines.push(`## ${lens.id}`);
18985
+ lines.push(`- tagline: ${lens.tagline}`);
18986
+ lines.push(
18987
+ `- description: Lens derived from ${lens.derived_from.domainA} and ${lens.derived_from.domainB} interaction, producing ${lens.derived_from.effect}.`
18988
+ );
18989
+ lines.push(`- formality: ${lens.tone.formality}`);
18990
+ lines.push(`- verbosity: ${lens.tone.verbosity}`);
18991
+ lines.push(`- emotion: ${lens.tone.emotion}`);
18992
+ lines.push(`- confidence: ${lens.tone.confidence}`);
18993
+ lines.push("- tags: behavioral, worldmodel, overlap");
18994
+ lines.push("- default_for_roles: all");
18995
+ lines.push("- priority: 50");
18996
+ lines.push("- stackable: true");
18997
+ lines.push("");
18998
+ for (const directive of lens.directives) {
18999
+ lines.push(`> ${directive.scope}: ${directive.instruction}`);
19000
+ }
19001
+ lines.push("");
19002
+ }
19003
+ }
19004
+ return lines.join("\n");
19005
+ }
19006
+ function emitSignalSchema(model) {
19007
+ const signals = model.evolution.signals.map((signal) => ({
19008
+ id: toSnakeCase(signal),
19009
+ name: titleCase(signal),
19010
+ type: "number",
19011
+ default: 70
19012
+ }));
19013
+ return {
19014
+ model_id: model.frontmatter.model_id,
19015
+ signals
19016
+ };
19017
+ }
19018
+ function emitOverlapMap(model) {
19019
+ const pairings = model.geometry.overlapEffects.map((o) => ({
19020
+ domainA: o.domainA,
19021
+ domainB: o.domainB,
19022
+ effect: o.effect
19023
+ }));
19024
+ const matrix = {};
19025
+ for (const overlap of model.geometry.overlapEffects) {
19026
+ const keyA = toKebabCase2(overlap.domainA);
19027
+ const keyB = toKebabCase2(overlap.domainB);
19028
+ if (!matrix[keyA]) matrix[keyA] = {};
19029
+ matrix[keyA][keyB] = overlap.effect;
19030
+ }
19031
+ return {
19032
+ model_id: model.frontmatter.model_id,
19033
+ pairings,
19034
+ matrix
19035
+ };
19036
+ }
19037
+ function emitContextsConfig(model) {
19038
+ return {
19039
+ model_id: model.frontmatter.model_id,
19040
+ authority_layers: model.modifiers.authorityLayers,
19041
+ spatial_contexts: model.modifiers.spatialContexts,
19042
+ interpretation_rules: model.modifiers.interpretationRules
19043
+ };
19044
+ }
19045
+ function deriveTone(domainA, domainB) {
19046
+ const combined = `${domainA} ${domainB}`.toLowerCase();
19047
+ let formality = "neutral";
19048
+ if (/strateg|technic|analytic|research|engineer/.test(combined)) {
19049
+ formality = "professional";
19050
+ } else if (/narrat|story|communi|creative/.test(combined)) {
19051
+ formality = "casual";
19052
+ }
19053
+ let verbosity = "balanced";
19054
+ if (/foresight|scenario|plan|design/.test(combined)) {
19055
+ verbosity = "detailed";
19056
+ } else if (/prosper|negotiat|stakeholder/.test(combined)) {
19057
+ verbosity = "concise";
19058
+ }
19059
+ let emotion = "neutral";
19060
+ if (/empath|emoti|care|safe|trust/.test(combined)) {
19061
+ emotion = "warm";
19062
+ } else if (/analytic|system|data/.test(combined)) {
19063
+ emotion = "clinical";
19064
+ }
19065
+ let confidence = "balanced";
19066
+ if (/lead|command|decis|strateg/.test(combined)) {
19067
+ confidence = "authoritative";
19068
+ } else if (/explor|experiment|creat/.test(combined)) {
19069
+ confidence = "exploratory";
19070
+ }
19071
+ return { formality, verbosity, emotion, confidence };
19072
+ }
19073
+ function buildLensSuggestions(model) {
19074
+ const lenses = [];
19075
+ const domainMap = new Map(model.geometry.domains.map((d) => [d.name.toLowerCase(), d]));
19076
+ for (const overlap of model.geometry.overlapEffects) {
19077
+ const lensId = toKebabCase2(overlap.effect);
19078
+ const tone = deriveTone(overlap.domainA, overlap.domainB);
19079
+ const domainAData = domainMap.get(overlap.domainA.toLowerCase());
19080
+ const domainBData = domainMap.get(overlap.domainB.toLowerCase());
19081
+ const directives = [];
19082
+ if (domainAData && domainAData.skills.length > 0) {
19083
+ directives.push({
19084
+ scope: "response_framing",
19085
+ instruction: `Approach through the lens of ${domainAData.skills.join(", ").toLowerCase()}.`
19086
+ });
19087
+ }
19088
+ if (domainBData && domainBData.values.length > 0) {
19089
+ directives.push({
19090
+ scope: "behavior_shaping",
19091
+ instruction: `Maintain ${domainBData.values.join(", ").toLowerCase()} in all responses.`
19092
+ });
19093
+ }
19094
+ directives.push({
19095
+ scope: "value_emphasis",
19096
+ instruction: `Emphasize ${overlap.effect.toLowerCase()} as the emergent state of aligned behavior.`
19097
+ });
19098
+ lenses.push({
19099
+ id: lensId,
19100
+ name: titleCase(overlap.effect),
19101
+ tagline: `${overlap.effect} through ${overlap.domainA} and ${overlap.domainB}.`,
19102
+ derived_from: {
19103
+ domainA: overlap.domainA,
19104
+ domainB: overlap.domainB,
19105
+ effect: overlap.effect
19106
+ },
19107
+ tone,
19108
+ directives
19109
+ });
19110
+ }
19111
+ return lenses;
19112
+ }
19113
+ function emitLensSuggestions(model) {
19114
+ return buildLensSuggestions(model);
19115
+ }
19116
+ function compileWorldModel(model) {
19117
+ return {
19118
+ worldMarkdown: emitWorldMarkdown(model),
19119
+ signalSchema: emitSignalSchema(model),
19120
+ overlapMap: emitOverlapMap(model),
19121
+ contextsConfig: emitContextsConfig(model),
19122
+ lensSuggestions: emitLensSuggestions(model)
19123
+ };
19124
+ }
19125
+ var init_worldmodel_compiler = __esm({
19126
+ "src/engine/worldmodel-compiler.ts"() {
19127
+ "use strict";
19128
+ }
19129
+ });
19130
+
19131
+ // src/cli/worldmodel.ts
19132
+ var worldmodel_exports = {};
19133
+ __export(worldmodel_exports, {
19134
+ main: () => main33
19135
+ });
19136
+ function parseArgs26(argv) {
19137
+ const args = {
19138
+ inputPath: "",
19139
+ output: "",
19140
+ name: "",
19141
+ json: false,
19142
+ help: false
19143
+ };
19144
+ for (let i = 0; i < argv.length; i++) {
19145
+ const arg = argv[i];
19146
+ if (arg === "--json") {
19147
+ args.json = true;
19148
+ } else if (arg === "--help" || arg === "-h") {
19149
+ args.help = true;
19150
+ } else if (arg === "--output" && i + 1 < argv.length) {
19151
+ args.output = argv[++i];
19152
+ } else if (arg === "--name" && i + 1 < argv.length) {
19153
+ args.name = argv[++i];
19154
+ } else if (!arg.startsWith("--") && !args.inputPath) {
19155
+ args.inputPath = arg;
19156
+ }
19157
+ }
19158
+ return args;
19159
+ }
19160
+ function formatIssue(issue) {
19161
+ const color = issue.severity === "error" ? RED : issue.severity === "warning" ? YELLOW2 : DIM2;
19162
+ const icon = issue.severity === "error" ? "x" : issue.severity === "warning" ? "!" : "i";
19163
+ const lineRef = issue.line > 0 ? `:${issue.line}` : "";
19164
+ return ` ${color}${icon}${RESET2} [${issue.section}${lineRef}] ${issue.message}`;
19165
+ }
19166
+ async function readSourceFile(inputPath) {
19167
+ const fullPath = (0, import_path12.resolve)(inputPath);
19168
+ if (!(0, import_fs11.existsSync)(fullPath)) {
19169
+ process.stderr.write(`File not found: ${fullPath}
19170
+ `);
19171
+ process.exit(3);
19172
+ }
19173
+ return (0, import_promises6.readFile)(fullPath, "utf-8");
19174
+ }
19175
+ async function loadAndParse(inputPath) {
19176
+ const content = await readSourceFile(inputPath);
19177
+ const result = parseWorldModel(content);
19178
+ if (!result.model) {
19179
+ process.stderr.write(`${RED}Failed to parse ${inputPath}${RESET2}
19180
+ `);
19181
+ for (const issue of result.issues) {
19182
+ process.stderr.write(formatIssue(issue) + "\n");
19183
+ }
19184
+ process.exit(1);
19185
+ }
19186
+ return { model: result.model, issues: result.issues };
19187
+ }
19188
+ async function cmdInit(argv) {
19189
+ const args = parseArgs26(argv);
19190
+ if (args.help) {
19191
+ process.stdout.write(
19192
+ 'neuroverse worldmodel init \u2014 Scaffold a new .worldmodel.md template\n\nOptions:\n --name <name> Model name (default: "My Behavioral Model")\n --output <path> Output path (default: ./model.worldmodel.md)\n'
19193
+ );
19194
+ return;
19195
+ }
19196
+ const modelName = args.name || "My Behavioral Model";
19197
+ const outputPath = (0, import_path12.resolve)(
19198
+ args.output || `./${toFileName(modelName)}.worldmodel.md`
19199
+ );
19200
+ if ((0, import_fs11.existsSync)(outputPath)) {
19201
+ process.stderr.write(`File already exists: ${outputPath}
19202
+ `);
19203
+ process.stderr.write("Use --output to specify a different path.\n");
19204
+ process.exit(1);
19205
+ }
19206
+ const template = generateScaffold(modelName);
19207
+ const dir = (0, import_path12.dirname)(outputPath);
19208
+ if (!(0, import_fs11.existsSync)(dir)) {
19209
+ await (0, import_promises6.mkdir)(dir, { recursive: true });
19210
+ }
19211
+ await (0, import_promises6.writeFile)(outputPath, template, "utf-8");
19212
+ process.stderr.write(`${GREEN2}Created${RESET2} ${outputPath}
19213
+ `);
19214
+ process.stderr.write(
19215
+ `${DIM2}Edit the template, then run: neuroverse worldmodel validate ${(0, import_path12.basename)(outputPath)}${RESET2}
19216
+ `
19217
+ );
19218
+ }
19219
+ function toFileName(name) {
19220
+ return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
19221
+ }
19222
+ function generateScaffold(modelName) {
19223
+ return `---
19224
+ name: ${modelName}
19225
+ version: 1.0.0
19226
+ ---
19227
+
19228
+ # Core Model Geometry
19229
+ <!--
19230
+ This section defines the STRUCTURE of your behavioral system.
19231
+
19232
+ You are defining:
19233
+ - what the system is trying to achieve (mission)
19234
+ - the major domains it operates within (2-4 recommended)
19235
+ - the skills inside each domain
19236
+ - the values that govern those skills
19237
+ - what emerges when domains interact
19238
+ - what identity forms when everything is aligned
19239
+
19240
+ Think of this as the "physics" of your system.
19241
+ -->
19242
+
19243
+ ## Mission
19244
+ <!-- What is this system trying to achieve? This is not a slogan \u2014 it is the core aim. -->
19245
+
19246
+ Replace with your mission statement.
19247
+
19248
+ ## Domains
19249
+ <!--
19250
+ Define 2-4 domains. Each domain is a mode of operating.
19251
+ Each domain MUST include:
19252
+ - Skills (what it can do)
19253
+ - Values (how it must behave while doing it)
19254
+
19255
+ Domains are NOT personality traits \u2014 they are capability environments.
19256
+ -->
19257
+
19258
+ ### Domain One
19259
+
19260
+ #### Skills
19261
+ - Replace with a capability
19262
+ - Replace with another capability
19263
+
19264
+ #### Values
19265
+ - Replace with a constraint
19266
+ - Replace with another constraint
19267
+
19268
+ ### Domain Two
19269
+
19270
+ #### Skills
19271
+ - Replace with a capability
19272
+ - Replace with another capability
19273
+
19274
+ #### Values
19275
+ - Replace with a constraint
19276
+ - Replace with another constraint
19277
+
19278
+ ## Overlap Effects
19279
+ <!--
19280
+ Define what emerges when TWO domains interact well.
19281
+
19282
+ Format:
19283
+ - Domain A + Domain B = Emergent State
19284
+
19285
+ These are NOT enforced rules.
19286
+ These are INTERPRETIVE STATES used downstream.
19287
+
19288
+ They answer:
19289
+ "What does it feel like / look like when these are working together?"
19290
+ -->
19291
+
19292
+ - Domain One + Domain Two = Replace With Emergent State
19293
+
19294
+ ## Center Identity
19295
+ <!--
19296
+ What does the system become when all domains are aligned?
19297
+ This is the CORE IDENTITY of the system.
19298
+ -->
19299
+
19300
+ Replace with center identity name
19301
+
19302
+ # Contextual Modifiers
19303
+ <!--
19304
+ This section defines how BEHAVIOR IS INTERPRETED differently depending on context.
19305
+
19306
+ These do NOT define truth.
19307
+ They define how meaning changes depending on:
19308
+ - who is acting
19309
+ - where behavior occurs
19310
+ - what phase the system is in
19311
+
19312
+ This is what makes the model multidimensional.
19313
+ -->
19314
+
19315
+ ## Authority Layers
19316
+ <!-- Who is acting? -->
19317
+ - founder
19318
+ - maintainer
19319
+ - contributor
19320
+ - agent
19321
+
19322
+ ## Spatial Contexts
19323
+ <!-- Where is behavior happening? -->
19324
+ - planning
19325
+ - execution
19326
+ - deployment
19327
+ - governance
19328
+
19329
+ ## Interpretation Rules
19330
+ <!--
19331
+ How does context change meaning?
19332
+
19333
+ Examples:
19334
+ - ambiguity from a founder carries more risk than ambiguity from a contributor
19335
+ - weak ownership in deployment is more serious than in planning
19336
+ -->
19337
+
19338
+ - Replace with an interpretation rule
19339
+
19340
+ # Evolution Layer
19341
+ <!--
19342
+ This section defines:
19343
+ - what GOOD behavior looks like
19344
+ - what DRIFT looks like
19345
+ - what can be OBSERVED
19346
+ - how decisions should be made
19347
+ - how the model EVOLVES
19348
+
19349
+ This is the EXECUTABLE layer.
19350
+ -->
19351
+
19352
+ ## Aligned Behaviors
19353
+ <!-- What does success look like in action? -->
19354
+ - Replace with an aligned behavior
19355
+
19356
+ ## Drift Behaviors
19357
+ <!-- What does misalignment look like? -->
19358
+ - Replace with a drift behavior
19359
+
19360
+ ## Signals
19361
+ <!--
19362
+ What can be measured or observed?
19363
+
19364
+ Use simple snake_case identifiers:
19365
+ - clarity
19366
+ - ownership
19367
+ - follow_through
19368
+ -->
19369
+
19370
+ - clarity
19371
+ - ownership
19372
+
19373
+ ## Decision Priorities
19374
+ <!--
19375
+ What wins when tradeoffs appear?
19376
+
19377
+ Format:
19378
+ - preferred > secondary
19379
+ -->
19380
+
19381
+ - quality > speed
19382
+
19383
+ ## Evolution Conditions
19384
+ <!--
19385
+ When should the model adapt?
19386
+
19387
+ Examples:
19388
+ - repeated successful behavior outside assumptions should trigger review
19389
+ - persistent drift across scopes should trigger evolution proposal
19390
+ -->
19391
+
19392
+ - Replace with an evolution condition
19393
+ `;
19394
+ }
19395
+ async function cmdValidate(argv) {
19396
+ const args = parseArgs26(argv);
19397
+ if (args.help || !args.inputPath) {
19398
+ process.stdout.write(
19399
+ "neuroverse worldmodel validate <source.worldmodel.md> [--json]\n"
19400
+ );
19401
+ return;
19402
+ }
19403
+ const content = await readSourceFile(args.inputPath);
19404
+ const result = parseWorldModel(content);
19405
+ const errors = result.issues.filter((i) => i.severity === "error");
19406
+ const warnings = result.issues.filter((i) => i.severity === "warning");
19407
+ const infos = result.issues.filter((i) => i.severity === "info");
19408
+ if (args.json) {
19409
+ const summary2 = result.model ? {
19410
+ valid: errors.length === 0,
19411
+ domains: result.model.geometry.domains.length,
19412
+ overlaps: result.model.geometry.overlapEffects.length,
19413
+ signals: result.model.evolution.signals.length,
19414
+ aligned_behaviors: result.model.evolution.alignedBehaviors.length,
19415
+ drift_behaviors: result.model.evolution.driftBehaviors.length,
19416
+ priorities: result.model.evolution.decisionPriorities.length,
19417
+ errors: errors.length,
19418
+ warnings: warnings.length
19419
+ } : { valid: false, errors: errors.length, warnings: warnings.length };
19420
+ process.stdout.write(
19421
+ JSON.stringify({ summary: summary2, issues: result.issues }, null, 2) + "\n"
19422
+ );
19423
+ process.exit(errors.length > 0 ? 1 : 0);
19424
+ return;
19425
+ }
19426
+ if (errors.length === 0) {
19427
+ process.stderr.write(
19428
+ `${GREEN2}Valid${RESET2} ${args.inputPath}
19429
+ `
19430
+ );
19431
+ } else {
19432
+ process.stderr.write(
19433
+ `${RED}Invalid${RESET2} ${args.inputPath}
19434
+ `
19435
+ );
19436
+ }
19437
+ if (result.model) {
19438
+ const m = result.model;
19439
+ process.stderr.write(
19440
+ `${DIM2} Domains: ${m.geometry.domains.length} Overlaps: ${m.geometry.overlapEffects.length} Signals: ${m.evolution.signals.length}${RESET2}
19441
+ `
19442
+ );
19443
+ }
19444
+ if (result.issues.length > 0) {
19445
+ process.stderr.write("\n");
19446
+ for (const issue of result.issues) {
19447
+ process.stderr.write(formatIssue(issue) + "\n");
19448
+ }
19449
+ }
19450
+ process.exit(errors.length > 0 ? 1 : 0);
19451
+ }
19452
+ async function cmdExplain(argv) {
19453
+ const args = parseArgs26(argv);
19454
+ if (args.help || !args.inputPath) {
19455
+ process.stdout.write(
19456
+ "neuroverse worldmodel explain <source.worldmodel.md> [--json]\n"
19457
+ );
19458
+ return;
19459
+ }
19460
+ const { model } = await loadAndParse(args.inputPath);
19461
+ if (args.json) {
19462
+ const output = buildExplainData(model);
19463
+ process.stdout.write(JSON.stringify(output, null, 2) + "\n");
19464
+ return;
19465
+ }
19466
+ const out = process.stdout;
19467
+ out.write(`
19468
+ ${BOLD2}MODEL:${RESET2} ${model.frontmatter.name} (v${model.frontmatter.version})
19469
+
19470
+ `);
19471
+ out.write(`${CYAN2}${BOLD2}CORE MODEL GEOMETRY${RESET2}
19472
+ `);
19473
+ out.write(` ${BOLD2}Mission:${RESET2} ${model.geometry.mission}
19474
+ `);
19475
+ const domainNames = model.geometry.domains.map((d) => d.name).join(", ");
19476
+ out.write(
19477
+ ` ${BOLD2}Domains (${model.geometry.domains.length}):${RESET2} ${domainNames}
19478
+ `
19479
+ );
19480
+ for (const domain of model.geometry.domains) {
19481
+ out.write(`
19482
+ ${MAGENTA2}${domain.name}${RESET2}
19483
+ `);
19484
+ if (domain.skills.length > 0) {
19485
+ out.write(` ${DIM2}Skills:${RESET2} ${domain.skills.join(", ")}
19486
+ `);
19487
+ }
19488
+ if (domain.values.length > 0) {
19489
+ out.write(` ${DIM2}Values:${RESET2} ${domain.values.join(", ")}
19490
+ `);
19491
+ }
19492
+ }
19493
+ if (model.geometry.overlapEffects.length > 0) {
19494
+ out.write(`
19495
+ ${BOLD2}Overlaps (${model.geometry.overlapEffects.length}):${RESET2}
19496
+ `);
19497
+ for (const o of model.geometry.overlapEffects) {
19498
+ out.write(` ${o.domainA} + ${o.domainB} = ${GREEN2}${o.effect}${RESET2}
19499
+ `);
19500
+ }
19501
+ }
19502
+ if (model.geometry.centerIdentity) {
19503
+ out.write(
19504
+ `
19505
+ ${BOLD2}Center Identity:${RESET2} ${GREEN2}${model.geometry.centerIdentity}${RESET2}
19506
+ `
19507
+ );
19508
+ }
19509
+ out.write(`
19510
+ ${CYAN2}${BOLD2}CONTEXTUAL MODIFIERS${RESET2}
19511
+ `);
19512
+ if (model.modifiers.authorityLayers.length > 0) {
19513
+ out.write(
19514
+ ` ${BOLD2}Authority:${RESET2} ${model.modifiers.authorityLayers.join(", ")}
19515
+ `
19516
+ );
19517
+ }
19518
+ if (model.modifiers.spatialContexts.length > 0) {
19519
+ out.write(
19520
+ ` ${BOLD2}Spatial:${RESET2} ${model.modifiers.spatialContexts.join(", ")}
19521
+ `
19522
+ );
19523
+ }
19524
+ if (model.modifiers.interpretationRules.length > 0) {
19525
+ out.write(
19526
+ ` ${BOLD2}Interpretation Rules:${RESET2} ${model.modifiers.interpretationRules.length} defined
19527
+ `
19528
+ );
19529
+ for (const rule of model.modifiers.interpretationRules) {
19530
+ out.write(` ${DIM2}- ${rule}${RESET2}
19531
+ `);
19532
+ }
19533
+ }
19534
+ out.write(`
19535
+ ${CYAN2}${BOLD2}EVOLUTION LAYER${RESET2}
19536
+ `);
19537
+ out.write(
19538
+ ` Aligned behaviors: ${model.evolution.alignedBehaviors.length} defined
19539
+ `
19540
+ );
19541
+ out.write(
19542
+ ` Drift behaviors: ${model.evolution.driftBehaviors.length} defined
19543
+ `
19544
+ );
19545
+ out.write(
19546
+ ` Signals: ${model.evolution.signals.length} tracked
19547
+ `
19548
+ );
19549
+ out.write(
19550
+ ` Decision priorities: ${model.evolution.decisionPriorities.length} defined
19551
+ `
19552
+ );
19553
+ out.write(
19554
+ ` Evolution conditions: ${model.evolution.evolutionConditions.length} defined
19555
+ `
19556
+ );
19557
+ out.write(`
19558
+ ${DIM2}---${RESET2}
19559
+ `);
19560
+ const overlapEffects = model.geometry.overlapEffects.map((o) => o.effect).join(", ");
19561
+ out.write(
19562
+ `
19563
+ This model operates across ${model.geometry.domains.length} domains governed by embedded values.
19564
+ `
19565
+ );
19566
+ if (overlapEffects) {
19567
+ out.write(
19568
+ `It produces ${GREEN2}${overlapEffects}${RESET2} when domains interact well.
19569
+ `
19570
+ );
19571
+ }
19572
+ if (model.evolution.driftBehaviors.length > 0) {
19573
+ const driftSample = model.evolution.driftBehaviors.slice(0, 3).join("; ");
19574
+ out.write(`Drift shows as: ${YELLOW2}${driftSample}${RESET2}.
19575
+ `);
19576
+ }
19577
+ if (model.geometry.centerIdentity) {
19578
+ out.write(
19579
+ `When aligned, the system becomes: ${GREEN2}${BOLD2}${model.geometry.centerIdentity}${RESET2}.
19580
+ `
19581
+ );
19582
+ }
19583
+ out.write("\n");
19584
+ }
19585
+ function buildExplainData(model) {
19586
+ return {
19587
+ name: model.frontmatter.name,
19588
+ version: model.frontmatter.version,
19589
+ model_id: model.frontmatter.model_id,
19590
+ geometry: {
19591
+ mission: model.geometry.mission,
19592
+ domains: model.geometry.domains.map((d) => ({
19593
+ name: d.name,
19594
+ skills: d.skills,
19595
+ values: d.values
19596
+ })),
19597
+ overlaps: model.geometry.overlapEffects.map((o) => ({
19598
+ domainA: o.domainA,
19599
+ domainB: o.domainB,
19600
+ effect: o.effect
19601
+ })),
19602
+ centerIdentity: model.geometry.centerIdentity
19603
+ },
19604
+ modifiers: {
19605
+ authority: model.modifiers.authorityLayers,
19606
+ spatial: model.modifiers.spatialContexts,
19607
+ interpretationRules: model.modifiers.interpretationRules.length
19608
+ },
19609
+ evolution: {
19610
+ alignedBehaviors: model.evolution.alignedBehaviors.length,
19611
+ driftBehaviors: model.evolution.driftBehaviors.length,
19612
+ signals: model.evolution.signals,
19613
+ priorities: model.evolution.decisionPriorities.length,
19614
+ evolutionConditions: model.evolution.evolutionConditions.length
19615
+ }
19616
+ };
19617
+ }
19618
+ async function cmdBuild(argv) {
19619
+ const args = parseArgs26(argv);
19620
+ if (args.help || !args.inputPath) {
19621
+ process.stdout.write(
19622
+ "neuroverse worldmodel build <source.worldmodel.md> [--output <dir>] [--json]\n"
19623
+ );
19624
+ return;
19625
+ }
19626
+ const { model, issues } = await loadAndParse(args.inputPath);
19627
+ const errors = issues.filter((i) => i.severity === "error");
19628
+ if (errors.length > 0) {
19629
+ process.stderr.write(`${RED}Cannot build \u2014 validation errors:${RESET2}
19630
+ `);
19631
+ for (const issue of errors) {
19632
+ process.stderr.write(formatIssue(issue) + "\n");
19633
+ }
19634
+ process.exit(1);
19635
+ }
19636
+ const warnings = issues.filter((i) => i.severity === "warning");
19637
+ if (warnings.length > 0) {
19638
+ process.stderr.write(`${YELLOW2}Warnings:${RESET2}
19639
+ `);
19640
+ for (const issue of warnings) {
19641
+ process.stderr.write(formatIssue(issue) + "\n");
19642
+ }
19643
+ process.stderr.write("\n");
19644
+ }
19645
+ const output = compileWorldModel(model);
19646
+ const outputDir = (0, import_path12.resolve)(
19647
+ args.output || `.neuroverse/worldmodels/${model.frontmatter.model_id}/`
19648
+ );
19649
+ if (!(0, import_fs11.existsSync)(outputDir)) {
19650
+ await (0, import_promises6.mkdir)(outputDir, { recursive: true });
19651
+ }
19652
+ const worldPath = (0, import_path12.join)(outputDir, `${model.frontmatter.model_id}.nv-world.md`);
19653
+ const signalsPath = (0, import_path12.join)(outputDir, "signals.json");
19654
+ const overlapsPath = (0, import_path12.join)(outputDir, "overlaps.json");
19655
+ const contextsPath = (0, import_path12.join)(outputDir, "contexts.json");
19656
+ const lensesPath = (0, import_path12.join)(outputDir, "lenses.json");
19657
+ await Promise.all([
19658
+ (0, import_promises6.writeFile)(worldPath, output.worldMarkdown, "utf-8"),
19659
+ (0, import_promises6.writeFile)(signalsPath, JSON.stringify(output.signalSchema, null, 2) + "\n", "utf-8"),
19660
+ (0, import_promises6.writeFile)(overlapsPath, JSON.stringify(output.overlapMap, null, 2) + "\n", "utf-8"),
19661
+ (0, import_promises6.writeFile)(contextsPath, JSON.stringify(output.contextsConfig, null, 2) + "\n", "utf-8"),
19662
+ (0, import_promises6.writeFile)(lensesPath, JSON.stringify(output.lensSuggestions, null, 2) + "\n", "utf-8")
19663
+ ]);
19664
+ if (args.json) {
19665
+ process.stdout.write(
19666
+ JSON.stringify(
19667
+ {
19668
+ success: true,
19669
+ outputDir,
19670
+ files: {
19671
+ world: worldPath,
19672
+ signals: signalsPath,
19673
+ overlaps: overlapsPath,
19674
+ contexts: contextsPath,
19675
+ lenses: lensesPath
19676
+ }
19677
+ },
19678
+ null,
19679
+ 2
19680
+ ) + "\n"
19681
+ );
19682
+ } else {
19683
+ process.stderr.write(`${GREEN2}Built${RESET2} ${model.frontmatter.name}
19684
+
19685
+ `);
19686
+ process.stderr.write(` ${BOLD2}Output:${RESET2} ${outputDir}/
19687
+ `);
19688
+ process.stderr.write(` ${(0, import_path12.basename)(worldPath)}${DIM2} \u2014 executable world${RESET2}
19689
+ `);
19690
+ process.stderr.write(` signals.json${DIM2} \u2014 signal schema${RESET2}
19691
+ `);
19692
+ process.stderr.write(` overlaps.json${DIM2} \u2014 overlap map${RESET2}
19693
+ `);
19694
+ process.stderr.write(` contexts.json${DIM2} \u2014 contextual modifiers${RESET2}
19695
+ `);
19696
+ process.stderr.write(` lenses.json${DIM2} \u2014 lens suggestions${RESET2}
19697
+
19698
+ `);
19699
+ const ruleCount = model.evolution.driftBehaviors.length + model.evolution.alignedBehaviors.length + model.evolution.decisionPriorities.length;
19700
+ const invariantCount = model.geometry.domains.reduce(
19701
+ (sum, d) => sum + d.values.length,
19702
+ 0
19703
+ );
19704
+ process.stderr.write(
19705
+ ` ${DIM2}${invariantCount} invariants, ${model.evolution.signals.length + 1} state vars, ${ruleCount} rules, 5 gates, ${model.geometry.overlapEffects.length} lenses${RESET2}
19706
+ `
19707
+ );
19708
+ process.stderr.write(
19709
+ `
19710
+ ${DIM2}Next: neuroverse bootstrap --input ${worldPath} --output ${outputDir}${RESET2}
19711
+ `
19712
+ );
19713
+ }
19714
+ }
19715
+ async function cmdEmitWorld(argv) {
19716
+ const args = parseArgs26(argv);
19717
+ if (args.help || !args.inputPath) {
19718
+ process.stdout.write("neuroverse worldmodel emit-world <source.worldmodel.md>\n");
19719
+ return;
19720
+ }
19721
+ const { model } = await loadAndParse(args.inputPath);
19722
+ const markdown = emitWorldMarkdown(model);
19723
+ if (args.output) {
19724
+ const dir = (0, import_path12.dirname)((0, import_path12.resolve)(args.output));
19725
+ if (!(0, import_fs11.existsSync)(dir)) await (0, import_promises6.mkdir)(dir, { recursive: true });
19726
+ await (0, import_promises6.writeFile)((0, import_path12.resolve)(args.output), markdown, "utf-8");
19727
+ process.stderr.write(`${GREEN2}Written${RESET2} ${args.output}
19728
+ `);
19729
+ } else {
19730
+ process.stdout.write(markdown);
19731
+ }
19732
+ }
19733
+ async function cmdEmitSignals(argv) {
19734
+ const args = parseArgs26(argv);
19735
+ if (args.help || !args.inputPath) {
19736
+ process.stdout.write(
19737
+ "neuroverse worldmodel emit-signals <source.worldmodel.md> [--json]\n"
19738
+ );
19739
+ return;
19740
+ }
19741
+ const { model } = await loadAndParse(args.inputPath);
19742
+ const schema = emitSignalSchema(model);
19743
+ process.stdout.write(JSON.stringify(schema, null, 2) + "\n");
19744
+ }
19745
+ async function cmdEmitLenses(argv) {
19746
+ const args = parseArgs26(argv);
19747
+ if (args.help || !args.inputPath) {
19748
+ process.stdout.write(
19749
+ "neuroverse worldmodel emit-lenses <source.worldmodel.md> [--json]\n"
19750
+ );
19751
+ return;
19752
+ }
19753
+ const { model } = await loadAndParse(args.inputPath);
19754
+ const lenses = emitLensSuggestions(model);
19755
+ process.stdout.write(JSON.stringify(lenses, null, 2) + "\n");
19756
+ }
19757
+ async function cmdEmitContexts(argv) {
19758
+ const args = parseArgs26(argv);
19759
+ if (args.help || !args.inputPath) {
19760
+ process.stdout.write(
19761
+ "neuroverse worldmodel emit-contexts <source.worldmodel.md> [--json]\n"
19762
+ );
19763
+ return;
19764
+ }
19765
+ const { model } = await loadAndParse(args.inputPath);
19766
+ const contexts = emitContextsConfig(model);
19767
+ process.stdout.write(JSON.stringify(contexts, null, 2) + "\n");
19768
+ }
19769
+ async function cmdEmitOverlaps(argv) {
19770
+ const args = parseArgs26(argv);
19771
+ if (args.help || !args.inputPath) {
19772
+ process.stdout.write(
19773
+ "neuroverse worldmodel emit-overlaps <source.worldmodel.md> [--json]\n"
19774
+ );
19775
+ return;
19776
+ }
19777
+ const { model } = await loadAndParse(args.inputPath);
19778
+ const overlaps = emitOverlapMap(model);
19779
+ process.stdout.write(JSON.stringify(overlaps, null, 2) + "\n");
19780
+ }
19781
+ async function main33(argv = process.argv.slice(2)) {
19782
+ const subcommand = argv[0] ?? "";
19783
+ const subArgs = argv.slice(1);
19784
+ switch (subcommand) {
19785
+ case "init":
19786
+ return cmdInit(subArgs);
19787
+ case "validate":
19788
+ return cmdValidate(subArgs);
19789
+ case "explain":
19790
+ return cmdExplain(subArgs);
19791
+ case "build":
19792
+ return cmdBuild(subArgs);
19793
+ case "emit-world":
19794
+ return cmdEmitWorld(subArgs);
19795
+ case "emit-signals":
19796
+ return cmdEmitSignals(subArgs);
19797
+ case "emit-lenses":
19798
+ return cmdEmitLenses(subArgs);
19799
+ case "emit-contexts":
19800
+ return cmdEmitContexts(subArgs);
19801
+ case "emit-overlaps":
19802
+ return cmdEmitOverlaps(subArgs);
19803
+ case "--help":
19804
+ case "-h":
19805
+ case "help":
19806
+ case "":
19807
+ process.stdout.write(USAGE9 + "\n");
19808
+ break;
19809
+ default:
19810
+ process.stderr.write(`Unknown worldmodel command: "${subcommand}"
19811
+
19812
+ `);
19813
+ process.stdout.write(USAGE9 + "\n");
19814
+ process.exit(1);
19815
+ }
19816
+ }
19817
+ var import_promises6, import_fs11, import_path12, BOLD2, DIM2, CYAN2, GREEN2, YELLOW2, RED, MAGENTA2, RESET2, USAGE9;
19818
+ var init_worldmodel = __esm({
19819
+ "src/cli/worldmodel.ts"() {
19820
+ "use strict";
19821
+ import_promises6 = require("fs/promises");
19822
+ import_fs11 = require("fs");
19823
+ import_path12 = require("path");
19824
+ init_worldmodel_parser();
19825
+ init_worldmodel_compiler();
19826
+ BOLD2 = "\x1B[1m";
19827
+ DIM2 = "\x1B[2m";
19828
+ CYAN2 = "\x1B[36m";
19829
+ GREEN2 = "\x1B[32m";
19830
+ YELLOW2 = "\x1B[33m";
19831
+ RED = "\x1B[31m";
19832
+ MAGENTA2 = "\x1B[35m";
19833
+ RESET2 = "\x1B[0m";
19834
+ USAGE9 = `
19835
+ neuroverse worldmodel \u2014 Behavioral world model toolkit
19836
+
19837
+ ${BOLD2}This file defines how a system behaves, how that behavior
19838
+ is interpreted, and how it evolves over time.${RESET2}
19839
+
19840
+ Commands:
19841
+ init Scaffold a new .worldmodel.md template
19842
+ validate Check structure and completeness
19843
+ explain Human-readable model summary
19844
+ build Compile to .nv-world.md + signals + overlaps + contexts + lenses
19845
+ emit-world Emit compiled .nv-world.md to stdout
19846
+ emit-signals Emit signal schema JSON to stdout
19847
+ emit-lenses Emit lens suggestions JSON to stdout
19848
+ emit-contexts Emit contextual modifiers JSON to stdout
19849
+ emit-overlaps Emit overlap map JSON to stdout
19850
+
19851
+ Usage:
19852
+ neuroverse worldmodel init [--name "Name"] [--output path]
19853
+ neuroverse worldmodel validate <source.worldmodel.md> [--json]
19854
+ neuroverse worldmodel explain <source.worldmodel.md> [--json]
19855
+ neuroverse worldmodel build <source.worldmodel.md> [--output <dir>]
19856
+ neuroverse worldmodel emit-world <source.worldmodel.md>
19857
+ neuroverse worldmodel emit-signals <source.worldmodel.md> [--json]
19858
+ neuroverse worldmodel emit-lenses <source.worldmodel.md> [--json]
19859
+ neuroverse worldmodel emit-contexts <source.worldmodel.md> [--json]
19860
+ neuroverse worldmodel emit-overlaps <source.worldmodel.md> [--json]
19861
+
19862
+ Examples:
19863
+ neuroverse worldmodel init --name "Auki Vanguard"
19864
+ neuroverse worldmodel build ./auki-vanguard.worldmodel.md --output ./world/
19865
+ neuroverse worldmodel explain ./auki-vanguard.worldmodel.md
19866
+ `.trim();
19867
+ }
19868
+ });
19869
+
19870
+ // src/cli/neuroverse.ts
19871
+ var USAGE10 = `
19872
+ neuroverse \u2014 Turn ideas into worlds.
19873
+
19874
+ Commands:
19875
+ add Add a guard, rule, or invariant to a world
19876
+ build Build a world from markdown (derive + compile in one step)
19877
+ explain Human-readable summary of a compiled world
19878
+ simulate Step-by-step state evolution
19879
+ improve Actionable suggestions for strengthening a world
19880
+ init Scaffold a new .nv-world.md template
19881
+ init-world Generate a governed world from a template (e.g., autoresearch)
19882
+ infer-world Scan a repo and infer a governance world from its structure
19883
+ validate Static analysis on world files
19884
+ guard Runtime governance evaluation (stdin \u2192 stdout)
19885
+ test Run guard simulation suite against a world
19886
+ redteam Adversarial containment testing (agent escape detection)
19887
+ demo Interactive governance demo (flow viz + simulation)
19888
+ doctor Environment sanity check
19889
+ playground Interactive web demo (opens in browser)
19890
+ plan Plan enforcement (compile, check, status, advance, derive)
19891
+ run Governed runtime (pipe mode or interactive chat)
19892
+ mcp MCP governance server (for Claude, Cursor, etc.)
19893
+ worlds List available worlds (alias for world list)
19894
+ trace Runtime action audit log
19895
+ impact Counterfactual governance impact report
19896
+ decision-flow Intent \u2192 Rule \u2192 Outcome visualization (behavioral governance)
19897
+ equity-penalties Fortune 500 equity PENALIZE/REWARD simulation
19898
+ world World management (status, diff, snapshot, rollback)
19899
+ keygen Generate Ed25519 signing keypair
19900
+ sign Sign a world artifact (cryptographic manifest)
19901
+ verify Verify a signed world artifact
19902
+ migrate Migrate world schema between versions
19903
+ derive AI-assisted synthesis of .nv-world.md from markdown
19904
+ bootstrap Compile .nv-world.md \u2192 world JSON files
19905
+ configure-ai Configure AI provider credentials
19906
+ configure-world Interactive wizard: define your system in plain language
19907
+ lens Manage behavioral lenses (list, preview, compile, compare, add)
19908
+ worldmodel Behavioral world model builder (init, validate, build, explain)
19909
+
19910
+ Usage:
19911
+ neuroverse add "Block dairy orders" --world <dir>
19912
+ neuroverse add guard --world <dir> --label "Block dairy" --pattern "*dairy*"
19913
+ neuroverse add rule --world <dir> --label "Cost overrun" --trigger "cost > 100" --effect "viability *= 0.5"
19914
+ neuroverse add invariant --world <dir> --label "Budget must never exceed 1000"
19915
+ neuroverse build <input.md> [--output <dir>]
19916
+ neuroverse explain <world-path-or-id> [--json]
19917
+ neuroverse simulate <world-path-or-id> [--steps N] [--set key=value] [--profile name]
19918
+ neuroverse improve <world-path-or-id> [--json]
19919
+ neuroverse init [--name "World Name"] [--output path]
19920
+ neuroverse init-world autoresearch [--context "topic"] [--dataset "name"] [--goal "goal"]
19921
+ neuroverse infer-world ./repo [--output path] [--json] [--dry-run]
19922
+ neuroverse validate --world <dir> [--format full|summary|findings]
19923
+ neuroverse guard --world <dir> [--trace] [--level basic|standard|strict]
19924
+ neuroverse test --world <dir> [--fuzz] [--count N]
19925
+ neuroverse redteam --world <dir> [--level basic|standard|strict]
19926
+ neuroverse demo [--world social-media] [--port 3456] [--no-browser]
19927
+ neuroverse doctor [--world <dir>] [--json]
19928
+ neuroverse playground --world <dir> [--port 4242]
19929
+ neuroverse trace [--log <path>] [--summary] [--filter BLOCK] [--last 20]
19930
+ neuroverse impact [--log <path>] [--json]
19931
+ neuroverse world status <path>
19932
+ neuroverse world diff <path1> <path2>
19933
+ neuroverse world snapshot <path>
19934
+ neuroverse world rollback <path>
19935
+ neuroverse derive --input <path> [--output <path>] [--dry-run]
19936
+ neuroverse bootstrap --input <.md> --output <dir> [--validate]
19937
+ neuroverse decision-flow [--log <path>] [--json]
19938
+ neuroverse equity-penalties --world <dir> [--agents N] [--rounds N] [--json]
19939
+ neuroverse configure-ai --provider <name> --model <name> --api-key <key>
19940
+ neuroverse configure-world [--output <dir>]
19941
+ neuroverse keygen [--output <dir>] [--name <name>]
19942
+ neuroverse sign --world <dir> [--key <path>]
19943
+ neuroverse verify --world <dir> [--key <path>]
19944
+ neuroverse migrate --world <dir> [--dry-run] [--backup]
19945
+ neuroverse lens list [--world <dir>] [--json]
19946
+ neuroverse lens preview <id> [--world <dir>]
19947
+ neuroverse lens compile <id,...> [--world <dir>] [--role <role>] [--json]
19948
+ neuroverse lens compare --input "text" --lenses stoic,coach,calm
19949
+ neuroverse lens add --world <dir> --name "Name" --tagline "..." [options]
19950
+ neuroverse worldmodel init --name "My Model"
19951
+ neuroverse worldmodel build ./model.worldmodel.md --output ./world/
19952
+ neuroverse worldmodel explain ./model.worldmodel.md
19953
+
19954
+ Examples:
19955
+ neuroverse build horror-notes.md
19956
+ neuroverse explain inherited_silence
19957
+ neuroverse simulate inherited_silence --steps 5
19958
+ neuroverse improve inherited_silence
19959
+ neuroverse build ./docs/ --output ./my-world/
19960
+ neuroverse init --name "Customer Service Governance"
19961
+ neuroverse validate --world ./world/ --format summary
19962
+ echo '{"intent":"delete user data"}' | neuroverse guard --world ./world/ --trace
19963
+ neuroverse plan compile plan.md --output plan.json
19964
+ echo '{"intent":"write blog"}' | neuroverse plan check --plan plan.json
19965
+ neuroverse plan status --plan plan.json
19966
+ neuroverse plan advance write_blog_post --plan plan.json
19967
+ neuroverse plan derive plan.md --output ./derived-world/
19968
+ neuroverse run --pipe --world ./world/ --plan plan.json
19969
+ neuroverse run --interactive --world ./world/ --provider openai
19970
+ neuroverse mcp --world ./world/ --plan plan.json
19971
+ neuroverse test --world ./world/ --fuzz --count 50
19972
+ neuroverse redteam --world ./world/ --level strict
19973
+ neuroverse doctor
19974
+ neuroverse playground --world ./world/
19975
+ `.trim();
19976
+ async function main34() {
19977
+ const args = process.argv.slice(2);
19978
+ const command = args[0];
19979
+ const subArgs = args.slice(1);
19980
+ switch (command) {
19981
+ case "add": {
19982
+ const { main: addMain } = await Promise.resolve().then(() => (init_add(), add_exports));
19983
+ return addMain(subArgs);
19984
+ }
19985
+ case "build": {
19986
+ const { main: buildMain } = await Promise.resolve().then(() => (init_build(), build_exports));
19987
+ return buildMain(subArgs);
19988
+ }
19989
+ case "explain": {
19990
+ const { main: explainMain } = await Promise.resolve().then(() => (init_explain(), explain_exports));
19991
+ return explainMain(subArgs);
19992
+ }
19993
+ case "simulate": {
19994
+ const { main: simulateMain } = await Promise.resolve().then(() => (init_simulate(), simulate_exports));
19995
+ return simulateMain(subArgs);
19996
+ }
19997
+ case "improve": {
19998
+ const { main: improveMain } = await Promise.resolve().then(() => (init_improve(), improve_exports));
19999
+ return improveMain(subArgs);
20000
+ }
20001
+ case "init": {
20002
+ const { main: initMain } = await Promise.resolve().then(() => (init_init(), init_exports));
20003
+ return initMain(subArgs);
20004
+ }
20005
+ case "init-world": {
20006
+ const { main: initWorldMain } = await Promise.resolve().then(() => (init_init_world(), init_world_exports));
20007
+ return initWorldMain(subArgs);
20008
+ }
20009
+ case "infer-world": {
20010
+ const { main: inferWorldMain } = await Promise.resolve().then(() => (init_infer_world(), infer_world_exports));
20011
+ return inferWorldMain(subArgs);
17183
20012
  }
17184
20013
  case "bootstrap": {
17185
20014
  const { main: bootstrapMain } = await Promise.resolve().then(() => (init_bootstrap(), bootstrap_exports));
@@ -17257,6 +20086,22 @@ async function main29() {
17257
20086
  const { main: equityPenaltiesMain } = await Promise.resolve().then(() => (init_equity_penalties(), equity_penalties_exports));
17258
20087
  return equityPenaltiesMain(subArgs);
17259
20088
  }
20089
+ case "keygen": {
20090
+ const { main: keygenMain } = await Promise.resolve().then(() => (init_keygen(), keygen_exports));
20091
+ return keygenMain(subArgs);
20092
+ }
20093
+ case "sign": {
20094
+ const { main: signMain } = await Promise.resolve().then(() => (init_sign(), sign_exports));
20095
+ return signMain(subArgs);
20096
+ }
20097
+ case "verify": {
20098
+ const { main: verifyMain } = await Promise.resolve().then(() => (init_verify(), verify_exports));
20099
+ return verifyMain(subArgs);
20100
+ }
20101
+ case "migrate": {
20102
+ const { main: migrateMain } = await Promise.resolve().then(() => (init_migrate(), migrate_exports));
20103
+ return migrateMain(subArgs);
20104
+ }
17260
20105
  case "configure-ai": {
17261
20106
  const { main: configureAiMain } = await Promise.resolve().then(() => (init_configure_ai(), configure_ai_exports));
17262
20107
  return configureAiMain(subArgs);
@@ -17269,11 +20114,15 @@ async function main29() {
17269
20114
  const { main: lensMain } = await Promise.resolve().then(() => (init_lens2(), lens_exports));
17270
20115
  return lensMain(subArgs);
17271
20116
  }
20117
+ case "worldmodel": {
20118
+ const { main: worldmodelMain } = await Promise.resolve().then(() => (init_worldmodel(), worldmodel_exports));
20119
+ return worldmodelMain(subArgs);
20120
+ }
17272
20121
  case "--help":
17273
20122
  case "-h":
17274
20123
  case "help":
17275
20124
  case void 0: {
17276
- process.stdout.write(USAGE5 + "\n");
20125
+ process.stdout.write(USAGE10 + "\n");
17277
20126
  process.exit(0);
17278
20127
  break;
17279
20128
  }
@@ -17281,12 +20130,12 @@ async function main29() {
17281
20130
  process.stderr.write(`Unknown command: "${command}"
17282
20131
 
17283
20132
  `);
17284
- process.stdout.write(USAGE5 + "\n");
20133
+ process.stdout.write(USAGE10 + "\n");
17285
20134
  process.exit(1);
17286
20135
  }
17287
20136
  }
17288
20137
  }
17289
- main29().catch((e) => {
20138
+ main34().catch((e) => {
17290
20139
  process.stderr.write(`Fatal: ${e}
17291
20140
  `);
17292
20141
  process.exit(3);