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