@neuroverseos/governance 0.2.3 → 0.3.1
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/package.json +4 -2
- package/policies/content-moderation-rules.txt +8 -0
- package/policies/marketing-rules.txt +8 -0
- package/policies/science-research-rules.txt +11 -0
- package/policies/social-media-rules.txt +7 -0
- package/policies/strict-rules.txt +8 -0
- package/policies/trading-rules.txt +8 -0
- package/simulate.html +1899 -0
- package/dist/adapters/autoresearch.cjs +0 -196
- package/dist/adapters/autoresearch.d.cts +0 -103
- package/dist/adapters/autoresearch.d.ts +0 -103
- package/dist/adapters/autoresearch.js +0 -7
- package/dist/adapters/deep-agents.cjs +0 -1472
- package/dist/adapters/deep-agents.d.cts +0 -181
- package/dist/adapters/deep-agents.d.ts +0 -181
- package/dist/adapters/deep-agents.js +0 -17
- package/dist/adapters/express.cjs +0 -1196
- package/dist/adapters/express.d.cts +0 -66
- package/dist/adapters/express.d.ts +0 -66
- package/dist/adapters/express.js +0 -12
- package/dist/adapters/index.cjs +0 -2038
- package/dist/adapters/index.d.cts +0 -8
- package/dist/adapters/index.d.ts +0 -8
- package/dist/adapters/index.js +0 -68
- package/dist/adapters/langchain.cjs +0 -1259
- package/dist/adapters/langchain.d.cts +0 -89
- package/dist/adapters/langchain.d.ts +0 -89
- package/dist/adapters/langchain.js +0 -17
- package/dist/adapters/openai.cjs +0 -1289
- package/dist/adapters/openai.d.cts +0 -99
- package/dist/adapters/openai.d.ts +0 -99
- package/dist/adapters/openai.js +0 -17
- package/dist/adapters/openclaw.cjs +0 -1281
- package/dist/adapters/openclaw.d.cts +0 -99
- package/dist/adapters/openclaw.d.ts +0 -99
- package/dist/adapters/openclaw.js +0 -17
- package/dist/bootstrap-GXVDZNF7.js +0 -114
- package/dist/build-X5MZY4IA.js +0 -339
- package/dist/chunk-4L6OPKMQ.js +0 -100
- package/dist/chunk-4NGDRRQH.js +0 -10
- package/dist/chunk-5U2MQO5P.js +0 -57
- package/dist/chunk-6BB55YJI.js +0 -113
- package/dist/chunk-6CZSKEY5.js +0 -164
- package/dist/chunk-7P3S7MAY.js +0 -1090
- package/dist/chunk-A5W4GNQO.js +0 -130
- package/dist/chunk-AF2VX4AL.js +0 -363
- package/dist/chunk-AKW5YVCE.js +0 -96
- package/dist/chunk-BMOXICAB.js +0 -340
- package/dist/chunk-BQZMOEML.js +0 -43
- package/dist/chunk-D2UCV5AK.js +0 -326
- package/dist/chunk-EVDJUSZ2.js +0 -91
- package/dist/chunk-FYS2CBUW.js +0 -304
- package/dist/chunk-I3RRAYK2.js +0 -11
- package/dist/chunk-IZSO75NZ.js +0 -792
- package/dist/chunk-JCKSW2PZ.js +0 -304
- package/dist/chunk-JZPQGIKR.js +0 -79
- package/dist/chunk-KTFTTLTP.js +0 -246
- package/dist/chunk-MH7BT4VH.js +0 -15
- package/dist/chunk-ORJ3NOE6.js +0 -622
- package/dist/chunk-OT6PXH54.js +0 -61
- package/dist/chunk-Q6O7ZLO2.js +0 -62
- package/dist/chunk-QLPTHTVB.js +0 -253
- package/dist/chunk-REXY4LUL.js +0 -226
- package/dist/chunk-T5EUJQE5.js +0 -172
- package/dist/chunk-TTBKTF3P.js +0 -608
- package/dist/chunk-XPDMYECO.js +0 -642
- package/dist/chunk-YZFATT7X.js +0 -9
- package/dist/chunk-ZIVQNSZU.js +0 -119
- package/dist/chunk-ZJTDUCC2.js +0 -194
- package/dist/cli/neuroverse.cjs +0 -12564
- package/dist/cli/neuroverse.d.cts +0 -1
- package/dist/cli/neuroverse.d.ts +0 -1
- package/dist/cli/neuroverse.js +0 -208
- package/dist/cli/plan.cjs +0 -1686
- package/dist/cli/plan.d.cts +0 -20
- package/dist/cli/plan.d.ts +0 -20
- package/dist/cli/plan.js +0 -353
- package/dist/cli/run.cjs +0 -1945
- package/dist/cli/run.d.cts +0 -20
- package/dist/cli/run.d.ts +0 -20
- package/dist/cli/run.js +0 -143
- package/dist/configure-ai-TK67ZWZL.js +0 -132
- package/dist/decision-flow-LETV5NWY.js +0 -61
- package/dist/derive-7365SUFU.js +0 -152
- package/dist/doctor-QYISMKEL.js +0 -173
- package/dist/equity-penalties-63FGB3I2.js +0 -244
- package/dist/explain-A2EWI2OL.js +0 -51
- package/dist/guard-3BWL3IGH.js +0 -92
- package/dist/guard-contract-C9_zKbzd.d.cts +0 -821
- package/dist/guard-contract-C9_zKbzd.d.ts +0 -821
- package/dist/guard-engine-QFMIBWJY.js +0 -10
- package/dist/impact-UB6DXKSX.js +0 -59
- package/dist/improve-XZA57GER.js +0 -66
- package/dist/index.cjs +0 -6821
- package/dist/index.d.cts +0 -1829
- package/dist/index.d.ts +0 -1829
- package/dist/index.js +0 -430
- package/dist/infer-world-7GVZWFX4.js +0 -543
- package/dist/init-PKPIYHYE.js +0 -144
- package/dist/init-world-VWMQZQC7.js +0 -223
- package/dist/mcp-server-XWQZXNW7.js +0 -13
- package/dist/model-adapter-BB7G4MFI.js +0 -11
- package/dist/playground-ADWZORNV.js +0 -550
- package/dist/redteam-JRQ7FD2F.js +0 -357
- package/dist/session-MMYX5YCF.js +0 -15
- package/dist/shared--Q8wPBVN.d.ts +0 -60
- package/dist/shared-HpAG90PX.d.cts +0 -60
- package/dist/shared-U2QFV7JH.js +0 -16
- package/dist/simulate-GMIFFXYV.js +0 -83
- package/dist/test-JBBZ65X4.js +0 -217
- package/dist/trace-3MYWIDEF.js +0 -166
- package/dist/validate-LLBWVPGV.js +0 -81
- package/dist/validate-engine-UIABSIHD.js +0 -7
- package/dist/world-BFJCIQSH.js +0 -378
- package/dist/world-loader-HMPTOEA2.js +0 -9
- package/dist/worlds/autoresearch.nv-world.md +0 -230
- package/dist/worlds/coding-agent.nv-world.md +0 -211
- package/dist/worlds/derivation-world.nv-world.md +0 -278
package/dist/cli/plan.cjs
DELETED
|
@@ -1,1686 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __create = Object.create;
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
-
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
-
var __esm = (fn, res) => function __init() {
|
|
9
|
-
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
-
};
|
|
11
|
-
var __export = (target, all) => {
|
|
12
|
-
for (var name in all)
|
|
13
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
-
};
|
|
15
|
-
var __copyProps = (to, from, except, desc) => {
|
|
16
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
17
|
-
for (let key of __getOwnPropNames(from))
|
|
18
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
19
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
-
}
|
|
21
|
-
return to;
|
|
22
|
-
};
|
|
23
|
-
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
-
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
-
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
-
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
-
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
-
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
-
mod
|
|
30
|
-
));
|
|
31
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
|
-
|
|
33
|
-
// src/engine/text-utils.ts
|
|
34
|
-
function normalizeEventText(event) {
|
|
35
|
-
return [
|
|
36
|
-
event.intent,
|
|
37
|
-
event.tool ?? "",
|
|
38
|
-
event.scope ?? ""
|
|
39
|
-
].join(" ").toLowerCase();
|
|
40
|
-
}
|
|
41
|
-
function extractKeywords(text, minLength = 3) {
|
|
42
|
-
return text.toLowerCase().split(/\s+/).filter((w) => w.length > minLength);
|
|
43
|
-
}
|
|
44
|
-
function matchesAllKeywords(eventText, ruleText) {
|
|
45
|
-
const keywords = extractKeywords(ruleText);
|
|
46
|
-
if (keywords.length === 0) return false;
|
|
47
|
-
return keywords.every((kw) => eventText.includes(kw));
|
|
48
|
-
}
|
|
49
|
-
function matchesKeywordThreshold(eventText, ruleText, threshold = 0.5) {
|
|
50
|
-
const keywords = extractKeywords(ruleText);
|
|
51
|
-
if (keywords.length === 0) return false;
|
|
52
|
-
const matched = keywords.filter((kw) => eventText.includes(kw));
|
|
53
|
-
return matched.length >= Math.ceil(keywords.length * threshold);
|
|
54
|
-
}
|
|
55
|
-
function tokenSimilarity(a, b) {
|
|
56
|
-
const tokensA = new Set(a.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
57
|
-
const tokensB = new Set(b.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
|
|
58
|
-
if (tokensA.size === 0 || tokensB.size === 0) return 0;
|
|
59
|
-
let intersection = 0;
|
|
60
|
-
for (const t of tokensA) {
|
|
61
|
-
if (tokensB.has(t)) intersection++;
|
|
62
|
-
}
|
|
63
|
-
const union = (/* @__PURE__ */ new Set([...tokensA, ...tokensB])).size;
|
|
64
|
-
return union > 0 ? intersection / union : 0;
|
|
65
|
-
}
|
|
66
|
-
var init_text_utils = __esm({
|
|
67
|
-
"src/engine/text-utils.ts"() {
|
|
68
|
-
"use strict";
|
|
69
|
-
}
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
// src/engine/plan-engine.ts
|
|
73
|
-
function keywordMatch(eventText, step) {
|
|
74
|
-
const stepText = [
|
|
75
|
-
step.label,
|
|
76
|
-
step.description ?? "",
|
|
77
|
-
...step.tags ?? []
|
|
78
|
-
].join(" ");
|
|
79
|
-
return matchesKeywordThreshold(eventText, stepText, 0.5);
|
|
80
|
-
}
|
|
81
|
-
function tokenSimilarity2(a, b) {
|
|
82
|
-
return tokenSimilarity(a, b);
|
|
83
|
-
}
|
|
84
|
-
function findMatchingStep(eventText, event, steps) {
|
|
85
|
-
const pendingOrActive = steps.filter((s) => s.status === "pending" || s.status === "active");
|
|
86
|
-
if (pendingOrActive.length === 0) {
|
|
87
|
-
return { matched: null, closest: null, closestScore: 0 };
|
|
88
|
-
}
|
|
89
|
-
for (const step of pendingOrActive) {
|
|
90
|
-
if (keywordMatch(eventText, step)) {
|
|
91
|
-
if (step.tools && event.tool && !step.tools.includes(event.tool)) {
|
|
92
|
-
continue;
|
|
93
|
-
}
|
|
94
|
-
return { matched: step, closest: step, closestScore: 1 };
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
const intentText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ");
|
|
98
|
-
let bestStep = null;
|
|
99
|
-
let bestScore = 0;
|
|
100
|
-
for (const step of pendingOrActive) {
|
|
101
|
-
const stepText = [step.label, step.description ?? "", ...step.tags ?? []].join(" ");
|
|
102
|
-
const score = tokenSimilarity2(intentText, stepText);
|
|
103
|
-
if (score > bestScore) {
|
|
104
|
-
bestScore = score;
|
|
105
|
-
bestStep = step;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
const SIMILARITY_THRESHOLD = 0.35;
|
|
109
|
-
if (bestScore >= SIMILARITY_THRESHOLD && bestStep) {
|
|
110
|
-
if (bestStep.tools && event.tool && !bestStep.tools.includes(event.tool)) {
|
|
111
|
-
return { matched: null, closest: bestStep, closestScore: bestScore };
|
|
112
|
-
}
|
|
113
|
-
return { matched: bestStep, closest: bestStep, closestScore: bestScore };
|
|
114
|
-
}
|
|
115
|
-
return { matched: null, closest: bestStep, closestScore: bestScore };
|
|
116
|
-
}
|
|
117
|
-
function isSequenceValid(step, plan) {
|
|
118
|
-
if (!plan.sequential) return true;
|
|
119
|
-
if (!step.requires || step.requires.length === 0) return true;
|
|
120
|
-
return step.requires.every((reqId) => {
|
|
121
|
-
const reqStep = plan.steps.find((s) => s.id === reqId);
|
|
122
|
-
return reqStep?.status === "completed";
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
function checkConstraints(event, eventText, constraints) {
|
|
126
|
-
const checks = [];
|
|
127
|
-
for (const constraint of constraints) {
|
|
128
|
-
if (constraint.type === "approval") {
|
|
129
|
-
if (constraint.trigger && eventText.includes(constraint.trigger.substring(0, 10).toLowerCase())) {
|
|
130
|
-
checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
|
|
131
|
-
return { violated: constraint, checks };
|
|
132
|
-
}
|
|
133
|
-
const keywords = constraint.description.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
|
|
134
|
-
const relevant = keywords.some((kw) => eventText.includes(kw));
|
|
135
|
-
if (relevant) {
|
|
136
|
-
checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
|
|
137
|
-
return { violated: constraint, checks };
|
|
138
|
-
}
|
|
139
|
-
checks.push({ constraintId: constraint.id, passed: true });
|
|
140
|
-
continue;
|
|
141
|
-
}
|
|
142
|
-
if (constraint.type === "scope" && constraint.trigger) {
|
|
143
|
-
const keywords = extractKeywords(constraint.trigger);
|
|
144
|
-
const violated = keywords.length > 0 && keywords.every((kw) => eventText.includes(kw));
|
|
145
|
-
checks.push({
|
|
146
|
-
constraintId: constraint.id,
|
|
147
|
-
passed: !violated,
|
|
148
|
-
reason: violated ? constraint.description : void 0
|
|
149
|
-
});
|
|
150
|
-
if (violated) {
|
|
151
|
-
return { violated: constraint, checks };
|
|
152
|
-
}
|
|
153
|
-
continue;
|
|
154
|
-
}
|
|
155
|
-
checks.push({ constraintId: constraint.id, passed: true });
|
|
156
|
-
}
|
|
157
|
-
return { violated: null, checks };
|
|
158
|
-
}
|
|
159
|
-
function getPlanProgress(plan) {
|
|
160
|
-
const completed = plan.steps.filter((s) => s.status === "completed").length;
|
|
161
|
-
const total = plan.steps.length;
|
|
162
|
-
return {
|
|
163
|
-
completed,
|
|
164
|
-
total,
|
|
165
|
-
percentage: total > 0 ? Math.round(completed / total * 100) : 0
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
function advancePlan(plan, stepId, evidence) {
|
|
169
|
-
const step = plan.steps.find((s) => s.id === stepId);
|
|
170
|
-
if (!step) {
|
|
171
|
-
return { success: false, reason: `Step "${stepId}" not found in plan.` };
|
|
172
|
-
}
|
|
173
|
-
if (step.status === "completed") {
|
|
174
|
-
return { success: false, reason: `Step "${stepId}" is already completed.` };
|
|
175
|
-
}
|
|
176
|
-
const mode = plan.completion ?? "trust";
|
|
177
|
-
if (mode === "verified" && step.verify) {
|
|
178
|
-
if (!evidence) {
|
|
179
|
-
return {
|
|
180
|
-
success: false,
|
|
181
|
-
reason: `Step "${step.label}" requires evidence (verify: ${step.verify}). Provide evidence to advance.`
|
|
182
|
-
};
|
|
183
|
-
}
|
|
184
|
-
if (evidence.type !== step.verify) {
|
|
185
|
-
return {
|
|
186
|
-
success: false,
|
|
187
|
-
reason: `Evidence type "${evidence.type}" does not match required verification "${step.verify}".`
|
|
188
|
-
};
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
const updatedPlan = {
|
|
192
|
-
...plan,
|
|
193
|
-
steps: plan.steps.map(
|
|
194
|
-
(s) => s.id === stepId ? { ...s, status: "completed" } : s
|
|
195
|
-
)
|
|
196
|
-
};
|
|
197
|
-
return {
|
|
198
|
-
success: true,
|
|
199
|
-
plan: updatedPlan,
|
|
200
|
-
evidence: evidence ?? void 0
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
function evaluatePlan(event, plan) {
|
|
204
|
-
const progress = getPlanProgress(plan);
|
|
205
|
-
if (plan.expires_at) {
|
|
206
|
-
const expiresAt = new Date(plan.expires_at).getTime();
|
|
207
|
-
if (Date.now() > expiresAt) {
|
|
208
|
-
return {
|
|
209
|
-
allowed: true,
|
|
210
|
-
status: "PLAN_COMPLETE",
|
|
211
|
-
reason: "Plan has expired.",
|
|
212
|
-
progress
|
|
213
|
-
};
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
if (progress.completed === progress.total) {
|
|
217
|
-
return {
|
|
218
|
-
allowed: true,
|
|
219
|
-
status: "PLAN_COMPLETE",
|
|
220
|
-
reason: "All plan steps are completed.",
|
|
221
|
-
progress
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
const eventText = normalizeEventText(event);
|
|
225
|
-
const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
|
|
226
|
-
if (!matched) {
|
|
227
|
-
return {
|
|
228
|
-
allowed: false,
|
|
229
|
-
status: "OFF_PLAN",
|
|
230
|
-
reason: "Action does not match any plan step.",
|
|
231
|
-
closestStep: closest?.label,
|
|
232
|
-
similarityScore: closestScore,
|
|
233
|
-
progress
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
if (!isSequenceValid(matched, plan)) {
|
|
237
|
-
const pendingDeps = (matched.requires ?? []).filter((reqId) => plan.steps.find((s) => s.id === reqId)?.status !== "completed").join(", ");
|
|
238
|
-
return {
|
|
239
|
-
allowed: false,
|
|
240
|
-
status: "OFF_PLAN",
|
|
241
|
-
reason: `Step "${matched.label}" requires completion of: ${pendingDeps}`,
|
|
242
|
-
matchedStep: matched.id,
|
|
243
|
-
progress
|
|
244
|
-
};
|
|
245
|
-
}
|
|
246
|
-
const { violated } = checkConstraints(event, eventText, plan.constraints);
|
|
247
|
-
if (violated) {
|
|
248
|
-
return {
|
|
249
|
-
allowed: false,
|
|
250
|
-
status: "CONSTRAINT_VIOLATED",
|
|
251
|
-
reason: violated.description,
|
|
252
|
-
matchedStep: matched.id,
|
|
253
|
-
progress
|
|
254
|
-
};
|
|
255
|
-
}
|
|
256
|
-
return {
|
|
257
|
-
allowed: true,
|
|
258
|
-
status: "ON_PLAN",
|
|
259
|
-
reason: `Matches step: ${matched.label}`,
|
|
260
|
-
matchedStep: matched.id,
|
|
261
|
-
progress
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
function buildPlanCheck(event, plan, verdict) {
|
|
265
|
-
const eventText = normalizeEventText(event);
|
|
266
|
-
const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
|
|
267
|
-
const { checks: constraintChecks } = checkConstraints(event, eventText, plan.constraints);
|
|
268
|
-
const progress = getPlanProgress(plan);
|
|
269
|
-
return {
|
|
270
|
-
planId: plan.plan_id,
|
|
271
|
-
matched: !!matched,
|
|
272
|
-
matchedStepId: matched?.id,
|
|
273
|
-
matchedStepLabel: matched?.label,
|
|
274
|
-
closestStepId: !matched ? closest?.id : void 0,
|
|
275
|
-
closestStepLabel: !matched ? closest?.label : void 0,
|
|
276
|
-
similarityScore: !matched ? closestScore : void 0,
|
|
277
|
-
sequenceValid: matched ? isSequenceValid(matched, plan) : void 0,
|
|
278
|
-
constraintsChecked: constraintChecks,
|
|
279
|
-
progress: { completed: progress.completed, total: progress.total }
|
|
280
|
-
};
|
|
281
|
-
}
|
|
282
|
-
var init_plan_engine = __esm({
|
|
283
|
-
"src/engine/plan-engine.ts"() {
|
|
284
|
-
"use strict";
|
|
285
|
-
init_text_utils();
|
|
286
|
-
}
|
|
287
|
-
});
|
|
288
|
-
|
|
289
|
-
// src/loader/world-loader.ts
|
|
290
|
-
var world_loader_exports = {};
|
|
291
|
-
__export(world_loader_exports, {
|
|
292
|
-
loadWorld: () => loadWorld,
|
|
293
|
-
loadWorldFromDirectory: () => loadWorldFromDirectory
|
|
294
|
-
});
|
|
295
|
-
async function loadWorldFromDirectory(dirPath) {
|
|
296
|
-
const { readFile } = await import("fs/promises");
|
|
297
|
-
const { join } = await import("path");
|
|
298
|
-
const { readdirSync } = await import("fs");
|
|
299
|
-
async function readJson(filename) {
|
|
300
|
-
try {
|
|
301
|
-
const content = await readFile(join(dirPath, filename), "utf-8");
|
|
302
|
-
return JSON.parse(content);
|
|
303
|
-
} catch {
|
|
304
|
-
return void 0;
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
const worldJson = await readJson("world.json");
|
|
308
|
-
if (!worldJson) {
|
|
309
|
-
throw new Error(`Cannot read world.json in ${dirPath}`);
|
|
310
|
-
}
|
|
311
|
-
const invariantsJson = await readJson("invariants.json");
|
|
312
|
-
const assumptionsJson = await readJson("assumptions.json");
|
|
313
|
-
const stateSchemaJson = await readJson("state-schema.json");
|
|
314
|
-
const gatesJson = await readJson("gates.json");
|
|
315
|
-
const outcomesJson = await readJson("outcomes.json");
|
|
316
|
-
const guardsJson = await readJson("guards.json");
|
|
317
|
-
const rolesJson = await readJson("roles.json");
|
|
318
|
-
const kernelJson = await readJson("kernel.json");
|
|
319
|
-
const metadataJson = await readJson("metadata.json");
|
|
320
|
-
const rules = [];
|
|
321
|
-
try {
|
|
322
|
-
const rulesDir = join(dirPath, "rules");
|
|
323
|
-
const ruleFiles = readdirSync(rulesDir).filter((f) => f.endsWith(".json")).sort();
|
|
324
|
-
for (const file of ruleFiles) {
|
|
325
|
-
const content = await readFile(join(rulesDir, file), "utf-8");
|
|
326
|
-
rules.push(JSON.parse(content));
|
|
327
|
-
}
|
|
328
|
-
} catch {
|
|
329
|
-
}
|
|
330
|
-
return {
|
|
331
|
-
world: worldJson,
|
|
332
|
-
invariants: invariantsJson?.invariants ?? [],
|
|
333
|
-
assumptions: assumptionsJson ?? { profiles: {}, parameter_definitions: {} },
|
|
334
|
-
stateSchema: stateSchemaJson ?? { variables: {}, presets: {} },
|
|
335
|
-
rules,
|
|
336
|
-
gates: gatesJson ?? {
|
|
337
|
-
viability_classification: [],
|
|
338
|
-
structural_override: { description: "", enforcement: "mandatory" },
|
|
339
|
-
sustainability_threshold: 0,
|
|
340
|
-
collapse_visual: { background: "", text: "", border: "", label: "" }
|
|
341
|
-
},
|
|
342
|
-
outcomes: outcomesJson ?? {
|
|
343
|
-
computed_outcomes: [],
|
|
344
|
-
comparison_layout: { primary_card: "", status_badge: "", structural_indicators: [] }
|
|
345
|
-
},
|
|
346
|
-
guards: guardsJson,
|
|
347
|
-
roles: rolesJson,
|
|
348
|
-
kernel: kernelJson,
|
|
349
|
-
metadata: metadataJson ?? {
|
|
350
|
-
format_version: "1.0.0",
|
|
351
|
-
created_at: "",
|
|
352
|
-
last_modified: "",
|
|
353
|
-
authoring_method: "manual-authoring"
|
|
354
|
-
}
|
|
355
|
-
};
|
|
356
|
-
}
|
|
357
|
-
async function loadWorld(worldPath) {
|
|
358
|
-
const { stat } = await import("fs/promises");
|
|
359
|
-
const info = await stat(worldPath);
|
|
360
|
-
if (info.isDirectory()) {
|
|
361
|
-
return loadWorldFromDirectory(worldPath);
|
|
362
|
-
}
|
|
363
|
-
if (worldPath.endsWith(".nv-world.zip")) {
|
|
364
|
-
throw new Error(".nv-world.zip loading not yet implemented \u2014 use a world directory");
|
|
365
|
-
}
|
|
366
|
-
throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory or .nv-world.zip`);
|
|
367
|
-
}
|
|
368
|
-
var init_world_loader = __esm({
|
|
369
|
-
"src/loader/world-loader.ts"() {
|
|
370
|
-
"use strict";
|
|
371
|
-
}
|
|
372
|
-
});
|
|
373
|
-
|
|
374
|
-
// src/engine/guard-engine.ts
|
|
375
|
-
var guard_engine_exports = {};
|
|
376
|
-
__export(guard_engine_exports, {
|
|
377
|
-
evaluateGuard: () => evaluateGuard,
|
|
378
|
-
eventToAllowlistKey: () => eventToAllowlistKey
|
|
379
|
-
});
|
|
380
|
-
function levelRequiresConfirmation(level, actionType) {
|
|
381
|
-
if (level === "strict") return true;
|
|
382
|
-
if (level === "standard") {
|
|
383
|
-
return actionType === "delete" || actionType === "credential-access";
|
|
384
|
-
}
|
|
385
|
-
return false;
|
|
386
|
-
}
|
|
387
|
-
function isExternalScope(scope) {
|
|
388
|
-
const internalPatterns = [
|
|
389
|
-
/^\.?\/?src\//i,
|
|
390
|
-
/^\.?\/?lib\//i,
|
|
391
|
-
/^\.?\/?app\//i,
|
|
392
|
-
/^\.?\/?components\//i,
|
|
393
|
-
/^\.?\/?pages\//i,
|
|
394
|
-
/^\.?\/?public\//i,
|
|
395
|
-
/^\.?\/?assets\//i,
|
|
396
|
-
/^\.\//
|
|
397
|
-
];
|
|
398
|
-
return !internalPatterns.some((p) => p.test(scope));
|
|
399
|
-
}
|
|
400
|
-
function evaluateGuard(event, world, options = {}) {
|
|
401
|
-
const startTime = performance.now();
|
|
402
|
-
const level = options.level ?? "standard";
|
|
403
|
-
const includeTrace = options.trace ?? false;
|
|
404
|
-
const eventText = normalizeEventText(event);
|
|
405
|
-
const invariantChecks = [];
|
|
406
|
-
const safetyChecks = [];
|
|
407
|
-
let planCheckResult;
|
|
408
|
-
const roleChecks = [];
|
|
409
|
-
const guardChecks = [];
|
|
410
|
-
const kernelRuleChecks = [];
|
|
411
|
-
const levelChecks = [];
|
|
412
|
-
let decidingLayer = "default-allow";
|
|
413
|
-
let decidingId;
|
|
414
|
-
const guardsMatched = [];
|
|
415
|
-
const rulesMatched = [];
|
|
416
|
-
checkInvariantCoverage(world, invariantChecks);
|
|
417
|
-
if (event.roleId && options.agentStates) {
|
|
418
|
-
const agentState = options.agentStates.get(event.roleId);
|
|
419
|
-
if (agentState && agentState.cooldownRemaining > 0) {
|
|
420
|
-
decidingLayer = "safety";
|
|
421
|
-
decidingId = `penalize-cooldown-${event.roleId}`;
|
|
422
|
-
const verdict = buildVerdict(
|
|
423
|
-
"PENALIZE",
|
|
424
|
-
`Agent "${event.roleId}" is frozen for ${agentState.cooldownRemaining} more round(s) due to prior penalty.`,
|
|
425
|
-
`penalize-cooldown-${event.roleId}`,
|
|
426
|
-
void 0,
|
|
427
|
-
world,
|
|
428
|
-
level,
|
|
429
|
-
invariantChecks,
|
|
430
|
-
guardsMatched,
|
|
431
|
-
rulesMatched,
|
|
432
|
-
includeTrace ? buildTrace(
|
|
433
|
-
invariantChecks,
|
|
434
|
-
safetyChecks,
|
|
435
|
-
planCheckResult,
|
|
436
|
-
roleChecks,
|
|
437
|
-
guardChecks,
|
|
438
|
-
kernelRuleChecks,
|
|
439
|
-
levelChecks,
|
|
440
|
-
decidingLayer,
|
|
441
|
-
decidingId,
|
|
442
|
-
startTime
|
|
443
|
-
) : void 0
|
|
444
|
-
);
|
|
445
|
-
verdict.intentRecord = {
|
|
446
|
-
originalIntent: event.intent,
|
|
447
|
-
finalAction: "blocked (agent frozen)",
|
|
448
|
-
enforcement: "PENALIZE",
|
|
449
|
-
consequence: { type: "freeze", rounds: agentState.cooldownRemaining, description: "Agent still in cooldown from prior penalty" }
|
|
450
|
-
};
|
|
451
|
-
return verdict;
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
if (options.sessionAllowlist) {
|
|
455
|
-
const key = eventToAllowlistKey(event);
|
|
456
|
-
if (options.sessionAllowlist.has(key)) {
|
|
457
|
-
decidingLayer = "session-allowlist";
|
|
458
|
-
decidingId = `allowlist:${key}`;
|
|
459
|
-
return buildVerdict(
|
|
460
|
-
"ALLOW",
|
|
461
|
-
void 0,
|
|
462
|
-
`allowlist:${key}`,
|
|
463
|
-
void 0,
|
|
464
|
-
world,
|
|
465
|
-
level,
|
|
466
|
-
invariantChecks,
|
|
467
|
-
guardsMatched,
|
|
468
|
-
rulesMatched,
|
|
469
|
-
includeTrace ? buildTrace(
|
|
470
|
-
invariantChecks,
|
|
471
|
-
safetyChecks,
|
|
472
|
-
planCheckResult,
|
|
473
|
-
roleChecks,
|
|
474
|
-
guardChecks,
|
|
475
|
-
kernelRuleChecks,
|
|
476
|
-
levelChecks,
|
|
477
|
-
decidingLayer,
|
|
478
|
-
decidingId,
|
|
479
|
-
startTime
|
|
480
|
-
) : void 0
|
|
481
|
-
);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
const safetyVerdict = checkSafety(event, eventText, safetyChecks);
|
|
485
|
-
if (safetyVerdict) {
|
|
486
|
-
decidingLayer = "safety";
|
|
487
|
-
decidingId = safetyVerdict.ruleId;
|
|
488
|
-
return buildVerdict(
|
|
489
|
-
safetyVerdict.status,
|
|
490
|
-
safetyVerdict.reason,
|
|
491
|
-
safetyVerdict.ruleId,
|
|
492
|
-
void 0,
|
|
493
|
-
world,
|
|
494
|
-
level,
|
|
495
|
-
invariantChecks,
|
|
496
|
-
guardsMatched,
|
|
497
|
-
rulesMatched,
|
|
498
|
-
includeTrace ? buildTrace(
|
|
499
|
-
invariantChecks,
|
|
500
|
-
safetyChecks,
|
|
501
|
-
planCheckResult,
|
|
502
|
-
roleChecks,
|
|
503
|
-
guardChecks,
|
|
504
|
-
kernelRuleChecks,
|
|
505
|
-
levelChecks,
|
|
506
|
-
decidingLayer,
|
|
507
|
-
decidingId,
|
|
508
|
-
startTime
|
|
509
|
-
) : void 0
|
|
510
|
-
);
|
|
511
|
-
}
|
|
512
|
-
if (options.plan) {
|
|
513
|
-
const planVerdict = evaluatePlan(event, options.plan);
|
|
514
|
-
planCheckResult = buildPlanCheck(event, options.plan, planVerdict);
|
|
515
|
-
if (!planVerdict.allowed && planVerdict.status !== "PLAN_COMPLETE") {
|
|
516
|
-
decidingLayer = "plan-enforcement";
|
|
517
|
-
decidingId = `plan-${options.plan.plan_id}`;
|
|
518
|
-
const planStatus = planVerdict.status === "CONSTRAINT_VIOLATED" ? "PAUSE" : "BLOCK";
|
|
519
|
-
let reason = planVerdict.reason ?? "Action blocked by plan.";
|
|
520
|
-
if (planVerdict.status === "OFF_PLAN" && planVerdict.closestStep) {
|
|
521
|
-
reason += ` Closest step: "${planVerdict.closestStep}" (similarity: ${(planVerdict.similarityScore ?? 0).toFixed(2)})`;
|
|
522
|
-
}
|
|
523
|
-
return buildVerdict(
|
|
524
|
-
planStatus,
|
|
525
|
-
reason,
|
|
526
|
-
`plan-${options.plan.plan_id}`,
|
|
527
|
-
void 0,
|
|
528
|
-
world,
|
|
529
|
-
level,
|
|
530
|
-
invariantChecks,
|
|
531
|
-
guardsMatched,
|
|
532
|
-
rulesMatched,
|
|
533
|
-
includeTrace ? buildTrace(
|
|
534
|
-
invariantChecks,
|
|
535
|
-
safetyChecks,
|
|
536
|
-
planCheckResult,
|
|
537
|
-
roleChecks,
|
|
538
|
-
guardChecks,
|
|
539
|
-
kernelRuleChecks,
|
|
540
|
-
levelChecks,
|
|
541
|
-
decidingLayer,
|
|
542
|
-
decidingId,
|
|
543
|
-
startTime
|
|
544
|
-
) : void 0
|
|
545
|
-
);
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
const roleVerdict = checkRoleRules(event, eventText, world, roleChecks);
|
|
549
|
-
if (roleVerdict) {
|
|
550
|
-
decidingLayer = "role";
|
|
551
|
-
decidingId = roleVerdict.ruleId;
|
|
552
|
-
return buildVerdict(
|
|
553
|
-
roleVerdict.status,
|
|
554
|
-
roleVerdict.reason,
|
|
555
|
-
roleVerdict.ruleId,
|
|
556
|
-
void 0,
|
|
557
|
-
world,
|
|
558
|
-
level,
|
|
559
|
-
invariantChecks,
|
|
560
|
-
guardsMatched,
|
|
561
|
-
rulesMatched,
|
|
562
|
-
includeTrace ? buildTrace(
|
|
563
|
-
invariantChecks,
|
|
564
|
-
safetyChecks,
|
|
565
|
-
planCheckResult,
|
|
566
|
-
roleChecks,
|
|
567
|
-
guardChecks,
|
|
568
|
-
kernelRuleChecks,
|
|
569
|
-
levelChecks,
|
|
570
|
-
decidingLayer,
|
|
571
|
-
decidingId,
|
|
572
|
-
startTime
|
|
573
|
-
) : void 0
|
|
574
|
-
);
|
|
575
|
-
}
|
|
576
|
-
const guardVerdict = checkGuards(event, eventText, world, guardChecks, guardsMatched);
|
|
577
|
-
if (guardVerdict) {
|
|
578
|
-
if (guardVerdict.status !== "ALLOW") {
|
|
579
|
-
decidingLayer = "guard";
|
|
580
|
-
decidingId = guardVerdict.ruleId;
|
|
581
|
-
const intentRecord = {
|
|
582
|
-
originalIntent: event.intent,
|
|
583
|
-
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",
|
|
584
|
-
ruleApplied: guardVerdict.ruleId,
|
|
585
|
-
enforcement: guardVerdict.status,
|
|
586
|
-
modifiedTo: guardVerdict.modifiedTo,
|
|
587
|
-
consequence: guardVerdict.consequence,
|
|
588
|
-
reward: guardVerdict.reward
|
|
589
|
-
};
|
|
590
|
-
const verdict = buildVerdict(
|
|
591
|
-
guardVerdict.status,
|
|
592
|
-
guardVerdict.reason,
|
|
593
|
-
guardVerdict.ruleId,
|
|
594
|
-
void 0,
|
|
595
|
-
world,
|
|
596
|
-
level,
|
|
597
|
-
invariantChecks,
|
|
598
|
-
guardsMatched,
|
|
599
|
-
rulesMatched,
|
|
600
|
-
includeTrace ? buildTrace(
|
|
601
|
-
invariantChecks,
|
|
602
|
-
safetyChecks,
|
|
603
|
-
planCheckResult,
|
|
604
|
-
roleChecks,
|
|
605
|
-
guardChecks,
|
|
606
|
-
kernelRuleChecks,
|
|
607
|
-
levelChecks,
|
|
608
|
-
decidingLayer,
|
|
609
|
-
decidingId,
|
|
610
|
-
startTime
|
|
611
|
-
) : void 0
|
|
612
|
-
);
|
|
613
|
-
verdict.intentRecord = intentRecord;
|
|
614
|
-
if (guardVerdict.consequence) verdict.consequence = guardVerdict.consequence;
|
|
615
|
-
if (guardVerdict.reward) verdict.reward = guardVerdict.reward;
|
|
616
|
-
return verdict;
|
|
617
|
-
}
|
|
618
|
-
}
|
|
619
|
-
const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
|
|
620
|
-
if (kernelVerdict) {
|
|
621
|
-
decidingLayer = "kernel-rule";
|
|
622
|
-
decidingId = kernelVerdict.ruleId;
|
|
623
|
-
return buildVerdict(
|
|
624
|
-
kernelVerdict.status,
|
|
625
|
-
kernelVerdict.reason,
|
|
626
|
-
kernelVerdict.ruleId,
|
|
627
|
-
void 0,
|
|
628
|
-
world,
|
|
629
|
-
level,
|
|
630
|
-
invariantChecks,
|
|
631
|
-
guardsMatched,
|
|
632
|
-
rulesMatched,
|
|
633
|
-
includeTrace ? buildTrace(
|
|
634
|
-
invariantChecks,
|
|
635
|
-
safetyChecks,
|
|
636
|
-
planCheckResult,
|
|
637
|
-
roleChecks,
|
|
638
|
-
guardChecks,
|
|
639
|
-
kernelRuleChecks,
|
|
640
|
-
levelChecks,
|
|
641
|
-
decidingLayer,
|
|
642
|
-
decidingId,
|
|
643
|
-
startTime
|
|
644
|
-
) : void 0
|
|
645
|
-
);
|
|
646
|
-
}
|
|
647
|
-
const levelVerdict = checkLevelConstraints(event, level, levelChecks);
|
|
648
|
-
if (levelVerdict) {
|
|
649
|
-
decidingLayer = "level-constraint";
|
|
650
|
-
decidingId = levelVerdict.ruleId;
|
|
651
|
-
return buildVerdict(
|
|
652
|
-
levelVerdict.status,
|
|
653
|
-
levelVerdict.reason,
|
|
654
|
-
levelVerdict.ruleId,
|
|
655
|
-
void 0,
|
|
656
|
-
world,
|
|
657
|
-
level,
|
|
658
|
-
invariantChecks,
|
|
659
|
-
guardsMatched,
|
|
660
|
-
rulesMatched,
|
|
661
|
-
includeTrace ? buildTrace(
|
|
662
|
-
invariantChecks,
|
|
663
|
-
safetyChecks,
|
|
664
|
-
planCheckResult,
|
|
665
|
-
roleChecks,
|
|
666
|
-
guardChecks,
|
|
667
|
-
kernelRuleChecks,
|
|
668
|
-
levelChecks,
|
|
669
|
-
decidingLayer,
|
|
670
|
-
decidingId,
|
|
671
|
-
startTime
|
|
672
|
-
) : void 0
|
|
673
|
-
);
|
|
674
|
-
}
|
|
675
|
-
const warning = guardVerdict?.warning;
|
|
676
|
-
return buildVerdict(
|
|
677
|
-
"ALLOW",
|
|
678
|
-
void 0,
|
|
679
|
-
void 0,
|
|
680
|
-
warning,
|
|
681
|
-
world,
|
|
682
|
-
level,
|
|
683
|
-
invariantChecks,
|
|
684
|
-
guardsMatched,
|
|
685
|
-
rulesMatched,
|
|
686
|
-
includeTrace ? buildTrace(
|
|
687
|
-
invariantChecks,
|
|
688
|
-
safetyChecks,
|
|
689
|
-
planCheckResult,
|
|
690
|
-
roleChecks,
|
|
691
|
-
guardChecks,
|
|
692
|
-
kernelRuleChecks,
|
|
693
|
-
levelChecks,
|
|
694
|
-
decidingLayer,
|
|
695
|
-
decidingId,
|
|
696
|
-
startTime
|
|
697
|
-
) : void 0
|
|
698
|
-
);
|
|
699
|
-
}
|
|
700
|
-
function checkInvariantCoverage(world, checks) {
|
|
701
|
-
const invariants = world.invariants ?? [];
|
|
702
|
-
const guards = world.guards?.guards ?? [];
|
|
703
|
-
for (const invariant of invariants) {
|
|
704
|
-
const coveringGuard = guards.find(
|
|
705
|
-
(g) => g.invariant_ref === invariant.id && g.immutable
|
|
706
|
-
);
|
|
707
|
-
checks.push({
|
|
708
|
-
invariantId: invariant.id,
|
|
709
|
-
label: invariant.label,
|
|
710
|
-
hasGuardCoverage: !!coveringGuard,
|
|
711
|
-
coveringGuardId: coveringGuard?.id
|
|
712
|
-
});
|
|
713
|
-
}
|
|
714
|
-
}
|
|
715
|
-
function checkSafety(event, eventText, checks) {
|
|
716
|
-
const textToCheck = event.intent + (event.payload ? JSON.stringify(event.payload) : "");
|
|
717
|
-
for (const { pattern, label } of PROMPT_INJECTION_PATTERNS) {
|
|
718
|
-
const triggered = pattern.test(textToCheck);
|
|
719
|
-
checks.push({
|
|
720
|
-
checkType: "prompt-injection",
|
|
721
|
-
triggered,
|
|
722
|
-
matchedPattern: triggered ? label : void 0
|
|
723
|
-
});
|
|
724
|
-
if (triggered) {
|
|
725
|
-
for (const remaining of PROMPT_INJECTION_PATTERNS.filter((p) => p.label !== label)) {
|
|
726
|
-
checks.push({
|
|
727
|
-
checkType: "prompt-injection",
|
|
728
|
-
triggered: remaining.pattern.test(textToCheck),
|
|
729
|
-
matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
|
-
return {
|
|
733
|
-
status: "PAUSE",
|
|
734
|
-
reason: NEUTRAL_MESSAGES["prompt-injection"],
|
|
735
|
-
ruleId: `safety-injection-${label}`
|
|
736
|
-
};
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
const scopeToCheck = event.scope ?? event.intent;
|
|
740
|
-
for (const { pattern, label } of SCOPE_ESCAPE_PATTERNS) {
|
|
741
|
-
const triggered = pattern.test(scopeToCheck);
|
|
742
|
-
checks.push({
|
|
743
|
-
checkType: "scope-escape",
|
|
744
|
-
triggered,
|
|
745
|
-
matchedPattern: triggered ? label : void 0
|
|
746
|
-
});
|
|
747
|
-
if (triggered) {
|
|
748
|
-
for (const remaining of SCOPE_ESCAPE_PATTERNS.filter((p) => p.label !== label)) {
|
|
749
|
-
checks.push({
|
|
750
|
-
checkType: "scope-escape",
|
|
751
|
-
triggered: remaining.pattern.test(scopeToCheck),
|
|
752
|
-
matchedPattern: remaining.pattern.test(scopeToCheck) ? remaining.label : void 0
|
|
753
|
-
});
|
|
754
|
-
}
|
|
755
|
-
return {
|
|
756
|
-
status: "PAUSE",
|
|
757
|
-
reason: NEUTRAL_MESSAGES["scope-escape"],
|
|
758
|
-
ruleId: `safety-scope-${label}`
|
|
759
|
-
};
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
if (event.direction === "output") {
|
|
763
|
-
for (const { pattern, label } of EXECUTION_CLAIM_PATTERNS) {
|
|
764
|
-
const triggered = pattern.test(textToCheck);
|
|
765
|
-
checks.push({
|
|
766
|
-
checkType: "execution-claim",
|
|
767
|
-
triggered,
|
|
768
|
-
matchedPattern: triggered ? label : void 0
|
|
769
|
-
});
|
|
770
|
-
if (triggered) {
|
|
771
|
-
for (const remaining of EXECUTION_CLAIM_PATTERNS.filter((p) => p.label !== label)) {
|
|
772
|
-
checks.push({
|
|
773
|
-
checkType: "execution-claim",
|
|
774
|
-
triggered: remaining.pattern.test(textToCheck),
|
|
775
|
-
matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
return {
|
|
779
|
-
status: "PAUSE",
|
|
780
|
-
reason: NEUTRAL_MESSAGES["execution-claim"],
|
|
781
|
-
ruleId: `safety-execution-claim-${label}`
|
|
782
|
-
};
|
|
783
|
-
}
|
|
784
|
-
}
|
|
785
|
-
}
|
|
786
|
-
if (event.direction === "input") {
|
|
787
|
-
const intentTrimmed = event.intent.trim();
|
|
788
|
-
for (const { pattern, label } of EXECUTION_INTENT_PATTERNS) {
|
|
789
|
-
const triggered = pattern.test(intentTrimmed);
|
|
790
|
-
checks.push({
|
|
791
|
-
checkType: "execution-intent",
|
|
792
|
-
triggered,
|
|
793
|
-
matchedPattern: triggered ? label : void 0
|
|
794
|
-
});
|
|
795
|
-
if (triggered) {
|
|
796
|
-
for (const remaining of EXECUTION_INTENT_PATTERNS.filter((p) => p.label !== label)) {
|
|
797
|
-
checks.push({
|
|
798
|
-
checkType: "execution-intent",
|
|
799
|
-
triggered: remaining.pattern.test(intentTrimmed),
|
|
800
|
-
matchedPattern: remaining.pattern.test(intentTrimmed) ? remaining.label : void 0
|
|
801
|
-
});
|
|
802
|
-
}
|
|
803
|
-
return {
|
|
804
|
-
status: "PAUSE",
|
|
805
|
-
reason: NEUTRAL_MESSAGES["execution-intent"],
|
|
806
|
-
ruleId: `safety-execution-intent-${label}`
|
|
807
|
-
};
|
|
808
|
-
}
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
return null;
|
|
812
|
-
}
|
|
813
|
-
function checkRoleRules(event, eventText, world, checks) {
|
|
814
|
-
if (!event.roleId || !world.roles) return null;
|
|
815
|
-
const role = world.roles.roles.find((r) => r.id === event.roleId);
|
|
816
|
-
if (!role) return null;
|
|
817
|
-
if (role.requiresApproval) {
|
|
818
|
-
checks.push({
|
|
819
|
-
roleId: role.id,
|
|
820
|
-
roleName: role.name,
|
|
821
|
-
rule: "All actions require approval",
|
|
822
|
-
ruleType: "requiresApproval",
|
|
823
|
-
matched: true
|
|
824
|
-
});
|
|
825
|
-
return {
|
|
826
|
-
status: "PAUSE",
|
|
827
|
-
reason: `Role "${role.name}" requires approval for all actions.`,
|
|
828
|
-
ruleId: `role-${role.id}-requires-approval`
|
|
829
|
-
};
|
|
830
|
-
}
|
|
831
|
-
for (const rule of role.cannotDo) {
|
|
832
|
-
const matched = matchesKeywords(eventText, rule);
|
|
833
|
-
checks.push({
|
|
834
|
-
roleId: role.id,
|
|
835
|
-
roleName: role.name,
|
|
836
|
-
rule,
|
|
837
|
-
ruleType: "cannotDo",
|
|
838
|
-
matched
|
|
839
|
-
});
|
|
840
|
-
if (matched) {
|
|
841
|
-
return {
|
|
842
|
-
status: "BLOCK",
|
|
843
|
-
reason: `Role "${role.name}" cannot: ${rule}`,
|
|
844
|
-
ruleId: `role-${role.id}-cannotdo`
|
|
845
|
-
};
|
|
846
|
-
}
|
|
847
|
-
}
|
|
848
|
-
for (const rule of role.canDo) {
|
|
849
|
-
checks.push({
|
|
850
|
-
roleId: role.id,
|
|
851
|
-
roleName: role.name,
|
|
852
|
-
rule,
|
|
853
|
-
ruleType: "canDo",
|
|
854
|
-
matched: matchesKeywords(eventText, rule)
|
|
855
|
-
});
|
|
856
|
-
}
|
|
857
|
-
return null;
|
|
858
|
-
}
|
|
859
|
-
function checkGuards(event, eventText, world, checks, guardsMatched) {
|
|
860
|
-
if (!world.guards) return null;
|
|
861
|
-
const guardsConfig = world.guards;
|
|
862
|
-
let warnResult = null;
|
|
863
|
-
const compiledPatterns = /* @__PURE__ */ new Map();
|
|
864
|
-
for (const [key, def] of Object.entries(guardsConfig.intent_vocabulary)) {
|
|
865
|
-
try {
|
|
866
|
-
compiledPatterns.set(key, new RegExp(def.pattern, "i"));
|
|
867
|
-
} catch {
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
const eventTool = (event.tool ?? "").toLowerCase();
|
|
871
|
-
for (const guard of guardsConfig.guards) {
|
|
872
|
-
if (guard.appliesTo && guard.appliesTo.length > 0) {
|
|
873
|
-
const normalizedAppliesTo = guard.appliesTo.map((t) => t.toLowerCase());
|
|
874
|
-
if (!normalizedAppliesTo.includes(eventTool)) {
|
|
875
|
-
continue;
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
const enabled = guard.immutable || guard.default_enabled !== false;
|
|
879
|
-
const matchedPatterns = [];
|
|
880
|
-
for (const patternKey of guard.intent_patterns) {
|
|
881
|
-
const regex = compiledPatterns.get(patternKey);
|
|
882
|
-
if (regex?.test(eventText)) {
|
|
883
|
-
matchedPatterns.push(patternKey);
|
|
884
|
-
}
|
|
885
|
-
}
|
|
886
|
-
const matched = matchedPatterns.length > 0 && enabled;
|
|
887
|
-
let roleGated = false;
|
|
888
|
-
if (matched && guard.required_roles && guard.required_roles.length > 0 && event.roleId && guard.required_roles.includes(event.roleId)) {
|
|
889
|
-
roleGated = true;
|
|
890
|
-
}
|
|
891
|
-
checks.push({
|
|
892
|
-
guardId: guard.id,
|
|
893
|
-
label: guard.label,
|
|
894
|
-
category: guard.category,
|
|
895
|
-
enabled,
|
|
896
|
-
matched: matched && !roleGated,
|
|
897
|
-
enforcement: guard.enforcement,
|
|
898
|
-
matchedPatterns,
|
|
899
|
-
roleGated
|
|
900
|
-
});
|
|
901
|
-
if (!matched || roleGated) continue;
|
|
902
|
-
guardsMatched.push(guard.id);
|
|
903
|
-
const actionMode = guard.player_modes?.action ?? guard.enforcement;
|
|
904
|
-
const reason = guard.redirect ? `${guard.description} \u2014 ${guard.redirect}` : guard.description;
|
|
905
|
-
if (actionMode === "block") {
|
|
906
|
-
return { status: "BLOCK", reason, ruleId: `guard-${guard.id}` };
|
|
907
|
-
}
|
|
908
|
-
if (actionMode === "pause") {
|
|
909
|
-
return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
|
|
910
|
-
}
|
|
911
|
-
if (actionMode === "penalize") {
|
|
912
|
-
const consequence = guard.consequence ? { ...guard.consequence } : { type: "freeze", rounds: 1, description: `Penalized for violating: ${guard.label}` };
|
|
913
|
-
return { status: "PENALIZE", reason, ruleId: `guard-${guard.id}`, consequence };
|
|
914
|
-
}
|
|
915
|
-
if (actionMode === "reward") {
|
|
916
|
-
const reward = guard.reward ? { ...guard.reward } : { type: "boost_influence", magnitude: 0.1, description: `Rewarded for: ${guard.label}` };
|
|
917
|
-
return { status: "REWARD", reason, ruleId: `guard-${guard.id}`, reward };
|
|
918
|
-
}
|
|
919
|
-
if (actionMode === "modify") {
|
|
920
|
-
const modifiedTo = guard.modify_to ?? guard.redirect ?? "hold";
|
|
921
|
-
return { status: "MODIFY", reason: `${reason} \u2192 Modified to: ${modifiedTo}`, ruleId: `guard-${guard.id}`, modifiedTo };
|
|
922
|
-
}
|
|
923
|
-
if (actionMode === "neutral") {
|
|
924
|
-
return { status: "NEUTRAL", reason, ruleId: `guard-${guard.id}` };
|
|
925
|
-
}
|
|
926
|
-
if (actionMode === "warn" && !warnResult) {
|
|
927
|
-
warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
|
|
928
|
-
}
|
|
929
|
-
}
|
|
930
|
-
return warnResult;
|
|
931
|
-
}
|
|
932
|
-
function checkKernelRules(eventText, world, checks, rulesMatched) {
|
|
933
|
-
if (!world.kernel) return null;
|
|
934
|
-
const forbidden = world.kernel.input_boundaries?.forbidden_patterns ?? [];
|
|
935
|
-
const output = world.kernel.output_boundaries?.forbidden_patterns ?? [];
|
|
936
|
-
for (const rule of forbidden) {
|
|
937
|
-
let matched = false;
|
|
938
|
-
let matchMethod = "none";
|
|
939
|
-
if (rule.pattern) {
|
|
940
|
-
try {
|
|
941
|
-
matched = new RegExp(rule.pattern, "i").test(eventText);
|
|
942
|
-
matchMethod = "pattern";
|
|
943
|
-
} catch {
|
|
944
|
-
}
|
|
945
|
-
}
|
|
946
|
-
if (!matched && rule.reason) {
|
|
947
|
-
matched = matchesKeywords(eventText, rule.reason);
|
|
948
|
-
if (matched) matchMethod = "keyword";
|
|
949
|
-
}
|
|
950
|
-
checks.push({
|
|
951
|
-
ruleId: rule.id,
|
|
952
|
-
text: rule.reason,
|
|
953
|
-
category: "forbidden",
|
|
954
|
-
matched,
|
|
955
|
-
matchMethod
|
|
956
|
-
});
|
|
957
|
-
if (matched) {
|
|
958
|
-
rulesMatched.push(rule.id);
|
|
959
|
-
if (rule.action === "BLOCK") {
|
|
960
|
-
return {
|
|
961
|
-
status: "BLOCK",
|
|
962
|
-
reason: rule.reason,
|
|
963
|
-
ruleId: `kernel-${rule.id}`
|
|
964
|
-
};
|
|
965
|
-
}
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
return null;
|
|
969
|
-
}
|
|
970
|
-
function checkLevelConstraints(event, level, checks) {
|
|
971
|
-
if (level === "basic") return null;
|
|
972
|
-
const intent = event.intent.toLowerCase();
|
|
973
|
-
const tool = (event.tool ?? "").toLowerCase();
|
|
974
|
-
const isDelete = intent.includes("delete") || intent.includes("remove") || intent.includes("rm ") || tool === "delete";
|
|
975
|
-
const deleteTriggered = isDelete && levelRequiresConfirmation(level, "delete");
|
|
976
|
-
checks.push({
|
|
977
|
-
checkType: "delete",
|
|
978
|
-
level,
|
|
979
|
-
triggered: deleteTriggered,
|
|
980
|
-
reason: deleteTriggered ? NEUTRAL_MESSAGES["delete"] : void 0
|
|
981
|
-
});
|
|
982
|
-
if (deleteTriggered) {
|
|
983
|
-
return { status: "PAUSE", reason: NEUTRAL_MESSAGES["delete"], ruleId: "level-delete-check" };
|
|
984
|
-
}
|
|
985
|
-
const isExternal = event.scope ? isExternalScope(event.scope) : false;
|
|
986
|
-
const externalTriggered = isExternal && levelRequiresConfirmation(level, "write-external");
|
|
987
|
-
checks.push({
|
|
988
|
-
checkType: "write-external",
|
|
989
|
-
level,
|
|
990
|
-
triggered: externalTriggered,
|
|
991
|
-
reason: externalTriggered ? NEUTRAL_MESSAGES["write-external"] : void 0
|
|
992
|
-
});
|
|
993
|
-
if (externalTriggered) {
|
|
994
|
-
return { status: "PAUSE", reason: NEUTRAL_MESSAGES["write-external"], ruleId: "level-external-write-check" };
|
|
995
|
-
}
|
|
996
|
-
const isNetwork = tool === "http" || tool === "fetch" || tool === "request" || intent.includes("post ") || intent.includes("sending");
|
|
997
|
-
const networkTriggered = isNetwork && levelRequiresConfirmation(level, "network-mutate");
|
|
998
|
-
checks.push({
|
|
999
|
-
checkType: "network-mutate",
|
|
1000
|
-
level,
|
|
1001
|
-
triggered: networkTriggered,
|
|
1002
|
-
reason: networkTriggered ? NEUTRAL_MESSAGES["network-mutate"] : void 0
|
|
1003
|
-
});
|
|
1004
|
-
if (networkTriggered) {
|
|
1005
|
-
return { status: "PAUSE", reason: NEUTRAL_MESSAGES["network-mutate"], ruleId: "level-network-mutate-check" };
|
|
1006
|
-
}
|
|
1007
|
-
const isCredential = intent.includes("credential") || intent.includes("password") || intent.includes("secret") || intent.includes("api key") || intent.includes("token");
|
|
1008
|
-
const credentialTriggered = isCredential && levelRequiresConfirmation(level, "credential-access");
|
|
1009
|
-
checks.push({
|
|
1010
|
-
checkType: "credential-access",
|
|
1011
|
-
level,
|
|
1012
|
-
triggered: credentialTriggered,
|
|
1013
|
-
reason: credentialTriggered ? NEUTRAL_MESSAGES["credential-access"] : void 0
|
|
1014
|
-
});
|
|
1015
|
-
if (credentialTriggered) {
|
|
1016
|
-
return { status: "PAUSE", reason: NEUTRAL_MESSAGES["credential-access"], ruleId: "level-credential-check" };
|
|
1017
|
-
}
|
|
1018
|
-
const irreversibleTriggered = !!event.irreversible && level !== "basic";
|
|
1019
|
-
checks.push({
|
|
1020
|
-
checkType: "irreversible",
|
|
1021
|
-
level,
|
|
1022
|
-
triggered: irreversibleTriggered,
|
|
1023
|
-
reason: irreversibleTriggered ? "This action is marked as irreversible." : void 0
|
|
1024
|
-
});
|
|
1025
|
-
if (irreversibleTriggered) {
|
|
1026
|
-
return {
|
|
1027
|
-
status: "PAUSE",
|
|
1028
|
-
reason: "This action is marked as irreversible.",
|
|
1029
|
-
ruleId: "level-irreversible-check"
|
|
1030
|
-
};
|
|
1031
|
-
}
|
|
1032
|
-
return null;
|
|
1033
|
-
}
|
|
1034
|
-
function matchesKeywords(eventText, ruleText) {
|
|
1035
|
-
return matchesAllKeywords(eventText, ruleText);
|
|
1036
|
-
}
|
|
1037
|
-
function eventToAllowlistKey(event) {
|
|
1038
|
-
return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
|
|
1039
|
-
}
|
|
1040
|
-
function buildTrace(invariantChecks, safetyChecks, planCheck, roleChecks, guardChecks, kernelRuleChecks, levelChecks, decidingLayer, decidingId, startTime) {
|
|
1041
|
-
const trace = {
|
|
1042
|
-
invariantChecks,
|
|
1043
|
-
safetyChecks,
|
|
1044
|
-
roleChecks,
|
|
1045
|
-
guardChecks,
|
|
1046
|
-
kernelRuleChecks,
|
|
1047
|
-
levelChecks,
|
|
1048
|
-
precedenceResolution: {
|
|
1049
|
-
decidingLayer,
|
|
1050
|
-
decidingId,
|
|
1051
|
-
strategy: "first-match-wins",
|
|
1052
|
-
chainOrder: [
|
|
1053
|
-
"invariant-coverage",
|
|
1054
|
-
"session-allowlist",
|
|
1055
|
-
"safety-injection",
|
|
1056
|
-
"safety-scope-escape",
|
|
1057
|
-
"safety-execution-claim",
|
|
1058
|
-
"safety-execution-intent",
|
|
1059
|
-
"plan-enforcement",
|
|
1060
|
-
"role-rules",
|
|
1061
|
-
"declarative-guards",
|
|
1062
|
-
"kernel-rules",
|
|
1063
|
-
"level-constraints",
|
|
1064
|
-
"default-allow"
|
|
1065
|
-
]
|
|
1066
|
-
},
|
|
1067
|
-
durationMs: performance.now() - startTime
|
|
1068
|
-
};
|
|
1069
|
-
if (planCheck) {
|
|
1070
|
-
trace.planCheck = planCheck;
|
|
1071
|
-
}
|
|
1072
|
-
return trace;
|
|
1073
|
-
}
|
|
1074
|
-
function buildVerdict(status, reason, ruleId, warning, world, level, invariantChecks, guardsMatched, rulesMatched, trace) {
|
|
1075
|
-
const evidence = {
|
|
1076
|
-
worldId: world.world.world_id,
|
|
1077
|
-
worldName: world.world.name,
|
|
1078
|
-
worldVersion: world.world.version,
|
|
1079
|
-
evaluatedAt: Date.now(),
|
|
1080
|
-
invariantsSatisfied: invariantChecks.filter((c) => c.hasGuardCoverage).length,
|
|
1081
|
-
invariantsTotal: invariantChecks.length,
|
|
1082
|
-
guardsMatched,
|
|
1083
|
-
rulesMatched,
|
|
1084
|
-
enforcementLevel: level
|
|
1085
|
-
};
|
|
1086
|
-
const verdict = {
|
|
1087
|
-
status,
|
|
1088
|
-
evidence
|
|
1089
|
-
};
|
|
1090
|
-
if (reason) verdict.reason = reason;
|
|
1091
|
-
if (ruleId) verdict.ruleId = ruleId;
|
|
1092
|
-
if (warning) verdict.warning = warning;
|
|
1093
|
-
if (trace) verdict.trace = trace;
|
|
1094
|
-
return verdict;
|
|
1095
|
-
}
|
|
1096
|
-
var PROMPT_INJECTION_PATTERNS, EXECUTION_CLAIM_PATTERNS, EXECUTION_INTENT_PATTERNS, SCOPE_ESCAPE_PATTERNS, NEUTRAL_MESSAGES;
|
|
1097
|
-
var init_guard_engine = __esm({
|
|
1098
|
-
"src/engine/guard-engine.ts"() {
|
|
1099
|
-
"use strict";
|
|
1100
|
-
init_plan_engine();
|
|
1101
|
-
init_text_utils();
|
|
1102
|
-
PROMPT_INJECTION_PATTERNS = [
|
|
1103
|
-
// Instruction override
|
|
1104
|
-
{ pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
|
|
1105
|
-
{ pattern: /disregard\s+(your|the)\s+(rules|constraints)/i, label: "disregard-rules" },
|
|
1106
|
-
{ pattern: /new\s+instructions?:/i, label: "new-instructions" },
|
|
1107
|
-
// Identity manipulation
|
|
1108
|
-
{ pattern: /you\s+are\s+now/i, label: "identity-override" },
|
|
1109
|
-
{ pattern: /new\s+persona/i, label: "new-persona" },
|
|
1110
|
-
{ pattern: /act\s+as\s+if/i, label: "act-as-if" },
|
|
1111
|
-
{ pattern: /pretend\s+(you|to\s+be|you\s+are\s+unrestricted)/i, label: "pretend-to-be" },
|
|
1112
|
-
// Context reset
|
|
1113
|
-
{ pattern: /forget\s+(everything|all|your)/i, label: "forget-context" },
|
|
1114
|
-
{ pattern: /system\s*:\s*override/i, label: "system-override" },
|
|
1115
|
-
// Constraint bypass
|
|
1116
|
-
{ pattern: /override\s+(your|the)\s+(programming|constraints)/i, label: "override-constraints" },
|
|
1117
|
-
{ pattern: /bypass\s+(your|the)\s+(filters|constraints|rules)/i, label: "bypass-filters" },
|
|
1118
|
-
// Prompt extraction
|
|
1119
|
-
{ pattern: /system\s+prompt/i, label: "system-prompt-probe" },
|
|
1120
|
-
{ pattern: /reveal\s+your\s+(instructions?|prompt|rules)/i, label: "reveal-instructions" },
|
|
1121
|
-
// Known jailbreak terms
|
|
1122
|
-
{ pattern: /jailbreak/i, label: "jailbreak" },
|
|
1123
|
-
{ pattern: /DAN\s+mode/i, label: "dan-mode" },
|
|
1124
|
-
{ pattern: /developer\s+mode/i, label: "developer-mode" }
|
|
1125
|
-
];
|
|
1126
|
-
EXECUTION_CLAIM_PATTERNS = [
|
|
1127
|
-
{ pattern: /I have (executed|completed|performed|done|made|created|sent|deleted|modified|updated)/i, label: "claim-i-have" },
|
|
1128
|
-
{ pattern: /Successfully (created|deleted|modified|updated|sent|executed|performed)/i, label: "claim-successfully" },
|
|
1129
|
-
{ pattern: /The file has been/i, label: "claim-file-modified" },
|
|
1130
|
-
{ pattern: /I've made the changes/i, label: "claim-made-changes" },
|
|
1131
|
-
{ pattern: /I('ve| have) (sent|posted|submitted|uploaded|downloaded)/i, label: "claim-sent" },
|
|
1132
|
-
{ pattern: /Your (email|message|file|request) has been (sent|submitted)/i, label: "claim-your-sent" },
|
|
1133
|
-
{ pattern: /Transaction complete/i, label: "claim-transaction" },
|
|
1134
|
-
{ pattern: /Order placed/i, label: "claim-order" },
|
|
1135
|
-
{ pattern: /Payment processed/i, label: "claim-payment" }
|
|
1136
|
-
];
|
|
1137
|
-
EXECUTION_INTENT_PATTERNS = [
|
|
1138
|
-
{ pattern: /^(execute|run|perform|do this)/i, label: "intent-execute" },
|
|
1139
|
-
{ pattern: /^(create|write|delete|modify) (a |the )?(file|folder|document)/i, label: "intent-file-ops" },
|
|
1140
|
-
{ pattern: /^(send|post|submit) (a |an |the )?(email|message|tweet|post)/i, label: "intent-send" },
|
|
1141
|
-
{ pattern: /^(search|look up|browse) (the )?web/i, label: "intent-web-search" },
|
|
1142
|
-
{ pattern: /^(make|call|invoke) (a |an )?(api|http|rest) (call|request)/i, label: "intent-api-call" },
|
|
1143
|
-
{ pattern: /^(buy|purchase|order|pay|transfer|send money)/i, label: "intent-financial" },
|
|
1144
|
-
{ pattern: /^(book|schedule|reserve)/i, label: "intent-booking" },
|
|
1145
|
-
{ pattern: /^(download|upload|save to|export to)/i, label: "intent-transfer" }
|
|
1146
|
-
];
|
|
1147
|
-
SCOPE_ESCAPE_PATTERNS = [
|
|
1148
|
-
{ pattern: /\.\.\//, label: "parent-traversal" },
|
|
1149
|
-
{ pattern: /^\/(?!home|project|workspace)/i, label: "absolute-path-outside-safe" },
|
|
1150
|
-
{ pattern: /~\//, label: "home-directory" },
|
|
1151
|
-
{ pattern: /\/etc\//i, label: "system-config" },
|
|
1152
|
-
{ pattern: /\/usr\//i, label: "system-binaries" },
|
|
1153
|
-
{ pattern: /\/var\//i, label: "system-variable-data" }
|
|
1154
|
-
];
|
|
1155
|
-
NEUTRAL_MESSAGES = {
|
|
1156
|
-
"prompt-injection": "This input contains patterns that could alter agent behavior.",
|
|
1157
|
-
"scope-escape": "This action would affect resources outside the declared scope.",
|
|
1158
|
-
"execution-claim": "This response claims to have performed an action.",
|
|
1159
|
-
"execution-intent": "This input requests execution in a thinking-only environment.",
|
|
1160
|
-
"delete": "This action would remove files. Confirmation needed.",
|
|
1161
|
-
"write-external": "This action would write outside the project folder.",
|
|
1162
|
-
"network-mutate": "This action would send data to an external service.",
|
|
1163
|
-
"credential-access": "This action would access stored credentials."
|
|
1164
|
-
};
|
|
1165
|
-
}
|
|
1166
|
-
});
|
|
1167
|
-
|
|
1168
|
-
// src/cli/plan.ts
|
|
1169
|
-
var plan_exports = {};
|
|
1170
|
-
__export(plan_exports, {
|
|
1171
|
-
main: () => main
|
|
1172
|
-
});
|
|
1173
|
-
module.exports = __toCommonJS(plan_exports);
|
|
1174
|
-
var import_fs = require("fs");
|
|
1175
|
-
|
|
1176
|
-
// src/engine/plan-parser.ts
|
|
1177
|
-
function slugify(text) {
|
|
1178
|
-
return text.toLowerCase().replace(/[^a-z0-9\s]/g, "").trim().replace(/\s+/g, "_");
|
|
1179
|
-
}
|
|
1180
|
-
function extractBracketAnnotation(line, key) {
|
|
1181
|
-
const regex = new RegExp(`\\[${key}:\\s*([^\\]]+)\\]`, "i");
|
|
1182
|
-
const match = line.match(regex);
|
|
1183
|
-
if (!match) return null;
|
|
1184
|
-
return match[1].split(",").map((s) => s.trim()).filter(Boolean);
|
|
1185
|
-
}
|
|
1186
|
-
function extractParenAnnotation(line, key) {
|
|
1187
|
-
const regex = new RegExp(`\\(${key}:\\s*([^)]+)\\)`, "i");
|
|
1188
|
-
const match = line.match(regex);
|
|
1189
|
-
if (!match) return null;
|
|
1190
|
-
return match[1].split(",").map((s) => s.trim()).filter(Boolean);
|
|
1191
|
-
}
|
|
1192
|
-
function stripAnnotations(line) {
|
|
1193
|
-
return line.replace(/\[(?:tools|tag|verify|type):\s*[^\]]+\]/gi, "").replace(/\((?:after):\s*[^)]+\)/gi, "").trim();
|
|
1194
|
-
}
|
|
1195
|
-
function parseFrontmatter(content) {
|
|
1196
|
-
const frontmatter = {};
|
|
1197
|
-
const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n/);
|
|
1198
|
-
if (!fmMatch) {
|
|
1199
|
-
return { frontmatter, body: content };
|
|
1200
|
-
}
|
|
1201
|
-
const fmBody = fmMatch[1];
|
|
1202
|
-
for (const line of fmBody.split("\n")) {
|
|
1203
|
-
const colonIndex = line.indexOf(":");
|
|
1204
|
-
if (colonIndex > 0) {
|
|
1205
|
-
const key = line.slice(0, colonIndex).trim();
|
|
1206
|
-
const value = line.slice(colonIndex + 1).trim();
|
|
1207
|
-
frontmatter[key] = value;
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
return { frontmatter, body: content.slice(fmMatch[0].length) };
|
|
1211
|
-
}
|
|
1212
|
-
function parseSections(body) {
|
|
1213
|
-
const steps = [];
|
|
1214
|
-
const constraints = [];
|
|
1215
|
-
let currentSection = "none";
|
|
1216
|
-
for (const line of body.split("\n")) {
|
|
1217
|
-
const trimmed = line.trim();
|
|
1218
|
-
if (/^#+\s*Steps/i.test(trimmed)) {
|
|
1219
|
-
currentSection = "steps";
|
|
1220
|
-
continue;
|
|
1221
|
-
}
|
|
1222
|
-
if (/^#+\s*Constraints/i.test(trimmed)) {
|
|
1223
|
-
currentSection = "constraints";
|
|
1224
|
-
continue;
|
|
1225
|
-
}
|
|
1226
|
-
if (/^#+\s/.test(trimmed) && currentSection !== "none") {
|
|
1227
|
-
currentSection = "none";
|
|
1228
|
-
continue;
|
|
1229
|
-
}
|
|
1230
|
-
if (trimmed.startsWith("- ")) {
|
|
1231
|
-
const item = trimmed.slice(2).trim();
|
|
1232
|
-
if (currentSection === "steps") {
|
|
1233
|
-
steps.push(item);
|
|
1234
|
-
} else if (currentSection === "constraints") {
|
|
1235
|
-
constraints.push(item);
|
|
1236
|
-
}
|
|
1237
|
-
}
|
|
1238
|
-
}
|
|
1239
|
-
return { steps, constraints };
|
|
1240
|
-
}
|
|
1241
|
-
function parseStep(raw) {
|
|
1242
|
-
const label = stripAnnotations(raw);
|
|
1243
|
-
const id = slugify(label);
|
|
1244
|
-
const tools = extractBracketAnnotation(raw, "tools");
|
|
1245
|
-
const tags = extractBracketAnnotation(raw, "tag");
|
|
1246
|
-
const verifyArr = extractBracketAnnotation(raw, "verify");
|
|
1247
|
-
const requires = extractParenAnnotation(raw, "after");
|
|
1248
|
-
return {
|
|
1249
|
-
id,
|
|
1250
|
-
label,
|
|
1251
|
-
tools: tools ?? void 0,
|
|
1252
|
-
tags: tags ?? void 0,
|
|
1253
|
-
verify: verifyArr?.[0] ?? void 0,
|
|
1254
|
-
requires: requires ?? void 0,
|
|
1255
|
-
status: "pending"
|
|
1256
|
-
};
|
|
1257
|
-
}
|
|
1258
|
-
function parseConstraint(raw, index) {
|
|
1259
|
-
const typeAnnotation = extractBracketAnnotation(raw, "type");
|
|
1260
|
-
const description = stripAnnotations(raw);
|
|
1261
|
-
const id = `constraint_${index}`;
|
|
1262
|
-
let type = "custom";
|
|
1263
|
-
let enforcement = "block";
|
|
1264
|
-
let limit;
|
|
1265
|
-
let unit;
|
|
1266
|
-
if (typeAnnotation?.[0] === "approval") {
|
|
1267
|
-
type = "approval";
|
|
1268
|
-
enforcement = "pause";
|
|
1269
|
-
} else if (/budget|\$|spending|cost/i.test(description)) {
|
|
1270
|
-
type = "budget";
|
|
1271
|
-
const amountMatch = description.match(/\$?([\d,]+)/);
|
|
1272
|
-
if (amountMatch) {
|
|
1273
|
-
limit = parseInt(amountMatch[1].replace(/,/g, ""), 10);
|
|
1274
|
-
unit = "USD";
|
|
1275
|
-
}
|
|
1276
|
-
} else if (/time|hour|minute|day|deadline/i.test(description)) {
|
|
1277
|
-
type = "time";
|
|
1278
|
-
} else if (/scope|access|database|production/i.test(description)) {
|
|
1279
|
-
type = "scope";
|
|
1280
|
-
}
|
|
1281
|
-
const trigger = description.toLowerCase();
|
|
1282
|
-
return {
|
|
1283
|
-
id,
|
|
1284
|
-
type,
|
|
1285
|
-
description,
|
|
1286
|
-
enforcement,
|
|
1287
|
-
limit,
|
|
1288
|
-
unit,
|
|
1289
|
-
trigger
|
|
1290
|
-
};
|
|
1291
|
-
}
|
|
1292
|
-
function parsePlanMarkdown(markdown) {
|
|
1293
|
-
const errors = [];
|
|
1294
|
-
const { frontmatter, body } = parseFrontmatter(markdown.trim());
|
|
1295
|
-
const { steps: stepLines, constraints: constraintLines } = parseSections(body);
|
|
1296
|
-
if (!frontmatter.plan_id) {
|
|
1297
|
-
errors.push("Missing required field: plan_id");
|
|
1298
|
-
}
|
|
1299
|
-
if (stepLines.length === 0) {
|
|
1300
|
-
errors.push("Plan must have at least one step");
|
|
1301
|
-
}
|
|
1302
|
-
if (errors.length > 0) {
|
|
1303
|
-
return { success: false, errors };
|
|
1304
|
-
}
|
|
1305
|
-
const steps = stepLines.map((line) => parseStep(line));
|
|
1306
|
-
const constraints = constraintLines.map((line, i) => parseConstraint(line, i));
|
|
1307
|
-
let expires_at;
|
|
1308
|
-
if (frontmatter.expires) {
|
|
1309
|
-
expires_at = new Date(frontmatter.expires).toISOString();
|
|
1310
|
-
}
|
|
1311
|
-
const completionRaw = frontmatter.completion?.toLowerCase();
|
|
1312
|
-
const completion = completionRaw === "verified" ? "verified" : "trust";
|
|
1313
|
-
const plan = {
|
|
1314
|
-
plan_id: frontmatter.plan_id,
|
|
1315
|
-
objective: frontmatter.objective ?? "",
|
|
1316
|
-
sequential: frontmatter.sequential === "true",
|
|
1317
|
-
completion,
|
|
1318
|
-
steps,
|
|
1319
|
-
constraints,
|
|
1320
|
-
world_id: frontmatter.world ?? void 0,
|
|
1321
|
-
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1322
|
-
expires_at
|
|
1323
|
-
};
|
|
1324
|
-
return { success: true, plan, errors: [] };
|
|
1325
|
-
}
|
|
1326
|
-
|
|
1327
|
-
// src/cli/plan.ts
|
|
1328
|
-
init_plan_engine();
|
|
1329
|
-
|
|
1330
|
-
// src/contracts/plan-contract.ts
|
|
1331
|
-
var PLAN_EXIT_CODES = {
|
|
1332
|
-
ON_PLAN: 0,
|
|
1333
|
-
OFF_PLAN: 1,
|
|
1334
|
-
CONSTRAINT_VIOLATED: 2,
|
|
1335
|
-
ERROR: 3,
|
|
1336
|
-
PLAN_COMPLETE: 4
|
|
1337
|
-
};
|
|
1338
|
-
|
|
1339
|
-
// src/cli/cli-utils.ts
|
|
1340
|
-
async function readStdin() {
|
|
1341
|
-
const chunks = [];
|
|
1342
|
-
for await (const chunk of process.stdin) {
|
|
1343
|
-
chunks.push(chunk);
|
|
1344
|
-
}
|
|
1345
|
-
return Buffer.concat(chunks).toString("utf-8");
|
|
1346
|
-
}
|
|
1347
|
-
|
|
1348
|
-
// src/cli/plan.ts
|
|
1349
|
-
function parseArg(args, flag) {
|
|
1350
|
-
const idx = args.indexOf(flag);
|
|
1351
|
-
return idx >= 0 && idx + 1 < args.length ? args[idx + 1] : void 0;
|
|
1352
|
-
}
|
|
1353
|
-
async function compileCommand(args) {
|
|
1354
|
-
const inputPath = args.find((a) => !a.startsWith("--"));
|
|
1355
|
-
if (!inputPath) {
|
|
1356
|
-
process.stderr.write("Usage: neuroverse plan compile <plan.md> [--output plan.json]\n");
|
|
1357
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1358
|
-
return;
|
|
1359
|
-
}
|
|
1360
|
-
const outputPath = parseArg(args, "--output") ?? inputPath.replace(/\.md$/, ".json");
|
|
1361
|
-
let markdown;
|
|
1362
|
-
try {
|
|
1363
|
-
markdown = (0, import_fs.readFileSync)(inputPath, "utf-8");
|
|
1364
|
-
} catch (err) {
|
|
1365
|
-
process.stderr.write(`Error reading ${inputPath}: ${err}
|
|
1366
|
-
`);
|
|
1367
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1368
|
-
return;
|
|
1369
|
-
}
|
|
1370
|
-
const result = parsePlanMarkdown(markdown);
|
|
1371
|
-
if (!result.success || !result.plan) {
|
|
1372
|
-
process.stderr.write(`Parse errors:
|
|
1373
|
-
`);
|
|
1374
|
-
for (const error of result.errors) {
|
|
1375
|
-
process.stderr.write(` - ${error}
|
|
1376
|
-
`);
|
|
1377
|
-
}
|
|
1378
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1379
|
-
return;
|
|
1380
|
-
}
|
|
1381
|
-
(0, import_fs.writeFileSync)(outputPath, JSON.stringify(result.plan, null, 2) + "\n");
|
|
1382
|
-
const plan = result.plan;
|
|
1383
|
-
process.stdout.write(`Plan compiled: ${plan.plan_id}
|
|
1384
|
-
`);
|
|
1385
|
-
process.stdout.write(` Objective: ${plan.objective}
|
|
1386
|
-
`);
|
|
1387
|
-
process.stdout.write(` Steps: ${plan.steps.length}
|
|
1388
|
-
`);
|
|
1389
|
-
process.stdout.write(` Constraints: ${plan.constraints.length}
|
|
1390
|
-
`);
|
|
1391
|
-
process.stdout.write(` Sequential: ${plan.sequential}
|
|
1392
|
-
`);
|
|
1393
|
-
process.stdout.write(` Completion: ${plan.completion}
|
|
1394
|
-
`);
|
|
1395
|
-
if (plan.world_id) process.stdout.write(` World: ${plan.world_id}
|
|
1396
|
-
`);
|
|
1397
|
-
if (plan.expires_at) process.stdout.write(` Expires: ${plan.expires_at}
|
|
1398
|
-
`);
|
|
1399
|
-
process.stdout.write(` Output: ${outputPath}
|
|
1400
|
-
`);
|
|
1401
|
-
}
|
|
1402
|
-
async function checkCommand(args) {
|
|
1403
|
-
const planPath = parseArg(args, "--plan");
|
|
1404
|
-
if (!planPath) {
|
|
1405
|
-
process.stderr.write(`Usage: echo '{"intent":"..."}' | neuroverse plan check --plan plan.json
|
|
1406
|
-
`);
|
|
1407
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1408
|
-
return;
|
|
1409
|
-
}
|
|
1410
|
-
let plan;
|
|
1411
|
-
try {
|
|
1412
|
-
plan = JSON.parse((0, import_fs.readFileSync)(planPath, "utf-8"));
|
|
1413
|
-
} catch (err) {
|
|
1414
|
-
process.stderr.write(`Error reading plan: ${err}
|
|
1415
|
-
`);
|
|
1416
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1417
|
-
return;
|
|
1418
|
-
}
|
|
1419
|
-
const stdinData = await readStdin();
|
|
1420
|
-
let event;
|
|
1421
|
-
try {
|
|
1422
|
-
event = JSON.parse(stdinData);
|
|
1423
|
-
} catch {
|
|
1424
|
-
process.stderr.write('Error: stdin must be valid JSON with an "intent" field.\n');
|
|
1425
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1426
|
-
return;
|
|
1427
|
-
}
|
|
1428
|
-
if (!event.intent) {
|
|
1429
|
-
process.stderr.write('Error: event must have an "intent" field.\n');
|
|
1430
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1431
|
-
return;
|
|
1432
|
-
}
|
|
1433
|
-
const worldPath = parseArg(args, "--world");
|
|
1434
|
-
if (worldPath) {
|
|
1435
|
-
const { loadWorld: loadWorld2 } = await Promise.resolve().then(() => (init_world_loader(), world_loader_exports));
|
|
1436
|
-
const { evaluateGuard: evaluateGuard2 } = await Promise.resolve().then(() => (init_guard_engine(), guard_engine_exports));
|
|
1437
|
-
const world = await loadWorld2(worldPath);
|
|
1438
|
-
const verdict2 = evaluateGuard2(event, world, { plan });
|
|
1439
|
-
process.stdout.write(JSON.stringify(verdict2, null, 2) + "\n");
|
|
1440
|
-
const exitCode2 = verdict2.status === "ALLOW" ? 0 : verdict2.status === "BLOCK" ? 1 : 2;
|
|
1441
|
-
process.exit(exitCode2);
|
|
1442
|
-
return;
|
|
1443
|
-
}
|
|
1444
|
-
const verdict = evaluatePlan(event, plan);
|
|
1445
|
-
process.stdout.write(JSON.stringify(verdict, null, 2) + "\n");
|
|
1446
|
-
const exitCode = PLAN_EXIT_CODES[verdict.status] ?? PLAN_EXIT_CODES.ERROR;
|
|
1447
|
-
process.exit(exitCode);
|
|
1448
|
-
}
|
|
1449
|
-
async function statusCommand(args) {
|
|
1450
|
-
const planPath = parseArg(args, "--plan");
|
|
1451
|
-
if (!planPath) {
|
|
1452
|
-
process.stderr.write("Usage: neuroverse plan status --plan plan.json\n");
|
|
1453
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1454
|
-
return;
|
|
1455
|
-
}
|
|
1456
|
-
let plan;
|
|
1457
|
-
try {
|
|
1458
|
-
plan = JSON.parse((0, import_fs.readFileSync)(planPath, "utf-8"));
|
|
1459
|
-
} catch (err) {
|
|
1460
|
-
process.stderr.write(`Error reading plan: ${err}
|
|
1461
|
-
`);
|
|
1462
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1463
|
-
return;
|
|
1464
|
-
}
|
|
1465
|
-
const progress = getPlanProgress(plan);
|
|
1466
|
-
process.stdout.write(`Plan: ${plan.plan_id}
|
|
1467
|
-
`);
|
|
1468
|
-
process.stdout.write(`Objective: ${plan.objective}
|
|
1469
|
-
`);
|
|
1470
|
-
process.stdout.write(`Completion: ${plan.completion ?? "trust"}
|
|
1471
|
-
`);
|
|
1472
|
-
process.stdout.write(`Progress: ${progress.completed}/${progress.total} (${progress.percentage}%)
|
|
1473
|
-
`);
|
|
1474
|
-
process.stdout.write(`
|
|
1475
|
-
Steps:
|
|
1476
|
-
`);
|
|
1477
|
-
for (const step of plan.steps) {
|
|
1478
|
-
const status = step.status === "completed" ? "[x]" : step.status === "active" ? "[>]" : step.status === "skipped" ? "[-]" : "[ ]";
|
|
1479
|
-
let line = ` ${status} ${step.label}`;
|
|
1480
|
-
if (step.tags?.length) line += ` [tag: ${step.tags.join(", ")}]`;
|
|
1481
|
-
if (step.verify) line += ` [verify: ${step.verify}]`;
|
|
1482
|
-
if (step.requires?.length) line += ` (after: ${step.requires.join(", ")})`;
|
|
1483
|
-
process.stdout.write(line + "\n");
|
|
1484
|
-
}
|
|
1485
|
-
if (plan.constraints.length > 0) {
|
|
1486
|
-
process.stdout.write(`
|
|
1487
|
-
Constraints:
|
|
1488
|
-
`);
|
|
1489
|
-
for (const c of plan.constraints) {
|
|
1490
|
-
process.stdout.write(` - ${c.description} [${c.type}/${c.enforcement}]
|
|
1491
|
-
`);
|
|
1492
|
-
}
|
|
1493
|
-
}
|
|
1494
|
-
}
|
|
1495
|
-
async function advanceCommand(args) {
|
|
1496
|
-
const stepId = args.find((a) => !a.startsWith("--"));
|
|
1497
|
-
const planPath = parseArg(args, "--plan");
|
|
1498
|
-
if (!stepId || !planPath) {
|
|
1499
|
-
process.stderr.write("Usage: neuroverse plan advance <step_id> --plan plan.json [--evidence <type> --proof <proof>]\n");
|
|
1500
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1501
|
-
return;
|
|
1502
|
-
}
|
|
1503
|
-
let plan;
|
|
1504
|
-
try {
|
|
1505
|
-
plan = JSON.parse((0, import_fs.readFileSync)(planPath, "utf-8"));
|
|
1506
|
-
} catch (err) {
|
|
1507
|
-
process.stderr.write(`Error reading plan: ${err}
|
|
1508
|
-
`);
|
|
1509
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1510
|
-
return;
|
|
1511
|
-
}
|
|
1512
|
-
const evidenceType = parseArg(args, "--evidence");
|
|
1513
|
-
const evidenceProof = parseArg(args, "--proof");
|
|
1514
|
-
let evidence;
|
|
1515
|
-
if (evidenceType && evidenceProof) {
|
|
1516
|
-
evidence = {
|
|
1517
|
-
type: evidenceType,
|
|
1518
|
-
proof: evidenceProof,
|
|
1519
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
1520
|
-
};
|
|
1521
|
-
} else if (evidenceType || evidenceProof) {
|
|
1522
|
-
process.stderr.write("Error: --evidence and --proof must both be provided.\n");
|
|
1523
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1524
|
-
return;
|
|
1525
|
-
}
|
|
1526
|
-
const result = advancePlan(plan, stepId, evidence);
|
|
1527
|
-
if (!result.success) {
|
|
1528
|
-
process.stderr.write(`Error: ${result.reason}
|
|
1529
|
-
`);
|
|
1530
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1531
|
-
return;
|
|
1532
|
-
}
|
|
1533
|
-
(0, import_fs.writeFileSync)(planPath, JSON.stringify(result.plan, null, 2) + "\n");
|
|
1534
|
-
const progress = getPlanProgress(result.plan);
|
|
1535
|
-
const step = plan.steps.find((s) => s.id === stepId);
|
|
1536
|
-
process.stdout.write(`Step completed: ${step.label}
|
|
1537
|
-
`);
|
|
1538
|
-
if (result.evidence) {
|
|
1539
|
-
process.stdout.write(`Evidence: ${result.evidence.type} = ${result.evidence.proof}
|
|
1540
|
-
`);
|
|
1541
|
-
}
|
|
1542
|
-
process.stdout.write(`Progress: ${progress.completed}/${progress.total} (${progress.percentage}%)
|
|
1543
|
-
`);
|
|
1544
|
-
if (progress.completed === progress.total) {
|
|
1545
|
-
process.stdout.write(`
|
|
1546
|
-
Plan complete!
|
|
1547
|
-
`);
|
|
1548
|
-
}
|
|
1549
|
-
}
|
|
1550
|
-
async function deriveCommand(args) {
|
|
1551
|
-
const inputPath = args.find((a) => !a.startsWith("--"));
|
|
1552
|
-
if (!inputPath) {
|
|
1553
|
-
process.stderr.write("Usage: neuroverse plan derive <plan.md> [--output ./world/]\n");
|
|
1554
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1555
|
-
return;
|
|
1556
|
-
}
|
|
1557
|
-
const outputDir = parseArg(args, "--output") ?? "./derived-world/";
|
|
1558
|
-
let markdown;
|
|
1559
|
-
try {
|
|
1560
|
-
markdown = (0, import_fs.readFileSync)(inputPath, "utf-8");
|
|
1561
|
-
} catch (err) {
|
|
1562
|
-
process.stderr.write(`Error reading ${inputPath}: ${err}
|
|
1563
|
-
`);
|
|
1564
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1565
|
-
return;
|
|
1566
|
-
}
|
|
1567
|
-
const result = parsePlanMarkdown(markdown);
|
|
1568
|
-
if (!result.success || !result.plan) {
|
|
1569
|
-
process.stderr.write(`Parse errors:
|
|
1570
|
-
`);
|
|
1571
|
-
for (const error of result.errors) {
|
|
1572
|
-
process.stderr.write(` - ${error}
|
|
1573
|
-
`);
|
|
1574
|
-
}
|
|
1575
|
-
process.exit(PLAN_EXIT_CODES.ERROR);
|
|
1576
|
-
return;
|
|
1577
|
-
}
|
|
1578
|
-
const plan = result.plan;
|
|
1579
|
-
const { mkdirSync } = await import("fs");
|
|
1580
|
-
mkdirSync(outputDir, { recursive: true });
|
|
1581
|
-
const worldJson = {
|
|
1582
|
-
world_id: `plan_${plan.plan_id}`,
|
|
1583
|
-
name: `Derived: ${plan.objective}`,
|
|
1584
|
-
thesis: plan.objective,
|
|
1585
|
-
version: "1.0.0",
|
|
1586
|
-
runtime_mode: "COMPLIANCE",
|
|
1587
|
-
default_assumption_profile: "default",
|
|
1588
|
-
default_alternative_profile: "default",
|
|
1589
|
-
modules: ["governance"],
|
|
1590
|
-
players: { thinking_space: true, experience_space: false, action_space: true }
|
|
1591
|
-
};
|
|
1592
|
-
const invariants = plan.constraints.map((c, i) => ({
|
|
1593
|
-
id: `inv_${c.id}`,
|
|
1594
|
-
label: c.description,
|
|
1595
|
-
type: "structural",
|
|
1596
|
-
enforcement: c.enforcement === "block" ? "hard" : "soft"
|
|
1597
|
-
}));
|
|
1598
|
-
const guards = {
|
|
1599
|
-
intent_vocabulary: {},
|
|
1600
|
-
guards: plan.steps.map((step) => {
|
|
1601
|
-
const patternKey = `plan_step_${step.id}`;
|
|
1602
|
-
return {
|
|
1603
|
-
id: `guard_${step.id}`,
|
|
1604
|
-
label: `Plan step: ${step.label}`,
|
|
1605
|
-
description: `Governs execution of plan step: ${step.label}`,
|
|
1606
|
-
category: "operational",
|
|
1607
|
-
enforcement: "warn",
|
|
1608
|
-
intent_patterns: [patternKey],
|
|
1609
|
-
appliesTo: step.tools ?? [],
|
|
1610
|
-
default_enabled: true,
|
|
1611
|
-
immutable: false
|
|
1612
|
-
};
|
|
1613
|
-
})
|
|
1614
|
-
};
|
|
1615
|
-
for (const step of plan.steps) {
|
|
1616
|
-
const keywords = step.label.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
|
|
1617
|
-
const pattern = keywords.map((k) => `(?=.*${k})`).join("") + ".*";
|
|
1618
|
-
guards.intent_vocabulary[`plan_step_${step.id}`] = {
|
|
1619
|
-
pattern,
|
|
1620
|
-
description: step.label
|
|
1621
|
-
};
|
|
1622
|
-
}
|
|
1623
|
-
(0, import_fs.writeFileSync)(`${outputDir}/world.json`, JSON.stringify(worldJson, null, 2) + "\n");
|
|
1624
|
-
(0, import_fs.writeFileSync)(`${outputDir}/invariants.json`, JSON.stringify(invariants, null, 2) + "\n");
|
|
1625
|
-
(0, import_fs.writeFileSync)(`${outputDir}/guards.json`, JSON.stringify(guards, null, 2) + "\n");
|
|
1626
|
-
process.stdout.write(`World derived from plan: ${plan.plan_id}
|
|
1627
|
-
`);
|
|
1628
|
-
process.stdout.write(` Output: ${outputDir}
|
|
1629
|
-
`);
|
|
1630
|
-
process.stdout.write(` Files: world.json, invariants.json, guards.json
|
|
1631
|
-
`);
|
|
1632
|
-
process.stdout.write(` Guards: ${plan.steps.length} (one per step)
|
|
1633
|
-
`);
|
|
1634
|
-
process.stdout.write(` Invariants: ${plan.constraints.length} (one per constraint)
|
|
1635
|
-
`);
|
|
1636
|
-
}
|
|
1637
|
-
var PLAN_USAGE = `
|
|
1638
|
-
neuroverse plan \u2014 Plan enforcement for AI agents.
|
|
1639
|
-
|
|
1640
|
-
Subcommands:
|
|
1641
|
-
compile Parse plan markdown into plan.json
|
|
1642
|
-
check Check an action against a plan (stdin \u2192 stdout)
|
|
1643
|
-
status Show plan progress
|
|
1644
|
-
advance Mark a step as completed
|
|
1645
|
-
derive Generate a full world from a plan
|
|
1646
|
-
|
|
1647
|
-
Usage:
|
|
1648
|
-
neuroverse plan compile <plan.md> [--output plan.json]
|
|
1649
|
-
echo '{"intent":"..."}' | neuroverse plan check --plan plan.json [--world ./world/]
|
|
1650
|
-
neuroverse plan status --plan plan.json
|
|
1651
|
-
neuroverse plan advance <step_id> --plan plan.json
|
|
1652
|
-
neuroverse plan derive <plan.md> [--output ./world/]
|
|
1653
|
-
`.trim();
|
|
1654
|
-
async function main(args) {
|
|
1655
|
-
const subcommand = args[0];
|
|
1656
|
-
const subArgs = args.slice(1);
|
|
1657
|
-
switch (subcommand) {
|
|
1658
|
-
case "compile":
|
|
1659
|
-
return compileCommand(subArgs);
|
|
1660
|
-
case "check":
|
|
1661
|
-
return checkCommand(subArgs);
|
|
1662
|
-
case "status":
|
|
1663
|
-
return statusCommand(subArgs);
|
|
1664
|
-
case "advance":
|
|
1665
|
-
return advanceCommand(subArgs);
|
|
1666
|
-
case "derive":
|
|
1667
|
-
return deriveCommand(subArgs);
|
|
1668
|
-
case "--help":
|
|
1669
|
-
case "-h":
|
|
1670
|
-
case "help":
|
|
1671
|
-
case void 0:
|
|
1672
|
-
process.stdout.write(PLAN_USAGE + "\n");
|
|
1673
|
-
process.exit(0);
|
|
1674
|
-
break;
|
|
1675
|
-
default:
|
|
1676
|
-
process.stderr.write(`Unknown plan subcommand: "${subcommand}"
|
|
1677
|
-
|
|
1678
|
-
`);
|
|
1679
|
-
process.stdout.write(PLAN_USAGE + "\n");
|
|
1680
|
-
process.exit(1);
|
|
1681
|
-
}
|
|
1682
|
-
}
|
|
1683
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
1684
|
-
0 && (module.exports = {
|
|
1685
|
-
main
|
|
1686
|
-
});
|