@neuroverseos/governance 0.3.1 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/.well-known/ai-plugin.json +34 -9
  2. package/AGENTS.md +72 -24
  3. package/README.md +343 -248
  4. package/dist/adapters/autoresearch.cjs +1345 -0
  5. package/dist/adapters/autoresearch.d.cts +111 -0
  6. package/dist/adapters/autoresearch.d.ts +111 -0
  7. package/dist/adapters/autoresearch.js +12 -0
  8. package/dist/adapters/deep-agents.cjs +1528 -0
  9. package/dist/adapters/deep-agents.d.cts +181 -0
  10. package/dist/adapters/deep-agents.d.ts +181 -0
  11. package/dist/adapters/deep-agents.js +17 -0
  12. package/dist/adapters/express.cjs +1253 -0
  13. package/dist/adapters/express.d.cts +66 -0
  14. package/dist/adapters/express.d.ts +66 -0
  15. package/dist/adapters/express.js +12 -0
  16. package/dist/adapters/index.cjs +2112 -0
  17. package/dist/adapters/index.d.cts +8 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +68 -0
  20. package/dist/adapters/langchain.cjs +1315 -0
  21. package/dist/adapters/langchain.d.cts +89 -0
  22. package/dist/adapters/langchain.d.ts +89 -0
  23. package/dist/adapters/langchain.js +17 -0
  24. package/dist/adapters/openai.cjs +1345 -0
  25. package/dist/adapters/openai.d.cts +99 -0
  26. package/dist/adapters/openai.d.ts +99 -0
  27. package/dist/adapters/openai.js +17 -0
  28. package/dist/adapters/openclaw.cjs +1337 -0
  29. package/dist/adapters/openclaw.d.cts +99 -0
  30. package/dist/adapters/openclaw.d.ts +99 -0
  31. package/dist/adapters/openclaw.js +17 -0
  32. package/dist/add-ROOZLU62.js +314 -0
  33. package/dist/behavioral-MJO34S6Q.js +118 -0
  34. package/dist/bootstrap-CQRZVOXK.js +116 -0
  35. package/dist/bootstrap-emitter-Q7UIJZ2O.js +7 -0
  36. package/dist/bootstrap-parser-EEF36XDU.js +7 -0
  37. package/dist/browser.global.js +941 -0
  38. package/dist/build-ZHPMX5AZ.js +342 -0
  39. package/dist/chunk-3WQLXYTP.js +91 -0
  40. package/dist/chunk-4FLICVVA.js +119 -0
  41. package/dist/chunk-4NGDRRQH.js +10 -0
  42. package/dist/chunk-5TPFNWRU.js +215 -0
  43. package/dist/chunk-5U2MQO5P.js +57 -0
  44. package/dist/chunk-6CZSKEY5.js +164 -0
  45. package/dist/chunk-7P3S7MAY.js +1090 -0
  46. package/dist/chunk-A5W4GNQO.js +130 -0
  47. package/dist/chunk-A7GKPPU7.js +226 -0
  48. package/dist/chunk-AKW5YVCE.js +96 -0
  49. package/dist/chunk-B6OXJLJ5.js +622 -0
  50. package/dist/chunk-BNKJPUPQ.js +113 -0
  51. package/dist/chunk-BQZMOEML.js +43 -0
  52. package/dist/chunk-CNSO6XW5.js +207 -0
  53. package/dist/chunk-CTZHONLA.js +135 -0
  54. package/dist/chunk-D2UCV5AK.js +326 -0
  55. package/dist/chunk-EMQDLDAF.js +458 -0
  56. package/dist/chunk-F66BVUYB.js +340 -0
  57. package/dist/chunk-FMSTRBBS.js +17 -0
  58. package/dist/chunk-G7DJ6VOD.js +101 -0
  59. package/dist/chunk-I3RRAYK2.js +11 -0
  60. package/dist/chunk-INWQHLPS.js +47 -0
  61. package/dist/chunk-IS4WUH6Y.js +363 -0
  62. package/dist/chunk-O5ABKEA7.js +304 -0
  63. package/dist/chunk-OT6PXH54.js +61 -0
  64. package/dist/chunk-PVTQQS3Y.js +186 -0
  65. package/dist/chunk-QLPTHTVB.js +253 -0
  66. package/dist/chunk-QWGCMQQD.js +16 -0
  67. package/dist/chunk-QXBFT7NI.js +201 -0
  68. package/dist/chunk-TG6SEF24.js +246 -0
  69. package/dist/chunk-U6U7EJZL.js +177 -0
  70. package/dist/chunk-VXHSMA3I.js +166 -0
  71. package/dist/chunk-W7LLXRGY.js +830 -0
  72. package/dist/chunk-YEKMVDWK.js +624 -0
  73. package/dist/chunk-ZJTDUCC2.js +194 -0
  74. package/dist/chunk-ZWI3NIXK.js +314 -0
  75. package/dist/cli/neuroverse.cjs +14379 -0
  76. package/dist/cli/neuroverse.d.cts +1 -0
  77. package/dist/cli/neuroverse.d.ts +1 -0
  78. package/dist/cli/neuroverse.js +227 -0
  79. package/dist/cli/plan.cjs +2439 -0
  80. package/dist/cli/plan.d.cts +20 -0
  81. package/dist/cli/plan.d.ts +20 -0
  82. package/dist/cli/plan.js +353 -0
  83. package/dist/cli/run.cjs +2001 -0
  84. package/dist/cli/run.d.cts +20 -0
  85. package/dist/cli/run.d.ts +20 -0
  86. package/dist/cli/run.js +143 -0
  87. package/dist/configure-ai-5MP5DWTT.js +134 -0
  88. package/dist/decision-flow-M63D47LO.js +61 -0
  89. package/dist/demo-G43RLCPK.js +469 -0
  90. package/dist/derive-LMDUTXDD.js +154 -0
  91. package/dist/doctor-6BC6X2VO.js +173 -0
  92. package/dist/equity-penalties-SG5IZQ7I.js +244 -0
  93. package/dist/explain-RHBU2GBR.js +51 -0
  94. package/dist/guard-AEEJNWLD.js +126 -0
  95. package/dist/guard-contract-B7lplwm9.d.cts +837 -0
  96. package/dist/guard-contract-B7lplwm9.d.ts +837 -0
  97. package/dist/guard-engine-PNR6MHCM.js +10 -0
  98. package/dist/impact-3XVDSCBU.js +59 -0
  99. package/dist/improve-TQP4ECSY.js +66 -0
  100. package/dist/index.cjs +7738 -0
  101. package/dist/index.d.cts +2350 -0
  102. package/dist/index.d.ts +2350 -0
  103. package/dist/index.js +479 -0
  104. package/dist/infer-world-IFXCACJ5.js +543 -0
  105. package/dist/init-FYPV4SST.js +144 -0
  106. package/dist/init-world-TI7ARHBT.js +223 -0
  107. package/dist/mcp-server-5Y3ZM7TV.js +13 -0
  108. package/dist/model-adapter-VXEKB4LS.js +11 -0
  109. package/dist/playground-VZBNPPBO.js +560 -0
  110. package/dist/redteam-MZPZD3EF.js +357 -0
  111. package/dist/session-JYOARW54.js +15 -0
  112. package/dist/shared-7RLUHNMU.js +16 -0
  113. package/dist/shared-C_zpdvBm.d.cts +60 -0
  114. package/dist/shared-Cf7yxx4-.d.ts +60 -0
  115. package/dist/simulate-LJXYBC6M.js +83 -0
  116. package/dist/test-BOOR4A5F.js +217 -0
  117. package/dist/trace-PKV4KX56.js +166 -0
  118. package/dist/validate-RALX7CZS.js +81 -0
  119. package/dist/validate-engine-7ZXFVGF2.js +7 -0
  120. package/dist/viz/assets/index-B8SaeJZZ.js +23 -0
  121. package/dist/viz/index.html +23 -0
  122. package/dist/world-BIP4GZBZ.js +376 -0
  123. package/dist/world-loader-Y6HMQH2D.js +13 -0
  124. package/dist/worlds/autoresearch.nv-world.md +230 -0
  125. package/dist/worlds/coding-agent.nv-world.md +211 -0
  126. package/dist/worlds/derivation-world.nv-world.md +278 -0
  127. package/dist/worlds/research-agent.nv-world.md +169 -0
  128. package/dist/worlds/social-media.nv-world.md +198 -0
  129. package/dist/worlds/trading-agent.nv-world.md +218 -0
  130. package/examples/social-media-sim/bridge.py +209 -0
  131. package/examples/social-media-sim/simulation.py +927 -0
  132. package/package.json +16 -3
  133. package/simulate.html +4 -336
@@ -0,0 +1,469 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ govern,
4
+ handleCreateCapsule,
5
+ handleHealthCheck,
6
+ handleListPresets,
7
+ handleReasonRequest,
8
+ writeTempWorld
9
+ } from "./chunk-U6U7EJZL.js";
10
+ import {
11
+ adaptationFromVerdict,
12
+ detectBehavioralPatterns,
13
+ generateAdaptationNarrative
14
+ } from "./chunk-CNSO6XW5.js";
15
+ import {
16
+ resolveWorldPath
17
+ } from "./chunk-AKW5YVCE.js";
18
+ import "./chunk-W7LLXRGY.js";
19
+ import "./chunk-QLPTHTVB.js";
20
+ import {
21
+ DEFAULT_BUNDLED_WORLD,
22
+ loadBundledWorld,
23
+ loadWorld
24
+ } from "./chunk-CTZHONLA.js";
25
+ import {
26
+ __require
27
+ } from "./chunk-QWGCMQQD.js";
28
+
29
+ // src/cli/demo.ts
30
+ import { createServer } from "http";
31
+ import { spawn } from "child_process";
32
+ import { join, extname } from "path";
33
+ import { tmpdir } from "os";
34
+ import { existsSync, readFileSync } from "fs";
35
+ import { fileURLToPath } from "url";
36
+ async function main(args) {
37
+ let port = 3456;
38
+ let worldName;
39
+ let noBrowser = false;
40
+ for (let i = 0; i < args.length; i++) {
41
+ if (args[i] === "--port" && args[i + 1]) {
42
+ port = parseInt(args[i + 1], 10);
43
+ i++;
44
+ } else if (args[i] === "--world" && args[i + 1]) {
45
+ worldName = args[i + 1];
46
+ i++;
47
+ } else if (args[i] === "--no-browser") {
48
+ noBrowser = true;
49
+ } else if (args[i] === "--help" || args[i] === "-h") {
50
+ process.stdout.write(`
51
+ neuroverse demo \u2014 Interactive governance demo
52
+
53
+ Usage:
54
+ neuroverse demo [options]
55
+
56
+ Options:
57
+ --world <name> Load a specific world (e.g., social-media, trading-agent)
58
+ --port <number> Server port (default: 3456)
59
+ --no-browser Don't open browser automatically
60
+
61
+ The demo server wraps the real guard engine.
62
+ Same evaluateGuard() as \`neuroverse guard\`. ONE engine. ONE path.
63
+ `);
64
+ return;
65
+ }
66
+ }
67
+ const TEMP_WORLD_DIR = join(tmpdir(), "neuroverse-demo");
68
+ let activePolicy = "";
69
+ let policyUpdatedAt = null;
70
+ let activeWorld = null;
71
+ let activeSimulation = null;
72
+ if (worldName) {
73
+ try {
74
+ const worldPath = await resolveWorldPath(worldName);
75
+ if (worldPath) {
76
+ activeWorld = await loadWorld(worldPath);
77
+ process.stderr.write(` Loaded world: ${worldName} (${worldPath})
78
+ `);
79
+ }
80
+ } catch {
81
+ process.stderr.write(` Warning: Could not load world "${worldName}"
82
+ `);
83
+ }
84
+ }
85
+ if (!activeWorld) {
86
+ activeWorld = await loadBundledWorld(DEFAULT_BUNDLED_WORLD);
87
+ process.stderr.write(` Using default world: ${DEFAULT_BUNDLED_WORLD}
88
+ `);
89
+ }
90
+ async function syncPolicyToWorld() {
91
+ if (!activePolicy) {
92
+ activeWorld = null;
93
+ return;
94
+ }
95
+ const lines = activePolicy.split("\n").filter((l) => l.trim().length > 0);
96
+ await writeTempWorld(TEMP_WORLD_DIR, lines);
97
+ activeWorld = await loadWorld(TEMP_WORLD_DIR);
98
+ }
99
+ const sseClients = /* @__PURE__ */ new Set();
100
+ let eventCounter = 0;
101
+ const evaluationHistory = [];
102
+ function resolveVizDir() {
103
+ const candidates = [
104
+ join(process.cwd(), "dist", "viz"),
105
+ join(process.cwd(), "node_modules", "@neuroverseos", "governance", "dist", "viz")
106
+ ];
107
+ try {
108
+ const thisDir = typeof __dirname !== "undefined" ? __dirname : join(fileURLToPath(import.meta.url), "..");
109
+ candidates.push(join(thisDir, "..", "viz"));
110
+ } catch {
111
+ }
112
+ for (const dir of candidates) {
113
+ if (existsSync(join(dir, "index.html"))) return dir;
114
+ }
115
+ return null;
116
+ }
117
+ const MIME_TYPES = {
118
+ ".html": "text/html",
119
+ ".js": "application/javascript",
120
+ ".css": "text/css",
121
+ ".json": "application/json",
122
+ ".svg": "image/svg+xml",
123
+ ".png": "image/png",
124
+ ".woff": "font/woff",
125
+ ".woff2": "font/woff2"
126
+ };
127
+ function serveStaticFile(res, filePath) {
128
+ if (!existsSync(filePath)) return false;
129
+ const ext = extname(filePath);
130
+ const mime = MIME_TYPES[ext] ?? "application/octet-stream";
131
+ res.writeHead(200, { "Content-Type": mime });
132
+ res.end(readFileSync(filePath));
133
+ return true;
134
+ }
135
+ const vizDir = resolveVizDir();
136
+ function broadcastEvent(event) {
137
+ const id = ++eventCounter;
138
+ const data = JSON.stringify({ id, timestamp: (/* @__PURE__ */ new Date()).toISOString(), ...event });
139
+ const message = `id: ${id}
140
+ data: ${data}
141
+
142
+ `;
143
+ for (const client of sseClients) {
144
+ try {
145
+ client.write(message);
146
+ } catch {
147
+ sseClients.delete(client);
148
+ }
149
+ }
150
+ }
151
+ function setCors(res) {
152
+ res.setHeader("Access-Control-Allow-Origin", "*");
153
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
154
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
155
+ }
156
+ function readBody(req) {
157
+ return new Promise((resolve, reject) => {
158
+ const chunks = [];
159
+ req.on("data", (chunk) => chunks.push(chunk));
160
+ req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
161
+ req.on("error", reject);
162
+ });
163
+ }
164
+ function normalizeAction(body) {
165
+ if (body.action && typeof body.action === "object" && body.action.agentId) {
166
+ return body.action;
167
+ }
168
+ if (body.actor || body.action && typeof body.action === "string") {
169
+ const agentId = body.actor ?? "unknown";
170
+ const actionType = typeof body.action === "string" ? body.action : "unknown";
171
+ const payload = body.payload ?? {};
172
+ return {
173
+ agentId,
174
+ type: actionType,
175
+ description: payload.description ?? `${agentId}: ${actionType}`,
176
+ magnitude: payload.confidence ?? 0.5,
177
+ context: { ...payload, world: body.world, source: "connector" }
178
+ };
179
+ }
180
+ return { error: "Invalid request format." };
181
+ }
182
+ const server = createServer(async (req, res) => {
183
+ setCors(res);
184
+ if (req.method === "OPTIONS") {
185
+ res.writeHead(204);
186
+ res.end();
187
+ return;
188
+ }
189
+ const url = req.url ?? "/";
190
+ try {
191
+ if (url === "/api/v1/events" && req.method === "GET") {
192
+ res.writeHead(200, {
193
+ "Content-Type": "text/event-stream",
194
+ "Cache-Control": "no-cache",
195
+ "Connection": "keep-alive",
196
+ "Access-Control-Allow-Origin": "*"
197
+ });
198
+ res.write(`data: ${JSON.stringify({ type: "connected", activePolicy: activePolicy.length > 0, eventCount: eventCounter })}
199
+
200
+ `);
201
+ sseClients.add(res);
202
+ req.on("close", () => {
203
+ sseClients.delete(res);
204
+ });
205
+ const keepAlive = setInterval(() => {
206
+ try {
207
+ res.write(": keepalive\n\n");
208
+ } catch {
209
+ clearInterval(keepAlive);
210
+ }
211
+ }, 15e3);
212
+ req.on("close", () => clearInterval(keepAlive));
213
+ return;
214
+ }
215
+ res.setHeader("Content-Type", "application/json");
216
+ if (url === "/api/v1/policy" && req.method === "POST") {
217
+ const body = JSON.parse(await readBody(req));
218
+ const text = body.policyText ?? body.policy ?? body.text;
219
+ if (!text || typeof text !== "string") {
220
+ res.writeHead(400);
221
+ res.end(JSON.stringify({ error: "policyText is required" }));
222
+ return;
223
+ }
224
+ activePolicy = text;
225
+ policyUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
226
+ await syncPolicyToWorld();
227
+ broadcastEvent({ type: "policy_updated", policyText: activePolicy, updatedAt: policyUpdatedAt });
228
+ res.writeHead(200);
229
+ res.end(JSON.stringify({ status: "ok", policyText: activePolicy, updatedAt: policyUpdatedAt }));
230
+ return;
231
+ }
232
+ if (url === "/api/v1/policy" && req.method === "GET") {
233
+ res.writeHead(200);
234
+ res.end(JSON.stringify({ policyText: activePolicy, active: activePolicy.length > 0, updatedAt: policyUpdatedAt }));
235
+ return;
236
+ }
237
+ if ((url === "/api/v1/evaluate" || url === "/api/evaluate") && req.method === "POST") {
238
+ const body = JSON.parse(await readBody(req));
239
+ const action = normalizeAction(body);
240
+ if ("error" in action) {
241
+ res.writeHead(400);
242
+ res.end(JSON.stringify({ error: action.error }));
243
+ return;
244
+ }
245
+ if (!activeWorld) {
246
+ res.writeHead(400);
247
+ res.end(JSON.stringify({ error: "No governance rules set. POST /api/v1/policy first." }));
248
+ return;
249
+ }
250
+ const verdict = govern(action, activeWorld);
251
+ evaluationHistory.push({ action, verdict });
252
+ broadcastEvent({
253
+ type: "evaluation",
254
+ action,
255
+ verdict: { status: verdict.status, reason: verdict.reason, ruleId: verdict.ruleId, consequence: verdict.consequence, reward: verdict.reward }
256
+ });
257
+ res.writeHead(200);
258
+ res.end(JSON.stringify(verdict));
259
+ return;
260
+ }
261
+ if (url === "/api/v1/simulate" && req.method === "POST") {
262
+ const body = JSON.parse(await readBody(req));
263
+ const agents = body.agents ?? 50;
264
+ const steps = body.steps ?? 20;
265
+ const policyText = body.policyText ?? activePolicy;
266
+ if (policyText && policyText !== activePolicy) {
267
+ activePolicy = policyText;
268
+ policyUpdatedAt = (/* @__PURE__ */ new Date()).toISOString();
269
+ await syncPolicyToWorld();
270
+ broadcastEvent({ type: "policy_updated", policyText: activePolicy, updatedAt: policyUpdatedAt });
271
+ }
272
+ if (!activeWorld) {
273
+ res.writeHead(400);
274
+ res.end(JSON.stringify({ error: "No governance rules set." }));
275
+ return;
276
+ }
277
+ if (activeSimulation) {
278
+ try {
279
+ activeSimulation.kill();
280
+ } catch {
281
+ }
282
+ activeSimulation = null;
283
+ }
284
+ const scriptCandidates = [
285
+ join(process.cwd(), "examples", "social-media-sim", "simulation.py"),
286
+ join(process.cwd(), "demo", "simulations", "social_simulation.py")
287
+ ];
288
+ const scriptPath = scriptCandidates.find((p) => existsSync(p));
289
+ if (!scriptPath) {
290
+ res.writeHead(500);
291
+ res.end(JSON.stringify({ error: "Simulation script not found" }));
292
+ return;
293
+ }
294
+ const simArgs = [scriptPath, "--agents", String(agents), "--steps", String(steps)];
295
+ if (body.llmApiKey) {
296
+ simArgs.push("--llm-api-key", body.llmApiKey);
297
+ if (body.llmBaseUrl) simArgs.push("--llm-base-url", body.llmBaseUrl);
298
+ if (body.llmModel) simArgs.push("--llm-model", body.llmModel);
299
+ }
300
+ broadcastEvent({ type: "simulation_start", agents, steps, mode: body.llmApiKey ? "llm" : "rule-based" });
301
+ const proc = spawn("python3", simArgs, { cwd: process.cwd(), env: { ...process.env } });
302
+ activeSimulation = proc;
303
+ let buffer = "";
304
+ proc.stdout.on("data", (chunk) => {
305
+ buffer += chunk.toString();
306
+ const lines = buffer.split("\n");
307
+ buffer = lines.pop() ?? "";
308
+ for (const line of lines) {
309
+ if (!line.trim()) continue;
310
+ try {
311
+ broadcastEvent({ type: "simulation_event", ...JSON.parse(line) });
312
+ } catch {
313
+ }
314
+ }
315
+ });
316
+ proc.stderr.on("data", (chunk) => {
317
+ const msg = chunk.toString().trim();
318
+ if (msg) process.stderr.write(`[SIM] ${msg}
319
+ `);
320
+ });
321
+ proc.on("close", (code) => {
322
+ activeSimulation = null;
323
+ broadcastEvent({ type: "simulation_complete", exitCode: code });
324
+ });
325
+ res.writeHead(200);
326
+ res.end(JSON.stringify({ status: "started", agents, steps }));
327
+ return;
328
+ }
329
+ if (url === "/api/v1/simulate/stop" && req.method === "POST") {
330
+ if (activeSimulation) {
331
+ activeSimulation.kill();
332
+ activeSimulation = null;
333
+ broadcastEvent({ type: "simulation_stopped" });
334
+ res.writeHead(200);
335
+ res.end(JSON.stringify({ status: "stopped" }));
336
+ } else {
337
+ res.writeHead(200);
338
+ res.end(JSON.stringify({ status: "no_simulation_running" }));
339
+ }
340
+ return;
341
+ }
342
+ if (url === "/api/v1/simulate/source" && req.method === "GET") {
343
+ const candidates = [
344
+ { sim: "examples/social-media-sim/simulation.py", bridge: "examples/social-media-sim/bridge.py" },
345
+ { sim: "demo/simulations/social_simulation.py", bridge: "demo/simulations/neuroverse_bridge.py" }
346
+ ];
347
+ const files = [];
348
+ for (const c of candidates) {
349
+ const simPath = join(process.cwd(), c.sim);
350
+ if (existsSync(simPath)) {
351
+ files.push({ name: "simulation.py", path: c.sim, content: readFileSync(simPath, "utf-8"), language: "python" });
352
+ const bridgePath = join(process.cwd(), c.bridge);
353
+ if (existsSync(bridgePath)) {
354
+ files.push({ name: "bridge.py", path: c.bridge, content: readFileSync(bridgePath, "utf-8"), language: "python" });
355
+ }
356
+ break;
357
+ }
358
+ }
359
+ res.writeHead(200);
360
+ res.end(JSON.stringify({ files }));
361
+ return;
362
+ }
363
+ if (url === "/api/v1/reason" && req.method === "POST") {
364
+ const body = JSON.parse(await readBody(req));
365
+ const result = await handleReasonRequest(body);
366
+ res.writeHead("error" in result && result.status === "error" ? 400 : 200);
367
+ res.end(JSON.stringify(result));
368
+ return;
369
+ }
370
+ if (url === "/api/v1/reason/capsule" && req.method === "POST") {
371
+ const body = JSON.parse(await readBody(req));
372
+ res.writeHead(200);
373
+ res.end(JSON.stringify(handleCreateCapsule(body)));
374
+ return;
375
+ }
376
+ if (url === "/api/v1/reason/health" && req.method === "GET") {
377
+ res.writeHead(200);
378
+ res.end(JSON.stringify(handleHealthCheck()));
379
+ return;
380
+ }
381
+ if (url === "/api/v1/reason/presets" && req.method === "GET") {
382
+ res.writeHead(200);
383
+ res.end(JSON.stringify(await handleListPresets(join(process.cwd(), "policies"))));
384
+ return;
385
+ }
386
+ if (url === "/api/v1/behavioral" && req.method === "GET") {
387
+ const adaptations = evaluationHistory.map(({ action, verdict }) => {
388
+ const executed = verdict.status === "BLOCK" ? "idle" : action.type;
389
+ return adaptationFromVerdict(action.agentId, action.type, executed, verdict);
390
+ });
391
+ const patterns = detectBehavioralPatterns(adaptations, new Set(evaluationHistory.map((e) => e.action.agentId)).size);
392
+ const narrative = generateAdaptationNarrative(patterns);
393
+ res.writeHead(200);
394
+ res.end(JSON.stringify({ patterns, narrative, adaptations: adaptations.length, agents: new Set(evaluationHistory.map((e) => e.action.agentId)).size }));
395
+ return;
396
+ }
397
+ if (req.method === "GET" && vizDir) {
398
+ const reqPath = url === "/" || url === "/index.html" ? "/index.html" : url;
399
+ const filePath = join(vizDir, reqPath);
400
+ if (filePath.startsWith(vizDir) && serveStaticFile(res, filePath)) return;
401
+ }
402
+ if (req.method === "GET" && (url === "/" || url === "/index.html")) {
403
+ res.writeHead(200, { "Content-Type": "text/html" });
404
+ res.end(`<html><body style="background:#0a0a0a;color:#e2e8f0;font-family:monospace;padding:40px">
405
+ <h2>NeuroVerse Demo Server</h2>
406
+ <p>API is running. Build the viz to see the Governance Observation Deck:</p>
407
+ <pre style="color:#8b5cf6">npm run build:viz</pre>
408
+ <p style="color:#64748b">Then refresh this page.</p>
409
+ <p style="margin-top:20px">API endpoints:</p>
410
+ <pre style="color:#64748b">POST /api/v1/policy \u2014 Set rules
411
+ POST /api/v1/evaluate \u2014 Guard evaluation
412
+ GET /api/v1/events \u2014 SSE governance feed
413
+ GET /api/v1/behavioral \u2014 Behavioral analysis
414
+ POST /api/v1/simulate \u2014 Launch simulation</pre>
415
+ </body></html>`);
416
+ return;
417
+ }
418
+ res.writeHead(404);
419
+ res.end(JSON.stringify({ error: "Not found" }));
420
+ } catch (err) {
421
+ console.error("Server error:", err);
422
+ res.writeHead(500);
423
+ res.end(JSON.stringify({ error: "Internal server error" }));
424
+ }
425
+ });
426
+ server.listen(port, () => {
427
+ process.stderr.write(`
428
+ NeuroVerse Demo Server
429
+ `);
430
+ process.stderr.write(` http://localhost:${port}
431
+ `);
432
+ process.stderr.write(`
433
+ Engine: evaluateGuard() \u2014 same as \`neuroverse guard\`
434
+ `);
435
+ process.stderr.write(` Temp world: ${TEMP_WORLD_DIR}
436
+ `);
437
+ if (worldName) {
438
+ process.stderr.write(` World: ${worldName}
439
+ `);
440
+ }
441
+ process.stderr.write(`
442
+ POST /api/v1/policy \u2192 Set rules (writes temp world)
443
+ `);
444
+ process.stderr.write(` POST /api/v1/evaluate \u2192 Guard evaluation (real engine)
445
+ `);
446
+ process.stderr.write(` GET /api/v1/events \u2192 SSE governance feed
447
+ `);
448
+ process.stderr.write(` POST /api/v1/simulate \u2192 Launch social simulation
449
+ `);
450
+ process.stderr.write(`
451
+ ONE engine. ONE path. CLI is the bible.
452
+
453
+ `);
454
+ if (!noBrowser) {
455
+ const url = `http://localhost:${port}`;
456
+ try {
457
+ const { exec } = __require("child_process");
458
+ const cmd = process.platform === "darwin" ? `open ${url}` : process.platform === "win32" ? `start ${url}` : `xdg-open ${url}`;
459
+ exec(cmd);
460
+ } catch {
461
+ }
462
+ }
463
+ });
464
+ await new Promise(() => {
465
+ });
466
+ }
467
+ export {
468
+ main
469
+ };
@@ -0,0 +1,154 @@
1
+ import {
2
+ DeriveInputError,
3
+ DeriveProviderError,
4
+ deriveWorld
5
+ } from "./chunk-YEKMVDWK.js";
6
+ import {
7
+ DERIVE_EXIT_CODES
8
+ } from "./chunk-FMSTRBBS.js";
9
+ import "./chunk-OT6PXH54.js";
10
+ import "./chunk-INWQHLPS.js";
11
+ import "./chunk-7P3S7MAY.js";
12
+ import "./chunk-EMQDLDAF.js";
13
+ import "./chunk-PVTQQS3Y.js";
14
+ import "./chunk-QWGCMQQD.js";
15
+
16
+ // src/cli/derive.ts
17
+ function parseArgs(argv) {
18
+ let inputPath = "";
19
+ let outputPath = "./derived.nv-world.md";
20
+ let validate = true;
21
+ let dryRun = false;
22
+ let bootstrapDir;
23
+ let provider;
24
+ let model;
25
+ let endpoint;
26
+ for (let i = 0; i < argv.length; i++) {
27
+ const arg = argv[i];
28
+ if (arg === "--input" && i + 1 < argv.length) {
29
+ inputPath = argv[++i];
30
+ } else if (arg === "--output" && i + 1 < argv.length) {
31
+ outputPath = argv[++i];
32
+ } else if (arg === "--validate") {
33
+ validate = true;
34
+ } else if (arg === "--no-validate") {
35
+ validate = false;
36
+ } else if (arg === "--dry-run") {
37
+ dryRun = true;
38
+ } else if (arg === "--bootstrap" && i + 1 < argv.length) {
39
+ bootstrapDir = argv[++i];
40
+ } else if (arg === "--provider" && i + 1 < argv.length) {
41
+ provider = argv[++i];
42
+ } else if (arg === "--model" && i + 1 < argv.length) {
43
+ model = argv[++i];
44
+ } else if (arg === "--endpoint" && i + 1 < argv.length) {
45
+ endpoint = argv[++i];
46
+ }
47
+ }
48
+ if (!inputPath) throw new DeriveInputError("--input <path> is required");
49
+ return { inputPath, outputPath, validate, dryRun, bootstrapDir, provider, model, endpoint };
50
+ }
51
+ async function main(argv = process.argv.slice(2)) {
52
+ try {
53
+ const args = parseArgs(argv);
54
+ const { result, exitCode, dryRunOutput } = await deriveWorld({
55
+ inputPath: args.inputPath,
56
+ outputPath: args.outputPath,
57
+ validate: args.validate,
58
+ dryRun: args.dryRun,
59
+ providerOverride: args.provider || args.model || args.endpoint ? {
60
+ provider: args.provider,
61
+ model: args.model,
62
+ endpoint: args.endpoint
63
+ } : void 0
64
+ });
65
+ if (dryRunOutput) {
66
+ process.stdout.write(JSON.stringify({
67
+ dryRun: true,
68
+ systemPrompt: dryRunOutput.systemPrompt,
69
+ userPrompt: dryRunOutput.userPrompt,
70
+ durationMs: result.durationMs
71
+ }, null, 2) + "\n");
72
+ process.exit(DERIVE_EXIT_CODES.SUCCESS);
73
+ return;
74
+ }
75
+ process.stderr.write(`
76
+ Derived world written to: ${result.outputPath}
77
+ `);
78
+ process.stderr.write(`Derivation Gate: ${result.gate}
79
+ `);
80
+ if (result.normalization) {
81
+ const n = result.normalization;
82
+ const details = [];
83
+ if (n.invariantIds > 0) details.push(`${n.invariantIds} invariant ID(s) wrapped`);
84
+ if (n.gateThresholds > 0) details.push(`${n.gateThresholds} gate threshold(s) converted`);
85
+ if (n.triggerTags > 0) details.push(`${n.triggerTags} trigger(s) tagged with [state]`);
86
+ process.stderr.write(`
87
+ Normalization: ${n.fixCount} fix(es) applied
88
+ `);
89
+ for (const d of details) process.stderr.write(` - ${d}
90
+ `);
91
+ }
92
+ if (result.findings.length > 0) {
93
+ process.stderr.write(`
94
+ `);
95
+ const errs = result.findings.filter((f) => f.severity === "error");
96
+ const warns = result.findings.filter((f) => f.severity === "warning");
97
+ if (errs.length > 0) {
98
+ process.stderr.write(`Errors (${errs.length}):
99
+ `);
100
+ for (const f of errs) {
101
+ process.stderr.write(` ERROR [${f.section}]: ${f.message}
102
+ `);
103
+ }
104
+ }
105
+ if (warns.length > 0) {
106
+ process.stderr.write(`Warnings (${warns.length}):
107
+ `);
108
+ for (const f of warns) {
109
+ process.stderr.write(` WARN [${f.section}]: ${f.message}
110
+ `);
111
+ }
112
+ }
113
+ process.stderr.write(`
114
+ `);
115
+ }
116
+ if (result.gate === "SUSPECT" || result.gate === "DERIVATION_REJECTED") {
117
+ process.stderr.write(`The file has been written. Open ${result.outputPath} to review and fix.
118
+ `);
119
+ }
120
+ if (args.bootstrapDir && exitCode === 0) {
121
+ process.stderr.write(`
122
+ Bootstrapping to ${args.bootstrapDir}...
123
+ `);
124
+ const { main: bootstrapMain } = await import("./bootstrap-CQRZVOXK.js");
125
+ await bootstrapMain([
126
+ "--input",
127
+ result.outputPath,
128
+ "--output",
129
+ args.bootstrapDir,
130
+ ...args.validate ? ["--validate"] : []
131
+ ]);
132
+ return;
133
+ }
134
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
135
+ process.exit(exitCode);
136
+ } catch (e) {
137
+ if (e instanceof DeriveInputError) {
138
+ process.stderr.write(JSON.stringify({ error: e.message }, null, 2) + "\n");
139
+ process.exit(DERIVE_EXIT_CODES.INPUT_ERROR);
140
+ } else if (e instanceof DeriveProviderError) {
141
+ process.stderr.write(JSON.stringify({ error: e.message }, null, 2) + "\n");
142
+ process.exit(DERIVE_EXIT_CODES.PROVIDER_ERROR);
143
+ } else {
144
+ process.stderr.write(JSON.stringify({
145
+ error: "Derive failed",
146
+ detail: e instanceof Error ? e.message : String(e)
147
+ }, null, 2) + "\n");
148
+ process.exit(DERIVE_EXIT_CODES.PROVIDER_ERROR);
149
+ }
150
+ }
151
+ }
152
+ export {
153
+ main
154
+ };