@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
@@ -1,1114 +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 __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/adapters/express.ts
31
- var express_exports = {};
32
- __export(express_exports, {
33
- createGovernanceMiddleware: () => createGovernanceMiddleware,
34
- createGovernanceMiddlewareFromWorld: () => createGovernanceMiddlewareFromWorld
35
- });
36
- module.exports = __toCommonJS(express_exports);
37
-
38
- // src/engine/plan-engine.ts
39
- function keywordMatch(eventText, step) {
40
- const stepText = [
41
- step.label,
42
- step.description ?? "",
43
- ...step.tags ?? []
44
- ].join(" ").toLowerCase();
45
- const keywords = stepText.split(/\s+/).filter((w) => w.length > 3);
46
- if (keywords.length === 0) return false;
47
- const matched = keywords.filter((kw) => eventText.includes(kw));
48
- return matched.length >= Math.ceil(keywords.length * 0.5);
49
- }
50
- function tokenSimilarity(a, b) {
51
- const tokensA = new Set(a.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
52
- const tokensB = new Set(b.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
53
- if (tokensA.size === 0 || tokensB.size === 0) return 0;
54
- let intersection = 0;
55
- for (const t of tokensA) {
56
- if (tokensB.has(t)) intersection++;
57
- }
58
- const union = (/* @__PURE__ */ new Set([...tokensA, ...tokensB])).size;
59
- return union > 0 ? intersection / union : 0;
60
- }
61
- function findMatchingStep(eventText, event, steps) {
62
- const pendingOrActive = steps.filter((s) => s.status === "pending" || s.status === "active");
63
- if (pendingOrActive.length === 0) {
64
- return { matched: null, closest: null, closestScore: 0 };
65
- }
66
- for (const step of pendingOrActive) {
67
- if (keywordMatch(eventText, step)) {
68
- if (step.tools && event.tool && !step.tools.includes(event.tool)) {
69
- continue;
70
- }
71
- return { matched: step, closest: step, closestScore: 1 };
72
- }
73
- }
74
- const intentText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ");
75
- let bestStep = null;
76
- let bestScore = 0;
77
- for (const step of pendingOrActive) {
78
- const stepText = [step.label, step.description ?? "", ...step.tags ?? []].join(" ");
79
- const score = tokenSimilarity(intentText, stepText);
80
- if (score > bestScore) {
81
- bestScore = score;
82
- bestStep = step;
83
- }
84
- }
85
- const SIMILARITY_THRESHOLD = 0.35;
86
- if (bestScore >= SIMILARITY_THRESHOLD && bestStep) {
87
- if (bestStep.tools && event.tool && !bestStep.tools.includes(event.tool)) {
88
- return { matched: null, closest: bestStep, closestScore: bestScore };
89
- }
90
- return { matched: bestStep, closest: bestStep, closestScore: bestScore };
91
- }
92
- return { matched: null, closest: bestStep, closestScore: bestScore };
93
- }
94
- function isSequenceValid(step, plan) {
95
- if (!plan.sequential) return true;
96
- if (!step.requires || step.requires.length === 0) return true;
97
- return step.requires.every((reqId) => {
98
- const reqStep = plan.steps.find((s) => s.id === reqId);
99
- return reqStep?.status === "completed";
100
- });
101
- }
102
- function checkConstraints(event, eventText, constraints) {
103
- const checks = [];
104
- for (const constraint of constraints) {
105
- if (constraint.type === "approval") {
106
- if (constraint.trigger && eventText.includes(constraint.trigger.substring(0, 10).toLowerCase())) {
107
- checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
108
- return { violated: constraint, checks };
109
- }
110
- const keywords = constraint.description.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
111
- const relevant = keywords.some((kw) => eventText.includes(kw));
112
- if (relevant) {
113
- checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
114
- return { violated: constraint, checks };
115
- }
116
- checks.push({ constraintId: constraint.id, passed: true });
117
- continue;
118
- }
119
- if (constraint.type === "scope" && constraint.trigger) {
120
- const keywords = constraint.trigger.split(/\s+/).filter((w) => w.length > 3);
121
- const violated = keywords.length > 0 && keywords.every((kw) => eventText.includes(kw));
122
- checks.push({
123
- constraintId: constraint.id,
124
- passed: !violated,
125
- reason: violated ? constraint.description : void 0
126
- });
127
- if (violated) {
128
- return { violated: constraint, checks };
129
- }
130
- continue;
131
- }
132
- checks.push({ constraintId: constraint.id, passed: true });
133
- }
134
- return { violated: null, checks };
135
- }
136
- function getPlanProgress(plan) {
137
- const completed = plan.steps.filter((s) => s.status === "completed").length;
138
- const total = plan.steps.length;
139
- return {
140
- completed,
141
- total,
142
- percentage: total > 0 ? Math.round(completed / total * 100) : 0
143
- };
144
- }
145
- function evaluatePlan(event, plan) {
146
- const progress = getPlanProgress(plan);
147
- if (plan.expires_at) {
148
- const expiresAt = new Date(plan.expires_at).getTime();
149
- if (Date.now() > expiresAt) {
150
- return {
151
- allowed: true,
152
- status: "PLAN_COMPLETE",
153
- reason: "Plan has expired.",
154
- progress
155
- };
156
- }
157
- }
158
- if (progress.completed === progress.total) {
159
- return {
160
- allowed: true,
161
- status: "PLAN_COMPLETE",
162
- reason: "All plan steps are completed.",
163
- progress
164
- };
165
- }
166
- const eventText = [
167
- event.intent,
168
- event.tool ?? "",
169
- event.scope ?? ""
170
- ].join(" ").toLowerCase();
171
- const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
172
- if (!matched) {
173
- return {
174
- allowed: false,
175
- status: "OFF_PLAN",
176
- reason: "Action does not match any plan step.",
177
- closestStep: closest?.label,
178
- similarityScore: closestScore,
179
- progress
180
- };
181
- }
182
- if (!isSequenceValid(matched, plan)) {
183
- const pendingDeps = (matched.requires ?? []).filter((reqId) => plan.steps.find((s) => s.id === reqId)?.status !== "completed").join(", ");
184
- return {
185
- allowed: false,
186
- status: "OFF_PLAN",
187
- reason: `Step "${matched.label}" requires completion of: ${pendingDeps}`,
188
- matchedStep: matched.id,
189
- progress
190
- };
191
- }
192
- const { violated } = checkConstraints(event, eventText, plan.constraints);
193
- if (violated) {
194
- return {
195
- allowed: false,
196
- status: "CONSTRAINT_VIOLATED",
197
- reason: violated.description,
198
- matchedStep: matched.id,
199
- progress
200
- };
201
- }
202
- return {
203
- allowed: true,
204
- status: "ON_PLAN",
205
- reason: `Matches step: ${matched.label}`,
206
- matchedStep: matched.id,
207
- progress
208
- };
209
- }
210
- function buildPlanCheck(event, plan, verdict) {
211
- const eventText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ").toLowerCase();
212
- const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
213
- const { checks: constraintChecks } = checkConstraints(event, eventText, plan.constraints);
214
- const progress = getPlanProgress(plan);
215
- return {
216
- planId: plan.plan_id,
217
- matched: !!matched,
218
- matchedStepId: matched?.id,
219
- matchedStepLabel: matched?.label,
220
- closestStepId: !matched ? closest?.id : void 0,
221
- closestStepLabel: !matched ? closest?.label : void 0,
222
- similarityScore: !matched ? closestScore : void 0,
223
- sequenceValid: matched ? isSequenceValid(matched, plan) : void 0,
224
- constraintsChecked: constraintChecks,
225
- progress: { completed: progress.completed, total: progress.total }
226
- };
227
- }
228
-
229
- // src/engine/guard-engine.ts
230
- var PROMPT_INJECTION_PATTERNS = [
231
- // Instruction override
232
- { pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
233
- { pattern: /disregard\s+(your|the)\s+(rules|constraints)/i, label: "disregard-rules" },
234
- { pattern: /new\s+instructions?:/i, label: "new-instructions" },
235
- // Identity manipulation
236
- { pattern: /you\s+are\s+now/i, label: "identity-override" },
237
- { pattern: /new\s+persona/i, label: "new-persona" },
238
- { pattern: /act\s+as\s+if/i, label: "act-as-if" },
239
- { pattern: /pretend\s+(you|to\s+be|you\s+are\s+unrestricted)/i, label: "pretend-to-be" },
240
- // Context reset
241
- { pattern: /forget\s+(everything|all|your)/i, label: "forget-context" },
242
- { pattern: /system\s*:\s*override/i, label: "system-override" },
243
- // Constraint bypass
244
- { pattern: /override\s+(your|the)\s+(programming|constraints)/i, label: "override-constraints" },
245
- { pattern: /bypass\s+(your|the)\s+(filters|constraints|rules)/i, label: "bypass-filters" },
246
- // Prompt extraction
247
- { pattern: /system\s+prompt/i, label: "system-prompt-probe" },
248
- { pattern: /reveal\s+your\s+(instructions?|prompt|rules)/i, label: "reveal-instructions" },
249
- // Known jailbreak terms
250
- { pattern: /jailbreak/i, label: "jailbreak" },
251
- { pattern: /DAN\s+mode/i, label: "dan-mode" },
252
- { pattern: /developer\s+mode/i, label: "developer-mode" }
253
- ];
254
- var EXECUTION_CLAIM_PATTERNS = [
255
- { pattern: /I have (executed|completed|performed|done|made|created|sent|deleted|modified|updated)/i, label: "claim-i-have" },
256
- { pattern: /Successfully (created|deleted|modified|updated|sent|executed|performed)/i, label: "claim-successfully" },
257
- { pattern: /The file has been/i, label: "claim-file-modified" },
258
- { pattern: /I've made the changes/i, label: "claim-made-changes" },
259
- { pattern: /I('ve| have) (sent|posted|submitted|uploaded|downloaded)/i, label: "claim-sent" },
260
- { pattern: /Your (email|message|file|request) has been (sent|submitted)/i, label: "claim-your-sent" },
261
- { pattern: /Transaction complete/i, label: "claim-transaction" },
262
- { pattern: /Order placed/i, label: "claim-order" },
263
- { pattern: /Payment processed/i, label: "claim-payment" }
264
- ];
265
- var EXECUTION_INTENT_PATTERNS = [
266
- { pattern: /^(execute|run|perform|do this)/i, label: "intent-execute" },
267
- { pattern: /^(create|write|delete|modify) (a |the )?(file|folder|document)/i, label: "intent-file-ops" },
268
- { pattern: /^(send|post|submit) (a |an |the )?(email|message|tweet|post)/i, label: "intent-send" },
269
- { pattern: /^(search|look up|browse) (the )?web/i, label: "intent-web-search" },
270
- { pattern: /^(make|call|invoke) (a |an )?(api|http|rest) (call|request)/i, label: "intent-api-call" },
271
- { pattern: /^(buy|purchase|order|pay|transfer|send money)/i, label: "intent-financial" },
272
- { pattern: /^(book|schedule|reserve)/i, label: "intent-booking" },
273
- { pattern: /^(download|upload|save to|export to)/i, label: "intent-transfer" }
274
- ];
275
- var SCOPE_ESCAPE_PATTERNS = [
276
- { pattern: /\.\.\//, label: "parent-traversal" },
277
- { pattern: /^\/(?!home|project|workspace)/i, label: "absolute-path-outside-safe" },
278
- { pattern: /~\//, label: "home-directory" },
279
- { pattern: /\/etc\//i, label: "system-config" },
280
- { pattern: /\/usr\//i, label: "system-binaries" },
281
- { pattern: /\/var\//i, label: "system-variable-data" }
282
- ];
283
- var NEUTRAL_MESSAGES = {
284
- "prompt-injection": "This input contains patterns that could alter agent behavior.",
285
- "scope-escape": "This action would affect resources outside the declared scope.",
286
- "execution-claim": "This response claims to have performed an action.",
287
- "execution-intent": "This input requests execution in a thinking-only environment.",
288
- "delete": "This action would remove files. Confirmation needed.",
289
- "write-external": "This action would write outside the project folder.",
290
- "network-mutate": "This action would send data to an external service.",
291
- "credential-access": "This action would access stored credentials."
292
- };
293
- function levelRequiresConfirmation(level, actionType) {
294
- if (level === "strict") return true;
295
- if (level === "standard") {
296
- return actionType === "delete" || actionType === "credential-access";
297
- }
298
- return false;
299
- }
300
- function isExternalScope(scope) {
301
- const internalPatterns = [
302
- /^\.?\/?src\//i,
303
- /^\.?\/?lib\//i,
304
- /^\.?\/?app\//i,
305
- /^\.?\/?components\//i,
306
- /^\.?\/?pages\//i,
307
- /^\.?\/?public\//i,
308
- /^\.?\/?assets\//i,
309
- /^\.\//
310
- ];
311
- return !internalPatterns.some((p) => p.test(scope));
312
- }
313
- function evaluateGuard(event, world, options = {}) {
314
- const startTime = performance.now();
315
- const level = options.level ?? "standard";
316
- const includeTrace = options.trace ?? false;
317
- const eventText = (event.intent + " " + (event.tool ?? "") + " " + (event.scope ?? "")).toLowerCase();
318
- const invariantChecks = [];
319
- const safetyChecks = [];
320
- let planCheckResult;
321
- const roleChecks = [];
322
- const guardChecks = [];
323
- const kernelRuleChecks = [];
324
- const levelChecks = [];
325
- let decidingLayer = "default-allow";
326
- let decidingId;
327
- const guardsMatched = [];
328
- const rulesMatched = [];
329
- checkInvariantCoverage(world, invariantChecks);
330
- if (options.sessionAllowlist) {
331
- const key = eventToAllowlistKey(event);
332
- if (options.sessionAllowlist.has(key)) {
333
- decidingLayer = "session-allowlist";
334
- decidingId = `allowlist:${key}`;
335
- return buildVerdict(
336
- "ALLOW",
337
- void 0,
338
- `allowlist:${key}`,
339
- void 0,
340
- world,
341
- level,
342
- invariantChecks,
343
- guardsMatched,
344
- rulesMatched,
345
- includeTrace ? buildTrace(
346
- invariantChecks,
347
- safetyChecks,
348
- planCheckResult,
349
- roleChecks,
350
- guardChecks,
351
- kernelRuleChecks,
352
- levelChecks,
353
- decidingLayer,
354
- decidingId,
355
- startTime
356
- ) : void 0
357
- );
358
- }
359
- }
360
- const safetyVerdict = checkSafety(event, eventText, safetyChecks);
361
- if (safetyVerdict) {
362
- decidingLayer = "safety";
363
- decidingId = safetyVerdict.ruleId;
364
- return buildVerdict(
365
- safetyVerdict.status,
366
- safetyVerdict.reason,
367
- safetyVerdict.ruleId,
368
- void 0,
369
- world,
370
- level,
371
- invariantChecks,
372
- guardsMatched,
373
- rulesMatched,
374
- includeTrace ? buildTrace(
375
- invariantChecks,
376
- safetyChecks,
377
- planCheckResult,
378
- roleChecks,
379
- guardChecks,
380
- kernelRuleChecks,
381
- levelChecks,
382
- decidingLayer,
383
- decidingId,
384
- startTime
385
- ) : void 0
386
- );
387
- }
388
- if (options.plan) {
389
- const planVerdict = evaluatePlan(event, options.plan);
390
- planCheckResult = buildPlanCheck(event, options.plan, planVerdict);
391
- if (!planVerdict.allowed && planVerdict.status !== "PLAN_COMPLETE") {
392
- decidingLayer = "plan-enforcement";
393
- decidingId = `plan-${options.plan.plan_id}`;
394
- const planStatus = planVerdict.status === "CONSTRAINT_VIOLATED" ? "PAUSE" : "BLOCK";
395
- let reason = planVerdict.reason ?? "Action blocked by plan.";
396
- if (planVerdict.status === "OFF_PLAN" && planVerdict.closestStep) {
397
- reason += ` Closest step: "${planVerdict.closestStep}" (similarity: ${(planVerdict.similarityScore ?? 0).toFixed(2)})`;
398
- }
399
- return buildVerdict(
400
- planStatus,
401
- reason,
402
- `plan-${options.plan.plan_id}`,
403
- void 0,
404
- world,
405
- level,
406
- invariantChecks,
407
- guardsMatched,
408
- rulesMatched,
409
- includeTrace ? buildTrace(
410
- invariantChecks,
411
- safetyChecks,
412
- planCheckResult,
413
- roleChecks,
414
- guardChecks,
415
- kernelRuleChecks,
416
- levelChecks,
417
- decidingLayer,
418
- decidingId,
419
- startTime
420
- ) : void 0
421
- );
422
- }
423
- }
424
- const roleVerdict = checkRoleRules(event, eventText, world, roleChecks);
425
- if (roleVerdict) {
426
- decidingLayer = "role";
427
- decidingId = roleVerdict.ruleId;
428
- return buildVerdict(
429
- roleVerdict.status,
430
- roleVerdict.reason,
431
- roleVerdict.ruleId,
432
- void 0,
433
- world,
434
- level,
435
- invariantChecks,
436
- guardsMatched,
437
- rulesMatched,
438
- includeTrace ? buildTrace(
439
- invariantChecks,
440
- safetyChecks,
441
- planCheckResult,
442
- roleChecks,
443
- guardChecks,
444
- kernelRuleChecks,
445
- levelChecks,
446
- decidingLayer,
447
- decidingId,
448
- startTime
449
- ) : void 0
450
- );
451
- }
452
- const guardVerdict = checkGuards(event, eventText, world, guardChecks, guardsMatched);
453
- if (guardVerdict) {
454
- if (guardVerdict.status !== "ALLOW") {
455
- decidingLayer = "guard";
456
- decidingId = guardVerdict.ruleId;
457
- return buildVerdict(
458
- guardVerdict.status,
459
- guardVerdict.reason,
460
- guardVerdict.ruleId,
461
- void 0,
462
- world,
463
- level,
464
- invariantChecks,
465
- guardsMatched,
466
- rulesMatched,
467
- includeTrace ? buildTrace(
468
- invariantChecks,
469
- safetyChecks,
470
- planCheckResult,
471
- roleChecks,
472
- guardChecks,
473
- kernelRuleChecks,
474
- levelChecks,
475
- decidingLayer,
476
- decidingId,
477
- startTime
478
- ) : void 0
479
- );
480
- }
481
- }
482
- const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
483
- if (kernelVerdict) {
484
- decidingLayer = "kernel-rule";
485
- decidingId = kernelVerdict.ruleId;
486
- return buildVerdict(
487
- kernelVerdict.status,
488
- kernelVerdict.reason,
489
- kernelVerdict.ruleId,
490
- void 0,
491
- world,
492
- level,
493
- invariantChecks,
494
- guardsMatched,
495
- rulesMatched,
496
- includeTrace ? buildTrace(
497
- invariantChecks,
498
- safetyChecks,
499
- planCheckResult,
500
- roleChecks,
501
- guardChecks,
502
- kernelRuleChecks,
503
- levelChecks,
504
- decidingLayer,
505
- decidingId,
506
- startTime
507
- ) : void 0
508
- );
509
- }
510
- const levelVerdict = checkLevelConstraints(event, level, levelChecks);
511
- if (levelVerdict) {
512
- decidingLayer = "level-constraint";
513
- decidingId = levelVerdict.ruleId;
514
- return buildVerdict(
515
- levelVerdict.status,
516
- levelVerdict.reason,
517
- levelVerdict.ruleId,
518
- void 0,
519
- world,
520
- level,
521
- invariantChecks,
522
- guardsMatched,
523
- rulesMatched,
524
- includeTrace ? buildTrace(
525
- invariantChecks,
526
- safetyChecks,
527
- planCheckResult,
528
- roleChecks,
529
- guardChecks,
530
- kernelRuleChecks,
531
- levelChecks,
532
- decidingLayer,
533
- decidingId,
534
- startTime
535
- ) : void 0
536
- );
537
- }
538
- const warning = guardVerdict?.warning;
539
- return buildVerdict(
540
- "ALLOW",
541
- void 0,
542
- void 0,
543
- warning,
544
- world,
545
- level,
546
- invariantChecks,
547
- guardsMatched,
548
- rulesMatched,
549
- includeTrace ? buildTrace(
550
- invariantChecks,
551
- safetyChecks,
552
- planCheckResult,
553
- roleChecks,
554
- guardChecks,
555
- kernelRuleChecks,
556
- levelChecks,
557
- decidingLayer,
558
- decidingId,
559
- startTime
560
- ) : void 0
561
- );
562
- }
563
- function checkInvariantCoverage(world, checks) {
564
- const invariants = world.invariants ?? [];
565
- const guards = world.guards?.guards ?? [];
566
- for (const invariant of invariants) {
567
- const coveringGuard = guards.find(
568
- (g) => g.invariant_ref === invariant.id && g.immutable
569
- );
570
- checks.push({
571
- invariantId: invariant.id,
572
- label: invariant.label,
573
- hasGuardCoverage: !!coveringGuard,
574
- coveringGuardId: coveringGuard?.id
575
- });
576
- }
577
- }
578
- function checkSafety(event, eventText, checks) {
579
- const textToCheck = event.intent + (event.payload ? JSON.stringify(event.payload) : "");
580
- for (const { pattern, label } of PROMPT_INJECTION_PATTERNS) {
581
- const triggered = pattern.test(textToCheck);
582
- checks.push({
583
- checkType: "prompt-injection",
584
- triggered,
585
- matchedPattern: triggered ? label : void 0
586
- });
587
- if (triggered) {
588
- for (const remaining of PROMPT_INJECTION_PATTERNS.filter((p) => p.label !== label)) {
589
- checks.push({
590
- checkType: "prompt-injection",
591
- triggered: remaining.pattern.test(textToCheck),
592
- matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
593
- });
594
- }
595
- return {
596
- status: "PAUSE",
597
- reason: NEUTRAL_MESSAGES["prompt-injection"],
598
- ruleId: `safety-injection-${label}`
599
- };
600
- }
601
- }
602
- const scopeToCheck = event.scope ?? event.intent;
603
- for (const { pattern, label } of SCOPE_ESCAPE_PATTERNS) {
604
- const triggered = pattern.test(scopeToCheck);
605
- checks.push({
606
- checkType: "scope-escape",
607
- triggered,
608
- matchedPattern: triggered ? label : void 0
609
- });
610
- if (triggered) {
611
- for (const remaining of SCOPE_ESCAPE_PATTERNS.filter((p) => p.label !== label)) {
612
- checks.push({
613
- checkType: "scope-escape",
614
- triggered: remaining.pattern.test(scopeToCheck),
615
- matchedPattern: remaining.pattern.test(scopeToCheck) ? remaining.label : void 0
616
- });
617
- }
618
- return {
619
- status: "PAUSE",
620
- reason: NEUTRAL_MESSAGES["scope-escape"],
621
- ruleId: `safety-scope-${label}`
622
- };
623
- }
624
- }
625
- if (event.direction === "output") {
626
- for (const { pattern, label } of EXECUTION_CLAIM_PATTERNS) {
627
- const triggered = pattern.test(textToCheck);
628
- checks.push({
629
- checkType: "execution-claim",
630
- triggered,
631
- matchedPattern: triggered ? label : void 0
632
- });
633
- if (triggered) {
634
- for (const remaining of EXECUTION_CLAIM_PATTERNS.filter((p) => p.label !== label)) {
635
- checks.push({
636
- checkType: "execution-claim",
637
- triggered: remaining.pattern.test(textToCheck),
638
- matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
639
- });
640
- }
641
- return {
642
- status: "PAUSE",
643
- reason: NEUTRAL_MESSAGES["execution-claim"],
644
- ruleId: `safety-execution-claim-${label}`
645
- };
646
- }
647
- }
648
- }
649
- if (event.direction === "input") {
650
- const intentTrimmed = event.intent.trim();
651
- for (const { pattern, label } of EXECUTION_INTENT_PATTERNS) {
652
- const triggered = pattern.test(intentTrimmed);
653
- checks.push({
654
- checkType: "execution-intent",
655
- triggered,
656
- matchedPattern: triggered ? label : void 0
657
- });
658
- if (triggered) {
659
- for (const remaining of EXECUTION_INTENT_PATTERNS.filter((p) => p.label !== label)) {
660
- checks.push({
661
- checkType: "execution-intent",
662
- triggered: remaining.pattern.test(intentTrimmed),
663
- matchedPattern: remaining.pattern.test(intentTrimmed) ? remaining.label : void 0
664
- });
665
- }
666
- return {
667
- status: "PAUSE",
668
- reason: NEUTRAL_MESSAGES["execution-intent"],
669
- ruleId: `safety-execution-intent-${label}`
670
- };
671
- }
672
- }
673
- }
674
- return null;
675
- }
676
- function checkRoleRules(event, eventText, world, checks) {
677
- if (!event.roleId || !world.roles) return null;
678
- const role = world.roles.roles.find((r) => r.id === event.roleId);
679
- if (!role) return null;
680
- if (role.requiresApproval) {
681
- checks.push({
682
- roleId: role.id,
683
- roleName: role.name,
684
- rule: "All actions require approval",
685
- ruleType: "requiresApproval",
686
- matched: true
687
- });
688
- return {
689
- status: "PAUSE",
690
- reason: `Role "${role.name}" requires approval for all actions.`,
691
- ruleId: `role-${role.id}-requires-approval`
692
- };
693
- }
694
- for (const rule of role.cannotDo) {
695
- const matched = matchesKeywords(eventText, rule);
696
- checks.push({
697
- roleId: role.id,
698
- roleName: role.name,
699
- rule,
700
- ruleType: "cannotDo",
701
- matched
702
- });
703
- if (matched) {
704
- return {
705
- status: "BLOCK",
706
- reason: `Role "${role.name}" cannot: ${rule}`,
707
- ruleId: `role-${role.id}-cannotdo`
708
- };
709
- }
710
- }
711
- for (const rule of role.canDo) {
712
- checks.push({
713
- roleId: role.id,
714
- roleName: role.name,
715
- rule,
716
- ruleType: "canDo",
717
- matched: matchesKeywords(eventText, rule)
718
- });
719
- }
720
- return null;
721
- }
722
- function checkGuards(event, eventText, world, checks, guardsMatched) {
723
- if (!world.guards) return null;
724
- const guardsConfig = world.guards;
725
- let warnResult = null;
726
- const compiledPatterns = /* @__PURE__ */ new Map();
727
- for (const [key, def] of Object.entries(guardsConfig.intent_vocabulary)) {
728
- try {
729
- compiledPatterns.set(key, new RegExp(def.pattern, "i"));
730
- } catch {
731
- }
732
- }
733
- const eventTool = (event.tool ?? "").toLowerCase();
734
- for (const guard of guardsConfig.guards) {
735
- if (guard.appliesTo && guard.appliesTo.length > 0) {
736
- const normalizedAppliesTo = guard.appliesTo.map((t) => t.toLowerCase());
737
- if (!normalizedAppliesTo.includes(eventTool)) {
738
- continue;
739
- }
740
- }
741
- const enabled = guard.immutable || guard.default_enabled !== false;
742
- const matchedPatterns = [];
743
- for (const patternKey of guard.intent_patterns) {
744
- const regex = compiledPatterns.get(patternKey);
745
- if (regex?.test(eventText)) {
746
- matchedPatterns.push(patternKey);
747
- }
748
- }
749
- const matched = matchedPatterns.length > 0 && enabled;
750
- let roleGated = false;
751
- if (matched && guard.required_roles && guard.required_roles.length > 0 && event.roleId && guard.required_roles.includes(event.roleId)) {
752
- roleGated = true;
753
- }
754
- checks.push({
755
- guardId: guard.id,
756
- label: guard.label,
757
- category: guard.category,
758
- enabled,
759
- matched: matched && !roleGated,
760
- enforcement: guard.enforcement,
761
- matchedPatterns,
762
- roleGated
763
- });
764
- if (!matched || roleGated) continue;
765
- guardsMatched.push(guard.id);
766
- const actionMode = guard.player_modes?.action ?? guard.enforcement;
767
- const reason = guard.redirect ? `${guard.description} \u2014 ${guard.redirect}` : guard.description;
768
- if (actionMode === "block") {
769
- return { status: "BLOCK", reason, ruleId: `guard-${guard.id}` };
770
- }
771
- if (actionMode === "pause") {
772
- return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
773
- }
774
- if (actionMode === "warn" && !warnResult) {
775
- warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
776
- }
777
- }
778
- return warnResult;
779
- }
780
- function checkKernelRules(eventText, world, checks, rulesMatched) {
781
- if (!world.kernel) return null;
782
- const forbidden = world.kernel.input_boundaries?.forbidden_patterns ?? [];
783
- const output = world.kernel.output_boundaries?.forbidden_patterns ?? [];
784
- for (const rule of forbidden) {
785
- let matched = false;
786
- let matchMethod = "none";
787
- if (rule.pattern) {
788
- try {
789
- matched = new RegExp(rule.pattern, "i").test(eventText);
790
- matchMethod = "pattern";
791
- } catch {
792
- }
793
- }
794
- if (!matched && rule.reason) {
795
- matched = matchesKeywords(eventText, rule.reason);
796
- if (matched) matchMethod = "keyword";
797
- }
798
- checks.push({
799
- ruleId: rule.id,
800
- text: rule.reason,
801
- category: "forbidden",
802
- matched,
803
- matchMethod
804
- });
805
- if (matched) {
806
- rulesMatched.push(rule.id);
807
- if (rule.action === "BLOCK") {
808
- return {
809
- status: "BLOCK",
810
- reason: rule.reason,
811
- ruleId: `kernel-${rule.id}`
812
- };
813
- }
814
- }
815
- }
816
- return null;
817
- }
818
- function checkLevelConstraints(event, level, checks) {
819
- if (level === "basic") return null;
820
- const intent = event.intent.toLowerCase();
821
- const tool = (event.tool ?? "").toLowerCase();
822
- const isDelete = intent.includes("delete") || intent.includes("remove") || intent.includes("rm ") || tool === "delete";
823
- const deleteTriggered = isDelete && levelRequiresConfirmation(level, "delete");
824
- checks.push({
825
- checkType: "delete",
826
- level,
827
- triggered: deleteTriggered,
828
- reason: deleteTriggered ? NEUTRAL_MESSAGES["delete"] : void 0
829
- });
830
- if (deleteTriggered) {
831
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["delete"], ruleId: "level-delete-check" };
832
- }
833
- const isExternal = event.scope ? isExternalScope(event.scope) : false;
834
- const externalTriggered = isExternal && levelRequiresConfirmation(level, "write-external");
835
- checks.push({
836
- checkType: "write-external",
837
- level,
838
- triggered: externalTriggered,
839
- reason: externalTriggered ? NEUTRAL_MESSAGES["write-external"] : void 0
840
- });
841
- if (externalTriggered) {
842
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["write-external"], ruleId: "level-external-write-check" };
843
- }
844
- const isNetwork = tool === "http" || tool === "fetch" || tool === "request" || intent.includes("post ") || intent.includes("sending");
845
- const networkTriggered = isNetwork && levelRequiresConfirmation(level, "network-mutate");
846
- checks.push({
847
- checkType: "network-mutate",
848
- level,
849
- triggered: networkTriggered,
850
- reason: networkTriggered ? NEUTRAL_MESSAGES["network-mutate"] : void 0
851
- });
852
- if (networkTriggered) {
853
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["network-mutate"], ruleId: "level-network-mutate-check" };
854
- }
855
- const isCredential = intent.includes("credential") || intent.includes("password") || intent.includes("secret") || intent.includes("api key") || intent.includes("token");
856
- const credentialTriggered = isCredential && levelRequiresConfirmation(level, "credential-access");
857
- checks.push({
858
- checkType: "credential-access",
859
- level,
860
- triggered: credentialTriggered,
861
- reason: credentialTriggered ? NEUTRAL_MESSAGES["credential-access"] : void 0
862
- });
863
- if (credentialTriggered) {
864
- return { status: "PAUSE", reason: NEUTRAL_MESSAGES["credential-access"], ruleId: "level-credential-check" };
865
- }
866
- const irreversibleTriggered = !!event.irreversible && level !== "basic";
867
- checks.push({
868
- checkType: "irreversible",
869
- level,
870
- triggered: irreversibleTriggered,
871
- reason: irreversibleTriggered ? "This action is marked as irreversible." : void 0
872
- });
873
- if (irreversibleTriggered) {
874
- return {
875
- status: "PAUSE",
876
- reason: "This action is marked as irreversible.",
877
- ruleId: "level-irreversible-check"
878
- };
879
- }
880
- return null;
881
- }
882
- function matchesKeywords(eventText, ruleText) {
883
- const keywords = ruleText.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
884
- if (keywords.length === 0) return false;
885
- return keywords.every((kw) => eventText.includes(kw));
886
- }
887
- function eventToAllowlistKey(event) {
888
- return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
889
- }
890
- function buildTrace(invariantChecks, safetyChecks, planCheck, roleChecks, guardChecks, kernelRuleChecks, levelChecks, decidingLayer, decidingId, startTime) {
891
- const trace = {
892
- invariantChecks,
893
- safetyChecks,
894
- roleChecks,
895
- guardChecks,
896
- kernelRuleChecks,
897
- levelChecks,
898
- precedenceResolution: {
899
- decidingLayer,
900
- decidingId,
901
- strategy: "first-match-wins",
902
- chainOrder: [
903
- "invariant-coverage",
904
- "session-allowlist",
905
- "safety-injection",
906
- "safety-scope-escape",
907
- "safety-execution-claim",
908
- "safety-execution-intent",
909
- "plan-enforcement",
910
- "role-rules",
911
- "declarative-guards",
912
- "kernel-rules",
913
- "level-constraints",
914
- "default-allow"
915
- ]
916
- },
917
- durationMs: performance.now() - startTime
918
- };
919
- if (planCheck) {
920
- trace.planCheck = planCheck;
921
- }
922
- return trace;
923
- }
924
- function buildVerdict(status, reason, ruleId, warning, world, level, invariantChecks, guardsMatched, rulesMatched, trace) {
925
- const evidence = {
926
- worldId: world.world.world_id,
927
- worldName: world.world.name,
928
- worldVersion: world.world.version,
929
- evaluatedAt: Date.now(),
930
- invariantsSatisfied: invariantChecks.filter((c) => c.hasGuardCoverage).length,
931
- invariantsTotal: invariantChecks.length,
932
- guardsMatched,
933
- rulesMatched,
934
- enforcementLevel: level
935
- };
936
- const verdict = {
937
- status,
938
- evidence
939
- };
940
- if (reason) verdict.reason = reason;
941
- if (ruleId) verdict.ruleId = ruleId;
942
- if (warning) verdict.warning = warning;
943
- if (trace) verdict.trace = trace;
944
- return verdict;
945
- }
946
-
947
- // src/loader/world-loader.ts
948
- async function loadWorldFromDirectory(dirPath) {
949
- const { readFile } = await import("fs/promises");
950
- const { join } = await import("path");
951
- const { readdirSync } = await import("fs");
952
- async function readJson(filename) {
953
- try {
954
- const content = await readFile(join(dirPath, filename), "utf-8");
955
- return JSON.parse(content);
956
- } catch {
957
- return void 0;
958
- }
959
- }
960
- const worldJson = await readJson("world.json");
961
- if (!worldJson) {
962
- throw new Error(`Cannot read world.json in ${dirPath}`);
963
- }
964
- const invariantsJson = await readJson("invariants.json");
965
- const assumptionsJson = await readJson("assumptions.json");
966
- const stateSchemaJson = await readJson("state-schema.json");
967
- const gatesJson = await readJson("gates.json");
968
- const outcomesJson = await readJson("outcomes.json");
969
- const guardsJson = await readJson("guards.json");
970
- const rolesJson = await readJson("roles.json");
971
- const kernelJson = await readJson("kernel.json");
972
- const metadataJson = await readJson("metadata.json");
973
- const rules = [];
974
- try {
975
- const rulesDir = join(dirPath, "rules");
976
- const ruleFiles = readdirSync(rulesDir).filter((f) => f.endsWith(".json")).sort();
977
- for (const file of ruleFiles) {
978
- const content = await readFile(join(rulesDir, file), "utf-8");
979
- rules.push(JSON.parse(content));
980
- }
981
- } catch {
982
- }
983
- return {
984
- world: worldJson,
985
- invariants: invariantsJson?.invariants ?? [],
986
- assumptions: assumptionsJson ?? { profiles: {}, parameter_definitions: {} },
987
- stateSchema: stateSchemaJson ?? { variables: {}, presets: {} },
988
- rules,
989
- gates: gatesJson ?? {
990
- viability_classification: [],
991
- structural_override: { description: "", enforcement: "mandatory" },
992
- sustainability_threshold: 0,
993
- collapse_visual: { background: "", text: "", border: "", label: "" }
994
- },
995
- outcomes: outcomesJson ?? {
996
- computed_outcomes: [],
997
- comparison_layout: { primary_card: "", status_badge: "", structural_indicators: [] }
998
- },
999
- guards: guardsJson,
1000
- roles: rolesJson,
1001
- kernel: kernelJson,
1002
- metadata: metadataJson ?? {
1003
- format_version: "1.0.0",
1004
- created_at: "",
1005
- last_modified: "",
1006
- authoring_method: "manual-authoring"
1007
- }
1008
- };
1009
- }
1010
- async function loadWorld(worldPath) {
1011
- const { stat } = await import("fs/promises");
1012
- const info = await stat(worldPath);
1013
- if (info.isDirectory()) {
1014
- return loadWorldFromDirectory(worldPath);
1015
- }
1016
- if (worldPath.endsWith(".nv-world.zip")) {
1017
- throw new Error(".nv-world.zip loading not yet implemented \u2014 use a world directory");
1018
- }
1019
- throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory or .nv-world.zip`);
1020
- }
1021
-
1022
- // src/adapters/express.ts
1023
- function methodToCategory(method) {
1024
- switch (method.toUpperCase()) {
1025
- case "GET":
1026
- case "HEAD":
1027
- case "OPTIONS":
1028
- return "read";
1029
- case "POST":
1030
- case "PUT":
1031
- case "PATCH":
1032
- return "write";
1033
- case "DELETE":
1034
- return "delete";
1035
- default:
1036
- return "other";
1037
- }
1038
- }
1039
- function defaultMapRequest(req) {
1040
- const method = (req.method ?? "GET").toUpperCase();
1041
- const path = req.path ?? req.url ?? "/";
1042
- return {
1043
- intent: `${method} ${path}`,
1044
- tool: "http",
1045
- scope: path,
1046
- actionCategory: methodToCategory(method),
1047
- direction: "input",
1048
- args: {
1049
- method,
1050
- path,
1051
- ...req.params ?? {},
1052
- ...req.query ?? {}
1053
- }
1054
- };
1055
- }
1056
- function defaultOnBlock(verdict, _req, res, statusCode) {
1057
- const body = {
1058
- error: "Governance policy violation",
1059
- reason: verdict.reason ?? "Action not permitted",
1060
- ruleId: verdict.ruleId,
1061
- status: verdict.status
1062
- };
1063
- if (res.status && res.json) {
1064
- res.status(statusCode).json(body);
1065
- } else if (res.send) {
1066
- res.statusCode = statusCode;
1067
- res.send(JSON.stringify(body));
1068
- } else if (res.end) {
1069
- res.statusCode = statusCode;
1070
- res.end();
1071
- }
1072
- }
1073
- async function createGovernanceMiddleware(worldPath, options) {
1074
- const world = await loadWorld(worldPath);
1075
- return createGovernanceMiddlewareFromWorld(world, options);
1076
- }
1077
- function createGovernanceMiddlewareFromWorld(world, options = {}) {
1078
- const engineOptions = {
1079
- trace: options.trace ?? false,
1080
- level: options.level
1081
- };
1082
- const mapRequest = options.mapRequest ?? defaultMapRequest;
1083
- const blockStatusCode = options.blockStatusCode ?? 403;
1084
- return async function neuroVerseGovernance(req, res, next) {
1085
- try {
1086
- const event = mapRequest(req);
1087
- const verdict = evaluateGuard(event, world, engineOptions);
1088
- options.onEvaluate?.(verdict, event, req);
1089
- if (verdict.status === "ALLOW") {
1090
- next();
1091
- return;
1092
- }
1093
- if (verdict.status === "PAUSE") {
1094
- const approved = await options.onPause?.(verdict, req);
1095
- if (approved) {
1096
- next();
1097
- return;
1098
- }
1099
- }
1100
- if (options.onBlock) {
1101
- options.onBlock(verdict, req, res);
1102
- } else {
1103
- defaultOnBlock(verdict, req, res, blockStatusCode);
1104
- }
1105
- } catch (err) {
1106
- next(err);
1107
- }
1108
- };
1109
- }
1110
- // Annotate the CommonJS export names for ESM import in node:
1111
- 0 && (module.exports = {
1112
- createGovernanceMiddleware,
1113
- createGovernanceMiddlewareFromWorld
1114
- });