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