@h-rig/guard-plugin 0.0.6-alpha.156 → 0.0.6-alpha.158

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.
@@ -3,8 +3,658 @@
3
3
 
4
4
  // packages/guard-plugin/src/hooks/test-integrity-guard.ts
5
5
  import { resolveTaskScopes, resolvePolicyContent, isTestFilePath, runTypedHook } from "@rig/hook-kit";
6
- import { evaluate, seedPolicyFromContent } from "@rig/runtime/control-plane/runtime/guard";
6
+
7
+ // packages/guard-plugin/src/guard.ts
8
+ import { optimizeNextInvocation } from "bun:jsc";
9
+ import { existsSync, readFileSync, statSync } from "fs";
10
+ import { resolve } from "path";
11
+
12
+ // packages/guard-plugin/src/scope.ts
13
+ import { getScopeRules } from "@rig/core/scope-rules";
14
+ var scopeRegexCache = new Map;
15
+ function unique(values) {
16
+ return [...new Set(values)];
17
+ }
18
+ function normalizeRelativeScopePath(inputPath) {
19
+ let normalized = inputPath.replace(/^\.\//, "");
20
+ const rules = getScopeRules();
21
+ if (rules?.stripPrefixes) {
22
+ for (const prefix of rules.stripPrefixes) {
23
+ if (normalized.startsWith(prefix)) {
24
+ normalized = normalized.slice(prefix.length);
25
+ }
26
+ }
27
+ }
28
+ return normalized;
29
+ }
30
+ function normalizePathToScope(projectRoot, monorepoRoot, inputPath) {
31
+ let normalized = inputPath.replace(/^\.\//, "");
32
+ if (normalized.startsWith(projectRoot + "/")) {
33
+ normalized = normalized.slice(projectRoot.length + 1);
34
+ }
35
+ if (normalized.startsWith(monorepoRoot + "/")) {
36
+ normalized = normalized.slice(monorepoRoot.length + 1);
37
+ }
38
+ return normalizeRelativeScopePath(normalized);
39
+ }
40
+ function scopeGlobToRegex(glob) {
41
+ const cached = scopeRegexCache.get(glob);
42
+ if (cached) {
43
+ return cached;
44
+ }
45
+ const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*\*/g, "__GLOBSTAR__").replace(/\*/g, "[^/]*").replace(/__GLOBSTAR__/g, ".*");
46
+ const compiled = new RegExp(`^${escaped}$`);
47
+ scopeRegexCache.set(glob, compiled);
48
+ return compiled;
49
+ }
50
+ function scopeMatches(path, scopes) {
51
+ const pathVariants = unique([path, normalizeRelativeScopePath(path)]);
52
+ for (const scope of scopes) {
53
+ const scopeVariants = unique([scope, normalizeRelativeScopePath(scope)]);
54
+ for (const candidatePath of pathVariants) {
55
+ for (const candidateScope of scopeVariants) {
56
+ if (candidatePath === candidateScope || scopeGlobToRegex(candidateScope).test(candidatePath)) {
57
+ return true;
58
+ }
59
+ }
60
+ }
61
+ }
62
+ return false;
63
+ }
64
+
65
+ // packages/guard-plugin/src/guard.ts
66
+ import {
67
+ POLICY_VERSION
68
+ } from "@rig/contracts";
69
+ var DEFAULT_SCOPE = {
70
+ fail_closed: true,
71
+ harness_paths_exempt: true,
72
+ runtime_paths_exempt: true
73
+ };
74
+ var DEFAULT_SANDBOX = {
75
+ mode: "enforce",
76
+ network: true,
77
+ read_deny: [],
78
+ write_allow_from_runtime: true
79
+ };
80
+ var DEFAULT_ISOLATION = {
81
+ default_mode: "worktree",
82
+ repo_symlink_fallback: false,
83
+ strict_provisioning: true,
84
+ fail_closed_on_provision_error: true
85
+ };
86
+ var DEFAULT_COMPLETION = {
87
+ derive_checks_from_scope: true,
88
+ checks: [],
89
+ typescript_config_probe: ["tsconfig.json"],
90
+ eslint_config_probe: [".eslintrc.js", ".eslintrc.json", "eslint.config.js"]
91
+ };
92
+ var DEFAULT_RUNTIME_IMAGE = {
93
+ deps: {
94
+ monorepo_install: false,
95
+ hp_next_install: false
96
+ },
97
+ plugins_require_binaries: true
98
+ };
99
+ var DEFAULT_RUNTIME_SNAPSHOT = {
100
+ enabled: true
101
+ };
102
+ function defaultPolicy() {
103
+ return {
104
+ version: POLICY_VERSION,
105
+ mode: "enforce",
106
+ scope: { ...DEFAULT_SCOPE },
107
+ rules: [],
108
+ sandbox: { ...DEFAULT_SANDBOX },
109
+ isolation: { ...DEFAULT_ISOLATION },
110
+ completion: { ...DEFAULT_COMPLETION },
111
+ runtime_image: {
112
+ deps: { ...DEFAULT_RUNTIME_IMAGE.deps },
113
+ plugins_require_binaries: DEFAULT_RUNTIME_IMAGE.plugins_require_binaries
114
+ },
115
+ runtime_snapshot: { ...DEFAULT_RUNTIME_SNAPSHOT }
116
+ };
117
+ }
118
+ var policyCache = null;
119
+ var policyCachePath = null;
120
+ var seededPolicyConfig = null;
121
+ var compiledRegexCache = new Map;
122
+ function seedPolicyFromContent(rawJson) {
123
+ try {
124
+ const parsed = JSON.parse(rawJson);
125
+ seededPolicyConfig = mergeWithDefaults(parsed);
126
+ } catch {}
127
+ }
128
+ function loadPolicy(projectRoot) {
129
+ if (seededPolicyConfig) {
130
+ return seededPolicyConfig;
131
+ }
132
+ const configPath = resolve(projectRoot, "rig/policy/policy.json");
133
+ if (!existsSync(configPath)) {
134
+ return defaultPolicy();
135
+ }
136
+ let mtimeMs;
137
+ try {
138
+ mtimeMs = statSync(configPath).mtimeMs;
139
+ } catch {
140
+ return defaultPolicy();
141
+ }
142
+ if (policyCache && policyCachePath === configPath && policyCache.mtimeMs === mtimeMs) {
143
+ return policyCache.config;
144
+ }
145
+ let parsed;
146
+ try {
147
+ parsed = JSON.parse(readFileSync(configPath, "utf-8"));
148
+ } catch {
149
+ return defaultPolicy();
150
+ }
151
+ const config = mergeWithDefaults(parsed);
152
+ policyCache = { mtimeMs, config };
153
+ policyCachePath = configPath;
154
+ return config;
155
+ }
156
+ function mergeWithDefaults(parsed) {
157
+ const base = defaultPolicy();
158
+ if (typeof parsed.mode === "string" && isValidMode(parsed.mode)) {
159
+ base.mode = parsed.mode;
160
+ }
161
+ if (parsed.scope && typeof parsed.scope === "object" && !Array.isArray(parsed.scope)) {
162
+ const s = parsed.scope;
163
+ if (typeof s.fail_closed === "boolean")
164
+ base.scope.fail_closed = s.fail_closed;
165
+ if (typeof s.harness_paths_exempt === "boolean")
166
+ base.scope.harness_paths_exempt = s.harness_paths_exempt;
167
+ if (typeof s.runtime_paths_exempt === "boolean")
168
+ base.scope.runtime_paths_exempt = s.runtime_paths_exempt;
169
+ }
170
+ if (Array.isArray(parsed.rules)) {
171
+ base.rules = precompilePolicyRuleRegexes(parsed.rules.filter(isValidRule));
172
+ }
173
+ if (Array.isArray(parsed.deny) && base.rules.length === 0) {
174
+ base.rules = precompilePolicyRuleRegexes(migrateLegacyDeny(parsed.deny));
175
+ }
176
+ if (parsed.sandbox && typeof parsed.sandbox === "object" && !Array.isArray(parsed.sandbox)) {
177
+ const sb = parsed.sandbox;
178
+ if (typeof sb.mode === "string" && isValidMode(sb.mode))
179
+ base.sandbox.mode = sb.mode;
180
+ if (typeof sb.network === "boolean")
181
+ base.sandbox.network = sb.network;
182
+ if (Array.isArray(sb.read_deny))
183
+ base.sandbox.read_deny = sb.read_deny.filter((v) => typeof v === "string");
184
+ if (typeof sb.write_allow_from_runtime === "boolean")
185
+ base.sandbox.write_allow_from_runtime = sb.write_allow_from_runtime;
186
+ }
187
+ if (parsed.isolation && typeof parsed.isolation === "object" && !Array.isArray(parsed.isolation)) {
188
+ const iso = parsed.isolation;
189
+ if (iso.default_mode === "worktree")
190
+ base.isolation.default_mode = iso.default_mode;
191
+ if (typeof iso.repo_symlink_fallback === "boolean")
192
+ base.isolation.repo_symlink_fallback = iso.repo_symlink_fallback;
193
+ if (typeof iso.strict_provisioning === "boolean")
194
+ base.isolation.strict_provisioning = iso.strict_provisioning;
195
+ if (typeof iso.fail_closed_on_provision_error === "boolean")
196
+ base.isolation.fail_closed_on_provision_error = iso.fail_closed_on_provision_error;
197
+ }
198
+ if (parsed.completion && typeof parsed.completion === "object" && !Array.isArray(parsed.completion)) {
199
+ const comp = parsed.completion;
200
+ if (typeof comp.derive_checks_from_scope === "boolean")
201
+ base.completion.derive_checks_from_scope = comp.derive_checks_from_scope;
202
+ if (Array.isArray(comp.checks))
203
+ base.completion.checks = comp.checks.filter((v) => typeof v === "string");
204
+ if (Array.isArray(comp.typescript_config_probe))
205
+ base.completion.typescript_config_probe = comp.typescript_config_probe.filter((v) => typeof v === "string");
206
+ if (Array.isArray(comp.eslint_config_probe))
207
+ base.completion.eslint_config_probe = comp.eslint_config_probe.filter((v) => typeof v === "string");
208
+ }
209
+ if (parsed.runtime_image && typeof parsed.runtime_image === "object" && !Array.isArray(parsed.runtime_image)) {
210
+ const runtimeImage = parsed.runtime_image;
211
+ if (runtimeImage.deps && typeof runtimeImage.deps === "object" && !Array.isArray(runtimeImage.deps)) {
212
+ const deps = runtimeImage.deps;
213
+ if (typeof deps.monorepo_install === "boolean") {
214
+ base.runtime_image.deps.monorepo_install = deps.monorepo_install;
215
+ }
216
+ if (typeof deps.hp_next_install === "boolean") {
217
+ base.runtime_image.deps.hp_next_install = deps.hp_next_install;
218
+ }
219
+ }
220
+ if (typeof runtimeImage.plugins_require_binaries === "boolean") {
221
+ base.runtime_image.plugins_require_binaries = runtimeImage.plugins_require_binaries;
222
+ }
223
+ }
224
+ if (parsed.runtime_snapshot && typeof parsed.runtime_snapshot === "object" && !Array.isArray(parsed.runtime_snapshot)) {
225
+ const runtimeSnapshot = parsed.runtime_snapshot;
226
+ if (typeof runtimeSnapshot.enabled === "boolean") {
227
+ base.runtime_snapshot.enabled = runtimeSnapshot.enabled;
228
+ }
229
+ }
230
+ return base;
231
+ }
232
+ function isValidMode(value) {
233
+ return value === "off" || value === "observe" || value === "enforce";
234
+ }
235
+ function isValidRule(value) {
236
+ if (!value || typeof value !== "object" || Array.isArray(value))
237
+ return false;
238
+ const r = value;
239
+ return typeof r.id === "string" && typeof r.category === "string" && r.match != null && typeof r.match === "object";
240
+ }
241
+ function migrateLegacyDeny(deny) {
242
+ const rules = [];
243
+ for (const entry of deny) {
244
+ if (typeof entry.id !== "string")
245
+ continue;
246
+ const match = {};
247
+ if (typeof entry.pattern === "string")
248
+ match.pattern = entry.pattern;
249
+ if (typeof entry.regex === "string")
250
+ match.regex = entry.regex;
251
+ if (!match.pattern && !match.regex)
252
+ continue;
253
+ rules.push({
254
+ id: entry.id,
255
+ category: "command",
256
+ match,
257
+ action: "block",
258
+ ...typeof entry.description === "string" ? { description: entry.description } : {}
259
+ });
260
+ }
261
+ return rules;
262
+ }
263
+ function precompilePolicyRuleRegexes(rules) {
264
+ return rules.map((rule) => {
265
+ const compiledRegex = rule.match.regex ? compileSafeRegex(rule.match.regex, `rules.${rule.id}.match.regex`, true) : undefined;
266
+ const compiledUnlessRegex = rule.unless?.regex ? compileSafeRegex(rule.unless.regex, `rules.${rule.id}.unless.regex`, true) : undefined;
267
+ return {
268
+ ...rule,
269
+ ...compiledRegex ? { compiledRegex } : {},
270
+ ...compiledUnlessRegex ? { compiledUnlessRegex } : {}
271
+ };
272
+ });
273
+ }
274
+ function getRegexUnsafeReason(pattern) {
275
+ if (pattern.length > 512) {
276
+ return "pattern exceeds max safe length (512 chars)";
277
+ }
278
+ if (/\\[1-9]/.test(pattern)) {
279
+ return "pattern uses backreferences";
280
+ }
281
+ if (/\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)\s*[*+{]/.test(pattern)) {
282
+ return "pattern contains nested quantifiers";
283
+ }
284
+ if (/\((?:[^()\\]|\\.)*\.\\?[+*](?:[^()\\]|\\.)*\)\s*[*+{]/.test(pattern)) {
285
+ return "pattern contains nested broad quantifiers";
286
+ }
287
+ return null;
288
+ }
289
+ function compileSafeRegex(pattern, sourceLabel, logOnFailure) {
290
+ const cached = compiledRegexCache.get(pattern);
291
+ if (cached !== undefined) {
292
+ return cached ?? undefined;
293
+ }
294
+ const unsafeReason = getRegexUnsafeReason(pattern);
295
+ if (unsafeReason) {
296
+ if (logOnFailure) {
297
+ console.warn(`[policy] Skipping unsafe regex in ${sourceLabel}: ${unsafeReason}`);
298
+ }
299
+ compiledRegexCache.set(pattern, null);
300
+ return;
301
+ }
302
+ try {
303
+ const compiled = new RegExp(pattern);
304
+ compiledRegexCache.set(pattern, compiled);
305
+ return compiled;
306
+ } catch (error) {
307
+ if (logOnFailure) {
308
+ const message = error instanceof Error ? error.message : String(error);
309
+ console.warn(`[policy] Skipping invalid regex in ${sourceLabel}: ${message}`);
310
+ }
311
+ compiledRegexCache.set(pattern, null);
312
+ return;
313
+ }
314
+ }
315
+ function matchRule(rule, input) {
316
+ const { match } = rule;
317
+ if (match.pattern && input.includes(match.pattern)) {
318
+ return true;
319
+ }
320
+ if (match.regex) {
321
+ const compiled = rule.compiledRegex || compileSafeRegex(match.regex, `rules.${rule.id}.match.regex`, false);
322
+ if (!compiled) {
323
+ return false;
324
+ }
325
+ try {
326
+ return compiled.test(input);
327
+ } catch {
328
+ return false;
329
+ }
330
+ }
331
+ return false;
332
+ }
333
+ function matchRuleUnless(rule, command, taskId) {
334
+ if (!rule.unless)
335
+ return false;
336
+ if (rule.unless.regex) {
337
+ const compiled = rule.compiledUnlessRegex || compileSafeRegex(rule.unless.regex, `rules.${rule.id}.unless.regex`, false);
338
+ if (!compiled) {
339
+ return false;
340
+ }
341
+ try {
342
+ if (compiled.test(command))
343
+ return true;
344
+ } catch {}
345
+ }
346
+ if (rule.unless.task_in && taskId) {
347
+ if (rule.unless.task_in.includes(taskId))
348
+ return true;
349
+ }
350
+ return false;
351
+ }
352
+ function resolveAction(mode, matched) {
353
+ if (matched.length === 0)
354
+ return "allow";
355
+ if (mode === "off")
356
+ return "allow";
357
+ if (mode === "observe")
358
+ return "warn";
359
+ return "block";
360
+ }
361
+ function resolveAbsolutePath(projectRoot, rawPath) {
362
+ if (rawPath.startsWith("/"))
363
+ return resolve(rawPath);
364
+ return resolve(projectRoot, rawPath);
365
+ }
366
+ function isHarnessPath(projectRoot, rawPath) {
367
+ const absPath = resolveAbsolutePath(projectRoot, rawPath);
368
+ const managedRoots = [
369
+ resolve(projectRoot, "rig"),
370
+ resolve(projectRoot, ".rig"),
371
+ resolve(projectRoot, "artifacts")
372
+ ];
373
+ return managedRoots.some((root) => absPath === root || absPath.startsWith(root + "/"));
374
+ }
375
+ function isRuntimePath(projectRoot, rawPath, taskWorkspace) {
376
+ const absPath = resolveAbsolutePath(projectRoot, rawPath);
377
+ if (taskWorkspace) {
378
+ const workspaceRigRoot = resolve(taskWorkspace, ".rig");
379
+ const workspaceArtifactsRoot = resolve(taskWorkspace, "artifacts");
380
+ if (absPath === workspaceRigRoot || absPath.startsWith(workspaceRigRoot + "/") || absPath === workspaceArtifactsRoot || absPath.startsWith(workspaceArtifactsRoot + "/")) {
381
+ return true;
382
+ }
383
+ }
384
+ const runtimeRoot = resolve(projectRoot, ".rig/runtime/agents");
385
+ return absPath === runtimeRoot || absPath.startsWith(runtimeRoot + "/");
386
+ }
387
+ function isTestFile(path) {
388
+ return /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(path) || /\/(__tests__|tests|test)\//.test(path);
389
+ }
390
+ function evaluate(context) {
391
+ const policy = loadPolicy(context.projectRoot);
392
+ switch (context.evaluation.type) {
393
+ case "tool-call":
394
+ return evaluateToolCall(policy, context);
395
+ case "command":
396
+ return evaluateCommand(policy, context);
397
+ case "content-write":
398
+ return evaluateContent(policy, context);
399
+ case "file-access":
400
+ return evaluateScope(policy, context, context.evaluation.file_path, context.evaluation.access);
401
+ }
402
+ }
403
+ function evaluateScope(policy, context, filePath, access) {
404
+ const allowed = () => ({
405
+ allowed: true,
406
+ matchedRules: [],
407
+ action: "allow",
408
+ failClosed: false
409
+ });
410
+ if (policy.scope.harness_paths_exempt && isHarnessPath(context.projectRoot, filePath)) {
411
+ return allowed();
412
+ }
413
+ if (policy.scope.runtime_paths_exempt && isRuntimePath(context.projectRoot, filePath, context.taskWorkspace)) {
414
+ return allowed();
415
+ }
416
+ if (!context.taskId) {
417
+ if (access === "write" && policy.scope.fail_closed) {
418
+ return {
419
+ allowed: false,
420
+ matchedRules: [],
421
+ action: resolveAction(policy.mode, [{ id: "scope:no-task", category: "command", reason: "No active task; fail-closed for write operations" }]),
422
+ failClosed: true
423
+ };
424
+ }
425
+ return allowed();
426
+ }
427
+ const scopes = context.taskScopes || [];
428
+ if (scopes.length === 0) {
429
+ return allowed();
430
+ }
431
+ if (context.taskWorkspace && context.taskWorkspace !== context.projectRoot && filePath.startsWith("/")) {
432
+ const absPath = resolve(filePath);
433
+ if (!absPath.startsWith(context.taskWorkspace + "/") && !isHarnessPath(context.projectRoot, filePath)) {
434
+ const reason2 = `Absolute path '${filePath}' is outside task runtime boundary. Allowed root: ${context.taskWorkspace}`;
435
+ const matched2 = [{ id: "scope:workspace-boundary", category: "command", reason: reason2 }];
436
+ return {
437
+ allowed: policy.mode !== "enforce",
438
+ matchedRules: matched2,
439
+ action: resolveAction(policy.mode, matched2),
440
+ failClosed: false
441
+ };
442
+ }
443
+ }
444
+ const monorepoRoot = context.monorepoRoot || process.env.MONOREPO_ROOT?.trim() || context.taskWorkspace || context.projectRoot;
445
+ let normalizedPath = filePath;
446
+ if (context.taskWorkspace && context.taskWorkspace !== context.projectRoot && filePath.startsWith(context.taskWorkspace + "/")) {
447
+ normalizedPath = filePath.slice(context.taskWorkspace.length + 1);
448
+ }
449
+ normalizedPath = normalizePathToScope(context.projectRoot, monorepoRoot, normalizedPath);
450
+ if (scopeMatches(filePath, scopes) || scopeMatches(normalizedPath, scopes)) {
451
+ return allowed();
452
+ }
453
+ const reason = `File '${filePath}' (normalized: '${normalizedPath}') is outside scope of task ${context.taskId}`;
454
+ const matched = [{ id: "scope:out-of-scope", category: "command", reason }];
455
+ return {
456
+ allowed: policy.mode !== "enforce",
457
+ matchedRules: matched,
458
+ action: resolveAction(policy.mode, matched),
459
+ failClosed: false
460
+ };
461
+ }
462
+ function evaluateCommand(policy, context) {
463
+ const evaluation = context.evaluation;
464
+ if (evaluation.type !== "command") {
465
+ return { allowed: true, matchedRules: [], action: "allow", failClosed: false };
466
+ }
467
+ const command = evaluation.command;
468
+ const matchedRules = [];
469
+ for (const rule of policy.rules) {
470
+ if (rule.category !== "command")
471
+ continue;
472
+ if (!matchRule(rule, command))
473
+ continue;
474
+ if (matchRuleUnless(rule, command, context.taskId))
475
+ continue;
476
+ matchedRules.push({
477
+ id: rule.id,
478
+ category: rule.category,
479
+ ...rule.description !== undefined ? { description: rule.description } : {},
480
+ reason: rule.description || `Matched rule ${rule.id}`
481
+ });
482
+ }
483
+ const writeTarget = extractWriteTarget(command);
484
+ if (writeTarget && !/^\/dev\//.test(writeTarget) && !/^\/proc\//.test(writeTarget)) {
485
+ const scopeResult = evaluateScope(policy, context, writeTarget, "write");
486
+ if (!scopeResult.allowed || scopeResult.matchedRules.length > 0) {
487
+ matchedRules.push(...scopeResult.matchedRules);
488
+ }
489
+ }
490
+ const action = resolveAction(policy.mode, matchedRules);
491
+ return {
492
+ allowed: action !== "block",
493
+ matchedRules,
494
+ action,
495
+ failClosed: false
496
+ };
497
+ }
498
+ function extractWriteTarget(command) {
499
+ const redirect = command.match(/>>?\s+([^\s;|&]+)/);
500
+ if (redirect?.[1])
501
+ return redirect[1];
502
+ const tee = command.match(/tee\s+(-a\s+)?([^\s;|&]+)/);
503
+ if (tee?.[2])
504
+ return tee[2];
505
+ return "";
506
+ }
507
+ function evaluateContent(policy, context) {
508
+ const evaluation = context.evaluation;
509
+ if (evaluation.type !== "content-write") {
510
+ return { allowed: true, matchedRules: [], action: "allow", failClosed: false };
511
+ }
512
+ const { content, file_path } = evaluation;
513
+ const matchedRules = [];
514
+ const scopeResult = evaluateScope(policy, context, file_path, "write");
515
+ if (scopeResult.matchedRules.length > 0) {
516
+ matchedRules.push(...scopeResult.matchedRules);
517
+ }
518
+ for (const rule of policy.rules) {
519
+ if (rule.category !== "content" && rule.category !== "import" && rule.category !== "test-integrity")
520
+ continue;
521
+ if (rule.applies_to === "test-files" && !isTestFile(file_path))
522
+ continue;
523
+ if (!matchRule(rule, content))
524
+ continue;
525
+ if (matchRuleUnless(rule, content, context.taskId))
526
+ continue;
527
+ matchedRules.push({
528
+ id: rule.id,
529
+ category: rule.category,
530
+ ...rule.description !== undefined ? { description: rule.description } : {},
531
+ reason: rule.description || `Matched rule ${rule.id}`
532
+ });
533
+ }
534
+ const action = resolveAction(policy.mode, matchedRules);
535
+ return {
536
+ allowed: action !== "block",
537
+ matchedRules,
538
+ action,
539
+ failClosed: false
540
+ };
541
+ }
542
+ function evaluateToolCall(policy, context) {
543
+ const evaluation = context.evaluation;
544
+ if (evaluation.type !== "tool-call") {
545
+ return { allowed: true, matchedRules: [], action: "allow", failClosed: false };
546
+ }
547
+ const { tool_name, tool_input } = evaluation;
548
+ const allMatched = [];
549
+ const filePaths = extractFilePathsFromToolInput(tool_name, tool_input);
550
+ for (const fp of filePaths) {
551
+ const access = isWriteTool(tool_name) ? "write" : "read";
552
+ const scopeResult = evaluateScope(policy, context, fp, access);
553
+ if (scopeResult.matchedRules.length > 0) {
554
+ allMatched.push(...scopeResult.matchedRules);
555
+ }
556
+ }
557
+ const content = extractContentFromToolInput(tool_input);
558
+ if (content) {
559
+ const filePath = filePaths[0] || "";
560
+ const contentContext = {
561
+ ...context,
562
+ evaluation: { type: "content-write", file_path: filePath, content }
563
+ };
564
+ const contentPolicy = loadPolicy(context.projectRoot);
565
+ for (const rule of contentPolicy.rules) {
566
+ if (rule.category !== "content" && rule.category !== "import" && rule.category !== "test-integrity")
567
+ continue;
568
+ if (rule.applies_to === "test-files" && !isTestFile(filePath))
569
+ continue;
570
+ if (!matchRule(rule, content))
571
+ continue;
572
+ if (matchRuleUnless(rule, content, context.taskId))
573
+ continue;
574
+ allMatched.push({
575
+ id: rule.id,
576
+ category: rule.category,
577
+ ...rule.description !== undefined ? { description: rule.description } : {},
578
+ reason: rule.description || `Matched rule ${rule.id}`
579
+ });
580
+ }
581
+ }
582
+ if (tool_name === "Bash") {
583
+ const command = String(tool_input.command || tool_input.cmd || "");
584
+ if (command) {
585
+ const cmdContext = {
586
+ ...context,
587
+ evaluation: { type: "command", command }
588
+ };
589
+ const cmdResult = evaluateCommand(policy, cmdContext);
590
+ if (cmdResult.matchedRules.length > 0) {
591
+ allMatched.push(...cmdResult.matchedRules);
592
+ }
593
+ }
594
+ }
595
+ const seen = new Set;
596
+ const deduplicated = [];
597
+ for (const rule of allMatched) {
598
+ if (!seen.has(rule.id)) {
599
+ seen.add(rule.id);
600
+ deduplicated.push(rule);
601
+ }
602
+ }
603
+ const action = resolveAction(policy.mode, deduplicated);
604
+ return {
605
+ allowed: action !== "block",
606
+ matchedRules: deduplicated,
607
+ action,
608
+ failClosed: false
609
+ };
610
+ }
611
+ function isWriteTool(toolName) {
612
+ return toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit";
613
+ }
614
+ function extractFilePathsFromToolInput(toolName, input) {
615
+ const paths = [];
616
+ const add = (value) => {
617
+ if (typeof value === "string" && value.trim()) {
618
+ paths.push(value.trim());
619
+ }
620
+ };
621
+ if (toolName === "Read" || toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
622
+ add(input.file_path);
623
+ add(input.path);
624
+ } else if (toolName === "Glob") {
625
+ add(input.path);
626
+ } else if (toolName === "Grep") {
627
+ add(input.path);
628
+ } else {
629
+ add(input.file_path);
630
+ add(input.path);
631
+ }
632
+ return paths;
633
+ }
634
+ function extractContentFromToolInput(input) {
635
+ if (typeof input.content === "string")
636
+ return input.content;
637
+ if (typeof input.new_string === "string")
638
+ return input.new_string;
639
+ return "";
640
+ }
641
+ var guardHotPathPrimed = false;
642
+ function primeGuardHotPaths() {
643
+ if (guardHotPathPrimed) {
644
+ return;
645
+ }
646
+ guardHotPathPrimed = true;
647
+ try {
648
+ optimizeNextInvocation(matchRule);
649
+ optimizeNextInvocation(evaluate);
650
+ } catch {}
651
+ }
652
+ primeGuardHotPaths();
653
+
654
+ // packages/guard-plugin/src/hook-ids.ts
7
655
  var TEST_INTEGRITY_GUARD_HOOK_ID = "@rig/guard-plugin:test-integrity-guard";
656
+
657
+ // packages/guard-plugin/src/hooks/test-integrity-guard.ts
8
658
  async function testIntegrityGuardHandler(ctx) {
9
659
  const projectRoot = ctx.projectRoot;
10
660
  seedPolicyFromContent(resolvePolicyContent(projectRoot));
@@ -1,4 +1,5 @@
1
1
  export * from "./plugin";
2
+ export * from "./guard";
2
3
  export { safetyGuardHandler, SAFETY_GUARD_HOOK_ID } from "./hooks/safety-guard";
3
4
  export { scopeGuardHandler, SCOPE_GUARD_HOOK_ID } from "./hooks/scope-guard";
4
5
  export { importGuardHandler, IMPORT_GUARD_HOOK_ID } from "./hooks/import-guard";