@neuroverseos/governance 0.3.1 → 0.3.3

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