@neuroverseos/governance 0.6.1 → 0.8.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.
@@ -2002,10 +2002,10 @@ __export(world_loader_exports, {
2002
2002
  });
2003
2003
  async function loadWorldFromDirectory(dirPath) {
2004
2004
  const { readFile: readFile4 } = await import("fs/promises");
2005
- const { join: join16 } = await import("path");
2006
- const { readdirSync: readdirSync7 } = await import("fs");
2005
+ const { join: join18 } = await import("path");
2006
+ const { readdirSync: readdirSync10 } = await import("fs");
2007
2007
  async function readJson(filename) {
2008
- const filePath = join16(dirPath, filename);
2008
+ const filePath = join18(dirPath, filename);
2009
2009
  try {
2010
2010
  const content = await readFile4(filePath, "utf-8");
2011
2011
  return JSON.parse(content);
@@ -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 = join16(dirPath, "rules");
2039
- const ruleFiles = readdirSync7(rulesDir).filter((f) => f.endsWith(".json")).sort();
2038
+ const rulesDir = join18(dirPath, "rules");
2039
+ const ruleFiles = readdirSync10(rulesDir).filter((f) => f.endsWith(".json")).sort();
2040
2040
  for (const file of ruleFiles) {
2041
2041
  try {
2042
- const content = await readFile4(join16(rulesDir, file), "utf-8");
2042
+ const content = await readFile4(join18(rulesDir, file), "utf-8");
2043
2043
  rules.push(JSON.parse(content));
2044
2044
  } catch (err) {
2045
2045
  process.stderr.write(
@@ -2093,8 +2093,8 @@ async function loadWorld(worldPath) {
2093
2093
  }
2094
2094
  async function loadBundledWorld(name = DEFAULT_BUNDLED_WORLD) {
2095
2095
  const { readFile: readFile4 } = await import("fs/promises");
2096
- const { join: join16, dirname: dirname4 } = await import("path");
2097
- const { existsSync: existsSync12 } = await import("fs");
2096
+ const { join: join18, dirname: dirname4 } = await import("path");
2097
+ const { existsSync: existsSync14 } = 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));
@@ -2102,16 +2102,16 @@ async function loadBundledWorld(name = DEFAULT_BUNDLED_WORLD) {
2102
2102
  let packageRoot;
2103
2103
  try {
2104
2104
  const thisFile = typeof __dirname !== "undefined" ? __dirname : dirname4(fileURLToPath3(import_meta.url));
2105
- packageRoot = join16(thisFile, "..", "..");
2105
+ packageRoot = join18(thisFile, "..", "..");
2106
2106
  } catch {
2107
2107
  packageRoot = process.cwd();
2108
2108
  }
2109
2109
  const candidates = [
2110
- join16(packageRoot, "dist", "worlds", filename),
2111
- join16(packageRoot, "src", "worlds", filename)
2110
+ join18(packageRoot, "dist", "worlds", filename),
2111
+ join18(packageRoot, "src", "worlds", filename)
2112
2112
  ];
2113
2113
  for (const candidate of candidates) {
2114
- if (existsSync12(candidate)) {
2114
+ if (existsSync14(candidate)) {
2115
2115
  const markdown = await readFile4(candidate, "utf-8");
2116
2116
  const parsed = parseWorldMarkdown2(markdown);
2117
2117
  if (!parsed.world) {
@@ -2141,8 +2141,8 @@ function slugify(text) {
2141
2141
  }
2142
2142
  async function addGuard(worldDir, input) {
2143
2143
  const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
2144
- const { join: join16 } = await import("path");
2145
- const guardsPath = join16(worldDir, "guards.json");
2144
+ const { join: join18 } = await import("path");
2145
+ const guardsPath = join18(worldDir, "guards.json");
2146
2146
  let config;
2147
2147
  try {
2148
2148
  const raw = await readFile4(guardsPath, "utf-8");
@@ -2182,13 +2182,13 @@ async function addGuard(worldDir, input) {
2182
2182
  }
2183
2183
  async function addRule(worldDir, input) {
2184
2184
  const { readFile: readFile4, writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
2185
- const { join: join16 } = await import("path");
2186
- const { readdirSync: readdirSync7 } = await import("fs");
2187
- const rulesDir = join16(worldDir, "rules");
2185
+ const { join: join18 } = await import("path");
2186
+ const { readdirSync: readdirSync10 } = await import("fs");
2187
+ const rulesDir = join18(worldDir, "rules");
2188
2188
  await mkdir3(rulesDir, { recursive: true });
2189
2189
  let nextNum = 1;
2190
2190
  try {
2191
- const existing = readdirSync7(rulesDir).filter((f) => f.match(/^rule-\d+\.json$/)).sort();
2191
+ const existing = readdirSync10(rulesDir).filter((f) => f.match(/^rule-\d+\.json$/)).sort();
2192
2192
  if (existing.length > 0) {
2193
2193
  const lastFile = existing[existing.length - 1];
2194
2194
  const match = lastFile.match(/rule-(\d+)\.json/);
@@ -2214,7 +2214,7 @@ 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 = join16(rulesDir, `rule-${ruleNum}.json`);
2217
+ const rulePath = join18(rulesDir, `rule-${ruleNum}.json`);
2218
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);
@@ -2230,8 +2230,8 @@ async function addRule(worldDir, input) {
2230
2230
  }
2231
2231
  async function addInvariant(worldDir, input) {
2232
2232
  const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
2233
- const { join: join16 } = await import("path");
2234
- const invariantsPath = join16(worldDir, "invariants.json");
2233
+ const { join: join18 } = await import("path");
2234
+ const invariantsPath = join18(worldDir, "invariants.json");
2235
2235
  let config;
2236
2236
  try {
2237
2237
  const raw = await readFile4(invariantsPath, "utf-8");
@@ -2849,28 +2849,28 @@ ${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: extname3, basename: basename4 } = await import("path");
2852
+ const { join: pathJoin, extname: extname4, basename: basename5 } = 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: basename4(inputPath), content }];
2856
+ return [{ filename: basename5(inputPath), content }];
2857
2857
  }
2858
2858
  if (stats.isDirectory()) {
2859
2859
  const sources = [];
2860
- await collectDir(inputPath, sources, rf, pathJoin, extname3, basename4);
2860
+ await collectDir(inputPath, sources, rf, pathJoin, extname4, basename5);
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, extname3, basename4) {
2866
+ async function collectDir(dir, sources, rf, pathJoin, extname4, basename5) {
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, extname3, basename4);
2873
- } else if (entry.isFile() && extname3(entry.name).toLowerCase() === ".md") {
2872
+ await collectDir(fullPath, sources, rf, pathJoin, extname4, basename5);
2873
+ } else if (entry.isFile() && extname4(entry.name).toLowerCase() === ".md") {
2874
2874
  const content = await rf(fullPath, "utf-8");
2875
2875
  sources.push({ filename: entry.name, content });
2876
2876
  }
@@ -3528,21 +3528,21 @@ function parseArgs2(argv) {
3528
3528
  }
3529
3529
  async function writeWorldFiles(outputDir, world) {
3530
3530
  const { writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
3531
- const { join: join16 } = await import("path");
3531
+ const { join: join18 } = await import("path");
3532
3532
  await mkdir3(outputDir, { recursive: true });
3533
- await writeFile6(join16(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
3534
- await writeFile6(join16(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
3535
- await writeFile6(join16(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
3536
- await writeFile6(join16(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
3537
- await writeFile6(join16(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
3538
- await writeFile6(join16(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
3539
- await writeFile6(join16(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
3540
- const rulesDir = join16(outputDir, "rules");
3533
+ await writeFile6(join18(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
3534
+ await writeFile6(join18(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
3535
+ await writeFile6(join18(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
3536
+ await writeFile6(join18(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
3537
+ await writeFile6(join18(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
3538
+ await writeFile6(join18(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
3539
+ await writeFile6(join18(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
3540
+ const rulesDir = join18(outputDir, "rules");
3541
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 writeFile6(join16(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
3545
+ await writeFile6(join18(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
3546
3546
  }
3547
3547
  }
3548
3548
  function write(msg) {
@@ -3557,12 +3557,12 @@ 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: basename4 } = await import("path");
3560
+ const { basename: basename5 } = await import("path");
3561
3561
  write(`
3562
3562
  NeuroVerse World Builder
3563
3563
  `);
3564
3564
  write(`
3565
- Analyzing: ${basename4(args.inputPath)}
3565
+ Analyzing: ${basename5(args.inputPath)}
3566
3566
  `);
3567
3567
  const derivedPath = args.outputDir ? `${args.outputDir}/source.nv-world.md` : ".neuroverse/build-output.nv-world.md";
3568
3568
  const { mkdir: mkdir3 } = await import("fs/promises");
@@ -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: join16 } = await import("path");
3676
+ const { join: join18 } = await import("path");
3677
3677
  const { copyFile } = await import("fs/promises");
3678
- const sourceDest = join16(outputDir, "source.nv-world.md");
3678
+ const sourceDest = join18(outputDir, "source.nv-world.md");
3679
3679
  if (derivedPath !== sourceDest) {
3680
3680
  await copyFile(derivedPath, sourceDest);
3681
3681
  }
@@ -5009,8 +5009,8 @@ async function main6(argv = process.argv.slice(2)) {
5009
5009
  try {
5010
5010
  const args = parseArgs6(argv);
5011
5011
  const { writeFile: writeFile6 } = await import("fs/promises");
5012
- const { existsSync: existsSync12 } = await import("fs");
5013
- if (existsSync12(args.outputPath)) {
5012
+ const { existsSync: existsSync14 } = await import("fs");
5013
+ if (existsSync14(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");
@@ -5868,22 +5868,22 @@ function parseArgs9(argv) {
5868
5868
  }
5869
5869
  async function writeWorldFiles2(outputDir, world) {
5870
5870
  const { writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
5871
- const { join: join16 } = await import("path");
5871
+ const { join: join18 } = await import("path");
5872
5872
  await mkdir3(outputDir, { recursive: true });
5873
- await writeFile6(join16(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
5874
- await writeFile6(join16(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
5875
- await writeFile6(join16(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
5876
- await writeFile6(join16(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
5877
- const rulesDir = join16(outputDir, "rules");
5873
+ await writeFile6(join18(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
5874
+ await writeFile6(join18(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
5875
+ await writeFile6(join18(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
5876
+ await writeFile6(join18(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
5877
+ const rulesDir = join18(outputDir, "rules");
5878
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 writeFile6(join16(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
5882
+ await writeFile6(join18(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
5883
5883
  }
5884
- await writeFile6(join16(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
5885
- await writeFile6(join16(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
5886
- await writeFile6(join16(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
5884
+ await writeFile6(join18(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
5885
+ await writeFile6(join18(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
5886
+ await writeFile6(join18(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();
@@ -8242,13 +8242,13 @@ function handleHealthCheck() {
8242
8242
  }
8243
8243
  async function handleListPresets(policiesDir) {
8244
8244
  const { readdir, readFile: readFile4 } = await import("fs/promises");
8245
- const { join: join16 } = await import("path");
8246
- const dir = policiesDir ?? join16(process.cwd(), "policies");
8245
+ const { join: join18 } = await import("path");
8246
+ const dir = policiesDir ?? join18(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 readFile4(join16(dir, file), "utf-8");
8251
+ const content = await readFile4(join18(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) ?? "";
@@ -8320,7 +8320,7 @@ function govern(action, world, options) {
8320
8320
  }
8321
8321
  async function writeTempWorld(dir, policyLines) {
8322
8322
  const { writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
8323
- const { join: join16 } = await import("path");
8323
+ const { join: join18 } = await import("path");
8324
8324
  await mkdir3(dir, { recursive: true });
8325
8325
  const worldJson = {
8326
8326
  world_id: "demo-live",
@@ -8362,9 +8362,9 @@ async function writeTempWorld(dir, policyLines) {
8362
8362
  authoring_method: "manual-authoring"
8363
8363
  };
8364
8364
  await Promise.all([
8365
- writeFile6(join16(dir, "world.json"), JSON.stringify(worldJson, null, 2)),
8366
- writeFile6(join16(dir, "kernel.json"), JSON.stringify(kernelJson, null, 2)),
8367
- writeFile6(join16(dir, "metadata.json"), JSON.stringify(metadataJson, null, 2))
8365
+ writeFile6(join18(dir, "world.json"), JSON.stringify(worldJson, null, 2)),
8366
+ writeFile6(join18(dir, "kernel.json"), JSON.stringify(kernelJson, null, 2)),
8367
+ writeFile6(join18(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((resolve8, reject) => {
8711
+ return new Promise((resolve10, reject) => {
8712
8712
  const chunks = [];
8713
8713
  req.on("data", (chunk) => chunks.push(chunk));
8714
- req.on("end", () => resolve8(Buffer.concat(chunks).toString("utf-8")));
8714
+ req.on("end", () => resolve10(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: existsSync12 } = await import("fs");
11479
- const { join: join16 } = await import("path");
11480
- const hasWorld = existsSync12(join16(worldPath, "world.json"));
11478
+ const { existsSync: existsSync14 } = await import("fs");
11479
+ const { join: join18 } = await import("path");
11480
+ const hasWorld = existsSync14(join18(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: existsSync12 } = await import("fs");
11496
- const { join: join16 } = await import("path");
11495
+ const { existsSync: existsSync14 } = await import("fs");
11496
+ const { join: join18 } = await import("path");
11497
11497
  const candidates = ["./world", "./.neuroverse", "./worlds"];
11498
11498
  let found;
11499
11499
  for (const dir of candidates) {
11500
- if (existsSync12(join16(dir, "world.json"))) {
11500
+ if (existsSync14(join18(dir, "world.json"))) {
11501
11501
  found = dir;
11502
11502
  break;
11503
11503
  }
@@ -12549,8 +12549,8 @@ async function deriveCommand(args) {
12549
12549
  return;
12550
12550
  }
12551
12551
  const plan = result.plan;
12552
- const { mkdirSync: mkdirSync5 } = await import("fs");
12553
- mkdirSync5(outputDir, { recursive: true });
12552
+ const { mkdirSync: mkdirSync6 } = await import("fs");
12553
+ mkdirSync6(outputDir, { recursive: true });
12554
12554
  const worldJson = {
12555
12555
  world_id: `plan_${plan.plan_id}`,
12556
12556
  name: `Derived: ${plan.objective}`,
@@ -13148,7 +13148,7 @@ async function runPipeMode(config) {
13148
13148
  `);
13149
13149
  }
13150
13150
  const MAX_BUFFER_SIZE = 1e6;
13151
- return new Promise((resolve8, reject) => {
13151
+ return new Promise((resolve10, 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
- resolve8();
13197
+ resolve10();
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((resolve8) => {
13314
- rl2.on("close", resolve8);
13313
+ return new Promise((resolve10) => {
13314
+ rl2.on("close", resolve10);
13315
13315
  });
13316
13316
  }
13317
13317
  var SessionManager;
@@ -14422,27 +14422,27 @@ function computeWorldDiff(a, b) {
14422
14422
  }
14423
14423
  async function worldSnapshot(worldPath) {
14424
14424
  const { readdir, readFile: readFile4, mkdir: mkdir3, writeFile: writeFile6 } = await import("fs/promises");
14425
- const { join: join16 } = await import("path");
14425
+ const { join: join18 } = await import("path");
14426
14426
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
14427
- const snapshotDir = join16(worldPath, ".snapshots", timestamp);
14427
+ const snapshotDir = join18(worldPath, ".snapshots", timestamp);
14428
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 readFile4(join16(worldPath, file), "utf-8");
14434
- await writeFile6(join16(snapshotDir, file), content, "utf-8");
14433
+ const content = await readFile4(join18(worldPath, file), "utf-8");
14434
+ await writeFile6(join18(snapshotDir, file), content, "utf-8");
14435
14435
  copied++;
14436
14436
  }
14437
14437
  }
14438
14438
  try {
14439
- const rulesDir = join16(worldPath, "rules");
14439
+ const rulesDir = join18(worldPath, "rules");
14440
14440
  const ruleFiles = await readdir(rulesDir);
14441
- await mkdir3(join16(snapshotDir, "rules"), { recursive: true });
14441
+ await mkdir3(join18(snapshotDir, "rules"), { recursive: true });
14442
14442
  for (const file of ruleFiles) {
14443
14443
  if (file.endsWith(".json")) {
14444
- const content = await readFile4(join16(rulesDir, file), "utf-8");
14445
- await writeFile6(join16(snapshotDir, "rules", file), content, "utf-8");
14444
+ const content = await readFile4(join18(rulesDir, file), "utf-8");
14445
+ await writeFile6(join18(snapshotDir, "rules", file), content, "utf-8");
14446
14446
  copied++;
14447
14447
  }
14448
14448
  }
@@ -14455,8 +14455,8 @@ async function worldSnapshot(worldPath) {
14455
14455
  }
14456
14456
  async function worldRollback(worldPath) {
14457
14457
  const { readdir, readFile: readFile4, writeFile: writeFile6, mkdir: mkdir3 } = await import("fs/promises");
14458
- const { join: join16 } = await import("path");
14459
- const snapshotsDir = join16(worldPath, ".snapshots");
14458
+ const { join: join18 } = await import("path");
14459
+ const snapshotsDir = join18(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 = join16(snapshotsDir, latest);
14474
+ const snapshotDir = join18(snapshotsDir, latest);
14475
14475
  const backupTimestamp = "pre-rollback-" + (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
14476
- const backupDir = join16(snapshotsDir, backupTimestamp);
14476
+ const backupDir = join18(snapshotsDir, backupTimestamp);
14477
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 readFile4(join16(worldPath, file), "utf-8");
14482
- await writeFile6(join16(backupDir, file), content, "utf-8");
14481
+ const content = await readFile4(join18(worldPath, file), "utf-8");
14482
+ await writeFile6(join18(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 readFile4(join16(snapshotDir, file), "utf-8");
14490
- await writeFile6(join16(worldPath, file), content, "utf-8");
14489
+ const content = await readFile4(join18(snapshotDir, file), "utf-8");
14490
+ await writeFile6(join18(worldPath, file), content, "utf-8");
14491
14491
  restored++;
14492
14492
  }
14493
14493
  }
14494
14494
  try {
14495
- const rulesDir = join16(snapshotDir, "rules");
14495
+ const rulesDir = join18(snapshotDir, "rules");
14496
14496
  const ruleFiles = await readdir(rulesDir);
14497
- await mkdir3(join16(worldPath, "rules"), { recursive: true });
14497
+ await mkdir3(join18(worldPath, "rules"), { recursive: true });
14498
14498
  for (const file of ruleFiles) {
14499
14499
  if (file.endsWith(".json")) {
14500
- const content = await readFile4(join16(rulesDir, file), "utf-8");
14501
- await writeFile6(join16(worldPath, "rules", file), content, "utf-8");
14500
+ const content = await readFile4(join18(rulesDir, file), "utf-8");
14501
+ await writeFile6(join18(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((resolve8) => {
16403
+ return new Promise((resolve10) => {
16404
16404
  getRL().question(`
16405
16405
  ${question}${suffix}: `, (answer) => {
16406
16406
  const val = answer.trim();
16407
- resolve8(val || defaultValue || "");
16407
+ resolve10(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((resolve8) => {
16413
+ return new Promise((resolve10) => {
16414
16414
  getRL().question(`
16415
16415
  ${question} ${hint}: `, (answer) => {
16416
16416
  const val = answer.trim().toLowerCase();
16417
- if (val === "") resolve8(defaultYes);
16418
- else resolve8(val === "y" || val === "yes");
16417
+ if (val === "") resolve10(defaultYes);
16418
+ else resolve10(val === "y" || val === "yes");
16419
16419
  });
16420
16420
  });
16421
16421
  }
16422
16422
  function choose(question, options) {
16423
- return new Promise((resolve8) => {
16423
+ return new Promise((resolve10) => {
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
- resolve8(options[idx]);
16433
+ resolve10(options[idx]);
16434
16434
  } else {
16435
- resolve8(options[0]);
16435
+ resolve10(options[0]);
16436
16436
  }
16437
16437
  });
16438
16438
  });
@@ -16901,15 +16901,15 @@ 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: existsSync12 } = await import("fs");
16904
+ const { mkdirSync: mkdirSync6, existsSync: existsSync14 } = await import("fs");
16905
16905
  const { writeFile: writeFile6 } = await import("fs/promises");
16906
- const { join: join16 } = await import("path");
16906
+ const { join: join18 } = await import("path");
16907
16907
  const files = [];
16908
- if (!existsSync12(outputDir)) mkdirSync5(outputDir, { recursive: true });
16909
- const rulesDir = join16(outputDir, "rules");
16910
- if (!existsSync12(rulesDir)) mkdirSync5(rulesDir, { recursive: true });
16908
+ if (!existsSync14(outputDir)) mkdirSync6(outputDir, { recursive: true });
16909
+ const rulesDir = join18(outputDir, "rules");
16910
+ if (!existsSync14(rulesDir)) mkdirSync6(rulesDir, { recursive: true });
16911
16911
  const writeJson = async (name, data) => {
16912
- const path = join16(outputDir, name);
16912
+ const path = join18(outputDir, name);
16913
16913
  await writeFile6(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
16914
16914
  files.push(path);
16915
16915
  };
@@ -16921,7 +16921,7 @@ 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 = join16(rulesDir, `${rule.id}.json`);
16924
+ const rulePath = join18(rulesDir, `${rule.id}.json`);
16925
16925
  await writeFile6(rulePath, JSON.stringify(rule, null, 2) + "\n", "utf-8");
16926
16926
  files.push(rulePath);
16927
16927
  }
@@ -17008,7 +17008,7 @@ async function main31(argv = process.argv.slice(2)) {
17008
17008
  }
17009
17009
  async function phaseRefine(outputDir, world) {
17010
17010
  const { writeFile: writeFile6 } = await import("fs/promises");
17011
- const { join: join16 } = await import("path");
17011
+ const { join: join18 } = await import("path");
17012
17012
  heading("Refinement: Thresholds & Collapse");
17013
17013
  const primaryMetric = world.gatesJson.viability_classification[0]?.field || "system_health";
17014
17014
  info(`
@@ -17025,7 +17025,7 @@ async function phaseRefine(outputDir, world) {
17025
17025
  if (!isNaN(parsed)) gate.value = parsed;
17026
17026
  }
17027
17027
  await writeFile6(
17028
- join16(outputDir, "gates.json"),
17028
+ join18(outputDir, "gates.json"),
17029
17029
  JSON.stringify(world.gatesJson, null, 2) + "\n",
17030
17030
  "utf-8"
17031
17031
  );
@@ -17047,7 +17047,7 @@ async function phaseRefine(outputDir, world) {
17047
17047
  result: "MODEL_COLLAPSES"
17048
17048
  };
17049
17049
  await writeFile6(
17050
- join16(outputDir, "rules", `${rule.id}.json`),
17050
+ join18(outputDir, "rules", `${rule.id}.json`),
17051
17051
  JSON.stringify(rule, null, 2) + "\n",
17052
17052
  "utf-8"
17053
17053
  );
@@ -18100,9 +18100,9 @@ async function cmdAdd(argv) {
18100
18100
  id = name.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
18101
18101
  }
18102
18102
  const { readFile: readFile4, writeFile: writeFile6 } = await import("fs/promises");
18103
- const { join: join16 } = await import("path");
18103
+ const { join: join18 } = await import("path");
18104
18104
  const possiblePaths = [
18105
- join16(worldPath, "world.nv-world.md"),
18105
+ join18(worldPath, "world.nv-world.md"),
18106
18106
  worldPath
18107
18107
  ];
18108
18108
  let mdPath = "";
@@ -18123,7 +18123,7 @@ async function cmdAdd(argv) {
18123
18123
  const files = await readdir(worldPath);
18124
18124
  const mdFile = files.find((f) => f.endsWith(".nv-world.md"));
18125
18125
  if (mdFile) {
18126
- mdPath = join16(worldPath, mdFile);
18126
+ mdPath = join18(worldPath, mdFile);
18127
18127
  mdContent = await readFile4(mdPath, "utf-8");
18128
18128
  }
18129
18129
  } catch {
@@ -20473,17 +20473,30 @@ var init_think = __esm({
20473
20473
  });
20474
20474
 
20475
20475
  // src/radiant/core/scopes.ts
20476
- function parseRepoScope(scope) {
20476
+ function parseScope(scope) {
20477
20477
  const cleaned = scope.replace(/^https?:\/\//, "").replace(/^github\.com\//, "").replace(/\.git$/, "").replace(/\/$/, "");
20478
- const parts = cleaned.split("/");
20479
- if (parts.length < 2 || !parts[0] || !parts[1]) {
20478
+ const parts = cleaned.split("/").filter(Boolean);
20479
+ if (parts.length === 0 || !parts[0]) {
20480
20480
  throw new Error(
20481
- `Cannot parse repo scope: "${scope}". Expected "owner/repo" or a GitHub URL.`
20481
+ `Cannot parse scope: "${scope}". Expected "owner/repo" or "owner".`
20482
20482
  );
20483
20483
  }
20484
- return { owner: parts[0], repo: parts[1] };
20484
+ if (parts.length === 1) {
20485
+ return { type: "org", owner: parts[0] };
20486
+ }
20487
+ return { type: "repo", owner: parts[0], repo: parts[1] };
20488
+ }
20489
+ function parseRepoScope(scope) {
20490
+ const parsed = parseScope(scope);
20491
+ if (parsed.type === "org") {
20492
+ throw new Error(
20493
+ `Expected "owner/repo" but got org-level scope "${parsed.owner}". Use parseScope() for org-level.`
20494
+ );
20495
+ }
20496
+ return parsed;
20485
20497
  }
20486
20498
  function formatScope(scope) {
20499
+ if (scope.type === "org") return `${scope.owner} (org)`;
20487
20500
  return `${scope.owner}/${scope.repo}`;
20488
20501
  }
20489
20502
  var init_scopes = __esm({
@@ -20658,6 +20671,40 @@ async function fetchJSON(url, headers) {
20658
20671
  }
20659
20672
  return await res.json();
20660
20673
  }
20674
+ async function fetchGitHubOrgActivity(scope, token, options = {}) {
20675
+ const perPage = options.perPage ?? 100;
20676
+ const headers = {
20677
+ Authorization: `token ${token}`,
20678
+ Accept: "application/vnd.github.v3+json",
20679
+ "User-Agent": "neuroverseos-radiant"
20680
+ };
20681
+ const repos = await fetchJSON(
20682
+ `https://api.github.com/orgs/${scope.owner}/repos?sort=pushed&direction=desc&per_page=${perPage}`,
20683
+ headers
20684
+ );
20685
+ const windowDays = options.windowDays ?? 14;
20686
+ const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1e3);
20687
+ const activeRepos = repos.filter(
20688
+ (r) => new Date(r.pushed_at) >= since
20689
+ );
20690
+ const cappedRepos = activeRepos.slice(0, 10);
20691
+ const allEvents = [];
20692
+ const repoNames = [];
20693
+ for (const repo of cappedRepos) {
20694
+ const [owner, repoName] = repo.full_name.split("/");
20695
+ try {
20696
+ const repoScope = { type: "repo", owner, repo: repoName };
20697
+ const events = await fetchGitHubActivity(repoScope, token, options);
20698
+ allEvents.push(...events);
20699
+ if (events.length > 0) repoNames.push(repo.full_name);
20700
+ } catch {
20701
+ }
20702
+ }
20703
+ allEvents.sort(
20704
+ (a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp)
20705
+ );
20706
+ return { events: allEvents, repos: repoNames };
20707
+ }
20661
20708
  var KNOWN_AI_LOGINS, KNOWN_AI_CO_AUTHOR_NAMES;
20662
20709
  var init_github2 = __esm({
20663
20710
  "src/radiant/adapters/github.ts"() {
@@ -20770,6 +20817,318 @@ var init_exocortex = __esm({
20770
20817
  }
20771
20818
  });
20772
20819
 
20820
+ // src/radiant/memory/palace.ts
20821
+ function writeRead(exocortexDir, frontmatter, text) {
20822
+ const dir = (0, import_path14.resolve)(exocortexDir, "radiant", "reads");
20823
+ (0, import_fs13.mkdirSync)(dir, { recursive: true });
20824
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
20825
+ const filename = `${date}.md`;
20826
+ const filepath = (0, import_path14.join)(dir, filename);
20827
+ const content = `${frontmatter}
20828
+
20829
+ ${text}
20830
+ `;
20831
+ (0, import_fs13.writeFileSync)(filepath, content, "utf-8");
20832
+ return filepath;
20833
+ }
20834
+ function updateKnowledge(exocortexDir, persistence, options) {
20835
+ const dir = (0, import_path14.resolve)(exocortexDir, "radiant");
20836
+ (0, import_fs13.mkdirSync)(dir, { recursive: true });
20837
+ const filepath = (0, import_path14.join)(dir, "knowledge.md");
20838
+ const totalReads = options?.totalReads ?? 0;
20839
+ const existingUntriggered = loadUntriggeredCounts(filepath);
20840
+ const lines = [
20841
+ "# Radiant \u2014 Accumulated Behavioral Knowledge",
20842
+ "",
20843
+ `Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
20844
+ `Total reads: ${totalReads}`,
20845
+ "",
20846
+ "---",
20847
+ "",
20848
+ "## Evolution proposals",
20849
+ ""
20850
+ ];
20851
+ const addCandidates = persistence.filter((p) => p.occurrences >= 3);
20852
+ if (addCandidates.length > 0) {
20853
+ lines.push("### Consider adding");
20854
+ lines.push("");
20855
+ lines.push("These candidate patterns keep recurring. They are not yet in the worldmodel.");
20856
+ lines.push("If they represent real behavioral patterns worth tracking, add them.");
20857
+ lines.push("If they were temporary, dismiss them.");
20858
+ lines.push("");
20859
+ for (const p of addCandidates) {
20860
+ lines.push(
20861
+ `- **${p.name}** \u2014 observed ${p.occurrences} times (${p.dates.join(", ")}). Add to auki-strategy.worldmodel.md \u2192 Evolution Layer \u2192 Drift Behaviors (if concerning) or Aligned Behaviors (if healthy).`
20862
+ );
20863
+ }
20864
+ lines.push("");
20865
+ }
20866
+ if (options?.declaredItems && options.declaredItems.length > 0) {
20867
+ const triggered = new Set(options.triggeredItems ?? []);
20868
+ const removeCandidates = [];
20869
+ for (const item of options.declaredItems) {
20870
+ if (!triggered.has(item.name)) {
20871
+ const prior = existingUntriggered.get(item.name) ?? 0;
20872
+ const count = prior + 1;
20873
+ existingUntriggered.set(item.name, count);
20874
+ if (count >= 4) {
20875
+ removeCandidates.push({ item, weeksSilent: count });
20876
+ }
20877
+ } else {
20878
+ existingUntriggered.set(item.name, 0);
20879
+ }
20880
+ }
20881
+ if (removeCandidates.length > 0) {
20882
+ lines.push("### Consider removing");
20883
+ lines.push("");
20884
+ lines.push("These items are declared in the worldmodel but haven't triggered in multiple reads.");
20885
+ lines.push("Either the team has internalized them (the rule is redundant) or they haven't been tested.");
20886
+ lines.push("A lean worldmodel with 5 sharp invariants is stronger than a bloated one with 20.");
20887
+ lines.push("");
20888
+ for (const { item, weeksSilent } of removeCandidates) {
20889
+ lines.push(
20890
+ `- **${item.name}** (${item.type}) \u2014 hasn't triggered in ${weeksSilent} reads. Internalized or untested? Review whether it still earns its place.`
20891
+ );
20892
+ }
20893
+ lines.push("");
20894
+ }
20895
+ }
20896
+ if (options?.triggeredItems && options.triggeredItems.length > 0) {
20897
+ lines.push("### Keep (recently active)");
20898
+ lines.push("");
20899
+ lines.push("These worldmodel items triggered governance in the most recent read. They're earning their place.");
20900
+ lines.push("");
20901
+ for (const name of options.triggeredItems) {
20902
+ lines.push(`- **${name}** \u2014 triggered this read. Holding.`);
20903
+ }
20904
+ lines.push("");
20905
+ }
20906
+ lines.push("---");
20907
+ lines.push("");
20908
+ lines.push("## Pattern persistence (all observed)");
20909
+ lines.push("");
20910
+ for (const p of persistence) {
20911
+ const status = p.occurrences >= 4 ? "**persistent**" : p.occurrences >= 2 ? "recurring" : "observed once";
20912
+ lines.push(`### ${p.name}`);
20913
+ lines.push(`- Status: ${status}`);
20914
+ lines.push(`- Observed ${p.occurrences} time${p.occurrences > 1 ? "s" : ""}: ${p.dates.join(", ")}`);
20915
+ lines.push("");
20916
+ }
20917
+ lines.push("---");
20918
+ lines.push("");
20919
+ lines.push("<!-- untriggered_counts (machine-readable, do not edit)");
20920
+ for (const [name, count] of existingUntriggered.entries()) {
20921
+ lines.push(`${name}=${count}`);
20922
+ }
20923
+ lines.push("-->");
20924
+ (0, import_fs13.writeFileSync)(filepath, lines.join("\n"), "utf-8");
20925
+ return filepath;
20926
+ }
20927
+ function loadUntriggeredCounts(filepath) {
20928
+ const counts = /* @__PURE__ */ new Map();
20929
+ if (!(0, import_fs13.existsSync)(filepath)) return counts;
20930
+ try {
20931
+ const content = (0, import_fs13.readFileSync)(filepath, "utf-8");
20932
+ const match = content.match(
20933
+ /<!-- untriggered_counts[\s\S]*?-->/
20934
+ );
20935
+ if (match) {
20936
+ const lines = match[0].split("\n");
20937
+ for (const line of lines) {
20938
+ const eq = line.match(/^([^=]+)=(\d+)$/);
20939
+ if (eq) {
20940
+ counts.set(eq[1], parseInt(eq[2], 10));
20941
+ }
20942
+ }
20943
+ }
20944
+ } catch {
20945
+ }
20946
+ return counts;
20947
+ }
20948
+ function loadPriorReads(exocortexDir) {
20949
+ const dir = (0, import_path14.resolve)(exocortexDir, "radiant", "reads");
20950
+ if (!(0, import_fs13.existsSync)(dir)) return [];
20951
+ const files = (0, import_fs13.readdirSync)(dir).filter((f) => f.endsWith(".md")).sort();
20952
+ const reads = [];
20953
+ for (const filename of files) {
20954
+ const filepath = (0, import_path14.join)(dir, filename);
20955
+ const content = (0, import_fs13.readFileSync)(filepath, "utf-8");
20956
+ const date = filename.replace(".md", "");
20957
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
20958
+ const frontmatter = fmMatch ? fmMatch[1] : "";
20959
+ const patternNames = [];
20960
+ const nameMatches = frontmatter.matchAll(/- name: ["']?([^"'\n]+)["']?/g);
20961
+ for (const m of nameMatches) {
20962
+ patternNames.push(m[1].trim());
20963
+ }
20964
+ reads.push({ date, filename, patternNames, frontmatter });
20965
+ }
20966
+ return reads;
20967
+ }
20968
+ function computePersistence(priorReads, currentPatternNames) {
20969
+ const allPatterns = /* @__PURE__ */ new Map();
20970
+ for (const read of priorReads) {
20971
+ for (const name of read.patternNames) {
20972
+ const dates = allPatterns.get(name) ?? [];
20973
+ if (!dates.includes(read.date)) dates.push(read.date);
20974
+ allPatterns.set(name, dates);
20975
+ }
20976
+ }
20977
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
20978
+ for (const name of currentPatternNames) {
20979
+ const dates = allPatterns.get(name) ?? [];
20980
+ if (!dates.includes(today)) dates.push(today);
20981
+ allPatterns.set(name, dates);
20982
+ }
20983
+ return Array.from(allPatterns.entries()).map(([name, dates]) => ({
20984
+ name,
20985
+ occurrences: dates.length,
20986
+ dates: dates.sort()
20987
+ })).sort((a, b) => b.occurrences - a.occurrences);
20988
+ }
20989
+ function formatPriorReadsForPrompt(priorReads) {
20990
+ if (priorReads.length === 0) return "";
20991
+ const lines = [
20992
+ "## Prior Radiant reads (history)",
20993
+ "",
20994
+ `Radiant has run ${priorReads.length} time${priorReads.length > 1 ? "s" : ""} before on this scope.`,
20995
+ "If you see patterns that appeared in prior reads, note their persistence.",
20996
+ "Patterns that recur across 3+ reads are strong candidates for declaration in the strategy file.",
20997
+ ""
20998
+ ];
20999
+ for (const read of priorReads.slice(-4)) {
21000
+ lines.push(`### Read from ${read.date}`);
21001
+ if (read.patternNames.length > 0) {
21002
+ lines.push(`Patterns observed: ${read.patternNames.join(", ")}`);
21003
+ } else {
21004
+ lines.push("No patterns extracted from frontmatter.");
21005
+ }
21006
+ lines.push("");
21007
+ }
21008
+ return lines.join("\n");
21009
+ }
21010
+ var import_fs13, import_path14;
21011
+ var init_palace = __esm({
21012
+ "src/radiant/memory/palace.ts"() {
21013
+ "use strict";
21014
+ import_fs13 = require("fs");
21015
+ import_path14 = require("path");
21016
+ }
21017
+ });
21018
+
21019
+ // src/radiant/core/governance.ts
21020
+ async function auditGovernance(events, worldPath) {
21021
+ let world;
21022
+ try {
21023
+ world = await loadWorld(worldPath);
21024
+ } catch {
21025
+ return emptyAudit(events.length, "Could not load compiled worldmodel for governance audit.");
21026
+ }
21027
+ const verdicts = [];
21028
+ for (const ce of events) {
21029
+ const intent = ce.event.content?.slice(0, 500) || ce.event.kind || "activity";
21030
+ const scope = ce.event.metadata?.scope || void 0;
21031
+ try {
21032
+ const result = evaluateGuard(
21033
+ {
21034
+ intent,
21035
+ scope,
21036
+ actionCategory: mapKindToCategory(ce.event.kind)
21037
+ },
21038
+ world
21039
+ );
21040
+ verdicts.push({
21041
+ eventId: ce.event.id,
21042
+ domain: ce.domain,
21043
+ status: result.status,
21044
+ reason: result.reason,
21045
+ ruleId: result.ruleId,
21046
+ warning: result.warning
21047
+ });
21048
+ } catch {
21049
+ verdicts.push({
21050
+ eventId: ce.event.id,
21051
+ domain: ce.domain,
21052
+ status: "ALLOW",
21053
+ reason: "guard evaluation skipped (error)"
21054
+ });
21055
+ }
21056
+ }
21057
+ const human = bucketVerdicts(verdicts.filter((v) => v.domain === "life"));
21058
+ const cyber = bucketVerdicts(verdicts.filter((v) => v.domain === "cyber"));
21059
+ const joint = bucketVerdicts(verdicts.filter((v) => v.domain === "joint"));
21060
+ const summary2 = buildSummary(human, cyber, joint, events.length);
21061
+ return {
21062
+ totalEvents: events.length,
21063
+ human,
21064
+ cyber,
21065
+ joint,
21066
+ summary: summary2
21067
+ };
21068
+ }
21069
+ function bucketVerdicts(verdicts) {
21070
+ const nonAllow = verdicts.filter((v) => v.status !== "ALLOW");
21071
+ return {
21072
+ allow: verdicts.filter((v) => v.status === "ALLOW").length,
21073
+ modify: verdicts.filter((v) => v.status === "MODIFY").length,
21074
+ block: verdicts.filter((v) => v.status === "BLOCK").length,
21075
+ details: nonAllow
21076
+ };
21077
+ }
21078
+ function buildSummary(human, cyber, joint, total) {
21079
+ const humanTriggered = human.modify + human.block;
21080
+ const cyberTriggered = cyber.modify + cyber.block;
21081
+ const jointTriggered = joint.modify + joint.block;
21082
+ const totalTriggered = humanTriggered + cyberTriggered + jointTriggered;
21083
+ if (totalTriggered === 0) {
21084
+ return `${total} events evaluated. All passed. The cocoon held \u2014 no governance triggered.`;
21085
+ }
21086
+ const parts = [];
21087
+ parts.push(`${total} events evaluated. ${totalTriggered} triggered governance.`);
21088
+ if (humanTriggered > 0) {
21089
+ parts.push(`Human side: ${humanTriggered} (${human.block} blocked, ${human.modify} modified).`);
21090
+ }
21091
+ if (cyberTriggered > 0) {
21092
+ parts.push(`AI side: ${cyberTriggered} (${cyber.block} blocked, ${cyber.modify} modified).`);
21093
+ }
21094
+ if (jointTriggered > 0) {
21095
+ parts.push(`Joint work: ${jointTriggered} (${joint.block} blocked, ${joint.modify} modified).`);
21096
+ }
21097
+ if (humanTriggered > 0 && cyberTriggered > 0) {
21098
+ const ratio = humanTriggered / cyberTriggered;
21099
+ if (ratio > 2) {
21100
+ parts.push("Human side is testing the frame more than AI. Either the worldmodel needs calibrating for human workflows, or humans are genuinely drifting.");
21101
+ } else if (ratio < 0.5) {
21102
+ parts.push("AI side is testing the frame more than humans. Check whether the AI's output patterns match the declared invariants.");
21103
+ } else {
21104
+ parts.push("Roughly balanced between human and AI \u2014 both sides are testing the frame.");
21105
+ }
21106
+ }
21107
+ return parts.join(" ");
21108
+ }
21109
+ function mapKindToCategory(kind) {
21110
+ if (!kind) return "other";
21111
+ if (kind.includes("commit") || kind.includes("merge")) return "write";
21112
+ if (kind.includes("review") || kind.includes("comment")) return "read";
21113
+ return "other";
21114
+ }
21115
+ function emptyAudit(total, reason) {
21116
+ return {
21117
+ totalEvents: total,
21118
+ human: { allow: 0, modify: 0, block: 0, details: [] },
21119
+ cyber: { allow: 0, modify: 0, block: 0, details: [] },
21120
+ joint: { allow: 0, modify: 0, block: 0, details: [] },
21121
+ summary: reason
21122
+ };
21123
+ }
21124
+ var init_governance = __esm({
21125
+ "src/radiant/core/governance.ts"() {
21126
+ "use strict";
21127
+ init_guard_engine();
21128
+ init_world_loader();
21129
+ }
21130
+ });
21131
+
20773
21132
  // src/radiant/core/domain.ts
20774
21133
  function isLifeSide(k) {
20775
21134
  return k === "human" || k === "unknown";
@@ -21060,6 +21419,14 @@ ${jargonTable}
21060
21419
 
21061
21420
  For example: don't say "update the worldmodel." Say "add a line to your strategy file."
21062
21421
 
21422
+ ## When the same invariant keeps firing
21423
+
21424
+ If the prior read history or the current evidence shows the same worldmodel invariant being triggered repeatedly (by the same side \u2014 human or AI), name it in MEANING and ask the real question:
21425
+
21426
+ "This invariant has been tested N times across M reads. Always on the [human/AI] side. Either the team needs alignment on WHY this rule exists \u2014 or the team is telling you something the worldmodel hasn't absorbed yet."
21427
+
21428
+ Don't just say "invariant held." Say what it means that people keep pushing against the same wall.
21429
+
21063
21430
  ## Health is a valid read
21064
21431
 
21065
21432
  If the activity is healthy and aligned with the worldmodel, SAY SO. Don't fabricate problems. Over-prescription is a voice failure. Legitimate outputs include:
@@ -21088,7 +21455,7 @@ Only recommend a move when the evidence actually calls for one.
21088
21455
  }
21089
21456
  ],
21090
21457
  "meaning": "3-5 sentences. Weave the patterns into ONE strategic thesis. Compress. The reader should finish this paragraph and understand the one thing that matters most in this read. Plain English \u2014 no system jargon.",
21091
- "move": "1-3 direct imperatives, OR explicit 'nothing to act on' if the read is healthy. Do not fabricate urgency. Examples: 'Force cross-module ownership this sprint.' / 'Nothing's broken. Keep shipping.' / 'If you want future reads to track this pattern by name, add a line to your strategy file.'"
21458
+ "move": "1-3 direct imperatives, OR explicit 'nothing to act on' if the read is healthy. Do not fabricate urgency. When a candidate pattern has high confidence (>0.6), tell the reader EXACTLY where to declare it: 'If you want Radiant to track [pattern_name] over time, add it to auki-strategy.worldmodel.md under Evolution Layer \u2192 Drift Behaviors (or Aligned Behaviors if it is positive). If you don't, Radiant will rediscover it from scratch next run.' Be specific about the file and section \u2014 don't make them guess."
21092
21459
  }
21093
21460
  \`\`\`
21094
21461
 
@@ -21249,6 +21616,27 @@ Lens: ${input.lens.name}`
21249
21616
  ` Composite: ${formatScore(input.scores.R)}`
21250
21617
  ].join("\n");
21251
21618
  sections.push(alignBlock);
21619
+ if (input.governance && input.governance.totalEvents > 0) {
21620
+ const gov = input.governance;
21621
+ const govLines = ["GOVERNANCE", "", ` ${gov.summary}`];
21622
+ const showSide = (label, side) => {
21623
+ if (side.allow + side.modify + side.block === 0) return;
21624
+ govLines.push("");
21625
+ govLines.push(` ${label}:`);
21626
+ govLines.push(` ${side.allow} ALLOW \xB7 ${side.modify} MODIFY \xB7 ${side.block} BLOCK`);
21627
+ for (const d of side.details.slice(0, 3)) {
21628
+ const reason = d.reason ? ` \u2192 ${d.reason}` : "";
21629
+ govLines.push(` ${d.status}: ${d.eventId}${reason}`);
21630
+ }
21631
+ if (side.details.length > 3) {
21632
+ govLines.push(` ... and ${side.details.length - 3} more`);
21633
+ }
21634
+ };
21635
+ showSide("Human side", gov.human);
21636
+ showSide("AI side", gov.cyber);
21637
+ showSide("Human\u2013AI joint", gov.joint);
21638
+ sections.push(govLines.join("\n"));
21639
+ }
21252
21640
  sections.push(renderDepth(input.priorReadCount ?? 0, input.windowDays));
21253
21641
  return sections.join("\n\n");
21254
21642
  }
@@ -21425,14 +21813,31 @@ async function emergent(input) {
21425
21813
  const windowDays = input.windowDays ?? 14;
21426
21814
  let statedIntent;
21427
21815
  let exocortexContext;
21816
+ let priorReadContext = "";
21428
21817
  if (input.exocortexPath) {
21429
21818
  exocortexContext = readExocortex(input.exocortexPath);
21430
21819
  const formatted = formatExocortexForPrompt(exocortexContext);
21431
21820
  if (formatted) statedIntent = formatted;
21821
+ const priorReads = loadPriorReads(input.exocortexPath);
21822
+ if (priorReads.length > 0) {
21823
+ priorReadContext = formatPriorReadsForPrompt(priorReads);
21824
+ }
21825
+ }
21826
+ let events;
21827
+ let orgRepos;
21828
+ if (input.scope.type === "org") {
21829
+ const orgResult = await fetchGitHubOrgActivity(
21830
+ input.scope,
21831
+ input.githubToken,
21832
+ { windowDays }
21833
+ );
21834
+ events = orgResult.events;
21835
+ orgRepos = orgResult.repos;
21836
+ } else {
21837
+ events = await fetchGitHubActivity(input.scope, input.githubToken, {
21838
+ windowDays
21839
+ });
21432
21840
  }
21433
- const events = await fetchGitHubActivity(input.scope, input.githubToken, {
21434
- windowDays
21435
- });
21436
21841
  const classified = classifyEvents(events);
21437
21842
  const signals = extractSignals(classified);
21438
21843
  const scores = computeScores(signals, input.worldmodelContent !== "");
@@ -21443,11 +21848,18 @@ async function emergent(input) {
21443
21848
  lens,
21444
21849
  ai: input.ai,
21445
21850
  canonicalPatterns: input.canonicalPatterns,
21446
- statedIntent
21851
+ statedIntent: statedIntent ? statedIntent + (priorReadContext ? "\n\n" + priorReadContext : "") : priorReadContext || void 0
21447
21852
  });
21448
21853
  const rewrittenPatterns = patterns.map((p) => lens.rewrite(p));
21449
21854
  const allDescriptions = rewrittenPatterns.map((p) => p.description).join("\n");
21450
21855
  const voiceViolations = checkForbiddenPhrases(lens, allDescriptions);
21856
+ let governance;
21857
+ if (input.worldPath) {
21858
+ try {
21859
+ governance = await auditGovernance(classified, input.worldPath);
21860
+ } catch {
21861
+ }
21862
+ }
21451
21863
  const rendered = render({
21452
21864
  scope: input.scope,
21453
21865
  windowDays,
@@ -21457,8 +21869,27 @@ async function emergent(input) {
21457
21869
  scores,
21458
21870
  lens,
21459
21871
  meaning: meaning || void 0,
21460
- move: move || void 0
21872
+ move: move || void 0,
21873
+ governance
21461
21874
  });
21875
+ if (input.exocortexPath) {
21876
+ try {
21877
+ const readPath = writeRead(input.exocortexPath, rendered.frontmatter, rendered.text);
21878
+ const priorReads = loadPriorReads(input.exocortexPath);
21879
+ const currentPatternNames = rewrittenPatterns.map((p) => p.name);
21880
+ const persistence = computePersistence(priorReads, currentPatternNames);
21881
+ const triggeredItems = governance ? [
21882
+ ...governance.human.details.map((d) => d.ruleId).filter(Boolean),
21883
+ ...governance.cyber.details.map((d) => d.ruleId).filter(Boolean),
21884
+ ...governance.joint.details.map((d) => d.ruleId).filter(Boolean)
21885
+ ] : [];
21886
+ updateKnowledge(input.exocortexPath, persistence, {
21887
+ triggeredItems,
21888
+ totalReads: priorReads.length + 1
21889
+ });
21890
+ } catch {
21891
+ }
21892
+ }
21462
21893
  return {
21463
21894
  text: rendered.text,
21464
21895
  frontmatter: rendered.frontmatter,
@@ -21522,6 +21953,8 @@ var init_emergent = __esm({
21522
21953
  init_lenses();
21523
21954
  init_github2();
21524
21955
  init_exocortex();
21956
+ init_palace();
21957
+ init_governance();
21525
21958
  init_signals();
21526
21959
  init_math();
21527
21960
  init_patterns();
@@ -21570,6 +22003,277 @@ var init_ai = __esm({
21570
22003
  }
21571
22004
  });
21572
22005
 
22006
+ // src/radiant/mcp/server.ts
22007
+ var server_exports = {};
22008
+ __export(server_exports, {
22009
+ RadiantMcpServer: () => RadiantMcpServer,
22010
+ startRadiantMcp: () => startRadiantMcp
22011
+ });
22012
+ function loadWorldmodelContent(worldsPath) {
22013
+ const resolved = (0, import_path15.resolve)(worldsPath);
22014
+ if (!(0, import_fs14.existsSync)(resolved)) {
22015
+ throw new Error(`Worlds path not found: ${resolved}`);
22016
+ }
22017
+ const stat = (0, import_fs14.statSync)(resolved);
22018
+ if (stat.isFile()) {
22019
+ return (0, import_fs14.readFileSync)(resolved, "utf-8");
22020
+ }
22021
+ if (stat.isDirectory()) {
22022
+ const files = (0, import_fs14.readdirSync)(resolved).filter(
22023
+ (f) => (0, import_path15.extname)(f) === ".md" && (f.endsWith(".worldmodel.md") || f.endsWith(".nv-world.md"))
22024
+ ).sort();
22025
+ if (files.length === 0) {
22026
+ throw new Error(`No worldmodel files found in ${resolved}`);
22027
+ }
22028
+ return files.map((f) => (0, import_fs14.readFileSync)((0, import_path15.join)(resolved, f), "utf-8")).join("\n\n---\n\n");
22029
+ }
22030
+ throw new Error(`Worlds path is neither a file nor directory: ${resolved}`);
22031
+ }
22032
+ async function startRadiantMcp(args) {
22033
+ function parseArg3(flag) {
22034
+ const idx = args.indexOf(flag);
22035
+ return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : void 0;
22036
+ }
22037
+ const worldsPath = parseArg3("--worlds") ?? process.env.RADIANT_WORLDS;
22038
+ const lensId = parseArg3("--lens") ?? process.env.RADIANT_LENS ?? "auki-builder";
22039
+ const model = parseArg3("--model") ?? process.env.RADIANT_MODEL;
22040
+ if (!worldsPath) {
22041
+ process.stderr.write("Error: --worlds <dir> or RADIANT_WORLDS required.\n");
22042
+ process.exit(1);
22043
+ }
22044
+ const server = new RadiantMcpServer({ worldsPath, lensId, model });
22045
+ await server.start();
22046
+ }
22047
+ var import_fs14, import_path15, TOOLS, RadiantMcpServer;
22048
+ var init_server = __esm({
22049
+ "src/radiant/mcp/server.ts"() {
22050
+ "use strict";
22051
+ import_fs14 = require("fs");
22052
+ import_path15 = require("path");
22053
+ init_think();
22054
+ init_emergent();
22055
+ init_ai();
22056
+ init_scopes();
22057
+ TOOLS = [
22058
+ {
22059
+ name: "radiant_think",
22060
+ description: "Send a query through the loaded worldmodel + rendering lens and get an Auki-framed response. Use this for strategic questions, decision evaluation, or any question that should be interpreted through the organization's behavioral model.",
22061
+ inputSchema: {
22062
+ type: "object",
22063
+ properties: {
22064
+ query: {
22065
+ type: "string",
22066
+ description: "The question or prompt to interpret through the worldmodel + lens."
22067
+ }
22068
+ },
22069
+ required: ["query"]
22070
+ }
22071
+ },
22072
+ {
22073
+ name: "radiant_emergent",
22074
+ description: "Run a behavioral read on a GitHub repository. Fetches recent activity, classifies events, extracts signals, identifies patterns, computes alignment scores, and produces the EMERGENT / MEANING / MOVE / ALIGNMENT output. Use this when asked about team activity, coordination patterns, or alignment with the worldmodel.",
22075
+ inputSchema: {
22076
+ type: "object",
22077
+ properties: {
22078
+ scope: {
22079
+ type: "string",
22080
+ description: 'GitHub repository in "owner/repo" format (e.g. "aukiverse/posemesh").'
22081
+ },
22082
+ exocortex_dir: {
22083
+ type: "string",
22084
+ description: "Optional path to an exocortex directory for stated-intent-vs-observed-behavior comparison."
22085
+ }
22086
+ },
22087
+ required: ["scope"]
22088
+ }
22089
+ }
22090
+ ];
22091
+ RadiantMcpServer = class {
22092
+ config;
22093
+ worldmodelContent;
22094
+ buffer = "";
22095
+ constructor(config) {
22096
+ this.config = config;
22097
+ this.worldmodelContent = loadWorldmodelContent(config.worldsPath);
22098
+ }
22099
+ async start() {
22100
+ process.stderr.write(
22101
+ `Radiant MCP server starting
22102
+ Worlds: ${this.config.worldsPath}
22103
+ Lens: ${this.config.lensId}
22104
+ Tools: radiant_think, radiant_emergent
22105
+ `
22106
+ );
22107
+ process.stdin.setEncoding("utf-8");
22108
+ process.stdin.on("data", (chunk) => {
22109
+ this.buffer += chunk;
22110
+ this.processBuffer();
22111
+ });
22112
+ process.stdin.on("end", () => {
22113
+ process.exit(0);
22114
+ });
22115
+ }
22116
+ processBuffer() {
22117
+ const lines = this.buffer.split("\n");
22118
+ this.buffer = lines.pop() ?? "";
22119
+ for (const line of lines) {
22120
+ const trimmed = line.trim();
22121
+ if (!trimmed) continue;
22122
+ try {
22123
+ const request = JSON.parse(trimmed);
22124
+ this.handleRequest(request).catch((err) => {
22125
+ this.sendError(request.id, -32603, String(err));
22126
+ });
22127
+ } catch {
22128
+ }
22129
+ }
22130
+ }
22131
+ async handleRequest(req) {
22132
+ switch (req.method) {
22133
+ case "initialize":
22134
+ this.sendResult(req.id, {
22135
+ protocolVersion: "2024-11-05",
22136
+ capabilities: { tools: {} },
22137
+ serverInfo: {
22138
+ name: "radiant",
22139
+ version: "0.6.1"
22140
+ }
22141
+ });
22142
+ break;
22143
+ case "notifications/initialized":
22144
+ break;
22145
+ case "tools/list":
22146
+ this.sendResult(req.id, { tools: TOOLS });
22147
+ break;
22148
+ case "tools/call":
22149
+ await this.handleToolCall(req);
22150
+ break;
22151
+ default:
22152
+ this.sendError(req.id, -32601, `Unknown method: ${req.method}`);
22153
+ }
22154
+ }
22155
+ async handleToolCall(req) {
22156
+ const params = req.params;
22157
+ if (!params?.name) {
22158
+ this.sendError(req.id, -32602, "Missing tool name");
22159
+ return;
22160
+ }
22161
+ const args = params.arguments ?? {};
22162
+ try {
22163
+ switch (params.name) {
22164
+ case "radiant_think":
22165
+ await this.handleThink(req.id, args);
22166
+ break;
22167
+ case "radiant_emergent":
22168
+ await this.handleEmergent(req.id, args);
22169
+ break;
22170
+ default:
22171
+ this.sendError(req.id, -32602, `Unknown tool: ${params.name}`);
22172
+ }
22173
+ } catch (err) {
22174
+ this.sendResult(req.id, {
22175
+ content: [{ type: "text", text: `Error: ${err}` }],
22176
+ isError: true
22177
+ });
22178
+ }
22179
+ }
22180
+ async handleThink(id, args) {
22181
+ const query = String(args.query ?? "");
22182
+ if (!query) {
22183
+ this.sendResult(id, {
22184
+ content: [{ type: "text", text: "Error: query is required" }],
22185
+ isError: true
22186
+ });
22187
+ return;
22188
+ }
22189
+ const apiKey = process.env.ANTHROPIC_API_KEY;
22190
+ if (!apiKey) {
22191
+ this.sendResult(id, {
22192
+ content: [{ type: "text", text: "Error: ANTHROPIC_API_KEY not set" }],
22193
+ isError: true
22194
+ });
22195
+ return;
22196
+ }
22197
+ const ai = createAnthropicAI(apiKey, this.config.model || void 0);
22198
+ const result = await think({
22199
+ worldmodelContent: this.worldmodelContent,
22200
+ lensId: this.config.lensId,
22201
+ query,
22202
+ ai
22203
+ });
22204
+ let text = result.response;
22205
+ if (!result.voiceClean) {
22206
+ text += `
22207
+
22208
+ \u26A0 Voice violations detected: ${result.voiceViolations.map((v) => v.phrase).join(", ")}`;
22209
+ }
22210
+ this.sendResult(id, {
22211
+ content: [{ type: "text", text }]
22212
+ });
22213
+ }
22214
+ async handleEmergent(id, args) {
22215
+ const scopeStr = String(args.scope ?? "");
22216
+ if (!scopeStr) {
22217
+ this.sendResult(id, {
22218
+ content: [{ type: "text", text: 'Error: scope is required (e.g. "aukiverse/posemesh")' }],
22219
+ isError: true
22220
+ });
22221
+ return;
22222
+ }
22223
+ const apiKey = process.env.ANTHROPIC_API_KEY;
22224
+ const githubToken = process.env.GITHUB_TOKEN;
22225
+ if (!apiKey) {
22226
+ this.sendResult(id, {
22227
+ content: [{ type: "text", text: "Error: ANTHROPIC_API_KEY not set" }],
22228
+ isError: true
22229
+ });
22230
+ return;
22231
+ }
22232
+ if (!githubToken) {
22233
+ this.sendResult(id, {
22234
+ content: [{ type: "text", text: "Error: GITHUB_TOKEN not set" }],
22235
+ isError: true
22236
+ });
22237
+ return;
22238
+ }
22239
+ const scope = parseRepoScope(scopeStr);
22240
+ const ai = createAnthropicAI(apiKey, this.config.model || void 0);
22241
+ const exocortexPath = args.exocortex_dir ? String(args.exocortex_dir) : void 0;
22242
+ const result = await emergent({
22243
+ scope,
22244
+ githubToken,
22245
+ worldmodelContent: this.worldmodelContent,
22246
+ lensId: this.config.lensId,
22247
+ ai,
22248
+ windowDays: 14,
22249
+ exocortexPath
22250
+ });
22251
+ let text = result.text;
22252
+ if (!result.voiceClean) {
22253
+ text += `
22254
+
22255
+ \u26A0 Voice violations: ${result.voiceViolations.map((v) => v.phrase).join(", ")}`;
22256
+ }
22257
+ this.sendResult(id, {
22258
+ content: [{ type: "text", text }]
22259
+ });
22260
+ }
22261
+ sendResult(id, result) {
22262
+ const response = { jsonrpc: "2.0", id, result };
22263
+ process.stdout.write(JSON.stringify(response) + "\n");
22264
+ }
22265
+ sendError(id, code, message) {
22266
+ const response = {
22267
+ jsonrpc: "2.0",
22268
+ id: id ?? null,
22269
+ error: { code, message }
22270
+ };
22271
+ process.stdout.write(JSON.stringify(response) + "\n");
22272
+ }
22273
+ };
22274
+ }
22275
+ });
22276
+
21573
22277
  // src/cli/radiant.ts
21574
22278
  var radiant_exports = {};
21575
22279
  __export(radiant_exports, {
@@ -21583,6 +22287,8 @@ function parseArgs27(argv) {
21583
22287
  query: void 0,
21584
22288
  model: void 0,
21585
22289
  exocortex: void 0,
22290
+ teamExocortex: void 0,
22291
+ view: void 0,
21586
22292
  json: false,
21587
22293
  help: false,
21588
22294
  rest: []
@@ -21610,6 +22316,12 @@ function parseArgs27(argv) {
21610
22316
  case "--exocortex":
21611
22317
  result.exocortex = argv[++i];
21612
22318
  break;
22319
+ case "--team-exocortex":
22320
+ result.teamExocortex = argv[++i];
22321
+ break;
22322
+ case "--view":
22323
+ result.view = argv[++i];
22324
+ break;
21613
22325
  case "--json":
21614
22326
  result.json = true;
21615
22327
  break;
@@ -21625,18 +22337,18 @@ function parseArgs27(argv) {
21625
22337
  }
21626
22338
  return result;
21627
22339
  }
21628
- function loadWorldmodelContent(worldsPath) {
21629
- const resolved = (0, import_path14.resolve)(worldsPath);
21630
- if (!(0, import_fs13.existsSync)(resolved)) {
22340
+ function loadWorldmodelContent2(worldsPath) {
22341
+ const resolved = (0, import_path16.resolve)(worldsPath);
22342
+ if (!(0, import_fs15.existsSync)(resolved)) {
21631
22343
  throw new Error(`Worlds path not found: ${resolved}`);
21632
22344
  }
21633
- const stat = (0, import_fs13.statSync)(resolved);
22345
+ const stat = (0, import_fs15.statSync)(resolved);
21634
22346
  if (stat.isFile()) {
21635
- return (0, import_fs13.readFileSync)(resolved, "utf-8");
22347
+ return (0, import_fs15.readFileSync)(resolved, "utf-8");
21636
22348
  }
21637
22349
  if (stat.isDirectory()) {
21638
- const files = (0, import_fs13.readdirSync)(resolved).filter(
21639
- (f) => (0, import_path14.extname)(f) === ".md" && (f.endsWith(".worldmodel.md") || f.endsWith(".nv-world.md"))
22350
+ const files = (0, import_fs15.readdirSync)(resolved).filter(
22351
+ (f) => (0, import_path16.extname)(f) === ".md" && (f.endsWith(".worldmodel.md") || f.endsWith(".nv-world.md"))
21640
22352
  ).sort();
21641
22353
  if (files.length === 0) {
21642
22354
  throw new Error(
@@ -21644,7 +22356,7 @@ function loadWorldmodelContent(worldsPath) {
21644
22356
  );
21645
22357
  }
21646
22358
  return files.map((f) => {
21647
- const content = (0, import_fs13.readFileSync)((0, import_path14.join)(resolved, f), "utf-8");
22359
+ const content = (0, import_fs15.readFileSync)((0, import_path16.join)(resolved, f), "utf-8");
21648
22360
  return `<!-- worldmodel: ${f} -->
21649
22361
  ${content}`;
21650
22362
  }).join("\n\n---\n\n");
@@ -21683,7 +22395,7 @@ ${DIM3}Set it to your Anthropic API key to use Radiant's AI features.${RESET3}
21683
22395
  query = args.rest.join(" ");
21684
22396
  }
21685
22397
  if (!query && !process.stdin.isTTY) {
21686
- query = (0, import_fs13.readFileSync)(0, "utf-8").trim();
22398
+ query = (0, import_fs15.readFileSync)(0, "utf-8").trim();
21687
22399
  }
21688
22400
  if (!query) {
21689
22401
  process.stderr.write(
@@ -21693,7 +22405,7 @@ ${DIM3}Use --query "...", pass as trailing args, or pipe via stdin.${RESET3}
21693
22405
  );
21694
22406
  process.exit(1);
21695
22407
  }
21696
- const worldmodelContent = loadWorldmodelContent(worldsPath);
22408
+ const worldmodelContent = loadWorldmodelContent2(worldsPath);
21697
22409
  const model = args.model ?? process.env.RADIANT_MODEL;
21698
22410
  const ai = createAnthropicAI(apiKey, model || void 0);
21699
22411
  process.stderr.write(
@@ -21751,7 +22463,7 @@ async function cmdEmergent(args) {
21751
22463
  );
21752
22464
  process.exit(1);
21753
22465
  }
21754
- const scope = parseRepoScope(scopeStr);
22466
+ const scope = parseScope(scopeStr);
21755
22467
  const lensId = args.lens ?? process.env.RADIANT_LENS;
21756
22468
  if (!lensId) {
21757
22469
  process.stderr.write(
@@ -21786,9 +22498,18 @@ ${DIM3}Set it to a GitHub PAT with repo read access.${RESET3}
21786
22498
  );
21787
22499
  process.exit(1);
21788
22500
  }
21789
- const worldmodelContent = loadWorldmodelContent(worldsPath);
22501
+ const worldmodelContent = loadWorldmodelContent2(worldsPath);
21790
22502
  const model = args.model ?? process.env.RADIANT_MODEL;
21791
22503
  const ai = createAnthropicAI(anthropicKey, model || void 0);
22504
+ const view = args.view ?? process.env.RADIANT_VIEW ?? "community";
22505
+ const validViews = ["community", "team", "full"];
22506
+ if (!validViews.includes(view)) {
22507
+ process.stderr.write(
22508
+ `${RED2}Error:${RESET3} --view must be community, team, or full. Got "${view}".
22509
+ `
22510
+ );
22511
+ process.exit(1);
22512
+ }
21792
22513
  const exocortexPath = args.exocortex ?? process.env.RADIANT_EXOCORTEX;
21793
22514
  let exocortexStatus = "not loaded";
21794
22515
  if (exocortexPath) {
@@ -21796,7 +22517,8 @@ ${DIM3}Set it to a GitHub PAT with repo read access.${RESET3}
21796
22517
  exocortexStatus = summarizeExocortex(ctx);
21797
22518
  }
21798
22519
  process.stderr.write(
21799
- `${DIM3}Scope: ${scope.owner}/${scope.repo}${RESET3}
22520
+ `${DIM3}Scope: ${scope.type === "org" ? scope.owner + " (entire org)" : scope.owner + "/" + scope.repo}${RESET3}
22521
+ ${DIM3}View: ${view}${RESET3}
21800
22522
  ${DIM3}Lens: ${lensId}${RESET3}
21801
22523
  ${DIM3}Model: ${model ?? "claude-sonnet-4-20250514 (default)"}${RESET3}
21802
22524
  ${DIM3}ExoCortex: ${exocortexStatus}${RESET3}
@@ -21926,6 +22648,10 @@ async function main34(argv) {
21926
22648
  return cmdLenses(args);
21927
22649
  case "emergent":
21928
22650
  return cmdEmergent(args);
22651
+ case "mcp": {
22652
+ const { startRadiantMcp: startRadiantMcp2 } = await Promise.resolve().then(() => (init_server(), server_exports));
22653
+ return startRadiantMcp2(argv);
22654
+ }
21929
22655
  case "decision":
21930
22656
  case "signals":
21931
22657
  case "drift":
@@ -21946,12 +22672,12 @@ async function main34(argv) {
21946
22672
  process.exit(1);
21947
22673
  }
21948
22674
  }
21949
- var import_fs13, import_path14, RED2, DIM3, BOLD3, YELLOW3, RESET3, USAGE10;
22675
+ var import_fs15, import_path16, RED2, DIM3, BOLD3, YELLOW3, RESET3, USAGE10;
21950
22676
  var init_radiant = __esm({
21951
22677
  "src/cli/radiant.ts"() {
21952
22678
  "use strict";
21953
- import_fs13 = require("fs");
21954
- import_path14 = require("path");
22679
+ import_fs15 = require("fs");
22680
+ import_path16 = require("path");
21955
22681
  init_think();
21956
22682
  init_emergent();
21957
22683
  init_ai();