@neuroverseos/governance 0.2.2 → 0.2.3
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.
- package/.well-known/ai-plugin.json +26 -0
- package/.well-known/mcp.json +68 -0
- package/AGENTS.md +219 -0
- package/README.md +84 -4
- package/dist/adapters/autoresearch.cjs +196 -0
- package/dist/adapters/autoresearch.d.cts +103 -0
- package/dist/adapters/autoresearch.d.ts +103 -0
- package/dist/adapters/autoresearch.js +7 -0
- package/dist/adapters/deep-agents.cjs +1472 -0
- package/dist/adapters/deep-agents.d.cts +181 -0
- package/dist/adapters/deep-agents.d.ts +181 -0
- package/dist/adapters/deep-agents.js +17 -0
- package/dist/adapters/express.cjs +103 -21
- package/dist/adapters/express.d.cts +1 -1
- package/dist/adapters/express.d.ts +1 -1
- package/dist/adapters/express.js +3 -3
- package/dist/adapters/index.cjs +649 -109
- package/dist/adapters/index.d.cts +4 -1
- package/dist/adapters/index.d.ts +4 -1
- package/dist/adapters/index.js +39 -13
- package/dist/adapters/langchain.cjs +152 -48
- package/dist/adapters/langchain.d.cts +5 -5
- package/dist/adapters/langchain.d.ts +5 -5
- package/dist/adapters/langchain.js +4 -3
- package/dist/adapters/openai.cjs +154 -50
- package/dist/adapters/openai.d.cts +5 -5
- package/dist/adapters/openai.d.ts +5 -5
- package/dist/adapters/openai.js +4 -3
- package/dist/adapters/openclaw.cjs +152 -48
- package/dist/adapters/openclaw.d.cts +5 -5
- package/dist/adapters/openclaw.d.ts +5 -5
- package/dist/adapters/openclaw.js +4 -3
- package/dist/{build-P42YFKQV.js → build-X5MZY4IA.js} +2 -2
- package/dist/{chunk-2NICNKOM.js → chunk-4L6OPKMQ.js} +1 -1
- package/dist/chunk-5U2MQO5P.js +57 -0
- package/dist/{chunk-SKU3GAPD.js → chunk-6BB55YJI.js} +16 -34
- package/dist/{chunk-KEST3MWO.js → chunk-AF2VX4AL.js} +47 -8
- package/dist/chunk-BQZMOEML.js +43 -0
- package/dist/chunk-D2UCV5AK.js +326 -0
- package/dist/{chunk-RWXVAH6P.js → chunk-EVDJUSZ2.js} +16 -34
- package/dist/{chunk-4JRYGIO7.js → chunk-IZSO75NZ.js} +72 -7
- package/dist/chunk-JCKSW2PZ.js +304 -0
- package/dist/{chunk-PDOZHZWL.js → chunk-KTFTTLTP.js} +25 -4
- package/dist/{chunk-MWDQ4MJB.js → chunk-MH7BT4VH.js} +5 -1
- package/dist/{chunk-4QXB6PEO.js → chunk-QLPTHTVB.js} +37 -16
- package/dist/{chunk-QPASI2BR.js → chunk-REXY4LUL.js} +49 -10
- package/dist/chunk-T5EUJQE5.js +172 -0
- package/dist/{chunk-DPVS43ZT.js → chunk-TTBKTF3P.js} +5 -5
- package/dist/{chunk-OHAC6HJE.js → chunk-ZIVQNSZU.js} +16 -36
- package/dist/{chunk-BUWWN2NX.js → chunk-ZJTDUCC2.js} +9 -7
- package/dist/cli/neuroverse.cjs +2582 -493
- package/dist/cli/neuroverse.js +39 -15
- package/dist/cli/plan.cjs +119 -32
- package/dist/cli/plan.js +5 -13
- package/dist/cli/run.cjs +223 -24
- package/dist/cli/run.js +2 -2
- package/dist/decision-flow-LETV5NWY.js +61 -0
- package/dist/{derive-TLIV4OOU.js → derive-7365SUFU.js} +2 -2
- package/dist/{doctor-QV6HELS5.js → doctor-QYISMKEL.js} +5 -2
- package/dist/equity-penalties-63FGB3I2.js +244 -0
- package/dist/{explain-IDCRWMPX.js → explain-A2EWI2OL.js} +4 -23
- package/dist/{guard-GFLQZY6U.js → guard-3BWL3IGH.js} +6 -10
- package/dist/{guard-contract-Cm91Kp4j.d.ts → guard-contract-C9_zKbzd.d.cts} +117 -5
- package/dist/{guard-contract-Cm91Kp4j.d.cts → guard-contract-C9_zKbzd.d.ts} +117 -5
- package/dist/{guard-engine-JLTUARGU.js → guard-engine-QFMIBWJY.js} +2 -2
- package/dist/{impact-XPECYRLH.js → impact-UB6DXKSX.js} +4 -4
- package/dist/{improve-GPUBKTEA.js → improve-XZA57GER.js} +5 -24
- package/dist/index.cjs +592 -44
- package/dist/index.d.cts +218 -5
- package/dist/index.d.ts +218 -5
- package/dist/index.js +92 -41
- package/dist/infer-world-7GVZWFX4.js +543 -0
- package/dist/init-world-VWMQZQC7.js +223 -0
- package/dist/{mcp-server-LZVJHBT5.js → mcp-server-XWQZXNW7.js} +3 -3
- package/dist/{playground-FGOMASHN.js → playground-ADWZORNV.js} +2 -2
- package/dist/{redteam-SK7AMIG3.js → redteam-JRQ7FD2F.js} +2 -2
- package/dist/{session-VISISNWJ.js → session-MMYX5YCF.js} +4 -3
- package/dist/shared--Q8wPBVN.d.ts +60 -0
- package/dist/shared-HpAG90PX.d.cts +60 -0
- package/dist/shared-U2QFV7JH.js +16 -0
- package/dist/{simulate-VDOYQFRO.js → simulate-GMIFFXYV.js} +5 -30
- package/dist/{test-75AVHC3R.js → test-JBBZ65X4.js} +2 -2
- package/dist/{trace-JVF67VR3.js → trace-3MYWIDEF.js} +3 -3
- package/dist/worlds/autoresearch.nv-world.md +230 -0
- package/dist/worlds/coding-agent.nv-world.md +211 -0
- package/llms.txt +79 -0
- package/openapi.yaml +230 -0
- package/package.json +26 -4
- package/dist/{chunk-GR6DGCZ2.js → chunk-BMOXICAB.js} +3 -3
- package/dist/{chunk-NF5POFCI.js → chunk-ORJ3NOE6.js} +3 -3
- package/dist/{world-LAXO6DOX.js → world-BFJCIQSH.js} +3 -3
package/dist/cli/neuroverse.cjs
CHANGED
|
@@ -1975,27 +1975,27 @@ ${candidates.map((c) => ` - ${c}`).join("\n")}`
|
|
|
1975
1975
|
}
|
|
1976
1976
|
async function collectMarkdownSources(inputPath) {
|
|
1977
1977
|
const { stat, readFile: rf, readdir } = await import("fs/promises");
|
|
1978
|
-
const { join: pathJoin, extname, basename } = await import("path");
|
|
1978
|
+
const { join: pathJoin, extname, basename: basename2 } = await import("path");
|
|
1979
1979
|
const stats = await stat(inputPath);
|
|
1980
1980
|
if (stats.isFile()) {
|
|
1981
1981
|
const content = await rf(inputPath, "utf-8");
|
|
1982
|
-
return [{ filename:
|
|
1982
|
+
return [{ filename: basename2(inputPath), content }];
|
|
1983
1983
|
}
|
|
1984
1984
|
if (stats.isDirectory()) {
|
|
1985
1985
|
const sources = [];
|
|
1986
|
-
await collectDir(inputPath, sources, rf, pathJoin, extname,
|
|
1986
|
+
await collectDir(inputPath, sources, rf, pathJoin, extname, basename2);
|
|
1987
1987
|
sources.sort((a, b) => a.filename.localeCompare(b.filename));
|
|
1988
1988
|
return sources;
|
|
1989
1989
|
}
|
|
1990
1990
|
throw new Error(`Input path is neither a file nor a directory: ${inputPath}`);
|
|
1991
1991
|
}
|
|
1992
|
-
async function collectDir(dir, sources, rf, pathJoin, extname,
|
|
1992
|
+
async function collectDir(dir, sources, rf, pathJoin, extname, basename2) {
|
|
1993
1993
|
const { readdir } = await import("fs/promises");
|
|
1994
1994
|
const entries = await readdir(dir, { withFileTypes: true });
|
|
1995
1995
|
for (const entry of entries) {
|
|
1996
1996
|
const fullPath = pathJoin(dir, entry.name);
|
|
1997
1997
|
if (entry.isDirectory()) {
|
|
1998
|
-
await collectDir(fullPath, sources, rf, pathJoin, extname,
|
|
1998
|
+
await collectDir(fullPath, sources, rf, pathJoin, extname, basename2);
|
|
1999
1999
|
} else if (entry.isFile() && extname(entry.name).toLowerCase() === ".md") {
|
|
2000
2000
|
const content = await rf(fullPath, "utf-8");
|
|
2001
2001
|
sources.push({ filename: entry.name, content });
|
|
@@ -2653,22 +2653,22 @@ function parseArgs(argv) {
|
|
|
2653
2653
|
return { inputPath, outputDir, validate, dryRun, provider, model, endpoint };
|
|
2654
2654
|
}
|
|
2655
2655
|
async function writeWorldFiles(outputDir, world) {
|
|
2656
|
-
const { writeFile:
|
|
2657
|
-
const { join:
|
|
2656
|
+
const { writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
|
|
2657
|
+
const { join: join8 } = await import("path");
|
|
2658
2658
|
await mkdir2(outputDir, { recursive: true });
|
|
2659
|
-
await
|
|
2660
|
-
await
|
|
2661
|
-
await
|
|
2662
|
-
await
|
|
2663
|
-
await
|
|
2664
|
-
await
|
|
2665
|
-
await
|
|
2666
|
-
const rulesDir =
|
|
2659
|
+
await writeFile5(join8(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
|
|
2660
|
+
await writeFile5(join8(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
|
|
2661
|
+
await writeFile5(join8(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
|
|
2662
|
+
await writeFile5(join8(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
|
|
2663
|
+
await writeFile5(join8(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
|
|
2664
|
+
await writeFile5(join8(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
|
|
2665
|
+
await writeFile5(join8(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
|
|
2666
|
+
const rulesDir = join8(outputDir, "rules");
|
|
2667
2667
|
await mkdir2(rulesDir, { recursive: true });
|
|
2668
2668
|
const sortedRules = [...world.rules].sort((a, b) => a.order - b.order);
|
|
2669
2669
|
for (let i = 0; i < sortedRules.length; i++) {
|
|
2670
2670
|
const ruleNum = String(i + 1).padStart(3, "0");
|
|
2671
|
-
await
|
|
2671
|
+
await writeFile5(join8(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
|
|
2672
2672
|
}
|
|
2673
2673
|
}
|
|
2674
2674
|
function write(msg) {
|
|
@@ -2683,17 +2683,17 @@ function printInsight(finding2) {
|
|
|
2683
2683
|
async function main(argv = process.argv.slice(2)) {
|
|
2684
2684
|
try {
|
|
2685
2685
|
const args = parseArgs(argv);
|
|
2686
|
-
const { basename } = await import("path");
|
|
2686
|
+
const { basename: basename2 } = await import("path");
|
|
2687
2687
|
write(`
|
|
2688
2688
|
NeuroVerse World Builder
|
|
2689
2689
|
`);
|
|
2690
2690
|
write(`
|
|
2691
|
-
Analyzing: ${
|
|
2691
|
+
Analyzing: ${basename2(args.inputPath)}
|
|
2692
2692
|
`);
|
|
2693
2693
|
const derivedPath = args.outputDir ? `${args.outputDir}/source.nv-world.md` : ".neuroverse/build-output.nv-world.md";
|
|
2694
2694
|
const { mkdir: mkdir2 } = await import("fs/promises");
|
|
2695
|
-
const { dirname:
|
|
2696
|
-
await mkdir2(
|
|
2695
|
+
const { dirname: dirname3 } = await import("path");
|
|
2696
|
+
await mkdir2(dirname3(derivedPath), { recursive: true });
|
|
2697
2697
|
const { result, exitCode, dryRunOutput } = await deriveWorld({
|
|
2698
2698
|
inputPath: args.inputPath,
|
|
2699
2699
|
outputPath: derivedPath,
|
|
@@ -2799,9 +2799,9 @@ World source written to: ${derivedPath}
|
|
|
2799
2799
|
try {
|
|
2800
2800
|
const emitResult = emitWorldDefinition(parseResult.world);
|
|
2801
2801
|
await writeWorldFiles(outputDir, emitResult.world);
|
|
2802
|
-
const { join:
|
|
2802
|
+
const { join: join8 } = await import("path");
|
|
2803
2803
|
const { copyFile } = await import("fs/promises");
|
|
2804
|
-
const sourceDest =
|
|
2804
|
+
const sourceDest = join8(outputDir, "source.nv-world.md");
|
|
2805
2805
|
if (derivedPath !== sourceDest) {
|
|
2806
2806
|
await copyFile(derivedPath, sourceDest);
|
|
2807
2807
|
}
|
|
@@ -2878,11 +2878,11 @@ __export(world_loader_exports, {
|
|
|
2878
2878
|
});
|
|
2879
2879
|
async function loadWorldFromDirectory(dirPath) {
|
|
2880
2880
|
const { readFile: readFile3 } = await import("fs/promises");
|
|
2881
|
-
const { join:
|
|
2882
|
-
const { readdirSync:
|
|
2881
|
+
const { join: join8 } = await import("path");
|
|
2882
|
+
const { readdirSync: readdirSync5 } = await import("fs");
|
|
2883
2883
|
async function readJson(filename) {
|
|
2884
2884
|
try {
|
|
2885
|
-
const content = await readFile3(
|
|
2885
|
+
const content = await readFile3(join8(dirPath, filename), "utf-8");
|
|
2886
2886
|
return JSON.parse(content);
|
|
2887
2887
|
} catch {
|
|
2888
2888
|
return void 0;
|
|
@@ -2903,10 +2903,10 @@ async function loadWorldFromDirectory(dirPath) {
|
|
|
2903
2903
|
const metadataJson = await readJson("metadata.json");
|
|
2904
2904
|
const rules = [];
|
|
2905
2905
|
try {
|
|
2906
|
-
const rulesDir =
|
|
2907
|
-
const ruleFiles =
|
|
2906
|
+
const rulesDir = join8(dirPath, "rules");
|
|
2907
|
+
const ruleFiles = readdirSync5(rulesDir).filter((f) => f.endsWith(".json")).sort();
|
|
2908
2908
|
for (const file of ruleFiles) {
|
|
2909
|
-
const content = await readFile3(
|
|
2909
|
+
const content = await readFile3(join8(rulesDir, file), "utf-8");
|
|
2910
2910
|
rules.push(JSON.parse(content));
|
|
2911
2911
|
}
|
|
2912
2912
|
} catch {
|
|
@@ -2955,6 +2955,20 @@ var init_world_loader = __esm({
|
|
|
2955
2955
|
}
|
|
2956
2956
|
});
|
|
2957
2957
|
|
|
2958
|
+
// src/engine/rule-utils.ts
|
|
2959
|
+
function collectAllEffects(rule) {
|
|
2960
|
+
const effects = [...rule.effects ?? []];
|
|
2961
|
+
for (const ce of rule.effects_conditional ?? []) {
|
|
2962
|
+
effects.push(...ce.effects);
|
|
2963
|
+
}
|
|
2964
|
+
return effects;
|
|
2965
|
+
}
|
|
2966
|
+
var init_rule_utils = __esm({
|
|
2967
|
+
"src/engine/rule-utils.ts"() {
|
|
2968
|
+
"use strict";
|
|
2969
|
+
}
|
|
2970
|
+
});
|
|
2971
|
+
|
|
2958
2972
|
// src/engine/explain-engine.ts
|
|
2959
2973
|
function detectTensions(rules) {
|
|
2960
2974
|
const increases = /* @__PURE__ */ new Map();
|
|
@@ -2988,13 +3002,6 @@ function detectTensions(rules) {
|
|
|
2988
3002
|
}
|
|
2989
3003
|
return tensions;
|
|
2990
3004
|
}
|
|
2991
|
-
function collectAllEffects(rule) {
|
|
2992
|
-
const effects = [...rule.effects ?? []];
|
|
2993
|
-
for (const ce of rule.effects_conditional ?? []) {
|
|
2994
|
-
effects.push(...ce.effects);
|
|
2995
|
-
}
|
|
2996
|
-
return effects;
|
|
2997
|
-
}
|
|
2998
3005
|
function explainWorld(world) {
|
|
2999
3006
|
const dynamics = [...world.rules].sort((a, b) => a.order - b.order).map((rule) => {
|
|
3000
3007
|
const allEffects = collectAllEffects(rule);
|
|
@@ -3145,30 +3152,11 @@ function renderExplainText(output) {
|
|
|
3145
3152
|
var init_explain_engine = __esm({
|
|
3146
3153
|
"src/engine/explain-engine.ts"() {
|
|
3147
3154
|
"use strict";
|
|
3155
|
+
init_rule_utils();
|
|
3148
3156
|
}
|
|
3149
3157
|
});
|
|
3150
3158
|
|
|
3151
|
-
// src/cli/
|
|
3152
|
-
var explain_exports = {};
|
|
3153
|
-
__export(explain_exports, {
|
|
3154
|
-
main: () => main2
|
|
3155
|
-
});
|
|
3156
|
-
function parseArgs2(argv) {
|
|
3157
|
-
let worldPath = "";
|
|
3158
|
-
let json = false;
|
|
3159
|
-
for (let i = 0; i < argv.length; i++) {
|
|
3160
|
-
const arg = argv[i];
|
|
3161
|
-
if (arg === "--json") {
|
|
3162
|
-
json = true;
|
|
3163
|
-
} else if (!arg.startsWith("--") && !worldPath) {
|
|
3164
|
-
worldPath = arg;
|
|
3165
|
-
}
|
|
3166
|
-
}
|
|
3167
|
-
if (!worldPath) {
|
|
3168
|
-
throw new Error("Usage: neuroverse explain <world-path-or-id>");
|
|
3169
|
-
}
|
|
3170
|
-
return { worldPath, json };
|
|
3171
|
-
}
|
|
3159
|
+
// src/cli/cli-utils.ts
|
|
3172
3160
|
async function resolveWorldPath(input) {
|
|
3173
3161
|
const { stat } = await import("fs/promises");
|
|
3174
3162
|
try {
|
|
@@ -3191,6 +3179,47 @@ Tried:
|
|
|
3191
3179
|
Build a world first: neuroverse build <input.md>`
|
|
3192
3180
|
);
|
|
3193
3181
|
}
|
|
3182
|
+
async function readStdin() {
|
|
3183
|
+
const chunks = [];
|
|
3184
|
+
for await (const chunk of process.stdin) {
|
|
3185
|
+
chunks.push(chunk);
|
|
3186
|
+
}
|
|
3187
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
3188
|
+
}
|
|
3189
|
+
function parseCliValue(raw) {
|
|
3190
|
+
if (raw === "true") return true;
|
|
3191
|
+
if (raw === "false") return false;
|
|
3192
|
+
const num = Number(raw);
|
|
3193
|
+
if (!isNaN(num) && raw.trim() !== "") return num;
|
|
3194
|
+
return raw;
|
|
3195
|
+
}
|
|
3196
|
+
var init_cli_utils = __esm({
|
|
3197
|
+
"src/cli/cli-utils.ts"() {
|
|
3198
|
+
"use strict";
|
|
3199
|
+
}
|
|
3200
|
+
});
|
|
3201
|
+
|
|
3202
|
+
// src/cli/explain.ts
|
|
3203
|
+
var explain_exports = {};
|
|
3204
|
+
__export(explain_exports, {
|
|
3205
|
+
main: () => main2
|
|
3206
|
+
});
|
|
3207
|
+
function parseArgs2(argv) {
|
|
3208
|
+
let worldPath = "";
|
|
3209
|
+
let json = false;
|
|
3210
|
+
for (let i = 0; i < argv.length; i++) {
|
|
3211
|
+
const arg = argv[i];
|
|
3212
|
+
if (arg === "--json") {
|
|
3213
|
+
json = true;
|
|
3214
|
+
} else if (!arg.startsWith("--") && !worldPath) {
|
|
3215
|
+
worldPath = arg;
|
|
3216
|
+
}
|
|
3217
|
+
}
|
|
3218
|
+
if (!worldPath) {
|
|
3219
|
+
throw new Error("Usage: neuroverse explain <world-path-or-id>");
|
|
3220
|
+
}
|
|
3221
|
+
return { worldPath, json };
|
|
3222
|
+
}
|
|
3194
3223
|
async function main2(argv = process.argv.slice(2)) {
|
|
3195
3224
|
try {
|
|
3196
3225
|
const args = parseArgs2(argv);
|
|
@@ -3215,6 +3244,7 @@ var init_explain = __esm({
|
|
|
3215
3244
|
"use strict";
|
|
3216
3245
|
init_world_loader();
|
|
3217
3246
|
init_explain_engine();
|
|
3247
|
+
init_cli_utils();
|
|
3218
3248
|
}
|
|
3219
3249
|
});
|
|
3220
3250
|
|
|
@@ -3550,7 +3580,7 @@ function parseArgs3(argv) {
|
|
|
3550
3580
|
if (eqIdx > 0) {
|
|
3551
3581
|
const key = pair.slice(0, eqIdx);
|
|
3552
3582
|
const rawValue = pair.slice(eqIdx + 1);
|
|
3553
|
-
stateOverrides[key] =
|
|
3583
|
+
stateOverrides[key] = parseCliValue(rawValue);
|
|
3554
3584
|
}
|
|
3555
3585
|
} else if (!arg.startsWith("--") && !worldPath) {
|
|
3556
3586
|
worldPath = arg;
|
|
@@ -3561,39 +3591,10 @@ function parseArgs3(argv) {
|
|
|
3561
3591
|
}
|
|
3562
3592
|
return { worldPath, steps, stateOverrides, profile, json };
|
|
3563
3593
|
}
|
|
3564
|
-
function parseValue(raw) {
|
|
3565
|
-
if (raw === "true") return true;
|
|
3566
|
-
if (raw === "false") return false;
|
|
3567
|
-
const num = Number(raw);
|
|
3568
|
-
if (!isNaN(num) && raw.trim() !== "") return num;
|
|
3569
|
-
return raw;
|
|
3570
|
-
}
|
|
3571
|
-
async function resolveWorldPath2(input) {
|
|
3572
|
-
const { stat } = await import("fs/promises");
|
|
3573
|
-
try {
|
|
3574
|
-
const info = await stat(input);
|
|
3575
|
-
if (info.isDirectory()) return input;
|
|
3576
|
-
} catch {
|
|
3577
|
-
}
|
|
3578
|
-
const neuroversePath = `.neuroverse/worlds/${input}`;
|
|
3579
|
-
try {
|
|
3580
|
-
const info = await stat(neuroversePath);
|
|
3581
|
-
if (info.isDirectory()) return neuroversePath;
|
|
3582
|
-
} catch {
|
|
3583
|
-
}
|
|
3584
|
-
throw new Error(
|
|
3585
|
-
`World not found: "${input}"
|
|
3586
|
-
Tried:
|
|
3587
|
-
${input}
|
|
3588
|
-
${neuroversePath}
|
|
3589
|
-
|
|
3590
|
-
Build a world first: neuroverse build <input.md>`
|
|
3591
|
-
);
|
|
3592
|
-
}
|
|
3593
3594
|
async function main3(argv = process.argv.slice(2)) {
|
|
3594
3595
|
try {
|
|
3595
3596
|
const args = parseArgs3(argv);
|
|
3596
|
-
const resolvedPath = await
|
|
3597
|
+
const resolvedPath = await resolveWorldPath(args.worldPath);
|
|
3597
3598
|
const world = await loadWorld(resolvedPath);
|
|
3598
3599
|
const result = simulateWorld(world, {
|
|
3599
3600
|
steps: args.steps,
|
|
@@ -3628,6 +3629,7 @@ var init_simulate = __esm({
|
|
|
3628
3629
|
"use strict";
|
|
3629
3630
|
init_world_loader();
|
|
3630
3631
|
init_simulate_engine();
|
|
3632
|
+
init_cli_utils();
|
|
3631
3633
|
}
|
|
3632
3634
|
});
|
|
3633
3635
|
|
|
@@ -3988,32 +3990,10 @@ function parseArgs4(argv) {
|
|
|
3988
3990
|
}
|
|
3989
3991
|
return { worldPath, json };
|
|
3990
3992
|
}
|
|
3991
|
-
async function resolveWorldPath3(input) {
|
|
3992
|
-
const { stat } = await import("fs/promises");
|
|
3993
|
-
try {
|
|
3994
|
-
const info = await stat(input);
|
|
3995
|
-
if (info.isDirectory()) return input;
|
|
3996
|
-
} catch {
|
|
3997
|
-
}
|
|
3998
|
-
const neuroversePath = `.neuroverse/worlds/${input}`;
|
|
3999
|
-
try {
|
|
4000
|
-
const info = await stat(neuroversePath);
|
|
4001
|
-
if (info.isDirectory()) return neuroversePath;
|
|
4002
|
-
} catch {
|
|
4003
|
-
}
|
|
4004
|
-
throw new Error(
|
|
4005
|
-
`World not found: "${input}"
|
|
4006
|
-
Tried:
|
|
4007
|
-
${input}
|
|
4008
|
-
${neuroversePath}
|
|
4009
|
-
|
|
4010
|
-
Build a world first: neuroverse build <input.md>`
|
|
4011
|
-
);
|
|
4012
|
-
}
|
|
4013
3993
|
async function main4(argv = process.argv.slice(2)) {
|
|
4014
3994
|
try {
|
|
4015
3995
|
const args = parseArgs4(argv);
|
|
4016
|
-
const resolvedPath = await
|
|
3996
|
+
const resolvedPath = await resolveWorldPath(args.worldPath);
|
|
4017
3997
|
const world = await loadWorld(resolvedPath);
|
|
4018
3998
|
const report = improveWorld(world);
|
|
4019
3999
|
if (args.json) {
|
|
@@ -4047,6 +4027,7 @@ var init_improve = __esm({
|
|
|
4047
4027
|
"use strict";
|
|
4048
4028
|
init_world_loader();
|
|
4049
4029
|
init_improve_engine();
|
|
4030
|
+
init_cli_utils();
|
|
4050
4031
|
}
|
|
4051
4032
|
});
|
|
4052
4033
|
|
|
@@ -4164,9 +4145,9 @@ function parseArgs5(argv) {
|
|
|
4164
4145
|
async function main5(argv = process.argv.slice(2)) {
|
|
4165
4146
|
try {
|
|
4166
4147
|
const args = parseArgs5(argv);
|
|
4167
|
-
const { writeFile:
|
|
4168
|
-
const { existsSync:
|
|
4169
|
-
if (
|
|
4148
|
+
const { writeFile: writeFile5 } = await import("fs/promises");
|
|
4149
|
+
const { existsSync: existsSync5 } = await import("fs");
|
|
4150
|
+
if (existsSync5(args.outputPath)) {
|
|
4170
4151
|
process.stderr.write(`File already exists: ${args.outputPath}
|
|
4171
4152
|
`);
|
|
4172
4153
|
process.stderr.write("Use a different --output path or remove the existing file.\n");
|
|
@@ -4174,7 +4155,7 @@ async function main5(argv = process.argv.slice(2)) {
|
|
|
4174
4155
|
return;
|
|
4175
4156
|
}
|
|
4176
4157
|
const template = generateTemplate(args.name);
|
|
4177
|
-
await
|
|
4158
|
+
await writeFile5(args.outputPath, template, "utf-8");
|
|
4178
4159
|
const result = {
|
|
4179
4160
|
created: args.outputPath,
|
|
4180
4161
|
worldName: args.name,
|
|
@@ -4199,119 +4180,898 @@ var init_init = __esm({
|
|
|
4199
4180
|
}
|
|
4200
4181
|
});
|
|
4201
4182
|
|
|
4202
|
-
// src/
|
|
4203
|
-
var
|
|
4204
|
-
|
|
4205
|
-
"src/contracts/bootstrap-contract.ts"() {
|
|
4206
|
-
"use strict";
|
|
4207
|
-
BOOTSTRAP_EXIT_CODES = {
|
|
4208
|
-
SUCCESS: 0,
|
|
4209
|
-
FAIL: 1,
|
|
4210
|
-
ERROR: 3
|
|
4211
|
-
};
|
|
4212
|
-
}
|
|
4213
|
-
});
|
|
4214
|
-
|
|
4215
|
-
// src/cli/bootstrap.ts
|
|
4216
|
-
var bootstrap_exports = {};
|
|
4217
|
-
__export(bootstrap_exports, {
|
|
4183
|
+
// src/cli/init-world.ts
|
|
4184
|
+
var init_world_exports = {};
|
|
4185
|
+
__export(init_world_exports, {
|
|
4218
4186
|
main: () => main6
|
|
4219
4187
|
});
|
|
4220
4188
|
function parseArgs6(argv) {
|
|
4221
|
-
|
|
4189
|
+
const template = argv[0] || "";
|
|
4222
4190
|
let outputPath = "";
|
|
4223
|
-
|
|
4224
|
-
let
|
|
4225
|
-
for (let i = 0; i < argv.length; i++) {
|
|
4191
|
+
const config = {};
|
|
4192
|
+
for (let i = 1; i < argv.length; i++) {
|
|
4226
4193
|
const arg = argv[i];
|
|
4227
|
-
if (arg === "--
|
|
4228
|
-
|
|
4194
|
+
if (arg === "--context" && i + 1 < argv.length) {
|
|
4195
|
+
config.context = argv[++i];
|
|
4196
|
+
} else if (arg === "--dataset" && i + 1 < argv.length) {
|
|
4197
|
+
config.dataset = argv[++i];
|
|
4198
|
+
} else if (arg === "--goal" && i + 1 < argv.length) {
|
|
4199
|
+
config.goal = argv[++i];
|
|
4200
|
+
} else if (arg === "--metric" && i + 1 < argv.length) {
|
|
4201
|
+
config.metric = argv[++i];
|
|
4202
|
+
} else if (arg === "--optimize" && i + 1 < argv.length) {
|
|
4203
|
+
const dir = argv[++i];
|
|
4204
|
+
if (dir === "minimize" || dir === "maximize") {
|
|
4205
|
+
config.optimize = dir;
|
|
4206
|
+
}
|
|
4207
|
+
} else if (arg === "--compute" && i + 1 < argv.length) {
|
|
4208
|
+
config.computeBudgetMinutes = parseInt(argv[++i], 10);
|
|
4229
4209
|
} else if (arg === "--output" && i + 1 < argv.length) {
|
|
4230
4210
|
outputPath = argv[++i];
|
|
4231
|
-
} else if (arg === "--validate") {
|
|
4232
|
-
validate = true;
|
|
4233
|
-
} else if (arg === "--format" && i + 1 < argv.length) {
|
|
4234
|
-
const val = argv[++i];
|
|
4235
|
-
if (val === "full" || val === "summary") format = val;
|
|
4236
4211
|
}
|
|
4237
4212
|
}
|
|
4238
|
-
|
|
4239
|
-
if (!outputPath) throw new Error("--output <path> is required");
|
|
4240
|
-
return { inputPath, outputPath, validate, format };
|
|
4213
|
+
return { template, config, outputPath };
|
|
4241
4214
|
}
|
|
4242
|
-
|
|
4243
|
-
|
|
4244
|
-
|
|
4245
|
-
|
|
4246
|
-
|
|
4247
|
-
|
|
4248
|
-
|
|
4249
|
-
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4215
|
+
function loadBaseTemplate(template) {
|
|
4216
|
+
let currentDir;
|
|
4217
|
+
try {
|
|
4218
|
+
currentDir = (0, import_path3.dirname)((0, import_url.fileURLToPath)(import_meta2.url));
|
|
4219
|
+
} catch {
|
|
4220
|
+
currentDir = __dirname;
|
|
4221
|
+
}
|
|
4222
|
+
const candidates = [
|
|
4223
|
+
(0, import_path3.join)(currentDir, "..", "worlds", `${template}.nv-world.md`),
|
|
4224
|
+
(0, import_path3.join)(currentDir, "worlds", `${template}.nv-world.md`),
|
|
4225
|
+
// Fallback: resolve from process.cwd()
|
|
4226
|
+
(0, import_path3.join)(process.cwd(), "src", "worlds", `${template}.nv-world.md`)
|
|
4227
|
+
];
|
|
4228
|
+
for (const candidate of candidates) {
|
|
4229
|
+
if ((0, import_fs.existsSync)(candidate)) {
|
|
4230
|
+
return (0, import_fs.readFileSync)(candidate, "utf-8");
|
|
4231
|
+
}
|
|
4232
|
+
}
|
|
4233
|
+
throw new Error(`Template "${template}" not found. Available: ${AVAILABLE_TEMPLATES.join(", ")}`);
|
|
4234
|
+
}
|
|
4235
|
+
function customizeAutoresearchWorld(baseTemplate, config) {
|
|
4236
|
+
let output = baseTemplate;
|
|
4237
|
+
if (config.context) {
|
|
4238
|
+
const worldId = config.context.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "").slice(0, 40);
|
|
4239
|
+
output = output.replace(/^world_id: autoresearch$/m, `world_id: ${worldId}_research`);
|
|
4240
|
+
output = output.replace(/^name: Autoresearch Governance$/m, `name: ${config.context} Research`);
|
|
4241
|
+
}
|
|
4242
|
+
if (config.context) {
|
|
4243
|
+
const customThesis = `Autonomous AI research loops investigating ${config.context} must operate within structured governance: experiments are reproducible, metrics are tracked, compute budgets are enforced, and agents cannot drift beyond their declared research context. A research world without constraints produces noise, not knowledge.`;
|
|
4244
|
+
output = output.replace(
|
|
4245
|
+
/^Autonomous AI research loops must operate.*$/m,
|
|
4246
|
+
customThesis
|
|
4247
|
+
);
|
|
4248
|
+
}
|
|
4249
|
+
if (config.dataset) {
|
|
4250
|
+
output = output.replace(
|
|
4251
|
+
/- `dataset_must_be_declared`[^\n]+/,
|
|
4252
|
+
`- \`dataset_must_be_declared\` \u2014 The dataset "${config.dataset}" must be used for training and evaluation and never changed without governance approval (structural, immutable)`
|
|
4253
|
+
);
|
|
4254
|
+
}
|
|
4255
|
+
if (config.context && config.constraints && config.constraints.length > 0) {
|
|
4256
|
+
const constraintInvariants = config.constraints.map(
|
|
4257
|
+
(c, i) => `- \`custom_constraint_${i + 1}\` \u2014 ${c} (prompt, immutable)`
|
|
4258
|
+
).join("\n");
|
|
4259
|
+
output = output.replace(
|
|
4260
|
+
/- `architecture_constraints_honored`[^\n]+/,
|
|
4261
|
+
`- \`architecture_constraints_honored\` \u2014 If the research context declares architectural constraints, experiments must satisfy them (prompt, immutable)
|
|
4262
|
+
${constraintInvariants}`
|
|
4263
|
+
);
|
|
4264
|
+
}
|
|
4265
|
+
if (config.metric) {
|
|
4266
|
+
output = output.replace(
|
|
4267
|
+
/Best value achieved for the primary evaluation metric/g,
|
|
4268
|
+
`Best value achieved for ${config.metric}`
|
|
4269
|
+
);
|
|
4270
|
+
}
|
|
4271
|
+
if (config.computeBudgetMinutes) {
|
|
4272
|
+
output = output.replace(
|
|
4273
|
+
/- default: 1440\n- label: Compute Budget/,
|
|
4274
|
+
`- default: ${config.computeBudgetMinutes}
|
|
4275
|
+
- label: Compute Budget`
|
|
4276
|
+
);
|
|
4277
|
+
}
|
|
4278
|
+
if (config.optimize === "maximize") {
|
|
4279
|
+
output = output.replace(
|
|
4280
|
+
/- default: 100\n- label: Best Metric Value/,
|
|
4281
|
+
"- default: -1000\n- label: Best Metric Value"
|
|
4282
|
+
);
|
|
4256
4283
|
}
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4284
|
+
return output;
|
|
4285
|
+
}
|
|
4286
|
+
function generateResearchContext(config) {
|
|
4287
|
+
const context = {
|
|
4288
|
+
research: {
|
|
4289
|
+
context: config.context || "Define your research context",
|
|
4290
|
+
dataset: config.dataset || "Define your dataset",
|
|
4291
|
+
goal: config.goal || "Define your optimization goal",
|
|
4292
|
+
metric: {
|
|
4293
|
+
name: config.metric || "val_bpb",
|
|
4294
|
+
optimization: config.optimize || "minimize"
|
|
4295
|
+
}
|
|
4296
|
+
},
|
|
4297
|
+
roles: config.roles || [
|
|
4298
|
+
"hypothesis_generator",
|
|
4299
|
+
"experiment_runner",
|
|
4300
|
+
"result_evaluator",
|
|
4301
|
+
"critic"
|
|
4302
|
+
],
|
|
4303
|
+
experiment_loop: {
|
|
4304
|
+
generate_architecture: true,
|
|
4305
|
+
train_model: true,
|
|
4306
|
+
evaluate_results: true,
|
|
4307
|
+
iterate: true
|
|
4308
|
+
},
|
|
4309
|
+
state: {
|
|
4310
|
+
experiments_run: 0,
|
|
4311
|
+
best_result: null,
|
|
4312
|
+
architectures_tested: []
|
|
4313
|
+
}
|
|
4314
|
+
};
|
|
4315
|
+
return JSON.stringify(context, null, 2);
|
|
4260
4316
|
}
|
|
4261
4317
|
async function main6(argv = process.argv.slice(2)) {
|
|
4262
|
-
const startTime = performance.now();
|
|
4263
4318
|
try {
|
|
4264
4319
|
const args = parseArgs6(argv);
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
|
|
4268
|
-
|
|
4269
|
-
|
|
4270
|
-
|
|
4271
|
-
|
|
4272
|
-
process.
|
|
4320
|
+
if (!args.template) {
|
|
4321
|
+
process.stderr.write("Usage: neuroverse init-world <template> [options]\n\n");
|
|
4322
|
+
process.stderr.write("Available templates:\n");
|
|
4323
|
+
for (const t of AVAILABLE_TEMPLATES) {
|
|
4324
|
+
process.stderr.write(` ${t} Generate a governed research world for autonomous AI experiments
|
|
4325
|
+
`);
|
|
4326
|
+
}
|
|
4327
|
+
process.stderr.write("\nExample:\n");
|
|
4328
|
+
process.stderr.write(' neuroverse init-world autoresearch --context "attention-free LLM architectures" --dataset "TinyStories"\n');
|
|
4329
|
+
process.exit(1);
|
|
4273
4330
|
return;
|
|
4274
4331
|
}
|
|
4275
|
-
|
|
4276
|
-
|
|
4277
|
-
|
|
4278
|
-
|
|
4279
|
-
|
|
4280
|
-
|
|
4281
|
-
issues: parseResult.issues,
|
|
4282
|
-
parsedSections: [],
|
|
4283
|
-
durationMs: performance.now() - startTime
|
|
4284
|
-
};
|
|
4285
|
-
process.stdout.write(JSON.stringify(result2, null, 2) + "\n");
|
|
4286
|
-
process.exit(BOOTSTRAP_EXIT_CODES.FAIL);
|
|
4332
|
+
if (!AVAILABLE_TEMPLATES.includes(args.template)) {
|
|
4333
|
+
process.stderr.write(`Unknown template: "${args.template}"
|
|
4334
|
+
`);
|
|
4335
|
+
process.stderr.write(`Available: ${AVAILABLE_TEMPLATES.join(", ")}
|
|
4336
|
+
`);
|
|
4337
|
+
process.exit(1);
|
|
4287
4338
|
return;
|
|
4288
4339
|
}
|
|
4289
|
-
const
|
|
4290
|
-
const
|
|
4291
|
-
|
|
4292
|
-
|
|
4293
|
-
|
|
4294
|
-
|
|
4295
|
-
|
|
4340
|
+
const worldFileName = args.config.context ? args.config.context.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) + ".nv-world.md" : "research.nv-world.md";
|
|
4341
|
+
const outputPath = args.outputPath || `./${worldFileName}`;
|
|
4342
|
+
if ((0, import_fs.existsSync)(outputPath)) {
|
|
4343
|
+
process.stderr.write(`File already exists: ${outputPath}
|
|
4344
|
+
`);
|
|
4345
|
+
process.stderr.write("Use --output to specify a different path.\n");
|
|
4346
|
+
process.exit(2);
|
|
4347
|
+
return;
|
|
4296
4348
|
}
|
|
4349
|
+
const baseTemplate = loadBaseTemplate(args.template);
|
|
4350
|
+
const customized = customizeAutoresearchWorld(baseTemplate, args.config);
|
|
4351
|
+
await (0, import_promises4.writeFile)(outputPath, customized, "utf-8");
|
|
4352
|
+
const contextPath = outputPath.replace(/\.nv-world\.md$/, ".research.json");
|
|
4353
|
+
await (0, import_promises4.writeFile)(contextPath, generateResearchContext(args.config), "utf-8");
|
|
4297
4354
|
const result = {
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4355
|
+
created: {
|
|
4356
|
+
world: outputPath,
|
|
4357
|
+
context: contextPath
|
|
4358
|
+
},
|
|
4359
|
+
template: args.template,
|
|
4360
|
+
config: {
|
|
4361
|
+
context: args.config.context || null,
|
|
4362
|
+
dataset: args.config.dataset || null,
|
|
4363
|
+
goal: args.config.goal || null,
|
|
4364
|
+
metric: args.config.metric || "val_bpb",
|
|
4365
|
+
optimize: args.config.optimize || "minimize",
|
|
4366
|
+
computeBudgetMinutes: args.config.computeBudgetMinutes || 1440
|
|
4367
|
+
},
|
|
4368
|
+
nextSteps: [
|
|
4369
|
+
`Edit ${outputPath} to refine governance rules for your research`,
|
|
4370
|
+
`neuroverse bootstrap --input ${outputPath} --output ./world/ --validate`,
|
|
4371
|
+
`neuroverse simulate ${outputPath} --steps 5`,
|
|
4372
|
+
`neuroverse guard --world ./world/ < experiment.json`,
|
|
4373
|
+
`npx autoresearch run --world ${contextPath}`
|
|
4374
|
+
]
|
|
4308
4375
|
};
|
|
4309
|
-
if (validateReport) {
|
|
4310
|
-
result.validateReport = args.format === "summary" ? { summary: validateReport.summary } : validateReport;
|
|
4311
|
-
}
|
|
4312
4376
|
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
|
|
4313
|
-
|
|
4314
|
-
process.
|
|
4377
|
+
process.stderr.write("\n");
|
|
4378
|
+
process.stderr.write(`\u2713 World created: ${outputPath}
|
|
4379
|
+
`);
|
|
4380
|
+
process.stderr.write(`\u2713 Research context: ${contextPath}
|
|
4381
|
+
`);
|
|
4382
|
+
process.stderr.write("\n");
|
|
4383
|
+
process.stderr.write("Next steps:\n");
|
|
4384
|
+
process.stderr.write(` Compile world neuroverse bootstrap --input ${outputPath} --output ./world/ --validate
|
|
4385
|
+
`);
|
|
4386
|
+
process.stderr.write(` Simulate neuroverse simulate ${outputPath} --steps 5
|
|
4387
|
+
`);
|
|
4388
|
+
process.stderr.write(` Run autoresearch npx autoresearch run --world ${contextPath}
|
|
4389
|
+
`);
|
|
4390
|
+
process.stderr.write(` Launch dashboard make dashboard
|
|
4391
|
+
`);
|
|
4392
|
+
process.stderr.write("\n");
|
|
4393
|
+
process.exit(0);
|
|
4394
|
+
} catch (e) {
|
|
4395
|
+
process.stderr.write(`init-world failed: ${e instanceof Error ? e.message : e}
|
|
4396
|
+
`);
|
|
4397
|
+
process.exit(3);
|
|
4398
|
+
}
|
|
4399
|
+
}
|
|
4400
|
+
var import_fs, import_promises4, import_path3, import_url, import_meta2, AVAILABLE_TEMPLATES;
|
|
4401
|
+
var init_init_world = __esm({
|
|
4402
|
+
"src/cli/init-world.ts"() {
|
|
4403
|
+
"use strict";
|
|
4404
|
+
import_fs = require("fs");
|
|
4405
|
+
import_promises4 = require("fs/promises");
|
|
4406
|
+
import_path3 = require("path");
|
|
4407
|
+
import_url = require("url");
|
|
4408
|
+
import_meta2 = {};
|
|
4409
|
+
AVAILABLE_TEMPLATES = ["autoresearch"];
|
|
4410
|
+
}
|
|
4411
|
+
});
|
|
4412
|
+
|
|
4413
|
+
// src/cli/infer-world.ts
|
|
4414
|
+
var infer_world_exports = {};
|
|
4415
|
+
__export(infer_world_exports, {
|
|
4416
|
+
main: () => main7
|
|
4417
|
+
});
|
|
4418
|
+
function scanRepo(repoPath) {
|
|
4419
|
+
const signals = [];
|
|
4420
|
+
let entries;
|
|
4421
|
+
try {
|
|
4422
|
+
entries = (0, import_fs2.readdirSync)(repoPath);
|
|
4423
|
+
} catch {
|
|
4424
|
+
return signals;
|
|
4425
|
+
}
|
|
4426
|
+
for (const entry of entries) {
|
|
4427
|
+
const lower = entry.toLowerCase();
|
|
4428
|
+
const fullPath = (0, import_path4.join)(repoPath, entry);
|
|
4429
|
+
if (SCAN_PATTERNS[lower]) {
|
|
4430
|
+
signals.push({
|
|
4431
|
+
path: entry,
|
|
4432
|
+
signal: SCAN_PATTERNS[lower].signal,
|
|
4433
|
+
confidence: SCAN_PATTERNS[lower].confidence
|
|
4434
|
+
});
|
|
4435
|
+
}
|
|
4436
|
+
if (entry !== lower && SCAN_PATTERNS[entry]) {
|
|
4437
|
+
signals.push({
|
|
4438
|
+
path: entry,
|
|
4439
|
+
signal: SCAN_PATTERNS[entry].signal,
|
|
4440
|
+
confidence: SCAN_PATTERNS[entry].confidence
|
|
4441
|
+
});
|
|
4442
|
+
}
|
|
4443
|
+
if (lower === "readme.md" || lower === "readme.rst" || lower === "readme.txt") {
|
|
4444
|
+
signals.push({ path: entry, signal: "documentation", confidence: 0.3 });
|
|
4445
|
+
}
|
|
4446
|
+
if (lower === "package.json" || lower === "cargo.toml" || lower === "go.mod") {
|
|
4447
|
+
signals.push({ path: entry, signal: "project manifest", confidence: 0.4 });
|
|
4448
|
+
}
|
|
4449
|
+
try {
|
|
4450
|
+
if ((0, import_fs2.statSync)(fullPath).isDirectory() && RESEARCH_DIRECTORIES.includes(lower)) {
|
|
4451
|
+
signals.push({
|
|
4452
|
+
path: entry + "/",
|
|
4453
|
+
signal: `${lower} directory`,
|
|
4454
|
+
confidence: 0.6
|
|
4455
|
+
});
|
|
4456
|
+
}
|
|
4457
|
+
} catch {
|
|
4458
|
+
}
|
|
4459
|
+
}
|
|
4460
|
+
return signals;
|
|
4461
|
+
}
|
|
4462
|
+
function readFileContent(path, maxBytes = 5e4) {
|
|
4463
|
+
try {
|
|
4464
|
+
const stat = (0, import_fs2.statSync)(path);
|
|
4465
|
+
if (stat.size > maxBytes) {
|
|
4466
|
+
return (0, import_fs2.readFileSync)(path, { encoding: "utf-8", flag: "r" }).slice(0, maxBytes);
|
|
4467
|
+
}
|
|
4468
|
+
return (0, import_fs2.readFileSync)(path, "utf-8");
|
|
4469
|
+
} catch {
|
|
4470
|
+
return null;
|
|
4471
|
+
}
|
|
4472
|
+
}
|
|
4473
|
+
function extractFromContent(repoPath, signals) {
|
|
4474
|
+
const result = {
|
|
4475
|
+
architectures: [],
|
|
4476
|
+
constraints: [],
|
|
4477
|
+
goals: []
|
|
4478
|
+
};
|
|
4479
|
+
const filesToRead = [
|
|
4480
|
+
"program.md",
|
|
4481
|
+
"train.py",
|
|
4482
|
+
"train.js",
|
|
4483
|
+
"train.ts",
|
|
4484
|
+
"prepare.py",
|
|
4485
|
+
"config.yaml",
|
|
4486
|
+
"config.json",
|
|
4487
|
+
"dataset.yaml",
|
|
4488
|
+
"dataset.json",
|
|
4489
|
+
"README.md",
|
|
4490
|
+
"readme.md"
|
|
4491
|
+
];
|
|
4492
|
+
const allContent = [];
|
|
4493
|
+
for (const file of filesToRead) {
|
|
4494
|
+
const content = readFileContent((0, import_path4.join)(repoPath, file));
|
|
4495
|
+
if (content) {
|
|
4496
|
+
allContent.push(content);
|
|
4497
|
+
}
|
|
4498
|
+
}
|
|
4499
|
+
const combined = allContent.join("\n");
|
|
4500
|
+
if (!combined) return result;
|
|
4501
|
+
for (const pattern of DATASET_PATTERNS) {
|
|
4502
|
+
const match = combined.match(pattern);
|
|
4503
|
+
if (match) {
|
|
4504
|
+
result.dataset = match[1] || match[0].trim();
|
|
4505
|
+
break;
|
|
4506
|
+
}
|
|
4507
|
+
}
|
|
4508
|
+
for (const pattern of METRIC_PATTERNS) {
|
|
4509
|
+
const match = combined.match(pattern);
|
|
4510
|
+
if (match) {
|
|
4511
|
+
result.metric = match[0].trim().toLowerCase().replace(/\s+/g, "_");
|
|
4512
|
+
break;
|
|
4513
|
+
}
|
|
4514
|
+
}
|
|
4515
|
+
if (result.metric) {
|
|
4516
|
+
const lossLike = /loss|bpb|perplexity|mse|rmse|mae|error/i.test(result.metric);
|
|
4517
|
+
result.optimization = lossLike ? "minimize" : "maximize";
|
|
4518
|
+
}
|
|
4519
|
+
const archs = /* @__PURE__ */ new Set();
|
|
4520
|
+
for (const pattern of ARCHITECTURE_PATTERNS) {
|
|
4521
|
+
const match = combined.match(pattern);
|
|
4522
|
+
if (match) {
|
|
4523
|
+
archs.add(match[0].trim());
|
|
4524
|
+
}
|
|
4525
|
+
}
|
|
4526
|
+
result.architectures = [...archs];
|
|
4527
|
+
for (const [pattern, framework] of FRAMEWORK_PATTERNS) {
|
|
4528
|
+
if (pattern.test(combined)) {
|
|
4529
|
+
result.framework = framework;
|
|
4530
|
+
break;
|
|
4531
|
+
}
|
|
4532
|
+
}
|
|
4533
|
+
const programContent = readFileContent((0, import_path4.join)(repoPath, "program.md"));
|
|
4534
|
+
if (programContent) {
|
|
4535
|
+
result.hasProgram = true;
|
|
4536
|
+
const lines = programContent.split("\n");
|
|
4537
|
+
for (const line of lines) {
|
|
4538
|
+
const trimmed = line.trim();
|
|
4539
|
+
if ((trimmed.startsWith("- ") || trimmed.startsWith("* ")) && trimmed.length > 10 && trimmed.length < 200) {
|
|
4540
|
+
result.goals.push(trimmed.slice(2).trim());
|
|
4541
|
+
}
|
|
4542
|
+
}
|
|
4543
|
+
}
|
|
4544
|
+
result.hasExperimentLoop = /experiment|loop|iteration|epoch|trial|run|sweep/i.test(combined) && /result|metric|eval|score|loss|accuracy/i.test(combined);
|
|
4545
|
+
return result;
|
|
4546
|
+
}
|
|
4547
|
+
function classifyEnvironment(signals, extracted) {
|
|
4548
|
+
let type = "unknown";
|
|
4549
|
+
let confidence = 0;
|
|
4550
|
+
const hasTrainCode = signals.some((s) => s.signal.includes("training code"));
|
|
4551
|
+
const hasDataset = !!extracted.dataset;
|
|
4552
|
+
const hasMetric = !!extracted.metric;
|
|
4553
|
+
const hasExperimentLoop = !!extracted.hasExperimentLoop;
|
|
4554
|
+
const hasResearchDirs = signals.some(
|
|
4555
|
+
(s) => ["experiments directory", "results directory", "notebooks directory", "models directory"].includes(s.signal)
|
|
4556
|
+
);
|
|
4557
|
+
const researchScore = (hasTrainCode ? 30 : 0) + (hasDataset ? 20 : 0) + (hasMetric ? 20 : 0) + (hasExperimentLoop ? 15 : 0) + (hasResearchDirs ? 10 : 0) + (extracted.hasProgram ? 15 : 0);
|
|
4558
|
+
if (researchScore >= 40) {
|
|
4559
|
+
type = "research";
|
|
4560
|
+
confidence = Math.min(researchScore, 100);
|
|
4561
|
+
} else if (signals.length > 0) {
|
|
4562
|
+
type = "application";
|
|
4563
|
+
confidence = 30;
|
|
4564
|
+
}
|
|
4565
|
+
return {
|
|
4566
|
+
type,
|
|
4567
|
+
confidence,
|
|
4568
|
+
dataset: extracted.dataset || null,
|
|
4569
|
+
metric: extracted.metric || null,
|
|
4570
|
+
optimization: extracted.optimization || null,
|
|
4571
|
+
framework: extracted.framework || null,
|
|
4572
|
+
architectures: extracted.architectures || [],
|
|
4573
|
+
constraints: extracted.constraints || [],
|
|
4574
|
+
hasExperimentLoop,
|
|
4575
|
+
hasProgram: !!extracted.hasProgram,
|
|
4576
|
+
goals: extracted.goals || [],
|
|
4577
|
+
files: signals
|
|
4578
|
+
};
|
|
4579
|
+
}
|
|
4580
|
+
function generateWorldFromDetection(env, repoName) {
|
|
4581
|
+
const worldId = repoName.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
|
|
4582
|
+
const dataset = env.dataset || "UNDETECTED";
|
|
4583
|
+
const metric = env.metric || "val_loss";
|
|
4584
|
+
const optimization = env.optimization || "minimize";
|
|
4585
|
+
const framework = env.framework || "Unknown";
|
|
4586
|
+
const architectures = env.architectures.length > 0 ? env.architectures.join(", ") : "not detected";
|
|
4587
|
+
const contextDescription = env.type === "research" ? `ML research using ${framework} on ${dataset}` : `AI application with governance requirements`;
|
|
4588
|
+
const goals = env.goals.length > 0 ? env.goals.slice(0, 3).map((g) => ` - ${g}`).join("\n") : " - Define research goals here";
|
|
4589
|
+
return `---
|
|
4590
|
+
world_id: ${worldId}
|
|
4591
|
+
name: ${repoName} Research World
|
|
4592
|
+
version: 1.0.0
|
|
4593
|
+
runtime_mode: SIMULATION
|
|
4594
|
+
default_profile: inferred
|
|
4595
|
+
alternative_profile: strict
|
|
4596
|
+
---
|
|
4597
|
+
|
|
4598
|
+
# Thesis
|
|
4599
|
+
|
|
4600
|
+
${contextDescription}. Experiments must be reproducible, metrics must be tracked, and agents must operate within the declared research context. This world was inferred from repository structure \u2014 review and refine the constraints below.
|
|
4601
|
+
|
|
4602
|
+
# Invariants
|
|
4603
|
+
|
|
4604
|
+
- \`experiments_must_be_reproducible\` \u2014 Every experiment must log architecture, hyperparameters, dataset, and training config sufficient to reproduce results (structural, immutable)
|
|
4605
|
+
- \`metrics_must_be_recorded\` \u2014 Every training run must produce the primary evaluation metric (${metric}); runs without metrics are invalid (structural, immutable)
|
|
4606
|
+
- \`dataset_is_${dataset.toLowerCase().replace(/[^a-z0-9]+/g, "_")}\` \u2014 The dataset "${dataset}" must be used for training and evaluation (structural, immutable)
|
|
4607
|
+
- \`compute_budget_enforced\` \u2014 Experiments must respect declared compute limits (structural, immutable)
|
|
4608
|
+
|
|
4609
|
+
# State
|
|
4610
|
+
|
|
4611
|
+
## experiments_run
|
|
4612
|
+
- type: number
|
|
4613
|
+
- min: 0
|
|
4614
|
+
- max: 10000
|
|
4615
|
+
- step: 1
|
|
4616
|
+
- default: 0
|
|
4617
|
+
- label: Experiments Run
|
|
4618
|
+
- description: Total number of experiments completed
|
|
4619
|
+
|
|
4620
|
+
## best_metric_value
|
|
4621
|
+
- type: number
|
|
4622
|
+
- min: -1000
|
|
4623
|
+
- max: 1000
|
|
4624
|
+
- step: 0.01
|
|
4625
|
+
- default: ${optimization === "minimize" ? "100" : "-1000"}
|
|
4626
|
+
- label: Best ${metric}
|
|
4627
|
+
- description: Best value achieved for ${metric}
|
|
4628
|
+
|
|
4629
|
+
## keep_rate
|
|
4630
|
+
- type: number
|
|
4631
|
+
- min: 0
|
|
4632
|
+
- max: 100
|
|
4633
|
+
- step: 1
|
|
4634
|
+
- default: 0
|
|
4635
|
+
- label: Keep Rate
|
|
4636
|
+
- description: Percentage of experiments that improved on the best result
|
|
4637
|
+
|
|
4638
|
+
## compute_used_minutes
|
|
4639
|
+
- type: number
|
|
4640
|
+
- min: 0
|
|
4641
|
+
- max: 100000
|
|
4642
|
+
- step: 1
|
|
4643
|
+
- default: 0
|
|
4644
|
+
- label: Compute Used (minutes)
|
|
4645
|
+
- description: Total wall-clock training time consumed
|
|
4646
|
+
|
|
4647
|
+
## compute_budget_minutes
|
|
4648
|
+
- type: number
|
|
4649
|
+
- min: 0
|
|
4650
|
+
- max: 100000
|
|
4651
|
+
- step: 60
|
|
4652
|
+
- default: 1440
|
|
4653
|
+
- label: Compute Budget (minutes)
|
|
4654
|
+
- description: Maximum allowed compute time
|
|
4655
|
+
|
|
4656
|
+
## failed_experiments
|
|
4657
|
+
- type: number
|
|
4658
|
+
- min: 0
|
|
4659
|
+
- max: 10000
|
|
4660
|
+
- step: 1
|
|
4661
|
+
- default: 0
|
|
4662
|
+
- label: Failed Experiments
|
|
4663
|
+
- description: Number of experiments that failed to produce valid results
|
|
4664
|
+
|
|
4665
|
+
# Assumptions
|
|
4666
|
+
|
|
4667
|
+
## inferred
|
|
4668
|
+
- name: Inferred Configuration
|
|
4669
|
+
- description: Configuration inferred from repository structure. Framework: ${framework}. Architectures: ${architectures}.
|
|
4670
|
+
- framework: ${framework.toLowerCase().replace(/\s+/g, "_")}
|
|
4671
|
+
- dataset: ${dataset.toLowerCase()}
|
|
4672
|
+
- metric: ${metric}
|
|
4673
|
+
|
|
4674
|
+
## strict
|
|
4675
|
+
- name: Strict Configuration
|
|
4676
|
+
- description: Conservative settings with tight compute limits and strict reproducibility requirements.
|
|
4677
|
+
- framework: ${framework.toLowerCase().replace(/\s+/g, "_")}
|
|
4678
|
+
- dataset: ${dataset.toLowerCase()}
|
|
4679
|
+
- metric: ${metric}
|
|
4680
|
+
|
|
4681
|
+
# Rules
|
|
4682
|
+
|
|
4683
|
+
## rule-001: Compute Budget Exhausted (structural)
|
|
4684
|
+
When compute budget is exceeded, the research loop must halt.
|
|
4685
|
+
|
|
4686
|
+
When compute_used_minutes > compute_budget_minutes [state]
|
|
4687
|
+
Then research_viability *= 0.00
|
|
4688
|
+
Collapse: research_viability < 0.05
|
|
4689
|
+
|
|
4690
|
+
> trigger: Compute usage exceeds declared budget.
|
|
4691
|
+
> rule: Compute budget is a hard constraint. Exceeding it halts all experiments.
|
|
4692
|
+
> shift: Research loop terminates. Final results are reported.
|
|
4693
|
+
> effect: Research viability set to zero.
|
|
4694
|
+
|
|
4695
|
+
## rule-002: High Failure Rate (degradation)
|
|
4696
|
+
Too many failed experiments indicate a systemic problem.
|
|
4697
|
+
|
|
4698
|
+
When failed_experiments > 5 [state] AND experiments_run > 0 [state]
|
|
4699
|
+
Then research_viability *= 0.50
|
|
4700
|
+
|
|
4701
|
+
> trigger: More than 5 experiments have failed.
|
|
4702
|
+
> rule: High failure rates waste compute and signal infrastructure problems.
|
|
4703
|
+
> shift: Research viability degrades. Investigation needed.
|
|
4704
|
+
> effect: Research viability reduced to 50%.
|
|
4705
|
+
|
|
4706
|
+
## rule-003: No Metrics Recorded (structural)
|
|
4707
|
+
Experiments without metrics are invalid.
|
|
4708
|
+
|
|
4709
|
+
When experiments_run > 0 [state] AND best_metric_value == ${optimization === "minimize" ? "100" : "-1000"} [state]
|
|
4710
|
+
Then research_viability *= 0.30
|
|
4711
|
+
Collapse: research_viability < 0.05
|
|
4712
|
+
|
|
4713
|
+
> trigger: Experiments ran but no metric improvement from default.
|
|
4714
|
+
> rule: Research without measurement is not research.
|
|
4715
|
+
> shift: Research viability drops sharply.
|
|
4716
|
+
> effect: Research viability reduced to 30%.
|
|
4717
|
+
|
|
4718
|
+
## rule-004: Strong Progress (advantage)
|
|
4719
|
+
Consistent metric improvement validates the research approach.
|
|
4720
|
+
|
|
4721
|
+
When keep_rate > 20 [state] AND experiments_run > 5 [state]
|
|
4722
|
+
Then research_viability *= 1.20
|
|
4723
|
+
|
|
4724
|
+
> trigger: Keep rate above 20% after 5+ experiments.
|
|
4725
|
+
> rule: Productive research should be encouraged.
|
|
4726
|
+
> shift: Research viability improves.
|
|
4727
|
+
> effect: Research viability boosted by 20%.
|
|
4728
|
+
|
|
4729
|
+
# Gates
|
|
4730
|
+
|
|
4731
|
+
- BREAKTHROUGH: research_viability >= 90
|
|
4732
|
+
- PRODUCTIVE: research_viability >= 60
|
|
4733
|
+
- ONGOING: research_viability >= 35
|
|
4734
|
+
- STRUGGLING: research_viability > 10
|
|
4735
|
+
- HALTED: research_viability <= 10
|
|
4736
|
+
|
|
4737
|
+
# Outcomes
|
|
4738
|
+
|
|
4739
|
+
## research_viability
|
|
4740
|
+
- type: number
|
|
4741
|
+
- range: 0-100
|
|
4742
|
+
- display: percentage
|
|
4743
|
+
- label: Research Viability
|
|
4744
|
+
- primary: true
|
|
4745
|
+
|
|
4746
|
+
## best_metric_value
|
|
4747
|
+
- type: number
|
|
4748
|
+
- range: -1000-1000
|
|
4749
|
+
- display: decimal
|
|
4750
|
+
- label: Best ${metric}
|
|
4751
|
+
|
|
4752
|
+
## keep_rate
|
|
4753
|
+
- type: number
|
|
4754
|
+
- range: 0-100
|
|
4755
|
+
- display: percentage
|
|
4756
|
+
- label: Keep Rate
|
|
4757
|
+
`;
|
|
4758
|
+
}
|
|
4759
|
+
function parseArgs7(argv) {
|
|
4760
|
+
let repoPath = "";
|
|
4761
|
+
let outputPath = "";
|
|
4762
|
+
let json = false;
|
|
4763
|
+
let dryRun = false;
|
|
4764
|
+
for (let i = 0; i < argv.length; i++) {
|
|
4765
|
+
const arg = argv[i];
|
|
4766
|
+
if (arg === "--output" && i + 1 < argv.length) {
|
|
4767
|
+
outputPath = argv[++i];
|
|
4768
|
+
} else if (arg === "--json") {
|
|
4769
|
+
json = true;
|
|
4770
|
+
} else if (arg === "--dry-run") {
|
|
4771
|
+
dryRun = true;
|
|
4772
|
+
} else if (!arg.startsWith("-") && !repoPath) {
|
|
4773
|
+
repoPath = arg;
|
|
4774
|
+
}
|
|
4775
|
+
}
|
|
4776
|
+
return { repoPath, outputPath, json, dryRun };
|
|
4777
|
+
}
|
|
4778
|
+
async function main7(argv = process.argv.slice(2)) {
|
|
4779
|
+
try {
|
|
4780
|
+
const args = parseArgs7(argv);
|
|
4781
|
+
if (!args.repoPath) {
|
|
4782
|
+
process.stderr.write("Usage: neuroverse infer-world <repo-path> [options]\n\n");
|
|
4783
|
+
process.stderr.write("Scans an existing repository and generates a governance world file.\n\n");
|
|
4784
|
+
process.stderr.write("Options:\n");
|
|
4785
|
+
process.stderr.write(" --output <path> Output file path\n");
|
|
4786
|
+
process.stderr.write(" --json Output detection results as JSON\n");
|
|
4787
|
+
process.stderr.write(" --dry-run Show detections without writing\n");
|
|
4788
|
+
process.stderr.write("\nExample:\n");
|
|
4789
|
+
process.stderr.write(" neuroverse infer-world ./my-research-repo\n");
|
|
4790
|
+
process.exit(1);
|
|
4791
|
+
return;
|
|
4792
|
+
}
|
|
4793
|
+
const repoPath = (0, import_path4.resolve)(args.repoPath);
|
|
4794
|
+
if (!(0, import_fs2.existsSync)(repoPath)) {
|
|
4795
|
+
process.stderr.write(`Repository not found: ${repoPath}
|
|
4796
|
+
`);
|
|
4797
|
+
process.exit(1);
|
|
4798
|
+
return;
|
|
4799
|
+
}
|
|
4800
|
+
process.stderr.write(`Scanning ${repoPath}...
|
|
4801
|
+
`);
|
|
4802
|
+
const signals = scanRepo(repoPath);
|
|
4803
|
+
if (signals.length === 0) {
|
|
4804
|
+
process.stderr.write("No recognizable project structure detected.\n");
|
|
4805
|
+
process.exit(2);
|
|
4806
|
+
return;
|
|
4807
|
+
}
|
|
4808
|
+
const extracted = extractFromContent(repoPath, signals);
|
|
4809
|
+
const env = classifyEnvironment(signals, extracted);
|
|
4810
|
+
if (args.json) {
|
|
4811
|
+
process.stdout.write(JSON.stringify(env, null, 2) + "\n");
|
|
4812
|
+
process.exit(0);
|
|
4813
|
+
return;
|
|
4814
|
+
}
|
|
4815
|
+
process.stderr.write("\n");
|
|
4816
|
+
process.stderr.write(`Detected: ${env.type} environment (${env.confidence}% confidence)
|
|
4817
|
+
`);
|
|
4818
|
+
if (env.dataset) process.stderr.write(` Dataset: ${env.dataset}
|
|
4819
|
+
`);
|
|
4820
|
+
if (env.metric) process.stderr.write(` Metric: ${env.metric} (${env.optimization})
|
|
4821
|
+
`);
|
|
4822
|
+
if (env.framework) process.stderr.write(` Framework: ${env.framework}
|
|
4823
|
+
`);
|
|
4824
|
+
if (env.architectures.length > 0) process.stderr.write(` Architectures: ${env.architectures.join(", ")}
|
|
4825
|
+
`);
|
|
4826
|
+
if (env.hasExperimentLoop) process.stderr.write(` Experiment loop detected
|
|
4827
|
+
`);
|
|
4828
|
+
if (env.hasProgram) process.stderr.write(` Program file found (agent instructions)
|
|
4829
|
+
`);
|
|
4830
|
+
process.stderr.write("\n");
|
|
4831
|
+
process.stderr.write(" Files analyzed:\n");
|
|
4832
|
+
for (const s of env.files) {
|
|
4833
|
+
process.stderr.write(` ${s.path} \u2014 ${s.signal}
|
|
4834
|
+
`);
|
|
4835
|
+
}
|
|
4836
|
+
process.stderr.write("\n");
|
|
4837
|
+
if (args.dryRun) {
|
|
4838
|
+
process.stderr.write("Dry run \u2014 no files written.\n");
|
|
4839
|
+
process.exit(0);
|
|
4840
|
+
return;
|
|
4841
|
+
}
|
|
4842
|
+
const repoName = (0, import_path4.basename)(repoPath);
|
|
4843
|
+
const worldContent = generateWorldFromDetection(env, repoName);
|
|
4844
|
+
const outputPath = args.outputPath || (0, import_path4.join)(repoPath, "inferred.nv-world.md");
|
|
4845
|
+
if ((0, import_fs2.existsSync)(outputPath)) {
|
|
4846
|
+
process.stderr.write(`File already exists: ${outputPath}
|
|
4847
|
+
`);
|
|
4848
|
+
process.stderr.write("Use --output to specify a different path.\n");
|
|
4849
|
+
process.exit(1);
|
|
4850
|
+
return;
|
|
4851
|
+
}
|
|
4852
|
+
await (0, import_promises5.writeFile)(outputPath, worldContent, "utf-8");
|
|
4853
|
+
process.stderr.write(`\u2713 World created: ${outputPath}
|
|
4854
|
+
|
|
4855
|
+
`);
|
|
4856
|
+
process.stderr.write("Next steps:\n");
|
|
4857
|
+
process.stderr.write(` Review and refine Edit ${outputPath}
|
|
4858
|
+
`);
|
|
4859
|
+
process.stderr.write(` Compile neuroverse bootstrap --input ${outputPath} --output ./world/ --validate
|
|
4860
|
+
`);
|
|
4861
|
+
process.stderr.write(` Simulate neuroverse simulate ${outputPath} --steps 5
|
|
4862
|
+
`);
|
|
4863
|
+
process.stderr.write("\n");
|
|
4864
|
+
const result = {
|
|
4865
|
+
created: outputPath,
|
|
4866
|
+
environment: env,
|
|
4867
|
+
nextSteps: [
|
|
4868
|
+
`Edit ${outputPath} to refine inferred governance rules`,
|
|
4869
|
+
`neuroverse bootstrap --input ${outputPath} --output ./world/ --validate`,
|
|
4870
|
+
`neuroverse simulate ${outputPath} --steps 5`
|
|
4871
|
+
]
|
|
4872
|
+
};
|
|
4873
|
+
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
|
|
4874
|
+
process.exit(0);
|
|
4875
|
+
} catch (e) {
|
|
4876
|
+
process.stderr.write(`infer-world failed: ${e instanceof Error ? e.message : e}
|
|
4877
|
+
`);
|
|
4878
|
+
process.exit(3);
|
|
4879
|
+
}
|
|
4880
|
+
}
|
|
4881
|
+
var import_fs2, import_promises5, import_path4, SCAN_PATTERNS, RESEARCH_DIRECTORIES, DATASET_PATTERNS, METRIC_PATTERNS, ARCHITECTURE_PATTERNS, FRAMEWORK_PATTERNS;
|
|
4882
|
+
var init_infer_world = __esm({
|
|
4883
|
+
"src/cli/infer-world.ts"() {
|
|
4884
|
+
"use strict";
|
|
4885
|
+
import_fs2 = require("fs");
|
|
4886
|
+
import_promises5 = require("fs/promises");
|
|
4887
|
+
import_path4 = require("path");
|
|
4888
|
+
SCAN_PATTERNS = {
|
|
4889
|
+
"program.md": { signal: "experiment goals / agent instructions", confidence: 0.9 },
|
|
4890
|
+
"train.py": { signal: "model training code", confidence: 0.8 },
|
|
4891
|
+
"train.js": { signal: "model training code", confidence: 0.8 },
|
|
4892
|
+
"train.ts": { signal: "model training code", confidence: 0.8 },
|
|
4893
|
+
"prepare.py": { signal: "data preparation", confidence: 0.7 },
|
|
4894
|
+
"dataset.yaml": { signal: "dataset configuration", confidence: 0.8 },
|
|
4895
|
+
"dataset.json": { signal: "dataset configuration", confidence: 0.8 },
|
|
4896
|
+
"config.yaml": { signal: "project configuration", confidence: 0.5 },
|
|
4897
|
+
"config.json": { signal: "project configuration", confidence: 0.5 },
|
|
4898
|
+
"pyproject.toml": { signal: "Python project", confidence: 0.4 },
|
|
4899
|
+
"requirements.txt": { signal: "Python dependencies", confidence: 0.5 },
|
|
4900
|
+
"setup.py": { signal: "Python package", confidence: 0.4 },
|
|
4901
|
+
"Makefile": { signal: "build automation", confidence: 0.3 },
|
|
4902
|
+
"docker-compose.yml": { signal: "containerized environment", confidence: 0.4 },
|
|
4903
|
+
"Dockerfile": { signal: "containerized environment", confidence: 0.4 }
|
|
4904
|
+
};
|
|
4905
|
+
RESEARCH_DIRECTORIES = ["experiments", "results", "notebooks", "models", "checkpoints", "logs", "data", "eval"];
|
|
4906
|
+
DATASET_PATTERNS = [
|
|
4907
|
+
/dataset\s*[:=]\s*["']?([A-Za-z0-9_\-]+)/i,
|
|
4908
|
+
/--dataset\s+["']?([A-Za-z0-9_\-]+)/i,
|
|
4909
|
+
/load_dataset\(["']([^"']+)/i,
|
|
4910
|
+
/TinyStories/i,
|
|
4911
|
+
/OpenWebText/i,
|
|
4912
|
+
/WikiText/i,
|
|
4913
|
+
/C4/i,
|
|
4914
|
+
/The\s*Pile/i,
|
|
4915
|
+
/MNIST/i,
|
|
4916
|
+
/CIFAR/i,
|
|
4917
|
+
/ImageNet/i
|
|
4918
|
+
];
|
|
4919
|
+
METRIC_PATTERNS = [
|
|
4920
|
+
/val_bpb/i,
|
|
4921
|
+
/val_loss/i,
|
|
4922
|
+
/val_acc(?:uracy)?/i,
|
|
4923
|
+
/test_acc(?:uracy)?/i,
|
|
4924
|
+
/perplexity/i,
|
|
4925
|
+
/bleu/i,
|
|
4926
|
+
/rouge/i,
|
|
4927
|
+
/f1[_\s]?score/i,
|
|
4928
|
+
/auc/i,
|
|
4929
|
+
/mse/i,
|
|
4930
|
+
/rmse/i,
|
|
4931
|
+
/mae/i
|
|
4932
|
+
];
|
|
4933
|
+
ARCHITECTURE_PATTERNS = [
|
|
4934
|
+
/transformer/i,
|
|
4935
|
+
/RWKV/i,
|
|
4936
|
+
/SSM/i,
|
|
4937
|
+
/Mamba/i,
|
|
4938
|
+
/linear\s*attention/i,
|
|
4939
|
+
/GPT/i,
|
|
4940
|
+
/BERT/i,
|
|
4941
|
+
/ResNet/i,
|
|
4942
|
+
/CNN/i,
|
|
4943
|
+
/RNN/i,
|
|
4944
|
+
/LSTM/i,
|
|
4945
|
+
/GRU/i,
|
|
4946
|
+
/ViT/i,
|
|
4947
|
+
/diffusion/i,
|
|
4948
|
+
/autoencoder/i,
|
|
4949
|
+
/GAN/i
|
|
4950
|
+
];
|
|
4951
|
+
FRAMEWORK_PATTERNS = [
|
|
4952
|
+
[/import\s+torch|from\s+torch/i, "PyTorch"],
|
|
4953
|
+
[/import\s+tensorflow|from\s+tensorflow/i, "TensorFlow"],
|
|
4954
|
+
[/import\s+jax|from\s+jax/i, "JAX"],
|
|
4955
|
+
[/from\s+transformers\s+import/i, "HuggingFace Transformers"],
|
|
4956
|
+
[/import\s+keras|from\s+keras/i, "Keras"],
|
|
4957
|
+
[/torch/i, "PyTorch"]
|
|
4958
|
+
];
|
|
4959
|
+
}
|
|
4960
|
+
});
|
|
4961
|
+
|
|
4962
|
+
// src/contracts/bootstrap-contract.ts
|
|
4963
|
+
var BOOTSTRAP_EXIT_CODES;
|
|
4964
|
+
var init_bootstrap_contract = __esm({
|
|
4965
|
+
"src/contracts/bootstrap-contract.ts"() {
|
|
4966
|
+
"use strict";
|
|
4967
|
+
BOOTSTRAP_EXIT_CODES = {
|
|
4968
|
+
SUCCESS: 0,
|
|
4969
|
+
FAIL: 1,
|
|
4970
|
+
ERROR: 3
|
|
4971
|
+
};
|
|
4972
|
+
}
|
|
4973
|
+
});
|
|
4974
|
+
|
|
4975
|
+
// src/cli/bootstrap.ts
|
|
4976
|
+
var bootstrap_exports = {};
|
|
4977
|
+
__export(bootstrap_exports, {
|
|
4978
|
+
main: () => main8
|
|
4979
|
+
});
|
|
4980
|
+
function parseArgs8(argv) {
|
|
4981
|
+
let inputPath = "";
|
|
4982
|
+
let outputPath = "";
|
|
4983
|
+
let validate = false;
|
|
4984
|
+
let format = "full";
|
|
4985
|
+
for (let i = 0; i < argv.length; i++) {
|
|
4986
|
+
const arg = argv[i];
|
|
4987
|
+
if (arg === "--input" && i + 1 < argv.length) {
|
|
4988
|
+
inputPath = argv[++i];
|
|
4989
|
+
} else if (arg === "--output" && i + 1 < argv.length) {
|
|
4990
|
+
outputPath = argv[++i];
|
|
4991
|
+
} else if (arg === "--validate") {
|
|
4992
|
+
validate = true;
|
|
4993
|
+
} else if (arg === "--format" && i + 1 < argv.length) {
|
|
4994
|
+
const val = argv[++i];
|
|
4995
|
+
if (val === "full" || val === "summary") format = val;
|
|
4996
|
+
}
|
|
4997
|
+
}
|
|
4998
|
+
if (!inputPath) throw new Error("--input <path> is required");
|
|
4999
|
+
if (!outputPath) throw new Error("--output <path> is required");
|
|
5000
|
+
return { inputPath, outputPath, validate, format };
|
|
5001
|
+
}
|
|
5002
|
+
async function writeWorldFiles2(outputDir, world) {
|
|
5003
|
+
const { writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
|
|
5004
|
+
const { join: join8 } = await import("path");
|
|
5005
|
+
await mkdir2(outputDir, { recursive: true });
|
|
5006
|
+
await writeFile5(join8(outputDir, "world.json"), JSON.stringify(world.world, null, 2));
|
|
5007
|
+
await writeFile5(join8(outputDir, "invariants.json"), JSON.stringify({ invariants: world.invariants }, null, 2));
|
|
5008
|
+
await writeFile5(join8(outputDir, "assumptions.json"), JSON.stringify(world.assumptions, null, 2));
|
|
5009
|
+
await writeFile5(join8(outputDir, "state-schema.json"), JSON.stringify(world.stateSchema, null, 2));
|
|
5010
|
+
const rulesDir = join8(outputDir, "rules");
|
|
5011
|
+
await mkdir2(rulesDir, { recursive: true });
|
|
5012
|
+
const sortedRules = [...world.rules].sort((a, b) => a.order - b.order);
|
|
5013
|
+
for (let i = 0; i < sortedRules.length; i++) {
|
|
5014
|
+
const ruleNum = String(i + 1).padStart(3, "0");
|
|
5015
|
+
await writeFile5(join8(rulesDir, `rule-${ruleNum}.json`), JSON.stringify(sortedRules[i], null, 2));
|
|
5016
|
+
}
|
|
5017
|
+
await writeFile5(join8(outputDir, "gates.json"), JSON.stringify(world.gates, null, 2));
|
|
5018
|
+
await writeFile5(join8(outputDir, "outcomes.json"), JSON.stringify(world.outcomes, null, 2));
|
|
5019
|
+
await writeFile5(join8(outputDir, "metadata.json"), JSON.stringify(world.metadata, null, 2));
|
|
5020
|
+
}
|
|
5021
|
+
async function main8(argv = process.argv.slice(2)) {
|
|
5022
|
+
const startTime = performance.now();
|
|
5023
|
+
try {
|
|
5024
|
+
const args = parseArgs8(argv);
|
|
5025
|
+
const { readFile: readFile3 } = await import("fs/promises");
|
|
5026
|
+
let markdown;
|
|
5027
|
+
try {
|
|
5028
|
+
markdown = await readFile3(args.inputPath, "utf-8");
|
|
5029
|
+
} catch {
|
|
5030
|
+
const errorResult = { error: `Cannot read file: ${args.inputPath}` };
|
|
5031
|
+
process.stderr.write(JSON.stringify(errorResult, null, 2) + "\n");
|
|
5032
|
+
process.exit(BOOTSTRAP_EXIT_CODES.ERROR);
|
|
5033
|
+
return;
|
|
5034
|
+
}
|
|
5035
|
+
const parseResult = parseWorldMarkdown(markdown);
|
|
5036
|
+
const parseErrors = parseResult.issues.filter((i) => i.severity === "error");
|
|
5037
|
+
if (parseErrors.length > 0 || !parseResult.world) {
|
|
5038
|
+
const result2 = {
|
|
5039
|
+
success: false,
|
|
5040
|
+
sourcePath: args.inputPath,
|
|
5041
|
+
issues: parseResult.issues,
|
|
5042
|
+
parsedSections: [],
|
|
5043
|
+
durationMs: performance.now() - startTime
|
|
5044
|
+
};
|
|
5045
|
+
process.stdout.write(JSON.stringify(result2, null, 2) + "\n");
|
|
5046
|
+
process.exit(BOOTSTRAP_EXIT_CODES.FAIL);
|
|
5047
|
+
return;
|
|
5048
|
+
}
|
|
5049
|
+
const emitResult = emitWorldDefinition(parseResult.world);
|
|
5050
|
+
const allIssues = [...parseResult.issues, ...emitResult.issues];
|
|
5051
|
+
await writeWorldFiles2(args.outputPath, emitResult.world);
|
|
5052
|
+
let validateReport;
|
|
5053
|
+
if (args.validate) {
|
|
5054
|
+
const { validateWorld: validateWorld2 } = await Promise.resolve().then(() => (init_validate_engine(), validate_engine_exports));
|
|
5055
|
+
validateReport = validateWorld2(emitResult.world);
|
|
5056
|
+
}
|
|
5057
|
+
const result = {
|
|
5058
|
+
success: true,
|
|
5059
|
+
sourcePath: args.inputPath,
|
|
5060
|
+
issues: allIssues,
|
|
5061
|
+
parsedSections: Object.keys(parseResult.world).filter((k) => {
|
|
5062
|
+
const val = parseResult.world[k];
|
|
5063
|
+
if (Array.isArray(val)) return val.length > 0;
|
|
5064
|
+
if (typeof val === "string") return val.length > 0;
|
|
5065
|
+
return !!val;
|
|
5066
|
+
}),
|
|
5067
|
+
durationMs: performance.now() - startTime
|
|
5068
|
+
};
|
|
5069
|
+
if (validateReport) {
|
|
5070
|
+
result.validateReport = args.format === "summary" ? { summary: validateReport.summary } : validateReport;
|
|
5071
|
+
}
|
|
5072
|
+
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
|
|
5073
|
+
const hasErrors = allIssues.some((i) => i.severity === "error");
|
|
5074
|
+
process.exit(hasErrors ? BOOTSTRAP_EXIT_CODES.FAIL : BOOTSTRAP_EXIT_CODES.SUCCESS);
|
|
4315
5075
|
} catch (e) {
|
|
4316
5076
|
const errorResult = { error: "Bootstrap failed", detail: String(e) };
|
|
4317
5077
|
process.stderr.write(JSON.stringify(errorResult, null, 2) + "\n");
|
|
@@ -4344,9 +5104,9 @@ var init_validate_contract = __esm({
|
|
|
4344
5104
|
// src/cli/validate.ts
|
|
4345
5105
|
var validate_exports = {};
|
|
4346
5106
|
__export(validate_exports, {
|
|
4347
|
-
main: () =>
|
|
5107
|
+
main: () => main9
|
|
4348
5108
|
});
|
|
4349
|
-
function
|
|
5109
|
+
function parseArgs9(argv) {
|
|
4350
5110
|
let worldPath = "";
|
|
4351
5111
|
let format = "full";
|
|
4352
5112
|
let mode = "standard";
|
|
@@ -4391,9 +5151,9 @@ function formatOutput(report, format) {
|
|
|
4391
5151
|
}
|
|
4392
5152
|
return JSON.stringify(report, null, 2);
|
|
4393
5153
|
}
|
|
4394
|
-
async function
|
|
5154
|
+
async function main9(argv = process.argv.slice(2)) {
|
|
4395
5155
|
try {
|
|
4396
|
-
const args =
|
|
5156
|
+
const args = parseArgs9(argv);
|
|
4397
5157
|
const world = await loadWorld(args.worldPath);
|
|
4398
5158
|
const report = validateWorld(world, args.mode);
|
|
4399
5159
|
process.stdout.write(formatOutput(report, args.format) + "\n");
|
|
@@ -4421,17 +5181,27 @@ var init_validate = __esm({
|
|
|
4421
5181
|
}
|
|
4422
5182
|
});
|
|
4423
5183
|
|
|
4424
|
-
// src/engine/
|
|
4425
|
-
function
|
|
4426
|
-
|
|
4427
|
-
|
|
4428
|
-
|
|
4429
|
-
|
|
5184
|
+
// src/engine/text-utils.ts
|
|
5185
|
+
function normalizeEventText(event) {
|
|
5186
|
+
return [
|
|
5187
|
+
event.intent,
|
|
5188
|
+
event.tool ?? "",
|
|
5189
|
+
event.scope ?? ""
|
|
4430
5190
|
].join(" ").toLowerCase();
|
|
4431
|
-
|
|
5191
|
+
}
|
|
5192
|
+
function extractKeywords(text, minLength = 3) {
|
|
5193
|
+
return text.toLowerCase().split(/\s+/).filter((w) => w.length > minLength);
|
|
5194
|
+
}
|
|
5195
|
+
function matchesAllKeywords(eventText, ruleText) {
|
|
5196
|
+
const keywords = extractKeywords(ruleText);
|
|
5197
|
+
if (keywords.length === 0) return false;
|
|
5198
|
+
return keywords.every((kw) => eventText.includes(kw));
|
|
5199
|
+
}
|
|
5200
|
+
function matchesKeywordThreshold(eventText, ruleText, threshold = 0.5) {
|
|
5201
|
+
const keywords = extractKeywords(ruleText);
|
|
4432
5202
|
if (keywords.length === 0) return false;
|
|
4433
5203
|
const matched = keywords.filter((kw) => eventText.includes(kw));
|
|
4434
|
-
return matched.length >= Math.ceil(keywords.length *
|
|
5204
|
+
return matched.length >= Math.ceil(keywords.length * threshold);
|
|
4435
5205
|
}
|
|
4436
5206
|
function tokenSimilarity(a, b) {
|
|
4437
5207
|
const tokensA = new Set(a.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
@@ -4444,6 +5214,24 @@ function tokenSimilarity(a, b) {
|
|
|
4444
5214
|
const union = (/* @__PURE__ */ new Set([...tokensA, ...tokensB])).size;
|
|
4445
5215
|
return union > 0 ? intersection / union : 0;
|
|
4446
5216
|
}
|
|
5217
|
+
var init_text_utils = __esm({
|
|
5218
|
+
"src/engine/text-utils.ts"() {
|
|
5219
|
+
"use strict";
|
|
5220
|
+
}
|
|
5221
|
+
});
|
|
5222
|
+
|
|
5223
|
+
// src/engine/plan-engine.ts
|
|
5224
|
+
function keywordMatch(eventText, step) {
|
|
5225
|
+
const stepText = [
|
|
5226
|
+
step.label,
|
|
5227
|
+
step.description ?? "",
|
|
5228
|
+
...step.tags ?? []
|
|
5229
|
+
].join(" ");
|
|
5230
|
+
return matchesKeywordThreshold(eventText, stepText, 0.5);
|
|
5231
|
+
}
|
|
5232
|
+
function tokenSimilarity2(a, b) {
|
|
5233
|
+
return tokenSimilarity(a, b);
|
|
5234
|
+
}
|
|
4447
5235
|
function findMatchingStep(eventText, event, steps) {
|
|
4448
5236
|
const pendingOrActive = steps.filter((s) => s.status === "pending" || s.status === "active");
|
|
4449
5237
|
if (pendingOrActive.length === 0) {
|
|
@@ -4462,7 +5250,7 @@ function findMatchingStep(eventText, event, steps) {
|
|
|
4462
5250
|
let bestScore = 0;
|
|
4463
5251
|
for (const step of pendingOrActive) {
|
|
4464
5252
|
const stepText = [step.label, step.description ?? "", ...step.tags ?? []].join(" ");
|
|
4465
|
-
const score =
|
|
5253
|
+
const score = tokenSimilarity2(intentText, stepText);
|
|
4466
5254
|
if (score > bestScore) {
|
|
4467
5255
|
bestScore = score;
|
|
4468
5256
|
bestStep = step;
|
|
@@ -4503,7 +5291,7 @@ function checkConstraints(event, eventText, constraints) {
|
|
|
4503
5291
|
continue;
|
|
4504
5292
|
}
|
|
4505
5293
|
if (constraint.type === "scope" && constraint.trigger) {
|
|
4506
|
-
const keywords = constraint.trigger
|
|
5294
|
+
const keywords = extractKeywords(constraint.trigger);
|
|
4507
5295
|
const violated = keywords.length > 0 && keywords.every((kw) => eventText.includes(kw));
|
|
4508
5296
|
checks.push({
|
|
4509
5297
|
constraintId: constraint.id,
|
|
@@ -4584,11 +5372,7 @@ function evaluatePlan(event, plan) {
|
|
|
4584
5372
|
progress
|
|
4585
5373
|
};
|
|
4586
5374
|
}
|
|
4587
|
-
const eventText =
|
|
4588
|
-
event.intent,
|
|
4589
|
-
event.tool ?? "",
|
|
4590
|
-
event.scope ?? ""
|
|
4591
|
-
].join(" ").toLowerCase();
|
|
5375
|
+
const eventText = normalizeEventText(event);
|
|
4592
5376
|
const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
|
|
4593
5377
|
if (!matched) {
|
|
4594
5378
|
return {
|
|
@@ -4629,7 +5413,7 @@ function evaluatePlan(event, plan) {
|
|
|
4629
5413
|
};
|
|
4630
5414
|
}
|
|
4631
5415
|
function buildPlanCheck(event, plan, verdict) {
|
|
4632
|
-
const eventText =
|
|
5416
|
+
const eventText = normalizeEventText(event);
|
|
4633
5417
|
const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
|
|
4634
5418
|
const { checks: constraintChecks } = checkConstraints(event, eventText, plan.constraints);
|
|
4635
5419
|
const progress = getPlanProgress(plan);
|
|
@@ -4649,6 +5433,7 @@ function buildPlanCheck(event, plan, verdict) {
|
|
|
4649
5433
|
var init_plan_engine = __esm({
|
|
4650
5434
|
"src/engine/plan-engine.ts"() {
|
|
4651
5435
|
"use strict";
|
|
5436
|
+
init_text_utils();
|
|
4652
5437
|
}
|
|
4653
5438
|
});
|
|
4654
5439
|
|
|
@@ -4682,7 +5467,7 @@ function evaluateGuard(event, world, options = {}) {
|
|
|
4682
5467
|
const startTime = performance.now();
|
|
4683
5468
|
const level = options.level ?? "standard";
|
|
4684
5469
|
const includeTrace = options.trace ?? false;
|
|
4685
|
-
const eventText = (event
|
|
5470
|
+
const eventText = normalizeEventText(event);
|
|
4686
5471
|
const invariantChecks = [];
|
|
4687
5472
|
const safetyChecks = [];
|
|
4688
5473
|
let planCheckResult;
|
|
@@ -4695,6 +5480,43 @@ function evaluateGuard(event, world, options = {}) {
|
|
|
4695
5480
|
const guardsMatched = [];
|
|
4696
5481
|
const rulesMatched = [];
|
|
4697
5482
|
checkInvariantCoverage(world, invariantChecks);
|
|
5483
|
+
if (event.roleId && options.agentStates) {
|
|
5484
|
+
const agentState = options.agentStates.get(event.roleId);
|
|
5485
|
+
if (agentState && agentState.cooldownRemaining > 0) {
|
|
5486
|
+
decidingLayer = "safety";
|
|
5487
|
+
decidingId = `penalize-cooldown-${event.roleId}`;
|
|
5488
|
+
const verdict = buildVerdict(
|
|
5489
|
+
"PENALIZE",
|
|
5490
|
+
`Agent "${event.roleId}" is frozen for ${agentState.cooldownRemaining} more round(s) due to prior penalty.`,
|
|
5491
|
+
`penalize-cooldown-${event.roleId}`,
|
|
5492
|
+
void 0,
|
|
5493
|
+
world,
|
|
5494
|
+
level,
|
|
5495
|
+
invariantChecks,
|
|
5496
|
+
guardsMatched,
|
|
5497
|
+
rulesMatched,
|
|
5498
|
+
includeTrace ? buildTrace(
|
|
5499
|
+
invariantChecks,
|
|
5500
|
+
safetyChecks,
|
|
5501
|
+
planCheckResult,
|
|
5502
|
+
roleChecks,
|
|
5503
|
+
guardChecks,
|
|
5504
|
+
kernelRuleChecks,
|
|
5505
|
+
levelChecks,
|
|
5506
|
+
decidingLayer,
|
|
5507
|
+
decidingId,
|
|
5508
|
+
startTime
|
|
5509
|
+
) : void 0
|
|
5510
|
+
);
|
|
5511
|
+
verdict.intentRecord = {
|
|
5512
|
+
originalIntent: event.intent,
|
|
5513
|
+
finalAction: "blocked (agent frozen)",
|
|
5514
|
+
enforcement: "PENALIZE",
|
|
5515
|
+
consequence: { type: "freeze", rounds: agentState.cooldownRemaining, description: "Agent still in cooldown from prior penalty" }
|
|
5516
|
+
};
|
|
5517
|
+
return verdict;
|
|
5518
|
+
}
|
|
5519
|
+
}
|
|
4698
5520
|
if (options.sessionAllowlist) {
|
|
4699
5521
|
const key = eventToAllowlistKey(event);
|
|
4700
5522
|
if (options.sessionAllowlist.has(key)) {
|
|
@@ -4822,7 +5644,16 @@ function evaluateGuard(event, world, options = {}) {
|
|
|
4822
5644
|
if (guardVerdict.status !== "ALLOW") {
|
|
4823
5645
|
decidingLayer = "guard";
|
|
4824
5646
|
decidingId = guardVerdict.ruleId;
|
|
4825
|
-
|
|
5647
|
+
const intentRecord = {
|
|
5648
|
+
originalIntent: event.intent,
|
|
5649
|
+
finalAction: guardVerdict.status === "MODIFY" ? guardVerdict.modifiedTo ?? "modified" : guardVerdict.status === "PENALIZE" ? "blocked + penalized" : guardVerdict.status === "REWARD" ? event.intent : guardVerdict.status === "NEUTRAL" ? event.intent : guardVerdict.status === "BLOCK" ? "blocked" : "paused",
|
|
5650
|
+
ruleApplied: guardVerdict.ruleId,
|
|
5651
|
+
enforcement: guardVerdict.status,
|
|
5652
|
+
modifiedTo: guardVerdict.modifiedTo,
|
|
5653
|
+
consequence: guardVerdict.consequence,
|
|
5654
|
+
reward: guardVerdict.reward
|
|
5655
|
+
};
|
|
5656
|
+
const verdict = buildVerdict(
|
|
4826
5657
|
guardVerdict.status,
|
|
4827
5658
|
guardVerdict.reason,
|
|
4828
5659
|
guardVerdict.ruleId,
|
|
@@ -4845,6 +5676,10 @@ function evaluateGuard(event, world, options = {}) {
|
|
|
4845
5676
|
startTime
|
|
4846
5677
|
) : void 0
|
|
4847
5678
|
);
|
|
5679
|
+
verdict.intentRecord = intentRecord;
|
|
5680
|
+
if (guardVerdict.consequence) verdict.consequence = guardVerdict.consequence;
|
|
5681
|
+
if (guardVerdict.reward) verdict.reward = guardVerdict.reward;
|
|
5682
|
+
return verdict;
|
|
4848
5683
|
}
|
|
4849
5684
|
}
|
|
4850
5685
|
const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
|
|
@@ -5139,6 +5974,21 @@ function checkGuards(event, eventText, world, checks, guardsMatched) {
|
|
|
5139
5974
|
if (actionMode === "pause") {
|
|
5140
5975
|
return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
|
|
5141
5976
|
}
|
|
5977
|
+
if (actionMode === "penalize") {
|
|
5978
|
+
const consequence = guard.consequence ? { ...guard.consequence } : { type: "freeze", rounds: 1, description: `Penalized for violating: ${guard.label}` };
|
|
5979
|
+
return { status: "PENALIZE", reason, ruleId: `guard-${guard.id}`, consequence };
|
|
5980
|
+
}
|
|
5981
|
+
if (actionMode === "reward") {
|
|
5982
|
+
const reward = guard.reward ? { ...guard.reward } : { type: "boost_influence", magnitude: 0.1, description: `Rewarded for: ${guard.label}` };
|
|
5983
|
+
return { status: "REWARD", reason, ruleId: `guard-${guard.id}`, reward };
|
|
5984
|
+
}
|
|
5985
|
+
if (actionMode === "modify") {
|
|
5986
|
+
const modifiedTo = guard.modify_to ?? guard.redirect ?? "hold";
|
|
5987
|
+
return { status: "MODIFY", reason: `${reason} \u2192 Modified to: ${modifiedTo}`, ruleId: `guard-${guard.id}`, modifiedTo };
|
|
5988
|
+
}
|
|
5989
|
+
if (actionMode === "neutral") {
|
|
5990
|
+
return { status: "NEUTRAL", reason, ruleId: `guard-${guard.id}` };
|
|
5991
|
+
}
|
|
5142
5992
|
if (actionMode === "warn" && !warnResult) {
|
|
5143
5993
|
warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
|
|
5144
5994
|
}
|
|
@@ -5248,9 +6098,7 @@ function checkLevelConstraints(event, level, checks) {
|
|
|
5248
6098
|
return null;
|
|
5249
6099
|
}
|
|
5250
6100
|
function matchesKeywords(eventText, ruleText) {
|
|
5251
|
-
|
|
5252
|
-
if (keywords.length === 0) return false;
|
|
5253
|
-
return keywords.every((kw) => eventText.includes(kw));
|
|
6101
|
+
return matchesAllKeywords(eventText, ruleText);
|
|
5254
6102
|
}
|
|
5255
6103
|
function eventToAllowlistKey(event) {
|
|
5256
6104
|
return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
|
|
@@ -5316,6 +6164,7 @@ var init_guard_engine = __esm({
|
|
|
5316
6164
|
"src/engine/guard-engine.ts"() {
|
|
5317
6165
|
"use strict";
|
|
5318
6166
|
init_plan_engine();
|
|
6167
|
+
init_text_utils();
|
|
5319
6168
|
PROMPT_INJECTION_PATTERNS = [
|
|
5320
6169
|
// Instruction override
|
|
5321
6170
|
{ pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
|
|
@@ -5384,31 +6233,31 @@ var init_guard_engine = __esm({
|
|
|
5384
6233
|
|
|
5385
6234
|
// src/loader/world-resolver.ts
|
|
5386
6235
|
function listWorlds(cwd = process.cwd()) {
|
|
5387
|
-
const worldsDir = (0,
|
|
5388
|
-
if (!(0,
|
|
6236
|
+
const worldsDir = (0, import_path5.join)(cwd, WORLDS_DIR);
|
|
6237
|
+
if (!(0, import_fs3.existsSync)(worldsDir)) return [];
|
|
5389
6238
|
const activeName = getActiveWorldName(cwd);
|
|
5390
|
-
const entries = (0,
|
|
6239
|
+
const entries = (0, import_fs3.readdirSync)(worldsDir);
|
|
5391
6240
|
return entries.filter((name) => {
|
|
5392
|
-
const worldJson = (0,
|
|
5393
|
-
return (0,
|
|
6241
|
+
const worldJson = (0, import_path5.join)(worldsDir, name, "world.json");
|
|
6242
|
+
return (0, import_fs3.existsSync)(worldJson);
|
|
5394
6243
|
}).map((name) => ({
|
|
5395
6244
|
name,
|
|
5396
|
-
path: (0,
|
|
6245
|
+
path: (0, import_path5.join)(worldsDir, name),
|
|
5397
6246
|
active: name === activeName
|
|
5398
6247
|
})).sort((a, b) => a.name.localeCompare(b.name));
|
|
5399
6248
|
}
|
|
5400
6249
|
function getActiveWorldName(cwd = process.cwd()) {
|
|
5401
|
-
const filePath = (0,
|
|
6250
|
+
const filePath = (0, import_path5.join)(cwd, ACTIVE_WORLD_FILE);
|
|
5402
6251
|
try {
|
|
5403
|
-
return (0,
|
|
6252
|
+
return (0, import_fs3.readFileSync)(filePath, "utf-8").trim() || void 0;
|
|
5404
6253
|
} catch {
|
|
5405
6254
|
return void 0;
|
|
5406
6255
|
}
|
|
5407
6256
|
}
|
|
5408
6257
|
function setActiveWorld(name, cwd = process.cwd()) {
|
|
5409
|
-
const worldsDir = (0,
|
|
5410
|
-
const worldPath = (0,
|
|
5411
|
-
if (!(0,
|
|
6258
|
+
const worldsDir = (0, import_path5.join)(cwd, WORLDS_DIR);
|
|
6259
|
+
const worldPath = (0, import_path5.join)(worldsDir, name, "world.json");
|
|
6260
|
+
if (!(0, import_fs3.existsSync)(worldPath)) {
|
|
5412
6261
|
const available = listWorlds(cwd);
|
|
5413
6262
|
const names = available.map((w) => w.name).join(", ");
|
|
5414
6263
|
throw new Error(
|
|
@@ -5416,11 +6265,11 @@ function setActiveWorld(name, cwd = process.cwd()) {
|
|
|
5416
6265
|
` + (names ? `Available: ${names}` : "No worlds found. Run `neuroverse build` first.")
|
|
5417
6266
|
);
|
|
5418
6267
|
}
|
|
5419
|
-
const dir = (0,
|
|
5420
|
-
if (!(0,
|
|
5421
|
-
(0,
|
|
6268
|
+
const dir = (0, import_path5.join)(cwd, ".neuroverse");
|
|
6269
|
+
if (!(0, import_fs3.existsSync)(dir)) (0, import_fs3.mkdirSync)(dir, { recursive: true });
|
|
6270
|
+
(0, import_fs3.writeFileSync)((0, import_path5.join)(cwd, ACTIVE_WORLD_FILE), name + "\n", "utf-8");
|
|
5422
6271
|
}
|
|
5423
|
-
function
|
|
6272
|
+
function resolveWorldPath2(explicit, cwd = process.cwd()) {
|
|
5424
6273
|
if (explicit) {
|
|
5425
6274
|
return resolveNameOrPath(explicit, cwd);
|
|
5426
6275
|
}
|
|
@@ -5434,7 +6283,7 @@ function resolveWorldPath4(explicit, cwd = process.cwd()) {
|
|
|
5434
6283
|
}
|
|
5435
6284
|
const worlds = listWorlds(cwd);
|
|
5436
6285
|
if (worlds.length === 1) {
|
|
5437
|
-
return (0,
|
|
6286
|
+
return (0, import_path5.resolve)(worlds[0].path);
|
|
5438
6287
|
}
|
|
5439
6288
|
return void 0;
|
|
5440
6289
|
}
|
|
@@ -5457,21 +6306,21 @@ function describeActiveWorld(explicit, cwd = process.cwd()) {
|
|
|
5457
6306
|
return void 0;
|
|
5458
6307
|
}
|
|
5459
6308
|
function resolveNameOrPath(ref, cwd) {
|
|
5460
|
-
if (ref.includes("/") || ref.includes("\\") || ref.startsWith(".") || (0,
|
|
5461
|
-
return (0,
|
|
6309
|
+
if (ref.includes("/") || ref.includes("\\") || ref.startsWith(".") || (0, import_path5.isAbsolute)(ref)) {
|
|
6310
|
+
return (0, import_path5.resolve)(cwd, ref);
|
|
5462
6311
|
}
|
|
5463
|
-
const namedPath = (0,
|
|
5464
|
-
if ((0,
|
|
5465
|
-
return (0,
|
|
6312
|
+
const namedPath = (0, import_path5.join)(cwd, WORLDS_DIR, ref);
|
|
6313
|
+
if ((0, import_fs3.existsSync)((0, import_path5.join)(namedPath, "world.json"))) {
|
|
6314
|
+
return (0, import_path5.resolve)(namedPath);
|
|
5466
6315
|
}
|
|
5467
|
-
return (0,
|
|
6316
|
+
return (0, import_path5.resolve)(cwd, ref);
|
|
5468
6317
|
}
|
|
5469
|
-
var
|
|
6318
|
+
var import_fs3, import_path5, WORLDS_DIR, ACTIVE_WORLD_FILE;
|
|
5470
6319
|
var init_world_resolver = __esm({
|
|
5471
6320
|
"src/loader/world-resolver.ts"() {
|
|
5472
6321
|
"use strict";
|
|
5473
|
-
|
|
5474
|
-
|
|
6322
|
+
import_fs3 = require("fs");
|
|
6323
|
+
import_path5 = require("path");
|
|
5475
6324
|
WORLDS_DIR = ".neuroverse/worlds";
|
|
5476
6325
|
ACTIVE_WORLD_FILE = ".neuroverse/active_world";
|
|
5477
6326
|
}
|
|
@@ -5486,7 +6335,11 @@ var init_guard_contract = __esm({
|
|
|
5486
6335
|
ALLOW: 0,
|
|
5487
6336
|
BLOCK: 1,
|
|
5488
6337
|
PAUSE: 2,
|
|
5489
|
-
ERROR: 3
|
|
6338
|
+
ERROR: 3,
|
|
6339
|
+
MODIFY: 4,
|
|
6340
|
+
PENALIZE: 5,
|
|
6341
|
+
REWARD: 6,
|
|
6342
|
+
NEUTRAL: 7
|
|
5490
6343
|
};
|
|
5491
6344
|
}
|
|
5492
6345
|
});
|
|
@@ -5494,9 +6347,9 @@ var init_guard_contract = __esm({
|
|
|
5494
6347
|
// src/cli/guard.ts
|
|
5495
6348
|
var guard_exports = {};
|
|
5496
6349
|
__export(guard_exports, {
|
|
5497
|
-
main: () =>
|
|
6350
|
+
main: () => main10
|
|
5498
6351
|
});
|
|
5499
|
-
function
|
|
6352
|
+
function parseArgs10(argv) {
|
|
5500
6353
|
let worldPath = "";
|
|
5501
6354
|
let trace = false;
|
|
5502
6355
|
let level;
|
|
@@ -5517,17 +6370,10 @@ function parseArgs8(argv) {
|
|
|
5517
6370
|
}
|
|
5518
6371
|
return { worldPath, trace, level };
|
|
5519
6372
|
}
|
|
5520
|
-
async function
|
|
5521
|
-
const chunks = [];
|
|
5522
|
-
for await (const chunk of process.stdin) {
|
|
5523
|
-
chunks.push(chunk);
|
|
5524
|
-
}
|
|
5525
|
-
return Buffer.concat(chunks).toString("utf-8");
|
|
5526
|
-
}
|
|
5527
|
-
async function main8(argv = process.argv.slice(2)) {
|
|
6373
|
+
async function main10(argv = process.argv.slice(2)) {
|
|
5528
6374
|
try {
|
|
5529
|
-
const args =
|
|
5530
|
-
const worldPath =
|
|
6375
|
+
const args = parseArgs10(argv);
|
|
6376
|
+
const worldPath = resolveWorldPath2(args.worldPath);
|
|
5531
6377
|
if (!worldPath) {
|
|
5532
6378
|
throw new Error(
|
|
5533
6379
|
"No world specified. Use --world <path>, set NEUROVERSE_WORLD, or run `neuroverse world use <name>`"
|
|
@@ -5579,13 +6425,14 @@ var init_guard = __esm({
|
|
|
5579
6425
|
init_world_loader();
|
|
5580
6426
|
init_world_resolver();
|
|
5581
6427
|
init_guard_contract();
|
|
6428
|
+
init_cli_utils();
|
|
5582
6429
|
}
|
|
5583
6430
|
});
|
|
5584
6431
|
|
|
5585
6432
|
// src/cli/test.ts
|
|
5586
6433
|
var test_exports = {};
|
|
5587
6434
|
__export(test_exports, {
|
|
5588
|
-
main: () =>
|
|
6435
|
+
main: () => main11
|
|
5589
6436
|
});
|
|
5590
6437
|
function generateFuzzEvent() {
|
|
5591
6438
|
const verb = FUZZ_VERBS[Math.floor(Math.random() * FUZZ_VERBS.length)];
|
|
@@ -5603,7 +6450,7 @@ function generateFuzzEvent() {
|
|
|
5603
6450
|
}
|
|
5604
6451
|
};
|
|
5605
6452
|
}
|
|
5606
|
-
function
|
|
6453
|
+
function parseArgs11(argv) {
|
|
5607
6454
|
let worldPath;
|
|
5608
6455
|
let fuzz = false;
|
|
5609
6456
|
let count = 20;
|
|
@@ -5619,8 +6466,8 @@ function parseArgs9(argv) {
|
|
|
5619
6466
|
}
|
|
5620
6467
|
return { worldPath, fuzz, count, json, level };
|
|
5621
6468
|
}
|
|
5622
|
-
async function
|
|
5623
|
-
const args =
|
|
6469
|
+
async function main11(argv) {
|
|
6470
|
+
const args = parseArgs11(argv);
|
|
5624
6471
|
if (!args.worldPath) {
|
|
5625
6472
|
process.stderr.write("Usage: neuroverse test --world <dir> [--fuzz] [--count N] [--json]\n");
|
|
5626
6473
|
process.exit(1);
|
|
@@ -5803,9 +6650,9 @@ var init_test = __esm({
|
|
|
5803
6650
|
// src/cli/redteam.ts
|
|
5804
6651
|
var redteam_exports = {};
|
|
5805
6652
|
__export(redteam_exports, {
|
|
5806
|
-
main: () =>
|
|
6653
|
+
main: () => main12
|
|
5807
6654
|
});
|
|
5808
|
-
function
|
|
6655
|
+
function parseArgs12(argv) {
|
|
5809
6656
|
let worldPath;
|
|
5810
6657
|
let level = "standard";
|
|
5811
6658
|
let json = false;
|
|
@@ -5817,8 +6664,8 @@ function parseArgs10(argv) {
|
|
|
5817
6664
|
}
|
|
5818
6665
|
return { worldPath, level, json };
|
|
5819
6666
|
}
|
|
5820
|
-
async function
|
|
5821
|
-
const args =
|
|
6667
|
+
async function main12(argv) {
|
|
6668
|
+
const args = parseArgs12(argv);
|
|
5822
6669
|
if (!args.worldPath) {
|
|
5823
6670
|
process.stderr.write("Usage: neuroverse redteam --world <dir> [--level basic|standard|strict] [--json]\n");
|
|
5824
6671
|
process.exit(1);
|
|
@@ -6158,6 +7005,552 @@ var init_redteam = __esm({
|
|
|
6158
7005
|
}
|
|
6159
7006
|
});
|
|
6160
7007
|
|
|
7008
|
+
// src/adapters/autoresearch.ts
|
|
7009
|
+
var autoresearch_exports = {};
|
|
7010
|
+
__export(autoresearch_exports, {
|
|
7011
|
+
AutoresearchGovernor: () => AutoresearchGovernor
|
|
7012
|
+
});
|
|
7013
|
+
var AutoresearchGovernor;
|
|
7014
|
+
var init_autoresearch = __esm({
|
|
7015
|
+
"src/adapters/autoresearch.ts"() {
|
|
7016
|
+
"use strict";
|
|
7017
|
+
AutoresearchGovernor = class {
|
|
7018
|
+
config;
|
|
7019
|
+
state;
|
|
7020
|
+
constructor(config) {
|
|
7021
|
+
this.config = config;
|
|
7022
|
+
this.state = {
|
|
7023
|
+
experiments_run: 0,
|
|
7024
|
+
best_result: null,
|
|
7025
|
+
architectures_tested: [],
|
|
7026
|
+
experiment_log: [],
|
|
7027
|
+
total_compute_minutes: 0,
|
|
7028
|
+
keep_count: 0
|
|
7029
|
+
};
|
|
7030
|
+
}
|
|
7031
|
+
/**
|
|
7032
|
+
* Convert an experiment proposal into a GuardEvent for governance evaluation.
|
|
7033
|
+
*/
|
|
7034
|
+
proposalToGuardEvent(proposal) {
|
|
7035
|
+
return {
|
|
7036
|
+
intent: `run experiment: ${proposal.description}`,
|
|
7037
|
+
tool: "experiment_runner",
|
|
7038
|
+
scope: "experiment",
|
|
7039
|
+
roleId: "experiment_runner",
|
|
7040
|
+
direction: "output",
|
|
7041
|
+
actionCategory: "shell",
|
|
7042
|
+
args: {
|
|
7043
|
+
experiment_id: String(proposal.experiment_id),
|
|
7044
|
+
architecture: proposal.architecture,
|
|
7045
|
+
estimated_minutes: String(proposal.estimated_minutes || 5)
|
|
7046
|
+
}
|
|
7047
|
+
};
|
|
7048
|
+
}
|
|
7049
|
+
/**
|
|
7050
|
+
* Evaluate an experiment proposal against governance rules.
|
|
7051
|
+
* Returns a simplified verdict without requiring the full guard engine.
|
|
7052
|
+
*/
|
|
7053
|
+
evaluateProposal(proposal) {
|
|
7054
|
+
const warnings = [];
|
|
7055
|
+
const estimatedMinutes = proposal.estimated_minutes || 5;
|
|
7056
|
+
if (this.state.total_compute_minutes + estimatedMinutes > this.config.computeBudgetMinutes) {
|
|
7057
|
+
return {
|
|
7058
|
+
allowed: false,
|
|
7059
|
+
reason: `Compute budget exhausted: ${this.state.total_compute_minutes}/${this.config.computeBudgetMinutes} minutes used`,
|
|
7060
|
+
warnings
|
|
7061
|
+
};
|
|
7062
|
+
}
|
|
7063
|
+
if (this.config.constraints) {
|
|
7064
|
+
for (const constraint of this.config.constraints) {
|
|
7065
|
+
const lower = constraint.toLowerCase();
|
|
7066
|
+
const archLower = proposal.architecture.toLowerCase();
|
|
7067
|
+
const descLower = proposal.description.toLowerCase();
|
|
7068
|
+
if (lower.startsWith("no ")) {
|
|
7069
|
+
const forbidden = lower.slice(3).trim();
|
|
7070
|
+
if (archLower.includes(forbidden) || descLower.includes(forbidden)) {
|
|
7071
|
+
return {
|
|
7072
|
+
allowed: false,
|
|
7073
|
+
reason: `Architecture constraint violated: ${constraint}`,
|
|
7074
|
+
warnings
|
|
7075
|
+
};
|
|
7076
|
+
}
|
|
7077
|
+
}
|
|
7078
|
+
}
|
|
7079
|
+
}
|
|
7080
|
+
const failureCount = this.state.experiment_log.filter((e) => !e.success).length;
|
|
7081
|
+
if (failureCount > 5) {
|
|
7082
|
+
warnings.push(`High failure rate: ${failureCount} failed experiments. Consider investigating root cause.`);
|
|
7083
|
+
}
|
|
7084
|
+
const recentArchitectures = this.state.experiment_log.slice(-5).map((e) => e.architecture);
|
|
7085
|
+
const uniqueRecent = new Set(recentArchitectures).size;
|
|
7086
|
+
if (recentArchitectures.length >= 5 && uniqueRecent === 1) {
|
|
7087
|
+
warnings.push("Research may be stuck: last 5 experiments used the same architecture.");
|
|
7088
|
+
}
|
|
7089
|
+
return { allowed: true, reason: "Experiment approved", warnings };
|
|
7090
|
+
}
|
|
7091
|
+
/**
|
|
7092
|
+
* Record an experiment result and update research state.
|
|
7093
|
+
*/
|
|
7094
|
+
recordResult(result) {
|
|
7095
|
+
this.state.experiments_run++;
|
|
7096
|
+
this.state.total_compute_minutes += result.wall_clock_minutes;
|
|
7097
|
+
this.state.experiment_log.push(result);
|
|
7098
|
+
if (!this.state.architectures_tested.includes(result.architecture)) {
|
|
7099
|
+
this.state.architectures_tested.push(result.architecture);
|
|
7100
|
+
}
|
|
7101
|
+
if (!result.success) {
|
|
7102
|
+
return { kept: false, improvement: null, state: { ...this.state } };
|
|
7103
|
+
}
|
|
7104
|
+
let kept = false;
|
|
7105
|
+
let improvement = null;
|
|
7106
|
+
if (this.state.best_result === null) {
|
|
7107
|
+
kept = true;
|
|
7108
|
+
this.state.best_result = result;
|
|
7109
|
+
this.state.keep_count++;
|
|
7110
|
+
} else {
|
|
7111
|
+
const prev = this.state.best_result.metric_value;
|
|
7112
|
+
const curr = result.metric_value;
|
|
7113
|
+
if (this.config.optimize === "minimize") {
|
|
7114
|
+
kept = curr < prev;
|
|
7115
|
+
improvement = kept ? prev - curr : null;
|
|
7116
|
+
} else {
|
|
7117
|
+
kept = curr > prev;
|
|
7118
|
+
improvement = kept ? curr - prev : null;
|
|
7119
|
+
}
|
|
7120
|
+
if (kept) {
|
|
7121
|
+
this.state.best_result = result;
|
|
7122
|
+
this.state.keep_count++;
|
|
7123
|
+
}
|
|
7124
|
+
}
|
|
7125
|
+
return { kept, improvement, state: { ...this.state } };
|
|
7126
|
+
}
|
|
7127
|
+
/**
|
|
7128
|
+
* Export current state as a state snapshot compatible with the world file.
|
|
7129
|
+
*/
|
|
7130
|
+
toWorldState() {
|
|
7131
|
+
const successfulExperiments = this.state.experiment_log.filter((e) => e.success);
|
|
7132
|
+
const failedCount = this.state.experiment_log.filter((e) => !e.success).length;
|
|
7133
|
+
const keepRate = this.state.experiments_run > 0 ? Math.round(this.state.keep_count / this.state.experiments_run * 100) : 0;
|
|
7134
|
+
let improvementRate = 0;
|
|
7135
|
+
if (successfulExperiments.length >= 2) {
|
|
7136
|
+
const recent = successfulExperiments.slice(-10);
|
|
7137
|
+
let improvements = 0;
|
|
7138
|
+
for (let i = 1; i < recent.length; i++) {
|
|
7139
|
+
const prev = recent[i - 1].metric_value;
|
|
7140
|
+
const curr = recent[i].metric_value;
|
|
7141
|
+
if (this.config.optimize === "minimize" ? curr < prev : curr > prev) {
|
|
7142
|
+
improvements++;
|
|
7143
|
+
}
|
|
7144
|
+
}
|
|
7145
|
+
improvementRate = Math.round(improvements / (recent.length - 1) * 100);
|
|
7146
|
+
}
|
|
7147
|
+
return {
|
|
7148
|
+
experiments_run: this.state.experiments_run,
|
|
7149
|
+
best_metric_value: this.state.best_result?.metric_value ?? (this.config.optimize === "minimize" ? 100 : -1e3),
|
|
7150
|
+
keep_rate: keepRate,
|
|
7151
|
+
compute_used_minutes: Math.round(this.state.total_compute_minutes),
|
|
7152
|
+
compute_budget_minutes: this.config.computeBudgetMinutes,
|
|
7153
|
+
failed_experiments: failedCount,
|
|
7154
|
+
metric_improvement_rate: improvementRate,
|
|
7155
|
+
research_context_drift: 0
|
|
7156
|
+
// would need NLP to compute properly
|
|
7157
|
+
};
|
|
7158
|
+
}
|
|
7159
|
+
/**
|
|
7160
|
+
* Get a summary of the current research state.
|
|
7161
|
+
*/
|
|
7162
|
+
getSummary() {
|
|
7163
|
+
return {
|
|
7164
|
+
experiments_run: this.state.experiments_run,
|
|
7165
|
+
best_result: this.state.best_result,
|
|
7166
|
+
keep_rate: this.state.experiments_run > 0 ? Math.round(this.state.keep_count / this.state.experiments_run * 100) : 0,
|
|
7167
|
+
compute_remaining_minutes: this.config.computeBudgetMinutes - this.state.total_compute_minutes,
|
|
7168
|
+
architectures_tested: [...this.state.architectures_tested]
|
|
7169
|
+
};
|
|
7170
|
+
}
|
|
7171
|
+
/**
|
|
7172
|
+
* Load state from a persisted research context file.
|
|
7173
|
+
*/
|
|
7174
|
+
loadState(state) {
|
|
7175
|
+
this.state = { ...state };
|
|
7176
|
+
}
|
|
7177
|
+
/**
|
|
7178
|
+
* Export state for persistence.
|
|
7179
|
+
*/
|
|
7180
|
+
exportState() {
|
|
7181
|
+
return { ...this.state };
|
|
7182
|
+
}
|
|
7183
|
+
};
|
|
7184
|
+
}
|
|
7185
|
+
});
|
|
7186
|
+
|
|
7187
|
+
// src/adapters/shared.ts
|
|
7188
|
+
var shared_exports = {};
|
|
7189
|
+
__export(shared_exports, {
|
|
7190
|
+
GovernanceBlockedError: () => GovernanceBlockedError,
|
|
7191
|
+
buildEngineOptions: () => buildEngineOptions,
|
|
7192
|
+
defaultBlockMessage: () => defaultBlockMessage,
|
|
7193
|
+
extractScope: () => extractScope,
|
|
7194
|
+
trackPlanProgress: () => trackPlanProgress
|
|
7195
|
+
});
|
|
7196
|
+
function trackPlanProgress(event, state, callbacks) {
|
|
7197
|
+
if (!state.activePlan) return;
|
|
7198
|
+
const planVerdict = evaluatePlan(event, state.activePlan);
|
|
7199
|
+
if (planVerdict.matchedStep) {
|
|
7200
|
+
const advResult = advancePlan(state.activePlan, planVerdict.matchedStep);
|
|
7201
|
+
if (advResult.success && advResult.plan) {
|
|
7202
|
+
state.activePlan = advResult.plan;
|
|
7203
|
+
state.engineOptions.plan = state.activePlan;
|
|
7204
|
+
}
|
|
7205
|
+
const progress = getPlanProgress(state.activePlan);
|
|
7206
|
+
callbacks.onPlanProgress?.(progress);
|
|
7207
|
+
if (progress.completed === progress.total) {
|
|
7208
|
+
callbacks.onPlanComplete?.();
|
|
7209
|
+
}
|
|
7210
|
+
}
|
|
7211
|
+
}
|
|
7212
|
+
function extractScope(args) {
|
|
7213
|
+
if (typeof args.path === "string") return args.path;
|
|
7214
|
+
if (typeof args.file_path === "string") return args.file_path;
|
|
7215
|
+
if (typeof args.filename === "string") return args.filename;
|
|
7216
|
+
if (typeof args.url === "string") return args.url;
|
|
7217
|
+
if (typeof args.command === "string") return args.command;
|
|
7218
|
+
return void 0;
|
|
7219
|
+
}
|
|
7220
|
+
function buildEngineOptions(options, plan) {
|
|
7221
|
+
return {
|
|
7222
|
+
trace: options.trace ?? false,
|
|
7223
|
+
level: options.level,
|
|
7224
|
+
plan: plan ?? options.plan
|
|
7225
|
+
};
|
|
7226
|
+
}
|
|
7227
|
+
function defaultBlockMessage(verdict) {
|
|
7228
|
+
return `Action blocked by governance policy: ${verdict.reason ?? "rule violation"}. Rule: ${verdict.ruleId ?? "unknown"}.`;
|
|
7229
|
+
}
|
|
7230
|
+
var GovernanceBlockedError;
|
|
7231
|
+
var init_shared = __esm({
|
|
7232
|
+
"src/adapters/shared.ts"() {
|
|
7233
|
+
"use strict";
|
|
7234
|
+
init_plan_engine();
|
|
7235
|
+
GovernanceBlockedError = class extends Error {
|
|
7236
|
+
verdict;
|
|
7237
|
+
constructor(verdict, message) {
|
|
7238
|
+
super(message ?? `[NeuroVerse] BLOCKED: ${verdict.reason ?? verdict.ruleId ?? "governance rule"}`);
|
|
7239
|
+
this.name = "GovernanceBlockedError";
|
|
7240
|
+
this.verdict = verdict;
|
|
7241
|
+
}
|
|
7242
|
+
};
|
|
7243
|
+
}
|
|
7244
|
+
});
|
|
7245
|
+
|
|
7246
|
+
// src/engine/tool-classifier.ts
|
|
7247
|
+
function classifyTool(toolName) {
|
|
7248
|
+
const normalized = toolName.toLowerCase().replace(/[-\s]/g, "_");
|
|
7249
|
+
return TOOL_CATEGORY_MAP[normalized] ?? "unknown";
|
|
7250
|
+
}
|
|
7251
|
+
function isDangerousCommand(command) {
|
|
7252
|
+
const matched = DANGEROUS_SHELL_PATTERNS.filter((p) => p.pattern.test(command)).map((p) => p.label);
|
|
7253
|
+
return { dangerous: matched.length > 0, labels: matched };
|
|
7254
|
+
}
|
|
7255
|
+
function isDangerousGitCommand(command) {
|
|
7256
|
+
const matched = DANGEROUS_GIT_PATTERNS.filter((p) => p.pattern.test(command)).map((p) => p.label);
|
|
7257
|
+
return { dangerous: matched.length > 0, labels: matched };
|
|
7258
|
+
}
|
|
7259
|
+
function assessRiskLevel(category) {
|
|
7260
|
+
if (category === "file_read" || category === "context") return "low";
|
|
7261
|
+
if (category === "file_write" || category === "sub_agent") return "medium";
|
|
7262
|
+
if (category === "shell" || category === "file_delete" || category === "git" || category === "network") return "high";
|
|
7263
|
+
return void 0;
|
|
7264
|
+
}
|
|
7265
|
+
function categoryToActionCategory(category) {
|
|
7266
|
+
if (category === "file_read" || category === "context") return "read";
|
|
7267
|
+
if (category === "file_write") return "write";
|
|
7268
|
+
if (category === "file_delete") return "delete";
|
|
7269
|
+
if (category === "shell") return "shell";
|
|
7270
|
+
if (category === "network") return "network";
|
|
7271
|
+
return "other";
|
|
7272
|
+
}
|
|
7273
|
+
var TOOL_CATEGORY_MAP, DANGEROUS_SHELL_PATTERNS, DANGEROUS_GIT_PATTERNS;
|
|
7274
|
+
var init_tool_classifier = __esm({
|
|
7275
|
+
"src/engine/tool-classifier.ts"() {
|
|
7276
|
+
"use strict";
|
|
7277
|
+
TOOL_CATEGORY_MAP = {
|
|
7278
|
+
// File operations
|
|
7279
|
+
read_file: "file_read",
|
|
7280
|
+
read: "file_read",
|
|
7281
|
+
glob: "file_read",
|
|
7282
|
+
grep: "file_read",
|
|
7283
|
+
list_files: "file_read",
|
|
7284
|
+
write_file: "file_write",
|
|
7285
|
+
write: "file_write",
|
|
7286
|
+
create_file: "file_write",
|
|
7287
|
+
edit_file: "file_write",
|
|
7288
|
+
edit: "file_write",
|
|
7289
|
+
patch: "file_write",
|
|
7290
|
+
delete_file: "file_delete",
|
|
7291
|
+
remove_file: "file_delete",
|
|
7292
|
+
// Shell
|
|
7293
|
+
shell: "shell",
|
|
7294
|
+
bash: "shell",
|
|
7295
|
+
execute: "shell",
|
|
7296
|
+
run_command: "shell",
|
|
7297
|
+
terminal: "shell",
|
|
7298
|
+
// Git
|
|
7299
|
+
git: "git",
|
|
7300
|
+
git_commit: "git",
|
|
7301
|
+
git_push: "git",
|
|
7302
|
+
git_checkout: "git",
|
|
7303
|
+
// Network
|
|
7304
|
+
http: "network",
|
|
7305
|
+
fetch: "network",
|
|
7306
|
+
curl: "network",
|
|
7307
|
+
web_search: "network",
|
|
7308
|
+
// Sub-agents
|
|
7309
|
+
sub_agent: "sub_agent",
|
|
7310
|
+
spawn_agent: "sub_agent",
|
|
7311
|
+
delegate: "sub_agent",
|
|
7312
|
+
// Context management
|
|
7313
|
+
summarize: "context",
|
|
7314
|
+
compress_context: "context"
|
|
7315
|
+
};
|
|
7316
|
+
DANGEROUS_SHELL_PATTERNS = [
|
|
7317
|
+
{ pattern: /rm\s+(-[a-zA-Z]*f[a-zA-Z]*\s+|.*-rf\s+|.*--force)/, label: "force-delete" },
|
|
7318
|
+
{ pattern: /rm\s+-[a-zA-Z]*r/, label: "recursive-delete" },
|
|
7319
|
+
{ pattern: />\s*\/dev\/sd/, label: "disk-overwrite" },
|
|
7320
|
+
{ pattern: /mkfs\./, label: "format-disk" },
|
|
7321
|
+
{ pattern: /dd\s+if=/, label: "disk-dump" },
|
|
7322
|
+
{ pattern: /chmod\s+(-R\s+)?777/, label: "world-writable" },
|
|
7323
|
+
{ pattern: /curl\s+.*\|\s*(bash|sh|zsh)/, label: "pipe-to-shell" },
|
|
7324
|
+
{ pattern: /wget\s+.*\|\s*(bash|sh|zsh)/, label: "pipe-to-shell" },
|
|
7325
|
+
{ pattern: /:(){ :\|:& };:/, label: "fork-bomb" },
|
|
7326
|
+
{ pattern: />\s*\/etc\//, label: "system-config-overwrite" },
|
|
7327
|
+
{ pattern: /shutdown|reboot|halt|poweroff/, label: "system-shutdown" },
|
|
7328
|
+
{ pattern: /kill\s+-9\s+1\b/, label: "kill-init" }
|
|
7329
|
+
];
|
|
7330
|
+
DANGEROUS_GIT_PATTERNS = [
|
|
7331
|
+
{ pattern: /push\s+.*--force/, label: "force-push" },
|
|
7332
|
+
{ pattern: /push\s+.*-f\b/, label: "force-push" },
|
|
7333
|
+
{ pattern: /push\s+(origin\s+)?main\b/, label: "push-main" },
|
|
7334
|
+
{ pattern: /push\s+(origin\s+)?master\b/, label: "push-master" },
|
|
7335
|
+
{ pattern: /reset\s+--hard/, label: "hard-reset" },
|
|
7336
|
+
{ pattern: /clean\s+-fd/, label: "clean-force" },
|
|
7337
|
+
{ pattern: /branch\s+-D/, label: "force-delete-branch" }
|
|
7338
|
+
];
|
|
7339
|
+
}
|
|
7340
|
+
});
|
|
7341
|
+
|
|
7342
|
+
// src/adapters/deep-agents.ts
|
|
7343
|
+
var deep_agents_exports = {};
|
|
7344
|
+
__export(deep_agents_exports, {
|
|
7345
|
+
DeepAgentsGuard: () => DeepAgentsGuard,
|
|
7346
|
+
GovernanceBlockedError: () => GovernanceBlockedError2,
|
|
7347
|
+
createDeepAgentsGuard: () => createDeepAgentsGuard,
|
|
7348
|
+
createDeepAgentsGuardFromWorld: () => createDeepAgentsGuardFromWorld
|
|
7349
|
+
});
|
|
7350
|
+
function defaultMapToolCall(toolCall) {
|
|
7351
|
+
const category = classifyTool(toolCall.tool);
|
|
7352
|
+
const args = toolCall.args;
|
|
7353
|
+
const scope = extractScope(args);
|
|
7354
|
+
let intent = toolCall.tool;
|
|
7355
|
+
if (category === "shell" && typeof args.command === "string") {
|
|
7356
|
+
intent = `shell: ${args.command}`;
|
|
7357
|
+
} else if (category === "git" && typeof args.command === "string") {
|
|
7358
|
+
intent = `git ${args.command}`;
|
|
7359
|
+
} else if (category === "file_write" && scope) {
|
|
7360
|
+
intent = `write ${scope}`;
|
|
7361
|
+
} else if (category === "file_delete" && scope) {
|
|
7362
|
+
intent = `delete ${scope}`;
|
|
7363
|
+
}
|
|
7364
|
+
const riskLevel = assessRiskLevel(category);
|
|
7365
|
+
let irreversible = false;
|
|
7366
|
+
if (category === "shell" && typeof args.command === "string") {
|
|
7367
|
+
irreversible = DANGEROUS_SHELL_PATTERNS.some((p) => p.pattern.test(args.command));
|
|
7368
|
+
} else if (category === "git" && typeof args.command === "string") {
|
|
7369
|
+
irreversible = DANGEROUS_GIT_PATTERNS.some((p) => p.pattern.test(args.command));
|
|
7370
|
+
} else if (category === "file_delete") {
|
|
7371
|
+
irreversible = true;
|
|
7372
|
+
}
|
|
7373
|
+
return {
|
|
7374
|
+
intent,
|
|
7375
|
+
tool: toolCall.tool,
|
|
7376
|
+
scope,
|
|
7377
|
+
args,
|
|
7378
|
+
direction: "input",
|
|
7379
|
+
actionCategory: categoryToActionCategory(category),
|
|
7380
|
+
riskLevel,
|
|
7381
|
+
irreversible
|
|
7382
|
+
};
|
|
7383
|
+
}
|
|
7384
|
+
async function createDeepAgentsGuard(worldPath, options) {
|
|
7385
|
+
const world = await loadWorld(worldPath);
|
|
7386
|
+
return new DeepAgentsGuard(world, options);
|
|
7387
|
+
}
|
|
7388
|
+
function createDeepAgentsGuardFromWorld(world, options) {
|
|
7389
|
+
return new DeepAgentsGuard(world, options);
|
|
7390
|
+
}
|
|
7391
|
+
var GovernanceBlockedError2, DeepAgentsGuard;
|
|
7392
|
+
var init_deep_agents = __esm({
|
|
7393
|
+
"src/adapters/deep-agents.ts"() {
|
|
7394
|
+
"use strict";
|
|
7395
|
+
init_guard_engine();
|
|
7396
|
+
init_world_loader();
|
|
7397
|
+
init_shared();
|
|
7398
|
+
init_tool_classifier();
|
|
7399
|
+
GovernanceBlockedError2 = class extends GovernanceBlockedError {
|
|
7400
|
+
toolCall;
|
|
7401
|
+
category;
|
|
7402
|
+
constructor(verdict, toolCall, category) {
|
|
7403
|
+
super(verdict);
|
|
7404
|
+
this.toolCall = toolCall;
|
|
7405
|
+
this.category = category;
|
|
7406
|
+
}
|
|
7407
|
+
};
|
|
7408
|
+
DeepAgentsGuard = class {
|
|
7409
|
+
name = "neuroverse-deep-agents-guard";
|
|
7410
|
+
world;
|
|
7411
|
+
options;
|
|
7412
|
+
engineOptions;
|
|
7413
|
+
mapToolCall;
|
|
7414
|
+
activePlan;
|
|
7415
|
+
constructor(world, options = {}) {
|
|
7416
|
+
this.world = world;
|
|
7417
|
+
this.options = options;
|
|
7418
|
+
this.activePlan = options.plan;
|
|
7419
|
+
this.engineOptions = buildEngineOptions(options, this.activePlan);
|
|
7420
|
+
this.mapToolCall = options.mapToolCall ?? defaultMapToolCall;
|
|
7421
|
+
}
|
|
7422
|
+
/**
|
|
7423
|
+
* Evaluate a tool call against governance rules.
|
|
7424
|
+
* Returns the result without side effects.
|
|
7425
|
+
*/
|
|
7426
|
+
evaluate(toolCall) {
|
|
7427
|
+
const event = this.mapToolCall(toolCall);
|
|
7428
|
+
this.engineOptions.plan = this.activePlan;
|
|
7429
|
+
const verdict = evaluateGuard(event, this.world, this.engineOptions);
|
|
7430
|
+
const category = classifyTool(toolCall.tool);
|
|
7431
|
+
const result = {
|
|
7432
|
+
allowed: verdict.status === "ALLOW",
|
|
7433
|
+
verdict,
|
|
7434
|
+
toolCall,
|
|
7435
|
+
category
|
|
7436
|
+
};
|
|
7437
|
+
this.options.onEvaluate?.(result);
|
|
7438
|
+
if (verdict.status === "ALLOW" && this.activePlan) {
|
|
7439
|
+
this.trackPlanProgressInternal(event);
|
|
7440
|
+
}
|
|
7441
|
+
return result;
|
|
7442
|
+
}
|
|
7443
|
+
/**
|
|
7444
|
+
* Evaluate and enforce governance on a tool call.
|
|
7445
|
+
*
|
|
7446
|
+
* @throws GovernanceBlockedError if BLOCKED
|
|
7447
|
+
* @throws GovernanceBlockedError if PAUSED and onPause returns false
|
|
7448
|
+
* @returns DeepAgentsGuardResult on ALLOW
|
|
7449
|
+
*/
|
|
7450
|
+
async enforce(toolCall) {
|
|
7451
|
+
const result = this.evaluate(toolCall);
|
|
7452
|
+
if (result.verdict.status === "BLOCK") {
|
|
7453
|
+
this.options.onBlock?.(result);
|
|
7454
|
+
throw new GovernanceBlockedError2(result.verdict, toolCall, result.category);
|
|
7455
|
+
}
|
|
7456
|
+
if (result.verdict.status === "PAUSE") {
|
|
7457
|
+
const approved = await this.options.onPause?.(result);
|
|
7458
|
+
if (!approved) {
|
|
7459
|
+
throw new GovernanceBlockedError2(result.verdict, toolCall, result.category);
|
|
7460
|
+
}
|
|
7461
|
+
}
|
|
7462
|
+
return result;
|
|
7463
|
+
}
|
|
7464
|
+
/**
|
|
7465
|
+
* Evaluate and execute a tool call with governance enforcement.
|
|
7466
|
+
*
|
|
7467
|
+
* If ALLOW: runs the executor and returns its result.
|
|
7468
|
+
* If BLOCK: returns a governance-blocked message.
|
|
7469
|
+
* If PAUSE: calls onPause; blocks if not approved.
|
|
7470
|
+
*
|
|
7471
|
+
* @param toolCall - The Deep Agents tool call to evaluate
|
|
7472
|
+
* @param executor - The actual tool execution function
|
|
7473
|
+
* @returns The tool execution result or a blocked message
|
|
7474
|
+
*/
|
|
7475
|
+
async execute(toolCall, executor) {
|
|
7476
|
+
const guardResult = this.evaluate(toolCall);
|
|
7477
|
+
if (guardResult.verdict.status === "BLOCK") {
|
|
7478
|
+
this.options.onBlock?.(guardResult);
|
|
7479
|
+
return {
|
|
7480
|
+
blocked: true,
|
|
7481
|
+
verdict: guardResult.verdict,
|
|
7482
|
+
reason: guardResult.verdict.reason ?? "Action blocked by governance policy."
|
|
7483
|
+
};
|
|
7484
|
+
}
|
|
7485
|
+
if (guardResult.verdict.status === "PAUSE") {
|
|
7486
|
+
const approved = await this.options.onPause?.(guardResult);
|
|
7487
|
+
if (!approved) {
|
|
7488
|
+
return {
|
|
7489
|
+
blocked: true,
|
|
7490
|
+
verdict: guardResult.verdict,
|
|
7491
|
+
reason: guardResult.verdict.reason ?? "Action requires approval."
|
|
7492
|
+
};
|
|
7493
|
+
}
|
|
7494
|
+
}
|
|
7495
|
+
const result = await executor(toolCall);
|
|
7496
|
+
return { result, verdict: guardResult.verdict };
|
|
7497
|
+
}
|
|
7498
|
+
/**
|
|
7499
|
+
* Returns a middleware function compatible with Deep Agents' tool pipeline.
|
|
7500
|
+
*
|
|
7501
|
+
* The middleware intercepts tool calls before execution:
|
|
7502
|
+
* agent.use(guard.middleware());
|
|
7503
|
+
*/
|
|
7504
|
+
middleware() {
|
|
7505
|
+
return async (toolCall, next) => {
|
|
7506
|
+
await this.enforce(toolCall);
|
|
7507
|
+
return next();
|
|
7508
|
+
};
|
|
7509
|
+
}
|
|
7510
|
+
/**
|
|
7511
|
+
* Returns a callback-handler-style object for LangChain integration.
|
|
7512
|
+
* Compatible with Deep Agents' callback system.
|
|
7513
|
+
*/
|
|
7514
|
+
callbacks() {
|
|
7515
|
+
return {
|
|
7516
|
+
handleToolStart: async (tool, input) => {
|
|
7517
|
+
let parsedInput;
|
|
7518
|
+
try {
|
|
7519
|
+
parsedInput = typeof input === "string" ? JSON.parse(input) : input;
|
|
7520
|
+
} catch {
|
|
7521
|
+
parsedInput = { raw: input };
|
|
7522
|
+
}
|
|
7523
|
+
await this.enforce({ tool: tool.name, args: parsedInput });
|
|
7524
|
+
}
|
|
7525
|
+
};
|
|
7526
|
+
}
|
|
7527
|
+
/**
|
|
7528
|
+
* Check if a shell command contains dangerous patterns.
|
|
7529
|
+
* Useful for pre-screening before full governance evaluation.
|
|
7530
|
+
*/
|
|
7531
|
+
static isDangerousCommand(command) {
|
|
7532
|
+
return isDangerousCommand(command);
|
|
7533
|
+
}
|
|
7534
|
+
/**
|
|
7535
|
+
* Check if a git command contains dangerous patterns.
|
|
7536
|
+
*/
|
|
7537
|
+
static isDangerousGitCommand(command) {
|
|
7538
|
+
return isDangerousGitCommand(command);
|
|
7539
|
+
}
|
|
7540
|
+
/**
|
|
7541
|
+
* Classify a tool name into a category.
|
|
7542
|
+
*/
|
|
7543
|
+
static classifyTool(toolName) {
|
|
7544
|
+
return classifyTool(toolName);
|
|
7545
|
+
}
|
|
7546
|
+
// ─── Private ──────────────────────────────────────────────────────────────
|
|
7547
|
+
trackPlanProgressInternal(event) {
|
|
7548
|
+
trackPlanProgress(event, this, this.options);
|
|
7549
|
+
}
|
|
7550
|
+
};
|
|
7551
|
+
}
|
|
7552
|
+
});
|
|
7553
|
+
|
|
6161
7554
|
// src/adapters/express.ts
|
|
6162
7555
|
var express_exports = {};
|
|
6163
7556
|
__export(express_exports, {
|
|
@@ -6262,16 +7655,16 @@ var init_express = __esm({
|
|
|
6262
7655
|
// src/adapters/langchain.ts
|
|
6263
7656
|
var langchain_exports = {};
|
|
6264
7657
|
__export(langchain_exports, {
|
|
6265
|
-
GovernanceBlockedError: () =>
|
|
7658
|
+
GovernanceBlockedError: () => GovernanceBlockedError3,
|
|
6266
7659
|
NeuroVerseCallbackHandler: () => NeuroVerseCallbackHandler,
|
|
6267
7660
|
createNeuroVerseCallbackHandler: () => createNeuroVerseCallbackHandler,
|
|
6268
7661
|
createNeuroVerseCallbackHandlerFromWorld: () => createNeuroVerseCallbackHandlerFromWorld
|
|
6269
7662
|
});
|
|
6270
|
-
function
|
|
7663
|
+
function defaultMapToolCall2(toolName, toolInput) {
|
|
6271
7664
|
return {
|
|
6272
7665
|
intent: toolName,
|
|
6273
7666
|
tool: toolName,
|
|
6274
|
-
scope:
|
|
7667
|
+
scope: extractScope(toolInput),
|
|
6275
7668
|
args: toolInput,
|
|
6276
7669
|
direction: "input"
|
|
6277
7670
|
};
|
|
@@ -6283,20 +7676,17 @@ async function createNeuroVerseCallbackHandler(worldPath, options) {
|
|
|
6283
7676
|
function createNeuroVerseCallbackHandlerFromWorld(world, options) {
|
|
6284
7677
|
return new NeuroVerseCallbackHandler(world, options);
|
|
6285
7678
|
}
|
|
6286
|
-
var
|
|
7679
|
+
var GovernanceBlockedError3, NeuroVerseCallbackHandler;
|
|
6287
7680
|
var init_langchain = __esm({
|
|
6288
7681
|
"src/adapters/langchain.ts"() {
|
|
6289
7682
|
"use strict";
|
|
6290
7683
|
init_guard_engine();
|
|
6291
|
-
init_plan_engine();
|
|
6292
7684
|
init_world_loader();
|
|
6293
|
-
|
|
6294
|
-
|
|
7685
|
+
init_shared();
|
|
7686
|
+
GovernanceBlockedError3 = class extends GovernanceBlockedError {
|
|
6295
7687
|
event;
|
|
6296
7688
|
constructor(verdict, event) {
|
|
6297
|
-
super(
|
|
6298
|
-
this.name = "GovernanceBlockedError";
|
|
6299
|
-
this.verdict = verdict;
|
|
7689
|
+
super(verdict);
|
|
6300
7690
|
this.event = event;
|
|
6301
7691
|
}
|
|
6302
7692
|
};
|
|
@@ -6311,12 +7701,8 @@ var init_langchain = __esm({
|
|
|
6311
7701
|
this.world = world;
|
|
6312
7702
|
this.options = options;
|
|
6313
7703
|
this.activePlan = options.plan;
|
|
6314
|
-
this.engineOptions =
|
|
6315
|
-
|
|
6316
|
-
level: options.level,
|
|
6317
|
-
plan: this.activePlan
|
|
6318
|
-
};
|
|
6319
|
-
this.mapToolCall = options.mapToolCall ?? defaultMapToolCall;
|
|
7704
|
+
this.engineOptions = buildEngineOptions(options, this.activePlan);
|
|
7705
|
+
this.mapToolCall = options.mapToolCall ?? defaultMapToolCall2;
|
|
6320
7706
|
}
|
|
6321
7707
|
/**
|
|
6322
7708
|
* Called before a tool is executed.
|
|
@@ -6338,28 +7724,16 @@ var init_langchain = __esm({
|
|
|
6338
7724
|
this.options.onEvaluate?.(verdict, event);
|
|
6339
7725
|
if (verdict.status === "BLOCK") {
|
|
6340
7726
|
this.options.onBlock?.(verdict, event);
|
|
6341
|
-
throw new
|
|
7727
|
+
throw new GovernanceBlockedError3(verdict, event);
|
|
6342
7728
|
}
|
|
6343
7729
|
if (verdict.status === "PAUSE") {
|
|
6344
7730
|
const approved = await this.options.onPause?.(verdict, event);
|
|
6345
7731
|
if (!approved) {
|
|
6346
|
-
throw new
|
|
7732
|
+
throw new GovernanceBlockedError3(verdict, event);
|
|
6347
7733
|
}
|
|
6348
7734
|
}
|
|
6349
|
-
if (verdict.status === "ALLOW"
|
|
6350
|
-
|
|
6351
|
-
if (planVerdict.matchedStep) {
|
|
6352
|
-
const advResult = advancePlan(this.activePlan, planVerdict.matchedStep);
|
|
6353
|
-
if (advResult.success && advResult.plan) {
|
|
6354
|
-
this.activePlan = advResult.plan;
|
|
6355
|
-
this.engineOptions.plan = this.activePlan;
|
|
6356
|
-
}
|
|
6357
|
-
const progress = getPlanProgress(this.activePlan);
|
|
6358
|
-
this.options.onPlanProgress?.(progress);
|
|
6359
|
-
if (progress.completed === progress.total) {
|
|
6360
|
-
this.options.onPlanComplete?.();
|
|
6361
|
-
}
|
|
6362
|
-
}
|
|
7735
|
+
if (verdict.status === "ALLOW") {
|
|
7736
|
+
trackPlanProgress(event, this, this.options);
|
|
6363
7737
|
}
|
|
6364
7738
|
}
|
|
6365
7739
|
};
|
|
@@ -6369,7 +7743,7 @@ var init_langchain = __esm({
|
|
|
6369
7743
|
// src/adapters/openai.ts
|
|
6370
7744
|
var openai_exports = {};
|
|
6371
7745
|
__export(openai_exports, {
|
|
6372
|
-
GovernanceBlockedError: () =>
|
|
7746
|
+
GovernanceBlockedError: () => GovernanceBlockedError4,
|
|
6373
7747
|
GovernedToolExecutor: () => GovernedToolExecutor,
|
|
6374
7748
|
createGovernedToolExecutor: () => createGovernedToolExecutor,
|
|
6375
7749
|
createGovernedToolExecutorFromWorld: () => createGovernedToolExecutorFromWorld
|
|
@@ -6378,14 +7752,11 @@ function defaultMapFunctionCall(name, args) {
|
|
|
6378
7752
|
return {
|
|
6379
7753
|
intent: name,
|
|
6380
7754
|
tool: name,
|
|
6381
|
-
scope:
|
|
7755
|
+
scope: extractScope(args),
|
|
6382
7756
|
args,
|
|
6383
7757
|
direction: "input"
|
|
6384
7758
|
};
|
|
6385
7759
|
}
|
|
6386
|
-
function defaultBlockMessage(verdict) {
|
|
6387
|
-
return `Action blocked by governance policy: ${verdict.reason ?? "rule violation"}. Rule: ${verdict.ruleId ?? "unknown"}.`;
|
|
6388
|
-
}
|
|
6389
7760
|
async function createGovernedToolExecutor(worldPath, options) {
|
|
6390
7761
|
const world = await loadWorld(worldPath);
|
|
6391
7762
|
return new GovernedToolExecutor(world, options);
|
|
@@ -6393,20 +7764,17 @@ async function createGovernedToolExecutor(worldPath, options) {
|
|
|
6393
7764
|
function createGovernedToolExecutorFromWorld(world, options) {
|
|
6394
7765
|
return new GovernedToolExecutor(world, options);
|
|
6395
7766
|
}
|
|
6396
|
-
var
|
|
7767
|
+
var GovernanceBlockedError4, GovernedToolExecutor;
|
|
6397
7768
|
var init_openai = __esm({
|
|
6398
7769
|
"src/adapters/openai.ts"() {
|
|
6399
7770
|
"use strict";
|
|
6400
7771
|
init_guard_engine();
|
|
6401
|
-
init_plan_engine();
|
|
6402
7772
|
init_world_loader();
|
|
6403
|
-
|
|
6404
|
-
|
|
7773
|
+
init_shared();
|
|
7774
|
+
GovernanceBlockedError4 = class extends GovernanceBlockedError {
|
|
6405
7775
|
toolCallId;
|
|
6406
7776
|
constructor(verdict, toolCallId) {
|
|
6407
|
-
super(
|
|
6408
|
-
this.name = "GovernanceBlockedError";
|
|
6409
|
-
this.verdict = verdict;
|
|
7777
|
+
super(verdict);
|
|
6410
7778
|
this.toolCallId = toolCallId;
|
|
6411
7779
|
}
|
|
6412
7780
|
};
|
|
@@ -6421,11 +7789,7 @@ var init_openai = __esm({
|
|
|
6421
7789
|
this.world = world;
|
|
6422
7790
|
this.options = options;
|
|
6423
7791
|
this.activePlan = options.plan;
|
|
6424
|
-
this.engineOptions =
|
|
6425
|
-
trace: options.trace ?? false,
|
|
6426
|
-
level: options.level,
|
|
6427
|
-
plan: this.activePlan
|
|
6428
|
-
};
|
|
7792
|
+
this.engineOptions = buildEngineOptions(options, this.activePlan);
|
|
6429
7793
|
this.mapFn = options.mapFunctionCall ?? defaultMapFunctionCall;
|
|
6430
7794
|
this.blockMsg = options.blockMessage ?? defaultBlockMessage;
|
|
6431
7795
|
}
|
|
@@ -6444,20 +7808,8 @@ var init_openai = __esm({
|
|
|
6444
7808
|
this.engineOptions.plan = this.activePlan;
|
|
6445
7809
|
const verdict = evaluateGuard(event, this.world, this.engineOptions);
|
|
6446
7810
|
this.options.onEvaluate?.(verdict, event);
|
|
6447
|
-
if (verdict.status === "ALLOW"
|
|
6448
|
-
|
|
6449
|
-
if (planVerdict.matchedStep) {
|
|
6450
|
-
const advResult = advancePlan(this.activePlan, planVerdict.matchedStep);
|
|
6451
|
-
if (advResult.success && advResult.plan) {
|
|
6452
|
-
this.activePlan = advResult.plan;
|
|
6453
|
-
this.engineOptions.plan = this.activePlan;
|
|
6454
|
-
}
|
|
6455
|
-
const progress = getPlanProgress(this.activePlan);
|
|
6456
|
-
this.options.onPlanProgress?.(progress);
|
|
6457
|
-
if (progress.completed === progress.total) {
|
|
6458
|
-
this.options.onPlanComplete?.();
|
|
6459
|
-
}
|
|
6460
|
-
}
|
|
7811
|
+
if (verdict.status === "ALLOW") {
|
|
7812
|
+
trackPlanProgress(event, this, this.options);
|
|
6461
7813
|
}
|
|
6462
7814
|
return verdict;
|
|
6463
7815
|
}
|
|
@@ -6483,7 +7835,7 @@ var init_openai = __esm({
|
|
|
6483
7835
|
};
|
|
6484
7836
|
}
|
|
6485
7837
|
if (verdict.status === "PAUSE") {
|
|
6486
|
-
throw new
|
|
7838
|
+
throw new GovernanceBlockedError4(verdict, toolCall.id);
|
|
6487
7839
|
}
|
|
6488
7840
|
let args;
|
|
6489
7841
|
try {
|
|
@@ -6506,7 +7858,7 @@ var init_openai = __esm({
|
|
|
6506
7858
|
// src/adapters/openclaw.ts
|
|
6507
7859
|
var openclaw_exports = {};
|
|
6508
7860
|
__export(openclaw_exports, {
|
|
6509
|
-
GovernanceBlockedError: () =>
|
|
7861
|
+
GovernanceBlockedError: () => GovernanceBlockedError5,
|
|
6510
7862
|
NeuroVersePlugin: () => NeuroVersePlugin,
|
|
6511
7863
|
createNeuroVersePlugin: () => createNeuroVersePlugin,
|
|
6512
7864
|
createNeuroVersePluginFromWorld: () => createNeuroVersePluginFromWorld
|
|
@@ -6517,7 +7869,7 @@ function defaultMapAction(action, direction) {
|
|
|
6517
7869
|
tool: action.tool ?? action.type,
|
|
6518
7870
|
args: action.input,
|
|
6519
7871
|
direction,
|
|
6520
|
-
scope:
|
|
7872
|
+
scope: action.input ? extractScope(action.input) : void 0
|
|
6521
7873
|
};
|
|
6522
7874
|
}
|
|
6523
7875
|
async function createNeuroVersePlugin(worldPath, options) {
|
|
@@ -6527,20 +7879,17 @@ async function createNeuroVersePlugin(worldPath, options) {
|
|
|
6527
7879
|
function createNeuroVersePluginFromWorld(world, options) {
|
|
6528
7880
|
return new NeuroVersePlugin(world, options);
|
|
6529
7881
|
}
|
|
6530
|
-
var
|
|
7882
|
+
var GovernanceBlockedError5, NeuroVersePlugin;
|
|
6531
7883
|
var init_openclaw = __esm({
|
|
6532
7884
|
"src/adapters/openclaw.ts"() {
|
|
6533
7885
|
"use strict";
|
|
6534
7886
|
init_guard_engine();
|
|
6535
|
-
init_plan_engine();
|
|
6536
7887
|
init_world_loader();
|
|
6537
|
-
|
|
6538
|
-
|
|
7888
|
+
init_shared();
|
|
7889
|
+
GovernanceBlockedError5 = class extends GovernanceBlockedError {
|
|
6539
7890
|
action;
|
|
6540
7891
|
constructor(verdict, action) {
|
|
6541
|
-
super(
|
|
6542
|
-
this.name = "GovernanceBlockedError";
|
|
6543
|
-
this.verdict = verdict;
|
|
7892
|
+
super(verdict);
|
|
6544
7893
|
this.action = action;
|
|
6545
7894
|
}
|
|
6546
7895
|
};
|
|
@@ -6555,11 +7904,7 @@ var init_openclaw = __esm({
|
|
|
6555
7904
|
this.world = world;
|
|
6556
7905
|
this.options = options;
|
|
6557
7906
|
this.activePlan = options.plan;
|
|
6558
|
-
this.engineOptions =
|
|
6559
|
-
trace: options.trace ?? false,
|
|
6560
|
-
level: options.level,
|
|
6561
|
-
plan: this.activePlan
|
|
6562
|
-
};
|
|
7907
|
+
this.engineOptions = buildEngineOptions(options, this.activePlan);
|
|
6563
7908
|
this.mapAction = options.mapAction ?? defaultMapAction;
|
|
6564
7909
|
}
|
|
6565
7910
|
/**
|
|
@@ -6579,22 +7924,10 @@ var init_openclaw = __esm({
|
|
|
6579
7924
|
};
|
|
6580
7925
|
this.options.onEvaluate?.(result);
|
|
6581
7926
|
if (verdict.status === "BLOCK") {
|
|
6582
|
-
throw new
|
|
7927
|
+
throw new GovernanceBlockedError5(verdict, action);
|
|
6583
7928
|
}
|
|
6584
|
-
if (verdict.status === "ALLOW"
|
|
6585
|
-
|
|
6586
|
-
if (planVerdict.matchedStep) {
|
|
6587
|
-
const advResult = advancePlan(this.activePlan, planVerdict.matchedStep);
|
|
6588
|
-
if (advResult.success && advResult.plan) {
|
|
6589
|
-
this.activePlan = advResult.plan;
|
|
6590
|
-
this.engineOptions.plan = this.activePlan;
|
|
6591
|
-
}
|
|
6592
|
-
const progress = getPlanProgress(this.activePlan);
|
|
6593
|
-
this.options.onPlanProgress?.(progress);
|
|
6594
|
-
if (progress.completed === progress.total) {
|
|
6595
|
-
this.options.onPlanComplete?.();
|
|
6596
|
-
}
|
|
6597
|
-
}
|
|
7929
|
+
if (verdict.status === "ALLOW") {
|
|
7930
|
+
trackPlanProgress(event, this, this.options);
|
|
6598
7931
|
}
|
|
6599
7932
|
return result;
|
|
6600
7933
|
}
|
|
@@ -6615,7 +7948,7 @@ var init_openclaw = __esm({
|
|
|
6615
7948
|
};
|
|
6616
7949
|
this.options.onEvaluate?.(result);
|
|
6617
7950
|
if (verdict.status === "BLOCK") {
|
|
6618
|
-
throw new
|
|
7951
|
+
throw new GovernanceBlockedError5(verdict, action);
|
|
6619
7952
|
}
|
|
6620
7953
|
return result;
|
|
6621
7954
|
}
|
|
@@ -6635,12 +7968,19 @@ var init_openclaw = __esm({
|
|
|
6635
7968
|
// src/adapters/index.ts
|
|
6636
7969
|
var adapters_exports = {};
|
|
6637
7970
|
__export(adapters_exports, {
|
|
7971
|
+
AutoresearchGovernor: () => AutoresearchGovernor,
|
|
7972
|
+
DeepAgentsGovernanceBlockedError: () => GovernanceBlockedError2,
|
|
7973
|
+
DeepAgentsGuard: () => DeepAgentsGuard,
|
|
7974
|
+
GovernanceBlockedError: () => GovernanceBlockedError,
|
|
6638
7975
|
GovernedToolExecutor: () => GovernedToolExecutor,
|
|
6639
|
-
LangChainGovernanceBlockedError: () =>
|
|
7976
|
+
LangChainGovernanceBlockedError: () => GovernanceBlockedError3,
|
|
6640
7977
|
NeuroVerseCallbackHandler: () => NeuroVerseCallbackHandler,
|
|
6641
7978
|
NeuroVersePlugin: () => NeuroVersePlugin,
|
|
6642
|
-
OpenAIGovernanceBlockedError: () =>
|
|
6643
|
-
OpenClawGovernanceBlockedError: () =>
|
|
7979
|
+
OpenAIGovernanceBlockedError: () => GovernanceBlockedError4,
|
|
7980
|
+
OpenClawGovernanceBlockedError: () => GovernanceBlockedError5,
|
|
7981
|
+
buildEngineOptions: () => buildEngineOptions,
|
|
7982
|
+
createDeepAgentsGuard: () => createDeepAgentsGuard,
|
|
7983
|
+
createDeepAgentsGuardFromWorld: () => createDeepAgentsGuardFromWorld,
|
|
6644
7984
|
createGovernanceMiddleware: () => createGovernanceMiddleware,
|
|
6645
7985
|
createGovernanceMiddlewareFromWorld: () => createGovernanceMiddlewareFromWorld,
|
|
6646
7986
|
createGovernedToolExecutor: () => createGovernedToolExecutor,
|
|
@@ -6648,15 +7988,21 @@ __export(adapters_exports, {
|
|
|
6648
7988
|
createNeuroVerseCallbackHandler: () => createNeuroVerseCallbackHandler,
|
|
6649
7989
|
createNeuroVerseCallbackHandlerFromWorld: () => createNeuroVerseCallbackHandlerFromWorld,
|
|
6650
7990
|
createNeuroVersePlugin: () => createNeuroVersePlugin,
|
|
6651
|
-
createNeuroVersePluginFromWorld: () => createNeuroVersePluginFromWorld
|
|
7991
|
+
createNeuroVersePluginFromWorld: () => createNeuroVersePluginFromWorld,
|
|
7992
|
+
defaultBlockMessage: () => defaultBlockMessage,
|
|
7993
|
+
extractScope: () => extractScope,
|
|
7994
|
+
trackPlanProgress: () => trackPlanProgress
|
|
6652
7995
|
});
|
|
6653
7996
|
var init_adapters = __esm({
|
|
6654
7997
|
"src/adapters/index.ts"() {
|
|
6655
7998
|
"use strict";
|
|
7999
|
+
init_shared();
|
|
6656
8000
|
init_langchain();
|
|
6657
8001
|
init_openai();
|
|
6658
8002
|
init_openclaw();
|
|
6659
8003
|
init_express();
|
|
8004
|
+
init_autoresearch();
|
|
8005
|
+
init_deep_agents();
|
|
6660
8006
|
}
|
|
6661
8007
|
});
|
|
6662
8008
|
|
|
@@ -6665,11 +8011,14 @@ var globImport_adapters;
|
|
|
6665
8011
|
var init_ = __esm({
|
|
6666
8012
|
'import("../adapters/**/*") in src/cli/doctor.ts'() {
|
|
6667
8013
|
globImport_adapters = __glob({
|
|
8014
|
+
"../adapters/autoresearch.ts": () => Promise.resolve().then(() => (init_autoresearch(), autoresearch_exports)),
|
|
8015
|
+
"../adapters/deep-agents.ts": () => Promise.resolve().then(() => (init_deep_agents(), deep_agents_exports)),
|
|
6668
8016
|
"../adapters/express.ts": () => Promise.resolve().then(() => (init_express(), express_exports)),
|
|
6669
8017
|
"../adapters/index.ts": () => Promise.resolve().then(() => (init_adapters(), adapters_exports)),
|
|
6670
8018
|
"../adapters/langchain.ts": () => Promise.resolve().then(() => (init_langchain(), langchain_exports)),
|
|
6671
8019
|
"../adapters/openai.ts": () => Promise.resolve().then(() => (init_openai(), openai_exports)),
|
|
6672
|
-
"../adapters/openclaw.ts": () => Promise.resolve().then(() => (init_openclaw(), openclaw_exports))
|
|
8020
|
+
"../adapters/openclaw.ts": () => Promise.resolve().then(() => (init_openclaw(), openclaw_exports)),
|
|
8021
|
+
"../adapters/shared.ts": () => Promise.resolve().then(() => (init_shared(), shared_exports))
|
|
6673
8022
|
});
|
|
6674
8023
|
}
|
|
6675
8024
|
});
|
|
@@ -6677,9 +8026,9 @@ var init_ = __esm({
|
|
|
6677
8026
|
// src/cli/doctor.ts
|
|
6678
8027
|
var doctor_exports = {};
|
|
6679
8028
|
__export(doctor_exports, {
|
|
6680
|
-
main: () =>
|
|
8029
|
+
main: () => main13
|
|
6681
8030
|
});
|
|
6682
|
-
async function
|
|
8031
|
+
async function main13(argv) {
|
|
6683
8032
|
const json = argv.includes("--json");
|
|
6684
8033
|
let worldPath;
|
|
6685
8034
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -6727,9 +8076,9 @@ async function main11(argv) {
|
|
|
6727
8076
|
}
|
|
6728
8077
|
if (worldPath) {
|
|
6729
8078
|
try {
|
|
6730
|
-
const { existsSync:
|
|
6731
|
-
const { join:
|
|
6732
|
-
const hasWorld =
|
|
8079
|
+
const { existsSync: existsSync5 } = await import("fs");
|
|
8080
|
+
const { join: join8 } = await import("path");
|
|
8081
|
+
const hasWorld = existsSync5(join8(worldPath, "world.json"));
|
|
6733
8082
|
checks.push({
|
|
6734
8083
|
label: "World file detected",
|
|
6735
8084
|
status: hasWorld ? "pass" : "fail",
|
|
@@ -6744,12 +8093,12 @@ async function main11(argv) {
|
|
|
6744
8093
|
});
|
|
6745
8094
|
}
|
|
6746
8095
|
} else {
|
|
6747
|
-
const { existsSync:
|
|
6748
|
-
const { join:
|
|
8096
|
+
const { existsSync: existsSync5 } = await import("fs");
|
|
8097
|
+
const { join: join8 } = await import("path");
|
|
6749
8098
|
const candidates = ["./world", "./.neuroverse", "./worlds"];
|
|
6750
8099
|
let found;
|
|
6751
8100
|
for (const dir of candidates) {
|
|
6752
|
-
if (
|
|
8101
|
+
if (existsSync5(join8(dir, "world.json"))) {
|
|
6753
8102
|
found = dir;
|
|
6754
8103
|
break;
|
|
6755
8104
|
}
|
|
@@ -6841,7 +8190,7 @@ var init_doctor = __esm({
|
|
|
6841
8190
|
// src/cli/playground.ts
|
|
6842
8191
|
var playground_exports = {};
|
|
6843
8192
|
__export(playground_exports, {
|
|
6844
|
-
main: () =>
|
|
8193
|
+
main: () => main14
|
|
6845
8194
|
});
|
|
6846
8195
|
function buildPlaygroundHtml(world, healthSummary) {
|
|
6847
8196
|
const worldName = world.world.name;
|
|
@@ -7267,7 +8616,7 @@ function esc(s) {
|
|
|
7267
8616
|
function esc(s) {
|
|
7268
8617
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
7269
8618
|
}
|
|
7270
|
-
function
|
|
8619
|
+
function parseArgs13(argv) {
|
|
7271
8620
|
let worldPath;
|
|
7272
8621
|
let port = 4242;
|
|
7273
8622
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -7277,8 +8626,8 @@ function parseArgs11(argv) {
|
|
|
7277
8626
|
}
|
|
7278
8627
|
return { worldPath, port };
|
|
7279
8628
|
}
|
|
7280
|
-
async function
|
|
7281
|
-
const args =
|
|
8629
|
+
async function main14(argv) {
|
|
8630
|
+
const args = parseArgs13(argv);
|
|
7282
8631
|
if (!args.worldPath) {
|
|
7283
8632
|
process.stderr.write("Usage: neuroverse playground --world <dir> [--port N]\n");
|
|
7284
8633
|
process.exit(1);
|
|
@@ -7561,23 +8910,12 @@ var init_plan_contract = __esm({
|
|
|
7561
8910
|
// src/cli/plan.ts
|
|
7562
8911
|
var plan_exports = {};
|
|
7563
8912
|
__export(plan_exports, {
|
|
7564
|
-
main: () =>
|
|
8913
|
+
main: () => main15
|
|
7565
8914
|
});
|
|
7566
8915
|
function parseArg(args, flag) {
|
|
7567
8916
|
const idx = args.indexOf(flag);
|
|
7568
8917
|
return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : void 0;
|
|
7569
8918
|
}
|
|
7570
|
-
function readStdin2() {
|
|
7571
|
-
return new Promise((resolve3, reject) => {
|
|
7572
|
-
let data = "";
|
|
7573
|
-
process.stdin.setEncoding("utf-8");
|
|
7574
|
-
process.stdin.on("data", (chunk) => {
|
|
7575
|
-
data += chunk;
|
|
7576
|
-
});
|
|
7577
|
-
process.stdin.on("end", () => resolve3(data));
|
|
7578
|
-
process.stdin.on("error", reject);
|
|
7579
|
-
});
|
|
7580
|
-
}
|
|
7581
8919
|
async function compileCommand(args) {
|
|
7582
8920
|
const inputPath = args.find((a) => !a.startsWith("--"));
|
|
7583
8921
|
if (!inputPath) {
|
|
@@ -7588,7 +8926,7 @@ async function compileCommand(args) {
|
|
|
7588
8926
|
const outputPath = parseArg(args, "--output") ?? inputPath.replace(/\.md$/, ".json");
|
|
7589
8927
|
let markdown;
|
|
7590
8928
|
try {
|
|
7591
|
-
markdown = (0,
|
|
8929
|
+
markdown = (0, import_fs4.readFileSync)(inputPath, "utf-8");
|
|
7592
8930
|
} catch (err) {
|
|
7593
8931
|
process.stderr.write(`Error reading ${inputPath}: ${err}
|
|
7594
8932
|
`);
|
|
@@ -7606,7 +8944,7 @@ async function compileCommand(args) {
|
|
|
7606
8944
|
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
7607
8945
|
return;
|
|
7608
8946
|
}
|
|
7609
|
-
(0,
|
|
8947
|
+
(0, import_fs4.writeFileSync)(outputPath, JSON.stringify(result.plan, null, 2) + "\n");
|
|
7610
8948
|
const plan = result.plan;
|
|
7611
8949
|
process.stdout.write(`Plan compiled: ${plan.plan_id}
|
|
7612
8950
|
`);
|
|
@@ -7637,14 +8975,14 @@ async function checkCommand(args) {
|
|
|
7637
8975
|
}
|
|
7638
8976
|
let plan;
|
|
7639
8977
|
try {
|
|
7640
|
-
plan = JSON.parse((0,
|
|
8978
|
+
plan = JSON.parse((0, import_fs4.readFileSync)(planPath, "utf-8"));
|
|
7641
8979
|
} catch (err) {
|
|
7642
8980
|
process.stderr.write(`Error reading plan: ${err}
|
|
7643
8981
|
`);
|
|
7644
8982
|
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
7645
8983
|
return;
|
|
7646
8984
|
}
|
|
7647
|
-
const stdinData = await
|
|
8985
|
+
const stdinData = await readStdin();
|
|
7648
8986
|
let event;
|
|
7649
8987
|
try {
|
|
7650
8988
|
event = JSON.parse(stdinData);
|
|
@@ -7683,7 +9021,7 @@ async function statusCommand(args) {
|
|
|
7683
9021
|
}
|
|
7684
9022
|
let plan;
|
|
7685
9023
|
try {
|
|
7686
|
-
plan = JSON.parse((0,
|
|
9024
|
+
plan = JSON.parse((0, import_fs4.readFileSync)(planPath, "utf-8"));
|
|
7687
9025
|
} catch (err) {
|
|
7688
9026
|
process.stderr.write(`Error reading plan: ${err}
|
|
7689
9027
|
`);
|
|
@@ -7730,7 +9068,7 @@ async function advanceCommand(args) {
|
|
|
7730
9068
|
}
|
|
7731
9069
|
let plan;
|
|
7732
9070
|
try {
|
|
7733
|
-
plan = JSON.parse((0,
|
|
9071
|
+
plan = JSON.parse((0, import_fs4.readFileSync)(planPath, "utf-8"));
|
|
7734
9072
|
} catch (err) {
|
|
7735
9073
|
process.stderr.write(`Error reading plan: ${err}
|
|
7736
9074
|
`);
|
|
@@ -7758,7 +9096,7 @@ async function advanceCommand(args) {
|
|
|
7758
9096
|
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
7759
9097
|
return;
|
|
7760
9098
|
}
|
|
7761
|
-
(0,
|
|
9099
|
+
(0, import_fs4.writeFileSync)(planPath, JSON.stringify(result.plan, null, 2) + "\n");
|
|
7762
9100
|
const progress = getPlanProgress(result.plan);
|
|
7763
9101
|
const step = plan.steps.find((s) => s.id === stepId);
|
|
7764
9102
|
process.stdout.write(`Step completed: ${step.label}
|
|
@@ -7785,7 +9123,7 @@ async function deriveCommand(args) {
|
|
|
7785
9123
|
const outputDir = parseArg(args, "--output") ?? "./derived-world/";
|
|
7786
9124
|
let markdown;
|
|
7787
9125
|
try {
|
|
7788
|
-
markdown = (0,
|
|
9126
|
+
markdown = (0, import_fs4.readFileSync)(inputPath, "utf-8");
|
|
7789
9127
|
} catch (err) {
|
|
7790
9128
|
process.stderr.write(`Error reading ${inputPath}: ${err}
|
|
7791
9129
|
`);
|
|
@@ -7848,9 +9186,9 @@ async function deriveCommand(args) {
|
|
|
7848
9186
|
description: step.label
|
|
7849
9187
|
};
|
|
7850
9188
|
}
|
|
7851
|
-
(0,
|
|
7852
|
-
(0,
|
|
7853
|
-
(0,
|
|
9189
|
+
(0, import_fs4.writeFileSync)(`${outputDir}/world.json`, JSON.stringify(worldJson, null, 2) + "\n");
|
|
9190
|
+
(0, import_fs4.writeFileSync)(`${outputDir}/invariants.json`, JSON.stringify(invariants, null, 2) + "\n");
|
|
9191
|
+
(0, import_fs4.writeFileSync)(`${outputDir}/guards.json`, JSON.stringify(guards, null, 2) + "\n");
|
|
7854
9192
|
process.stdout.write(`World derived from plan: ${plan.plan_id}
|
|
7855
9193
|
`);
|
|
7856
9194
|
process.stdout.write(` Output: ${outputDir}
|
|
@@ -7862,7 +9200,7 @@ async function deriveCommand(args) {
|
|
|
7862
9200
|
process.stdout.write(` Invariants: ${plan.constraints.length} (one per constraint)
|
|
7863
9201
|
`);
|
|
7864
9202
|
}
|
|
7865
|
-
async function
|
|
9203
|
+
async function main15(args) {
|
|
7866
9204
|
const subcommand = args[0];
|
|
7867
9205
|
const subArgs = args.slice(1);
|
|
7868
9206
|
switch (subcommand) {
|
|
@@ -7891,14 +9229,15 @@ async function main13(args) {
|
|
|
7891
9229
|
process.exit(1);
|
|
7892
9230
|
}
|
|
7893
9231
|
}
|
|
7894
|
-
var
|
|
9232
|
+
var import_fs4, PLAN_USAGE;
|
|
7895
9233
|
var init_plan = __esm({
|
|
7896
9234
|
"src/cli/plan.ts"() {
|
|
7897
9235
|
"use strict";
|
|
7898
|
-
|
|
9236
|
+
import_fs4 = require("fs");
|
|
7899
9237
|
init_plan_parser();
|
|
7900
9238
|
init_plan_engine();
|
|
7901
9239
|
init_plan_contract();
|
|
9240
|
+
init_cli_utils();
|
|
7902
9241
|
PLAN_USAGE = `
|
|
7903
9242
|
neuroverse plan \u2014 Plan enforcement for AI agents.
|
|
7904
9243
|
|
|
@@ -8056,6 +9395,329 @@ Do not attempt to bypass governance rules.`;
|
|
|
8056
9395
|
}
|
|
8057
9396
|
});
|
|
8058
9397
|
|
|
9398
|
+
// src/engine/decision-flow-engine.ts
|
|
9399
|
+
function generateDecisionFlow(events) {
|
|
9400
|
+
if (events.length === 0) {
|
|
9401
|
+
return emptyFlow();
|
|
9402
|
+
}
|
|
9403
|
+
const intentMap = /* @__PURE__ */ new Map();
|
|
9404
|
+
for (const e of events) {
|
|
9405
|
+
const intentKey = normalizeIntent(e.intent);
|
|
9406
|
+
const entry = intentMap.get(intentKey) ?? { agents: /* @__PURE__ */ new Set(), count: 0 };
|
|
9407
|
+
entry.count++;
|
|
9408
|
+
entry.agents.add(e.actor ?? "unknown");
|
|
9409
|
+
intentMap.set(intentKey, entry);
|
|
9410
|
+
}
|
|
9411
|
+
const maxCount = Math.max(...[...intentMap.values()].map((v) => v.count), 1);
|
|
9412
|
+
const intents = [...intentMap.entries()].map(([intent, data]) => ({
|
|
9413
|
+
intent,
|
|
9414
|
+
agentCount: data.count,
|
|
9415
|
+
intensity: data.count / maxCount,
|
|
9416
|
+
agents: [...data.agents]
|
|
9417
|
+
})).sort((a, b) => b.agentCount - a.agentCount);
|
|
9418
|
+
const ruleMap = /* @__PURE__ */ new Map();
|
|
9419
|
+
for (const e of events) {
|
|
9420
|
+
if (!e.ruleId && e.guardsMatched.length === 0) continue;
|
|
9421
|
+
const ruleIds = [e.ruleId, ...e.guardsMatched].filter(Boolean);
|
|
9422
|
+
for (const rId of new Set(ruleIds)) {
|
|
9423
|
+
const existing = ruleMap.get(rId) ?? {
|
|
9424
|
+
ruleId: rId,
|
|
9425
|
+
label: rId,
|
|
9426
|
+
interceptCount: 0,
|
|
9427
|
+
enforcements: { blocked: 0, modified: 0, penalized: 0, paused: 0, rewarded: 0 }
|
|
9428
|
+
};
|
|
9429
|
+
existing.interceptCount++;
|
|
9430
|
+
switch (e.decision) {
|
|
9431
|
+
case "BLOCK":
|
|
9432
|
+
existing.enforcements.blocked++;
|
|
9433
|
+
break;
|
|
9434
|
+
case "PAUSE":
|
|
9435
|
+
existing.enforcements.paused++;
|
|
9436
|
+
break;
|
|
9437
|
+
case "MODIFY":
|
|
9438
|
+
existing.enforcements.modified++;
|
|
9439
|
+
break;
|
|
9440
|
+
case "PENALIZE":
|
|
9441
|
+
existing.enforcements.penalized++;
|
|
9442
|
+
break;
|
|
9443
|
+
case "REWARD":
|
|
9444
|
+
existing.enforcements.rewarded++;
|
|
9445
|
+
break;
|
|
9446
|
+
}
|
|
9447
|
+
ruleMap.set(rId, existing);
|
|
9448
|
+
}
|
|
9449
|
+
}
|
|
9450
|
+
const rules = [...ruleMap.values()].sort((a, b) => b.interceptCount - a.interceptCount);
|
|
9451
|
+
const outcomeMap = /* @__PURE__ */ new Map();
|
|
9452
|
+
for (const e of events) {
|
|
9453
|
+
const key = e.decision;
|
|
9454
|
+
const entry = outcomeMap.get(key) ?? { agents: /* @__PURE__ */ new Set(), count: 0 };
|
|
9455
|
+
entry.count++;
|
|
9456
|
+
entry.agents.add(e.actor ?? "unknown");
|
|
9457
|
+
outcomeMap.set(key, entry);
|
|
9458
|
+
}
|
|
9459
|
+
const outcomes = [...outcomeMap.entries()].map(([enforcement, data]) => ({
|
|
9460
|
+
enforcement,
|
|
9461
|
+
agentCount: data.count,
|
|
9462
|
+
agents: [...data.agents],
|
|
9463
|
+
style: enforcementToStyle(enforcement)
|
|
9464
|
+
})).sort((a, b) => b.agentCount - a.agentCount);
|
|
9465
|
+
const paths = events.map((e) => ({
|
|
9466
|
+
intent: normalizeIntent(e.intent),
|
|
9467
|
+
ruleId: e.ruleId ?? e.guardsMatched[0],
|
|
9468
|
+
enforcement: e.decision,
|
|
9469
|
+
agentId: e.actor ?? "unknown",
|
|
9470
|
+
originalAction: e.intent,
|
|
9471
|
+
finalAction: e.decision === "ALLOW" ? e.intent : e.decision === "BLOCK" ? "blocked" : e.decision === "PENALIZE" ? "blocked + penalized" : e.decision === "REWARD" ? e.intent + " (rewarded)" : e.decision === "MODIFY" ? "modified" : e.decision === "NEUTRAL" ? e.intent : "paused"
|
|
9472
|
+
}));
|
|
9473
|
+
const totalIntents = events.length;
|
|
9474
|
+
const allowed = events.filter((e) => e.decision === "ALLOW" || e.decision === "REWARD" || e.decision === "NEUTRAL").length;
|
|
9475
|
+
const totalRedirected = totalIntents - allowed;
|
|
9476
|
+
const totalPenalties = events.filter((e) => e.decision === "PENALIZE").length;
|
|
9477
|
+
const totalRewards = events.filter((e) => e.decision === "REWARD").length;
|
|
9478
|
+
const byEnforcement = {};
|
|
9479
|
+
for (const e of events) {
|
|
9480
|
+
byEnforcement[e.decision] = (byEnforcement[e.decision] ?? 0) + 1;
|
|
9481
|
+
}
|
|
9482
|
+
const metrics = {
|
|
9483
|
+
totalIntents,
|
|
9484
|
+
totalRedirected,
|
|
9485
|
+
redirectionRate: totalIntents > 0 ? totalRedirected / totalIntents : 0,
|
|
9486
|
+
byEnforcement,
|
|
9487
|
+
totalPenalties,
|
|
9488
|
+
totalRewards,
|
|
9489
|
+
netBehavioralPressure: totalRewards - totalPenalties
|
|
9490
|
+
};
|
|
9491
|
+
return {
|
|
9492
|
+
intents,
|
|
9493
|
+
rules,
|
|
9494
|
+
outcomes,
|
|
9495
|
+
paths,
|
|
9496
|
+
metrics,
|
|
9497
|
+
periodStart: events[0]?.timestamp ?? "",
|
|
9498
|
+
periodEnd: events[events.length - 1]?.timestamp ?? "",
|
|
9499
|
+
worldName: events[0]?.worldName ?? "unknown"
|
|
9500
|
+
};
|
|
9501
|
+
}
|
|
9502
|
+
function createAgentState(agentId) {
|
|
9503
|
+
return {
|
|
9504
|
+
agentId,
|
|
9505
|
+
cooldownRemaining: 0,
|
|
9506
|
+
influence: 1,
|
|
9507
|
+
rewardMultiplier: 1,
|
|
9508
|
+
totalPenalties: 0,
|
|
9509
|
+
totalRewards: 0,
|
|
9510
|
+
consequenceHistory: [],
|
|
9511
|
+
rewardHistory: []
|
|
9512
|
+
};
|
|
9513
|
+
}
|
|
9514
|
+
function applyConsequence(state, consequence, ruleId) {
|
|
9515
|
+
const updated = { ...state };
|
|
9516
|
+
updated.totalPenalties++;
|
|
9517
|
+
updated.consequenceHistory = [
|
|
9518
|
+
...state.consequenceHistory,
|
|
9519
|
+
{ ruleId, consequence, appliedAt: Date.now() }
|
|
9520
|
+
];
|
|
9521
|
+
switch (consequence.type) {
|
|
9522
|
+
case "freeze":
|
|
9523
|
+
case "cooldown":
|
|
9524
|
+
updated.cooldownRemaining = Math.max(
|
|
9525
|
+
state.cooldownRemaining,
|
|
9526
|
+
consequence.rounds ?? 1
|
|
9527
|
+
);
|
|
9528
|
+
break;
|
|
9529
|
+
case "reduce_influence":
|
|
9530
|
+
updated.influence = Math.max(0, state.influence - (consequence.magnitude ?? 0.1));
|
|
9531
|
+
break;
|
|
9532
|
+
case "increase_risk":
|
|
9533
|
+
break;
|
|
9534
|
+
case "custom":
|
|
9535
|
+
break;
|
|
9536
|
+
}
|
|
9537
|
+
return updated;
|
|
9538
|
+
}
|
|
9539
|
+
function applyReward(state, reward, ruleId) {
|
|
9540
|
+
const updated = { ...state };
|
|
9541
|
+
updated.totalRewards++;
|
|
9542
|
+
updated.rewardHistory = [
|
|
9543
|
+
...state.rewardHistory,
|
|
9544
|
+
{ ruleId, reward, appliedAt: Date.now() }
|
|
9545
|
+
];
|
|
9546
|
+
switch (reward.type) {
|
|
9547
|
+
case "boost_influence":
|
|
9548
|
+
updated.influence = Math.min(2, state.influence + (reward.magnitude ?? 0.1));
|
|
9549
|
+
break;
|
|
9550
|
+
case "weight_increase":
|
|
9551
|
+
updated.rewardMultiplier = Math.min(3, state.rewardMultiplier + (reward.magnitude ?? 0.1));
|
|
9552
|
+
break;
|
|
9553
|
+
case "priority":
|
|
9554
|
+
case "faster_execution":
|
|
9555
|
+
break;
|
|
9556
|
+
case "custom":
|
|
9557
|
+
break;
|
|
9558
|
+
}
|
|
9559
|
+
return updated;
|
|
9560
|
+
}
|
|
9561
|
+
function tickAgentStates(states) {
|
|
9562
|
+
const updated = /* @__PURE__ */ new Map();
|
|
9563
|
+
for (const [id, state] of states) {
|
|
9564
|
+
updated.set(id, {
|
|
9565
|
+
...state,
|
|
9566
|
+
cooldownRemaining: Math.max(0, state.cooldownRemaining - 1)
|
|
9567
|
+
});
|
|
9568
|
+
}
|
|
9569
|
+
return updated;
|
|
9570
|
+
}
|
|
9571
|
+
function renderDecisionFlow(flow) {
|
|
9572
|
+
const lines = [];
|
|
9573
|
+
lines.push("DECISION FLOW \u2014 Intent \u2192 Rule \u2192 Outcome");
|
|
9574
|
+
lines.push("\u2550".repeat(60));
|
|
9575
|
+
lines.push("");
|
|
9576
|
+
lines.push(` World: ${flow.worldName}`);
|
|
9577
|
+
lines.push(` Period: ${flow.periodStart.split("T")[0] ?? "\u2014"} \u2192 ${flow.periodEnd.split("T")[0] ?? "\u2014"}`);
|
|
9578
|
+
lines.push("");
|
|
9579
|
+
lines.push(` "${(flow.metrics.redirectionRate * 100).toFixed(1)}% of agent intent was redirected by governance"`);
|
|
9580
|
+
lines.push("");
|
|
9581
|
+
lines.push("INTENT POOL (what agents wanted)");
|
|
9582
|
+
lines.push("\u2500".repeat(60));
|
|
9583
|
+
for (const cluster of flow.intents.slice(0, 15)) {
|
|
9584
|
+
const bar = "\u2588".repeat(Math.max(1, Math.round(cluster.intensity * 20)));
|
|
9585
|
+
lines.push(` ${cluster.intent.padEnd(25)} ${String(cluster.agentCount).padStart(5)} agents ${bar}`);
|
|
9586
|
+
}
|
|
9587
|
+
lines.push("");
|
|
9588
|
+
lines.push("RULE OBSTACLES (what intercepted)");
|
|
9589
|
+
lines.push("\u2500".repeat(60));
|
|
9590
|
+
for (const rule of flow.rules.slice(0, 10)) {
|
|
9591
|
+
const parts = [];
|
|
9592
|
+
if (rule.enforcements.blocked > 0) parts.push(`${rule.enforcements.blocked} blocked`);
|
|
9593
|
+
if (rule.enforcements.modified > 0) parts.push(`${rule.enforcements.modified} modified`);
|
|
9594
|
+
if (rule.enforcements.penalized > 0) parts.push(`${rule.enforcements.penalized} penalized`);
|
|
9595
|
+
if (rule.enforcements.paused > 0) parts.push(`${rule.enforcements.paused} paused`);
|
|
9596
|
+
if (rule.enforcements.rewarded > 0) parts.push(`${rule.enforcements.rewarded} rewarded`);
|
|
9597
|
+
lines.push(` ${rule.ruleId.padEnd(30)} ${String(rule.interceptCount).padStart(5)} intercepts (${parts.join(", ")})`);
|
|
9598
|
+
}
|
|
9599
|
+
lines.push("");
|
|
9600
|
+
lines.push("OUTCOME POOL (what actually happened)");
|
|
9601
|
+
lines.push("\u2500".repeat(60));
|
|
9602
|
+
for (const outcome of flow.outcomes) {
|
|
9603
|
+
const icon = outcomeIcon(outcome.enforcement);
|
|
9604
|
+
lines.push(` ${icon} ${outcome.enforcement.padEnd(12)} ${String(outcome.agentCount).padStart(5)} agents`);
|
|
9605
|
+
}
|
|
9606
|
+
lines.push("");
|
|
9607
|
+
if (flow.metrics.totalPenalties > 0 || flow.metrics.totalRewards > 0) {
|
|
9608
|
+
lines.push("BEHAVIORAL ECONOMY");
|
|
9609
|
+
lines.push("\u2500".repeat(60));
|
|
9610
|
+
lines.push(` Penalties applied: ${flow.metrics.totalPenalties}`);
|
|
9611
|
+
lines.push(` Rewards applied: ${flow.metrics.totalRewards}`);
|
|
9612
|
+
lines.push(` Net behavioral pressure: ${flow.metrics.netBehavioralPressure > 0 ? "+" : ""}${flow.metrics.netBehavioralPressure}`);
|
|
9613
|
+
lines.push("");
|
|
9614
|
+
}
|
|
9615
|
+
lines.push("ENFORCEMENT BREAKDOWN");
|
|
9616
|
+
lines.push("\u2500".repeat(60));
|
|
9617
|
+
for (const [enforcement, count] of Object.entries(flow.metrics.byEnforcement)) {
|
|
9618
|
+
const pct = (count / flow.metrics.totalIntents * 100).toFixed(1);
|
|
9619
|
+
lines.push(` ${enforcement.padEnd(12)} ${String(count).padStart(5)} (${pct}%)`);
|
|
9620
|
+
}
|
|
9621
|
+
lines.push("");
|
|
9622
|
+
return lines.join("\n");
|
|
9623
|
+
}
|
|
9624
|
+
function normalizeIntent(intent) {
|
|
9625
|
+
const lower = intent.toLowerCase().trim();
|
|
9626
|
+
const verbs = [
|
|
9627
|
+
"sell",
|
|
9628
|
+
"buy",
|
|
9629
|
+
"trade",
|
|
9630
|
+
"publish",
|
|
9631
|
+
"delete",
|
|
9632
|
+
"create",
|
|
9633
|
+
"modify",
|
|
9634
|
+
"send",
|
|
9635
|
+
"withdraw",
|
|
9636
|
+
"transfer",
|
|
9637
|
+
"attack",
|
|
9638
|
+
"deploy",
|
|
9639
|
+
"execute",
|
|
9640
|
+
"read",
|
|
9641
|
+
"write",
|
|
9642
|
+
"hold",
|
|
9643
|
+
"stake",
|
|
9644
|
+
"approve",
|
|
9645
|
+
"reject",
|
|
9646
|
+
"escalate"
|
|
9647
|
+
];
|
|
9648
|
+
for (const verb of verbs) {
|
|
9649
|
+
if (lower.startsWith(verb) || lower.includes(verb)) {
|
|
9650
|
+
return verb;
|
|
9651
|
+
}
|
|
9652
|
+
}
|
|
9653
|
+
return lower.split(/\s+/)[0] ?? lower;
|
|
9654
|
+
}
|
|
9655
|
+
function enforcementToStyle(enforcement) {
|
|
9656
|
+
switch (enforcement) {
|
|
9657
|
+
case "ALLOW":
|
|
9658
|
+
return "green";
|
|
9659
|
+
case "MODIFY":
|
|
9660
|
+
return "yellow";
|
|
9661
|
+
case "BLOCK":
|
|
9662
|
+
return "red";
|
|
9663
|
+
case "PENALIZE":
|
|
9664
|
+
return "gray";
|
|
9665
|
+
case "REWARD":
|
|
9666
|
+
return "blue";
|
|
9667
|
+
case "NEUTRAL":
|
|
9668
|
+
return "white";
|
|
9669
|
+
case "PAUSE":
|
|
9670
|
+
return "yellow";
|
|
9671
|
+
default:
|
|
9672
|
+
return "white";
|
|
9673
|
+
}
|
|
9674
|
+
}
|
|
9675
|
+
function outcomeIcon(enforcement) {
|
|
9676
|
+
switch (enforcement) {
|
|
9677
|
+
case "ALLOW":
|
|
9678
|
+
return "\u25CF";
|
|
9679
|
+
case "MODIFY":
|
|
9680
|
+
return "\u25D0";
|
|
9681
|
+
case "BLOCK":
|
|
9682
|
+
return "\u25CB";
|
|
9683
|
+
case "PENALIZE":
|
|
9684
|
+
return "\u25CC";
|
|
9685
|
+
case "REWARD":
|
|
9686
|
+
return "\u25C9";
|
|
9687
|
+
case "NEUTRAL":
|
|
9688
|
+
return "\u25EF";
|
|
9689
|
+
case "PAUSE":
|
|
9690
|
+
return "\u25D1";
|
|
9691
|
+
default:
|
|
9692
|
+
return "\xB7";
|
|
9693
|
+
}
|
|
9694
|
+
}
|
|
9695
|
+
function emptyFlow() {
|
|
9696
|
+
return {
|
|
9697
|
+
intents: [],
|
|
9698
|
+
rules: [],
|
|
9699
|
+
outcomes: [],
|
|
9700
|
+
paths: [],
|
|
9701
|
+
metrics: {
|
|
9702
|
+
totalIntents: 0,
|
|
9703
|
+
totalRedirected: 0,
|
|
9704
|
+
redirectionRate: 0,
|
|
9705
|
+
byEnforcement: {},
|
|
9706
|
+
totalPenalties: 0,
|
|
9707
|
+
totalRewards: 0,
|
|
9708
|
+
netBehavioralPressure: 0
|
|
9709
|
+
},
|
|
9710
|
+
periodStart: "",
|
|
9711
|
+
periodEnd: "",
|
|
9712
|
+
worldName: "unknown"
|
|
9713
|
+
};
|
|
9714
|
+
}
|
|
9715
|
+
var init_decision_flow_engine = __esm({
|
|
9716
|
+
"src/engine/decision-flow-engine.ts"() {
|
|
9717
|
+
"use strict";
|
|
9718
|
+
}
|
|
9719
|
+
});
|
|
9720
|
+
|
|
8059
9721
|
// src/runtime/session.ts
|
|
8060
9722
|
var session_exports = {};
|
|
8061
9723
|
__export(session_exports, {
|
|
@@ -8078,7 +9740,7 @@ async function runPipeMode(config) {
|
|
|
8078
9740
|
process.stderr.write(`[neuroverse] Plan: ${state.plan.plan_id} (${state.plan.objective})
|
|
8079
9741
|
`);
|
|
8080
9742
|
}
|
|
8081
|
-
return new Promise((
|
|
9743
|
+
return new Promise((resolve5, reject) => {
|
|
8082
9744
|
let buffer = "";
|
|
8083
9745
|
process.stdin.setEncoding("utf-8");
|
|
8084
9746
|
process.stdin.on("data", (chunk) => {
|
|
@@ -8119,7 +9781,7 @@ async function runPipeMode(config) {
|
|
|
8119
9781
|
`[neuroverse] Session complete: ${finalState.actionsEvaluated} evaluated, ${finalState.actionsAllowed} allowed, ${finalState.actionsBlocked} blocked, ${finalState.actionsPaused} paused
|
|
8120
9782
|
`
|
|
8121
9783
|
);
|
|
8122
|
-
|
|
9784
|
+
resolve5();
|
|
8123
9785
|
});
|
|
8124
9786
|
process.stdin.on("error", reject);
|
|
8125
9787
|
});
|
|
@@ -8190,7 +9852,9 @@ async function runInteractiveMode(config, model) {
|
|
|
8190
9852
|
`);
|
|
8191
9853
|
process.stdout.write(` Actions: ${s.actionsEvaluated} evaluated
|
|
8192
9854
|
`);
|
|
8193
|
-
process.stdout.write(` Allowed: ${s.actionsAllowed} | Blocked: ${s.actionsBlocked} | Paused: ${s.actionsPaused}
|
|
9855
|
+
process.stdout.write(` Allowed: ${s.actionsAllowed} | Blocked: ${s.actionsBlocked} | Modified: ${s.actionsModified} | Paused: ${s.actionsPaused}
|
|
9856
|
+
`);
|
|
9857
|
+
process.stdout.write(` Penalized: ${s.actionsPenalized} | Rewarded: ${s.actionsRewarded}
|
|
8194
9858
|
`);
|
|
8195
9859
|
if (s.progress && s.plan) {
|
|
8196
9860
|
process.stdout.write(` Plan: ${s.plan.plan_id} \u2014 ${s.progress.completed}/${s.progress.total} (${s.progress.percentage}%)
|
|
@@ -8233,8 +9897,8 @@ ${response.content}
|
|
|
8233
9897
|
rl.on("close", () => {
|
|
8234
9898
|
session.stop();
|
|
8235
9899
|
});
|
|
8236
|
-
return new Promise((
|
|
8237
|
-
rl.on("close",
|
|
9900
|
+
return new Promise((resolve5) => {
|
|
9901
|
+
rl.on("close", resolve5);
|
|
8238
9902
|
});
|
|
8239
9903
|
}
|
|
8240
9904
|
var SessionManager;
|
|
@@ -8244,6 +9908,7 @@ var init_session = __esm({
|
|
|
8244
9908
|
init_guard_engine();
|
|
8245
9909
|
init_plan_engine();
|
|
8246
9910
|
init_world_loader();
|
|
9911
|
+
init_decision_flow_engine();
|
|
8247
9912
|
SessionManager = class {
|
|
8248
9913
|
config;
|
|
8249
9914
|
state;
|
|
@@ -8265,7 +9930,11 @@ var init_session = __esm({
|
|
|
8265
9930
|
actionsEvaluated: 0,
|
|
8266
9931
|
actionsAllowed: 0,
|
|
8267
9932
|
actionsBlocked: 0,
|
|
8268
|
-
actionsPaused: 0
|
|
9933
|
+
actionsPaused: 0,
|
|
9934
|
+
actionsModified: 0,
|
|
9935
|
+
actionsPenalized: 0,
|
|
9936
|
+
actionsRewarded: 0,
|
|
9937
|
+
agentStates: /* @__PURE__ */ new Map()
|
|
8269
9938
|
};
|
|
8270
9939
|
}
|
|
8271
9940
|
/**
|
|
@@ -8287,14 +9956,41 @@ var init_session = __esm({
|
|
|
8287
9956
|
*/
|
|
8288
9957
|
evaluate(event) {
|
|
8289
9958
|
this.engineOptions.plan = this.state.plan;
|
|
9959
|
+
this.engineOptions.agentStates = this.state.agentStates;
|
|
8290
9960
|
const verdict = evaluateGuard(event, this.state.world, this.engineOptions);
|
|
8291
9961
|
this.state.actionsEvaluated++;
|
|
8292
9962
|
if (verdict.status === "ALLOW") this.state.actionsAllowed++;
|
|
8293
9963
|
if (verdict.status === "BLOCK") this.state.actionsBlocked++;
|
|
8294
9964
|
if (verdict.status === "PAUSE") this.state.actionsPaused++;
|
|
9965
|
+
if (verdict.status === "MODIFY") this.state.actionsModified++;
|
|
9966
|
+
if (verdict.status === "PENALIZE") this.state.actionsPenalized++;
|
|
9967
|
+
if (verdict.status === "REWARD") this.state.actionsRewarded++;
|
|
9968
|
+
if (event.roleId) {
|
|
9969
|
+
let agentState = this.state.agentStates.get(event.roleId) ?? createAgentState(event.roleId);
|
|
9970
|
+
if (verdict.status === "PENALIZE" && verdict.consequence) {
|
|
9971
|
+
agentState = applyConsequence(agentState, verdict.consequence, verdict.ruleId ?? "unknown");
|
|
9972
|
+
}
|
|
9973
|
+
if (verdict.status === "REWARD" && verdict.reward) {
|
|
9974
|
+
agentState = applyReward(agentState, verdict.reward, verdict.ruleId ?? "unknown");
|
|
9975
|
+
}
|
|
9976
|
+
this.state.agentStates.set(event.roleId, agentState);
|
|
9977
|
+
}
|
|
8295
9978
|
this.config.onVerdict?.(verdict, event);
|
|
8296
9979
|
return verdict;
|
|
8297
9980
|
}
|
|
9981
|
+
/**
|
|
9982
|
+
* Advance all agent states by one round.
|
|
9983
|
+
* Call this at the end of each simulation round to decrement cooldowns.
|
|
9984
|
+
*/
|
|
9985
|
+
tickRound() {
|
|
9986
|
+
this.state.agentStates = tickAgentStates(this.state.agentStates);
|
|
9987
|
+
}
|
|
9988
|
+
/**
|
|
9989
|
+
* Get the behavior state for a specific agent.
|
|
9990
|
+
*/
|
|
9991
|
+
getAgentState(agentId) {
|
|
9992
|
+
return this.state.agentStates.get(agentId);
|
|
9993
|
+
}
|
|
8298
9994
|
/**
|
|
8299
9995
|
* Evaluate and execute a tool call.
|
|
8300
9996
|
* Returns the execution result or block reason.
|
|
@@ -8313,7 +10009,7 @@ var init_session = __esm({
|
|
|
8313
10009
|
direction: "input"
|
|
8314
10010
|
};
|
|
8315
10011
|
const verdict = this.evaluate(event);
|
|
8316
|
-
if (verdict.status === "BLOCK") {
|
|
10012
|
+
if (verdict.status === "BLOCK" || verdict.status === "PENALIZE") {
|
|
8317
10013
|
return { allowed: false, verdict };
|
|
8318
10014
|
}
|
|
8319
10015
|
if (verdict.status === "PAUSE") {
|
|
@@ -8381,7 +10077,7 @@ var init_session = __esm({
|
|
|
8381
10077
|
// src/cli/run.ts
|
|
8382
10078
|
var run_exports = {};
|
|
8383
10079
|
__export(run_exports, {
|
|
8384
|
-
main: () =>
|
|
10080
|
+
main: () => main16
|
|
8385
10081
|
});
|
|
8386
10082
|
function parseArg2(args, flag) {
|
|
8387
10083
|
const idx = args.indexOf(flag);
|
|
@@ -8392,11 +10088,11 @@ function hasFlag(args, flag) {
|
|
|
8392
10088
|
}
|
|
8393
10089
|
function autoDetectPlan() {
|
|
8394
10090
|
const nvDir = ".neuroverse/plans";
|
|
8395
|
-
if (!(0,
|
|
8396
|
-
const entries = (0,
|
|
10091
|
+
if (!(0, import_fs5.existsSync)(nvDir)) return void 0;
|
|
10092
|
+
const entries = (0, import_fs5.readdirSync)(nvDir).filter((e) => e.endsWith(".json"));
|
|
8397
10093
|
if (entries.length === 1) {
|
|
8398
10094
|
try {
|
|
8399
|
-
return JSON.parse((0,
|
|
10095
|
+
return JSON.parse((0, import_fs5.readFileSync)((0, import_path6.join)(nvDir, entries[0]), "utf-8"));
|
|
8400
10096
|
} catch {
|
|
8401
10097
|
return void 0;
|
|
8402
10098
|
}
|
|
@@ -8404,15 +10100,15 @@ function autoDetectPlan() {
|
|
|
8404
10100
|
return void 0;
|
|
8405
10101
|
}
|
|
8406
10102
|
function loadPlan(path) {
|
|
8407
|
-
return JSON.parse((0,
|
|
10103
|
+
return JSON.parse((0, import_fs5.readFileSync)(path, "utf-8"));
|
|
8408
10104
|
}
|
|
8409
|
-
async function
|
|
10105
|
+
async function main16(args) {
|
|
8410
10106
|
if (hasFlag(args, "--help") || hasFlag(args, "-h")) {
|
|
8411
10107
|
process.stdout.write(RUN_USAGE + "\n");
|
|
8412
10108
|
process.exit(0);
|
|
8413
10109
|
return;
|
|
8414
10110
|
}
|
|
8415
|
-
const worldPath =
|
|
10111
|
+
const worldPath = resolveWorldPath2(parseArg2(args, "--world"));
|
|
8416
10112
|
if (!worldPath) {
|
|
8417
10113
|
process.stderr.write(
|
|
8418
10114
|
"Error: No world found.\nUse --world <path>, set NEUROVERSE_WORLD, or run `neuroverse world use <name>`\n"
|
|
@@ -8488,12 +10184,12 @@ async function main14(args) {
|
|
|
8488
10184
|
process.exit(0);
|
|
8489
10185
|
}
|
|
8490
10186
|
}
|
|
8491
|
-
var
|
|
10187
|
+
var import_fs5, import_path6, RUN_USAGE;
|
|
8492
10188
|
var init_run = __esm({
|
|
8493
10189
|
"src/cli/run.ts"() {
|
|
8494
10190
|
"use strict";
|
|
8495
|
-
|
|
8496
|
-
|
|
10191
|
+
import_fs5 = require("fs");
|
|
10192
|
+
import_path6 = require("path");
|
|
8497
10193
|
init_world_resolver();
|
|
8498
10194
|
RUN_USAGE = `
|
|
8499
10195
|
neuroverse run \u2014 Governed runtime for AI agents.
|
|
@@ -8545,20 +10241,20 @@ ${err.stderr ?? ""}`;
|
|
|
8545
10241
|
}
|
|
8546
10242
|
}
|
|
8547
10243
|
function executeReadFile(path, workingDir) {
|
|
8548
|
-
const fullPath = (0,
|
|
8549
|
-
return (0,
|
|
10244
|
+
const fullPath = (0, import_path7.resolve)(workingDir ?? ".", path);
|
|
10245
|
+
return (0, import_fs6.readFileSync)(fullPath, "utf-8");
|
|
8550
10246
|
}
|
|
8551
10247
|
function executeWriteFile(path, content, workingDir) {
|
|
8552
|
-
const fullPath = (0,
|
|
8553
|
-
(0,
|
|
10248
|
+
const fullPath = (0, import_path7.resolve)(workingDir ?? ".", path);
|
|
10249
|
+
(0, import_fs6.writeFileSync)(fullPath, content);
|
|
8554
10250
|
return `File written: ${fullPath}`;
|
|
8555
10251
|
}
|
|
8556
10252
|
function executeListDir(path, workingDir) {
|
|
8557
|
-
const fullPath = (0,
|
|
8558
|
-
const entries = (0,
|
|
10253
|
+
const fullPath = (0, import_path7.resolve)(workingDir ?? ".", path);
|
|
10254
|
+
const entries = (0, import_fs6.readdirSync)(fullPath);
|
|
8559
10255
|
return entries.map((e) => {
|
|
8560
10256
|
try {
|
|
8561
|
-
const stat = (0,
|
|
10257
|
+
const stat = (0, import_fs6.statSync)((0, import_path7.join)(fullPath, e));
|
|
8562
10258
|
return `${stat.isDirectory() ? "d" : "-"} ${e}`;
|
|
8563
10259
|
} catch {
|
|
8564
10260
|
return `? ${e}`;
|
|
@@ -8580,7 +10276,7 @@ async function startMcpServer(args) {
|
|
|
8580
10276
|
const idx = args.indexOf(flag);
|
|
8581
10277
|
return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : void 0;
|
|
8582
10278
|
}
|
|
8583
|
-
const worldPath =
|
|
10279
|
+
const worldPath = resolveWorldPath2(parseArg3("--world"));
|
|
8584
10280
|
const planPath = parseArg3("--plan");
|
|
8585
10281
|
const level = parseArg3("--level");
|
|
8586
10282
|
const trace = args.includes("--trace");
|
|
@@ -8609,7 +10305,7 @@ async function startMcpServer(args) {
|
|
|
8609
10305
|
});
|
|
8610
10306
|
await server.start();
|
|
8611
10307
|
}
|
|
8612
|
-
var import_child_process,
|
|
10308
|
+
var import_child_process, import_fs6, import_path7, GOVERNED_TOOLS, McpGovernanceServer;
|
|
8613
10309
|
var init_mcp_server = __esm({
|
|
8614
10310
|
"src/runtime/mcp-server.ts"() {
|
|
8615
10311
|
"use strict";
|
|
@@ -8618,8 +10314,8 @@ var init_mcp_server = __esm({
|
|
|
8618
10314
|
init_world_loader();
|
|
8619
10315
|
init_world_resolver();
|
|
8620
10316
|
import_child_process = require("child_process");
|
|
8621
|
-
|
|
8622
|
-
|
|
10317
|
+
import_fs6 = require("fs");
|
|
10318
|
+
import_path7 = require("path");
|
|
8623
10319
|
GOVERNED_TOOLS = [
|
|
8624
10320
|
{
|
|
8625
10321
|
name: "governed_shell",
|
|
@@ -8745,7 +10441,7 @@ var init_mcp_server = __esm({
|
|
|
8745
10441
|
throw new Error("No world provided");
|
|
8746
10442
|
}
|
|
8747
10443
|
if (this.config.planPath && !this.plan) {
|
|
8748
|
-
this.plan = JSON.parse((0,
|
|
10444
|
+
this.plan = JSON.parse((0, import_fs6.readFileSync)(this.config.planPath, "utf-8"));
|
|
8749
10445
|
this.engineOptions.plan = this.plan;
|
|
8750
10446
|
}
|
|
8751
10447
|
process.stderr.write(`[neuroverse-mcp] Server starting
|
|
@@ -9119,7 +10815,7 @@ Progress: ${progress.completed}/${progress.total} (${progress.percentage}%)`;
|
|
|
9119
10815
|
text += "\n\nPlan complete!";
|
|
9120
10816
|
}
|
|
9121
10817
|
if (this.config.planPath) {
|
|
9122
|
-
(0,
|
|
10818
|
+
(0, import_fs6.writeFileSync)(this.config.planPath, JSON.stringify(this.plan, null, 2) + "\n");
|
|
9123
10819
|
}
|
|
9124
10820
|
return { content: [{ type: "text", text }] };
|
|
9125
10821
|
}
|
|
@@ -9130,9 +10826,9 @@ Progress: ${progress.completed}/${progress.total} (${progress.percentage}%)`;
|
|
|
9130
10826
|
// src/cli/world.ts
|
|
9131
10827
|
var world_exports = {};
|
|
9132
10828
|
__export(world_exports, {
|
|
9133
|
-
main: () =>
|
|
10829
|
+
main: () => main17
|
|
9134
10830
|
});
|
|
9135
|
-
function
|
|
10831
|
+
function parseArgs14(argv) {
|
|
9136
10832
|
const subcommand = argv[0];
|
|
9137
10833
|
const paths = [];
|
|
9138
10834
|
const flags = {};
|
|
@@ -9273,28 +10969,28 @@ function computeWorldDiff(a, b) {
|
|
|
9273
10969
|
return { changes };
|
|
9274
10970
|
}
|
|
9275
10971
|
async function worldSnapshot(worldPath) {
|
|
9276
|
-
const { readdir, readFile: readFile3, mkdir: mkdir2, writeFile:
|
|
9277
|
-
const { join:
|
|
10972
|
+
const { readdir, readFile: readFile3, mkdir: mkdir2, writeFile: writeFile5 } = await import("fs/promises");
|
|
10973
|
+
const { join: join8 } = await import("path");
|
|
9278
10974
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
9279
|
-
const snapshotDir =
|
|
10975
|
+
const snapshotDir = join8(worldPath, ".snapshots", timestamp);
|
|
9280
10976
|
await mkdir2(snapshotDir, { recursive: true });
|
|
9281
10977
|
const files = await readdir(worldPath);
|
|
9282
10978
|
let copied = 0;
|
|
9283
10979
|
for (const file of files) {
|
|
9284
10980
|
if (file.endsWith(".json")) {
|
|
9285
|
-
const content = await readFile3(
|
|
9286
|
-
await
|
|
10981
|
+
const content = await readFile3(join8(worldPath, file), "utf-8");
|
|
10982
|
+
await writeFile5(join8(snapshotDir, file), content, "utf-8");
|
|
9287
10983
|
copied++;
|
|
9288
10984
|
}
|
|
9289
10985
|
}
|
|
9290
10986
|
try {
|
|
9291
|
-
const rulesDir =
|
|
10987
|
+
const rulesDir = join8(worldPath, "rules");
|
|
9292
10988
|
const ruleFiles = await readdir(rulesDir);
|
|
9293
|
-
await mkdir2(
|
|
10989
|
+
await mkdir2(join8(snapshotDir, "rules"), { recursive: true });
|
|
9294
10990
|
for (const file of ruleFiles) {
|
|
9295
10991
|
if (file.endsWith(".json")) {
|
|
9296
|
-
const content = await readFile3(
|
|
9297
|
-
await
|
|
10992
|
+
const content = await readFile3(join8(rulesDir, file), "utf-8");
|
|
10993
|
+
await writeFile5(join8(snapshotDir, "rules", file), content, "utf-8");
|
|
9298
10994
|
copied++;
|
|
9299
10995
|
}
|
|
9300
10996
|
}
|
|
@@ -9306,9 +11002,9 @@ async function worldSnapshot(worldPath) {
|
|
|
9306
11002
|
`);
|
|
9307
11003
|
}
|
|
9308
11004
|
async function worldRollback(worldPath) {
|
|
9309
|
-
const { readdir, readFile: readFile3, writeFile:
|
|
9310
|
-
const { join:
|
|
9311
|
-
const snapshotsDir =
|
|
11005
|
+
const { readdir, readFile: readFile3, writeFile: writeFile5, mkdir: mkdir2 } = await import("fs/promises");
|
|
11006
|
+
const { join: join8 } = await import("path");
|
|
11007
|
+
const snapshotsDir = join8(worldPath, ".snapshots");
|
|
9312
11008
|
let snapshots;
|
|
9313
11009
|
try {
|
|
9314
11010
|
snapshots = (await readdir(snapshotsDir)).sort();
|
|
@@ -9323,34 +11019,34 @@ async function worldRollback(worldPath) {
|
|
|
9323
11019
|
return;
|
|
9324
11020
|
}
|
|
9325
11021
|
const latest = snapshots[snapshots.length - 1];
|
|
9326
|
-
const snapshotDir =
|
|
11022
|
+
const snapshotDir = join8(snapshotsDir, latest);
|
|
9327
11023
|
const backupTimestamp = "pre-rollback-" + (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
|
|
9328
|
-
const backupDir =
|
|
11024
|
+
const backupDir = join8(snapshotsDir, backupTimestamp);
|
|
9329
11025
|
await mkdir2(backupDir, { recursive: true });
|
|
9330
11026
|
const currentFiles = await readdir(worldPath);
|
|
9331
11027
|
for (const file of currentFiles) {
|
|
9332
11028
|
if (file.endsWith(".json")) {
|
|
9333
|
-
const content = await readFile3(
|
|
9334
|
-
await
|
|
11029
|
+
const content = await readFile3(join8(worldPath, file), "utf-8");
|
|
11030
|
+
await writeFile5(join8(backupDir, file), content, "utf-8");
|
|
9335
11031
|
}
|
|
9336
11032
|
}
|
|
9337
11033
|
const snapshotFiles = await readdir(snapshotDir);
|
|
9338
11034
|
let restored = 0;
|
|
9339
11035
|
for (const file of snapshotFiles) {
|
|
9340
11036
|
if (file.endsWith(".json")) {
|
|
9341
|
-
const content = await readFile3(
|
|
9342
|
-
await
|
|
11037
|
+
const content = await readFile3(join8(snapshotDir, file), "utf-8");
|
|
11038
|
+
await writeFile5(join8(worldPath, file), content, "utf-8");
|
|
9343
11039
|
restored++;
|
|
9344
11040
|
}
|
|
9345
11041
|
}
|
|
9346
11042
|
try {
|
|
9347
|
-
const rulesDir =
|
|
11043
|
+
const rulesDir = join8(snapshotDir, "rules");
|
|
9348
11044
|
const ruleFiles = await readdir(rulesDir);
|
|
9349
|
-
await mkdir2(
|
|
11045
|
+
await mkdir2(join8(worldPath, "rules"), { recursive: true });
|
|
9350
11046
|
for (const file of ruleFiles) {
|
|
9351
11047
|
if (file.endsWith(".json")) {
|
|
9352
|
-
const content = await readFile3(
|
|
9353
|
-
await
|
|
11048
|
+
const content = await readFile3(join8(rulesDir, file), "utf-8");
|
|
11049
|
+
await writeFile5(join8(worldPath, "rules", file), content, "utf-8");
|
|
9354
11050
|
restored++;
|
|
9355
11051
|
}
|
|
9356
11052
|
}
|
|
@@ -9412,8 +11108,8 @@ function worldCurrent(json) {
|
|
|
9412
11108
|
process.stdout.write(`Source: ${info.source}
|
|
9413
11109
|
`);
|
|
9414
11110
|
}
|
|
9415
|
-
async function
|
|
9416
|
-
const { subcommand, paths, flags } =
|
|
11111
|
+
async function main17(argv = process.argv.slice(2)) {
|
|
11112
|
+
const { subcommand, paths, flags } = parseArgs14(argv);
|
|
9417
11113
|
if (flags.help || !subcommand) {
|
|
9418
11114
|
process.stdout.write(USAGE + "\n");
|
|
9419
11115
|
process.exit(0);
|
|
@@ -9435,7 +11131,7 @@ async function main15(argv = process.argv.slice(2)) {
|
|
|
9435
11131
|
}
|
|
9436
11132
|
case "status": {
|
|
9437
11133
|
const ref = paths[0];
|
|
9438
|
-
const resolved = ref ?
|
|
11134
|
+
const resolved = ref ? resolveWorldPath2(ref) : resolveWorldPath2();
|
|
9439
11135
|
if (!resolved) {
|
|
9440
11136
|
process.stderr.write("Usage: neuroverse world status <path|name>\n");
|
|
9441
11137
|
process.stderr.write("Or set an active world: neuroverse world use <name>\n");
|
|
@@ -9502,6 +11198,41 @@ Options:
|
|
|
9502
11198
|
});
|
|
9503
11199
|
|
|
9504
11200
|
// src/engine/audit-logger.ts
|
|
11201
|
+
function verdictToAuditEvent(event, verdict) {
|
|
11202
|
+
const auditEvent = {
|
|
11203
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
11204
|
+
worldId: verdict.evidence.worldId,
|
|
11205
|
+
worldName: verdict.evidence.worldName,
|
|
11206
|
+
worldVersion: verdict.evidence.worldVersion,
|
|
11207
|
+
intent: event.intent,
|
|
11208
|
+
tool: event.tool,
|
|
11209
|
+
scope: event.scope,
|
|
11210
|
+
actor: event.roleId,
|
|
11211
|
+
direction: event.direction,
|
|
11212
|
+
decision: verdict.status,
|
|
11213
|
+
reason: verdict.reason,
|
|
11214
|
+
ruleId: verdict.ruleId,
|
|
11215
|
+
warning: verdict.warning,
|
|
11216
|
+
guardsMatched: verdict.evidence.guardsMatched,
|
|
11217
|
+
rulesMatched: verdict.evidence.rulesMatched,
|
|
11218
|
+
invariantsSatisfied: verdict.evidence.invariantsSatisfied,
|
|
11219
|
+
invariantsTotal: verdict.evidence.invariantsTotal,
|
|
11220
|
+
enforcementLevel: verdict.evidence.enforcementLevel,
|
|
11221
|
+
durationMs: verdict.trace?.durationMs,
|
|
11222
|
+
args: event.args
|
|
11223
|
+
};
|
|
11224
|
+
if (verdict.consequence) {
|
|
11225
|
+
auditEvent.consequence = verdict.consequence;
|
|
11226
|
+
}
|
|
11227
|
+
if (verdict.reward) {
|
|
11228
|
+
auditEvent.reward = verdict.reward;
|
|
11229
|
+
}
|
|
11230
|
+
if (verdict.intentRecord) {
|
|
11231
|
+
auditEvent.originalIntent = verdict.intentRecord.originalIntent;
|
|
11232
|
+
auditEvent.finalAction = verdict.intentRecord.finalAction;
|
|
11233
|
+
}
|
|
11234
|
+
return auditEvent;
|
|
11235
|
+
}
|
|
9505
11236
|
async function readAuditLog(logPath, filter) {
|
|
9506
11237
|
const { readFile: readFile3 } = await import("fs/promises");
|
|
9507
11238
|
let content;
|
|
@@ -9528,16 +11259,22 @@ function summarizeAuditEvents(events) {
|
|
|
9528
11259
|
const allowed = events.filter((e) => e.decision === "ALLOW").length;
|
|
9529
11260
|
const blocked = events.filter((e) => e.decision === "BLOCK").length;
|
|
9530
11261
|
const paused = events.filter((e) => e.decision === "PAUSE").length;
|
|
11262
|
+
const modified = events.filter((e) => e.decision === "MODIFY").length;
|
|
11263
|
+
const penalized = events.filter((e) => e.decision === "PENALIZE").length;
|
|
11264
|
+
const rewarded = events.filter((e) => e.decision === "REWARD").length;
|
|
11265
|
+
const neutral = events.filter((e) => e.decision === "NEUTRAL").length;
|
|
9531
11266
|
const actorSet = /* @__PURE__ */ new Set();
|
|
9532
11267
|
for (const e of events) {
|
|
9533
11268
|
if (e.actor) actorSet.add(e.actor);
|
|
9534
11269
|
}
|
|
9535
11270
|
const intentMap = /* @__PURE__ */ new Map();
|
|
9536
11271
|
for (const e of events) {
|
|
9537
|
-
const entry = intentMap.get(e.intent) ?? { count: 0, blocked: 0, paused: 0 };
|
|
11272
|
+
const entry = intentMap.get(e.intent) ?? { count: 0, blocked: 0, paused: 0, penalized: 0, rewarded: 0 };
|
|
9538
11273
|
entry.count++;
|
|
9539
11274
|
if (e.decision === "BLOCK") entry.blocked++;
|
|
9540
11275
|
if (e.decision === "PAUSE") entry.paused++;
|
|
11276
|
+
if (e.decision === "PENALIZE") entry.penalized++;
|
|
11277
|
+
if (e.decision === "REWARD") entry.rewarded++;
|
|
9541
11278
|
intentMap.set(e.intent, entry);
|
|
9542
11279
|
}
|
|
9543
11280
|
const topIntents = [...intentMap.entries()].map(([intent, data]) => ({ intent, ...data })).sort((a, b) => b.count - a.count);
|
|
@@ -9551,16 +11288,28 @@ function summarizeAuditEvents(events) {
|
|
|
9551
11288
|
}
|
|
9552
11289
|
}
|
|
9553
11290
|
const topRules = [...ruleMap.entries()].map(([ruleId, count]) => ({ ruleId, count })).sort((a, b) => b.count - a.count);
|
|
11291
|
+
const redirected = blocked + paused + modified + penalized;
|
|
11292
|
+
const total = events.length;
|
|
9554
11293
|
return {
|
|
9555
|
-
totalActions:
|
|
11294
|
+
totalActions: total,
|
|
9556
11295
|
allowed,
|
|
9557
11296
|
blocked,
|
|
9558
11297
|
paused,
|
|
11298
|
+
modified,
|
|
11299
|
+
penalized,
|
|
11300
|
+
rewarded,
|
|
11301
|
+
neutral,
|
|
9559
11302
|
actors: [...actorSet],
|
|
9560
11303
|
topIntents,
|
|
9561
11304
|
topRules,
|
|
9562
11305
|
firstEvent: events[0]?.timestamp ?? "",
|
|
9563
|
-
lastEvent: events[events.length - 1]?.timestamp ?? ""
|
|
11306
|
+
lastEvent: events[events.length - 1]?.timestamp ?? "",
|
|
11307
|
+
behavioralEconomy: {
|
|
11308
|
+
totalPenalties: penalized,
|
|
11309
|
+
totalRewards: rewarded,
|
|
11310
|
+
netPressure: rewarded - penalized,
|
|
11311
|
+
redirectionRate: total > 0 ? redirected / total : 0
|
|
11312
|
+
}
|
|
9564
11313
|
};
|
|
9565
11314
|
}
|
|
9566
11315
|
var init_audit_logger = __esm({
|
|
@@ -9573,9 +11322,9 @@ var init_audit_logger = __esm({
|
|
|
9573
11322
|
// src/cli/trace.ts
|
|
9574
11323
|
var trace_exports = {};
|
|
9575
11324
|
__export(trace_exports, {
|
|
9576
|
-
main: () =>
|
|
11325
|
+
main: () => main18
|
|
9577
11326
|
});
|
|
9578
|
-
function
|
|
11327
|
+
function parseArgs15(argv) {
|
|
9579
11328
|
const args = {};
|
|
9580
11329
|
for (let i = 0; i < argv.length; i++) {
|
|
9581
11330
|
const arg = argv[i];
|
|
@@ -9659,8 +11408,8 @@ function formatSummary(events) {
|
|
|
9659
11408
|
}
|
|
9660
11409
|
return lines.join("\n");
|
|
9661
11410
|
}
|
|
9662
|
-
async function
|
|
9663
|
-
const args =
|
|
11411
|
+
async function main18(argv = process.argv.slice(2)) {
|
|
11412
|
+
const args = parseArgs15(argv);
|
|
9664
11413
|
if (args.help) {
|
|
9665
11414
|
process.stdout.write(USAGE2 + "\n");
|
|
9666
11415
|
process.exit(0);
|
|
@@ -9744,7 +11493,11 @@ function generateImpactReport(events) {
|
|
|
9744
11493
|
}
|
|
9745
11494
|
const blocked = events.filter((e) => e.decision === "BLOCK");
|
|
9746
11495
|
const paused = events.filter((e) => e.decision === "PAUSE");
|
|
9747
|
-
const
|
|
11496
|
+
const modified = events.filter((e) => e.decision === "MODIFY");
|
|
11497
|
+
const penalized = events.filter((e) => e.decision === "PENALIZE");
|
|
11498
|
+
const rewarded = events.filter((e) => e.decision === "REWARD");
|
|
11499
|
+
const neutralEvents = events.filter((e) => e.decision === "NEUTRAL");
|
|
11500
|
+
const prevented = [...blocked, ...paused, ...modified, ...penalized];
|
|
9748
11501
|
const categoryMap = /* @__PURE__ */ new Map();
|
|
9749
11502
|
for (const e of prevented) {
|
|
9750
11503
|
const cat = classifyPreventionCategory(e);
|
|
@@ -9829,6 +11582,8 @@ function generateImpactReport(events) {
|
|
|
9829
11582
|
violationMap.set(key, entry);
|
|
9830
11583
|
}
|
|
9831
11584
|
const repeatViolations = [...violationMap.values()].filter((v) => v.attempts > 1).sort((a, b) => b.attempts - a.attempts).slice(0, 10);
|
|
11585
|
+
const allowedCount = events.filter((e) => e.decision === "ALLOW").length;
|
|
11586
|
+
const redirected = events.length - allowedCount - neutralEvents.length;
|
|
9832
11587
|
return {
|
|
9833
11588
|
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
9834
11589
|
periodStart: events[0].timestamp,
|
|
@@ -9837,8 +11592,13 @@ function generateImpactReport(events) {
|
|
|
9837
11592
|
totalEvaluations: events.length,
|
|
9838
11593
|
totalBlocked: blocked.length,
|
|
9839
11594
|
totalPaused: paused.length,
|
|
9840
|
-
totalAllowed:
|
|
9841
|
-
|
|
11595
|
+
totalAllowed: allowedCount,
|
|
11596
|
+
totalModified: modified.length,
|
|
11597
|
+
totalPenalized: penalized.length,
|
|
11598
|
+
totalRewarded: rewarded.length,
|
|
11599
|
+
totalNeutral: neutralEvents.length,
|
|
11600
|
+
preventionRate: events.length > 0 ? prevented.length / events.length : 0,
|
|
11601
|
+
redirectionRate: events.length > 0 ? redirected / events.length : 0,
|
|
9842
11602
|
preventedByCategory,
|
|
9843
11603
|
topPreventedIntents,
|
|
9844
11604
|
hotActors,
|
|
@@ -9877,8 +11637,13 @@ function renderImpactReport(report) {
|
|
|
9877
11637
|
lines.push(` Total evaluations: ${report.totalEvaluations}`);
|
|
9878
11638
|
lines.push(` Allowed: ${report.totalAllowed}`);
|
|
9879
11639
|
lines.push(` Blocked: ${report.totalBlocked}`);
|
|
11640
|
+
lines.push(` Modified: ${report.totalModified}`);
|
|
9880
11641
|
lines.push(` Paused: ${report.totalPaused}`);
|
|
11642
|
+
lines.push(` Penalized: ${report.totalPenalized}`);
|
|
11643
|
+
lines.push(` Rewarded: ${report.totalRewarded}`);
|
|
11644
|
+
lines.push(` Neutral: ${report.totalNeutral}`);
|
|
9881
11645
|
lines.push(` Prevention rate: ${(report.preventionRate * 100).toFixed(1)}%`);
|
|
11646
|
+
lines.push(` Redirection rate: ${(report.redirectionRate * 100).toFixed(1)}%`);
|
|
9882
11647
|
lines.push("");
|
|
9883
11648
|
if (report.totalBlocked > 0 || report.totalPaused > 0) {
|
|
9884
11649
|
lines.push("WITHOUT GOVERNANCE");
|
|
@@ -9939,7 +11704,12 @@ function emptyReport() {
|
|
|
9939
11704
|
totalBlocked: 0,
|
|
9940
11705
|
totalPaused: 0,
|
|
9941
11706
|
totalAllowed: 0,
|
|
11707
|
+
totalModified: 0,
|
|
11708
|
+
totalPenalized: 0,
|
|
11709
|
+
totalRewarded: 0,
|
|
11710
|
+
totalNeutral: 0,
|
|
9942
11711
|
preventionRate: 0,
|
|
11712
|
+
redirectionRate: 0,
|
|
9943
11713
|
preventedByCategory: [],
|
|
9944
11714
|
topPreventedIntents: [],
|
|
9945
11715
|
hotActors: [],
|
|
@@ -9958,9 +11728,9 @@ var init_impact_report = __esm({
|
|
|
9958
11728
|
// src/cli/impact.ts
|
|
9959
11729
|
var impact_exports = {};
|
|
9960
11730
|
__export(impact_exports, {
|
|
9961
|
-
main: () =>
|
|
11731
|
+
main: () => main19
|
|
9962
11732
|
});
|
|
9963
|
-
function
|
|
11733
|
+
function parseArgs16(argv) {
|
|
9964
11734
|
const args = {};
|
|
9965
11735
|
for (let i = 0; i < argv.length; i++) {
|
|
9966
11736
|
const arg = argv[i];
|
|
@@ -9970,8 +11740,8 @@ function parseArgs14(argv) {
|
|
|
9970
11740
|
}
|
|
9971
11741
|
return args;
|
|
9972
11742
|
}
|
|
9973
|
-
async function
|
|
9974
|
-
const args =
|
|
11743
|
+
async function main19(argv = process.argv.slice(2)) {
|
|
11744
|
+
const args = parseArgs16(argv);
|
|
9975
11745
|
if (args.help) {
|
|
9976
11746
|
process.stdout.write(USAGE3 + "\n");
|
|
9977
11747
|
process.exit(0);
|
|
@@ -10016,9 +11786,9 @@ repeat violations, and actor behavior patterns.
|
|
|
10016
11786
|
// src/cli/derive.ts
|
|
10017
11787
|
var derive_exports = {};
|
|
10018
11788
|
__export(derive_exports, {
|
|
10019
|
-
main: () =>
|
|
11789
|
+
main: () => main20
|
|
10020
11790
|
});
|
|
10021
|
-
function
|
|
11791
|
+
function parseArgs17(argv) {
|
|
10022
11792
|
let inputPath = "";
|
|
10023
11793
|
let outputPath = "./derived.nv-world.md";
|
|
10024
11794
|
let validate = true;
|
|
@@ -10052,9 +11822,9 @@ function parseArgs15(argv) {
|
|
|
10052
11822
|
if (!inputPath) throw new DeriveInputError("--input <path> is required");
|
|
10053
11823
|
return { inputPath, outputPath, validate, dryRun, bootstrapDir, provider, model, endpoint };
|
|
10054
11824
|
}
|
|
10055
|
-
async function
|
|
11825
|
+
async function main20(argv = process.argv.slice(2)) {
|
|
10056
11826
|
try {
|
|
10057
|
-
const args =
|
|
11827
|
+
const args = parseArgs17(argv);
|
|
10058
11828
|
const { result, exitCode, dryRunOutput } = await deriveWorld({
|
|
10059
11829
|
inputPath: args.inputPath,
|
|
10060
11830
|
outputPath: args.outputPath,
|
|
@@ -10161,12 +11931,307 @@ var init_derive = __esm({
|
|
|
10161
11931
|
}
|
|
10162
11932
|
});
|
|
10163
11933
|
|
|
11934
|
+
// src/cli/decision-flow.ts
|
|
11935
|
+
var decision_flow_exports = {};
|
|
11936
|
+
__export(decision_flow_exports, {
|
|
11937
|
+
main: () => main21
|
|
11938
|
+
});
|
|
11939
|
+
async function main21(args) {
|
|
11940
|
+
let logPath = ".neuroverse/audit.ndjson";
|
|
11941
|
+
let jsonOutput = false;
|
|
11942
|
+
for (let i = 0; i < args.length; i++) {
|
|
11943
|
+
if (args[i] === "--log" && args[i + 1]) {
|
|
11944
|
+
logPath = args[++i];
|
|
11945
|
+
}
|
|
11946
|
+
if (args[i] === "--json") {
|
|
11947
|
+
jsonOutput = true;
|
|
11948
|
+
}
|
|
11949
|
+
if (args[i] === "--help" || args[i] === "-h") {
|
|
11950
|
+
process.stdout.write(`
|
|
11951
|
+
neuroverse decision-flow \u2014 Visualize Intent \u2192 Rule \u2192 Outcome
|
|
11952
|
+
|
|
11953
|
+
Usage:
|
|
11954
|
+
neuroverse decision-flow [--log <path>] [--json]
|
|
11955
|
+
|
|
11956
|
+
Options:
|
|
11957
|
+
--log <path> Path to audit log (default: .neuroverse/audit.ndjson)
|
|
11958
|
+
--json Output as JSON instead of text
|
|
11959
|
+
|
|
11960
|
+
Shows:
|
|
11961
|
+
- What agents WANTED to do (Intent Pool)
|
|
11962
|
+
- What rules INTERCEPTED (Rule Obstacles)
|
|
11963
|
+
- What actually HAPPENED (Outcome Pool)
|
|
11964
|
+
- Behavioral economy (penalties vs rewards)
|
|
11965
|
+
|
|
11966
|
+
Headline metric: "X% of agent intent was redirected by governance"
|
|
11967
|
+
`.trim() + "\n");
|
|
11968
|
+
return;
|
|
11969
|
+
}
|
|
11970
|
+
}
|
|
11971
|
+
const events = await readAuditLog(logPath);
|
|
11972
|
+
if (events.length === 0) {
|
|
11973
|
+
process.stderr.write("No audit events found. Run governed actions first.\n");
|
|
11974
|
+
process.stderr.write(`Looking in: ${logPath}
|
|
11975
|
+
`);
|
|
11976
|
+
process.exit(1);
|
|
11977
|
+
}
|
|
11978
|
+
const flow = generateDecisionFlow(events);
|
|
11979
|
+
if (jsonOutput) {
|
|
11980
|
+
process.stdout.write(JSON.stringify(flow, null, 2) + "\n");
|
|
11981
|
+
} else {
|
|
11982
|
+
process.stdout.write(renderDecisionFlow(flow) + "\n");
|
|
11983
|
+
}
|
|
11984
|
+
}
|
|
11985
|
+
var init_decision_flow = __esm({
|
|
11986
|
+
"src/cli/decision-flow.ts"() {
|
|
11987
|
+
"use strict";
|
|
11988
|
+
init_audit_logger();
|
|
11989
|
+
init_decision_flow_engine();
|
|
11990
|
+
}
|
|
11991
|
+
});
|
|
11992
|
+
|
|
11993
|
+
// src/cli/equity-penalties.ts
|
|
11994
|
+
var equity_penalties_exports = {};
|
|
11995
|
+
__export(equity_penalties_exports, {
|
|
11996
|
+
main: () => main22
|
|
11997
|
+
});
|
|
11998
|
+
function generateActionsForRound(agents, round) {
|
|
11999
|
+
const actions = [];
|
|
12000
|
+
for (const agent of agents) {
|
|
12001
|
+
if (agent.strategy === "aggressive") {
|
|
12002
|
+
if (round % 2 === 0) {
|
|
12003
|
+
actions.push({
|
|
12004
|
+
intent: `sell Fortune 500 equity AAPL position for ${agent.name}`,
|
|
12005
|
+
tool: "trade",
|
|
12006
|
+
roleId: agent.id,
|
|
12007
|
+
actionCategory: "write"
|
|
12008
|
+
});
|
|
12009
|
+
} else {
|
|
12010
|
+
actions.push({
|
|
12011
|
+
intent: `sell Fortune 500 equity MSFT shares for ${agent.name}`,
|
|
12012
|
+
tool: "trade",
|
|
12013
|
+
roleId: agent.id,
|
|
12014
|
+
actionCategory: "write"
|
|
12015
|
+
});
|
|
12016
|
+
}
|
|
12017
|
+
}
|
|
12018
|
+
if (agent.strategy === "conservative") {
|
|
12019
|
+
actions.push({
|
|
12020
|
+
intent: `hold current position during market volatility for ${agent.name}`,
|
|
12021
|
+
tool: "trade",
|
|
12022
|
+
roleId: agent.id,
|
|
12023
|
+
actionCategory: "read"
|
|
12024
|
+
});
|
|
12025
|
+
}
|
|
12026
|
+
if (agent.strategy === "balanced") {
|
|
12027
|
+
if (round % 3 === 0) {
|
|
12028
|
+
actions.push({
|
|
12029
|
+
intent: `sell Fortune 500 equity GOOGL for ${agent.name}`,
|
|
12030
|
+
tool: "trade",
|
|
12031
|
+
roleId: agent.id,
|
|
12032
|
+
actionCategory: "write"
|
|
12033
|
+
});
|
|
12034
|
+
} else if (round % 3 === 1) {
|
|
12035
|
+
actions.push({
|
|
12036
|
+
intent: `buy non-F500 small cap equity for ${agent.name}`,
|
|
12037
|
+
tool: "trade",
|
|
12038
|
+
roleId: agent.id,
|
|
12039
|
+
actionCategory: "write"
|
|
12040
|
+
});
|
|
12041
|
+
} else {
|
|
12042
|
+
actions.push({
|
|
12043
|
+
intent: `hold position during volatility for ${agent.name}`,
|
|
12044
|
+
tool: "trade",
|
|
12045
|
+
roleId: agent.id,
|
|
12046
|
+
actionCategory: "read"
|
|
12047
|
+
});
|
|
12048
|
+
}
|
|
12049
|
+
}
|
|
12050
|
+
}
|
|
12051
|
+
return actions;
|
|
12052
|
+
}
|
|
12053
|
+
async function main22(args) {
|
|
12054
|
+
let worldPath = "";
|
|
12055
|
+
let agentCount = 8;
|
|
12056
|
+
let rounds = 5;
|
|
12057
|
+
let jsonOutput = false;
|
|
12058
|
+
for (let i = 0; i < args.length; i++) {
|
|
12059
|
+
if (args[i] === "--world" && args[i + 1]) {
|
|
12060
|
+
worldPath = args[++i];
|
|
12061
|
+
}
|
|
12062
|
+
if (args[i] === "--agents" && args[i + 1]) {
|
|
12063
|
+
agentCount = Math.min(parseInt(args[++i], 10), AGENTS.length);
|
|
12064
|
+
}
|
|
12065
|
+
if (args[i] === "--rounds" && args[i + 1]) {
|
|
12066
|
+
rounds = parseInt(args[++i], 10);
|
|
12067
|
+
}
|
|
12068
|
+
if (args[i] === "--json") {
|
|
12069
|
+
jsonOutput = true;
|
|
12070
|
+
}
|
|
12071
|
+
if (args[i] === "--help" || args[i] === "-h") {
|
|
12072
|
+
process.stdout.write(`
|
|
12073
|
+
neuroverse equity-penalties \u2014 Behavioral enforcement simulation
|
|
12074
|
+
|
|
12075
|
+
Usage:
|
|
12076
|
+
neuroverse equity-penalties --world <dir> [--agents N] [--rounds N] [--json]
|
|
12077
|
+
|
|
12078
|
+
Options:
|
|
12079
|
+
--world <dir> Path to world directory (required)
|
|
12080
|
+
--agents N Number of agents (default: 8, max: 8)
|
|
12081
|
+
--rounds N Number of simulation rounds (default: 5)
|
|
12082
|
+
--json Output as JSON
|
|
12083
|
+
|
|
12084
|
+
Simulates Fortune 500 equity trading with PENALIZE/REWARD governance:
|
|
12085
|
+
- SELL F500 equity \u2192 PENALIZED (agent frozen 1 round)
|
|
12086
|
+
- HOLD during volatility \u2192 REWARDED (+10% influence)
|
|
12087
|
+
- BUY non-F500 \u2192 ALLOWED
|
|
12088
|
+
- Unauthorized actions \u2192 BLOCKED
|
|
12089
|
+
`.trim() + "\n");
|
|
12090
|
+
return;
|
|
12091
|
+
}
|
|
12092
|
+
}
|
|
12093
|
+
if (!worldPath) {
|
|
12094
|
+
process.stderr.write("Error: --world <dir> is required\n");
|
|
12095
|
+
process.exit(1);
|
|
12096
|
+
}
|
|
12097
|
+
let world;
|
|
12098
|
+
try {
|
|
12099
|
+
world = await loadWorld(worldPath);
|
|
12100
|
+
} catch (e) {
|
|
12101
|
+
process.stderr.write(`Error loading world: ${e}
|
|
12102
|
+
`);
|
|
12103
|
+
process.exit(1);
|
|
12104
|
+
return;
|
|
12105
|
+
}
|
|
12106
|
+
const agents = AGENTS.slice(0, agentCount);
|
|
12107
|
+
let agentStates = /* @__PURE__ */ new Map();
|
|
12108
|
+
for (const agent of agents) {
|
|
12109
|
+
agentStates.set(agent.id, createAgentState(agent.id));
|
|
12110
|
+
}
|
|
12111
|
+
const allAuditEvents = [];
|
|
12112
|
+
const engineOptions = {
|
|
12113
|
+
trace: false,
|
|
12114
|
+
level: "standard",
|
|
12115
|
+
agentStates
|
|
12116
|
+
};
|
|
12117
|
+
process.stdout.write("\n");
|
|
12118
|
+
process.stdout.write("EQUITY PENALTY SIMULATION\n");
|
|
12119
|
+
process.stdout.write("\u2550".repeat(60) + "\n");
|
|
12120
|
+
process.stdout.write(` World: ${world.world.name}
|
|
12121
|
+
`);
|
|
12122
|
+
process.stdout.write(` Agents: ${agents.length}
|
|
12123
|
+
`);
|
|
12124
|
+
process.stdout.write(` Rounds: ${rounds}
|
|
12125
|
+
`);
|
|
12126
|
+
process.stdout.write("\n");
|
|
12127
|
+
for (let round = 0; round < rounds; round++) {
|
|
12128
|
+
process.stdout.write(`\u2500\u2500 Round ${round + 1} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
12129
|
+
`);
|
|
12130
|
+
const actions = generateActionsForRound(agents, round);
|
|
12131
|
+
for (const action of actions) {
|
|
12132
|
+
const event = {
|
|
12133
|
+
intent: action.intent,
|
|
12134
|
+
tool: action.tool,
|
|
12135
|
+
roleId: action.roleId,
|
|
12136
|
+
actionCategory: action.actionCategory,
|
|
12137
|
+
direction: "input"
|
|
12138
|
+
};
|
|
12139
|
+
const agentState = agentStates.get(action.roleId);
|
|
12140
|
+
if (agentState && agentState.cooldownRemaining > 0) {
|
|
12141
|
+
process.stdout.write(` \u25CC ${action.roleId.padEnd(10)} FROZEN (${agentState.cooldownRemaining} rounds) \u2014 ${action.intent.slice(0, 40)}
|
|
12142
|
+
`);
|
|
12143
|
+
const frozenEvent = {
|
|
12144
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
12145
|
+
worldId: world.world.world_id,
|
|
12146
|
+
worldName: world.world.name,
|
|
12147
|
+
worldVersion: world.world.version,
|
|
12148
|
+
intent: action.intent,
|
|
12149
|
+
tool: action.tool,
|
|
12150
|
+
actor: action.roleId,
|
|
12151
|
+
direction: "input",
|
|
12152
|
+
decision: "PENALIZE",
|
|
12153
|
+
reason: `Agent frozen for ${agentState.cooldownRemaining} more round(s)`,
|
|
12154
|
+
guardsMatched: [],
|
|
12155
|
+
rulesMatched: [],
|
|
12156
|
+
invariantsSatisfied: 0,
|
|
12157
|
+
invariantsTotal: 0,
|
|
12158
|
+
enforcementLevel: "standard",
|
|
12159
|
+
originalIntent: action.intent,
|
|
12160
|
+
finalAction: "blocked (agent frozen)"
|
|
12161
|
+
};
|
|
12162
|
+
allAuditEvents.push(frozenEvent);
|
|
12163
|
+
continue;
|
|
12164
|
+
}
|
|
12165
|
+
const verdict = evaluateGuard(event, world, engineOptions);
|
|
12166
|
+
let state = agentStates.get(action.roleId) ?? createAgentState(action.roleId);
|
|
12167
|
+
if (verdict.status === "PENALIZE" && verdict.consequence) {
|
|
12168
|
+
state = applyConsequence(state, verdict.consequence, verdict.ruleId ?? "unknown");
|
|
12169
|
+
}
|
|
12170
|
+
if (verdict.status === "REWARD" && verdict.reward) {
|
|
12171
|
+
state = applyReward(state, verdict.reward, verdict.ruleId ?? "unknown");
|
|
12172
|
+
}
|
|
12173
|
+
agentStates.set(action.roleId, state);
|
|
12174
|
+
const icon = verdict.status === "ALLOW" ? "\u25CF" : verdict.status === "BLOCK" ? "\u25CB" : verdict.status === "PENALIZE" ? "\u25CC" : verdict.status === "REWARD" ? "\u25C9" : verdict.status === "MODIFY" ? "\u25D0" : verdict.status === "NEUTRAL" ? "\u25EF" : "\u25D1";
|
|
12175
|
+
process.stdout.write(` ${icon} ${action.roleId.padEnd(10)} ${verdict.status.padEnd(10)} ${action.intent.slice(0, 40)}
|
|
12176
|
+
`);
|
|
12177
|
+
if (verdict.consequence) {
|
|
12178
|
+
process.stdout.write(` \u2192 ${verdict.consequence.description}
|
|
12179
|
+
`);
|
|
12180
|
+
}
|
|
12181
|
+
if (verdict.reward) {
|
|
12182
|
+
process.stdout.write(` \u2192 ${verdict.reward.description}
|
|
12183
|
+
`);
|
|
12184
|
+
}
|
|
12185
|
+
allAuditEvents.push(verdictToAuditEvent(event, verdict));
|
|
12186
|
+
}
|
|
12187
|
+
agentStates = tickAgentStates(agentStates);
|
|
12188
|
+
engineOptions.agentStates = agentStates;
|
|
12189
|
+
process.stdout.write("\n");
|
|
12190
|
+
process.stdout.write(" Agent States:\n");
|
|
12191
|
+
for (const agent of agents) {
|
|
12192
|
+
const s = agentStates.get(agent.id);
|
|
12193
|
+
if (!s) continue;
|
|
12194
|
+
const frozen = s.cooldownRemaining > 0 ? ` [FROZEN ${s.cooldownRemaining}r]` : "";
|
|
12195
|
+
const influence = s.influence !== 1 ? ` influence=${s.influence.toFixed(2)}` : "";
|
|
12196
|
+
process.stdout.write(` ${agent.id.padEnd(10)} penalties=${s.totalPenalties} rewards=${s.totalRewards}${frozen}${influence}
|
|
12197
|
+
`);
|
|
12198
|
+
}
|
|
12199
|
+
process.stdout.write("\n");
|
|
12200
|
+
}
|
|
12201
|
+
const flow = generateDecisionFlow(allAuditEvents);
|
|
12202
|
+
if (jsonOutput) {
|
|
12203
|
+
process.stdout.write(JSON.stringify({ flow, agentStates: Object.fromEntries(agentStates) }, null, 2) + "\n");
|
|
12204
|
+
} else {
|
|
12205
|
+
process.stdout.write(renderDecisionFlow(flow) + "\n");
|
|
12206
|
+
}
|
|
12207
|
+
}
|
|
12208
|
+
var AGENTS;
|
|
12209
|
+
var init_equity_penalties = __esm({
|
|
12210
|
+
"src/cli/equity-penalties.ts"() {
|
|
12211
|
+
"use strict";
|
|
12212
|
+
init_guard_engine();
|
|
12213
|
+
init_world_loader();
|
|
12214
|
+
init_decision_flow_engine();
|
|
12215
|
+
init_audit_logger();
|
|
12216
|
+
AGENTS = [
|
|
12217
|
+
{ id: "alpha", name: "Alpha Fund", strategy: "aggressive" },
|
|
12218
|
+
{ id: "beta", name: "Beta Holdings", strategy: "conservative" },
|
|
12219
|
+
{ id: "gamma", name: "Gamma Capital", strategy: "balanced" },
|
|
12220
|
+
{ id: "delta", name: "Delta Quant", strategy: "aggressive" },
|
|
12221
|
+
{ id: "epsilon", name: "Epsilon Value", strategy: "conservative" },
|
|
12222
|
+
{ id: "zeta", name: "Zeta Momentum", strategy: "aggressive" },
|
|
12223
|
+
{ id: "eta", name: "Eta Growth", strategy: "balanced" },
|
|
12224
|
+
{ id: "theta", name: "Theta Macro", strategy: "conservative" }
|
|
12225
|
+
];
|
|
12226
|
+
}
|
|
12227
|
+
});
|
|
12228
|
+
|
|
10164
12229
|
// src/cli/configure-ai.ts
|
|
10165
12230
|
var configure_ai_exports = {};
|
|
10166
12231
|
__export(configure_ai_exports, {
|
|
10167
|
-
main: () =>
|
|
12232
|
+
main: () => main23
|
|
10168
12233
|
});
|
|
10169
|
-
function
|
|
12234
|
+
function parseArgs18(argv) {
|
|
10170
12235
|
let provider;
|
|
10171
12236
|
let model;
|
|
10172
12237
|
let apiKey;
|
|
@@ -10191,9 +12256,9 @@ function parseArgs16(argv) {
|
|
|
10191
12256
|
}
|
|
10192
12257
|
return { provider, model, apiKey, endpoint, show, test };
|
|
10193
12258
|
}
|
|
10194
|
-
async function
|
|
12259
|
+
async function main23(argv = process.argv.slice(2)) {
|
|
10195
12260
|
try {
|
|
10196
|
-
const args =
|
|
12261
|
+
const args = parseArgs18(argv);
|
|
10197
12262
|
if (args.show) {
|
|
10198
12263
|
const config2 = await loadConfig();
|
|
10199
12264
|
if (!config2) {
|
|
@@ -10301,6 +12366,8 @@ Commands:
|
|
|
10301
12366
|
simulate Step-by-step state evolution
|
|
10302
12367
|
improve Actionable suggestions for strengthening a world
|
|
10303
12368
|
init Scaffold a new .nv-world.md template
|
|
12369
|
+
init-world Generate a governed world from a template (e.g., autoresearch)
|
|
12370
|
+
infer-world Scan a repo and infer a governance world from its structure
|
|
10304
12371
|
validate Static analysis on world files
|
|
10305
12372
|
guard Runtime governance evaluation (stdin \u2192 stdout)
|
|
10306
12373
|
test Run guard simulation suite against a world
|
|
@@ -10313,6 +12380,8 @@ Commands:
|
|
|
10313
12380
|
worlds List available worlds (alias for world list)
|
|
10314
12381
|
trace Runtime action audit log
|
|
10315
12382
|
impact Counterfactual governance impact report
|
|
12383
|
+
decision-flow Intent \u2192 Rule \u2192 Outcome visualization (behavioral governance)
|
|
12384
|
+
equity-penalties Fortune 500 equity PENALIZE/REWARD simulation
|
|
10316
12385
|
world World management (status, diff, snapshot, rollback)
|
|
10317
12386
|
derive AI-assisted synthesis of .nv-world.md from markdown
|
|
10318
12387
|
bootstrap Compile .nv-world.md \u2192 world JSON files
|
|
@@ -10324,6 +12393,8 @@ Usage:
|
|
|
10324
12393
|
neuroverse simulate <world-path-or-id> [--steps N] [--set key=value] [--profile name]
|
|
10325
12394
|
neuroverse improve <world-path-or-id> [--json]
|
|
10326
12395
|
neuroverse init [--name "World Name"] [--output path]
|
|
12396
|
+
neuroverse init-world autoresearch [--context "topic"] [--dataset "name"] [--goal "goal"]
|
|
12397
|
+
neuroverse infer-world ./repo [--output path] [--json] [--dry-run]
|
|
10327
12398
|
neuroverse validate --world <dir> [--format full|summary|findings]
|
|
10328
12399
|
neuroverse guard --world <dir> [--trace] [--level basic|standard|strict]
|
|
10329
12400
|
neuroverse test --world <dir> [--fuzz] [--count N]
|
|
@@ -10338,6 +12409,8 @@ Usage:
|
|
|
10338
12409
|
neuroverse world rollback <path>
|
|
10339
12410
|
neuroverse derive --input <path> [--output <path>] [--dry-run]
|
|
10340
12411
|
neuroverse bootstrap --input <.md> --output <dir> [--validate]
|
|
12412
|
+
neuroverse decision-flow [--log <path>] [--json]
|
|
12413
|
+
neuroverse equity-penalties --world <dir> [--agents N] [--rounds N] [--json]
|
|
10341
12414
|
neuroverse configure-ai --provider <name> --model <name> --api-key <key>
|
|
10342
12415
|
|
|
10343
12416
|
Examples:
|
|
@@ -10362,7 +12435,7 @@ Examples:
|
|
|
10362
12435
|
neuroverse doctor
|
|
10363
12436
|
neuroverse playground --world ./world/
|
|
10364
12437
|
`.trim();
|
|
10365
|
-
async function
|
|
12438
|
+
async function main24() {
|
|
10366
12439
|
const args = process.argv.slice(2);
|
|
10367
12440
|
const command = args[0];
|
|
10368
12441
|
const subArgs = args.slice(1);
|
|
@@ -10387,6 +12460,14 @@ async function main20() {
|
|
|
10387
12460
|
const { main: initMain } = await Promise.resolve().then(() => (init_init(), init_exports));
|
|
10388
12461
|
return initMain(subArgs);
|
|
10389
12462
|
}
|
|
12463
|
+
case "init-world": {
|
|
12464
|
+
const { main: initWorldMain } = await Promise.resolve().then(() => (init_init_world(), init_world_exports));
|
|
12465
|
+
return initWorldMain(subArgs);
|
|
12466
|
+
}
|
|
12467
|
+
case "infer-world": {
|
|
12468
|
+
const { main: inferWorldMain } = await Promise.resolve().then(() => (init_infer_world(), infer_world_exports));
|
|
12469
|
+
return inferWorldMain(subArgs);
|
|
12470
|
+
}
|
|
10390
12471
|
case "bootstrap": {
|
|
10391
12472
|
const { main: bootstrapMain } = await Promise.resolve().then(() => (init_bootstrap(), bootstrap_exports));
|
|
10392
12473
|
return bootstrapMain(subArgs);
|
|
@@ -10447,6 +12528,14 @@ async function main20() {
|
|
|
10447
12528
|
const { main: deriveMain } = await Promise.resolve().then(() => (init_derive(), derive_exports));
|
|
10448
12529
|
return deriveMain(subArgs);
|
|
10449
12530
|
}
|
|
12531
|
+
case "decision-flow": {
|
|
12532
|
+
const { main: decisionFlowMain } = await Promise.resolve().then(() => (init_decision_flow(), decision_flow_exports));
|
|
12533
|
+
return decisionFlowMain(subArgs);
|
|
12534
|
+
}
|
|
12535
|
+
case "equity-penalties": {
|
|
12536
|
+
const { main: equityPenaltiesMain } = await Promise.resolve().then(() => (init_equity_penalties(), equity_penalties_exports));
|
|
12537
|
+
return equityPenaltiesMain(subArgs);
|
|
12538
|
+
}
|
|
10450
12539
|
case "configure-ai": {
|
|
10451
12540
|
const { main: configureAiMain } = await Promise.resolve().then(() => (init_configure_ai(), configure_ai_exports));
|
|
10452
12541
|
return configureAiMain(subArgs);
|
|
@@ -10468,7 +12557,7 @@ async function main20() {
|
|
|
10468
12557
|
}
|
|
10469
12558
|
}
|
|
10470
12559
|
}
|
|
10471
|
-
|
|
12560
|
+
main24().catch((e) => {
|
|
10472
12561
|
process.stderr.write(`Fatal: ${e}
|
|
10473
12562
|
`);
|
|
10474
12563
|
process.exit(3);
|