@neuroverseos/governance 0.5.1 → 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 (69) hide show
  1. package/README.md +55 -0
  2. package/dist/adapters/autoresearch.js +2 -2
  3. package/dist/adapters/deep-agents.js +2 -2
  4. package/dist/adapters/express.js +2 -2
  5. package/dist/adapters/github.js +2 -2
  6. package/dist/adapters/index.js +8 -8
  7. package/dist/adapters/langchain.js +2 -2
  8. package/dist/adapters/mentraos.js +2 -2
  9. package/dist/adapters/openai.js +2 -2
  10. package/dist/adapters/openclaw.js +2 -2
  11. package/dist/{add-JP7TC2K3.js → add-XSANI3FK.js} +1 -1
  12. package/dist/{build-THUEYMVT.js → build-UTVDGHB3.js} +4 -4
  13. package/dist/{chunk-TZBERHFM.js → chunk-7FL3U7Z5.js} +1 -1
  14. package/dist/{chunk-FGOSKQDE.js → chunk-A2UZTLRV.js} +1 -1
  15. package/dist/{chunk-R23T5SZG.js → chunk-B3IIPTY3.js} +1 -1
  16. package/dist/chunk-EQR7BGFN.js +337 -0
  17. package/dist/{chunk-LAKUB76X.js → chunk-FDPPZLSQ.js} +1 -1
  18. package/dist/{chunk-UZBW44KD.js → chunk-FKQCPRKI.js} +1 -1
  19. package/dist/{chunk-XPMZB46F.js → chunk-FS2UUJJO.js} +3 -3
  20. package/dist/{chunk-6UPEUMJ2.js → chunk-HDNDL6D5.js} +1 -1
  21. package/dist/{chunk-7UU7V3AD.js → chunk-IOVXB6QN.js} +1 -1
  22. package/dist/{chunk-EK77AJAH.js → chunk-OTZU76DH.js} +1 -1
  23. package/dist/{chunk-5RAQ5DZW.js → chunk-T6GMRZWC.js} +1 -1
  24. package/dist/{chunk-RF2L5SYG.js → chunk-TIXVEPS2.js} +1 -1
  25. package/dist/{chunk-TL4DLMMW.js → chunk-TJ5L2UTE.js} +1 -1
  26. package/dist/chunk-UGTNKTHS.js +542 -0
  27. package/dist/cli/neuroverse.cjs +1987 -303
  28. package/dist/cli/neuroverse.js +27 -19
  29. package/dist/cli/plan.js +1 -1
  30. package/dist/cli/run.js +2 -2
  31. package/dist/cli/worldmodel.cjs +1624 -0
  32. package/dist/cli/worldmodel.d.cts +24 -0
  33. package/dist/cli/worldmodel.d.ts +24 -0
  34. package/dist/cli/worldmodel.js +742 -0
  35. package/dist/{demo-N5K4VXJW.js → demo-6W3YXLAX.js} +2 -2
  36. package/dist/{derive-5LOMN7GO.js → derive-42IJW7JI.js} +3 -3
  37. package/dist/engine/worldmodel-compiler.cjs +366 -0
  38. package/dist/engine/worldmodel-compiler.d.cts +46 -0
  39. package/dist/engine/worldmodel-compiler.d.ts +46 -0
  40. package/dist/engine/worldmodel-compiler.js +17 -0
  41. package/dist/engine/worldmodel-parser.cjs +566 -0
  42. package/dist/engine/worldmodel-parser.d.cts +22 -0
  43. package/dist/engine/worldmodel-parser.d.ts +22 -0
  44. package/dist/engine/worldmodel-parser.js +7 -0
  45. package/dist/{equity-penalties-PYCJ3Q4U.js → equity-penalties-CCO3GVHS.js} +1 -1
  46. package/dist/{explain-42TVC3QD.js → explain-HDFN4ION.js} +1 -1
  47. package/dist/{guard-TPYDFG6V.js → guard-IHJEKHL2.js} +1 -1
  48. package/dist/{improve-HLZGJ54Z.js → improve-LRORRYEX.js} +1 -1
  49. package/dist/index.js +48 -48
  50. package/dist/{lens-NFGZHD76.js → lens-TLDZQXBI.js} +61 -2
  51. package/dist/{mcp-server-5XXNG6VC.js → mcp-server-CKYBHXWK.js} +2 -2
  52. package/dist/{playground-2EU5CFIH.js → playground-3TTBN7XD.js} +1 -1
  53. package/dist/{redteam-VK6OVHAE.js → redteam-W644UMWN.js} +1 -1
  54. package/dist/{session-NGA4DUPL.js → session-FMAROEIE.js} +2 -2
  55. package/dist/{simulate-4YNOBMES.js → simulate-VT437EEL.js} +1 -1
  56. package/dist/{test-HDBPMQTG.js → test-XDB2DH3L.js} +1 -1
  57. package/dist/{validate-6MFQZ2EG.js → validate-M52DX22Y.js} +1 -1
  58. package/dist/{world-H5WVURKU.js → world-O4HTQPDP.js} +1 -1
  59. package/dist/{world-loader-J47PCPDZ.js → world-loader-YTYFOP7D.js} +1 -1
  60. package/dist/worldmodel-contract-BPGhiuW5.d.cts +221 -0
  61. package/dist/worldmodel-contract-BPGhiuW5.d.ts +221 -0
  62. package/dist/worlds/auki-vanguard.worldmodel.md +116 -0
  63. package/dist/worlds/behavioral-demo.nv-world.md +130 -0
  64. package/dist/worlds/neuroverse-governance.worldmodel.md +115 -0
  65. package/package.json +2 -2
  66. package/dist/{bootstrap-IP5QMC3Q.js → bootstrap-2OW5ZLBL.js} +3 -3
  67. package/dist/{chunk-QZ666FCV.js → chunk-735Z3HA4.js} +3 -3
  68. /package/dist/{chunk-EQUAWNXW.js → chunk-I4RTIMLX.js} +0 -0
  69. /package/dist/{doctor-Q5APJOTS.js → doctor-XEMLO6UA.js} +0 -0
@@ -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: join13 } = await import("path");
2004
+ const { readFile: readFile4 } = await import("fs/promises");
2005
+ const { join: join14 } = await import("path");
2006
2006
  const { readdirSync: readdirSync6 } = await import("fs");
2007
2007
  async function readJson(filename) {
2008
- const filePath = join13(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 = join13(dirPath, "rules");
2038
+ const rulesDir = join14(dirPath, "rules");
2039
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(join13(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: join13, dirname: dirname3 } = await import("path");
2097
- const { existsSync: existsSync9 } = 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 = join13(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
- join13(packageRoot, "dist", "worlds", filename),
2111
- join13(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 (existsSync9(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: join13 } = await import("path");
2145
- const guardsPath = join13(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,11 +2181,11 @@ 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: join13 } = await import("path");
2184
+ const { readFile: readFile4, writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
2185
+ const { join: join14 } = await import("path");
2186
2186
  const { readdirSync: readdirSync6 } = await import("fs");
2187
- const rulesDir = join13(worldDir, "rules");
2188
- await mkdir2(rulesDir, { recursive: true });
2187
+ const rulesDir = join14(worldDir, "rules");
2188
+ await mkdir3(rulesDir, { recursive: true });
2189
2189
  let nextNum = 1;
2190
2190
  try {
2191
2191
  const existing = readdirSync6(rulesDir).filter((f) => f.match(/^rule-\d+\.json$/)).sort();
@@ -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 = join13(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: join13 } = await import("path");
2234
- const invariantsPath = join13(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: basename3 } = 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: basename3(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, basename3);
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, basename3) {
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, basename3);
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: join13 } = await import("path");
3532
- await mkdir2(outputDir, { recursive: true });
3533
- await writeFile5(join13(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
3534
- await writeFile5(join13(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
3535
- await writeFile5(join13(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
3536
- await writeFile5(join13(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
3537
- await writeFile5(join13(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
3538
- await writeFile5(join13(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
3539
- await writeFile5(join13(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
3540
- const rulesDir = join13(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(join13(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: basename3 } = 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: ${basename3(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: ${basename3(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: join13 } = await import("path");
3676
+ const { join: join14 } = await import("path");
3677
3677
  const { copyFile } = await import("fs/promises");
3678
- const sourceDest = join13(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: existsSync9 } = await import("fs");
5013
- if (existsSync9(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: join13 } = await import("path");
5872
- await mkdir2(outputDir, { recursive: true });
5873
- await writeFile5(join13(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
5874
- await writeFile5(join13(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
5875
- await writeFile5(join13(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
5876
- await writeFile5(join13(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
5877
- const rulesDir = join13(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(join13(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(join13(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
5885
- await writeFile5(join13(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
5886
- await writeFile5(join13(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");
@@ -7401,10 +7401,10 @@ function verdictToAuditEvent(event, verdict) {
7401
7401
  return auditEvent;
7402
7402
  }
7403
7403
  async function readAuditLog(logPath, filter) {
7404
- const { readFile: readFile3 } = await import("fs/promises");
7404
+ const { readFile: readFile4 } = await import("fs/promises");
7405
7405
  let content;
7406
7406
  try {
7407
- content = await readFile3(logPath, "utf-8");
7407
+ content = await readFile4(logPath, "utf-8");
7408
7408
  } catch {
7409
7409
  return [];
7410
7410
  }
@@ -7509,9 +7509,9 @@ var init_audit_logger = __esm({
7509
7509
  }
7510
7510
  const lines = this.buffer.splice(0).join("\n") + "\n";
7511
7511
  try {
7512
- const { appendFile, mkdir: mkdir2 } = await import("fs/promises");
7513
- const { dirname: dirname3 } = await import("path");
7514
- await mkdir2(dirname3(this.logPath), { recursive: true });
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
7515
  await appendFile(this.logPath, lines, "utf-8");
7516
7516
  } catch {
7517
7517
  }
@@ -8241,14 +8241,14 @@ function handleHealthCheck() {
8241
8241
  };
8242
8242
  }
8243
8243
  async function handleListPresets(policiesDir) {
8244
- const { readdir, readFile: readFile3 } = await import("fs/promises");
8245
- const { join: join13 } = await import("path");
8246
- const dir = policiesDir ?? join13(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");
8247
8247
  const presets = [];
8248
8248
  try {
8249
8249
  const files = await readdir(dir);
8250
8250
  for (const file of files.filter((f) => f.endsWith(".txt")).sort()) {
8251
- const content = await readFile3(join13(dir, file), "utf-8");
8251
+ const content = await readFile4(join14(dir, file), "utf-8");
8252
8252
  const id = file.replace(".txt", "");
8253
8253
  const name = id.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
8254
8254
  const firstLine = content.split("\n").find((l) => l.trim().length > 0) ?? "";
@@ -8319,9 +8319,9 @@ function govern(action, world, options) {
8319
8319
  return evaluateGuard(event, world, options);
8320
8320
  }
8321
8321
  async function writeTempWorld(dir, policyLines) {
8322
- const { writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
8323
- const { join: join13 } = await import("path");
8324
- 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 });
8325
8325
  const worldJson = {
8326
8326
  world_id: "demo-live",
8327
8327
  name: "Live Demo World",
@@ -8362,9 +8362,9 @@ async function writeTempWorld(dir, policyLines) {
8362
8362
  authoring_method: "manual-authoring"
8363
8363
  };
8364
8364
  await Promise.all([
8365
- writeFile5(join13(dir, "world.json"), JSON.stringify(worldJson, null, 2)),
8366
- writeFile5(join13(dir, "kernel.json"), JSON.stringify(kernelJson, null, 2)),
8367
- writeFile5(join13(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))
8368
8368
  ]);
8369
8369
  }
8370
8370
  var init_govern = __esm({
@@ -8708,10 +8708,10 @@ data: ${data}
8708
8708
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
8709
8709
  }
8710
8710
  function readBody(req) {
8711
- return new Promise((resolve5, reject) => {
8711
+ return new Promise((resolve6, reject) => {
8712
8712
  const chunks = [];
8713
8713
  req.on("data", (chunk) => chunks.push(chunk));
8714
- req.on("end", () => resolve5(Buffer.concat(chunks).toString("utf-8")));
8714
+ req.on("end", () => resolve6(Buffer.concat(chunks).toString("utf-8")));
8715
8715
  req.on("error", reject);
8716
8716
  });
8717
8717
  }
@@ -11475,9 +11475,9 @@ async function main15(argv) {
11475
11475
  }
11476
11476
  if (worldPath) {
11477
11477
  try {
11478
- const { existsSync: existsSync9 } = await import("fs");
11479
- const { join: join13 } = await import("path");
11480
- const hasWorld = existsSync9(join13(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"));
11481
11481
  checks.push({
11482
11482
  label: "World file detected",
11483
11483
  status: hasWorld ? "pass" : "fail",
@@ -11492,12 +11492,12 @@ async function main15(argv) {
11492
11492
  });
11493
11493
  }
11494
11494
  } else {
11495
- const { existsSync: existsSync9 } = await import("fs");
11496
- const { join: join13 } = await import("path");
11495
+ const { existsSync: existsSync10 } = await import("fs");
11496
+ const { join: join14 } = await import("path");
11497
11497
  const candidates = ["./world", "./.neuroverse", "./worlds"];
11498
11498
  let found;
11499
11499
  for (const dir of candidates) {
11500
- if (existsSync9(join13(dir, "world.json"))) {
11500
+ if (existsSync10(join14(dir, "world.json"))) {
11501
11501
  found = dir;
11502
11502
  break;
11503
11503
  }
@@ -13148,7 +13148,7 @@ async function runPipeMode(config) {
13148
13148
  `);
13149
13149
  }
13150
13150
  const MAX_BUFFER_SIZE = 1e6;
13151
- return new Promise((resolve5, reject) => {
13151
+ return new Promise((resolve6, reject) => {
13152
13152
  let buffer = "";
13153
13153
  process.stdin.setEncoding("utf-8");
13154
13154
  process.stdin.on("data", (chunk) => {
@@ -13194,7 +13194,7 @@ async function runPipeMode(config) {
13194
13194
  `[neuroverse] Session complete: ${finalState.actionsEvaluated} evaluated, ${finalState.actionsAllowed} allowed, ${finalState.actionsBlocked} blocked, ${finalState.actionsPaused} paused
13195
13195
  `
13196
13196
  );
13197
- resolve5();
13197
+ resolve6();
13198
13198
  });
13199
13199
  process.stdin.on("error", reject);
13200
13200
  });
@@ -13310,8 +13310,8 @@ ${response.content}
13310
13310
  rl2.on("close", () => {
13311
13311
  session.stop();
13312
13312
  });
13313
- return new Promise((resolve5) => {
13314
- rl2.on("close", resolve5);
13313
+ return new Promise((resolve6) => {
13314
+ rl2.on("close", resolve6);
13315
13315
  });
13316
13316
  }
13317
13317
  var SessionManager;
@@ -14421,28 +14421,28 @@ function computeWorldDiff(a, b) {
14421
14421
  return { changes };
14422
14422
  }
14423
14423
  async function worldSnapshot(worldPath) {
14424
- const { readdir, readFile: readFile3, mkdir: mkdir2, writeFile: writeFile5 } = await import("fs/promises");
14425
- const { join: join13 } = await import("path");
14424
+ const { readdir, readFile: readFile4, mkdir: mkdir3, writeFile: writeFile6 } = await import("fs/promises");
14425
+ const { join: join14 } = await import("path");
14426
14426
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
14427
- const snapshotDir = join13(worldPath, ".snapshots", timestamp);
14428
- await mkdir2(snapshotDir, { recursive: true });
14427
+ const snapshotDir = join14(worldPath, ".snapshots", timestamp);
14428
+ await mkdir3(snapshotDir, { recursive: true });
14429
14429
  const files = await readdir(worldPath);
14430
14430
  let copied = 0;
14431
14431
  for (const file of files) {
14432
14432
  if (file.endsWith(".json")) {
14433
- const content = await readFile3(join13(worldPath, file), "utf-8");
14434
- await writeFile5(join13(snapshotDir, file), content, "utf-8");
14433
+ const content = await readFile4(join14(worldPath, file), "utf-8");
14434
+ await writeFile6(join14(snapshotDir, file), content, "utf-8");
14435
14435
  copied++;
14436
14436
  }
14437
14437
  }
14438
14438
  try {
14439
- const rulesDir = join13(worldPath, "rules");
14439
+ const rulesDir = join14(worldPath, "rules");
14440
14440
  const ruleFiles = await readdir(rulesDir);
14441
- await mkdir2(join13(snapshotDir, "rules"), { recursive: true });
14441
+ await mkdir3(join14(snapshotDir, "rules"), { recursive: true });
14442
14442
  for (const file of ruleFiles) {
14443
14443
  if (file.endsWith(".json")) {
14444
- const content = await readFile3(join13(rulesDir, file), "utf-8");
14445
- await writeFile5(join13(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");
14446
14446
  copied++;
14447
14447
  }
14448
14448
  }
@@ -14454,9 +14454,9 @@ async function worldSnapshot(worldPath) {
14454
14454
  `);
14455
14455
  }
14456
14456
  async function worldRollback(worldPath) {
14457
- const { readdir, readFile: readFile3, writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
14458
- const { join: join13 } = await import("path");
14459
- const snapshotsDir = join13(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");
14460
14460
  let snapshots;
14461
14461
  try {
14462
14462
  snapshots = (await readdir(snapshotsDir)).sort();
@@ -14471,34 +14471,34 @@ async function worldRollback(worldPath) {
14471
14471
  return;
14472
14472
  }
14473
14473
  const latest = snapshots[snapshots.length - 1];
14474
- const snapshotDir = join13(snapshotsDir, latest);
14474
+ const snapshotDir = join14(snapshotsDir, latest);
14475
14475
  const backupTimestamp = "pre-rollback-" + (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
14476
- const backupDir = join13(snapshotsDir, backupTimestamp);
14477
- await mkdir2(backupDir, { recursive: true });
14476
+ const backupDir = join14(snapshotsDir, backupTimestamp);
14477
+ await mkdir3(backupDir, { recursive: true });
14478
14478
  const currentFiles = await readdir(worldPath);
14479
14479
  for (const file of currentFiles) {
14480
14480
  if (file.endsWith(".json")) {
14481
- const content = await readFile3(join13(worldPath, file), "utf-8");
14482
- await writeFile5(join13(backupDir, file), content, "utf-8");
14481
+ const content = await readFile4(join14(worldPath, file), "utf-8");
14482
+ await writeFile6(join14(backupDir, file), content, "utf-8");
14483
14483
  }
14484
14484
  }
14485
14485
  const snapshotFiles = await readdir(snapshotDir);
14486
14486
  let restored = 0;
14487
14487
  for (const file of snapshotFiles) {
14488
14488
  if (file.endsWith(".json")) {
14489
- const content = await readFile3(join13(snapshotDir, file), "utf-8");
14490
- await writeFile5(join13(worldPath, file), content, "utf-8");
14489
+ const content = await readFile4(join14(snapshotDir, file), "utf-8");
14490
+ await writeFile6(join14(worldPath, file), content, "utf-8");
14491
14491
  restored++;
14492
14492
  }
14493
14493
  }
14494
14494
  try {
14495
- const rulesDir = join13(snapshotDir, "rules");
14495
+ const rulesDir = join14(snapshotDir, "rules");
14496
14496
  const ruleFiles = await readdir(rulesDir);
14497
- await mkdir2(join13(worldPath, "rules"), { recursive: true });
14497
+ await mkdir3(join14(worldPath, "rules"), { recursive: true });
14498
14498
  for (const file of ruleFiles) {
14499
14499
  if (file.endsWith(".json")) {
14500
- const content = await readFile3(join13(rulesDir, file), "utf-8");
14501
- await writeFile5(join13(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");
14502
14502
  restored++;
14503
14503
  }
14504
14504
  }
@@ -16400,27 +16400,27 @@ function closePrompts() {
16400
16400
  }
16401
16401
  function ask(question, defaultValue) {
16402
16402
  const suffix = defaultValue ? ` [${defaultValue}]` : "";
16403
- return new Promise((resolve5) => {
16403
+ return new Promise((resolve6) => {
16404
16404
  getRL().question(`
16405
16405
  ${question}${suffix}: `, (answer) => {
16406
16406
  const val = answer.trim();
16407
- resolve5(val || defaultValue || "");
16407
+ resolve6(val || defaultValue || "");
16408
16408
  });
16409
16409
  });
16410
16410
  }
16411
16411
  function confirm(question, defaultYes = true) {
16412
16412
  const hint = defaultYes ? "[Y/n]" : "[y/N]";
16413
- return new Promise((resolve5) => {
16413
+ return new Promise((resolve6) => {
16414
16414
  getRL().question(`
16415
16415
  ${question} ${hint}: `, (answer) => {
16416
16416
  const val = answer.trim().toLowerCase();
16417
- if (val === "") resolve5(defaultYes);
16418
- else resolve5(val === "y" || val === "yes");
16417
+ if (val === "") resolve6(defaultYes);
16418
+ else resolve6(val === "y" || val === "yes");
16419
16419
  });
16420
16420
  });
16421
16421
  }
16422
16422
  function choose(question, options) {
16423
- return new Promise((resolve5) => {
16423
+ return new Promise((resolve6) => {
16424
16424
  const r = getRL();
16425
16425
  r.write(`
16426
16426
  ${question}
@@ -16430,9 +16430,9 @@ function choose(question, options) {
16430
16430
  r.question(` Choice [1-${options.length}]: `, (answer) => {
16431
16431
  const idx = parseInt(answer.trim(), 10) - 1;
16432
16432
  if (idx >= 0 && idx < options.length) {
16433
- resolve5(options[idx]);
16433
+ resolve6(options[idx]);
16434
16434
  } else {
16435
- resolve5(options[0]);
16435
+ resolve6(options[0]);
16436
16436
  }
16437
16437
  });
16438
16438
  });
@@ -16901,16 +16901,16 @@ function generateWorld(state) {
16901
16901
  return { worldJson, stateSchema, guardsJson, rules, gatesJson, invariants, outcomes, metadata };
16902
16902
  }
16903
16903
  async function writeWorld(outputDir, world) {
16904
- const { mkdirSync: mkdirSync5, existsSync: existsSync9 } = await import("fs");
16905
- const { writeFile: writeFile5 } = await import("fs/promises");
16906
- const { join: join13 } = 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");
16907
16907
  const files = [];
16908
- if (!existsSync9(outputDir)) mkdirSync5(outputDir, { recursive: true });
16909
- const rulesDir = join13(outputDir, "rules");
16910
- if (!existsSync9(rulesDir)) mkdirSync5(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 });
16911
16911
  const writeJson = async (name, data) => {
16912
- const path = join13(outputDir, name);
16913
- 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");
16914
16914
  files.push(path);
16915
16915
  };
16916
16916
  await writeJson("world.json", world.worldJson);
@@ -16921,8 +16921,8 @@ async function writeWorld(outputDir, world) {
16921
16921
  await writeJson("outcomes.json", world.outcomes);
16922
16922
  await writeJson("metadata.json", world.metadata);
16923
16923
  for (const rule of world.rules) {
16924
- const rulePath = join13(rulesDir, `${rule.id}.json`);
16925
- 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");
16926
16926
  files.push(rulePath);
16927
16927
  }
16928
16928
  return files;
@@ -17007,8 +17007,8 @@ async function main31(argv = process.argv.slice(2)) {
17007
17007
  }
17008
17008
  }
17009
17009
  async function phaseRefine(outputDir, world) {
17010
- const { writeFile: writeFile5 } = await import("fs/promises");
17011
- const { join: join13 } = await import("path");
17010
+ const { writeFile: writeFile6 } = await import("fs/promises");
17011
+ const { join: join14 } = await import("path");
17012
17012
  heading("Refinement: Thresholds & Collapse");
17013
17013
  const primaryMetric = world.gatesJson.viability_classification[0]?.field || "system_health";
17014
17014
  info(`
@@ -17024,8 +17024,8 @@ async function phaseRefine(outputDir, world) {
17024
17024
  const parsed = parseInt(newVal, 10);
17025
17025
  if (!isNaN(parsed)) gate.value = parsed;
17026
17026
  }
17027
- await writeFile5(
17028
- join13(outputDir, "gates.json"),
17027
+ await writeFile6(
17028
+ join14(outputDir, "gates.json"),
17029
17029
  JSON.stringify(world.gatesJson, null, 2) + "\n",
17030
17030
  "utf-8"
17031
17031
  );
@@ -17046,8 +17046,8 @@ async function phaseRefine(outputDir, world) {
17046
17046
  value: parsed,
17047
17047
  result: "MODEL_COLLAPSES"
17048
17048
  };
17049
- await writeFile5(
17050
- join13(outputDir, "rules", `${rule.id}.json`),
17049
+ await writeFile6(
17050
+ join14(outputDir, "rules", `${rule.id}.json`),
17051
17051
  JSON.stringify(rule, null, 2) + "\n",
17052
17052
  "utf-8"
17053
17053
  );
@@ -17151,22 +17151,22 @@ ${parts.join(". ")}.
17151
17151
  `;
17152
17152
  }
17153
17153
  function previewLens(lens) {
17154
- const BOLD2 = "\x1B[1m";
17155
- const DIM2 = "\x1B[2m";
17156
- const CYAN2 = "\x1B[36m";
17157
- const YELLOW2 = "\x1B[33m";
17158
- const GREEN2 = "\x1B[32m";
17159
- 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";
17160
17160
  const lines = [];
17161
17161
  lines.push("");
17162
- lines.push(`${BOLD2}${CYAN2} ${lens.name}${RESET2} ${DIM2}\u2014 ${lens.tagline}${RESET2}`);
17163
- 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}`);
17164
17164
  lines.push("");
17165
17165
  for (const d of lens.directives) {
17166
17166
  if (d.example) {
17167
- lines.push(` ${BOLD2}${d.id}${RESET2}`);
17168
- lines.push(` ${YELLOW2}Without:${RESET2} ${DIM2}${d.example.without}${RESET2}`);
17169
- 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}`);
17170
17170
  lines.push("");
17171
17171
  }
17172
17172
  }
@@ -17213,7 +17213,7 @@ function lensForRole(world, roleId, roleLensOverride) {
17213
17213
  if (byRole) return byRole;
17214
17214
  return lenses[0];
17215
17215
  }
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, 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;
17217
17217
  var init_lens = __esm({
17218
17218
  "src/builder/lens.ts"() {
17219
17219
  "use strict";
@@ -17762,6 +17762,63 @@ var init_lens = __esm({
17762
17762
  }
17763
17763
  ]
17764
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
+ };
17765
17822
  BUILTIN_LENSES = [
17766
17823
  // Character lenses — each one is a person you'd want in your corner
17767
17824
  STOIC_LENS,
@@ -17773,7 +17830,9 @@ var init_lens = __esm({
17773
17830
  HYPE_MAN_LENS,
17774
17831
  MONK_LENS,
17775
17832
  SOCRATIC_LENS,
17776
- MINIMALIST_LENS
17833
+ MINIMALIST_LENS,
17834
+ // Behavioral lenses — governance overlays that interpret action, not tone
17835
+ BEHAVIORAL_INTERPRETER_LENS
17777
17836
  ];
17778
17837
  }
17779
17838
  });
@@ -18040,10 +18099,10 @@ async function cmdAdd(argv) {
18040
18099
  if (!id) {
18041
18100
  id = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
18042
18101
  }
18043
- const { readFile: readFile3, writeFile: writeFile5 } = await import("fs/promises");
18044
- const { join: join13 } = await import("path");
18102
+ const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
18103
+ const { join: join14 } = await import("path");
18045
18104
  const possiblePaths = [
18046
- join13(worldPath, "world.nv-world.md"),
18105
+ join14(worldPath, "world.nv-world.md"),
18047
18106
  worldPath
18048
18107
  ];
18049
18108
  let mdPath = "";
@@ -18051,7 +18110,7 @@ async function cmdAdd(argv) {
18051
18110
  for (const p of possiblePaths) {
18052
18111
  try {
18053
18112
  if (p.endsWith(".md")) {
18054
- mdContent = await readFile3(p, "utf-8");
18113
+ mdContent = await readFile4(p, "utf-8");
18055
18114
  mdPath = p;
18056
18115
  break;
18057
18116
  }
@@ -18064,8 +18123,8 @@ async function cmdAdd(argv) {
18064
18123
  const files = await readdir(worldPath);
18065
18124
  const mdFile = files.find((f) => f.endsWith(".nv-world.md"));
18066
18125
  if (mdFile) {
18067
- mdPath = join13(worldPath, mdFile);
18068
- mdContent = await readFile3(mdPath, "utf-8");
18126
+ mdPath = join14(worldPath, mdFile);
18127
+ mdContent = await readFile4(mdPath, "utf-8");
18069
18128
  }
18070
18129
  } catch {
18071
18130
  }
@@ -18099,7 +18158,7 @@ async function cmdAdd(argv) {
18099
18158
  } else {
18100
18159
  mdContent = mdContent.trimEnd() + "\n\n# Lenses\n" + lensBlock + "\n";
18101
18160
  }
18102
- await writeFile5(mdPath, mdContent, "utf-8");
18161
+ await writeFile6(mdPath, mdContent, "utf-8");
18103
18162
  process.stderr.write("\n");
18104
18163
  process.stderr.write(`${GREEN} Added lens "${name}" (${id}) to ${mdPath}${RESET}
18105
18164
  `);
@@ -18191,136 +18250,1757 @@ Examples:
18191
18250
  }
18192
18251
  });
18193
18252
 
18194
- // src/cli/neuroverse.ts
18195
- var USAGE9 = `
18196
- neuroverse \u2014 Turn ideas into worlds.
18197
-
18198
- Commands:
18199
- add Add a guard, rule, or invariant to a world
18200
- build Build a world from markdown (derive + compile in one step)
18201
- explain Human-readable summary of a compiled world
18202
- simulate Step-by-step state evolution
18203
- improve Actionable suggestions for strengthening a world
18204
- init Scaffold a new .nv-world.md template
18205
- init-world Generate a governed world from a template (e.g., autoresearch)
18206
- infer-world Scan a repo and infer a governance world from its structure
18207
- validate Static analysis on world files
18208
- guard Runtime governance evaluation (stdin \u2192 stdout)
18209
- test Run guard simulation suite against a world
18210
- redteam Adversarial containment testing (agent escape detection)
18211
- demo Interactive governance demo (flow viz + simulation)
18212
- doctor Environment sanity check
18213
- playground Interactive web demo (opens in browser)
18214
- plan Plan enforcement (compile, check, status, advance, derive)
18215
- run Governed runtime (pipe mode or interactive chat)
18216
- mcp MCP governance server (for Claude, Cursor, etc.)
18217
- worlds List available worlds (alias for world list)
18218
- trace Runtime action audit log
18219
- impact Counterfactual governance impact report
18220
- decision-flow Intent \u2192 Rule \u2192 Outcome visualization (behavioral governance)
18221
- equity-penalties Fortune 500 equity PENALIZE/REWARD simulation
18222
- world World management (status, diff, snapshot, rollback)
18223
- keygen Generate Ed25519 signing keypair
18224
- sign Sign a world artifact (cryptographic manifest)
18225
- verify Verify a signed world artifact
18226
- migrate Migrate world schema between versions
18227
- derive AI-assisted synthesis of .nv-world.md from markdown
18228
- bootstrap Compile .nv-world.md \u2192 world JSON files
18229
- configure-ai Configure AI provider credentials
18230
- configure-world Interactive wizard: define your system in plain language
18231
- lens Manage behavioral lenses (list, preview, compile, compare, add)
18232
-
18233
- Usage:
18234
- neuroverse add "Block dairy orders" --world <dir>
18235
- neuroverse add guard --world <dir> --label "Block dairy" --pattern "*dairy*"
18236
- neuroverse add rule --world <dir> --label "Cost overrun" --trigger "cost > 100" --effect "viability *= 0.5"
18237
- neuroverse add invariant --world <dir> --label "Budget must never exceed 1000"
18238
- neuroverse build <input.md> [--output <dir>]
18239
- neuroverse explain <world-path-or-id> [--json]
18240
- neuroverse simulate <world-path-or-id> [--steps N] [--set key=value] [--profile name]
18241
- neuroverse improve <world-path-or-id> [--json]
18242
- neuroverse init [--name "World Name"] [--output path]
18243
- neuroverse init-world autoresearch [--context "topic"] [--dataset "name"] [--goal "goal"]
18244
- neuroverse infer-world ./repo [--output path] [--json] [--dry-run]
18245
- neuroverse validate --world <dir> [--format full|summary|findings]
18246
- neuroverse guard --world <dir> [--trace] [--level basic|standard|strict]
18247
- neuroverse test --world <dir> [--fuzz] [--count N]
18248
- neuroverse redteam --world <dir> [--level basic|standard|strict]
18249
- neuroverse demo [--world social-media] [--port 3456] [--no-browser]
18250
- neuroverse doctor [--world <dir>] [--json]
18251
- neuroverse playground --world <dir> [--port 4242]
18252
- neuroverse trace [--log <path>] [--summary] [--filter BLOCK] [--last 20]
18253
- neuroverse impact [--log <path>] [--json]
18254
- neuroverse world status <path>
18255
- neuroverse world diff <path1> <path2>
18256
- neuroverse world snapshot <path>
18257
- neuroverse world rollback <path>
18258
- neuroverse derive --input <path> [--output <path>] [--dry-run]
18259
- neuroverse bootstrap --input <.md> --output <dir> [--validate]
18260
- neuroverse decision-flow [--log <path>] [--json]
18261
- neuroverse equity-penalties --world <dir> [--agents N] [--rounds N] [--json]
18262
- neuroverse configure-ai --provider <name> --model <name> --api-key <key>
18263
- neuroverse configure-world [--output <dir>]
18264
- neuroverse keygen [--output <dir>] [--name <name>]
18265
- neuroverse sign --world <dir> [--key <path>]
18266
- neuroverse verify --world <dir> [--key <path>]
18267
- neuroverse migrate --world <dir> [--dry-run] [--backup]
18268
- neuroverse lens list [--world <dir>] [--json]
18269
- neuroverse lens preview <id> [--world <dir>]
18270
- neuroverse lens compile <id,...> [--world <dir>] [--role <role>] [--json]
18271
- neuroverse lens compare --input "text" --lenses stoic,coach,calm
18272
- neuroverse lens add --world <dir> --name "Name" --tagline "..." [options]
18273
-
18274
- Examples:
18275
- neuroverse build horror-notes.md
18276
- neuroverse explain inherited_silence
18277
- neuroverse simulate inherited_silence --steps 5
18278
- neuroverse improve inherited_silence
18279
- neuroverse build ./docs/ --output ./my-world/
18280
- neuroverse init --name "Customer Service Governance"
18281
- neuroverse validate --world ./world/ --format summary
18282
- echo '{"intent":"delete user data"}' | neuroverse guard --world ./world/ --trace
18283
- neuroverse plan compile plan.md --output plan.json
18284
- echo '{"intent":"write blog"}' | neuroverse plan check --plan plan.json
18285
- neuroverse plan status --plan plan.json
18286
- neuroverse plan advance write_blog_post --plan plan.json
18287
- neuroverse plan derive plan.md --output ./derived-world/
18288
- neuroverse run --pipe --world ./world/ --plan plan.json
18289
- neuroverse run --interactive --world ./world/ --provider openai
18290
- neuroverse mcp --world ./world/ --plan plan.json
18291
- neuroverse test --world ./world/ --fuzz --count 50
18292
- neuroverse redteam --world ./world/ --level strict
18293
- neuroverse doctor
18294
- neuroverse playground --world ./world/
18295
- `.trim();
18296
- async function main33() {
18297
- const args = process.argv.slice(2);
18298
- const command = args[0];
18299
- const subArgs = args.slice(1);
18300
- switch (command) {
18301
- case "add": {
18302
- const { main: addMain } = await Promise.resolve().then(() => (init_add(), add_exports));
18303
- return addMain(subArgs);
18304
- }
18305
- case "build": {
18306
- const { main: buildMain } = await Promise.resolve().then(() => (init_build(), build_exports));
18307
- return buildMain(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;
18308
18263
  }
18309
- case "explain": {
18310
- const { main: explainMain } = await Promise.resolve().then(() => (init_explain(), explain_exports));
18311
- return explainMain(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);
18312
18284
  }
18313
- case "simulate": {
18314
- const { main: simulateMain } = await Promise.resolve().then(() => (init_simulate(), simulate_exports));
18315
- return simulateMain(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);
18316
18312
  }
18317
- case "improve": {
18318
- const { main: improveMain } = await Promise.resolve().then(() => (init_improve(), improve_exports));
18319
- return improveMain(subArgs);
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);
18320
18340
  }
18321
- case "init": {
18322
- const { main: initMain } = await Promise.resolve().then(() => (init_init(), init_exports));
18323
- return initMain(subArgs);
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);
18324
20004
  }
18325
20005
  case "init-world": {
18326
20006
  const { main: initWorldMain } = await Promise.resolve().then(() => (init_init_world(), init_world_exports));
@@ -18434,11 +20114,15 @@ async function main33() {
18434
20114
  const { main: lensMain } = await Promise.resolve().then(() => (init_lens2(), lens_exports));
18435
20115
  return lensMain(subArgs);
18436
20116
  }
20117
+ case "worldmodel": {
20118
+ const { main: worldmodelMain } = await Promise.resolve().then(() => (init_worldmodel(), worldmodel_exports));
20119
+ return worldmodelMain(subArgs);
20120
+ }
18437
20121
  case "--help":
18438
20122
  case "-h":
18439
20123
  case "help":
18440
20124
  case void 0: {
18441
- process.stdout.write(USAGE9 + "\n");
20125
+ process.stdout.write(USAGE10 + "\n");
18442
20126
  process.exit(0);
18443
20127
  break;
18444
20128
  }
@@ -18446,12 +20130,12 @@ async function main33() {
18446
20130
  process.stderr.write(`Unknown command: "${command}"
18447
20131
 
18448
20132
  `);
18449
- process.stdout.write(USAGE9 + "\n");
20133
+ process.stdout.write(USAGE10 + "\n");
18450
20134
  process.exit(1);
18451
20135
  }
18452
20136
  }
18453
20137
  }
18454
- main33().catch((e) => {
20138
+ main34().catch((e) => {
18455
20139
  process.stderr.write(`Fatal: ${e}
18456
20140
  `);
18457
20141
  process.exit(3);