@neuroverseos/governance 0.1.0 → 0.1.2

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 (94) hide show
  1. package/LICENSE.md +190 -0
  2. package/README.md +472 -115
  3. package/dist/adapters/express.cjs +874 -0
  4. package/dist/adapters/express.d.cts +66 -0
  5. package/dist/adapters/express.d.ts +66 -0
  6. package/dist/adapters/express.js +10 -0
  7. package/dist/adapters/index.cjs +1166 -0
  8. package/dist/adapters/index.d.cts +5 -0
  9. package/dist/adapters/index.d.ts +5 -0
  10. package/dist/adapters/index.js +40 -0
  11. package/dist/adapters/langchain.cjs +861 -0
  12. package/dist/adapters/langchain.d.cts +82 -0
  13. package/dist/adapters/langchain.d.ts +82 -0
  14. package/dist/adapters/langchain.js +14 -0
  15. package/dist/adapters/openai.cjs +891 -0
  16. package/dist/adapters/openai.d.cts +92 -0
  17. package/dist/adapters/openai.d.ts +92 -0
  18. package/dist/adapters/openai.js +14 -0
  19. package/dist/adapters/openclaw.cjs +883 -0
  20. package/dist/adapters/openclaw.d.cts +92 -0
  21. package/dist/adapters/openclaw.d.ts +92 -0
  22. package/dist/adapters/openclaw.js +14 -0
  23. package/dist/bootstrap-H4HHKQ5G.js +113 -0
  24. package/dist/build-73KAVHEY.js +308 -0
  25. package/dist/chunk-4NGDRRQH.js +10 -0
  26. package/dist/chunk-B4NF3OLW.js +673 -0
  27. package/dist/chunk-BUWWN2NX.js +192 -0
  28. package/dist/chunk-CROPZ75A.js +107 -0
  29. package/dist/chunk-D7BGWV2J.js +620 -0
  30. package/dist/chunk-EIUHJXBB.js +340 -0
  31. package/dist/chunk-EQXFOKH2.js +85 -0
  32. package/dist/chunk-FYPYZFV5.js +187 -0
  33. package/dist/chunk-FYS2CBUW.js +304 -0
  34. package/dist/chunk-FZQCRGUU.js +115 -0
  35. package/dist/chunk-I3RRAYK2.js +11 -0
  36. package/dist/chunk-ITJ3LCPG.js +225 -0
  37. package/dist/chunk-M3TZFGHO.js +79 -0
  38. package/dist/chunk-MWDQ4MJB.js +11 -0
  39. package/dist/chunk-O5OMJMIE.js +590 -0
  40. package/dist/chunk-T4X42QXC.js +121 -0
  41. package/dist/chunk-XPDMYECO.js +642 -0
  42. package/dist/chunk-Z2S2HIV5.js +100 -0
  43. package/dist/cli/neuroverse.cjs +5864 -0
  44. package/dist/cli/neuroverse.d.cts +1 -0
  45. package/dist/cli/neuroverse.d.ts +1 -0
  46. package/dist/cli/neuroverse.js +128 -0
  47. package/dist/configure-ai-46JVG56I.js +129 -0
  48. package/dist/derive-6NAEWLM5.js +150 -0
  49. package/dist/explain-3B3VB6TL.js +69 -0
  50. package/dist/guard-67Y66P3I.js +82 -0
  51. package/dist/guard-contract-D_RQz9kt.d.cts +529 -0
  52. package/dist/guard-contract-D_RQz9kt.d.ts +529 -0
  53. package/dist/impact-CHERK3O6.js +57 -0
  54. package/dist/improve-YG6I6ERG.js +84 -0
  55. package/dist/index.cjs +4227 -0
  56. package/dist/index.d.cts +1147 -0
  57. package/dist/index.d.ts +1139 -25
  58. package/dist/index.js +318 -1159
  59. package/dist/init-Z66T6TDI.js +142 -0
  60. package/dist/simulate-ETHHINZ4.js +107 -0
  61. package/dist/trace-3YODSSIP.js +164 -0
  62. package/dist/validate-UVE6GKQU.js +72 -0
  63. package/dist/validate-engine-657D75OG.js +6 -0
  64. package/dist/world-WLNHL5XC.js +298 -0
  65. package/dist/worlds/derivation-world.nv-world.md +278 -0
  66. package/package.json +74 -26
  67. package/LICENSE +0 -21
  68. package/dist/audit-logger.d.ts +0 -38
  69. package/dist/audit-logger.d.ts.map +0 -1
  70. package/dist/audit-logger.js +0 -100
  71. package/dist/audit-logger.js.map +0 -1
  72. package/dist/condition-engine.d.ts +0 -16
  73. package/dist/condition-engine.d.ts.map +0 -1
  74. package/dist/condition-engine.js +0 -186
  75. package/dist/condition-engine.js.map +0 -1
  76. package/dist/drift-monitor.d.ts +0 -81
  77. package/dist/drift-monitor.d.ts.map +0 -1
  78. package/dist/drift-monitor.js +0 -228
  79. package/dist/drift-monitor.js.map +0 -1
  80. package/dist/governance-engine.d.ts +0 -131
  81. package/dist/governance-engine.d.ts.map +0 -1
  82. package/dist/governance-engine.js +0 -660
  83. package/dist/governance-engine.js.map +0 -1
  84. package/dist/index.d.ts.map +0 -1
  85. package/dist/index.js.map +0 -1
  86. package/dist/types.d.ts +0 -196
  87. package/dist/types.d.ts.map +0 -1
  88. package/dist/types.js +0 -9
  89. package/dist/types.js.map +0 -1
  90. package/dist/world-bootstrap.d.ts +0 -31
  91. package/dist/world-bootstrap.d.ts.map +0 -1
  92. package/dist/world-bootstrap.js +0 -415
  93. package/dist/world-bootstrap.js.map +0 -1
  94. package/openclaw.plugin.json +0 -59
@@ -0,0 +1,874 @@
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/guard-engine.ts
39
+ var PROMPT_INJECTION_PATTERNS = [
40
+ // Instruction override
41
+ { pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
42
+ { pattern: /disregard\s+(your|the)\s+(rules|constraints)/i, label: "disregard-rules" },
43
+ { pattern: /new\s+instructions?:/i, label: "new-instructions" },
44
+ // Identity manipulation
45
+ { pattern: /you\s+are\s+now/i, label: "identity-override" },
46
+ { pattern: /new\s+persona/i, label: "new-persona" },
47
+ { pattern: /act\s+as\s+if/i, label: "act-as-if" },
48
+ { pattern: /pretend\s+(you|to\s+be|you\s+are\s+unrestricted)/i, label: "pretend-to-be" },
49
+ // Context reset
50
+ { pattern: /forget\s+(everything|all|your)/i, label: "forget-context" },
51
+ { pattern: /system\s*:\s*override/i, label: "system-override" },
52
+ // Constraint bypass
53
+ { pattern: /override\s+(your|the)\s+(programming|constraints)/i, label: "override-constraints" },
54
+ { pattern: /bypass\s+(your|the)\s+(filters|constraints|rules)/i, label: "bypass-filters" },
55
+ // Prompt extraction
56
+ { pattern: /system\s+prompt/i, label: "system-prompt-probe" },
57
+ { pattern: /reveal\s+your\s+(instructions?|prompt|rules)/i, label: "reveal-instructions" },
58
+ // Known jailbreak terms
59
+ { pattern: /jailbreak/i, label: "jailbreak" },
60
+ { pattern: /DAN\s+mode/i, label: "dan-mode" },
61
+ { pattern: /developer\s+mode/i, label: "developer-mode" }
62
+ ];
63
+ var EXECUTION_CLAIM_PATTERNS = [
64
+ { pattern: /I have (executed|completed|performed|done|made|created|sent|deleted|modified|updated)/i, label: "claim-i-have" },
65
+ { pattern: /Successfully (created|deleted|modified|updated|sent|executed|performed)/i, label: "claim-successfully" },
66
+ { pattern: /The file has been/i, label: "claim-file-modified" },
67
+ { pattern: /I've made the changes/i, label: "claim-made-changes" },
68
+ { pattern: /I('ve| have) (sent|posted|submitted|uploaded|downloaded)/i, label: "claim-sent" },
69
+ { pattern: /Your (email|message|file|request) has been (sent|submitted)/i, label: "claim-your-sent" },
70
+ { pattern: /Transaction complete/i, label: "claim-transaction" },
71
+ { pattern: /Order placed/i, label: "claim-order" },
72
+ { pattern: /Payment processed/i, label: "claim-payment" }
73
+ ];
74
+ var EXECUTION_INTENT_PATTERNS = [
75
+ { pattern: /^(execute|run|perform|do this)/i, label: "intent-execute" },
76
+ { pattern: /^(create|write|delete|modify) (a |the )?(file|folder|document)/i, label: "intent-file-ops" },
77
+ { pattern: /^(send|post|submit) (a |an |the )?(email|message|tweet|post)/i, label: "intent-send" },
78
+ { pattern: /^(search|look up|browse) (the )?web/i, label: "intent-web-search" },
79
+ { pattern: /^(make|call|invoke) (a |an )?(api|http|rest) (call|request)/i, label: "intent-api-call" },
80
+ { pattern: /^(buy|purchase|order|pay|transfer|send money)/i, label: "intent-financial" },
81
+ { pattern: /^(book|schedule|reserve)/i, label: "intent-booking" },
82
+ { pattern: /^(download|upload|save to|export to)/i, label: "intent-transfer" }
83
+ ];
84
+ var SCOPE_ESCAPE_PATTERNS = [
85
+ { pattern: /\.\.\//, label: "parent-traversal" },
86
+ { pattern: /^\/(?!home|project|workspace)/i, label: "absolute-path-outside-safe" },
87
+ { pattern: /~\//, label: "home-directory" },
88
+ { pattern: /\/etc\//i, label: "system-config" },
89
+ { pattern: /\/usr\//i, label: "system-binaries" },
90
+ { pattern: /\/var\//i, label: "system-variable-data" }
91
+ ];
92
+ var NEUTRAL_MESSAGES = {
93
+ "prompt-injection": "This input contains patterns that could alter agent behavior.",
94
+ "scope-escape": "This action would affect resources outside the declared scope.",
95
+ "execution-claim": "This response claims to have performed an action.",
96
+ "execution-intent": "This input requests execution in a thinking-only environment.",
97
+ "delete": "This action would remove files. Confirmation needed.",
98
+ "write-external": "This action would write outside the project folder.",
99
+ "network-mutate": "This action would send data to an external service.",
100
+ "credential-access": "This action would access stored credentials."
101
+ };
102
+ function levelRequiresConfirmation(level, actionType) {
103
+ if (level === "strict") return true;
104
+ if (level === "standard") {
105
+ return actionType === "delete" || actionType === "credential-access";
106
+ }
107
+ return false;
108
+ }
109
+ function isExternalScope(scope) {
110
+ const internalPatterns = [
111
+ /^\.?\/?src\//i,
112
+ /^\.?\/?lib\//i,
113
+ /^\.?\/?app\//i,
114
+ /^\.?\/?components\//i,
115
+ /^\.?\/?pages\//i,
116
+ /^\.?\/?public\//i,
117
+ /^\.?\/?assets\//i,
118
+ /^\.\//
119
+ ];
120
+ return !internalPatterns.some((p) => p.test(scope));
121
+ }
122
+ function evaluateGuard(event, world, options = {}) {
123
+ const startTime = performance.now();
124
+ const level = options.level ?? "standard";
125
+ const includeTrace = options.trace ?? false;
126
+ const eventText = (event.intent + " " + (event.tool ?? "") + " " + (event.scope ?? "")).toLowerCase();
127
+ const invariantChecks = [];
128
+ const safetyChecks = [];
129
+ const roleChecks = [];
130
+ const guardChecks = [];
131
+ const kernelRuleChecks = [];
132
+ const levelChecks = [];
133
+ let decidingLayer = "default-allow";
134
+ let decidingId;
135
+ const guardsMatched = [];
136
+ const rulesMatched = [];
137
+ checkInvariantCoverage(world, invariantChecks);
138
+ if (options.sessionAllowlist) {
139
+ const key = eventToAllowlistKey(event);
140
+ if (options.sessionAllowlist.has(key)) {
141
+ decidingLayer = "session-allowlist";
142
+ decidingId = `allowlist:${key}`;
143
+ return buildVerdict(
144
+ "ALLOW",
145
+ void 0,
146
+ `allowlist:${key}`,
147
+ void 0,
148
+ world,
149
+ level,
150
+ invariantChecks,
151
+ guardsMatched,
152
+ rulesMatched,
153
+ includeTrace ? buildTrace(
154
+ invariantChecks,
155
+ safetyChecks,
156
+ roleChecks,
157
+ guardChecks,
158
+ kernelRuleChecks,
159
+ levelChecks,
160
+ decidingLayer,
161
+ decidingId,
162
+ startTime
163
+ ) : void 0
164
+ );
165
+ }
166
+ }
167
+ const safetyVerdict = checkSafety(event, eventText, safetyChecks);
168
+ if (safetyVerdict) {
169
+ decidingLayer = "safety";
170
+ decidingId = safetyVerdict.ruleId;
171
+ return buildVerdict(
172
+ safetyVerdict.status,
173
+ safetyVerdict.reason,
174
+ safetyVerdict.ruleId,
175
+ void 0,
176
+ world,
177
+ level,
178
+ invariantChecks,
179
+ guardsMatched,
180
+ rulesMatched,
181
+ includeTrace ? buildTrace(
182
+ invariantChecks,
183
+ safetyChecks,
184
+ roleChecks,
185
+ guardChecks,
186
+ kernelRuleChecks,
187
+ levelChecks,
188
+ decidingLayer,
189
+ decidingId,
190
+ startTime
191
+ ) : void 0
192
+ );
193
+ }
194
+ const roleVerdict = checkRoleRules(event, eventText, world, roleChecks);
195
+ if (roleVerdict) {
196
+ decidingLayer = "role";
197
+ decidingId = roleVerdict.ruleId;
198
+ return buildVerdict(
199
+ roleVerdict.status,
200
+ roleVerdict.reason,
201
+ roleVerdict.ruleId,
202
+ void 0,
203
+ world,
204
+ level,
205
+ invariantChecks,
206
+ guardsMatched,
207
+ rulesMatched,
208
+ includeTrace ? buildTrace(
209
+ invariantChecks,
210
+ safetyChecks,
211
+ roleChecks,
212
+ guardChecks,
213
+ kernelRuleChecks,
214
+ levelChecks,
215
+ decidingLayer,
216
+ decidingId,
217
+ startTime
218
+ ) : void 0
219
+ );
220
+ }
221
+ const guardVerdict = checkGuards(event, eventText, world, guardChecks, guardsMatched);
222
+ if (guardVerdict) {
223
+ if (guardVerdict.status !== "ALLOW") {
224
+ decidingLayer = "guard";
225
+ decidingId = guardVerdict.ruleId;
226
+ return buildVerdict(
227
+ guardVerdict.status,
228
+ guardVerdict.reason,
229
+ guardVerdict.ruleId,
230
+ void 0,
231
+ world,
232
+ level,
233
+ invariantChecks,
234
+ guardsMatched,
235
+ rulesMatched,
236
+ includeTrace ? buildTrace(
237
+ invariantChecks,
238
+ safetyChecks,
239
+ roleChecks,
240
+ guardChecks,
241
+ kernelRuleChecks,
242
+ levelChecks,
243
+ decidingLayer,
244
+ decidingId,
245
+ startTime
246
+ ) : void 0
247
+ );
248
+ }
249
+ }
250
+ const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
251
+ if (kernelVerdict) {
252
+ decidingLayer = "kernel-rule";
253
+ decidingId = kernelVerdict.ruleId;
254
+ return buildVerdict(
255
+ kernelVerdict.status,
256
+ kernelVerdict.reason,
257
+ kernelVerdict.ruleId,
258
+ void 0,
259
+ world,
260
+ level,
261
+ invariantChecks,
262
+ guardsMatched,
263
+ rulesMatched,
264
+ includeTrace ? buildTrace(
265
+ invariantChecks,
266
+ safetyChecks,
267
+ roleChecks,
268
+ guardChecks,
269
+ kernelRuleChecks,
270
+ levelChecks,
271
+ decidingLayer,
272
+ decidingId,
273
+ startTime
274
+ ) : void 0
275
+ );
276
+ }
277
+ const levelVerdict = checkLevelConstraints(event, level, levelChecks);
278
+ if (levelVerdict) {
279
+ decidingLayer = "level-constraint";
280
+ decidingId = levelVerdict.ruleId;
281
+ return buildVerdict(
282
+ levelVerdict.status,
283
+ levelVerdict.reason,
284
+ levelVerdict.ruleId,
285
+ void 0,
286
+ world,
287
+ level,
288
+ invariantChecks,
289
+ guardsMatched,
290
+ rulesMatched,
291
+ includeTrace ? buildTrace(
292
+ invariantChecks,
293
+ safetyChecks,
294
+ roleChecks,
295
+ guardChecks,
296
+ kernelRuleChecks,
297
+ levelChecks,
298
+ decidingLayer,
299
+ decidingId,
300
+ startTime
301
+ ) : void 0
302
+ );
303
+ }
304
+ const warning = guardVerdict?.warning;
305
+ return buildVerdict(
306
+ "ALLOW",
307
+ void 0,
308
+ void 0,
309
+ warning,
310
+ world,
311
+ level,
312
+ invariantChecks,
313
+ guardsMatched,
314
+ rulesMatched,
315
+ includeTrace ? buildTrace(
316
+ invariantChecks,
317
+ safetyChecks,
318
+ roleChecks,
319
+ guardChecks,
320
+ kernelRuleChecks,
321
+ levelChecks,
322
+ decidingLayer,
323
+ decidingId,
324
+ startTime
325
+ ) : void 0
326
+ );
327
+ }
328
+ function checkInvariantCoverage(world, checks) {
329
+ const invariants = world.invariants ?? [];
330
+ const guards = world.guards?.guards ?? [];
331
+ for (const invariant of invariants) {
332
+ const coveringGuard = guards.find(
333
+ (g) => g.invariant_ref === invariant.id && g.immutable
334
+ );
335
+ checks.push({
336
+ invariantId: invariant.id,
337
+ label: invariant.label,
338
+ hasGuardCoverage: !!coveringGuard,
339
+ coveringGuardId: coveringGuard?.id
340
+ });
341
+ }
342
+ }
343
+ function checkSafety(event, eventText, checks) {
344
+ const textToCheck = event.intent + (event.payload ? JSON.stringify(event.payload) : "");
345
+ for (const { pattern, label } of PROMPT_INJECTION_PATTERNS) {
346
+ const triggered = pattern.test(textToCheck);
347
+ checks.push({
348
+ checkType: "prompt-injection",
349
+ triggered,
350
+ matchedPattern: triggered ? label : void 0
351
+ });
352
+ if (triggered) {
353
+ for (const remaining of PROMPT_INJECTION_PATTERNS.filter((p) => p.label !== label)) {
354
+ checks.push({
355
+ checkType: "prompt-injection",
356
+ triggered: remaining.pattern.test(textToCheck),
357
+ matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
358
+ });
359
+ }
360
+ return {
361
+ status: "PAUSE",
362
+ reason: NEUTRAL_MESSAGES["prompt-injection"],
363
+ ruleId: `safety-injection-${label}`
364
+ };
365
+ }
366
+ }
367
+ const scopeToCheck = event.scope ?? event.intent;
368
+ for (const { pattern, label } of SCOPE_ESCAPE_PATTERNS) {
369
+ const triggered = pattern.test(scopeToCheck);
370
+ checks.push({
371
+ checkType: "scope-escape",
372
+ triggered,
373
+ matchedPattern: triggered ? label : void 0
374
+ });
375
+ if (triggered) {
376
+ for (const remaining of SCOPE_ESCAPE_PATTERNS.filter((p) => p.label !== label)) {
377
+ checks.push({
378
+ checkType: "scope-escape",
379
+ triggered: remaining.pattern.test(scopeToCheck),
380
+ matchedPattern: remaining.pattern.test(scopeToCheck) ? remaining.label : void 0
381
+ });
382
+ }
383
+ return {
384
+ status: "PAUSE",
385
+ reason: NEUTRAL_MESSAGES["scope-escape"],
386
+ ruleId: `safety-scope-${label}`
387
+ };
388
+ }
389
+ }
390
+ if (event.direction === "output") {
391
+ for (const { pattern, label } of EXECUTION_CLAIM_PATTERNS) {
392
+ const triggered = pattern.test(textToCheck);
393
+ checks.push({
394
+ checkType: "execution-claim",
395
+ triggered,
396
+ matchedPattern: triggered ? label : void 0
397
+ });
398
+ if (triggered) {
399
+ for (const remaining of EXECUTION_CLAIM_PATTERNS.filter((p) => p.label !== label)) {
400
+ checks.push({
401
+ checkType: "execution-claim",
402
+ triggered: remaining.pattern.test(textToCheck),
403
+ matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
404
+ });
405
+ }
406
+ return {
407
+ status: "PAUSE",
408
+ reason: NEUTRAL_MESSAGES["execution-claim"],
409
+ ruleId: `safety-execution-claim-${label}`
410
+ };
411
+ }
412
+ }
413
+ }
414
+ if (event.direction === "input") {
415
+ const intentTrimmed = event.intent.trim();
416
+ for (const { pattern, label } of EXECUTION_INTENT_PATTERNS) {
417
+ const triggered = pattern.test(intentTrimmed);
418
+ checks.push({
419
+ checkType: "execution-intent",
420
+ triggered,
421
+ matchedPattern: triggered ? label : void 0
422
+ });
423
+ if (triggered) {
424
+ for (const remaining of EXECUTION_INTENT_PATTERNS.filter((p) => p.label !== label)) {
425
+ checks.push({
426
+ checkType: "execution-intent",
427
+ triggered: remaining.pattern.test(intentTrimmed),
428
+ matchedPattern: remaining.pattern.test(intentTrimmed) ? remaining.label : void 0
429
+ });
430
+ }
431
+ return {
432
+ status: "PAUSE",
433
+ reason: NEUTRAL_MESSAGES["execution-intent"],
434
+ ruleId: `safety-execution-intent-${label}`
435
+ };
436
+ }
437
+ }
438
+ }
439
+ return null;
440
+ }
441
+ function checkRoleRules(event, eventText, world, checks) {
442
+ if (!event.roleId || !world.roles) return null;
443
+ const role = world.roles.roles.find((r) => r.id === event.roleId);
444
+ if (!role) return null;
445
+ if (role.requiresApproval) {
446
+ checks.push({
447
+ roleId: role.id,
448
+ roleName: role.name,
449
+ rule: "All actions require approval",
450
+ ruleType: "requiresApproval",
451
+ matched: true
452
+ });
453
+ return {
454
+ status: "PAUSE",
455
+ reason: `Role "${role.name}" requires approval for all actions.`,
456
+ ruleId: `role-${role.id}-requires-approval`
457
+ };
458
+ }
459
+ for (const rule of role.cannotDo) {
460
+ const matched = matchesKeywords(eventText, rule);
461
+ checks.push({
462
+ roleId: role.id,
463
+ roleName: role.name,
464
+ rule,
465
+ ruleType: "cannotDo",
466
+ matched
467
+ });
468
+ if (matched) {
469
+ return {
470
+ status: "BLOCK",
471
+ reason: `Role "${role.name}" cannot: ${rule}`,
472
+ ruleId: `role-${role.id}-cannotdo`
473
+ };
474
+ }
475
+ }
476
+ for (const rule of role.canDo) {
477
+ checks.push({
478
+ roleId: role.id,
479
+ roleName: role.name,
480
+ rule,
481
+ ruleType: "canDo",
482
+ matched: matchesKeywords(eventText, rule)
483
+ });
484
+ }
485
+ return null;
486
+ }
487
+ function checkGuards(event, eventText, world, checks, guardsMatched) {
488
+ if (!world.guards) return null;
489
+ const guardsConfig = world.guards;
490
+ let warnResult = null;
491
+ const compiledPatterns = /* @__PURE__ */ new Map();
492
+ for (const [key, def] of Object.entries(guardsConfig.intent_vocabulary)) {
493
+ try {
494
+ compiledPatterns.set(key, new RegExp(def.pattern, "i"));
495
+ } catch {
496
+ }
497
+ }
498
+ const eventTool = (event.tool ?? "").toLowerCase();
499
+ for (const guard of guardsConfig.guards) {
500
+ if (guard.appliesTo && guard.appliesTo.length > 0) {
501
+ const normalizedAppliesTo = guard.appliesTo.map((t) => t.toLowerCase());
502
+ if (!normalizedAppliesTo.includes(eventTool)) {
503
+ continue;
504
+ }
505
+ }
506
+ const enabled = guard.immutable || guard.default_enabled !== false;
507
+ const matchedPatterns = [];
508
+ for (const patternKey of guard.intent_patterns) {
509
+ const regex = compiledPatterns.get(patternKey);
510
+ if (regex?.test(eventText)) {
511
+ matchedPatterns.push(patternKey);
512
+ }
513
+ }
514
+ const matched = matchedPatterns.length > 0 && enabled;
515
+ let roleGated = false;
516
+ if (matched && guard.required_roles && guard.required_roles.length > 0 && event.roleId && guard.required_roles.includes(event.roleId)) {
517
+ roleGated = true;
518
+ }
519
+ checks.push({
520
+ guardId: guard.id,
521
+ label: guard.label,
522
+ category: guard.category,
523
+ enabled,
524
+ matched: matched && !roleGated,
525
+ enforcement: guard.enforcement,
526
+ matchedPatterns,
527
+ roleGated
528
+ });
529
+ if (!matched || roleGated) continue;
530
+ guardsMatched.push(guard.id);
531
+ const actionMode = guard.player_modes?.action ?? guard.enforcement;
532
+ const reason = guard.redirect ? `${guard.description} \u2014 ${guard.redirect}` : guard.description;
533
+ if (actionMode === "block") {
534
+ return { status: "BLOCK", reason, ruleId: `guard-${guard.id}` };
535
+ }
536
+ if (actionMode === "pause") {
537
+ return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
538
+ }
539
+ if (actionMode === "warn" && !warnResult) {
540
+ warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
541
+ }
542
+ }
543
+ return warnResult;
544
+ }
545
+ function checkKernelRules(eventText, world, checks, rulesMatched) {
546
+ if (!world.kernel) return null;
547
+ const forbidden = world.kernel.input_boundaries?.forbidden_patterns ?? [];
548
+ const output = world.kernel.output_boundaries?.forbidden_patterns ?? [];
549
+ for (const rule of forbidden) {
550
+ let matched = false;
551
+ let matchMethod = "none";
552
+ if (rule.pattern) {
553
+ try {
554
+ matched = new RegExp(rule.pattern, "i").test(eventText);
555
+ matchMethod = "pattern";
556
+ } catch {
557
+ }
558
+ }
559
+ if (!matched && rule.reason) {
560
+ matched = matchesKeywords(eventText, rule.reason);
561
+ if (matched) matchMethod = "keyword";
562
+ }
563
+ checks.push({
564
+ ruleId: rule.id,
565
+ text: rule.reason,
566
+ category: "forbidden",
567
+ matched,
568
+ matchMethod
569
+ });
570
+ if (matched) {
571
+ rulesMatched.push(rule.id);
572
+ if (rule.action === "BLOCK") {
573
+ return {
574
+ status: "BLOCK",
575
+ reason: rule.reason,
576
+ ruleId: `kernel-${rule.id}`
577
+ };
578
+ }
579
+ }
580
+ }
581
+ return null;
582
+ }
583
+ function checkLevelConstraints(event, level, checks) {
584
+ if (level === "basic") return null;
585
+ const intent = event.intent.toLowerCase();
586
+ const tool = (event.tool ?? "").toLowerCase();
587
+ const isDelete = intent.includes("delete") || intent.includes("remove") || intent.includes("rm ") || tool === "delete";
588
+ const deleteTriggered = isDelete && levelRequiresConfirmation(level, "delete");
589
+ checks.push({
590
+ checkType: "delete",
591
+ level,
592
+ triggered: deleteTriggered,
593
+ reason: deleteTriggered ? NEUTRAL_MESSAGES["delete"] : void 0
594
+ });
595
+ if (deleteTriggered) {
596
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["delete"], ruleId: "level-delete-check" };
597
+ }
598
+ const isExternal = event.scope ? isExternalScope(event.scope) : false;
599
+ const externalTriggered = isExternal && levelRequiresConfirmation(level, "write-external");
600
+ checks.push({
601
+ checkType: "write-external",
602
+ level,
603
+ triggered: externalTriggered,
604
+ reason: externalTriggered ? NEUTRAL_MESSAGES["write-external"] : void 0
605
+ });
606
+ if (externalTriggered) {
607
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["write-external"], ruleId: "level-external-write-check" };
608
+ }
609
+ const isNetwork = tool === "http" || tool === "fetch" || tool === "request" || intent.includes("post ") || intent.includes("sending");
610
+ const networkTriggered = isNetwork && levelRequiresConfirmation(level, "network-mutate");
611
+ checks.push({
612
+ checkType: "network-mutate",
613
+ level,
614
+ triggered: networkTriggered,
615
+ reason: networkTriggered ? NEUTRAL_MESSAGES["network-mutate"] : void 0
616
+ });
617
+ if (networkTriggered) {
618
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["network-mutate"], ruleId: "level-network-mutate-check" };
619
+ }
620
+ const isCredential = intent.includes("credential") || intent.includes("password") || intent.includes("secret") || intent.includes("api key") || intent.includes("token");
621
+ const credentialTriggered = isCredential && levelRequiresConfirmation(level, "credential-access");
622
+ checks.push({
623
+ checkType: "credential-access",
624
+ level,
625
+ triggered: credentialTriggered,
626
+ reason: credentialTriggered ? NEUTRAL_MESSAGES["credential-access"] : void 0
627
+ });
628
+ if (credentialTriggered) {
629
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["credential-access"], ruleId: "level-credential-check" };
630
+ }
631
+ const irreversibleTriggered = !!event.irreversible && level !== "basic";
632
+ checks.push({
633
+ checkType: "irreversible",
634
+ level,
635
+ triggered: irreversibleTriggered,
636
+ reason: irreversibleTriggered ? "This action is marked as irreversible." : void 0
637
+ });
638
+ if (irreversibleTriggered) {
639
+ return {
640
+ status: "PAUSE",
641
+ reason: "This action is marked as irreversible.",
642
+ ruleId: "level-irreversible-check"
643
+ };
644
+ }
645
+ return null;
646
+ }
647
+ function matchesKeywords(eventText, ruleText) {
648
+ const keywords = ruleText.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
649
+ if (keywords.length === 0) return false;
650
+ return keywords.every((kw) => eventText.includes(kw));
651
+ }
652
+ function eventToAllowlistKey(event) {
653
+ return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
654
+ }
655
+ function buildTrace(invariantChecks, safetyChecks, roleChecks, guardChecks, kernelRuleChecks, levelChecks, decidingLayer, decidingId, startTime) {
656
+ return {
657
+ invariantChecks,
658
+ safetyChecks,
659
+ roleChecks,
660
+ guardChecks,
661
+ kernelRuleChecks,
662
+ levelChecks,
663
+ precedenceResolution: {
664
+ decidingLayer,
665
+ decidingId,
666
+ strategy: "first-match-wins",
667
+ chainOrder: [
668
+ "invariant-coverage",
669
+ "session-allowlist",
670
+ "safety-injection",
671
+ "safety-scope-escape",
672
+ "safety-execution-claim",
673
+ "safety-execution-intent",
674
+ "role-rules",
675
+ "declarative-guards",
676
+ "kernel-rules",
677
+ "level-constraints",
678
+ "default-allow"
679
+ ]
680
+ },
681
+ durationMs: performance.now() - startTime
682
+ };
683
+ }
684
+ function buildVerdict(status, reason, ruleId, warning, world, level, invariantChecks, guardsMatched, rulesMatched, trace) {
685
+ const evidence = {
686
+ worldId: world.world.world_id,
687
+ worldName: world.world.name,
688
+ worldVersion: world.world.version,
689
+ evaluatedAt: Date.now(),
690
+ invariantsSatisfied: invariantChecks.filter((c) => c.hasGuardCoverage).length,
691
+ invariantsTotal: invariantChecks.length,
692
+ guardsMatched,
693
+ rulesMatched,
694
+ enforcementLevel: level
695
+ };
696
+ const verdict = {
697
+ status,
698
+ evidence
699
+ };
700
+ if (reason) verdict.reason = reason;
701
+ if (ruleId) verdict.ruleId = ruleId;
702
+ if (warning) verdict.warning = warning;
703
+ if (trace) verdict.trace = trace;
704
+ return verdict;
705
+ }
706
+
707
+ // src/loader/world-loader.ts
708
+ async function loadWorldFromDirectory(dirPath) {
709
+ const { readFile } = await import("fs/promises");
710
+ const { join } = await import("path");
711
+ const { readdirSync } = await import("fs");
712
+ async function readJson(filename) {
713
+ try {
714
+ const content = await readFile(join(dirPath, filename), "utf-8");
715
+ return JSON.parse(content);
716
+ } catch {
717
+ return void 0;
718
+ }
719
+ }
720
+ const worldJson = await readJson("world.json");
721
+ if (!worldJson) {
722
+ throw new Error(`Cannot read world.json in ${dirPath}`);
723
+ }
724
+ const invariantsJson = await readJson("invariants.json");
725
+ const assumptionsJson = await readJson("assumptions.json");
726
+ const stateSchemaJson = await readJson("state-schema.json");
727
+ const gatesJson = await readJson("gates.json");
728
+ const outcomesJson = await readJson("outcomes.json");
729
+ const guardsJson = await readJson("guards.json");
730
+ const rolesJson = await readJson("roles.json");
731
+ const kernelJson = await readJson("kernel.json");
732
+ const metadataJson = await readJson("metadata.json");
733
+ const rules = [];
734
+ try {
735
+ const rulesDir = join(dirPath, "rules");
736
+ const ruleFiles = readdirSync(rulesDir).filter((f) => f.endsWith(".json")).sort();
737
+ for (const file of ruleFiles) {
738
+ const content = await readFile(join(rulesDir, file), "utf-8");
739
+ rules.push(JSON.parse(content));
740
+ }
741
+ } catch {
742
+ }
743
+ return {
744
+ world: worldJson,
745
+ invariants: invariantsJson?.invariants ?? [],
746
+ assumptions: assumptionsJson ?? { profiles: {}, parameter_definitions: {} },
747
+ stateSchema: stateSchemaJson ?? { variables: {}, presets: {} },
748
+ rules,
749
+ gates: gatesJson ?? {
750
+ viability_classification: [],
751
+ structural_override: { description: "", enforcement: "mandatory" },
752
+ sustainability_threshold: 0,
753
+ collapse_visual: { background: "", text: "", border: "", label: "" }
754
+ },
755
+ outcomes: outcomesJson ?? {
756
+ computed_outcomes: [],
757
+ comparison_layout: { primary_card: "", status_badge: "", structural_indicators: [] }
758
+ },
759
+ guards: guardsJson,
760
+ roles: rolesJson,
761
+ kernel: kernelJson,
762
+ metadata: metadataJson ?? {
763
+ format_version: "1.0.0",
764
+ created_at: "",
765
+ last_modified: "",
766
+ authoring_method: "manual-authoring"
767
+ }
768
+ };
769
+ }
770
+ async function loadWorld(worldPath) {
771
+ const { stat } = await import("fs/promises");
772
+ const info = await stat(worldPath);
773
+ if (info.isDirectory()) {
774
+ return loadWorldFromDirectory(worldPath);
775
+ }
776
+ if (worldPath.endsWith(".nv-world.zip")) {
777
+ throw new Error(".nv-world.zip loading not yet implemented \u2014 use a world directory");
778
+ }
779
+ throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory or .nv-world.zip`);
780
+ }
781
+
782
+ // src/adapters/express.ts
783
+ function methodToCategory(method) {
784
+ switch (method.toUpperCase()) {
785
+ case "GET":
786
+ case "HEAD":
787
+ case "OPTIONS":
788
+ return "read";
789
+ case "POST":
790
+ case "PUT":
791
+ case "PATCH":
792
+ return "write";
793
+ case "DELETE":
794
+ return "delete";
795
+ default:
796
+ return "other";
797
+ }
798
+ }
799
+ function defaultMapRequest(req) {
800
+ const method = (req.method ?? "GET").toUpperCase();
801
+ const path = req.path ?? req.url ?? "/";
802
+ return {
803
+ intent: `${method} ${path}`,
804
+ tool: "http",
805
+ scope: path,
806
+ actionCategory: methodToCategory(method),
807
+ direction: "input",
808
+ args: {
809
+ method,
810
+ path,
811
+ ...req.params ?? {},
812
+ ...req.query ?? {}
813
+ }
814
+ };
815
+ }
816
+ function defaultOnBlock(verdict, _req, res, statusCode) {
817
+ const body = {
818
+ error: "Governance policy violation",
819
+ reason: verdict.reason ?? "Action not permitted",
820
+ ruleId: verdict.ruleId,
821
+ status: verdict.status
822
+ };
823
+ if (res.status && res.json) {
824
+ res.status(statusCode).json(body);
825
+ } else if (res.send) {
826
+ res.statusCode = statusCode;
827
+ res.send(JSON.stringify(body));
828
+ } else if (res.end) {
829
+ res.statusCode = statusCode;
830
+ res.end();
831
+ }
832
+ }
833
+ async function createGovernanceMiddleware(worldPath, options) {
834
+ const world = await loadWorld(worldPath);
835
+ return createGovernanceMiddlewareFromWorld(world, options);
836
+ }
837
+ function createGovernanceMiddlewareFromWorld(world, options = {}) {
838
+ const engineOptions = {
839
+ trace: options.trace ?? false,
840
+ level: options.level
841
+ };
842
+ const mapRequest = options.mapRequest ?? defaultMapRequest;
843
+ const blockStatusCode = options.blockStatusCode ?? 403;
844
+ return async function neuroVerseGovernance(req, res, next) {
845
+ try {
846
+ const event = mapRequest(req);
847
+ const verdict = evaluateGuard(event, world, engineOptions);
848
+ options.onEvaluate?.(verdict, event, req);
849
+ if (verdict.status === "ALLOW") {
850
+ next();
851
+ return;
852
+ }
853
+ if (verdict.status === "PAUSE") {
854
+ const approved = await options.onPause?.(verdict, req);
855
+ if (approved) {
856
+ next();
857
+ return;
858
+ }
859
+ }
860
+ if (options.onBlock) {
861
+ options.onBlock(verdict, req, res);
862
+ } else {
863
+ defaultOnBlock(verdict, req, res, blockStatusCode);
864
+ }
865
+ } catch (err) {
866
+ next(err);
867
+ }
868
+ };
869
+ }
870
+ // Annotate the CommonJS export names for ESM import in node:
871
+ 0 && (module.exports = {
872
+ createGovernanceMiddleware,
873
+ createGovernanceMiddlewareFromWorld
874
+ });